From adsquaired at gmail.com  Wed Feb  1 11:22:44 2017
From: adsquaired at gmail.com (ad^2)
Date: Wed, 1 Feb 2017 11:22:44 -0500
Subject: [Tutor] Lock File Usage
In-Reply-To: <85y3xsrruh.fsf@benfinney.id.au>
References: <CAPdGaa3Q5yD4sQ33erTn5mTisci=8=YQRZ0LoXRizN+cd2q8vQ@mail.gmail.com>
 <85y3xsrruh.fsf@benfinney.id.au>
Message-ID: <CAPdGaa1B5zPUDxCTND=uobTDRYjBcjNQvBkP=PWHGimEv2Jxmw@mail.gmail.com>

On Mon, Jan 30, 2017 at 7:33 PM, Ben Finney <ben+python at benfinney.id.au>
wrote:

> "ad^2" <adsquaired at gmail.com> writes:
>
> >  So, IF: no lock file, create a lock file, execute, delete lock file
> > when finished successfully. ElSE: the script is running, exit. Then,
> > cron will try again an hour later.
> >
> > I do not necessarily require a "lock file" just looking for a
> > recommendation on a best practice with low complexity to make this
> > work.
>
> The third-party ?fasteners? library provides an API for locks
> <URL:https://pypi.python.org/pypi/fasteners> that you will want to
> consider.
>
> Specifically, the interpprocess lock decorators
> <URL:https://fasteners.readthedocs.io/en/latest/
> examples.html#lock-decorator>
> seem to be what you want.
> -------------------
>

Thanks for the help guys. This is what I ended up going with that works.

Requires: lockfile, syslog and os modules

pid = ('/var/lock/' + os.path.splitext(os.path.basename(__file__))[0])

try:
    lock = filelock.FileLock(pid)
    lock.acquire(timeout = 1)
    # my code function 1
    # my code function 2
    # and so on....
    lock.release(force = True)
    os.unlink(pid)
except (IOError, OSError) as e:
    syslog.syslog('%s' % e)
    print e

From jf_byrnes at comcast.net  Wed Feb  1 16:18:18 2017
From: jf_byrnes at comcast.net (Jim)
Date: Wed, 1 Feb 2017 15:18:18 -0600
Subject: [Tutor] How to interact with the result of subprocess.call()
In-Reply-To: <o3qsim$pi9$1@blaine.gmane.org>
References: <o3mtg2$jt2$1@blaine.gmane.org>
 <CAGZAPF7Fq=fKhoStohHGHE0KFuA+t5JYvfmwOSoQ9mhgtW8WPA@mail.gmail.com>
 <o3n6ub$e9e$1@blaine.gmane.org> <o3n87f$kg$1@blaine.gmane.org>
 <o3oscp$k6t$1@blaine.gmane.org> <o3qsim$pi9$1@blaine.gmane.org>
Message-ID: <o6tjak$e54$1@blaine.gmane.org>

On 12/26/2016 04:48 AM, Peter Otten wrote:
> Jim Byrnes wrote:
>
>> Is there a way to terminate subprocess and still keep LO open so
>> pykeyboard can send it keystrokes from the script?
>
> In theory you can open Libre Office from another thread, wait a moment and
> then send it keystrokes from the main thread. I managed to do this with the
> script below.
>
> However, the procedure is very brittle; while experimenting I managed to
> "press" the control key without releasing it afterwards. The interval from
> doing it to realizing what was going on to "fixing" it (reboot) was an
> interesting experience...
>
> from contextlib import contextmanager
> import subprocess
> import threading
> import time
>
> import pykeyboard
>
> kb = pykeyboard.PyKeyboard()
>
>
> @contextmanager
> def press_key(key, kb=kb):
>     kb.press_key(key)
>     try:
>         yield
>         time.sleep(1)
>     finally:
>         kb.release_key(key)
>
>
> def open_it(filename):
>     subprocess.call(["libreoffice", filename])
>     print("exiting libreoffice thread")
>
>
> LONG_ENOUGH = 15  # seconds
>
> # enter text into an existing odt file
> filename = "demo.odt"
> text = "hello and goodbye"
>
> opener = threading.Thread(target=open_it, args=(filename,))
> opener.start()
>
> time.sleep(LONG_ENOUGH)  # for libreoffice to start and open the file
>
> kb.type_string(text)
>
> with press_key(kb.control_key):
>     kb.tap_key("s")
> with press_key(kb.alt_key):
>     kb.tap_key(kb.function_keys[4])
>
>
> print("exiting main thread")
>
>

Peter,

My apologies for taking so long to get back and thank you for the code. 
With the holidays and moving to a new computer/OS I didn't have much 
time to work on my little project.

I was able to use your code and send the necessary keystrokes to 
manipulate LO. Thanks again.

Regards,  Jim



From ben+python at benfinney.id.au  Wed Feb  1 17:10:32 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Thu, 02 Feb 2017 09:10:32 +1100
Subject: [Tutor] Lock File Usage
References: <CAPdGaa3Q5yD4sQ33erTn5mTisci=8=YQRZ0LoXRizN+cd2q8vQ@mail.gmail.com>
 <85y3xsrruh.fsf@benfinney.id.au>
 <CAPdGaa1B5zPUDxCTND=uobTDRYjBcjNQvBkP=PWHGimEv2Jxmw@mail.gmail.com>
Message-ID: <851svhsgtj.fsf@benfinney.id.au>

"ad^2" <adsquaired at gmail.com> writes:

> Thanks for the help guys. This is what I ended up going with that works.
>
> Requires: lockfile, syslog and os modules

You're probably aware, but for others reading this thread:

The ?lockfile? library is explicitly deprecated by its maintainers
<URL:https://pypi.python.org/pypi/lockfile/>. They have declared they're
no longer maintaining it, and they recommend using a different library
for locking.

So long as you're aware that you are effectively accepting the burden of
maintaining that library yourself, go ahead :-)

-- 
 \        ?I think it would be a good idea.? ?Mohandas K. Gandhi (when |
  `\                    asked what he thought of Western civilization) |
_o__)                                                                  |
Ben Finney


From robertvstepp at gmail.com  Thu Feb  2 21:22:12 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 2 Feb 2017 20:22:12 -0600
Subject: [Tutor] Best Python 3 module to create simple text editor in
 Windows command prompt?
Message-ID: <CANDiX9J1kNfWrofu2N9ks_TKo8-2Zperv3E5ZMqv2x1v8DJZ8g@mail.gmail.com>

I wish to create a primitive text editor in Windows 7 command prompt
to enable me to manually enter and solve simple substitution
cryptograms by hand.  I would want the cipher text to be one color and
the plain text in another.  My intent is to set up things this way in
command prompt before creating a more interesting version (with
increased features) in tkinter.  What would be the best Python 3
module to best assist me in controlling the command prompt window
display, font colors, positioning the cursor dynamically, etc.?

TIA!

-- 
boB

From eryksun at gmail.com  Thu Feb  2 21:35:33 2017
From: eryksun at gmail.com (eryk sun)
Date: Fri, 3 Feb 2017 02:35:33 +0000
Subject: [Tutor] Best Python 3 module to create simple text editor in
 Windows command prompt?
In-Reply-To: <CANDiX9J1kNfWrofu2N9ks_TKo8-2Zperv3E5ZMqv2x1v8DJZ8g@mail.gmail.com>
References: <CANDiX9J1kNfWrofu2N9ks_TKo8-2Zperv3E5ZMqv2x1v8DJZ8g@mail.gmail.com>
Message-ID: <CACL+1asT=MDf+K-3yNNztie6EMPpEfCRVh8QBGaXFECdaN_y2A@mail.gmail.com>

On Fri, Feb 3, 2017 at 2:22 AM, boB Stepp <robertvstepp at gmail.com> wrote:
> What would be the best Python 3 module to best assist me in controlling
> the command prompt window display, font colors, positioning the cursor
> dynamically, etc.?

Try using curses [1]. Christoph Gohlke has a port for Windows Python
based on the PDCurses library [2].

[1]: https://docs.python.org/3/howto/curses.html
[2]: http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses

From robertvstepp at gmail.com  Thu Feb  2 23:42:24 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 2 Feb 2017 22:42:24 -0600
Subject: [Tutor] Best Python 3 module to create simple text editor in
 Windows command prompt?
In-Reply-To: <CACL+1asT=MDf+K-3yNNztie6EMPpEfCRVh8QBGaXFECdaN_y2A@mail.gmail.com>
References: <CANDiX9J1kNfWrofu2N9ks_TKo8-2Zperv3E5ZMqv2x1v8DJZ8g@mail.gmail.com>
 <CACL+1asT=MDf+K-3yNNztie6EMPpEfCRVh8QBGaXFECdaN_y2A@mail.gmail.com>
Message-ID: <CANDiX9JCG6uh8H3-irpTi54XkerNfKu=i7pvm8BV=K4kS4Ayqg@mail.gmail.com>

On Thu, Feb 2, 2017 at 8:35 PM, eryk sun <eryksun at gmail.com> wrote:
> On Fri, Feb 3, 2017 at 2:22 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>> What would be the best Python 3 module to best assist me in controlling
>> the command prompt window display, font colors, positioning the cursor
>> dynamically, etc.?
>
> Try using curses [1]. Christoph Gohlke has a port for Windows Python
> based on the PDCurses library [2].
>
> [1]: https://docs.python.org/3/howto/curses.html
> [2]: http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses

Thanks, Eryk.  I did not realize that curses had been ported to
Windows.  I thought it was for *nix only.

-- 
boB

From alan.gauld at yahoo.co.uk  Fri Feb  3 05:47:44 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 3 Feb 2017 10:47:44 +0000
Subject: [Tutor] Best Python 3 module to create simple text editor in
 Windows command prompt?
In-Reply-To: <CANDiX9JCG6uh8H3-irpTi54XkerNfKu=i7pvm8BV=K4kS4Ayqg@mail.gmail.com>
References: <CANDiX9J1kNfWrofu2N9ks_TKo8-2Zperv3E5ZMqv2x1v8DJZ8g@mail.gmail.com>
 <CACL+1asT=MDf+K-3yNNztie6EMPpEfCRVh8QBGaXFECdaN_y2A@mail.gmail.com>
 <CANDiX9JCG6uh8H3-irpTi54XkerNfKu=i7pvm8BV=K4kS4Ayqg@mail.gmail.com>
Message-ID: <o71n4a$mu9$1@blaine.gmane.org>

On 03/02/17 04:42, boB Stepp wrote:
> On Thu, Feb 2, 2017 at 8:35 PM, eryk sun <eryksun at gmail.com> wrote:
>>> 
>> Try using curses [1]. Christoph Gohlke has a port for Windows Python
>> based on the PDCurses library [2].
> 
> Thanks, Eryk.  I did not realize that curses had been ported to
> Windows.  I thought it was for *nix only.

There have been several attempts at a Python curses for "DOS"
over the years but none of them worked completely (except
the Cygwin version of course*). I haven't tried the one
that Eryk suggests, hopefully somebody finally got it working.

Should that fail, or be overly complex, there are several
terminal control libraries around, and if all else fails
there are the so called "High Level Console Functions"
in the Microsoft API:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682010(v=vs.85).aspx

These should be accessible using ctypes if you are really
stuck... They are not very "high level" though!

(*) If you are just doing this for personal use then I
strongly suggest installing cygwin and just running
Python there. By far the simplest way to get a decent
console on Windows and all the other *nix tools as well.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From poojabhalode11 at gmail.com  Fri Feb  3 19:24:49 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Fri, 3 Feb 2017 19:24:49 -0500
Subject: [Tutor] Copy/Paste in Tkinter
Message-ID: <CAK0ikxeo5pgh=f0P1cNr8mvNmtmPhC92qDgOP2SxfhKW4cSPUA@mail.gmail.com>

Hi,
I am trying to write a simple Tkinter code in Python in order to
demonstrate select/copy/paste/cut functionalities using keyboard keys and
menu options.
I tried looking up online, but I am finding examples of these in which they
create an event and then it is used:
eg.:

import Tkinter

def make_menu(w):
global the_menu
the_menu = Tkinter.Menu(w, tearoff=0)
# the_menu.add_command(label="Select")
the_menu.add_command(label="Cut")
the_menu.add_command(label="Copy")
the_menu.add_command(label="Paste")

def show_menu(e):
w = e.widget
# the_menu.entryconfigure("Select",command=lambda:
w.event_generate("<<Select>>"))
the_menu.entryconfigure("Cut",command=lambda: w.event_generate("<<Cut>>"))
the_menu.entryconfigure("Copy",command=lambda: w.event_generate("<<Copy>>"))
the_menu.entryconfigure("Paste",command=lambda:
w.event_generate("<<Paste>>"))
the_menu.tk.call("tk_popup", the_menu, e.x_root, e.y_root)

root = Tkinter.Tk()
make_menu(root)

e1 = Tkinter.Entry(); e1.pack()
e2 = Tkinter.Entry(); e2.pack()
e1.bind_class("Entry", "<Double-1><ButtonRelease-1>", show_menu)

root.mainloop()

I was wondering if someone could please tell me a simplified different way
of doing this, that would be great. Thank you.

Pooja

From poojabhalode11 at gmail.com  Fri Feb  3 21:34:22 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Fri, 3 Feb 2017 21:34:22 -0500
Subject: [Tutor] Tkinter Copy/Paste/Cut functionalities
Message-ID: <CAK0ikxd=MxNQqWaebHehvWSOu+EuOZFSTkfOGSTm_O+T0kvOQw@mail.gmail.com>

Hi,

I am new to tkinter and looking for some help with select/copy/paste
functionalities. I wish to keep these tabs in the Edit menu and as well as
be able to do it using the shortcut keys.
Here, I am trying to create a GUI and needed some help with that.
I came across some snippets of the code to do this but using a self class.
I was wondering if some one could help me create these functionalities in a
manner similar to the following code. (similar to the Quitcommand
function).

Another question I had, was how to make the status bar text as a variable
such that it keeps on displaying what is going on in the program?

I would really appreciate your help on this.
Thank you so much.

Pooja

Code:

from Tkinter import *
import datetime
import tkMessageBox

root = Tk()
root.title("Name of the interface")

def Doit():
   print "Inside the function"

from tkMessageBox import *

def Quitcommand():
    if askyesno('Verify', 'Are you sure you want to quit?'):
        if askyesno('Save file', 'Do you want to save the current file?'):
            print 'Saving file'
        root.quit()
    else:
        showinfo('Quit not implemented.')

def LoadNew():
    print 'Loading new .gPROMS files'
    # User enters the name of the to be executed.
    if tkMessageBox.askyesno('Reading new file','Do you want to read
in the new files'):
        print 'Reading new files. '

def show_about():
    print 'HELP function'

from tkFileDialog import askopenfilename

def OpenFile():
    name = askopenfilename()
    print name

### --- Menu bar ---- ####
menu = Menu(root)
root.config(menu=menu)

editmenu = Menu(menu, tearoff=0)
menu.add_cascade(label="Edit", menu=editmenu)

editmenu.add_command(label="Cut",accelerator="Ctrl+X",command=DoCut)
editmenu.add_command(label="Copy",accelerator="Ctrl+C",command=DoCopy)
editmenu.add_command(label="Paste", accelerator="Ctrl+V"command=DoPaste)
editmenu.add_command(label="Make Changes", command=TimeAllowed)
editmenu.add_command(label="Line", command=Doit)


### --- Status bar ---- ####
Status = Label(root, text = 'Static',bd=1, relief=SUNKEN, anchor=W)
Status.pack(side=BOTTOM, fill=X)



root.mainloop()

From alan.gauld at yahoo.co.uk  Sat Feb  4 05:32:31 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 4 Feb 2017 10:32:31 +0000
Subject: [Tutor] Copy/Paste in Tkinter
In-Reply-To: <CAK0ikxeo5pgh=f0P1cNr8mvNmtmPhC92qDgOP2SxfhKW4cSPUA@mail.gmail.com>
References: <CAK0ikxeo5pgh=f0P1cNr8mvNmtmPhC92qDgOP2SxfhKW4cSPUA@mail.gmail.com>
Message-ID: <o74ajp$4i4$1@blaine.gmane.org>

On 04/02/17 00:24, Pooja Bhalode wrote:

> I am trying to write a simple Tkinter code in Python in order to
> demonstrate select/copy/paste/cut functionalities using keyboard keys and
> menu options.

You are going a fairly long winded way about it.
Rather than generating events use the Text/Entry
widget methods directly.

Check the documentation for the following methods:

Text.get(....)   # copy
Text.selection_get(...) # copy a selection
Text.delete(...)  # cut
Text.insert(...)  # paste

To control selections look at the tag methods,
but that is more complex.

> def show_menu(e):
> w = e.widget
> # the_menu.entryconfigure("Select",command=lambda:
> w.event_generate("<<Select>>"))
> the_menu.entryconfigure("Cut",command=lambda: w.event_generate("<<Cut>>"))
> the_menu.entryconfigure("Copy",command=lambda: w.event_generate("<<Copy>>"))
> the_menu.entryconfigure("Paste",command=lambda:

These should be in the create function. You don't need
to configure the command every time you show the menu.

> w.event_generate("<<Paste>>"))
> the_menu.tk.call("tk_popup", the_menu, e.x_root, e.y_root)

You should only need to call the tk.call() method very,
very rarely, there is usually a more direct way to do things.

> root = Tkinter.Tk()
> make_menu(root)
> 
> e1 = Tkinter.Entry(); e1.pack()
> e2 = Tkinter.Entry(); e2.pack()

Shouldn't these Entries have a parent?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Sat Feb  4 05:39:25 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 4 Feb 2017 10:39:25 +0000
Subject: [Tutor] Tkinter Copy/Paste/Cut functionalities
In-Reply-To: <CAK0ikxd=MxNQqWaebHehvWSOu+EuOZFSTkfOGSTm_O+T0kvOQw@mail.gmail.com>
References: <CAK0ikxd=MxNQqWaebHehvWSOu+EuOZFSTkfOGSTm_O+T0kvOQw@mail.gmail.com>
Message-ID: <o74b0o$t81$1@blaine.gmane.org>

On 04/02/17 02:34, Pooja Bhalode wrote:

> I came across some snippets of the code to do this but using a self class.

I'm not sure what you mean by a "self class"?

> I was wondering if some one could help me create these functionalities in a
> manner similar to the following code. (similar to the Quitcommand
> function).

See my reply to your other post.

> Another question I had, was how to make the status bar text as a variable
> such that it keeps on displaying what is going on in the program?

Its always best to keep separate questions in separate
posts - it makes searching the archives easier in the
future. However,...

That depends on what you want to show in the Status bar. A Status
bar normally includes showing help text when the mouse moves over
widgets and the status of any component that the cursor enters.
That sounds different to what you want?

You may be able to use a StriVar variable linked to an Entry on
the status bar, or maybe even a Label(can a Label text link to
a StrVar? I'm not sure). Alternatively ifv your code controls
where the variable gets changed(as it should) then simply update
the status bar every time you change that variable. This is one
case where a setX type function becomes worthwhile. Then only
change X by calling setX()...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Sat Feb  4 13:47:16 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 4 Feb 2017 18:47:16 +0000
Subject: [Tutor] Copy/Paste in Tkinter
In-Reply-To: <CAK0ikxcZP=dF7+qJFgy52wAW+q4mL2QYc6V5SfjCzTk6WY4_Qw@mail.gmail.com>
References: <CAK0ikxeo5pgh=f0P1cNr8mvNmtmPhC92qDgOP2SxfhKW4cSPUA@mail.gmail.com>
 <o74ajp$4i4$1@blaine.gmane.org>
 <CAK0ikxcZP=dF7+qJFgy52wAW+q4mL2QYc6V5SfjCzTk6WY4_Qw@mail.gmail.com>
Message-ID: <80190f93-14ea-7bea-f6be-403fe03dcabc@yahoo.co.uk>

On 04/02/17 16:09, Pooja Bhalode wrote:

> I do not have a text box, but a GUI similar to a word editor.

That sounds like a text box to me!?
What are you using to enter the text if not a Text widget?

> I was learning from youtube videos about this.

You can start with the GUI topic in my tutorial(see .sig)

It contains links to a couple of other Tkinter tutorials on
the web. The Python.org Tkinter page also has links.
All of these cover text processing to some degree.

Finally there are a couple of books to consider:
1) Python & Tkinter by Grayson on Manning Press
2) Programming Python 4th edition which has about
400 pages of Tkinter material, including a text editor.

3) And I can't resist a plug for my recent book "Python Projects"
which has a more modest 30 page intro on Tkinter, but
includes coverage of the get, delete and insert text methods,
as well as how to set fonts and build menus :-)

You may be able to get these via your local public/college library.

-- 

Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From juan0christian at gmail.com  Sat Feb  4 12:44:57 2017
From: juan0christian at gmail.com (Juan C.)
Date: Sat, 4 Feb 2017 15:44:57 -0200
Subject: [Tutor] Using venv
In-Reply-To: <o6gf59$e96$1@blaine.gmane.org>
References: <o6gf59$e96$1@blaine.gmane.org>
Message-ID: <CAAp0bGsn_0oCgMx8f5zf1dg4tMcAqovC-RfUyaeyO2bMwQHOvQ@mail.gmail.com>

On Fri, Jan 27, 2017 at 7:47 PM, Jim <jf_byrnes at comcast.net> wrote:
>
> [...] This question seems a little dumb and maybe I am being a little dense, but then what?

Imagine that you are working on 5 different Python projects, each
using different packages with different versions. We can break this
down in two situations:

1. No virtualenv
1.a. You only have one Lib/site-packages to hold all your packages
1.b. Project A uses package-abc 1.2 while Project B uses package-abc 1.5
1.c. You go to work on Project B using package-abc 1.5, but later on
you have to do some changes on Project A so you must downgrade
package-abc to 1.2. Too bad you have to fix some bugs on Project B the
next day, need to update package-abc back to 1.5

2. Virtualenv
2.a. You had multiple virtualenvs, each of them having their own
Lib/site-packages
2.b. Project A uses one virtualenv with package-abc 1.2 while Project
B uses another virtualenv with package-abc 1.5
2.c. You go to work on Project B using package-abc 1.5, so you
activate its venv, but later on you have to do some changes on Project
A so you activate the other venv. Too bad you have to fix some bugs on
Project B the next day, activate Project B venv.

It's a simple command to activate/deactivate a venv vs all the work
you have to do when not using venv.

From poojabhalode11 at gmail.com  Sat Feb  4 11:09:15 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sat, 4 Feb 2017 11:09:15 -0500
Subject: [Tutor] Copy/Paste in Tkinter
In-Reply-To: <o74ajp$4i4$1@blaine.gmane.org>
References: <CAK0ikxeo5pgh=f0P1cNr8mvNmtmPhC92qDgOP2SxfhKW4cSPUA@mail.gmail.com>
 <o74ajp$4i4$1@blaine.gmane.org>
Message-ID: <CAK0ikxcZP=dF7+qJFgy52wAW+q4mL2QYc6V5SfjCzTk6WY4_Qw@mail.gmail.com>

Hi Alan,

Thank you so much for guiding me towards this. I am new to tkinter hence
not aware of all these features.
I am trying to find some simple examples, of how to use copy/paste/cut. I
do not have a text box, but a GUI similar to a word editor. I was wondering
if you could direct me towards or show me towards some simple examples of
the same, so that it would be easier to understand. I was learning from
youtube videos about this.
It would be a huge help. Thank you so much

Pooja

On Sat, Feb 4, 2017 at 5:32 AM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 04/02/17 00:24, Pooja Bhalode wrote:
>
> > I am trying to write a simple Tkinter code in Python in order to
> > demonstrate select/copy/paste/cut functionalities using keyboard keys and
> > menu options.
>
> You are going a fairly long winded way about it.
> Rather than generating events use the Text/Entry
> widget methods directly.
>
> Check the documentation for the following methods:
>
> Text.get(....)   # copy
> Text.selection_get(...) # copy a selection
> Text.delete(...)  # cut
> Text.insert(...)  # paste
>
> To control selections look at the tag methods,
> but that is more complex.
>
> > def show_menu(e):
> > w = e.widget
> > # the_menu.entryconfigure("Select",command=lambda:
> > w.event_generate("<<Select>>"))
> > the_menu.entryconfigure("Cut",command=lambda:
> w.event_generate("<<Cut>>"))
> > the_menu.entryconfigure("Copy",command=lambda:
> w.event_generate("<<Copy>>"))
> > the_menu.entryconfigure("Paste",command=lambda:
>
> These should be in the create function. You don't need
> to configure the command every time you show the menu.
>
> > w.event_generate("<<Paste>>"))
> > the_menu.tk.call("tk_popup", the_menu, e.x_root, e.y_root)
>
> You should only need to call the tk.call() method very,
> very rarely, there is usually a more direct way to do things.
>
> > root = Tkinter.Tk()
> > make_menu(root)
> >
> > e1 = Tkinter.Entry(); e1.pack()
> > e2 = Tkinter.Entry(); e2.pack()
>
> Shouldn't these Entries have a parent?
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From robertvstepp at gmail.com  Sat Feb  4 17:02:02 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 4 Feb 2017 16:02:02 -0600
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
Message-ID: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>

py3: a
['Mary', 'had', 'a', 'little', 'lamb', 'break']
py3: for w in a:
...     print(w)
... print('Huh?')
  File "<stdin>", line 3
    print('Huh?')
        ^
SyntaxError: invalid syntax

I don't understand why this throws a SyntaxError.  If I wrap
essentially the same code into a function it works:

py3: def print_list(a_list):
...     for item in a_list:
...             print(item)
...     print('Huh?')
...
py3: print_list(a)
Mary
had
a
little
lamb
break

What am I not understanding here?

-- 
boB

From bouncingcats at gmail.com  Sat Feb  4 17:40:12 2017
From: bouncingcats at gmail.com (David)
Date: Sun, 5 Feb 2017 09:40:12 +1100
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
In-Reply-To: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
Message-ID: <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>

On 5 February 2017 at 09:02, boB Stepp <robertvstepp at gmail.com> wrote:
> py3: a
> ['Mary', 'had', 'a', 'little', 'lamb', 'break']
> py3: for w in a:
> ...     print(w)
> ... print('Huh?')
>   File "<stdin>", line 3
>     print('Huh?')
>         ^
> SyntaxError: invalid syntax
>
> I don't understand why this throws a SyntaxError.  If I wrap
> essentially the same code into a function it works:

>From [1]: "When a compound statement is entered interactively, it must
be followed by a blank line to indicate completion (since the parser
cannot guess when you have typed the last line). Note that each line
within a basic block must be indented by the same amount."

Does that help?

[1] https://docs.python.org/3/tutorial/introduction.html

From robertvstepp at gmail.com  Sat Feb  4 17:56:51 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 4 Feb 2017 16:56:51 -0600
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
In-Reply-To: <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
 <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
Message-ID: <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>

On Sat, Feb 4, 2017 at 4:40 PM, David <bouncingcats at gmail.com> wrote:
> On 5 February 2017 at 09:02, boB Stepp <robertvstepp at gmail.com> wrote:
>> py3: a
>> ['Mary', 'had', 'a', 'little', 'lamb', 'break']
>> py3: for w in a:
>> ...     print(w)
>> ... print('Huh?')
>>   File "<stdin>", line 3
>>     print('Huh?')
>>         ^
>> SyntaxError: invalid syntax
>>
>> I don't understand why this throws a SyntaxError.  If I wrap
>> essentially the same code into a function it works:
>
> From [1]: "When a compound statement is entered interactively, it must
> be followed by a blank line to indicate completion (since the parser
> cannot guess when you have typed the last line). Note that each line
> within a basic block must be indented by the same amount."
>
> Does that help?

Not really.  I do not understand why I can define a function in the
interactive interpreter and nest (apparently) any number of for loops,
if-elif-else constructs, etc., and as long as I get the indentation of
each block correct, it will accept it.  But apparently if I start off
with something which is by definition multiline like typing in a for
loop, I cannot continue the multiline statements with something
outside the for loop even if the indentation indicates that the
following statement is not part of the for loop above.  I can accept
this, but I do not understand why this can't be parsed correctly by
the interpreter solely based on the indentation and lack of
indentation being used.

C'est la vie Python!



-- 
boB

From bouncingcats at gmail.com  Sat Feb  4 18:32:36 2017
From: bouncingcats at gmail.com (David)
Date: Sun, 5 Feb 2017 10:32:36 +1100
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
In-Reply-To: <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
 <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
 <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
Message-ID: <CAMPXz=qfYJWJPdmF98z9DnkgJBc8+gkU1t+Lx-B4Lk6LcnaVKw@mail.gmail.com>

On 5 February 2017 at 09:56, boB Stepp <robertvstepp at gmail.com> wrote:
> On Sat, Feb 4, 2017 at 4:40 PM, David <bouncingcats at gmail.com> wrote:
>>>
>>> I don't understand why this throws a SyntaxError.  If I wrap
>>> essentially the same code into a function it works:
>>
>> From [1]: "When a compound statement is entered interactively, it must
>> be followed by a blank line to indicate completion (since the parser
>> cannot guess when you have typed the last line). Note that each line
>> within a basic block must be indented by the same amount."
>>
>> Does that help?
>
> Not really.  I do not understand why I can define a function in the
> interactive interpreter and nest (apparently) any number of for loops,
> if-elif-else constructs, etc., and as long as I get the indentation of
> each block correct, it will accept it.  But apparently if I start off
> with something which is by definition multiline like typing in a for
> loop, I cannot continue the multiline statements with something
> outside the for loop even if the indentation indicates that the
> following statement is not part of the for loop above.  I can accept
> this, but I do not understand why this can't be parsed correctly by
> the interpreter solely based on the indentation and lack of
> indentation being used.

I am guessing it is because the interpreter implements only single
level of auto-indent, for every top-level compound statement, and it
requires that to be terminated with one blank line.

It appears that all extra indenting must be done manually.

I could be wrong, as I would not work this way. Instead I would use an
editor to create the function, and then import it to create the desired
initial state which could then be explored interactively.

I just tried to give you a quick response. Maybe someone else will
give you a more authoritative answer, if there is one.

From alan.gauld at yahoo.co.uk  Sat Feb  4 18:44:51 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 4 Feb 2017 23:44:51 +0000
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
In-Reply-To: <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
 <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
 <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
Message-ID: <o75p1e$vep$1@blaine.gmane.org>

On 04/02/17 22:56, boB Stepp wrote:
> On Sat, Feb 4, 2017 at 4:40 PM, David <bouncingcats at gmail.com> wrote:
>> On 5 February 2017 at 09:02, boB Stepp <robertvstepp at gmail.com> wrote:
>>> py3: a
>>> ['Mary', 'had', 'a', 'little', 'lamb', 'break']
>>> py3: for w in a:
>>> ...     print(w)
>>> ... print('Huh?')
>>>   File "<stdin>", line 3
>>>     print('Huh?')
>>>         ^
>>> SyntaxError: invalid syntax
>>>
>>> I don't understand why this throws a SyntaxError.  If I wrap
>>> essentially the same code into a function it works:

Because you never completed the for loop. The interactive
interpreter tries to exercise each Python statement as it
goes but it cannot exercise the loop until it sees the end
of the block. Your second print statement is outside the
block but the block has not yet been executed so it sees
an error.

If you put a blank line it will work OK.

Alternatively if you put your code inside a function
definition it will understand it because it interprets
the full definition. Then when you call the function
it executes it as a whole. There is no discrepency in
what the interpreter is trying to interpret. But when
you do it at the top level  the interpreter is still
waiting for the end of the loop.

Does that help?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Sat Feb  4 19:03:49 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 4 Feb 2017 18:03:49 -0600
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
In-Reply-To: <o75p1e$vep$1@blaine.gmane.org>
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
 <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
 <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
 <o75p1e$vep$1@blaine.gmane.org>
Message-ID: <CANDiX9+aXMEdHrQD0EuuHjjvTsZKW-yD8nDT8L-dPhwHbuA86A@mail.gmail.com>

On Sat, Feb 4, 2017 at 5:44 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 04/02/17 22:56, boB Stepp wrote:
>> On Sat, Feb 4, 2017 at 4:40 PM, David <bouncingcats at gmail.com> wrote:
>>> On 5 February 2017 at 09:02, boB Stepp <robertvstepp at gmail.com> wrote:
>>>> py3: a
>>>> ['Mary', 'had', 'a', 'little', 'lamb', 'break']
>>>> py3: for w in a:
>>>> ...     print(w)
>>>> ... print('Huh?')
>>>>   File "<stdin>", line 3
>>>>     print('Huh?')
>>>>         ^
>>>> SyntaxError: invalid syntax
>>>>
>>>> I don't understand why this throws a SyntaxError.  If I wrap
>>>> essentially the same code into a function it works:
>
> Because you never completed the for loop. The interactive
> interpreter tries to exercise each Python statement as it
> goes but it cannot exercise the loop until it sees the end
> of the block. Your second print statement is outside the
> block but the block has not yet been executed so it sees
> an error.

But would it not be more consistent to assume the user knows what he
is doing based on the new (lack of) indentation being used, accept
that a new section of code outside of the for loop is being typed in,
and wait for the blank line before executing everything typed in?

>
> Alternatively if you put your code inside a function
> definition it will understand it because it interprets
> the full definition. Then when you call the function
> it executes it as a whole. There is no discrepency in
> what the interpreter is trying to interpret. But when
> you do it at the top level  the interpreter is still
> waiting for the end of the loop.

Again, the interpreter is waiting for that blank line before deciding
the function definition is complete.  Why cannot this be the key
criteria for the for loop with additional code being added, wait for
the blank line to be entered, and then execute the whole shebang?  To
me, this seems to be more consistent behavior.

> Does that help?

It confirms what I was concluding.  This is what happens when I have
some extra time on my hand, decide to carefully scrutinize the
official Python 3 tutorial, and then think, wonder and play around in
the interpreter.  ~(:>))


-- 
boB

From ben+python at benfinney.id.au  Sat Feb  4 19:16:36 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sun, 05 Feb 2017 11:16:36 +1100
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
 <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
 <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
 <o75p1e$vep$1@blaine.gmane.org>
 <CANDiX9+aXMEdHrQD0EuuHjjvTsZKW-yD8nDT8L-dPhwHbuA86A@mail.gmail.com>
Message-ID: <85r33dpk4b.fsf@benfinney.id.au>

boB Stepp <robertvstepp at gmail.com> writes:

> But would it not be more consistent to assume the user knows what he
> is doing based on the new (lack of) indentation being used, accept
> that a new section of code outside of the for loop is being typed in,
> and wait for the blank line before executing everything typed in?

That's not the purpose of the REPL. It is to Read (one statement),
Evaluate the statement, Print the result, and Loop.

You're wanting a different behaviour: wait until all the input has been
read, then evaluate it all.

If that's what you want: just write it all into a text file, and execute
that.

-- 
 \     ?Nature is trying very hard to make us succeed, but nature does |
  `\       not depend on us. We are not the only experiment.? ?Richard |
_o__)                                   Buckminster Fuller, 1978-04-30 |
Ben Finney


From robertvstepp at gmail.com  Sat Feb  4 20:29:53 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 4 Feb 2017 19:29:53 -0600
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
In-Reply-To: <85r33dpk4b.fsf@benfinney.id.au>
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
 <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
 <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
 <o75p1e$vep$1@blaine.gmane.org>
 <CANDiX9+aXMEdHrQD0EuuHjjvTsZKW-yD8nDT8L-dPhwHbuA86A@mail.gmail.com>
 <85r33dpk4b.fsf@benfinney.id.au>
Message-ID: <CANDiX9LbktcCBZNfSDi_ch+Meo8kC4hjnR+AysVRpqFfD_xVtg@mail.gmail.com>

I'm beginning to believe I am being incredibly dense today ...

On Sat, Feb 4, 2017 at 6:16 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> boB Stepp <robertvstepp at gmail.com> writes:
>
>> But would it not be more consistent to assume the user knows what he
>> is doing based on the new (lack of) indentation being used, accept
>> that a new section of code outside of the for loop is being typed in,
>> and wait for the blank line before executing everything typed in?
>
> That's not the purpose of the REPL. It is to Read (one statement),
> Evaluate the statement, Print the result, and Loop.
>
> You're wanting a different behaviour: wait until all the input has been
> read, then evaluate it all.

Ben, I read your answer, did some Googling on REPL, seemed satisfied,
and consigned this thread of emails to the trash bin, believing it was
all settled in my mind.  But then I got to wondering again ...

As already mentioned the interactive interpreter handles multiline
statements.  In the case of defining a function, the interpreter
allows quite complex, nested code to be entered, only ending the input
of code process when that blank line occurs in proper context.  By
this I mean that quotes have been properly closed, all parens matched,
etc.

But it seems to me on further thought that both REPL and what seems
most consistent to me, "...wait until all the input has been read,
then evaluate it all..." amounts to the same thing in the case of
entering function definitions into the interpreter.  The interpreter
cannot know that the user has finished inputting code until it
encounters that finalizing blank line.  After all I can have in my
function many for loops followed by unindented print functions in
seeming as much complexity as I can bear to type in accurately.  This
is giving exactly the consistent behavior that I would expect.  But if
instead of starting with a for loop inside a function with following
unindented other statements I instead start with *exactly the same
sequence of statements* but without "def ...:", then I get a syntax
error.  I am not trying to be deliberately argumentative, but I do not
see why the two cases are treated differently when the entered code is
exactly the same between the two with the sole exception of one has an
enclosing function definition line the other code does not.  I am
continuing to scratch my evermore balding head on this one!  But it is
not a big deal, and I do not want to blow things out of proportion.

More practically, I wonder if it is all as simple as not having to hit
the enter key twice for true one-liner statements.  Such lines can
truly be handled one line at a time per REPL.  If I had things "my
way", then that would make the more common situation of true
one-line-at-a-time read-evaluate-print-loop more cumbersome.

-- 
boB

From robertvstepp at gmail.com  Sat Feb  4 21:50:00 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 4 Feb 2017 20:50:00 -0600
Subject: [Tutor] Function annotations
Message-ID: <CANDiX9JvCHB4Nt=h+uRay3HNgZgV7VuWZWMYmJ0=3LJbmsrBOg@mail.gmail.com>

I just finished looking at
https://docs.python.org/3/tutorial/controlflow.html#function-annotations
and skimming through PEP 484--Type Hints
(https://www.python.org/dev/peps/pep-0484/).  My initial impression is
that the purpose of function annotations is to enable static code
analysis tools like linters to be more effective.  Aesthetically, to
my eye it makes the function definition line more cluttered looking
and more difficult to interpret at a glance.  Of course, these are
apparently optional.  I now wonder if I should be endeavoring to add
these to my code?

It is not clear to me how to implement function annotations in all
instances.  Starting with a rather useless function:

def prt_stupid_msg():
    print('Duh!')

This takes no arguments and returns None.  While this particular
function is rather useless, many others of some utility may take no
arguments and return None.  How should these types of functions be
annotated?

What about:

def print_stuff(stuff):
    print(stuff)

Should this be annotated as:

def print_stuff(stuff: Any) -> None:

?

What about a function from the tutorial:

def make_incrementor(n):
    return lambda x: x + n

n might always be an int or might always be a float or might be
either, depending on the author's intent.  Therefore, how should n be
annotated?  In accordance with the author's intentions?  And what
about the case where n is sometimes an integer and sometimes a float?
And the return in this instance is a function.  Should the return be
annotated "function"?

And what about functions that return different types depending on
conditional statements?  How would these varying return types be
annotated?  Say:

def return_typed_value(desired_type, value):
    if desired_type = 'string':
        return str(value)
    elif desired_type = 'integer':
        return int(value)
    elif desired_type = 'float':
        return float(value)

What should I do with this?  As written "desired_type" will always be
a string, but "value" will be potentially several different types.
And the return value can be one of three types (Assuming no errors
occur as no exception handling is being done as written.).  What to do
about that?

I have more questions, but these will do for a start.  Just the long
PEP 484 document has tons of meat in it to consider, most of which is
dealing with aspects of Python I have not gotten to studying yet!


-- 
boB

From steve at pearwood.info  Sat Feb  4 22:23:55 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 5 Feb 2017 14:23:55 +1100
Subject: [Tutor] Function annotations
In-Reply-To: <CANDiX9JvCHB4Nt=h+uRay3HNgZgV7VuWZWMYmJ0=3LJbmsrBOg@mail.gmail.com>
References: <CANDiX9JvCHB4Nt=h+uRay3HNgZgV7VuWZWMYmJ0=3LJbmsrBOg@mail.gmail.com>
Message-ID: <20170205032354.GP7345@ando.pearwood.info>

On Sat, Feb 04, 2017 at 08:50:00PM -0600, boB Stepp wrote:
> I just finished looking at
> https://docs.python.org/3/tutorial/controlflow.html#function-annotations
> and skimming through PEP 484--Type Hints
> (https://www.python.org/dev/peps/pep-0484/).  My initial impression is
> that the purpose of function annotations is to enable static code
> analysis tools like linters to be more effective.

That's exactly what they're for.

> Aesthetically, to
> my eye it makes the function definition line more cluttered looking
> and more difficult to interpret at a glance.

Obviously they take up more room, but they also provide more 
information: the intended type of the argument,



> Of course, these are
> apparently optional.  I now wonder if I should be endeavoring to add
> these to my code?

Do you run a linter? If not, there doesn't seem much point in adding 
annotations.


> It is not clear to me how to implement function annotations in all
> instances.  Starting with a rather useless function:
> 
> def prt_stupid_msg():
>     print('Duh!')
> 
> This takes no arguments and returns None.  While this particular
> function is rather useless, many others of some utility may take no
> arguments and return None.  How should these types of functions be
> annotated?

Since it take no arguments, you cannot annotate the arguments it 
doesn't have.

You could annotate the return value:

def prt_stupid_msg() -> None: 
    print('Duh!')


but that's unlikely to be useful. I wouldn't bother.



> What about:
> 
> def print_stuff(stuff):
>     print(stuff)
> 
> Should this be annotated as:
> 
> def print_stuff(stuff: Any) -> None:
> 
> ?


Probably not. If you don't annotate the function, the linter should just 
assume it takes anything as argument.


> What about a function from the tutorial:
> 
> def make_incrementor(n):
>     return lambda x: x + n
> 
> n might always be an int or might always be a float or might be
> either, depending on the author's intent.  Therefore, how should n be
> annotated?  In accordance with the author's intentions?

Of course.

> And what
> about the case where n is sometimes an integer and sometimes a float?

That's a Union of two types. Think of Union as meaning "this OR that".


> And the return in this instance is a function.  Should the return be
> annotated "function"?

from typing import Union
from types import FunctionType

def make_incrementor(n: Union[int, float]) -> FunctionType:
    return lambda x: x + n



> And what about functions that return different types depending on
> conditional statements?

Probably a bad design...


> How would these varying return types be annotated?  Say:
> 
> def return_typed_value(desired_type, value):
>     if desired_type = 'string':
>         return str(value)
>     elif desired_type = 'integer':
>         return int(value)
>     elif desired_type = 'float':
>         return float(value)
> 
> What should I do with this?

Redesign it.

def return_typed_value(
        desired_type: str, value: Any) -> Union[str, int, float]:
    ...



> As written "desired_type" will always be
> a string, but "value" will be potentially several different types.

If you want to restrict the type of `value` depending on the value of 
`desired_type`, you cannot expect the compiler or linter or type-checker 
to do this at compile time. In general, it doesn't know what the value 
of `desired_type` is, so it can't tell whether the type of `value` is 
valid or not.

You would have to use a *dynamic* type check, rather than static:

def return_typed_value(desired_type, value):
    if desired_type == 'string':
        if isinstance(value, (int, float)):
            return str(value)
    elif desired_type == 'integer':
        if isinstance(value, (float, str)):
            return int(value)
    elif desired_type == 'float':
        if isinstance(value, (int, str)):
            return float(value)
    raise TypeError



When your type checking rules become this intricate, it's probably a bad 
idea.


-- 
Steve

From robertvstepp at gmail.com  Sat Feb  4 22:52:47 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 4 Feb 2017 21:52:47 -0600
Subject: [Tutor] sort() method and non-ASCII
Message-ID: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>

Does the list sort() method (and other sort methods in Python) just go
by the hex value assigned to each symbol to determine sort order in
whichever Unicode encoding chart is being implemented?  If yes, then
my expectation would be that the French "?" would come after the "z"
character.  I am not ready to get into the guts of Unicode.  I am
quite happy now to leave Python 3 at its default UTF-8 and strictly
type in the ASCII subset of UTF-8.  But I know I will eventually have
to get into this, so I thought I would ask about sorting so I don't
get any evil surprises with some text file I might have to manipulate
in the future.

Thanks!

-- 
boB

From robertvstepp at gmail.com  Sat Feb  4 23:11:39 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 4 Feb 2017 22:11:39 -0600
Subject: [Tutor] Function annotations
In-Reply-To: <20170205032354.GP7345@ando.pearwood.info>
References: <CANDiX9JvCHB4Nt=h+uRay3HNgZgV7VuWZWMYmJ0=3LJbmsrBOg@mail.gmail.com>
 <20170205032354.GP7345@ando.pearwood.info>
Message-ID: <CANDiX9LO0ot9noy2EsCdpSOGaH=bDnUf9r47=FOCmwucCTEQ+A@mail.gmail.com>

On Sat, Feb 4, 2017 at 9:23 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Feb 04, 2017 at 08:50:00PM -0600, boB Stepp wrote:

>> Of course, these are
>> apparently optional.  I now wonder if I should be endeavoring to add
>> these to my code?
>
> Do you run a linter? If not, there doesn't seem much point in adding
> annotations.

To date I have avoided adding a linter to vim/gvim as I believe I get
more educational benefit from making and correcting mistakes that a
linter would catch.  But I have it in the back of mind if I ever reach
a relative point of Python comfort to implement linting capabilities.
Are the people making linters implementing checking function
annotations?  Or is this something only gradually being adopted?

Steve, are you making use of function annotations?  If yes, are you
finding them worth the extra effort?

Cheers!
boB

From eryksun at gmail.com  Sun Feb  5 02:52:45 2017
From: eryksun at gmail.com (eryk sun)
Date: Sun, 5 Feb 2017 07:52:45 +0000
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
Message-ID: <CACL+1av0X4vaUL5J5PAXaS4ES3Es4Fq=S-65+Qzmrmxg6YTicw@mail.gmail.com>

On Sun, Feb 5, 2017 at 3:52 AM, boB Stepp <robertvstepp at gmail.com> wrote:
> Does the list sort() method (and other sort methods in Python) just go
> by the hex value assigned to each symbol to determine sort order in
> whichever Unicode encoding chart is being implemented?

list.sort uses a less-than comparison. What you really want to know is
how Python compares strings. They're compared by ordinal at
corresponding indexes, i.e. ord(s1[i]) vs ord(s2[i]) for i less than
min(len(s1), len(s2)).

This gets a bit interesting when you're comparing characters that have
composed and decomposed Unicode forms, i.e. a single code vs multiple
combining codes. For example:

    >>> s1 = '\xc7'
    >>> s2 = 'C' + '\u0327'
    >>> print(s1, s2)
    ? C?
    >>> s2 < s1
    True

where U+0327 is a combining cedilla. As characters, s1 and s2 are the
same. However, codewise s2 is less than s1 because 0x43 ("C") is less
than 0xc7 ("?"). In this case you can first normalize the strings to
either composed or decomposed form [1]. For example:

    >>> strings = ['\xc7', 'C\u0327', 'D']
    >>> sorted(strings)
    ['C?', 'D', '?']

    >>> norm_nfc = functools.partial(unicodedata.normalize, 'NFC')
    >>> sorted(strings, key=norm_nfc)
    ['D', '?', 'C?']

[1]: https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms

From steve at pearwood.info  Sun Feb  5 03:36:58 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 5 Feb 2017 19:36:58 +1100
Subject: [Tutor] Function annotations
In-Reply-To: <CANDiX9LO0ot9noy2EsCdpSOGaH=bDnUf9r47=FOCmwucCTEQ+A@mail.gmail.com>
References: <CANDiX9JvCHB4Nt=h+uRay3HNgZgV7VuWZWMYmJ0=3LJbmsrBOg@mail.gmail.com>
 <20170205032354.GP7345@ando.pearwood.info>
 <CANDiX9LO0ot9noy2EsCdpSOGaH=bDnUf9r47=FOCmwucCTEQ+A@mail.gmail.com>
Message-ID: <20170205083658.GS7345@ando.pearwood.info>

On Sat, Feb 04, 2017 at 10:11:39PM -0600, boB Stepp wrote:

> Are the people making linters implementing checking function
> annotations?  Or is this something only gradually being adopted?

Depends which linter :-)

MyPy is still the reference implementation for type hinting in Python:

http://mypy-lang.org/

As for pychecker, pylint, jedi, pyflakes, etc you'll have to check with 
the individual application itself.

> Steve, are you making use of function annotations?  If yes, are you
> finding them worth the extra effort?

Not yet.


-- 
Steve

From steve at pearwood.info  Sun Feb  5 03:32:37 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 5 Feb 2017 19:32:37 +1100
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
Message-ID: <20170205083236.GR7345@ando.pearwood.info>

On Sat, Feb 04, 2017 at 09:52:47PM -0600, boB Stepp wrote:
> Does the list sort() method (and other sort methods in Python) just go
> by the hex value assigned to each symbol to determine sort order in
> whichever Unicode encoding chart is being implemented?

Correct, except that there is only one Unicode encoding chart.

You may be thinking of the legacy Windows "code pages" system, where you 
can change the code page to re-interpret characters as different 
characters. E.g. ? in code page 1252 (Western European) becomes ? in 
code page 1253 (Greek).

Python supports encoding and decoding to and from legacy code page 
forms, but Unicode itself does away with the idea of using separate code 
pages. It effectively is a single, giant code page containing room for 
over a million characters. It's also a superset of ASCII, so pure ASCII 
text can be identical in Unicode.

Anyhoo, since Unicode supports dozens of languages from all over the 
world, it defines "collation rules" for sorting text in various 
languages. For example, sorting in Austria is different from sorting in 
Germany, despite them both using the same alphabet. Even in English, 
sorting rules can vary: some phone books sort Mc and Mac together, some 
don't.

However, Python doesn't directly support that. It just provides a single 
basic lexicographic sort based on the ord() of each character in the 
string.

> If yes, then
> my expectation would be that the French "?" would come after the "z"
> character. 

Correct:

py> "?" > "z"
True
py> sorted('?z')
['z', '?']



-- 
Steve


From random832 at fastmail.com  Sat Feb  4 23:50:47 2017
From: random832 at fastmail.com (Random832)
Date: Sat, 04 Feb 2017 23:50:47 -0500
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
Message-ID: <1486270247.481569.870639976.015EB601@webmail.messagingengine.com>

On Sat, Feb 4, 2017, at 22:52, boB Stepp wrote:
> Does the list sort() method (and other sort methods in Python) just go
> by the hex value assigned to each symbol to determine sort order in
> whichever Unicode encoding chart is being implemented?

By default. You need key=locale.strxfrm to make it do anything more
sophisticated.

I'm not sure what you mean by "whichever unicode encoding chart". Python
3 strings are unicode-unicode, not UTF-8.

From alan.gauld at yahoo.co.uk  Sun Feb  5 04:14:54 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 5 Feb 2017 09:14:54 +0000
Subject: [Tutor] Syntax error while attempting to type in multiline
 statements in the interactive interpreter
In-Reply-To: <CANDiX9LbktcCBZNfSDi_ch+Meo8kC4hjnR+AysVRpqFfD_xVtg@mail.gmail.com>
References: <CANDiX9LvdjRSwTquRqChuZR7q7aVaa-QQ6-GKq865rg01_qszg@mail.gmail.com>
 <CAMPXz=pyWbtzZAhm+BAHf3O6krY2P-38yR4BdLZ5KQyhGztT5g@mail.gmail.com>
 <CANDiX9+BGOA1fSAf6WB1y5oGRok1WGATbPeNw-ZONhnEex=Ukg@mail.gmail.com>
 <o75p1e$vep$1@blaine.gmane.org>
 <CANDiX9+aXMEdHrQD0EuuHjjvTsZKW-yD8nDT8L-dPhwHbuA86A@mail.gmail.com>
 <85r33dpk4b.fsf@benfinney.id.au>
 <CANDiX9LbktcCBZNfSDi_ch+Meo8kC4hjnR+AysVRpqFfD_xVtg@mail.gmail.com>
Message-ID: <o76qe8$oh8$1@blaine.gmane.org>

On 05/02/17 01:29, boB Stepp wrote:

> But it seems to me on further thought that both REPL and what seems
> most consistent to me, "...wait until all the input has been read,
> then evaluate it all..." amounts to the same thing in the case of
> entering function definitions into the interpreter.  

Nope, the function definition is a single executable statement.
def is a command just like print. The command is to compile the
block of code and store it as a function object that can later
be called. So the interpreter is being completely consistent
in looking for the full definition in that case.

You are right that the interactive interpreter *could* have read
all input before executing it, but by design it doesn't. It is
an arbitrary choice to make the interpreter act on a single
input statement at a time (and personally I think a good one).

The problem with executing multiple statements at a time is
that your mistakes are often not where you think they are.
And by showing you the output of every statement as you go
you notice the error as it happens and don't mistakenly make
assumptions about which of the previous N statements
contains the bug. So personally I prefer the Python style
interpreter. Perl by contrast is more like your preference
and interprets to an EOF and I find that too easy to make
mistakes.

Best of all I guess is Smalltalk which executes any code
you highlight with a mouse...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Sun Feb  5 17:30:47 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 5 Feb 2017 16:30:47 -0600
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <20170205083236.GR7345@ando.pearwood.info>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
 <20170205083236.GR7345@ando.pearwood.info>
Message-ID: <CANDiX9LjrY4m0x3M1NnP4CD9Cnm3jhNaZtGPFzTV4uY=kEuzcw@mail.gmail.com>

On Sun, Feb 5, 2017 at 2:32 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Feb 04, 2017 at 09:52:47PM -0600, boB Stepp wrote:
>> Does the list sort() method (and other sort methods in Python) just go
>> by the hex value assigned to each symbol to determine sort order in
>> whichever Unicode encoding chart is being implemented?
>
> Correct, except that there is only one Unicode encoding chart.

I was looking at http://unicode.org/charts/  Because they called them
charts, so did I.  I'm assuming that despite this organization into
charts, each and every character in each chart has its own unique
hexadecimal code to designate each character.



-- 
boB

From robertvstepp at gmail.com  Sun Feb  5 17:31:43 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 5 Feb 2017 16:31:43 -0600
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <1486270247.481569.870639976.015EB601@webmail.messagingengine.com>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
 <1486270247.481569.870639976.015EB601@webmail.messagingengine.com>
Message-ID: <CANDiX9K0SJ62ixqcMi4LFWJxVucp0w1P86Hr68kS2s3tccX5tA@mail.gmail.com>

On Sat, Feb 4, 2017 at 10:50 PM, Random832 <random832 at fastmail.com> wrote:
> On Sat, Feb 4, 2017, at 22:52, boB Stepp wrote:
>> Does the list sort() method (and other sort methods in Python) just go
>> by the hex value assigned to each symbol to determine sort order in
>> whichever Unicode encoding chart is being implemented?
>
> By default. You need key=locale.strxfrm to make it do anything more
> sophisticated.
>
> I'm not sure what you mean by "whichever unicode encoding chart". Python
> 3 strings are unicode-unicode, not UTF-8.

As I said in my response to Steve just now:  I was looking at
http://unicode.org/charts/  Because they called them charts, so did I.
I'm assuming that despite this organization into charts, each and
every character in each chart has its own unique hexadecimal code to
designate each character.


-- 
boB

From cs at zip.com.au  Sun Feb  5 18:25:01 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Mon, 6 Feb 2017 10:25:01 +1100
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9K0SJ62ixqcMi4LFWJxVucp0w1P86Hr68kS2s3tccX5tA@mail.gmail.com>
References: <CANDiX9K0SJ62ixqcMi4LFWJxVucp0w1P86Hr68kS2s3tccX5tA@mail.gmail.com>
Message-ID: <20170205232501.GA86556@cskk.homeip.net>

On 05Feb2017 16:31, boB Stepp <robertvstepp at gmail.com> wrote:
>On Sat, Feb 4, 2017 at 10:50 PM, Random832 <random832 at fastmail.com> wrote:
>> On Sat, Feb 4, 2017, at 22:52, boB Stepp wrote:
>>> Does the list sort() method (and other sort methods in Python) just go
>>> by the hex value assigned to each symbol to determine sort order in
>>> whichever Unicode encoding chart is being implemented?
>>
>> By default. You need key=locale.strxfrm to make it do anything more
>> sophisticated.
>>
>> I'm not sure what you mean by "whichever unicode encoding chart". Python
>> 3 strings are unicode-unicode, not UTF-8.
>
>As I said in my response to Steve just now:  I was looking at
>http://unicode.org/charts/  Because they called them charts, so did I.
>I'm assuming that despite this organization into charts, each and
>every character in each chart has its own unique hexadecimal code to
>designate each character.

You might want to drop this term "hexadecimal"; they're just ordinals (plain 
old numbers). Though Unicode ordinals are often _written_ in hexadecimal for 
compactness and because various character grouping are aligned on ranges based 
on power-of-2 multiples. Like ASCII has the upper case latin alphabet at 64 
(2^6) and lower case at 96 (2^6 + 2^32). Those values look rounder in base 16: 
0x40 and 0x60.

Cheers,
Cameron Simpson <cs at zip.com.au>

From eryksun at gmail.com  Sun Feb  5 18:40:27 2017
From: eryksun at gmail.com (eryk sun)
Date: Sun, 5 Feb 2017 23:40:27 +0000
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9LjrY4m0x3M1NnP4CD9Cnm3jhNaZtGPFzTV4uY=kEuzcw@mail.gmail.com>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
 <20170205083236.GR7345@ando.pearwood.info>
 <CANDiX9LjrY4m0x3M1NnP4CD9Cnm3jhNaZtGPFzTV4uY=kEuzcw@mail.gmail.com>
Message-ID: <CACL+1atcHSyh0R-EzTMGTTO7BWhUikdJS7Zav6AN9+tfNUgaiA@mail.gmail.com>

On Sun, Feb 5, 2017 at 10:30 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> I was looking at http://unicode.org/charts/  Because they called them
> charts, so did I.  I'm assuming that despite this organization into
> charts, each and every character in each chart has its own unique
> hexadecimal code to designate each character.

Those are PDF charts (i.e. tables) for Unicode blocks:

https://en.wikipedia.org/wiki/Unicode_block

A Unicode block always has a multiple of 16 codepoints, so it's
convenient to represent the ordinal values in hexadecimal.

From steve at pearwood.info  Sun Feb  5 20:23:56 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 6 Feb 2017 12:23:56 +1100
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9K0SJ62ixqcMi4LFWJxVucp0w1P86Hr68kS2s3tccX5tA@mail.gmail.com>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
 <1486270247.481569.870639976.015EB601@webmail.messagingengine.com>
 <CANDiX9K0SJ62ixqcMi4LFWJxVucp0w1P86Hr68kS2s3tccX5tA@mail.gmail.com>
Message-ID: <20170206012356.GT7345@ando.pearwood.info>

On Sun, Feb 05, 2017 at 04:31:43PM -0600, boB Stepp wrote:
> On Sat, Feb 4, 2017 at 10:50 PM, Random832 <random832 at fastmail.com> wrote:
> > On Sat, Feb 4, 2017, at 22:52, boB Stepp wrote:
> >> Does the list sort() method (and other sort methods in Python) just go
> >> by the hex value assigned to each symbol to determine sort order in
> >> whichever Unicode encoding chart is being implemented?
> >
> > By default. You need key=locale.strxfrm to make it do anything more
> > sophisticated.
> >
> > I'm not sure what you mean by "whichever unicode encoding chart". Python
> > 3 strings are unicode-unicode, not UTF-8.
> 
> As I said in my response to Steve just now:  I was looking at
> http://unicode.org/charts/  Because they called them charts, so did I.

Ah, that makes sense! They're just reference tables ("charts") for the 
convenience of people wishing to find particular characters.


> I'm assuming that despite this organization into charts, each and
> every character in each chart has its own unique hexadecimal code to
> designate each character.

Correct, although strictly speaking the codes are only conventionally 
given in hexadecimal. They are numbered from 0 to 1114111 in 
decimal (although not all codes are currently used).

The terminology used is that a "code point" is what I've been calling a 
"character", although not all code points are characters. Code points 
are usually written either as the character itself, e.g. 'A', or using 
the notation U+0041 where there are at least four and no more than six 
hexadecimal digits following the "U+". 

Bringing this back to Python, if you know the code point (as a number), 
you can use the chr() function to return it as a string:

py> chr(960)
'?'


Don't forget that Python understands hex too!

py> chr(0x03C0)  # better than chr(int('03C0', 16))
'?'


Alternatively, you can embed it right in the string. For code points 
between U+0000 and U+FFFF, use the \u escape, and for the rest, use \U 
escapes:

py> 'pi = \u03C0'  # requires exactly four hex digits
'pi = ?'

py> 'pi = \U000003C0'  # requires exactly eight hex digits
'pi = ?'


Lastly, you can use the code point's name:

py> 'pi = \N{GREEK SMALL LETTER PI}'
'pi = ?'


One last comment: Random832 said:

"Python 3 strings are unicode-unicode, not UTF-8."

To be pedantic, Unicode strings are sequences of abstract code points 
("characters"). UTF-8 is a particular concrete implementation that is 
used to store or transmit such code strings. Here are examples of three 
possible encoding forms for the string '?z':

UTF-16: either two, or four, bytes per character: 03C0 007A

UTF-32: exactly four bytes per character: 000003C0 0000007A

UTF-8: between one and four bytes per character: CF80 7A

(UTF-16 and UTF-32 are hardware-dependent, and the byte order could be 
reversed, e.g. C003 7A00. UTF-8 is not.)

Prior to version 3.3, there was a built-time option to select either 
"narrow" or "wide" Unicode strings. A narrow build used a fixed two 
bytes per code point, together with an incomplete and not quite correct 
scheme for using two code points together to represent the supplementary 
Unicode characters U+10000 through U+10FFFF. (This is sometimes called 
UCS-2, sometimes UTF-16, but strictly speaking it is neither, or at 
least an incomplete and "buggy" implementation of UTF-16.)


-- 
Steve

From robertvstepp at gmail.com  Sun Feb  5 23:09:17 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 5 Feb 2017 22:09:17 -0600
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <20170205232501.GA86556@cskk.homeip.net>
References: <CANDiX9K0SJ62ixqcMi4LFWJxVucp0w1P86Hr68kS2s3tccX5tA@mail.gmail.com>
 <20170205232501.GA86556@cskk.homeip.net>
Message-ID: <CANDiX9LOiYS97Ezs6CTnxm2bDsfV4ErXwhDdSLOOQvCz1Ha9bA@mail.gmail.com>

On Sun, Feb 5, 2017 at 5:25 PM, Cameron Simpson <cs at zip.com.au> wrote:

> You might want to drop this term "hexadecimal"; they're just ordinals (plain
> old numbers). Though Unicode ordinals are often _written_ in hexadecimal for
> compactness and because various character grouping are aligned on ranges
> based on power-of-2 multiples. Like ASCII has the upper case latin alphabet
> at 64 (2^6) and lower case at 96 (2^6 + 2^32). Those values look rounder in
> base 16: 0x40 and 0x60.

I will endeavor to use "code points" instead.  I am just used to
seeing these charts/tables in hexadecimal values.



-- 
boB

From robertvstepp at gmail.com  Sun Feb  5 23:27:41 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 5 Feb 2017 22:27:41 -0600
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <20170206012356.GT7345@ando.pearwood.info>
References: <CANDiX9LyzafjA_VGyKx0RcT=T3DBXAYx2fVLAhtHYMwU73P=pw@mail.gmail.com>
 <1486270247.481569.870639976.015EB601@webmail.messagingengine.com>
 <CANDiX9K0SJ62ixqcMi4LFWJxVucp0w1P86Hr68kS2s3tccX5tA@mail.gmail.com>
 <20170206012356.GT7345@ando.pearwood.info>
Message-ID: <CANDiX9K21yfqunvvn7Qtu3afvp6oLr42HaZoYhwBgJugxWOGyA@mail.gmail.com>

On Sun, Feb 5, 2017 at 7:23 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, Feb 05, 2017 at 04:31:43PM -0600, boB Stepp wrote:
>> On Sat, Feb 4, 2017 at 10:50 PM, Random832 <random832 at fastmail.com> wrote:
>> > On Sat, Feb 4, 2017, at 22:52, boB Stepp wrote:


> Alternatively, you can embed it right in the string. For code points
> between U+0000 and U+FFFF, use the \u escape, and for the rest, use \U
> escapes:
>
> py> 'pi = \u03C0'  # requires exactly four hex digits
> 'pi = ?'
>
> py> 'pi = \U000003C0'  # requires exactly eight hex digits
> 'pi = ?'
>
>
> Lastly, you can use the code point's name:
>
> py> 'pi = \N{GREEK SMALL LETTER PI}'
> 'pi = ?'

You have surprised me here by using single quotes to enclose the
entire assignment statements.  I thought this would throw a syntax
error, but it works just like you show.  What is going on here?

>
> One last comment: Random832 said:
>
> "Python 3 strings are unicode-unicode, not UTF-8."

If I recall what I originally wrote (and intended) I was merely
indicating I was happy with Python 3's default UTF-8 encoding.  I do
not know enough to know what these other UTF encodings offer.

> To be pedantic, Unicode strings are sequences of abstract code points
> ("characters"). UTF-8 is a particular concrete implementation that is
> used to store or transmit such code strings. Here are examples of three
> possible encoding forms for the string '?z':
>
> UTF-16: either two, or four, bytes per character: 03C0 007A
>
> UTF-32: exactly four bytes per character: 000003C0 0000007A
>
> UTF-8: between one and four bytes per character: CF80 7A

I have not tallied up how many code points are actually assigned to
characters.  Does UTF-8 encoding currently cover all of them?  If yes,
why is there a need for other encodings?  Or by saying:

> (UTF-16 and UTF-32 are hardware-dependent, and the byte order could be
> reversed, e.g. C003 7A00. UTF-8 is not.)

do you mean that some hardware configurations require UTF-16 or UTF-32?

Thank you (and the others in this thread) for taking the time to
clarify these matters.

-- 
boB

From cs at zip.com.au  Sun Feb  5 23:49:44 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Mon, 6 Feb 2017 15:49:44 +1100
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9K21yfqunvvn7Qtu3afvp6oLr42HaZoYhwBgJugxWOGyA@mail.gmail.com>
References: <CANDiX9K21yfqunvvn7Qtu3afvp6oLr42HaZoYhwBgJugxWOGyA@mail.gmail.com>
Message-ID: <20170206044944.GA69293@cskk.homeip.net>

On 05Feb2017 22:27, boB Stepp <robertvstepp at gmail.com> wrote:
>On Sun, Feb 5, 2017 at 7:23 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> Alternatively, you can embed it right in the string. For code points
>> between U+0000 and U+FFFF, use the \u escape, and for the rest, use \U
>> escapes:
>>
>> py> 'pi = \u03C0'  # requires exactly four hex digits
>> 'pi = ?'
>>
>> py> 'pi = \U000003C0'  # requires exactly eight hex digits
>> 'pi = ?'
>>
>>
>> Lastly, you can use the code point's name:
>>
>> py> 'pi = \N{GREEK SMALL LETTER PI}'
>> 'pi = ?'
>
>You have surprised me here by using single quotes to enclose the
>entire assignment statements.  I thought this would throw a syntax
>error, but it works just like you show.  What is going on here?

It's not an assignment statement. It's just a string. He's typing a string 
containing a \N{...} sequence and Python's printing that string back at you; 
pi's a printable character and gets displayed directly.

Try with this:

  py> 'here is a string\n\nline 3'

>> One last comment: Random832 said:
>> "Python 3 strings are unicode-unicode, not UTF-8."
>
>If I recall what I originally wrote (and intended) I was merely
>indicating I was happy with Python 3's default UTF-8 encoding.  I do
>not know enough to know what these other UTF encodings offer.

From the outside (i.e. to your code) Python 3 strings are sequences of Unicode 
code points (characters, near enough). How they're _stored_ internally is not 
your problem:-) When you write a string to a file or the terminal etc, the 
string needs to be _encoded_ into a sequence of bytes (a sequence of bytes 
because there are more Unicode code points than can be expressed with one 
byte).

UTF-8 is by far the commonest such encoding in use. It has several nice 
characteristics: for one, the ASCII code points _are_ stored in a single byte.  
While that's nice for Western almost-only-speaking-English folks like me, it 
also means that the zillions of extisting ASCII text files don't need to be 
recoded to work in UTF-8. It has other cool features too.

>> To be pedantic, Unicode strings are sequences of abstract code points
>> ("characters"). UTF-8 is a particular concrete implementation that is
>> used to store or transmit such code strings. Here are examples of three
>> possible encoding forms for the string '?z':
>>
>> UTF-16: either two, or four, bytes per character: 03C0 007A
>>
>> UTF-32: exactly four bytes per character: 000003C0 0000007A
>>
>> UTF-8: between one and four bytes per character: CF80 7A
>
>I have not tallied up how many code points are actually assigned to
>characters.  Does UTF-8 encoding currently cover all of them?  If yes,
>why is there a need for other encodings?  Or by saying:

UTF-8 is variable length. You can leap into the middle of a UTF-8 string and 
resync (== find the first byte of the next character) thanks to its neat coding 
design, but you can't "seek" directly to the position of an arbitrarily 
numbered character (eg go to character 102345). By contract, UTF-32 is fixed 
length.

>> (UTF-16 and UTF-32 are hardware-dependent, and the byte order could be
>> reversed, e.g. C003 7A00. UTF-8 is not.)
>
>do you mean that some hardware configurations require UTF-16 or UTF-32?

No, different machines order the bytes in a larger word in different orders.  
"Big endian" machines like SPARCs and M68k etc put the most significant bytes 
first; little endian machines put the least significant bytes first (eg Intel 
architecture machines). (Aside: the Alpha was switchable.)

So that "natural" way to write UTF-16 or UTF-32 might be big or little endian, 
and you need to know what was chosen for a given file.

Cheers,
Cameron Simpson <cs at zip.com.au>

From robertvstepp at gmail.com  Mon Feb  6 07:13:13 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 6 Feb 2017 06:13:13 -0600
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <20170206044944.GA69293@cskk.homeip.net>
References: <CANDiX9K21yfqunvvn7Qtu3afvp6oLr42HaZoYhwBgJugxWOGyA@mail.gmail.com>
 <20170206044944.GA69293@cskk.homeip.net>
Message-ID: <CANDiX9Ksc_SOgOcRn+gT0BAyry8Zutv5+h-OQ06=Yjxq6RiGdA@mail.gmail.com>

On Sun, Feb 5, 2017 at 10:49 PM, Cameron Simpson <cs at zip.com.au> wrote:
> On 05Feb2017 22:27, boB Stepp <robertvstepp at gmail.com> wrote:
>>
>> On Sun, Feb 5, 2017 at 7:23 PM, Steven D'Aprano <steve at pearwood.info>
>> wrote:
>>>
>>> Alternatively, you can embed it right in the string. For code points
>>> between U+0000 and U+FFFF, use the \u escape, and for the rest, use \U
>>> escapes:
>>>
>>> py> 'pi = \u03C0'  # requires exactly four hex digits
>>> 'pi = ?'
>>>
>>> py> 'pi = \U000003C0'  # requires exactly eight hex digits
>>> 'pi = ?'
>>>
>>>
>>> Lastly, you can use the code point's name:
>>>
>>> py> 'pi = \N{GREEK SMALL LETTER PI}'
>>> 'pi = ?'
>>
>>
>> You have surprised me here by using single quotes to enclose the
>> entire assignment statements.  I thought this would throw a syntax
>> error, but it works just like you show.  What is going on here?
>
>
> It's not an assignment statement. It's just a string. He's typing a string
> containing a \N{...} sequence and Python's printing that string back at you;
> pi's a printable character and gets displayed directly.

I just came out of the shower this morning thinking, "Stupid boB,
stupid.  That's just an escape sequence inside an overall string, not
an assignment statement."  Duh!  My brain works better asleep than
awake...

boB

From george at fischhof.hu  Mon Feb  6 07:12:39 2017
From: george at fischhof.hu (George Fischhof)
Date: Mon, 6 Feb 2017 13:12:39 +0100
Subject: [Tutor] Function annotations
In-Reply-To: <20170205083658.GS7345@ando.pearwood.info>
References: <CANDiX9JvCHB4Nt=h+uRay3HNgZgV7VuWZWMYmJ0=3LJbmsrBOg@mail.gmail.com>
 <20170205032354.GP7345@ando.pearwood.info>
 <CANDiX9LO0ot9noy2EsCdpSOGaH=bDnUf9r47=FOCmwucCTEQ+A@mail.gmail.com>
 <20170205083658.GS7345@ando.pearwood.info>
Message-ID: <CAFwcP0jzpJqGknZVR8Z+Tef9KNOSgUek+0zx9Mjj39PDETzHHw@mail.gmail.com>

2017-02-05 9:36 GMT+01:00 Steven D'Aprano <steve at pearwood.info>:

> On Sat, Feb 04, 2017 at 10:11:39PM -0600, boB Stepp wrote:
>
> > Are the people making linters implementing checking function
> > annotations?  Or is this something only gradually being adopted?
>
> Depends which linter :-)
>
> MyPy is still the reference implementation for type hinting in Python:
>
> http://mypy-lang.org/
>
> As for pychecker, pylint, jedi, pyflakes, etc you'll have to check with
> the individual application itself.
>
> > Steve, are you making use of function annotations?  If yes, are you
> > finding them worth the extra effort?
>
> Not yet.
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



Hi,

Pycharm ide has a built-in linter, and it is very good!  It shows the
result in code writing time.

George

From alan.gauld at yahoo.co.uk  Mon Feb  6 14:39:48 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 6 Feb 2017 19:39:48 +0000
Subject: [Tutor] sort() method and non-ASCII
In-Reply-To: <CANDiX9Ksc_SOgOcRn+gT0BAyry8Zutv5+h-OQ06=Yjxq6RiGdA@mail.gmail.com>
References: <CANDiX9K21yfqunvvn7Qtu3afvp6oLr42HaZoYhwBgJugxWOGyA@mail.gmail.com>
 <20170206044944.GA69293@cskk.homeip.net>
 <CANDiX9Ksc_SOgOcRn+gT0BAyry8Zutv5+h-OQ06=Yjxq6RiGdA@mail.gmail.com>
Message-ID: <o7ajdu$heu$1@blaine.gmane.org>

On 06/02/17 12:13, boB Stepp wrote:
>>>> py> 'pi = \N{GREEK SMALL LETTER PI}'
>>>> 'pi = ?'
>>>
>>>
>>> You have surprised me here by using single quotes to enclose the
>>> entire assignment statements.  I thought this would throw a syntax
>>> error, but it works just like you show.  What is going on here?

> I just came out of the shower this morning thinking, "Stupid boB,
> stupid.  That's just an escape sequence inside an overall string, not
> an assignment statement."  Duh!  My brain works better asleep than
> awake...

To be fair it did look like an assignment so when I first
saw it I too went "huh?!". But then I looked again and
figured it out. :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From poojabhalode11 at gmail.com  Mon Feb  6 11:40:07 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Mon, 6 Feb 2017 11:40:07 -0500
Subject: [Tutor] Multiple tabs using tkinter
Message-ID: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>

Hi,

I was wondering if someone could help me regarding multiple tabs in
tkinter.
I am working on a GUI which would have tabs similar to the ones we see in
excel, wherein we can navigate from one tab to the other and back. Could
you please direct me towards some information regarding how I should
proceed with this issue.
It would be a great help.

Also, I was wondering if there is a way in tkinter to create an explorer
bar that we see in finder in OS Mac or windows. I found a way to do that
using wxpython, but was wondering if there is a way using tkinter.
Please let me know. It would help me a lot. Would appreciate any help.
thank you

Pooja

From huseyin at piramit.com.tr  Mon Feb  6 11:13:35 2017
From: huseyin at piramit.com.tr (=?iso-8859-9?Q?H=FCseyin_Ertu=F0rul?=)
Date: Mon, 6 Feb 2017 16:13:35 +0000
Subject: [Tutor] Basic Tutorial for Python
Message-ID: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>

Hello all,
I am a system engineer and I want to learn python language. I don't know any program language and I need tutorial for beginner or for dummies.
By the way I want to see basic example codes for practice.

What is your suggestion for that case.

Thank you for your interest.

From john.b.larocca at intel.com  Mon Feb  6 19:08:09 2017
From: john.b.larocca at intel.com (Larocca, John B)
Date: Tue, 7 Feb 2017 00:08:09 +0000
Subject: [Tutor] Basic Tutorial for Python
In-Reply-To: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
References: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
Message-ID: <C91D0AAC93B84D4FB5D5C2B84682796F3C44AE31@FMSMSX105.amr.corp.intel.com>

I like this one...
https://learnpythonthehardway.org/book/
It can be done all online

-John

-----Original Message-----
From: Tutor [mailto:tutor-bounces+john.b.larocca=intel.com at python.org] On Behalf Of H?seyin Ertugrul
Sent: Monday, February 06, 2017 8:14 AM
To: tutor at python.org
Subject: [Tutor] Basic Tutorial for Python

Hello all,
I am a system engineer and I want to learn python language. I don't know any program language and I need tutorial for beginner or for dummies.
By the way I want to see basic example codes for practice.

What is your suggestion for that case.

Thank you for your interest.
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From steve at pearwood.info  Mon Feb  6 19:32:06 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 Feb 2017 11:32:06 +1100
Subject: [Tutor] Basic Tutorial for Python
In-Reply-To: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
References: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
Message-ID: <20170207003205.GV7345@ando.pearwood.info>

On Mon, Feb 06, 2017 at 04:13:35PM +0000, H?seyin Ertu?rul wrote:

> Hello all,

> I am a system engineer and I want to learn python language. I don't 
> know any program language and I need tutorial for beginner or for 
> dummies.

Alan's tutorial is worth working through:

http://www.alan-g.me.uk/

You can also look at the official tutorials. For version 2.7:

https://docs.python.org/2/tutorial/

For version 3:

https://docs.python.org/3/tutorial/


More resources here:

https://wiki.python.org/moin/BeginnersGuide/NonProgrammers


-- 
Steve

From akleider at sonic.net  Mon Feb  6 19:52:50 2017
From: akleider at sonic.net (Alex Kleider)
Date: Mon, 06 Feb 2017 16:52:50 -0800
Subject: [Tutor] Basic Tutorial for Python
In-Reply-To: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
References: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
Message-ID: <895d8c8e9bd0976d2bc4846ccdaecbfc@sonic.net>

On 2017-02-06 08:13, H?seyin Ertu?rul wrote:
> Hello all,
> I am a system engineer and I want to learn python language. I don't
> know any program language and I need tutorial for beginner or for
> dummies.
> By the way I want to see basic example codes for practice.
> 
> What is your suggestion for that case.

Allen B. Downey's book served me very well when I first got interested 
in Python; he's now got a Python 3 version as well.
It's available free on the web, or you can buy the book on Amazon and 
elsewhere.
http://greenteapress.com/wp/think-python/

From alan.gauld at yahoo.co.uk  Mon Feb  6 20:31:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 01:31:27 +0000
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
Message-ID: <o7b819$pqu$1@blaine.gmane.org>

On 06/02/17 16:40, Pooja Bhalode wrote:

> I was wondering if someone could help me regarding multiple tabs in
> tkinter.

Look at the tabbed notebook in the Tix module.
It should do what you want.

I give a tutorial on its use in my recent book but you can
also find online tutorials, especially in Tcl (Python ones
are much harder to find)

> Also, I was wondering if there is a way in tkinter to create an explorer
> bar that we see in finder in OS Mac or windows. I found a way to do that
> using wxpython, but was wondering if there is a way using tkinter.

Tkinter is a relatively low level GUI toolkit. You can
build most things but you have to start with the basic
widgets. So an explorer bar is just an Entry widget to
which you can attach any functionality you care to create.

The same applies to Status bars. In Tkinter its just a
label in a frame that you have to update in your code.
In other tookits there are status bar widgets that other
widgets know how to use with just a reference.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb  6 20:37:59 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 01:37:59 +0000
Subject: [Tutor] Basic Tutorial for Python
In-Reply-To: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
References: <VI1PR0601MB23183A13EB7F9B582108A24D92400@VI1PR0601MB2318.eurprd06.prod.outlook.com>
Message-ID: <o7b8dh$onk$1@blaine.gmane.org>

On 06/02/17 16:13, H?seyin Ertu?rul wrote:
> Hello all,
> I am a system engineer and I want to learn python language. 
> I don't know any program language

That's a common request and the python.org site has a whole page
dedicated to folks like you.

https://wiki.python.org/moin/BeginnersGuide/NonProgrammers

It lists many tutorials (including mine below)and they all
do the job. It just depends on what kind of style you prefer.
(Some aim at leisure users with emphasis on games etc, others
are targeted at more serious users and focus on, say,
sysadmin type tasks, some are more academically correct,
others easier to read but less rigorous). Try a couple and
go with whatever looks most to your taste.

If (when!) you get stuck or puzzled ask questions here.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From zachary.ware+pytut at gmail.com  Mon Feb  6 22:31:01 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Mon, 6 Feb 2017 21:31:01 -0600
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <o7b819$pqu$1@blaine.gmane.org>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
Message-ID: <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>

On Mon, Feb 6, 2017 at 7:31 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 06/02/17 16:40, Pooja Bhalode wrote:
>
>> I was wondering if someone could help me regarding multiple tabs in
>> tkinter.
>
> Look at the tabbed notebook in the Tix module.
> It should do what you want.

ttk rather than Tix; Tix is unmaintained and soft-deprecated in 3.6+.
ttk provides most of the useful parts of Tix, is maintained as part of
Tk, and also looks significantly more native than classic Tk or Tix.
Tix is also less available on platforms other than Windows, whereas
ttk is present in any Tk 8.5 or greater.

> I give a tutorial on its use in my recent book but you can
> also find online tutorials, especially in Tcl (Python ones
> are much harder to find)
>
>> Also, I was wondering if there is a way in tkinter to create an explorer
>> bar that we see in finder in OS Mac or windows. I found a way to do that
>> using wxpython, but was wondering if there is a way using tkinter.
>
> Tkinter is a relatively low level GUI toolkit. You can
> build most things but you have to start with the basic
> widgets. So an explorer bar is just an Entry widget to
> which you can attach any functionality you care to create.

Also have a look at ttk.Combobox, which combines an Entry and Listbox
(and, I think, if the list is long enough, a Scrollbar) into a
drop-down menu widget.

-- 
Zach

From garcia.laura1415 at gmail.com  Mon Feb  6 21:12:58 2017
From: garcia.laura1415 at gmail.com (Laura Garcia)
Date: Mon, 6 Feb 2017 18:12:58 -0800
Subject: [Tutor] Help Please on python
In-Reply-To: <CAGM-EYafq00PHGdM82Qb7LVvWhyoMF2gknhFmicGxmuEPDjBGw@mail.gmail.com>
References: <CAGM-EYbzRzFQu3utQ8U_OSA-6BBOVWeiBmdNWDhj9PR8+V60dQ@mail.gmail.com>
 <CAGM-EYaZ8ydwVMVc+27UfOk6vLqEDOrt24yOGXydj5YxNAUBjg@mail.gmail.com>
 <CAGM-EYZJvNFEevGov-OhiNJRg_utW=OwdLfh5cXSD9j5wFfo8Q@mail.gmail.com>
 <CAGM-EYafq00PHGdM82Qb7LVvWhyoMF2gknhFmicGxmuEPDjBGw@mail.gmail.com>
Message-ID: <CAGM-EYb9zrCvZPCDiCFm4nANJ40HXe35JaQnr8+wgF7qo0qreg@mail.gmail.com>

I need to create a python code that  should simulate throwing darts by
random landing between (a random x and a random y)0 and 1.  and the program
should print out number of darts that land within a rectangle.

From poojabhalode11 at gmail.com  Mon Feb  6 19:24:55 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Mon, 6 Feb 2017 19:24:55 -0500
Subject: [Tutor] Tkinter Calendar to receive user entry.
Message-ID: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>

Hi,

I am trying to create a calendar using tkinter GUI such that when the user
opens the GUI, it would show a drop down menu similar to the one seen on
flight websites for booking and then the user can select any specific date.
I need to make this such that the user can navigate between years and
months in the same window.

Can some one please help me with this? I looked up on the website, I came
across this one,
http://stackoverflow.com/questions/27774089/python-calendar-widget-return-the-user-selected-date
But when I try to run it, it gives me an error saying that it is not able
to recognize Calendar.

I would really appreciate some help with this. I also came to know that I
could use calendar.Calendar to create an object for the same, but I am not
good with working with objects and thus, not able to proceed or understand
how to link it up with GUI.

Please let me know.
Thankyou

Pooja

From poojabhalode11 at gmail.com  Mon Feb  6 22:56:38 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Mon, 6 Feb 2017 22:56:38 -0500
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
Message-ID: <CAK0ikxfVcQyNb+GSbe9F3nL1Tm=U59ROkaYeq172ZpyWcmvqVw@mail.gmail.com>

Hi Alan and Zackary,

Thank you so much for your inputs. I really appreciate any help on these
things.

Alan,

you mentioned that there are multiple toolkits which can be used instead of
tkinter. I was also looking into wxpython for building a explorer bar.
Mainly, I have to build a software entirely using python and thus, needed
all these things put in place. I have been exploring things on how to do
small bits of these using Tkinter. Would you suggest me to use some other
toolkit instead of tkinter or maybe combine and use whichever whenever
needed?

I was just going through your website and looking at the tutorials, wanted
to thank you. I think those would be really really helpful.

Zackary,

I tried using ttk for the multiple tabs feature and that worked out really
nicely.
Thank you once again.
I would also look into the ttk.Combobox package. Thank you

Yours truly,
Pooja


On Mon, Feb 6, 2017 at 10:31 PM, Zachary Ware <zachary.ware+pytut at gmail.com>
wrote:

> On Mon, Feb 6, 2017 at 7:31 PM, Alan Gauld via Tutor <tutor at python.org>
> wrote:
> > On 06/02/17 16:40, Pooja Bhalode wrote:
> >
> >> I was wondering if someone could help me regarding multiple tabs in
> >> tkinter.
> >
> > Look at the tabbed notebook in the Tix module.
> > It should do what you want.
>
> ttk rather than Tix; Tix is unmaintained and soft-deprecated in 3.6+.
> ttk provides most of the useful parts of Tix, is maintained as part of
> Tk, and also looks significantly more native than classic Tk or Tix.
> Tix is also less available on platforms other than Windows, whereas
> ttk is present in any Tk 8.5 or greater.
>
> > I give a tutorial on its use in my recent book but you can
> > also find online tutorials, especially in Tcl (Python ones
> > are much harder to find)
> >
> >> Also, I was wondering if there is a way in tkinter to create an explorer
> >> bar that we see in finder in OS Mac or windows. I found a way to do that
> >> using wxpython, but was wondering if there is a way using tkinter.
> >
> > Tkinter is a relatively low level GUI toolkit. You can
> > build most things but you have to start with the basic
> > widgets. So an explorer bar is just an Entry widget to
> > which you can attach any functionality you care to create.
>
> Also have a look at ttk.Combobox, which combines an Entry and Listbox
> (and, I think, if the list is long enough, a Scrollbar) into a
> drop-down menu widget.
>
> --
> Zach
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From sasil.adetunji at gmail.com  Mon Feb  6 23:08:49 2017
From: sasil.adetunji at gmail.com (Sasiliyu Adetunji)
Date: Tue, 7 Feb 2017 05:08:49 +0100
Subject: [Tutor] Help with this work
Message-ID: <CACv2vyw=XGWJqY8A8qC-x=FBJi7n1-Q6JLfcfOypX1Q1eNG8_w@mail.gmail.com>

Hi,
I have been working on yhis assignment

Create a class called ShoppingCart

Create a constructor that takes no arguments and sets the total attribute
to zero, and initializes an empty dict attribute named items.

Create a method add_item that requires item_name, quantity and price arguments.
This method should add the cost of the added items to the current value of
total. It should also add an entry to the items dict such that the key is
the item_name and the value is the quantity of the item.

Create a method remove_item that requires similar arguments as add_item. It
should remove items that have been added to the shopping cart and are not
required. This method should deduct the cost of the removed items from the
current total and also update the items dict accordingly.

If the quantity of an item to be removed exceeds the current quantity of
that item in the cart, assume that all entries of that item are to be
removed.

Create a method checkout that takes in cash_paid and returns the value of
balance from the payment. If cash_paid is not enough to cover the total,
return "Cash paid not enough".

Create a class called Shop that has a constructor which takes no arguments
and initializes an attribute called quantity at 100.

Make sure Shop inherits from ShoppingCart.

In the Shop class, override the remove_item method, such that calling
Shop's remove_item with no arguments decrements quantity by one.


For now this is what i have

class ShoppingCart(object):

  def __init__(self):

    self.total = 0

    self.items = {}

  def add_item(self, item_name, quantity, price):

    if not item_name in self.items:

      self.items[item_name] = quantity

    else:

      self.items[item_name] += quantity

    self.total += quantity * price

  def remove_item(self, item_name, quantity, price):

    if quantity > self.items[item_name]:

      self.items[item_name] = quantity

    else:

      self.items[item_name] -= quantity

    self.total -= quantity * price

  def checkout(self, cash_paid):

    self.cash_paid = cash_paid

    if cash_paid < self.total:

      return "Cash paid not enough"

    else:

      return cash_paid - self.total


class Shop(ShoppingCart):

  def __init__(self):

    self.quantity = 100

  def remove_item(self):

    self.quantity -= 1

Kindly assist me

From alan.gauld at yahoo.co.uk  Tue Feb  7 04:45:37 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 09:45:37 +0000
Subject: [Tutor] Tkinter Calendar to receive user entry.
In-Reply-To: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>
References: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>
Message-ID: <o7c4vr$e03$1@blaine.gmane.org>

On 07/02/17 00:24, Pooja Bhalode wrote:

> I am trying to create a calendar using tkinter GUI such that when the user
> opens the GUI, 

So far as I'm aware there is no such Calendar widget in the standard
modules, you would need to find a third party module.

> Can some one please help me with this? I looked up on the website, I came
> across this one,
> http://stackoverflow.com/questions/27774089/python-calendar-widget-return-the-user-selected-date
> But when I try to run it, it gives me an error saying that it is not able
> to recognize Calendar.

I'm really puzzled by that post because there is non Calendar widget
in ttk (or Tix) as of Python 3.4. They are discussing code that
should not work but they seem to have it working. I assume there
is a non standard ttk module out there somewhere?

> I would really appreciate some help with this. I also came to know that I
> could use calendar.Calendar to create an object for the same, but I am not
> good with working with objects 

You probably need to spend some time on that first. Everything
in Python is an object (even strings and numbers and lists etc).
So you really need to get comfortable with the idea of
accessing attributes and methods of objects.

You don't need to worry about creating classes and so on(yet),
but you do need to understand how to use other peoples objects.

Finally, if you are going to ask questions about code its
always good to show us exactly what code you typed as well
as the full error message.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb  7 04:47:41 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 09:47:41 +0000
Subject: [Tutor] Help Please on python
In-Reply-To: <CAGM-EYb9zrCvZPCDiCFm4nANJ40HXe35JaQnr8+wgF7qo0qreg@mail.gmail.com>
References: <CAGM-EYbzRzFQu3utQ8U_OSA-6BBOVWeiBmdNWDhj9PR8+V60dQ@mail.gmail.com>
 <CAGM-EYaZ8ydwVMVc+27UfOk6vLqEDOrt24yOGXydj5YxNAUBjg@mail.gmail.com>
 <CAGM-EYZJvNFEevGov-OhiNJRg_utW=OwdLfh5cXSD9j5wFfo8Q@mail.gmail.com>
 <CAGM-EYafq00PHGdM82Qb7LVvWhyoMF2gknhFmicGxmuEPDjBGw@mail.gmail.com>
 <CAGM-EYb9zrCvZPCDiCFm4nANJ40HXe35JaQnr8+wgF7qo0qreg@mail.gmail.com>
Message-ID: <o7c53n$e03$2@blaine.gmane.org>

On 07/02/17 02:12, Laura Garcia wrote:
> I need to create a python code that  should simulate throwing darts by
> random landing between (a random x and a random y)0 and 1.  and the program
> should print out number of darts that land within a rectangle.

Look in the random module. There are a bunch of different
random number generating functions in thee, just choose
the one that looks best suited to your task.

For the rest its just a case of some basic math. Write
some code and if you get stuck come back with a specific
question and we can try to answer it.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb  7 04:56:00 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 09:56:00 +0000
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
Message-ID: <o7c5ja$is6$1@blaine.gmane.org>

On 07/02/17 03:31, Zachary Ware wrote:

> ttk rather than Tix; Tix is unmaintained and soft-deprecated in 3.6+.

Really? Thats a pity.
Tix was supposed to be the module with the extra widgets
and ttk was purely the themed versions of same. Its a shame
to confuse their purposes.

OTOH it does mean that the full range of widgets should
hopefully appear in ttk. Does that also mean that ttk
is now a full superset of Tkinter like Tix? (ttk used
to be a subset so you had to import both...)

> Tk, and also looks significantly more native than classic Tk or Tix.

Sure that was its original purpose.

> Tix is also less available on platforms other than Windows, 

Really? I've used it on Windows and Linux.
Where is it missing? - MacOS?

You may finally have just given me a motivation to move to
Python 3.6 from 3.4... :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb  7 05:13:33 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 10:13:33 +0000
Subject: [Tutor] Help with this work
In-Reply-To: <CACv2vyw=XGWJqY8A8qC-x=FBJi7n1-Q6JLfcfOypX1Q1eNG8_w@mail.gmail.com>
References: <CACv2vyw=XGWJqY8A8qC-x=FBJi7n1-Q6JLfcfOypX1Q1eNG8_w@mail.gmail.com>
Message-ID: <o7c6k7$qjm$1@blaine.gmane.org>

On 07/02/17 04:08, Sasiliyu Adetunji wrote:
> I have been working on yhis assignment

You are asking for help but in what regard?
There is no question or problem statement in your post?

I've put some general comments below...

> class ShoppingCart(object):
> 
>   def __init__(self):
>     self.total = 0
>     self.items = {}
> 
>   def add_item(self, item_name, quantity, price):
>     if not item_name in self.items:
>       self.items[item_name] = quantity
>     else:
>       self.items[item_name] += quantity

This is often better done using the get()
or setdefault() methods of the dictionary.
For example:

self.items[item_name] = self.items.get(item_name,0)) + quantity

>     self.total += quantity * price
> 
>   def remove_item(self, item_name, quantity, price):
>     if quantity > self.items[item_name]:
>       self.items[item_name] = quantity
>     else:
>       self.items[item_name] -= quantity
>     self.total -= quantity * price

I'm pretty sure the first part of the if statement is wrong.
Read the specification again.

Also there is a more subtle problem with your last line
if quantity is greater than the stored self.items count.
Try working through it manually with some before/after
figures and see if the results are what you would expect.

>   def checkout(self, cash_paid):
>     self.cash_paid = cash_paid
>     if cash_paid < self.total:
>       return "Cash paid not enough"
>     else:
>       return cash_paid - self.total

This meets the specification but I hate the design
here. But that's not your fault....

> class Shop(ShoppingCart):
>   def __init__(self):
>     self.quantity = 100
> 
>   def remove_item(self):
>     self.quantity -= 1
> 

It says override the remove_item.
But shopping carts remove_item takes 3 parameters
so your new version should take the same three
parameters. It should probably call the superclass's
remove_item too. However I agree that you have done
what the spec asked for, I just suspect the spec
is badly written for this particular case...

> Kindly assist me

In what way? You haven't said what the issue is.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Tue Feb  7 05:18:53 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 07 Feb 2017 11:18:53 +0100
Subject: [Tutor] Tkinter Calendar to receive user entry.
References: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>
 <o7c4vr$e03$1@blaine.gmane.org>
Message-ID: <o7c6u9$fsg$1@blaine.gmane.org>

Alan Gauld via Tutor wrote:

> On 07/02/17 00:24, Pooja Bhalode wrote:
> 
>> I am trying to create a calendar using tkinter GUI such that when the
>> user opens the GUI,
> 
> So far as I'm aware there is no such Calendar widget in the standard
> modules, you would need to find a third party module.
> 
>> Can some one please help me with this? I looked up on the website, I came
>> across this one,
>> http://stackoverflow.com/questions/27774089/
>> python-calendar-widget-return-the-user-selected-date
>> But when I try to run it, it gives me an error saying that it is not able
>> to recognize Calendar.
> 
> I'm really puzzled by that post because there is non Calendar widget
> in ttk (or Tix) as of Python 3.4. They are discussing code that
> should not work but they seem to have it working. I assume there
> is a non standard ttk module out there somewhere?

The question on stackoverflow points to

http://svn.python.org/projects/sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py

A few imports are sufficient to turn test2() from the answer into a working 
script (python 2):

$ cat demo.py
#!/usr/bin/env python
import calendar
import ttk
import Tkinter
from ttkcalendar import Calendar

def test2():
    import sys
    root = Tkinter.Tk()
    root.title('Ttk Calendar')
    ttkcal = Calendar(firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')

    if 'win' not in sys.platform:
        style = ttk.Style()
        style.theme_use('clam')

    root.mainloop()

    x = ttkcal.selection    
    print 'x is: ', x

test2()
$ ./demo.py 
x is:  2017-05-11 00:00:00



From alan.gauld at yahoo.co.uk  Tue Feb  7 05:23:23 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 10:23:23 +0000
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <CAK0ikxfVcQyNb+GSbe9F3nL1Tm=U59ROkaYeq172ZpyWcmvqVw@mail.gmail.com>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
 <CAK0ikxfVcQyNb+GSbe9F3nL1Tm=U59ROkaYeq172ZpyWcmvqVw@mail.gmail.com>
Message-ID: <o7c76m$sr1$1@blaine.gmane.org>

On 07/02/17 03:56, Pooja Bhalode wrote:

> you mentioned that there are multiple toolkits which can be used instead of
> tkinter. I was also looking into wxpython for building a explorer bar.
> Mainly, I have to build a software entirely using python and thus, needed
> all these things put in place. I have been exploring things on how to do
> small bits of these using Tkinter. Would you suggest me to use some other
> toolkit instead of tkinter or maybe combine and use whichever whenever
> needed?

You can do it all in Tkinter if you want, it just takes more work. You
will need to create your own widgets. Other toolkits (like wxPython)
come with more powerful widgets already built, but the trade off is that
they are
1) not part of standard python which means you (and your users)
   need to install them
2) They are usually more difficult(*) to use than Tkinter
   (and will require more OOP knowlege than you currently have)

(*)But thats a relative thing, they are not very
difficult, just different. And once you get into them they
are much easier to use than creating your own widgets!
But there are no perfect toolkits, you need to look at
each and judge which one is best for you.

There is a page here that lists most of the options:

https://wiki.python.org/moin/GuiProgramming

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From zachary.ware+pytut at gmail.com  Tue Feb  7 11:41:43 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Tue, 7 Feb 2017 10:41:43 -0600
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <o7c5ja$is6$1@blaine.gmane.org>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
 <o7c5ja$is6$1@blaine.gmane.org>
Message-ID: <CAKJDb-OphDpWDxgYJ=cJpD5O3Vs4oOQmGTeR9UY_hT=2V0JkdQ@mail.gmail.com>

On Tue, Feb 7, 2017 at 3:56 AM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 07/02/17 03:31, Zachary Ware wrote:
>
>> ttk rather than Tix; Tix is unmaintained and soft-deprecated in 3.6+.
>
> Really? Thats a pity.
> Tix was supposed to be the module with the extra widgets
> and ttk was purely the themed versions of same. Its a shame
> to confuse their purposes.

Full disclosure, I've never actually used Tix beyond making it build
with the rest of CPython on Windows and making sure it actually worked
on one of my Linux buildbot workers.  I have only ever seen it as a
maintenance headache :)

I have used tkinter and specifically ttk quite a bit, though, and
never felt like anything that was present in Tix was missing from ttk.

> OTOH it does mean that the full range of widgets should
> hopefully appear in ttk. Does that also mean that ttk
> is now a full superset of Tkinter like Tix? (ttk used
> to be a subset so you had to import both...)

There are some things that still need to be imported from tkinter
rather than tkinter.ttk; tkinter.ttk is mostly just the themed widgets
and style manipulation stuff, whereas support functions/constants/etc.
are in tkinter.  My usual idiom is

   import tkinter as tk
   from tkinter import ttk

but it's also possible to do "from tkinter import *; from tkinter.ttk
import *" if you like the star import idiom for tkinter.

>> Tk, and also looks significantly more native than classic Tk or Tix.
>
> Sure that was its original purpose.
>
>> Tix is also less available on platforms other than Windows,
>
> Really? I've used it on Windows and Linux.
> Where is it missing? - MacOS?

"Less available" rather than "unavailable" :).  Tix ships with Tcl/Tk
with CPython on Windows; on Linux, you'd need to install it separately
from Tcl/Tk and python/tkinter.  I honestly don't have a clue how
you'd get it on macOS or any other platform that doesn't provide it in
a system repository.

> You may finally have just given me a motivation to move to
> Python 3.6 from 3.4... :-)

Not much has changed between 3.4 and 3.6 in tkinter-land, but I'd
still recommend the upgrade anyway.  Many nice new features in 3.5 and
3.6 :).

-- 
Zach

From poojabhalode11 at gmail.com  Tue Feb  7 09:39:03 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Tue, 7 Feb 2017 09:39:03 -0500
Subject: [Tutor] Tkinter Calendar to receive user entry.
In-Reply-To: <o7c6u9$fsg$1@blaine.gmane.org>
References: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>
 <o7c4vr$e03$1@blaine.gmane.org> <o7c6u9$fsg$1@blaine.gmane.org>
Message-ID: <CAK0ikxeKUZRg9v-UOpW7TDs00V3LiQ4QF+p1XTUHw4juS9PR3g@mail.gmail.com>

Hi Alan,

Thank you so much for your advice, I would start looking into learning some
object oriented programming to make myself familiar with it. That would
help me move ahead as well.

Hi Peter,

Thank you so much for your reply. Yes, that was the example that I was
looking at on stackoverflow. Yes, it works for me as well now. Thanks a lot
for your help there.

Yours truly,
Pooja

On Tue, Feb 7, 2017 at 5:18 AM, Peter Otten <__peter__ at web.de> wrote:

> Alan Gauld via Tutor wrote:
>
> > On 07/02/17 00:24, Pooja Bhalode wrote:
> >
> >> I am trying to create a calendar using tkinter GUI such that when the
> >> user opens the GUI,
> >
> > So far as I'm aware there is no such Calendar widget in the standard
> > modules, you would need to find a third party module.
> >
> >> Can some one please help me with this? I looked up on the website, I
> came
> >> across this one,
> >> http://stackoverflow.com/questions/27774089/
> >> python-calendar-widget-return-the-user-selected-date
> >> But when I try to run it, it gives me an error saying that it is not
> able
> >> to recognize Calendar.
> >
> > I'm really puzzled by that post because there is non Calendar widget
> > in ttk (or Tix) as of Python 3.4. They are discussing code that
> > should not work but they seem to have it working. I assume there
> > is a non standard ttk module out there somewhere?
>
> The question on stackoverflow points to
>
> http://svn.python.org/projects/sandbox/trunk/ttk-
> gsoc/samples/ttkcalendar.py
>
> A few imports are sufficient to turn test2() from the answer into a working
> script (python 2):
>
> $ cat demo.py
> #!/usr/bin/env python
> import calendar
> import ttk
> import Tkinter
> from ttkcalendar import Calendar
>
> def test2():
>     import sys
>     root = Tkinter.Tk()
>     root.title('Ttk Calendar')
>     ttkcal = Calendar(firstweekday=calendar.SUNDAY)
>     ttkcal.pack(expand=1, fill='both')
>
>     if 'win' not in sys.platform:
>         style = ttk.Style()
>         style.theme_use('clam')
>
>     root.mainloop()
>
>     x = ttkcal.selection
>     print 'x is: ', x
>
> test2()
> $ ./demo.py
> x is:  2017-05-11 00:00:00
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From rskovron at gmail.com  Tue Feb  7 10:34:36 2017
From: rskovron at gmail.com (Rafael Skovron)
Date: Tue, 7 Feb 2017 07:34:36 -0800
Subject: [Tutor] Error when trying to use classes
Message-ID: <CABXYKTr++q1iY4FE7U0YY4z3X1ZbtYnak_q2k8Raj_dU9KHRdA@mail.gmail.com>

I'm trying to learn how to use Classes but I keep getting  NameErrors no
matter what code I put into the script.

Any ideas why?

My general workflow is I edit in vim, then invoke python3 interpreter,
import the module and try to use the Class and methods from the class.

For example, importing customer.py and assigning this object yields:

>>> rafael = Customer('rafael',100.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Customer' is not defined



class Customer(object):
    """A customer of ABC Bank with a checking account. Customers have
the    following properties:
    Attributes:        name: A string representing the customer's
name.        balance: A float tracking the current balance of the
customer's account.    """

    def __init__(self, name, balance=0.0):
        """Return a Customer object whose name is *name* and starting
      balance is *balance*."""
        self.name = name
        self.balance = balance

    def withdraw(self, amount):
        """Return the balance remaining after withdrawing *amount*
   dollars."""
        if amount > self.balance:
            raise RuntimeError('Amount greater than available balance.')
        self.balance -= amount
        return self.balance

    def deposit(self, amount):
        """Return the balance remaining after depositing *amount*
  dollars."""
        self.balance += amount
        return self.balance

From alan.gauld at yahoo.co.uk  Tue Feb  7 13:59:04 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 18:59:04 +0000
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <CAKJDb-OphDpWDxgYJ=cJpD5O3Vs4oOQmGTeR9UY_hT=2V0JkdQ@mail.gmail.com>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
 <o7c5ja$is6$1@blaine.gmane.org>
 <CAKJDb-OphDpWDxgYJ=cJpD5O3Vs4oOQmGTeR9UY_hT=2V0JkdQ@mail.gmail.com>
Message-ID: <o7d5di$bba$1@blaine.gmane.org>

On 07/02/17 16:41, Zachary Ware wrote:

> Full disclosure, I've never actually used Tix beyond making it build
> with the rest of CPython on Windows and making sure it actually worked
> on one of my Linux buildbot workers.  I have only ever seen it as a
> maintenance headache :)

The beauty of Tix is that it is a full superset of Tkinter
so you can just put this at the top and it converts your
code to use Tix:

replace

import Tkinter

with

import Tix as Tkinter

But Tix has over 40 extra widgets including a tabbed notepad,
balloon, meter, shell and and a very powerful (but undocumented!)
grid control.

The most important and commonly used seem to have been
incorporated into the latest ttk, but not all of them.

> "Less available" rather than "unavailable" :).  Tix ships with Tcl/Tk
> with CPython on Windows; on Linux, you'd need to install it separately
> from Tcl/Tk and python/tkinter.  I honestly don't have a clue how
> you'd get it on macOS or any other platform that doesn't provide it in
> a system repository.

It should be easy since its just native Tcl code, there's no C
involved so far as I know (I haven't checked!). So anywhere Tcl
runs Tix should work.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb  7 14:01:00 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 19:01:00 +0000
Subject: [Tutor] Error when trying to use classes
In-Reply-To: <CABXYKTr++q1iY4FE7U0YY4z3X1ZbtYnak_q2k8Raj_dU9KHRdA@mail.gmail.com>
References: <CABXYKTr++q1iY4FE7U0YY4z3X1ZbtYnak_q2k8Raj_dU9KHRdA@mail.gmail.com>
Message-ID: <o7d5h6$bba$2@blaine.gmane.org>

On 07/02/17 15:34, Rafael Skovron wrote:

> My general workflow is I edit in vim, then invoke python3 interpreter,
> import the module and try to use the Class and methods from the class.
> 
> For example, importing customer.py and assigning this object yields:
> 
>>>> rafael = Customer('rafael',100.0)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'Customer' is not defined

You didn't show us the import but I'm guessing
you just did

import customer

In that case you need to reference the module:

rafael = customer.Customer(....)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb  7 14:05:35 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 19:05:35 +0000
Subject: [Tutor] Tkinter Calendar to receive user entry.
In-Reply-To: <o7c6u9$fsg$1@blaine.gmane.org>
References: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>
 <o7c4vr$e03$1@blaine.gmane.org> <o7c6u9$fsg$1@blaine.gmane.org>
Message-ID: <o7d5pp$cv4$1@blaine.gmane.org>

On 07/02/17 10:18, Peter Otten wrote:

> $ cat demo.py
> #!/usr/bin/env python
> import calendar
> import ttk
> import Tkinter
> from ttkcalendar import Calendar

Doesn't work for me in either Python 3.6.0 or in Python 2.7.6

Which version of 2.7 are you using?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From akleider at sonic.net  Tue Feb  7 14:01:27 2017
From: akleider at sonic.net (Alex Kleider)
Date: Tue, 07 Feb 2017 11:01:27 -0800
Subject: [Tutor] Error when trying to use classes
In-Reply-To: <CABXYKTr++q1iY4FE7U0YY4z3X1ZbtYnak_q2k8Raj_dU9KHRdA@mail.gmail.com>
References: <CABXYKTr++q1iY4FE7U0YY4z3X1ZbtYnak_q2k8Raj_dU9KHRdA@mail.gmail.com>
Message-ID: <90fb10784d8cb1235f96b3cc83f2781c@sonic.net>

On 2017-02-07 07:34, Rafael Skovron wrote:
> I'm trying to learn how to use Classes but I keep getting  NameErrors 
> no
> matter what code I put into the script.
> 
> Any ideas why?

Assuming the code you've edited using vim is in a file mymodule.py
And after invoking the interpreter you issue the following:
>>> import mymodule.py
your instantiation statement needs to be
>>> rafael = mymodule.Customer('rafael', 100.0)

Alternatively you can use the following import statement (not generally 
recommended:)
>>> from mymodule import Customer


> 
> My general workflow is I edit in vim, then invoke python3 interpreter,
> import the module and try to use the Class and methods from the class.
> 
> For example, importing customer.py and assigning this object yields:
> 
>>>> rafael = Customer('rafael',100.0)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'Customer' is not defined
> 
> 
> 
> class Customer(object):
>     """A customer of ABC Bank with a checking account. Customers have
> the    following properties:
>     Attributes:        name: A string representing the customer's
> name.        balance: A float tracking the current balance of the
> customer's account.    """
> 
>     def __init__(self, name, balance=0.0):
>         """Return a Customer object whose name is *name* and starting
>       balance is *balance*."""
>         self.name = name
>         self.balance = balance
> 
>     def withdraw(self, amount):
>         """Return the balance remaining after withdrawing *amount*
>    dollars."""
>         if amount > self.balance:
>             raise RuntimeError('Amount greater than available 
> balance.')
>         self.balance -= amount
>         return self.balance
> 
>     def deposit(self, amount):
>         """Return the balance remaining after depositing *amount*
>   dollars."""
>         self.balance += amount
>         return self.balance
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From __peter__ at web.de  Tue Feb  7 14:40:18 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 07 Feb 2017 20:40:18 +0100
Subject: [Tutor] Tkinter Calendar to receive user entry.
References: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>
 <o7c4vr$e03$1@blaine.gmane.org> <o7c6u9$fsg$1@blaine.gmane.org>
 <o7d5pp$cv4$1@blaine.gmane.org>
Message-ID: <o7d7r2$fi6$1@blaine.gmane.org>

Alan Gauld via Tutor wrote:

> On 07/02/17 10:18, Peter Otten wrote:
> 
>> $ cat demo.py
>> #!/usr/bin/env python
>> import calendar
>> import ttk
>> import Tkinter
>> from ttkcalendar import Calendar
> 
> Doesn't work for me in either Python 3.6.0 or in Python 2.7.6
> 
> Which version of 2.7 are you using?

The distribution's Python 2.7.6 on Linux Mint 17. After fixing the import 
statements...

$ head ttkcalendar.py
"""
Simple calendar using ttk Treeview together with calendar and datetime
classes.
"""
import calendar

try:
    import Tkinter
    import tkFont
    import ttk
except ImportError: # py3k
    import tkinter as Tkinter
    import tkinter.font as tkFont
    from tkinter import ttk

def get_calendar(locale, fwday):
    # instantiate proper calendar class
    if locale is None:
        return calendar.TextCalendar(fwday)
    else:
$ cat demo.py
#!/usr/bin/env python
import calendar

try:
    import tkinter as tk
    from tkinter import ttk
except ImportError:
    import ttk
    import Tkinter as tk

from ttkcalendar import Calendar

def test2():
    import sys
    root = tk.Tk()
    root.title('Ttk Calendar')
    ttkcal = Calendar(firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')

    if 'win' not in sys.platform:
        style = ttk.Style()
        style.theme_use('clam')

    root.mainloop()

    x = ttkcal.selection    
    print('x is: {}'.format(x))

test2()

... Python 3.4.3 works, too, as does the most recent compiled-from-source 
version I have lying around,

$ python3.7
Python 3.7.0a0 (default:09d4d47ad210, Jan 31 2017, 22:08:14) 
[GCC 4.8.4] on linux

The underlying tcl is 8.6.


From george at fischhof.hu  Tue Feb  7 13:59:08 2017
From: george at fischhof.hu (George Fischhof)
Date: Tue, 7 Feb 2017 19:59:08 +0100
Subject: [Tutor] Error when trying to use classes
In-Reply-To: <CABXYKTr++q1iY4FE7U0YY4z3X1ZbtYnak_q2k8Raj_dU9KHRdA@mail.gmail.com>
References: <CABXYKTr++q1iY4FE7U0YY4z3X1ZbtYnak_q2k8Raj_dU9KHRdA@mail.gmail.com>
Message-ID: <CAFwcP0jW74NWmjObD-fvMK1rpqMfFKj4=7-maQqyrSYEieBrAQ@mail.gmail.com>

2017-02-07 16:34 GMT+01:00 Rafael Skovron <rskovron at gmail.com>:

> I'm trying to learn how to use Classes but I keep getting  NameErrors no
> matter what code I put into the script.
>
> Any ideas why?
>
> My general workflow is I edit in vim, then invoke python3 interpreter,
> import the module and try to use the Class and methods from the class.
>
> For example, importing customer.py and assigning this object yields:
>
> >>> rafael = Customer('rafael',100.0)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'Customer' is not defined
>
>
>
> class Customer(object):
>     """A customer of ABC Bank with a checking account. Customers have
> the    following properties:
>     Attributes:        name: A string representing the customer's
> name.        balance: A float tracking the current balance of the
> customer's account.    """
>
>     def __init__(self, name, balance=0.0):
>         """Return a Customer object whose name is *name* and starting
>       balance is *balance*."""
>         self.name = name
>         self.balance = balance
>
>     def withdraw(self, amount):
>         """Return the balance remaining after withdrawing *amount*
>    dollars."""
>         if amount > self.balance:
>             raise RuntimeError('Amount greater than available balance.')
>         self.balance -= amount
>         return self.balance
>
>     def deposit(self, amount):
>         """Return the balance remaining after depositing *amount*
>   dollars."""
>         self.balance += amount
>         return self.balance
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


Hi,

with this statement:
>>> rafael = Customer('rafael',100.0)
you (the program) creates an instance of Customer class

to import the class (this is the first), you should use the import
statement:
>>> from customer import Customer
after this the program will work.

BR,
George

PS.: pycharm from JetBrains is a very good python ide. ... (instead of vim
;-) )

From zachary.ware+pytut at gmail.com  Tue Feb  7 14:51:19 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Tue, 7 Feb 2017 13:51:19 -0600
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <o7d5di$bba$1@blaine.gmane.org>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
 <o7c5ja$is6$1@blaine.gmane.org>
 <CAKJDb-OphDpWDxgYJ=cJpD5O3Vs4oOQmGTeR9UY_hT=2V0JkdQ@mail.gmail.com>
 <o7d5di$bba$1@blaine.gmane.org>
Message-ID: <CAKJDb-Me1A=ORGbyuhn6CAsVfaxniKpLvtZfNkmOm3x2=Bn2nw@mail.gmail.com>

On Tue, Feb 7, 2017 at 12:59 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 07/02/17 16:41, Zachary Ware wrote:
>
>> Full disclosure, I've never actually used Tix beyond making it build
>> with the rest of CPython on Windows and making sure it actually worked
>> on one of my Linux buildbot workers.  I have only ever seen it as a
>> maintenance headache :)
>
> The beauty of Tix is that it is a full superset of Tkinter
> so you can just put this at the top and it converts your
> code to use Tix:
>
> replace
>
> import Tkinter
>
> with
>
> import Tix as Tkinter

That's just because tix.py does "from tkinter import *".  You can
achieve the same by doing 'from tkinter import *;from tkinter.ttk
import *' (in a separate 'tk.py' if you want everything namespaced in
your code).

> But Tix has over 40 extra widgets including a tabbed notepad,
> balloon, meter, shell and and a very powerful (but undocumented!)
> grid control.

Very little of tkinter is actually documented outside of the official
Tcl/Tk docs, unfortunately.  How does tix.Grid differ from the
standard grid geometry manager (.grid() method on widgets)?

> The most important and commonly used seem to have been
> incorporated into the latest ttk, but not all of them.

Which ones are missing?  I'd recommend raising issues against Tk for
having them added.

>> "Less available" rather than "unavailable" :).  Tix ships with Tcl/Tk
>> with CPython on Windows; on Linux, you'd need to install it separately
>> from Tcl/Tk and python/tkinter.  I honestly don't have a clue how
>> you'd get it on macOS or any other platform that doesn't provide it in
>> a system repository.
>
> It should be easy since its just native Tcl code, there's no C
> involved so far as I know (I haven't checked!). So anywhere Tcl
> runs Tix should work.

There's some Tcl, but mostly C; see
http://svn.python.org/view/external/tix-8.4.3.x/ (particularly the
'generic', 'unix', and 'win' directories).

-- 
Zach

From alan.gauld at yahoo.co.uk  Tue Feb  7 14:54:48 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 19:54:48 +0000
Subject: [Tutor] Tkinter Calendar to receive user entry.
In-Reply-To: <o7d7r2$fi6$1@blaine.gmane.org>
References: <CAK0ikxcXK2j-m4qFkmeL5xSzWa6iQzRFjoeOBBmzc5A5sSMxMA@mail.gmail.com>
 <o7c4vr$e03$1@blaine.gmane.org> <o7c6u9$fsg$1@blaine.gmane.org>
 <o7d5pp$cv4$1@blaine.gmane.org> <o7d7r2$fi6$1@blaine.gmane.org>
Message-ID: <o7d8m2$6uq$1@blaine.gmane.org>

On 07/02/17 19:40, Peter Otten wrote:

>>> from ttkcalendar import Calendar
>>
>> Doesn't work for me in either Python 3.6.0 or in Python 2.7.6
>>
>> Which version of 2.7 are you using?
> 
> The distribution's Python 2.7.6 on Linux Mint 17. After fixing the import 
> statements...

OK, I went back to your original post again and realized I
needed to download the ttkcalendar.py, its not a standard
module...

works now.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb  7 15:04:11 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 20:04:11 +0000
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <o7d5di$bba$1@blaine.gmane.org>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
 <o7c5ja$is6$1@blaine.gmane.org>
 <CAKJDb-OphDpWDxgYJ=cJpD5O3Vs4oOQmGTeR9UY_hT=2V0JkdQ@mail.gmail.com>
 <o7d5di$bba$1@blaine.gmane.org>
Message-ID: <o7d97l$qol$1@blaine.gmane.org>

On 07/02/17 18:59, Alan Gauld via Tutor wrote:

> It should be easy since its just native Tcl code, there's no C

Scratch that, I just found a C API for Tix so I guess it
has some C after all.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb  7 15:10:44 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 7 Feb 2017 20:10:44 +0000
Subject: [Tutor] Multiple tabs using tkinter
In-Reply-To: <CAKJDb-Me1A=ORGbyuhn6CAsVfaxniKpLvtZfNkmOm3x2=Bn2nw@mail.gmail.com>
References: <CAK0ikxfu3Z6cfM5H-RQ_7Eo8PAgNLWHHgq1vfageoPGUobtsTw@mail.gmail.com>
 <o7b819$pqu$1@blaine.gmane.org>
 <CAKJDb-P+BXtWxm-i8HaEcViFmAH8P5L4SGtVye5RSDk3RsAM+w@mail.gmail.com>
 <o7c5ja$is6$1@blaine.gmane.org>
 <CAKJDb-OphDpWDxgYJ=cJpD5O3Vs4oOQmGTeR9UY_hT=2V0JkdQ@mail.gmail.com>
 <o7d5di$bba$1@blaine.gmane.org>
 <CAKJDb-Me1A=ORGbyuhn6CAsVfaxniKpLvtZfNkmOm3x2=Bn2nw@mail.gmail.com>
Message-ID: <o7d9ju$8jq$1@blaine.gmane.org>

On 07/02/17 19:51, Zachary Ware wrote:

>> But Tix has over 40 extra widgets including a tabbed notepad,
>> balloon, meter, shell and and a very powerful (but undocumented!)
>> grid control.
> 
> Very little of tkinter is actually documented outside of the official
> Tcl/Tk docs, unfortunately.  

Tix is barely documented even there!
I was actually considering writing a book to document the Tix
toolkit. If its now deprecated I won't bother!! :-)

> How does tix.Grid differ from the
> standard grid geometry manager (.grid() method on widgets)?

It's a widget not a window manager (although Tix does provide
a new "Form" WM, but I've never used it). The grid is a table
or simple spreadsheet control. Most GUI toolkits have one
but Tkinter doesn't... yet...

>> The most important and commonly used seem to have been
>> incorporated into the latest ttk, but not all of them.
> 
> Which ones are missing?  I'd recommend raising issues against Tk for
> having them added.

I'll need to do a bit of dir() and diff() to answer that

> There's some Tcl, but mostly C; see

Yes, I discovered that once I started doing some deeper
digging... see my other post that seems to have crossed
paths with yours.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From pkhattan at gmail.com  Tue Feb  7 16:09:32 2017
From: pkhattan at gmail.com (=?UTF-8?B?4YCQ4YCs4YCU4YC54YCB4YCQ4YC54YCe4YCU4YC5?=)
Date: Wed, 8 Feb 2017 10:09:32 +1300
Subject: [Tutor] (no subject)
Message-ID: <CACxRcyne8vYxyV2K6qR8M01YD_WcyxntTybo=3hsiV-W45RQsw@mail.gmail.com>

Hi,


I am just start learning Python and I have an activity to do
RockPaperScissors game using dictionary. I have written my code and it
doesn't work at all. I am sending my code and the
requirements. Can you please have a look and point out what is wrong there.
Thank you very much.

Warm regards,
Pau

program requirements:

? The program will display an appropriate welcome message and user
instructions.

? The program must use a Python dictionary to hold data shown in the table
below:

Game Command              Value

R                                             Rock

P                                             Paper

S                                              Scissors

E                                              Exit

? The player will enter their choice of shape by entering a valid Game
Command.

? Any invalid input must generate an exception that is handled and used to
display an appropriate error message.

? For correct inputs, the computer will randomly pick a dictionary item
(other than ?Exit?) and compare that value with the user?s, before
returning the game result.

? For the game result the program must return details of the following:

o The user?s selection

o The computer?s selection

o The winning hand

o A running total of user wins including this game and previous games

 The program will repeat the game until the user exits by entering ?e?.

# RockPaperScissors

import random
print ("Hello.. Welcome from Rock, Paper, Scissors Game!!\n"
       +"Game instruction:\n"
       +"You will be playing with the computer.\n"
       +"You need to choose one of your choice: Rock, Paper or Scissors.\n"
       +"Enter 'e' to exit the game.\n")

game_command = {"r":"Rock","p":"Paper","s":"Scissors","e":"Exit"}


score = 0
player = 0
try:
    while player == 'r' and player == 'p' and player == 's':


        pc = random.choice( list(game_command.keys())[:3])
        player = input("\nPlease enter your choice:'r','p' or 's': ")
        print ("You selects: ", player)
        print ("PC selects:",pc)


        if player == pc:
            print("It's a Tie!")
            score = score
            print("Your score is: ",score)

        elif player == "r":
            if pc == "p":
                print("PC win!")
            else:
                print("You win!")
                score = score + 1
                print("Your score is: ",score)

        elif player == "p":
            if pc == "s":
                print("PC win!")
            else:
                print("You win!")
                score = score + 1
                print("Your score is: ",score)

        elif player == "s":
            if pc == "r":
                print("PC win!")
            else:
                print("You win!")
                score = score + 1
                print("Your score is: ",score)
        elif player == 'e' :
            break
            print("You exit the game.")
except ValueError:
        print("\nInvalid character,try again!")

From david at graniteweb.com  Tue Feb  7 21:06:51 2017
From: david at graniteweb.com (David Rock)
Date: Tue, 7 Feb 2017 20:06:51 -0600
Subject: [Tutor] (no subject)
In-Reply-To: <CACxRcyne8vYxyV2K6qR8M01YD_WcyxntTybo=3hsiV-W45RQsw@mail.gmail.com>
References: <CACxRcyne8vYxyV2K6qR8M01YD_WcyxntTybo=3hsiV-W45RQsw@mail.gmail.com>
Message-ID: <C3B5FC94-74BA-459C-8164-F9CED6E9A0CB@graniteweb.com>

> On Feb 7, 2017, at 15:09, ?????????? <pkhattan at gmail.com> wrote:
> 
> 
> # RockPaperScissors
> 
> import random
> print ("Hello.. Welcome from Rock, Paper, Scissors Game!!\n"
>       +"Game instruction:\n"
>       +"You will be playing with the computer.\n"
>       +"You need to choose one of your choice: Rock, Paper or Scissors.\n"
>       +"Enter 'e' to exit the game.\n")
> 
> game_command = {"r":"Rock","p":"Paper","s":"Scissors","e":"Exit"}
> 
> 
> score = 0
> player = 0
> try:
>    while player == 'r' and player == 'p' and player == 's':
> 

There are two major things that you need to address first.

1. You never ask for user input before starting your while loop
2. Your while loop is testing for r, p, and s to all be equal to each other and set, which is not what you want to test.

Basically, your while loop is immediately false as soon as you run your script.  You need to rework your logic to test the player?s value.


? 
David Rock
david at graniteweb.com





From soweto at gmail.com  Wed Feb  8 02:11:32 2017
From: soweto at gmail.com (Vusa Moyo)
Date: Wed, 8 Feb 2017 09:11:32 +0200
Subject: [Tutor] Help with Multiple Inheritance in Classes
Message-ID: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>

I have a suspicion my lecturer's question is flawed, so I'd like to pose it
to you guys to confirm my suspicions.

Here goes..

I've gone and created a Class Cat1(cat): <-- inherited class, but cant seem
get the code right which allows the test code to run successfully.

We have a class defined for cats. Create a new cat called cat1. Set cat1 to
be a grey Burmese cat worth 3000 with the name Whiskers.

 # define the Cat class

 class Cat:
     name = ""

     kind = "cat"
     color = ""
     value = 100.00
     def description(self):

desc_str = "%s is a %s %s cat worth R%.2f." % (self.name, self.color,
self.kind, self.value)

         return desc_str

# your code goes here


# test code

 print(cat1.description())

From __peter__ at web.de  Wed Feb  8 03:29:28 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 08 Feb 2017 09:29:28 +0100
Subject: [Tutor] Help with Multiple Inheritance in Classes
References: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>
Message-ID: <o7ekt5$3tg$1@blaine.gmane.org>

Vusa Moyo wrote:

> I have a suspicion my lecturer's question is flawed, so I'd like to pose
> it to you guys to confirm my suspicions.
> 
> Here goes..
> 
> I've gone and created a Class Cat1(cat): <-- inherited class, but cant
> seem get the code right which allows the test code to run successfully.

Is the following... 

> We have a class defined for cats. Create a new cat called cat1. Set cat1
> to be a grey Burmese cat worth 3000 with the name Whiskers.

your task? Then your lecturer may be asking you to *instantiate* the Cat 
class, not to make a subclass.

>  # define the Cat class
> 
>  class Cat:
>      name = ""
> 
>      kind = "cat"
>      color = ""
>      value = 100.00

The above are all class attributes. This is unusual, as even two cates of 
the same race will have a different name and value. If I'm guessing right 
your solution will look more like

$ cat cars.py
class Car:
    def __init__(self, make, color, year):
        self.make = make
        self.color = color
        self.year = year

    def __str__(self):
        return "{0.color} {0.make}".format(self)

    def __repr__(self):
        return (
            "Car(color={0.color}, "
            "make={0.make}, "
            "year={0.year})"
        ).format(self)

carpark = [
    Car("Ford", "blue", 1973),
    Car("Volkswagen", "yellow", 2003)
]

print(carpark)  # uses Car.__repr__
print()

print("In our car park we have")
for car in carpark:
    print("    - a", car)  # uses Car.__str__
$ python3 cars.py 
[Car(color=blue, make=Ford, year=1973), Car(color=yellow, make=Volkswagen, 
year=2003)]

In our car park we have
    - a blue Ford
    - a yellow Volkswagen
$ 

>From the view of the script a VW and a Ford work the same, so there is no 
need to introduce subclasses, but if you're asked to do it anyway here's one 
way:

$ cat cars2.py
class Car:
    def __init__(self, color, year):
        self.color = color
        self.year = year

    def __str__(self):
        return "{0.color} {0.make}".format(self)

    def __repr__(self):
        return (
            "{classname}(color={0.color}, "
            "year={0.year})"
        ).format(self, classname=self.__class__.__name__)

class Ford(Car):
    make = "Ford"

class Volkswagen(Car):
    make = "VW"

carpark = [
    Ford("blue", 1973),
    Volkswagen("yellow", 2003)
]

print(carpark)  # uses Car.__repr__
print()

print("In our car park we have")
for car in carpark:
    print("    - a", car)  # uses Car.__str__
$ python3 cars2.py 
[Ford(color=blue, year=1973), Volkswagen(color=yellow, year=2003)]

In our car park we have
    - a blue Ford
    - a yellow VW
$ 

However, this is the kind of inheritance you will only ever see in textbook 
examples because the subclasses do not introduce differing features. As a 
rule of thumb there should be at least one method with a fundamentally 
different implementation, or one extra method that is not shared between 
baseclass and subclass.

>      def description(self):
> desc_str = "%s is a %s %s cat worth R%.2f." % (self.name, self.color,
> self.kind, self.value)
> 
>          return desc_str
> 
> # your code goes here
> 
> 
> # test code
> 
>  print(cat1.description())




From alan.gauld at yahoo.co.uk  Wed Feb  8 04:00:09 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 8 Feb 2017 09:00:09 +0000
Subject: [Tutor] (no subject)
In-Reply-To: <CACxRcyne8vYxyV2K6qR8M01YD_WcyxntTybo=3hsiV-W45RQsw@mail.gmail.com>
References: <CACxRcyne8vYxyV2K6qR8M01YD_WcyxntTybo=3hsiV-W45RQsw@mail.gmail.com>
Message-ID: <o7emmj$e7s$1@blaine.gmane.org>

On 07/02/17 21:09, ?????????? wrote:

> RockPaperScissors game using dictionary. I have written my code and it
> doesn't work at all.

So what does it do? Crash your PC? Give an error? Run silently and stop?
You need to be precise when telling us these things. If you get an error
message send us the full text.

> requirements. Can you please have a look and point out what is wrong there.

> import random
> print ("Hello.. Welcome from Rock, Paper, Scissors Game!!\n"
>        +"Game instruction:\n"
>        +"You will be playing with the computer.\n"
>        +"You need to choose one of your choice: Rock, Paper or Scissors.\n"
>        +"Enter 'e' to exit the game.\n")
> 
> game_command = {"r":"Rock","p":"Paper","s":"Scissors","e":"Exit"}
> 
> 
> score = 0
> player = 0

zero is not a valid value for player. Your code expects
a character not a number.

> try:
>     while player == 'r' and player == 'p' and player == 's':

'and' in computing implies both things must be true at the same time.
player can only have one value so this test will always be false and
your loop will never run. I suspect you either want to substitute 'or'
for 'and', or use:

while player in ('r','s','p'): ...

But since you use break to exit the loop later you could
just use:

while True: ...

To force the loop to run.
This is probably the most common technique in Python
for this kind of scenario.

>         pc = random.choice( list(game_command.keys())[:3])

Note that Python does not guarantee that a dictionary's values
are returned in the order you created them. So this could return
a different set of values from what you expect, eg ['r','e','p']

>         player = input("\nPlease enter your choice:'r','p' or 's': ")

shouldn't you do this before starting your loop too?
Just to be sure the player wants to play? And shouldn't the
player be allowed to choose 'e' too?
Otherwise how do they know how to exit?

>         print ("You selects: ", player)
>         print ("PC selects:",pc)
> 
> 
>         if player == pc:
>             print("It's a Tie!")
>             score = score
>             print("Your score is: ",score)
> 
>         elif player == "r":
>             if pc == "p":
>                 print("PC win!")

shouldn't you print the score here too?

>             else:
>                 print("You win!")
>                 score = score + 1
>                 print("Your score is: ",score)
> 
>         elif player == "p":
>             if pc == "s":
>                 print("PC win!")
>             else:
>                 print("You win!")
>                 score = score + 1
>                 print("Your score is: ",score)
> 
>         elif player == "s":
>             if pc == "r":
>                 print("PC win!")
>             else:
>                 print("You win!")
>                 score = score + 1
>                 print("Your score is: ",score)
>         elif player == 'e' :
>             break
>             print("You exit the game.")
> except ValueError:
>         print("\nInvalid character,try again!")

You never raise a ValueError so when would this
exception be generated?

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Wed Feb  8 04:06:34 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 8 Feb 2017 09:06:34 +0000
Subject: [Tutor] Help with Multiple Inheritance in Classes
In-Reply-To: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>
References: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>
Message-ID: <o7en2l$h9a$1@blaine.gmane.org>

On 08/02/17 07:11, Vusa Moyo wrote:
> I have a suspicion my lecturer's question is flawed, so I'd like to pose it
> to you guys to confirm my suspicions.

I think your interpretation of the question is flawed.
See Peter's reply for why.

However another point is....

>  class Cat:
>      name = ""
>      kind = "cat"
>      color = ""
>      value = 100.00
>      def description(self):
> 
> desc_str = "%s is a %s %s cat worth R%.2f." % (self.name, self.color,
> self.kind, self.value)

Python is sensitive to indentation. This line needs
to be indented inside the def statement. (This may
be a mail formatting issue but since the rest of
your code looks OK I doubt it)



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Wed Feb  8 07:05:49 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 8 Feb 2017 12:05:49 +0000
Subject: [Tutor] Rock,Paper Scissors (was no subject)
In-Reply-To: <CACxRcyn2Dz2ngP9xeJiF3gxWxTmcQT1rZHKfb0y_s1pHtesj0g@mail.gmail.com>
References: <CACxRcyne8vYxyV2K6qR8M01YD_WcyxntTybo=3hsiV-W45RQsw@mail.gmail.com>
 <o7emmj$e7s$1@blaine.gmane.org>
 <CACxRcyn2Dz2ngP9xeJiF3gxWxTmcQT1rZHKfb0y_s1pHtesj0g@mail.gmail.com>
Message-ID: <e02fd0a0-9e29-5e76-0052-6fb6412e2242@yahoo.co.uk>

On 08/02/17 10:02, ?????????? wrote:
> Thanks for your answers. Your explanation makes me understand what I
> didn't understand and it discourages me to go on Python in other way
> as I feel like this doesn't suit to me. :'(

Don't be discouraged. Your central program was very nearly right and
your mistakes
are just the normal kinds of mistakes that beginners make so you are
basically
on the right track.

> Any way, can you please help and guide me to get done this. I have
> some questions:
>
> 1. Could I define player value to 2/3 values like player = 'r' 'p' 's'
> , or should  I set just any one of them.

I would just set one, the important thing is that you should always set
default
values to the same type as the real values. In this case that means a
string.
You could even use an empty string "" if you like.

> 2. For this command pc = random.choice(
> list(game_command.keys())[:3]), I don't really how to control. I don't
> want the computer picks 'e' as you said.
>     Can you please  help me how to write there. I have been running a
> hundred times and it doesn't pick 'e', so I thought it works.

Yes, that is the problem, most of the time these things will work but you
cannot guarantee it. In this case, because there are only 3 values,
you could just use the values directly:

pc = random.choice( ['r','p','s'])

If you really prefer a variable, and it is better practice, then you can
change your variable definitions:

weapons = ['r','p','s']

choices = weapons + ['e']
game_command = dict(zip(choices,['Rock','Paper','Scissors','Exit']))

then use

pc = random.choice( weapons )


> 3. Is there any problem if I didn't print the player score when PC won?

The specification asked for the score to be printed:
-------------------------------
For the game result the program must return details of the following:
- The user?s selection
- The computer?s selection
- The winning hand
- A running total of user wins including this game and previous games
------------------
It did not say to only do that if the player won...

> 4. Also how the exception to be generated.

Test the input value is valid and if not, use:

raise ValueError

The value is not valid if it is not in choices....

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From lwaters at flinthill.org  Wed Feb  8 08:00:27 2017
From: lwaters at flinthill.org (Lisa Hasler Waters)
Date: Wed, 8 Feb 2017 08:00:27 -0500
Subject: [Tutor] Trying to use tkinter in Pycharm EDU
Message-ID: <CAF91wy_3hD97brEk5j9HNoRG099jzKXW07pjV30js-Cqtt_Ebw@mail.gmail.com>

Hello,

We have been able to get the turtle module in PycharmEDU by ending our code
with turtle.done()

However, we cannot get the tkinter module to actually run in PycharmEDU.
For example, when we input the following very simple code we get a line in
the console that reads  "Process finished with exit code" and we can see
that a canvas is trying to open but it never does:

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=500, height=500)
canvas.pack()

OR this code:

from tkinter import *
tk = Tk()
btn = Button(tk, text="click me")
btn.pack()

Both of these worked fine in IDLE. But we really like the Pycharm EDU and
want to continue using it.

We are working on Macs 10.11.6 with Pycharm EDU 3.0.1.

We are obviously missing something! Any advice would be appreciated!

Thanks so much!

Lisa

-- 
Lisa Waters, PhD
Technology Integration
Middle School Coding
Lower School Digital Literacy
Flint Hill School
703.584.2300
*www.flinthill.org* <http://www.flinthill.org/>

From __peter__ at web.de  Wed Feb  8 08:32:40 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 08 Feb 2017 14:32:40 +0100
Subject: [Tutor] Trying to use tkinter in Pycharm EDU
References: <CAF91wy_3hD97brEk5j9HNoRG099jzKXW07pjV30js-Cqtt_Ebw@mail.gmail.com>
Message-ID: <o7f6ll$65f$1@blaine.gmane.org>

Lisa Hasler Waters wrote:

> Hello,
> 
> We have been able to get the turtle module in PycharmEDU by ending our
> code with turtle.done()
> 
> However, we cannot get the tkinter module to actually run in PycharmEDU.
> For example, when we input the following very simple code we get a line in
> the console that reads  "Process finished with exit code" and we can see
> that a canvas is trying to open but it never does:
> 
> from tkinter import *
> tk = Tk()
> canvas = Canvas(tk, width=500, height=500)
> canvas.pack()
> 
> OR this code:
> 
> from tkinter import *
> tk = Tk()
> btn = Button(tk, text="click me")
> btn.pack()

Try adding the line

  tk.mainloop()


Running an event loop is necessary for every tkinter program.
 
> Both of these worked fine in IDLE. 

As idle itself uses tkinter there's probably an odd interference between 
idle and your script causing it to share the editor's event loop so that it 
appears to work.

> But we really like the Pycharm EDU and
> want to continue using it.
> 
> We are working on Macs 10.11.6 with Pycharm EDU 3.0.1.
> 
> We are obviously missing something! Any advice would be appreciated!
> 
> Thanks so much!
> 
> Lisa
> 



From sasil.adetunji at gmail.com  Wed Feb  8 05:04:07 2017
From: sasil.adetunji at gmail.com (Sasiliyu Adetunji)
Date: Wed, 8 Feb 2017 11:04:07 +0100
Subject: [Tutor] Help on shoppingcart
In-Reply-To: <CACv2vyz5d9H8GG+KQm-FPUF7phDNSrh50sKK8JW3EJ5QL3x9ow@mail.gmail.com>
References: <CACv2vyz5d9H8GG+KQm-FPUF7phDNSrh50sKK8JW3EJ5QL3x9ow@mail.gmail.com>
Message-ID: <CACv2vywMPJFUt8RpFKWUiDL0nU6YYw-ye_E6ej3+SWPFhye4ow@mail.gmail.com>

Hi,
Pls help me on this shoppingcart  assignment

Create  a class called ShoppingCart

Create a constructor that takes no arguments and sets the total attribute
to zero, and initializes an empty dict attribute named items.

Create a method add_item that requires item_name, quantity and price arguments.
This method should add the cost of the added items to the current value of
total. It should also add an entry to the items dict such that the key is
the item_name and the value is the quantity of the item.

Create a method remove_item that requires similar arguments as add_item. It
should remove items that have been added to the shopping cart and are not
required. This method should deduct the cost of the removed items from the
current total and also update the items dict accordingly.

If the quantity of an item to be removed exceeds the current quantity of
that item in the cart, assume that all entries of that item are to be
removed.

Create a method checkout that takes in cash_paid and returns the value of
balance from the payment. If cash_paid is not enough to cover the total,
return "Cash paid not enough".

Create a class called Shop that has a constructor which takes no arguments
and initializes an attribute called quantity at 100.

Make sure Shop inherits from ShoppingCart.

In the Shop class, override the remove_item method, such that calling
Shop's remove_item with no arguments decrements quantity by one.

From alan.gauld at yahoo.co.uk  Wed Feb  8 12:26:15 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 8 Feb 2017 17:26:15 +0000
Subject: [Tutor] Help on shoppingcart
In-Reply-To: <CACv2vywMPJFUt8RpFKWUiDL0nU6YYw-ye_E6ej3+SWPFhye4ow@mail.gmail.com>
References: <CACv2vyz5d9H8GG+KQm-FPUF7phDNSrh50sKK8JW3EJ5QL3x9ow@mail.gmail.com>
 <CACv2vywMPJFUt8RpFKWUiDL0nU6YYw-ye_E6ej3+SWPFhye4ow@mail.gmail.com>
Message-ID: <o7fkbh$jc$1@blaine.gmane.org>

On 08/02/17 10:04, Sasiliyu Adetunji wrote:

> Pls help me on this shoppingcart  assignment

Sure. You have a very specific set of tasks.
Which bit are you stuck on?
What have you tried?

Show us your code and we can help get it working.

> Create  a class called ShoppingCart

> Create a constructor...

> Create a method add_item...

> Create a method remove_item...

> If the quantity of an item to be removed ...

> Create a method checkout ...

> Create a class called Shop 

> that has a constructor which takes no arguments...

> Make sure Shop inherits from ShoppingCart.

> In the Shop class, override the remove_item method, 


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From poojabhalode11 at gmail.com  Wed Feb  8 18:09:08 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Wed, 8 Feb 2017 18:09:08 -0500
Subject: [Tutor] Explorer bar window(wxpython) combined to Tkinter
Message-ID: <CAK0ikxfVF+BZej5t23dy=CGpWWHiB1yVN=q+JyvVckQKu3s3Kg@mail.gmail.com>

Hi,

I have been working on creating an explorer bar in GUI. I found the code
the explorer bar online using wx python. This creates a window shown below.
[image: Inline image 1]

But, I want to create this in the original GUI window that I am working in
using Tkinter. However, when I tried importing it, I am not able to
understand how to deal with different roots,

wxpython:
root = wx.App(False)

Tkinter
root = Tk()

The code for the wxpython is given below:
import os
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.dir = wx.GenericDirCtrl(self.panel, size=(200, -1),
style=wx.DIRCTRL_DIR_ONLY)
        self.files = wx.ListCtrl(self.panel, style=wx.LC_LIST)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.dir, flag=wx.EXPAND)
        self.sizer.Add(self.files, proportion=1, flag=wx.EXPAND)

        self.border = wx.BoxSizer()
        self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)

        self.panel.SetSizerAndFit(self.border)
        self.Show()

        self.dir.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelect)


    def OnSelect(self, e):
        self.files.ClearAll()
        list = os.listdir(self.dir.GetPath())
        for a in reversed(list):
            self.files.InsertStringItem(0, a)

root = wx.App(False)

win = MainWindow(None, size=(600, 400))
root.MainLoop()

whereas the code for the GUI that I am working on using Tkinter is given
below:

from Tkinter import *
import datetime
import tkMessageBox
from tkFileDialog import *
from tkMessageBox import *

root = Tk()
root.title("Design of Experiments with Parameter Estimation")
root.geometry("1000x1000")

menu = Menu(root)

root.config(menu=menu)

submenu = Menu(menu)
menu.add_cascade(label="File", menu=submenu)

submenu.add_command(label="New", command=NewWindow)
submenu.add_command(label="Open", command=OpenFile)
submenu.add_command(label="Load", command=LoadNew)
submenu.add_separator()
submenu.add_command(label="Save", command=save)
submenu.add_command(label="Save As", command=Doit)

root.mainloop()

The GUI shows as below:

[image: Inline image 2]


Can someone please tell me how to combine these two so that the
Explorer bar shows up in the space shown in the figure.

Thank you so much in advance.

Yours truly,

Pooja

From alan.gauld at yahoo.co.uk  Wed Feb  8 19:25:08 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 9 Feb 2017 00:25:08 +0000
Subject: [Tutor] Explorer bar window(wxpython) combined to Tkinter
In-Reply-To: <CAK0ikxfVF+BZej5t23dy=CGpWWHiB1yVN=q+JyvVckQKu3s3Kg@mail.gmail.com>
References: <CAK0ikxfVF+BZej5t23dy=CGpWWHiB1yVN=q+JyvVckQKu3s3Kg@mail.gmail.com>
Message-ID: <o7gcsu$bji$1@blaine.gmane.org>

On 08/02/17 23:09, Pooja Bhalode wrote:

> But, I want to create this in the original GUI window that I am working in
> using Tkinter. However, when I tried importing it, I am not able to
> understand how to deal with different roots,

Unfortunately you cannot mix toolkits. You either use
Tkinter or wxPython. Similarly PyQt, PyGTK, Kivy etc
all need to be used on their own.

There are a few exceptions where one toolkit is built
on another so you might be able to mix the underlying
toolkit into the higher level one, but they are rare
cases and still often don't work due to event loop clashes.

So you must either write your entire app in wxPython
or in Tkinter.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From sasil.adetunji at gmail.com  Thu Feb  9 03:10:06 2017
From: sasil.adetunji at gmail.com (Sasiliyu Adetunji)
Date: Thu, 9 Feb 2017 09:10:06 +0100
Subject: [Tutor] Help on this assignment
Message-ID: <CACv2vywZRxQLG+_rKW1SWsHy7wHH5egKfUcRjjE8ajXZmCeS7A@mail.gmail.com>

Please can you assist me in this assignment


Write a function called remove_duplicates which will take one argument
called string. This string input will only have characters between a-z.

The function should remove all repeated characters in the string and return
a tuple with two values:

A new string with only unique, sorted characters.

The total number of duplicates dropp

From alan.gauld at yahoo.co.uk  Thu Feb  9 04:17:31 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 9 Feb 2017 09:17:31 +0000
Subject: [Tutor] Help on this assignment
In-Reply-To: <CACv2vywZRxQLG+_rKW1SWsHy7wHH5egKfUcRjjE8ajXZmCeS7A@mail.gmail.com>
References: <CACv2vywZRxQLG+_rKW1SWsHy7wHH5egKfUcRjjE8ajXZmCeS7A@mail.gmail.com>
Message-ID: <o7hc35$btl$1@blaine.gmane.org>

On 09/02/17 08:10, Sasiliyu Adetunji wrote:

> Write a function called remove_duplicates which will take one argument
> called string. This string input will only have characters between a-z.
> 
> The function should remove all repeated characters in the string and return
> a tuple with two values:
> 
> A new string with only unique, sorted characters.
> 
> The total number of duplicates dropp

You could use set() to remove the duplicates.
Then compare the lengths of the set with the length
of the original to determine how many letters were
dropped.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From soweto at gmail.com  Thu Feb  9 04:25:54 2017
From: soweto at gmail.com (Vusa Moyo)
Date: Thu, 9 Feb 2017 11:25:54 +0200
Subject: [Tutor] Help with Multiple Inheritance in Classes
In-Reply-To: <o7en2l$h9a$1@blaine.gmane.org>
References: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>
 <o7en2l$h9a$1@blaine.gmane.org>
Message-ID: <CAOXYWNx3KySUNnh_d9+JpRq62U6nu4oh=EKSN6vut4OeWtqHXw@mail.gmail.com>

Hi Alan.

You are correct with the indentation.

class Cat:
    name = ""
    kind = "cat"
    color = ""
    value = 100.00

    def description(self):
        desc_str = "%s is a %s %s cat worth R%.2f." % (self.name,
self.color, self.kind, self.value)
        return desc_str

The above code is the question, which I am not allowed to edit.

So just to test the lecturer's code, I run the command

print(Cat.description())

This returns an error.

>>>> TypeError: description() missing 1 required positional argument: 'self'

To me, this is flawed. I should be able to get a fault less response from
that command.

Any other code I append to it by inheriting the class Cat, will still  have
that similar error.

Now, I've added the following code to inherit the class Cat: description.

class Cat1(Cat):
    name = "Whiskers"
    kind = "Burmese cat"
    color = "grey"
    value = 3000.00

When I run this command, I still receive the same error.

print(Cat1.description())

Please assist where possible.

Regards

Vusa

On Wed, Feb 8, 2017 at 11:06 AM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 08/02/17 07:11, Vusa Moyo wrote:
> > I have a suspicion my lecturer's question is flawed, so I'd like to pose
> it
> > to you guys to confirm my suspicions.
>
> I think your interpretation of the question is flawed.
> See Peter's reply for why.
>
> However another point is....
>
> >  class Cat:
> >      name = ""
> >      kind = "cat"
> >      color = ""
> >      value = 100.00
> >      def description(self):
> >
> > desc_str = "%s is a %s %s cat worth R%.2f." % (self.name, self.color,
> > self.kind, self.value)
>
> Python is sensitive to indentation. This line needs
> to be indented inside the def statement. (This may
> be a mail formatting issue but since the rest of
> your code looks OK I doubt it)
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at yahoo.co.uk  Thu Feb  9 05:02:55 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 9 Feb 2017 10:02:55 +0000
Subject: [Tutor] Help with Multiple Inheritance in Classes
In-Reply-To: <CAOXYWNx3KySUNnh_d9+JpRq62U6nu4oh=EKSN6vut4OeWtqHXw@mail.gmail.com>
References: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>
 <o7en2l$h9a$1@blaine.gmane.org>
 <CAOXYWNx3KySUNnh_d9+JpRq62U6nu4oh=EKSN6vut4OeWtqHXw@mail.gmail.com>
Message-ID: <o7heo9$3bj$1@blaine.gmane.org>

On 09/02/17 09:25, Vusa Moyo wrote:

> class Cat:
>     name = ""
>     kind = "cat"
>     color = ""
>     value = 100.00
> 
>     def description(self):
>         desc_str = "%s is a %s %s cat worth R%.2f." % (self.name,
> self.color, self.kind, self.value)
>         return desc_str
> 
> The above code is the question, which I am not allowed to edit.
> 
> So just to test the lecturer's code, I run the command
> 
> print(Cat.description())

But the definition of description() take an argument - self.
self is expected to be an instance of Cat.
You can either pass that in manually

print( Cat.description(Cat()) )

or, more normally, create an instance of cat and call
description on that:

my_cat = Cat()
print( my_cat.description() )

> Any other code I append to it by inheriting the class Cat, will still  have
> that similar error.

I'm not sure what you mean by that, I'd need an example.
If you mean you just add the code after the above line then
obviously you will still get the error.

> Now, I've added the following code to inherit the class Cat: description.
> 
> class Cat1(Cat):
>     name = "Whiskers"
>     kind = "Burmese cat"
>     color = "grey"
>     value = 3000.00
> 
> When I run this command, I still receive the same error.
> 
> print(Cat1.description())

For the same reason; you are still not passing an instance
of Cat (or Cat1) to the method. You need to create an
instance and then call the method on that:

other_cat = Cat1()
print( other_cat.description() )


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From soweto at gmail.com  Thu Feb  9 05:42:03 2017
From: soweto at gmail.com (Vusa Moyo)
Date: Thu, 9 Feb 2017 12:42:03 +0200
Subject: [Tutor] Help with Multiple Inheritance in Classes
In-Reply-To: <o7heo9$3bj$1@blaine.gmane.org>
References: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>
 <o7en2l$h9a$1@blaine.gmane.org>
 <CAOXYWNx3KySUNnh_d9+JpRq62U6nu4oh=EKSN6vut4OeWtqHXw@mail.gmail.com>
 <o7heo9$3bj$1@blaine.gmane.org>
Message-ID: <CAOXYWNzZanfjKmc-BMbKpGxZzpBx4cr4PcmggW4yYxYQRTUJZA@mail.gmail.com>

Thanks so much. You've been a great help.

You have confirmed that the lecture's question is flawed.

Appreciate the help.

Regards

Vusa

On Thu, Feb 9, 2017 at 12:02 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 09/02/17 09:25, Vusa Moyo wrote:
>
> > class Cat:
> >     name = ""
> >     kind = "cat"
> >     color = ""
> >     value = 100.00
> >
> >     def description(self):
> >         desc_str = "%s is a %s %s cat worth R%.2f." % (self.name,
> > self.color, self.kind, self.value)
> >         return desc_str
> >
> > The above code is the question, which I am not allowed to edit.
> >
> > So just to test the lecturer's code, I run the command
> >
> > print(Cat.description())
>
> But the definition of description() take an argument - self.
> self is expected to be an instance of Cat.
> You can either pass that in manually
>
> print( Cat.description(Cat()) )
>
> or, more normally, create an instance of cat and call
> description on that:
>
> my_cat = Cat()
> print( my_cat.description() )
>
> > Any other code I append to it by inheriting the class Cat, will still
> have
> > that similar error.
>
> I'm not sure what you mean by that, I'd need an example.
> If you mean you just add the code after the above line then
> obviously you will still get the error.
>
> > Now, I've added the following code to inherit the class Cat: description.
> >
> > class Cat1(Cat):
> >     name = "Whiskers"
> >     kind = "Burmese cat"
> >     color = "grey"
> >     value = 3000.00
> >
> > When I run this command, I still receive the same error.
> >
> > print(Cat1.description())
>
> For the same reason; you are still not passing an instance
> of Cat (or Cat1) to the method. You need to create an
> instance and then call the method on that:
>
> other_cat = Cat1()
> print( other_cat.description() )
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at yahoo.co.uk  Thu Feb  9 06:08:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 9 Feb 2017 11:08:27 +0000
Subject: [Tutor] Help with Multiple Inheritance in Classes
In-Reply-To: <CAOXYWNzZanfjKmc-BMbKpGxZzpBx4cr4PcmggW4yYxYQRTUJZA@mail.gmail.com>
References: <CAOXYWNwQ-JjpfMzDVNd--dytcdj-D3r-u+rzWxvYyzJ7zMUuWw@mail.gmail.com>
 <o7en2l$h9a$1@blaine.gmane.org>
 <CAOXYWNx3KySUNnh_d9+JpRq62U6nu4oh=EKSN6vut4OeWtqHXw@mail.gmail.com>
 <o7heo9$3bj$1@blaine.gmane.org>
 <CAOXYWNzZanfjKmc-BMbKpGxZzpBx4cr4PcmggW4yYxYQRTUJZA@mail.gmail.com>
Message-ID: <20cbaccc-bb75-7daf-adc9-bba2b27ba6fe@yahoo.co.uk>

On 09/02/17 10:42, Vusa Moyo wrote:
> Thanks so much. You've been a great help. 
>
> You have confirmed that the lecture's question is flawed.

It is not, it is exactly right.
(Albeit unusual in its use of class attributes) but there is
nothing wrong with the code, only the way you were trying to use it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From sylwester.graczyk at gmail.com  Thu Feb  9 14:15:14 2017
From: sylwester.graczyk at gmail.com (Sylwester Graczyk)
Date: Thu, 9 Feb 2017 20:15:14 +0100
Subject: [Tutor] Find (list) strings in large textfile
Message-ID: <13907542-012b-36cc-7c02-157f708a50c7@gmail.com>

Hi all,
I'm try to write a code to search strings (from one textfile with lists 
of strings) in second large text file.
but script doesn't search my lists in entire file (not complete output file)

*[list_life.txt]*
1654
964563
41164
6165456
85248
999745
35496486
... +2000 row's

*[large_file.txt]
*1654    2017/02/02
666445    2017/02/02
964563    2017/02/02
41164    2017/02/02
2467924    2017/02/02
6165456    2017/02/02
1145    2017/01/02
85248    2017/01/02
3354110    2017/01/02
999745    2017/01/02
8778873    2017/01/02
35496486    2017/01/02
666564646    2017/01/02
... + 500000 rows

*[code]*
file_list = open("list_life.txt")
file_large = open("large_file.txt")
save_file = open('output.txt', 'w')

for line_list in file_list:
     splitted_line_list = line_list.split()
     for line_large in file_large:
         splitted_line_large = line_large.split()
         if splitted_line_large[0] == splitted_line_list[0]:
             save_file.write(line_large+"\n")

file_large.close()
file_list.close()

*
*

From dyoo at hashcollision.org  Thu Feb  9 20:08:18 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 9 Feb 2017 17:08:18 -0800
Subject: [Tutor] Find (list) strings in large textfile
In-Reply-To: <13907542-012b-36cc-7c02-157f708a50c7@gmail.com>
References: <13907542-012b-36cc-7c02-157f708a50c7@gmail.com>
Message-ID: <CAGZAPF59WP8dgHCydVrVUd-r_e5TSzdnp5Kda-48iYmLZefZqQ@mail.gmail.com>

Files don't rewind automatically, so once a loop goes through the file
once, subsequent attempts will finish immediately.

We might fix this by "seek", which will let us rewind files.

However, your data is large enough that you might want to consider
efficiency too.  The nested loop approach is going to be expensive, taking
time proportional to the product of the sizes of your input files.

The problem can be done more efficiently, iterating over each file exactly
once.  Here is a sketch:

Try storing the numbers you are looking to find, and keep it in a set.
That is the loop over the first file.

Then, loop over the second file, consulting the set to see if the line is a
candidate or not.  Set membership is expected to be an inexpensive
operation.

From alan.gauld at yahoo.co.uk  Thu Feb  9 20:24:02 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 10 Feb 2017 01:24:02 +0000
Subject: [Tutor] Find (list) strings in large textfile
In-Reply-To: <13907542-012b-36cc-7c02-157f708a50c7@gmail.com>
References: <13907542-012b-36cc-7c02-157f708a50c7@gmail.com>
Message-ID: <o7j4nc$a54$1@blaine.gmane.org>

On 09/02/17 19:15, Sylwester Graczyk wrote:
> Hi all,
> I'm try to write a code to search strings (from one textfile with lists 
> of strings) in second large text file.
> but script doesn't search my lists in entire file (not complete output file)

The problem is that you open the data file once,
before the loop, but you never reset the cursor so when
it reaches the end after the first iteration it never
reads any more data. You need to seek(0) at the start
of each loop. However...

Your approach looks very inefficient however.
You will read 500,000 lines 2000 times. That's
a lot of file access - about 1 billion reads!

It is probably better to store your key file in memory
then loop over the large data file and check the
line against each key. Better to check 2000 data
keys in memory for one loop of the data file.
That way you only read the key file and data file
once each - 502,000 reads instead of a billion.

Also instead of splitting the line you could
just use

if line_large.startswith(key)

If the length of the comparison is critical
use the optional positional arguments:

if line_large.startswith(key,start,stop)

That should save a small amount of time compared
to splitting and indexing both lines each time.


> *[list_life.txt]*
> 1654
> 964563
> ... +2000 row's
> 
> *[large_file.txt]
> *1654    2017/02/02
> 666445    2017/02/02
> 964563    2017/02/02
> ... + 500000 rows
> 
> *[code]*
> file_list = open("list_life.txt")
> file_large = open("large_file.txt")
> save_file = open('output.txt', 'w')
> 
> for line_list in file_list:
>      splitted_line_list = line_list.split()

       file_large.seek(0)    # reset the data file cursor here

>      for line_large in file_large:
>          splitted_line_large = line_large.split()
>          if splitted_line_large[0] == splitted_line_list[0]:
>              save_file.write(line_large+"\n")
> 
> file_large.close()
> file_list.close()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From poojabhalode11 at gmail.com  Thu Feb  9 20:19:02 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Thu, 9 Feb 2017 20:19:02 -0500
Subject: [Tutor] CheckButtons reset to default values
Message-ID: <CAK0ikxeNBJWX=CzyHRsK6vapb9xhK=fFmvPA6=oamHZhubW+bg@mail.gmail.com>

Hi,

I have a bunch of checkbuttons in my code and a default settings button
which restores the original setting in the checkbuttons. The code is given
below:


    var1 = IntVar()
    var2 = IntVar()
    var3 = IntVar()
    var4 = IntVar()
    Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
offvalue=0).grid(row=1, column = 1, sticky=W)
    Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column =
1, sticky=W)
    Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column =
1, sticky=W)
    check = Checkbutton(frame1, text = "Center", variable=var4)
    check.grid(row=4, column = 1, sticky=W)
    check.select()

    label2 = Label(frame1, text="2. Cut off Improvement %")
    label2.grid(row=5, column=0,sticky=W)
    Entry2 = Entry(frame1)
    Entry2.insert(END, '05')
    Entry2.grid(row=5, column = 1, sticky = W)

    def default():
        print "Inside default"

        var1.set(0)
        var2.set(0)
        var3.set(0)
        var4.set(1)
        Entry2.delete(0, END)
        Entry2.insert(END,'05')

    Button(frame1, text = "Select Default value",
command=default).grid(row=0, column = 2, sticky=W)


This resets the Entry2 but it does not reset the checkbuttons selection to
the values specified in default function.
Can some one please tell me where I am going wrong?
Thank you so much.

Pooja

From sasil.adetunji at gmail.com  Thu Feb  9 21:05:44 2017
From: sasil.adetunji at gmail.com (Sasiliyu Adetunji)
Date: Fri, 10 Feb 2017 03:05:44 +0100
Subject: [Tutor] Help
Message-ID: <CACv2vyyEzY-1kE_EyZSgeY_cqdX8nMxdeRRvmqW6T2z9ZmQ36g@mail.gmail.com>

Please assist with this assignment

Write a function my_sort which takes in a list of numbers (positive
integers).

The function should return a list of sorted numbers such that odd numbers
come first and even numbers come last.


Regards

From basuraj.2006 at gmail.com  Fri Feb 10 01:48:18 2017
From: basuraj.2006 at gmail.com (Basavaraj Lamani)
Date: Fri, 10 Feb 2017 12:18:18 +0530
Subject: [Tutor] Can I can use subprocess module for connecting to linux
 from windows
Message-ID: <CA+Z+VqBGp2pbvt25vCHoQmxVfZk5+YQw+3r0WCLGsqNEauuboQ@mail.gmail.com>

Hi,

down votefavorite
<http://stackoverflow.com/questions/42110127/how-i-can-use-subprocess-module-for-connecting-to-linux-from-windows#>

Manual testing: I have installed putty in windows10 machine and by using
putty, I will do SSH connection to Linux machine(VM). I enter username and
password to access Linux machine(VM) then I enter different commands to
install application in Linux machine.

Automation: I want to automate above manual task by using python standard
subprocess module. I don't want to use third party libraries like paramiko,
pexpect etc. I am running script from windows machine. Please help me.

Below is the code( First I am trying to connect linux machine from
windows10).

import subprocess
cmd = "ssh root at 10.106.213.235"
p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr =subprocess.PIPE, bufsize=1,shell=True)

output: Process finished with exit code 0

code 0 means i believe there is no error in the script. But how i can
confirm that windows machine is connected to linux machine. while running
this script, am i able to see the shell?.

I am new to programming. Please provide your inputs which is really helpful
for me.

Thanks & Regards,

Basavaraj

From __peter__ at web.de  Fri Feb 10 04:48:31 2017
From: __peter__ at web.de (Peter Otten)
Date: Fri, 10 Feb 2017 10:48:31 +0100
Subject: [Tutor] CheckButtons reset to default values
References: <CAK0ikxeNBJWX=CzyHRsK6vapb9xhK=fFmvPA6=oamHZhubW+bg@mail.gmail.com>
Message-ID: <o7k29b$3f1$1@blaine.gmane.org>

Pooja Bhalode wrote:

> Hi,
> 
> I have a bunch of checkbuttons in my code and a default settings button
> which restores the original setting in the checkbuttons. The code is given
> below:
> 
> 
>     var1 = IntVar()
>     var2 = IntVar()
>     var3 = IntVar()
>     var4 = IntVar()
>     Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
> offvalue=0).grid(row=1, column = 1, sticky=W)
>     Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column
>     =
> 1, sticky=W)
>     Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column
>     =
> 1, sticky=W)
>     check = Checkbutton(frame1, text = "Center", variable=var4)
>     check.grid(row=4, column = 1, sticky=W)
>     check.select()
> 
>     label2 = Label(frame1, text="2. Cut off Improvement %")
>     label2.grid(row=5, column=0,sticky=W)
>     Entry2 = Entry(frame1)
>     Entry2.insert(END, '05')
>     Entry2.grid(row=5, column = 1, sticky = W)
> 
>     def default():
>         print "Inside default"
> 
>         var1.set(0)
>         var2.set(0)
>         var3.set(0)
>         var4.set(1)
>         Entry2.delete(0, END)
>         Entry2.insert(END,'05')
> 
>     Button(frame1, text = "Select Default value",
> command=default).grid(row=0, column = 2, sticky=W)
> 
> 
> This resets the Entry2 but it does not reset the checkbuttons selection to
> the values specified in default function.
> Can some one please tell me where I am going wrong?

The problem has to be elsewhere in your code. If I run a script

from Tkinter import *

root = frame1 = Tk()

if 1:
   # your snippet shown above goes here

root.mainloop()

clicking the button unchecks Vertices, Edges, Faces and checks Center.


From alan.gauld at yahoo.co.uk  Fri Feb 10 04:51:28 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 10 Feb 2017 09:51:28 +0000
Subject: [Tutor] Help
In-Reply-To: <CACv2vyyEzY-1kE_EyZSgeY_cqdX8nMxdeRRvmqW6T2z9ZmQ36g@mail.gmail.com>
References: <CACv2vyyEzY-1kE_EyZSgeY_cqdX8nMxdeRRvmqW6T2z9ZmQ36g@mail.gmail.com>
Message-ID: <o7k2eq$96k$1@blaine.gmane.org>

On 10/02/17 02:05, Sasiliyu Adetunji wrote:
> Please assist with this assignment
> 
> Write a function my_sort which takes in a list of numbers (positive
> integers).
> 
> The function should return a list of sorted numbers such that odd numbers
> come first and even numbers come last.

def my_sort(number_list):
   # your code goes here

Does that help?

If not you will need to be more specific about what help you need
and show us your code. We won't write it for you (apart from the
line above...)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Fri Feb 10 05:06:54 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 10 Feb 2017 10:06:54 +0000
Subject: [Tutor] Can I can use subprocess module for connecting to linux
 from windows
In-Reply-To: <CA+Z+VqBGp2pbvt25vCHoQmxVfZk5+YQw+3r0WCLGsqNEauuboQ@mail.gmail.com>
References: <CA+Z+VqBGp2pbvt25vCHoQmxVfZk5+YQw+3r0WCLGsqNEauuboQ@mail.gmail.com>
Message-ID: <o7k3bo$5l0$1@blaine.gmane.org>

On 10/02/17 06:48, Basavaraj Lamani wrote:

> putty, I will do SSH connection to Linux machine(VM). I enter username and
> password to access Linux machine(VM) then I enter different commands to
> install application in Linux machine.
> 
> Automation: I want to automate above manual task by using python standard
> subprocess module. 

The way I'd do that is write a Linux shell script to do all the Linux
work then use Python to ftp(*) a copy of the script to the Linux box and
just use ssh to run that script.

Trying to use subprocess to drive an interactive ssh session is an
exercise in frustration which I would avoid if at all possible.
Running a single command is much easier.

(*)Of course that assume you have an ftp server running on Linux...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From Joaquin.Alzola at lebara.com  Fri Feb 10 04:33:02 2017
From: Joaquin.Alzola at lebara.com (Joaquin Alzola)
Date: Fri, 10 Feb 2017 09:33:02 +0000
Subject: [Tutor] Help
In-Reply-To: <CACv2vyyEzY-1kE_EyZSgeY_cqdX8nMxdeRRvmqW6T2z9ZmQ36g@mail.gmail.com>
References: <CACv2vyyEzY-1kE_EyZSgeY_cqdX8nMxdeRRvmqW6T2z9ZmQ36g@mail.gmail.com>
Message-ID: <DB5PR07MB080650D5CC598AE08996829FF0440@DB5PR07MB0806.eurprd07.prod.outlook.com>

>Please assist with this assignment

>Write a function my_sort which takes in a list of numbers (positive
>integers).

>The function should return a list of sorted numbers such that odd numbers
>come first and even numbers come last.

You can search for even or odd numbers with the modulo (%) operant.

def my_sort(*numbers):


my_sort(X,Y,Z,F)

just trying not to tell you the excersice just to give you hints.
The best way to learn is to struggle a bit doing it yourself.
This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.

From poojabhalode11 at gmail.com  Fri Feb 10 10:56:53 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Fri, 10 Feb 2017 10:56:53 -0500
Subject: [Tutor] CheckButtons reset to default values
In-Reply-To: <o7k29b$3f1$1@blaine.gmane.org>
References: <CAK0ikxeNBJWX=CzyHRsK6vapb9xhK=fFmvPA6=oamHZhubW+bg@mail.gmail.com>
 <o7k29b$3f1$1@blaine.gmane.org>
Message-ID: <CAK0ikxeL+vFx=veMx=yWXYOabY-qqALeCnQHawJa+CJXbCXUKw@mail.gmail.com>

Hi Peter,

The code is as shown below.  I have put it in the manner you have told me.

root = Tk()
root.title("Design of Experiments with Parameter Estimation")
root.geometry("1000x1000")

def DesignPoint():
    print "Inside Design Point"
    rootdesign=Tk()
    rootdesign.title("Estimation of Experimental Precision for Data
Var-CoVar")
    rootdesign.geometry("600x400")
    frame1 = Frame(rootdesign)
    frame1.grid(row=0, column=0)

    ## Inserting Checkboxes:
    label1 = Label(frame1, text="1. Design Point Suggestions")
    label1.grid(row=0, column=0,sticky=W )
    var1 = IntVar()
    var2 = IntVar()
    var3 = IntVar()
    var4 = IntVar()
    Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
offvalue=0).grid(row=1, column = 1, sticky=W)
    Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column =
1, sticky=W)
    Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column =
1, sticky=W)
    check = Checkbutton(frame1, text = "Center", variable=var4)
    check.grid(row=4, column = 1, sticky=W)
    check.select()


    label2 = Label(frame1, text="2. Cut off Improvement %")
    label2.grid(row=5, column=0,sticky=W)
    Entry2 = Entry(frame1)
    Entry2.insert(END, '05')
    Entry2.grid(row=5, column = 1, sticky = W)

    label3 = Label(frame1, text="3. Simulation of proposed Experiments: ")
    label3.grid(row=5, column=0,sticky=W)

    label4 = Label(frame1, text="4. Calculate sensitivities")
    label4.grid(row=6, column=0,sticky=W)

    def default():
        print "Inside default"

        var1.set(0)
        var2.set(0)
        var3.set(0)
        var4.set(1)
        Entry2.delete(0, END)
        Entry2.insert(END,'05')
   Button(frame1, text = "Select Default value",
command=default.grid(row=0, column = 2, sticky=W)

    rootdesign.mainloop()


## Secondary menu bar:
menusec = Frame(root, bg="white")
butt1 = Button(menusec, text="Part One", command=DesignPoint)
butt1.pack(side=LEFT, padx=1)
menusec.pack(side=TOP, fill=X)


root.mainloop()

It still doesn't work for me for the reason I am not able to figure out.
Please let me know.
Thank you once again in advance.

Pooja

On Fri, Feb 10, 2017 at 4:48 AM, Peter Otten <__peter__ at web.de> wrote:

> Pooja Bhalode wrote:
>
> > Hi,
> >
> > I have a bunch of checkbuttons in my code and a default settings button
> > which restores the original setting in the checkbuttons. The code is
> given
> > below:
> >
> >
> >     var1 = IntVar()
> >     var2 = IntVar()
> >     var3 = IntVar()
> >     var4 = IntVar()
> >     Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
> > offvalue=0).grid(row=1, column = 1, sticky=W)
> >     Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column
> >     =
> > 1, sticky=W)
> >     Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column
> >     =
> > 1, sticky=W)
> >     check = Checkbutton(frame1, text = "Center", variable=var4)
> >     check.grid(row=4, column = 1, sticky=W)
> >     check.select()
> >
> >     label2 = Label(frame1, text="2. Cut off Improvement %")
> >     label2.grid(row=5, column=0,sticky=W)
> >     Entry2 = Entry(frame1)
> >     Entry2.insert(END, '05')
> >     Entry2.grid(row=5, column = 1, sticky = W)
> >
> >     def default():
> >         print "Inside default"
> >
> >         var1.set(0)
> >         var2.set(0)
> >         var3.set(0)
> >         var4.set(1)
> >         Entry2.delete(0, END)
> >         Entry2.insert(END,'05')
> >
> >     Button(frame1, text = "Select Default value",
> > command=default).grid(row=0, column = 2, sticky=W)
> >
> >
> > This resets the Entry2 but it does not reset the checkbuttons selection
> to
> > the values specified in default function.
> > Can some one please tell me where I am going wrong?
>
> The problem has to be elsewhere in your code. If I run a script
>
> from Tkinter import *
>
> root = frame1 = Tk()
>
> if 1:
>    # your snippet shown above goes here
>
> root.mainloop()
>
> clicking the button unchecks Vertices, Edges, Faces and checks Center.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at yahoo.co.uk  Fri Feb 10 13:01:50 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 10 Feb 2017 18:01:50 +0000
Subject: [Tutor] CheckButtons reset to default values
In-Reply-To: <CAK0ikxeL+vFx=veMx=yWXYOabY-qqALeCnQHawJa+CJXbCXUKw@mail.gmail.com>
References: <CAK0ikxeNBJWX=CzyHRsK6vapb9xhK=fFmvPA6=oamHZhubW+bg@mail.gmail.com>
 <o7k29b$3f1$1@blaine.gmane.org>
 <CAK0ikxeL+vFx=veMx=yWXYOabY-qqALeCnQHawJa+CJXbCXUKw@mail.gmail.com>
Message-ID: <o7kv68$g5m$1@blaine.gmane.org>

On 10/02/17 15:56, Pooja Bhalode wrote:

> root = Tk()
> root.title("Design of Experiments with Parameter Estimation")
> root.geometry("1000x1000")
> 
> def DesignPoint():
>     rootdesign=Tk()

You should o0nly have one root. This create a new root
everytime you xcall Designpoint and even if thats only
once you still have a root already at the global level.

It would be better to define the function to have
a root parameter that you can pass in when you call it.

>     rootdesign.title("Estimation of Experimental Precision for Data
> Var-CoVar")
>     rootdesign.geometry("600x400")

Are you trying to create a second window? If so you
should probably use the TopLevel widget for that but
with the same toplevel root.

Alternatively you could create a Dialog using the Dialog
module but that probably requires a bit more OOP than
you seem comfortable with.


>     frame1 = Frame(rootdesign)
>     frame1.grid(row=0, column=0)
> 
>     ## Inserting Checkboxes:
>     label1 = Label(frame1, text="1. Design Point Suggestions")
>     label1.grid(row=0, column=0,sticky=W )
>     var1 = IntVar()
>     var2 = IntVar()
>     var3 = IntVar()
>     var4 = IntVar()

These vars should probably be declared and initialised
outside the function.

>     Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
> offvalue=0).grid(row=1, column = 1, sticky=W)
>     Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column =
> 1, sticky=W)
>     Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column =
> 1, sticky=W)
>     check = Checkbutton(frame1, text = "Center", variable=var4)
>     check.grid(row=4, column = 1, sticky=W)
>     check.select()
> 
> 
>     label2 = Label(frame1, text="2. Cut off Improvement %")
>     label2.grid(row=5, column=0,sticky=W)
>     Entry2 = Entry(frame1)
>     Entry2.insert(END, '05')
>     Entry2.grid(row=5, column = 1, sticky = W)
> 
>     label3 = Label(frame1, text="3. Simulation of proposed Experiments: ")
>     label3.grid(row=5, column=0,sticky=W)
> 
>     label4 = Label(frame1, text="4. Calculate sensitivities")
>     label4.grid(row=6, column=0,sticky=W)
> 

The above is ok but...


>     def default():
>         print "Inside default"
> 
>         var1.set(0)
>         var2.set(0)
>         var3.set(0)
>         var4.set(1)
>         Entry2.delete(0, END)
>         Entry2.insert(END,'05')

You have now defined this function inside the Designpoint
function. It should probably be outside except you would
lose visibility of the vars - which is why they should be global.

>    Button(frame1, text = "Select Default value",
> command=default.grid(row=0, column = 2, sticky=W)


But you cannot apply grid to a function. your command
should be default. In suspect you are just missing a
closing parenthesis

    Button(frame1,
           text = "Select Default value",
           command=default).grid(row=0, column = 2, sticky=W)

>     rootdesign.mainloop()
> 
> 
> ## Secondary menu bar:
> menusec = Frame(root, bg="white")
> butt1 = Button(menusec, text="Part One", command=DesignPoint)
> butt1.pack(side=LEFT, padx=1)
> menusec.pack(side=TOP, fill=X)
> 
> 
> root.mainloop()
> 
> It still doesn't work for me for the reason I am not able to figure out.
> Please let me know.

You have quite a few issues. The main things you should sort out are:

1) only use one root.
2) put the vars and default definitions outside the
   designpoint function.
3) add the closing parenthesis.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From feifan95323 at hotmail.com  Fri Feb 10 15:07:58 2017
From: feifan95323 at hotmail.com (fei fan)
Date: Fri, 10 Feb 2017 20:07:58 +0000
Subject: [Tutor] Climata package
Message-ID: <YQXPR01MB0134342E11A05087F14DAE22F2440@YQXPR01MB0134.CANPRD01.PROD.OUTLOOK.COM>

Hi tutor,

Do you know of any good resources to extract data using the climata package and to convert these data in .geojson format?

Thanks,

Fei

From alan.gauld at yahoo.co.uk  Fri Feb 10 18:41:07 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 10 Feb 2017 23:41:07 +0000
Subject: [Tutor] Climata package
In-Reply-To: <YQXPR01MB0134342E11A05087F14DAE22F2440@YQXPR01MB0134.CANPRD01.PROD.OUTLOOK.COM>
References: <YQXPR01MB0134342E11A05087F14DAE22F2440@YQXPR01MB0134.CANPRD01.PROD.OUTLOOK.COM>
Message-ID: <o7lj2d$gj2$1@blaine.gmane.org>

On 10/02/17 20:07, fei fan wrote:
> Hi tutor,
> 
> Do you know of any good resources to extract data using the climata 
> package and to convert these data in .geojson format?

This forum is for the core language and standard library so this is a
bit off topic, you might get a better response on the main Python list
which has a wider audience.

A quick Google search for "python climata geojson" threw up quite a lot
on geojson but nothing at all on climata.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Fri Feb 10 20:34:35 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Fri, 10 Feb 2017 19:34:35 -0600
Subject: [Tutor] Test for type(object) == ???
Message-ID: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>

I was playing around with type() tonight.  If I type (pun intended), I get:

py3: type(5)
<class 'int'>

So I naively thought a test for type int should go like:

py3: type(5) == "<class 'int'>"
False

Hmm.  So I tried these other failing tests:

py3: type(5) == <class 'int'>
  File "<stdin>", line 1
    type(5) == <class 'int'>
               ^
SyntaxError: invalid syntax

py3: type(5) == 'int()'
False

I finally stumbled onto the correct form:

py3: type(5) == int
True

So my question is why does "type(5)" result in "<class 'int'>", but
the correct Boolean test is "type(5) == int"?  I suspect it has
something to do with the built-in attributes of Python objects that I
currently know so very little about.

As always, many thanks in advance!

-- 
boB

From zachary.ware+pytut at gmail.com  Fri Feb 10 20:50:28 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Fri, 10 Feb 2017 19:50:28 -0600
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
Message-ID: <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>

On Fri, Feb 10, 2017 at 7:34 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> So my question is why does "type(5)" result in "<class 'int'>", but
> the correct Boolean test is "type(5) == int"?  I suspect it has
> something to do with the built-in attributes of Python objects that I
> currently know so very little about.

Try `help(repr)` and `int` on its own at the interactive prompt, and
see if that clarifies anything.  I hope that might be enough to nudge
you in the right direction, but if not, come back and ask :)

-- 
Zach

From akleider at sonic.net  Fri Feb 10 20:58:25 2017
From: akleider at sonic.net (Alex Kleider)
Date: Fri, 10 Feb 2017 17:58:25 -0800
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
Message-ID: <27d889751f29f01239861f12a1b48ffe@sonic.net>

On 2017-02-10 17:34, boB Stepp wrote:
> I was playing around with type() tonight.  .........

I've also "played around" with this subject-
Here's a source:
http://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python

... and a successful experiment:
alex at X301n3:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type(5) is int
True
>>> isinstance(5, int)
True

From robertvstepp at gmail.com  Fri Feb 10 20:59:04 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Fri, 10 Feb 2017 19:59:04 -0600
Subject: [Tutor] Python-list thread: int vs. float
Message-ID: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>

I have been following the thread "int vs. float"
(https://mail.python.org/pipermail/python-list/2017-February/719287.html)
on the main list.  A search for the OP on the Tutor archive came up
negative, so I am hoping he is not following Tutor tonight (Or anytime
prior to the due date for his homework!).  The central part of
adam14711993's question is:

"What I cannot figure out is how to write it so that if my user input
is, for example, 1.5, the program will result with: Sorry, you can
only order whole packages.

"I understand that because I am starting out by assigning my
number_purchases_str to be an int, when the user enters a float that
is a conflict and will crash."

He cannot figure out how to reliably tell if the user's input is an
integer, float or neither.  So I thought I would come up with my
solution, which currently is:

py3: def ck_input():
...     value_to_ck = input('Enter a number:')
...     try:
...             value = int(value_to_ck)
...             print('You have entered an integer.')
...     except ValueError:
...             try:
...                     value = float(value_to_ck)
...                     print('You have entered a float.')
...             except ValueError:
...                     print('You have failed to enter a numerical value.')
...

(Yes, I know I am not doing anything with the variable, "value", but
if I were to actually implement this in the future, I am sure I would
find a use for it.  So I left it as is for the moment.)

My quick checks are:

py3: ck_input()
Enter a number:5
You have entered an integer.
py3: ck_input()
Enter a number:5.0
You have entered a float.
py3: ck_input()
Enter a number:'5'
You have failed to enter a numerical value.

This is all well and good.  I am not trying to elicit an "Atta boy,
boB!" here. ~(:>)) Instead, I am wondering if there is something in
Python's wonderful cornucopia of programming stuff that can simplify
this type of check.  As you might guess from my earlier post this
evening, I have been playing around with "type()" and "isinstance()",
but if I try something like:

py3: isinstance(int('5.0'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'

I get the ValueError I make use of in my function above.

So, is there any easier way to do this check?  If not, can my function
be improved to make it a bit less lengthy, but still eminently
readable?

TIA!
-- 
boB

From ben+python at benfinney.id.au  Fri Feb 10 21:00:11 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sat, 11 Feb 2017 13:00:11 +1100
Subject: [Tutor] Test for type(object) == ???
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
Message-ID: <85bmu9o5as.fsf@benfinney.id.au>

boB Stepp <robertvstepp at gmail.com> writes:

> I was playing around with type() tonight.  If I type (pun intended), I get:
>
> py3: type(5)
> <class 'int'>

Ceci n'est pas un ?int?.

> So I naively thought a test for type int should go like:
>
> py3: type(5) == "<class 'int'>"
> False
>
> Hmm.

The output from the REPL can only be text. But a type, or any other
object in memory, is not text on the screen; the text only *represents*
an object.

More than that: You can't type objects into your program code. You have
to *reference* them, often by using names.

So the type ?int? can be referenced by the name, ?int?:

    >>> type(5) is int
    True

And that type, when asked for a text representation, will give you some
text.

    >>> type(5)
    <class 'int'>

The object is not its name. The object is not its representation. And
those can (and in this case, are) all different.

<URL:https://en.wikipedia.org/wiki/The_Treachery_of_Images>

-- 
 \              ?Programs must be written for people to read, and only |
  `\        incidentally for machines to execute.? ?Abelson & Sussman, |
_o__)              _Structure and Interpretation of Computer Programs_ |
Ben Finney


From eryksun at gmail.com  Fri Feb 10 21:05:30 2017
From: eryksun at gmail.com (eryk sun)
Date: Sat, 11 Feb 2017 02:05:30 +0000
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
Message-ID: <CACL+1at7pZhVKf0ujd4FyBHJ1HO5802W=GOw83j9MqWyu9NZkA@mail.gmail.com>

On Sat, Feb 11, 2017 at 1:34 AM, boB Stepp <robertvstepp at gmail.com> wrote:
> I was playing around with type() tonight.  If I type (pun intended), I get:
>
> py3: type(5)
> <class 'int'>

`type` is a metaclass that either creates a new class (given 3
arguments: name, bases, and dict) or returns a reference to the class
of an existing object. type(5) is the latter case, and it returns a
reference to the class `int`. What you see printed in the REPL is
repr(int), a string representation of the class object:

     >>> repr(int)
     "<class 'int'>"

Speaking of classes and metaclasses, note that you can't call
int.__repr__(int) to get this representation, because the __repr__
special method of int is meant for instances of int such as int(5).
Instead you have to explicitly use __repr__ from the metaclass, i.e.
`type`:

    >>> type(int)
    <class 'type'>
    >>> type.__repr__(int)
    "<class 'int'>"

But just use built-in repr().

From robertvstepp at gmail.com  Fri Feb 10 22:22:57 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Fri, 10 Feb 2017 21:22:57 -0600
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>
Message-ID: <CANDiX9+SfTm8W3tAzRsMHUiKZfL1r_+4+myFXB_u7Rd=FEGN-A@mail.gmail.com>

On Fri, Feb 10, 2017 at 7:50 PM, Zachary Ware
<zachary.ware+pytut at gmail.com> wrote:

> Try `help(repr)` and `int` on its own at the interactive prompt, and

py3: help(repr)
Help on built-in function repr in module builtins:

repr(obj, /)
    Return the canonical string representation of the object.

    For many object types, including most builtins, eval(repr(obj)) == obj.

Question:  What does the forward slash represent in this context?  If I type:

py3: repr(int, /)
  File "<stdin>", line 1
    repr(int, /)
              ^
SyntaxError: invalid syntax

whereas:

py3: repr(int)
"<class 'int'>"

appears to be correct.

-- 
boB

From robertvstepp at gmail.com  Fri Feb 10 23:32:10 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Fri, 10 Feb 2017 22:32:10 -0600
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CACL+1at7pZhVKf0ujd4FyBHJ1HO5802W=GOw83j9MqWyu9NZkA@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CACL+1at7pZhVKf0ujd4FyBHJ1HO5802W=GOw83j9MqWyu9NZkA@mail.gmail.com>
Message-ID: <CANDiX9+dpvHwENVKtU8qcWu7M0Y2iNdd-VzmvfYccVC3DmCboQ@mail.gmail.com>

On Fri, Feb 10, 2017 at 8:05 PM, eryk sun <eryksun at gmail.com> wrote:

> Speaking of classes and metaclasses, note that you can't call
> int.__repr__(int) to get this representation, because the __repr__
> special method of int is meant for instances of int such as int(5).

This bit got me experimenting.  Since the integer "5" is an integer
object instance, I am wondering why I can't do:

py3: 5.__repr__()
  File "<stdin>", line 1
    5.__repr__()
             ^
SyntaxError: invalid syntax

, but I can do:

py3: x = 5
py3: x.__repr__()
'5'

?

More experimentation.  Is this how I would define __repr__() for a custom class?

py3: class boB:
...     def __repr__(self):
...             return "<boB's namesake class>"
...
py3: x = boB()
py3: repr(x)
"<boB's namesake class>"

Seems to work.  But in class examples I've seen posted, I do not
recall __repr__ ever being defined.  So I infer that most of the time
I should not or need not do so, but under what circumstances should I
do so?

Another curiosity question.  If I type:

py3: repr(int)
"<class 'int'>"

I get what I expect, but if I do the same with my custom class, "boB",
I instead get:

py3: repr(boB)
"<class '__main__.boB'>"

Why the difference between the Python class "int" and my custom class
"boB"?  Did I not define __repr__() correctly?



-- 
boB

From eryksun at gmail.com  Sat Feb 11 00:27:54 2017
From: eryksun at gmail.com (eryk sun)
Date: Sat, 11 Feb 2017 05:27:54 +0000
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9+dpvHwENVKtU8qcWu7M0Y2iNdd-VzmvfYccVC3DmCboQ@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CACL+1at7pZhVKf0ujd4FyBHJ1HO5802W=GOw83j9MqWyu9NZkA@mail.gmail.com>
 <CANDiX9+dpvHwENVKtU8qcWu7M0Y2iNdd-VzmvfYccVC3DmCboQ@mail.gmail.com>
Message-ID: <CACL+1augMyGNmRZamo+_yPvb+3_xd89vCnp7JzaCn=XWyN_YtA@mail.gmail.com>

On Sat, Feb 11, 2017 at 4:32 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>
> This bit got me experimenting.  Since the integer "5" is an integer
> object instance, I am wondering why I can't do:
>
> py3: 5.__repr__()
>   File "<stdin>", line 1
>     5.__repr__()
>              ^
> SyntaxError: invalid syntax
>
> , but I can do:
>
> py3: x = 5
> py3: x.__repr__()
> '5'

The parser sees "5." as a floating point number. You can use
parentheses to force it to parse 5 as an integer:

    >>> (5).__repr__()
    '5'

> But in class examples I've seen posted, I do not recall __repr__ ever
> being defined.  So I infer that most of the time I should not or need not
> do so, but under what circumstances should I do so?

Classes inherit a default __repr__ from `object`. For example:

    >>> object.__repr__(5)
    '<int object at 0xa68ac0>'

Define a custom __repr__ when it's useful for debugging to include
additional information. It also gets called for str() if you don't
implement a custom __str__.

> Another curiosity question.  If I type:
>
> py3: repr(int)
> "<class 'int'>"
>
> I get what I expect, but if I do the same with my custom class, "boB",
> I instead get:
>
> py3: repr(boB)
> "<class '__main__.boB'>"
>
> Why the difference between the Python class "int" and my custom class
> "boB"?  Did I not define __repr__() correctly?

The __repr__ defined by your class is used for instances of the class,
not for the class itself. In the above you're seeing the return value
from the metaclass __repr__ that's defined by `type`:

In CPython, type.__repr__ is implemented in C as type_repr in
Objects/typeobject.c. If it can determine the module and qualified
name of a class, then it uses the template "<class '%U.%U'>".
Otherwise it uses the template "<class '%s'>" with the basic char
*tp_name from the PyTypeObject.

From robertvstepp at gmail.com  Sat Feb 11 00:49:36 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Fri, 10 Feb 2017 23:49:36 -0600
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CACL+1augMyGNmRZamo+_yPvb+3_xd89vCnp7JzaCn=XWyN_YtA@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CACL+1at7pZhVKf0ujd4FyBHJ1HO5802W=GOw83j9MqWyu9NZkA@mail.gmail.com>
 <CANDiX9+dpvHwENVKtU8qcWu7M0Y2iNdd-VzmvfYccVC3DmCboQ@mail.gmail.com>
 <CACL+1augMyGNmRZamo+_yPvb+3_xd89vCnp7JzaCn=XWyN_YtA@mail.gmail.com>
Message-ID: <CANDiX9Lo7Z7fj+2tKETtk+pvyjway3odoVtQ4FXkUsTk3w-DWA@mail.gmail.com>

Thanks for the detailed information.  I have a final really nitpicky question.

On Fri, Feb 10, 2017 at 11:27 PM, eryk sun <eryksun at gmail.com> wrote:
> On Sat, Feb 11, 2017 at 4:32 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>>
>> This bit got me experimenting.  Since the integer "5" is an integer
>> object instance, I am wondering why I can't do:
>>
>> py3: 5.__repr__()
>>   File "<stdin>", line 1
>>     5.__repr__()
>>              ^
>> SyntaxError: invalid syntax

[snip]

> The parser sees "5." as a floating point number.

I am curious as to why the caret does not point to the first
underscore after the decimal point in the error message?  It is at
that precise character that the discerned syntax error occurs.

boB

From eryksun at gmail.com  Sat Feb 11 00:49:02 2017
From: eryksun at gmail.com (eryk sun)
Date: Sat, 11 Feb 2017 05:49:02 +0000
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9+SfTm8W3tAzRsMHUiKZfL1r_+4+myFXB_u7Rd=FEGN-A@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>
 <CANDiX9+SfTm8W3tAzRsMHUiKZfL1r_+4+myFXB_u7Rd=FEGN-A@mail.gmail.com>
Message-ID: <CACL+1ata97rpoiLNp2U+kWOWrG3pKt2NKF7_NwQ84X4d2S0jDQ@mail.gmail.com>

On Sat, Feb 11, 2017 at 3:22 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>
> py3: help(repr)
> Help on built-in function repr in module builtins:
>
> repr(obj, /)
>     Return the canonical string representation of the object.
>
>     For many object types, including most builtins, eval(repr(obj)) == obj.
>
> Question:  What does the forward slash represent in this context?

It's from the function's __text_signature__.

    >>> repr.__text_signature__
    '($module, obj, /)'

It means "obj" is a positional-only argument that cannot be passed as a keyword.

    >>> s = inspect.signature(repr)
    >>> s.parameters['obj'].kind
    <_ParameterKind.POSITIONAL_ONLY: 0>

CPython has a lot of built-in functions that don't allow keyword arguments.

    >>> repr(obj=42)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: repr() takes no keyword arguments

Look at open() for comparison.

    >>> open.__text_signature__
    "($module, /, file, mode='r', buffering=-1, encoding=None,\n
    errors=None, newline=None, closefd=True, opener=None)"

All of its parameters can be passed as keyword arguments.

    >>> s = inspect.signature(open)
    >>> s.parameters['file'].kind
    <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>
    >>> s.parameters['mode'].kind
    <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>

For example:

    >>> open(file='spam', mode='w')
    <_io.TextIOWrapper name='spam' mode='w' encoding='UTF-8'>

From robertvstepp at gmail.com  Sat Feb 11 01:22:50 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 11 Feb 2017 00:22:50 -0600
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CACL+1ata97rpoiLNp2U+kWOWrG3pKt2NKF7_NwQ84X4d2S0jDQ@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>
 <CANDiX9+SfTm8W3tAzRsMHUiKZfL1r_+4+myFXB_u7Rd=FEGN-A@mail.gmail.com>
 <CACL+1ata97rpoiLNp2U+kWOWrG3pKt2NKF7_NwQ84X4d2S0jDQ@mail.gmail.com>
Message-ID: <CANDiX9+HQhXi2q7frJe=dswTjQ=ORus2TcE38Qj5npv7Us3eLQ@mail.gmail.com>

On Fri, Feb 10, 2017 at 11:49 PM, eryk sun <eryksun at gmail.com> wrote:
> On Sat, Feb 11, 2017 at 3:22 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>>
>> py3: help(repr)
>> Help on built-in function repr in module builtins:
>>
>> repr(obj, /)
>>     Return the canonical string representation of the object.
>>
>>     For many object types, including most builtins, eval(repr(obj)) == obj.
>>
>> Question:  What does the forward slash represent in this context?
>
> It's from the function's __text_signature__.
>
>     >>> repr.__text_signature__
>     '($module, obj, /)'
>
> It means "obj" is a positional-only argument that cannot be passed as a keyword.

[snip]

> Look at open() for comparison.
>
>     >>> open.__text_signature__
>     "($module, /, file, mode='r', buffering=-1, encoding=None,\n
>     errors=None, newline=None, closefd=True, opener=None)"

In your comparison example, a forward slash appears again, but this
time after "$module" in the location where "obj" previously appeared
in the repr example.  Is it indicating a similar use here?

Can you provide a link to "__text_signature__" in the docs?  I tried
searching for it, but came up empty.


-- 
boB

From eryksun at gmail.com  Sat Feb 11 01:57:19 2017
From: eryksun at gmail.com (eryk sun)
Date: Sat, 11 Feb 2017 06:57:19 +0000
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9+HQhXi2q7frJe=dswTjQ=ORus2TcE38Qj5npv7Us3eLQ@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>
 <CANDiX9+SfTm8W3tAzRsMHUiKZfL1r_+4+myFXB_u7Rd=FEGN-A@mail.gmail.com>
 <CACL+1ata97rpoiLNp2U+kWOWrG3pKt2NKF7_NwQ84X4d2S0jDQ@mail.gmail.com>
 <CANDiX9+HQhXi2q7frJe=dswTjQ=ORus2TcE38Qj5npv7Us3eLQ@mail.gmail.com>
Message-ID: <CACL+1asX3eWqZetgLu1qDR7aSixhCmzZ3NKABpxOkkrtBpFjTA@mail.gmail.com>

On Sat, Feb 11, 2017 at 6:22 AM, boB Stepp <robertvstepp at gmail.com> wrote:
> On Fri, Feb 10, 2017 at 11:49 PM, eryk sun <eryksun at gmail.com> wrote:
>
>> It's from the function's __text_signature__.
>>
>>     >>> repr.__text_signature__
>>     '($module, obj, /)'
>>
>> It means "obj" is a positional-only argument that cannot be passed as a keyword.
>
> [snip]
>
>> Look at open() for comparison.
>>
>>     >>> open.__text_signature__
>>     "($module, /, file, mode='r', buffering=-1, encoding=None,\n
>>     errors=None, newline=None, closefd=True, opener=None)"
>
> In your comparison example, a forward slash appears again, but this
> time after "$module" in the location where "obj" previously appeared
> in the repr example.  Is it indicating a similar use here?

All parameters listed before the slash are position-only. Everything
after the slash can be passed as a keyword argument.

> Can you provide a link to "__text_signature__" in the docs?  I tried
> searching for it, but came up empty.

No, I can't. It was added in issue 19674.

http://bugs.python.org/issue19674

The '/' syntax for positional-only arguments is documented in PEP 457.

https://www.python.org/dev/peps/pep-0457

Also see the how-to for CPython's "Argument Clinic" preprocessor,
since (for now) positional-only arguments are only a concern for
built-in functions.

https://docs.python.org/3/howto/clinic.html

From robertvstepp at gmail.com  Sat Feb 11 02:35:51 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 11 Feb 2017 01:35:51 -0600
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CACL+1asX3eWqZetgLu1qDR7aSixhCmzZ3NKABpxOkkrtBpFjTA@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>
 <CANDiX9+SfTm8W3tAzRsMHUiKZfL1r_+4+myFXB_u7Rd=FEGN-A@mail.gmail.com>
 <CACL+1ata97rpoiLNp2U+kWOWrG3pKt2NKF7_NwQ84X4d2S0jDQ@mail.gmail.com>
 <CANDiX9+HQhXi2q7frJe=dswTjQ=ORus2TcE38Qj5npv7Us3eLQ@mail.gmail.com>
 <CACL+1asX3eWqZetgLu1qDR7aSixhCmzZ3NKABpxOkkrtBpFjTA@mail.gmail.com>
Message-ID: <CANDiX9Kc6TQ7yNg3hvWmhtxHkT+135qTv9Ur9RVi+_-iHVsOBQ@mail.gmail.com>

On Sat, Feb 11, 2017 at 12:57 AM, eryk sun <eryksun at gmail.com> wrote:

>
> The '/' syntax for positional-only arguments is documented in PEP 457.
>
> https://www.python.org/dev/peps/pep-0457

At https://www.python.org/dev/peps/pep-0457/#id14 in PEP 457 it says:

<quote>

>From the "ten-thousand foot view", and ignoring *args and **kwargs for
now, the grammar for a function definition currently looks like this:

def name(positional_or_keyword_parameters, *, keyword_only_parameters):

Building on that perspective, the new syntax for functions would look like this:

def name(positional_only_parameters, /, positional_or_keyword_parameters,
         *, keyword_only_parameters):

All parameters before the / are positional-only. If / is not specified
in a function signature, that function does not accept any
positional-only parameters.

</quote>

Has this PEP been implemented yet?  I am running Python 3.5.2 and it
appears not to work.  Also, in "What's New In Python 3.6"
(https://docs.python.org/3/whatsnew/3.6.html) I did not see a mention
of it.


> Also see the how-to for CPython's "Argument Clinic" preprocessor,
> since (for now) positional-only arguments are only a concern for
> built-in functions.

So I am assuming this syntax is only being used for some built-in functions?

You have provided a lot of interesting information.  I'm not sure if I
am comprehending everything, but it has made interesting reading and
Googling tonight.  Enough so that I have stayed up much later than I
meant to!  Thanks!



-- 
boB

From eryksun at gmail.com  Sat Feb 11 03:02:24 2017
From: eryksun at gmail.com (eryk sun)
Date: Sat, 11 Feb 2017 08:02:24 +0000
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9Kc6TQ7yNg3hvWmhtxHkT+135qTv9Ur9RVi+_-iHVsOBQ@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <CAKJDb-NedYNK3yGAvXjWr=Wcwx+9sKEty_0Tg2kGWC_3toC38Q@mail.gmail.com>
 <CANDiX9+SfTm8W3tAzRsMHUiKZfL1r_+4+myFXB_u7Rd=FEGN-A@mail.gmail.com>
 <CACL+1ata97rpoiLNp2U+kWOWrG3pKt2NKF7_NwQ84X4d2S0jDQ@mail.gmail.com>
 <CANDiX9+HQhXi2q7frJe=dswTjQ=ORus2TcE38Qj5npv7Us3eLQ@mail.gmail.com>
 <CACL+1asX3eWqZetgLu1qDR7aSixhCmzZ3NKABpxOkkrtBpFjTA@mail.gmail.com>
 <CANDiX9Kc6TQ7yNg3hvWmhtxHkT+135qTv9Ur9RVi+_-iHVsOBQ@mail.gmail.com>
Message-ID: <CACL+1askUMu4D7LAB5wM56apre3Eg9Ecof7rHvfd3dyXhYuDLw@mail.gmail.com>

On Sat, Feb 11, 2017 at 7:35 AM, boB Stepp <robertvstepp at gmail.com> wrote:
> Has this PEP been implemented yet?  I am running Python 3.5.2 and it
> appears not to work.  Also, in "What's New In Python 3.6"
> (https://docs.python.org/3/whatsnew/3.6.html) I did not see a mention
> of it.

You can see in the document header that PEP 457 is an Informational
document at the draft stage, as opposed to a Standards Track document
that's finalized. It's the best I could find as provisional
documentation of CPython's usage of '/' to mark positional-only
arguments of built-in functions. FYI, the PEP's author, Larry
Hastings, is also the author of Argument Clinic.

From steve at pearwood.info  Sat Feb 11 03:06:07 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Feb 2017 19:06:07 +1100
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
Message-ID: <20170211080607.GF4796@ando.pearwood.info>

On Fri, Feb 10, 2017 at 07:59:04PM -0600, boB Stepp wrote:

> He cannot figure out how to reliably tell if the user's input is an
> integer, float or neither.  So I thought I would come up with my
> solution, which currently is:
> 
> py3: def ck_input():
> ...     value_to_ck = input('Enter a number:')
> ...     try:
> ...             value = int(value_to_ck)
> ...             print('You have entered an integer.')
> ...     except ValueError:
> ...             try:
> ...                     value = float(value_to_ck)
> ...                     print('You have entered a float.')
> ...             except ValueError:
> ...                     print('You have failed to enter a numerical value.')
> ...
[...]
> This is all well and good.  I am not trying to elicit an "Atta boy,
> boB!" here. ~(:>)) 

Nevertheless, atta boy boB! 

The only not-so-good part of this is that you have mixed user-interface 
and internal calculation. Better:


def to_number(string):
    """Convert string to either an int or a float, or raise ValueError."""
    try:
        return int(string)
    except ValueError:
        return float(string)


def check_input():
    value_to_ck = input('Enter a number: ')
    try:
        value = to_number(value_to_ck)
    except ValueError:
        print('You have failed to enter a numerical value.')
        return
    if isinstance(value, float):
        print('You have entered a float.')
    else:
        print('You have entered an int.')


This gives you nice separation between the function that interacts with 
the user, and the function that does the actual conversion.



> Instead, I am wondering if there is something in
> Python's wonderful cornucopia of programming stuff that can simplify
> this type of check.

The most reliable and foolproof way of checking if something is a valid 
int is to ask int to convert it, and see if it fails.

Likewise for floats, where the format is *very* complex. Any of these, 
and many more, should be accepted:

    1.2345
    +1.2345
    -1.2345e0
    123.45e+20
    123.45E-20
    .123
    -.123
    +.123e-12
    123.
    inf
    +inf
    -inf
    NaN

Getting all the gory details right of what is and isn't allowed may be 
tricky, but that's okay, because float() already understands how to do 
it for you.


> As you might guess from my earlier post this
> evening, I have been playing around with "type()" and "isinstance()",
> but if I try something like:
> 
> py3: isinstance(int('5.0'))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: invalid literal for int() with base 10: '5.0'

The problem here is that int('5.0') raises an exception because '.' is 
not a valid digit for integers, so it fails before isinstance() gets a 
chance to run.

Valid digits for integers include 0 through 9 in decimal, plus no more 
than one leading + or - sign, and whitespace (space, tabs, newlines) 
before or after the string. If you specify the base, the set of valid 
digits will change, e.g. int(string, 16) will allow 0 through 9 plus A 
through F in lower and upper case.

But whatever base you choose, '.' is not a valid digit.



-- 
Steve

From eryksun at gmail.com  Sat Feb 11 03:36:56 2017
From: eryksun at gmail.com (eryk sun)
Date: Sat, 11 Feb 2017 08:36:56 +0000
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <20170211080607.GF4796@ando.pearwood.info>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <20170211080607.GF4796@ando.pearwood.info>
Message-ID: <CACL+1atuA1xn-DiH6=-YPFNazQfBaH_fPZ1JckOmgJqSjHwrDA@mail.gmail.com>

On Sat, Feb 11, 2017 at 8:06 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> Valid digits for integers include 0 through 9 in decimal

Note that Python 3 uses the Unicode database to determine the decimal
value of characters, if any. It's not limited to the ASCII decimal
digits 0-9. For example:

    >>> s
    '???'
    >>> int(s)
    123
    >>> print(*(unicodedata.name(c) for c in s), sep='\n')
    TAMIL DIGIT ONE
    VAI DIGIT TWO
    ORIYA DIGIT THREE

From steve at pearwood.info  Sat Feb 11 04:30:06 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Feb 2017 20:30:06 +1100
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
Message-ID: <20170211093005.GG4796@ando.pearwood.info>

On Fri, Feb 10, 2017 at 07:34:35PM -0600, boB Stepp wrote:
> I was playing around with type() tonight.  If I type (pun intended), I get:
> 
> py3: type(5)
> <class 'int'>
> 
> So I naively thought a test for type int should go like:
> 
> py3: type(5) == "<class 'int'>"
> False


The interactive intepreter is great, but you have to remember that what 
you see is not necessarily what you've got. What you *see* is the string 
representation of the object:

py> print
<built-in function print>

but what you've actually got is the object itself; in this case, it is 
the print function, and in your case, it is the int class.

Generally angle brackets < > mean that the text between the brackets is 
just a display form, something intended for the human reader, and not a 
programmable syntax. You then have to know (from experience) how to 
refer to the object in code.

In the case of int, there are three distinct things here:

- the class (or type) itself, a blob of memory somewhere in the 
interpreter containing various methods and attributes used for working 
with integers;

- the name the interpreter knows that class by, namely "int";

- the string representation for the human reader, "<class 'int'>".


So long as you remember the difference between the object itself, the 
name we use to talk about the object, and the way we visually display 
the object, you can't go wrong :-)

(The nation Russia is not the same as a map of Russia, which is not the 
same as the word Russia, which is not the same as the letters R u 
s s i a, or even ? ? ? ? ? ?? for that matter). 

As they say: the map is not the territory. Or in the words of Steven 
Wright, "I have a map of the United States... Actual size. It says, 
'Scale: 1 mile = 1 mile.' I spent last summer folding it."


> I finally stumbled onto the correct form:
> 
> py3: type(5) == int
> True

type(5) returns the class that we call "int". The name "int" returns 
that same class.


> So my question is why does "type(5)" result in "<class 'int'>",

No, that's just the string representation of int.

Inside the interactive interpreter, when you hit ENTER, the interpreter 
evaluates the line of code you have, generates a result, and then does 
the equivalent of:

print(repr(result))

(except that None is suppressed).


-- 
Steve

From steve at pearwood.info  Sat Feb 11 05:27:08 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Feb 2017 21:27:08 +1100
Subject: [Tutor] Test for type(object) == ???
In-Reply-To: <85bmu9o5as.fsf@benfinney.id.au>
References: <CANDiX9JmhnPS7rU--=pK7MqZx42O1XxZuAmmzn7wGm8Q+x+Ntg@mail.gmail.com>
 <85bmu9o5as.fsf@benfinney.id.au>
Message-ID: <20170211102707.GH4796@ando.pearwood.info>

On Sat, Feb 11, 2017 at 01:00:11PM +1100, Ben Finney wrote:
> boB Stepp <robertvstepp at gmail.com> writes:
> 
> > I was playing around with type() tonight.  If I type (pun intended), I get:
> >
> > py3: type(5)
> > <class 'int'>
> 
> Ceci n'est pas un ?int?.
[...]
> <URL:https://en.wikipedia.org/wiki/The_Treachery_of_Images>


For anyone interested in this concept and how it relates to programming, 
and many other mind-expanding concepts, I cannot recommend enough the 
famous book 

G?del, Escher, Bach: An Eternal Golden Braid

by Douglas Hofstadter. It is a mighty tome, but don't be put off by the 
size and weight. It covers some *extremely* subtle concepts, but it 
works up to them in baby steps, with the aid of dialogs between 
Archilles and the Tortoise.

-- 
Steve

From poojabhalode11 at gmail.com  Sat Feb 11 10:28:56 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sat, 11 Feb 2017 10:28:56 -0500
Subject: [Tutor] Accessing an entry value input by the user
Message-ID: <CAK0ikxdZtS5Hgpt2EB8yV4iEcwjEezDCtRoroj7uzk6xn_cOyg@mail.gmail.com>

Hi,

I am trying to create a label and an entry widget. I am not able to
understand as to how to access the value input by the user in the entry
widget.

Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
entrynumberspecies = Entry(frame1)
entrynumberspecies.grid(row=0, column = 2, sticky=W)

print entrynumberspecies.get()

How can I make the entrynumberspecies store the value in once the user
inputs it and then use that value for later part of my code? or print it
for that matter.

Thank you

Pooja

From akleider at sonic.net  Sat Feb 11 12:10:04 2017
From: akleider at sonic.net (Alex Kleider)
Date: Sat, 11 Feb 2017 09:10:04 -0800
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <CACL+1atuA1xn-DiH6=-YPFNazQfBaH_fPZ1JckOmgJqSjHwrDA@mail.gmail.com>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <20170211080607.GF4796@ando.pearwood.info>
 <CACL+1atuA1xn-DiH6=-YPFNazQfBaH_fPZ1JckOmgJqSjHwrDA@mail.gmail.com>
Message-ID: <d578456ad6c27090988530796692a850@sonic.net>

On 2017-02-11 00:36, eryk sun wrote:
> On Sat, Feb 11, 2017 at 8:06 AM, Steven D'Aprano <steve at pearwood.info> 
> wrote:
>> Valid digits for integers include 0 through 9 in decimal
> 
> Note that Python 3 uses the Unicode database to determine the decimal
> value of characters, if any. It's not limited to the ASCII decimal
> digits 0-9. For example:
> 
>     >>> s
>     '???'
>     >>> int(s)
>     123
>     >>> print(*(unicodedata.name(c) for c in s), sep='\n')
>     TAMIL DIGIT ONE
>     VAI DIGIT TWO
>     ORIYA DIGIT THREE

???
alex at X301n3:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> 

What your 's' represents seems quite different to 'mine.'
There must be something else going on.
???

Also of interest (at least to me) was the 'magic' you demonstrated in 
the print function parameter list; my efforts to figure it out:
>>> word = "Hello"
>>> print((c for c in word))
<generator object <genexpr> at 0xb71d125c>
>>> print(*(c for c in word))
H e l l o
>>> print(*(c for c in word), sep='')
Hello
>>> 

From alan.gauld at yahoo.co.uk  Sat Feb 11 12:52:30 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 11 Feb 2017 17:52:30 +0000
Subject: [Tutor] Accessing an entry value input by the user
In-Reply-To: <CAK0ikxdZtS5Hgpt2EB8yV4iEcwjEezDCtRoroj7uzk6xn_cOyg@mail.gmail.com>
References: <CAK0ikxdZtS5Hgpt2EB8yV4iEcwjEezDCtRoroj7uzk6xn_cOyg@mail.gmail.com>
Message-ID: <o7nj0o$n8$1@blaine.gmane.org>

On 11/02/17 15:28, Pooja Bhalode wrote:

> I am trying to create a label and an entry widget. I am not able to
> understand as to how to access the value input by the user in the entry
> widget.
> 
> Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
> entrynumberspecies = Entry(frame1)
> entrynumberspecies.grid(row=0, column = 2, sticky=W)
> 
> print entrynumberspecies.get()

You just accessed it, via the get() method. Did that not work?

> How can I make the entrynumberspecies store the value in once the user
> inputs it and then use that value for later part of my code? 

You can do it the way you did above using the get() method.

But you can also do what you did for the checkboxes - use
a StringVar and attach it to the Entry widget textvariable
attribute. That way the variable will reflect whats in
the Entry automatically and if you update the variable
it will update the Entry. (Personally I prefer to use
get() in most cases but many use the StringVar technique.)
See the example at the bottom...

> or print it for that matter.

You can print it as you did above or you can store it in
a variable and then print it or you can print the StringVar:

print myEntry.get()

myVar = MyEntry.get()
print myVar

entryVar = StringVar()
myEntry = Entry(.....textvariable=entryVar)
print entryVar.get()

Here is a minimal example:

################
from Tkinter import *

def show():
    print "entry says: " + e.get()
    print "Variable holds: " + v.get()

top = Tk()
v = StringVar()
e = Entry(top,textvariable=v)
e.pack()
Button(top,text="Set foobar", command=lambda : v.set("foobar")).pack()
Button(top,text="Show me", command=show).pack()

top.mainloop()
#################


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Sat Feb 11 15:28:42 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 11 Feb 2017 14:28:42 -0600
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
Message-ID: <CANDiX9Lv6N1A4Ze_+-WTXefRXiqqqFLP0_n6AJKQtRCGB3nmiw@mail.gmail.com>

On Fri, Feb 10, 2017 at 7:59 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> I have been following the thread "int vs. float"
> (https://mail.python.org/pipermail/python-list/2017-February/719287.html)
> on the main list.  A search for the OP on the Tutor archive came up
> negative, so I am hoping he is not following Tutor tonight (Or anytime
> prior to the due date for his homework!).  The central part of
> adam14711993's question is:
>
> "What I cannot figure out is how to write it so that if my user input
> is, for example, 1.5, the program will result with: Sorry, you can
> only order whole packages.
>
> "I understand that because I am starting out by assigning my
> number_purchases_str to be an int, when the user enters a float that
> is a conflict and will crash."
>
> He cannot figure out how to reliably tell if the user's input is an
> integer, float or neither.

Back in the main Python list thread, Marko Rauhamaa suggested
(https://mail.python.org/pipermail/python-list/2017-February/719322.html):

"
...
Haven't been following the discussion, but this should be simply:

   ast.literal_eval("...")
...
"

This looks like it may do the trick quite concisely:

py3: import ast
py3: ast.literal_eval('5')
5
py3: ast.literal_eval('5.0')
5.0
py3: type(ast.literal_eval('5'))
<class 'int'>
py3: type(ast.literal_eval('5.0'))
<class 'float'>

It appears to reliably parse string input as to whether it is an
integer or float.  However, if the input is a non-numerical string:

py3: ast.literal_eval('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python35\lib\ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "C:\Program Files\Python35\lib\ast.py", line 83, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x0000000002C9D860>

But that seems okay, as in the OP's original problem spec, he just
needed a way to determine integer, float or other non-acceptable
input.  This seems to do this quite directly.  I am not familiar with
"abstract syntax trees" (Python has so much very interesting stuff!).
I am concerned about this paragraph at the beginning of the docs on it
(https://docs.python.org/3/library/ast.html?highlight=ast.literal_eval#module-ast):

"The ast module helps Python applications to process trees of the
Python abstract syntax grammar. The abstract syntax itself might
change with each Python release; this module helps to find out
programmatically what the current grammar looks like."

That statement about potentially changing with each Python release
bothers me.  Should I be bothered?  The link to ast.literal_eval():
https://docs.python.org/3/library/ast.html?highlight=ast.literal_eval#ast.literal_eval

What are the gotchas or other negatives from this approach?

boB

From robertvstepp at gmail.com  Sat Feb 11 15:42:03 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 11 Feb 2017 14:42:03 -0600
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <d578456ad6c27090988530796692a850@sonic.net>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <20170211080607.GF4796@ando.pearwood.info>
 <CACL+1atuA1xn-DiH6=-YPFNazQfBaH_fPZ1JckOmgJqSjHwrDA@mail.gmail.com>
 <d578456ad6c27090988530796692a850@sonic.net>
Message-ID: <CANDiX9LeHFReyQD-8McB1P-ErkJm9J92k_Zp_GXeXvD817Nygg@mail.gmail.com>

On Sat, Feb 11, 2017 at 11:10 AM, Alex Kleider <akleider at sonic.net> wrote:

> Also of interest (at least to me) was the 'magic' you demonstrated in the
> print function parameter list; my efforts to figure it out:

Isn't this just argument unpacking?  Thus the necessary "*".

>>>> word = "Hello"
>>>> print((c for c in word))

Need print(*(c...)) to unpack the sequence arguments.

> <generator object <genexpr> at 0xb71d125c>
>>>>
>>>> print(*(c for c in word))
>
> H e l l o

Spaces because of the default setting for sep argument for print() as
you demonstrate next.

>>>> print(*(c for c in word), sep='')
>
> Hello


-- 
boB

From robertvstepp at gmail.com  Sat Feb 11 15:53:07 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 11 Feb 2017 14:53:07 -0600
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <d578456ad6c27090988530796692a850@sonic.net>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <20170211080607.GF4796@ando.pearwood.info>
 <CACL+1atuA1xn-DiH6=-YPFNazQfBaH_fPZ1JckOmgJqSjHwrDA@mail.gmail.com>
 <d578456ad6c27090988530796692a850@sonic.net>
Message-ID: <CANDiX9+HnsRGLQth3pYrtTVQ7FrqnkQAO8nvc7h0kn+eZCRy6Q@mail.gmail.com>

On Sat, Feb 11, 2017 at 11:10 AM, Alex Kleider <akleider at sonic.net> wrote:
> On 2017-02-11 00:36, eryk sun wrote:
>>

>> Note that Python 3 uses the Unicode database to determine the decimal
>> value of characters, if any. It's not limited to the ASCII decimal
>> digits 0-9. For example:
>>
>>     >>> s
>>     '???'
>>     >>> int(s)
>>     123
>>     >>> print(*(unicodedata.name(c) for c in s), sep='\n')
>>     TAMIL DIGIT ONE
>>     VAI DIGIT TWO
>>     ORIYA DIGIT THREE
>
>
> ???
> alex at X301n3:~$ python3
> Python 3.4.3 (default, Nov 17 2016, 01:11:57)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>>
>>>> s
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 's' is not defined


> What your 's' represents seems quite different to 'mine.'
> There must be something else going on.

I suspect Eryk had set a normal 's' as an identifier for the character
code sequence that produces the non-ASCII output, but forgot to show
us that step.  But I could be mistaken.

Today I am working in Windows 7, not Linux Mint.  Of course when I
attempted to copy and paste the non-ASCII sequence from Gmail into
cmd.exe I got 3 rectangular boxes on the paste line, indicating
cmd.exe could not translate those characters.  However, if I paste
them into IDLE or gvim, things are translated correctly:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900
64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    s
NameError: name 's' is not defined
>>> '???'
'???'
>>>

I think that this demonstrates that 's' is just an identifier pointing
to the non-ASCII character sequence, but that the actual characters
can be copied and pasted *if* the editor or environment you paste
those characters into is setup to translate those characters.

boB

From robertvstepp at gmail.com  Sat Feb 11 16:28:19 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 11 Feb 2017 15:28:19 -0600
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <20170211080607.GF4796@ando.pearwood.info>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <20170211080607.GF4796@ando.pearwood.info>
Message-ID: <CANDiX9KqUSinf6u6VeFwU57Bf=O22AxZ_cgAUgifyRV+4ZT97Q@mail.gmail.com>

On Sat, Feb 11, 2017 at 2:06 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, Feb 10, 2017 at 07:59:04PM -0600, boB Stepp wrote:
>
>> He cannot figure out how to reliably tell if the user's input is an
>> integer, float or neither.  So I thought I would come up with my
>> solution, which currently is:
>>
>> py3: def ck_input():
>> ...     value_to_ck = input('Enter a number:')
>> ...     try:
>> ...             value = int(value_to_ck)
>> ...             print('You have entered an integer.')
>> ...     except ValueError:
>> ...             try:
>> ...                     value = float(value_to_ck)
>> ...                     print('You have entered a float.')
>> ...             except ValueError:
>> ...                     print('You have failed to enter a numerical value.')
>> ...

> The only not-so-good part of this is that you have mixed user-interface
> and internal calculation. Better:
>
>
> def to_number(string):
>     """Convert string to either an int or a float, or raise ValueError."""
>     try:
>         return int(string)
>     except ValueError:
>         return float(string)
>
>
> def check_input():
>     value_to_ck = input('Enter a number: ')
>     try:
>         value = to_number(value_to_ck)
>     except ValueError:
>         print('You have failed to enter a numerical value.')
>         return
>     if isinstance(value, float):
>         print('You have entered a float.')
>     else:
>         print('You have entered an int.')
>
>
> This gives you nice separation between the function that interacts with
> the user, and the function that does the actual conversion.

Ah!  I am glad I asked the questions.  There is a difference between
intellectually understanding what I should do and reliably
implementing it in my regular coding practice.  This is one such
instance, probably of many unfortunately.  I knew something was
bothering me about this.  I did not like nesting try...except
two-deep.  Now that you have shown the way, I see what was nagging at
me.  Thanks, Steve!

boB

From poojabhalode11 at gmail.com  Sat Feb 11 13:59:08 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sat, 11 Feb 2017 13:59:08 -0500
Subject: [Tutor] Accessing an entry value input by the user
In-Reply-To: <o7nj0o$n8$1@blaine.gmane.org>
References: <CAK0ikxdZtS5Hgpt2EB8yV4iEcwjEezDCtRoroj7uzk6xn_cOyg@mail.gmail.com>
 <o7nj0o$n8$1@blaine.gmane.org>
Message-ID: <CAK0ikxd7XgeOWE0uJow8AEuSO2Z57uWuNKuz5_1o9nzvPbf3JA@mail.gmail.com>

Hi Alan,

I had done what you suggested here, I also tried creating another file for
that snipet of the code to see if that section works. The other file works,
but I am not able to figure out why the original one doesn't work.
The variable here is entrynumberspeciesvar

Code:
from Tkinter import *
import datetime
import tkMessageBox
from tkFileDialog import *
from tkMessageBox import *
root = Tk()
root.title("Design of Experiments with Parameter Estimation")
root.geometry("1000x1000")

statusvar = StringVar()
statusvar = "Status Bar"

var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
var4 = IntVar()

varreac = IntVar()
varint = IntVar()
varpro = IntVar()

varconc = IntVar()
vartemp = IntVar()
entrynumberspeciesvar = IntVar()

def DesignPoint():
    print "Inside Design Point"
    rootdesign=Tk()
    rootdesign.title("Design Point Suggestions")
    rootdesign.geometry("700x400")
    frame1 = Frame(rootdesign)
    frame1.grid(row=0, column=0)

    label1 = Label(frame1, text="1. Responses to include: ")
    label1.grid(row=0, column=0,sticky=W)


    Label(frame1, text = "Number of species:").grid(row=0, column = 1,
sticky=W)
    entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
    entrynumberspecies.grid(row=0, column = 2, sticky=W)

    # print entrynumberspeciesvar.get()
    checkreac = Checkbutton(frame1, text = "Reactant species", variable =
varreac)
    checkreac.grid(row = 1, column = 1, sticky = W)
    checkreac.select()
    Checkbutton(frame1, text = "Intermediate species", variable =
varint).grid(row = 2, column = 1, sticky = W)
    Checkbutton(frame1, text = "Product species", variable =
varpro).grid(row = 3, column = 1, sticky = W)

    def Default():
        print "Inside default"

        var1.set(0)
        var2.set(0)
        var3.set(0)
        var4.set(1)
    Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
offvalue=0).grid(row=1, column = 2, sticky=W)
    Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column =
2, sticky=W)
    Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column =
2, sticky=W)
    check = Checkbutton(frame1, text = "Center", variable=var4)

    check.grid(row=4, column = 2, sticky=W)
    check.select()

    Label(frame1, text="2. Variables to be adjusted:").grid(row=5,
column=0,sticky=W)
    Checkbutton(frame1, text = "Concentration", variable=varconc,
onvalue=1, offvalue=0).grid(row=5, column = 1, sticky=W)
    Checkbutton(frame1, text = "Temperature", variable=vartemp).grid(row=6,
column = 1, sticky=W)

    def InsertRange():
        print "Inside InsertRange"
        # entrynumberspeciesvar.set(2)
        print entrynumberspeciesvar.get()
        for i in range(entrynumberspeciesvar.get()):
            textvar = StringVar()
            print i
            textvar = "\t Conc"+str(i)
            Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
            conclowerentry = Entry(frame1)
            conclowerentry.grid(row= (9+i), column = 1, sticky = W)
            concupperentry = Entry(frame1)
            concupperentry.grid(row= (9+i), column = 2, sticky = W)


    Label(frame1, text="3. Range of formulation:").grid(row=7,
column=0,sticky=W)
    Button(frame1, text = "Insert Range", command = InsertRange()).grid(row
= 7, column = 3, sticky=W)
    Label(frame1, text="Lower Limit").grid(row=7, column=1,sticky=W)
    Label(frame1, text="Upper Limit").grid(row=7, column=2,sticky=W)

    Label(frame1, text="\t Temperature").grid(row=8, column=0,sticky=W)
    templowerentry = Entry(frame1, text="0.0")
    templowerentry.grid(row= 8, column = 1, sticky = W)
    tempupperentry = Entry(frame1)
    tempupperentry.grid(row= 8, column = 2, sticky = W)

    rootdesign.mainloop()


## Secondary menu bar:
menusec = Frame(root, bg="white")
butt1 = Button(menusec, text="Part One", command=DesignPoint)
butt1.pack(side=LEFT, padx=1)
menusec.pack(side=TOP, fill=X)


### --- Status bar ---- ####
Status = Label(root, text = statusvar, bd=1, relief=SUNKEN, anchor=W)
Status.pack(side=BOTTOM, fill=X)

text = Text(root, width=1000, height = 400)
text.pack(side=BOTTOM)


root.mainloop()

I have removed other parts of the code and included only the ones related
to the entry box and the work that I need to do.
I also tried doing it in another file as mentioned before. That works the
exact way I want.

Code:
from Tkinter import *

rootdesign=Tk()
rootdesign.title("Design Point Suggestions")
rootdesign.geometry("650x400")
frame1 = Frame(rootdesign)
frame1.grid(row=0, column=0)
entrynumberspeciesvar = IntVar()
## Inserting Checkboxes:
label1 = Label(frame1, text="1. Responses to include: ")
label1.grid(row=0, column=0,sticky=W )
Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
entrynumberspecies.grid(row=0, column = 2, sticky=W)

def Print():
    print entrynumberspeciesvar.get()
    for i in range(entrynumberspeciesvar.get()):
        print i
        textvar = "\t Conc"+str(i+1)
        Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
        conclowerentry = Entry(frame1)
        conclowerentry.grid(row= (9+i), column = 1, sticky = W)
        concupperentry = Entry(frame1)
        concupperentry.grid(row= (9+i), column = 2, sticky = W)

Button(frame1, text = "Click", command = Print).grid(row = 2, column = 2,
sticky = W)
Label(frame1, text="\t Temperature").grid(row=8, column=0,sticky=W)
templowerentry = Entry(frame1, text="0.0")
templowerentry.grid(row= 8, column = 1, sticky = W)
tempupperentry = Entry(frame1)
tempupperentry.grid(row= 8, column = 2, sticky = W)
rootdesign.mainloop()


Please let me know where I am going wrong. Thank you so much.
Pooja

On Sat, Feb 11, 2017 at 12:52 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 11/02/17 15:28, Pooja Bhalode wrote:
>
> > I am trying to create a label and an entry widget. I am not able to
> > understand as to how to access the value input by the user in the entry
> > widget.
> >
> > Label(frame1, text = "Number of species:").grid(row=0, column = 1,
> sticky=W)
> > entrynumberspecies = Entry(frame1)
> > entrynumberspecies.grid(row=0, column = 2, sticky=W)
> >
> > print entrynumberspecies.get()
>
> You just accessed it, via the get() method. Did that not work?
>
> > How can I make the entrynumberspecies store the value in once the user
> > inputs it and then use that value for later part of my code?
>
> You can do it the way you did above using the get() method.
>
> But you can also do what you did for the checkboxes - use
> a StringVar and attach it to the Entry widget textvariable
> attribute. That way the variable will reflect whats in
> the Entry automatically and if you update the variable
> it will update the Entry. (Personally I prefer to use
> get() in most cases but many use the StringVar technique.)
> See the example at the bottom...
>
> > or print it for that matter.
>
> You can print it as you did above or you can store it in
> a variable and then print it or you can print the StringVar:
>
> print myEntry.get()
>
> myVar = MyEntry.get()
> print myVar
>
> entryVar = StringVar()
> myEntry = Entry(.....textvariable=entryVar)
> print entryVar.get()
>
> Here is a minimal example:
>
> ################
> from Tkinter import *
>
> def show():
>     print "entry says: " + e.get()
>     print "Variable holds: " + v.get()
>
> top = Tk()
> v = StringVar()
> e = Entry(top,textvariable=v)
> e.pack()
> Button(top,text="Set foobar", command=lambda : v.set("foobar")).pack()
> Button(top,text="Show me", command=show).pack()
>
> top.mainloop()
> #################
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From sylwester.graczyk at gmail.com  Sat Feb 11 15:30:53 2017
From: sylwester.graczyk at gmail.com (Sylwester Graczyk)
Date: Sat, 11 Feb 2017 21:30:53 +0100
Subject: [Tutor] Find (list) strings in large textfile
In-Reply-To: <o7j4nc$a54$1@blaine.gmane.org>
References: <13907542-012b-36cc-7c02-157f708a50c7@gmail.com>
 <o7j4nc$a54$1@blaine.gmane.org>
Message-ID: <296d8950-433a-6ffc-ac41-310eace280a3@gmail.com>

>
> It is probably better to store your key file in memory
> then loop over the large data file and check the
> line against each key. Better to check 2000 data
> keys in memory for one loop of the data file.
> That way you only read the key file and data file
> once each - 502,000 reads instead of a billion.
>
I replace one loop (in file), with searching in a *list*, and it's much 
faster :)

    my_list = open("list_file.txt")
    file_list = [i[:-1] for i in my_list.readlines()]

    file_large = open("large_file.txt")
    save_file = open("output.txt", "w")

    for row in file_large:
         split_row = row.split()
    if split_row[0] in file_list:
             save_file.write(row)

    file_large.close()
    file_list.close()


thx for all

From dyoo at hashcollision.org  Sat Feb 11 19:59:52 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sat, 11 Feb 2017 16:59:52 -0800
Subject: [Tutor] Find (list) strings in large textfile
In-Reply-To: <296d8950-433a-6ffc-ac41-310eace280a3@gmail.com>
References: <13907542-012b-36cc-7c02-157f708a50c7@gmail.com>
 <o7j4nc$a54$1@blaine.gmane.org>
 <296d8950-433a-6ffc-ac41-310eace280a3@gmail.com>
Message-ID: <CAGZAPF4o_tAG2jBPRybZ09+hW8tyLrLd+Joa6vAEnnkLTxc6wQ@mail.gmail.com>

Believe it or not, a change in two characters should make this even faster.  :)

Change the line:

    file_list = [i[:-1] for i in my_list.readlines()]

to:

    file_list = {i[:-1] for i in my_list.readlines()}


The change is to use a "set comprehension" instead of a "list
comprehension".  Sets allow membership checks in expected *constant*
time instead of *linear* time.  Try that, and compare the speed: you
should get a fairly good speedup.


See:

    https://docs.python.org/3/tutorial/datastructures.html#sets

for some more details.

From alan.gauld at yahoo.co.uk  Sat Feb 11 20:03:39 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 12 Feb 2017 01:03:39 +0000
Subject: [Tutor] Accessing an entry value input by the user
In-Reply-To: <CAK0ikxd7XgeOWE0uJow8AEuSO2Z57uWuNKuz5_1o9nzvPbf3JA@mail.gmail.com>
References: <CAK0ikxdZtS5Hgpt2EB8yV4iEcwjEezDCtRoroj7uzk6xn_cOyg@mail.gmail.com>
 <o7nj0o$n8$1@blaine.gmane.org>
 <CAK0ikxd7XgeOWE0uJow8AEuSO2Z57uWuNKuz5_1o9nzvPbf3JA@mail.gmail.com>
Message-ID: <o7oc95$mcv$1@blaine.gmane.org>

On 11/02/17 18:59, Pooja Bhalode wrote:
> Hi Alan,
> 
> I had done what you suggested here, I also tried creating another file for
> that snipet of the code to see if that section works. The other file works,
> but I am not able to figure out why the original one doesn't work.

Too late at night for a detailed analysis but your code
should be restructured its ghetting very messy and hard
to see whats going on. More on that another time.
Meanwhile some immediate thoughts...

> from Tkinter import *
> import datetime
> import tkMessageBox
> from tkFileDialog import *
> from tkMessageBox import *

If you do this there's no point in importing tkmessagebox earlier.

> root = Tk()
> root.title("Design of Experiments with Parameter Estimation")
> root.geometry("1000x1000")
> 
> statusvar = StringVar()
> statusvar = "Status Bar"

You create the stringvar but then throw it waay by overwriting it with a
string.

Maybe you meant to do:

statusvar = StringVar()
statusvar.set("Status Bar")

???


> var1 = IntVar()
> var2 = IntVar()
> var3 = IntVar()
> var4 = IntVar()
> 
> varreac = IntVar()
> varint = IntVar()
> varpro = IntVar()
> 
> varconc = IntVar()
> vartemp = IntVar()
> entrynumberspeciesvar = IntVar()

You can only use a stringvar with an Entry because
the Entry only holds text, not integers. You will
need to do the conversions yourself when you set/get
the values.

> def DesignPoint():
>     print "Inside Design Point"
>     rootdesign=Tk()

You are still creating multiple roots, that is
really bad practice and almost sure to create
problems later. Define the function as:

def DesignPoint(root):...

and call it as

DesignPoint(root)

>     rootdesign.title("Design Point Suggestions")
>     rootdesign.geometry("700x400")
>     frame1 = Frame(rootdesign)
>     frame1.grid(row=0, column=0)
> 

If you want a second window you should be
using a Toplevel widget not Frame here.


>     label1 = Label(frame1, text="1. Responses to include: ")
>     label1.grid(row=0, column=0,sticky=W)
> 
> 
>     Label(frame1, text = "Number of species:").grid(row=0, column = 1,
> sticky=W)
>     entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
>     entrynumberspecies.grid(row=0, column = 2, sticky=W)
> 
>     # print entrynumberspeciesvar.get()
>     checkreac = Checkbutton(frame1, text = "Reactant species", variable =
> varreac)
>     checkreac.grid(row = 1, column = 1, sticky = W)
>     checkreac.select()
>     Checkbutton(frame1, text = "Intermediate species", variable =
> varint).grid(row = 2, column = 1, sticky = W)
>     Checkbutton(frame1, text = "Product species", variable =
> varpro).grid(row = 3, column = 1, sticky = W)
> 
>     def Default():
>         print "Inside default"
> 
>         var1.set(0)
>         var2.set(0)
>         var3.set(0)
>         var4.set(1)

This function really should be defined outside
the DesignPoint one. It will be much easier to maintain
if you separate them out.

>     Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
> offvalue=0).grid(row=1, column = 2, sticky=W)
>     Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column =
> 2, sticky=W)
>     Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column =
> 2, sticky=W)
>     check = Checkbutton(frame1, text = "Center", variable=var4)
> 
>     check.grid(row=4, column = 2, sticky=W)
>     check.select()
> 
>     Label(frame1, text="2. Variables to be adjusted:").grid(row=5,
> column=0,sticky=W)
>     Checkbutton(frame1, text = "Concentration", variable=varconc,
> onvalue=1, offvalue=0).grid(row=5, column = 1, sticky=W)
>     Checkbutton(frame1, text = "Temperature", variable=vartemp).grid(row=6,
> column = 1, sticky=W)
> 
>     def InsertRange():
>         print "Inside InsertRange"
>         # entrynumberspeciesvar.set(2)
>         print entrynumberspeciesvar.get()
>         for i in range(entrynumberspeciesvar.get()):
>             textvar = StringVar()
>             print i
>             textvar = "\t Conc"+str(i)

Again you have deleted your StringVar object by overwriting it.
You need to set the value with the set() method. OTOH you
never use the StringVar so maybe you just need to delete
that line.

>             Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
>             conclowerentry = Entry(frame1)
>             conclowerentry.grid(row= (9+i), column = 1, sticky = W)
>             concupperentry = Entry(frame1)
>             concupperentry.grid(row= (9+i), column = 2, sticky = W)
> 

Same goes here. You should have very good reasons to define event
handlers inside the functions that build your UIs. It usually just makes
the code more complex with no benefit.

>     Label(frame1, text="3. Range of formulation:").grid(row=7,
> column=0,sticky=W)
>     Button(frame1, text = "Insert Range", command = InsertRange()).grid(row
> = 7, column = 3, sticky=W)
>     Label(frame1, text="Lower Limit").grid(row=7, column=1,sticky=W)
>     Label(frame1, text="Upper Limit").grid(row=7, column=2,sticky=W)
> 
>     Label(frame1, text="\t Temperature").grid(row=8, column=0,sticky=W)
>     templowerentry = Entry(frame1, text="0.0")
>     templowerentry.grid(row= 8, column = 1, sticky = W)
>     tempupperentry = Entry(frame1)
>     tempupperentry.grid(row= 8, column = 2, sticky = W)
> 
>     rootdesign.mainloop()
> 
> 
> ## Secondary menu bar:
> menusec = Frame(root, bg="white")
> butt1 = Button(menusec, text="Part One", command=DesignPoint)
> butt1.pack(side=LEFT, padx=1)
> menusec.pack(side=TOP, fill=X)
> 
> 
> ### --- Status bar ---- ####
> Status = Label(root, text = statusvar, bd=1, relief=SUNKEN, anchor=W)
> Status.pack(side=BOTTOM, fill=X)
> 
> text = Text(root, width=1000, height = 400)
> text.pack(side=BOTTOM)
> 
> 
> root.mainloop()
> 
> I have removed other parts of the code and included only the ones related
> to the entry box and the work that I need to do.
> I also tried doing it in another file as mentioned before. That works the
> exact way I want.
> 
> Code:
> from Tkinter import *
> 
> rootdesign=Tk()
> rootdesign.title("Design Point Suggestions")
> rootdesign.geometry("650x400")
> frame1 = Frame(rootdesign)
> frame1.grid(row=0, column=0)
> entrynumberspeciesvar = IntVar()
> ## Inserting Checkboxes:
> label1 = Label(frame1, text="1. Responses to include: ")
> label1.grid(row=0, column=0,sticky=W )
> Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
> entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
> entrynumberspecies.grid(row=0, column = 2, sticky=W)
> 
> def Print():
>     print entrynumberspeciesvar.get()
>     for i in range(entrynumberspeciesvar.get()):
>         print i
>         textvar = "\t Conc"+str(i+1)
>         Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
>         conclowerentry = Entry(frame1)
>         conclowerentry.grid(row= (9+i), column = 1, sticky = W)
>         concupperentry = Entry(frame1)
>         concupperentry.grid(row= (9+i), column = 2, sticky = W)
> 
> Button(frame1, text = "Click", command = Print).grid(row = 2, column = 2,
> sticky = W)
> Label(frame1, text="\t Temperature").grid(row=8, column=0,sticky=W)
> templowerentry = Entry(frame1, text="0.0")
> templowerentry.grid(row= 8, column = 1, sticky = W)
> tempupperentry = Entry(frame1)
> tempupperentry.grid(row= 8, column = 2, sticky = W)
> rootdesign.mainloop()
> 
> 
> Please let me know where I am going wrong. Thank you so much.
> Pooja
> 
> On Sat, Feb 11, 2017 at 12:52 PM, Alan Gauld via Tutor <tutor at python.org>
> wrote:
> 
>> On 11/02/17 15:28, Pooja Bhalode wrote:
>>
>>> I am trying to create a label and an entry widget. I am not able to
>>> understand as to how to access the value input by the user in the entry
>>> widget.
>>>
>>> Label(frame1, text = "Number of species:").grid(row=0, column = 1,
>> sticky=W)
>>> entrynumberspecies = Entry(frame1)
>>> entrynumberspecies.grid(row=0, column = 2, sticky=W)
>>>
>>> print entrynumberspecies.get()
>>
>> You just accessed it, via the get() method. Did that not work?
>>
>>> How can I make the entrynumberspecies store the value in once the user
>>> inputs it and then use that value for later part of my code?
>>
>> You can do it the way you did above using the get() method.
>>
>> But you can also do what you did for the checkboxes - use
>> a StringVar and attach it to the Entry widget textvariable
>> attribute. That way the variable will reflect whats in
>> the Entry automatically and if you update the variable
>> it will update the Entry. (Personally I prefer to use
>> get() in most cases but many use the StringVar technique.)
>> See the example at the bottom...
>>
>>> or print it for that matter.
>>
>> You can print it as you did above or you can store it in
>> a variable and then print it or you can print the StringVar:
>>
>> print myEntry.get()
>>
>> myVar = MyEntry.get()
>> print myVar
>>
>> entryVar = StringVar()
>> myEntry = Entry(.....textvariable=entryVar)
>> print entryVar.get()
>>
>> Here is a minimal example:
>>
>> ################
>> from Tkinter import *
>>
>> def show():
>>     print "entry says: " + e.get()
>>     print "Variable holds: " + v.get()
>>
>> top = Tk()
>> v = StringVar()
>> e = Entry(top,textvariable=v)
>> e.pack()
>> Button(top,text="Set foobar", command=lambda : v.set("foobar")).pack()
>> Button(top,text="Show me", command=show).pack()
>>
>> top.mainloop()
>> #################
>>
>>
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>> http://www.amazon.com/author/alan_gauld
>> Follow my photo-blog on Flickr at:
>> http://www.flickr.com/photos/alangauldphotos
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Sat Feb 11 20:08:15 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Feb 2017 12:08:15 +1100
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <CANDiX9Lv6N1A4Ze_+-WTXefRXiqqqFLP0_n6AJKQtRCGB3nmiw@mail.gmail.com>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <CANDiX9Lv6N1A4Ze_+-WTXefRXiqqqFLP0_n6AJKQtRCGB3nmiw@mail.gmail.com>
Message-ID: <20170212010814.GI4796@ando.pearwood.info>

On Sat, Feb 11, 2017 at 02:28:42PM -0600, boB Stepp wrote:

> Back in the main Python list thread, Marko Rauhamaa suggested
> (https://mail.python.org/pipermail/python-list/2017-February/719322.html):
> 
> "
> ...
> Haven't been following the discussion, but this should be simply:
> 
>    ast.literal_eval("...")
> ...
> "
> 
> This looks like it may do the trick quite concisely:

Nope. Not even close. The problem is that you have to accept ints and 
floats, but reject anything else, and literal_eval does not do that.

py> import ast
py> ast.literal_eval('[1, {}, None, "s", 2.4j, ()]')
[1, {}, None, 's', 2.4j, ()]


literal_eval will parse and evaluate anything that looks like one of:

- int
- float
- string
- bool (True or False)
- None
- complex (e.g. -3.5+4.5j)
- tuple
- list
- dict
- set


so it does *far* more than what the OP requires.

[...]
> That statement about potentially changing with each Python release
> bothers me.  Should I be bothered?

No. In this case, you are parsing a string, and the ast module itself 
parses it to an Abstract Syntax Tree before evaluating literals, so it 
doesn't matter if the AST is different from one version to the next.

You should only care if you generated an AST in (say) Python 3.5, saved 
it in a data file, then read it back in to Python 3.6 and tried to 
evaluate it. That may not succeed.



-- 
Steve

From steve at pearwood.info  Sat Feb 11 20:30:25 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Feb 2017 12:30:25 +1100
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <d578456ad6c27090988530796692a850@sonic.net>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <20170211080607.GF4796@ando.pearwood.info>
 <CACL+1atuA1xn-DiH6=-YPFNazQfBaH_fPZ1JckOmgJqSjHwrDA@mail.gmail.com>
 <d578456ad6c27090988530796692a850@sonic.net>
Message-ID: <20170212013024.GJ4796@ando.pearwood.info>

On Sat, Feb 11, 2017 at 09:10:04AM -0800, Alex Kleider wrote:

> What your 's' represents seems quite different to 'mine.'
> There must be something else going on.
> ???

I think there's an easy explanation for that, which is that eryksun 
probably just created a variable "s" but didn't show the code for that.

Unfortunately copying and pasting Unicode characters from email to the 
Python interpreter may not always work, as that depends on how well at 
least four software components deal with Unicode:

- the email program
- the copy/paste clipboard manager
- the console/terminal
- the Python interpreter

The second last one is particularly problematic under Windows.


When clarity is more important than brevity, the best way to insert 
Unicode characters into a string is to use the '\N{name}' form:

s = '\N{TAMIL DIGIT ONE}\N{VAI DIGIT TWO}\N{ORIYA DIGIT THREE}'

Since that's pure ASCII, you can copy and paste it easily even in the 
most poorly-configured system.


> Also of interest (at least to me) was the 'magic' you demonstrated in 
> the print function parameter list; my efforts to figure it out:
> >>>word = "Hello"
> >>>print((c for c in word))
> <generator object <genexpr> at 0xb71d125c>
> >>>print(*(c for c in word))
> H e l l o
> >>>print(*(c for c in word), sep='')
> Hello

Indeed: the leading * is just the systax for argument unpacking. If you 
have a sequence:

seq = [1, 2, 3, 4]

and unpack it:

print(*seq)

then what the print function sees is:

print(1, 2, 3, 4)


It works with any iterable, not just lists or tuples: also strings, 
generator expressions, and more.



-- 
Steve

From robertvstepp at gmail.com  Sat Feb 11 23:08:37 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 11 Feb 2017 22:08:37 -0600
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <20170212010814.GI4796@ando.pearwood.info>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <CANDiX9Lv6N1A4Ze_+-WTXefRXiqqqFLP0_n6AJKQtRCGB3nmiw@mail.gmail.com>
 <20170212010814.GI4796@ando.pearwood.info>
Message-ID: <CANDiX9+yNnMRpDq-EMJQX12Yr6dOZhrB_3c1UgmGq9fb65c3kw@mail.gmail.com>

On Sat, Feb 11, 2017 at 7:08 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Feb 11, 2017 at 02:28:42PM -0600, boB Stepp wrote:
>
>> Back in the main Python list thread, Marko Rauhamaa suggested
>> (https://mail.python.org/pipermail/python-list/2017-February/719322.html):
>>
>> "
>> ...
>> Haven't been following the discussion, but this should be simply:
>>
>>    ast.literal_eval("...")
>> ...
>> "
>>
>> This looks like it may do the trick quite concisely:
>
> Nope. Not even close. The problem is that you have to accept ints and
> floats, but reject anything else, and literal_eval does not do that.
>
> py> import ast
> py> ast.literal_eval('[1, {}, None, "s", 2.4j, ()]')
> [1, {}, None, 's', 2.4j, ()]

My intent was to follow up with
type(ast.literal_eval(string_input_from_user)) and if that does not
come out 'int' or 'float', then it can be rejected as invalid input
from the user.  In your example type() would return a list, which
would be invalid input for the OP's case.  Of course this seems like
swatting a gnat with a sledge hammer, but it still seems that the
combination of checking the return of
type(ast.literal_eval(user_input)) does the job since everything that
is not float or int can be rejected as invalid input, and the float
case can get its special error message.

Or am I missing something?

boB

From natanieldumont47 at gmail.com  Sun Feb 12 14:10:44 2017
From: natanieldumont47 at gmail.com (ViRuZ Fx .)
Date: Sun, 12 Feb 2017 14:10:44 -0500
Subject: [Tutor] ISSUE WITH PYTHON 3,5 API RUNTIME
Message-ID: <CAFBQ_nsAM13=hcy=DR9sMrFm2sH1pBuFwL=qvT7nX72ztPmJ_Q@mail.gmail.com>

Hello fellow programmers of Python, Im here writing you this because, since
I got a virus and my computer reseted to 0, I cant run anything, when I
start running a program , it pops this error :
api-ms-win-crt-runtime-l1-1-0.dll
I seriously need help , so yep, thanks for responding me the fast as
possible, I hope you can help me .. Have a great afternoon. :)

From alan.gauld at yahoo.co.uk  Sun Feb 12 14:40:18 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 12 Feb 2017 19:40:18 +0000
Subject: [Tutor] ISSUE WITH PYTHON 3,5 API RUNTIME
In-Reply-To: <CAFBQ_nsAM13=hcy=DR9sMrFm2sH1pBuFwL=qvT7nX72ztPmJ_Q@mail.gmail.com>
References: <CAFBQ_nsAM13=hcy=DR9sMrFm2sH1pBuFwL=qvT7nX72ztPmJ_Q@mail.gmail.com>
Message-ID: <o7qdmt$um0$1@blaine.gmane.org>

On 12/02/17 19:10, ViRuZ Fx . wrote:
> Hello fellow programmers of Python, Im here writing you this because, since
> I got a virus and my computer reseted to 0, 

I have no idea what reset to 0 means.
Did you reinsatall Windows and all your applications?
Did you use the Windows repair tool?

> I cant run anything, 

You mean anything at all? Not even Windows Exploirer or Notepad?
If dso its a Windows fault and nothing to do with python.

Or do you mean you can't run Python?
If so which commands have you tried? IDLE?
The command line interpreter?

> start running a program , it pops this error :

> api-ms-win-crt-runtime-l1-1-0.dll

That's not really an error but a filename. Is there any
explanatory text, such as "can't find file" or "not a command"
or somesuch?

[BTW Have you tried googling the error/filename?
You might find its a common fault with an easy fix...]

> I seriously need help

Indeed, but we can't tell at this point whether its
help with Windows or help with Python on windows.
We need more details.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From poojabhalode11 at gmail.com  Sun Feb 12 15:01:05 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sun, 12 Feb 2017 15:01:05 -0500
Subject: [Tutor] Accessing an entry value input by the user
In-Reply-To: <o7oc95$mcv$1@blaine.gmane.org>
References: <CAK0ikxdZtS5Hgpt2EB8yV4iEcwjEezDCtRoroj7uzk6xn_cOyg@mail.gmail.com>
 <o7nj0o$n8$1@blaine.gmane.org>
 <CAK0ikxd7XgeOWE0uJow8AEuSO2Z57uWuNKuz5_1o9nzvPbf3JA@mail.gmail.com>
 <o7oc95$mcv$1@blaine.gmane.org>
Message-ID: <CAK0ikxehmJu8+meb_A6PHL=Mmh4fH7TrZJPzhF1JzQk-uUq9ZA@mail.gmail.com>

Hi Alan,

Thank you so much for providing me your input on these things. I made all
the corrections to the code as per you suggested.

Thank you so much. I got stuck in another section:

Code:

from Tkinter import *


root=Tk()
root.title("Design Point Suggestions")
root.geometry("650x400")
frame1 = Frame(root)
frame1.grid(row=0, column=0)
entrynumberspeciesvar = IntVar()
Label(frame1, text="1. Responses to include: ").grid(row=0,
column=0,sticky=W )
Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
entrynumberspecies.grid(row=0, column = 2, sticky=W)

conclowerentry = []
concupperentry = []

def Print():
    print entrynumberspeciesvar.get()
    for i in range(entrynumberspeciesvar.get()):
        conclowertemp = StringVar()
        concuppertemp = StringVar()

        textvar = "\t Conc"+str(i+1)
        Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
        Entry(frame1, textvariable = conclowertemp).grid(row= (9+i), column
= 1, sticky = W)
        Entry(frame1, textvariable = concuppertemp).grid(row= (9+i), column
= 2, sticky = W)

        if len(concuppertemp.get()) != 0 and len(conclowertemp.get()) != 0:
            concupperentry.append(int(concuppertemp.get()))
            conclowerentry.append(int(conclowertemp.get()))

        def Submit():
            print "Submitted. "
            print conclowerentry.get()
            print concupperentry.get()

        Button(frame1, text="Submit", command = Submit).grid(row = 2,
column = 1, sticky = W)

Button(frame1, text = "Click", command = Print).grid(row = 2, column = 2,
sticky = W)
root.mainloop()

print conclowerentry
print concupperentry

This creates a window as given below:
[image: Inline image 1]
where the user inputs the number and the corresponding number of entry
boxes and labels get created.
Submit button is used for storing in the values in a list and then
printing.

But here, I am not able to store the value associated with each entry boxes
in the created list.
Can you please let me know where I am going wrong?
Thank you Alan.

Pooja

On Sat, Feb 11, 2017 at 8:03 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 11/02/17 18:59, Pooja Bhalode wrote:
> > Hi Alan,
> >
> > I had done what you suggested here, I also tried creating another file
> for
> > that snipet of the code to see if that section works. The other file
> works,
> > but I am not able to figure out why the original one doesn't work.
>
> Too late at night for a detailed analysis but your code
> should be restructured its ghetting very messy and hard
> to see whats going on. More on that another time.
> Meanwhile some immediate thoughts...
>
> > from Tkinter import *
> > import datetime
> > import tkMessageBox
> > from tkFileDialog import *
> > from tkMessageBox import *
>
> If you do this there's no point in importing tkmessagebox earlier.
>
> > root = Tk()
> > root.title("Design of Experiments with Parameter Estimation")
> > root.geometry("1000x1000")
> >
> > statusvar = StringVar()
> > statusvar = "Status Bar"
>
> You create the stringvar but then throw it waay by overwriting it with a
> string.
>
> Maybe you meant to do:
>
> statusvar = StringVar()
> statusvar.set("Status Bar")
>
> ???
>
>
> > var1 = IntVar()
> > var2 = IntVar()
> > var3 = IntVar()
> > var4 = IntVar()
> >
> > varreac = IntVar()
> > varint = IntVar()
> > varpro = IntVar()
> >
> > varconc = IntVar()
> > vartemp = IntVar()
> > entrynumberspeciesvar = IntVar()
>
> You can only use a stringvar with an Entry because
> the Entry only holds text, not integers. You will
> need to do the conversions yourself when you set/get
> the values.
>
> > def DesignPoint():
> >     print "Inside Design Point"
> >     rootdesign=Tk()
>
> You are still creating multiple roots, that is
> really bad practice and almost sure to create
> problems later. Define the function as:
>
> def DesignPoint(root):...
>
> and call it as
>
> DesignPoint(root)
>
> >     rootdesign.title("Design Point Suggestions")
> >     rootdesign.geometry("700x400")
> >     frame1 = Frame(rootdesign)
> >     frame1.grid(row=0, column=0)
> >
>
> If you want a second window you should be
> using a Toplevel widget not Frame here.
>
>
> >     label1 = Label(frame1, text="1. Responses to include: ")
> >     label1.grid(row=0, column=0,sticky=W)
> >
> >
> >     Label(frame1, text = "Number of species:").grid(row=0, column = 1,
> > sticky=W)
> >     entrynumberspecies = Entry(frame1, textvariable =
> entrynumberspeciesvar)
> >     entrynumberspecies.grid(row=0, column = 2, sticky=W)
> >
> >     # print entrynumberspeciesvar.get()
> >     checkreac = Checkbutton(frame1, text = "Reactant species", variable =
> > varreac)
> >     checkreac.grid(row = 1, column = 1, sticky = W)
> >     checkreac.select()
> >     Checkbutton(frame1, text = "Intermediate species", variable =
> > varint).grid(row = 2, column = 1, sticky = W)
> >     Checkbutton(frame1, text = "Product species", variable =
> > varpro).grid(row = 3, column = 1, sticky = W)
> >
> >     def Default():
> >         print "Inside default"
> >
> >         var1.set(0)
> >         var2.set(0)
> >         var3.set(0)
> >         var4.set(1)
>
> This function really should be defined outside
> the DesignPoint one. It will be much easier to maintain
> if you separate them out.
>
> >     Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
> > offvalue=0).grid(row=1, column = 2, sticky=W)
> >     Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2,
> column =
> > 2, sticky=W)
> >     Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3,
> column =
> > 2, sticky=W)
> >     check = Checkbutton(frame1, text = "Center", variable=var4)
> >
> >     check.grid(row=4, column = 2, sticky=W)
> >     check.select()
> >
> >     Label(frame1, text="2. Variables to be adjusted:").grid(row=5,
> > column=0,sticky=W)
> >     Checkbutton(frame1, text = "Concentration", variable=varconc,
> > onvalue=1, offvalue=0).grid(row=5, column = 1, sticky=W)
> >     Checkbutton(frame1, text = "Temperature",
> variable=vartemp).grid(row=6,
> > column = 1, sticky=W)
> >
> >     def InsertRange():
> >         print "Inside InsertRange"
> >         # entrynumberspeciesvar.set(2)
> >         print entrynumberspeciesvar.get()
> >         for i in range(entrynumberspeciesvar.get()):
> >             textvar = StringVar()
> >             print i
> >             textvar = "\t Conc"+str(i)
>
> Again you have deleted your StringVar object by overwriting it.
> You need to set the value with the set() method. OTOH you
> never use the StringVar so maybe you just need to delete
> that line.
>
> >             Label(frame1, text=textvar).grid(row=(9+i),
> column=0,sticky=W)
> >             conclowerentry = Entry(frame1)
> >             conclowerentry.grid(row= (9+i), column = 1, sticky = W)
> >             concupperentry = Entry(frame1)
> >             concupperentry.grid(row= (9+i), column = 2, sticky = W)
> >
>
> Same goes here. You should have very good reasons to define event
> handlers inside the functions that build your UIs. It usually just makes
> the code more complex with no benefit.
>
> >     Label(frame1, text="3. Range of formulation:").grid(row=7,
> > column=0,sticky=W)
> >     Button(frame1, text = "Insert Range", command =
> InsertRange()).grid(row
> > = 7, column = 3, sticky=W)
> >     Label(frame1, text="Lower Limit").grid(row=7, column=1,sticky=W)
> >     Label(frame1, text="Upper Limit").grid(row=7, column=2,sticky=W)
> >
> >     Label(frame1, text="\t Temperature").grid(row=8, column=0,sticky=W)
> >     templowerentry = Entry(frame1, text="0.0")
> >     templowerentry.grid(row= 8, column = 1, sticky = W)
> >     tempupperentry = Entry(frame1)
> >     tempupperentry.grid(row= 8, column = 2, sticky = W)
> >
> >     rootdesign.mainloop()
> >
> >
> > ## Secondary menu bar:
> > menusec = Frame(root, bg="white")
> > butt1 = Button(menusec, text="Part One", command=DesignPoint)
> > butt1.pack(side=LEFT, padx=1)
> > menusec.pack(side=TOP, fill=X)
> >
> >
> > ### --- Status bar ---- ####
> > Status = Label(root, text = statusvar, bd=1, relief=SUNKEN, anchor=W)
> > Status.pack(side=BOTTOM, fill=X)
> >
> > text = Text(root, width=1000, height = 400)
> > text.pack(side=BOTTOM)
> >
> >
> > root.mainloop()
> >
> > I have removed other parts of the code and included only the ones related
> > to the entry box and the work that I need to do.
> > I also tried doing it in another file as mentioned before. That works the
> > exact way I want.
> >
> > Code:
> > from Tkinter import *
> >
> > rootdesign=Tk()
> > rootdesign.title("Design Point Suggestions")
> > rootdesign.geometry("650x400")
> > frame1 = Frame(rootdesign)
> > frame1.grid(row=0, column=0)
> > entrynumberspeciesvar = IntVar()
> > ## Inserting Checkboxes:
> > label1 = Label(frame1, text="1. Responses to include: ")
> > label1.grid(row=0, column=0,sticky=W )
> > Label(frame1, text = "Number of species:").grid(row=0, column = 1,
> sticky=W)
> > entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
> > entrynumberspecies.grid(row=0, column = 2, sticky=W)
> >
> > def Print():
> >     print entrynumberspeciesvar.get()
> >     for i in range(entrynumberspeciesvar.get()):
> >         print i
> >         textvar = "\t Conc"+str(i+1)
> >         Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
> >         conclowerentry = Entry(frame1)
> >         conclowerentry.grid(row= (9+i), column = 1, sticky = W)
> >         concupperentry = Entry(frame1)
> >         concupperentry.grid(row= (9+i), column = 2, sticky = W)
> >
> > Button(frame1, text = "Click", command = Print).grid(row = 2, column = 2,
> > sticky = W)
> > Label(frame1, text="\t Temperature").grid(row=8, column=0,sticky=W)
> > templowerentry = Entry(frame1, text="0.0")
> > templowerentry.grid(row= 8, column = 1, sticky = W)
> > tempupperentry = Entry(frame1)
> > tempupperentry.grid(row= 8, column = 2, sticky = W)
> > rootdesign.mainloop()
> >
> >
> > Please let me know where I am going wrong. Thank you so much.
> > Pooja
> >
> > On Sat, Feb 11, 2017 at 12:52 PM, Alan Gauld via Tutor <tutor at python.org
> >
> > wrote:
> >
> >> On 11/02/17 15:28, Pooja Bhalode wrote:
> >>
> >>> I am trying to create a label and an entry widget. I am not able to
> >>> understand as to how to access the value input by the user in the entry
> >>> widget.
> >>>
> >>> Label(frame1, text = "Number of species:").grid(row=0, column = 1,
> >> sticky=W)
> >>> entrynumberspecies = Entry(frame1)
> >>> entrynumberspecies.grid(row=0, column = 2, sticky=W)
> >>>
> >>> print entrynumberspecies.get()
> >>
> >> You just accessed it, via the get() method. Did that not work?
> >>
> >>> How can I make the entrynumberspecies store the value in once the user
> >>> inputs it and then use that value for later part of my code?
> >>
> >> You can do it the way you did above using the get() method.
> >>
> >> But you can also do what you did for the checkboxes - use
> >> a StringVar and attach it to the Entry widget textvariable
> >> attribute. That way the variable will reflect whats in
> >> the Entry automatically and if you update the variable
> >> it will update the Entry. (Personally I prefer to use
> >> get() in most cases but many use the StringVar technique.)
> >> See the example at the bottom...
> >>
> >>> or print it for that matter.
> >>
> >> You can print it as you did above or you can store it in
> >> a variable and then print it or you can print the StringVar:
> >>
> >> print myEntry.get()
> >>
> >> myVar = MyEntry.get()
> >> print myVar
> >>
> >> entryVar = StringVar()
> >> myEntry = Entry(.....textvariable=entryVar)
> >> print entryVar.get()
> >>
> >> Here is a minimal example:
> >>
> >> ################
> >> from Tkinter import *
> >>
> >> def show():
> >>     print "entry says: " + e.get()
> >>     print "Variable holds: " + v.get()
> >>
> >> top = Tk()
> >> v = StringVar()
> >> e = Entry(top,textvariable=v)
> >> e.pack()
> >> Button(top,text="Set foobar", command=lambda : v.set("foobar")).pack()
> >> Button(top,text="Show me", command=show).pack()
> >>
> >> top.mainloop()
> >> #################
> >>
> >>
> >> --
> >> Alan G
> >> Author of the Learn to Program web site
> >> http://www.alan-g.me.uk/
> >> http://www.amazon.com/author/alan_gauld
> >> Follow my photo-blog on Flickr at:
> >> http://www.flickr.com/photos/alangauldphotos
> >>
> >>
> >> _______________________________________________
> >> Tutor maillist  -  Tutor at python.org
> >> To unsubscribe or change subscription options:
> >> https://mail.python.org/mailman/listinfo/tutor
> >>
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at yahoo.co.uk  Sun Feb 12 21:05:14 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 13 Feb 2017 02:05:14 +0000
Subject: [Tutor] Accessing an entry value input by the user
In-Reply-To: <CAK0ikxehmJu8+meb_A6PHL=Mmh4fH7TrZJPzhF1JzQk-uUq9ZA@mail.gmail.com>
References: <CAK0ikxdZtS5Hgpt2EB8yV4iEcwjEezDCtRoroj7uzk6xn_cOyg@mail.gmail.com>
 <o7nj0o$n8$1@blaine.gmane.org>
 <CAK0ikxd7XgeOWE0uJow8AEuSO2Z57uWuNKuz5_1o9nzvPbf3JA@mail.gmail.com>
 <o7oc95$mcv$1@blaine.gmane.org>
 <CAK0ikxehmJu8+meb_A6PHL=Mmh4fH7TrZJPzhF1JzQk-uUq9ZA@mail.gmail.com>
Message-ID: <o7r48k$7om$1@blaine.gmane.org>

On 12/02/17 20:01, Pooja Bhalode wrote:

> Thank you so much. I got stuck in another section:

It would be helpful if you gave more details of exactly how you get stuck.
What is happening(or not) that puzzles you.
Otherwise we just have to guess at what you mean.

Anyway, here goes...

> root=Tk()
> root.title("Design Point Suggestions")
> root.geometry("650x400")
> frame1 = Frame(root)
> frame1.grid(row=0, column=0)
> entrynumberspeciesvar = IntVar()
> Label(frame1, text="1. Responses to include: ").grid(row=0,
> column=0,sticky=W )
> Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
> entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
> entrynumberspecies.grid(row=0, column = 2, sticky=W)
> 
> conclowerentry = []
> concupperentry = []
> 
> def Print():
>     print entrynumberspeciesvar.get()
>     for i in range(entrynumberspeciesvar.get()):
>         conclowertemp = StringVar()
>         concuppertemp = StringVar()

Once again you are defining variables inside the function which
means they disappear when the function ends.

If you want to access what these hold you need to have them
outside the function.

>         textvar = "\t Conc"+str(i+1)
>         Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
>         Entry(frame1, textvariable = conclowertemp).grid(row= (9+i), column
> = 1, sticky = W)
>         Entry(frame1, textvariable = concuppertemp).grid(row= (9+i), column
> = 2, sticky = W)
> 
>         if len(concuppertemp.get()) != 0 and len(conclowertemp.get()) != 0:
>             concupperentry.append(int(concuppertemp.get()))
>             conclowerentry.append(int(conclowertemp.get()))
> 
>         def Submit():
>             print "Submitted. "
>             print conclowerentry.get()
>             print concupperentry.get()

Again this function could(should?) be outside the function
as a global level function. By defining it inside the function
you add extra complexity to the Print() code and break up
its flow making it harder to see what is going on.

You gain nothing by having it inside the Print() since
the variables it accesses are already declared outside
Print and are thus available for Submit to access.

> 
>         Button(frame1, text="Submit", command = Submit).grid(row = 2,
> column = 1, sticky = W)
> 
> Button(frame1, text = "Click", command = Print).grid(row = 2, column = 2,
> sticky = W)
> root.mainloop()
> 
> print conclowerentry
> print concupperentry
> 
> This creates a window as given below:
> [image: Inline image 1]

This is a text based mailing list so images usually
get stripped out by the server.


> where the user inputs the number and the corresponding number of entry
> boxes and labels get created.
> Submit button is used for storing in the values in a list and then
> printing.

Submit is not storing anything it just prints.
The only storage is in this segment of Print()

>         if len(concuppertemp.get()) != 0 and len(conclowertemp.get())
!= 0:
>             concupperentry.append(int(concuppertemp.get()))
>             conclowerentry.append(int(conclowertemp.get()))
>

And since that is called immediately after the creation of the Entry I
doubt that anything gets stored. You need to put this code inside the
Submit function.
> 
> But here, I am not able to store the value associated with each entry boxes
> in the created list.

See above.

Move the Submit function outside Print() and put the
storage lines above inside Submit() and see how that goes.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From eryksun at gmail.com  Sun Feb 12 23:07:23 2017
From: eryksun at gmail.com (eryk sun)
Date: Mon, 13 Feb 2017 04:07:23 +0000
Subject: [Tutor] Python-list thread: int vs. float
In-Reply-To: <CANDiX9+HnsRGLQth3pYrtTVQ7FrqnkQAO8nvc7h0kn+eZCRy6Q@mail.gmail.com>
References: <CANDiX9KKeK2kd1zHJpmuM0Tf4=6L7W4J-rspJPqOcJ0gZm_TfA@mail.gmail.com>
 <20170211080607.GF4796@ando.pearwood.info>
 <CACL+1atuA1xn-DiH6=-YPFNazQfBaH_fPZ1JckOmgJqSjHwrDA@mail.gmail.com>
 <d578456ad6c27090988530796692a850@sonic.net>
 <CANDiX9+HnsRGLQth3pYrtTVQ7FrqnkQAO8nvc7h0kn+eZCRy6Q@mail.gmail.com>
Message-ID: <CACL+1atkugf-LiVnT+uGaqFvF-zuqub6wDtaYqrYH+w03jW48w@mail.gmail.com>

On Sat, Feb 11, 2017 at 8:53 PM, boB Stepp <robertvstepp at gmail.com> wrote:
>
> I suspect Eryk had set a normal 's' as an identifier for the character
> code sequence that produces the non-ASCII output, but forgot to show
> us that step.  But I could be mistaken.

Sorry, I forgot to show the assignment of the string "???" to the variable s.

> Today I am working in Windows 7, not Linux Mint.  Of course when I
> attempted to copy and paste the non-ASCII sequence from Gmail into
> cmd.exe I got 3 rectangular boxes on the paste line, indicating
> cmd.exe could not translate those characters.

If you're running python.exe, it either inherits or allocates a
console, which is hosted by an instance of conhost.exe. At most you're
inheriting a console from cmd.exe. That's the extent of its
involvement. Think of conhost.exe as a terminal window, like GNOME
Terminal, etc. cmd.exe and powershell.exe are shells that use standard
I/O, much like Python's REPL -- or like running bash in a Unix
terminal.

The console window can handle characters in the basic multilingual
plane (BMP). Python 3.6 uses the console's wide-character (Unicode)
API, so it should have no problem reading the string "???" if typed or
pasted into the console. For example, if it's assigned to `s`, then
ascii(s) should show the correct \u literals:

    >>> ascii(s)
    "'\\u0be7\\ua622\\u0b69'"

Unfortunately, for rendering text the Windows console has limited font
support. It requires a strictly monospace font, among other criteria.
It won't switch automatically to other fonts when the current font
doesn't have a glyph for a character. It just displays an empty box
glyph. In Windows 7 a good font choice for the console window is
Consolas. It has pretty good coverage for Western languages, but not
for any of the characters in "???".

If you copy the empty-box glyphs from the console window to the
clipboard, it's actually copying the Unicode characters, which can be
pasted into a window that has better font support, such as notepad. So
in 3.6 this is just a superficial rendering issue that can be
addressed by using programs such as ConEmu that replace the standard
console window (it hides the console and hooks the API to write to its
own window).

From gerayap at gmail.com  Mon Feb 13 02:23:47 2017
From: gerayap at gmail.com (Yap Gerald)
Date: Mon, 13 Feb 2017 15:23:47 +0800
Subject: [Tutor] Issue with set_value function
Message-ID: <CAKT2Z12m967qriRVTmZchKYD_jWaUuhmXCcdx9fS1ROxjvQrqA@mail.gmail.com>

Hi Tutors,

I have a problem with the functions set_value which I could not find a
solution on the net. In my output below, I was able to set_value at the
first loop but not the second loop. The different check using print could
not identify what was the problem. I have attached my testset, function and
output below. Really appreciate if anyone can help me with this issue.
Thanks!

Regards
Gerald

Dataset plus processing:
Test_data as attached.
test_df = pd.read_csv("kargertest.txt", header = None, names = ["raw"])
test_df["raw_list"] = test_df["raw"].apply(lambda x : x.split('\t'))
test_df["vertexes"] = test_df["raw_list"].apply(lambda x : x[0])
test_df["edges"] = test_df["raw_list"].apply(lambda x : x[1:])

This is my function on min cut algorithm.


def min_cut(df,edges):
    df2 = copy.deepcopy(df)
    for i in range(len(df)):
        print "df at start of loop is ", df2
        if len(df2) == 2:
            print len(df2)
            print df2["edges"]
            return len(df2["edges"].values[1])
        else:
            contract_edge = pick_rand(edges)
            print "contract_edge is ", contract_edge
            row_a = df2[df2['vertexes'] == contract_edge[0]]
            row_b = df2[df2['vertexes'] == contract_edge[1]]

            index_a = row_a.index[0]
            index_b = row_b.index[0]

            edges_a = row_a['edges'].tolist()[0]
            edges_b = row_b['edges'].tolist()[0]

            edges_a = filter(lambda a : a != contract_edge[1], edges_a)
            edges_b = filter(lambda a : a != contract_edge[0], edges_b)

            edges_c = edges_a + edges_b
            print "edges_c is ", edges_c

            print "index a of field edges is ", df2["edges"][index_a]
            df2['edges'][index_a] = edges_c
            print "df2 after setting value is", df2
            df2 = df2.drop(index_b)

            for x in range(len(df2)):
                temp_list = df2.iloc[x]["edges"]
                while contract_edge[1] in temp_list:
                    temp_list.remove(contract_edge[1])
                    temp_list.append(contract_edge[0])
                    df2["edges"][x] = temp_list

            edges = filter(lambda a : a != contract_edge, edges)
            edges = filter(lambda a : a != (contract_edge[1],
contract_edge[0]), edges)

            for i in range(len(edges)):
                if edges[i][0] == contract_edge[1]:
                    edges[i] = (contract_edge[0],edges[i][1])
                if edges[i][1] == contract_edge[1]:
                    edges[i] = (edges[i][0],contract_edge[0])

            edges = filter(lambda a : a != (contract_edge[0],
contract_edge[0]), edges)


My output is:

df at start of loop is

raw      raw_list vertexes      edges
0     1\t2\t3     [1, 2, 3]        1     [2, 3]
1  2\t1\t3\t4  [2, 1, 3, 4]        2  [1, 3, 4]
2  3\t1\t2\t4  [3, 1, 2, 4]        3  [1, 2, 4]
3     4\t2\t3     [4, 2, 3]        4     [2, 3]

contract_edge is  ('4', '2')

edges_c is  ['3', '1', '3']

index a of field edges is  ['2', '3']

df2 after setting value is

raw      raw_list vertexes      edges

0     1\t2\t3     [1, 2, 3]        1     [2, 3]
1  2\t1\t3\t4  [2, 1, 3, 4]        2  [1, 3, 4]
2  3\t1\t2\t4  [3, 1, 2, 4]        3  [1, 2, 4]
3     4\t2\t3     [4, 2, 3]        4  [3, 1, 3]
df at start of loop is            raw      raw_list vertexes      edges
0     1\t2\t3     [1, 2, 3]        1     [3, 4]
2  3\t1\t2\t4  [3, 1, 2, 4]        3  [1, 4, 4]
3     4\t2\t3     [4, 2, 3]        4  [3, 1, 3]

contract_edge is  ('4', '3')

edges_c is  ['1', '1']

index a of field edges is  ['3', '1', '3']

df2 after setting value is


raw      raw_list vertexes      edges
0     1\t2\t3     [1, 2, 3]        1     [3, 4]
2  3\t1\t2\t4  [3, 1, 2, 4]        3  [1, 4, 4]
3     4\t2\t3     [4, 2, 3]        4  [3, 1, 3]

df at start of loop is


raw   raw_list vertexes      edges
0  1\t2\t3  [1, 2, 3]        1     [4, 4]
3  4\t2\t3  [4, 2, 3]        4  [1, 4, 4]

2
0       [4, 4]
3    [1, 4, 4]
1    [1, 4, 4]
Name: edges, dtype: object
-------------- next part --------------
1	2	3
2	1	3	4
3	1	2	4
4	2	3

From guest0x013 at gmail.com  Mon Feb 13 04:40:08 2017
From: guest0x013 at gmail.com (Freedom Peacemaker)
Date: Mon, 13 Feb 2017 10:40:08 +0100
Subject: [Tutor] GUI for ANSI colors
Message-ID: <CAL+yi2ZmSfW+cnxGhth8Qe=xyx=nMcrXB+5By6uSQaYQ2RjRLQ@mail.gmail.com>

Hi tutor,
I'm trying to put my script with randomly colored letters (ANSI escape
code) into GUI but cant find any. I've tried tkinter but it isn't good
choice. Then i was searching for capabilities of PyQt4 again without
success. Thats why im writing this message. Is there any GUI that can print
word with randomly colored letters?

From tuanbk05 at gmail.com  Mon Feb 13 01:44:05 2017
From: tuanbk05 at gmail.com (Thanh Tuan Le)
Date: Mon, 13 Feb 2017 13:44:05 +0700
Subject: [Tutor] Can we talk with a Real Time Clock hardware by Python?
Message-ID: <CADKc188K8rpxRMOn2gZs4mg7bTFZVu4kwJNT-QGSnhboK1p4CQ@mail.gmail.com>

Dear Mr, Mrs,

During working with Python, I have a matter that I am finding a solution. I
am not an experience programmer in Python, so may I raise this question to
you? I really appreciate for any help.

I have a board that have a Real Time Clock (RTC) chip on that board. I need
to communicate with that RTC chip by Python.

Following is my hardware info.
- Board from Variscite:
http://www.variscite.com/products/single-board-computers/dt6customboard
- RTC chip on board: ISL12057
- OS: Yocto

I need to do 2 basic operations for this RTC chip
- Write/Read to registers of that RTC.
- Detect the Interrupt at each time it asserted.

Do we have any technique or library of Python that can do the above
operations?

Thanks.

Best regards,
TuanLe

From alan.gauld at yahoo.co.uk  Mon Feb 13 05:47:00 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 13 Feb 2017 10:47:00 +0000
Subject: [Tutor] Can we talk with a Real Time Clock hardware by Python?
In-Reply-To: <CADKc188K8rpxRMOn2gZs4mg7bTFZVu4kwJNT-QGSnhboK1p4CQ@mail.gmail.com>
References: <CADKc188K8rpxRMOn2gZs4mg7bTFZVu4kwJNT-QGSnhboK1p4CQ@mail.gmail.com>
Message-ID: <o7s2qu$i0m$1@blaine.gmane.org>

On 13/02/17 06:44, Thanh Tuan Le wrote:
> I have a board that have a Real Time Clock (RTC) chip on that board. I need
> to communicate with that RTC chip by Python.
> 
> Following is my hardware info.
> - Board from Variscite:
> http://www.variscite.com/products/single-board-computers/dt6customboard
> - RTC chip on board: ISL12057
> - OS: Yocto

I know nothing about this specific board or clock.
However, in general you need an API to talk to any
kind of hardware. Boards like this usually provide
a C API - do you have documentation for that?

If thee is a C API there is a good chance that
you can talk to it using the ctypes module.
But ctypes is not easy to use so be prepared
for a lot of trial and error.

It's also possible, if you know C, to build a
library and then wrap it up as a Python module
using SWIG or similar technology. But this is
only an option if you are already comfortable
working in C.

The best option is if a Google search shows
that somebody has already done that work and
made the python module available to download.


> 
> I need to do 2 basic operations for this RTC chip
> - Write/Read to registers of that RTC.
> - Detect the Interrupt at each time it asserted.

It would also help to know more about your environment.
What is your host computing platform and OS?
How is the board attached to the computer?
(USB, PCI, jumper, soldered?)
And which version of Python are you using?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Mon Feb 13 05:52:07 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 13 Feb 2017 11:52:07 +0100
Subject: [Tutor] Issue with set_value function
References: <CAKT2Z12m967qriRVTmZchKYD_jWaUuhmXCcdx9fS1ROxjvQrqA@mail.gmail.com>
Message-ID: <o7s34i$qsd$1@blaine.gmane.org>

Yap Gerald wrote:

> I have a problem with the functions set_value which I could not find a
> solution on the net. In my output below, I was able to set_value at the
> first loop but not the second loop. The different check using print could
> not identify what was the problem. I have attached my testset, function
> and output below. Really appreciate if anyone can help me with this issue.

I'm sorry, your description does not give me an idea what your problem might 
be. There's not even a set_value() function in your code sample...

Please make the code you provide self-contained so that we can run it 
without modifications. The script should be as small as possible. If one 
step of your code produces the expected output give a script that starts 
with that output and only includes the failing step.

Show both the output you get and the expected output you want. Rather than 
providing arbitrary debugging data try to concentrate on the relevant 
parts.



From alan.gauld at yahoo.co.uk  Mon Feb 13 05:56:49 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 13 Feb 2017 10:56:49 +0000
Subject: [Tutor] Issue with set_value function
In-Reply-To: <CAKT2Z12m967qriRVTmZchKYD_jWaUuhmXCcdx9fS1ROxjvQrqA@mail.gmail.com>
References: <CAKT2Z12m967qriRVTmZchKYD_jWaUuhmXCcdx9fS1ROxjvQrqA@mail.gmail.com>
Message-ID: <o7s3db$r1p$1@blaine.gmane.org>

On 13/02/17 07:23, Yap Gerald wrote:

> I have a problem with the functions set_value which I could not find a
> solution on the net.

This is very confusing. You don't use set_value() anywhere
in the code you posted? You don't describe what the actual
problem with set_ value() is.

And most of all you don't tell us what set_value() is - its
not a standard Python function.

In short, it's impossible for us to guess what set_value
is, how you use it or what the problem is.

Simply posting input and output data and a random function
doesn't help us at all. We are not familiar with your
work area, we don't know the context. We have no idea
what the output should be. You need to help us to help you.

One thing I would say is that it looks sufficiently
technical that you should probably be using SciPy/NumPy
if you aren't already; that may be where some of your
functions come from?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 13 06:28:43 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 13 Feb 2017 11:28:43 +0000
Subject: [Tutor] GUI for ANSI colors
In-Reply-To: <CAL+yi2ZmSfW+cnxGhth8Qe=xyx=nMcrXB+5By6uSQaYQ2RjRLQ@mail.gmail.com>
References: <CAL+yi2ZmSfW+cnxGhth8Qe=xyx=nMcrXB+5By6uSQaYQ2RjRLQ@mail.gmail.com>
Message-ID: <o7s596$n9f$1@blaine.gmane.org>

On 13/02/17 09:40, Freedom Peacemaker wrote:

> I'm trying to put my script with randomly colored letters (ANSI escape
> code) into GUI but cant find any. I've tried tkinter but it isn't good
> choice. 

Why not? It can certainly do what you want. As can virtually
any other GUI toolkit. But programming GUIs is much harder
than programming the console regardless of toolkit choice.

Here is a sample Tkinter program that displays text in
different colors:

###############################
from Tkinter import *

n = 0
top = Tk()
t = Text(top, width=25, height=2)
t.pack()

# set up tags for the colors
colors = ['red','blue','green']
for col in colors:
    t.tag_config(col, foreground=col)

def addWords():
    n = 0
    for word in "Hello ", "bright ", "world ":
        t.insert(END,word,colors[n])  #use the color tags
        n +=1

Button(top,text="Add words",command=addWords).pack()

top.mainloop()
######################

Most other GUIs will be similar.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From lwaters at flinthill.org  Mon Feb 13 11:06:41 2017
From: lwaters at flinthill.org (Lisa Hasler Waters)
Date: Mon, 13 Feb 2017 11:06:41 -0500
Subject: [Tutor] Resending question with smaller file
Message-ID: <CAF91wy_Dtku04Eaj1=8cJCNvb7rRhPhOsdtrHpk5k6D8AOMR9w@mail.gmail.com>

Hello Python Tutor,

We are trying to use the random function in the Tkinter module in
PyCharmEDU 3.5. (on Macs running 10.11.6). However, we get a number of
error messages:

Here's the code:

from tkinter import *
import random
tk = Tk()

canvas = Canvas(tk, width=400, height=400)
canvas.pack()


def random_randrange(height):
    pass


def random_randrange(width):
    pass


def random_rectangle(width, height):
    x1 = random_randrange(width)
    y1 = random_randrange(height)
    x2 = x1 + random.randrange(width)
    y2 = y1 + random.randrange(height)
    canvas.create_rectangle(x1, y1, x2, y2)
    random_rectangle(400, 400)

tk.mainloop()

Here are the error messages:

Traceback (most recent call last):
  File "/Users/lwaters/PycharmProjects/tkinternew/rectangles.py", line
2, in <module>
    import random
  File "/Users/lwaters/PycharmProjects/tkinternew/random.py", line 17,
in <module>
    randomRects(100)
  File "/Users/lwaters/PycharmProjects/tkinternew/random.py", line 10,
in randomRects
    x1 = random.randrange(150)
AttributeError: module 'random' has no attribute 'randrange'

Process finished with exit code 1

Your advice is greatly appreciated!

Lisa Waters

-- 
Lisa Waters, PhD
Technology Integration
Middle School Coding
Lower School Digital Literacy
Flint Hill School
703.584.2300
*www.flinthill.org* <http://www.flinthill.org/>

From mail at timgolden.me.uk  Mon Feb 13 11:14:13 2017
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 13 Feb 2017 16:14:13 +0000
Subject: [Tutor] Resending question with smaller file
In-Reply-To: <CAF91wy_Dtku04Eaj1=8cJCNvb7rRhPhOsdtrHpk5k6D8AOMR9w@mail.gmail.com>
References: <CAF91wy_Dtku04Eaj1=8cJCNvb7rRhPhOsdtrHpk5k6D8AOMR9w@mail.gmail.com>
Message-ID: <f446cd85-d84e-c4a9-1d63-643445455a0a@timgolden.me.uk>

On 13/02/2017 16:06, Lisa Hasler Waters wrote:
> Hello Python Tutor,
>
> We are trying to use the random function in the Tkinter module in
> PyCharmEDU 3.5. (on Macs running 10.11.6). However, we get a number of
> error messages:
>
> Here's the code:
>
> from tkinter import *
> import random
> tk = Tk()
>
> canvas = Canvas(tk, width=400, height=400)
> canvas.pack()
>
>
> def random_randrange(height):
>     pass
>
>
> def random_randrange(width):
>     pass
>
>
> def random_rectangle(width, height):
>     x1 = random_randrange(width)
>     y1 = random_randrange(height)
>     x2 = x1 + random.randrange(width)
>     y2 = y1 + random.randrange(height)
>     canvas.create_rectangle(x1, y1, x2, y2)
>     random_rectangle(400, 400)
>
> tk.mainloop()
>
> Here are the error messages:
>
> Traceback (most recent call last):
>   File "/Users/lwaters/PycharmProjects/tkinternew/rectangles.py", line
> 2, in <module>
>     import random
>   File "/Users/lwaters/PycharmProjects/tkinternew/random.py", line 17,
> in <module>
>     randomRects(100)
>   File "/Users/lwaters/PycharmProjects/tkinternew/random.py", line 10,
> in randomRects
>     x1 = random.randrange(150)
> AttributeError: module 'random' has no attribute 'randrange'

You've called your own module "random.py"; call it something else

TJG


From lwaters at flinthill.org  Mon Feb 13 08:30:17 2017
From: lwaters at flinthill.org (Lisa Hasler Waters)
Date: Mon, 13 Feb 2017 08:30:17 -0500
Subject: [Tutor] Help with random in Tkinter
Message-ID: <CAF91wy9rT=8gYMBmL7pxqPRHSsLGCrU=-YY8i886vGVJH0P9Mw@mail.gmail.com>

Hello Python Tutor,

We are trying to use the random function in the Tkinter module in
PyCharmEDU 3.5. However, we get a number of error messages (see screen
shot):
[image: Inline image 1]



It runs fine when we use IDLE. But, we love PyCharmEDU as it is much more
user-friendly and so we hope to run the same programs in it as we can in
IDLE.

We are running PyCharm EDU 3.5 on Macs 10.11.6.

Your advice will be greatly appreciated!

Thanks,

Lisa Waters

-- 
Lisa Waters, PhD
Technology Integration
Middle School Coding
Lower School Digital Literacy
Flint Hill School
703.584.2300
*www.flinthill.org* <http://www.flinthill.org/>

From alan.gauld at yahoo.co.uk  Mon Feb 13 12:33:30 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 13 Feb 2017 17:33:30 +0000
Subject: [Tutor] Resending question with smaller file
In-Reply-To: <CAF91wy_Dtku04Eaj1=8cJCNvb7rRhPhOsdtrHpk5k6D8AOMR9w@mail.gmail.com>
References: <CAF91wy_Dtku04Eaj1=8cJCNvb7rRhPhOsdtrHpk5k6D8AOMR9w@mail.gmail.com>
Message-ID: <o7sql4$oaq$1@blaine.gmane.org>

On 13/02/17 16:06, Lisa Hasler Waters wrote:

> We are trying to use the random function in the Tkinter module 

> from tkinter import *
> import random

This looks for the random module and tries your local folder first.
If you have a file called random.py it tries to import that.

Based on your error messages there is a file is called random.py
so it tries to import it rather than the standard library version... Try
renaming your file to something more descriptive of what
makes it different from the library version.

> tk = Tk()
> 
> canvas = Canvas(tk, width=400, height=400)
> canvas.pack()
> 
> 
> def random_randrange(height):
>     pass
> 
> 
> def random_randrange(width):
>     pass

These two functions are the same since Python doesn't understand
the parameter names it just sees

def aFunctionName(aParameterName)

so the second def simply overwrites the first.
What you really mean (I think) is

def random_randrange(aNumber): pass

Although that's still not a very descriptive name...

> def random_rectangle(width, height):
>     x1 = random_randrange(width)
>     y1 = random_randrange(height)
>     x2 = x1 + random.randrange(width)
>     y2 = y1 + random.randrange(height)
>     canvas.create_rectangle(x1, y1, x2, y2)
>     random_rectangle(400, 400)

You call this same function recursively, this will
result in an infinite loop until you run out of memory.
I don't know what you are trying to do but this is
surely not it.

This function never gets called and, since
its not assigned as an event handler, it will
never be executed.


> tk.mainloop()

> Here are the error messages:
> 
> Traceback (most recent call last):
>   File "/Users/lwaters/PycharmProjects/tkinternew/rectangles.py", line
> 2, in <module>
>     import random
>   File "/Users/lwaters/PycharmProjects/tkinternew/random.py", line 17,
> in <module>
>     randomRects(100)

Notice the two files listed above are in the same folder and one
is called random.py


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 13 12:38:35 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 13 Feb 2017 17:38:35 +0000
Subject: [Tutor] Help with random in Tkinter
In-Reply-To: <CAF91wy9rT=8gYMBmL7pxqPRHSsLGCrU=-YY8i886vGVJH0P9Mw@mail.gmail.com>
References: <CAF91wy9rT=8gYMBmL7pxqPRHSsLGCrU=-YY8i886vGVJH0P9Mw@mail.gmail.com>
Message-ID: <o7squl$rdc$1@blaine.gmane.org>

On 13/02/17 13:30, Lisa Hasler Waters wrote:

> It runs fine when we use IDLE. But, we love PyCharmEDU as it is much more
> user-friendly and so we hope to run the same programs in it as we can in
> IDLE.

That shouldn't make much difference unless PyCharm sets its
default folders differently?

BTW running GUI programs from inside an IDE is always slightly
dodgy, the IDE tends to trap all kinds of things that might
happen when you run the program outside the IDE. Its always
worth testing GUI programs by launching them from the OS
 - eg by double clicking the file in Finder on OSX.

The IDE is fine while coding and debugging but it should
be thought of as a draft only, the final code needs to
be run outside the IDE before you can be sure it works.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From antonylily8 at gmail.com  Mon Feb 13 14:37:16 2017
From: antonylily8 at gmail.com (Lily ANTONY)
Date: Mon, 13 Feb 2017 11:37:16 -0800
Subject: [Tutor] Access a .tcl file in python
Message-ID: <CAPEuPV5zSObbVtK_M9WEs6EfG_hrDFKAFQyv0OqW4Q_GN23ajg@mail.gmail.com>

Hi,
I have a .tcl file.Does anyone know how to load a .tcl file in to python?I
need to call the .tcl file in
a python program..Thanks!

Lily.

From schen557 at wisc.edu  Mon Feb 13 13:34:17 2017
From: schen557 at wisc.edu (SIJIA CHEN)
Date: Mon, 13 Feb 2017 18:34:17 +0000
Subject: [Tutor] Q about .join()   Thanks!
Message-ID: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>

Dear, all,

I am a python novice and I am wondering if someone in the group could help me with a easy question about .join() method!

I find out that the outcome for using .join() on a dictionary is totally different than it using on list or string. for example,

                  >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
                  >>> print ':'.join(seq4)
                  boy:good:doiido:hello
So my question is why the outcome doesn't show sequentially as the same sequence of the original seq4?  What pattern do those "keys" of the dictionary in the outcome show ?

I would be really appreciate it!!!! Thanks!
Sincerely,
Sonia




From alan.gauld at yahoo.co.uk  Mon Feb 13 19:58:21 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 00:58:21 +0000
Subject: [Tutor] Fwd: Re:  GUI for ANSI colors
In-Reply-To: <CAL+yi2Y1vkYMJQDx_rM=C4n6GWs8vzNQO_GG3WTk5CCmA5cNLA@mail.gmail.com>
References: <CAL+yi2Y1vkYMJQDx_rM=C4n6GWs8vzNQO_GG3WTk5CCmA5cNLA@mail.gmail.com>
Message-ID: <288d1ec0-15f9-b736-286c-f02f9e9e0c6b@yahoo.co.uk>

Forwarding to list.

-------------------------------------------
Ive tried your suggestion but didnt work. Look this is my code and i
need to print final_word into GUI. Im working on Ubuntu 16.04

#! usr/bin/python3

from random import choice
from string import ascii_letters, digits

chars = ascii_letters + digits
word = ''.join(choice(chars) for i in range(12))

red = '\033[91m'
yel = '\033[93m'
blu = '\033[34m'
grn = '\033[32m'

colors = [red, yel, blu, grn]

final_word = ''.join(choice(colors) + char for char in word)
print(final_word)

2017-02-13 12:28 GMT+01:00 Alan Gauld via Tutor <tutor at python.org
<mailto:tutor at python.org>>:

    On 13/02/17 09:40, Freedom Peacemaker wrote:

    > I'm trying to put my script with randomly colored letters (ANSI escape
    > code) into GUI but cant find any. I've tried tkinter but it isn't good
    > choice.

    Why not? It can certainly do what you want. As can virtually
    any other GUI toolkit. But programming GUIs is much harder
    than programming the console regardless of toolkit choice.

    Here is a sample Tkinter program that displays text in
    different colors:

    ###############################
    from Tkinter import *

    n = 0
    top = Tk()
    t = Text(top, width=25, height=2)
    t.pack()

    # set up tags for the colors
    colors = ['red','blue','green']
    for col in colors:
        t.tag_config(col, foreground=col)

    def addWords():
        n = 0
        for word in "Hello ", "bright ", "world ":
            t.insert(END,word,colors[n])  #use the color tags
            n +=1

    Button(top,text="Add words",command=addWords).pack()

    top.mainloop()
    ######################

    Most other GUIs will be similar.

    --
    Alan G
    Author of the Learn to Program web site
    http://www.alan-g.me.uk/
    http://www.amazon.com/author/alan_gauld
    <http://www.amazon.com/author/alan_gauld>
    Follow my photo-blog on Flickr at:
    http://www.flickr.com/photos/alangauldphotos
    <http://www.flickr.com/photos/alangauldphotos>


    _______________________________________________
    Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
    To unsubscribe or change subscription options:
    https://mail.python.org/mailman/listinfo/tutor
    <https://mail.python.org/mailman/listinfo/tutor>



From alan.gauld at yahoo.co.uk  Mon Feb 13 20:17:39 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 01:17:39 +0000
Subject: [Tutor] Access a .tcl file in python
In-Reply-To: <CAPEuPV5zSObbVtK_M9WEs6EfG_hrDFKAFQyv0OqW4Q_GN23ajg@mail.gmail.com>
References: <CAPEuPV5zSObbVtK_M9WEs6EfG_hrDFKAFQyv0OqW4Q_GN23ajg@mail.gmail.com>
Message-ID: <o7tlrd$qau$1@blaine.gmane.org>

On 13/02/17 19:37, Lily ANTONY wrote:

> I have a .tcl file.Does anyone know how to load a .tcl file in to python?I
> need to call the .tcl file in
> a python program..Thanks!

In general you can't run code for one language in a
program written in another language. (There are a few
exceptions, usually where one language is written in
the other).

The nearest you can usually get is to execute the
Tcl program using the tcl interpreter (tclsh) from
the OS using a module like subprocess.

However, Tcl and Python do have a connection  via
the Tkinter module and you can call tcl code
using Tkinter like so(Python v3):

import tkinter
tcl = tkinter.Tcl()
tcl.eval("""
puts [expr 4+5]  # or any other arbitrary tcl
""")

So to execute a Tcl file you can read the contents
into a string and then execute that string. Note that
the return value will always be a string.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From david at graniteweb.com  Mon Feb 13 20:20:52 2017
From: david at graniteweb.com (David Rock)
Date: Mon, 13 Feb 2017 19:20:52 -0600
Subject: [Tutor] Q about .join()   Thanks!
In-Reply-To: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
References: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
Message-ID: <650DB54C-926B-4F22-BFB5-2941856F2B6F@graniteweb.com>


> On Feb 13, 2017, at 12:34, SIJIA CHEN <schen557 at wisc.edu> wrote:
> 
> I find out that the outcome for using .join() on a dictionary is totally different than it using on list or string. for example,
> 
>>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>>> print ':'.join(seq4)
>                  boy:good:doiido:hello
> So my question is why the outcome doesn't show sequentially as the same sequence of the original seq4?  What pattern do those "keys" of the dictionary in the outcome show ?

Dictionaries (in particular, their keys) are unordered.  You can not rely on them to be in a particular sequence.  The reason for this, from a practical perspective, is you are expected to ask for the specific key; you should not care about the ordering.

Lists, on the other hand, have a specific order by design so will always be in the order they were created.

What are you trying to do with join() on a dictionary in the first place?  Is there a specific outcome you are trying to get?  It?s unlikely that using join on a dictionary is what you actually want.

?
David Rock
david at graniteweb.com





From alan.gauld at yahoo.co.uk  Mon Feb 13 20:26:45 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 01:26:45 +0000
Subject: [Tutor] Fwd: Re: GUI for ANSI colors
In-Reply-To: <288d1ec0-15f9-b736-286c-f02f9e9e0c6b@yahoo.co.uk>
References: <CAL+yi2Y1vkYMJQDx_rM=C4n6GWs8vzNQO_GG3WTk5CCmA5cNLA@mail.gmail.com>
 <288d1ec0-15f9-b736-286c-f02f9e9e0c6b@yahoo.co.uk>
Message-ID: <o7tmcg$r61$1@blaine.gmane.org>

On 14/02/17 00:58, Alan Gauld forwarded:

> red = '\033[91m'
> yel = '\033[93m'
> blu = '\033[34m'
> grn = '\033[32m'

These are indeed the ANSI codes for the colours but ANSI
codes only work in an ANSI terminal and GUIs are not
ANSI terminals. Instead they have their own ideas on
colours and you need to use those. They all support
the standard 16 colours used in ANSI however, so in
your case (for Tkinter at least) just use the names
'red', 'yellow', 'blue' and 'green'

> colors = [red, yel, blu, grn]

colors = ['red', 'yellow', 'blue', 'green']


> final_word = ''.join(choice(colors) + char for char in word)

But again that won't work in a GUI, you need to use the GUIs
way of colouring. In Tkinter that's via tags as per my
previous post, reproduced here).

>     ###############################
>     from Tkinter import *
> 
>     n = 0
>     top = Tk()
>     t = Text(top, width=25, height=2)
>     t.pack()
> 
>     # set up tags for the colors
>     colors = ['red','blue','green']
>     for col in colors:
>         t.tag_config(col, foreground=col)
> 
>     def addWords():
>         n = 0
>         for word in "Hello ", "bright ", "world ":
>             t.insert(END,word,colors[n])  #use the color tags
>             n +=1
>

You need to change the loop to iterate over the letters
instead of words and choose the tags at random. But that
should be fairly straightforward.

>     Button(top,text="Add words",command=addWords).pack()
> 
>     top.mainloop()
>     ######################


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 13 20:31:57 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 01:31:57 +0000
Subject: [Tutor] Q about .join() Thanks!
In-Reply-To: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
References: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
Message-ID: <o7tmm7$4ga$1@blaine.gmane.org>

On 13/02/17 18:34, SIJIA CHEN wrote:
> I find out that the outcome for using .join() on a dictionary is 
> totally different than it using on list or string.

Not really, it just looks like that :-)

> 
>                   >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>                   >>> print ':'.join(seq4)
>                   boy:good:doiido:hello
> So my question is why the outcome doesn't show sequentially

That's because dictionaries are not stored sequentially and the
order of retrieval is not guaranteed - it can even change
during the execution of a program so you should never
depend on it. That's because dictionaries are optimised
for random access via the keys not to be iterated over.

You can sort the keys and then pull the values and that will
give you a guaranteed order but simply printing the dictionary
(or joining it as you did) is not reliable.

I've a vague memory that recent versions of Python may have
a special dictionary type that does return items in the order
they were inserted, but I may be mixing that up with
another language... Hopefully someone else can provide
a steer there.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From dyoo at hashcollision.org  Mon Feb 13 21:10:10 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 13 Feb 2017 18:10:10 -0800
Subject: [Tutor] Q about .join() Thanks!
In-Reply-To: <o7tmm7$4ga$1@blaine.gmane.org>
References: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
 <o7tmm7$4ga$1@blaine.gmane.org>
Message-ID: <CAGZAPF6kjraQWZzRt9OuTn-cCd0YMSr64Ob_AExMHfwoAo=kcg@mail.gmail.com>

> That's because dictionaries are not stored sequentially and the
> order of retrieval is not guaranteed - it can even change
> during the execution of a program so you should never
> depend on it. That's because dictionaries are optimised
> for random access via the keys not to be iterated over.

Moreover, most implementations *deliberately* randomize their iteration
order to avoid a particular kind of hash collision attack out there in
the wild.  See:

    https://en.wikipedia.org/wiki/Collision_attack

    https://arstechnica.com/business/2011/12/huge-portions-of-web-vulnerable-to-hashing-denial-of-service-attack/

    https://mail.python.org/pipermail/python-dev/2011-December/115116.html

for some details.


> I've a vague memory that recent versions of Python may have
> a special dictionary type that does return items in the order
> they were inserted, but I may be mixing that up with
> another language... Hopefully someone else can provide
> a steer there.

In Python, it's collections.OrderedDict:

    https://docs.python.org/3.6/library/collections.html#collections.OrderedDict

Other languages have similar libraries.  Java has LinkedHashMap, for example:

    https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html


Best of wishes!

From __peter__ at web.de  Tue Feb 14 03:50:04 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 14 Feb 2017 09:50:04 +0100
Subject: [Tutor] Q about .join() Thanks!
References: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
 <o7tmm7$4ga$1@blaine.gmane.org>
 <CAGZAPF6kjraQWZzRt9OuTn-cCd0YMSr64Ob_AExMHfwoAo=kcg@mail.gmail.com>
Message-ID: <o7ugbo$55h$1@blaine.gmane.org>

Danny Yoo wrote:

> Moreover, most implementations *deliberately* randomize their iteration
> order to avoid a particular kind of hash collision attack out there in
> the wild.  See:
 
In CPython the hash() of a string may change between different runs to fend 
off hash collision attacks, but that does not necessarily change the order 
of iteration:

In Python 3.4 for example both order and hash value change

$ python3.4 -c 'd = dict.fromkeys("foo bar baz".split()); print(hash("foo"), 
*d)'
-1599197652882818545 baz bar foo
$ python3.4 -c 'd = dict.fromkeys("foo bar baz".split()); print(hash("foo"), 
*d)'
-7773300350121034240 foo bar baz
$ python3.4 -c 'd = dict.fromkeys("foo bar baz".split()); print(hash("foo"), 
*d)'
4096077922251392823 baz bar foo

In Python 3.6 on the other side the hash values still change, but 
(insertion) order is preserved:

$ python3.6 -c 'd = dict.fromkeys("foo bar baz".split()); print(hash("foo"), 
*d)'
22453670082131454 foo bar baz
$ python3.6 -c 'd = dict.fromkeys("foo bar baz".split()); print(hash("foo"), 
*d)'
4601604916521659267 foo bar baz
$ python3.6 -c 'd = dict.fromkeys("foo bar baz".split()); print(hash("foo"), 
*d)'
5190466601789110813 foo bar baz

So if the OP had used Python 3.6 she would have seen the behaviour she 
expected. However, quoting 
<https://docs.python.org/dev/whatsnew/3.6.html#new-dict-implementation>

"""
The order-preserving aspect of this new [dict] implementation is considered 
an implementation detail and should not be relied upon
"""


From allantanaka11 at yahoo.com  Mon Feb 13 20:55:30 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Tue, 14 Feb 2017 01:55:30 +0000 (UTC)
Subject: [Tutor] NameError: name 'hurst' is not defined
References: <1935899150.3714253.1487037330466.ref@mail.yahoo.com>
Message-ID: <1935899150.3714253.1487037330466@mail.yahoo.com>

Hi. Not sure why this code produces the error like this. This error appears when i run the code of print "Hurst(GBM): ? %s" % hurst(gbm):?
Traceback (most recent call last):? File "<pyshell#31>", line 1, in <module>? ? print "Hurst(GBM): ? %s" % hurst(gbm)NameError: name 'hurst' is not defined

Here is the full code:>>> import statsmodels.tsa.stattools as ts
>>> import urllib>>> from datetime import datetime>>> from pandas_datareader import data, wb>>> from pandas_datareader.data import DataReader>>> goog = DataReader("GOOG", "yahoo", datetime(2000,1,1), datetime(2017,1,1))>>> ts.adfuller(goog['Adj Close'], 1>>> import numpy as np
>>> from numpy import cumsum, log, polyfit, sqrt, std, subtract>>> from numpy.random import randn>>> def hurst(ts): lags = range(2, 100) tau = [np.sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags] poly = np.polyfit(log(lags), log(tau), 1) return poly[0]*2.0>>> gbm = log(cumsum(randn(100000))+1000)>>> mr = log(randn(100000)+1000)>>> tr = log(cumsum(randn(100000)+1)+1000)>>> print "Hurst(GBM): ? %s" % hurst(gbm)

From Joaquin.Alzola at lebara.com  Mon Feb 13 20:25:35 2017
From: Joaquin.Alzola at lebara.com (Joaquin Alzola)
Date: Tue, 14 Feb 2017 01:25:35 +0000
Subject: [Tutor] Q about .join()   Thanks!
In-Reply-To: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
References: <CO2PR0601MB7268595B41616AF06442D69EA590@CO2PR0601MB726.namprd06.prod.outlook.com>
Message-ID: <AM2PR07MB080440ED8D0294D6A2FAE9C5F0580@AM2PR07MB0804.eurprd07.prod.outlook.com>

>I find out that the outcome for using .join() on a dictionary is totally different than it using on list or string. for example,

 >                 >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
 >                 >>>
 >                 boy:good:doiido:hello
>So my question is why the outcome doesn't show sequentially as the same sequence of the original seq4?  What pattern do those "keys" of the dictionary in the outcome show ?

Dictionaries are not an ordered sequence.

In order to do that you need to create and OrderedDict (in collections)

Modern Dictionaries --> https://www.youtube.com/watch?v=p33CVV29OG8
The mighty Dictionary --> https://www.youtube.com/watch?v=C4Kc8xzcA68&t=142s
This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.

From alan.gauld at yahoo.co.uk  Tue Feb 14 05:11:14 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 10:11:14 +0000
Subject: [Tutor] NameError: name 'hurst' is not defined
In-Reply-To: <1935899150.3714253.1487037330466@mail.yahoo.com>
References: <1935899150.3714253.1487037330466.ref@mail.yahoo.com>
 <1935899150.3714253.1487037330466@mail.yahoo.com>
Message-ID: <o7ul3s$crk$1@blaine.gmane.org>

On 14/02/17 01:55, Allan Tanaka via Tutor wrote:
> Hi. Not sure why this code produces the error like this. This error appears when i run the code of print "Hurst(GBM):   %s" % hurst(gbm): 
> Traceback (most recent call last):  File "<pyshell#31>", line 1, in <module>    print "Hurst(GBM):   %s" % hurst(gbm)NameError: name 'hurst' is not defined
> 
> Here is the full code:>>> import statsmodels.tsa.stattools as ts
>>>> import urllib>>> from datetime import datetime>>> from pandas_datareader import data, wb>>> from pandas_datareader.data import DataReader>>> goog = DataReader("GOOG", "yahoo", datetime(2000,1,1), datetime(2017,1,1))>>> ts.adfuller(goog['Adj Close'], 1>>> import numpy as np
>>>> from numpy import cumsum, log, polyfit, sqrt, std, subtract>>> from numpy.random import randn>>> def hurst(ts): lags = range(2, 100) tau = [np.sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags] poly = np.polyfit(log(lags), log(tau), 1) return poly[0]*2.0>>> gbm = log(cumsum(randn(100000))+1000)>>> mr = log(randn(100000)+1000)>>> tr = log(cumsum(randn(100000)+1)+1000)>>> print "Hurst(GBM):   %s" % hurst(gbm)

The mail system has mangled your code, you need to post
in plain text to preserve layout. I'll try to reconstruct
it based on >>> as the interpreter prompt:

>>> import urllib
>>> from datetime import datetime
>>> from pandas_datareader import data, wb
>>> from pandas_datareader.data import DataReader
>>> goog = DataReader("GOOG", "yahoo", datetime(2000,1,1),
                      datetime(2017,1,1))
>>> ts.adfuller(goog['Adj Close'], 1

there seems to be a missing closing  paren here?
Also where does 'ts' come from, its not defined above?

>>> import numpy as np
>>> from numpy import cumsum, log, polyfit, sqrt, std, subtract
>>> from numpy.random import randn
>>> def hurst(ts):
          lags = range(2, 100)
          tau = [np.sqrt(std(subtract(ts[lag:], ts[:-lag])))
                 for lag in lags]
          poly = np.polyfit(log(lags), log(tau), 1)
          return poly[0]*2.0
>>> gbm = log(cumsum(randn(100000))+1000)
>>> mr = log(randn(100000)+1000)
>>> tr = log(cumsum(randn(100000)+1)+1000)
>>> print "Hurst(GBM):   %s" % hurst(gbm)

Is that right?
Apart from the missing ')' and undefined ts, it looks OK.
Have you tried putting it into a file and running it
as a script? That will avoid risk of pollution from
any previous context in the interpreter.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Tue Feb 14 05:25:31 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 14 Feb 2017 11:25:31 +0100
Subject: [Tutor] NameError: name 'hurst' is not defined
References: <1935899150.3714253.1487037330466.ref@mail.yahoo.com>
 <1935899150.3714253.1487037330466@mail.yahoo.com>
Message-ID: <o7ulup$rs6$1@blaine.gmane.org>

Allan Tanaka via Tutor wrote:

> Hi. Not sure why this code produces the error like this. This error
> appears when i run the code of print "Hurst(GBM):   %s" % hurst(gbm):
> Traceback (most recent call last):  File "<pyshell#31>", line 1, in
> <module>    print "Hurst(GBM):   %s" % hurst(gbm)NameError: name 'hurst'
> is not defined
> 
> Here is the full code:>>> import statsmodels.tsa.stattools as ts
>>>> import urllib>>> from datetime import datetime>>> from
>>>> pandas_datareader import data, wb>>> from pandas_datareader.data import
>>>> DataReader>>> goog = DataReader("GOOG", "yahoo", datetime(2000,1,1),
>>>> datetime(2017,1,1))>>> ts.adfuller(goog['Adj Close'], 1>>> import numpy
>>>> as np from numpy import cumsum, log, polyfit, sqrt, std, subtract>>>
>>>> from numpy.random import randn>>> def hurst(ts): lags = range(2, 100)
>>>> tau = [np.sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags]
>>>> poly = np.polyfit(log(lags), log(tau), 1) return poly[0]*2.0>>> gbm =
>>>> log(cumsum(randn(100000))+1000)>>> mr = log(randn(100000)+1000)>>> tr =
>>>> log(cumsum(randn(100000)+1)+1000)>>> print "Hurst(GBM):   %s" %
>>>> hurst(gbm)

See that mess? You need to check your mail client. When I undo the 
scrambling...

$ cat hurst.py 
import statsmodels.tsa.stattools as ts
import urllib
from datetime import datetime
from pandas_datareader import data, wb
from pandas_datareader.data import DataReader

goog = DataReader("GOOG", "yahoo", datetime(2000,1,1), datetime(2017,1,1))
ts.adfuller(goog['Adj Close'], 1)

import numpy as np
from numpy import cumsum, log, polyfit, sqrt, std, subtract
from numpy.random import randn

def hurst(ts): 
    lags = range(2, 100) 
    tau = [np.sqrt(std(subtract(ts[lag:], ts[:-lag]))) for lag in lags]
    poly = np.polyfit(log(lags), log(tau), 1)
    return poly[0]*2.0

gbm = log(cumsum(randn(100000))+1000)
mr = log(randn(100000)+1000)
tr = log(cumsum(randn(100000)+1)+1000)

print "Hurst(GBM):   %s" % hurst(gbm)

...the code runs without error:

$ python hurst.py 
Hurst(GBM):   0.502272832664



From alan.gauld at yahoo.co.uk  Tue Feb 14 06:23:57 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 11:23:57 +0000
Subject: [Tutor] NameError: name 'hurst' is not defined
In-Reply-To: <o7ul3s$crk$1@blaine.gmane.org>
References: <1935899150.3714253.1487037330466.ref@mail.yahoo.com>
 <1935899150.3714253.1487037330466@mail.yahoo.com>
 <o7ul3s$crk$1@blaine.gmane.org>
Message-ID: <o7upc7$utg$1@blaine.gmane.org>

On 14/02/17 10:11, Alan Gauld via Tutor wrote:

>>>> ts.adfuller(goog['Adj Close'], 1
> 
> there seems to be a missing closing  paren here?
> Also where does 'ts' come from, its not defined above?

Ah! I see from Peters post that I missed the first line of code.
But I still see a missing ')'...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From aaliyahebrahim21 at gmail.com  Tue Feb 14 07:03:26 2017
From: aaliyahebrahim21 at gmail.com (Aaliyah Ebrahim)
Date: Tue, 14 Feb 2017 14:03:26 +0200
Subject: [Tutor] Exponential function
Message-ID: <CAEbJqrHG47pZ=seYhZ628Mg0qXKHDZje3mtgU0vk7uBt12tpyA@mail.gmail.com>

Hi

For the function 1*10^x, is there a specific way of computing *10^x or will
it just be the following :

1*10**x

Thank you.

From boriscobizaro8 at gmail.com  Tue Feb 14 14:53:54 2017
From: boriscobizaro8 at gmail.com (Borisco Bizaro)
Date: Tue, 14 Feb 2017 11:53:54 -0800
Subject: [Tutor] Tutor Digest, Vol 156, Issue 33
In-Reply-To: <mailman.2787.1487062220.2317.tutor@python.org>
References: <mailman.2787.1487062220.2317.tutor@python.org>
Message-ID: <CAKE=nh7tGH3PhUL6uBKz4gHYdbYqhomvtKLvYL8=6trrrvNpiA@mail.gmail.com>

Please l will like to have a mentor how can I have it
On Feb 14, 2017 09:53, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>         tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>         https://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>         tutor-request at python.org
>
> You can reach the person managing the list at
>         tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
> Today's Topics:
>
>    1. Re: Access a .tcl file in python (Alan Gauld)
>    2. Re: Q about .join()   Thanks! (David Rock)
>    3. Re: Fwd: Re: GUI for ANSI colors (Alan Gauld)
>    4. Re: Q about .join() Thanks! (Alan Gauld)
>    5. Re: Q about .join() Thanks! (Danny Yoo)
>    6. Re: Q about .join() Thanks! (Peter Otten)
>
>
> ---------- Forwarded message ----------
> From: Alan Gauld <alan.gauld at yahoo.co.uk>
> To: tutor at python.org
> Cc:
> Date: Tue, 14 Feb 2017 01:17:39 +0000
> Subject: Re: [Tutor] Access a .tcl file in python
> On 13/02/17 19:37, Lily ANTONY wrote:
>
> > I have a .tcl file.Does anyone know how to load a .tcl file in to
> python?I
> > need to call the .tcl file in
> > a python program..Thanks!
>
> In general you can't run code for one language in a
> program written in another language. (There are a few
> exceptions, usually where one language is written in
> the other).
>
> The nearest you can usually get is to execute the
> Tcl program using the tcl interpreter (tclsh) from
> the OS using a module like subprocess.
>
> However, Tcl and Python do have a connection  via
> the Tkinter module and you can call tcl code
> using Tkinter like so(Python v3):
>
> import tkinter
> tcl = tkinter.Tcl()
> tcl.eval("""
> puts [expr 4+5]  # or any other arbitrary tcl
> """)
>
> So to execute a Tcl file you can read the contents
> into a string and then execute that string. Note that
> the return value will always be a string.
>
> HTH
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
>
>
>
> ---------- Forwarded message ----------
> From: David Rock <david at graniteweb.com>
> To: "tutor at python.org" <tutor at python.org>
> Cc:
> Date: Mon, 13 Feb 2017 19:20:52 -0600
> Subject: Re: [Tutor] Q about .join() Thanks!
>
> > On Feb 13, 2017, at 12:34, SIJIA CHEN <schen557 at wisc.edu> wrote:
> >
> > I find out that the outcome for using .join() on a dictionary is totally
> different than it using on list or string. for example,
> >
> >>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
> >>>> print ':'.join(seq4)
> >                  boy:good:doiido:hello
> > So my question is why the outcome doesn't show sequentially as the same
> sequence of the original seq4?  What pattern do those "keys" of the
> dictionary in the outcome show ?
>
> Dictionaries (in particular, their keys) are unordered.  You can not rely
> on them to be in a particular sequence.  The reason for this, from a
> practical perspective, is you are expected to ask for the specific key; you
> should not care about the ordering.
>
> Lists, on the other hand, have a specific order by design so will always
> be in the order they were created.
>
> What are you trying to do with join() on a dictionary in the first place?
> Is there a specific outcome you are trying to get?  It?s unlikely that
> using join on a dictionary is what you actually want.
>
> ?
> David Rock
> david at graniteweb.com
>
>
>
>
>
>
> ---------- Forwarded message ----------
> From: Alan Gauld <alan.gauld at yahoo.co.uk>
> To: tutor at python.org
> Cc:
> Date: Tue, 14 Feb 2017 01:26:45 +0000
> Subject: Re: [Tutor] Fwd: Re: GUI for ANSI colors
> On 14/02/17 00:58, Alan Gauld forwarded:
>
> > red = '\033[91m'
> > yel = '\033[93m'
> > blu = '\033[34m'
> > grn = '\033[32m'
>
> These are indeed the ANSI codes for the colours but ANSI
> codes only work in an ANSI terminal and GUIs are not
> ANSI terminals. Instead they have their own ideas on
> colours and you need to use those. They all support
> the standard 16 colours used in ANSI however, so in
> your case (for Tkinter at least) just use the names
> 'red', 'yellow', 'blue' and 'green'
>
> > colors = [red, yel, blu, grn]
>
> colors = ['red', 'yellow', 'blue', 'green']
>
>
> > final_word = ''.join(choice(colors) + char for char in word)
>
> But again that won't work in a GUI, you need to use the GUIs
> way of colouring. In Tkinter that's via tags as per my
> previous post, reproduced here).
>
> >     ###############################
> >     from Tkinter import *
> >
> >     n = 0
> >     top = Tk()
> >     t = Text(top, width=25, height=2)
> >     t.pack()
> >
> >     # set up tags for the colors
> >     colors = ['red','blue','green']
> >     for col in colors:
> >         t.tag_config(col, foreground=col)
> >
> >     def addWords():
> >         n = 0
> >         for word in "Hello ", "bright ", "world ":
> >             t.insert(END,word,colors[n])  #use the color tags
> >             n +=1
> >
>
> You need to change the loop to iterate over the letters
> instead of words and choose the tags at random. But that
> should be fairly straightforward.
>
> >     Button(top,text="Add words",command=addWords).pack()
> >
> >     top.mainloop()
> >     ######################
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
>
>
>
> ---------- Forwarded message ----------
> From: Alan Gauld <alan.gauld at yahoo.co.uk>
> To: tutor at python.org
> Cc:
> Date: Tue, 14 Feb 2017 01:31:57 +0000
> Subject: Re: [Tutor] Q about .join() Thanks!
> On 13/02/17 18:34, SIJIA CHEN wrote:
> > I find out that the outcome for using .join() on a dictionary is
> > totally different than it using on list or string.
>
> Not really, it just looks like that :-)
>
> >
> >                   >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
> >                   >>> print ':'.join(seq4)
> >                   boy:good:doiido:hello
> > So my question is why the outcome doesn't show sequentially
>
> That's because dictionaries are not stored sequentially and the
> order of retrieval is not guaranteed - it can even change
> during the execution of a program so you should never
> depend on it. That's because dictionaries are optimised
> for random access via the keys not to be iterated over.
>
> You can sort the keys and then pull the values and that will
> give you a guaranteed order but simply printing the dictionary
> (or joining it as you did) is not reliable.
>
> I've a vague memory that recent versions of Python may have
> a special dictionary type that does return items in the order
> they were inserted, but I may be mixing that up with
> another language... Hopefully someone else can provide
> a steer there.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
>
>
>
> ---------- Forwarded message ----------
> From: Danny Yoo <dyoo at hashcollision.org>
> To: Alan Gauld <alan.gauld at yahoo.co.uk>
> Cc: Python Tutor Mailing List <tutor at python.org>
> Date: Mon, 13 Feb 2017 18:10:10 -0800
> Subject: Re: [Tutor] Q about .join() Thanks!
> > That's because dictionaries are not stored sequentially and the
> > order of retrieval is not guaranteed - it can even change
> > during the execution of a program so you should never
> > depend on it. That's because dictionaries are optimised
> > for random access via the keys not to be iterated over.
>
> Moreover, most implementations *deliberately* randomize their iteration
> order to avoid a particular kind of hash collision attack out there in
> the wild.  See:
>
>     https://en.wikipedia.org/wiki/Collision_attack
>
>     https://arstechnica.com/business/2011/12/huge-
> portions-of-web-vulnerable-to-hashing-denial-of-service-attack/
>
>     https://mail.python.org/pipermail/python-dev/2011-December/115116.html
>
> for some details.
>
>
> > I've a vague memory that recent versions of Python may have
> > a special dictionary type that does return items in the order
> > they were inserted, but I may be mixing that up with
> > another language... Hopefully someone else can provide
> > a steer there.
>
> In Python, it's collections.OrderedDict:
>
>     https://docs.python.org/3.6/library/collections.html#
> collections.OrderedDict
>
> Other languages have similar libraries.  Java has LinkedHashMap, for
> example:
>
>     https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
>
>
> Best of wishes!
>
>
>
> ---------- Forwarded message ----------
> From: Peter Otten <__peter__ at web.de>
> To: tutor at python.org
> Cc:
> Date: Tue, 14 Feb 2017 09:50:04 +0100
> Subject: Re: [Tutor] Q about .join() Thanks!
> Danny Yoo wrote:
>
> > Moreover, most implementations *deliberately* randomize their iteration
> > order to avoid a particular kind of hash collision attack out there in
> > the wild.  See:
>
> In CPython the hash() of a string may change between different runs to fend
> off hash collision attacks, but that does not necessarily change the order
> of iteration:
>
> In Python 3.4 for example both order and hash value change
>
> $ python3.4 -c 'd = dict.fromkeys("foo bar baz".split());
> print(hash("foo"),
> *d)'
> -1599197652882818545 baz bar foo
> $ python3.4 -c 'd = dict.fromkeys("foo bar baz".split());
> print(hash("foo"),
> *d)'
> -7773300350121034240 foo bar baz
> $ python3.4 -c 'd = dict.fromkeys("foo bar baz".split());
> print(hash("foo"),
> *d)'
> 4096077922251392823 baz bar foo
>
> In Python 3.6 on the other side the hash values still change, but
> (insertion) order is preserved:
>
> $ python3.6 -c 'd = dict.fromkeys("foo bar baz".split());
> print(hash("foo"),
> *d)'
> 22453670082131454 foo bar baz
> $ python3.6 -c 'd = dict.fromkeys("foo bar baz".split());
> print(hash("foo"),
> *d)'
> 4601604916521659267 foo bar baz
> $ python3.6 -c 'd = dict.fromkeys("foo bar baz".split());
> print(hash("foo"),
> *d)'
> 5190466601789110813 foo bar baz
>
> So if the OP had used Python 3.6 she would have seen the behaviour she
> expected. However, quoting
> <https://docs.python.org/dev/whatsnew/3.6.html#new-dict-implementation>
>
> """
> The order-preserving aspect of this new [dict] implementation is considered
> an implementation detail and should not be relied upon
> """
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> https://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at yahoo.co.uk  Tue Feb 14 18:01:10 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 23:01:10 +0000
Subject: [Tutor] Exponential function
In-Reply-To: <CAEbJqrHG47pZ=seYhZ628Mg0qXKHDZje3mtgU0vk7uBt12tpyA@mail.gmail.com>
References: <CAEbJqrHG47pZ=seYhZ628Mg0qXKHDZje3mtgU0vk7uBt12tpyA@mail.gmail.com>
Message-ID: <o8027g$o7j$1@blaine.gmane.org>

On 14/02/17 12:03, Aaliyah Ebrahim wrote:

> For the function 1*10^x, is there a specific way of computing *10^x or will
> it just be the following :
> 
> 1*10**x

To compute it if you don't know x in advance then yes,
use something like

value = 10**x

But if you know the value in advance you can write it in
a more compact form as:

value = 1e5  # or 3e7 or whatever...

say(if x=5).

Experiment at the interactive prompt to see how it works.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb 14 18:06:15 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 23:06:15 +0000
Subject: [Tutor] Tutor Digest, Vol 156, Issue 33
In-Reply-To: <CAKE=nh7tGH3PhUL6uBKz4gHYdbYqhomvtKLvYL8=6trrrvNpiA@mail.gmail.com>
References: <mailman.2787.1487062220.2317.tutor@python.org>
 <CAKE=nh7tGH3PhUL6uBKz4gHYdbYqhomvtKLvYL8=6trrrvNpiA@mail.gmail.com>
Message-ID: <2df577bc-285c-d0e3-fd2c-a3f5bf592799@yahoo.co.uk>

As per my offline reply, just send messages to the list and
the whole group will act as a virtual mentor.

One other thing though. Please start new topics with a new message.
Do NOT reply to an existing thread as it messes up the archives.
And especially do not reply to a digest message.

And use a meaningful subject line.

Its very hard to find a question in the archive if the
subject is

Re: Tutor Digest, Vol 156, Issue 33

or similar.

(unless of course you really are asking a question about
that particular digest message rather than its content
 - but if so it should probably go to the list owners.)

It's much easier to find a message with a subject like

help with python log functions

or whatever.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From alan.gauld at yahoo.co.uk  Tue Feb 14 18:06:15 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 14 Feb 2017 23:06:15 +0000
Subject: [Tutor] Tutor Digest, Vol 156, Issue 33
In-Reply-To: <CAKE=nh7tGH3PhUL6uBKz4gHYdbYqhomvtKLvYL8=6trrrvNpiA@mail.gmail.com>
References: <mailman.2787.1487062220.2317.tutor@python.org>
 <CAKE=nh7tGH3PhUL6uBKz4gHYdbYqhomvtKLvYL8=6trrrvNpiA@mail.gmail.com>
Message-ID: <2df577bc-285c-d0e3-fd2c-a3f5bf592799@yahoo.co.uk>

As per my offline reply, just send messages to the list and
the whole group will act as a virtual mentor.

One other thing though. Please start new topics with a new message.
Do NOT reply to an existing thread as it messes up the archives.
And especially do not reply to a digest message.

And use a meaningful subject line.

Its very hard to find a question in the archive if the
subject is

Re: Tutor Digest, Vol 156, Issue 33

or similar.

(unless of course you really are asking a question about
that particular digest message rather than its content
 - but if so it should probably go to the list owners.)

It's much easier to find a message with a subject like

help with python log functions

or whatever.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From eryksun at gmail.com  Tue Feb 14 23:43:22 2017
From: eryksun at gmail.com (eryk sun)
Date: Wed, 15 Feb 2017 04:43:22 +0000
Subject: [Tutor] Exponential function
In-Reply-To: <o8027g$o7j$1@blaine.gmane.org>
References: <CAEbJqrHG47pZ=seYhZ628Mg0qXKHDZje3mtgU0vk7uBt12tpyA@mail.gmail.com>
 <o8027g$o7j$1@blaine.gmane.org>
Message-ID: <CACL+1av+ufFG8dA0MT0Umbyvt2sPnJH60fmkufTemobcK1o8PA@mail.gmail.com>

On Tue, Feb 14, 2017 at 11:01 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> To compute it if you don't know x in advance then yes,
> use something like
>
> value = 10**x
>
> But if you know the value in advance you can write it in
> a more compact form as:
>
> value = 1e5  # or 3e7 or whatever...

10**5 is an int and 1e5 is a float. This could lead to a significant
loss of precision depending on the calculation. For example:

    >>> x = 10**5 * 1234567890123456789
    >>> y = 1e5 * 1234567890123456789
    >>> x - y
    16777216.0

Replacing 10**5 with 100000 is a compile-time optimization (constant
expression folding), so you needn't worry about manually optimizing
it. For example:

    >>> compile('10**5', '', 'exec').co_consts
    (10, 5, None, 100000)

The compiled bytecode refers to the pre-computed constant:

    >>> dis.dis(compile('10**5', '', 'exec'))
      1           0 LOAD_CONST               3 (100000)
                  3 POP_TOP
                  4 LOAD_CONST               2 (None)
                  7 RETURN_VALUE

From alan.gauld at yahoo.co.uk  Wed Feb 15 03:41:21 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 15 Feb 2017 08:41:21 +0000
Subject: [Tutor] Exponential function
In-Reply-To: <CACL+1av+ufFG8dA0MT0Umbyvt2sPnJH60fmkufTemobcK1o8PA@mail.gmail.com>
References: <CAEbJqrHG47pZ=seYhZ628Mg0qXKHDZje3mtgU0vk7uBt12tpyA@mail.gmail.com>
 <o8027g$o7j$1@blaine.gmane.org>
 <CACL+1av+ufFG8dA0MT0Umbyvt2sPnJH60fmkufTemobcK1o8PA@mail.gmail.com>
Message-ID: <o8147b$pub$1@blaine.gmane.org>

On 15/02/17 04:43, eryk sun wrote:

>> value = 1e5  # or 3e7 or whatever...
> 
> 10**5 is an int and 1e5 is a float. 

Good point, I'd forgotten about that distinction.

> Replacing 10**5 with 100000 is a compile-time optimization

And didn't know about that one.

Thanks for the clarification.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From jf_byrnes at comcast.net  Wed Feb 15 17:37:45 2017
From: jf_byrnes at comcast.net (Jim)
Date: Wed, 15 Feb 2017 16:37:45 -0600
Subject: [Tutor] Please explain part of this code
Message-ID: <o82l7j$418$1@blaine.gmane.org>

import sys
from notebook import Notebook, Note

class Menu:
     '''Display a menu and respond to choices when run.'''
     def __init__(self):
         self.notebook = Notebook()
         self.choices = {
                 "1": self.show_notes,
                 "2": self.search_notes,
                 "3": self.add_note,
                 "4": self.modify_note,
                 "5": self.quit
                 }

     def display_menu(self):
         print("""
Notebook Menu

1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")

     def run(self):
         '''Display the menu and respond to choices.'''
         while True:
             self.display_menu()
             choice = input("Enter an option: ")
             action = self.choices.get(choice)
             if action:
                 action()
             else:
                 print("{0} is not a valid choice".format(choice))
<snip>

The author says:

The action variable actually refers to a specific method and is called 
by appending empty brackets (since none of the methods require 
parameters) to the variable.

I sort of understand what is going on with "action". All of the choices 
to the right of the :'s are methods defined elsewhere in the code. So I 
guess that will call whatever method is associated with a choice.

I don't recall ever seeing this before.  What is this technique called?

Thanks,  Jim


From elhamkhanche at gmail.com  Wed Feb 15 13:06:02 2017
From: elhamkhanche at gmail.com (elham khanchebemehr)
Date: Wed, 15 Feb 2017 21:36:02 +0330
Subject: [Tutor] Memory Error
Message-ID: <CACNq6oKR2=amRuWv_6VmqahphorYeoez2+oFMNMRxMYrPw5RTw@mail.gmail.com>

Hi,
I'm trying to write a code in python that takes an array of integers as
sources, an array of integers as sinks, and an array of an array of
integers of capacities, returning the maximum flow. I'm new to python and I
got memory error, can you plaese help me because i have no idea how to
solve this problem?
entrances: sources
exits: sinks
path: capacities
------------------------------------------------------------------------------------------------------------------
def answer(entrances, exits, path):
    maxflow = 0
    for i in exits:
        path[i] = [0] * len(path)
    for i in range(len(path)):
        for j in entrances:
            path[i][j] = 0
    for i in entrances:
        augpathgen = bfs_paths(path, i, exits)
        while True:
            try:
                augpath = next(augpathgen)
            except StopIteration:
                break
            flows = [path[augpath[j]][augpath[j+1]] for j in
range(len(augpath)-1)]
            minCap = min(flows)
            maxflow += minCap
            for j in range(len(augpath)-1):
                path[augpath[j]][augpath[j+1]] -= minCap
    return maxflow

def bfs_paths(graph, start, goal):
    queue = [(start, [start])]
    while queue:
        (vertex, path) = queue.pop(0)
        for next in range(len(graph[vertex])):
            if graph[vertex][next] != 0:
                if next in goal:
                    yield path + [next]
                elif next not in path:
                    queue.append((next, path + [next]))
--------------------------------------------------------------------------------------------------------------------
thanks a lot
El

From howletta1234 at gmail.com  Wed Feb 15 13:00:30 2017
From: howletta1234 at gmail.com (Adam Howlett)
Date: Wed, 15 Feb 2017 13:00:30 -0500
Subject: [Tutor] Need help with one problem.
Message-ID: <7D4CBC9F-B925-4D70-8847-184CB5264E6D@gmail.com>

Write an if-else statement that assigns 20 to the variable y if the variable x is greater than 100. Otherwise, it should assign 0 to the variable y.

Is there an easy way to solve this problem?

From alan.gauld at yahoo.co.uk  Wed Feb 15 17:56:19 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 15 Feb 2017 22:56:19 +0000
Subject: [Tutor] Please explain part of this code
In-Reply-To: <o82l7j$418$1@blaine.gmane.org>
References: <o82l7j$418$1@blaine.gmane.org>
Message-ID: <o82mad$qch$1@blaine.gmane.org>

On 15/02/17 22:37, Jim wrote:

>          self.choices = {
>                  "1": self.show_notes,
>                  "2": self.search_notes,
>                  "3": self.add_note,
>                  "4": self.modify_note,
>                  "5": self.quit
>                  }
> 
> The author says:
> 
> The action variable actually refers to a specific method and is called 
> by appending empty brackets (since none of the methods require 
> parameters) to the variable.
> 

> I don't recall ever seeing this before.  What is this technique called?

Its very common, especially in GUIs and used in many
languages including C, VB, Java, Javascript and Lisp.
Its usually called a callback (because the stored
function is called back by the event receiver).

In C it is done by using a "pointer to a function".
In Lisp you create a Lambda (an anonymous function)
- which you can also do in Python and recent Java
versions. In Smalltalk and Ruby you define a "block".
In most of the other languages it's similar to Python,
you just pass the name of the function.

This is often referred to as the language treating
functions as "first class objects", and is a core
part of Functional Programming.

A common FP structure is the map function which takes
a function and a sequence and applies the function
to each member of the sequence, returning the
resultant sequence. Here is a short Python example:

def double(x): return x*2

data = [1,2,3,4]
result = map(double, data)   # -> [2,4,6,8]
print(result)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Wed Feb 15 17:59:45 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 15 Feb 2017 22:59:45 +0000
Subject: [Tutor] Need help with one problem.
In-Reply-To: <7D4CBC9F-B925-4D70-8847-184CB5264E6D@gmail.com>
References: <7D4CBC9F-B925-4D70-8847-184CB5264E6D@gmail.com>
Message-ID: <o82mgs$e37$1@blaine.gmane.org>

On 15/02/17 18:00, Adam Howlett wrote:
> Write an if-else statement that 
> assigns 20 to the variable y if the variable x is greater than 100. 
> Otherwise, it should assign 0 to the variable y.
> 
> Is there an easy way to solve this problem?

Yes, just do what it says.

Maybe if I reword the problem slightly it will
be easier to see?

if the variable x is greater than 100,
assign 20 to the variable y,
else
assign 0 to the variable y.

Does that help?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Wed Feb 15 18:13:11 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 16 Feb 2017 10:13:11 +1100
Subject: [Tutor] Memory Error
In-Reply-To: <CACNq6oKR2=amRuWv_6VmqahphorYeoez2+oFMNMRxMYrPw5RTw@mail.gmail.com>
References: <CACNq6oKR2=amRuWv_6VmqahphorYeoez2+oFMNMRxMYrPw5RTw@mail.gmail.com>
Message-ID: <20170215231311.GG5689@ando.pearwood.info>

On Wed, Feb 15, 2017 at 09:36:02PM +0330, elham khanchebemehr wrote:
> Hi,
> I'm trying to write a code in python that takes an array of integers as
> sources, an array of integers as sinks, and an array of an array of
> integers of capacities, returning the maximum flow. I'm new to python and I
> got memory error, can you plaese help me because i have no idea how to
> solve this problem?

Start by showing us the error you are getting. COPY AND PASTE the entire 
traceback you get, starting with the line "Traceback..." to the end 
showing the error message, don't take a screen shot, don't retype it 
from memory, don't simplify it or summarise it.

Generally you get a memory error because you've run out of memory for 
the program. How much memory do you have on your computer? What OS is it 
running? 32-bit or 64-bit?

How big are entrances, exits and path?

If you are dealing with extremely large data sets, the overhead of 
Python's "boxed" data types can become significant. For example, on my 
computer a list of 100 zeroes takes 432 bytes:

py> import sys
py> data = [0]*100
py> sys.getsizeof(data)
432

If this is the problem, you may be able to reduce memory consumption by 
using the array module:

py> import array
py> data = array.array('b', [0])*100
py> sys.getsizeof(data)
132

Using the third-party numpy library may also help.

But for really large amounts of data, you can't avoid needing large 
amounts of memory.


Another comment, this is not related to your memory error, but this 
bit of code is terribly clunky:


>     for i in entrances:
>         augpathgen = bfs_paths(path, i, exits)
>         while True:
>             try:
>                 augpath = next(augpathgen)
>             except StopIteration:
>                 break
>             flows = [path[augpath[j]][augpath[j+1]] for j in range(len(augpath)-1)]


Replace that with:

    for i in entrances:
        augpathgen = bfs_paths(path, i, exits)
        for augpath in augpathgen:
            flows = [path[augpath[j]][augpath[j+1]] for j in range(len(augpath)-1)]
            ...



-- 
Steve

From steve at pearwood.info  Wed Feb 15 18:17:13 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 16 Feb 2017 10:17:13 +1100
Subject: [Tutor] Need help with one problem.
In-Reply-To: <7D4CBC9F-B925-4D70-8847-184CB5264E6D@gmail.com>
References: <7D4CBC9F-B925-4D70-8847-184CB5264E6D@gmail.com>
Message-ID: <20170215231713.GH5689@ando.pearwood.info>

On Wed, Feb 15, 2017 at 01:00:30PM -0500, Adam Howlett wrote:

> Write an if-else statement that assigns 20 to the variable y if the 
> variable x is greater than 100. Otherwise, it should assign 0 to the 
> variable y.
> 
> Is there an easy way to solve this problem?

Yes. What have you tried?


Hint: here's a similar problem.

"Write an if-else statement that assigns "Hello" to the variable q if 
the variable p is equal to 11. Otherwise it should assign "Goodbye" to 
the variable q."

And here's the answer:

if p == 11:
    q = "Hello"
else:
    q = "Goodbye"


Can you see the pattern? Can you follow that same pattern for your own 
question?


(Hint: use > for "greater than".)


-- 
Steve

From jf_byrnes at comcast.net  Wed Feb 15 20:18:48 2017
From: jf_byrnes at comcast.net (Jim)
Date: Wed, 15 Feb 2017 19:18:48 -0600
Subject: [Tutor] Please explain part of this code
In-Reply-To: <o82mad$qch$1@blaine.gmane.org>
References: <o82l7j$418$1@blaine.gmane.org> <o82mad$qch$1@blaine.gmane.org>
Message-ID: <o82uli$mej$1@blaine.gmane.org>

On 02/15/2017 04:56 PM, Alan Gauld via Tutor wrote:
> On 15/02/17 22:37, Jim wrote:
>
>>          self.choices = {
>>                  "1": self.show_notes,
>>                  "2": self.search_notes,
>>                  "3": self.add_note,
>>                  "4": self.modify_note,
>>                  "5": self.quit
>>                  }
>>
>> The author says:
>>
>> The action variable actually refers to a specific method and is called
>> by appending empty brackets (since none of the methods require
>> parameters) to the variable.
>>
>
>> I don't recall ever seeing this before.  What is this technique called?
>
> Its very common, especially in GUIs and used in many
> languages including C, VB, Java, Javascript and Lisp.
> Its usually called a callback (because the stored
> function is called back by the event receiver).
>
> In C it is done by using a "pointer to a function".
> In Lisp you create a Lambda (an anonymous function)
> - which you can also do in Python and recent Java
> versions. In Smalltalk and Ruby you define a "block".
> In most of the other languages it's similar to Python,
> you just pass the name of the function.
>
> This is often referred to as the language treating
> functions as "first class objects", and is a core
> part of Functional Programming.
>
> A common FP structure is the map function which takes
> a function and a sequence and applies the function
> to each member of the sequence, returning the
> resultant sequence. Here is a short Python example:
>
> def double(x): return x*2
>
> data = [1,2,3,4]
> result = map(double, data)   # -> [2,4,6,8]
> print(result)
>
> HTH
>
It does help. I have done a little bit of tkinter programing and have 
used callbacks, but when I looked at this code it just didn't register 
that way in my mind. Thanks for your explanation.

Regards,  Jim


From allantanaka11 at yahoo.com  Thu Feb 16 08:26:08 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Thu, 16 Feb 2017 13:26:08 +0000 (UTC)
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
References: <1198682978.514330.1487251568223.ref@mail.yahoo.com>
Message-ID: <1198682978.514330.1487251568223@mail.yahoo.com>

Not completely sure why it doesn't open the chart on the web browser when i type this in the windows command prompt (cmd)?python -m SimpleHTTPServer port 80.So first i type?python ml.py data/sample.csv in cmd windows and then?python -m SimpleHTTPServer port 80, but it's not proceeding to the graph in html??
See attached image for screenshoot and complete .py file

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: ml.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20170216/94e7a091/attachment.ksh>

From alan.gauld at yahoo.co.uk  Thu Feb 16 17:09:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 16 Feb 2017 22:09:27 +0000
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <1198682978.514330.1487251568223@mail.yahoo.com>
References: <1198682978.514330.1487251568223.ref@mail.yahoo.com>
 <1198682978.514330.1487251568223@mail.yahoo.com>
Message-ID: <o857uh$9b7$1@blaine.gmane.org>

There are several issues here, I'll try to address
them separately below...

On 16/02/17 13:26, Allan Tanaka via Tutor wrote:
> Not completely sure why it doesn't open the chart on the web browser 

You haven't shown us chart.html so we can't guess how your data
in ticks.json is supposed to get into charts.html to be displayed.
Does ticks.json exist and does it look like you expect?
If so its probably not a Python problem but a web one.

> when i type this in the windows command prompt (cmd) 
> python -m SimpleHTTPServer port 80.

Your code says you are using port 8000:

    print "Done. Goto 0.0.0.0:8000/chart.html"

Which is it?

> So first i type python ml.py data/sample.csv in cmd 
> windows and then python -m SimpleHTTPServer port 80, 
> but it's not proceeding to the graph in html??
> 

> See attached image for screenshoot and complete .py file

This is a text based list so attachments, especially
binary files like images,  are usually strippped out.
I can see the .py file but that's all. Can you post
the image on a web site somewhere and send a link?
Or if its text just cut n paste into a mail?

I can't really comment much as its mostly numpy, pandas
and sklearn code which are all a bit off-topic for
this list.

But we need a bit more about the environment to
figure out where the issue lie.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From poojabhalode11 at gmail.com  Fri Feb 17 13:31:34 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Fri, 17 Feb 2017 13:31:34 -0500
Subject: [Tutor] Select and deselect for multiple checkboxes in Tkinter
Message-ID: <CAK0ikxcRFWKq+zdJ+mCi4rmzSxdZ+Gm9M4ZQ5mBfqu8X-UnkDw@mail.gmail.com>

Hi,

I am writing to create two buttons, for selecting and de-selecting multiple
checkboxes that I have created previously. These checkboxes have different
variables that they are associated with for their values and thus cannot
create a loop for the same.

Is there any way that I could create the above-mentioned buttons, without
having to manually select/deselect each checkbox under a select/deselect
function associated with the buttons?

Checkboxes are as shown below:
Checkbutton(paramroot, text = "K_eq", variable = keqparam).grid(row = 2,
column = 1, sticky = W)
Checkbutton(paramroot, text = "Hrxn", variable = delHrxnparam).grid(row =
3, column = 1, sticky = W)
Checkbutton(paramroot, text = "Kf", variable = kfparam).grid(row = 4,
column = 1, sticky = W)
Checkbutton(paramroot, text = "Af", variable = Afparam).grid(row = 5,
column = 1, sticky = W)
Checkbutton(paramroot, text = "k", variable = ksimparam).grid(row = 11,
column = 1, sticky = W)
Checkbutton(paramroot, text = "A", variable = Aparam).grid(row = 12, column
= 1, sticky = W)

Checkbutton(paramroot, text = "Reactant A", variable = RAparam).grid(row =
13, column = 2, sticky = W)
Checkbutton(paramroot, text = "Reactant B", variable = RBparam).grid(row =
14, column = 2, sticky = W)
Checkbutton(paramroot, text = "Reactant C", variable = RCparam).grid(row =
15, column = 2, sticky = W)

Please let me know.
Thank you

Pooja

From alan.gauld at yahoo.co.uk  Fri Feb 17 20:23:08 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 18 Feb 2017 01:23:08 +0000
Subject: [Tutor] Select and deselect for multiple checkboxes in Tkinter
In-Reply-To: <CAK0ikxcRFWKq+zdJ+mCi4rmzSxdZ+Gm9M4ZQ5mBfqu8X-UnkDw@mail.gmail.com>
References: <CAK0ikxcRFWKq+zdJ+mCi4rmzSxdZ+Gm9M4ZQ5mBfqu8X-UnkDw@mail.gmail.com>
Message-ID: <o887lm$vdg$1@blaine.gmane.org>

On 17/02/17 18:31, Pooja Bhalode wrote:

> I am writing to create two buttons, for selecting and de-selecting multiple
> checkboxes that I have created previously. These checkboxes have different
> variables that they are associated with for their values and thus cannot
> create a loop for the same.

You can still use a loop by putting the variables in
a list/tuple:

checkboxVars = [keqparam,delHrxnparam,kfparam,Afparam....,RCparam]

for var in checkboxVars:
    var = 0  #or whatever.

You can even use different reset values if necessary
by putting them in tuples:

checkboxVars = [(keqparam,0),(delHrxnparam,1),
                (kfparam,2),(Afparam....,
                 ...(RCparam,42)]

for var,val in checkboxVars:
    var = val  #or whatever.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From allantanaka11 at yahoo.com  Fri Feb 17 23:46:00 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Sat, 18 Feb 2017 04:46:00 +0000 (UTC)
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
Message-ID: <1900243490.5668.1487393160443@mail.yahoo.com>

Not completely sure why it doesn't open the chart on the web browser when i type this in the windows command prompt (cmd)?python -m SimpleHTTPServer port 80.So first i type?python ml.py data/sample.csv in cmd windows and then?python -m SimpleHTTPServer port 80, but it's not proceeding to the graph in html??
See attached image for screenshoot and complete .py file

From alan.gauld at yahoo.co.uk  Sat Feb 18 04:35:09 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 18 Feb 2017 09:35:09 +0000
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <1900243490.5668.1487393160443@mail.yahoo.com>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
Message-ID: <o894g7$b3b$1@blaine.gmane.org>


Please don't repeat post. We saw it the first time.
Please do post again with the extra information requested.

On 18/02/17 04:46, Allan Tanaka via Tutor wrote:
> Not completely sure why it doesn't open the chart on the web browser when i type this in the windows command prompt (cmd) python -m SimpleHTTPServer port 80.So first i type python ml.py data/sample.csv in cmd windows and then python -m SimpleHTTPServer port 80, but it's not proceeding to the graph in html??
> See attached image for screenshoot and complete .py file

One extra piece of information is how do you try to access the chart?
What url are you typing into ytour browser?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From poojabhalode11 at gmail.com  Sat Feb 18 09:34:21 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sat, 18 Feb 2017 09:34:21 -0500
Subject: [Tutor] Select and deselect for multiple checkboxes in Tkinter
In-Reply-To: <o887lm$vdg$1@blaine.gmane.org>
References: <CAK0ikxcRFWKq+zdJ+mCi4rmzSxdZ+Gm9M4ZQ5mBfqu8X-UnkDw@mail.gmail.com>
 <o887lm$vdg$1@blaine.gmane.org>
Message-ID: <CAK0ikxcziVCUwAAT3fU23XuvFmjVWMSZ7mhfYDDFqzNehC7=sg@mail.gmail.com>

Hi Alan,

Thank you for your input. That was an easy fix to it.
Thanks a lot.

Pooja

On Fri, Feb 17, 2017 at 8:23 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 17/02/17 18:31, Pooja Bhalode wrote:
>
> > I am writing to create two buttons, for selecting and de-selecting
> multiple
> > checkboxes that I have created previously. These checkboxes have
> different
> > variables that they are associated with for their values and thus cannot
> > create a loop for the same.
>
> You can still use a loop by putting the variables in
> a list/tuple:
>
> checkboxVars = [keqparam,delHrxnparam,kfparam,Afparam....,RCparam]
>
> for var in checkboxVars:
>     var = 0  #or whatever.
>
> You can even use different reset values if necessary
> by putting them in tuples:
>
> checkboxVars = [(keqparam,0),(delHrxnparam,1),
>                 (kfparam,2),(Afparam....,
>                  ...(RCparam,42)]
>
> for var,val in checkboxVars:
>     var = val  #or whatever.
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From Angelica.Bruhnke at trojans.dsu.edu  Sat Feb 18 16:28:56 2017
From: Angelica.Bruhnke at trojans.dsu.edu (Bruhnke, Angelica)
Date: Sat, 18 Feb 2017 21:28:56 +0000
Subject: [Tutor] Using numpy stack functions
Message-ID: <1487453335927.81326@trojans.dsu.edu>

Hi,


I'm new to python programming so this question will probably be a no brainer for the experienced programmer. I'm trying to create a 10x10 array of zeros and then framing it with a border of ones.


Output should look like this:

[[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]

[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]



This is the code I've written:

a = np.ones ((1,10))

print a

b = np.zeros ((10,10))

print b

c = np.vstack ((b,a))

print c


This is my output:

[[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]?

As you can see I have too many zeros once I stack them and don't have the ones framing the sides vertically.

Any guidance on where I'm going astray?

Much appreciated,

A.B.



From joseph.c.slater at gmail.com  Sat Feb 18 16:52:23 2017
From: joseph.c.slater at gmail.com (Joseph Slater)
Date: Sat, 18 Feb 2017 16:52:23 -0500
Subject: [Tutor] SciPy Optimize-like calling function as string
Message-ID: <0C99AB99-06A8-4338-A5C7-34CAF4600050@gmail.com>

I'm trying to use the scipy.optimize code as an example to be able to avoid using *eval* to call a function named by a string. 

The following appears to be the code used to do this:
# from scipy optimize
> def wrap_function(function, args):
>     ncalls = [0]
>     if function is None:
>         return ncalls, None
> 
>     def function_wrapper(*wrapper_args):
>         ncalls[0] += 1
>         print(type(function))
>         return function(*(wrapper_args + args))
> 
>     return ncalls, function_wrapper


where I should be able to use it to make the following work:

> def sqr(x):
>     return x**2.
> 
> 
> func = 'sqr'
> 
> args=()
> fcalls, func = wrap_function(func, args)
> 
> x=3
> func(x)

where I get:

> <class 'str'>
> 
> ---------------------------------------------------------------------------
> TypeError
>                                  Traceback (most recent call last)
> 
> <ipython-input-32-832f2a14d895> in <module>()
>       7 
>       8 x=3
> ----> 9 func(x)
> 
> 
> 
> <ipython-input-19-6f99e62c64af> in function_wrapper(*wrapper_args)
>       8         ncalls[0] += 1
>       9         print(type(function))
> ---> 10         return function(*(wrapper_args + args))
>      11 
>      12     return ncalls, function_wrapper
> 
> 
> 
> TypeError: 'str' object is not callable


This works in *optimize* but not for me. What am I missing?

I've seen this done with dictionaries on some pages, but it seems that this is intended to be faster (which will become necessary for me in the future). 

Thanks,
Joe





From poojabhalode11 at gmail.com  Sat Feb 18 11:27:55 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sat, 18 Feb 2017 11:27:55 -0500
Subject: [Tutor] Problems with matplotlib
Message-ID: <CAK0ikxfuPMm4sv260Xxxx8EqO0gkCLxH+q0UpOjSYyRTXA+QzA@mail.gmail.com>

Hi,

I am trying to create a simple normal plot. But I am getting some
errors which I am not able to understand. Would be a great help if someone
can guide me to what I am doing wrong.

Thankyou so much.
Here is the code:

# import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
(Here, I have tried both these import statements, but both give me the same
error.)

x = [1,2,4,5,6,8,9,10]
y = [6,7,8,9,10,11,12,14]
plt.figure()
plt.plot(x,y)
plt.show()

Error:

/Users/poojabhalode/.bash_profile: line 1: .bashrc: No such file or
directory
Traceback (most recent call last):
  File "/Users/poojabhalode/Google Drive/GUI Python/matplot.py", line 3, in
<module>
    from matplotlib import pyplot as plt
  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
line 123, in <module>
    import pyparsing
  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pyparsing.py",
line 3260, in <module>
    _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate")
+ Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") +
"]"
  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pyparsing.py",
line 775, in setResultsName
    newself = self.copy()
  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pyparsing.py",
line 749, in copy
    cpy = copy.copy( self )
AttributeError: 'module' object has no attribute 'copy'
[Finished in 2.4s with exit code 1]
[shell_cmd: python -u "/Users/poojabhalode/Google Drive/GUI
Python/matplot.py"]
[dir: /Users/poojabhalode/Google Drive/GUI Python]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

I am running this on the inbuilt python in Mac10.12
When I try running the same in terminal it works, but here it is not able
to compile.
Please let me know.

Thankyou.

Pooja

From alan.gauld at yahoo.co.uk  Sat Feb 18 18:21:10 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 18 Feb 2017 23:21:10 +0000
Subject: [Tutor] SciPy Optimize-like calling function as string
In-Reply-To: <0C99AB99-06A8-4338-A5C7-34CAF4600050@gmail.com>
References: <0C99AB99-06A8-4338-A5C7-34CAF4600050@gmail.com>
Message-ID: <o8akt0$d3e$1@blaine.gmane.org>

On 18/02/17 21:52, Joseph Slater wrote:
> I'm trying to use the scipy.optimize code ...
> I've seen this done with dictionaries on some pages, 
> but it seems that this is intended to be faster

There is a saying in programming that premature
optimization is the root of all evil.

If you don't know that you need to optimize then your
time is usually better spent elsewhere. Dictionaries
are pretty fast in Python and I'd suggest you try
that first before shaving milliseconds in places
that may not be where you need to make savings.

Identify an actual problem, then identify the cause
and optimise that. Don't try to second guess the future.
Most performance problems are down to bad algorithms
or bad data structures not bad dispatch techniques.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Sat Feb 18 19:18:33 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Feb 2017 01:18:33 +0100
Subject: [Tutor] Using numpy stack functions
References: <1487453335927.81326@trojans.dsu.edu>
Message-ID: <o8ao8k$dje$1@blaine.gmane.org>

Bruhnke, Angelica wrote:

> I'm new to python programming so this question will probably be a no
> brainer for the experienced programmer. I'm trying to create a 10x10 array
> of zeros and then framing it with a border of ones.

So the final array is 12x12.

> 
> Output should look like this:
> 
> [[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
> 
> [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]
> 
> 
> 
> This is the code I've written:
> 
> a = np.ones ((1,10))
> 
> print a
> 
> b = np.zeros ((10,10))
> 
> print b
> 
> c = np.vstack ((b,a))
> 
> print c
> 
> 
> This is my output:
> 
> [[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]
> [[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
> [[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
>  [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]?
> 
> As you can see I have too many zeros once I stack them and don't have the
> ones framing the sides vertically.
> 
> Any guidance on where I'm going astray?

Below I'm using the dimensions 4x4. To get

1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1

you can vstack()

>>> np.vstack(([1,1], [[0,0],[0,0]], [1,1]))
array([[1, 1],
       [0, 0],
       [0, 0],
       [1, 1]])

and use hstack() to add ones to the sides:

>>> side = [[1]]*4
>>> np.hstack((side, mid, side))
array([[1, 1, 1, 1],
       [1, 0, 0, 1],
       [1, 0, 0, 1],
       [1, 1, 1, 1]])

The same with ones() and zeros(), put into a function:

>>> def frame(N):
...     horz = np.ones((1, N))
...     inner = np.zeros((N, N))
...     vert = np.ones((N+2, 1))
...     mid = np.vstack((horz, inner, horz))
...     return np.hstack((vert, mid, vert))
... 
>>> frame(3)
array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]])
>>> frame(1)
array([[ 1.,  1.,  1.],
       [ 1.,  0.,  1.],
       [ 1.,  1.,  1.]])

Personally I'd probably use a simpler approach. Start with all ones and then 
set the inner values to 0:

>>> def frame2(N):
...     a = np.ones((N+2, N+2))
...     a[1: -1, 1: -1] = 0
...     return a
... 
>>> frame2(2)
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  1.],
       [ 1.,  1.,  1.,  1.]])



From __peter__ at web.de  Sat Feb 18 19:32:40 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Feb 2017 01:32:40 +0100
Subject: [Tutor] Problems with matplotlib
References: <CAK0ikxfuPMm4sv260Xxxx8EqO0gkCLxH+q0UpOjSYyRTXA+QzA@mail.gmail.com>
Message-ID: <o8ap32$tbe$1@blaine.gmane.org>

Pooja Bhalode wrote:

> Hi,
> 
> I am trying to create a simple normal plot. But I am getting some
> errors which I am not able to understand. Would be a great help if someone
> can guide me to what I am doing wrong.
> 
> Thankyou so much.
> Here is the code:
> 
> # import matplotlib.pyplot as plt
> from matplotlib import pyplot as plt
> (Here, I have tried both these import statements, but both give me the
> same error.)
> 
> x = [1,2,4,5,6,8,9,10]
> y = [6,7,8,9,10,11,12,14]
> plt.figure()
> plt.plot(x,y)
> plt.show()
> 
> Error:
> 
> /Users/poojabhalode/.bash_profile: line 1: .bashrc: No such file or
> directory
> Traceback (most recent call last):
>   File "/Users/poojabhalode/Google Drive/GUI Python/matplot.py", line 3,
>   in
> <module>
>     from matplotlib import pyplot as plt
>   File
> 
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
> line 123, in <module>
>     import pyparsing
>   File
> 
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pyparsing.py",
> line 3260, in <module>
>     _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate")
> + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") +
> "]"
>   File
> 
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pyparsing.py",
> line 775, in setResultsName
>     newself = self.copy()
>   File
> 
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pyparsing.py",
> line 749, in copy
>     cpy = copy.copy( self )
> AttributeError: 'module' object has no attribute 'copy'
> [Finished in 2.4s with exit code 1]
> [shell_cmd: python -u "/Users/poojabhalode/Google Drive/GUI
> Python/matplot.py"]
> [dir: /Users/poojabhalode/Google Drive/GUI Python]
> [path: /usr/bin:/bin:/usr/sbin:/sbin]
> 
> I am running this on the inbuilt python in Mac10.12
> When I try running the same in terminal it works, but here it is not able
> to compile.
> Please let me know.

You have a file copy.py, probably written by yourself, that shades the copy 
module in Python's standard library. To locate this module (if it is not in 
the current working directory) add the lines

import copy
print copy.__file__

If I'm guessing right everything should work after you have removed the pyc-
file and renamed the corresponding copy.py.


From __peter__ at web.de  Sat Feb 18 19:50:34 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Feb 2017 01:50:34 +0100
Subject: [Tutor] SciPy Optimize-like calling function as string
References: <0C99AB99-06A8-4338-A5C7-34CAF4600050@gmail.com>
Message-ID: <o8aq4k$re3$1@blaine.gmane.org>

Joseph Slater wrote:

> I'm trying to use the scipy.optimize code as an example to be able to
> avoid using *eval* to call a function named by a string.
> 
> The following appears to be the code used to do this:

No, wrap_function wraps an existing function, adds some extra args, and 
provides a way to keep track of the number of invocations. For example:

>>> def wrap_function(function, args):
...     ncalls = [0]
...     if function is None:
...         return ncalls, None
...     def function_wrapper(*wrapper_args):
...         ncalls[0] += 1
...         print(type(function))
...         return function(*(wrapper_args + args))
...     return ncalls, function_wrapper
... 
>>> def demo(*args):
...     print("demo() called with", args)
... 
>>> f = wrap_function(demo, ("one", "two"))
>>> calls, func = wrap_function(demo, ("one", "two"))
>>> calls
[0]
>>> func("x", "y")
<class 'function'>
demo() called with ('x', 'y', 'one', 'two')
>>> calls
[1]
>>> func()
<class 'function'>
demo() called with ('one', 'two')
>>> calls
[2]

To get a function in the current module from its name use globals():

>>> def square(x):
...     return x*x
... 
>>> def twice(x):
...     return 2*x
... 
>>> f = globals()["square"]
>>> f(3)
9
>>> f = globals()["twice"]
>>> f(3)
6

For a function in an external module try getattr():

>>> import os.path
>>> f = getattr(os.path, "join")
>>> f("foo", "bar")
'foo/bar'



From poojabhalode11 at gmail.com  Sat Feb 18 20:00:17 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sat, 18 Feb 2017 20:00:17 -0500
Subject: [Tutor] Problems with matplotlib
In-Reply-To: <o8ap32$tbe$1@blaine.gmane.org>
References: <CAK0ikxfuPMm4sv260Xxxx8EqO0gkCLxH+q0UpOjSYyRTXA+QzA@mail.gmail.com>
 <o8ap32$tbe$1@blaine.gmane.org>
Message-ID: <CAK0ikxc1uZ-DAjGZsFWY-MYAgkaRAnzMhMhj0mnq+Q_KNOqYdg@mail.gmail.com>

Hi Peter,

Thank you for that advice, that worked after I deleted the copy.py that I
had created.

Hope you are having a great weekend.

Thanks
Pooja

On Sat, Feb 18, 2017 at 7:32 PM, Peter Otten <__peter__ at web.de> wrote:

> Pooja Bhalode wrote:
>
> > Hi,
> >
> > I am trying to create a simple normal plot. But I am getting some
> > errors which I am not able to understand. Would be a great help if
> someone
> > can guide me to what I am doing wrong.
> >
> > Thankyou so much.
> > Here is the code:
> >
> > # import matplotlib.pyplot as plt
> > from matplotlib import pyplot as plt
> > (Here, I have tried both these import statements, but both give me the
> > same error.)
> >
> > x = [1,2,4,5,6,8,9,10]
> > y = [6,7,8,9,10,11,12,14]
> > plt.figure()
> > plt.plot(x,y)
> > plt.show()
> >
> > Error:
> >
> > /Users/poojabhalode/.bash_profile: line 1: .bashrc: No such file or
> > directory
> > Traceback (most recent call last):
> >   File "/Users/poojabhalode/Google Drive/GUI Python/matplot.py", line 3,
> >   in
> > <module>
> >     from matplotlib import pyplot as plt
> >   File
> >
> "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/matplotlib/__init__.py",
> > line 123, in <module>
> >     import pyparsing
> >   File
> >
> "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/pyparsing.py",
> > line 3260, in <module>
> >     _reBracketExpr = Literal("[") + Optional("^").setResultsName("
> negate")
> > + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") +
> > "]"
> >   File
> >
> "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/pyparsing.py",
> > line 775, in setResultsName
> >     newself = self.copy()
> >   File
> >
> "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/pyparsing.py",
> > line 749, in copy
> >     cpy = copy.copy( self )
> > AttributeError: 'module' object has no attribute 'copy'
> > [Finished in 2.4s with exit code 1]
> > [shell_cmd: python -u "/Users/poojabhalode/Google Drive/GUI
> > Python/matplot.py"]
> > [dir: /Users/poojabhalode/Google Drive/GUI Python]
> > [path: /usr/bin:/bin:/usr/sbin:/sbin]
> >
> > I am running this on the inbuilt python in Mac10.12
> > When I try running the same in terminal it works, but here it is not able
> > to compile.
> > Please let me know.
>
> You have a file copy.py, probably written by yourself, that shades the copy
> module in Python's standard library. To locate this module (if it is not in
> the current working directory) add the lines
>
> import copy
> print copy.__file__
>
> If I'm guessing right everything should work after you have removed the
> pyc-
> file and renamed the corresponding copy.py.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From marie_e_shaw at yahoo.co.uk  Sun Feb 19 11:34:21 2017
From: marie_e_shaw at yahoo.co.uk (Marie Shaw)
Date: Sun, 19 Feb 2017 16:34:21 +0000 (UTC)
Subject: [Tutor] Resources/Books for teaching OOP in Python and Tkinter
References: <612750075.974560.1487522061075.ref@mail.yahoo.com>
Message-ID: <612750075.974560.1487522061075@mail.yahoo.com>

I am a teacher of 16-18 year olds. Since September, my classes have been learning to program in Python, using all of the basics in console mode.
I now need to teach them OOP using Python, and GUI programming using Python.
Please could someone one point me in the direction of a good book, or some good teaching resources.
I already have Python for the Absolute Beginner, by Michael Dawson, and Python in Easy Steps, by Michael McGrath. I like these books and have covered the relevant chapters in them. However, I need to learn more.
Thanks, Marie.

From poojabhalode11 at gmail.com  Sun Feb 19 11:18:02 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sun, 19 Feb 2017 11:18:02 -0500
Subject: [Tutor] Creating tables in Tkinter
Message-ID: <CAK0ikxc05-Ha0mVYY0j2xg6118boBMSGRQPv_oRC7M_SVQHppg@mail.gmail.com>

Hi,

I am trying to create a simple table. But I was wondering how do I get the
title of the table to span over multiple columns in the first row.
Code:

from Tkinter import *

root = Tk()
root.geometry("700x500")
Label(root, text = "Table 1").grid(row = 0, column = 0, sticky = W)
Label
for i in range(1,11):

Label(root, text = i).grid(row = 1, column = i+1, sticky = W)
Label(root, text = i).grid(row = i+1, column = 0, sticky = W)

for j in range(1, 11):
Label(root, text = i*j).grid(row= i+1, column = j+1, sticky = W)
root.mainloop()

It opens a Tkinter window:
[image: Inline image 1]
So, here, how do I make the Table 1 span over the column range, or insert a
title: Table 1 multiplication table such that it doesn't affect the spacing
below. I am using grid packing in the code.

Also, how to make the labels for columns and rows: such that the labels are
placed in the centre of the range.

Thank you so much.

Pooja

From poojabhalode11 at gmail.com  Sun Feb 19 14:36:32 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sun, 19 Feb 2017 14:36:32 -0500
Subject: [Tutor] Matplotlib in Tkinter
Message-ID: <CAK0ikxdNMUWjzi2P-5fZtwE1mP--+w7KeBAtg7VhyLEZCc9M9A@mail.gmail.com>

Hi,

I am trying to create a graph in Tkinter window. And following is a snipet
of the code.

Code:
  simroot = Toplevel(root)
simroot.title("Simulation of experiments")
Label(simroot, text = "Displaying concentration profiles with respect to
time:").pack(side = TOP)

Label(simroot, text = "Select the experiments to be displayed: ").pack(side
= TOP)
optionexp = ['Experiment 1', 'Experiment 2', 'Experiment 3', 'Experiment
4', 'Experiment 5']
expsim = StringVar()
dropexp = OptionMenu(simroot, expsim, *optionexp)
dropexp.pack(side = TOP)
dropexp.config(width = 15)

# Row 1 would print the name of the experiment selected and the species
displayed would be in row3.
Label(simroot, text = "Select concentration species:").pack(side = TOP)
concsim = StringVar()
optionlistsim = ['A', 'B', 'C', 'D', 'E']
dropsim = OptionMenu(simroot, concsim, *optionlistsim)
dropsim.pack(side = TOP)
dropsim.config(width = 8)
Label(simroot, text = "").pack(side = LEFT)

def Submitplot():
print "Create plot"

f = Figure(figsize = (5,5), dpi = 80)
a = f.add_subplot(111)
a.plot([1,2,3,4,5],[10,11,12,14,15])

canvas = FigureCanvasTkAgg(f, simroot)
canvas.show()
canvas.get_tk_widget().pack(side = BOTTOM)

toolbar = NavigationToolbar2TkAgg(canvas, simroot)
toolbar.update()
canvas._tkcanvas.pack(side = BOTTOM)
Button(simroot, text = "Submit and Plot", command = Submitplot).pack(side =
BOTTOM)

Here, the output comes as:
[image: Inline image 1]
The problem is I am not able to use grid layout instead of pack (used
here). I want to place the text to the left, top side in the window.

Also, when I hover the mouse over the figure and the x and y values are
shown, it flickers really fast and the white space in the Tkinter window
turns black when it flickers. Can someone please tell me what the issue
could be? Also, the toolbar should have been at the bottom but it shows up
at the top.

I am using pack in this Toplevel of the main root whereas in the rest of
the code, I am using grid layout. I switched to pack for this
snipet because I could not figure out how grid would work for this part.

Can someone please let me know how to correct these issues?
Thankyou so much.

Pooja

From jpvaren at icloud.com  Sun Feb 19 21:05:35 2017
From: jpvaren at icloud.com (Juan Pablo Valladares)
Date: Sun, 19 Feb 2017 23:05:35 -0300
Subject: [Tutor]  convert an integer number to string.
Message-ID: <98D772AD-73CA-4B73-8639-5ADE6330D17A@icloud.com>

hi friend.

i send you this email for say you you have a great project with the python correctos, i dont know if you can help me with one code i try to make  functionality but not work i wish can you help me, thank you and than you again, to following the line with the error:

for i in range (10):
            cmds.button(label ="button", + srt(i+1))

thank you dude.

JP

From steve at pearwood.info  Mon Feb 20 04:36:58 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 20 Feb 2017 20:36:58 +1100
Subject: [Tutor] convert an integer number to string.
In-Reply-To: <98D772AD-73CA-4B73-8639-5ADE6330D17A@icloud.com>
References: <98D772AD-73CA-4B73-8639-5ADE6330D17A@icloud.com>
Message-ID: <20170220093658.GT5689@ando.pearwood.info>

On Sun, Feb 19, 2017 at 11:05:35PM -0300, Juan Pablo Valladares wrote:
> hi friend.
> 
> i send you this email for say you you have a great project with the python correctos, i dont know if you can help me with one code i try to make  functionality but not work i wish can you help me, thank you and than you again, to following the line with the error:
> 
> for i in range (10):
>             cmds.button(label ="button", + srt(i+1))

I see two errors:

You write "srt" instead of str.

Comma after "button" is not needed.

    cmds.button(label ="button" + srt(i+1))

may be better.



-- 
Steve

From alan.gauld at yahoo.co.uk  Mon Feb 20 04:57:08 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 20 Feb 2017 09:57:08 +0000
Subject: [Tutor] convert an integer number to string.
In-Reply-To: <20170220093658.GT5689@ando.pearwood.info>
References: <98D772AD-73CA-4B73-8639-5ADE6330D17A@icloud.com>
 <20170220093658.GT5689@ando.pearwood.info>
Message-ID: <o8eehe$gob$1@blaine.gmane.org>

On 20/02/17 09:36, Steven D'Aprano wrote:

> Comma after "button" is not needed.
> 
>     cmds.button(label ="button" + srt(i+1))
> 
> may be better.

and
     cmds.button(label ="button" + str(i+1))

better still :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 20 05:00:50 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 20 Feb 2017 10:00:50 +0000
Subject: [Tutor] Creating tables in Tkinter
In-Reply-To: <CAK0ikxc05-Ha0mVYY0j2xg6118boBMSGRQPv_oRC7M_SVQHppg@mail.gmail.com>
References: <CAK0ikxc05-Ha0mVYY0j2xg6118boBMSGRQPv_oRC7M_SVQHppg@mail.gmail.com>
Message-ID: <o8eeoc$ngj$1@blaine.gmane.org>

On 19/02/17 16:18, Pooja Bhalode wrote:
> Hi,
> 
> I am trying to create a simple table. But I was wondering how do I get the
> title of the table to span over multiple columns in the first row.
> Code:
> 
> from Tkinter import *
> 
> root = Tk()
> root.geometry("700x500")
> Label(root, text = "Table 1").grid(row = 0, column = 0, sticky = W)

grid has many attributes, you can see them using the help() function:
-------------
Help on function grid_configure in module tkinter:

grid_configure(self, cnf={}, **kw)
    Position a widget in the parent widget in a grid. Use as options:
    column=number - use cell identified with given column
                    (starting with 0)
    columnspan=number - this widget will span several columns
    in=master - use master to contain this widget
    in_=master - see 'in' option description
    ipadx=amount - add internal padding in x direction
    ipady=amount - add internal padding in y direction
    padx=amount - add padding in x direction
    pady=amount - add padding in y direction
    row=number - use cell identified with given row (starting with 0)
    rowspan=number - this widget will span several rows
    sticky=NSEW - if cell is larger on which sides will this
                  widget stick to the cell boundary
-----------------

Notice the columnspan option.
set it to the number of columns in your table.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 20 05:11:37 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 20 Feb 2017 10:11:37 +0000
Subject: [Tutor] Resources/Books for teaching OOP in Python and Tkinter
In-Reply-To: <612750075.974560.1487522061075@mail.yahoo.com>
References: <612750075.974560.1487522061075.ref@mail.yahoo.com>
 <612750075.974560.1487522061075@mail.yahoo.com>
Message-ID: <o8efcj$be$1@blaine.gmane.org>

On 19/02/17 16:34, Marie Shaw via Tutor wrote:
> I am a teacher of 16-18 year olds. 
> I now need to teach them OOP using Python, 

> and GUI programming using Python.

Those are two different topics, although most GUIs
are easier if used with OOP.

However, most tutorials (including mine) teach the basic
syntax and usage of OOP so I'm not sure what extra
information you need. It may e that a basic OOP text
would be better - something like Timothy Budd's
excellent intro(which uses Java) or even "UML Distilled"
by Fowler which uses the UML design language. These
both show how classes and objects should be used
rather than just focussing on the syntax.

As for GUI programming, if we assume you stick
with Tkinter for now as it comes with Python and,
although limited, is easy to learn, there are several
options. The Tkinter page in the official documentation
gives several online links.

For books there are a few. The massive "Programming
Python" tome by Lutz has about 400 pages dedicated
to Tkinter. My own books(and web tutor) both have
a (much shorter) chapter on it.
Several other tutorials cover it too:

Python, How to program by Dietel
Teach Yourself Python in 24 hours

and, if you can find it,
Python & Tkinter programming by Grayson goes into
great detail.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From mail at timgolden.me.uk  Mon Feb 20 05:29:30 2017
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 20 Feb 2017 10:29:30 +0000
Subject: [Tutor] Resources/Books for teaching OOP in Python and Tkinter
In-Reply-To: <612750075.974560.1487522061075@mail.yahoo.com>
References: <612750075.974560.1487522061075.ref@mail.yahoo.com>
 <612750075.974560.1487522061075@mail.yahoo.com>
Message-ID: <d2c7cdf7-f546-dfd0-0389-b3d274440136@timgolden.me.uk>

On 19/02/2017 16:34, Marie Shaw via Tutor wrote:
> I am a teacher of 16-18 year olds. Since September, my classes have
> been learning to program in Python, using all of the basics in
> console mode. I now need to teach them OOP using Python, and GUI
> programming using Python. Please could someone one point me in the
> direction of a good book, or some good teaching resources. I already
> have Python for the Absolute Beginner, by Michael Dawson, and Python
> in Easy Steps, by Michael McGrath. I like these books and have
> covered the relevant chapters in them. However, I need to learn
> more.

Have you tried the Computing At School forums, Marie? (I assume you're 
UK-based from your address and the fact that you're teaching Python in 
Years 11-13). There are quite a few resources there already, but you can 
always start a thread in, eg, the Secondary Education forum.

Here are a couple of links, but you'll need to have registered with CaS 
to view them.

http://community.computingatschool.org.uk/search/resources?action=search&controller=search&query=tkinter&utf8=%E2%9C%93

http://community.computingatschool.org.uk/forums/23

Also, see GUI Zero by a former teacher who now works with the RPi 
Foundation:

https://codeboom.wordpress.com/2017/01/07/gui-zero-making-python-guis-really-simple/

TJG

From robertvstepp at gmail.com  Mon Feb 20 07:38:21 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 20 Feb 2017 06:38:21 -0600
Subject: [Tutor] Resources/Books for teaching OOP in Python and Tkinter
In-Reply-To: <612750075.974560.1487522061075@mail.yahoo.com>
References: <612750075.974560.1487522061075.ref@mail.yahoo.com>
 <612750075.974560.1487522061075@mail.yahoo.com>
Message-ID: <CANDiX9+D7e99+Y+90YXuXPcVj=_xE1ETAyW4wHqtMNHat6s7oQ@mail.gmail.com>

On Sun, Feb 19, 2017 at 10:34 AM, Marie Shaw via Tutor <tutor at python.org> wrote:
> I am a teacher of 16-18 year olds. Since September, my classes have been learning to program in Python, using all of the basics in console mode.
> I now need to teach them OOP using Python, and GUI programming using Python.
> Please could someone one point me in the direction of a good book, or some good teaching resources.
> I already have Python for the Absolute Beginner, by Michael Dawson, and Python in Easy Steps, by Michael McGrath. I like these books and have covered the relevant chapters in them. However, I need to learn more.

There is a sequel to the "Absolute Beginner" book, but by a different
author.  It purports to go into more depth on OOP than the first book.
"More Python Programming for the Absolute Beginner" by Jonathan S.
Harbour:

https://www.amazon.com/More-Python-Programming-Absolute-Beginner/dp/1435459806

It continues doing game programming using straight Pygame instead of
that special package (Live Wires?) used in the first book.  I bought
the book once upon a time, but never used it, so I cannot vouch for
how well it does anything.

As for Tkinter/tkinter (Py2/Py3) I have yet to find a dedicated
resource I like.  The two books mentioned by Alan I own and use.
"Python and Tkinter Programming" by Grayson is Python 2-based and is
hard to follow, but has an excellent reference section and many
examples.  But so far the best in my mind seems to be "Programming
Python" by Lutz, which is Python 3-based.  He does a much better job
explaining things; however, he is assuming you are fairly competent in
basic Python, that is, it is a sequel to his other massive tome,
"Learning Python".

Online resources for tkinter are fairly plentiful.


-- 
boB

From poojabhalode11 at gmail.com  Mon Feb 20 09:54:41 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Mon, 20 Feb 2017 09:54:41 -0500
Subject: [Tutor] Matplotlib in Tkinter
In-Reply-To: <CAK0ikxdNMUWjzi2P-5fZtwE1mP--+w7KeBAtg7VhyLEZCc9M9A@mail.gmail.com>
References: <CAK0ikxdNMUWjzi2P-5fZtwE1mP--+w7KeBAtg7VhyLEZCc9M9A@mail.gmail.com>
Message-ID: <CAK0ikxeqrhf=-FkyU=D0S+OPb92BuUApZ7xE7Qi43Gih34_h8A@mail.gmail.com>

Hi,

Another issue, in this that is happening  which is far more important from
the perspective that I am looking at, is that when I click the button
twice, two graphs get created one below the other.

I tried adding a delete("all") statement as shown below.
Code:
      def Submitplot():
print "Create plot"
print concsim.get()
f = Figure(figsize = (5,5), dpi = 80)
canvas = FigureCanvasTkAgg(f, simroot)
canvas.get_tk_widget().delete("all")
a = f.add_subplot(111)
a.plot([1,2,3,4,5],[10,11,12,14,15])
canvas.show()
canvas.get_tk_widget().pack(side = TOP)

toolbar = NavigationToolbar2TkAgg(canvas, simroot)
toolbar.update()
canvas._tkcanvas.pack(side = TOP)

Button(simroot, text = "Submit and Plot", command = Submitplot).pack(side =
TOP)

But this still does not clear the earlier made canvas and creates another
graph at the bottom. Can someone please tell me what I am doing wrong here?
I would really appreciate it.
I have also added the image as to how the two plots look like.
[image: Inline image 1]

Thankyou


On Sun, Feb 19, 2017 at 2:36 PM, Pooja Bhalode <poojabhalode11 at gmail.com>
wrote:

> Hi,
>
> I am trying to create a graph in Tkinter window. And following is a snipet
> of the code.
>
> Code:
>   simroot = Toplevel(root)
> simroot.title("Simulation of experiments")
> Label(simroot, text = "Displaying concentration profiles with respect to
> time:").pack(side = TOP)
>
> Label(simroot, text = "Select the experiments to be displayed:
> ").pack(side = TOP)
> optionexp = ['Experiment 1', 'Experiment 2', 'Experiment 3', 'Experiment
> 4', 'Experiment 5']
> expsim = StringVar()
> dropexp = OptionMenu(simroot, expsim, *optionexp)
> dropexp.pack(side = TOP)
> dropexp.config(width = 15)
>
> # Row 1 would print the name of the experiment selected and the species
> displayed would be in row3.
> Label(simroot, text = "Select concentration species:").pack(side = TOP)
> concsim = StringVar()
> optionlistsim = ['A', 'B', 'C', 'D', 'E']
> dropsim = OptionMenu(simroot, concsim, *optionlistsim)
> dropsim.pack(side = TOP)
> dropsim.config(width = 8)
> Label(simroot, text = "").pack(side = LEFT)
>
> def Submitplot():
> print "Create plot"
>
> f = Figure(figsize = (5,5), dpi = 80)
> a = f.add_subplot(111)
> a.plot([1,2,3,4,5],[10,11,12,14,15])
>
> canvas = FigureCanvasTkAgg(f, simroot)
> canvas.show()
> canvas.get_tk_widget().pack(side = BOTTOM)
>
> toolbar = NavigationToolbar2TkAgg(canvas, simroot)
> toolbar.update()
> canvas._tkcanvas.pack(side = BOTTOM)
> Button(simroot, text = "Submit and Plot", command = Submitplot).pack(side
> = BOTTOM)
>
> Here, the output comes as:
> [image: Inline image 1]
> The problem is I am not able to use grid layout instead of pack (used
> here). I want to place the text to the left, top side in the window.
>
> Also, when I hover the mouse over the figure and the x and y values are
> shown, it flickers really fast and the white space in the Tkinter window
> turns black when it flickers. Can someone please tell me what the issue
> could be? Also, the toolbar should have been at the bottom but it shows up
> at the top.
>
> I am using pack in this Toplevel of the main root whereas in the rest of
> the code, I am using grid layout. I switched to pack for this
> snipet because I could not figure out how grid would work for this part.
>
> Can someone please let me know how to correct these issues?
> Thankyou so much.
>
> Pooja
>

From joseph_rodrigues44 at yahoo.com  Mon Feb 20 09:32:09 2017
From: joseph_rodrigues44 at yahoo.com (Joe)
Date: Mon, 20 Feb 2017 14:32:09 +0000 (UTC)
Subject: [Tutor] Wedscraping Yahoo API
References: <935409597.954498.1487601129646.ref@mail.yahoo.com>
Message-ID: <935409597.954498.1487601129646@mail.yahoo.com>

Hi,
I keep getting the following error as I am new to programming and I am following a tutorial and I am using Python 3.6. Can you please point me in the right direction as to what I am doing wrong. This is code I am running
import datetime as dtimport matplotlib.pyplot as pltfrom matplotlib import style#from matplotlib.finance import candlestick_ohlcimport matplotlib.dates as mdatesimport pandas as pdimport pandas_datareader.data as webimport bs4 as bsimport pickleimport requestsimport osimport csvimport numpy as npimport time
style.use('ggplot')
def save_tsx_tickers():? ? resp = requests.get('http://web.tmxmoney.com/indices.php?section=tsx&index=%5ETSX')? ? soup = bs.BeautifulSoup(resp.text, "lxml")? ? table = soup.find('table', {'class': 'indices-table'})? ? tickers = []? ? for row in table.findAll('tr')[1:]:? ? ? ? ticker = row.findAll('td')[1].text? ? ? ? tickers.append(ticker.replace(".","-") + ".TO")
? ? with open("tsxtickers.pickle", "wb") as f:? ? ? ? pickle.dump(tickers, f)
? ? #print(tickers)? ??? ? return tickers
def get_data_from_yahoo(reload_tsx = False):? ? if reload_tsx:? ? ? ? tickers = save_tsx_tickers()? ? else:? ? ? ? with open("tsxtickers.pickle", "rb") as f:? ? ? ? ? ? tickers = pickle.load(f)
? ? if not os.path.exists('stock_dfs'):? ? ? ? os.makedirs('stock_dfs')
? ? start = dt.datetime(2000, 1, 1)? ? end = dt.datetime(2016, 12, 31)
? ? for i in tickers:? ? ? ? if not os.path.exists('stock_dfs/{}.csv'.format(i)):? ? ? ? ? ? time.sleep(2)? ? ? ? ? ? df = web.DataReader(i, 'yahoo', start, end)? ? ? ? ? ? df.to_csv('stock_dfs/{}.csv'.format(i))? ? ? ? else:? ? ? ? ? ? print('Already have {}'.format(i))


However, I keep getting this error. Please help in identifying the problem. Thank you.


Traceback (most recent call last):? File "<pyshell#3>", line 1, in <module>? ? get_data_from_yahoo()? File "C:\Users\Joe\Desktop\joe\Tutorial Python.py", line 50, in get_data_from_yahoo? ? df = web.DataReader(i, 'yahoo', start, end)? File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\data.py", line 116, in DataReader? ? session=session).read()? File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\yahoo\daily.py", line 76, in read? ? df = super(YahooDailyReader, self).read()? File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 155, in read? ? df = self._read_one_data(self.url, params=self._get_params(self.symbols))? File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 74, in _read_one_data? ? out = self._read_url_as_StringIO(url, params=params)? File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 85, in _read_url_as_StringIO? ? response = self._get_response(url, params=params)? File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 120, in _get_response? ? raise RemoteDataError('Unable to read URL: {0}'.format(url))pandas_datareader._utils.RemoteDataError: Unable to read URL: http://ichart.finance.yahoo.com/table.csv?s=OTEX.TO&a=0&b=1&c=2000&d=11&e=31&f=2016&g=d&ignore=.csv

From alan.gauld at yahoo.co.uk  Mon Feb 20 13:41:51 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 20 Feb 2017 18:41:51 +0000
Subject: [Tutor] Matplotlib in Tkinter
In-Reply-To: <CAK0ikxeqrhf=-FkyU=D0S+OPb92BuUApZ7xE7Qi43Gih34_h8A@mail.gmail.com>
References: <CAK0ikxdNMUWjzi2P-5fZtwE1mP--+w7KeBAtg7VhyLEZCc9M9A@mail.gmail.com>
 <CAK0ikxeqrhf=-FkyU=D0S+OPb92BuUApZ7xE7Qi43Gih34_h8A@mail.gmail.com>
Message-ID: <o8fd98$sck$1@blaine.gmane.org>

On 20/02/17 14:54, Pooja Bhalode wrote:

> Another issue, in this that is happening  which is far more important from
> the perspective that I am looking at, is that when I click the button
> twice, two graphs get created one below the other.
> 
> I tried adding a delete("all") statement as shown below.

I don't use matplotlib with Tkinter so can't comment but
matplotlib is not part of the standard library. Therefore
it is technically off-topic for this list, although
I know some folks here do use it.

However, you might get a better response on the SciPy/Matplot
lib support forums where I'm sure there will be many more
users hanging out.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 20 13:43:20 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 20 Feb 2017 18:43:20 +0000
Subject: [Tutor] Wedscraping Yahoo API
In-Reply-To: <935409597.954498.1487601129646@mail.yahoo.com>
References: <935409597.954498.1487601129646.ref@mail.yahoo.com>
 <935409597.954498.1487601129646@mail.yahoo.com>
Message-ID: <o8fdc2$sck$2@blaine.gmane.org>

Please post in plain text. Formatting is very important in
Python and RTF or HTML tend to get scrambled in transit
making your code and error hard to read.

Thanks

Alan G.

On 20/02/17 14:32, Joe via Tutor wrote:
> Hi,
> I keep getting the following error as I am new to programming and I am following a tutorial and I am using Python 3.6. Can you please point me in the right direction as to what I am doing wrong. This is code I am running
> import datetime as dtimport matplotlib.pyplot as pltfrom matplotlib import style#from matplotlib.finance import candlestick_ohlcimport matplotlib.dates as mdatesimport pandas as pdimport pandas_datareader.data as webimport bs4 as bsimport pickleimport requestsimport osimport csvimport numpy as npimport time
> style.use('ggplot')
> def save_tsx_tickers():    resp = requests.get('http://web.tmxmoney.com/indices.php?section=tsx&index=%5ETSX')    soup = bs.BeautifulSoup(resp.text, "lxml")    table = soup.find('table', {'class': 'indices-table'})    tickers = []    for row in table.findAll('tr')[1:]:        ticker = row.findAll('td')[1].text        tickers.append(ticker.replace(".","-") + ".TO")
>     with open("tsxtickers.pickle", "wb") as f:        pickle.dump(tickers, f)
>     #print(tickers)        return tickers
> def get_data_from_yahoo(reload_tsx = False):    if reload_tsx:        tickers = save_tsx_tickers()    else:        with open("tsxtickers.pickle", "rb") as f:            tickers = pickle.load(f)
>     if not os.path.exists('stock_dfs'):        os.makedirs('stock_dfs')
>     start = dt.datetime(2000, 1, 1)    end = dt.datetime(2016, 12, 31)
>     for i in tickers:        if not os.path.exists('stock_dfs/{}.csv'.format(i)):            time.sleep(2)            df = web.DataReader(i, 'yahoo', start, end)            df.to_csv('stock_dfs/{}.csv'.format(i))        else:            print('Already have {}'.format(i))
> 
> 
> However, I keep getting this error. Please help in identifying the problem. Thank you.
> 
> 
> Traceback (most recent call last):  File "<pyshell#3>", line 1, in <module>    get_data_from_yahoo()  File "C:\Users\Joe\Desktop\joe\Tutorial Python.py", line 50, in get_data_from_yahoo    df = web.DataReader(i, 'yahoo', start, end)  File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\data.py", line 116, in DataReader    session=session).read()  File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\yahoo\daily.py", line 76, in read    df = super(YahooDailyReader, self).read()  File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 155, in read    df = self._read_one_data(self.url, params=self._get_params(self.symbols))  File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 74, in _read_one_data    out = self._read_url_as_StringIO(url, params=params)  File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 85, in _read_url_as_StringIO    response = self._get_response(url, params=params)  File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\base.py", line 120, in _get_response    raise RemoteDataError('Unable to read URL: {0}'.format(url))pandas_datareader._utils.RemoteDataError: Unable to read URL: http://ichart.finance.yahoo.com/table.csv?s=OTEX.TO&a=0&b=1&c=2000&d=11&e=31&f=2016&g=d&ignore=.csv
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 



From dyoo at hashcollision.org  Mon Feb 20 14:31:54 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 20 Feb 2017 11:31:54 -0800
Subject: [Tutor] Wedscraping Yahoo API
In-Reply-To: <935409597.954498.1487601129646@mail.yahoo.com>
References: <935409597.954498.1487601129646.ref@mail.yahoo.com>
 <935409597.954498.1487601129646@mail.yahoo.com>
Message-ID: <CAGZAPF4y10-S5m8nKcrBcGz+wbuO3ArCbVh8akRwa3B1w8SG6w@mail.gmail.com>

Hi Joe,


On Mon, Feb 20, 2017 at 6:32 AM, Joe via Tutor <tutor at python.org> wrote:
> Hi,
> I keep getting the following error as I am new to programming and I am following a tutorial and I am using Python 3.6. Can you please point me in the right direction as to what I am doing wrong.


You have made an assumption that you have done something wrong.

Although this might be true, when we program anything substantial that
interacts with other remote services, failures can happen anywhere in
that chain, be it problems in third-party libraries, to problems with
the servers, to even interference from the low-level network!


Read the error message carefully, especially the last part:

######################################################################
RemoteDataError: Unable to read URL:
http://ichart.finance.yahoo.com/table.csv?s=OTEX.TO&a=0&b=1&c=2000&d=11&e=31&f=2016&g=d&ignore=.csv
######################################################################

It says that it can't read the content at that URL.


So there are a few possibilities.  Perhaps there is a problem in your
code.  However, you mention that this script is web-scraping Yahoo.
Web-scraping is known to be an extremely fragile endeavor, because it
introduces factors entirely out of your control:

  * Perhaps that URL is wrong.

  * Perhaps the page is no longer available.

  * Perhaps the page structure has changed.

  * Perhaps the page is available sometimes, but the server recognizes
that it is being scraped for content, and so returns an error response
occasionally as a way to discourage scraping.

  * Perhaps your network is injecting content that breaks parsing.

(The last is not as crazy as it sounds.  See:
https://arstechnica.com/tech-policy/2014/09/why-comcasts-javascript-ad-injections-threaten-security-net-neutrality/.
A HTTPS-only web can't come soon enough.)

Web scraping introduces all this uncertainty, making it a mess even
for professional programmers.

For these reasons, I contend that web scraping is a very bad example
for introductory beginner programming. It's also usually a very bad
idea for professional programmers too.  Without a strong fundamental
background, it's way too easy for a beginner to learn superstitious
beliefs in that kind of environment, because too many things can
happen that are outside of your control.


You mention that you're new to programming.  You might want to try a
tutorial that doesn't depend so much on the external world. I would
strongly recommend not continuing with this example, and go into
something like:

    https://wiki.python.org/moin/BeginnersGuide/Programmers

Have you taken a look at these tutorials?  One of them might be better
suited for you.


Hope that makes sense; good luck!

From malaclypse2 at gmail.com  Mon Feb 20 17:06:26 2017
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 20 Feb 2017 17:06:26 -0500
Subject: [Tutor] Please explain part of this code
In-Reply-To: <o82l7j$418$1@blaine.gmane.org>
References: <o82l7j$418$1@blaine.gmane.org>
Message-ID: <CADwdpybLnJ3SytL-WOnuqdCrRaWnwDuRcQJ5f6D8Li4DKW2h3g@mail.gmail.com>

On Wed, Feb 15, 2017 at 5:37 PM, Jim <jf_byrnes at comcast.net> wrote:
> I don't recall ever seeing this before.  What is this technique called?

I've heard picking which function to call sometimes called
"dispatching", and picking which function to call based on functions
held in a dictionary called "dictionary dispatch", or "dictionary
based dispatching".  I think this is in contrast to a C technique
called "table dispatching".  A google search for the phrase "python
dictionary dispatch" should get lots of hits talking about the
technique (I had to include "python" otherwise google kept trying to
give me the dictionary definition of the word dispatch).

Jerry

From rafael.knuth at gmail.com  Tue Feb 21 04:49:23 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Tue, 21 Feb 2017 10:49:23 +0100
Subject: [Tutor] Class Inheritance
Message-ID: <CAM-E2X5XYtQYtSS5EPR79XUP10RaFGKL5ZdmT=LM2Me13LA6QQ@mail.gmail.com>

Hey there,

I am trying to wrap my head around Class Inheritance in Python, and I
wrote a little program which is supposed to calculate revenues from
customers who don't get a discount (parent class) and those who get a
30% discount (child class):

class FullPriceCustomer(object):
    def __init__(self, customer, rate, hours):
        self.customer = customer
        self.rate = rate
        self.hours = hours

        print ("Your customer %s made you %s USD this year." %
(customer, rate * hours))

class DiscountCustomer(FullPriceCustomer):
    discount = 0.7
    def calculate_discount(self, rate, hours):
        print ("Your customer %s made you %s USD at a 30% discount
rate this year." % (self.customer, self.rate * rate * discount))

customer_one = DiscountCustomer("Customer A", 75, 100)
customer_two = FullPriceCustomer("Customer B", 75, 100)

The DiscountCustomer class instance gets me the wrong result (it does
not calculate the discount) and I was not able to figure out what I
did wrong here.
Can anyone help? Thanks!

All the best,

Rafael

From alan.gauld at yahoo.co.uk  Tue Feb 21 05:23:33 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 21 Feb 2017 10:23:33 +0000
Subject: [Tutor] Class Inheritance
In-Reply-To: <CAM-E2X5XYtQYtSS5EPR79XUP10RaFGKL5ZdmT=LM2Me13LA6QQ@mail.gmail.com>
References: <CAM-E2X5XYtQYtSS5EPR79XUP10RaFGKL5ZdmT=LM2Me13LA6QQ@mail.gmail.com>
Message-ID: <o8h4ev$n11$1@blaine.gmane.org>

On 21/02/17 09:49, Rafael Knuth wrote:

> class FullPriceCustomer(object):
>     def __init__(self, customer, rate, hours):
> 
> 
> class DiscountCustomer(FullPriceCustomer):
>     discount = 0.7
>     def calculate_discount(self, rate, hours):
> 
> customer_one = DiscountCustomer("Customer A", 75, 100)
> customer_two = FullPriceCustomer("Customer B", 75, 100)

You create two instances and as such the
FullPriceCustomer.__init__() method gets
executed in both cases. This is because
the subclass does not provide an __init__()
of its own, so the inherited one is used.

Your discount is calculated in the
calculate_discount() method, but that is
never called. If you added a line:

customer_one.calculate_discount(75,100)

you would see the discount appear.

Alternatively create an init() for your
subclass that calls the superclass init()
then calls

self.calculate_discount(rate,hours)

BTW It's bad practice to mix calculations
and display(print) in the same method,
it's better to separate them, but
that's probably a topic for another thread
Get the inheritance sorted first :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb 21 05:27:34 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 21 Feb 2017 10:27:34 +0000
Subject: [Tutor] Class Inheritance
In-Reply-To: <CAM-E2X5XYtQYtSS5EPR79XUP10RaFGKL5ZdmT=LM2Me13LA6QQ@mail.gmail.com>
References: <CAM-E2X5XYtQYtSS5EPR79XUP10RaFGKL5ZdmT=LM2Me13LA6QQ@mail.gmail.com>
Message-ID: <o8h4mg$2go$1@blaine.gmane.org>

On 21/02/17 09:49, Rafael Knuth wrote:

> class DiscountCustomer(FullPriceCustomer):
>     discount = 0.7
>     def calculate_discount(self, rate, hours):
>         print ("Your customer %s made you %s USD at a 30% discount
> rate this year." % (self.customer, self.rate * rate * discount))

I meant to add... are you sure that calculation is what you meant?
First point is that discount is not defined, you need to prefix
it with either self or DiscountCustomer.
But also, it doesn't use hours? Is that correct?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Tue Feb 21 06:01:40 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 21 Feb 2017 12:01:40 +0100
Subject: [Tutor] Class Inheritance
References: <CAM-E2X5XYtQYtSS5EPR79XUP10RaFGKL5ZdmT=LM2Me13LA6QQ@mail.gmail.com>
Message-ID: <o8h6mg$346$1@blaine.gmane.org>

Rafael Knuth wrote:

> Hey there,
> 
> I am trying to wrap my head around Class Inheritance in Python, and I
> wrote a little program which is supposed to calculate revenues from
> customers who don't get a discount (parent class) and those who get a
> 30% discount (child class):
> 
> class FullPriceCustomer(object):
>     def __init__(self, customer, rate, hours):
>         self.customer = customer
>         self.rate = rate
>         self.hours = hours
> 
>         print ("Your customer %s made you %s USD this year." %
> (customer, rate * hours))
> 
> class DiscountCustomer(FullPriceCustomer):
>     discount = 0.7
>     def calculate_discount(self, rate, hours):
>         print ("Your customer %s made you %s USD at a 30% discount
> rate this year." % (self.customer, self.rate * rate * discount))
> 
> customer_one = DiscountCustomer("Customer A", 75, 100)
> customer_two = FullPriceCustomer("Customer B", 75, 100)
> 
> The DiscountCustomer class instance gets me the wrong result (it does
> not calculate the discount) and I was not able to figure out what I
> did wrong here.
> Can anyone help? Thanks!

In a real application you would not introduce two classes for this -- a 
FullPriceCustomer would be a customer with a discount of 0%.

Then you mix output with initialisation, so let's fix that first:

class FullPriceCustomer(object):
    def __init__(self, customer, rate, hours):
        self.customer = customer
        self.rate = rate
        self.hours = hours

    def print_summary(self):
        print(
            "Your customer %s made you %s USD this year." %
            (self.customer, self.rate * self.hours)
        )


customer = FullPriceCustomer("Customer B", 75, 100)
customer.print_summary()

Now look at your code: what has to change for a customer who gets a 
discount?

self.rate * self.hours

will become

self.discount * self.rate * self.hours

or as I prefer to store the part that the customer doesn't pay as the 
discount

(1 - self.discount) * self.rate * self.hours

To make overriding easy we put that calculation into a separate method:

class FullPriceCustomer(object):
    def __init__(self, customer, rate, hours):
        self.customer = customer
        self.rate = rate
        self.hours = hours

    def print_summary(self):
        print(
            "Your customer %s made you %s USD this year." %
            (self.customer, self.get_total())
        )

    def get_total(self):
        return self.rate * self.hours


customer = FullPriceCustomer("Customer B", 75, 100)
customer.print_summary()

Then the DiscountCustomer class can be written

class FullPriceCustomer(object):
    def __init__(self, customer, rate, hours):
        self.customer = customer
        self.rate = rate
        self.hours = hours

    def print_summary(self):
        print(
            "Your customer %s made you %s USD this year." %
            (self.customer, self.get_total())
        )

    def get_total(self):
        return self.rate * self.hours


class DiscountCustomer(FullPriceCustomer):
    discount = 0.3
    def get_total(self):
        return (1 - self.discount) * self.rate * self.hours

customers = [
    DiscountCustomer("Customer A", 75, 100),
    FullPriceCustomer("Customer B", 75, 100),
]
    
for customer in customers:
    customer.print_summary()

If we run that we see that the calculation may be correct, but the discount 
is not mentioned. We could solve this by overriding print_summary, but 
here's another way:

class FullPriceCustomer(object):
    summary_template = (
        "Your customer {0.customer} made you {0.total} USD this year."
    )

    def __init__(self, customer, rate, hours):
        self.customer = customer
        self.rate = rate
        self.hours = hours

    def print_summary(self):
        print(self.summary_template.format(self))

    @property
    def total(self):
        return self.rate * self.hours


class DiscountCustomer(FullPriceCustomer):
    summary_template = (
        "Your customer {0.customer} made you {0.total} USD "
        "at a {0.discount:.0%} this year."
    )
    discount = 0.3

    @property
    def total(self):
        return (1 - self.discount) * self.rate * self.hours


class VIC(DiscountCustomer):
    discount = 0.33

customers = [
    DiscountCustomer("Customer A", 75, 100),
    FullPriceCustomer("Customer B", 75, 100),
    VIC("Customer C", 75, 100),
]

for customer in customers:
    customer.print_summary()

If one day you choose to use an isinstance check to see if you have a 
FullPriceCustomer

for customer in customers:
    if isinstance(customer, FullPriceCustomer):
        print(customer.customer, "pays the full price")

you may be surprised to see that all customers seem to be paying the full 
price. That's because isinstance(obj, class_) is true even if the actual 
class of obj is a subclass of class_. Therefore I recommend that you change 
your class hierarchy to

class Customer(object):
   ...

class FullPriceCustomer(Customer):
   ...

class DiscountCustomer(Customer):
   ...

Also, if there are more than two or three fixed discounts you'll put the 
discount into the instance rather than the class:

class DiscountCustomer(Customer):
    def __init__(self, customer, rate, hours, discount):
        super().__init__(customer, rate, hours)
        self.discount = discount



From pinof1 at mail.montclair.edu  Tue Feb 21 21:55:01 2017
From: pinof1 at mail.montclair.edu (Francis Pino)
Date: Tue, 21 Feb 2017 21:55:01 -0500
Subject: [Tutor] Trip Advisor Web Scraping
Message-ID: <CADD24yuT69Jofk36R-AEmDNeMQczj6FDMvkJBdxdRmxBTd=XvQ@mail.gmail.com>

I need to recode my hotel ratings as 1-3  = Negative and  4-5 Positive. Can
you help point me in the direction to do this? I know I need to make a loop
using for and in and may statement like for rating in review if review >= 3
 print ('Negative') else print 'Negative'.  Here's my code so far.


from bs4 import BeautifulSoup
from selenium import webdriver
import csv

url = "
https://www.tripadvisor.com/Hotel_Review-g34678-d87695-Reviews-Clarion_Hotel_Conference_Center-Tampa_Florida.html
"
# driver = webdriver.Firefox()
driver = webdriver.Chrome()
driver.get(url)

# The HTML code for the web page is stored in the html variable
html = driver.page_source

# we will use the soup object to parse HTML
# BeautifulSoup reference
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/

soup = BeautifulSoup(html, "lxml")


# we will use find_all method to find all paragraph tags of class
partial_entry
# The result of this command is a list
# we use for .. in [] to iterate through the list

reviews = []
ratings= []

for review in soup.find_all("p", "partial_entry"):
    print(review.text)
    #print ('\n\n')
    reviews += review
    print(len(reviews))

# similarly we can identify the ratings
# note that the code is incomplete - it will require additional work


for rating in soup.find_all("span", "ui_bubble_rating"):
    print(rating.text)



Thanks!

From alan.gauld at yahoo.co.uk  Wed Feb 22 04:39:21 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 22 Feb 2017 09:39:21 +0000
Subject: [Tutor] Trip Advisor Web Scraping
In-Reply-To: <CADD24yuT69Jofk36R-AEmDNeMQczj6FDMvkJBdxdRmxBTd=XvQ@mail.gmail.com>
References: <CADD24yuT69Jofk36R-AEmDNeMQczj6FDMvkJBdxdRmxBTd=XvQ@mail.gmail.com>
Message-ID: <o8jm83$8im$1@blaine.gmane.org>

On 22/02/17 02:55, Francis Pino wrote:
> I need to recode my hotel ratings as 1-3  = Negative and  4-5 Positive. Can
> you help point me in the direction to do this? I know I need to make a loop
> using for and in and may statement like for rating in review if review >= 3
>  print ('Negative') else print 'Negative'.  Here's my code so far.

The short answer is that it looks like:

for rating in review:
  if rating >= 3:
     print 'Positive'
  else: print 'Negative'

but...

Your code looks much more sophisticated than your question
would suggest so you should have been able to figure that
much out for yourself.. Did you write the code below yourself?
Do you understand how it works so far? Indeed, does it work so far? What
output are you seeing?

Also are you sure TripAdvisor allow web scraping - you
could find yourself blacklisted from the site. Or they
may have a web service API for extracting stats that is
both easier and more reliable to use.

> from bs4 import BeautifulSoup
> from selenium import webdriver
> import csv
> 
> url = "
> https://www.tripadvisor.com/Hotel_Review-g34678-d87695-Reviews-Clarion_Hotel_Conference_Center-Tampa_Florida.html
> "
> # driver = webdriver.Firefox()
> driver = webdriver.Chrome()
> driver.get(url)
> 
> # The HTML code for the web page is stored in the html variable
> html = driver.page_source
> 
> # we will use the soup object to parse HTML
> # BeautifulSoup reference
> # https://www.crummy.com/software/BeautifulSoup/bs4/doc/
> 
> soup = BeautifulSoup(html, "lxml")
> 
> 
> # we will use find_all method to find all paragraph tags of class
> partial_entry
> # The result of this command is a list
> # we use for .. in [] to iterate through the list
> 
> reviews = []
> ratings= []
> 
> for review in soup.find_all("p", "partial_entry"):
>     print(review.text)
>     #print ('\n\n')
>     reviews += review
>     print(len(reviews))
> 
> # similarly we can identify the ratings
> # note that the code is incomplete - it will require additional work
> 
> 
> for rating in soup.find_all("span", "ui_bubble_rating"):
>     print(rating.text)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Wed Feb 22 23:25:58 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 22 Feb 2017 22:25:58 -0600
Subject: [Tutor] How to access an instance variable of a superclass from an
 instance of the subclass?
Message-ID: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>

I am trying to wrap my head around the mechanics of inheritance in
Python 3.  I thought that all attributes of a superclass were
accessible to an instance of a subclass.  But when I try the
following:

py3: class A:
...     def __init__(self):
...             self.aa = 'class A'
...
py3: class B(A):
...     def __init__(self):
...             self.bb = 'class B'
...
py3: a = A()
py3: b = B()
py3: b.aa
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'B' object has no attribute 'aa'

I am unsuccessful.  The only way I have been able to access an
attribute aa of class A is to make aa a class variable.  Then I
succeed:

py3: class A:
...     aa = 'class A'
...
py3: class B(A):
...     def __init__(self):
...             self.b = 'class B'
...
py3: a = A()
py3: b = B()
py3: b.aa
'class A'

Obviously I am horribly misunderstanding something, and being
currently sleepy is not helping my cause.

Help, please?


-- 
boB

From zachary.ware+pytut at gmail.com  Wed Feb 22 23:49:37 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Wed, 22 Feb 2017 22:49:37 -0600
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
Message-ID: <CAKJDb-OxjFXi_Hc1EoyAvkwiNFO=K3482EzYwCQQk_z=u4G4UA@mail.gmail.com>

On Wed, Feb 22, 2017 at 10:25 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> I am trying to wrap my head around the mechanics of inheritance in
> Python 3.  I thought that all attributes of a superclass were
> accessible to an instance of a subclass.
>
> Obviously I am horribly misunderstanding something, and being
> currently sleepy is not helping my cause.

I'll give you a couple of hints.  First, try this:

print('defining A')
class A:
    print('Setting a on class A')
    a = 'a on class A'
    def __init__(self):
        print('Setting aa on instance of', self.__class__.__name__)
        self.aa = 'aa in A.__init__'

print('defining B')
class B(A):
    print('Setting b on class B')
    b = 'b on class B'
    def __init__(self):
        print('Setting bb on instance of', self.__class__.__name__)
        self.bb = 'bb in B.__init__'

print('Instantiating a')
a = A()
print('Instantiating b')
b = B()

Next, have a look at
https://docs.python.org/3/library/functions.html#super and in
particular the link at the end to Raymond Hettinger's "super
considered super" essay.

And finally, there's one line you can add to B.__init__ that will get
what you're after.

I hope this is helpful, I'm sure others will be along with in-depth
explanations before long anyway :)

Regards,
-- 
Zach

From robertvstepp at gmail.com  Wed Feb 22 23:53:03 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 22 Feb 2017 22:53:03 -0600
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
Message-ID: <CANDiX9+6d9V39ATLkEGVdjCR2XBkBBxLYe_q9-+KMircXg67Uw@mail.gmail.com>

On Wed, Feb 22, 2017 at 10:25 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> I am trying to wrap my head around the mechanics of inheritance in
> Python 3.  I thought that all attributes of a superclass were
> accessible to an instance of a subclass.  But when I try the
> following:
>
> py3: class A:
> ...     def __init__(self):
> ...             self.aa = 'class A'
> ...
> py3: class B(A):
> ...     def __init__(self):
> ...             self.bb = 'class B'
> ...
> py3: a = A()
> py3: b = B()
> py3: b.aa
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'B' object has no attribute 'aa'
>
> I am unsuccessful...

I have partially answered my own question, but I am not sure I
understand the mechanics yet.  Apparently I must explicitly assign
class A's attribute, aa, to an instance of class B as follows:

py3: class B(A):
...     def __init__(self):
...             self.aa = super().aa
...             self.bb = 'class B'
...
py3: b = B()
py3: b.aa
'class A'

I was expecting that all of A's methods and attributes would
seamlessly be available to any instance of class B, but apparently
this is wrong-headed on my part.  Instead, it looks like I need to
explicitly attach A's methods and attributes to B's instances via B's
self.

I will continue to mull this over.

-- 
boB

From akleider at sonic.net  Thu Feb 23 00:02:57 2017
From: akleider at sonic.net (Alex Kleider)
Date: Wed, 22 Feb 2017 21:02:57 -0800
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CANDiX9+6d9V39ATLkEGVdjCR2XBkBBxLYe_q9-+KMircXg67Uw@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
 <CANDiX9+6d9V39ATLkEGVdjCR2XBkBBxLYe_q9-+KMircXg67Uw@mail.gmail.com>
Message-ID: <785b7356695414c4c0e536c02cf399e7@sonic.net>

On 2017-02-22 20:53, boB Stepp wrote:
> On Wed, Feb 22, 2017 at 10:25 PM, boB Stepp <robertvstepp at gmail.com> 
> wrote:
>> I am trying to wrap my head around the mechanics of inheritance in
>> Python 3.  I thought that all attributes of a superclass were
>> accessible to an instance of a subclass.  But when I try the
>> following:
>> 
>> py3: class A:
>> ...     def __init__(self):
>> ...             self.aa = 'class A'
>> ...
>> py3: class B(A):
>> ...     def __init__(self):
>> ...             self.bb = 'class B'
>> ...
>> py3: a = A()
>> py3: b = B()
>> py3: b.aa
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> AttributeError: 'B' object has no attribute 'aa'
>> 
>> I am unsuccessful...

The 'attribute(s)' to which you refer only exist because of the 
__init__s.
B's __init__ over rides that of A so A's __init__ never gets called 
during instantiation of b and hence b.aa never comes into being.


From __peter__ at web.de  Thu Feb 23 03:30:26 2017
From: __peter__ at web.de (Peter Otten)
Date: Thu, 23 Feb 2017 09:30:26 +0100
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
 <CANDiX9+6d9V39ATLkEGVdjCR2XBkBBxLYe_q9-+KMircXg67Uw@mail.gmail.com>
Message-ID: <o8m6is$lc0$1@blaine.gmane.org>

boB Stepp wrote:

> On Wed, Feb 22, 2017 at 10:25 PM, boB Stepp <robertvstepp at gmail.com>
> wrote:
>> I am trying to wrap my head around the mechanics of inheritance in
>> Python 3.  I thought that all attributes of a superclass were
>> accessible to an instance of a subclass.  But when I try the
>> following:
>>
>> py3: class A:
>> ...     def __init__(self):
>> ...             self.aa = 'class A'
>> ...
>> py3: class B(A):
>> ...     def __init__(self):
>> ...             self.bb = 'class B'
>> ...
>> py3: a = A()
>> py3: b = B()
>> py3: b.aa
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> AttributeError: 'B' object has no attribute 'aa'
>>
>> I am unsuccessful...
> 
> I have partially answered my own question, but I am not sure I
> understand the mechanics yet.  Apparently I must explicitly assign
> class A's attribute, aa, to an instance of class B as follows:
> 
> py3: class B(A):
> ...     def __init__(self):
> ...             self.aa = super().aa
> ...             self.bb = 'class B'
> ...
> py3: b = B()
> py3: b.aa
> 'class A'
> 
> I was expecting that all of A's methods and attributes would
> seamlessly be available to any instance of class B, but apparently
> this is wrong-headed on my part.  Instead, it looks like I need to
> explicitly attach A's methods and attributes to B's instances via B's
> self.
> 
> I will continue to mull this over.
 
You are making this harder than need be. If you have one class

class A:
   def __init__(self):
       # complex calculation --> a
       self.a = a
       self.b = "whatever"

you could split the code into two methods, to keep it manageable, say:

class A:
    def __init__(self):
        self.init_a()
        self.b = "whatever"

    def init_a(self):
        # complex calculation
        self.a = a

This will obviously continue to work with two classes:

class A:
    def init_a(self):
        # complex calculation
        self.a = a

class B(A):
    def __init__(self):
        self.init_a()
        self.b = "whatever"

Now what if init_a() is actually called __init__? Just renaming will not 
work

class A:
    def __init__(self):
        # complex ...
        self.a = a

class B(A)
    def __init__(self):
        self.__init__() # this will invoke B.__init__ again
                        # --> infinite recursion
        self.b = "whatever"

so you either have to be explicit

class B(A)
    def __init__(self):
        A.__init__(self) # this will invoke A.__init__
                         # because we told it to
        self.b = "whatever"

or use "black magic"

class B(A):
    def __init__(self):
        super().__init__() # have Python figure out
                           # what to call
        self.b = "whatever"


From steve at pearwood.info  Thu Feb 23 04:57:14 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Feb 2017 20:57:14 +1100
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
Message-ID: <20170223095714.GY5689@ando.pearwood.info>

On Wed, Feb 22, 2017 at 10:25:58PM -0600, boB Stepp wrote:
> I am trying to wrap my head around the mechanics of inheritance in
> Python 3.  I thought that all attributes of a superclass were
> accessible to an instance of a subclass.  But when I try the
> following:
> 
> py3: class A:
> ...     def __init__(self):
> ...             self.aa = 'class A'
> ...

There you have a class with an initializer method.

And here you subclass it:

> py3: class B(A):
> ...     def __init__(self):
> ...             self.bb = 'class B'
> ...

But you *override* the initialiser method and prevent the superclass' 
method from running. Only B's custom version will run.

That's allowed, but fairly unusual. Normally you want to "overload" the 
method. Python can't guess if you want to call the superclass' version 
before or after your customization, so you have to decide for yourself:

class B(A):
    def __init__(self):
        super().__init__()  # call the superclass first
        self.bb = 'class B'
        super().__init__()  # or last

(Just don't do it twice, as I have! :-)

In this specific instance, it doesn't matter whether you call super() 
first or last, but often it will.


Welcome to the complexity of inheritence! And wait until you learn about 
multiple-inheritence, diamond diagrams, mixins, traits, and more. 

It's not *always* this complex. Often you subclass just to extend the 
class by adding a new method, and inheritence Just Works. You don't even 
have to think about it. But when overriding and overloading methods, you 
do have to think about what you are doing.



-- 
Steve

From alan.gauld at yahoo.co.uk  Thu Feb 23 05:09:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 23 Feb 2017 10:09:27 +0000
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
Message-ID: <o8mccg$1i4$1@blaine.gmane.org>

On 23/02/17 04:25, boB Stepp wrote:
> I am trying to wrap my head around the mechanics of inheritance in
> Python 3.  I thought that all attributes of a superclass were
> accessible to an instance of a subclass. 

For class attributes that happens automatically.

>>> class A:
	a = 'A'
	def __init__(self):
		self.aa = 'aa'

		
>>> class X(A): pass

>>> x = X()
>>> x.a
'A'
>>> x.aa
'aa'

Notice that both the class and instance variables
are inherited. That's because there is no
__init__() in X so the inherited A.__init__()
is called.

Now, if we add an init to the subclass:

>>> class B(A):
	b = 'B'
	def __init__(self):
		self.bb='bb'

		
>>> b = B()
>>> b.a
'A'
>>> b.bb
'bb'
>>> b.aa
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    b.aa
AttributeError: 'B' object has no attribute 'aa'

We get the scenario you found. (But with the additional fact
that B can access A's class variable 'a')

The B.__init__() is called, but it does not create an aa instance
variable. To do so we need to call the superclass constructor:

>>> class C(A):
	c = 'C'
	def __init__(self):
		super().__init__()
		self.cc = 'cc'

		
>>> c = C()
>>> c.a
'A'
>>> c.aa
'aa'
>>> c.cc
'cc'
>>> c.bb
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    c.bb
AttributeError: 'C' object has no attribute 'bb'
>>>

Now C can access cc and aa (as well as a), but
not B.bb of course because its not in the inheritance line.

There is no real magic(*) going on here.
When you call SomeClass() the SomeClass.__new__() method
gets called which is usually the one defined in object.
That method results in __init__() getting called. The
usual method lookup applies, the first init() found will
be executed. If it doesn't explicitly call the
superclass init then that method will never be
called.

(*)Actually its not quite this straightforward because
meta-classes are involved in the invocation of new()
and it all gets a bit mind-bending. But as a concept
you can stick with new() as the constructor calling
init() as the initializer and both being subject
to the usual method resolution rules.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Thu Feb 23 05:40:14 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Feb 2017 21:40:14 +1100
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
Message-ID: <20170223104003.GZ5689@ando.pearwood.info>

On Wed, Feb 22, 2017 at 10:25:58PM -0600, boB Stepp wrote:
> I am trying to wrap my head around the mechanics of inheritance in
> Python 3.

Here is a simplified picture of how inheritence usually works in Python.

For an instance `spam`, when you look up an attribute (which includes 
methods), Python checks the following places *in this order*:

- attributes attached to spam itself ("instance attributes");

- attributes attached to spam's class ("class attributes");

- attributes attached to any parent classes (class attributes
  of superclasses).


(The actual rules are much more complex, but this will do for starters.)

If no such attribute is found, Python will try calling the class 
__getattr__ (if any) or superclass __getattr__, and if that doesn't 
exist or fails, Python will raise AttributeError.

How do class attributes normally get set? In the class definition:

class MyClass:
    attribute = None


How do instance attributes normally get set? In the __init__ method:

class MyClass:
    def __init__(self):
        self.attribute = None


If the __init__ method does get run, it doesn't get the chance to create 
the instance attributes. So if you have a subclass that defines 
__init__, you need to allow the superclass' __init__ to run too.



-- 
Steve

From quangnguyen51291 at gmail.com  Thu Feb 23 17:16:00 2017
From: quangnguyen51291 at gmail.com (Quang nguyen)
Date: Thu, 23 Feb 2017 15:16:00 -0700
Subject: [Tutor] Asking about Opening Teminal on Python
Message-ID: <CAGHbcgN4ccwQmnZ7c0riz5vg8iYC0GQC=-tv9FunRYOtTW7w8Q@mail.gmail.com>

Hi everyone,
I need to open a terminal on Raspberry Pi 2 in order to execute codesend of
433Utils to send a signal to RF Receiver. Anyone know how to open a
terminal?
Thank you.

From poojabhalode11 at gmail.com  Thu Feb 23 17:25:31 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Thu, 23 Feb 2017 17:25:31 -0500
Subject: [Tutor] Multiple muti-selection dropdown options
Message-ID: <CAK0ikxcuS2Z71HvcuVe1dkHgv+hEu1rhcX5Fzv3_ibq+SSHF7A@mail.gmail.com>

Hi,

I am working on GUI where I have two dropdown menus in a Toplevel of the
main root. Here, both the dropdown menus have mutiple selection option and
thus, the selections can be taken as an input from the user and printed out
in the code.

The window shows as below:
[image: Inline image 1]
Whereas the code is:

simroot = Toplevel(root)
simroot.title("Simulation of experiments")

Label(simroot, text = "Displaying concentration profiles with respect to
time:").grid(row = 0, column = 0, sticky = W)

Label(simroot, text = "Select the experiments to be displayed: ").grid(row
= 1, column = 0, sticky = W)
varlist = StringVar()
varlist.set("Experiment1 Experiment2 Experiment3 Experiment4 Experiment5")
scroll1 = Scrollbar(simroot, orient = "vertical")
scroll1.grid(column = 2, sticky = W)

lstbox = Listbox(simroot, listvariable = varlist, selectmode = MULTIPLE,
yscrollcommand = scroll1.set, width = 20, height = 3)
lstbox.grid(row = 2, column = 1, sticky = W)
scroll1.config(command = lstbox.yview)

def selectexp():
newlist = list()
selection = lstbox.curselection()
for i in selection:
tempvar = lstbox.get(i)
newlist.append(tempvar)

for val in newlist:
print (val)


selectbutt = Button(simroot, text = "Submit", command = selectexp)
selectbutt.grid(row = 6,column = 1, sticky = W)
# Row 1 would print the name of the experiment selected and the species
displayed would be in row3.

Label(simroot, text = "Select concentration species:").grid(row = 7, column
= 0, sticky = W)
concvarlist = StringVar()
concvarlist.set("A B C D E")
scroll2 = Scrollbar(simroot, orient = "vertical")
scroll2.grid(column = 2, sticky = W)
lstbox2 = Listbox(simroot, listvariable = concvarlist, selectmode =
MULTIPLE, yscrollcommand = scroll2.set, width = 20, height = 3)
lstbox2.grid(row = 8, column = 1, sticky = W)
scroll2.config(command = lstbox2.yview)
def selectexp2():
newlist2 = list()
selection2 = lstbox2.curselection()
for i in selection2:
tempvar2 = lstbox2.get(i)
newlist2.append(tempvar2)

for val in newlist2:
print (val)
selectbutt = Button(simroot, text = "Submit", command = selectexp2)
selectbutt.grid(row = 9,column = 1, sticky = W)


def Submitplot():
print "Create plot"

Button(simroot, text = "Submit and Plot", command = Submitplot).grid(row =
10, column = 0, sticky = W)

However, the issue is that when the user selects options from the first
dropdown menu and moves on to selecting the second one, the first dropdown
selections are lost, is there a way to store the highlighted selections on
the display screen? In the code, I can get them printed and save the
selections, however I was looking for a way to keep them highlighted on the
screen as well for both the drop down menus.
Please let me know.
Thank you

Pooja

From alan.gauld at yahoo.co.uk  Thu Feb 23 20:41:31 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 24 Feb 2017 01:41:31 +0000
Subject: [Tutor] Asking about Opening Teminal on Python
In-Reply-To: <CAGHbcgN4ccwQmnZ7c0riz5vg8iYC0GQC=-tv9FunRYOtTW7w8Q@mail.gmail.com>
References: <CAGHbcgN4ccwQmnZ7c0riz5vg8iYC0GQC=-tv9FunRYOtTW7w8Q@mail.gmail.com>
Message-ID: <o8o305$fq2$1@blaine.gmane.org>

On 23/02/17 22:16, Quang nguyen wrote:
> Hi everyone,
> I need to open a terminal on Raspberry Pi 2 in order to execute codesend of
> 433Utils to send a signal to RF Receiver. Anyone know how to open a
> terminal?

Do you really need a terminal? Or do you only need to execute some commands?

In either case the subprocess module should do what you need.
In the first case execute your local terminal program (eg xterm)
In the second case execute the command you want directly
via subprocess. This will be more efficient and save an extra
terminal window popping up to distract your user.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Thu Feb 23 20:51:42 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 24 Feb 2017 01:51:42 +0000
Subject: [Tutor] Multiple muti-selection dropdown options
In-Reply-To: <CAK0ikxcuS2Z71HvcuVe1dkHgv+hEu1rhcX5Fzv3_ibq+SSHF7A@mail.gmail.com>
References: <CAK0ikxcuS2Z71HvcuVe1dkHgv+hEu1rhcX5Fzv3_ibq+SSHF7A@mail.gmail.com>
Message-ID: <o8o3j7$rg0$1@blaine.gmane.org>

On 23/02/17 22:25, Pooja Bhalode wrote:

> I am working on GUI where I have two dropdown menus in a Toplevel of the
> main root. 

That's not what your code shows. It shows scrolling listboxes, not
menus. But it seems like a Frame with a set of checkboxes would be
closer to what you actually want?

Anyway...

> The window shows as below:
> [image: Inline image 1]

As I keep pointing out you cannot send images to this list,
the server throws them away as potential security risks.

> Whereas the code is:
> 
> def selectexp():
> newlist = list()
> selection = lstbox.curselection()
> for i in selection:
> tempvar = lstbox.get(i)
> newlist.append(tempvar)
> 

Note that in this function you create a list, populate
it with values and then throw them all away. If you want
to keep the values you need to declare the list as a
global variable.

> for val in newlist:
> print (val)

Because you are not posting in plain text I can't
tell if those two lines are inside the previous
function or not. I'm assuming they are inside the
function? If not I'd expect a name error for newlist?

> def selectexp2():
> newlist2 = list()
> selection2 = lstbox2.curselection()
> for i in selection2:
> tempvar2 = lstbox2.get(i)
> newlist2.append(tempvar2)
> 
> for val in newlist2:
> print (val)

Same problem here, you declare newlist2 as a new
list inside the function, then when the function
exits it throws it away. If you want to access
variables after the function exits you need to
make them global (or start using classes and
objects)

> However, the issue is that when the user selects options from the first
> dropdown menu and moves on to selecting the second one, the first dropdown
> selections are lost, 

See comments above. Make the lists global.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Thu Feb 23 22:01:34 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 23 Feb 2017 21:01:34 -0600
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CANDiX9+6d9V39ATLkEGVdjCR2XBkBBxLYe_q9-+KMircXg67Uw@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
 <CANDiX9+6d9V39ATLkEGVdjCR2XBkBBxLYe_q9-+KMircXg67Uw@mail.gmail.com>
Message-ID: <CANDiX9JGNeEW19Wg29n3MY-DiErsPC=Opo+czaoEXTGYScEdhA@mail.gmail.com>

Thank you to everyone that provided illumination in this thread!
Things seem much clearer now, which caused me to realize that what I
wrote below cannot work as written (Even though I did copy and paste
it from the interpreter):

On Wed, Feb 22, 2017 at 10:53 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> On Wed, Feb 22, 2017 at 10:25 PM, boB Stepp <robertvstepp at gmail.com> wrote:
>> I am trying to wrap my head around the mechanics of inheritance in
>> Python 3.  I thought that all attributes of a superclass were
>> accessible to an instance of a subclass.  But when I try the
>> following:
>>
>> py3: class A:
>> ...     def __init__(self):
>> ...             self.aa = 'class A'
>> ...
>> py3: class B(A):
>> ...     def __init__(self):
>> ...             self.bb = 'class B'
>> ...
>> py3: a = A()
>> py3: b = B()
>> py3: b.aa
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> AttributeError: 'B' object has no attribute 'aa'
>>
>> I am unsuccessful...
>
> I have partially answered my own question, but I am not sure I
> understand the mechanics yet.  Apparently I must explicitly assign
> class A's attribute, aa, to an instance of class B as follows:
>
> py3: class B(A):
> ...     def __init__(self):
> ...             self.aa = super().aa
> ...             self.bb = 'class B'
> ...
> py3: b = B()
> py3: b.aa
> 'class A'

If I had copied and pasted the above two sections of code
*contiguously*, this should have resulted in:

py3: class B(A):
...     def __init__(self):
...             self.aa = super().aa
...             self.bb = 'class B'
...
py3: b = B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
AttributeError: 'super' object has no attribute 'aa'
py3: a = A()
py3: b = B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
AttributeError: 'super' object has no attribute 'aa'

When I went back to scroll back in ConEmu (Thanks Eryk Sun for
bringing this program to my attention!), I found that I had redefined
class A as follows:

py3: class A:
...     aa = 'class A'
...

between those two blocks of code, which explains why "b = B()"
followed by "b.aa" worked.

Sorry 'bout that!  I did mention I was sleepy at the time... ~(:>))

-- 
boB

From robertvstepp at gmail.com  Thu Feb 23 22:11:37 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 23 Feb 2017 21:11:37 -0600
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <CAKJDb-OxjFXi_Hc1EoyAvkwiNFO=K3482EzYwCQQk_z=u4G4UA@mail.gmail.com>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
 <CAKJDb-OxjFXi_Hc1EoyAvkwiNFO=K3482EzYwCQQk_z=u4G4UA@mail.gmail.com>
Message-ID: <CANDiX9Jp_YEWc1yU=02FDQNp9sgp6YO_VtbwOLz3mcFqshdD5Q@mail.gmail.com>

On Wed, Feb 22, 2017 at 10:49 PM, Zachary Ware
<zachary.ware+pytut at gmail.com> wrote:
> On Wed, Feb 22, 2017 at 10:25 PM, boB Stepp <robertvstepp at gmail.com> wrote:

>
> I'll give you a couple of hints.  First, try this:
>
> print('defining A')
> class A:
>     print('Setting a on class A')

When I typed this in I was surprised to find that the print() happens
without having created an instance of this class yet.  Further
experimentation seems to indicate that all class methods and
attributes get executed and assigned when the class definition is
first read into the interpreter without any need to create an instance
of the class.  This is good to know!

> Next, have a look at
> https://docs.python.org/3/library/functions.html#super and in
> particular the link at the end to Raymond Hettinger's "super
> considered super" essay.

I had actually bookmarked this last week in my browser for later
reading.  I just got finished reading it.  It has brought additional
clarity, but also much more I need to think about and explore.

Thanks, Zach!



-- 
boB

From steve at pearwood.info  Thu Feb 23 23:45:03 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 Feb 2017 15:45:03 +1100
Subject: [Tutor] How to access an instance variable of a superclass from
 an instance of the subclass?
In-Reply-To: <20170223104003.GZ5689@ando.pearwood.info>
References: <CANDiX9J5KBXKOfnaqLf9RMeNU+tdzBnkGqAZ02sVMem8rmzT1g@mail.gmail.com>
 <20170223104003.GZ5689@ando.pearwood.info>
Message-ID: <20170224044503.GF5689@ando.pearwood.info>

On Thu, Feb 23, 2017 at 09:40:14PM +1100, Steven D'Aprano wrote:

> How do instance attributes normally get set? In the __init__ method:
> 
> class MyClass:
>     def __init__(self):
>         self.attribute = None
> 
> 
> If the __init__ method does get run, it doesn't get the chance to create 
> the instance attributes. So if you have a subclass that defines 
> __init__, you need to allow the superclass' __init__ to run too.

/me slaps forehead

Of course I meant to write:

If the __init__ method does NOT get run, it doesn't get the chance to 
create the instance attributes.


Sorry for any confusion.


-- 
Steve

From alan.gauld at yahoo.co.uk  Fri Feb 24 04:28:02 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 24 Feb 2017 09:28:02 +0000
Subject: [Tutor] Asking about Opening Teminal on Python
In-Reply-To: <CAGHbcgMxKzrxcK8xP1xaZPOfdFKH9dAF+v8PCcun8q4xTFRk3A@mail.gmail.com>
References: <CAGHbcgN4ccwQmnZ7c0riz5vg8iYC0GQC=-tv9FunRYOtTW7w8Q@mail.gmail.com>
 <o8o305$fq2$1@blaine.gmane.org>
 <CAGHbcgOfbPKBf+QL08-vh9q8z6FhORg-9sVO7nFr8VE9gmUP5Q@mail.gmail.com>
 <CAGHbcgOqJQ7F2nPgosbmBuGJBzXUAFVJM4GxEQFB5gy=41vKjg@mail.gmail.com>
 <CAGHbcgOFaduJf02Rx2WZY4xLpstvN2rjas+1u+mNh0aip1btug@mail.gmail.com>
 <CAGHbcgOT=WSkCx+oNxEQWR4-L0uT-AXtCi3ZGYTeh9H5tfRz1g@mail.gmail.com>
 <CAGHbcgN9tF7kWt--ajR-f2oYU7iZ8D3tEs6U9nZ-ak=G8KxXQg@mail.gmail.com>
 <CAGHbcgPWELwKCrHwGSdo7BUwx79YvhOUnS5Bac-nwgMu-VDe3g@mail.gmail.com>
 <CAGHbcgMKt5mruuZD6WgZLKw+SdfhpHYq2zMcG0RGPCjBHqMnjw@mail.gmail.com>
 <CAGHbcgOPQS78yL4CRVLGVhKghHUDcwJs589WDqXTW3LVk6Mocw@mail.gmail.com>
 <CAGHbcgMxKzrxcK8xP1xaZPOfdFKH9dAF+v8PCcun8q4xTFRk3A@mail.gmail.com>
Message-ID: <d1af3c60-ac55-56d1-cadf-7fc4ee354afb@yahoo.co.uk>

On 24/02/17 02:04, Quang nguyen wrote:
> Right now, I have school project for sending signal from Pi2 to
> mutilple devices. And I am using 433Utils library for sending
> and receiving signal. They provided file for do that but it only
> execute on terminal, and i also have an UI.
>
> So I have an idea that will execute the sending command
> by terminal behind my UI.

That's probably the wrong approach.
What you really want to do is execute the command you
would normally type at the terminal, directly from your GUI.
You only need to start a terminal if your user needs to
enter the commands manually.

For example, here is some code to execute the 'ls'
command and print only files that have a name shorter
than 6 characters:

#!/usr/bin/python3
import subprocess as sub

ls_out = sub.Popen(['ls'], stdout=sub.PIPE).stdout
for name in ls_out:
    if len(name) < 6:
        print(name)
###############

You can substitute any command for 'ls' and you
can add arguments too.

You can also assign stdin as a pipe in the same way
as stdout and use that to inject data into the
command.

You can even make stdin/stdout use files too. Here is
the above example saving the output to a text file:

sub.Popen(['ls'], stdout=open('ls_out.txt','w'))

You can then read and manipulate the data
from ls_out.txt as desired.

The subprocess module documentation contains
many examples.

So unless you really need your user to type
the commands by hand you don't need a
terminal window.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From poojabhalode11 at gmail.com  Fri Feb 24 09:39:52 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Fri, 24 Feb 2017 09:39:52 -0500
Subject: [Tutor] Multiple muti-selection dropdown options
In-Reply-To: <CAK0ikxfo+U6PGDdFEiBJ3s3Q0nYKbHJasAcnTpjCzbH_LR_ejw@mail.gmail.com>
References: <CAK0ikxcuS2Z71HvcuVe1dkHgv+hEu1rhcX5Fzv3_ibq+SSHF7A@mail.gmail.com>
 <o8o3j7$rg0$1@blaine.gmane.org>
 <CAK0ikxfo+U6PGDdFEiBJ3s3Q0nYKbHJasAcnTpjCzbH_LR_ejw@mail.gmail.com>
Message-ID: <CAK0ikxdrZAA80vc=70H_eL7kx9f-VXYe3+ACFG56NYVfAkXR-g@mail.gmail.com>

Hi Alan,

Thank you for your inputs. I made the lists global in the Toplevel root. I
still have the problem where in if I select few options from the first
list, and then move to the next list, I loose the selections made on the
screen in the first list. I can however print it out and store it in the
code, but I would like to show it on the screen as well as highlighted even
after moving to the next list. Can you please tell me if there is a way?
Sorry about inserting the images, I was unaware of that and also regarding
some of my nomenclature mistakes, still learning :)

Thank you

Pooja

On Thu, Feb 23, 2017 at 10:37 PM, Pooja Bhalode <poojabhalode11 at gmail.com>
wrote:

>
> ---------- Forwarded message ----------
> From: Alan Gauld via Tutor <tutor at python.org>
> Date: Thu, Feb 23, 2017 at 8:51 PM
> Subject: Re: [Tutor] Multiple muti-selection dropdown options
> To: tutor at python.org
>
>
> On 23/02/17 22:25, Pooja Bhalode wrote:
>
> > I am working on GUI where I have two dropdown menus in a Toplevel of the
> > main root.
>
> That's not what your code shows. It shows scrolling listboxes, not
> menus. But it seems like a Frame with a set of checkboxes would be
> closer to what you actually want?
>
> Anyway...
>
> > The window shows as below:
> > [image: Inline image 1]
>
> As I keep pointing out you cannot send images to this list,
> the server throws them away as potential security risks.
>
> > Whereas the code is:
> >
> > def selectexp():
> > newlist = list()
> > selection = lstbox.curselection()
> > for i in selection:
> > tempvar = lstbox.get(i)
> > newlist.append(tempvar)
> >
>
> Note that in this function you create a list, populate
> it with values and then throw them all away. If you want
> to keep the values you need to declare the list as a
> global variable.
>
> > for val in newlist:
> > print (val)
>
> Because you are not posting in plain text I can't
> tell if those two lines are inside the previous
> function or not. I'm assuming they are inside the
> function? If not I'd expect a name error for newlist?
>
> > def selectexp2():
> > newlist2 = list()
> > selection2 = lstbox2.curselection()
> > for i in selection2:
> > tempvar2 = lstbox2.get(i)
> > newlist2.append(tempvar2)
> >
> > for val in newlist2:
> > print (val)
>
> Same problem here, you declare newlist2 as a new
> list inside the function, then when the function
> exits it throws it away. If you want to access
> variables after the function exits you need to
> make them global (or start using classes and
> objects)
>
> > However, the issue is that when the user selects options from the first
> > dropdown menu and moves on to selecting the second one, the first
> dropdown
> > selections are lost,
>
> See comments above. Make the lists global.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>

From __peter__ at web.de  Fri Feb 24 14:02:30 2017
From: __peter__ at web.de (Peter Otten)
Date: Fri, 24 Feb 2017 20:02:30 +0100
Subject: [Tutor] Multiple muti-selection dropdown options
References: <CAK0ikxcuS2Z71HvcuVe1dkHgv+hEu1rhcX5Fzv3_ibq+SSHF7A@mail.gmail.com>
Message-ID: <o8q004$l3o$1@blaine.gmane.org>

Pooja Bhalode wrote:

> I am working on GUI where I have two dropdown menus in a Toplevel

Actually your code shows two Listbox wigets.

> However, the issue is that when the user selects options from the first
> dropdown menu and moves on to selecting the second one, the first dropdown
> selections are lost, is there a way to store the highlighted selections on
> the display screen?

With the help of a search engine I found out that you need to specify

listbox = Listbox(..., exportselection=False)


From alan.gauld at yahoo.co.uk  Fri Feb 24 14:58:56 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 24 Feb 2017 19:58:56 +0000
Subject: [Tutor] Multiple muti-selection dropdown options
In-Reply-To: <CAK0ikxdrZAA80vc=70H_eL7kx9f-VXYe3+ACFG56NYVfAkXR-g@mail.gmail.com>
References: <CAK0ikxcuS2Z71HvcuVe1dkHgv+hEu1rhcX5Fzv3_ibq+SSHF7A@mail.gmail.com>
 <o8o3j7$rg0$1@blaine.gmane.org>
 <CAK0ikxfo+U6PGDdFEiBJ3s3Q0nYKbHJasAcnTpjCzbH_LR_ejw@mail.gmail.com>
 <CAK0ikxdrZAA80vc=70H_eL7kx9f-VXYe3+ACFG56NYVfAkXR-g@mail.gmail.com>
Message-ID: <o8q39q$56k$1@blaine.gmane.org>

On 24/02/17 14:39, Pooja Bhalode wrote:

> list, and then move to the next list, I loose the selections made on the
> screen in the first list. I can however print it out and store it in the
> code, but I would like to show it on the screen as well

Peter has given you the answer: you need to specify
exportselection as False.

What he didn't explain is why... The default behaviour is
for the selections to be copied to the OS Windows selection
mechanism, so when tyou move to a new widget and select
something else the OS selection moves there and you lose
the previous selection. This interchange between the OS
selection and the Tkinter selection is the "export"
bit of exportselection. By making it false the OS no
longer grabs your selection and thus each widget
is free to keep track of its own. The downside is
you can no onger use your selection in any other
window (eg paste it into a field). But for this
example I doubt if that matters.

BTW You may want to change selectionmode to EXTENDED
Which shows the multiple selections more clearly
 - I think that will suit your needs better.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From ehsan2324 at gmail.com  Sat Feb 25 05:35:21 2017
From: ehsan2324 at gmail.com (ehsan faraz)
Date: Sat, 25 Feb 2017 02:35:21 -0800
Subject: [Tutor] Invalid Syntax
Message-ID: <FD27B649-C604-41F3-BC15-963D8EBF7E9B@gmail.com>

Hello, I am working on the following assignment where ?tip? is an invalid syntax. Can someone please tell me how to fix this? Here is what it should look like:

Welcome to Restaurant Helper. 
Enter the menu price for your meal: 100 
Enter your tip percentage: 15 T
he price of the meal is: 100.00 
The sales tax due is: 8.50 
The tip amount is: 15.00 
The total due is: 123.50

The program asks the diner for the menu price of the meal and what percentage of that price the diner wishes to give as a tip. 
The program then computes the sales tax amount, the tip amount, and the total that will be paid to the restaurant.
The program should assume that the local sales tax is 8.5 percent. Also, the program should compute the amount of the tip by applying the tip percentage only to the menu price. 


sales_tax = 0.085 * price

total_due = sales_tax * price + tip

tip = tip

print("Welcome to Restaurant Helper.")
price = int(input("Enter the menu price for your meal:")
tip = int(input("Enter your tip percentage:")
print("The price of the meal is:" , price)
print("The sales tax due is:" , sales_tax)
print("The tip amount is:" , tip)
print("the total due is:" , total_due) 

From rafael.knuth at gmail.com  Sat Feb 25 12:12:02 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Sat, 25 Feb 2017 18:12:02 +0100
Subject: [Tutor] counting number of loops
Message-ID: <CAM-E2X7p-uSKszU1q0Q-7AXXuuyOTnXbE4mAPFJHEWaE3XPHqQ@mail.gmail.com>

I want to compare two strings and count the number of identical letters:

stringB = "ABCD"
stringA = "AABBCCDDEE"
for b in stringB:
    if b in stringA:
        r = 0
        r += 1
        print (r)

How do I count the output (r) instead of printing it out?
(result should be 4). Thanks!

From alan.gauld at yahoo.co.uk  Sat Feb 25 12:24:44 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 25 Feb 2017 17:24:44 +0000
Subject: [Tutor] Fwd: Re:  SciPy Optimize-like calling function as string
In-Reply-To: <1E391E1A-76D2-42B6-9CA4-C78F7037C4C6@wright.edu>
References: <1E391E1A-76D2-42B6-9CA4-C78F7037C4C6@wright.edu>
Message-ID: <dbbe5d22-7f07-5258-49a7-f838933ceca4@yahoo.co.uk>

Forwarding to list.

Please always use reply-All or Reply-list when responding to the list.

On Feb 18, 2017, at 6:21 PM, Alan Gauld via Tutor <tutor at python.org
<mailto:tutor at python.org>> wrote:
>
> On 18/02/17 21:52, Joseph Slater wrote:
>> I'm trying to use the scipy.optimize code ...
>> I've seen this done with dictionaries on some pages,
>> but it seems that this is intended to be faster
>
> There is a saying in programming that premature
> optimization is the root of all evil.

This is true, but I'm conceding that I don't need the solution so much
as I'm trying to polish my Python. In fact, there is no problem I'm
solving today. This is mostly a training exercise. I'd like to be as
"pythonic" as possible in the long run.

>
> If you don't know that you need to optimize then your
> time is usually better spent elsewhere. Dictionaries
> are pretty fast in Python and I'd suggest you try
> that first before shaving milliseconds in places
> that may not be where you need to make savings.

Honestly, that method makes no sense to me whatsoever. 

>
> Identify an actual problem, then identify the cause
> and optimise that. Don't try to second guess the future.
> Most performance problems are down to bad algorithms
> or bad data structures not bad dispatch techniques.

(I will go Google "dispatch techniques"). 

I'm trying to overcome 20 years of "Matlab" programming to modernize.
I've fallen way out of touch and taken this up as a hobby that may also
be professionally helpful from time to time. 

Sorry for the delay. I really do appreciate the responses. It's my hobby
versus my day job now. My students get all the fun of actually
programing these days!


Professor & Chair
~~~~~~~~~~~~~~~~~~~~~~~~
(+1) 937-775-5040
https://people.wright.edu/joseph.slater


From alan.gauld at yahoo.co.uk  Sat Feb 25 12:28:29 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 25 Feb 2017 17:28:29 +0000
Subject: [Tutor] counting number of loops
In-Reply-To: <CAM-E2X7p-uSKszU1q0Q-7AXXuuyOTnXbE4mAPFJHEWaE3XPHqQ@mail.gmail.com>
References: <CAM-E2X7p-uSKszU1q0Q-7AXXuuyOTnXbE4mAPFJHEWaE3XPHqQ@mail.gmail.com>
Message-ID: <o8sern$aeu$1@blaine.gmane.org>

On 25/02/17 17:12, Rafael Knuth wrote:
> I want to compare two strings and count the number of identical letters:
> 
> stringB = "ABCD"
> stringA = "AABBCCDDEE"
> for b in stringB:
>     if b in stringA:
>         r = 0
>         r += 1
>         print (r)
> 
> How do I count the output (r) instead of printing it out?
> (result should be 4). Thanks!

You are very close.
You are doing too much inside the for loop.
1) initialise the counter 'r' before the loop starts
 - you only want it set to zero at the begiunning not
   everytime you go through the loop.

2) move the print(r) line out of the loop at the end
 - you only really need to know the final answer, not
   the answer after each loop iteration..

BTW If you have covered sets then there is an easier
solution by converting both strings to sets and
taking the intersection. But you may not have
done sets yet...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Sat Feb 25 12:33:39 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 25 Feb 2017 17:33:39 +0000
Subject: [Tutor] Invalid Syntax
In-Reply-To: <FD27B649-C604-41F3-BC15-963D8EBF7E9B@gmail.com>
References: <FD27B649-C604-41F3-BC15-963D8EBF7E9B@gmail.com>
Message-ID: <o8sf5d$hg5$1@blaine.gmane.org>

On 25/02/17 10:35, ehsan faraz wrote:
> ... where ?tip? is an invalid syntax. 

You need to assign a value to tip before trying
to read it, otherwise tip is undefined.

Similarly you should define price before trying
to use it.

But those would give you a NameError not a
syntax error... Can you send us the full error
text please (always do this when posting, it
helps a lot)


> sales_tax = 0.085 * price
> total_due = sales_tax * price + tip

You access price and tip before defining them.

And shouldn't that * be a +?

> tip = tip

This line does nothing

> print("Welcome to Restaurant Helper.")

> price = int(input("Enter the menu price for your meal:")
> tip = int(input("Enter your tip percentage:")

You need these 2 lines before the calculations above.

> print("The price of the meal is:" , price)
> print("The sales tax due is:" , sales_tax)
> print("The tip amount is:" , tip)
> print("the total due is:" , total_due) 


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Sat Feb 25 12:36:58 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 26 Feb 2017 04:36:58 +1100
Subject: [Tutor] Invalid Syntax
In-Reply-To: <FD27B649-C604-41F3-BC15-963D8EBF7E9B@gmail.com>
References: <FD27B649-C604-41F3-BC15-963D8EBF7E9B@gmail.com>
Message-ID: <20170225173655.GH5689@ando.pearwood.info>

On Sat, Feb 25, 2017 at 02:35:21AM -0800, ehsan faraz wrote:

> Hello, I am working on the following assignment where ?tip? is an 
> invalid syntax. Can someone please tell me how to fix this? Here is 
> what it should look like:

Hello, and welcome!

Why don't you show us the actual error message you get? That will point 
to the line with the problem, or at worst the next line. Otherwise we 
have to GUESS where the problem is.

My guess is that the syntax error is this line:

> tip = int(input("Enter your tip percentage:")

Count the opening brackets ( and the closing brackets ). They don't 
match:

  ( ( )


By the way, you had an earlier line of code:


> tip = tip

That line is useless. Take it out.



-- 
Steve

From alan.gauld at yahoo.co.uk  Sat Feb 25 12:37:15 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 25 Feb 2017 17:37:15 +0000
Subject: [Tutor] Fwd: Re: SciPy Optimize-like calling function as string
In-Reply-To: <dbbe5d22-7f07-5258-49a7-f838933ceca4@yahoo.co.uk>
References: <1E391E1A-76D2-42B6-9CA4-C78F7037C4C6@wright.edu>
 <dbbe5d22-7f07-5258-49a7-f838933ceca4@yahoo.co.uk>
Message-ID: <o8sfc5$q30$1@blaine.gmane.org>

On 25/02/17 17:24, Alan Gauld via Tutor wrote:

>> If you don't know that you need to optimize then your
>> time is usually better spent elsewhere. Dictionaries
>> are pretty fast in Python and I'd suggest you try
>> that first before shaving milliseconds in places
>> that may not be where you need to make savings.
> 
> Honestly, that method makes no sense to me whatsoever. 

Sorry, what I meant is: try the simpler dictionary
based technique first. Dictionaries are what Python
uses internally for almost everything so they
are very fast. Only if you know you need to improve
on their performance should you try using other
techniques (and that's an extremely rare scenario).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Sat Feb 25 12:43:24 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 25 Feb 2017 18:43:24 +0100
Subject: [Tutor] Invalid Syntax
References: <FD27B649-C604-41F3-BC15-963D8EBF7E9B@gmail.com>
 <o8sf5d$hg5$1@blaine.gmane.org>
Message-ID: <o8sfnm$u50$1@blaine.gmane.org>

Alan Gauld via Tutor wrote:

> On 25/02/17 10:35, ehsan faraz wrote:
>> ... where ?tip? is an invalid syntax.

Alan went one step ahead and addressed the logical errors, but the 
SyntaxError is caused by missing closing parentheses:

>> price = int(input("Enter the menu price for your meal:")
>> tip = int(input("Enter your tip percentage:")



From sjeik_appie at hotmail.com  Sun Feb 26 01:22:02 2017
From: sjeik_appie at hotmail.com (Albert-Jan Roskam)
Date: Sun, 26 Feb 2017 06:22:02 +0000
Subject: [Tutor] Matplotlib in Tkinter
In-Reply-To: <CAK0ikxdNMUWjzi2P-5fZtwE1mP--+w7KeBAtg7VhyLEZCc9M9A@mail.gmail.com>
References: <CAK0ikxdNMUWjzi2P-5fZtwE1mP--+w7KeBAtg7VhyLEZCc9M9A@mail.gmail.com>
Message-ID: <AM4PR1001MB1250BDA71AFF6E020068CF7383540@AM4PR1001MB1250.EURPRD10.PROD.OUTLOOK.COM>

(Sorry for top-posting)

Hi, I recently ran into the same problem when I wanted to embed an interactive Matplotlib choropleth in my Tkinter app. I solved it by creating a separate class MyPlot for plot + toolbar (it inherited from Tkinter.Frame). MyPlot internally uses the pack geometry manager as given in the example from the mpl website. Then, you use MyPlot as 'one unit', and you use the grid method on its instances.

Best wishes,
Albert-Jan
________________________________
From: Tutor <tutor-bounces+sjeik_appie=hotmail.com at python.org> on behalf of Pooja Bhalode <poojabhalode11 at gmail.com>
Sent: Sunday, February 19, 2017 7:36:32 PM
To: tutor at python.org
Subject: [Tutor] Matplotlib in Tkinter

Hi,

I am trying to create a graph in Tkinter window. And following is a snipet
of the code.

Code:
  simroot = Toplevel(root)
simroot.title("Simulation of experiments")
Label(simroot, text = "Displaying concentration profiles with respect to
time:").pack(side = TOP)

Label(simroot, text = "Select the experiments to be displayed: ").pack(side
= TOP)
optionexp = ['Experiment 1', 'Experiment 2', 'Experiment 3', 'Experiment
4', 'Experiment 5']
expsim = StringVar()
dropexp = OptionMenu(simroot, expsim, *optionexp)
dropexp.pack(side = TOP)
dropexp.config(width = 15)

# Row 1 would print the name of the experiment selected and the species
displayed would be in row3.
Label(simroot, text = "Select concentration species:").pack(side = TOP)
concsim = StringVar()
optionlistsim = ['A', 'B', 'C', 'D', 'E']
dropsim = OptionMenu(simroot, concsim, *optionlistsim)
dropsim.pack(side = TOP)
dropsim.config(width = 8)
Label(simroot, text = "").pack(side = LEFT)

def Submitplot():
print "Create plot"

f = Figure(figsize = (5,5), dpi = 80)
a = f.add_subplot(111)
a.plot([1,2,3,4,5],[10,11,12,14,15])

canvas = FigureCanvasTkAgg(f, simroot)
canvas.show()
canvas.get_tk_widget().pack(side = BOTTOM)

toolbar = NavigationToolbar2TkAgg(canvas, simroot)
toolbar.update()
canvas._tkcanvas.pack(side = BOTTOM)
Button(simroot, text = "Submit and Plot", command = Submitplot).pack(side =
BOTTOM)

Here, the output comes as:
[image: Inline image 1]
The problem is I am not able to use grid layout instead of pack (used
here). I want to place the text to the left, top side in the window.

Also, when I hover the mouse over the figure and the x and y values are
shown, it flickers really fast and the white space in the Tkinter window
turns black when it flickers. Can someone please tell me what the issue
could be? Also, the toolbar should have been at the bottom but it shows up
at the top.

I am using pack in this Toplevel of the main root whereas in the rest of
the code, I am using grid layout. I switched to pack for this
snipet because I could not figure out how grid would work for this part.

Can someone please let me know how to correct these issues?
Thankyou so much.

Pooja
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From phil_lor at bigpond.com  Sun Feb 26 01:44:22 2017
From: phil_lor at bigpond.com (Phil)
Date: Sun, 26 Feb 2017 16:44:22 +1000
Subject: [Tutor] UDP client
Message-ID: <71f5ec42-fba2-aeab-c3d5-e92e6ec695b5@bigpond.com>

Thank you for reading this.

As an exercise, and for no other purpose, I'm trying to convert some C++ 
code that I put together 17 years ago. I'm very rusty and hours of 
Internet searches have made me more confused that I was to start with.

The following works under Python2 but not under Python3.

import socket

host = "127.0.0.1"
#host = "localhost"

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.connect((host, 1210))

data = "GET_LIST"

s.sendall(data)

#s.sendto(data, (host, 1210))

s.shutdown(1)

while 1:
     buf = s.recv(2048)
     if not len(buf):
         break
     #print "Received: %s" % buf

According to the Python3 wiki sendto() should work under Python3 but I 
get this error:

Traceback (most recent call last):
   File "/home/phil/Python/predict_client1.py", line 12, in <module>
     s.sendall(data)
TypeError: a bytes-like object is required, not 'str'

The same error is received if I use sendall(data).

So, is this reasonable UDP client code and what have I overlooked to get 
this to work under Python3?

-- 
Regards,
Phil

From __peter__ at web.de  Sun Feb 26 03:33:43 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 26 Feb 2017 09:33:43 +0100
Subject: [Tutor] UDP client
References: <71f5ec42-fba2-aeab-c3d5-e92e6ec695b5@bigpond.com>
Message-ID: <o8u3t2$fqs$1@blaine.gmane.org>

Phil wrote:

> Thank you for reading this.
> 
> As an exercise, and for no other purpose, I'm trying to convert some C++
> code that I put together 17 years ago. I'm very rusty and hours of
> Internet searches have made me more confused that I was to start with.
> 
> The following works under Python2 but not under Python3.

> data = "GET_LIST"

This is a sequence of bytes in Python 2 and a sequence of unicode codepoints 
in Python 3. You are using a low-level protocol and need bytes

data = b"GET_LIST"

If your original data is a string you have to encode, for example

data = "M?glich".encode("utf-8")

> So, is this reasonable UDP client code and what have I overlooked to get
> this to work under Python3?

You ran into one of the most prominent changes between Python 2 and 3. In 
py3 you have to be explicit if you want bytes

b"bytes", "unicode", u"unicode"

which resembles the needs of most users while in py2 you have to be explicit 
if you want unicode

b"bytes", "bytes", u"unicode"

which in combination with implicit conversion led to many bugs that only 
users in non-ascii-land would encounter.



From alan.gauld at yahoo.co.uk  Sun Feb 26 03:42:15 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 26 Feb 2017 08:42:15 +0000
Subject: [Tutor] UDP client
In-Reply-To: <71f5ec42-fba2-aeab-c3d5-e92e6ec695b5@bigpond.com>
References: <71f5ec42-fba2-aeab-c3d5-e92e6ec695b5@bigpond.com>
Message-ID: <o8u4d1$58o$1@blaine.gmane.org>

On 26/02/17 06:44, Phil wrote:

> s.connect((host, 1210))
> data = "GET_LIST"

This is a string, you need to use bytes.

data = bytes("GET_LIST",'utf8')

> s.sendall(data)
> #s.sendto(data, (host, 1210))
> s.shutdown(1)

> Traceback (most recent call last):
>    File "/home/phil/Python/predict_client1.py", line 12, in <module>
>      s.sendall(data)
> TypeError: a bytes-like object is required, not 'str'

Python 3 uses unicode strings by default.
Many low level functions need a byte array instead.
Usually you can just wrap your original string in
a bytes call with utf8. If you are using more complex
strings you may need to start using explicit encode/decode.
But in this case it shouldn't be needed.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phil_lor at bigpond.com  Sun Feb 26 04:21:17 2017
From: phil_lor at bigpond.com (Phil)
Date: Sun, 26 Feb 2017 19:21:17 +1000
Subject: [Tutor] UDP client
In-Reply-To: <o8u4d1$58o$1@blaine.gmane.org>
References: <71f5ec42-fba2-aeab-c3d5-e92e6ec695b5@bigpond.com>
 <o8u4d1$58o$1@blaine.gmane.org>
Message-ID: <a909801b-2249-393c-4a9f-8fa9fcb774f6@bigpond.com>

On 26/02/17 18:42, Alan Gauld via Tutor wrote:
> On 26/02/17 06:44, Phil wrote:
>
>> s.connect((host, 1210))
>> data = "GET_LIST"
>
> This is a string, you need to use bytes.
>
> data = bytes("GET_LIST",'utf8')
>

Thank you Peter and Alan for your response.

Converting "data" to bytes worked, of course. Now I have to, I think, do 
the opposite to the received data.

while 1:
     buf = s.recv(2048)
     if not len(buf):
         break
     print("Received: %s" % buf)

This prints the correct result like this:

b'ABC\DEF\ETC\n' n/

Instead of:

ABC
DEF
ETC

I tried str.decode(buf) but doesn't seem to be the answer.

-- 
Regards,
Phil

From __peter__ at web.de  Sun Feb 26 04:41:30 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 26 Feb 2017 10:41:30 +0100
Subject: [Tutor] UDP client
References: <71f5ec42-fba2-aeab-c3d5-e92e6ec695b5@bigpond.com>
 <o8u4d1$58o$1@blaine.gmane.org>
 <a909801b-2249-393c-4a9f-8fa9fcb774f6@bigpond.com>
Message-ID: <o8u7s9$8hh$1@blaine.gmane.org>

Phil wrote:

> On 26/02/17 18:42, Alan Gauld via Tutor wrote:
>> On 26/02/17 06:44, Phil wrote:
>>
>>> s.connect((host, 1210))
>>> data = "GET_LIST"
>>
>> This is a string, you need to use bytes.
>>
>> data = bytes("GET_LIST",'utf8')
>>
> 
> Thank you Peter and Alan for your response.
> 
> Converting "data" to bytes worked, of course. Now I have to, I think, do
> the opposite to the received data.
> 
> while 1:
>      buf = s.recv(2048)
>      if not len(buf):
>          break
>      print("Received: %s" % buf)
> 
> This prints the correct result like this:
> 
> b'ABC\DEF\ETC\n' n/
> 
> Instead of:
> 
> ABC
> DEF
> ETC
> 
> I tried str.decode(buf) but doesn't seem to be the answer.
 
Try

buf.decode("utf-8")

Generally:

bytes --> unicode:

some_str = some_bytes.decode(encoding)
some_str = str(some_bytes, encoding)

unicode --> bytes:

some_bytes = some_str.encode(encoding)
some_bytes = bytes(some_str, encoding)

I always use encode/decode, probably because bytes is an alias of str in py2 
and does not accept a second argument.


From sjeik_appie at hotmail.com  Sun Feb 26 16:02:22 2017
From: sjeik_appie at hotmail.com (Albert-Jan Roskam)
Date: Sun, 26 Feb 2017 21:02:22 +0000
Subject: [Tutor] Matplotlib in Tkinter
In-Reply-To: <CAK0ikxcpACUe9c3FEmem+-6wQvGjSv6W8_yNW3X5bwfEp6U-Sw@mail.gmail.com>
References: <CAK0ikxdNMUWjzi2P-5fZtwE1mP--+w7KeBAtg7VhyLEZCc9M9A@mail.gmail.com>
 <AM4PR1001MB1250BDA71AFF6E020068CF7383540@AM4PR1001MB1250.EURPRD10.PROD.OUTLOOK.COM>,
 <CAK0ikxcpACUe9c3FEmem+-6wQvGjSv6W8_yNW3X5bwfEp6U-Sw@mail.gmail.com>
Message-ID: <AM4PR1001MB12508165FEAE462118C745D283540@AM4PR1001MB1250.EURPRD10.PROD.OUTLOOK.COM>

Hi,

(CCing Python Tutor again). I meant something like below. I am sending this from my phone, which is cumbersome to use an understatement, so the indentation is lost. But I hope you get the idea. You need to inherit from Frame.

Btw, this is useful if you would like to create an interactive graph: http://stackoverflow.com/questions/22052532/matplotlib-python-clickable-points

from Tkinter import *

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class PlotGraph(Frame):. # inherits from Frame
def __init__(self, root, xaxis, yaxis):
Frame.__init__(self, root, *args, **kwargs)  # execute __init__ from super class
self.root = root
root.title("Plotting a graph")
self.xaxis = xaxis
self.yaxis = yaxis
self.f = Figure(figsize = (5,5), dpi = 90)
self.a = self.f.add_subplot(111)
self.a.plot(self.xaxis,self.yaxis)

self.canvas = FigureCanvasTkAgg(self.f,self.root)
self.canvas.show()
self.canvas.get_tk_widget().pack(side = TOP, fill = BOTH, expand = True)

# Navigation Toolbar:
self.toolbar = NavigationToolbar2TkAgg(self.canvas,self.root)
self.toolbar.update()
self.canvas._tkcanvas.pack()

if __name__ == '__main__':
root = Tk()
root.title( "Creating a plot")
xaxis = [1,2,3,4,5,6]
yaxis = [7,8,9,10,11,12]
my_plot = PlotGraph(root, xaxis, yaxis, relief=SUNKEN) # you can add any of the arguments for the Frame initializer
my_plot.grid(row=0, column=0) # use grid here
button = Button (root, text="quit", fg='red', command=root.quit)
button.grid(row=1, column=0)
root.mainloop()
________________________________
From: Pooja Bhalode <poojabhalode11 at gmail.com>
Sent: Sunday, February 26, 2017 3:47:37 PM
To: Albert-Jan Roskam
Subject: Re: [Tutor] Matplotlib in Tkinter

Hi Albert,

Thank you so much for getting back to me. I tried your approach but it still fails for me. I created a class with pack(). But when I try using grid for the Label highlighted below, the gui hangs up and does not show anything.
Can you please shed more light on how to use my_plot as one unit and use grid packing for its instances?
Thank you so much.

Also, does using class with a pack layout help with screen blackening or two plots getting created?

Please let me know.
Yours truly,
Pooja

Code:

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

from Tkinter import *
root = Tk()

Label(root, text = "Creating a plot").pack()

class PlotGraph:
def __init__(self, root, xaxis, yaxis):
self.root = root
root.title("Plotting a graph")
self.xaxis = xaxis
self.yaxis = yaxis
self.f = Figure(figsize = (5,5), dpi = 90)
self.a = self.f.add_subplot(111)
self.a.plot(self.xaxis,self.yaxis)


self.canvas = FigureCanvasTkAgg(self.f,self.root)
self.canvas.show()
self.canvas.get_tk_widget().pack(side = TOP, fill = BOTH, expand = True)

# Navigation Toolbar:
self.toolbar = NavigationToolbar2TkAgg(self.canvas,self.root)
self.toolbar.update()
self.canvas._tkcanvas.pack()

self.CloseButton = Button(root, text = "Close", command = root.quit)
self.CloseButton.pack()

xaxis = [1,2,3,4,5,6]
yaxis = [7,8,9,10,11,12]
my_plot = PlotGraph(root, xaxis, yaxis)
root.mainloop()

On Sun, Feb 26, 2017 at 1:22 AM, Albert-Jan Roskam <sjeik_appie at hotmail.com<mailto:sjeik_appie at hotmail.com>> wrote:
(Sorry for top-posting)

Hi, I recently ran into the same problem when I wanted to embed an interactive Matplotlib choropleth in my Tkinter app. I solved it by creating a separate class MyPlot for plot + toolbar (it inherited from Tkinter.Frame). MyPlot internally uses the pack geometry manager as given in the example from the mpl website. Then, you use MyPlot as 'one unit', and you use the grid method on its instances.

Best wishes,
Albert-Jan
________________________________
From: Tutor <tutor-bounces+sjeik_appie=hotmail.com at python.org<mailto:hotmail.com at python.org>> on behalf of Pooja Bhalode <poojabhalode11 at gmail.com<mailto:poojabhalode11 at gmail.com>>
Sent: Sunday, February 19, 2017 7:36:32 PM
To: tutor at python.org<mailto:tutor at python.org>
Subject: [Tutor] Matplotlib in Tkinter

Hi,

I am trying to create a graph in Tkinter window. And following is a snipet
of the code.

Code:
  simroot = Toplevel(root)
simroot.title("Simulation of experiments")
Label(simroot, text = "Displaying concentration profiles with respect to
time:").pack(side = TOP)

Label(simroot, text = "Select the experiments to be displayed: ").pack(side
= TOP)
optionexp = ['Experiment 1', 'Experiment 2', 'Experiment 3', 'Experiment
4', 'Experiment 5']
expsim = StringVar()
dropexp = OptionMenu(simroot, expsim, *optionexp)
dropexp.pack(side = TOP)
dropexp.config(width = 15)

# Row 1 would print the name of the experiment selected and the species
displayed would be in row3.
Label(simroot, text = "Select concentration species:").pack(side = TOP)
concsim = StringVar()
optionlistsim = ['A', 'B', 'C', 'D', 'E']
dropsim = OptionMenu(simroot, concsim, *optionlistsim)
dropsim.pack(side = TOP)
dropsim.config(width = 8)
Label(simroot, text = "").pack(side = LEFT)

def Submitplot():
print "Create plot"

f = Figure(figsize = (5,5), dpi = 80)
a = f.add_subplot(111)
a.plot([1,2,3,4,5],[10,11,12,14,15])

canvas = FigureCanvasTkAgg(f, simroot)
canvas.show()
canvas.get_tk_widget().pack(side = BOTTOM)

toolbar = NavigationToolbar2TkAgg(canvas, simroot)
toolbar.update()
canvas._tkcanvas.pack(side = BOTTOM)
Button(simroot, text = "Submit and Plot", command = Submitplot).pack(side =
BOTTOM)

Here, the output comes as:
[image: Inline image 1]
The problem is I am not able to use grid layout instead of pack (used
here). I want to place the text to the left, top side in the window.

Also, when I hover the mouse over the figure and the x and y values are
shown, it flickers really fast and the white space in the Tkinter window
turns black when it flickers. Can someone please tell me what the issue
could be? Also, the toolbar should have been at the bottom but it shows up
at the top.

I am using pack in this Toplevel of the main root whereas in the rest of
the code, I am using grid layout. I switched to pack for this
snipet because I could not figure out how grid would work for this part.

Can someone please let me know how to correct these issues?
Thankyou so much.

Pooja
_______________________________________________
Tutor maillist  -  Tutor at python.org<mailto:Tutor at python.org>
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


From allantanaka11 at yahoo.com  Sun Feb 26 21:44:15 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Mon, 27 Feb 2017 02:44:15 +0000 (UTC)
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <o894g7$b3b$1@blaine.gmane.org>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
Message-ID: <665954003.1450570.1488163455613@mail.yahoo.com>

I try to access it with?http://0.0.0.0:8000/chart.html?via Google Chrome, FireFox, and Opera.I don't think the python code is the problem right, or? 

    On Saturday, 18 February 2017, 16:36, Alan Gauld via Tutor <tutor at python.org> wrote:
 

 
Please don't repeat post. We saw it the first time.
Please do post again with the extra information requested.

On 18/02/17 04:46, Allan Tanaka via Tutor wrote:
> Not completely sure why it doesn't open the chart on the web browser when i type this in the windows command prompt (cmd) python -m SimpleHTTPServer port 80.So first i type python ml.py data/sample.csv in cmd windows and then python -m SimpleHTTPServer port 80, but it's not proceeding to the graph in html??
> See attached image for screenshoot and complete .py file

One extra piece of information is how do you try to access the chart?
What url are you typing into ytour browser?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


   

From poojabhalode11 at gmail.com  Sun Feb 26 22:06:36 2017
From: poojabhalode11 at gmail.com (Pooja Bhalode)
Date: Sun, 26 Feb 2017 22:06:36 -0500
Subject: [Tutor] Checkbuttons Variables PY_VAR
Message-ID: <CAK0ikxeqWCT4NZY61az8pNFExatDgMGwaVDRXZvAvt0RFNm4ew@mail.gmail.com>

Hi,

The following code creates a list of checkboxes (each associated with
different variables) for the user to select from, after having selected the
ones that user wants, I am trying to add the selected variables to another
list so that the selected variables can be accessed later in the code.
However, when I try appending to the new list, it gets appended as PY_VAR
instead of the variable name associated.
Can someone please let me know where I am going wrong. I would really
appreciate it.
Thank you

Pooja
Code given below:

keqparam = IntVar()
delHrxnparam = IntVar()
kfparam = IntVar()
Afparam = IntVar()
ksimparam = IntVar()
Aparam = IntVar()
RAparam = IntVar()
RCparam = IntVar()

total_number_parameters = IntVar()
selectedparam = []
checkboxVars = [keqparam, delHrxnparam, kfparam, Afparam, ksimparam,
Aparam, RAparam, RCparam]

def EstimateParameters():
print "EstimateParameters"
paramroot = Toplevel(root)
paramroot.title("Selection of Parameters to be estimated")
def SelectAll():
for var in checkboxVars:
var.set(1)
def DeselectAll():
for var in checkboxVars:
var.set(0)

Button(paramroot, text = "Select all", command = SelectAll).grid(row = 0,
column = 2, sticky = W)
Button(paramroot, text = "Deselect all", command = DeselectAll).grid(row =
0, column = 3, sticky = W)
Label(paramroot, text = "Select all the parameters to be estimated:
").grid(row = 0, column = 0, sticky = W)
sticklabel = Label(paramroot, text = "1. Reversible reaction001")
sticklabel.grid(row = 1, column = 0, sticky = W)
Label(paramroot, text = u"\t A + B \u21cc D").grid(row = 3, column = 0,
sticky = W)
Checkbutton(paramroot, text = "K_eq", variable = keqparam).grid(row = 2,
column = 1, sticky = W)
Checkbutton(paramroot, text = u"\u0394Hrxn", variable =
delHrxnparam).grid(row = 3, column = 1, sticky = W)
Checkbutton(paramroot, text = "K_f", variable = kfparam).grid(row = 4,
column = 1, sticky = W)
Checkbutton(paramroot, text = "Eact_f", variable = Afparam).grid(row = 5,
column = 1, sticky = W)

sticklabel = Label(paramroot, text = "2. Simple reaction001")
sticklabel.grid(row = 10, column = 0, sticky = W)
Label(paramroot, text = u"\t A + C \u2192 E").grid(row = 12, column = 0,
sticky = W)
Checkbutton(paramroot, text = "Rate of reaction (k)", variable =
ksimparam).grid(row = 11, column = 1, sticky = W)
Checkbutton(paramroot, text = "Act Energy (A)", variable = Aparam).grid(row
= 12, column = 1, sticky = W)
Label(paramroot, text = "Order of reaction:").grid(row = 13, column=1,
sticky = W)
Checkbutton(paramroot, text = "Reactant A", variable = RAparam).grid(row =
13, column = 2, sticky = W)
Checkbutton(paramroot, text = "Reactant C", variable = RCparam).grid(row =
14, column = 2, sticky = W)

def SubmitParam():
global total_number_parameters
total_number_parameters = RCparam.get() + RAparam.get() + Aparam.get() +
ksimparam.get() + Afparam.get() + kfparam.get() + delHrxnparam.get() +
keqparam.get()
print total_number_parameters

for i in range(len(checkboxVars)):
if checkboxVars[i].get() == 1:
print checkboxVars[i]
selectedparam.append(checkboxVars[i])

print selectedparam


Button(paramroot, text = "Submit", command = SubmitParam).grid(row = 17,
column = 3, sticky =W)


butt1 = Button(explorer, text = "Parameters to be estimated",width = 15,
command = EstimateParameters)
butt1.pack(side = TOP)
butt1.config(font=("",9))

The highlighted area is where I am checking if the checkbutton is selected
and if selected, I am trying to append the variable name in the list
checkboxVar to the new list-selectedparam.

however, when I try to print selectedparam, I get the following output:
[<Tkinter.IntVar instance at 0x104829098>, <Tkinter.IntVar instance at
0x104829128>]
And when I try to print out checkboxVar[i] which is just above the previous
line, I get PY_VAR2
PY_VAR3

Can someone please let me know where I am going wrong?

Thankyou

Pooja

From alan.gauld at yahoo.co.uk  Mon Feb 27 04:52:49 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 09:52:49 +0000
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <665954003.1450570.1488163455613@mail.yahoo.com>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
Message-ID: <o90sta$mf5$1@blaine.gmane.org>

On 27/02/17 02:44, Allan Tanaka via Tutor wrote:
> I try to access it with http://0.0.0.0:8000/chart.html via Google Chrome, 

> On 18/02/17 04:46, Allan Tanaka via Tutor wrote:
>> Not completely sure why it doesn't open the chart on the web browser 
>> when i type this in the windows command prompt (cmd)
>> python -m SimpleHTTPServer port 80.

First that should give an error... The syntax should be:

python -m SimpleHTTPServer 80

Which should then print a message like:

Serving HTTP on 0.0.0.0 port 80 ...

Second, you are starting the web server using port 80
but you are trying to access it using port 8000. You need
to change the server startup command or change the url
so that they match.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 27 05:04:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 10:04:27 +0000
Subject: [Tutor] Checkbuttons Variables PY_VAR
In-Reply-To: <CAK0ikxeqWCT4NZY61az8pNFExatDgMGwaVDRXZvAvt0RFNm4ew@mail.gmail.com>
References: <CAK0ikxeqWCT4NZY61az8pNFExatDgMGwaVDRXZvAvt0RFNm4ew@mail.gmail.com>
Message-ID: <o90tj5$aij$1@blaine.gmane.org>

On 27/02/17 03:06, Pooja Bhalode wrote:
> The following code creates a list of checkboxes

It would really help uif you posted in plain text.
The HTML/RTF is getting very hard to read with
no indentation.

> ones that user wants, I am trying to add the selected variables to another
> list so that the selected variables can be accessed later in the code.
> However, when I try appending to the new list, it gets appended as PY_VAR
> instead of the variable name associated.

> keqparam = IntVar()
> delHrxnparam = IntVar()
> kfparam = IntVar()
> Afparam = IntVar()
> ksimparam = IntVar()
> Aparam = IntVar()
> RAparam = IntVar()
> RCparam = IntVar()
> 
> total_number_parameters = IntVar()
> selectedparam = []

> checkboxVars = [keqparam, delHrxnparam, kfparam, Afparam, ksimparam,
> Aparam, RAparam, RCparam]
...

> def SubmitParam():
> global total_number_parameters
> total_number_parameters = RCparam.get() + RAparam.get() + Aparam.get() +
> ksimparam.get() + Afparam.get() + kfparam.get() + delHrxnparam.get() +
> keqparam.get()
> print total_number_parameters

I assume this works OK and you see the correct value printed?

> for i in range(len(checkboxVars)):
> if checkboxVars[i].get() == 1:
> print checkboxVars[i]
> selectedparam.append(checkboxVars[i])

So here you append an IntVar object.


How does an IntVar show up in a ptrint?

>>> from Tkinter import *
>>> top = Tk()
>>> v = IntVar()
>>> print(v)
PY_VAR0

Which is what you see. You need to use get() to get the value:

>>> print v.get()
0
>>>

> however, when I try to print selectedparam, I get the following output:
> [<Tkinter.IntVar instance at 0x104829098>, <Tkinter.IntVar instance at
> 0x104829128>]
> And when I try to print out checkboxVar[i] which is just above the previous
> line, I get PY_VAR2
> PY_VAR3

Hopefully the reasons are now clear? You are seeing Python's
descriptions of the objects. To see the values you need to
use the get() method.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From allantanaka11 at yahoo.com  Mon Feb 27 05:13:13 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Mon, 27 Feb 2017 10:13:13 +0000 (UTC)
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <o90sta$mf5$1@blaine.gmane.org>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
Message-ID: <1622247392.1606164.1488190393519@mail.yahoo.com>

I have changed the syntax to be?python -m SimpleHTTPServer 8000 to match my ?ml python script.Still it doesn't work? Scracthing my head...See attached file for screenshoots


 

    On Monday, 27 February 2017, 16:54, Alan Gauld via Tutor <tutor at python.org> wrote:
 

 On 27/02/17 02:44, Allan Tanaka via Tutor wrote:
> I try to access it with http://0.0.0.0:8000/chart.html via Google Chrome, 

> On 18/02/17 04:46, Allan Tanaka via Tutor wrote:
>> Not completely sure why it doesn't open the chart on the web browser 
>> when i type this in the windows command prompt (cmd)
>> python -m SimpleHTTPServer port 80.

First that should give an error... The syntax should be:

python -m SimpleHTTPServer 80

Which should then print a message like:

Serving HTTP on 0.0.0.0 port 80 ...

Second, you are starting the web server using port 80
but you are trying to access it using port 8000. You need
to change the server startup command or change the url
so that they match.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


   

From phil_lor at bigpond.com  Sun Feb 26 20:14:50 2017
From: phil_lor at bigpond.com (Phil)
Date: Mon, 27 Feb 2017 11:14:50 +1000
Subject: [Tutor] UDP client
In-Reply-To: <o8u7s9$8hh$1@blaine.gmane.org>
References: <71f5ec42-fba2-aeab-c3d5-e92e6ec695b5@bigpond.com>
 <o8u4d1$58o$1@blaine.gmane.org>
 <a909801b-2249-393c-4a9f-8fa9fcb774f6@bigpond.com>
 <o8u7s9$8hh$1@blaine.gmane.org>
Message-ID: <6aede532-2d6e-a54a-291d-bf7d2ed8b253@bigpond.com>

On 26/02/17 19:41, Peter Otten wrote:
>
> Try
>
> buf.decode("utf-8")

Thank you once again Peter.

-- 
Regards,
Phil

From alan.gauld at yahoo.co.uk  Mon Feb 27 05:24:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 10:24:27 +0000
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <1622247392.1606164.1488190393519@mail.yahoo.com>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
 <1622247392.1606164.1488190393519@mail.yahoo.com>
Message-ID: <o90uol$3sg$1@blaine.gmane.org>

On 27/02/17 10:13, Allan Tanaka via Tutor wrote:
> I have changed the syntax to be python -m SimpleHTTPServer 8000 
> to match my  ml python script. Still it doesn't work?

Define "doesn't work"?

What happens? Do you see an error message - if so which one?
What happens if you use the base url?

http://0.0.0.0:8000

Do you get a list of files?
Is your chart.html listed? What happens if you click on the link?

The more specific information you give us the easier it is
for us to help you.

> Scracthing my head...See attached file for screenshoots

This is a text  based server it strips out binary
attachments as potential security risks. Cut 'n
paste the text instead.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 27 05:28:43 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 10:28:43 +0000
Subject: [Tutor] Checkbuttons Variables PY_VAR
In-Reply-To: <CAK0ikxeqWCT4NZY61az8pNFExatDgMGwaVDRXZvAvt0RFNm4ew@mail.gmail.com>
References: <CAK0ikxeqWCT4NZY61az8pNFExatDgMGwaVDRXZvAvt0RFNm4ew@mail.gmail.com>
Message-ID: <o90v0k$rig$1@blaine.gmane.org>

On 27/02/17 03:06, Pooja Bhalode wrote:

> for i in range(len(checkboxVars)):
>     if checkboxVars[i].get() == 1:
>        print checkboxVars[i]
>        selectedparam.append(checkboxVars[i])

As a point of Pythonic style this would be better
written (and easier to read) as

for var in checkboxVars:
   if var.get() == 1:
      print var.get()
      selectedparam.append(var)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 27 05:34:44 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 10:34:44 +0000
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <o90uol$3sg$1@blaine.gmane.org>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
 <1622247392.1606164.1488190393519@mail.yahoo.com>
 <o90uol$3sg$1@blaine.gmane.org>
Message-ID: <o90vbt$3kl$1@blaine.gmane.org>

On 27/02/17 10:24, Alan Gauld via Tutor wrote:
> On 27/02/17 10:13, Allan Tanaka via Tutor wrote:
>> I have changed the syntax to be python -m SimpleHTTPServer 8000 
>> to match my  ml python script. Still it doesn't work?

A couple of other things to check:

1) does check.html exist and have the content you
expect? What happens if you open it in Notepad say?

2) Does it have the right permissions to be opened
by the web server? Is it readable by users other
than yourself?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From allantanaka11 at yahoo.com  Mon Feb 27 05:40:58 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Mon, 27 Feb 2017 10:40:58 +0000 (UTC)
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <o90uol$3sg$1@blaine.gmane.org>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
 <1622247392.1606164.1488190393519@mail.yahoo.com>
 <o90uol$3sg$1@blaine.gmane.org>
Message-ID: <1362234802.1607003.1488192058596@mail.yahoo.com>

After typing?python -m SimpleHTTPServer 8000 in CMD then i proceed to my google chrome and type?http://allan-pc:8000/
That's where?Directory listing for/
Then i proceed to?http://allan-pc:8000/chart.html?No chart image whatsoever...Blank webpageIn command prompt, the message after i type?python -m SimpleHTTPServer 8000 is:Serving HTTP on 0.0.0.0 port 8000....192.168.100.6 - - [27/Feb/2017 17.36.53] "GET / HTTP/1.1" 200 -

 

    On Monday, 27 February 2017, 17:25, Alan Gauld via Tutor <tutor at python.org> wrote:
 

 On 27/02/17 10:13, Allan Tanaka via Tutor wrote:
> I have changed the syntax to be python -m SimpleHTTPServer 8000 
> to match my? ml python script. Still it doesn't work?

Define "doesn't work"?

What happens? Do you see an error message - if so which one?
What happens if you use the base url?

http://0.0.0.0:8000

Do you get a list of files?
Is your chart.html listed? What happens if you click on the link?

The more specific information you give us the easier it is
for us to help you.

> Scracthing my head...See attached file for screenshoots

This is a text? based server it strips out binary
attachments as potential security risks. Cut 'n
paste the text instead.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


   

From allantanaka11 at yahoo.com  Mon Feb 27 05:46:46 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Mon, 27 Feb 2017 10:46:46 +0000 (UTC)
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <1362234802.1607003.1488192058596@mail.yahoo.com>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
 <1622247392.1606164.1488190393519@mail.yahoo.com>
 <o90uol$3sg$1@blaine.gmane.org>
 <1362234802.1607003.1488192058596@mail.yahoo.com>
Message-ID: <1149553981.1605562.1488192406229@mail.yahoo.com>

Yes chart.html is listed but when clicked it, the page doesn't show anything. Just blank.In command prompt, the message after i clicked chart.html is like this:Serving HTTP on 0.0.0.0 port 8000....192.168.100.6 - - [27/Feb/2017 17.36.53] "GET / HTTP/1.1" 200 - 

    On Monday, 27 February 2017, 17:40, Allan Tanaka <allantanaka11 at yahoo.com> wrote:
 

 After typing?python -m SimpleHTTPServer 8000 in CMD then i proceed to my google chrome and type?http://allan-pc:8000/
That's where?Directory listing for/
Then i proceed to?http://allan-pc:8000/chart.html?No chart image whatsoever...Blank webpageIn command prompt, the message after i type?python -m SimpleHTTPServer 8000 is:Serving HTTP on 0.0.0.0 port 8000....192.168.100.6 - - [27/Feb/2017 17.36.53] "GET / HTTP/1.1" 200 -

 

    On Monday, 27 February 2017, 17:25, Alan Gauld via Tutor <tutor at python.org> wrote:
 

 On 27/02/17 10:13, Allan Tanaka via Tutor wrote:
> I have changed the syntax to be python -m SimpleHTTPServer 8000 
> to match my? ml python script. Still it doesn't work?

Define "doesn't work"?

What happens? Do you see an error message - if so which one?
What happens if you use the base url?

http://0.0.0.0:8000

Do you get a list of files?
Is your chart.html listed? What happens if you click on the link?

The more specific information you give us the easier it is
for us to help you.

> Scracthing my head...See attached file for screenshoots

This is a text? based server it strips out binary
attachments as potential security risks. Cut 'n
paste the text instead.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


   

   

From leamhall at gmail.com  Mon Feb 27 05:44:55 2017
From: leamhall at gmail.com (Leam Hall)
Date: Mon, 27 Feb 2017 05:44:55 -0500
Subject: [Tutor] Learning Objectives?
Message-ID: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>

Is there a list of Python skill progression, like "Intermediates should 
know <this> and Advanced should know <this and that>?" Trying to map out 
a well rounded study list.

Thanks!

Leam

From alan.gauld at yahoo.co.uk  Mon Feb 27 06:07:54 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 11:07:54 +0000
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <1362234802.1607003.1488192058596@mail.yahoo.com>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
 <1622247392.1606164.1488190393519@mail.yahoo.com>
 <o90uol$3sg$1@blaine.gmane.org>
 <1362234802.1607003.1488192058596@mail.yahoo.com>
Message-ID: <o911a4$i9r$1@blaine.gmane.org>

On 27/02/17 10:40, Allan Tanaka via Tutor wrote:
> After typing python -m SimpleHTTPServer 8000 in CMD 
> then i proceed to my google chrome and type http://allan-pc:8000/

OK, But to be safe I'd probably stick to 0.0.0.0 rather than your PC
name - it eliminates routing errors from the equation.

> That's where Directory listing for/

And did you see chart.html in that listing?

> Then i proceed to http://allan-pc:8000/chart.html 

How did you "proceed"?
Did you click the link in the directorty listing
or did you type it in by hand?

> No chart image whatsoever...Blank webpage

And have you checked that chart.htm is not empty
and that the html is valid?

What happens if you hand craft an html file and
try accessing that?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From allantanaka11 at yahoo.com  Mon Feb 27 06:22:15 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Mon, 27 Feb 2017 11:22:15 +0000 (UTC)
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <o911a4$i9r$1@blaine.gmane.org>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
 <1622247392.1606164.1488190393519@mail.yahoo.com>
 <o90uol$3sg$1@blaine.gmane.org>
 <1362234802.1607003.1488192058596@mail.yahoo.com>
 <o911a4$i9r$1@blaine.gmane.org>
Message-ID: <1404890103.934608.1488194535041@mail.yahoo.com>

- And did you see chart.html in that listing?
Yes it's there
- How did you "proceed"?
Did you click the link in the directorty listing
or did you type it in by hand?
I click the link in directory listing
have you checked that chart.htm is not empty?and that the html is valid?
As i click the chart.htm, it doesn't show anything. Just blank. Does it mean that i have checked chart.htm is not empty?
What happens if you hand craft an html file and try accessing that?If i type?0.0.0.0:8000/chart.html, then the error is like this:
This site can?t be reached
The webpage at?http://0.0.0.0:8000/chart.html?might be temporarily down or it may have moved permanently to a new web address.ERR_ADDRESS_INVALID
 

    On Monday, 27 February 2017, 18:11, Alan Gauld via Tutor <tutor at python.org> wrote:
 

 On 27/02/17 10:40, Allan Tanaka via Tutor wrote:
> After typing python -m SimpleHTTPServer 8000 in CMD 
> then i proceed to my google chrome and type http://allan-pc:8000/

OK, But to be safe I'd probably stick to 0.0.0.0 rather than your PC
name - it eliminates routing errors from the equation.

> That's where Directory listing for/

And did you see chart.html in that listing?

> Then i proceed to http://allan-pc:8000/chart.html 

How did you "proceed"?
Did you click the link in the directorty listing
or did you type it in by hand?

> No chart image whatsoever...Blank webpage

And have you checked that chart.htm is not empty
and that the html is valid?

What happens if you hand craft an html file and
try accessing that?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


   

From alan.gauld at yahoo.co.uk  Mon Feb 27 09:22:20 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 14:22:20 +0000
Subject: [Tutor] [Python 2.7] HELP: Serving HTTP on 0.0.0.0 port 80 not
 proceeding
In-Reply-To: <1404890103.934608.1488194535041@mail.yahoo.com>
References: <1900243490.5668.1487393160443.ref@mail.yahoo.com>
 <1900243490.5668.1487393160443@mail.yahoo.com>
 <o894g7$b3b$1@blaine.gmane.org>
 <665954003.1450570.1488163455613@mail.yahoo.com>
 <o90sta$mf5$1@blaine.gmane.org>
 <1622247392.1606164.1488190393519@mail.yahoo.com>
 <o90uol$3sg$1@blaine.gmane.org>
 <1362234802.1607003.1488192058596@mail.yahoo.com>
 <o911a4$i9r$1@blaine.gmane.org>
 <1404890103.934608.1488194535041@mail.yahoo.com>
Message-ID: <1e9b60ce-0735-04ed-f8d2-1c4e043c21e5@yahoo.co.uk>

On 27/02/17 11:22, Allan Tanaka wrote:
> - And did you see chart.html in that listing?
> Yes it's there
>
> - How did you "proceed"?
> Did you click the link in the directorty listing
> or did you type it in by hand?
> I click the link in directory listing

OK, It looks like the server side is working OK.
That takes us back to the file itself.

> have you checked that chart.htm is not empty and that the html is valid?
> As i click the chart.htm, it doesn't show anything. Just blank.
> Does it mean that i have checked chart.htm is not empty?

No it just means the file exists but does not display. There are several
possible
reasons for that...

First, while it is displaying(or not!) in the browser right click and
choose
the "view source" option to see what the browser sees.

Next check that the file is not empty. The easiest way is to open in a
text editor such as Notepad - I'm guessing you use Windows?

Do you see any content?
Does it look like HTML

Second check that the file allows users to read its contents - check its
security permissions that it has read access.

Finally check that the html is valid. by running it through your favourite
html validator - for example htmltidy. You can find online validators
via google.

See how that goes.

-- 

Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From alan.gauld at yahoo.co.uk  Mon Feb 27 09:28:04 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 27 Feb 2017 14:28:04 +0000
Subject: [Tutor] Learning Objectives?
In-Reply-To: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
Message-ID: <o91d1e$9vo$1@blaine.gmane.org>

On 27/02/17 10:44, Leam Hall wrote:
> Is there a list of Python skill progression, like "Intermediates should 
> know <this> and Advanced should know <this and that>?" Trying to map out 
> a well rounded study list.

I'm not aware of such a list, and I'm not sure it's of much value.
Better to just learn what you need and use it. When you need
to learn more, learn it. The worst thing you can do is study an
arbitrary list of topics that don't have any relevance to
the problems you need to solve!

Nobody is going to ask for an intermediate programmer, or a
beginner programmer. They might ask for an expert, but if you
are really an expert you will know that already - and you
won't be able to become one by studying anything extra.

Once you are past the basics - ie. you can write a program
that does something useful, it's all about writing code and
learning as you go. And you never stop learning.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From leamhall at gmail.com  Mon Feb 27 09:57:08 2017
From: leamhall at gmail.com (leam hall)
Date: Mon, 27 Feb 2017 09:57:08 -0500
Subject: [Tutor] Learning Objectives?
In-Reply-To: <o91d1e$9vo$1@blaine.gmane.org>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
Message-ID: <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>

On Mon, Feb 27, 2017 at 9:28 AM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 27/02/17 10:44, Leam Hall wrote:
> > Is there a list of Python skill progression, like "Intermediates should
> > know <this> and Advanced should know <this and that>?" Trying to map out
> > a well rounded study list.
>
> I'm not aware of such a list, and I'm not sure it's of much value.
> Better to just learn what you need and use it. When you need
> to learn more, learn it. The worst thing you can do is study an
> arbitrary list of topics that don't have any relevance to
> the problems you need to solve!
>
> Nobody is going to ask for an intermediate programmer, or a
> beginner programmer. They might ask for an expert, but if you
> are really an expert you will know that already - and you
> won't be able to become one by studying anything extra.
>
> Once you are past the basics - ie. you can write a program
> that does something useful, it's all about writing code and
> learning as you go. And you never stop learning.
>
>
> Hey Alan!

When I was coming up as a Linux guy I took the old SAGE guidelines and
studied each "level" in turn. It was useful for making me a well-rounded
admin and helped me put off some higher end stuff I wasn't really ready
for.

Things like Testing and documentation are useful, but only learning what
seems to bee needed for this one project seems harder for the new coder.
Most of us didn't know TDD was useful until we started doing it. Same for
documentation. It's sort of the "if we hired a junior or senior coder, what
basics would we want them to know?"

Thanks!

Leam

From s.molnar at sbcglobal.net  Mon Feb 27 13:46:48 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Mon, 27 Feb 2017 13:46:48 -0500
Subject: [Tutor] Problem with Spyder IDE in Anaconda3
Message-ID: <58B47418.2060007@sbcglobal.net>

I had sent the following message to Anaconda Support:

I have just installed anaconda3-4.3.0 and upgraded Spyder to v-3.1.3.

When I open Spyder and run a python script that has run perfectly in a 
previous  version of Spyder I get the results that I expect,but with 
'Kernel died, restarting' and I get a new iPython console prompt. Also a 
popup that asks 'Do  you want to close this console?'.  If I answer 'No' 
I get the following in the Internal Console:


Spyder Internal Console

This console is used to report application
internal errors and to inspect Spyder
internals with the following commands:
   spy.app, spy.window, dir(spy)

Please don't use it to run your code

 >>> WARNING:traitlets:kernel restarted
Traceback (most recent call last):
   File 
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/base_frontend_mixin.py", 
line 163, in _dispatch
     handler(msg)
   File 
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py", 
line 192, in _handle_execute_reply
     super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
   File 
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/jupyter_widget.py", 
line 184, in _handle_execute_reply
     super(JupyterWidget, self)._handle_execute_reply(msg)
   File 
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/frontend_widget.py", 
line 492, in _handle_execute_reply
     self._request_info['execute'].pop(msg_id)
KeyError: '50af986d-2e5c-4cef-aef4-827370619c86'

Very strange, and most annoying.

I received an answer:

I know a solution for this problem. I guess you are using Kaspersky 
product. You need to add "python.exe", and "pythonw.exe" of Anaconda 
specific into Exclusions list and make them trusted applications.


Where would I find such a list?  There is no mention of such a list in 
the Debian Handbook and a Google search didn't find anything that I 
could see would apply to solution to this problem.  Nothing I found 
about the Kaspersky product told me where (or how) to find an exclusion 
list.

I'm hoping that kind sole on this list can help em solve this problem.

Thanks in advance.

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1

From marc.tompkins at gmail.com  Mon Feb 27 14:29:41 2017
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 27 Feb 2017 11:29:41 -0800
Subject: [Tutor] Problem with Spyder IDE in Anaconda3
In-Reply-To: <58B47418.2060007@sbcglobal.net>
References: <58B47418.2060007@sbcglobal.net>
Message-ID: <CAKK8jXZhRiZFaS6t+SykNrEorw27BAZ0rrVRbsrqHY5dzX3H-g@mail.gmail.com>

On Mon, Feb 27, 2017 at 10:46 AM, Stephen P. Molnar <s.molnar at sbcglobal.net>
wrote:

> I had sent the following message to Anaconda Support:
>
> I have just installed anaconda3-4.3.0 and upgraded Spyder to v-3.1.3.
>
> When I open Spyder and run a python script that has run perfectly in a
> previous  version of Spyder I get the results that I expect,but with
> 'Kernel died, restarting' and I get a new iPython console prompt. Also a
> popup that asks 'Do  you want to close this console?'.  If I answer 'No' I
> get the following in the Internal Console:
>
>
> Spyder Internal Console
>
> This console is used to report application
> internal errors and to inspect Spyder
> internals with the following commands:
>   spy.app, spy.window, dir(spy)
>
> Please don't use it to run your code
>
> >>> WARNING:traitlets:kernel restarted
> Traceback (most recent call last):
>   File "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/base_frontend_mixin.py",
> line 163, in _dispatch
>     handler(msg)
>   File "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyde
> r/widgets/ipythonconsole/namespacebrowser.py", line 192, in
> _handle_execute_reply
>     super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
>   File "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/jupyter_widget.py",
> line 184, in _handle_execute_reply
>     super(JupyterWidget, self)._handle_execute_reply(msg)
>   File "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/frontend_widget.py",
> line 492, in _handle_execute_reply
>     self._request_info['execute'].pop(msg_id)
> KeyError: '50af986d-2e5c-4cef-aef4-827370619c86'
>
> Very strange, and most annoying.
>
> I received an answer:
>
> I know a solution for this problem. I guess you are using Kaspersky
> product. You need to add "python.exe", and "pythonw.exe" of Anaconda
> specific into Exclusions list and make them trusted applications.
>
>
> Where would I find such a list?  There is no mention of such a list in the
> Debian Handbook and a Google search didn't find anything that I could see
> would apply to solution to this problem.  Nothing I found about the
> Kaspersky product told me where (or how) to find an exclusion list.
>
>
With the usual caveats that your question isn't Python-specific, here's the
page from Kaspersky's website on how to create exclusions:
https://support.kaspersky.com/2695#block2

But: are you actually running Kaspersky Antivirus on a Debian machine?
Nothing wrong with that if so, but it's pretty unusual.  If not, then you
need to push the Anaconda people a bit harder for ideas.

From marc.tompkins at gmail.com  Mon Feb 27 18:39:06 2017
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 27 Feb 2017 15:39:06 -0800
Subject: [Tutor] Problem with Spyder IDE in Anaconda3
In-Reply-To: <58B4917A.8000100@sbcglobal.net>
References: <58B47418.2060007@sbcglobal.net>
 <CAKK8jXZhRiZFaS6t+SykNrEorw27BAZ0rrVRbsrqHY5dzX3H-g@mail.gmail.com>
 <58B4917A.8000100@sbcglobal.net>
Message-ID: <CAKK8jXYidtz7K2-Ksj9Jz_Y62LKtjvoS7cwQ=Ez808-bmj4OpA@mail.gmail.com>

On Mon, Feb 27, 2017 at 12:52 PM, Stephen P. Molnar <s.molnar at sbcglobal.net>
wrote:

> On 02/27/2017 02:29 PM, Marc Tompkins wrote:
>
>> On Mon, Feb 27, 2017 at 10:46 AM, Stephen P. Molnar
>> <s.molnar at sbcglobal.net <mailto:s.molnar at sbcglobal.net>> wrote:
>>
>>     I had sent the following message to Anaconda Support:
>>
>>     I have just installed anaconda3-4.3.0 and upgraded Spyder to v-3.1.3.
>>
>>     When I open Spyder and run a python script that has run perfectly in
>>     a previous  version of Spyder I get the results that I expect,but
>>     with 'Kernel died, restarting' and I get a new iPython console
>>     prompt. Also a popup that asks 'Do  you want to close this
>>     console?'.  If I answer 'No' I get the following in the Internal
>>     Console:
>>
>>
>>     Spyder Internal Console
>>
>>     This console is used to report application
>>     internal errors and to inspect Spyder
>>     internals with the following commands:
>>        spy.app, spy.window, dir(spy)
>>
>>     Please don't use it to run your code
>>
>>      >>> WARNING:traitlets:kernel restarted
>>     Traceback (most recent call last):
>>        File
>>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtcon
>> sole/base_frontend_mixin.py",
>>     line 163, in _dispatch
>>          handler(msg)
>>        File
>>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyde
>> r/widgets/ipythonconsole/namespacebrowser.py",
>>     line 192, in _handle_execute_reply
>>          super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
>>        File
>>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtcon
>> sole/jupyter_widget.py",
>>     line 184, in _handle_execute_reply
>>          super(JupyterWidget, self)._handle_execute_reply(msg)
>>        File
>>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtcon
>> sole/frontend_widget.py",
>>     line 492, in _handle_execute_reply
>>          self._request_info['execute'].pop(msg_id)
>>     KeyError: '50af986d-2e5c-4cef-aef4-827370619c86'
>>
>>     Very strange, and most annoying.
>>
>>     I received an answer:
>>
>>     I know a solution for this problem. I guess you are using Kaspersky
>>     product. You need to add "python.exe", and "pythonw.exe" of Anaconda
>>     specific into Exclusions list and make them trusted applications.
>>
>>
>>     Where would I find such a list?  There is no mention of such a list
>>     in the Debian Handbook and a Google search didn't find anything that
>>     I could see would apply to solution to this problem.  Nothing I
>>     found about the Kaspersky product told me where (or how) to find an
>>     exclusion list.
>>
>>
>> With the usual caveats that your question isn't Python-specific, here's
>> the page from Kaspersky's website on how to create exclusions:
>> https://support.kaspersky.com/2695#block2
>>
>> But: are you actually running Kaspersky Antivirus on a Debian machine?
>> Nothing wrong with that if so, but it's pretty unusual.  If not, then
>> you need to push the Anaconda people a bit harder for ideas.
>>
>
>
> To the best of my knowledge I am not running any anti-virus software. This
> has always been a Linux computer and there has been no need.
>
> In fact, this has only happened since I had to reinstall Debian v8.5 and
> all of the upgrades.
>
>
In that case, their answer was completely irrelevant to your problem.  I'm
afraid I don't know Anaconda at all, nor the Spyder IDE, so I really don't
have any insight - and, since this is the Python Tutor list, I don't know
whether anyone else here will either.  The Anaconda Community is probably
your best bet:
https://www.continuum.io/anaconda-community

Good luck!

From s.molnar at sbcglobal.net  Mon Feb 27 15:52:10 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Mon, 27 Feb 2017 15:52:10 -0500
Subject: [Tutor] Problem with Spyder IDE in Anaconda3
In-Reply-To: <CAKK8jXZhRiZFaS6t+SykNrEorw27BAZ0rrVRbsrqHY5dzX3H-g@mail.gmail.com>
References: <58B47418.2060007@sbcglobal.net>
 <CAKK8jXZhRiZFaS6t+SykNrEorw27BAZ0rrVRbsrqHY5dzX3H-g@mail.gmail.com>
Message-ID: <58B4917A.8000100@sbcglobal.net>

On 02/27/2017 02:29 PM, Marc Tompkins wrote:
> On Mon, Feb 27, 2017 at 10:46 AM, Stephen P. Molnar
> <s.molnar at sbcglobal.net <mailto:s.molnar at sbcglobal.net>> wrote:
>
>     I had sent the following message to Anaconda Support:
>
>     I have just installed anaconda3-4.3.0 and upgraded Spyder to v-3.1.3.
>
>     When I open Spyder and run a python script that has run perfectly in
>     a previous  version of Spyder I get the results that I expect,but
>     with 'Kernel died, restarting' and I get a new iPython console
>     prompt. Also a popup that asks 'Do  you want to close this
>     console?'.  If I answer 'No' I get the following in the Internal
>     Console:
>
>
>     Spyder Internal Console
>
>     This console is used to report application
>     internal errors and to inspect Spyder
>     internals with the following commands:
>        spy.app, spy.window, dir(spy)
>
>     Please don't use it to run your code
>
>      >>> WARNING:traitlets:kernel restarted
>     Traceback (most recent call last):
>        File
>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/base_frontend_mixin.py",
>     line 163, in _dispatch
>          handler(msg)
>        File
>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/widgets/ipythonconsole/namespacebrowser.py",
>     line 192, in _handle_execute_reply
>          super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
>        File
>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/jupyter_widget.py",
>     line 184, in _handle_execute_reply
>          super(JupyterWidget, self)._handle_execute_reply(msg)
>        File
>     "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/frontend_widget.py",
>     line 492, in _handle_execute_reply
>          self._request_info['execute'].pop(msg_id)
>     KeyError: '50af986d-2e5c-4cef-aef4-827370619c86'
>
>     Very strange, and most annoying.
>
>     I received an answer:
>
>     I know a solution for this problem. I guess you are using Kaspersky
>     product. You need to add "python.exe", and "pythonw.exe" of Anaconda
>     specific into Exclusions list and make them trusted applications.
>
>
>     Where would I find such a list?  There is no mention of such a list
>     in the Debian Handbook and a Google search didn't find anything that
>     I could see would apply to solution to this problem.  Nothing I
>     found about the Kaspersky product told me where (or how) to find an
>     exclusion list.
>
>
> With the usual caveats that your question isn't Python-specific, here's
> the page from Kaspersky's website on how to create exclusions:
> https://support.kaspersky.com/2695#block2
>
> But: are you actually running Kaspersky Antivirus on a Debian machine?
> Nothing wrong with that if so, but it's pretty unusual.  If not, then
> you need to push the Anaconda people a bit harder for ideas.


To the best of my knowledge I am not running any anti-virus software. 
This has always been a Linux computer and there has been no need.

In fact, this has only happened since I had to reinstall Debian v8.5 and 
all of the upgrades.

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1

From mats at wichmann.us  Mon Feb 27 15:57:55 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 27 Feb 2017 13:57:55 -0700
Subject: [Tutor] Learning Objectives?
In-Reply-To: <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
 <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
Message-ID: <699b82ae-097c-76c5-2f25-fe8e9f1d79ee@wichmann.us>

On 02/27/2017 07:57 AM, leam hall wrote:

> When I was coming up as a Linux guy I took the old SAGE guidelines and
> studied each "level" in turn. It was useful for making me a well-rounded
> admin and helped me put off some higher end stuff I wasn't really ready
> for.
> 
> Things like Testing and documentation are useful, but only learning what
> seems to bee needed for this one project seems harder for the new coder.
> Most of us didn't know TDD was useful until we started doing it. Same for
> documentation. It's sort of the "if we hired a junior or senior coder, what
> basics would we want them to know?"
> 
> Thanks!
> 
> Leam

Just as a suggestion,

I think if you look at the curriculum of various training courses,
books, online tutorial series you will get each author's view of what a
logical progression is. There are probably as many different
progressions as there are people expressing an opinion, but it seems to
me the flow is at least roughly aligned when I glance at these from time
to time.

For example (this is no endorsement, just a site I do peer at now and
then and so remember it), look here:

http://www.python-course.eu/python3_course.php

the left bar has a kind of order that's not insane (except I'd be
looking at files in the first 10 minutes, but that's just me); then
there's a tab called "advanced topics": forking, threads, etc. and then
some stuff you look at if you need it: wsgi, mod_python, sql connectors.
And then another tab for a great big "external" topics like NumPy,
Machine Learning and there are lots more in that category like Django,
Flask, SciPy, and so on - all can be considered "advanced" because
they're not the language itself, but stuff some people might expect you
to be proficient in for a given job that's billed as a "Python Job".

If you're looking at abstract base classes in your first few days,
that's probably not the right order ;)

I even have a bit of a bone to pick with the TDD movement, not that it's
a bad idea by itself, but when treated as a "religion" it seems to lead
to a mindset that unit tests alone are sufficient to prove a codebase,
when integration testing is just as important.

From ryan at allwegot.net  Mon Feb 27 18:03:01 2017
From: ryan at allwegot.net (Ryan Smith)
Date: Mon, 27 Feb 2017 18:03:01 -0500
Subject: [Tutor] feedback on simple python code
Message-ID: <D4DA1A54.D012%ryan@allwegot.net>

Hi all,

New python student here. I have been using O?reilly?s "Python Beyond the
Basics: Object Oriented Programming video series". In one of the
assignments we are to write a simple inheritance hierarchy of three
classes that write to text files. I have actually written the code for the
assignment and it runs as well as meets the requirements of the
assignment. I am posting to get feedback on how I can improve this and
making it more pythonic and concise.

Please keep in mind that I am simply ?simulating" writing to a log file
and a tabbed delimited file, so I?m not necessarily looking for which
modules I could have to create actual log files or writing to actual csv
files. The output of the code should be two text files with text written
to them that have been passed to the instance of each respective object.

#!/usr/bin/env python

import abc
import datetime

class WriteFile(object):
    __metaclass__ = abc.ABCMeta
    
    
    @abc.abstractmethod
    def write(self,text):
        """Write to file"""
        return 
    

class LogFile(WriteFile):
    def __init__(self,fh):
    self.fh = fh
        

    def write(self, text):
    date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    entry = "{0} {1}{2}".format(date, text, '\n')
    with open(self.fh, 'a') as f:
    f.write(entry)

class DelimWrite(WriteFile):
    def __init__(self, fh, delim):
    self.fh = fh
    self.delim = delim
        

    def write(self, text):
    with open(self.fh, 'a') as f:
        entry = ""
        for item in text:
            if self.delim in item:
	        entry += ' "{0}"{1} '.format(item,self.delim)
	    else:
                entry += item+self.delim
        f.write(entry.strip(self.delim) + '\n')
            
            
            

if __name__ == "__main__":
    
    
    log = LogFile('log.txt')
    log.write('This is a log message')
    log.write('This is another log message')
    
    
    d = DelimWrite('test.csv',',')
    d.write([?1?,?2?,?3?])
    d.write(['a','this, that','c?])    #Double quote item if delimiter
included as list item
    d.write([?basketball?,'football?,'golfball'])





From superman323a at gmail.com  Mon Feb 27 17:00:26 2017
From: superman323a at gmail.com (Johnny Hh)
Date: Mon, 27 Feb 2017 17:00:26 -0500
Subject: [Tutor] Help with this question
Message-ID: <CABccA1q=OU15jqq5Qn10A=yiV7BS8X1eoDAanuZ7q_Q8nkt+HQ@mail.gmail.com>

write a python function called find_most_freq() that returns the element of
a given list that occurs the most frequently. If there are ties, take the
number found first.

From alan.gauld at yahoo.co.uk  Mon Feb 27 20:07:43 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 28 Feb 2017 01:07:43 +0000
Subject: [Tutor] Problem with Spyder IDE in Anaconda3
In-Reply-To: <58B4917A.8000100@sbcglobal.net>
References: <58B47418.2060007@sbcglobal.net>
 <CAKK8jXZhRiZFaS6t+SykNrEorw27BAZ0rrVRbsrqHY5dzX3H-g@mail.gmail.com>
 <58B4917A.8000100@sbcglobal.net>
Message-ID: <o92igp$631$1@blaine.gmane.org>

On 27/02/17 20:52, Stephen P. Molnar wrote:

> To the best of my knowledge I am not running any anti-virus software. 
> This has always been a Linux computer and there has been no need.

There are threats to Linux just fewer of them, plus you could
be used as a host to pass on damaged files so you probably
should run an AV program at least periodically. Clam is a
popular option.

But that aside, Marc is right this has nothing to do with the
focus of this mailing list so you are more likely to get responses
back on the Anaconda list. Just be sure to point outyou are on
Linux with no active AV software running.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 27 20:12:25 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 28 Feb 2017 01:12:25 +0000
Subject: [Tutor] Learning Objectives?
In-Reply-To: <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
 <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
Message-ID: <o92ipi$6np$1@blaine.gmane.org>

On 27/02/17 14:57, leam hall wrote:

>> I'm not aware of such a list, and I'm not sure it's of much value.
>> Better to just learn what you need and use it. ...

> When I was coming up as a Linux guy I took the old SAGE guidelines and
> studied each "level" in turn. It was useful for making me a well-rounded
> admin and helped me put off some higher end stuff I wasn't really ready
> for.

Its an individual choice, so if it works for you don't let
me stop you :-) But I still don't know of any such list.

> documentation. It's sort of the "if we hired a junior or senior coder, what
> basics would we want them to know?"

That's the thing. I've never, in 40 years in IT, seen
anyone advertise for a junior programmer. Just doesn't seem to
happen. It's a bit like having a headache and asking for a
weak pain killer...

There are places offered for programming apprenticeships,
but they assume you are starting from scratch.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb 27 20:16:13 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 28 Feb 2017 01:16:13 +0000
Subject: [Tutor] Help with this question
In-Reply-To: <CABccA1q=OU15jqq5Qn10A=yiV7BS8X1eoDAanuZ7q_Q8nkt+HQ@mail.gmail.com>
References: <CABccA1q=OU15jqq5Qn10A=yiV7BS8X1eoDAanuZ7q_Q8nkt+HQ@mail.gmail.com>
Message-ID: <o92j0m$6np$2@blaine.gmane.org>

On 27/02/17 22:00, Johnny Hh wrote:
> write a python function called find_most_freq() that returns the element of
> a given list that occurs the most frequently. If there are ties, take the
> number found first.

OK, You've shown us the exercise, now show us your attempt at a solution.

Here is a starter:

def find_most_freq():
    # your code here
    return element

Now show us how you think you fill that in. Or tell us where
and how you are stuck.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From dyoo at hashcollision.org  Mon Feb 27 22:00:04 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 27 Feb 2017 19:00:04 -0800
Subject: [Tutor] feedback on simple python code
In-Reply-To: <D4DA1A54.D012%ryan@allwegot.net>
References: <D4DA1A54.D012%ryan@allwegot.net>
Message-ID: <CAGZAPF6-LPb7LF6s4sfWCmujaC4aEkgNFV91QTAxsEKJzDanZQ@mail.gmail.com>

Hi Ryan,

Let's take a look...

Overloading the "write" method to take in different types of arguments
looks a bit suspicious.


You have a superclass that defines a write method, and you have two
subclasses that implement that method.  However, your first
implementation, LogFile.write, appears to take in a string, while the
second, DelimWrite.write,  appears to take a list of strings.

That's what looks somewhat problematic.  According to inheritance
rules, the methods of subclasses should be able to take the same kind
of input as specified in the superclass.  You can read more about this
in https://en.wikipedia.org/wiki/Liskov_substitution_principle, but
it's roughly saying that if you have a superclass, subclass methods
should do their thing on the same kind of data.  Violating this can
lead to code that is hard to understand.

To solve this: I'd recommend normalizing the input if you have that
option.  If you can make the input always be a list of strings, that
would be one way to resolve this problem.  Alternatively, if you can
make the input always be a single string, then that would solve this
problem too.


Please feel free to ask questions.  Good luck!

From __peter__ at web.de  Tue Feb 28 03:32:54 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 28 Feb 2017 09:32:54 +0100
Subject: [Tutor] feedback on simple python code
References: <D4DA1A54.D012%ryan@allwegot.net>
Message-ID: <o93cji$caq$1@blaine.gmane.org>

Ryan Smith wrote:

> Hi all,
> 
> New python student here. I have been using O?reilly?s "Python Beyond the
> Basics: Object Oriented Programming video series". In one of the
> assignments we are to write a simple inheritance hierarchy of three
> classes that write to text files. I have actually written the code for the
> assignment and it runs as well as meets the requirements of the
> assignment. I am posting to get feedback on how I can improve this and
> making it more pythonic and concise.
> 
> Please keep in mind that I am simply ?simulating" writing to a log file
> and a tabbed delimited file, so I?m not necessarily looking for which
> modules I could have to create actual log files or writing to actual csv
> files. The output of the code should be two text files with text written
> to them that have been passed to the instance of each respective object.
> 
> #!/usr/bin/env python
> 
> import abc
> import datetime
> 
> class WriteFile(object):
>     __metaclass__ = abc.ABCMeta
>     
>     
>     @abc.abstractmethod
>     def write(self,text):

You might run a tool like https://pypi.python.org/pypi/pycodestyle over your 
code to ensure it follows common standards.

>         """Write to file"""
>         return
>     
> 
> class LogFile(WriteFile):
>     def __init__(self,fh):
>     self.fh = fh
>         
> 
>     def write(self, text):
>     date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
>     entry = "{0} {1}{2}".format(date, text, '\n')
>     with open(self.fh, 'a') as f:
>     f.write(entry)
> 
> class DelimWrite(WriteFile):
>     def __init__(self, fh, delim):
>     self.fh = fh
>     self.delim = delim
>         
> 
>     def write(self, text):
>     with open(self.fh, 'a') as f:
>         entry = ""
>         for item in text:
>             if self.delim in item:
> entry += ' "{0}"{1} '.format(item,self.delim)

What will happen if text contains double quotes?

> else:
>                 entry += item+self.delim

Have a look at the str.join() method. Example:

>>> ",".join(["foo", "bar", "baz"])
'foo,bar,baz'

>         f.write(entry.strip(self.delim) + '\n')

I will mention another "principle", DRY (don't repeat yourself), i. e. do 
not write the same code twice.

When I look at your code I see that both DelimWrite and LogFile open a file. 
If you want modify your code to accept file objects like sys.stdout you have 
to make changes in both subclasses. To avoid that you might put the file-
writing part into a separate method:

class WriteFile(object):
    def __init__(self, file):
        self.file = file

    def write_record(self, record):
        with open(self.file, "a") as f:
            f.write(self.format_record(record))

    def format_record(self, record):
        return record


class LogFile(WriteFile):
    def format_record(self, record):
        date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return "{0} {1}\n".format(date, record)


class DelimWrite(WriteFile):
    quote = '"'
    def __init__(self, file, delimiter):
        super(DelimWrite, self).__init__(file)
        self.delimiter = delimiter

    def escaped(self, value):
        value = str(value)
        if self.delimiter in value:
            quote = self.quote
            value = '"{}"'.format(value.replace(quote, quote + quote))
        return value

    def format_record(self, record):
        escaped_rows = (self.escaped(value) for value in record)
        return self.delimiter.join(escaped_rows) + "\n"



From aaronmyatt at googlemail.com  Tue Feb 28 03:39:09 2017
From: aaronmyatt at googlemail.com (Aaron Myatt)
Date: Tue, 28 Feb 2017 16:39:09 +0800
Subject: [Tutor] Learning Objectives?
In-Reply-To: <o92ipi$6np$1@blaine.gmane.org>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
 <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
 <o92ipi$6np$1@blaine.gmane.org>
Message-ID: <CAAD4-9g3EHc5yQTtUCyqoWf+3MD0WDGdDzD6dKG=vZUyF98nPw@mail.gmail.com>

Just my humble contribution: I rather appreciated this fellows intermediate
python tutorial series:
https://youtu.be/YSe9Tu_iNQQ?list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_

Though I would argue some other topics, like context managers, would also
be worth including in his list.

On 28 Feb 2017 9:15 a.m., "Alan Gauld via Tutor" <tutor at python.org> wrote:

> On 27/02/17 14:57, leam hall wrote:
>
> >> I'm not aware of such a list, and I'm not sure it's of much value.
> >> Better to just learn what you need and use it. ...
>
> > When I was coming up as a Linux guy I took the old SAGE guidelines and
> > studied each "level" in turn. It was useful for making me a well-rounded
> > admin and helped me put off some higher end stuff I wasn't really ready
> > for.
>
> Its an individual choice, so if it works for you don't let
> me stop you :-) But I still don't know of any such list.
>
> > documentation. It's sort of the "if we hired a junior or senior coder,
> what
> > basics would we want them to know?"
>
> That's the thing. I've never, in 40 years in IT, seen
> anyone advertise for a junior programmer. Just doesn't seem to
> happen. It's a bit like having a headache and asking for a
> weak pain killer...
>
> There are places offered for programming apprenticeships,
> but they assume you are starting from scratch.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From ben+python at benfinney.id.au  Tue Feb 28 10:57:19 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 01 Mar 2017 02:57:19 +1100
Subject: [Tutor] The benefits of a junior programmer (was: Learning
 Objectives?)
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
 <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
 <o92ipi$6np$1@blaine.gmane.org>
Message-ID: <85efyil34w.fsf_-_@benfinney.id.au>

Alan Gauld via Tutor <tutor at python.org> writes:

> That's the thing. I've never, in 40 years in IT, seen anyone advertise
> for a junior programmer. Just doesn't seem to happen.

Several employers in my career, including my current employer, actively
seek to fill some positions with junior programmers.

> It's a bit like having a headache and asking for a weak pain killer...

Not at all. Apart from the obvious (a junior position commands a smaller
payroll, so is easier to fit into a departmental budget), junior
programmers can only gain proper experience if someone employs them and
many employers recognise that.

There is a world of difference between lack of specific experience with
a tool, and lack of ability to learn in the right environment. A good
junior programmer will be in the former category only.

> There are places offered for programming apprenticeships, but they
> assume you are starting from scratch.

In my experience, many employers will seek programmers who have some
amount of experience but not enough to demand a senior salary. Most
projects are complex and specific enough that every new hire, regardless
of seniority, will spend a lot of time initially coming up to speed on
that project.

Junior programmers paired with senior programmers can be a powerful
force in an organisation. I encourage junior programmers to see their
fresh perspective and lower salary demand as an attractive and saleable
feature when seeking employment.

-- 
 \       ?Firmness in decision is often merely a form of stupidity. It |
  `\        indicates an inability to think the same thing out twice.? |
_o__)                                                ?Henry L. Mencken |
Ben Finney


From leamhall at gmail.com  Tue Feb 28 05:27:40 2017
From: leamhall at gmail.com (Leam Hall)
Date: Tue, 28 Feb 2017 05:27:40 -0500
Subject: [Tutor] Learning Objectives?
In-Reply-To: <o92ipi$6np$1@blaine.gmane.org>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
 <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
 <o92ipi$6np$1@blaine.gmane.org>
Message-ID: <b8a58453-34b2-e6ce-9fba-3800caa4f0fa@gmail.com>

On 02/27/17 20:12, Alan Gauld via Tutor wrote:
> On 27/02/17 14:57, leam hall wrote:
>
>>> I'm not aware of such a list, and I'm not sure it's of much value.
>>> Better to just learn what you need and use it. ...
>
>> When I was coming up as a Linux guy I took the old SAGE guidelines and
>> studied each "level" in turn. It was useful for making me a well-rounded
>> admin and helped me put off some higher end stuff I wasn't really ready
>> for.
>
> Its an individual choice, so if it works for you don't let
> me stop you :-) But I still don't know of any such list.

Understood. However, think about the issue from a newbie perspective.

1. The Python Tutor e-mail list helps with questions when someone can 
frame a question.

2. Books or videos like "Learning Python", "Learn Python the Hard Way", 
or the Coursera/EdX classes cover what the publisher felt could be 
covered in a profitable way.

3. Books like "Python Projects" can help someone go from absolute newbie 
to being able to do useful stuff. <Shameless plug for Alan's book>

When I was learning Ruby I put section dividers in a 3 ring binder and 
had one section for each of the topics in the Pickaxe book. That way as 
I learned and relearned things could gel a little better. I have an old 
copy of "Learning Python" and will break out the section dividers today.

I don't know about anyone else, but I have a bad habit of jumping in way 
over my head and getting frustrated when I can't make things work. By 
setting a sequential list it helps prevent that; learning Objects is 
much easier when one understands functions.

>> documentation. It's sort of the "if we hired a junior or senior coder, what
>> basics would we want them to know?"
>
> That's the thing. I've never, in 40 years in IT, seen
> anyone advertise for a junior programmer. Just doesn't seem to
> happen. It's a bit like having a headache and asking for a
> weak pain killer...
>
> There are places offered for programming apprenticeships,
> but they assume you are starting from scratch.


The PHP community has a Mentoring thing (https://php-mentoring.org/), 
and I would assume there are many open source Python projects that would 
be willing to bring a junior in and help them grow. Growth and 
contributing seem to go hand in hand. It's easy to read a book and think 
you "know" a language. It's more challenging when you're in the lab with 
seasoned programmers and you're pushed to produce better and better code.

It's a lot nicer for the seasoned programmers if you don't have to be 
convinced to write tests or taught what an object is.  :)

The "junior" level is more a gift to the seasoned programmers; someone 
who can do those basics has proven a willingness to learn coding past 
the "type what's in the book" phase. Of course, one must go through 
junior to get to senior.

For those interested, GIAC has a Certified Python Programmer. It focuses 
on using security tools, which is GIAC's forte.

http://www.giac.org/certification/python-coder-gpyc

Does a certification make you a better coder? Not really, there are lots 
of uncertified (but probably certifiable!) expert coders out there. 
However, certifications can help in the job search and it's nice to get 
paid for what you enjoy.

Leam





From mhashmi1979 at gmail.com  Tue Feb 28 05:24:45 2017
From: mhashmi1979 at gmail.com (M Hashmi)
Date: Tue, 28 Feb 2017 03:24:45 -0700
Subject: [Tutor] Learning Objectives?
In-Reply-To: <CAAD4-9g3EHc5yQTtUCyqoWf+3MD0WDGdDzD6dKG=vZUyF98nPw@mail.gmail.com>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
 <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
 <o92ipi$6np$1@blaine.gmane.org>
 <CAAD4-9g3EHc5yQTtUCyqoWf+3MD0WDGdDzD6dKG=vZUyF98nPw@mail.gmail.com>
Message-ID: <CANoUts42Aww8SZH8UDEN=6yDhaG904fgwUTvEHYLHuvQOzXceA@mail.gmail.com>

Coding is an art....that helps you craft beautiful things in digital world.
As beginner it's pretty natural to confuse about which learning curve can
benefit you most in future.

If I were you I would go with simple approach. I would choose best of the
best software available and start building its source by looking at it. Bit
by bit piece by piece it would help you to understand a pre-built
application.

Lets assume as you've posted in Django group so you might be interested in
web development. Pick a best project and start writing your own guide for
yourself. The best one I came across is django-oscar. Start building it's
replica and document each step in the process for yourself. You can consult
the django's own docs as well as django-oscar's documentation for
understanding what the function/class is about.

I bet that in a single month you will be able to build a semi-dynamic site
yourself. In maximum 3 to 4 months you can really do wonders.

Hope it helps.

Regards,
M

On Tue, Feb 28, 2017 at 1:39 AM, Aaron Myatt via Tutor <tutor at python.org>
wrote:

> Just my humble contribution: I rather appreciated this fellows intermediate
> python tutorial series:
> https://youtu.be/YSe9Tu_iNQQ?list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_
>
> Though I would argue some other topics, like context managers, would also
> be worth including in his list.
>
> On 28 Feb 2017 9:15 a.m., "Alan Gauld via Tutor" <tutor at python.org> wrote:
>
> > On 27/02/17 14:57, leam hall wrote:
> >
> > >> I'm not aware of such a list, and I'm not sure it's of much value.
> > >> Better to just learn what you need and use it. ...
> >
> > > When I was coming up as a Linux guy I took the old SAGE guidelines and
> > > studied each "level" in turn. It was useful for making me a
> well-rounded
> > > admin and helped me put off some higher end stuff I wasn't really ready
> > > for.
> >
> > Its an individual choice, so if it works for you don't let
> > me stop you :-) But I still don't know of any such list.
> >
> > > documentation. It's sort of the "if we hired a junior or senior coder,
> > what
> > > basics would we want them to know?"
> >
> > That's the thing. I've never, in 40 years in IT, seen
> > anyone advertise for a junior programmer. Just doesn't seem to
> > happen. It's a bit like having a headache and asking for a
> > weak pain killer...
> >
> > There are places offered for programming apprenticeships,
> > but they assume you are starting from scratch.
> >
> > --
> > Alan G
> > Author of the Learn to Program web site
> > http://www.alan-g.me.uk/
> > http://www.amazon.com/author/alan_gauld
> > Follow my photo-blog on Flickr at:
> > http://www.flickr.com/photos/alangauldphotos
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From fred at bristle.com  Tue Feb 28 16:44:55 2017
From: fred at bristle.com (Fred Stluka)
Date: Tue, 28 Feb 2017 16:44:55 -0500
Subject: [Tutor] Learning Objectives?
In-Reply-To: <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com>
 <o91d1e$9vo$1@blaine.gmane.org>
 <CACv9p5rBU=BELcqnDuABEVs9qXU=GaueR5XjzfmOLowmxsRcOQ@mail.gmail.com>
Message-ID: <a7fab448-2456-2683-4575-0831dad2aa3f@bristle.com>

   On 2/27/17 9:57 AM, leam hall wrote:

 On Mon, Feb 27, 2017 at 9:28 AM, Alan Gauld via Tutor [1]<tutor at python.org>
 wrote:


 On 27/02/17 10:44, Leam Hall wrote:

 Is there a list of Python skill progression, like "Intermediates should
 know <this> and Advanced should know <this and that>?" Trying to map out
 a well rounded study list.

 I'm not aware of such a list, and I'm not sure it's of much value.
 Better to just learn what you need and use it. When you need
 to learn more, learn it. The worst thing you can do is study an
 arbitrary list of topics that don't have any relevance to
 the problems you need to solve!

 ...

 When I was coming up as a Linux guy I took the old SAGE guidelines and
 studied each "level" in turn. It was useful for making me a well-rounded
 admin and helped me put off some higher end stuff I wasn't really ready
 for.

 ...



   I agree with Leam.  If anyone has such a list, I think many of us
   would be interested to see it.

   Personally, I'd already been a programmer for 30 years when I
   first started using Python and Django.  I learned them in bits and
   pieces, as needed for a 4 year project.  I never took time to read
   a comprehensive book on either topic.  Also, they both evolved
   quite a bit during those 4 years, with many new and changed
   features.  So it's possible that I've completely overlooked some
   relatively basic features.

   If there were such a list, I'd quickly scan the "basic" section to
   what I may have missed.  Then, I'd scan the more advanced
   sections to what else exists.

   It would also be useful when teaching Python to someone else,
   to have some guidance about which language constructs are
   used most often.

   As a quick straw man, here's a syllabus I started whipping up
   recently for a Python and Django class I was asked to teach.
   - [2]http://bristle.com/Courses/PythonDjangoIntro/syllabus.html

   It has 5 main sections:
   - Python
   - Django
   - Possible Advanced Python Topics
   - Possible Advanced Django Topics
   - Possible Related Topics

   The class would be ten weeks, with 6 hours of lecture and 4
   hours of lab per week, so I'd hope to cover all of the 1st 2
   sections, and perhaps some/all of the last 3 sections.

   Feel free to comment on errors, omissions, misplaced items, etc.

   Enjoy!
   --Fred

   --------------------------------------------------------------------------

   Fred Stluka -- [3]mailto:fred at bristle.com -- [4]http://bristle.com/~fred/
   Bristle Software, Inc -- [5]http://bristle.com -- Glad to be of service!
   Open Source: Without walls and fences, we need no Windows or Gates.

   --------------------------------------------------------------------------

References

   Visible links
   1. mailto:tutor at python.org
   2. http://bristle.com/Courses/PythonDjangoIntro/syllabus.html
   3. mailto:fred at bristle.com
   4. http://bristle.com/~fred/
   5. http://bristle.com/

From jmssnyder at ucdavis.edu  Tue Feb 28 17:42:10 2017
From: jmssnyder at ucdavis.edu (Jason Snyder)
Date: Tue, 28 Feb 2017 22:42:10 +0000
Subject: [Tutor] pygrib issues involving wind
Message-ID: <CAPFZY7WkaEiZKQrK5NpxA86gKfg5bey1s_CJCKsf9yAgNQYQNQ@mail.gmail.com>

I have a grib2 file.  You can see the components of this grib2 file below:

wgrib2 -v chart_2017022812_0057.grb2

1:0:d=2017022812:RH Relative Humidity [%]:2 m above ground:57 hour fcst:
2:227081:d=2017022812:TMAX Maximum Temperature [K]:2 m above ground:54-57
hour max fcst:
3:486870:d=2017022812:UGRD U-Component of Wind [m/s]:10 m above ground:57
hour fcst:
4:751610:d=2017022812:VGRD V-Component of Wind [m/s]:10 m above ground:57
hour fcst:
5:1009523:d=2017022812:PRATE Precipitation Rate [kg/m^2/s]:surface:54-57
hour ave fcst:


Now I am trying to use pygrib to extract the U and V wind components of
this grib2 file with the below python script:

grib = 'chart_2017022812_0057.grb2'

grbs=pygrib.open(grib)
uwind = grbs.select(name='U-component of wind')[0]
rh = grbs.select(name='Relative humidity')[0]
temp = grbs.select(name='Maximum temperature')[0]
prate = grbs.select(name='Precipitation rate')[0]

while with this script, I am able to successfully extract relative
humidity, temperature, and precipitation rate, I am having a problem
extracting the u component of wind.  I get the error:

Traceback (most recent call last):
  File "testgrib.py", line 16, in <module>
    uwind = grbs.select(name='U-Component of wind')[0]
  File "pygrib.pyx", line 609, in pygrib.open.select (pygrib.c:6175)
ValueError: no matches found


How can I resolve this issue?

From cannedham284 at hotmail.com  Tue Feb 28 19:30:27 2017
From: cannedham284 at hotmail.com (Ben Iannitelli)
Date: Wed, 1 Mar 2017 00:30:27 +0000
Subject: [Tutor] pygrib issues involving wind
In-Reply-To: <CAPFZY7WkaEiZKQrK5NpxA86gKfg5bey1s_CJCKsf9yAgNQYQNQ@mail.gmail.com>
References: <CAPFZY7WkaEiZKQrK5NpxA86gKfg5bey1s_CJCKsf9yAgNQYQNQ@mail.gmail.com>
Message-ID: <CY4PR19MB12711B7E54505718A49DB68F96290@CY4PR19MB1271.namprd19.prod.outlook.com>

Hi Jason,


I know nothing about pygrib, but usually Python is case-sensitive.


Look again at the upper-case and lower-case letters in the original file:

1:0:d=2017022812:RH Relative Humidity [%]:2 m above ground:57 hour fcst:
2:227081:d=2017022812:TMAX Maximum Temperature [K]:2 m above ground:54-57
hour max fcst:
3:486870:d=2017022812:UGRD U-Component of Wind [m/s]:10 m above ground:57
hour fcst:
4:751610:d=2017022812:VGRD V-Component of Wind [m/s]:10 m above ground:57
hour fcst:
5:1009523:d=2017022812:PRATE Precipitation Rate [kg/m^2/s]:surface:54-57
hour ave fcst:

Now look again at your code:

grbs=pygrib.open(grib)
uwind = grbs.select(name='U-component of wind')[0] #<----"component" with small "c" and #"wind" with small "w"
rh = grbs.select(name='Relative humidity')[0] #<----"humidity" with a small "h"
temp = grbs.select(name='Maximum temperature')[0] #<----"temperature" with a small "t"
prate = grbs.select(name='Precipitation rate')[0] #<---- "rate" with a small "r"

while with this script, I am able to successfully extract relative
humidity, temperature, and precipitation rate, I am having a problem
extracting the u component of wind.

I don't know why letter case wouldn't matter for the other fields (did you cut and paste, or type from memory?), but if you alter your code to match the capitalization exactly, you might rule case sensitivity out.

Traceback (most recent call last):
  File "testgrib.py", line 16, in <module>
    uwind = grbs.select(name='U-Component of wind')[0]
  File "pygrib.pyx", line 609, in pygrib.open.select (pygrib.c:6175)
ValueError: no matches found

HTH,

-Ben I.


From quangnguyen51291 at gmail.com  Tue Feb 28 20:29:41 2017
From: quangnguyen51291 at gmail.com (Quang nguyen)
Date: Tue, 28 Feb 2017 18:29:41 -0700
Subject: [Tutor] Asking about sending signal to RF receiver through GPIO pins
Message-ID: <CAGHbcgPB8jUJ8FO_oX1B3JvVMk0=zc9FqszhTwofDX1hhJcW2A@mail.gmail.com>

Hi all,

Right now, I am working on a school project that using raspberry Pi 2 to
send the signal to RF receiver through pins in Pi2. I need to send the
signal from clicking a button in UI.

Can anyone give me some hints?

Thanks all.