From steve at pearwood.info  Sat Apr  1 00:24:31 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 1 Apr 2017 15:24:31 +1100
Subject: [Tutor] Validating String contains IP address
In-Reply-To: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
Message-ID: <20170401042431.GE9464@ando.pearwood.info>

On Fri, Mar 31, 2017 at 07:35:48PM -0400, Ed Manning wrote:
> 
> What's the best way to validate a string contains a IP address 

Don't reinvent the wheel, use the ipaddress module.

py> import ipaddress
py> ipaddress.ip_address('99.99.99.99')
IPv4Address('99.99.99.99')


If the address is not a valid address syntax, it will raise ValueError.


-- 
Steve

From akleider at sonic.net  Sat Apr  1 12:29:42 2017
From: akleider at sonic.net (Alex Kleider)
Date: Sat, 01 Apr 2017 09:29:42 -0700
Subject: [Tutor] Validating String contains IP address
In-Reply-To: <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us>
References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
 <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net>
 <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us>
Message-ID: <01dc2f1b33ea567cff32f140835dda07@sonic.net>

On 2017-03-31 18:01, Mats Wichmann wrote:
> On 03/31/2017 06:44 PM, Alex Kleider wrote:
>> On 2017-03-31 16:35, Ed Manning wrote:
>>> What's the best way to validate a string contains a IP address
>>> Sent from my iPad
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> https://mail.python.org/mailman/listinfo/tutor
>> 
>> The re module perhaps?

> This assumes "an IP address" is the four dotted numbers characteristic
> of IPv4. These days that's a bad assumption unless you're absolutely
> sure an IPv6 address can never appear.  Can you?

Good point! I hadn't considered IPV6 and didn't know about the ipaddress 
module.
Live and learn.

From alan.gauld at yahoo.co.uk  Sat Apr  1 15:12:38 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 1 Apr 2017 20:12:38 +0100
Subject: [Tutor] Validating String contains IP address
In-Reply-To: <01dc2f1b33ea567cff32f140835dda07@sonic.net>
References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
 <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net>
 <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us>
 <01dc2f1b33ea567cff32f140835dda07@sonic.net>
Message-ID: <obou30$id5$1@blaine.gmane.org>

On 01/04/17 17:29, Alex Kleider wrote:

> Good point! I hadn't considered IPV6 and didn't know about the ipaddress 
> module.

Me too, on both counts. Actually I should have known about
ipaddress because this question has come up before but
I'd forgotten... :-(

And as for forgetting IP6 - as an ex telco engineer - sheesh!

mea mucho culpa!

-- 
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 kevinpeterodoherty at gmail.com  Sat Apr  1 15:24:45 2017
From: kevinpeterodoherty at gmail.com (Peter O'Doherty)
Date: Sat, 1 Apr 2017 20:24:45 +0100
Subject: [Tutor] Function question
In-Reply-To: <ob5jk2$jq6$1@blaine.gmane.org>
References: <9e8a0cc7-d7bc-f61b-fc8b-a3379ac7c07c@gmail.com>
 <ob5jk2$jq6$1@blaine.gmane.org>
Message-ID: <fcab264e-3542-3c1a-6091-2c42afdb450e@gmail.com>

Many thanks!

On 25-03-17 11:17, Alan Gauld via Tutor wrote:
> On 25/03/17 10:01, Peter O'Doherty wrote:
>
>> def myFunc(num):
>>       for i in range(num):
>>           print(i)
>>
>> print(myFunc(4))
>> 0
>> 1
>> 2
>> 3
>> None #why None here?
> Because your function does not have an explicit return
> value so Python returns its default value - None.
> So the print() inside the function body prints the 0-3
> values then the function terminates and returns the (default)
> None to your top level print.
>
>> def myFunc(num):
>>       for i in range(num):
>>           return i
>>
>> print(myFunc(4))
>> 0 #why just 0?
> Because return always returns from the function immediately.
> So you call the function, it enters the loop, sees the return for the
> first element and exits. The print() then prints that returned value.
>
> The preferred method to do what I think you were expecting is to build a
> list:
>
> def anotherFunction(num):
>      result = []
>      for i in range(num):
>         result.append(i)
>      return result
>
> Which is more concisely written using a list comprehension but
> that would hide the general point - that you should accumulate results
> in a collection if you want to return more than a single value.
>
> To print the result you would typically use the string.join()
> method:
>
> print(' '.join(anotherFunction(4))
>
>


//=============================
// Peter O'Doherty

// http://www.peterodoherty.net
// mail at peterodoherty.net
//=============================


From mail at peterodoherty.net  Sat Apr  1 15:24:33 2017
From: mail at peterodoherty.net (Peter O'Doherty)
Date: Sat, 1 Apr 2017 20:24:33 +0100
Subject: [Tutor] Function question
In-Reply-To: <ob5jk2$jq6$1@blaine.gmane.org>
References: <9e8a0cc7-d7bc-f61b-fc8b-a3379ac7c07c@gmail.com>
 <ob5jk2$jq6$1@blaine.gmane.org>
Message-ID: <5b6e20ac-6269-4b2d-e972-19a50749dea0@peterodoherty.net>



On 25-03-17 11:17, Alan Gauld via Tutor wrote:
>
> method:
>
> print(' '.join(anotherFunction(4))

Many thanks!

From cs at zip.com.au  Sat Apr  1 18:46:23 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Sun, 2 Apr 2017 08:46:23 +1000
Subject: [Tutor] python gtk serial loop thread readind data close
In-Reply-To: <1451978270.277856.1490877641049@mail.yahoo.com>
References: <1451978270.277856.1490877641049@mail.yahoo.com>
Message-ID: <20170401224623.GA66860@cskk.homeip.net>

On 30Mar2017 12:40, Alexandru Achim <achim_alexandru at yahoo.com> wrote:
>Dear users,
>I had a problem regarding Threads in python and Gtk3. I want to stop a while loop in Gtk , a loop starded with a thread.
>I want to control a delay timer laser board with give me ,when I send a command by serial connection, give back continuous status values ; but I want to stop this loop , to modify parameters and start the loop again.
>
>A part of my code is here :
>import serial
>import threading
>import gi
>gi.require_version('Gtk', '3.0')
>from gi.repository import Gtk
>from gi.repository import GObject,Pango, GLib
>from threading import Thread
>GObject.threads_init().............
>#START BUTTON
>
>??? def start(self,button_start):
>?????? Thread(target=self.start_on,args=(self.button_start))

You don't seem to start the Thread here.

>??? def start_on(self,widget,data=None):
>??? if ser.isOpen():
>??? ??? cmd = 's'???
>??? ??? ser.write(cmd.encode('ascii')+'\r\n')
>??? ??? while True:
>??? ??? ??? try:
>????? ??? ?????? values = ser.readline()
>??? ??? ??? ???? self.label_result.set_text(values)
>??? ??? ??? except:
>????? ??? ??? ??? ??? pass
>??? ???
>#STOP BUTTON??? ????
>??? def stop(self,button_stop):
>???? Thread(target=self.stops,args=(button_stop)).start()
>??? ???
>??? def stops(self,widget,data=None):
>??? if ser.isOpen():
>??? ??? try:??
>??? ??? ??? cmd = 'f'???
>??? ??? ??? ser.write(cmd.encode('ascii')+'\r\n')
>??? ??? ??? status = ser.readline()
>??? ??? ??? self.label_result.set_text(status)
>??? ??? except:
>??? ??? ??? pass
>...........win=sincrolaser()
>win.show_all()
>Gtk.main()
>
>But the problem is when I send STOP button program freeze , probably the loop from the start is looping forever. How do I stop the start thread?
>Is there a posibility to give a thread flag or identity to find him and close?

It is easy enough to keep the identities of threads. Example:

  def start(self, button,start):
    self.start_thread = Thread(target=.......)
    self.start_thread.start()

But to stop a thread you pretty much need to set a flag and have the thread 
check it periodicly. Example:

  def start(self, button,start):
    self.start_thread = Thread(target=.......)
    self.start_run = True
    self.start_thread.start()

  def start_one(self, widget, data=None):
    ...
    while self.start_run:
      try:
        ...

and to stop it one goes:

  self.start_run = False

Next time around the loop the thread checks the flag and quits the while loop.

Another concern I have with your code is that nothing prevents _both_ the stop 
and start threads from running at the same time. I Imagine that calling 
ser.readline from two threads at once leads to unpredictable and possible 
insane behaviour. And having both threads writing to the serial line at one may 
write nonsense to the other end, etc.

I recommand you take a mutex around your worker threads, so that only one can 
be active at once. Example:

  from threading import Lock

  # wherever your setup stuff happens; you need to allocate the Lock
  def __init__(self, ...):
    self.ser_lock = Lock()

  def start_one(self, widget, data=None):
    with self.ser_lock:
      ...
      while start_run:
        try:
          ..

and likewise in stops:

  def stop(self,button_stop):
    self.start_run = False    # ask "start" tyhread to terminate
    self.stop_thread = Thread(target=self.stops,args=(button_stop))
    self.stop_thread.start()

  def stops(self,widget,data=None):
    with self.ser_lock:
      if ser.isOpen():
        try:??
          ...

You can see that neither thread will try to user the serial device until it 
holds the lock, avoiding conflict. The stop button active sets the "start_run" 
flag variable to False, causing the start thread to exit when it notices.

Hopefully this will give you more control over your program's behaviour. A few 
helpful print() calls scattered throughout should show you what is going on, 
too.

Note that it would also be prudent to prevent more than one start thread 
running, and so forth.

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

From nasbelyakova at gmail.com  Sun Apr  2 05:23:47 2017
From: nasbelyakova at gmail.com (=?UTF-8?B?0JHQtdC70Y/QutC+0LLQsCDQkNC90LDRgdGC0LDRgdC40Y8=?=)
Date: Sun, 2 Apr 2017 12:23:47 +0300
Subject: [Tutor] (no subject)
Message-ID: <CADUrRc3WHqmjNLRdGcYcGgP3sHnXVOCzupC+Zy0qZaw5v94cBA@mail.gmail.com>

Hi there! How are you?
I need an advise.

I need to get values from html form, but form.getvalues['query'] returns
None. Incorporated in function and not. The aim is to get the user input
after filling form and clicking submit button. Here is a piece of code:

form = cgi.FieldStorage()

A = ['Course_Name', 'Gender', 'Phone_No', 'Residential_Address',
'Student_LastName',
     'Student_FirstName', 'Password']
data_values = {}for i in dict(form).keys():
    if i in A:
        data_values[(str(i))] = "'" + dict(form)[str(i)].value + "'"



course, gender, phone, adress, last_name, first_name, password=
[data_values[i] for i in sorted(data_values.keys())]

And this is a fragment of html:

<form action="/cgi-bin/Hello.py" name="StudentRegistrationForm"
method="post" onsubmit="return ValidateForm()">

<input type="text" name="Student_LastName" size="40" maxlength="30"
style="font-weight: 700"/></font></td>

What could be the reason? What can I do?

From __peter__ at web.de  Sun Apr  2 12:07:49 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 02 Apr 2017 18:07:49 +0200
Subject: [Tutor] (no subject)
References: <CADUrRc3WHqmjNLRdGcYcGgP3sHnXVOCzupC+Zy0qZaw5v94cBA@mail.gmail.com>
Message-ID: <obr7kk$9t$1@blaine.gmane.org>

???????? ????????? wrote:

> Hi there! How are you?
> I need an advise.
> 
> I need to get values from html form, but form.getvalues['query'] returns
> None. 

I took a quick look into the cgi module, and FieldStorage class doesn't seem 
to have a getvalues attribute. You should get an exception rather than a 
None value. For easier debugging make sure your script starts with the lines

#!/usr/bin/env python3
import cgitb
cgitb.enable()

> Incorporated in function and not. The aim is to get the user input
> after filling form and clicking submit button. Here is a piece of code:
> 
> form = cgi.FieldStorage()
> 
> A = ['Course_Name', 'Gender', 'Phone_No', 'Residential_Address',
> 'Student_LastName',
>      'Student_FirstName', 'Password']
> data_values = {}for i in dict(form).keys():
>     if i in A:
>         data_values[(str(i))] = "'" + dict(form)[str(i)].value + "'"
> 
> 
> 
> course, gender, phone, adress, last_name, first_name, password=
> [data_values[i] for i in sorted(data_values.keys())]
> 
> And this is a fragment of html:
> 
> <form action="/cgi-bin/Hello.py" name="StudentRegistrationForm"
> method="post" onsubmit="return ValidateForm()">
> 
> <input type="text" name="Student_LastName" size="40" maxlength="30"
> style="font-weight: 700"/></font></td>
> 
> What could be the reason? What can I do?

Remove as much as you can from your script. E. g., does the following script 
show the contents of the form when you replace your current Hello.py with 
it?

#!/usr/bin/env python3
import cgitb
cgitb.enable()

import cgi
import sys

sys.stdout.write("Content-type: text/html\r\n\r\n")

print("""<html><body>""")
try:
    form = cgi.FieldStorage()
    cgi.print_form(form)
except:
    cgi.print_exception()
print("""</body></html>""")

If it doesn't double-check your setup (is the script executable, is your 
server configured properly etc.); once the basics work put stuff back in 
until the code does what you want -- or breaks. Then you can at least point 
to the exact statement that causes the breakage.


From s.molnar at sbcglobal.net  Sun Apr  2 13:41:27 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Sun, 2 Apr 2017 13:41:27 -0400
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
Message-ID: <58E137C7.7040501@sbcglobal.net>

I am trying to port a program that I wrote in FORTRAN twenty years ago 
into Python 3 and am having a hard time trying to calculate the 
Euclidean distance between each atom in the molecule and every other 
atom in the molecule.

Here is a typical table of coordinates:


       MASS         X         Y         Z
0   12.011 -3.265636  0.198894  0.090858
1   12.011 -1.307161  1.522212  1.003463
2   12.011  1.213336  0.948208 -0.033373
3   14.007  3.238650  1.041523  1.301322
4   12.011 -5.954489  0.650878  0.803379
5   12.011  5.654476  0.480066  0.013757
6   12.011  6.372043  2.731713 -1.662411
7   12.011  7.655753  0.168393  2.096802
8   12.011  5.563051 -1.990203 -1.511875
9    1.008 -2.939469 -1.327967 -1.247635
10   1.008 -1.460475  2.993912  2.415410
11   1.008  1.218042  0.451815 -2.057439
12   1.008 -6.255901  2.575035  1.496984
13   1.008 -6.560562 -0.695722  2.248982
14   1.008 -7.152500  0.390758 -0.864115
15   1.008  4.959548  3.061356 -3.139100
16   1.008  8.197613  2.429073 -2.588339
17   1.008  6.503322  4.471092 -0.543939
18   1.008  7.845274  1.892126  3.227577
19   1.008  9.512371 -0.273198  1.291080
20   1.008  7.147039 -1.365346  3.393778
21   1.008  4.191488 -1.928466 -3.057804
22   1.008  5.061650 -3.595015 -0.302810
23   1.008  7.402586 -2.392148 -2.374554

What I need for further calculation is a matrix of the Euclidean 
distances between the atoms.

So far in searching the Python literature I have only managed to confuse 
myself and would greatly appreciate any pointers towards a solution.

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 alan.gauld at yahoo.co.uk  Sun Apr  2 19:02:51 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Apr 2017 00:02:51 +0100
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
In-Reply-To: <58E137C7.7040501@sbcglobal.net>
References: <58E137C7.7040501@sbcglobal.net>
Message-ID: <obrvul$s7n$1@blaine.gmane.org>

On 02/04/17 18:41, Stephen P. Molnar wrote:
> I am trying to port a program that I wrote in FORTRAN twenty years ago 
> into Python 3 and am having a hard time trying to calculate the 
> Euclidean distance between each atom in the molecule and every other 
> atom in the molecule.

Sounds highly specialized. Remember this is a general language
tutor group and very few of us even know what Euclidean
distances between atoms might mean let alone how to calculate
them.

You need to either ask on a more technical group (such as
the SciPy forum maybe?) or provide the context so we know
what you are talking about. Its easy for experts to forget
just how little the rest of humanity knows about their area.


>        MASS         X         Y         Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
> 2   12.011  1.213336  0.948208 -0.033373
> 3   14.007  3.238650  1.041523  1.301322
> 4   12.011 -5.954489  0.650878  0.803379
> 
> What I need for further calculation is a matrix of the Euclidean 
> distances between the atoms.
> 
> So far in searching the Python literature I have only managed 
> to confuse myself

Where are you searching and what for? You are very unlikely
to find any references to Euclidean maths in the standard
library of docs. You might find them in the SciPy forums.

What have you tried? How did it fail?

-- 
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  Sun Apr  2 22:58:33 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 3 Apr 2017 12:58:33 +1000
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
In-Reply-To: <58E137C7.7040501@sbcglobal.net>
References: <58E137C7.7040501@sbcglobal.net>
Message-ID: <20170403025833.GK9464@ando.pearwood.info>

On Sun, Apr 02, 2017 at 01:41:27PM -0400, Stephen P. Molnar wrote:
> I am trying to port a program that I wrote in FORTRAN twenty years ago 
> into Python 3 and am having a hard time trying to calculate the 
> Euclidean distance between each atom in the molecule and every other 
> atom in the molecule.
> 
> Here is a typical table of coordinates:
> 
> 
>       MASS         X         Y         Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
[...]

> What I need for further calculation is a matrix of the Euclidean 
> distances between the atoms.

It is quite likely that the third-party Numpy or Scipy packages include 
read-made solutions to this. It sounds like the sort of thing that they 
will do, and probably much more efficiently than pure Python code.

But as a simple example, if I have two coordinates written as tuples:

p  = (-3.265636, 0.198894, 0.090858)
q = (-1.307161, 1.522212, 1.003463)

I can write a Euclidean distance function like this:


import math

def distance(a, b):
    """Return the Euclidean distance between 3D points a and b."""
    return math.sqrt(
            (a[0] - b[0])**2 + (a[1] - b[1])**2 + (a[2] - b[2])**2
            )


and then call the function:

result = distance(p, q)

which will return 2.5337013913983633 and assign it to the variable 
"result".

Does that help?



-- 
Steve

From mruffalo at cs.cmu.edu  Sun Apr  2 19:32:26 2017
From: mruffalo at cs.cmu.edu (Matt Ruffalo)
Date: Sun, 2 Apr 2017 19:32:26 -0400
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
In-Reply-To: <58E137C7.7040501@sbcglobal.net>
References: <58E137C7.7040501@sbcglobal.net>
Message-ID: <f2d473a4-2474-dec9-74ec-8157bb8eb2a4@cs.cmu.edu>

Hi Stephen-

The `scipy.spatial.distance` module (part of the SciPy package) contains
what you will need -- specifically, the `scipy.spatial.distance.pdist`
function, which takes a matrix of m observations in n-dimensional space,
and returns a condensed distance matrix as described in
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html
. This condensed distance matrix can be expanded into a full m by m
matrix with `scipy.spatial.distance.squareform` as follows:

"""
In [1]: import pandas as pd

In [2]: from io import StringIO

In [3]: s = StringIO('''
   ...:       MASS         X         Y         Z
   ...: 0   12.011 -3.265636  0.198894  0.090858
   ...: 1   12.011 -1.307161  1.522212  1.003463
   ...: 2   12.011  1.213336  0.948208 -0.033373
   ...: 3   14.007  3.238650  1.041523  1.301322
   ...: 4   12.011 -5.954489  0.650878  0.803379
   ...: 5   12.011  5.654476  0.480066  0.013757
   ...: 6   12.011  6.372043  2.731713 -1.662411
   ...: 7   12.011  7.655753  0.168393  2.096802
   ...: 8   12.011  5.563051 -1.990203 -1.511875
   ...: 9    1.008 -2.939469 -1.327967 -1.247635
   ...: 10   1.008 -1.460475  2.993912  2.415410
   ...: 11   1.008  1.218042  0.451815 -2.057439
   ...: 12   1.008 -6.255901  2.575035  1.496984
   ...: 13   1.008 -6.560562 -0.695722  2.248982
   ...: 14   1.008 -7.152500  0.390758 -0.864115
   ...: 15   1.008  4.959548  3.061356 -3.139100
   ...: 16   1.008  8.197613  2.429073 -2.588339
   ...: 17   1.008  6.503322  4.471092 -0.543939
   ...: 18   1.008  7.845274  1.892126  3.227577
   ...: 19   1.008  9.512371 -0.273198  1.291080
   ...: 20   1.008  7.147039 -1.365346  3.393778
   ...: 21   1.008  4.191488 -1.928466 -3.057804
   ...: 22   1.008  5.061650 -3.595015 -0.302810
   ...: 23   1.008  7.402586 -2.392148 -2.374554
   ...: ''')

In [4]: d = pd.read_table(s, sep='\\s+', index_col=0)

In [5]: d.head()
Out[5]:
     MASS         X         Y         Z
0  12.011 -3.265636  0.198894  0.090858
1  12.011 -1.307161  1.522212  1.003463
2  12.011  1.213336  0.948208 -0.033373
3  14.007  3.238650  1.041523  1.301322
4  12.011 -5.954489  0.650878  0.803379

In [6]: points = d.loc[:, ['X', 'Y', 'Z']]

In [7]: import scipy.spatial.distance

In [8]: distances = scipy.spatial.distance.pdist(points)

In [9]: distances.shape
Out[9]: (276,)

In [10]: distances
Out[10]:
array([  2.53370139,   4.54291701,   6.6694065 ,   2.81813878,
         8.92487537,  10.11800281,  11.10411993,   9.23615791,
         2.05651475,   4.0588513 ,   4.97820424,   4.0700026 ,
         4.03910564,   4.0070559 ,   9.28870116,  11.98156386,
        10.68116021,  11.66869152,  12.84293061,  11.03539433,
         8.36949409,   9.15928011,  11.25178722,   2.78521357,
         4.58084922,   4.73253781,   7.10844399,   8.21826934,
         9.13028167,   8.11565138,   3.98188296,   2.04523847,

<remaining elements not shown here>

In [11]: scipy.spatial.distance.squareform(distances)
Out[11]:
array([[  0.        ,   2.53370139,   4.54291701,   6.6694065 ,
          2.81813878,   8.92487537,  10.11800281,  11.10411993,
          9.23615791,   2.05651475,   4.0588513 ,   4.97820424,
          4.0700026 ,   4.03910564,   4.0070559 ,   9.28870116,
         11.98156386,  10.68116021,  11.66869152,  12.84293061,
         11.03539433,   8.36949409,   9.15928011,  11.25178722],
       [  2.53370139,   0.        ,   2.78521357,   4.58084922,
          4.73253781,   7.10844399,   8.21826934,   9.13028167,
          8.11565138,   3.98188296,   2.04523847,   4.10992956,
          5.08350537,   5.83684597,   6.2398737 ,   7.66820932,
         10.2011846 ,   8.49081803,   9.42605887,  10.9712576 ,
          9.24797787,   7.65742836,   8.27370019,  10.12881562],

<remaining elements not shown here>
"""

MMR...

On 2017-04-02 13:41, Stephen P. Molnar wrote:
> I am trying to port a program that I wrote in FORTRAN twenty years ago
> into Python 3 and am having a hard time trying to calculate the
> Euclidean distance between each atom in the molecule and every other
> atom in the molecule.
>
> Here is a typical table of coordinates:
>
>
>       MASS         X         Y         Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
> 2   12.011  1.213336  0.948208 -0.033373
> 3   14.007  3.238650  1.041523  1.301322
> 4   12.011 -5.954489  0.650878  0.803379
> 5   12.011  5.654476  0.480066  0.013757
> 6   12.011  6.372043  2.731713 -1.662411
> 7   12.011  7.655753  0.168393  2.096802
> 8   12.011  5.563051 -1.990203 -1.511875
> 9    1.008 -2.939469 -1.327967 -1.247635
> 10   1.008 -1.460475  2.993912  2.415410
> 11   1.008  1.218042  0.451815 -2.057439
> 12   1.008 -6.255901  2.575035  1.496984
> 13   1.008 -6.560562 -0.695722  2.248982
> 14   1.008 -7.152500  0.390758 -0.864115
> 15   1.008  4.959548  3.061356 -3.139100
> 16   1.008  8.197613  2.429073 -2.588339
> 17   1.008  6.503322  4.471092 -0.543939
> 18   1.008  7.845274  1.892126  3.227577
> 19   1.008  9.512371 -0.273198  1.291080
> 20   1.008  7.147039 -1.365346  3.393778
> 21   1.008  4.191488 -1.928466 -3.057804
> 22   1.008  5.061650 -3.595015 -0.302810
> 23   1.008  7.402586 -2.392148 -2.374554
>
> What I need for further calculation is a matrix of the Euclidean
> distances between the atoms.
>
> So far in searching the Python literature I have only managed to
> confuse myself and would greatly appreciate any pointers towards a
> solution.
>
> Thanks in advance.
>


From qiaozha at gmail.com  Sun Apr  2 19:06:47 2017
From: qiaozha at gmail.com (Asurin)
Date: Sun, 2 Apr 2017 19:06:47 -0400
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
In-Reply-To: <58E137C7.7040501@sbcglobal.net>
References: <58E137C7.7040501@sbcglobal.net>
Message-ID: <8FCCEE75-389C-4078-8C68-DA1653BC9BD3@gmail.com>

Dr. Molnar:

This might be your solution:
>>> import numpy
>>> a = numpy.array((-3.265636,  0.198894,  0.090858))
>>> b = numpy.array((-1.307161,  1.522212,  1.003463))
>>> dist = numpy.linalg.norm(a-b)
>>> dist
2.5337013913983633
>>> 


Qiao Qiao
> On Apr 2, 2017, at 1:41 PM, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
> 
> I am trying to port a program that I wrote in FORTRAN twenty years ago into Python 3 and am having a hard time trying to calculate the Euclidean distance between each atom in the molecule and every other atom in the molecule.
> 
> Here is a typical table of coordinates:
> 
> 
>      MASS         X         Y         Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
> 2   12.011  1.213336  0.948208 -0.033373
> 3   14.007  3.238650  1.041523  1.301322
> 4   12.011 -5.954489  0.650878  0.803379
> 5   12.011  5.654476  0.480066  0.013757
> 6   12.011  6.372043  2.731713 -1.662411
> 7   12.011  7.655753  0.168393  2.096802
> 8   12.011  5.563051 -1.990203 -1.511875
> 9    1.008 -2.939469 -1.327967 -1.247635
> 10   1.008 -1.460475  2.993912  2.415410
> 11   1.008  1.218042  0.451815 -2.057439
> 12   1.008 -6.255901  2.575035  1.496984
> 13   1.008 -6.560562 -0.695722  2.248982
> 14   1.008 -7.152500  0.390758 -0.864115
> 15   1.008  4.959548  3.061356 -3.139100
> 16   1.008  8.197613  2.429073 -2.588339
> 17   1.008  6.503322  4.471092 -0.543939
> 18   1.008  7.845274  1.892126  3.227577
> 19   1.008  9.512371 -0.273198  1.291080
> 20   1.008  7.147039 -1.365346  3.393778
> 21   1.008  4.191488 -1.928466 -3.057804
> 22   1.008  5.061650 -3.595015 -0.302810
> 23   1.008  7.402586 -2.392148 -2.374554
> 
> What I need for further calculation is a matrix of the Euclidean distances between the atoms.
> 
> So far in searching the Python literature I have only managed to confuse myself and would greatly appreciate any pointers towards a solution.
> 
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From quangnguyen51291 at gmail.com  Mon Apr  3 00:34:01 2017
From: quangnguyen51291 at gmail.com (Quang nguyen)
Date: Sun, 2 Apr 2017 22:34:01 -0600
Subject: [Tutor] Asking about Run python script at Startup
Message-ID: <CAGHbcgOPFFaE7_07Dj7UdgRxo-CQ8b_9UQ-VQCdQXrPEL-GyyA@mail.gmail.com>

Hi guys,

I do not know how to run my python 3 script after my PI2 finished startup.

I searched about it on some websites, and I feel so confused. Anyone know
the easy way to run at startup with escape plan?. I am afraid that it will
be a looping trap if I do not have escape plan :)

Thank you

From __peter__ at web.de  Mon Apr  3 05:36:10 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 03 Apr 2017 11:36:10 +0200
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
References: <58E137C7.7040501@sbcglobal.net>
Message-ID: <obt525$ths$1@blaine.gmane.org>

Stephen P. Molnar wrote:

> I am trying to port a program that I wrote in FORTRAN twenty years ago
> into Python 3 and am having a hard time trying to calculate the
> Euclidean distance between each atom in the molecule and every other
> atom in the molecule.
> 
> Here is a typical table of coordinates:
> 
> 
>        MASS         X         Y         Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
> 2   12.011  1.213336  0.948208 -0.033373
> 3   14.007  3.238650  1.041523  1.301322
> 4   12.011 -5.954489  0.650878  0.803379
> 5   12.011  5.654476  0.480066  0.013757
> 6   12.011  6.372043  2.731713 -1.662411
> 7   12.011  7.655753  0.168393  2.096802
> 8   12.011  5.563051 -1.990203 -1.511875
> 9    1.008 -2.939469 -1.327967 -1.247635
> 10   1.008 -1.460475  2.993912  2.415410
> 11   1.008  1.218042  0.451815 -2.057439
> 12   1.008 -6.255901  2.575035  1.496984
> 13   1.008 -6.560562 -0.695722  2.248982
> 14   1.008 -7.152500  0.390758 -0.864115
> 15   1.008  4.959548  3.061356 -3.139100
> 16   1.008  8.197613  2.429073 -2.588339
> 17   1.008  6.503322  4.471092 -0.543939
> 18   1.008  7.845274  1.892126  3.227577
> 19   1.008  9.512371 -0.273198  1.291080
> 20   1.008  7.147039 -1.365346  3.393778
> 21   1.008  4.191488 -1.928466 -3.057804
> 22   1.008  5.061650 -3.595015 -0.302810
> 23   1.008  7.402586 -2.392148 -2.374554
> 
> What I need for further calculation is a matrix of the Euclidean
> distances between the atoms.
> 
> So far in searching the Python literature I have only managed to confuse
> myself and would greatly appreciate any pointers towards a solution.
> 
> Thanks in advance.
> 

Stitched together with heavy use of a search engine:

$ cat data.txt
       MASS         X         Y         Z
0   12.011 -3.265636  0.198894  0.090858
1   12.011 -1.307161  1.522212  1.003463
2   12.011  1.213336  0.948208 -0.033373
3   14.007  3.238650  1.041523  1.301322
4   12.011 -5.954489  0.650878  0.803379
5   12.011  5.654476  0.480066  0.013757
6   12.011  6.372043  2.731713 -1.662411
7   12.011  7.655753  0.168393  2.096802
8   12.011  5.563051 -1.990203 -1.511875
9    1.008 -2.939469 -1.327967 -1.247635
10   1.008 -1.460475  2.993912  2.415410
11   1.008  1.218042  0.451815 -2.057439
12   1.008 -6.255901  2.575035  1.496984
13   1.008 -6.560562 -0.695722  2.248982
14   1.008 -7.152500  0.390758 -0.864115
15   1.008  4.959548  3.061356 -3.139100
16   1.008  8.197613  2.429073 -2.588339
17   1.008  6.503322  4.471092 -0.543939
18   1.008  7.845274  1.892126  3.227577
19   1.008  9.512371 -0.273198  1.291080
20   1.008  7.147039 -1.365346  3.393778
21   1.008  4.191488 -1.928466 -3.057804
22   1.008  5.061650 -3.595015 -0.302810
23   1.008  7.402586 -2.392148 -2.374554
$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy, pandas, scipy.spatial.distance as dist
>>> df = pandas.read_table("data.txt", sep=" ", skipinitialspace=True)      
>>> a = numpy.array(df[["X", "Y", "Z"]])
>>> dist.squareform(dist.pdist(a, "euclidean"))
<snip big matrix>

Here's an example with just the first 4 atoms:

>>> dist.squareform(dist.pdist(a[:4], "euclidean"))
array([[ 0.        ,  2.53370139,  4.54291701,  6.6694065 ],
       [ 2.53370139,  0.        ,  2.78521357,  4.58084922],
       [ 4.54291701,  2.78521357,  0.        ,  2.42734737],
       [ 6.6694065 ,  4.58084922,  2.42734737,  0.        ]])

See 
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html
There may be a way to do this with pandas.pivot_table(), but I didn't manage 
to find that.

As Alan says, this is not the appropriate forum for the topic you are 
belabouring. 

Work your way through a Python tutorial to pick up the basics (we can help 
you with this), then go straight to where the (numpy/scipy) experts are.


From alan.gauld at yahoo.co.uk  Mon Apr  3 06:20:57 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Apr 2017 11:20:57 +0100
Subject: [Tutor] Asking about Run python script at Startup
In-Reply-To: <CAGHbcgOPFFaE7_07Dj7UdgRxo-CQ8b_9UQ-VQCdQXrPEL-GyyA@mail.gmail.com>
References: <CAGHbcgOPFFaE7_07Dj7UdgRxo-CQ8b_9UQ-VQCdQXrPEL-GyyA@mail.gmail.com>
Message-ID: <obt7m3$osd$1@blaine.gmane.org>

On 03/04/17 05:34, Quang nguyen wrote:

> I do not know how to run my python 3 script after my PI2 finished startup.

This might be a better question for a PI forum since it doesn't
seem to have anything directly to do with Python.

> the easy way to run at startup with escape plan?. 

You will need to define what you want more clearly.
Do you want your script to start as soon as the PI boots
up - before you login? Or do you want it to start as soon
as you login? Or do you want to start it manually as soon
as you finish logging in?

Also, if you are running a GUI then you must decide if
you want the script to start before or after the GUI
launches.

(BTW I have no idea what you mean by an escape plan?
Do you mean stopping the script when you hit Escape?
Ctl-C is the usual means of doing 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 rafael.knuth at gmail.com  Mon Apr  3 08:22:29 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Mon, 3 Apr 2017 14:22:29 +0200
Subject: [Tutor] Count for loops
Message-ID: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>

I wrote a program which checks if PI (first one million digits)
contains a person's birth year.

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"

with open (file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

for year in b:
    if get_year in b:
        print("Your year of birth occurs in PI!")
        break
    else:
        print("Your year of birth does not occur in PI.")
        break

As a next challenge, I wanted to check how often a person's birth year
occurs in PI. Unfortunately, I wasn't able to figure out how to use
the loop count properly. Can anyone help? Thanks!

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"
with open(file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

count = 0
for year in b:
    if get_year in b:
        count += 1
    else:
        print("Your birth date does not occur in PI.")
        break
    sum_count = sum(count)
    print("Your birth date occurs %s times in PI!" % (sum_count))

From alan.gauld at yahoo.co.uk  Mon Apr  3 10:52:20 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Apr 2017 15:52:20 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
Message-ID: <obtnit$k8t$1@blaine.gmane.org>

On 03/04/17 13:22, Rafael Knuth wrote:

> with open (file_path) as a:
>     b = a.read()
> 
> get_year = input("What year were you born? ")
> 
> for year in b:

Can you explain what you think this loop line is doing?
I'm pretty sure it's not doing what you expect.

>     if get_year in b:
>         print("Your year of birth occurs in PI!")
>         break
>     else:
>         print("Your year of birth does not occur in PI.")
>         break
> 
> As a next challenge, I wanted to check how often a person's birth year
> occurs in PI. Unfortunately, I wasn't able to figure out how to use
> the loop count properly. 

What loop count?
There is none, its a for loop, no counter needed.
(OK I just spotted your code below...)

But there is a count() method on a string object that should help.


> count = 0
> for year in b:
>     if get_year in b:
>         count += 1
>     else:
>         print("Your birth date does not occur in PI.")
>         break

>     sum_count = sum(count)

sum() sums a sequence, but count is an integer. You have been
incrementing it as you go, the final value is already 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 dvnsarma at gmail.com  Mon Apr  3 11:07:37 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Mon, 3 Apr 2017 20:37:37 +0530
Subject: [Tutor] Count for loops
In-Reply-To: <obtnit$k8t$1@blaine.gmane.org>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
Message-ID: <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>

Modifying the code as shown below may work.

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"
with open(file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

count = 0
for year in b:
    if get_year in b:
        count += 1
print("Your birth date occurs %s times in PI!" % (count))

regards,
Sarma.

On Mon, Apr 3, 2017 at 8:22 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 03/04/17 13:22, Rafael Knuth wrote:
>
> > with open (file_path) as a:
> >     b = a.read()
> >
> > get_year = input("What year were you born? ")
> >
> > for year in b:
>
> Can you explain what you think this loop line is doing?
> I'm pretty sure it's not doing what you expect.
>
> >     if get_year in b:
> >         print("Your year of birth occurs in PI!")
> >         break
> >     else:
> >         print("Your year of birth does not occur in PI.")
> >         break
> >
> > As a next challenge, I wanted to check how often a person's birth year
> > occurs in PI. Unfortunately, I wasn't able to figure out how to use
> > the loop count properly.
>
> What loop count?
> There is none, its a for loop, no counter needed.
> (OK I just spotted your code below...)
>
> But there is a count() method on a string object that should help.
>
>
> > count = 0
> > for year in b:
> >     if get_year in b:
> >         count += 1
> >     else:
> >         print("Your birth date does not occur in PI.")
> >         break
>
> >     sum_count = sum(count)
>
> sum() sums a sequence, but count is an integer. You have been
> incrementing it as you go, the final value is already 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
>
>
> _______________________________________________
> 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 Apr  3 11:14:57 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Apr 2017 16:14:57 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
Message-ID: <obtota$jtf$1@blaine.gmane.org>

On 03/04/17 16:07, D.V.N.Sarma ??.??.???.???? wrote:
> Modifying the code as shown below may work.

I doubt it.

> with open(file_path) as a:
>     b = a.read()
> 
> get_year = input("What year were you born? ")
> 
> count = 0
> for year in b:

Once more I ask, what does this loop do?

>     if get_year in b:
>         count += 1
> print("Your birth date occurs %s times in PI!" % (count))

-- 
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 dvnsarma at gmail.com  Mon Apr  3 11:42:08 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Mon, 3 Apr 2017 21:12:08 +0530
Subject: [Tutor] Count for loops
In-Reply-To: <obtota$jtf$1@blaine.gmane.org>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
Message-ID: <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>

Sorry. That was  stupid of me. The loop does nothing.




regards,
Sarma.

On Mon, Apr 3, 2017 at 8:44 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 03/04/17 16:07, D.V.N.Sarma ??.??.???.???? wrote:
> > Modifying the code as shown below may work.
>
> I doubt it.
>
> > with open(file_path) as a:
> >     b = a.read()
> >
> > get_year = input("What year were you born? ")
> >
> > count = 0
> > for year in b:
>
> Once more I ask, what does this loop do?
>
> >     if get_year in b:
> >         count += 1
> > print("Your birth date occurs %s times in PI!" % (count))
>
> --
> 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 Apr  3 12:07:35 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Apr 2017 17:07:35 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
Message-ID: <obts00$vfu$1@blaine.gmane.org>

On 03/04/17 16:42, D.V.N.Sarma ??.??.???.???? wrote:
> Sorry. That was  stupid of me. The loop does nothing.
> 

On the contrary, the loop does an awful lot, just
not what the OP was expecting.

>>> with open(file_path) as a:
>>>     b = a.read()

>>> for year in b:
>>>     if get_year in b:
>>>         count += 1

-- 
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 Apr  3 12:16:45 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Apr 2017 17:16:45 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
Message-ID: <obtsh6$6cu$1@blaine.gmane.org>

On 03/04/17 16:42, D.V.N.Sarma ??.??.???.???? wrote:
> Sorry. That was  stupid of me. The loop does nothing.

Let me rewrite the code with some different variable names...

>>> with open(file_path) as a:
>>>     b = a.read()

with open (file_path) as PI_text:
     PI_as_a_long_string = PI_text.read()

>>> for year in b:

for each_char in PI_as_a_long_string:

>>>     if get_year in b:
>>>         count += 1

      if get_year in PI_as_a_long_string:
          count += 1

>>> print("Your birth date occurs %s times in PI!" % (count))

if count:
   print("Your birth date occurs in PI, I checked, count, "times!")


Aren't meaningful variable names great? We should all do
them more often.

-- 
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 mats at wichmann.us  Mon Apr  3 12:03:31 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 3 Apr 2017 10:03:31 -0600
Subject: [Tutor] Asking about Run python script at Startup
In-Reply-To: <obt7m3$osd$1@blaine.gmane.org>
References: <CAGHbcgOPFFaE7_07Dj7UdgRxo-CQ8b_9UQ-VQCdQXrPEL-GyyA@mail.gmail.com>
 <obt7m3$osd$1@blaine.gmane.org>
Message-ID: <e2af2175-e42a-3997-a4e1-bf722985d6be@wichmann.us>

On 04/03/2017 04:20 AM, Alan Gauld via Tutor wrote:
> On 03/04/17 05:34, Quang nguyen wrote:
> 
>> I do not know how to run my python 3 script after my PI2 finished startup.
> 
> This might be a better question for a PI forum since it doesn't
> seem to have anything directly to do with Python.
> 
>> the easy way to run at startup with escape plan?. 
> 
> You will need to define what you want more clearly.
> Do you want your script to start as soon as the PI boots
> up - before you login? Or do you want it to start as soon
> as you login? Or do you want to start it manually as soon
> as you finish logging in?
> 
> Also, if you are running a GUI then you must decide if
> you want the script to start before or after the GUI
> launches.
> 
> (BTW I have no idea what you mean by an escape plan?
> Do you mean stopping the script when you hit Escape?
> Ctl-C is the usual means of doing that)
> 

Indeed, this doesn't even reveal what the RPi is running, since there
are many many options. Presumably it's a linux variant (like Raspbian
which I think is still the "default", been a while since I looked);
there's plenty of information on "initscripts" (older way) and "systemd"
(newer way) if you're looking for a system-level startup script for
Linux, as well as ways to run things at a user level (when you log in,
or when your desktop environment is instantiated if you run one).
Rapsberry PI forums and Linux forums are good places to look.



From ejmmanning at gmail.com  Mon Apr  3 14:43:51 2017
From: ejmmanning at gmail.com (Ed Manning)
Date: Mon, 3 Apr 2017 14:43:51 -0400
Subject: [Tutor] Validating String contains IP address
In-Reply-To: <01dc2f1b33ea567cff32f140835dda07@sonic.net>
References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
 <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net>
 <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us>
 <01dc2f1b33ea567cff32f140835dda07@sonic.net>
Message-ID: <2583766A-2FFD-40CA-88B9-61923B609ED1@gmail.com>

Hello 

what am I going wrong here? i need to validate this is an IP or ask the question again 

untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 172.20.2.3/28"'':')
while not ipaddress.ip_network untrust_ip_address:
           untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 172.20.2.3/28"'':')
 
 
> On Apr 1, 2017, at 12:29 PM, Alex Kleider <akleider at sonic.net> wrote:
> 
> On 2017-03-31 18:01, Mats Wichmann wrote:
>> On 03/31/2017 06:44 PM, Alex Kleider wrote:
>>> On 2017-03-31 16:35, Ed Manning wrote:
>>>> What's the best way to validate a string contains a IP address
>>>> Sent from my iPad
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> https://mail.python.org/mailman/listinfo/tutor
>>> The re module perhaps?
> 
>> This assumes "an IP address" is the four dotted numbers characteristic
>> of IPv4. These days that's a bad assumption unless you're absolutely
>> sure an IPv6 address can never appear.  Can you?
> 
> Good point! I hadn't considered IPV6 and didn't know about the ipaddress module.
> Live and learn.


From mats at wichmann.us  Mon Apr  3 15:24:51 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 3 Apr 2017 13:24:51 -0600
Subject: [Tutor] Count for loops
In-Reply-To: <obtsh6$6cu$1@blaine.gmane.org>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
Message-ID: <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>

On 04/03/2017 10:16 AM, Alan Gauld via Tutor wrote:
> On 03/04/17 16:42, D.V.N.Sarma ??.??.???.???? wrote:
>> Sorry. That was  stupid of me. The loop does nothing.
> 
> Let me rewrite the code with some different variable names...
> 
>>>> with open(file_path) as a:
>>>>     b = a.read()
> 
> with open (file_path) as PI_text:
>      PI_as_a_long_string = PI_text.read()
> 
>>>> for year in b:
> 
> for each_char in PI_as_a_long_string:
> 
>>>>     if get_year in b:
>>>>         count += 1
> 
>       if get_year in PI_as_a_long_string:
>           count += 1
> 
>>>> print("Your birth date occurs %s times in PI!" % (count))
> 
> if count:
>    print("Your birth date occurs in PI, I checked, count, "times!")
> 
> 
> Aren't meaningful variable names great? We should all do
> them more often.


So the takeaways here are:

in the first ("non-counting") sample, there's no need to use a loop,
because you're going to quit after the outcome "in" or "not in" right
away - there's no loop behavior at all.

for year in b:
    if get_year in b:
        print("Your year of birth occurs in PI!")
        break
    else:
        print("Your year of birth does not occur in PI.")
        break

for the counting version you could do something that searches for the
year repeatedly, avoiding starting over from the beginning so you're
actually finding fresh instances, not the same one (hint, hint). There
are several ways to do this, including slicing, indexing, etc.  Alan's
suggestion looks as good as any.

Or, if you don't care about overlapping cases, the count method of a
string will do just fine:

PI_as_a_long_string.count(year)

If you're talking about 4-digit year numbers using a Western calendar in
digits of PI, the overlap effect seems unlikely to matter - let's say
the year is 1919, do we think PI contains the sequence 191919? count
would report back one instead of two in that case. In other cases it
might matter; count is written specifically to not care about overlaps:
"Return the number of (non-overlapping) occurrences"  So that's worth
keeping in mind when you think about what you need from
substrings-in-strings cases.




From quangnguyen51291 at gmail.com  Mon Apr  3 16:29:28 2017
From: quangnguyen51291 at gmail.com (Quang nguyen)
Date: Mon, 3 Apr 2017 14:29:28 -0600
Subject: [Tutor] asking about run the python 3 script in terminal
Message-ID: <CAGHbcgOFmYn9-r8N=X6nnKLbb4L7C+6WhYnCWvH-bd=FuCTBxA@mail.gmail.com>

Hi guys,

I would like to open the script in Terminal with several extra pictures
which be called inside the script.

I tried to open in Terminal, but it gave me trouble about where is the
location of my pictures.

Thank you for time.

From s.molnar at sbcglobal.net  Mon Apr  3 15:44:05 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Mon, 3 Apr 2017 15:44:05 -0400
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
In-Reply-To: <obt525$ths$1@blaine.gmane.org>
References: <58E137C7.7040501@sbcglobal.net> <obt525$ths$1@blaine.gmane.org>
Message-ID: <58E2A605.6000305@sbcglobal.net>

On 04/03/2017 05:36 AM, Peter Otten wrote:
> Stephen P. Molnar wrote:
>
>> I am trying to port a program that I wrote in FORTRAN twenty years ago
>> into Python 3 and am having a hard time trying to calculate the
>> Euclidean distance between each atom in the molecule and every other
>> atom in the molecule.
>>
>> Here is a typical table of coordinates:
>>
>>
>>         MASS         X         Y         Z
>> 0   12.011 -3.265636  0.198894  0.090858
>> 1   12.011 -1.307161  1.522212  1.003463
>> 2   12.011  1.213336  0.948208 -0.033373
>> 3   14.007  3.238650  1.041523  1.301322
>> 4   12.011 -5.954489  0.650878  0.803379
>> 5   12.011  5.654476  0.480066  0.013757
>> 6   12.011  6.372043  2.731713 -1.662411
>> 7   12.011  7.655753  0.168393  2.096802
>> 8   12.011  5.563051 -1.990203 -1.511875
>> 9    1.008 -2.939469 -1.327967 -1.247635
>> 10   1.008 -1.460475  2.993912  2.415410
>> 11   1.008  1.218042  0.451815 -2.057439
>> 12   1.008 -6.255901  2.575035  1.496984
>> 13   1.008 -6.560562 -0.695722  2.248982
>> 14   1.008 -7.152500  0.390758 -0.864115
>> 15   1.008  4.959548  3.061356 -3.139100
>> 16   1.008  8.197613  2.429073 -2.588339
>> 17   1.008  6.503322  4.471092 -0.543939
>> 18   1.008  7.845274  1.892126  3.227577
>> 19   1.008  9.512371 -0.273198  1.291080
>> 20   1.008  7.147039 -1.365346  3.393778
>> 21   1.008  4.191488 -1.928466 -3.057804
>> 22   1.008  5.061650 -3.595015 -0.302810
>> 23   1.008  7.402586 -2.392148 -2.374554
>>
>> What I need for further calculation is a matrix of the Euclidean
>> distances between the atoms.
>>
>> So far in searching the Python literature I have only managed to confuse
>> myself and would greatly appreciate any pointers towards a solution.
>>
>> Thanks in advance.
>>
>
> Stitched together with heavy use of a search engine:
>
> $ cat data.txt
>         MASS         X         Y         Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
> 2   12.011  1.213336  0.948208 -0.033373
> 3   14.007  3.238650  1.041523  1.301322
> 4   12.011 -5.954489  0.650878  0.803379
> 5   12.011  5.654476  0.480066  0.013757
> 6   12.011  6.372043  2.731713 -1.662411
> 7   12.011  7.655753  0.168393  2.096802
> 8   12.011  5.563051 -1.990203 -1.511875
> 9    1.008 -2.939469 -1.327967 -1.247635
> 10   1.008 -1.460475  2.993912  2.415410
> 11   1.008  1.218042  0.451815 -2.057439
> 12   1.008 -6.255901  2.575035  1.496984
> 13   1.008 -6.560562 -0.695722  2.248982
> 14   1.008 -7.152500  0.390758 -0.864115
> 15   1.008  4.959548  3.061356 -3.139100
> 16   1.008  8.197613  2.429073 -2.588339
> 17   1.008  6.503322  4.471092 -0.543939
> 18   1.008  7.845274  1.892126  3.227577
> 19   1.008  9.512371 -0.273198  1.291080
> 20   1.008  7.147039 -1.365346  3.393778
> 21   1.008  4.191488 -1.928466 -3.057804
> 22   1.008  5.061650 -3.595015 -0.302810
> 23   1.008  7.402586 -2.392148 -2.374554
> $ python3
> Python 3.4.3 (default, Nov 17 2016, 01:08:31)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import numpy, pandas, scipy.spatial.distance as dist
>>>> df = pandas.read_table("data.txt", sep=" ", skipinitialspace=True)
>>>> a = numpy.array(df[["X", "Y", "Z"]])
>>>> dist.squareform(dist.pdist(a, "euclidean"))
> <snip big matrix>
>
> Here's an example with just the first 4 atoms:
>
>>>> dist.squareform(dist.pdist(a[:4], "euclidean"))
> array([[ 0.        ,  2.53370139,  4.54291701,  6.6694065 ],
>         [ 2.53370139,  0.        ,  2.78521357,  4.58084922],
>         [ 4.54291701,  2.78521357,  0.        ,  2.42734737],
>         [ 6.6694065 ,  4.58084922,  2.42734737,  0.        ]])
>
> See
> https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html
> There may be a way to do this with pandas.pivot_table(), but I didn't manage
> to find that.
>
> As Alan says, this is not the appropriate forum for the topic you are
> belabouring.
>
> Work your way through a Python tutorial to pick up the basics (we can help
> you with this), then go straight to where the (numpy/scipy) experts are.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

Thanks to everyone who answered.

The problem has been solved.

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1

From ben+python at benfinney.id.au  Mon Apr  3 18:43:30 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Tue, 04 Apr 2017 08:43:30 +1000
Subject: [Tutor] asking about run the python 3 script in terminal
References: <CAGHbcgOFmYn9-r8N=X6nnKLbb4L7C+6WhYnCWvH-bd=FuCTBxA@mail.gmail.com>
Message-ID: <85inmldsdp.fsf@benfinney.id.au>

Quang nguyen <quangnguyen51291 at gmail.com> writes:

> I would like to open the script in Terminal with several extra
> pictures which be called inside the script.

I think by ?Terminal? you mean the text-only terminal emulator.

By definition, then, a text-only terminal is not going to display
graphic images.

So, can you explain what you mean by ?open the script [?] with several
extra pictures??

> I tried to open in Terminal, but it gave me trouble about where is the
> location of my pictures.

If you can give a very simple example that shows what you're trying to
do ? enough that we can try it too, and try to see what you're seeing
when you do it ? then we may be able to help.

-- 
 \       ?To have the choice between proprietary software packages, is |
  `\      being able to choose your master. Freedom means not having a |
_o__)                        master.? ?Richard M. Stallman, 2007-05-16 |
Ben Finney


From martin at linux-ip.net  Mon Apr  3 19:04:46 2017
From: martin at linux-ip.net (Martin A. Brown)
Date: Mon, 3 Apr 2017 16:04:46 -0700
Subject: [Tutor] Validating String contains IP address
In-Reply-To: <2583766A-2FFD-40CA-88B9-61923B609ED1@gmail.com>
References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
 <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net>
 <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us>
 <01dc2f1b33ea567cff32f140835dda07@sonic.net>
 <2583766A-2FFD-40CA-88B9-61923B609ED1@gmail.com>
Message-ID: <alpine.LSU.2.11.1704031550120.2147@znpeba.jbaqresebt.arg>


Hello there,

>what am I going wrong here? i need to validate this is an IP or ask 
>the question again
>
>untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 172.20.2.3/28"'':')

This is a representation of an IP address along with the mask length for the
prefix:

  172.20.2.3/28 

That is not, strictly speaking an IP, because there is ancillary 
information included.  This corresponds to:

  172.20.2.3     IP address
  172.20.2.0/28  prefix

The form you are showing is found on some systems, for example in 
the output from `ip address show` on Linux systems, but it is a 
commonly understood form.  Look further at the library that I 
recommended last week, and I think you will find a solution.

>while not ipaddress.ip_network untrust_ip_address:
>           untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 172.20.2.3/28"'':')

You might try using the ipaddress library in the following way:

  >>> i = ipaddress.ip_interface(u'172.20.2.3/28')
  >>> i.ip
  IPv4Address(u'172.20.2.3')
  >>> i.network
  IPv4Network(u'172.20.2.0/28')
  >>> i.with_prefixlen
  u'172.20.2.3/28'

Good luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/

From alan.gauld at yahoo.co.uk  Mon Apr  3 19:35:00 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Apr 2017 00:35:00 +0100
Subject: [Tutor] Validating String contains IP address
In-Reply-To: <2583766A-2FFD-40CA-88B9-61923B609ED1@gmail.com>
References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
 <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net>
 <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us>
 <01dc2f1b33ea567cff32f140835dda07@sonic.net>
 <2583766A-2FFD-40CA-88B9-61923B609ED1@gmail.com>
Message-ID: <obum6u$h8m$1@blaine.gmane.org>

On 03/04/17 19:43, Ed Manning wrote:

> untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 172.20.2.3/28"'':')
> while not ipaddress.ip_network untrust_ip_address:

Doesn't that give a syntax error?

-- 
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 dvnsarma at gmail.com  Mon Apr  3 19:37:29 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Tue, 4 Apr 2017 05:07:29 +0530
Subject: [Tutor] Count for loops
In-Reply-To: <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
Message-ID: <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>

I will go for this modification of the original code.

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"
with open(file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

count = 0
b= '3'+b[2:]
n = len(b)
for i in range(n-4):
    if b[i:i+4] == get_year:
        count += 1
print("Your birth date occurs %s times in PI!" % (count))

regards,
Sarma.

On Tue, Apr 4, 2017 at 12:54 AM, Mats Wichmann <mats at wichmann.us> wrote:

> On 04/03/2017 10:16 AM, Alan Gauld via Tutor wrote:
> > On 03/04/17 16:42, D.V.N.Sarma ??.??.???.???? wrote:
> >> Sorry. That was  stupid of me. The loop does nothing.
> >
> > Let me rewrite the code with some different variable names...
> >
> >>>> with open(file_path) as a:
> >>>>     b = a.read()
> >
> > with open (file_path) as PI_text:
> >      PI_as_a_long_string = PI_text.read()
> >
> >>>> for year in b:
> >
> > for each_char in PI_as_a_long_string:
> >
> >>>>     if get_year in b:
> >>>>         count += 1
> >
> >       if get_year in PI_as_a_long_string:
> >           count += 1
> >
> >>>> print("Your birth date occurs %s times in PI!" % (count))
> >
> > if count:
> >    print("Your birth date occurs in PI, I checked, count, "times!")
> >
> >
> > Aren't meaningful variable names great? We should all do
> > them more often.
>
>
> So the takeaways here are:
>
> in the first ("non-counting") sample, there's no need to use a loop,
> because you're going to quit after the outcome "in" or "not in" right
> away - there's no loop behavior at all.
>
> for year in b:
>     if get_year in b:
>         print("Your year of birth occurs in PI!")
>         break
>     else:
>         print("Your year of birth does not occur in PI.")
>         break
>
> for the counting version you could do something that searches for the
> year repeatedly, avoiding starting over from the beginning so you're
> actually finding fresh instances, not the same one (hint, hint). There
> are several ways to do this, including slicing, indexing, etc.  Alan's
> suggestion looks as good as any.
>
> Or, if you don't care about overlapping cases, the count method of a
> string will do just fine:
>
> PI_as_a_long_string.count(year)
>
> If you're talking about 4-digit year numbers using a Western calendar in
> digits of PI, the overlap effect seems unlikely to matter - let's say
> the year is 1919, do we think PI contains the sequence 191919? count
> would report back one instead of two in that case. In other cases it
> might matter; count is written specifically to not care about overlaps:
> "Return the number of (non-overlapping) occurrences"  So that's worth
> keeping in mind when you think about what you need from
> substrings-in-strings cases.
>
>
>
> _______________________________________________
> 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 Apr  3 20:07:44 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Apr 2017 01:07:44 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
Message-ID: <obuo4a$ao9$1@blaine.gmane.org>

On 04/04/17 00:37, D.V.N.Sarma ??.??.???.???? wrote:
> I will go for this modification of the original code.

> count = 0
> b= '3'+b[2:]
> n = len(b)
> for i in range(n-4):
>     if b[i:i+4] == get_year:
>         count += 1

While I think this works OK, I would probably suggest
that this is one of the rare valid cases for using
a regex(*) with a simple string. The findall() method
with a suitable pattern and flags should catch
overlaps. And is probably faster being written in C.

(*)Assuming you want to include overlapping cases,
otherwise just use b.count()...

-- 
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 dvnsarma at gmail.com  Mon Apr  3 20:13:49 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Tue, 4 Apr 2017 05:43:49 +0530
Subject: [Tutor] Count for loops
In-Reply-To: <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
Message-ID: <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>

Small correction.

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"
with open(file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

count = 0
b= '3'+b[2:]
n = len(b)
for i in range(n-3):
    if b[i:i+4] == get_year:
        count += 1
print("Your birth date occurs %s times in PI!" % (count))


regards,
Sarma.

On Tue, Apr 4, 2017 at 5:07 AM, D.V.N.Sarma ??.??.???.???? <
dvnsarma at gmail.com> wrote:

> I will go for this modification of the original code.
>
> file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"
> with open(file_path) as a:
>     b = a.read()
>
> get_year = input("What year were you born? ")
>
> count = 0
> b= '3'+b[2:]
> n = len(b)
> for i in range(n-4):
>     if b[i:i+4] == get_year:
>         count += 1
> print("Your birth date occurs %s times in PI!" % (count))
>
> regards,
> Sarma.
>
> On Tue, Apr 4, 2017 at 12:54 AM, Mats Wichmann <mats at wichmann.us> wrote:
>
>> On 04/03/2017 10:16 AM, Alan Gauld via Tutor wrote:
>> > On 03/04/17 16:42, D.V.N.Sarma ??.??.???.???? wrote:
>> >> Sorry. That was  stupid of me. The loop does nothing.
>> >
>> > Let me rewrite the code with some different variable names...
>> >
>> >>>> with open(file_path) as a:
>> >>>>     b = a.read()
>> >
>> > with open (file_path) as PI_text:
>> >      PI_as_a_long_string = PI_text.read()
>> >
>> >>>> for year in b:
>> >
>> > for each_char in PI_as_a_long_string:
>> >
>> >>>>     if get_year in b:
>> >>>>         count += 1
>> >
>> >       if get_year in PI_as_a_long_string:
>> >           count += 1
>> >
>> >>>> print("Your birth date occurs %s times in PI!" % (count))
>> >
>> > if count:
>> >    print("Your birth date occurs in PI, I checked, count, "times!")
>> >
>> >
>> > Aren't meaningful variable names great? We should all do
>> > them more often.
>>
>>
>> So the takeaways here are:
>>
>> in the first ("non-counting") sample, there's no need to use a loop,
>> because you're going to quit after the outcome "in" or "not in" right
>> away - there's no loop behavior at all.
>>
>> for year in b:
>>     if get_year in b:
>>         print("Your year of birth occurs in PI!")
>>         break
>>     else:
>>         print("Your year of birth does not occur in PI.")
>>         break
>>
>> for the counting version you could do something that searches for the
>> year repeatedly, avoiding starting over from the beginning so you're
>> actually finding fresh instances, not the same one (hint, hint). There
>> are several ways to do this, including slicing, indexing, etc.  Alan's
>> suggestion looks as good as any.
>>
>> Or, if you don't care about overlapping cases, the count method of a
>> string will do just fine:
>>
>> PI_as_a_long_string.count(year)
>>
>> If you're talking about 4-digit year numbers using a Western calendar in
>> digits of PI, the overlap effect seems unlikely to matter - let's say
>> the year is 1919, do we think PI contains the sequence 191919? count
>> would report back one instead of two in that case. In other cases it
>> might matter; count is written specifically to not care about overlaps:
>> "Return the number of (non-overlapping) occurrences"  So that's worth
>> keeping in mind when you think about what you need from
>> substrings-in-strings cases.
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>

From ejmmanning at gmail.com  Mon Apr  3 19:10:31 2017
From: ejmmanning at gmail.com (Ed Manning)
Date: Mon, 3 Apr 2017 19:10:31 -0400
Subject: [Tutor] Validating String contains IP address
In-Reply-To: <alpine.LSU.2.11.1704031550120.2147@znpeba.jbaqresebt.arg>
References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com>
 <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net>
 <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us>
 <01dc2f1b33ea567cff32f140835dda07@sonic.net>
 <2583766A-2FFD-40CA-88B9-61923B609ED1@gmail.com>
 <alpine.LSU.2.11.1704031550120.2147@znpeba.jbaqresebt.arg>
Message-ID: <E21BFB07-B94D-406C-B907-B96B74F1D3D4@gmail.com>

Thank you very much 

Sent from my iPhone

> On Apr 3, 2017, at 7:04 PM, Martin A. Brown <martin at linux-ip.net> wrote:
> 
> 
> Hello there,
> 
>> what am I going wrong here? i need to validate this is an IP or ask 
>> the question again
>> 
>> untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 172.20.2.3/28"'':')
> 
> This is a representation of an IP address along with the mask length for the
> prefix:
> 
>  172.20.2.3/28 
> 
> That is not, strictly speaking an IP, because there is ancillary 
> information included.  This corresponds to:
> 
>  172.20.2.3     IP address
>  172.20.2.0/28  prefix
> 
> The form you are showing is found on some systems, for example in 
> the output from `ip address show` on Linux systems, but it is a 
> commonly understood form.  Look further at the library that I 
> recommended last week, and I think you will find a solution.
> 
>> while not ipaddress.ip_network untrust_ip_address:
>>          untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 172.20.2.3/28"'':')
> 
> You might try using the ipaddress library in the following way:
> 
>>>> i = ipaddress.ip_interface(u'172.20.2.3/28')
>>>> i.ip
>  IPv4Address(u'172.20.2.3')
>>>> i.network
>  IPv4Network(u'172.20.2.0/28')
>>>> i.with_prefixlen
>  u'172.20.2.3/28'
> 
> Good luck,
> 
> -Martin
> 
> -- 
> Martin A. Brown
> http://linux-ip.net/

From lwaters at flinthill.org  Tue Apr  4 12:55:27 2017
From: lwaters at flinthill.org (Lisa Hasler Waters)
Date: Tue, 4 Apr 2017 12:55:27 -0400
Subject: [Tutor] How do we create a GUI to run a simple calculation program
 in Python?
Message-ID: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>

Hello Tutor,

A middle school student of mine created a program to calculate simple and
compound interest. He built it in PyCharm EDU using a Mac running 10.11.6.

He would like to create a GUI to run this program. Please, can you advise
on how he could build this?

Here is his code:

def simple(m, t, r):
    r = r/100
    print("The interest is {} and the total is {} ".format(r*m*t, m+r*m*t))

def compound(m, t, r):
    morg = m
    r = r/100
    for x in range(0, t):
        m = m*r+m
    print("The interest is {} and the total is {} if compounded
yearly.".format(m-morg, m))
    m = morg
    r = r/12
    for x in range(0, t*12):
        m = m*r+m
    print("The interest is {} and the total is {} if compounded
monthly.".format(m-morg, m))

choice = str(input("Would you like to use simple or compound interest? "))
m = int(input("Input the amount of money you would like to deposit
(don't use the $ symbol): "))
t = int(input("Input the amount of time you will be keeping your money
in the bank (in years): "))
r = int(input("Input the interest rate the bank offers (don't use the
% symbol): "))

if choice == 'simple':
    simple(m, t, r)
elif choice == 'compound':
    compound(m, t, r)
else:
    print("Your input is invalid")


Many 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  Tue Apr  4 15:12:40 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Apr 2017 20:12:40 +0100
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
Message-ID: <oc0r72$djt$1@blaine.gmane.org>

On 04/04/17 17:55, Lisa Hasler Waters wrote:

> A middle school student of mine created a program to calculate simple and
> compound interest. He built it in PyCharm EDU using a Mac running 10.11.6.
> 
> He would like to create a GUI to run this program. Please, can you advise
> on how he could build this?

He could use Tkinter, or he could create an HTML screen and
write a small server using a Framework like Flask.

Whatever he does he will need to dsepsarate his UI from his
logic - a good programming skill regardless of UI.

So his first step should be to create a CLI UI on top of
his existing code such that none of hi functions contain
print() or input() statements, they should all be in
new UI code.

The next step is to convert it to event driven style.
For this code that should almost be a done deal.

Finally decide on his GUI/Web framework and do a tutorial
to get up to speed and fit his new event-driven backend
code into that.

> Here is his code:
> 
> def simple(m, t, r):
>     r = r/100
>     print("The interest is {} and the total is {} ".format(r*m*t, m+r*m*t))

Should return a value not print a message

> def compound(m, t, r):
>     morg = m
>     r = r/100
>     for x in range(0, t):
>         m = m*r+m
>     print("The interest is {} and the total is {} if compounded
> yearly.".format(m-morg, m))
>     m = morg
>     r = r/12
>     for x in range(0, t*12):
>         m = m*r+m
>     print("The interest is {} and the total is {} if compounded
> monthly.".format(m-morg, m))
> 

Possiobly should be two separate methods, and definitely
should be returning values not printing stuff.


> choice = str(input("Would you like to use simple or compound interest? "))
> m = int(input("Input the amount of money you would like to deposit
> (don't use the $ symbol): "))
> t = int(input("Input the amount of time you will be keeping your money
> in the bank (in years): "))
> r = int(input("Input the interest rate the bank offers (don't use the
> % symbol): "))
> 
> if choice == 'simple':
>     simple(m, t, r)
> elif choice == 'compound':
>     compound(m, t, r)
> else:
>     print("Your input is invalid")

This needs to turn into a UI event loop which it almost is
but with no loop and no exit option.


-- 
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 gvmcmt at gmail.com  Tue Apr  4 14:40:35 2017
From: gvmcmt at gmail.com (Sri Kavi)
Date: Wed, 5 Apr 2017 00:10:35 +0530
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
Message-ID: <CADEQGhaWb2WofQ8pAh30rr4v4RKGHRH1YaHuG-_f6EjBqDvROw@mail.gmail.com>

On Tue, Apr 4, 2017 at 10:25, Lisa Hasler Waters wrote:

> Hello Tutor,
>
> A middle school student of mine created a program to calculate simple and
> compound interest. He built it in PyCharm EDU using a Mac running 10.11.6.
>
> He would like to create a GUI to run this program. Please, can you advise
> on how he could build this?
>
>
Please take a look at https://wiki.python.org/moin/GuiProgramming and
https://wiki.python.org/moin/TkInter

Hope that helps.

Sri

From mitukab at gmail.com  Tue Apr  4 07:19:48 2017
From: mitukab at gmail.com (brian mituka)
Date: Tue, 4 Apr 2017 14:19:48 +0300
Subject: [Tutor] learning resources
Message-ID: <CAKocXtSE-8TBAgYGR-+cY1Xwk9UPU+eCHp8Spmaq8WjuO9m_AQ@mail.gmail.com>

what are the best learning resources for a beginner in python... I want to
be able to write good code in ! month. Thanks..

From rafael.knuth at gmail.com  Tue Apr  4 07:04:42 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Tue, 4 Apr 2017 13:04:42 +0200
Subject: [Tutor] Count for loops
In-Reply-To: <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
Message-ID: <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>

Sarma: thank you so much, I checked your code, it works. However, can
you enlighten me what it exactly does?
I do not understand it (yet). Thank you in advance.

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"

with open (file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

count = 0
b = "3"+b[2:]
n = len(b)
for i in range(n-3):
    if b[i:i+4] == get_year:
        count += 1
print("Your birth date occurs %s times in PI!" % (count))

From akleider at sonic.net  Tue Apr  4 19:21:59 2017
From: akleider at sonic.net (Alex Kleider)
Date: Tue, 04 Apr 2017 16:21:59 -0700
Subject: [Tutor] Asking about Run python script at Startup
In-Reply-To: <CAGHbcgOPFFaE7_07Dj7UdgRxo-CQ8b_9UQ-VQCdQXrPEL-GyyA@mail.gmail.com>
References: <CAGHbcgOPFFaE7_07Dj7UdgRxo-CQ8b_9UQ-VQCdQXrPEL-GyyA@mail.gmail.com>
Message-ID: <58c8b1ec20c253dc340740f1858a9975@sonic.net>

On 2017-04-02 21:34, Quang nguyen wrote:
> Hi guys,
> 
> I do not know how to run my python 3 script after my PI2 finished 
> startup.

Have you looked here? :
http://raspberrypi.stackexchange.com/questions/8734/execute-script-on-start-up


From alan.gauld at yahoo.co.uk  Tue Apr  4 20:14:02 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 5 Apr 2017 01:14:02 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
Message-ID: <oc1cs3$gla$1@blaine.gmane.org>

On 04/04/17 12:04, Rafael Knuth wrote:
> Sarma: thank you so much, I checked your code, it works. However, can
> you enlighten me what it exactly does?

It just iterates over the PI string manually and compares
the birth date with the first 4 PI string characters.

It would probably be more pythonic and easier to read
to use startswith() instead

> count = 0
> b = "3"+b[2:]

I think this is to eliminate the period after the 3 of PI

> n = len(b)
> for i in range(n-3):
>     if b[i:i+4] == get_year:
>         count += 1

This is the core of it.
It starts with i = 0 and goes up to i = n-4
If b[i] to b[i+3] equals the birthdate you count
a match

You could rewrite it as

for i in range(n-3):
    if b.startswith(get_year, i):
       count += 1

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 marc.tompkins at gmail.com  Tue Apr  4 20:15:29 2017
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 4 Apr 2017 17:15:29 -0700
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
Message-ID: <CAKK8jXZH-h8BsneFb=93rh4BD50frpJfUH1fXRmpRAXRtpEiVQ@mail.gmail.com>

On Tue, Apr 4, 2017 at 9:55 AM, Lisa Hasler Waters <lwaters at flinthill.org>
wrote:

> Hello Tutor,
>
> A middle school student of mine created a program to calculate simple and
> compound interest. He built it in PyCharm EDU using a Mac running 10.11.6.
>
> He would like to create a GUI to run this program. Please, can you advise
> on how he could build this?
>
> Others have mentioned Tkinter and HTML; I''d like to put in my two cents'
worth for wxPython <https://wxpython.org/>.  HTML is probably the best
cross-platform solution, and requires the least extra stuff bolted on, but
wxPython lets you create desktop apps that look like they were actually
developed for the computer they run on.

Alan Gauld's comments about separating the GUI from the program logic are,
as usual, spot-on.

From alan.gauld at yahoo.co.uk  Tue Apr  4 20:18:48 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 5 Apr 2017 01:18:48 +0100
Subject: [Tutor] learning resources
In-Reply-To: <CAKocXtSE-8TBAgYGR-+cY1Xwk9UPU+eCHp8Spmaq8WjuO9m_AQ@mail.gmail.com>
References: <CAKocXtSE-8TBAgYGR-+cY1Xwk9UPU+eCHp8Spmaq8WjuO9m_AQ@mail.gmail.com>
Message-ID: <oc1d51$qgm$1@blaine.gmane.org>

On 04/04/17 12:19, brian mituka wrote:
> what are the best learning resources for a beginner in python...

Look on Python.org and you will find a beginners page with
many links. But... it will depend on whether you can
already program in another language which beginners
page you go to.

I am, of coutse, biased, but you could try my tutorial,
linked below.

> I want to be able to write good code in ! month. 

Define "good code". An expert may tell you he is
still struggling to write good code after 20 years
of using Python. A beginner might tell an employer
that he writes good code after only a few days.

In reality, if you already know how to code in any other
language, you should be able to write productive code
within a week.

If you are a complete programming novice then a month
is probably ambitious!

-- 
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 sergio_r at mail.com  Tue Apr  4 20:04:59 2017
From: sergio_r at mail.com (Sergio Rojas)
Date: Wed, 5 Apr 2017 02:04:59 +0200
Subject: [Tutor] A contribution for enhancing your Python SciPy skills
Message-ID: <trinity-aa699da7-284a-4c4b-8015-3512b3c66315-1491350699788@3capp-mailcom-lxa07>

Hello Guys,

I am just very happy to have finished my video project with Pack on a brief introduction to Machine Learning via SciPy :

https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video

Previously, as you might know, we finished this one:

https://www.packtpub.com/big-data-and-business-intelligence/learning-scipy-numerical-and-scientific-computing-second-edition

https://github.com/rojassergio/Learning-Scipy 

Hope you can spread the word.

Salut,

Sergio

From lwaters at flinthill.org  Wed Apr  5 08:49:09 2017
From: lwaters at flinthill.org (Lisa Hasler Waters)
Date: Wed, 5 Apr 2017 08:49:09 -0400
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <CAKK8jXZH-h8BsneFb=93rh4BD50frpJfUH1fXRmpRAXRtpEiVQ@mail.gmail.com>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
 <CAKK8jXZH-h8BsneFb=93rh4BD50frpJfUH1fXRmpRAXRtpEiVQ@mail.gmail.com>
Message-ID: <CAF91wy-HO13DsxMT+uOXBVpuPAf+ExZ0OTmcpCa=B8R1xNmJVw@mail.gmail.com>

Wonderful! Thank you all so very much for all this invaluable expertise. We
have a lot of ways to make this work. We are excited to continue learning
so much.

Lisa

On Tue, Apr 4, 2017 at 8:15 PM, Marc Tompkins <marc.tompkins at gmail.com>
wrote:

> On Tue, Apr 4, 2017 at 9:55 AM, Lisa Hasler Waters <lwaters at flinthill.org>
> wrote:
>
>> Hello Tutor,
>>
>> A middle school student of mine created a program to calculate simple and
>> compound interest. He built it in PyCharm EDU using a Mac running 10.11.6.
>>
>> He would like to create a GUI to run this program. Please, can you advise
>> on how he could build this?
>>
>> Others have mentioned Tkinter and HTML; I''d like to put in my two cents'
> worth for wxPython <https://wxpython.org/>.  HTML is probably the best
> cross-platform solution, and requires the least extra stuff bolted on, but
> wxPython lets you create desktop apps that look like they were actually
> developed for the computer they run on.
>
> Alan Gauld's comments about separating the GUI from the program logic are,
> as usual, spot-on.
>
>


-- 
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 neilc at norwich.edu  Wed Apr  5 10:43:00 2017
From: neilc at norwich.edu (Neil Cerutti)
Date: Wed, 5 Apr 2017 14:43:00 +0000 (UTC)
Subject: [Tutor] Count for loops
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
Message-ID: <oc2vpk$l3q$1@blaine.gmane.org>

On 2017-04-03, Mats Wichmann <mats at wichmann.us> wrote:
> If you're talking about 4-digit year numbers using a Western
> calendar in digits of PI, the overlap effect seems unlikely to
> matter - let's say the year is 1919, do we think PI contains
> the sequence 191919? count would report back one instead of two
> in that case. In other cases it might matter; count is written
> specifically to not care about overlaps: "Return the number of
> (non-overlapping) occurrences"  So that's worth keeping in mind
> when you think about what you need from substrings-in-strings
> cases.

Composing a FSA (finite state automata) by hand would be an
excellent exercise in addition to covering the overlapping cases.

Another fun exercise might be to find the bithdays using
arithmetic operations instead of string operations.

-- 
Neil Cerutti


From fazal.h.khan at gmail.com  Wed Apr  5 15:07:05 2017
From: fazal.h.khan at gmail.com (Fazal Khan)
Date: Wed, 5 Apr 2017 12:07:05 -0700
Subject: [Tutor] Question about loop and assigning variables
Message-ID: <CAAsX1=2FJr8J0a5qRe_ShsYd3C3E_TfTuP8zimU=yvL504Qj7Q@mail.gmail.com>

Hello,

Heres another newbie python question: How can I loop through some data and
assign different variables with each loop

So this is my original code:

def BeamInfo(x):
  for Bnum in x:
        if plan1.IonBeamSequence[Bnum].ScanMode == 'MODULATED':
            TxTableAngle =
plan1.IonBeamSequence[Bnum].IonControlPointSequence[0].PatientSupportAngle
            print(TxTableAngle)
        else:
            None

BeamInfo([0,1,2,3,4,5,6])


Ideally what I want is this: when Bnum is 0, then "TxTableAngle" will be
appended with "_0" (eg.TxTableAngle_0). When Bnum is 1 then TxTableAngle_1,
etc. How do I do this in python?

Thanks
-Fuz

From sergio_r at mail.com  Wed Apr  5 15:38:40 2017
From: sergio_r at mail.com (Sergio Rojas)
Date: Wed, 5 Apr 2017 21:38:40 +0200
Subject: [Tutor] Euclidean Distances between Atoms in a Molecule.
In-Reply-To: <mailman.502.1491232067.2960.tutor@python.org>
References: <mailman.502.1491232067.2960.tutor@python.org>
Message-ID: <trinity-b21f9334-2ce1-4a60-8dc9-b61adb90dce0-1491421120830@3capp-mailcom-lxa06>



------------------------------

Message: 2
Date: Mon, 03 Apr 2017 11:36:10 +0200
From: Peter Otten <__peter__ at web.de>
To: tutor at python.org
Subject: Re: [Tutor] Euclidean Distances between Atoms in a Molecule.
Message-ID: <obt525$ths$1 at blaine.gmane.org>
Content-Type: text/plain; charset="ISO-8859-1"

Stephen P. Molnar wrote:

> I am trying to port a program that I wrote in FORTRAN twenty years ago
> into Python 3 and am having a hard time trying to calculate the
> Euclidean distance between each atom in the molecule and every other
> atom in the molecule.
>
> Here is a typical table of coordinates:
>
>
> MASS X Y Z
> 0 12.011 -3.265636 0.198894 0.090858
> 1 12.011 -1.307161 1.522212 1.003463
> 2 12.011 1.213336 0.948208 -0.033373
> 3 14.007 3.238650 1.041523 1.301322
> 4 12.011 -5.954489 0.650878 0.803379
> 5 12.011 5.654476 0.480066 0.013757
> 6 12.011 6.372043 2.731713 -1.662411
> 7 12.011 7.655753 0.168393 2.096802
> 8 12.011 5.563051 -1.990203 -1.511875
> 9 1.008 -2.939469 -1.327967 -1.247635
> 10 1.008 -1.460475 2.993912 2.415410
> 11 1.008 1.218042 0.451815 -2.057439
> 12 1.008 -6.255901 2.575035 1.496984
> 13 1.008 -6.560562 -0.695722 2.248982
> 14 1.008 -7.152500 0.390758 -0.864115
> 15 1.008 4.959548 3.061356 -3.139100
> 16 1.008 8.197613 2.429073 -2.588339
> 17 1.008 6.503322 4.471092 -0.543939
> 18 1.008 7.845274 1.892126 3.227577
> 19 1.008 9.512371 -0.273198 1.291080
> 20 1.008 7.147039 -1.365346 3.393778
> 21 1.008 4.191488 -1.928466 -3.057804
> 22 1.008 5.061650 -3.595015 -0.302810
> 23 1.008 7.402586 -2.392148 -2.374554
>
> What I need for further calculation is a matrix of the Euclidean
> distances between the atoms.
>
> So far in searching the Python literature I have only managed to confuse
> myself and would greatly appreciate any pointers towards a solution.
>
> Thanks in advance.
>

Stitched together with heavy use of a search engine:

$ cat data.txt
MASS X Y Z
0 12.011 -3.265636 0.198894 0.090858
1 12.011 -1.307161 1.522212 1.003463
2 12.011 1.213336 0.948208 -0.033373
3 14.007 3.238650 1.041523 1.301322
4 12.011 -5.954489 0.650878 0.803379
5 12.011 5.654476 0.480066 0.013757
6 12.011 6.372043 2.731713 -1.662411
7 12.011 7.655753 0.168393 2.096802
8 12.011 5.563051 -1.990203 -1.511875
9 1.008 -2.939469 -1.327967 -1.247635
10 1.008 -1.460475 2.993912 2.415410
11 1.008 1.218042 0.451815 -2.057439
12 1.008 -6.255901 2.575035 1.496984
13 1.008 -6.560562 -0.695722 2.248982
14 1.008 -7.152500 0.390758 -0.864115
15 1.008 4.959548 3.061356 -3.139100
16 1.008 8.197613 2.429073 -2.588339
17 1.008 6.503322 4.471092 -0.543939
18 1.008 7.845274 1.892126 3.227577
19 1.008 9.512371 -0.273198 1.291080
20 1.008 7.147039 -1.365346 3.393778
21 1.008 4.191488 -1.928466 -3.057804
22 1.008 5.061650 -3.595015 -0.302810
23 1.008 7.402586 -2.392148 -2.374554
$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy, pandas, scipy.spatial.distance as dist
>>> df = pandas.read_table("data.txt", sep=" ", skipinitialspace=True)
>>> a = numpy.array(df[["X", "Y", "Z"]])
>>> dist.squareform(dist.pdist(a, "euclidean"))
<snip big matrix>

Here's an example with just the first 4 atoms:

>>> dist.squareform(dist.pdist(a[:4], "euclidean"))
array([[ 0. , 2.53370139, 4.54291701, 6.6694065 ],
[ 2.53370139, 0. , 2.78521357, 4.58084922],
[ 4.54291701, 2.78521357, 0. , 2.42734737],
[ 6.6694065 , 4.58084922, 2.42734737, 0. ]])

See
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html[https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html]
There may be a way to do this with pandas.pivot_table(), but I didn't manage
to find that.

As Alan says, this is not the appropriate forum for the topic you are
belabouring.

Work your way through a Python tutorial to pick up the basics (we can help
you with this), then go straight to where the (numpy/scipy) experts are.

------------------------------
An alternative starting from the numpy array "a" from Peter answer:

import numpy as np

#Taking the number of rows and columns of the array
anrows, ancols = np.shape(a)

# Gather the coordinates as one dimensional arrays
a_new = a.reshape(anrows, 1, ancols)

# Takes the difference between each of the elements (one Vs all)
diff = a_new - a   

# Computes the sum of the squared difference
D = (diff ** 2).sum(2)

# Takes the square root
D = np.sqrt(D)

#Check that both answers are the same:
print(D-dist.squareform(dist.pdist(a, "euclidean")))


Salut,

Sergio
Avoiding for loops section of:
https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video

From alan.gauld at yahoo.co.uk  Wed Apr  5 21:02:33 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 6 Apr 2017 02:02:33 +0100
Subject: [Tutor] Question about loop and assigning variables
In-Reply-To: <CAAsX1=2FJr8J0a5qRe_ShsYd3C3E_TfTuP8zimU=yvL504Qj7Q@mail.gmail.com>
References: <CAAsX1=2FJr8J0a5qRe_ShsYd3C3E_TfTuP8zimU=yvL504Qj7Q@mail.gmail.com>
Message-ID: <oc4433$9ld$1@blaine.gmane.org>

On 05/04/17 20:07, Fazal Khan wrote:

> assign different variables with each loop

You can't, but you can fake it...

> def BeamInfo(x):
>   for Bnum in x:
>         if plan1.IonBeamSequence[Bnum].ScanMode == 'MODULATED':
>             TxTableAngle =
> plan1.IonBeamSequence[Bnum].IonControlPointSequence[0].PatientSupportAngle
>             print(TxTableAngle)
>         else:
>             None

> Ideally what I want is this: when Bnum is 0, then "TxTableAngle" will be
> appended with "_0" (eg.TxTableAngle_0). When Bnum is 1 then TxTableAngle_1,
> etc. How do I do this in python?

Use a list (or a dictionary if the values are not sequential or numeric)

So
TxTableAngle_0 -> TxTableAngle[0]
TxTableAngle_1 -> TxTableAngle[1]

It's one extra character but hopefully that won't be too painful...

-- 
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 Apr  5 22:41:11 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 6 Apr 2017 12:41:11 +1000
Subject: [Tutor] Question about loop and assigning variables
In-Reply-To: <CAAsX1=2FJr8J0a5qRe_ShsYd3C3E_TfTuP8zimU=yvL504Qj7Q@mail.gmail.com>
References: <CAAsX1=2FJr8J0a5qRe_ShsYd3C3E_TfTuP8zimU=yvL504Qj7Q@mail.gmail.com>
Message-ID: <20170406024111.GP9464@ando.pearwood.info>

On Wed, Apr 05, 2017 at 12:07:05PM -0700, Fazal Khan wrote:
> Hello,
> 
> Heres another newbie python question: How can I loop through some data and
> assign different variables with each loop

You don't. That's a bad idea.

Instead, you use a sequence (a tuple, or a list), and use an index:

TxTableAngle[0]  # the first item
TxTableAngle[1]  # the second item
etc.


> So this is my original code:
> 
> def BeamInfo(x):
>   for Bnum in x:
>         if plan1.IonBeamSequence[Bnum].ScanMode == 'MODULATED':
>             TxTableAngle =
> plan1.IonBeamSequence[Bnum].IonControlPointSequence[0].PatientSupportAngle
>             print(TxTableAngle)
>         else:
>             None


Let's say you succeed in doing what you want, and you have a bunch of 
variables called TxTableAngle_0, TxTableAngle_1, TxTableAngle_2, and so 
on. How do you use them?

The first problem is that you don't know if they even exist! You might 
not have *any* TxTableAngle variables at all, if x is empty, of if 
ScanMode is never MODULATED. So even

    TxTableAngle_0

might fail with a NameError exception. But even if you can guarantee 
that there is *at least one* variable, you don't know how many there 
will be! That depends on how many times the ScanMode is MODULATED. 
Perhaps there is only one, perhaps there is a thousand. How do you know 
if it is safe to refer to:

    TxTableAngle_3

or not? This rapidly becomes hard to code, difficult to write, harder to 
debug and maintain, a real nightmare.

Better is to collect the results into a list:

def BeamInfo(x):
    results = []
    for bnum in x:
        beam = plan1.IonBeamSequence[bnum]
        if beam.ScanMode == 'MODULATED':
            TxTableAngle = beam.IonControlPointSequence[0].PatientSupportAngle
            results.append(TxTableAngle)
            print(TxtTableAngle)
    return results

TxTableAngles = BeamInfo([0,1,2,3,4,5,6])

Now you know that TxTableAngles *must* exist. You can find out how many 
items there actually are:

    len(TxTableAngles)

you can grab any one specific item (provided the index actually exists):

    TxTableAngles[i]

and most importantly you can process all of the angles one after the 
other:

    for angle in TxTableAngles:
        print(angle)


-- 
Steve

From mats at wichmann.us  Wed Apr  5 21:19:42 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 5 Apr 2017 19:19:42 -0600
Subject: [Tutor] Question about loop and assigning variables
In-Reply-To: <CAAsX1=2FJr8J0a5qRe_ShsYd3C3E_TfTuP8zimU=yvL504Qj7Q@mail.gmail.com>
References: <CAAsX1=2FJr8J0a5qRe_ShsYd3C3E_TfTuP8zimU=yvL504Qj7Q@mail.gmail.com>
Message-ID: <a507e3d4-c96e-6b55-b254-dd3646fa98db@wichmann.us>

On 04/05/2017 01:07 PM, Fazal Khan wrote:
> Hello,
> 
> Heres another newbie python question: How can I loop through some data and
> assign different variables with each loop
> 
> So this is my original code:
> 
> def BeamInfo(x):
>   for Bnum in x:
>         if plan1.IonBeamSequence[Bnum].ScanMode == 'MODULATED':
>             TxTableAngle =
> plan1.IonBeamSequence[Bnum].IonControlPointSequence[0].PatientSupportAngle
>             print(TxTableAngle)
>         else:
>             None
> 
> BeamInfo([0,1,2,3,4,5,6])
> 
> 
> Ideally what I want is this: when Bnum is 0, then "TxTableAngle" will be
> appended with "_0" (eg.TxTableAngle_0). When Bnum is 1 then TxTableAngle_1,
> etc. How do I do this in python?

well... what you're doing now is not very useful, as TxTableTangle goes
out of scope when the function has completed. Which means the work is
just lost.  And the else: clause - if you don't want to do anything here
(the terminology would be "pass", not "None", you don't even need to say
that).

the most likely solution, along the lines of what Alan has suggested, is
to create a list; and then you need to return it so it's actually usable
- just printing the output doesn't leave you with anything other than
characters on the console.  So consider this as a concept (not a working
implementation since there are other things missing):

def BeamInfo(x):
    TxTableAngle = []
    for Bnum in x:
        if blah :
            TxTableAngle.append(blah blah)
    return TxTableAngle

var = BeamInfo([0,1,2,3,4,5,6])

(of course whenever you have a create-empty-list followed by a loop of
append-to-list you can replace that by a list comprehension)

that gets you back a variable var containing a a reference to a list
("array" if you prefer to think of it that way) you can iterate over.




From someukdeveloper at gmail.com  Fri Apr  7 01:07:06 2017
From: someukdeveloper at gmail.com (Some Developer)
Date: Fri, 7 Apr 2017 06:07:06 +0100
Subject: [Tutor] Network Sniffing on Windows with Python 3.6
Message-ID: <9a6863d4-0bb6-18d3-680d-ee4c3c181e53@googlemail.com>

Hi,

This is more a query about where to look for information rather than 
asking for specific code.

There is a game that passes data over the network and I want to sniff 
the network protocol used by the game to pass data between the client 
and the server (before anyone asks no I am not cheating it is an MMO and 
I want to create a database site that holds information on all the items 
and quests in the game etc).

How would I go about writing a Python 3.6 script for Windows that would 
sniff the network traffic and take the individual packets and then 
reassemble them into something that is useful data? I've never done 
something like this before.

I was thinking of installing Wireshark to have a look at the network 
communications but I wasn't really sure what I would do with the data. 
Are there any library functions in Python 3.6 that would help with this 
task?

Basically I need to lock onto the games process and sniff any incomming 
or outgoing network traffic from that process. Is that possible?

Also does the Python script require admin permissions for this to work 
or can it run as a normal user? It doesn't matter if it does require 
admin permissions but it would be better for my users if it didn't 
require admin permissions.

I'm just looking for some help to push me in the right direction. If 
there are any books on the subject that would be even better as I like 
reading books on programming subjects.

Thanks for any help :).

From phil_lor at bigpond.com  Thu Apr  6 22:09:49 2017
From: phil_lor at bigpond.com (Phil)
Date: Fri, 7 Apr 2017 12:09:49 +1000
Subject: [Tutor] Tkinter grid question
Message-ID: <20170407120949.184fd6b9@raspberrypi>

Thank you for reading this.

This is my first attempt at using Tkinter and I've quickly run into a problem.

If e is a one dimensional list then all is OK and I can delete and insert entries. The problem comes about when the list is made two dimensional, as follows:

from tkinter import *

master = Tk()

e = [None] * 6 , [None] * 2

for i in range(6):
    for j in range(2):
        e[i][j] = Entry(master, width=5)
        e[i][j].grid(row=i, column=j)
        e[i][j].insert(0,"6")

mainloop( )

Traceback (most recent call last):
  File "/home/pi/tkinter_example.py", line 50, in <module>
    e[i][j] = Entry(master, width=5)
IndexError: tuple index out of range

I can see that the problem occurs when i is greater than 1 which makes me think that my method of attempting to create a two denominational array of edit boxes is wrong.

I've search for an example but haven't turned up anything. Where had I failed?

-- 
Regards,
Phil

From __peter__ at web.de  Fri Apr  7 04:01:21 2017
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Apr 2017 10:01:21 +0200
Subject: [Tutor] Tkinter grid question
References: <20170407120949.184fd6b9@raspberrypi>
Message-ID: <oc7h0e$an3$1@blaine.gmane.org>

Phil wrote:

> Thank you for reading this.
> 
> This is my first attempt at using Tkinter and I've quickly run into a
> problem.
> 
> If e is a one dimensional list then all is OK and I can delete and insert
> entries. The problem comes about when the list is made two dimensional, as
> follows:
> 
> from tkinter import *
> 
> master = Tk()
> 
> e = [None] * 6 , [None] * 2

In the above line you are creating a 2-tuple consisting of two lists:

>>> [None]*6, [None]*2
([None, None, None, None, None, None], [None, None])

What you want is a list of lists
[
[None, None],
[None, None],
...
]

You can create such a list with

>>> [[None] * 2 for _ in range(6)]
[[None, None], [None, None], [None, None], [None, None], [None, None], 
[None, None]]

> 
> for i in range(6):
>     for j in range(2):
>         e[i][j] = Entry(master, width=5)
>         e[i][j].grid(row=i, column=j)
>         e[i][j].insert(0,"6")
> 
> mainloop( )
> 
> Traceback (most recent call last):
>   File "/home/pi/tkinter_example.py", line 50, in <module>
>     e[i][j] = Entry(master, width=5)
> IndexError: tuple index out of range
> 
> I can see that the problem occurs when i is greater than 1 which makes me
> think that my method of attempting to create a two denominational array of
> edit boxes is wrong.
> 
> I've search for an example but haven't turned up anything. Where had I
> failed?
 
As shown above this has nothing to do with tkinter. Personally I would 
create the list of list dynamically

entries = []
for row in range(6):
    entries_row = []
    entries.append(entries_row)
    for column in range(2):
        entry = Entry(master, width=5)
        entry.grid(row=row, column=column)
        entry.insert(0,"6")
        entries_row.append(entry)

or even use a dict with (row, column) keys:

def make_entry(row, column):
    entry = Entry(master, width=5)
    entry.grid(row=row, column=column)
    entry.insert(0,"6")
    return entry

master = Tk()

entries = {
    (r, c): make_entry(r, c)
    for r in range(6) for c in range(2)
}




From alan.gauld at yahoo.co.uk  Fri Apr  7 05:00:24 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 7 Apr 2017 10:00:24 +0100
Subject: [Tutor] Network Sniffing on Windows with Python 3.6
In-Reply-To: <9a6863d4-0bb6-18d3-680d-ee4c3c181e53@googlemail.com>
References: <9a6863d4-0bb6-18d3-680d-ee4c3c181e53@googlemail.com>
Message-ID: <oc7kf2$ask$1@blaine.gmane.org>

On 07/04/17 06:07, Some Developer wrote:

> How would I go about writing a Python 3.6 script for Windows that would 
> sniff the network traffic and take the individual packets and then 
> reassemble them into something that is useful data?

That is definitely possible using Python although it is fairly advanced
networking code. Certainly further than I've ever gone using Python.

> I was thinking of installing Wireshark to have a look at the network 
> communications but I wasn't really sure what I would do with the data. 
> Are there any library functions in Python 3.6 that would help with this 
> task?

For sure, but I'd definitely install wireshark, if nothing else
its likely to be near essential in debugging your code.

> Also does the Python script require admin permissions for this to work 
> or can it run as a normal user? It doesn't matter if it does require 
> admin permissions but it would be better for my users if it didn't 
> require admin permissions.

That's more likely to be a feature of the OS and who is running the
code producing the data. Unless everything is running as your
user account I'd suspect admin privileges will be necessary
 - in fact I'd hope so!
> there are any books on the subject that would be even better as I like 
> reading books on programming subjects.

My two main sources for Python networking are:

Python Network Programming by Goerzen, published by APress
This is a great intro to the general theory of network programming
as well as the Python specifics. If you are already familiar with
networking through say, the classic Stephens books on C networking, then
this will be familiar ground. Its good if you want to
understand what you are doing rather than just copy somebody
else's code.

Programming Python 4th edition.
A monster book (1600 pages?) with about 500 pages dedicated to
networking. It's a book within a book! A bjt less background theory,
more code. If you like books this is a great value buy since it
also covers GUI/Tkinter(400 pages) and  Systems programming
(200 pages) as well as miscellaneous other topics.

-- 
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 Apr  7 05:08:40 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 7 Apr 2017 10:08:40 +0100
Subject: [Tutor] Tkinter grid question
In-Reply-To: <20170407120949.184fd6b9@raspberrypi>
References: <20170407120949.184fd6b9@raspberrypi>
Message-ID: <oc7kui$8hi$1@blaine.gmane.org>

On 07/04/17 03:09, Phil wrote:
> Thank you for reading this.
> 
> This is my first attempt at using Tkinter and I've quickly run into a problem.
> 

Peter has already answered the problem but I'd like
to point out how he used the interactive prompt >>> to
demonstrate what was going wrong. You should get into
the habit of always having an interactive shell running
while you code, then you can instantly answer questions
like this by copying code from your script into the shell
and seeing the output.

The shell is a vastly underused piece of pythons
programming environment, its not just for beginners
to learn on, it can greatly speed up your coding workflow.

Anytime you wonder what a particular method does,
or what a data structure looks like, just type it
into the shell and find out. No more guessing.

-- 
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 Apr  7 04:28:59 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Fri, 7 Apr 2017 08:28:59 +0000 (UTC)
Subject: [Tutor] [Python 3.5] TypeError: a bytes-like object is required,
 not 'str' PICKLE
References: <1055293161.3004301.1491553739896.ref@mail.yahoo.com>
Message-ID: <1055293161.3004301.1491553739896@mail.yahoo.com>

Hi
I have added b so that it translates into bytes object. save_cPickle part is not problem...
But i still get an error when coming into load_cPickle for this function: 
Dataset.save_part_features('categorical_counts', Dataset.get_part_features('categorical'))
although i have defined b in save_cPickle

THE CODE:
import _pickle as cPickle
def save_cPickle(filename, data):
    with open(filename, 'wb') as f:
        cPickle.dump(data, f)


def load_cPickle(filename):
    with open(filename) as f:

        return cPickle.load(f)

class Dataset(object): 

    part_types = { 
    'id': 'd1', 
    'loss': 'd1',
    }
    parts = part_types.keys() 

    @classmethod 
    def save_part_features(cls, part_name, features): 
    save_cPickle('%s/%s-features.pickle' % (cache_dir, part_name), features) 

    @classmethod 
    def get_part_features(cls, part_name): 
    return load_cPickle('%s/%s-features.pickle' % (cache_dir, part_name))

Dataset.save_part_features('categorical_counts', Dataset.get_part_features('categorical'))
Dataset(categorical_counts=train_cat_counts).save('train')

From george at fischhof.hu  Fri Apr  7 03:51:11 2017
From: george at fischhof.hu (George Fischhof)
Date: Fri, 7 Apr 2017 09:51:11 +0200
Subject: [Tutor] Network Sniffing on Windows with Python 3.6
In-Reply-To: <9a6863d4-0bb6-18d3-680d-ee4c3c181e53@googlemail.com>
References: <9a6863d4-0bb6-18d3-680d-ee4c3c181e53@googlemail.com>
Message-ID: <CAFwcP0i3jGgG-P2fayGUZiWuLq==bG3cDz80HbRJkpmO+hPgNg@mail.gmail.com>

2017-04-07 7:07 GMT+02:00 Some Developer <someukdeveloper at gmail.com>:

> Hi,
>
> This is more a query about where to look for information rather than
> asking for specific code.
>
> There is a game that passes data over the network and I want to sniff the
> network protocol used by the game to pass data between the client and the
> server (before anyone asks no I am not cheating it is an MMO and I want to
> create a database site that holds information on all the items and quests
> in the game etc).
>
> How would I go about writing a Python 3.6 script for Windows that would
> sniff the network traffic and take the individual packets and then
> reassemble them into something that is useful data? I've never done
> something like this before.
>
> I was thinking of installing Wireshark to have a look at the network
> communications but I wasn't really sure what I would do with the data. Are
> there any library functions in Python 3.6 that would help with this task?
>
> Basically I need to lock onto the games process and sniff any incomming or
> outgoing network traffic from that process. Is that possible?
>
> Also does the Python script require admin permissions for this to work or
> can it run as a normal user? It doesn't matter if it does require admin
> permissions but it would be better for my users if it didn't require admin
> permissions.
>
> I'm just looking for some help to push me in the right direction. If there
> are any books on the subject that would be even better as I like reading
> books on programming subjects.
>
> Thanks for any help :).
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



Hi,

some days ago I started to investigate similar problem (check traffic) and
I found the following libraries (maybe it helps You):

https://pypi.python.org/pypi/pyshark_parser/0.1

https://pypi.python.org/pypi/pyshark/0.3.6.2

https://www.wireshark.org/docs/man-pages/tshark.html

BR,
George

From phil_lor at bigpond.com  Fri Apr  7 06:08:44 2017
From: phil_lor at bigpond.com (Phil)
Date: Fri, 7 Apr 2017 20:08:44 +1000
Subject: [Tutor] Tkinter grid question
In-Reply-To: <oc7kui$8hi$1@blaine.gmane.org>
References: <20170407120949.184fd6b9@raspberrypi>
 <oc7kui$8hi$1@blaine.gmane.org>
Message-ID: <20170407200844.0e9948cd@raspberrypi>

On Fri, 7 Apr 2017 10:08:40 +0100
Alan Gauld via Tutor <tutor at python.org> wrote:

> Peter has already answered the problem but I'd like
> to point out how he used the interactive prompt >>> to
> demonstrate what was going wrong.

Thank you Alan. The >>> prompt, print() and Duckduckgo do get a good workout. In this case I become confused because had expected [][] to be the same as a C two dimensional array.

-- 
Regards,
Phil

From __peter__ at web.de  Fri Apr  7 06:28:21 2017
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Apr 2017 12:28:21 +0200
Subject: [Tutor] [Python 3.5] TypeError: a bytes-like object is required,
 not 'str' PICKLE
References: <1055293161.3004301.1491553739896.ref@mail.yahoo.com>
 <1055293161.3004301.1491553739896@mail.yahoo.com>
Message-ID: <oc7pjv$66m$1@blaine.gmane.org>

Allan Tanaka via Tutor wrote:

> Hi
> I have added b so that it translates into bytes object. save_cPickle part
> is not problem... But i still get an error when coming into load_cPickle
> for this function: Dataset.save_part_features('categorical_counts',
> Dataset.get_part_features('categorical')) although i have defined b in
> save_cPickle
> 
> THE CODE:

> import _pickle as cPickle

Why not just

import pickle

?

> def load_cPickle(filename):
>     with open(filename) as f:
> 
>         return cPickle.load(f)

I've no idea what your code is supposed to do, and my attempt to run it 
didn't get this far -- but you have to open the file in binary mode

with open(filename, "rb") as f: ...

to load the pickled data.


From phil_lor at bigpond.com  Fri Apr  7 04:33:31 2017
From: phil_lor at bigpond.com (Phil)
Date: Fri, 7 Apr 2017 18:33:31 +1000
Subject: [Tutor] Tkinter grid question
In-Reply-To: <oc7h0e$an3$1@blaine.gmane.org>
References: <20170407120949.184fd6b9@raspberrypi>
 <oc7h0e$an3$1@blaine.gmane.org>
Message-ID: <20170407183331.673257a6@raspberrypi>

On Fri, 07 Apr 2017 10:01:21 +0200
Peter Otten <__peter__ at web.de> wrote:

> > e = [None] * 6 , [None] * 2
> 
> In the above line you are creating a 2-tuple consisting of two lists:
> 
> >>> [None]*6, [None]*2
> ([None, None, None, None, None, None], [None, None])
> 
> What you want is a list of lists
> [
> [None, None],
> [None, None],
> ...
> ]
> 
> You can create such a list with
> 
> >>> [[None] * 2 for _ in range(6)]
> [[None, None], [None, None], [None, None], [None, None], [None,
> None], [None, None]]
> 

Thank you Peter, that makes sense.

What I'm trying to do is convert a sudoku solver that I wrote using C++ and the QT library in 2005. As well as coming to grips with Tkinter I'm having trouble following my C++ code.

-- 
Regards,
Phil

From alan.gauld at yahoo.co.uk  Fri Apr  7 07:38:55 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 7 Apr 2017 12:38:55 +0100
Subject: [Tutor] Tkinter grid question
In-Reply-To: <20170407200844.0e9948cd@raspberrypi>
References: <20170407120949.184fd6b9@raspberrypi>
 <oc7kui$8hi$1@blaine.gmane.org> <20170407200844.0e9948cd@raspberrypi>
Message-ID: <oc7to8$7nu$1@blaine.gmane.org>

On 07/04/17 11:08, Phil wrote:
> ...In this case I become confused because had expected [][] 
> to be the same as a C two dimensional array.

It is, sort of.
If you set the data up correctly to start with :-)

-- 
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 Apr  7 07:45:11 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 7 Apr 2017 12:45:11 +0100
Subject: [Tutor] [Python 3.5] TypeError: a bytes-like object is required,
 not 'str' PICKLE
In-Reply-To: <1055293161.3004301.1491553739896@mail.yahoo.com>
References: <1055293161.3004301.1491553739896.ref@mail.yahoo.com>
 <1055293161.3004301.1491553739896@mail.yahoo.com>
Message-ID: <oc7u41$6e5$1@blaine.gmane.org>

Please always send the full error trace not just the last line. The
message is full of useful details which we can't currently see.



On 07/04/17 09:28, Allan Tanaka via Tutor wrote:
> Hi
> I have added b so that it translates into bytes object. save_cPickle part is not problem...
> But i still get an error when coming into load_cPickle for this function: 
> Dataset.save_part_features('categorical_counts', Dataset.get_part_features('categorical'))
> although i have defined b in save_cPickle
> 
> THE CODE:
> import _pickle as cPickle
> def save_cPickle(filename, data):
>     with open(filename, 'wb') as f:
>         cPickle.dump(data, f)
> 
> 
> def load_cPickle(filename):
>     with open(filename) as f:
> 
>         return cPickle.load(f)
> 
> class Dataset(object): 
> 
>     part_types = { 
>     'id': 'd1', 
>     'loss': 'd1',
>     }
>     parts = part_types.keys() 
> 
>     @classmethod 
>     def save_part_features(cls, part_name, features): 
>     save_cPickle('%s/%s-features.pickle' % (cache_dir, part_name), features) 
> 
>     @classmethod 
>     def get_part_features(cls, part_name): 
>     return load_cPickle('%s/%s-features.pickle' % (cache_dir, part_name))

Does the class add anything here given it only has two class
attributes and two class methods? If you aren't going to create
instances then a simple module level function is probably as useful.

> Dataset.save_part_features('categorical_counts', Dataset.get_part_features('categorical'))
> Dataset(categorical_counts=train_cat_counts).save('train')

This tries to create an instance of Dataset but there is no matching
init() method...nor is there a save() 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 tianjiaocui721 at gmail.com  Fri Apr  7 18:01:17 2017
From: tianjiaocui721 at gmail.com (Tianjiao Cui)
Date: Fri, 7 Apr 2017 15:01:17 -0700
Subject: [Tutor] want to set IDLE setting to default.
Message-ID: <CADcPsEd+X1JQsCTt5z0EOQph_qVLZkHXWzGhLJTAOdfkm=Uhww@mail.gmail.com>

Hi, all. I have met a very annoying issue that i messed up with IDlL
configuration. I changed "run" key in settings but i found it does not work
and then i tried to reset it to default but i failed. Pls help me get rid
of this problem because it has been bothering me for a while.
Thanks.
Chris

From alan.gauld at yahoo.co.uk  Fri Apr  7 19:20:47 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 8 Apr 2017 00:20:47 +0100
Subject: [Tutor] want to set IDLE setting to default.
In-Reply-To: <CADcPsEd+X1JQsCTt5z0EOQph_qVLZkHXWzGhLJTAOdfkm=Uhww@mail.gmail.com>
References: <CADcPsEd+X1JQsCTt5z0EOQph_qVLZkHXWzGhLJTAOdfkm=Uhww@mail.gmail.com>
Message-ID: <oc96s9$4bu$1@blaine.gmane.org>

On 07/04/17 23:01, Tianjiao Cui wrote:
> Hi, all. I have met a very annoying issue that i messed up with IDlL
> configuration. I changed "run" key in settings but i found it does not work
> and then i tried to reset it to default but i failed. 

You need to give us more detailed descriptions of what you did.
How did you change it in settings - did you change the overall key
definitions to a different standard set? Did you create a bespoke key
set? Did you edit the settings file directly or use the dialog?

And how did you change it back?
And what does "not work" mean? What happened, if anything?

I'd try first of all loading a standard key set like
"Classic windows" and se if those settings work.

Finally, there is a dedicated IDLE mailing list which is
quite helpful, so you should probably try asking there too.
Its on Gmane at:

gmane.comp.python.idle


-- 
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  Fri Apr  7 12:00:38 2017
From: phil_lor at bigpond.com (Phil)
Date: Sat, 8 Apr 2017 02:00:38 +1000
Subject: [Tutor] Tkinter class question
Message-ID: <20170408020038.5acdb8a2@raspberrypi>

Thank you for reading this.

I've progressed a little further but I'm now having a problem knowing when to use the "self" reference. In the following code, the function "ckeck" is called without the need to press the "check" button. This didn't occur before I sprinkled "selfs" into the code and added "array" to the "ckeck" function. I found that I needed "self" to point "array" to my list array "e" and I think that is where the fault is. 

from tkinter import *

class TestGUI:
    def __init__(self, master):
        self.master = master
        master.title("Testing")

        num_rows = 6
        num_cols = 3

        self.e = [[None] * num_cols for _ in range(num_rows)]

        for i in range(num_rows):
            for j in range(num_cols):
                self.e[i][j] = Entry(master, width=4, justify=CENTER, foreground="gray")
                self.e[i][j].grid(row=i, column=j)
                self.e[i][j].insert(0,"6")

        self.check_button = Button(master, text="Check", command=self.check(self.e))
        self.check_button.grid(row=7, column=7)
        
    def check(self, array):
        print("checked")
        array[2][2].insert(0, "4")
        
root = Tk()
my_gui = TestGUI(root)
root.mainloop()


-- 
Regards,
Phil

From phil_lor at bigpond.com  Fri Apr  7 14:13:03 2017
From: phil_lor at bigpond.com (Phil)
Date: Sat, 8 Apr 2017 04:13:03 +1000
Subject: [Tutor] Tkinter class question - refinement
In-Reply-To: <20170408020038.5acdb8a2@raspberrypi>
References: <20170408020038.5acdb8a2@raspberrypi>
Message-ID: <20170408041303.1c5db81b@raspberrypi>

On Sat, 8 Apr 2017 02:00:38 +1000
Phil <phil_lor at bigpond.com> wrote:

If I define "e" lists before the class then everything works as I had expected, however, I don't that's technically correct. Or is it?

-- 
Regards,
Phil

From __peter__ at web.de  Sat Apr  8 03:12:17 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 08 Apr 2017 09:12:17 +0200
Subject: [Tutor] Tkinter class question
References: <20170408020038.5acdb8a2@raspberrypi>
Message-ID: <oca2ge$ire$1@blaine.gmane.org>

Phil wrote:

> I've progressed a little further but I'm now having a problem knowing when
> to use the "self" reference. In the following code, the function "ckeck"
> is called without the need to press the "check" button. This didn't occur
> before I sprinkled "selfs" into the code and added "array" to the "ckeck"
> function. I found that I needed "self" to point "array" to my list array
> "e" and I think that is where the fault is.
> 
> from tkinter import *
> 
> class TestGUI:
>     def __init__(self, master):
<...>

>         self.check_button = Button(master, text="Check",
>         command=self.check(self.e))

Think hard about what the expression

command=self.check(self.e)

does. Spoiler:

The check() method is invoked, and the result is passed as the command 
argument. But what is that result?

>     def check(self, array):
>         print("checked")
>         array[2][2].insert(0, "4")

No explicit return means the return value is None. Your above code is 
equivalent to

# print "checked" and insert "4"
self.check(self.e)
# create a button with no command
self.check_button = Button(master, text="Check", command=None)

To set a command you must define a function or method that takes no 
arguments:

class TestGUI:
    def check_2_2(self):
        print("checked"
        self.e[2][2].insert(0, "4")

    def __init__(self, master):
        ...
        self.check_button = Button(
            master,
            text="Check",
            command=self.check_2_2  # note there's no () -- the bound method
                                    # is not invoked
        )
        ...


> root = Tk()
> my_gui = TestGUI(root)
> root.mainloop()

If there are a lot of similar commands the command is often constructed by 
wrapping a method in a lambda with default arguments. Simple example:

import tkinter as tk

class TestGUI:
    def __init__(self, master):
        for i in range(5):
            button = tk.Button(
                master, 
                text="Button {}".format(i),
                command=lambda n=i: self.button_pressed(n)
            )
            button.grid(row=i, column=0)

    def button_pressed(self, n):
        print("You pressed button {}".format(n))

root = tk.Tk()
test = TestGUI(root)
root.mainloop()

There's also functools.partial() which can be used to the same effect

command=functools.partial(self.button_pressed, i)


From alan.gauld at yahoo.co.uk  Sat Apr  8 03:57:10 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 8 Apr 2017 08:57:10 +0100
Subject: [Tutor] Tkinter class question
In-Reply-To: <20170408020038.5acdb8a2@raspberrypi>
References: <20170408020038.5acdb8a2@raspberrypi>
Message-ID: <oca54g$knq$1@blaine.gmane.org>

On 07/04/17 17:00, Phil wrote:

> ...I'm now having a problem knowing when to use the "self" reference.

self is needed every time you use an instance attribute or method.
It is equivalent to 'this' in C++(or Java), but in Python it is
never implicit you always have to explicitly specify self when accessing
a member of the class.

>  ...the function "ckeck" is called without the need to press 

Peter has addressed this.

-- 
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  Fri Apr  7 15:21:07 2017
From: phil_lor at bigpond.com (Phil)
Date: Sat, 8 Apr 2017 05:21:07 +1000
Subject: [Tutor] Tkinter class question - solved
In-Reply-To: <20170408020038.5acdb8a2@raspberrypi>
References: <20170408020038.5acdb8a2@raspberrypi>
Message-ID: <20170408052107.142314e2@raspberrypi>

On Sat, 8 Apr 2017 02:00:38 +1000

This is one of those times where I wish I could delete a sent message.

After a bit more thought I now realise that I just need to use self to reference e[][] in my check function.

-- 
Regards,
Phil

From phil_lor at bigpond.com  Fri Apr  7 18:24:00 2017
From: phil_lor at bigpond.com (Phil)
Date: Sat, 8 Apr 2017 08:24:00 +1000
Subject: [Tutor] Tkinter class question
In-Reply-To: <oca2ge$ire$1@blaine.gmane.org>
References: <20170408020038.5acdb8a2@raspberrypi>
 <oca2ge$ire$1@blaine.gmane.org>
Message-ID: <20170408082400.6a04eea2@raspberrypi>

On Sat, 08 Apr 2017 09:12:17 +0200
Peter Otten <__peter__ at web.de> wrote:

Thank you yet again Peter.

I realised what the answer is after taking a break for a couple of hours, however, I didn't know about:

>         ...
>         self.check_button = Button(
>             master,
>             text="Check",
>             command=self.check_2_2  # note there's no () -- the bound
> method # is not invoked
>         )
>         ...
> 

My working method uses the () but I will remove them and see what difference it makes.

-- 
Regards,
Phil

From __peter__ at web.de  Sat Apr  8 06:07:51 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 08 Apr 2017 12:07:51 +0200
Subject: [Tutor] Tkinter class question - solved
References: <20170408020038.5acdb8a2@raspberrypi>
 <20170408052107.142314e2@raspberrypi>
Message-ID: <ocacph$vh6$1@blaine.gmane.org>

Phil wrote:

> On Sat, 8 Apr 2017 02:00:38 +1000
> 
> This is one of those times where I wish I could delete a sent message.
> 
> After a bit more thought I now realise that I just need to use self to
> reference e[][] in my check function.

Relax ;) We all had to go through a learning process. 



From __peter__ at web.de  Sat Apr  8 06:16:05 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 08 Apr 2017 12:16:05 +0200
Subject: [Tutor] Tkinter class question
References: <20170408020038.5acdb8a2@raspberrypi>
 <oca2ge$ire$1@blaine.gmane.org> <20170408082400.6a04eea2@raspberrypi>
Message-ID: <ocad92$ats$1@blaine.gmane.org>

Phil wrote:

> On Sat, 08 Apr 2017 09:12:17 +0200
> Peter Otten <__peter__ at web.de> wrote:
> 
> Thank you yet again Peter.
> 
> I realised what the answer is after taking a break for a couple of hours,
> however, I didn't know about:
> 
>>         ...
>>         self.check_button = Button(
>>             master,
>>             text="Check",
>>             command=self.check_2_2  # note there's no () -- the bound
>> method # is not invoked
>>         )
>>         ...
>> 
> 
> My working method uses the () 

This is unlikely unless you have found out about factory methods (functions 
that return functions).

> but I will remove them and see what
> difference it makes.

Make sure you understand the difference between calling a function and 
passing around a function as a value.

def f(): return 42

a = f
b = f()

You have understood the difference if you can predict the outcome of 
all four lines below:

print(a)
print(b)
print(a())
print(b())

Once you think you know the answer try it in the interactive interpreter.


From alan.gauld at yahoo.co.uk  Sat Apr  8 07:16:11 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 8 Apr 2017 12:16:11 +0100
Subject: [Tutor] Tkinter class question - solved
In-Reply-To: <20170408052107.142314e2@raspberrypi>
References: <20170408020038.5acdb8a2@raspberrypi>
 <20170408052107.142314e2@raspberrypi>
Message-ID: <ocagpk$i03$1@blaine.gmane.org>

On 07/04/17 20:21, Phil wrote:

> After a bit more thought I now realise that I just 
> need to use self to reference e[][] in my check function.

You need to use self any time you access any member of your
class. So in your case:

class TestGUI:
    def __init__(self, master):
        self.master = master
...
        self.e = [[None] * num_cols for _ in range(num_rows)]
...
        self.check_button = Button(master,text="Check",
                                   command=self.check)
...

    def check(self,array): ...

The following attributes all need to be prefixed with self
any time you access them:

self.master
self.e
self.check_button
self.check

In this specific case you only need to use self.e

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 __peter__ at web.de  Sat Apr  8 08:04:41 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 08 Apr 2017 14:04:41 +0200
Subject: [Tutor] want to set IDLE setting to default.
References: <CADcPsEd+X1JQsCTt5z0EOQph_qVLZkHXWzGhLJTAOdfkm=Uhww@mail.gmail.com>
Message-ID: <ocajki$qqe$1@blaine.gmane.org>

Tianjiao Cui wrote:

> Hi, all. I have met a very annoying issue that i messed up with IDlL
> configuration. I changed "run" key in settings but i found it does not
> work and then i tried to reset it to default but i failed. Pls help me get
> rid of this problem because it has been bothering me for a while.
> Thanks.

If things are seriously messed up you can close idle, rename the 
configuration directory ~/.idlerc (the ~ is the placeholder for your user 
directory) and then start idle again. This should create a new ~/.idlerc 
directory with all defaults restored.

If everything works to your satisfaction you can delete the renamed 
directory.


From rafael.knuth at gmail.com  Sat Apr  8 08:49:41 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Sat, 8 Apr 2017 14:49:41 +0200
Subject: [Tutor] Count for loops
In-Reply-To: <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
Message-ID: <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>

Dear Sama,

thank you so much for your explanation and sorry to bother you on the
same subject again.
I learn the most by taking code apart line by line, putting it
together, taking apart again, modifying it slightly ... which is
exactly what I did with your code.

On Tue, Apr 4, 2017 at 3:20 PM, D.V.N.Sarma ??.??.???.????
<dvnsarma at gmail.com> wrote:
> b = "3"+b[2:]  #Removing the decimal point so that there are digits only in

my_number = 3.14159
my_number = "3"+my_number[2:]
print(my_number)

This is the error code I got:

== RESTART: C:/Users/Rafael/Documents/01 - BIZ/CODING/Python Code/PPC_56.py ==
Traceback (most recent call last):
  File "C:/Users/Rafael/Documents/01 - BIZ/CODING/Python
Code/PPC_56.py", line 2, in <module>
    my_number = "1"+my_number[2:]
TypeError: 'float' object is not subscriptable
>>>

I am really trying to understand how to modify strings, floats and
variables from different sources.
In case of a text file, your code works, but if I apply the same to a
float assigned to a variable, it does not work.
What am I doing wrong here? Thank you so much for your patience.



> the file
> n = len(b)
> for i in range(n-3):
>     if b[i:i+4] == get_year:  # Taking 4 digit long chunks from successive
> positions in b and seeing whether they are equal to get_year
>         count += 1  # If they are equal increase the count by 1
>
> regards,
> Sarma.

From alan.gauld at yahoo.co.uk  Sat Apr  8 14:38:14 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 8 Apr 2017 19:38:14 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
Message-ID: <ocbamf$miv$1@blaine.gmane.org>

On 08/04/17 13:49, Rafael Knuth wrote:

>> b = "3"+b[2:]  #Removing the decimal point so that there are digits only in
> 
> my_number = 3.14159

Here you assign a floating point number to mmy_number but
the code Sama wrote was for working with strings read
from a text file.

You would need to convert it first:

my_number = str(3.14159)

> my_number = "3"+my_number[2:]
> print(my_number)
> 
> This is the error code I got:
> 
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/CODING/Python Code/PPC_56.py ==
> Traceback (most recent call last):
>   File "C:/Users/Rafael/Documents/01 - BIZ/CODING/Python
> Code/PPC_56.py", line 2, in <module>
>     my_number = "1"+my_number[2:]
> TypeError: 'float' object is not subscriptable

And that is what the error tells you, that you are trying
to index a float but it should be a string.

> In case of a text file, your code works, but if I apply the same to a
> float assigned to a variable, it does not work.

That's right, the set of operations applicable to numbers is
completely different to those applicable to strings, you cannot
mix 'n match. You need to convert between the types.

-- 
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  Sat Apr  8 20:12:20 2017
From: akleider at sonic.net (Alex Kleider)
Date: Sat, 08 Apr 2017 17:12:20 -0700
Subject: [Tutor] Count for loops
In-Reply-To: <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
Message-ID: <815e24d9ffb533ea38dbeb7516c719c4@sonic.net>

On 2017-04-08 05:49, Rafael Knuth wrote:
> Dear Sama,
> 
> thank you so much for your explanation and sorry to bother you on the
> same subject again.
> I learn the most by taking code apart line by line, putting it
> together, taking apart again, modifying it slightly ... which is
> exactly what I did with your code.
> 
> On Tue, Apr 4, 2017 at 3:20 PM, D.V.N.Sarma ??.??.???.????
> <dvnsarma at gmail.com> wrote:
>> b = "3"+b[2:]  #Removing the decimal point so that there are digits 
>> only in
> 
> my_number = 3.14159
> my_number = "3"+my_number[2:]
> print(my_number)
> 
> This is the error code I got:
> 
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/CODING/Python 
> Code/PPC_56.py ==
> Traceback (most recent call last):
>   File "C:/Users/Rafael/Documents/01 - BIZ/CODING/Python
> Code/PPC_56.py", line 2, in <module>
>     my_number = "1"+my_number[2:]
> TypeError: 'float' object is not subscriptable
>>>> 
> 
> I am really trying to understand how to modify strings, floats and
> variables from different sources.
> In case of a text file, your code works, but if I apply the same to a
> float assigned to a variable, it does not work.
> What am I doing wrong here? Thank you so much for your patience.

The error message is telling you exactly what is wrong:
"not subscriptable"
You've tried to use string functionality on a float.
Specifically: my_number is a float.
"""my_number[2:]""" would only make sense to the interpreter if 
it("my_number", not the interpretery:-) were a string (or some other 
sequence.)
try changing your code to:
   my_number_as_a_string = "3.14159"
   my_new_number_still_a_string = "3" + my_number_as_a_string[2:]  # 
spaces added for clarity
   print(my_new_number_still_a_string)
   my_float = float(my_new_number_still_a_string)
   print(my_float)
HTH
ps warning: not tested

From robertvstepp at gmail.com  Sat Apr  8 23:00:21 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 8 Apr 2017 22:00:21 -0500
Subject: [Tutor] What would be good use cases for the enum module?
Message-ID: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>

After reading some discussion on the Python main list about the enum
module and some suggested changes, I thought I would read the docs on
it at
https://docs.python.org/3/library/enum.html?highlight=enum#module-enum

Most of the mechanics of using it, Enum in particular, seem
understandable to me, but I am having difficulty imagining where I
might want to use these features.

I did some searching and read the first few results, mostly from Stack
Overflow.  So far only a couple of situations occur to me:

1)  Seems I could have a Constants class, like:

class Constants(Enum):
    PI = 3.1415
    E = 2.718
    etc.

2)  Or if I had a GUI, I could give names to things like radio
buttons, checklist boxes, etc., though I don't see why I would not
just use the normal indices (Which start from the usual zero, unlike
how the examples seem to be written in the enum docs.).

And I am having an even harder time imagining what I would want to use
Enum for if I don't care about the values assigned to the names and
use auto to automatically assign values.  I am having a real crisis of
imagination here!  Anyone with some commonplace and practical
applications of the enum module?

TIA!

-- 
boB

From steve at pearwood.info  Sun Apr  9 00:13:24 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 9 Apr 2017 14:13:24 +1000
Subject: [Tutor] What would be good use cases for the enum module?
In-Reply-To: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
References: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
Message-ID: <20170409041323.GU9464@ando.pearwood.info>

On Sat, Apr 08, 2017 at 10:00:21PM -0500, boB Stepp wrote:
> After reading some discussion on the Python main list about the enum
> module and some suggested changes, I thought I would read the docs on
> it at
> https://docs.python.org/3/library/enum.html?highlight=enum#module-enum
[...]
> And I am having an even harder time imagining what I would want to use
> Enum for if I don't care about the values assigned to the names and
> use auto to automatically assign values.  I am having a real crisis of
> imagination here!  Anyone with some commonplace and practical
> applications of the enum module?

Have you read the PEP for the enum module? There's also an earlier, 
rejected PEP:

https://www.python.org/dev/peps/pep-0354/

https://www.python.org/dev/peps/pep-0435/

There are a few uses for enums where they have to behave like ints for 
compatibility with code following C conventions, but basically an enum 
is an abstract symbol with a pretty representation to make debugging 
easier.

For example, suppose I have a function that justifies a paragraph of 
text:

def justify(paragraph, where):
    ...

where the `where` argument specifies whether to justify the text on the 
left, on the right, in the centre, or fully justified on both sides. One 
way to specify that is to use numeric constants:

if where == 1:
    # justify on the left
elif where == 2:
    # justify on the right
elif where == 3:
    # justify in the centre
elif where == 4:
    # fully justify at both ends

but there's no connection between the numbers I choose and the type of 
justification. I could just have sensibly used -3, 87, 4 and 32.5 as 1, 
2, 3 and 4.

A bit better is to use strings:

if where == 'LEFT':
    # justify on the left
elif where == 'RIGHT':
    # etc

which at least now is self-documenting, but it suggests that the `where` 
argument might take any string at all, which is not correct. There are 
only four fixed values it can take. And besides, having to use the 
quotation marks is tiresome.

So let's invent four (or even five, for Americans) named constants:

LEFT = 'LEFT'
RIGHT = 'RIGHT'
CENTRE = CENTER = 'CENTRE'
FULL = 'FULLY JUSTIFIED'


Now we're getting closer. The caller can say:

text = justify(some_text, CENTRE)

which is nice, and the justify() function can include:

if where == LEFT:
    ...

without quotation marks, which is also nice. That solves about 95% of 
the problem.

The last niggly 5% is a subtle thing. Because the constants are strings, 
we might be tempted to do string things to them, either deliberately or 
by mistake:


justification_mode = CENTRE.lower() + LEFT[1:]  # Oops!
# much later
justify(some_text, justification_mode)


which of course will fail, but it will fail *when the string is used*, 
not when you do the string-stuff to those constants. It would be nice if 
it failed straight away, at the "justification_mode" line.

To fix that, we need something which looks like a string when you print 
it, for debugging, but actually isn't a string, so it doesn't accept all 
the usual string methods. That's effectively just an abstract symbol, 
and the way to get this in Python is with an enum.

Enums have a few other nice properties, which you may or may not care 
about, but the primary use is to act as set of related named symbols.



-- 
Steve

From bfishbein79 at gmail.com  Sun Apr  9 03:23:24 2017
From: bfishbein79 at gmail.com (Benjamin Fishbein)
Date: Sun, 9 Apr 2017 02:23:24 -0500
Subject: [Tutor] downloading modules for both python 2 and 3
Message-ID: <76DEC9B2-5E45-4598-83A1-877D482D6D93@gmail.com>

I?ve been writing an app using Kivy, and now I want to test it out on an iPhone. However, this can currently only be done in Python 2.
https://kivy.org/docs/guide/packaging-ios.html <https://kivy.org/docs/guide/packaging-ios.html>
But when I import kivy in Python2, I get an ImportError.
ImportError: No module named kivy
So I need to install kivy for Python 2.
But when I do:
sudo pip install kivy
I get the following:
Requirement already satisfied: requests in ./anaconda/lib/python3.5/site-packages (from Kivy-Garden>=0.1.4->kivy) 

Do you know how I can convince my computer to download a module for Python 2 when I already have it for Python 3?


From alan.gauld at yahoo.co.uk  Sun Apr  9 03:54:53 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 9 Apr 2017 08:54:53 +0100
Subject: [Tutor] What would be good use cases for the enum module?
In-Reply-To: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
References: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
Message-ID: <occpc7$5ck$1@blaine.gmane.org>

On 09/04/17 04:00, boB Stepp wrote:

> understandable to me, but I am having difficulty imagining where I
> might want to use these features.
> 

Steven has given the basics, here are a few more real world examples:

Any kind of status value:
(open,closed,opening, closing,locked)  - control valve
(on, off) - light
(red,green,amber,red-amber) - uk traffic light

small collections:
days of week
months in year
(cleaning, reception, waiting, valet) - rota duties
(hourly,daily,weekly,monthly,annual) - schedules

Enums are very common in larger programs once you get
used to the concept. It's a bit like dictionaries: many
traditional programmers think of everything as arrays
and can't initially think of when they would use a dictionary
(arbitrary key rather than numeric index) But once you
get started you find dictionaries are at least as useful
as arrays..

And, surprise, surprise, there is a link. Very often
enums form the set of valid keys to a dictionary...

-- 
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  Sun Apr  9 04:20:06 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 09 Apr 2017 10:20:06 +0200
Subject: [Tutor] downloading modules for both python 2 and 3
References: <76DEC9B2-5E45-4598-83A1-877D482D6D93@gmail.com>
Message-ID: <occqrg$h8i$2@blaine.gmane.org>

Benjamin Fishbein wrote:

> I?ve been writing an app using Kivy, and now I want to test it out on an
> iPhone. However, this can currently only be done in Python 2.
> https://kivy.org/docs/guide/packaging-ios.html
> <https://kivy.org/docs/guide/packaging-ios.html> But when I import kivy in
> Python2, I get an ImportError. ImportError: No module named kivy So I need
> to install kivy for Python 2. But when I do:
> sudo pip install kivy
> I get the following:
> Requirement already satisfied: requests in
> ./anaconda/lib/python3.5/site-packages (from Kivy-Garden>=0.1.4->kivy)
> 
> Do you know how I can convince my computer to download a module for Python
> 2 when I already have it for Python 3?

On my (Linux) system there are multiple versions of pip, called pip2, pip3, 
pip3.7; you might look for those.

Or you try to pick the desired interpreter with

$ sudo /path/to/desired/python -m pip install kivy


From mats at wichmann.us  Sun Apr  9 08:58:02 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 9 Apr 2017 06:58:02 -0600
Subject: [Tutor] What would be good use cases for the enum module?
In-Reply-To: <occpc7$5ck$1@blaine.gmane.org>
References: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
 <occpc7$5ck$1@blaine.gmane.org>
Message-ID: <b0e65e39-74e4-fbf6-9cf5-66b6931035f9@wichmann.us>

On 04/09/2017 01:54 AM, Alan Gauld via Tutor wrote:
> On 09/04/17 04:00, boB Stepp wrote:
> 
>> understandable to me, but I am having difficulty imagining where I
>> might want to use these features.
>>
> 
> Steven has given the basics, here are a few more real world examples:
> 
> Any kind of status value:
> (open,closed,opening, closing,locked)  - control valve
> (on, off) - light
> (red,green,amber,red-amber) - uk traffic light
> 
> small collections:
> days of week
> months in year
> (cleaning, reception, waiting, valet) - rota duties
> (hourly,daily,weekly,monthly,annual) - schedules

All of these can of course be done without enums.  So the extra benefit
of an enum is that the set is closed (immutable) and requires
uniqueness: picking some other value will be an error, adding a new
enumerator with an already used value is an error.

Not sure if the question really way "what good are enums" or "what good
is the new Python enum module"... in looking that over there seems to be
a lot of stuff, almost seems unlike the Python project to add something
with so many options, that really doesn't have *huge* utility.



From mats at wichmann.us  Sun Apr  9 09:50:20 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 9 Apr 2017 07:50:20 -0600
Subject: [Tutor] downloading modules for both python 2 and 3
In-Reply-To: <occqrg$h8i$2@blaine.gmane.org>
References: <76DEC9B2-5E45-4598-83A1-877D482D6D93@gmail.com>
 <occqrg$h8i$2@blaine.gmane.org>
Message-ID: <73ed9aff-e9a4-7fde-ee07-aef41d56a110@wichmann.us>

On 04/09/2017 02:20 AM, Peter Otten wrote:
> Benjamin Fishbein wrote:
> 
>> I?ve been writing an app using Kivy, and now I want to test it out on an
>> iPhone. However, this can currently only be done in Python 2.
>> https://kivy.org/docs/guide/packaging-ios.html
>> <https://kivy.org/docs/guide/packaging-ios.html> But when I import kivy in
>> Python2, I get an ImportError. ImportError: No module named kivy So I need
>> to install kivy for Python 2. But when I do:
>> sudo pip install kivy
>> I get the following:
>> Requirement already satisfied: requests in
>> ./anaconda/lib/python3.5/site-packages (from Kivy-Garden>=0.1.4->kivy)
>>
>> Do you know how I can convince my computer to download a module for Python
>> 2 when I already have it for Python 3?
> 
> On my (Linux) system there are multiple versions of pip, called pip2, pip3, 
> pip3.7; you might look for those.
> 
> Or you try to pick the desired interpreter with
> 
> $ sudo /path/to/desired/python -m pip install kivy

I'd highly suggest building a virtualenv for work requiring a specific
project to be installed. When doing that, you can call out the Python
you want involved, something like this sequence I just ran:

$ virtualenv -p /usr/bin/python2 kivywork
Already using interpreter /usr/bin/python2
New python executable in /home/mats/kivywork/bin/python2
Also creating executable in /home/mats/kivywork/bin/python
Installing setuptools, pip, wheel...done.
$ cd kivywork/bin
$ source activate
(kivywork) $ pip install --upgrade pip
Requirement already up-to-date: pip in
/home/mats/kivywork/lib/python2.7/site-packages
(kivywork) $ pip install --upgrade setuptools
Requirement already up-to-date: setuptools in
/home/mats/kivywork/lib/python2.7/site-packages
Requirement already up-to-date: appdirs>=1.4.0 in
/home/mats/kivywork/lib/python2.7/site-packages (from setuptools)
Requirement already up-to-date: packaging>=16.8 in
/home/mats/kivywork/lib/python2.7/site-packages (from setuptools)
Requirement already up-to-date: six>=1.6.0 in
/home/mats/kivywork/lib/python2.7/site-packages (from setuptools)
Requirement already up-to-date: pyparsing in
/home/mats/kivywork/lib/python2.7/site-packages (from
packaging>=16.8->setuptools)
(kivywork) $ pip install kivy
Collecting kivy
  Downloading kivy-1.9.1.tar.gz (16.4MB)
    100% |????????????????????????????????| 16.4MB 91kB/s
    Complete output from command python setup.py egg_info:
    Using distutils

    Cython is missing, its required for compiling kivy !


    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-ZXsSua/kivy/setup.py", line 184, in <module>
        from Cython.Distutils import build_ext
    ImportError: No module named Cython.Distutils

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in
/tmp/pip-build-ZXsSua/kivy/
$


Well, you get the idea.  I couldn't finish the install for the reason
listed.  With a virtualenv you get a controlled environment specifically
for what you want to do; the "activate" step gets it going, and changes
your prompt to show you you're in that environment. Should you need to
clean up now, it's a snap - just remove the virtualenv directory; you
have not messed with your "system" python.



From skgoyal721 at gmail.com  Sun Apr  9 06:42:15 2017
From: skgoyal721 at gmail.com (shubham goyal)
Date: Sun, 9 Apr 2017 16:12:15 +0530
Subject: [Tutor] (no subject)
Message-ID: <CAN1d+19ZUW90NgB4jx6x507TxgjYr2Y2E-cnBWbS0M582S3FSA@mail.gmail.com>

Hello, I am a c++ programmer and wants to learn python for internship
purposes. How can i learn the advanced python fast mostly data science
packages, I know basic python.

From robertvstepp at gmail.com  Sun Apr  9 11:21:49 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 9 Apr 2017 10:21:49 -0500
Subject: [Tutor] What would be good use cases for the enum module?
In-Reply-To: <20170409041323.GU9464@ando.pearwood.info>
References: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
 <20170409041323.GU9464@ando.pearwood.info>
Message-ID: <CANDiX9+hOB5pghK3koPZYMtOUwQR08YbJFWobEReDGx3AQ8OEQ@mail.gmail.com>

On Sat, Apr 8, 2017 at 11:13 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Apr 08, 2017 at 10:00:21PM -0500, boB Stepp wrote:
>> After reading some discussion on the Python main list about the enum
>> module and some suggested changes, I thought I would read the docs on
>> it at
>> https://docs.python.org/3/library/enum.html?highlight=enum#module-enum
> [...]
>> And I am having an even harder time imagining what I would want to use
>> Enum for if I don't care about the values assigned to the names and
>> use auto to automatically assign values.  I am having a real crisis of
>> imagination here!  Anyone with some commonplace and practical
>> applications of the enum module?
>
> Have you read the PEP for the enum module? There's also an earlier,
> rejected PEP:
>
> https://www.python.org/dev/peps/pep-0354/
>
> https://www.python.org/dev/peps/pep-0435/

A general question about PEPs:  Is there generally a PEP preceding the
addition of any new feature to the core language or the standard
library?  I gather that even an accepted PEP (In this instance PEP
0435.) may not reflect the final form of the added feature(s) as I did
not see direct mention of "auto", though that feature was alluded to.

> ... but basically an enum
> is an abstract symbol with a pretty representation to make debugging
> easier.
>
> For example, suppose I have a function that justifies a paragraph of
> text:
>
> def justify(paragraph, where):
>     ...
>
> where the `where` argument specifies whether to justify the text on the
> left, on the right, in the centre, or fully justified on both sides. One
> way to specify that is to use numeric constants:
>
> if where == 1:
>     # justify on the left
> elif where == 2:
>     # justify on the right
> elif where == 3:
>     # justify in the centre
> elif where == 4:
>     # fully justify at both ends
>
> but there's no connection between the numbers I choose and the type of
> justification. I could just have sensibly used -3, 87, 4 and 32.5 as 1,
> 2, 3 and 4.
>
> A bit better is to use strings:
>
> if where == 'LEFT':
>     # justify on the left
> elif where == 'RIGHT':
>     # etc
>
> which at least now is self-documenting, but it suggests that the `where`
> argument might take any string at all, which is not correct. There are
> only four fixed values it can take. And besides, having to use the
> quotation marks is tiresome.
>
> So let's invent four (or even five, for Americans) named constants:
>
> LEFT = 'LEFT'
> RIGHT = 'RIGHT'
> CENTRE = CENTER = 'CENTRE'
> FULL = 'FULLY JUSTIFIED'
>
>
> Now we're getting closer. The caller can say:
>
> text = justify(some_text, CENTRE)
>
> which is nice, and the justify() function can include:
>
> if where == LEFT:
>     ...
>
> without quotation marks, which is also nice. That solves about 95% of
> the problem.

Up to this point was basically where I was at when I submitted my
questions.  Why have enumerations when this is already quite doable?
But what you write next turns on the light bulb for me:

> The last niggly 5% is a subtle thing. Because the constants are strings,
> we might be tempted to do string things to them, either deliberately or
> by mistake:
>
>
> justification_mode = CENTRE.lower() + LEFT[1:]  # Oops!
> # much later
> justify(some_text, justification_mode)
>
>
> which of course will fail, but it will fail *when the string is used*,
> not when you do the string-stuff to those constants. It would be nice if
> it failed straight away, at the "justification_mode" line.
>
> To fix that, we need something which looks like a string when you print
> it, for debugging, but actually isn't a string, so it doesn't accept all
> the usual string methods. That's effectively just an abstract symbol,
> and the way to get this in Python is with an enum.

Thanks, Steve, that clarifies things quite nicely.  Great example!

> Enums have a few other nice properties, which you may or may not care
> about, but the primary use is to act as set of related named symbols.
>

The iterability looks useful.  IntEnum looks interesting.  IntFlag and
Flag I am currently clueless about.  I would have to dig deeper as I
don't fully understand their uses yet.

-- 
boB

From alan.gauld at yahoo.co.uk  Sun Apr  9 11:26:32 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 9 Apr 2017 16:26:32 +0100
Subject: [Tutor] What would be good use cases for the enum module?
In-Reply-To: <b0e65e39-74e4-fbf6-9cf5-66b6931035f9@wichmann.us>
References: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
 <occpc7$5ck$1@blaine.gmane.org>
 <b0e65e39-74e4-fbf6-9cf5-66b6931035f9@wichmann.us>
Message-ID: <ocdjr1$g5t$1@blaine.gmane.org>

On 09/04/17 13:58, Mats Wichmann wrote:

> All of these can of course be done without enums.  So the extra benefit
> of an enum is that the set is closed (immutable) and requires
> uniqueness: picking some other value will be an error, 

Indeed, good catch. The value of an enum over an integer is
that the values are limited to those prescribed by the enum,
any attempt to pass or create a different value will be an error.

-- 
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 mats at wichmann.us  Sun Apr  9 11:42:43 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 9 Apr 2017 09:42:43 -0600
Subject: [Tutor] (no subject)
In-Reply-To: <CAN1d+19ZUW90NgB4jx6x507TxgjYr2Y2E-cnBWbS0M582S3FSA@mail.gmail.com>
References: <CAN1d+19ZUW90NgB4jx6x507TxgjYr2Y2E-cnBWbS0M582S3FSA@mail.gmail.com>
Message-ID: <9e82ccc4-1f07-1d78-3dd9-181e9dae9c0a@wichmann.us>

On 04/09/2017 04:42 AM, shubham goyal wrote:
> Hello, I am a c++ programmer and wants to learn python for internship
> purposes. How can i learn the advanced python fast mostly data science
> packages, I know basic python.

Try an internet search?

Don't mean to be snide, but there are lots of resources, including a ton
of books, several courses, tutorials, websites, etc.  For example:

https://www.analyticsvidhya.com/blog/2016/10/18-new-must-read-books-for-data-scientists-on-r-and-python/

We can /possibly/ help you with specific questions here.


Quick hint: you will need to think a little differently in Python than
C++, static vs. dynamic typing, classes work differently, private things
are not really private, etc.



From alan.gauld at yahoo.co.uk  Sun Apr  9 14:49:31 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 9 Apr 2017 19:49:31 +0100
Subject: [Tutor] (no subject)
In-Reply-To: <CAN1d+19ZUW90NgB4jx6x507TxgjYr2Y2E-cnBWbS0M582S3FSA@mail.gmail.com>
References: <CAN1d+19ZUW90NgB4jx6x507TxgjYr2Y2E-cnBWbS0M582S3FSA@mail.gmail.com>
Message-ID: <ocdvnl$vsg$1@blaine.gmane.org>

On 09/04/17 11:42, shubham goyal wrote:
> Hello, I am a c++ programmer and wants to learn python for internship
> purposes. How can i learn the advanced python fast mostly data science
> packages, I know basic python.

There are tutorials on most things.
But it depends on what you mean by advanced python. The ScyPy and NumPy
type stuff is certainly for advanced users of Python but mostly the
Python itself is fairly standard. To me, advanced Python means messing
around with metaclasses, decorators, functools, itertools and the like.

But thee are so many niche areas where Python is used its almost
impossible to recommend any single direction. Once past the basics
its a case of specializing in a given domain.

The biggest jump for most C++ programmers is giving up on type safety.
C++ has strict typing embedded as a religious dogma that it can seem
very strange for a C++ programmer to rely on dynamic typing and trust
that the system will just work. It was one of the things that surprised
me - that by giving up strict typing my programs were no less reliable.
But that understanding does change the way you design and think about
code - and, in particular, how you design and use objects.

-- 
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  Mon Apr 10 00:43:30 2017
From: phil_lor at bigpond.com (Phil)
Date: Mon, 10 Apr 2017 14:43:30 +1000
Subject: [Tutor] Tkinter entry box text changed event
Message-ID: <20170410144330.23cdd89e@raspberrypi>

Again, thank you for reading this.

I would like a function to be called when I enter text and then tab to the next entry box. I've been trying to follow the answers to similar questions in Stack Overflow but I've become hopelessly confused because of the different answers given to seemingly the same question.

I have created a row of entry boxes and a matching function like this:

for i in range(8):
    self.numbers[i]= Entry(master, width=4, justify=CENTER, foreground="gray")
    self.numbers[i].grid(row=16, column=i)
    self.numbers[i].bind('StringVar()', self.my_function)

def my_function(event):
	print("function called")

The function is not called and I know that the binding of the function to the entry boxes is not the correct method. What am I missing?

-- 
Regards,
Phil

From __peter__ at web.de  Mon Apr 10 03:31:10 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 10 Apr 2017 09:31:10 +0200
Subject: [Tutor] Tkinter entry box text changed event
References: <20170410144330.23cdd89e@raspberrypi>
Message-ID: <ocfcbq$nrq$1@blaine.gmane.org>

Phil wrote:

> Again, thank you for reading this.
> 
> I would like a function to be called when I enter text and then tab to the
> next entry box. I've been trying to follow the answers to similar
> questions in Stack Overflow but I've become hopelessly confused because of
> the different answers given to seemingly the same question.
> 
> I have created a row of entry boxes and a matching function like this:
> 
> for i in range(8):
>     self.numbers[i]= Entry(master, width=4, justify=CENTER,
>     foreground="gray") self.numbers[i].grid(row=16, column=i)
>     self.numbers[i].bind('StringVar()', self.my_function)
> 
> def my_function(event):
> print("function called")

To be consistent with the other code snippet this should be a method, not a 
function.
> 
> The function is not called and I know that the binding of the function to
> the entry boxes is not the correct method. What am I missing?
> 

What the ... did you expect from the "StringVar()" argument?

You can find valid events here:

http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/event-types.html

Here's a simple example without a class:

import Tkinter as tk

def welcome(event):
    print("Welcome")

def bye(event):
    print("Bye!")

root = tk.Tk()
for i in range(3):
    entry = tk.Entry(root)
    entry.bind("<FocusIn>", welcome)
    entry.bind("<FocusOut>", bye)
    entry.pack()

root.mainloop()

If you want to pass the index of the entry, say, you can use the 
extra-arguments trick,

http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/extra-args.html

also shown in one of my previous answers.


From alan.gauld at yahoo.co.uk  Mon Apr 10 04:28:49 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 10 Apr 2017 09:28:49 +0100
Subject: [Tutor] Tkinter entry box text changed event
In-Reply-To: <20170410144330.23cdd89e@raspberrypi>
References: <20170410144330.23cdd89e@raspberrypi>
Message-ID: <ocffnr$lm1$1@blaine.gmane.org>

On 10/04/17 05:43, Phil wrote:

> I would like a function to be called when I enter text 
> and then tab to the next entry box.
One of the things about Entry boxes is that they are extremely
flexible and have many event types associated with them.
The consequence of this is that you as a programmer need
to be very, very specific in deciding which events you
want to bind to:

Enter text includes events such as key-press,
key-release. These catch individual keystrokes.

Then there are the navigation bindings such as focusIn
and FocusOut for entering and leaving the Entry(regardless
of whether you change anything.

And of course you have mouse events to consider too.

And you also have the StringVar() mechanism which auto
detects changed values and assigns them to the nominated
textvariable.

So do you want to trigger your code when keys are pressed?
or when the user leaves the box? or when the user arrives
in the next box? And do you only want to do this when the
user is tabbing around in sequence? Or what if they
randomly select one of the entry boxes using the mouse?
What if they use the mouse to select boxes rather than
the tab key?

Once you know that you will know which event types you
want to bind to. But 'StringVar()' is not one of them...

-- 
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 marcus.luetolf at bluewin.ch  Mon Apr 10 03:55:50 2017
From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=)
Date: Mon, 10 Apr 2017 09:55:50 +0200
Subject: [Tutor] counting function calls
Message-ID: <000101d2b1cf$df0f8a90$9d2e9fb0$@bluewin.ch>

Dear experts,
I have written the following code for motion detection with a PIR sensor
with a function and
I need to count how many times the funtion is called, but I get a traceback:

#!/usr/bin/python3
import sys, time
import RPi.GPIO as gpio

gpio.setmode(gpio.BOARD)
gpio.setup(23, gpio.IN)
count = 0
def mein_callback(pin):
    count += 1
    print('PIR 1 aktiviert', count)
    return

try:
    gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
    while True:
        time.sleep(2)
except KeyboardInterrupt:
    print('PIR deaktiviert')

PIR 1 aktiviert
Traceback (most recent call last):
  File "./PIRex.py", line 9, in mein_callback
    count += 1
UnboundLocalError: local variable 'count' referenced before assignment
^CPIR deaktiviert

Tanks for help, marcus.


---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From alan.gauld at yahoo.co.uk  Mon Apr 10 06:15:14 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 10 Apr 2017 11:15:14 +0100
Subject: [Tutor] counting function calls
In-Reply-To: <000101d2b1cf$df0f8a90$9d2e9fb0$@bluewin.ch>
References: <000101d2b1cf$df0f8a90$9d2e9fb0$@bluewin.ch>
Message-ID: <ocflvb$g5d$1@blaine.gmane.org>

On 10/04/17 08:55, marcus l?tolf wrote:
> Dear experts,
> I have written the following code for motion detection with a PIR sensor
> with a function and
> I need to count how many times the funtion is called, but I get a traceback:
> 
> #!/usr/bin/python3
> import sys, time
> import RPi.GPIO as gpio
> 
> gpio.setmode(gpio.BOARD)
> gpio.setup(23, gpio.IN)
> count = 0
> def mein_callback(pin):
>     count += 1
>     print('PIR 1 aktiviert', count)
>     return

> UnboundLocalError: local variable 'count' referenced before assignment
> ^CPIR deaktiviert


You are trying to modify a variable defined in the module or
global scope. To do that you must tell Python that it is
the global variable you mean. You do that by adding

global count

at the top of your function:

def mein_callback(pin):
    global count   # use the global variable
    count += 1
    print('PIR 1 aktiviert', count)
    return

You don;t need the return since Python returns None automatically
at the end of a function. But it doesn't do any harm either...

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 phil_lor at bigpond.com  Mon Apr 10 05:18:39 2017
From: phil_lor at bigpond.com (Phil)
Date: Mon, 10 Apr 2017 19:18:39 +1000
Subject: [Tutor] Tkinter entry box text changed event
In-Reply-To: <ocfcbq$nrq$1@blaine.gmane.org>
References: <20170410144330.23cdd89e@raspberrypi>
 <ocfcbq$nrq$1@blaine.gmane.org>
Message-ID: <20170410191839.3434f026@raspberrypi>

On Mon, 10 Apr 2017 09:31:10 +0200
Peter Otten <__peter__ at web.de> wrote:

>     entry.bind("<FocusOut>", bye)

Thank you Peter and Alan,

I had tried key-press but that caused the error message shown bellow which made me think that I was not on the correct track. So in desperation, after hours of frustration, I tried StringVar() because I'd seen that in a Stack overflow answer.

Adapting Peter's example I have:

self.numbers[i].bind("<FocusOut>", self.my_method)

def my_method(self.event):
    print("method called")

(self.event) is a syntax error and if I leave off "self", this is the result:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
    return self.func(*args)
TypeError: my_method() takes 1 positional argument but 2 were given

I must be close, surely.

-- 
Regards,
Phil

From alan.gauld at yahoo.co.uk  Mon Apr 10 14:40:01 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 10 Apr 2017 19:40:01 +0100
Subject: [Tutor] Tkinter entry box text changed event
In-Reply-To: <20170410191839.3434f026@raspberrypi>
References: <20170410144330.23cdd89e@raspberrypi>
 <ocfcbq$nrq$1@blaine.gmane.org> <20170410191839.3434f026@raspberrypi>
Message-ID: <ocgjhq$i8b$1@blaine.gmane.org>

On 10/04/17 10:18, Phil wrote:

> def my_method(self.event):
>     print("method called")
> 
> (self.event) is a syntax error and if I leave off "self", this is the result:

You want two parameters
self becaiuse its a method of a class so must have a self
event which is the event passsed by the GUI
So:

def my_method(self, event):
    print("method called with ",event)


> I must be close, surely.

A comma instead of a dot...


-- 
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  Mon Apr 10 05:34:05 2017
From: phil_lor at bigpond.com (Phil)
Date: Mon, 10 Apr 2017 19:34:05 +1000
Subject: [Tutor] Tkinter entry box text changed event
In-Reply-To: <ocgjhq$i8b$1@blaine.gmane.org>
References: <20170410144330.23cdd89e@raspberrypi>
 <ocfcbq$nrq$1@blaine.gmane.org>
 <20170410191839.3434f026@raspberrypi>
 <ocgjhq$i8b$1@blaine.gmane.org>
Message-ID: <20170410193405.396e1991@raspberrypi>

On Mon, 10 Apr 2017 19:40:01 +0100
Alan Gauld via Tutor <tutor at python.org> wrote:

> You want two parameters
> self becaiuse its a method of a class so must have a self
> event which is the event passsed by the GUI
> So:
> 
> def my_method(self, event):
>     print("method called with ",event)
> 
> 
> > I must be close, surely.
> 
> A comma instead of a dot...
> 
Thank you so much for your patience Alan.

I woke during the early hours thinking about the requirement for two parameters and realised that my other methods only have self as a single parameter and wondered if "event" was the other parameter. I hadn't though of printing the event. 

Take no notice of this message's posting time, I started my Raspberry Pi before the modem had established an Internet connection. It's pre sunrise here.

-- 
Regards,
Phil

From allantanaka11 at yahoo.com  Mon Apr 10 10:10:34 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Mon, 10 Apr 2017 14:10:34 +0000 (UTC)
Subject: [Tutor] [PYTHON27] How to save into .npy file?
References: <1619968220.293694.1491833434841.ref@mail.yahoo.com>
Message-ID: <1619968220.293694.1491833434841@mail.yahoo.com>

Hi.
Is there a way to save module type data into .npy file that can be used latter?

From mats at wichmann.us  Mon Apr 10 09:15:07 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 10 Apr 2017 07:15:07 -0600
Subject: [Tutor] counting function calls
In-Reply-To: <000101d2b1cf$df0f8a90$9d2e9fb0$@bluewin.ch>
References: <000101d2b1cf$df0f8a90$9d2e9fb0$@bluewin.ch>
Message-ID: <2e560fbf-f7d6-3767-68f4-bd41d9eb6964@wichmann.us>

On 04/10/2017 01:55 AM, marcus l?tolf wrote:
> Dear experts,
> I have written the following code for motion detection with a PIR sensor
> with a function and
> I need to count how many times the funtion is called, but I get a traceback:
> 
> #!/usr/bin/python3
> import sys, time
> import RPi.GPIO as gpio
> 
> gpio.setmode(gpio.BOARD)
> gpio.setup(23, gpio.IN)
> count = 0
> def mein_callback(pin):
>     count += 1
>     print('PIR 1 aktiviert', count)
>     return
> 
> try:
>     gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
>     while True:
>         time.sleep(2)
> except KeyboardInterrupt:
>     print('PIR deaktiviert')
> 
> PIR 1 aktiviert
> Traceback (most recent call last):
>   File "./PIRex.py", line 9, in mein_callback
>     count += 1
> UnboundLocalError: local variable 'count' referenced before assignment
> ^CPIR deaktiviert
> 
> Tanks for help, marcus.

Yes, what Python does here may be surprising at first: if you only
read-access a global variable in a local (function in this case) scope,
it gives you the value just fine.  If you however try to save something
to a global variable what happens is it creates a local variable,
*unless* you have previously informed Python you mean the global one, by
using the global statement as Alan listed. The specific error you see is
because in order to increment 'count' (which Python has already figured
out has to be local because it will be assigned to) you have to read the
existing value first, but there is no existing value in the local scope.

The Python programming FAQ has a short explanation of why this might be so:

https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python


From steve at pearwood.info  Mon Apr 10 21:17:28 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 11 Apr 2017 11:17:28 +1000
Subject: [Tutor] [PYTHON27] How to save into .npy file?
In-Reply-To: <1619968220.293694.1491833434841@mail.yahoo.com>
References: <1619968220.293694.1491833434841.ref@mail.yahoo.com>
 <1619968220.293694.1491833434841@mail.yahoo.com>
Message-ID: <20170411011728.GX9464@ando.pearwood.info>

On Mon, Apr 10, 2017 at 02:10:34PM +0000, Allan Tanaka via Tutor wrote:
> Hi.
> Is there a way to save module type data into .npy file that can be used latter?

What's "module type data"?

What's a .npy file?

To answer your question, literally, the answer is "Yes, of course. 
Python can save ANY data into a file with ANY file extention". But I 
guess that answer isn't helpful to you if you need to save specific data 
to a specific file format.

But without knowing what that specific data is, and the specific format, 
how can we answer?



-- 
Steve

From steve at pearwood.info  Mon Apr 10 23:50:49 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 11 Apr 2017 13:50:49 +1000
Subject: [Tutor] What would be good use cases for the enum module?
In-Reply-To: <CANDiX9+hOB5pghK3koPZYMtOUwQR08YbJFWobEReDGx3AQ8OEQ@mail.gmail.com>
References: <CANDiX9LHQpQBG8xRGAzqg+OV3+SnpY=HyQfxQYXTBWy4=-W9GQ@mail.gmail.com>
 <20170409041323.GU9464@ando.pearwood.info>
 <CANDiX9+hOB5pghK3koPZYMtOUwQR08YbJFWobEReDGx3AQ8OEQ@mail.gmail.com>
Message-ID: <20170411035049.GB9464@ando.pearwood.info>

On Sun, Apr 09, 2017 at 10:21:49AM -0500, boB Stepp wrote:

> A general question about PEPs:  Is there generally a PEP preceding the
> addition of any new feature to the core language or the standard
> library?  I gather that even an accepted PEP (In this instance PEP
> 0435.) may not reflect the final form of the added feature(s) as I did
> not see direct mention of "auto", though that feature was alluded to.

It depends on the natural of the new feature. Generally only large, 
complex or controversial changes require a PEP. Simple bug fixes or 
small additions to existing functionality don't.

Once a feature/module has been added to the language, the PEP usually 
stops being updated. So it effectively becomes a snapshot of what the 
feature was intended to look like in Version X when it was first added, 
not necessarily what it looks like in Version X+1.


> > Enums have a few other nice properties, which you may or may not care
> > about, but the primary use is to act as set of related named symbols.
> >
> 
> The iterability looks useful.  IntEnum looks interesting.  IntFlag and
> Flag I am currently clueless about.  I would have to dig deeper as I
> don't fully understand their uses yet.

Basically IntEnum and similar exist for compatability with C-style 
enums, which are basically integers. That lets you combine flags with 
bitwise OR. Sometimes that's useful, but its not the default for Python 
enums.


-- 
Steve

From mats at wichmann.us  Mon Apr 10 23:16:02 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 10 Apr 2017 21:16:02 -0600
Subject: [Tutor] [PYTHON27] How to save into .npy file?
In-Reply-To: <20170411011728.GX9464@ando.pearwood.info>
References: <1619968220.293694.1491833434841.ref@mail.yahoo.com>
 <1619968220.293694.1491833434841@mail.yahoo.com>
 <20170411011728.GX9464@ando.pearwood.info>
Message-ID: <04932c19-9073-834c-6ea8-bee7e6be8e41@wichmann.us>

On 04/10/2017 07:17 PM, Steven D'Aprano wrote:
> On Mon, Apr 10, 2017 at 02:10:34PM +0000, Allan Tanaka via Tutor wrote:
>> Hi.
>> Is there a way to save module type data into .npy file that can be used latter?
> 
> What's "module type data"?
> 
> What's a .npy file?
> 
> To answer your question, literally, the answer is "Yes, of course. 
> Python can save ANY data into a file with ANY file extention". But I 
> guess that answer isn't helpful to you if you need to save specific data 
> to a specific file format.
> 
> But without knowing what that specific data is, and the specific format, 
> how can we answer?
> 
> 
> 

.npy is a (the?) NumPy format.  Sadly, I know no more than that...

maybe this is of use (quick search):

https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html



From bergiel at gmx.de  Tue Apr 11 12:12:43 2017
From: bergiel at gmx.de (Daniel Berger)
Date: Tue, 11 Apr 2017 18:12:43 +0200
Subject: [Tutor] Question to Phyton and XBee
Message-ID: <trinity-953fcf22-a1ad-4cde-9878-ca3280c1b30e-1491927163105@3capp-gmx-bs73>

   Hello,

   I have installed the modules to control xbee with Python
   https://pypi.python.org/pypi/XBee). Afterwards I have set the path
   variable on C:\Python27\python-xbee-master and also the subdirectories. To
   check, if the modules are available, I have written the code as
   recommended (https://pypi.python.org/pypi/XBee)

   # Import and init xbee device
   from xbee import XBee
   import serial
   import arduino

   The interpreter gave the error message
   File "C:/Users/daniel/PycharmProjects/hardware_test/test_xbee.py", line 2,
   in <module>
   from xbee import XBee
   ImportError: No module named xbee

   I have done the same with https://github.com/nioinnovation/python-xbee and
   it have the same effect.
   As I'm not very familiar with Python, I would like to know, what is going
   wrong and how I can find the module.

   Regards and thank you very much
   Daniel

From rafael.knuth at gmail.com  Tue Apr 11 12:48:31 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Tue, 11 Apr 2017 18:48:31 +0200
Subject: [Tutor] Count for loops
In-Reply-To: <ocbamf$miv$1@blaine.gmane.org>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
Message-ID: <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>

>>> b = "3"+b[2:]  #Removing the decimal point so that there are digits only in
>>
>> my_number = 3.14159
>
> Here you assign a floating point number to mmy_number but
> the code Sama wrote was for working with strings read
> from a text file.
>
> You would need to convert it first:
>
> my_number = str(3.14159)
>
>> my_number = "3"+my_number[2:]
>> print(my_number)

Thanks for the clarification.
I tested this approach, and I noticed one weird thing:

Pi_Number = str(3.14159265358979323846264338327950288419716939)
Pi_Number = "3" + Pi_Number[2:]
print(Pi_Number)

== RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python Code\PPC_56.py ==
3141592653589793
>>>

How come that not the entire string is being printed, but only the
first 16 digits?

From marc.tompkins at gmail.com  Tue Apr 11 15:04:48 2017
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 11 Apr 2017 12:04:48 -0700
Subject: [Tutor] Question to Phyton and XBee
In-Reply-To: <trinity-953fcf22-a1ad-4cde-9878-ca3280c1b30e-1491927163105@3capp-gmx-bs73>
References: <trinity-953fcf22-a1ad-4cde-9878-ca3280c1b30e-1491927163105@3capp-gmx-bs73>
Message-ID: <CAKK8jXZ00Dbnbe07sUh2Fmn9OA6XRt0RhL-3qOuf4QQBsumFrA@mail.gmail.com>

On Tue, Apr 11, 2017 at 9:12 AM, Daniel Berger <bergiel at gmx.de> wrote:

>    Hello,
>
>    I have installed the modules to control xbee with Python
>    https://pypi.python.org/pypi/XBee). Afterwards I have set the path
>    variable on C:\Python27\python-xbee-master and also the subdirectories.
> To
>    check, if the modules are available, I have written the code as
>    recommended (https://pypi.python.org/pypi/XBee)
>
>    # Import and init xbee device
>    from xbee import XBee
>    import serial
>    import arduino
>
>    The interpreter gave the error message
>    File "C:/Users/daniel/PycharmProjects/hardware_test/test_xbee.py",
> line 2,
>    in <module>
>    from xbee import XBee
>    ImportError: No module named xbee
>
>    I have done the same with https://github.com/nioinnovation/python-xbee
> and
>    it have the same effect.
>    As I'm not very familiar with Python, I would like to know, what is
> going
>    wrong and how I can find the module.
>

How did you install it?  If you use the very simplest method -  "pip
install xbee" - it should automatically take care of the path for you.

From marc.tompkins at gmail.com  Tue Apr 11 15:18:42 2017
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 11 Apr 2017 12:18:42 -0700
Subject: [Tutor] Count for loops
In-Reply-To: <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
Message-ID: <CAKK8jXaN-53yoGqPK7=2KHmD2mA_H_AeH=f4ntojFYbVrNZojw@mail.gmail.com>

On Tue, Apr 11, 2017 at 9:48 AM, Rafael Knuth <rafael.knuth at gmail.com>
wrote:

> I tested this approach, and I noticed one weird thing:
>
> Pi_Number = str(3.14159265358979323846264338327950288419716939)
> Pi_Number = "3" + Pi_Number[2:]
> print(Pi_Number)
>
> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python
> Code\PPC_56.py ==
> 3141592653589793
> >>>
>
> How come that not the entire string is being printed, but only the
> first 16 digits?
>

That's due to how str() works; it's simply making (its own conception) of a
pretty representation of what's fed to it, which in the case of
floating-point numbers means that they're represented to 16 digits
precision.
str(3.14159265358979323846264338327950288419716939) is _not_ the same as
    "3.14159265358979323846264338327950288419716939"

>From the docs: "Return a string containing a nicely printable
representation of an object. For strings, this returns the string itself.
The difference with repr(object) is that str(object) does not always
attempt to return a string that is acceptable to eval()
<https://docs.python.org/2/library/functions.html#eval>; its goal is to
return a printable string."

From alan.gauld at yahoo.co.uk  Tue Apr 11 16:32:37 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 11 Apr 2017 21:32:37 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
Message-ID: <ocjegv$jjk$1@blaine.gmane.org>

On 11/04/17 17:48, Rafael Knuth wrote:

> Pi_Number = str(3.14159265358979323846264338327950288419716939)
> Pi_Number = "3" + Pi_Number[2:]
> print(Pi_Number)
> 3141592653589793
>>>>
> 
> How come that not the entire string is being printed, but only the
> first 16 digits?

There are two problems here.
First str() truncates the length of the output to make it look nicer.
Second your version of PI has too many decimal places for a floating
point to hold. Flosting point numbers can hold a huge range of numbers
but not a huge precision.


-- 
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 mats at wichmann.us  Tue Apr 11 14:44:42 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 11 Apr 2017 12:44:42 -0600
Subject: [Tutor] Count for loops
In-Reply-To: <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
Message-ID: <d395182f-88a0-026f-e27d-fefb8a2aa006@wichmann.us>

On 04/11/2017 10:48 AM, Rafael Knuth wrote:

> Thanks for the clarification.
> I tested this approach, and I noticed one weird thing:
> 
> Pi_Number = str(3.14159265358979323846264338327950288419716939)
> Pi_Number = "3" + Pi_Number[2:]
> print(Pi_Number)
> 
> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python Code\PPC_56.py ==
> 3141592653589793
>>>>
> 
> How come that not the entire string is being printed, but only the
> first 16 digits?

Believe it or not, this is one of the Mysteries of Life (Monty Python
reference since that's what the language is named after... sorry).

To get what you're expecting, you could do this:

import decimal

Pi_Number =
str(decimal.Decimal(3.14159265358979323846264338327950288419716939))

in general, (binary) floats and all other things don't interact the way
we mere mortals might expect, and there's a ton of writing on that
topic. The decimal module documentation contains this pithy comment near
the top:

Decimal ?is based on a floating-point model which was designed with
people in mind, and necessarily has a paramount guiding principle ?
computers must provide an arithmetic that works in the same way as the
arithmetic that people learn at school.?


From ben+python at benfinney.id.au  Tue Apr 11 16:43:01 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 12 Apr 2017 06:43:01 +1000
Subject: [Tutor] Precision of floating-point number representation (was:
 Count for loops)
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
Message-ID: <85wpaqbrqi.fsf_-_@benfinney.id.au>

Rafael Knuth <rafael.knuth at gmail.com> writes:

> I tested this approach, and I noticed one weird thing:
>
> Pi_Number = str(3.14159265358979323846264338327950288419716939)
> Pi_Number = "3" + Pi_Number[2:]
> print(Pi_Number)

The mistake is in assuming such a precise number would survive
representation as a ?float? object. Instead, a ?float? object has only a
limited precision::

    >>> 3.14159265358979323846264338327950288419716939 == \
        3.141592653589793238462643383279502884
    True

See the discussion of floating-point numbers in the tutorial
<URL:https://docs.python.org/3/tutorial/floatingpoint.html>.

In fact, you should work through the entire tutorial
<URL:https://docs.python.org/3/tutorial/>, try all the exercises to
understand each section before moving to the next.

-- 
 \      ?If you fell down yesterday, stand up today.? ?_The Anatomy of |
  `\                                   Frustration_, H. G. Wells, 1936 |
_o__)                                                                  |
Ben Finney


From alan.gauld at yahoo.co.uk  Tue Apr 11 16:43:18 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 11 Apr 2017 21:43:18 +0100
Subject: [Tutor] Count for loops
In-Reply-To: <d395182f-88a0-026f-e27d-fefb8a2aa006@wichmann.us>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
 <d395182f-88a0-026f-e27d-fefb8a2aa006@wichmann.us>
Message-ID: <ocjf4v$8sc$1@blaine.gmane.org>

On 11/04/17 19:44, Mats Wichmann wrote:

> import decimal
> 
> Pi_Number =
> str(decimal.Decimal(3.14159265358979323846264338327950288419716939))
> 

Unfortunately that doesn't work either:

>>> "   " + str(decimal.Decimal(
... 3.14159265358979323846264338327950288419716939))
'   3.141592653589793115997963468544185161590576171875'
>>>

Notice the output is both longer and has completely different
numbers in the last half of the result.


> topic. The decimal module documentation contains this pithy comment near
> the top:
> 
> Decimal ?is based on a floating-point model which was designed with
> people in mind, and necessarily has a paramount guiding principle ?
> computers must provide an arithmetic that works in the same way as the
> arithmetic that people learn at school.?

But sadly they haven't beat the problem of storing high precision
decimal numbers in binary storage.

-- 
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  Tue Apr 11 23:40:46 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 11 Apr 2017 22:40:46 -0500
Subject: [Tutor] Count for loops
In-Reply-To: <CAKK8jXaN-53yoGqPK7=2KHmD2mA_H_AeH=f4ntojFYbVrNZojw@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
 <CAKK8jXaN-53yoGqPK7=2KHmD2mA_H_AeH=f4ntojFYbVrNZojw@mail.gmail.com>
Message-ID: <CANDiX9Kyr59Fpd=UToctF0COy5YTzeypk-9t-6tgkSXeq-j-fw@mail.gmail.com>

On Tue, Apr 11, 2017 at 2:18 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Tue, Apr 11, 2017 at 9:48 AM, Rafael Knuth <rafael.knuth at gmail.com>
> wrote:
>
>> I tested this approach, and I noticed one weird thing:
>>
>> Pi_Number = str(3.14159265358979323846264338327950288419716939)
>> Pi_Number = "3" + Pi_Number[2:]

Minor note:  If the OP's original effort was to reproduce his pi
approximation with a decimal point, then his slice indexing should
have been Pi_Number[1:]

>> print(Pi_Number)
>>
>> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python
>> Code\PPC_56.py ==
>> 3141592653589793
>> >>>
>>
>> How come that not the entire string is being printed, but only the
>> first 16 digits?
>>
>
> That's due to how str() works; it's simply making (its own conception) of a
> pretty representation of what's fed to it, which in the case of
> floating-point numbers means that they're represented to 16 digits
> precision.
> str(3.14159265358979323846264338327950288419716939) is _not_ the same as
>     "3.14159265358979323846264338327950288419716939"
>
> From the docs: "Return a string containing a nicely printable
> representation of an object. For strings, this returns the string itself.
> The difference with repr(object) is that str(object) does not always
> attempt to return a string that is acceptable to eval()
> <https://docs.python.org/2/library/functions.html#eval>; its goal is to
> return a printable string."

I have to say I am surprised by this as well as the OP.  I knew that
str() in general makes a nice printable representation, but I did not
realize that using str() on an arbitrarily typed in "float-like" value
would convert the typed in value to a normal float's max precision.
So I guess the only way to get a string representation of such a
number is to do something like:

py3: str_pi = '3.14159265358979323846264338327950288419716939'
py3: len(str_pi)
46
py3: str_pi
'3.14159265358979323846264338327950288419716939'

or perhaps:

py3: new_pi = '3' + '.' + '14159265358979323846264338327950288419716939'
py3: len(new_pi)
46
py3: new_pi
'3.14159265358979323846264338327950288419716939'

or even with str():

py3: new_pi = '3' + '.' + str(14159265358979323846264338327950288419716939)
py3: len(new_pi)
46
py3: new_pi
'3.14159265358979323846264338327950288419716939'

since in Python 3 integers are unlimited in precision (within RAM constraints).

I guess this has to be this way or the conversions of actual Python
numerical literals to strings and back again would otherwise be
inconsistent.

Still learning!

-- 
boB

From robertvstepp at gmail.com  Wed Apr 12 00:03:04 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 11 Apr 2017 23:03:04 -0500
Subject: [Tutor] Count for loops
In-Reply-To: <ocjf4v$8sc$1@blaine.gmane.org>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
 <d395182f-88a0-026f-e27d-fefb8a2aa006@wichmann.us>
 <ocjf4v$8sc$1@blaine.gmane.org>
Message-ID: <CANDiX9LaMaWRPZ_dO-Y_FnB1YQOAQK48YES310W5wYOkmheu8w@mail.gmail.com>

On Tue, Apr 11, 2017 at 3:43 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 11/04/17 19:44, Mats Wichmann wrote:
>
>> import decimal
>>
>> Pi_Number =
>> str(decimal.Decimal(3.14159265358979323846264338327950288419716939))
>>
>
> Unfortunately that doesn't work either:
>
>>>> "   " + str(decimal.Decimal(
> ... 3.14159265358979323846264338327950288419716939))
> '   3.141592653589793115997963468544185161590576171875'
>>>>
>
> Notice the output is both longer and has completely different
> numbers in the last half of the result.

I have not used the decimal module (until tonight).  I just now played
around with it some, but cannot get it to do an exact conversion of
the number under discussion to a string using str().  I notice that
the module has the methods to_eng_string() and to_sci_string(), but I
see no substitute for str() listed.  Surely there is some way to use
the decimal module to get the desired conversion to a string?  I have
to retire for the evening and will try to figure this out tomorrow.

Cheers!

boB

From eryksun at gmail.com  Wed Apr 12 01:15:25 2017
From: eryksun at gmail.com (eryk sun)
Date: Wed, 12 Apr 2017 05:15:25 +0000
Subject: [Tutor] Count for loops
In-Reply-To: <CANDiX9Kyr59Fpd=UToctF0COy5YTzeypk-9t-6tgkSXeq-j-fw@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
 <CAKK8jXaN-53yoGqPK7=2KHmD2mA_H_AeH=f4ntojFYbVrNZojw@mail.gmail.com>
 <CANDiX9Kyr59Fpd=UToctF0COy5YTzeypk-9t-6tgkSXeq-j-fw@mail.gmail.com>
Message-ID: <CACL+1avigx3CPBSyOLm4R4QfLtU4JYzxhto8wNi7559EcNmZGw@mail.gmail.com>

On Wed, Apr 12, 2017 at 3:40 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>
> I have to say I am surprised by this as well as the OP.  I knew that
> str() in general makes a nice printable representation

The single-argument str() constructor calls the object's __str__
method (or __repr__ if __str__ isn't defined). In Python 3,
float.__str__ and float.__repr__ behave the same. They use as many
digits as is required to round trip back to the float value exactly.
That's up to 17 digits.

    >>> str(1.2345678901234567)
    '1.2345678901234567'
    >>> str(1.)
    '1.0'

In Python 2, float.__str__ uses up to 12 digits:

    >>> str(1.2345678901234567)
    '1.23456789012'

> realize that using str() on an arbitrarily typed in "float-like" value
> would convert the typed in value to a normal float's max precision.

For a literal floating-point value in source code, the compiler
(component of the interpreter) first parses a NUMBER node:

    >>> e = parser.expr('3.14159265358979323846264338327950288419716939')
    >>> p = parser.st2list(e)
    >>> while p[0] != token.NUMBER:
    ...     p = p[1]
    ...
    >>> p
    [2, '3.14159265358979323846264338327950288419716939']

Next it transforms this concrete syntax tree into a abstract syntax tree:

    >>> a = ast.parse('3.14159265358979323846264338327950288419716939',
    ...               mode='eval')
    >>> ast.dump(a)
    'Expression(body=Num(n=3.141592653589793))'

    >>> a.body.n
    3.141592653589793
    >>> type(a.body.n)
    <class 'float'>

You see above that the AST transforms the NUMBER node into a Num node
that references a float object. The value of the float is the closest
possible approximation of the source code literal as a
double-precision binary float.

If the compiler instead used Decimal objects, then it could retain all
of the literal's precision. Double-precision binary floats are fast
and efficient by virtue of hardware support, but that's not a
compelling reason in Python. Maybe some future version of Python will
switch to using Decimals for floating-point literals.

The final step is to compile this AST into bytecode and create a code
object. The float value is referenced in the code object's co_consts
attribute:

    >>> c = compile(a, '', 'eval')
    >>> c.co_consts
    (3.141592653589793,)

The code in this case is simple; just load and return the constant value:

    >>> dis.dis(c)
      1           0 LOAD_CONST               0 (3.141592653589793)
                  3 RETURN_VALUE

    >>> eval(c)
    3.141592653589793

From eryksun at gmail.com  Wed Apr 12 01:41:01 2017
From: eryksun at gmail.com (eryk sun)
Date: Wed, 12 Apr 2017 05:41:01 +0000
Subject: [Tutor] Count for loops
In-Reply-To: <CANDiX9LaMaWRPZ_dO-Y_FnB1YQOAQK48YES310W5wYOkmheu8w@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
 <d395182f-88a0-026f-e27d-fefb8a2aa006@wichmann.us>
 <ocjf4v$8sc$1@blaine.gmane.org>
 <CANDiX9LaMaWRPZ_dO-Y_FnB1YQOAQK48YES310W5wYOkmheu8w@mail.gmail.com>
Message-ID: <CACL+1avu1OfctcscuAxPW01X_c-gKdw0o=69jJFKtP7C=d0PJw@mail.gmail.com>

On Wed, Apr 12, 2017 at 4:03 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>
> I have not used the decimal module (until tonight).  I just now played
> around with it some, but cannot get it to do an exact conversion of
> the number under discussion to a string using str().

Pass a string to the constructor:

    >>> d = decimal.Decimal('3.14159265358979323846264338327950288419716939')
    >>> str(d)
    '3.14159265358979323846264338327950288419716939'

When formatting for printing, note that classic string interpolation
has to first convert the Decimal to a float, which only has 15 digits
of precision (15.95 rounded down).

    >>> '%.44f' % d
    '3.14159265358979311599796346854418516159057617'
    >>> '%.44f' % float(d)
    '3.14159265358979311599796346854418516159057617'

The result is more accurate using Python's newer string formatting
system, which allows types to define a custom __format__ method.

    >>> '{:.44f}'.format(d)
    '3.14159265358979323846264338327950288419716939'
    >>> format(d, '.44f')
    '3.14159265358979323846264338327950288419716939'

From bergiel at gmx.de  Wed Apr 12 10:32:51 2017
From: bergiel at gmx.de (Daniel Berger)
Date: Wed, 12 Apr 2017 16:32:51 +0200
Subject: [Tutor] Question to Phyton and XBee
In-Reply-To: <CAKK8jXZ00Dbnbe07sUh2Fmn9OA6XRt0RhL-3qOuf4QQBsumFrA@mail.gmail.com>
References: <trinity-953fcf22-a1ad-4cde-9878-ca3280c1b30e-1491927163105@3capp-gmx-bs73>, 
 <CAKK8jXZ00Dbnbe07sUh2Fmn9OA6XRt0RhL-3qOuf4QQBsumFrA@mail.gmail.com>
Message-ID: <trinity-d0ffc75d-4523-47df-8fe3-7488398cec1f-1492007571222@3capp-gmx-bs43>

   Hello,

   thank you very much for your help. I have done a mistake during
   installation.
   I have tested the code for reading data from Xbee:

 #! /usr/bin/python
 # Import and init an XBee device
 from xbee import XBee, ZigBee
 import serial
 ser = serial.Serial('COM4', 9600)
 xbee = XBee(ser)
 while True:
     try:
         response =  xbee.wait_read_frame()
         print response
     except KeyboardInterrupt:
         break
 ser.close()

   At the moment it is not possible to get any data received by the Xbee,
   although it is possible to read the data by XCTU. I have chosen the
   following setup:
   - A TMP36-sensor is connected to an Arduino Uno
   - A Sparkfun XBee-shield with an XBee S2C is mounted on the Arduino
   (Router). The Arduino is connected to COM3.
   - COM4 is connected with a Sparkfun XBee-Explorer (USB-connection).
   Another XBee S2C is connected on the explorer. This XBee is the
   coordinator.
   If I send sensor data (sensor reading and sending to Xbee is done by
   Arduino Software) from the router to the coordinator, I'm able to read the
   data frames by XCTU and the results make sense. If I use the Python-code
   above, I did not get any data frames, although the RSSI-diodes of router
   and coordinator are blinking independently from the software (XCTU or
   Python) I use.
   For me it is not clear what is going wrong and I would be happy to get
   some help to solve the problem.

   Regards and thank you very much
   Daniel Berger




   Gesendet: Dienstag, 11. April 2017 um 21:04 Uhr
   Von: "Marc Tompkins" <marc.tompkins at gmail.com>
   An: "Daniel Berger" <bergiel at gmx.de>
   Cc: "tutor at python.org" <tutor at python.org>
   Betreff: Re: [Tutor] Question to Phyton and XBee
   On Tue, Apr 11, 2017 at 9:12 AM, Daniel Berger <[1]bergiel at gmx.de> wrote:

        Hello,

        I have installed the modules to control xbee with Python
        [2]https://pypi.python.org/pypi/XBee). Afterwards I have set the path
        variable on C:\Python27\python-xbee-master and also the
     subdirectories. To
        check, if the modules are available, I have written the code as
        recommended ([3]https://pypi.python.org/pypi/XBee)

        # Import and init xbee device
        from xbee import XBee
        import serial
        import arduino

        The interpreter gave the error message
        File "C:/Users/daniel/PycharmProjects/hardware_test/test_xbee.py",
     line 2,
        in <module>
        from xbee import XBee
        ImportError: No module named xbee

        I have done the same with
     [4]https://github.com/nioinnovation/python-xbee and
        it have the same effect.
        As I'm not very familiar with Python, I would like to know, what is
     going
        wrong and how I can find the module.


   How did you install it?  If you use the very simplest method -  "pip
   install xbee" - it should automatically take care of the path for you.



References

   Visible links
   1. mailto:bergiel at gmx.de
   2. https://pypi.python.org/pypi/XBee
   3. https://pypi.python.org/pypi/XBee
   4. https://github.com/nioinnovation/python-xbee

From wimberrelkamp at gmail.com  Wed Apr 12 08:47:26 2017
From: wimberrelkamp at gmail.com (Wim Berrelkamp)
Date: Wed, 12 Apr 2017 14:47:26 +0200
Subject: [Tutor] Startup Python
Message-ID: <CAFLus-errs6bXRLdsmk+ApaosjPB10h+9sii-0eeKdmC+wEt6w@mail.gmail.com>

Dear Tutor,

In earlier days I programmed a lot with Quick Basic in DOS.
Now I retiered, I hoped to have Python as a platform.
So I installed it and saw a lot of simmularity with Basic.

I hope you can help me with the following, which should not be difficult,
but I cannot find the solution.

When I type this:

>>> a=2
>>> d=a+4
>>> print(d)
6

I got the correct answer.

When I try this to run it in a Module:

a=input('-->' )
print(a)
d=a+4
print(d)

I get this as a result:


input test.py
-->2
2
Traceback (most recent call last):
  File
"C:\Users\Gebruiker\AppData\Local\Programs\Python\Python36\Lib\idlelib\input
test.py", line 3, in <module>
    d=a+4
TypeError: must be str, not int
>>>

I receive this message.

I tried to use float(), but nothing works.
What am I doing wrong ?

Thanks in advance !
Regards,
Wim Berrelkamp
Groningen, The Netherlands

From alan.gauld at yahoo.co.uk  Wed Apr 12 13:41:30 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 12 Apr 2017 18:41:30 +0100
Subject: [Tutor] Startup Python
In-Reply-To: <CAFLus-errs6bXRLdsmk+ApaosjPB10h+9sii-0eeKdmC+wEt6w@mail.gmail.com>
References: <CAFLus-errs6bXRLdsmk+ApaosjPB10h+9sii-0eeKdmC+wEt6w@mail.gmail.com>
Message-ID: <oclos3$jph$1@blaine.gmane.org>

On 12/04/17 13:47, Wim Berrelkamp wrote:

>>>> a=2

Here you assign the number 2 to 'a'

>>>> d=a+4
>>>> print(d)
> 6
> a=input('-->' )

Here you assign whatever character(s) the user types to 'a'.
The fact that it looks like 2 doesn't change the fact that it
is really the character '2'. So you need to convert it to
a number using either int() or float()

a = int(input('-->'))
or
a = float(input('-->'))

> print(a)
> d=a+4
> print(d)
> 

> I tried to use float(), but nothing works.
> What am I doing wrong ?

I don't know, because you don't show us how you tried to
use float(), but if you apply it as shown above it
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  Wed Apr 12 13:44:29 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 12 Apr 2017 18:44:29 +0100
Subject: [Tutor] Question to Phyton and XBee
In-Reply-To: <trinity-d0ffc75d-4523-47df-8fe3-7488398cec1f-1492007571222@3capp-gmx-bs43>
References: <trinity-953fcf22-a1ad-4cde-9878-ca3280c1b30e-1491927163105@3capp-gmx-bs73>
 <CAKK8jXZ00Dbnbe07sUh2Fmn9OA6XRt0RhL-3qOuf4QQBsumFrA@mail.gmail.com>
 <trinity-d0ffc75d-4523-47df-8fe3-7488398cec1f-1492007571222@3capp-gmx-bs43>
Message-ID: <oclp1n$m2$1@blaine.gmane.org>

On 12/04/17 15:32, Daniel Berger wrote:

>    For me it is not clear what is going wrong and I would be happy to get
>    some help to solve the problem.

This list is for the core language and library, so while we
can help with installing third party packages that doesn't
mean anyone here will know how to use them. You might get
lucky and find somebody, but you are more likely to find
someone on a dedicated XBee support forum.

If both of those options fail then you can try the main
Python list.

-- 
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 dvnsarma at gmail.com  Wed Apr 12 21:18:25 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Thu, 13 Apr 2017 06:48:25 +0530
Subject: [Tutor] Count for loops
In-Reply-To: <CACL+1avu1OfctcscuAxPW01X_c-gKdw0o=69jJFKtP7C=d0PJw@mail.gmail.com>
References: <CAM-E2X5=UYQtXNDRaz5M=h3tGqodep6O8yEHA+zLp21k+OgBng@mail.gmail.com>
 <obtnit$k8t$1@blaine.gmane.org>
 <CAOZcEcf9WCjnr7vJiRiXpi8G_EKaq-oukMzORsB6=7137LDkQA@mail.gmail.com>
 <obtota$jtf$1@blaine.gmane.org>
 <CAOZcEcdui0sy+9=4YrQn2+=eufVFynD6kEbh=WY4mzXV=mtLjA@mail.gmail.com>
 <obtsh6$6cu$1@blaine.gmane.org>
 <9feb1111-0dae-41b2-205e-41707aeaecc8@wichmann.us>
 <CAOZcEcckMe5A-C9VmfFc5BEp7nDJ_3pq-dRq2Ht8sBu5hjeSUg@mail.gmail.com>
 <CAOZcEcc3ZBqEdC0ucHDhDoL1_H-8jBYm=D6AqZxRov3PtR2K0g@mail.gmail.com>
 <CAM-E2X4N4sguNrV6x9UZWYQOKvfvg39JUkpiwy-XkHNrCBdRDQ@mail.gmail.com>
 <CAOZcEcfyE+cMXSsiC6TTW0xYr3UM0_ZL7sh4onxQ21h129Bvyg@mail.gmail.com>
 <CAM-E2X5QkEytUHLvxezw3+PXgR4JdkLHCJVojuJOyBkELGjyuA@mail.gmail.com>
 <ocbamf$miv$1@blaine.gmane.org>
 <CAM-E2X77z-6sb864FnRNGt_PYXE_QQjuGCQHpR8xQh0Ng3MvKw@mail.gmail.com>
 <d395182f-88a0-026f-e27d-fefb8a2aa006@wichmann.us>
 <ocjf4v$8sc$1@blaine.gmane.org>
 <CANDiX9LaMaWRPZ_dO-Y_FnB1YQOAQK48YES310W5wYOkmheu8w@mail.gmail.com>
 <CACL+1avu1OfctcscuAxPW01X_c-gKdw0o=69jJFKtP7C=d0PJw@mail.gmail.com>
Message-ID: <CAOZcEcfcaCdYchoWa5VnqnYfOVWUZ=JLYmVzxkV24_w2u4xm5g@mail.gmail.com>

A lot of confusion is caused by the print function converting an integer or
float
to a string before printing to console. thus both '1234 and '1234' are
shown as
1234 on the console. Similarly '15.4' and 15.4 are displayed as 15.4. There
is no way
to tell which is a string, which is an int and which is a float by looking
at the display on
console. In order to find which is which one has to type the variables.


>>> s = '1234'

>>> print(s)
1234

>>> s = 1234

>>> print(s)
1234

>>> s = '15.4'

>>> print(s)
15.4

>>> s = 15.4

>>> print(s)
15.4

regards,
Sarma.

On Wed, Apr 12, 2017 at 11:11 AM, eryk sun <eryksun at gmail.com> wrote:

> On Wed, Apr 12, 2017 at 4:03 AM, boB Stepp <robertvstepp at gmail.com> wrote:
> >
> > I have not used the decimal module (until tonight).  I just now played
> > around with it some, but cannot get it to do an exact conversion of
> > the number under discussion to a string using str().
>
> Pass a string to the constructor:
>
>     >>> d = decimal.Decimal('3.141592653589793238462643383279
> 50288419716939')
>     >>> str(d)
>     '3.14159265358979323846264338327950288419716939'
>
> When formatting for printing, note that classic string interpolation
> has to first convert the Decimal to a float, which only has 15 digits
> of precision (15.95 rounded down).
>
>     >>> '%.44f' % d
>     '3.14159265358979311599796346854418516159057617'
>     >>> '%.44f' % float(d)
>     '3.14159265358979311599796346854418516159057617'
>
> The result is more accurate using Python's newer string formatting
> system, which allows types to define a custom __format__ method.
>
>     >>> '{:.44f}'.format(d)
>     '3.14159265358979323846264338327950288419716939'
>     >>> format(d, '.44f')
>     '3.14159265358979323846264338327950288419716939'
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From allantanaka11 at yahoo.com  Wed Apr 12 22:01:30 2017
From: allantanaka11 at yahoo.com (Allan Tanaka)
Date: Thu, 13 Apr 2017 02:01:30 +0000 (UTC)
Subject: [Tutor] [PYTHON27] How to save into .npy file?
References: <1041466606.953831.1492048890508.ref@mail.yahoo.com>
Message-ID: <1041466606.953831.1492048890508@mail.yahoo.com>

.npy is numpy array. Thanks it's ok i manage to save it..








On Tuesday, 11 April 2017, 8:23, Steven D'Aprano <steve at pearwood.info> wrote:




On Mon, Apr 10, 2017 at 02:10:34PM +0000, Allan Tanaka via Tutor wrote:

> Hi.

> Is there a way to save module type data into .npy file that can be used latter?


What's "module type data"?


What's a .npy file?


To answer your question, literally, the answer is "Yes, of course. 

Python can save ANY data into a file with ANY file extention". But I 

guess that answer isn't helpful to you if you need to save specific data 

to a specific file format.


But without knowing what that specific data is, and the specific format, 

how can we answer?




-- 

Steve


_______________________________________________

Tutor maillist  -  Tutor at python.org

To unsubscribe or change subscription options:

https://mail.python.org/mailman/listinfo/tutor

From hammerc2 at mail.montclair.edu  Thu Apr 13 10:33:22 2017
From: hammerc2 at mail.montclair.edu (Christina Hammer)
Date: Thu, 13 Apr 2017 10:33:22 -0400
Subject: [Tutor] python help
Message-ID: <CAG4DYMi-7A_vgLzUhZqBP5FMCgBeu+f0vu7HhzB1oR_Jgp5Scw@mail.gmail.com>

Hi,
I downloaded the newest version of Python on my windows computer and am
having some trouble using it. I need to save my work because I am using it
for an online class and am going to have to send it to my professor. But I
cannot access a tool bar that would allow me to save it. I'm not sure if
someone can help me with this.
Thank you
Christina Hammer

From marcus.luetolf at bluewin.ch  Thu Apr 13 12:10:45 2017
From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=)
Date: Thu, 13 Apr 2017 18:10:45 +0200
Subject: [Tutor] counting function calls
In-Reply-To: <2e560fbf-f7d6-3767-68f4-bd41d9eb6964@wichmann.us>
References: <000101d2b1cf$df0f8a90$9d2e9fb0$@bluewin.ch>
 <2e560fbf-f7d6-3767-68f4-bd41d9eb6964@wichmann.us>
Message-ID: <000101d2b470$824d0c30$86e72490$@bluewin.ch>

Dear experts, Mats
I have found the solution, I put the counting variable at the wrong place: 

> #!/usr/bin/python3
> import sys, time
> import RPi.GPIO as gpio
> 
> gpio.setmode(gpio.BOARD)
> gpio.setup(23, gpio.IN)
> count = 0
> def mein_callback(pin):
>     count += 1
>     print('PIR 1 aktiviert', count)
>     return
> 
> try:
       count = 0
>     gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
>     while True:
>         time.sleep(2)
           count += 1
> except KeyboardInterrupt:
>     print('PIR deaktiviert')

Marcus.
----------------------------------------------------------------------------
--------------------
-----Urspr?ngliche Nachricht-----
Von: Mats Wichmann [mailto:mats at wichmann.us] 
Gesendet: Montag, 10. April 2017 15:15
An: marcus l?tolf <marcus.luetolf at bluewin.ch>; tutor at python.org
Betreff: Re: [Tutor] counting function calls

On 04/10/2017 01:55 AM, marcus l?tolf wrote:
> Dear experts,
> I have written the following code for motion detection with a PIR 
> sensor with a function and I need to count how many times the funtion 
> is called, but I get a traceback:
> 
> #!/usr/bin/python3
> import sys, time
> import RPi.GPIO as gpio
> 
> gpio.setmode(gpio.BOARD)
> gpio.setup(23, gpio.IN)
> count = 0
> def mein_callback(pin):
>     count += 1
>     print('PIR 1 aktiviert', count)
>     return
> 
> try:
>     gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
>     while True:
>         time.sleep(2)
> except KeyboardInterrupt:
>     print('PIR deaktiviert')
> 
> PIR 1 aktiviert
> Traceback (most recent call last):
>   File "./PIRex.py", line 9, in mein_callback
>     count += 1
> UnboundLocalError: local variable 'count' referenced before assignment 
> ^CPIR deaktiviert
> 
> Tanks for help, marcus.

Yes, what Python does here may be surprising at first: if you only
read-access a global variable in a local (function in this case) scope, it
gives you the value just fine.  If you however try to save something to a
global variable what happens is it creates a local variable,
*unless* you have previously informed Python you mean the global one, by
using the global statement as Alan listed. The specific error you see is
because in order to increment 'count' (which Python has already figured out
has to be local because it will be assigned to) you have to read the
existing value first, but there is no existing value in the local scope.

The Python programming FAQ has a short explanation of why this might be so:

https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-
and-global-variables-in-python



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From rafael.knuth at gmail.com  Thu Apr 13 12:32:41 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Thu, 13 Apr 2017 18:32:41 +0200
Subject: [Tutor] creating .json files
Message-ID: <CAM-E2X5DArgEYQrGM_kVpzWdmpvSwQRnmcLuc72N8B1TQjbdfQ@mail.gmail.com>

Is there a way to split these two into separate steps:
a) creating a .json file
b) manipulating it (a, r, w ...)

Example:

"import json
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
file_name = "my_numbers.json"
with open(file_name, "w") as a:
    json.dump(number_list, a)

What if I just wanted to create a .json file and do nothing with it?

import json
file_name = "my_numbers.json"

The above does not do the job. What am I getting wrong here? Thanks.

From alan.gauld at yahoo.co.uk  Thu Apr 13 13:18:35 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 13 Apr 2017 18:18:35 +0100
Subject: [Tutor] python help
In-Reply-To: <CAG4DYMi-7A_vgLzUhZqBP5FMCgBeu+f0vu7HhzB1oR_Jgp5Scw@mail.gmail.com>
References: <CAG4DYMi-7A_vgLzUhZqBP5FMCgBeu+f0vu7HhzB1oR_Jgp5Scw@mail.gmail.com>
Message-ID: <ocobt5$2dd$1@blaine.gmane.org>

On 13/04/17 15:33, Christina Hammer wrote:

> I downloaded the newest version of Python on my windows computer and am
> having some trouble using it. I need to save my work because I am using it
> for an online class and am going to have to send it to my professor. But I
> cannot access a tool bar that would allow me to save it. I'm not sure if
> someone can help me with this.

Python is a programming language interpreter, and as such it
does not have a GUI. Instead you create your programs using
a separate program, usually a text editor like Notepad,
or sometjhing more powerful. From there you save the program
as a file ending with .py.

On Windows you can then get Python to execute that file by either
1) Double clicking in Windows explorer (but this often results
in the program starting, running and closing so quickly you
can't see what it did*)
2) Start a command console (CMD.EXE) and type

C:\WINDOWS> python myprogram.py

--------
(*)You can force the program to pause by adding a line
input("Hit ENTER to continue")
in your code.
---------

Most Python downloads simplify this process by including a
development tool called IDLE and you should have an entry
for that in your menus. IDLE presents a GUI into which
you can enter python commands or open a new edit window
to type your code. You can then save that as before. But
IDLE also includes menus for running your code from within
IDLE. If you search on YouTube you will find several short
tutorial videos showing how to get started with IDLE.

Here is one specifically for Windows...

https://www.youtube.com/watch?v=5hwG2gEGzVg


-- 
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 Apr 13 13:23:56 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 13 Apr 2017 18:23:56 +0100
Subject: [Tutor] counting function calls
In-Reply-To: <000101d2b470$824d0c30$86e72490$@bluewin.ch>
References: <000101d2b1cf$df0f8a90$9d2e9fb0$@bluewin.ch>
 <2e560fbf-f7d6-3767-68f4-bd41d9eb6964@wichmann.us>
 <000101d2b470$824d0c30$86e72490$@bluewin.ch>
Message-ID: <ococ76$pub$1@blaine.gmane.org>

On 13/04/17 17:10, marcus l?tolf wrote:
> Dear experts, Mats
> I have found the solution, I put the counting variable at the wrong place: 

I don;t think so, what you have done now is count the times
through the loop, but thats not (always) the same as the
number of times the function gets called, which is what
you said you wanted to count..


>> #!/usr/bin/python3
>> import sys, time
>> import RPi.GPIO as gpio
>>
>> gpio.setmode(gpio.BOARD)
>> gpio.setup(23, gpio.IN)
>> count = 0
>> def mein_callback(pin):
>>     count += 1

This line will still give you an error.

>>     print('PIR 1 aktiviert', count)
>>     return
>>
>> try:
>        count = 0
>>     gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
>>     while True:
>>         time.sleep(2)
>            count += 1

This just counts how many times your while loop goes
round - once every 2 seconds. It says nothing about
how often the callback gets executed.

To do that you need to add the line

global count

to your callback function.

But then both the loop and function will increment
the global count variable so you need to remove
(or rename) the one in the loop.

-- 
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 george at fischhof.hu  Thu Apr 13 13:30:28 2017
From: george at fischhof.hu (George Fischhof)
Date: Thu, 13 Apr 2017 19:30:28 +0200
Subject: [Tutor] python help
In-Reply-To: <CAG4DYMi-7A_vgLzUhZqBP5FMCgBeu+f0vu7HhzB1oR_Jgp5Scw@mail.gmail.com>
References: <CAG4DYMi-7A_vgLzUhZqBP5FMCgBeu+f0vu7HhzB1oR_Jgp5Scw@mail.gmail.com>
Message-ID: <CAFwcP0jvxUkLxpdqx2A=MQvTCVSNA=jNF51ZwSK4ToJ_tJS2NQ@mail.gmail.com>

Hi Christina,

you should use an editor or an IDE (Integrated Development Environment) (a
quite good and my favorite IDE is PyCharm
https://www.jetbrains.com/pycharm/download/#section=windows ), write the
script in it,then save,  then run it from the IDE or from command line with
similar command:
python script_name.py

BR,
George

2017-04-13 16:33 GMT+02:00 Christina Hammer <hammerc2 at mail.montclair.edu>:

> Hi,
> I downloaded the newest version of Python on my windows computer and am
> having some trouble using it. I need to save my work because I am using it
> for an online class and am going to have to send it to my professor. But I
> cannot access a tool bar that would allow me to save it. I'm not sure if
> someone can help me with this.
> Thank you
> Christina Hammer
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From leamhall at gmail.com  Thu Apr 13 13:12:10 2017
From: leamhall at gmail.com (leam hall)
Date: Thu, 13 Apr 2017 13:12:10 -0400
Subject: [Tutor] creating .json files
In-Reply-To: <CAM-E2X5DArgEYQrGM_kVpzWdmpvSwQRnmcLuc72N8B1TQjbdfQ@mail.gmail.com>
References: <CAM-E2X5DArgEYQrGM_kVpzWdmpvSwQRnmcLuc72N8B1TQjbdfQ@mail.gmail.com>
Message-ID: <CACv9p5pWpiGachQoxoEof-qhcuQ6sTzQeq4YGuzB=z8Jqo+hBQ@mail.gmail.com>

On Thu, Apr 13, 2017 at 12:32 PM, Rafael Knuth <rafael.knuth at gmail.com>
wrote:

> Is there a way to split these two into separate steps:
> a) creating a .json file
> b) manipulating it (a, r, w ...)
>
> Example:
>
> "import json
> number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> file_name = "my_numbers.json"
> with open(file_name, "w") as a:
>     json.dump(number_list, a)
>
> What if I just wanted to create a .json file and do nothing with it?
>
> import json
> file_name = "my_numbers.json"
>
> The above does not do the job. What am I getting wrong here? Thanks.
>
> If you want to have a file after the program runs you need to "open" it.
And close it. Otherwise you reference a file but leave no trace.

From qiaozha at gmail.com  Thu Apr 13 13:05:19 2017
From: qiaozha at gmail.com (Qiao Qiao)
Date: Thu, 13 Apr 2017 13:05:19 -0400
Subject: [Tutor] python help
In-Reply-To: <CAG4DYMi-7A_vgLzUhZqBP5FMCgBeu+f0vu7HhzB1oR_Jgp5Scw@mail.gmail.com>
References: <CAG4DYMi-7A_vgLzUhZqBP5FMCgBeu+f0vu7HhzB1oR_Jgp5Scw@mail.gmail.com>
Message-ID: <CAK0Q1SC1SWeh9xqcYWHnUF_FkYcn61j3Va6Dv6z1TAXhyPJEvw@mail.gmail.com>

If you are going to send it to your professor. Maybe just copy all your
result to a txt file and send the text?

Qiao

Qiao Qiao
Web Engineer

On Thu, Apr 13, 2017 at 10:33 AM, Christina Hammer <
hammerc2 at mail.montclair.edu> wrote:

> Hi,
> I downloaded the newest version of Python on my windows computer and am
> having some trouble using it. I need to save my work because I am using it
> for an online class and am going to have to send it to my professor. But I
> cannot access a tool bar that would allow me to save it. I'm not sure if
> someone can help me with this.
> Thank you
> Christina Hammer
> _______________________________________________
> 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 Apr 13 13:51:48 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 13 Apr 2017 18:51:48 +0100
Subject: [Tutor] creating .json files
In-Reply-To: <CAM-E2X5DArgEYQrGM_kVpzWdmpvSwQRnmcLuc72N8B1TQjbdfQ@mail.gmail.com>
References: <CAM-E2X5DArgEYQrGM_kVpzWdmpvSwQRnmcLuc72N8B1TQjbdfQ@mail.gmail.com>
Message-ID: <ocodre$i6s$1@blaine.gmane.org>

On 13/04/17 17:32, Rafael Knuth wrote:
> Is there a way to split these two into separate steps:
> a) creating a .json file
> b) manipulating it (a, r, w ...)

Of course.

> What if I just wanted to create a .json file and do nothing with it?
> 
> import json
> file_name = "my_numbers.json"
> 
> The above does not do the job. What am I getting wrong here? Thanks.

The above creates a variable called file_name that stores a string.
It has nothing to do with any files.

You need to open the file to create it:

with open(file_name,'w') as json_file: pass

Will open a new file and immediately close it again.

You could do the same explicitly with

json_file = open(file_name,'w')
json_file.close()

Remember that variable names are just labels for your benefit.
The fact that you call it file_name means nothing to Python,
you might as well call it xcdseqplrtyg123 so far as Python is concerned,
its just a lablel. The name is only meaningful to
you (and possibly to other human readers).

Similarly, although your string looks like a file name to
a human reader, to Python it's just a string of characters.
Python cannot draw any meaning from that.

Finally, the code above creates a new file called my_numbers.json
But it is an empty file and is NOT a json file, despite the name.
It only becomes a json file once you add some json data to it.
open() creates text files, it has no understanding of what the
data you write to those files means.

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 s.molnar at sbcglobal.net  Thu Apr 13 15:41:09 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Thu, 13 Apr 2017 15:41:09 -0400
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
Message-ID: <58EFD455.6070902@sbcglobal.net>

I am attempting to port a program that I wrote about 20 years ago from 
FORTRAN to Python.  So far, I have bumbled my way to the point that I 
can get all of the input data resulting from a quantum mechanical 
calculation of a very simple organic molecule in to a Python program, 
but am encountering problems with processing the data.

I have an list generated by:   s = np.linspace(start,finish,points)

and an array D:

  [ 0.          2.059801    3.60937686  3.32591826  2.81569212]
  [ 2.059801    0.          4.71452879  4.45776445  4.00467382]
  [ 3.60937686  4.71452879  0.          5.66500917  5.26602175]
  [ 3.32591826  4.45776445  5.66500917  0.          5.02324896]
  [ 2.81569212  4.00467382  5.26602175  5.02324896  0.        ]

Now I can multiply the Array by one element of the list:

s2 = 1.100334448160535050  (The first non-zero list element.)
s2_D = s2*np.array(D)

which results in:

  [ 0.          2.26647     3.97152169  3.65962243  3.09820303]
  [ 2.26647     0.          5.18755844  4.90503178  4.40648056]
  [ 3.97152169  5.18755844  0.          6.23340474  5.79438514]
  [ 3.65962243  4.90503178  6.23340474  0.          5.52725387]
  [ 3.09820303  4.40648056  5.79438514  5.52725387  0.        ]

I checked this, rather laboriously, in a spreadsheet.

However, what I want to do is multiply each element ob D by each element 
of s and sum all of the products.

I have Goggled quite a bit, but have not found anything too awfully useful.

Any pointers in the right direction will be much appreciated.

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 steve at pearwood.info  Thu Apr 13 20:42:55 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 14 Apr 2017 10:42:55 +1000
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
In-Reply-To: <58EFD455.6070902@sbcglobal.net>
References: <58EFD455.6070902@sbcglobal.net>
Message-ID: <20170414004255.GH9464@ando.pearwood.info>

On Thu, Apr 13, 2017 at 03:41:09PM -0400, Stephen P. Molnar wrote:

> I have an list generated by:   s = np.linspace(start,finish,points)
> 
> and an array D:
> 
>  [ 0.          2.059801    3.60937686  3.32591826  2.81569212]
>  [ 2.059801    0.          4.71452879  4.45776445  4.00467382]
>  [ 3.60937686  4.71452879  0.          5.66500917  5.26602175]
>  [ 3.32591826  4.45776445  5.66500917  0.          5.02324896]
>  [ 2.81569212  4.00467382  5.26602175  5.02324896  0.        ]

Some advice for when you ask for help: we're volunteers, not paid to 
work on your problem, so the easier you make it for us, the more likely 
you will get a good answer.

Start off by simplifying the problem. Do you really need a 5x5 array 
with so many decimal places just to ask the question? Probably not. A 
2x2 array will probably demonstrate the question just as well, and be 
MUCH easier for us to read and type.

What code did you use to create D? It is better to show us that rather 
than just the output of what D looks like. I've tried various things, 
and I cannot duplicate the output that you show. That means I cannot 
tell if I'm working with the same data type as you.

My *guess* is that you did something like this to get D:

py> D = np.array([[1.5, 2.5], [3.5, 4.5]])
py> print D
[[ 1.5  2.5]
 [ 3.5  4.5]]

but I can't be sure, and of course I have no idea what the mystery list 
"s" contains, because you don't tell us. So I'm working in the dark.


> However, what I want to do is multiply each element ob D by each element 
> of s and sum all of the products.

Can you give us an example? This is ambiguous, it could mean either of 
*at least* two things.

(1) Take each element of D in turn, and multiply by the corresponding 
element of s. Here is an example:

D = [[ 1  2 ]
     [ 3  4 ]]

s = [10 20 30 40]

So you want:

1*10 + 2*20 + 3*30 + 4*40


(2) Take each element of D in turn, and multiply by each of the elements 
of s. Using the same examples for D and s:

( 1*10 + 1*20 + 1*30 + 1*40 + 
  2*10 + 2*20 + 2*30 + 2*40 + 
  3*10 + 3*20 + 3*30 + 3*40 + 
  4*10 + 4*20 + 4*30 + 4*40 )


Which do you want?

Remember, the better the question you ask, the better the answers we can 
give.



-- 
Steve

From rafael.knuth at gmail.com  Fri Apr 14 04:09:01 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Fri, 14 Apr 2017 10:09:01 +0200
Subject: [Tutor] creating .json files
In-Reply-To: <ocodre$i6s$1@blaine.gmane.org>
References: <CAM-E2X5DArgEYQrGM_kVpzWdmpvSwQRnmcLuc72N8B1TQjbdfQ@mail.gmail.com>
 <ocodre$i6s$1@blaine.gmane.org>
Message-ID: <CAM-E2X4Q1FuMJ7bqPDbMnBzxQLDzznTYGCYtmX+_chCUwae5_g@mail.gmail.com>

> You need to open the file to create it:

Ok, got you. Thanks, Alan!

From wimberrelkamp at gmail.com  Fri Apr 14 01:37:50 2017
From: wimberrelkamp at gmail.com (Wim Berrelkamp)
Date: Fri, 14 Apr 2017 07:37:50 +0200
Subject: [Tutor] Fwd: Startup Python
In-Reply-To: <CAFLus-errs6bXRLdsmk+ApaosjPB10h+9sii-0eeKdmC+wEt6w@mail.gmail.com>
References: <CAFLus-errs6bXRLdsmk+ApaosjPB10h+9sii-0eeKdmC+wEt6w@mail.gmail.com>
Message-ID: <CAFLus-eino4bxRJEpJk5f5xxPrQBNLx8A892UBZmQMVH9PJgLw@mail.gmail.com>

Dear Alan Gauld,

Pure by co?ncedent I found your answer to me on the internet at
http://code.activestate.com/lists/python-tutor/109848/
There was no answer on my e-mail account.
Your answer works !
Thanks for that !

Regards,
Wim Berrelkamp
Groningen, The Netherlands

On 12/04/17 13:47, Wim Berrelkamp wrote:

>>>> a=2

Here you assign the number 2 to 'a'

>>>> d=a+4>>>> print(d)> 6> a=input('-->' )

Here you assign whatever character(s) the user types to 'a'.
The fact that it looks like 2 doesn't change the fact that it
is really the character '2'. So you need to convert it to
a number using either int() or float()

a = int(input('-->'))
or
a = float(input('-->'))

> print(a)> d=a+4> print(d)> > I tried to use float(), but nothing works.>
What am I doing wrong ?

I don't know, because you don't show us how you tried to
use float(), but if you apply it as shown above it
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

---------- Forwarded message ----------
From: Wim Berrelkamp <wimberrelkamp at gmail.com>
Date: 2017-04-12 14:47 GMT+02:00
Subject: Startup Python
To: tutor at python.org


Dear Tutor,

In earlier days I programmed a lot with Quick Basic in DOS.
Now I retiered, I hoped to have Python as a platform.
So I installed it and saw a lot of simmularity with Basic.

I hope you can help me with the following, which should not be difficult,
but I cannot find the solution.

When I type this:

>>> a=2
>>> d=a+4
>>> print(d)
6

I got the correct answer.

When I try this to run it in a Module:

a=input('-->' )
print(a)
d=a+4
print(d)

I get this as a result:


input test.py
-->2
2
Traceback (most recent call last):
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python36\Lib\idlelib\input
test.py", line 3, in <module>
    d=a+4
TypeError: must be str, not int
>>>

I receive this message.

I tried to use float(), but nothing works.
What am I doing wrong ?

Thanks in advance !
Regards,
Wim Berrelkamp
Groningen, The Netherlands

From __peter__ at web.de  Fri Apr 14 04:21:13 2017
From: __peter__ at web.de (Peter Otten)
Date: Fri, 14 Apr 2017 10:21:13 +0200
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
References: <58EFD455.6070902@sbcglobal.net>
Message-ID: <ocq0pm$s48$1@blaine.gmane.org>

Stephen P. Molnar wrote:

> However, what I want to do is multiply each element ob D by each element
> of s and sum all of the products.

If you *really* want this: 

sum_of_all_products = s.sum() * D.sum()

example:

s = [a b c]

D = [[a1 a2]
     [a3 a4]]

a*a1 + a*a2 + a*a3 + a*a4 = a * D.sum()

d := D.sum()
a*d + b*d + c*d = s.sum() * d

Even if that's what you want you should heed Steven's advice.





From s.molnar at sbcglobal.net  Fri Apr 14 08:41:38 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Fri, 14 Apr 2017 08:41:38 -0400
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
In-Reply-To: <ocq0pm$s48$1@blaine.gmane.org>
References: <58EFD455.6070902@sbcglobal.net> <ocq0pm$s48$1@blaine.gmane.org>
Message-ID: <58F0C382.4010609@sbcglobal.net>

On 04/14/2017 04:21 AM, Peter Otten wrote:
> Stephen P. Molnar wrote:
>
>> However, what I want to do is multiply each element ob D by each element
>> of s and sum all of the products.
>
> If you *really* want this:
>
> sum_of_all_products = s.sum() * D.sum()
>
> example:
>
> s = [a b c]
>
> D = [[a1 a2]
>       [a3 a4]]
>
> a*a1 + a*a2 + a*a3 + a*a4 = a * D.sum()
>
> d := D.sum()
> a*d + b*d + c*d = s.sum() * d
>
> Even if that's what you want you should heed Steven's advice.
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
Thanks for the replies to my message.

First of all, allow me to apologize for the imprecise nature of my request.

Then I want t assure everyone that I am not asking someone else to write 
a program for me, I am not a student with a homework problem.

Rather as I wrote in my email I am attempting to port a program from 
FORTRAN to Python.

The equation that I a want to evaluate (the one that I programmed in 
FORTRAN) is equation (7) in the attached scan of one of the pages of

Stephen P. Molnar and James W. King, Theory and Applications of the 
Integrated Molecular Transform and the Normalized Molecular Moment 
Structure Descriptors: QSAR and QSPR Paradigms, Int. J Quantum Chem., 
85, 662 (2001).

What I have managed to do so far is:

import numpy as np
import numpy, pandas, scipy.spatial.distance as dist


start=1
finish=31
points=300
s = np.linspace(start,finish,points) #300 points between 1.0 and 31.0

name = input("Enter Molecule ID: ")
name = str(name)
name_in = name+'.dat'

df = pandas.read_table(name_in, skiprows=2, sep=" ", 
skipinitialspace=True)
mass_data = numpy.array(df["MASS"])
print('MASS = ',mass_data)
N =  numpy.ma.size(mass_data)
a = numpy.array(df[["X", "Y", "Z"]])
dist.squareform(dist.pdist(a, "euclidean"))
anrows, ancols = np.shape(a)
a_new = a.reshape(anrows, 1, ancols)
diff = a_new - a

D = (diff ** 2).sum(2)
D = np.sqrt(D)

df = pandas.read_table(name_in, skiprows=2, sep=" ", 
skipinitialspace=True)
mass_data = numpy.array(df["MASS"])
print('MASS = ',mass_data)
N =  numpy.ma.size(mass_data)
a = numpy.array(df[["X", "Y", "Z"]])
dist.squareform(dist.pdist(a, "euclidean"))
anrows, ancols = np.shape(a)
a_new = a.reshape(anrows, 1, ancols)
diff = a_new - a

D = (diff ** 2).sum(2)
D = np.sqrt(D)
print(D)

for i in range(numpy.ma.size(mass_data)):
     for j in range(0, N-1):
         for k in range(j+1,N):
             print(D[j,k])

np.savetxt('D(ij)',D,delimiter=' ')

for k in range(0, N-1):

     for k in range(k+1,N):
         A = (mass_data[j]*mass_data[k])

Now, the problem with which I am struggling is the evaluation of the s 
times the r_sub_i_sub_j term.  This should result in 300 floating point 
numbers between 1.0 and 31.0.

I hope that I have eliminated the confusion at this point.

This is, of course, not the end point of my modeling, but what I feel is 
an important result in QSAR studies.

I will be very appreciative of help at this point.

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 alan.gauld at yahoo.co.uk  Fri Apr 14 13:11:34 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 14 Apr 2017 18:11:34 +0100
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
In-Reply-To: <58F0C382.4010609@sbcglobal.net>
References: <58EFD455.6070902@sbcglobal.net> <ocq0pm$s48$1@blaine.gmane.org>
 <58F0C382.4010609@sbcglobal.net>
Message-ID: <ocqvs0$86g$1@blaine.gmane.org>

On 14/04/17 13:41, Stephen P. Molnar wrote:

> The equation that I a want to evaluate (the one that I programmed in 
> FORTRAN) is equation (7) in the attached scan of one of the pages of
> 
> Stephen P. Molnar and James W. King, Theory and Applications of the 
> Integrated Molecular Transform and the Normalized Molecular Moment 
> Structure Descriptors: QSAR and QSPR Paradigms, Int. J Quantum Chem., 
> 85, 662 (2001).

The problem is that you are asking quite technical questions on a
list aimed at beginners to both programming and the Python language. I'd
estimate that only about 10-20% of the readership have
a math/science background of the depth required for your issues.
And a similar few will be familiar with numpy which is not part
of the standard library (although to confuse things there are
Python distros like Anaconda that do include the SciPy stuff,
but the standard library as described on python.org does not.)

As has already been suggested you would get a much higher hit
rate by asking on the SciPy/Numpy support fora:

https://scipy.org/scipylib/mailing-lists.html

On those lists more like 90% of the readers will be in a position
to understand your issues and they will be experienced in using
SciPy and numpy. There is a very good chance that someone there
will understand what the problem is and have already solved it.

We are very happy to answer questions about the core language
and libraries but detailed Numpy stuff really is beyond the
scope of this list.

-- 
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  Fri Apr 14 13:13:48 2017
From: __peter__ at web.de (Peter Otten)
Date: Fri, 14 Apr 2017 19:13:48 +0200
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
References: <58EFD455.6070902@sbcglobal.net> <ocq0pm$s48$1@blaine.gmane.org>
 <58F0C382.4010609@sbcglobal.net>
Message-ID: <ocr00b$kbq$1@blaine.gmane.org>

Stephen P. Molnar wrote:

> The equation that I a want to evaluate (the one that I programmed in
> FORTRAN) is equation (7) in the attached scan of one of the pages of

Sorry Stephen, this is a text-only mailing list / news group. As far as I'm 
concerned there is no attached scan. 

Even if there were I would greatly appreciate if you made an attempt to 
follow the path outlined by Steven D'Aprano, so that to help you solve your 
problem we need not be physicists or know FORTRAN.



From s.molnar at sbcglobal.net  Fri Apr 14 13:24:23 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Fri, 14 Apr 2017 13:24:23 -0400
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
In-Reply-To: <ocqvs0$86g$1@blaine.gmane.org>
References: <58EFD455.6070902@sbcglobal.net> <ocq0pm$s48$1@blaine.gmane.org>
 <58F0C382.4010609@sbcglobal.net> <ocqvs0$86g$1@blaine.gmane.org>
Message-ID: <58F105C7.7020600@sbcglobal.net>

On 04/14/2017 01:11 PM, Alan Gauld via Tutor wrote:
> On 14/04/17 13:41, Stephen P. Molnar wrote:
>
>> The equation that I a want to evaluate (the one that I programmed in
>> FORTRAN) is equation (7) in the attached scan of one of the pages of
>>
>> Stephen P. Molnar and James W. King, Theory and Applications of the
>> Integrated Molecular Transform and the Normalized Molecular Moment
>> Structure Descriptors: QSAR and QSPR Paradigms, Int. J Quantum Chem.,
>> 85, 662 (2001).
>
> The problem is that you are asking quite technical questions on a
> list aimed at beginners to both programming and the Python language. I'd
> estimate that only about 10-20% of the readership have
> a math/science background of the depth required for your issues.
> And a similar few will be familiar with numpy which is not part
> of the standard library (although to confuse things there are
> Python distros like Anaconda that do include the SciPy stuff,
> but the standard library as described on python.org does not.)
>
> As has already been suggested you would get a much higher hit
> rate by asking on the SciPy/Numpy support fora:
>
> https://scipy.org/scipylib/mailing-lists.html
>
> On those lists more like 90% of the readers will be in a position
> to understand your issues and they will be experienced in using
> SciPy and numpy. There is a very good chance that someone there
> will understand what the problem is and have already solved it.
>
> We are very happy to answer questions about the core language
> and libraries but detailed Numpy stuff really is beyond the
> scope of this list.
>

I appreciate the suggestion of the SciPy Mailing List.

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1

From skgoyal721 at gmail.com  Fri Apr 14 14:29:25 2017
From: skgoyal721 at gmail.com (shubham goyal)
Date: Fri, 14 Apr 2017 23:59:25 +0530
Subject: [Tutor] sorted function
Message-ID: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>

Dear mentors,
sorted function is not working when i am trying to sort the list of strings
but list.sort() is working. can you please help me understand.In this
question i was trying to sort the list but first sorting the letter
starting from x and taking them first.

def front_x(words):
  # +++your code here+++
  ls=[]
  ls1=[]
  for str in words:
      if str[0]=='x':
          ls.append(str)
      else:
          ls1.append(str);
  print ls
  print ls1
  sorted(ls)
  sorted(ls1)
  ls.extend(ls1)
  return ls

front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])

Output:['xzz', 'xaa', 'bbb', 'ccc', 'axx']
Output should be:  ['xaa', 'xzz', 'axx', 'bbb', 'ccc']

Thankyou. Sorry for bad writing skills.

From alan.gauld at yahoo.co.uk  Fri Apr 14 19:56:12 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 15 Apr 2017 00:56:12 +0100
Subject: [Tutor] sorted function
In-Reply-To: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>
References: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>
Message-ID: <ocrnil$adj$1@blaine.gmane.org>

On 14/04/17 19:29, shubham goyal wrote:

> sorted function is not working when i am trying to sort the list of strings
> but list.sort() is working. can you please help me understand.

sort() sorts the list "in place". That is it sorts itself.
sorted() returns a sorted copy of the list. It does not
alter the original list

> def front_x(words):
>   ls=[]
>   ls1=[]
>   for str in words:
>       if str[0]=='x':
>           ls.append(str)
>       else:
>           ls1.append(str);
>   sorted(ls)
>   sorted(ls1)

So here you should either do this:

ls.sort()
ls1.sort()

or this:

ls = sorted(ls)
ls1 = sorted(ls1)

In this case I'd suggest the first version is 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 dvnsarma at gmail.com  Fri Apr 14 19:46:50 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Sat, 15 Apr 2017 05:16:50 +0530
Subject: [Tutor] sorted function
In-Reply-To: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>
References: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>
Message-ID: <CAOZcEcfqH7Yy+xPH4QdknxOKzw4MCYDBXGbjytN8UfR9MPyXYg@mail.gmail.com>

Change your code to

def front_x(words):
  # +++your code here+++
  ls=[]
  ls1=[]
  for str in words:
      if str[0]=='x':
          ls.append(str)
      else:
          ls1.append(str);
  print ls
  print ls1
  ls =  sorted(ls)
  ls1 = sorted(ls1)
  ls.extend(ls1)
  return ls

regards,
Sarma.

On Fri, Apr 14, 2017 at 11:59 PM, shubham goyal <skgoyal721 at gmail.com>
wrote:

> Dear mentors,
> sorted function is not working when i am trying to sort the list of strings
> but list.sort() is working. can you please help me understand.In this
> question i was trying to sort the list but first sorting the letter
> starting from x and taking them first.
>
> def front_x(words):
>   # +++your code here+++
>   ls=[]
>   ls1=[]
>   for str in words:
>       if str[0]=='x':
>           ls.append(str)
>       else:
>           ls1.append(str);
>   print ls
>   print ls1
>   sorted(ls)
>   sorted(ls1)
>   ls.extend(ls1)
>   return ls
>
> front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])
>
> Output:['xzz', 'xaa', 'bbb', 'ccc', 'axx']
> Output should be:  ['xaa', 'xzz', 'axx', 'bbb', 'ccc']
>
> Thankyou. Sorry for bad writing skills.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From steve at pearwood.info  Fri Apr 14 20:14:56 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 15 Apr 2017 10:14:56 +1000
Subject: [Tutor] sorted function
In-Reply-To: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>
References: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>
Message-ID: <20170415001455.GK9464@ando.pearwood.info>

On Fri, Apr 14, 2017 at 11:59:25PM +0530, shubham goyal wrote:

>   sorted(ls)
>   sorted(ls1)

Here you sort ls and throw the result away, then you do the same to ls1.

sorted() makes a copy of the list and sorts it. You need to write:

ls = sorted(ls)
ls1 = sorted(ls1)

but even better would be to sort in place:

ls.sort()
ls1.sort()

which doesn't make a copy.



-- 
Steve

From akleider at sonic.net  Fri Apr 14 22:38:31 2017
From: akleider at sonic.net (Alex Kleider)
Date: Fri, 14 Apr 2017 19:38:31 -0700
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <oc0r72$djt$1@blaine.gmane.org>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
 <oc0r72$djt$1@blaine.gmane.org>
Message-ID: <827fd3e0f60af588b8f1d819ca9d97d1@sonic.net>

On 2017-04-04 12:12, Alan Gauld via Tutor wrote:
> On 04/04/17 17:55, Lisa Hasler Waters wrote:
> 
>> A middle school student of mine created a program to calculate simple 
>> and
>> compound interest. He built it in PyCharm EDU using a Mac running 
>> 10.11.6.
>> 
>> He would like to create a GUI to run this program. Please, can you 
>> advise
>> on how he could build this?
> 
> He could use Tkinter, or he could create an HTML screen and
> write a small server using a Framework like Flask.
> 
> Whatever he does he will need to dsepsarate his UI from his
> logic - a good programming skill regardless of UI.

Can anyone suggest a good tutorial that explains exactly what this means 
and how to achieve it?
(separate UI from logic I mean.)

From alan.gauld at yahoo.co.uk  Sat Apr 15 04:04:44 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 15 Apr 2017 09:04:44 +0100
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <827fd3e0f60af588b8f1d819ca9d97d1@sonic.net>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
 <oc0r72$djt$1@blaine.gmane.org> <827fd3e0f60af588b8f1d819ca9d97d1@sonic.net>
Message-ID: <ocsk6m$8c5$1@blaine.gmane.org>

On 15/04/17 03:38, Alex Kleider wrote:

>> Whatever he does he will need to separate his UI from his
>> logic - a good programming skill regardless of UI.
> 
> Can anyone suggest a good tutorial that explains exactly what this means 
> and how to achieve it?
> (separate UI from logic I mean.)

I don't know of a tutorial as such but the principles are enshrined
in the Model-View-Controller (MVC) design pattern and there are lots
of articles and tutorials on that. One caveat is that there are
almost as many variations on MVC as there are articles so you can expect
some contradiction in the details. That's ok, just focus
on the big ideas.

At the most basic just do as I suggested in the post. Identify the
functions that do the work(the logic) and make sure they take all
of their input via parameters and deliver a result back to the
caller with no UI (eg input() or print()) statements inside
the function.

Then write the code that interacts with the user as a separate
function which calls the logic functions as needed. You should
be able to put the core functions into a separate module and
import that into the UI module/main program. That's quite a
good check that you have made your logic reusable.

This is good practice for all programming projects but its
essential for GUI and Web projects.

Finally, if you can find a copy of my recent book "Python Projects"
there is a rolling project within that which demonstrates how
the same logic code can be used to build a CLI, a GUI and a
Web app. [ In fact it goes even further by demonstrating how
to break an app into 3 tiers - data, logic and UI - which
is industry best practice, but usually overkill for small
projects.]

-- 
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 gvmcmt at gmail.com  Sat Apr 15 03:03:48 2017
From: gvmcmt at gmail.com (Sri Kavi)
Date: Sat, 15 Apr 2017 12:33:48 +0530
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <oc0r72$djt$1@blaine.gmane.org>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
 <oc0r72$djt$1@blaine.gmane.org>
Message-ID: <CADEQGhYjaXk_GFSccb6Nw8i0k8K_=9E-Z4gC1Hm_RSCFnf_OpA@mail.gmail.com>

On Wed, Apr 5, 2017 at 12:42 AM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 04/04/17 17:55, Lisa Hasler Waters wrote:
>
> > A middle school student of mine created a program to calculate simple and
> > compound interest. He built it in PyCharm EDU using a Mac running
> 10.11.6.
> >
> > He would like to create a GUI to run this program. Please, can you advise
> > on how he could build this?
>
> He could use Tkinter, or he could create an HTML screen and
> write a small server using a Framework like Flask.
>
> Whatever he does he will need to dsepsarate his UI from his
> logic - a good programming skill regardless of UI.
>
> So his first step should be to create a CLI UI on top of
> his existing code such that none of hi functions contain
> print() or input() statements, they should all be in
> new UI code.
>
> The next step is to convert it to event driven style.
> For this code that should almost be a done deal.
>
> Finally decide on his GUI/Web framework and do a tutorial
> to get up to speed and fit his new event-driven backend
> code into that.
>
> > Here is his code:
> >
> > def simple(m, t, r):
> >     r = r/100
> >     print("The interest is {} and the total is {} ".format(r*m*t,
> m+r*m*t))
>
> Should return a value not print a message
>
> > def compound(m, t, r):
> >     morg = m
> >     r = r/100
> >     for x in range(0, t):
> >         m = m*r+m
> >     print("The interest is {} and the total is {} if compounded
> > yearly.".format(m-morg, m))
> >     m = morg
> >     r = r/12
> >     for x in range(0, t*12):
> >         m = m*r+m
> >     print("The interest is {} and the total is {} if compounded
> > monthly.".format(m-morg, m))
> >
>
> Possiobly should be two separate methods, and definitely
> should be returning values not printing stuff.
>
>
> > choice = str(input("Would you like to use simple or compound interest?
> "))
> > m = int(input("Input the amount of money you would like to deposit
> > (don't use the $ symbol): "))
> > t = int(input("Input the amount of time you will be keeping your money
> > in the bank (in years): "))
> > r = int(input("Input the interest rate the bank offers (don't use the
> > % symbol): "))
> >
> > if choice == 'simple':
> >     simple(m, t, r)
> > elif choice == 'compound':
> >     compound(m, t, r)
> > else:
> >     print("Your input is invalid")
>
> This needs to turn into a UI event loop which it almost is
> but with no loop and no exit option.
>
>

I?m feeling inspired by Alan Gauld?s reply and using this as an opportunity
to learn Flask.  Thank you, Alan. I have written a similar calculator
program and created two separate versions of CLI UI using argparse and
Google?s Python Fire. I?m trying to create an HTML screen and use my Python
script that imports the Flask module which will pass data to the HTML file.
When the web page is loaded, it should run the code associated with the
page.


Once I can make this work, I will submit it for your kind comments :)

Sri

From skgoyal721 at gmail.com  Sat Apr 15 02:35:51 2017
From: skgoyal721 at gmail.com (shubham goyal)
Date: Sat, 15 Apr 2017 12:05:51 +0530
Subject: [Tutor] sorted function
In-Reply-To: <20170415001455.GK9464@ando.pearwood.info>
References: <CAN1d+1-tBt5GgTBMgCo=j7W-vTgE2G6_2gb3A9g_7TJc7dza4w@mail.gmail.com>
 <20170415001455.GK9464@ando.pearwood.info>
Message-ID: <CAN1d+1-Nbx3ovA8p8zm0izKj0XhXxNCPSDq61CWovpyWD505sQ@mail.gmail.com>

Thankyou. got it.

On Sat, Apr 15, 2017 at 5:44 AM, Steven D'Aprano <steve at pearwood.info>
wrote:

> On Fri, Apr 14, 2017 at 11:59:25PM +0530, shubham goyal wrote:
>
> >   sorted(ls)
> >   sorted(ls1)
>
> Here you sort ls and throw the result away, then you do the same to ls1.
>
> sorted() makes a copy of the list and sorts it. You need to write:
>
> ls = sorted(ls)
> ls1 = sorted(ls1)
>
> but even better would be to sort in place:
>
> ls.sort()
> ls1.sort()
>
> which doesn't make a copy.
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From timeofsands at gmail.com  Fri Apr 14 22:17:29 2017
From: timeofsands at gmail.com (Palm Tree)
Date: Sat, 15 Apr 2017 06:17:29 +0400
Subject: [Tutor] bracket issue
In-Reply-To: <CAGC2tijNn8w_nyNp=AyGvAoB_jF8X8j=Hg6vOvJsUEOoRrnsNw@mail.gmail.com>
References: <CAGC2tijHcjX+p+1d8n_CgRGo-G=0f0-Mf2K64XsKFQ7UB-6vfQ@mail.gmail.com>
 <CAGC2tihc65YjTFfuFGp8k4_3up7eCTRaQ9X+XWPmpJmQt9UskQ@mail.gmail.com>
 <CAGC2tihoA7vv9tbJVXBU_be2wBvJ4-N_4dMN4cxtL84P6csYnA@mail.gmail.com>
 <CAGC2tii4AC-FsaJ1wgx4bQO4S7-nt0pqnG5OWjDMwzO=d=kpxA@mail.gmail.com>
 <CAGC2tii3SScP-bdUjf784_bSa=00WSQnrm3x74xdDGJCGjKF3w@mail.gmail.com>
 <CAGC2tii_SqO5=caENHyDfrZPzqjRPeTtos-4a6=5sP8xgPmGBw@mail.gmail.com>
 <CAGC2tig7BXJcqZMvmzQzu0_7oEaauoS7nKwLyj7oEPLTSK9CXg@mail.gmail.com>
 <CAGC2tihpPzix=fHqkkdZ-HcVgzf=aAy_97AZ6bxvz0nMG1+soQ@mail.gmail.com>
 <CAGC2tigpsLz7mMBvDM1voVm++wGVzBmG22hboy+EC-9EMhv8qg@mail.gmail.com>
 <CAGC2tiiOiy0WsWvnE34WN20MhSQ75WXp0GQyfpUF0D8KWDgWhw@mail.gmail.com>
 <CAGC2tijs=ZrLdLRZMVmUF5HppxRFDfxUMjmk__c+z0OKfE3SVA@mail.gmail.com>
 <CAGC2tijz2dTyDp_NtWj3C51+B3a8tT-GSakDfx3+mhTaHRZVPQ@mail.gmail.com>
 <CAGC2tih9=Sw+Ww1Ru73syf-FPk4p50XDSbFQVtqE0dqDLi15BA@mail.gmail.com>
 <CAGC2tigc9r6Nfp0vsOeChHQe84kKbKU9_EeOiJ8uUs_mTzSvQA@mail.gmail.com>
 <CAGC2tigis_c55L_H=jxwatDTcWSa16Z-iL_jY9kGPriBQ7a7_w@mail.gmail.com>
 <CAGC2tij9fpABrzmeCKdOt_KdrRo-yyUwJTuSpQJOCVAhRnP93g@mail.gmail.com>
 <CAGC2tihG3iq_WDwVdNR6wcjG_oUPQQbAxKBT_VbNUO20EXj5+g@mail.gmail.com>
 <CAGC2tigy0SXNz4F798xNo=Yot7EJx4Ddig-egA8kGtJnvmhG7w@mail.gmail.com>
 <CAGC2tijNn8w_nyNp=AyGvAoB_jF8X8j=Hg6vOvJsUEOoRrnsNw@mail.gmail.com>
Message-ID: <CAGC2tiheAzE3tPvnNbSpFjQAEKsb07bjwUH=BcNPxFcDJMrhcA@mail.gmail.com>

hi all. i'm trying to write a simple program. i'm using python 3.4

let us say i have

s="2*3+3(8-4(5+6+9))+2+3+3(4/4)"

i want to find expression enclosed in brackets.

i want outputs to be like:
(8-4(5+6+9))
(5+6+9)
(4/4)

i've tried where >>>> denotes an indentation level :

#first part
sbracket=[ ]
ebracket=[ ]
for i in range(len(s)):
>>>>global sbracket
>>>>global ebracket
>>>>if f[i] == "(":
>>>>>>>>sbracket.append(i)
>>>>elif f[i] == ")":
>>>>>>>>ebracket.append(i)

#second part
for i in range(len(sbracket)):
>>>>print(f[sbracket[i]:ebracket[i]])

however, the above code works well as long as there are no nested brackets
like

s="(1+2)(2+3)"

but fails as soon as

s="((3+2))2"

prior to that i wrote it like:
for i in range(len(f)):
>>>>if f[i] == "(":
>>>>>>>>sbracket.append(i)
>>>>>>>>for x in range(len(f)):
>>>>>>>>>>>>if f[i+x]==")":
>>>>>>>>>>>>>>>>ebracket.append(x)
>>>>>>>>>>>>>>>>break

but that too failed to output correctly

note : i'd like an answer involving recursion if possible

From aero.maxx.d at gmail.com  Sat Apr 15 04:33:31 2017
From: aero.maxx.d at gmail.com (Aero Maxx D)
Date: Sat, 15 Apr 2017 09:33:31 +0100
Subject: [Tutor] Using Modules
Message-ID: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>

Hi everyone,

I'm very very new to Python, and trying to learn and I'm struggling with the import statements.

I understand they are importing modules that I can then use in my code, what I'm struggling with though is how do I find out which modules I need to use to do any given task?

I do have a programming background in that I know PHP however this is a scripting language, and one that doesn't require me to import modules or anything, can easily just look at the functions available on the php.net website and carry on as normal.

With Python I'm not finding which modules I need if any as easy as that, mainly due to the vast number of modules available.

I'd like to start with something that in my mind is relatively simple in php, so I thought I'd connect to a MySQL database read what was in a table and insert some data into the table.

I've done some googling and read some books, the book mentioned using import dbm, however I understand this isn't for MySQL but my problem is the book glosses over the import statement and just says use this, but gives no explanation as to why I'm using that and/or how to find out that's what I should use.  Googling found some forum posts saying to use MySQLdb.

I'm wanting to learn Python properly and find things out myself, without relying on someone to of posted on a blog or a forum who may have done something similar to what I may be trying to do at that particular time, and then just blindly follow their example and use the same modules without an understanding why I'm using those modules, or using modules that I'm actually not using in the code.

Sorry for the long email, I didn't initially intend or expect it to be this long.

Thanks,
Daniel

From joel.goldstick at gmail.com  Sat Apr 15 08:48:41 2017
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sat, 15 Apr 2017 08:48:41 -0400
Subject: [Tutor] Using Modules
In-Reply-To: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>
References: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>
Message-ID: <CAPM-O+wA3JpeuX_tZBh_P0xHA1tHP=8EyUQnX6sdF8-Fnj+dhg@mail.gmail.com>

On Sat, Apr 15, 2017 at 4:33 AM, Aero Maxx D <aero.maxx.d at gmail.com> wrote:
> Hi everyone,
>
> I'm very very new to Python, and trying to learn and I'm struggling with the import statements.
>
> I understand they are importing modules that I can then use in my code, what I'm struggling with though is how do I find out which modules I need to use to do any given task?
>
> I do have a programming background in that I know PHP however this is a scripting language, and one that doesn't require me to import modules or anything, can easily just look at the functions available on the php.net website and carry on as normal.
>
> With Python I'm not finding which modules I need if any as easy as that, mainly due to the vast number of modules available.
>
> I'd like to start with something that in my mind is relatively simple in php, so I thought I'd connect to a MySQL database read what was in a table and insert some data into the table.
>
> I've done some googling and read some books, the book mentioned using import dbm, however I understand this isn't for MySQL but my problem is the book glosses over the import statement and just says use this, but gives no explanation as to why I'm using that and/or how to find out that's what I should use.  Googling found some forum posts saying to use MySQLdb.
>
> I'm wanting to learn Python properly and find things out myself, without relying on someone to of posted on a blog or a forum who may have done something similar to what I may be trying to do at that particular time, and then just blindly follow their example and use the same modules without an understanding why I'm using those modules, or using modules that I'm actually not using in the code.
>
> Sorry for the long email, I didn't initially intend or expect it to be this long.
>
> Thanks,
> Daniel
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Look at the tutorials on python.org for a start

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

From alan.gauld at yahoo.co.uk  Sat Apr 15 09:05:56 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 15 Apr 2017 14:05:56 +0100
Subject: [Tutor] bracket issue
In-Reply-To: <CAGC2tiheAzE3tPvnNbSpFjQAEKsb07bjwUH=BcNPxFcDJMrhcA@mail.gmail.com>
References: <CAGC2tijHcjX+p+1d8n_CgRGo-G=0f0-Mf2K64XsKFQ7UB-6vfQ@mail.gmail.com>
 <CAGC2tihpPzix=fHqkkdZ-HcVgzf=aAy_97AZ6bxvz0nMG1+soQ@mail.gmail.com>
 <CAGC2tigpsLz7mMBvDM1voVm++wGVzBmG22hboy+EC-9EMhv8qg@mail.gmail.com>
 <CAGC2tiiOiy0WsWvnE34WN20MhSQ75WXp0GQyfpUF0D8KWDgWhw@mail.gmail.com>
 <CAGC2tijs=ZrLdLRZMVmUF5HppxRFDfxUMjmk__c+z0OKfE3SVA@mail.gmail.com>
 <CAGC2tijz2dTyDp_NtWj3C51+B3a8tT-GSakDfx3+mhTaHRZVPQ@mail.gmail.com>
 <CAGC2tih9=Sw+Ww1Ru73syf-FPk4p50XDSbFQVtqE0dqDLi15BA@mail.gmail.com>
 <CAGC2tigc9r6Nfp0vsOeChHQe84kKbKU9_EeOiJ8uUs_mTzSvQA@mail.gmail.com>
 <CAGC2tigis_c55L_H=jxwatDTcWSa16Z-iL_jY9kGPriBQ7a7_w@mail.gmail.com>
 <CAGC2tij9fpABrzmeCKdOt_KdrRo-yyUwJTuSpQJOCVAhRnP93g@mail.gmail.com>
 <CAGC2tihG3iq_WDwVdNR6wcjG_oUPQQbAxKBT_VbNUO20EXj5+g@mail.gmail.com>
 <CAGC2tigy0SXNz4F798xNo=Yot7EJx4Ddig-egA8kGtJnvmhG7w@mail.gmail.com>
 <CAGC2tijNn8w_nyNp=AyGvAoB_jF8X8j=Hg6vOvJsUEOoRrnsNw@mail.gmail.com>
 <CAGC2tiheAzE3tPvnNbSpFjQAEKsb07bjwUH=BcNPxFcDJMrhcA@mail.gmail.com>
Message-ID: <oct5re$81b$1@blaine.gmane.org>

On 15/04/17 03:17, Palm Tree wrote:

> s="2*3+3(8-4(5+6+9))+2+3+3(4/4)"
> 
> i want to find expression enclosed in brackets.
> 
> i want outputs to be like:
> (8-4(5+6+9))
> (5+6+9)
> (4/4)
> 

You probably could do it with some fancy regex but personally
I'd investigate a proper text parser. There is a module to
support that in the standard library but I can't recall its
name, however you need a bit of background in parsing to use
it. Google(or bing or...) is your friend.

If you really want to do it manually you need to count the
brackets going in and then back out. So as you scan your
sample data the counter will go 0,1,2,1,0,1,0

If you store those counts along with the string index where
they change you can use that to slice your string accordingly.
Its all a bit messy but 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  Sat Apr 15 09:09:51 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 15 Apr 2017 14:09:51 +0100
Subject: [Tutor] Using Modules
In-Reply-To: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>
References: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>
Message-ID: <oct62o$pcs$1@blaine.gmane.org>

On 15/04/17 09:33, Aero Maxx D wrote:

> With Python I'm not finding which modules I need 

Search for the functionality within the python.org site.
The documentation tells you which module you are looking for.

> ...I thought I'd connect to a MySQL database 

There is a standard DB interface in Python for SQL based data.
But there is a separate module for each database. The idea
being that you should theoretically be able to write the code
that uses the database and then change the database from, say,
MySql to Oracle by just changing the import.

In practice it's not quite that easy but you should be able
to do it with only minor tweaks - usually around the login process.

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 __peter__ at web.de  Sat Apr 15 10:34:52 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 15 Apr 2017 16:34:52 +0200
Subject: [Tutor] Using Modules
References: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>
Message-ID: <octb26$1ql$3@blaine.gmane.org>

Aero Maxx D wrote:



From __peter__ at web.de  Sat Apr 15 10:45:53 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 15 Apr 2017 16:45:53 +0200
Subject: [Tutor] bracket issue
Message-ID: <octbmr$1ql$6@blaine.gmane.org>

Palm Tree wrote:

> hi all. i'm trying to write a simple program. i'm using python 3.4
> 
> let us say i have
> 
> s="2*3+3(8-4(5+6+9))+2+3+3(4/4)"
> 
> i want to find expression enclosed in brackets.
> 
> i want outputs to be like:
> (8-4(5+6+9))
> (5+6+9)
> (4/4)
> note : i'd like an answer involving recursion if possible

No recursion, but a stack managed manually:

>>> s = "2*3+3(8-4(5+6+9))+2+3+3(4/4)"
>>> stack = []
>>> for i, c in enumerate(s):
...     if c == "(":
...         stack.append(i)
...     elif c == ")":
...         print(s[stack.pop():i+1])
... 
(5+6+9)
(8-4(5+6+9))
(4/4)

The order is determined by the closing parenthesis, you could sort if you 
don't want that.

I did not find a convincing translation using recursion, but I'll give one 
anyway:

def find_closing(s):
    i = c = None
    pairs = enumerate(s)
    def step(start=None):
        nonlocal i, c
        for i, c in pairs:
            if c == "(":
                step(i)
            elif c == ")":
                if start is not None:
                    print(s[start:i+1])
                return
    step()


From gvmcmt at gmail.com  Sat Apr 15 09:03:38 2017
From: gvmcmt at gmail.com (Sri Kavi)
Date: Sat, 15 Apr 2017 18:33:38 +0530
Subject: [Tutor] Using Modules
In-Reply-To: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>
References: <DBA65D1B-C8CF-4A48-904F-41B4DC1184F6@gmail.com>
Message-ID: <CADEQGhZe9FqZdO0bbGVAYd7vAm02rGRS0xH6KVOZ=Rfii-z7bA@mail.gmail.com>

Hi,

Start with the tutorial at https://docs.python.org/3/tutorial/

It includes Brief Tour of the Standard Library:

https://docs.python.org/3/tutorial/stdlib.html
https://docs.python.org/3/tutorial/stdlib2.html

Hope that helps.


Sri

On Sat, Apr 15, 2017 at 2:03 PM, Aero Maxx D <aero.maxx.d at gmail.com> wrote:

> Hi everyone,
>
> I'm very very new to Python, and trying to learn and I'm struggling with
> the import statements.
>
> I understand they are importing modules that I can then use in my code,
> what I'm struggling with though is how do I find out which modules I need
> to use to do any given task?
>
> I do have a programming background in that I know PHP however this is a
> scripting language, and one that doesn't require me to import modules or
> anything, can easily just look at the functions available on the php.net
> website and carry on as normal.
>
> With Python I'm not finding which modules I need if any as easy as that,
> mainly due to the vast number of modules available.
>
> I'd like to start with something that in my mind is relatively simple in
> php, so I thought I'd connect to a MySQL database read what was in a table
> and insert some data into the table.
>
> I've done some googling and read some books, the book mentioned using
> import dbm, however I understand this isn't for MySQL but my problem is the
> book glosses over the import statement and just says use this, but gives no
> explanation as to why I'm using that and/or how to find out that's what I
> should use.  Googling found some forum posts saying to use MySQLdb.
>
> I'm wanting to learn Python properly and find things out myself, without
> relying on someone to of posted on a blog or a forum who may have done
> something similar to what I may be trying to do at that particular time,
> and then just blindly follow their example and use the same modules without
> an understanding why I'm using those modules, or using modules that I'm
> actually not using in the code.
>
> Sorry for the long email, I didn't initially intend or expect it to be
> this long.
>
> Thanks,
> Daniel
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From rafael.knuth at gmail.com  Sat Apr 15 10:33:20 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Sat, 15 Apr 2017 16:33:20 +0200
Subject: [Tutor] understanding code testing
Message-ID: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>

can anyone point me to good learning resources on this subject?
(python 3)

From joel.goldstick at gmail.com  Sat Apr 15 13:10:04 2017
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sat, 15 Apr 2017 13:10:04 -0400
Subject: [Tutor] understanding code testing
In-Reply-To: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
References: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
Message-ID: <CAPM-O+yidYw0XHUesJ85AvEapRpCr2X_oVzoixvV1v+bLv9ghw@mail.gmail.com>

On Sat, Apr 15, 2017 at 10:33 AM, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> can anyone point me to good learning resources on this subject?
> (python 3)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

This looks like a good book: http://www.obeythetestinggoat.com/


-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

From leamhall at gmail.com  Sat Apr 15 13:48:32 2017
From: leamhall at gmail.com (leam hall)
Date: Sat, 15 Apr 2017 13:48:32 -0400
Subject: [Tutor] understanding code testing
In-Reply-To: <CAPM-O+yidYw0XHUesJ85AvEapRpCr2X_oVzoixvV1v+bLv9ghw@mail.gmail.com>
References: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
 <CAPM-O+yidYw0XHUesJ85AvEapRpCr2X_oVzoixvV1v+bLv9ghw@mail.gmail.com>
Message-ID: <CACv9p5qX9f=DAUXgBbr1H-AyLKUezZV-NQenDmdfKqzntEn0NA@mail.gmail.com>

For python specific I'd look at unittest:
https://docs.python.org/3/library/unittest.html?highlight=test#module-unittest

For testing in general then "Test Driven Development By Example" by Kent
Beck. Examples are in Java but he explains the theory.

I've been on a testing kick lately and am slogging through Binder's
"Testing Object Oriented Systems". It's a great book, well written, but
still a bit over my head. I wasn't a math whiz in school.

Lots of web pages on testing, and probably some on python TDD if you make
sure it's not focusing on Django. Unless you're doing Django, that is.

Leam

On Sat, Apr 15, 2017 at 1:10 PM, Joel Goldstick <joel.goldstick at gmail.com>
wrote:

> On Sat, Apr 15, 2017 at 10:33 AM, Rafael Knuth <rafael.knuth at gmail.com>
> wrote:
> > can anyone point me to good learning resources on this subject?
> > (python 3)
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
>
> This looks like a good book: http://www.obeythetestinggoat.com/
>
>
> --
> Joel Goldstick
> http://joelgoldstick.com/blog
> http://cc-baseballstats.info/stats/birthdays
> _______________________________________________
> 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  Sat Apr 15 15:17:55 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 15 Apr 2017 20:17:55 +0100
Subject: [Tutor] understanding code testing
In-Reply-To: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
References: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
Message-ID: <octrks$i2h$1@blaine.gmane.org>

On 15/04/17 15:33, Rafael Knuth wrote:
> can anyone point me to good learning resources on this subject?

I'd recommend YouTube as your first port of call.
There are a few python unit test videos but most of
the best stuff is Java focused, but it translates
to Python easily enough.

Once you've watched half a dozen and had a play with
your own code I'd then switch to a web site or book
for the details.

I'd also leave mocking till later, it can be confusing
until you really get to grips with TDD.

-- 
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 Apr 15 19:17:40 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 15 Apr 2017 18:17:40 -0500
Subject: [Tutor] =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
	=?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python?=
	=?utf-8?q?=22?=
Message-ID: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>

In the section

https://docs.python.org/3/library/test.html#writing-unit-tests-for-the-test-package

I have been trying to make sense of the given pointer and code snippet:

<quote>
Try to maximize code reuse. On occasion, tests will vary by something
as small as what type of input is used. Minimize code duplication by
subclassing a basic test class with a class that specifies the input:

class TestFuncAcceptsSequencesMixin:

    func = mySuperWhammyFunction

    def test_func(self):
        self.func(self.arg)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = (1, 2, 3)

When using this pattern, remember that all classes that inherit from
unittest.TestCase are run as tests. The Mixin class in the example
above does not have any data and so can?t be run by itself, thus it
does not inherit from unittest.TestCase.
</quote>

I have tried to implement this in various ways, but cannot overcome a
basic hurdle where I get an argument mismatch.  Following is my
simplest effort to implement the above which does not actually test
anything yet, but demonstrates this mismatch hurdle:

--------------------------------------------------------------------------------------
#!/usr/bin/env python3

def mySuperWhammyFunction(any_input):
    return any_input

import unittest

class TestFuncAcceptsSequencesMixin:

    func = mySuperWhammyFunction

    def test_func(self):
        self.func(self.arg)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = (1, 2, 3)

if __name__ == '__main__':
    unittest.main()
--------------------------------------------------------------------------------------

This gives me the following result:

--------------------------------------------------------------------------------------
> python -m unittest test_super.py
EEE
======================================================================
ERROR: test_func (test_super.AcceptLists)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\Projects\test_super.py", line 13, in test_func
    self.func(self.arg)
TypeError: mySuperWhammyFunction() takes 1 positional argument but 2 were given

======================================================================
ERROR: test_func (test_super.AcceptStrings)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\Projects\test_super.py", line 13, in test_func
    self.func(self.arg)
TypeError: mySuperWhammyFunction() takes 1 positional argument but 2 were given

======================================================================
ERROR: test_func (test_super.AcceptTuples)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\Projects\test_super.py", line 13, in test_func
    self.func(self.arg)
TypeError: mySuperWhammyFunction() takes 1 positional argument but 2 were given

----------------------------------------------------------------------
Ran 3 tests in 0.000s

FAILED (errors=3)
--------------------------------------------------------------------------------------

I suspect that both an object instance and self.arg is getting passed
to mySuperWhammyFunction(), but I am not seeing how the object
instance is getting passed -- if my suspicion is indeed correct.

I also am not truly understanding how this code is working within the
unittest framework.

Help!

TIA!

boB

From alan.gauld at yahoo.co.uk  Sat Apr 15 19:31:50 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 16 Apr 2017 00:31:50 +0100
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
In-Reply-To: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
Message-ID: <ocuagv$5im$1@blaine.gmane.org>

On 16/04/17 00:17, boB Stepp wrote:

> --------------------------------------------------------------------------------------
> #!/usr/bin/env python3
> 
> def mySuperWhammyFunction(any_input):
>     return any_input

This is a simple function, its not bound to an object

> 
> import unittest
> 
> class TestFuncAcceptsSequencesMixin:
> 
>     func = mySuperWhammyFunction
> 
>     def test_func(self):
>         self.func(self.arg)

This is calling self.function which implies a method.

Convert your function to a method and it should work.

> ERROR: test_func (test_super.AcceptLists)
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>   File "c:\Projects\test_super.py", line 13, in test_func
>     self.func(self.arg)
> TypeError: mySuperWhammyFunction() takes 1 positional argument but 2 were given

The missing self parameter...

> I suspect that both an object instance and self.arg is getting passed

Its self.
When you do

object.method()

object gets passed as the first parameter (traditionally
called self) But because your function is not a method
it does not expect a self to be passed.

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 akleider at sonic.net  Sun Apr 16 01:49:40 2017
From: akleider at sonic.net (Alex Kleider)
Date: Sat, 15 Apr 2017 22:49:40 -0700
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <ocsk6m$8c5$1@blaine.gmane.org>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
 <oc0r72$djt$1@blaine.gmane.org> <827fd3e0f60af588b8f1d819ca9d97d1@sonic.net>
 <ocsk6m$8c5$1@blaine.gmane.org>
Message-ID: <e26e8c9102e7e1bb641ec262ff13a282@sonic.net>

On 2017-04-15 01:04, Alan Gauld via Tutor wrote:


> 
> Finally, if you can find a copy of my recent book "Python Projects"
> there is a rolling project within that which demonstrates how
> the same logic code can be used to build a CLI, a GUI and a
> Web app. [ In fact it goes even further by demonstrating how
> to break an app into 3 tiers - data, logic and UI - which
> is industry best practice, but usually overkill for small
> projects.]

Thanks, Alan, for the guidance.  As it happens, I have a copy of your 
Python Projects" book- time to get it off the shelf and have a closer 
look!
Alex

From aaronmyatt at googlemail.com  Sat Apr 15 22:18:17 2017
From: aaronmyatt at googlemail.com (Aaron Myatt)
Date: Sun, 16 Apr 2017 10:18:17 +0800
Subject: [Tutor] understanding code testing
In-Reply-To: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
References: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
Message-ID: <CAAD4-9j6fOEbQYTOVJqAUaBRFXy1zr4s7W0XpXAStuFBAa8+Vg@mail.gmail.com>

My favourite book on testing. It is a pretty thorough walk through of
building a django app that helps you get a feel for the TDD work flow and
red, green, refactor cycle. A rather more practical and real world
applicable introduction to TDD,  in my opinion.

On 16 Apr 2017 12:59 a.m., "Rafael Knuth" <rafael.knuth at gmail.com> wrote:

> can anyone point me to good learning resources on this subject?
> (python 3)
> _______________________________________________
> 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 Apr 16 04:12:24 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 16 Apr 2017 09:12:24 +0100
Subject: [Tutor] understanding code testing
In-Reply-To: <CAAD4-9j6fOEbQYTOVJqAUaBRFXy1zr4s7W0XpXAStuFBAa8+Vg@mail.gmail.com>
References: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
 <CAAD4-9j6fOEbQYTOVJqAUaBRFXy1zr4s7W0XpXAStuFBAa8+Vg@mail.gmail.com>
Message-ID: <ocv911$b1r$1@blaine.gmane.org>

On 16/04/17 03:18, Aaron Myatt via Tutor wrote:
> My favourite book on testing. It is a pretty thorough walk through of
> building a django app that helps you get a feel for the TDD work flow and
> red, green, refactor cycle. A rather more practical and real world
> applicable introduction to TDD,  in my opinion.

But which book is 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 mats at wichmann.us  Sun Apr 16 10:08:02 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 16 Apr 2017 08:08:02 -0600
Subject: [Tutor] understanding code testing
In-Reply-To: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
References: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
Message-ID: <e37e647b-5306-ceba-5dfc-7c3f256ea3a4@wichmann.us>

On 04/15/2017 08:33 AM, Rafael Knuth wrote:
> can anyone point me to good learning resources on this subject?
> (python 3)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

There is a lot of information on the PyTest website - the
talks/tutorials in particular might be interesting.

https://docs.pytest.org/en/latest/



From jf_byrnes at comcast.net  Sun Apr 16 10:45:28 2017
From: jf_byrnes at comcast.net (Jim)
Date: Sun, 16 Apr 2017 09:45:28 -0500
Subject: [Tutor] Can a virtual environment be renamed?
Message-ID: <od0022$rnl$1@blaine.gmane.org>

My system python is 2.7.12 so I created a virtual environment using venu 
to run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 
and put it in env36. Is it possible to change env to env35 for 3.5.2 
without breaking things?

Thanks, Jim


From kwpolska at gmail.com  Sun Apr 16 11:10:41 2017
From: kwpolska at gmail.com (Chris Warrick)
Date: Sun, 16 Apr 2017 17:10:41 +0200
Subject: [Tutor] Can a virtual environment be renamed?
In-Reply-To: <od0022$rnl$1@blaine.gmane.org>
References: <od0022$rnl$1@blaine.gmane.org>
Message-ID: <CAMw+j7+jUNs_it0nTPGtyEnn58gtDf+hA1-VvpUMG6D8BbuUiw@mail.gmail.com>

On 16 April 2017 at 16:45, Jim <jf_byrnes at comcast.net> wrote:
> My system python is 2.7.12 so I created a virtual environment using venu to
> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
> put it in env36. Is it possible to change env to env35 for 3.5.2 without
> breaking things?

No. You need to delete your existing virtualenv and create a new one.
You can just use `pip freeze > requirements.txt` in the old one and
run `pip install -r requirements.txt` in the new one to ?move? all the
packages you had.


-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16

From robertvstepp at gmail.com  Sun Apr 16 11:21:46 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 16 Apr 2017 10:21:46 -0500
Subject: [Tutor] 
	=?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
	=?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python?=
	=?utf-8?q?=22?=
In-Reply-To: <ocuagv$5im$1@blaine.gmane.org>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
Message-ID: <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>

On Sat, Apr 15, 2017 at 6:31 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 16/04/17 00:17, boB Stepp wrote:
>
>> --------------------------------------------------------------------------------------
>> #!/usr/bin/env python3
>>
>> def mySuperWhammyFunction(any_input):
>>     return any_input
>
> This is a simple function, its not bound to an object

I did not name this function.  I think that if the docs' example meant
it to be a method, they would have named it, "mySuperWhammyMethod".

>>
>> import unittest
>>
>> class TestFuncAcceptsSequencesMixin:
>>
>>     func = mySuperWhammyFunction
>>
>>     def test_func(self):
>>         self.func(self.arg)
>
> This is calling self.function which implies a method.
>
> Convert your function to a method and it should work.

I did this and it indeed works.  But how do I use this technique to
unittest the given function?  I am just not seeing how to do it with
this with this mixin approach, and I have yet to study mixins, though
apparently I have just now started!

In the modified program (per your suggestion) to test a method (I
still need to know how to make this test the original *function*!), I
now have:

--------------------------------------------------------------------------------------
class SuperWhammy:
    def mySuperWhammyFunction(self, any_input):
        return any_input

import unittest

class TestFuncAcceptsSequencesMixin:

    obj = SuperWhammy
    func = obj.mySuperWhammyFunction

    def test_func(self):
        f = self.func(self.arg)
        self.assertEqual(f, self.arg)
        print(f)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = (1, 2, 3)

if __name__ == '__main__':
    unittest.main()
--------------------------------------------------------------------------------------

This gives me the results:

> python -m unittest -v test_super.py
test_func (test_super.AcceptLists) ... [1, 2, 3]
ok
test_func (test_super.AcceptStrings) ... abc
ok
test_func (test_super.AcceptTuples) ... (1, 2, 3)
ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

Questions:

1)  I did not notice it until this AM, but I used (as above) "obj =
SuperWhammy".  Normally I would write this as "obj = SuperWhammy()"
with parentheses.  But I see that both work.  Are the parentheses
unneeded when creating an object instance if there are no
initialization arguments needed?

2)  The big question:  What is the program flow for this program?  I
am not seeing the order of execution here.  How is the unittest module
handling the execution of this?  The ending comment in the docs'
example cited reads:

"When using this pattern, remember that all classes that inherit from
unittest.TestCase are run as tests. The Mixin class in the example
above does not have any data and so can?t be run by itself, thus it
does not inherit from unittest.TestCase."

This suggests to me that unittest "uses" the bottom three classes, but
even though each of the three inherits from the class
TestFuncAcceptsSequenceMixin, those classes don't have any methods
that they call on that class, so how does its code get run?  I suspect
that the mixin's concepts is where I am stumbling.  I have yet to find
a reference that is making things clear to me, though I will continue
searching and reading.

-- 
boB

From jf_byrnes at comcast.net  Sun Apr 16 12:16:45 2017
From: jf_byrnes at comcast.net (Jim)
Date: Sun, 16 Apr 2017 11:16:45 -0500
Subject: [Tutor] Can a virtual environment be renamed?
In-Reply-To: <CAMw+j7+jUNs_it0nTPGtyEnn58gtDf+hA1-VvpUMG6D8BbuUiw@mail.gmail.com>
References: <od0022$rnl$1@blaine.gmane.org>
 <CAMw+j7+jUNs_it0nTPGtyEnn58gtDf+hA1-VvpUMG6D8BbuUiw@mail.gmail.com>
Message-ID: <od05d7$8na$1@blaine.gmane.org>

On 04/16/2017 10:10 AM, Chris Warrick wrote:
> On 16 April 2017 at 16:45, Jim <jf_byrnes at comcast.net> wrote:
>> My system python is 2.7.12 so I created a virtual environment using venu to
>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
>> put it in env36. Is it possible to change env to env35 for 3.5.2 without
>> breaking things?
>
> No. You need to delete your existing virtualenv and create a new one.
> You can just use `pip freeze > requirements.txt` in the old one and
> run `pip install -r requirements.txt` in the new one to ?move? all the
> packages you had.
>
>

Thanks Chris. I thought that would be the answer but wanted to check 
before I spent a lot of time trying to do something that was not possible.

Virtual environments tend to confuse me. My system is Mint 18.1 with 
2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6, 
then build it and then use it's version of venv to create a virtual 
environment to try 3.6. Is that correct?

Thanks,  Jim


From kwpolska at gmail.com  Sun Apr 16 12:24:38 2017
From: kwpolska at gmail.com (Chris Warrick)
Date: Sun, 16 Apr 2017 18:24:38 +0200
Subject: [Tutor] Can a virtual environment be renamed?
In-Reply-To: <od05d7$8na$1@blaine.gmane.org>
References: <od0022$rnl$1@blaine.gmane.org>
 <CAMw+j7+jUNs_it0nTPGtyEnn58gtDf+hA1-VvpUMG6D8BbuUiw@mail.gmail.com>
 <od05d7$8na$1@blaine.gmane.org>
Message-ID: <CAMw+j7+o+8DdyK3MsobcCOKkfxT0jQZs00MmYAyjqo82ONwdXw@mail.gmail.com>

On 16 April 2017 at 18:16, Jim <jf_byrnes at comcast.net> wrote:
> On 04/16/2017 10:10 AM, Chris Warrick wrote:
>>
>> On 16 April 2017 at 16:45, Jim <jf_byrnes at comcast.net> wrote:
>>>
>>> My system python is 2.7.12 so I created a virtual environment using venu
>>> to
>>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
>>> put it in env36. Is it possible to change env to env35 for 3.5.2 without
>>> breaking things?
>>
>>
>> No. You need to delete your existing virtualenv and create a new one.
>> You can just use `pip freeze > requirements.txt` in the old one and
>> run `pip install -r requirements.txt` in the new one to ?move? all the
>> packages you had.
>>
>>
>
> Thanks Chris. I thought that would be the answer but wanted to check before
> I spent a lot of time trying to do something that was not possible.
>
> Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12
> & 3.5.2 installed. So I would have to download a tar file of 3.6, then build
> it and then use it's version of venv to create a virtual environment to try
> 3.6. Is that correct?

Yes, you need to install the appropriate interpreter first, and
likewise a virtualenv won?t work if you uninstall an
interpreter/upgrade it to a new minor version*. You might not need to
use the source tarball if
https://launchpad.net/~fkrull/+archive/ubuntu/deadsnakes works on Mint
(and if you do use tarballs, make sure to install somewhere in /opt or
whatever not to make a mess ? it?s easy to break your OS if you?re not
careful)

* eg. 3.5 ? 3.6. Won?t ever happen on Mint or other ?friendly?
distros, unless you do a dist-upgrade. Happens pretty often on
rolling-release distros or macOS with homebrew.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16

From alan.gauld at yahoo.co.uk  Sun Apr 16 13:06:41 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 16 Apr 2017 18:06:41 +0100
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
In-Reply-To: <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
 <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
Message-ID: <od08ar$kn2$1@blaine.gmane.org>

On 16/04/17 16:21, boB Stepp wrote:

> I did this and it indeed works.  But how do I use this technique to
> unittest the given function?  I am just not seeing how to do it with
> this with this mixin approach, and I have yet to study mixins, though
> apparently I have just now started!

I'm not familiar with the mixin approach so don;t know what
they intend but...

> --------------------------------------------------------------------------------------
> class SuperWhammy:
>     def mySuperWhammyFunction(self, any_input):
>         return any_input
> 
> import unittest
> 
> class TestFuncAcceptsSequencesMixin:
> 
>     obj = SuperWhammy
>     func = obj.mySuperWhammyFunction

Note this is a class attribute not an instance one
so you could attach a "normal" function and call it
via the class.

>     def test_func(self):
>         f = self.func(self.arg)

    f = TestFuncAcceptsSequencesMixin.func(self.args)

>         self.assertEqual(f, self.arg)
>         print(f)

But I've no idea if that's what the author intended...

I tried it on your original code and it seemed to work OK.

> 1)  I did not notice it until this AM, but I used (as above) "obj =
> SuperWhammy".  Normally I would write this as "obj = SuperWhammy()"
> with parentheses.  But I see that both work.  Are the parentheses
> unneeded when creating an object instance if there are no
> initialization arguments needed?

No, you are not creating an instance but a reference to the class.
So when you assigned the function you were in effect doing

func = SuperWhammy.mySuperWhammyFunction

Which of course works fine.

> 2)  The big question:  What is the program flow for this program?  I
> am not seeing the order of execution here.  How is the unittest module
> handling the execution of this?  The ending comment in the docs'
> example cited reads:

I'll let a unittest expert comment on that fully.

So far as I understand it, the unittest framework
just calls all the test_xxx methods of all classes
that inherit from TestCase. And because all three
test classes inherit the mixin and its test_func()
method they all execute that method but each providing
their own version of args.

Exactly how that magic is accomplished I leave to
the framework authors! ;-)


> "When using this pattern, remember that all classes that inherit from
> unittest.TestCase are run as tests. The Mixin class in the example
> above does not have any data and so can?t be run by itself, thus it
> does not inherit from unittest.TestCase."
> 
> This suggests to me that unittest "uses" the bottom three classes, but
> even though each of the three inherits from the class
> TestFuncAcceptsSequenceMixin, those classes don't have any methods
> that they call on that class, so how does its code get run?  

They inherit the test_fujnc() method from the mixin.
And the TestCase looks for  methods called test_xxx
and runs them. (It could be as simple as doing a dir(self),
I really don't know.)

> that the mixin's concepts is where I am stumbling.  I have yet to find
> a reference that is making things clear to me, though I will continue
> searching and reading.

Mixins are conceptually very simple, just small classes
expressing a capability that you inherit along with your
other super classes. There is nothing intrinsically special
about them, its more about the concept than the implementation.
(Some languages use mixins a lot and have dedicated support
for them such as not having them inherit from object to avoid
the dreaded MI diamond patterns or other similar tricks.) The
introduction of interfaces into languages like Java and C#
have made mixins less common.

-- 
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 giacomo.boffi at gmail.com  Sun Apr 16 16:28:59 2017
From: giacomo.boffi at gmail.com (giacomo.boffi at gmail.com)
Date: Sun, 16 Apr 2017 22:28:59 +0200
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
References: <58EFD455.6070902@sbcglobal.net>
Message-ID: <878tn0gkqc.fsf@debian.i-did-not-set--mail-host-address--so-tickle-me>

"Stephen P. Molnar" <s.molnar at sbcglobal.net> writes:

> I have an list generated by:   s = np.linspace(start,finish,points)
>
> and an array D:
>
>  [ 0.          2.059801    3.60937686  3.32591826  2.81569212]
>  [ 2.059801    0.          4.71452879  4.45776445  4.00467382]
>  [ 3.60937686  4.71452879  0.          5.66500917  5.26602175]
>  [ 3.32591826  4.45776445  5.66500917  0.          5.02324896]
>  [ 2.81569212  4.00467382  5.26602175  5.02324896  0.        ]
>
> Now I can multiply the Array by one element of the list:
>
> s2 = 1.100334448160535050  (The first non-zero list element.)
> s2_D = s2*np.array(D)
>
> which results in:
>
>  [ 0.          2.26647     3.97152169  3.65962243  3.09820303]
>  [ 2.26647     0.          5.18755844  4.90503178  4.40648056]
>  [ 3.97152169  5.18755844  0.          6.23340474  5.79438514]
>  [ 3.65962243  4.90503178  6.23340474  0.          5.52725387]
>  [ 3.09820303  4.40648056  5.79438514  5.52725387  0.        ]
>
> I checked this, rather laboriously, in a spreadsheet.
>
> However, what I want to do is multiply each element ob D by each
> element of s and sum all of the products.

if I understand what you want to do,

  R_ij = sum_k(D_ij s_k)

you can do it in a number of ways, say D has shape(i, j) and s has shape(k)

Possibility 1

c = np.outer(D, s) # c has shape (i*j, k) as outer flattens its arguments 
c = sum(c, 1)      # c has shape (i*j) because se summed over 2nd index
c.reshape(D.shape) # c has the shape of D, i.e., (i, j)

Possibility 2

# https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html
stackoverflow.com/questions/26089893/understanding-numpys-einsum
c = np.einsum('ij,k -> ij', D, s)



From martin at linux-ip.net  Sun Apr 16 16:59:25 2017
From: martin at linux-ip.net (Martin A. Brown)
Date: Sun, 16 Apr 2017 13:59:25 -0700
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
In-Reply-To: <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
 <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
Message-ID: <alpine.LSU.2.11.1704160850280.2663@qnttre.jbaqresebt.arg>


Greetings boB,

>2)  The big question:  What is the program flow for this program?  I
>am not seeing the order of execution here.  How is the unittest module
>handling the execution of this? 

This is a very good question and one that was (at one time) 
inobvious to me, as well.

When you write a program, you usually have a clear notion of where 
the program will begin and then can follow its execution path (from 
"if __name__ == '__main__'") through your functions, class 
instantiations and method calls.  This is the execution structure of 
your program.  (I'd imagine you have used print and/or logging to 
debug program flow, as well....)

Testing flow is different.

The sequence of test execution has nothing to do with your program 
structure.  This is utterly intentional.

[ background / digression ] By breaking down a complex program into 
smaller testable pieces, you can have more assurance that your 
program is doing exactly what you intend.  Since you are breaking 
the program into smaller pieces, those pieces can (and should) be 
runnable and tested without requiring any of the other pieces.

Usually (almost always) tests are run in isolation.  This allows you 
to control exactly the arguments, environment and conditions of each 
test.

You may know most of the above already, but I repeat it because 
these facts help explain why testing tools work as they do...
[ end digression ]

Now, to the unittest module.

(Please note, I'm not an expert on unittest internals, so I may get 
a detail or two wrong.  Nonetheless, I hope that my answer will help 
you orient yourself around what's happening.)

When you run a tool to collect your tests and execute them, the path 
through your pieces of code under test has no connection whatsoever 
to process flow through your program.

The basic flow looks like this:

  * find the test cases / test suites you have written
  * run each of the tests independently, i.e. isolated conditions
  * report on the success/failure of each test case, test suite and 
    the whole batch

See below for more detail of the mechanics inside the unittest 
module.  What happens when you execute your testing suite?  Let's 
say you run:

  $ python -m unittest

(Unless there is customization of TestLoader TestSuite and/or 
TestRunner) the following sequence occurs:

  1. the Python interpreter starts up

  2. Python loads the unittest module and passes control to unittest

  3. unittest.main creates an instance of unittest.TestLoader [0]

  4. unittest.TestLoader scans the filesystem, collecting a list of 
     tests to run from:

       - any test suites subclassed from unittest.TestSuite [1]
       - any test cases subclassed unittest.TestCase [2]

  5. unittest.TestLoader imports anything it found and returns the 
     list of tests to the main testing program loop

  6. the main loop passes the tests to the unittest.TextTestRunner [3],
     which executes each test and (probably) produces some output 
     telling you either that your hard work has paid off or that 
     something is still wrong

Your next question is why do the mixins work?  And how do they work?

I'll make a few observations:

  - [on unittest] the unit testing tools use classes because it's a 
    natural way to accommodate the goal of reproducibly setting up 
    arguments and/or an environment for each test (note that each 
    TestCase can have its own setUp() and tearDown() methods; this 
    allows isolation)

  - [on unittest] each test collected by the TestLoader can be any 
    Python class (as long as it is also derived from 
    unittest.TestCase)

  - [on your classes] your classes use a multiple inheritance 
    model, deriving from TestFuncAcceptsSequencesMixin; when 
    instantiated, they'll have all of the expected TestCase methods
    and the method called 'test_func'

In more detail, you have created three different classes, each of 
which is derived from unittest.TestCase (I'm showing just the 
signatures):

  class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
  class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase): 
  class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):

Here's what's happening:

  - TestLoader finds the files that contains the above classes (probably
    named 'test_something.py')

  - Testloader imports the file 'test_something.py'; this defines your
    classes: AcceptLists, AcceptStrings and AcceptTuples (or will 
    produce a traceback if the code does not import; try breaking 
    your code and you should see that the import of your test code 
    fails during the TestLoader phase)

  - TestLoader appends the now-defined classes: AcceptLists,
    AcceptStrings and AcceptTuples to the list of tests

  - control passes back to main and then to TestRunner

  - for each unittest.TestCase in the list of tests, TestRunner will:

    - create an instance T from the defined class

    - for each method name starting with 'test_' (you have only 
      'test_func') TestRunner will:

      - execute the T.setUp() method if it exists

      - TestRunner will execute the method 'test_func'

      - collect the success / failure and any outputs

      - report on the success / failure

  - produce some final summary output and set the exit code 
    accordingly (os.EX_OK means success, anything else is failure)

>The ending comment in the docs' example cited reads:
>
>"When using this pattern, remember that all classes that inherit from
>unittest.TestCase are run as tests. The Mixin class in the example
>above does not have any data and so can?t be run by itself, thus it
>does not inherit from unittest.TestCase."
>
>This suggests to me that unittest "uses" the bottom three classes, but
>even though each of the three inherits from the class
>TestFuncAcceptsSequenceMixin, those classes don't have any methods
>that they call on that class, so how does its code get run?  I suspect
>that the mixin's concepts is where I am stumbling.  I have yet to find
>a reference that is making things clear to me, though I will continue
>searching and reading.

I hope my long-winded explanation amkes that a bit clearer.

Good luck,

-Martin

 [0] https://docs.python.org/3/library/unittest.html#unittest.TestLoader
 [1] https://docs.python.org/3/library/unittest.html#unittest.TestSuite
 [2] https://docs.python.org/3/library/unittest.html#unittest.TestCase
 [3] https://docs.python.org/3/library/unittest.html#unittest.TextTestRunner

http://www.drdobbs.com/testing/unit-testing-with-python/240165163

-- 
Martin A. Brown
http://linux-ip.net/

From giacomo.boffi at gmail.com  Sun Apr 16 17:08:43 2017
From: giacomo.boffi at gmail.com (giacomo.boffi at gmail.com)
Date: Sun, 16 Apr 2017 23:08:43 +0200
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
References: <58EFD455.6070902@sbcglobal.net>
 <878tn0gkqc.fsf@debian.i-did-not-set--mail-host-address--so-tickle-me>
Message-ID: <874lxogiw4.fsf@debian.i-did-not-set--mail-host-address--so-tickle-me>

giacomo.boffi at gmail.com writes:

I throw two errors in my answer, see the inline corrections

> Possibility 1
>
> c = np.outer(D, s) # c has shape (i*j, k) as outer flattens its arguments 
> c = sum(c, 1)      # c has shape (i*j) because se summed over 2nd index

  c = np.sum(c, 1)   # c has shape (i*j) because se summed over 2nd index
  
> c.reshape(D.shape) # c has the shape of D, i.e., (i, j)
>
> Possibility 2
>
> # https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html
> stackoverflow.com/questions/26089893/understanding-numpys-einsum

  # http://stackoverflow.com/questions/26089893/understanding-numpys-einsum

> c = np.einsum('ij,k -> ij', D, s)

in particular `c = sum(...)` instead of `c = np.sum(...)` is a nasty
error because `sum` is a builtin and the error message one gets could be
misleading


From mats at wichmann.us  Sun Apr 16 15:18:45 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 16 Apr 2017 13:18:45 -0600
Subject: [Tutor] Can a virtual environment be renamed?
In-Reply-To: <od05d7$8na$1@blaine.gmane.org>
References: <od0022$rnl$1@blaine.gmane.org>
 <CAMw+j7+jUNs_it0nTPGtyEnn58gtDf+hA1-VvpUMG6D8BbuUiw@mail.gmail.com>
 <od05d7$8na$1@blaine.gmane.org>
Message-ID: <17dd5b50-2ba4-1be8-2aa7-d3e98771ba8b@wichmann.us>

On 04/16/2017 10:16 AM, Jim wrote:
> On 04/16/2017 10:10 AM, Chris Warrick wrote:
>> On 16 April 2017 at 16:45, Jim <jf_byrnes at comcast.net> wrote:
>>> My system python is 2.7.12 so I created a virtual environment using
>>> venu to
>>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6
>>> and
>>> put it in env36. Is it possible to change env to env35 for 3.5.2 without
>>> breaking things?
>>
>> No. You need to delete your existing virtualenv and create a new one.
>> You can just use `pip freeze > requirements.txt` in the old one and
>> run `pip install -r requirements.txt` in the new one to ?move? all the
>> packages you had.
>>
>>
> 
> Thanks Chris. I thought that would be the answer but wanted to check
> before I spent a lot of time trying to do something that was not possible.
> 
> Virtual environments tend to confuse me. My system is Mint 18.1 with
> 2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6,
> then build it and then use it's version of venv to create a virtual
> environment to try 3.6. Is that correct?
> 
> Thanks,  Jim

It doesn't need to be terribly complicated, something called pyenv can
manage the install for you (yes, it will build it if needed).

pyenv install --list

to show what's available to install

pyenv install 3.6.0

to install a copy

If you set up the shell helpers, pyenv will let you create the
virtualenv and launch it:

pyenv virtualenv 3.6.0 test-3.6.0
pyenv activate test-3.6.0


From sergio_r at mail.com  Sun Apr 16 16:57:08 2017
From: sergio_r at mail.com (Sergio Rojas)
Date: Sun, 16 Apr 2017 22:57:08 +0200
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
In-Reply-To: <mailman.1570.1492214181.2950.tutor@python.org>
References: <mailman.1570.1492214181.2950.tutor@python.org>
Message-ID: <trinity-393b55a4-fda7-49cf-894a-695bf6edd73c-1492376228668@3capp-mailcom-lxa10>


On 04/14/2017 04:21 AM, Peter Otten wrote:
> Stephen P. Molnar wrote:
>
>> However, what I want to do is multiply each element ob D by each element
>> of s and sum all of the products.
>
> If you *really* want this:
>
> sum_of_all_products = s.sum() * D.sum()
>
> example:
>
> s = [a b c]
>
> D = [[a1 a2]
> [a3 a4]]
>
> a*a1 + a*a2 + a*a3 + a*a4 = a * D.sum()
>
> d := D.sum()
> a*d + b*d + c*d = s.sum() * d
>
> Even if that's what you want you should heed Steven's advice.
>

Nice example on "analyze before computing". Nevertheless,
A lazy man's approach to life might  go  using numpy ufunc.outer
 [ https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html ]


In [1]: import numpy as np

In [2]: from sympy import symbols

In [3]: x1, y1, z1, x2, y2, z2, x3, y3, z3 = symbols('x1 y1 z1 x2 y2 z2 x3 y3 z3
   ...: ')

In [4]: x=np.array([[x1,y1,z1], [x2,y2,z2], [x3,y3,z3]])

In [5]: z=np.array([z1,z2,z3])

In [6]: print(np.multiply.outer(z,x))
[[[x1*z1 y1*z1 z1**2]
  [x2*z1 y2*z1 z1*z2]
  [x3*z1 y3*z1 z1*z3]]

 [[x1*z2 y1*z2 z1*z2]
  [x2*z2 y2*z2 z2**2]
  [x3*z2 y3*z2 z2*z3]]

 [[x1*z3 y1*z3 z1*z3]
  [x2*z3 y2*z3 z2*z3]
  [x3*z3 y3*z3 z3**2]]]

In [7]: np.multiply.outer(z,x).sum()
Out[7]: x1*z1 + x1*z2 + x1*z3 + x2*z1 + x2*z2 + x2*z3 + x3*z1 + x3*z2 + x3*z3 + y1*z1 + y1*z2 + y1*z3 + y2*z1 + y2*z2 + y2*z3 + y3*z1 + y3*z2 + y3*z3 + z1**2 + 2*z1*z2 + 2*z1*z3 + z2**2 + 2*z2*z3 + z3**2

In [8]: 

Sergio
https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video
https://github.com/rojassergio/Learning-Scipy

From robertvstepp at gmail.com  Sun Apr 16 21:53:10 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 16 Apr 2017 20:53:10 -0500
Subject: [Tutor] understanding code testing
In-Reply-To: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
References: <CAM-E2X7Y-54tqqG=KuoXHHpp9SBWBFTyVT+4YuFiTBLpqZiFSg@mail.gmail.com>
Message-ID: <CANDiX9KVWB5dYf9=0J_45ZU-1BEiyFE1BcuHvNoMV9fkPEcjaA@mail.gmail.com>

On Sat, Apr 15, 2017 at 9:33 AM, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> can anyone point me to good learning resources on this subject?
> (python 3)

I have been liking "Testing Python -- Applying Unit Testing, TDD, BDD,
and Acceptance Testing" by David Sale, c. 2014.  If you are into
developing web stuff, then you might like "Test-Driven Development
with Python -- Obey the Testing Goat:  Using Django, Selenium, and
JavaScript" by Harry J. W. Percival, c. 2014.



-- 
boB

From robertvstepp at gmail.com  Sun Apr 16 23:16:15 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 16 Apr 2017 22:16:15 -0500
Subject: [Tutor] 
	=?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
	=?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python?=
	=?utf-8?q?=22?=
In-Reply-To: <alpine.LSU.2.11.1704160850280.2663@qnttre.jbaqresebt.arg>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
 <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
 <alpine.LSU.2.11.1704160850280.2663@qnttre.jbaqresebt.arg>
Message-ID: <CANDiX9LeDOXcA3oLsEi2dscfYP1ME0QEJmwF+tgLkN-2-ir20A@mail.gmail.com>

Thank you very much Martin; you filled in a lot of details.  I had an
overall understanding of what unittest does, but you have now enhanced
that understanding substantially.  I'm still iffy on how the mixin
class gets its test method called when this class does not subclass
from unittest.TestCase, but I think I may have an idea now on how it
is happening.  Let's get to that part of your response.

On Sun, Apr 16, 2017 at 3:59 PM, Martin A. Brown <martin at linux-ip.net> wrote:

[snip]

> Your next question is why do the mixins work?  And how do they work?
>
> I'll make a few observations:
>
>   - [on unittest] the unit testing tools use classes because it's a
>     natural way to accommodate the goal of reproducibly setting up
>     arguments and/or an environment for each test (note that each
>     TestCase can have its own setUp() and tearDown() methods; this
>     allows isolation)
>
>   - [on unittest] each test collected by the TestLoader can be any
>     Python class (as long as it is also derived from
>     unittest.TestCase)
>
>   - [on your classes] your classes use a multiple inheritance
>     model, deriving from TestFuncAcceptsSequencesMixin; when
>     instantiated, they'll have all of the expected TestCase methods
>     and the method called 'test_func'

It is here that I am struggling.  If the mixin class does not inherit
from unittest.TestCase, then how is test_func ever seen?

> In more detail, you have created three different classes, each of
> which is derived from unittest.TestCase (I'm showing just the
> signatures):
>
>   class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
>   class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
>   class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
>
> Here's what's happening:
>
>   - TestLoader finds the files that contains the above classes (probably
>     named 'test_something.py')
>
>   - Testloader imports the file 'test_something.py'; this defines your
>     classes: AcceptLists, AcceptStrings and AcceptTuples (or will
>     produce a traceback if the code does not import; try breaking
>     your code and you should see that the import of your test code
>     fails during the TestLoader phase)
>
>   - TestLoader appends the now-defined classes: AcceptLists,
>     AcceptStrings and AcceptTuples to the list of tests
>
>   - control passes back to main and then to TestRunner
>
>   - for each unittest.TestCase in the list of tests, TestRunner will:
>
>     - create an instance T from the defined class

This answers one important thing I was wondering about:  How do the
classes AcceptLists, AcceptStrings, and AcceptTuples get instantiated?
 Apparently the unittest machinery does this for me.

>     - for each method name starting with 'test_' (you have only
>       'test_func') TestRunner will:

And here is my precise sticking point:  How does the TestRunner find
test_func?  The classes it has collected and instantiated
(AcceptLists, AcceptStrings and AcceptTuples) do not themselves call
and make use of the test_func method they inherit from the mixin
class.

>       - execute the T.setUp() method if it exists
>
>       - TestRunner will execute the method 'test_func'

The only thing that makes sense to me is that the TestRunner follows
the MRO of the inherited classes and checks for any test_xxx methods
that might exist in those superclasses.  Is this correct or do I have
a conceptual misunderstanding?

>       - collect the success / failure and any outputs
>
>       - report on the success / failure
>
>   - produce some final summary output and set the exit code
>     accordingly (os.EX_OK means success, anything else is failure)
>

[snip]

> I hope my long-winded explanation amkes that a bit clearer.

More clarity has been achieved, but I am not fully there yet!

Thanks!

-- 
boB

From robertvstepp at gmail.com  Mon Apr 17 00:01:35 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 16 Apr 2017 23:01:35 -0500
Subject: [Tutor] 
	=?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
	=?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python?=
	=?utf-8?q?=22?=
In-Reply-To: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
Message-ID: <CANDiX9KU0VXAoP8ykZwr1rk4CixG79OjMAoAu9phQ3B7DcgLZA@mail.gmail.com>

OK, between Alan and Martin I think that I see how to make the code
snippet actually test a *function* as the snippet seems to suggest.
Recollect that my original question(s) started:

On Sat, Apr 15, 2017 at 6:17 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> In the section
>
> https://docs.python.org/3/library/test.html#writing-unit-tests-for-the-test-package
>
> I have been trying to make sense of the given pointer and code snippet:
>
> <quote>
> Try to maximize code reuse. On occasion, tests will vary by something
> as small as what type of input is used. Minimize code duplication by
> subclassing a basic test class with a class that specifies the input:
>
> class TestFuncAcceptsSequencesMixin:
>
>     func = mySuperWhammyFunction
>
>     def test_func(self):
>         self.func(self.arg)
>
> class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
>     arg = [1, 2, 3]
>
> class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
>     arg = 'abc'
>
> class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
>     arg = (1, 2, 3)
>
> When using this pattern, remember that all classes that inherit from
> unittest.TestCase are run as tests. The Mixin class in the example
> above does not have any data and so can?t be run by itself, thus it
> does not inherit from unittest.TestCase.
> </quote>

The snippet as supplied will not run.  "mySuperWhammyFunction" is not
defined anywhere.  Additionally, the code to start the unittest
machinery going was not included (But to be fair, it was just
discussed above this snippet.).  In my original effort I tried to stay
as true as possible to the code snippet in the docs and only added the
"missing" elements I just mentioned.  However, I think the docs are
misleading with this line:

func = mySuperWhammyFunciton

and this line:

self.func(self.arg)

I asked myself, how am I now testing functions with unittest?  I've
been doing it for a few months now.  What I would do in the context of
this Mixin approach would be:

def mySuperWhammyFunction(any_input):
    return any_input

import unittest

class TestFuncAcceptsSequencesMixin:

    def test_func(self):
        f = mySuperWhammyFunction(self.arg)    # What need is there
for the class variable func?
        self.assertEqual(f, self.arg)          # Just call and assign
the function being tested directly!
        print(f)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = (1, 2, 3)

if __name__ == '__main__':
    unittest.main()

This works fine and produces this output:

> python -m unittest -v test_super.py
test_func (test_super.AcceptLists) ... [1, 2, 3]
ok
test_func (test_super.AcceptStrings) ... abc
ok
test_func (test_super.AcceptTuples) ... (1, 2, 3)
ok

----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK

Am I missing anything?  If not, then why did the code snippet use the
(I believe to be misleading.) class variable approach with "func =
mySuperWhammyFunction" and "self.func(self.arg)"?

boB

From alan.gauld at yahoo.co.uk  Mon Apr 17 02:33:09 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 17 Apr 2017 07:33:09 +0100
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
In-Reply-To: <CANDiX9KU0VXAoP8ykZwr1rk4CixG79OjMAoAu9phQ3B7DcgLZA@mail.gmail.com>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <CANDiX9KU0VXAoP8ykZwr1rk4CixG79OjMAoAu9phQ3B7DcgLZA@mail.gmail.com>
Message-ID: <od1niu$s4n$1@blaine.gmane.org>

On 17/04/17 05:01, boB Stepp wrote:

> Am I missing anything?  If not, then why did the code snippet use the
> (I believe to be misleading.) class variable approach with "func =
> mySuperWhammyFunction" and "self.func(self.arg)"?

I suspect it was a slightly broken attempt at reuse in that
you can assign other functions to the class variable func.
In your code the function is hard coded into the test_func()
method. The original code (apart from using self.func) allowed
the mixin func attribute to be reset to different functions.

But I'm guessing at the authors intent, it may just have
been over-engineering...

-- 
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 mats at wichmann.us  Mon Apr 17 00:50:08 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 16 Apr 2017 22:50:08 -0600
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
In-Reply-To: <CANDiX9KU0VXAoP8ykZwr1rk4CixG79OjMAoAu9phQ3B7DcgLZA@mail.gmail.com>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <CANDiX9KU0VXAoP8ykZwr1rk4CixG79OjMAoAu9phQ3B7DcgLZA@mail.gmail.com>
Message-ID: <40b908cc-c537-9f61-7ff3-09499cbe48bd@wichmann.us>

On 04/16/2017 10:01 PM, boB Stepp wrote:
> OK, between Alan and Martin I think that I see how to make the code
> snippet actually test a *function* as the snippet seems to suggest.
> Recollect that my original question(s) started:


You got me thinking as well, as I don't much care for unittest, at least
partly because it forces you to use classes even when it doesn't feel
all that natural.

So here's a vaguely practical example of applying the same pattern using
pytest - that is, if you're going to test a function several different
ways, can you use just one test function instead of writing multiples.

First let's write the function to test: it tries to reverse its
argument, which should be something that can be iterated over, using
fancy list slicing.  To show it's working there is also code to try it
out if it is called as a program (as opposed to as a module).

=== reverser.py ==
def slicerev(collection):
    return collection[::-1]

if __name__ == "__main__":
    print slicerev([1,2,3,4])
    print slicerev((1,2,3,4))
    print slicerev('abcd')
===

Now write a test for this function, naming it, by convention,
test_{funcname}.py. (if it's named this way pytest can find it
automatically but it's not mandatory, you can give the name of the test
file as an argument).

Import pytest because we need the definition of the fixture decorator;
and import the function we're going to be testing, since it is, after
all, in a different file.

Since what we're factoring here is supplying different sets of data,
decorate a function "slicedata" which will return the data, turning it
into a pytest fixture (there's plenty of information on pytest fixtures
so won't repeat here); supply pairs of values where one value is the
data to call the function with and the other is the expected result of
calling the function under test.

The actual test function should be pretty straightforward.

=== test_slicerev.py ===
import pytest

from reverser import slicerev

@pytest.fixture(params=[
    ([1,2,3,4], [4,3,2,1]),
    ((1,2,3,4), (4,3,2,1)),
    ('abcd',    'edcba')
    ])
def slicedata(request):
    return request.param

def test_slicerev(slicedata):
    input, expected = slicedata
    output = slicerev(input)
    assert output == expected
===

Run the tests with "py.test test_slicerev.py"

Note the "expected" data for the string type is intentionally incorrect
so you should see an error with some explanatory output.

(you'll probably have to install pytest, since it's not in the standard
library; pytest can run all the unittest style tests too though).

From seacristt at hotmail.com  Sun Apr 16 13:26:19 2017
From: seacristt at hotmail.com (Tyler Seacrist)
Date: Sun, 16 Apr 2017 17:26:19 +0000
Subject: [Tutor] Need help with code
Message-ID: <CO2PR04MB826CDB4F99353DDC093B975B3070@CO2PR04MB826.namprd04.prod.outlook.com>

Hello,


I need to draw a stack diagram for print_n called with s = 'Hello' and n=2 and am unsure of how to do so.


Thanks,

Tyler

From timeofsands at gmail.com  Mon Apr 17 00:48:33 2017
From: timeofsands at gmail.com (Palm Tree)
Date: Mon, 17 Apr 2017 08:48:33 +0400
Subject: [Tutor] bracket issue
In-Reply-To: <CAGC2tih6H39QHnkpVNvPMnrhnhSqiu3jObtiexRAs3eG4cN6kg@mail.gmail.com>
References: <octbmr$1ql$6@blaine.gmane.org>
 <CAGC2tih6H39QHnkpVNvPMnrhnhSqiu3jObtiexRAs3eG4cN6kg@mail.gmail.com>
Message-ID: <CAGC2tijAdCkAybjmnHFk3Ku7fCaD2jNt-boXe-p5sFKC_asvpA@mail.gmail.com>

---------- Forwarded message ----------
From: "Palm Tree" <timeofsands at gmail.com>
Date: 16 Apr 2017 10:07
Subject: Re: [Tutor] bracket issue
To: "Peter Otten" <__peter__ at web.de>
Cc:

Ok thanks for the answers. Perfect.

Just to clarify why i wanted recursion was that well coming to compiler
theory, i created a python-based language called newB

it allows you to define your own keywords but don't abuse

like you can configure if to cheese

cheese x == 4:

coming to recursion well i currently use eval() so everything ok i don't
have to worry about brackets but i want to write my own parser. a top down
parser for expressions.

you can also view the lang here:
http://wp.me/p7UB6x-oV

thanks for the answers once more

On 15 Apr 2017 18:46, "Peter Otten" <__peter__ at web.de> wrote:

> Palm Tree wrote:
>
> > hi all. i'm trying to write a simple program. i'm using python 3.4
> >
> > let us say i have
> >
> > s="2*3+3(8-4(5+6+9))+2+3+3(4/4)"
> >
> > i want to find expression enclosed in brackets.
> >
> > i want outputs to be like:
> > (8-4(5+6+9))
> > (5+6+9)
> > (4/4)
> > note : i'd like an answer involving recursion if possible
>
> No recursion, but a stack managed manually:
>
> >>> s = "2*3+3(8-4(5+6+9))+2+3+3(4/4)"
> >>> stack = []
> >>> for i, c in enumerate(s):
> ...     if c == "(":
> ...         stack.append(i)
> ...     elif c == ")":
> ...         print(s[stack.pop():i+1])
> ...
> (5+6+9)
> (8-4(5+6+9))
> (4/4)
>
> The order is determined by the closing parenthesis, you could sort if you
> don't want that.
>
> I did not find a convincing translation using recursion, but I'll give one
> anyway:
>
> def find_closing(s):
>     i = c = None
>     pairs = enumerate(s)
>     def step(start=None):
>         nonlocal i, c
>         for i, c in pairs:
>             if c == "(":
>                 step(i)
>             elif c == ")":
>                 if start is not None:
>                     print(s[start:i+1])
>                 return
>     step()
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From timeofsands at gmail.com  Mon Apr 17 00:58:01 2017
From: timeofsands at gmail.com (Palm Tree)
Date: Mon, 17 Apr 2017 08:58:01 +0400
Subject: [Tutor] How do we create a GUI to run a simple calculation
 program in Python?
In-Reply-To: <CAGC2tih7StxMesJubrWOEin4uHxi3b6Gt1QoEL8s7jfBJk2ZFg@mail.gmail.com>
References: <CAF91wy9Pxs9-csarGsGvyFwA16qMUJkm8ykCmtiWH098A7cU0g@mail.gmail.com>
 <oc0r72$djt$1@blaine.gmane.org> <827fd3e0f60af588b8f1d819ca9d97d1@sonic.net>
 <ocsk6m$8c5$1@blaine.gmane.org> <e26e8c9102e7e1bb641ec262ff13a282@sonic.net>
 <CAGC2tih7StxMesJubrWOEin4uHxi3b6Gt1QoEL8s7jfBJk2ZFg@mail.gmail.com>
Message-ID: <CAGC2tigJpw_XbaZ56kwToyUj2jfgpTZSf5jZSNr1poE+Ggqhjw@mail.gmail.com>

On 16 Apr 2017 10:01, "Palm Tree" <timeofsands at gmail.com> wrote:

Sorry for late reply.

We usually organise python challenges.

Once we organise a gui calculator challenge.

You can view the submissions on my blog here:
https://abdurrahmaanjanhangeer.wordpress.com/gui-py-
calculator-challenge-19-1-17/

On 16 Apr 2017 09:50, "Alex Kleider" <akleider at sonic.net> wrote:

> On 2017-04-15 01:04, Alan Gauld via Tutor wrote:
>
>
>
>> Finally, if you can find a copy of my recent book "Python Projects"
>> there is a rolling project within that which demonstrates how
>> the same logic code can be used to build a CLI, a GUI and a
>> Web app. [ In fact it goes even further by demonstrating how
>> to break an app into 3 tiers - data, logic and UI - which
>> is industry best practice, but usually overkill for small
>> projects.]
>>
>
> Thanks, Alan, for the guidance.  As it happens, I have a copy of your
> Python Projects" book- time to get it off the shelf and have a closer look!
> Alex
> _______________________________________________
> 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 Apr 17 03:00:23 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 17 Apr 2017 08:00:23 +0100
Subject: [Tutor] Need help with code
In-Reply-To: <CO2PR04MB826CDB4F99353DDC093B975B3070@CO2PR04MB826.namprd04.prod.outlook.com>
References: <CO2PR04MB826CDB4F99353DDC093B975B3070@CO2PR04MB826.namprd04.prod.outlook.com>
Message-ID: <od1p60$bia$1@blaine.gmane.org>

On 16/04/17 18:26, Tyler Seacrist wrote:

> I need to draw a stack diagram for print_n 
> called with s = 'Hello' and n=2 and am unsure of how to do so.

Me too.

What is print_n?

Which stack?
One in your program or the interpreters internal stack?

We need a lot more detail.

-- 
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 Apr 17 04:37:20 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 17 Apr 2017 10:37:20 +0200
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
 <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
 <alpine.LSU.2.11.1704160850280.2663@qnttre.jbaqresebt.arg>
 <CANDiX9LeDOXcA3oLsEi2dscfYP1ME0QEJmwF+tgLkN-2-ir20A@mail.gmail.com>
Message-ID: <od1urr$bt6$1@blaine.gmane.org>

boB Stepp wrote:

> It is here that I am struggling.  If the mixin class does not inherit
> from unittest.TestCase, then how is test_func ever seen?

Perhaps it becomes clearer if we build our own class discovery / method 
runner system. Given T as the baseclass for classes that provide foo_...() 
methods that we want to run, and M as the mix-in that provides such methods 
but isn't itself a subclass of T...

class T:
    pass

class M:
    def foo_one(self):
        print(self.__class__.__name__, "one")
    def foo_two(self):
        print(self.__class__.__name__, "one")

class X(T):
    def foo_x(self):
        print(self.__class__.__name__, "x")

class Y(M, T):
    pass

we want our discovery function to find the classes X and Y.
First attempt:

def discover_Ts():
    for C in globals().values():
        if issubclass(C, T):
            print("found", C)


discover_Ts()

globals().values() gives all toplevel objects in the script and issubclass 
checks if we got a subclass of T. Let's try:

$ python3 discovery.py 
Traceback (most recent call last):
  File "discovery.py", line 23, in <module>
    discover_Ts()
  File "discovery.py", line 19, in discover_Ts
    if issubclass(C, T):
TypeError: issubclass() arg 1 must be a class

It turns out that issubclass() raises a TypeError if the object we want to 
check is not a class:

>>> issubclass(int, float)
False
>>> issubclass(42, float)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: issubclass() arg 1 must be a class

For our purposes False is the better answer, so let's write our own 
issubclass:

def safe_issubclass(S, B):
    try:
        return issubclass(S, B)
    except TypeError:
        return False

def discover_Ts():
    for C in globals().values():
        if safe_issubclass(C, T):
            print("found", C)

$ python3 discovery2.py 
found <class '__main__.Y'>
found <class '__main__.X'>
found <class '__main__.T'>

That's close, we only need to reject T:

def discover_Ts():
    for C in globals().values():
        if safe_issubclass(C, T) and C is not T:
            print("found", C)

Easy. Now we have the classes we can look for the methods:

def discover_Ts():
    for C in globals().values():
        if safe_issubclass(C, T) and C is not T:
            print("found", C, "with foo_... methods")
            for name in dir(C):
                if name.startswith("foo_"):
                    print("   ", name)

$ python3 discovery4.py 
found <class '__main__.X'> with foo_... methods
    foo_x
found <class '__main__.Y'> with foo_... methods
    foo_one
    foo_two

As you can see, to the discovery algorithm it doesn't matter where the 
method is defined, it suffices that it's part of the class and can be found 
by dir() or vars().

As a bonus, now that we have the class and the method let's invoke them:

def discover_Ts():
    for C in globals().values():
        if safe_issubclass(C, T) and C is not T:
            print("found", C, "with foo_... methods")
            for name in dir(C):
                if name.startswith("foo_"):
                    yield C, name
            
def run_method(cls, methodname):
    inst = cls()
    method = getattr(inst, methodname)
    method()

for cls, methodname in discover_Ts():
    run_method(cls, methodname)

While you could invoke run_method() inside discover_Ts() I turned 
discover_Ts() into a generator that produces class/methodname pairs which 
looks a bit more pythonic to me. Let's run it:

$ python3 discovery5.py 
found <class '__main__.X'> with foo_... methods
X x
Traceback (most recent call last):
  File "discovery5.py", line 36, in <module>
    for cls, methodname in discover_Ts():
  File "discovery5.py", line 24, in discover_Ts
    for C in globals().values():
RuntimeError: dictionary changed size during iteration

Oops, as the global names cls, and methodname spring into existence they 
torpedize our test discovery. We could (and should when we need a moderate 
amount of robustness) take a snapshot of the global variables with 
list(globals().values()), but for demonstration purposes we'll just move the 
toplevel loop into a function:

$ cat discovery6.py 
class T:
    pass

class M:
    def foo_one(self):
        print(self.__class__.__name__, "one")
    def foo_two(self):
        print(self.__class__.__name__, "two")

class X(T):
    def foo_x(self):
        print(self.__class__.__name__, "x")

class Y(M, T):
    pass

def safe_issubclass(S, B):
    try:
        return issubclass(S, B)
    except TypeError:
        return False

def discover_Ts():
    for C in globals().values():
        if safe_issubclass(C, T) and C is not T:
            print("found", C, "with foo_... methods")
            for name in dir(C):
                if name.startswith("foo_"):
                    yield C, name
            
def run_method(cls, methodname):
    inst = cls()
    method = getattr(inst, methodname)
    method()

def main():
    for cls, methodname in discover_Ts():
        run_method(cls, methodname)

if __name__ == "__main__":
    main()
$ python3 discovery6.py 
found <class '__main__.Y'> with foo_... methods
Y one
Y two
found <class '__main__.X'> with foo_... methods
X x

That was easy. We have replicated something similar to the unit test 
framework with very little code. 

Now you can go and find the equivalent parts in the unittest source code :)


From __peter__ at web.de  Mon Apr 17 04:47:21 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 17 Apr 2017 10:47:21 +0200
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
 <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
 <alpine.LSU.2.11.1704160850280.2663@qnttre.jbaqresebt.arg>
 <CANDiX9LeDOXcA3oLsEi2dscfYP1ME0QEJmwF+tgLkN-2-ir20A@mail.gmail.com>
 <od1urr$bt6$1@blaine.gmane.org>
Message-ID: <od1vej$6o8$1@blaine.gmane.org>

Peter Otten wrote:

> class M:
>     def foo_one(self):
>         print(self.__class__.__name__, "one")
>     def foo_two(self):
>         print(self.__class__.__name__, "one")
 
Oops, foo_two() should of course print "two", not "one".


From s.molnar at sbcglobal.net  Mon Apr 17 06:21:03 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Mon, 17 Apr 2017 06:21:03 -0400
Subject: [Tutor] Python 3.6 Multiply the elements of a 2D Array by the
 elements of a 1D Aeeay
In-Reply-To: <trinity-393b55a4-fda7-49cf-894a-695bf6edd73c-1492376228668@3capp-mailcom-lxa10>
References: <mailman.1570.1492214181.2950.tutor@python.org>
 <trinity-393b55a4-fda7-49cf-894a-695bf6edd73c-1492376228668@3capp-mailcom-lxa10>
Message-ID: <58F4970F.9030606@sbcglobal.net>

On 04/16/2017 04:57 PM, Sergio Rojas wrote:
>
> On 04/14/2017 04:21 AM, Peter Otten wrote:
>> Stephen P. Molnar wrote:
>>
>>> However, what I want to do is multiply each element ob D by each element
>>> of s and sum all of the products.
>>
>> If you *really* want this:
>>
>> sum_of_all_products = s.sum() * D.sum()
>>
>> example:
>>
>> s = [a b c]
>>
>> D = [[a1 a2]
>> [a3 a4]]
>>
>> a*a1 + a*a2 + a*a3 + a*a4 = a * D.sum()
>>
>> d := D.sum()
>> a*d + b*d + c*d = s.sum() * d
>>
>> Even if that's what you want you should heed Steven's advice.
>>
>
> Nice example on "analyze before computing". Nevertheless,
> A lazy man's approach to life might  go  using numpy ufunc.outer
>   [ https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html ]
>
>
> In [1]: import numpy as np
>
> In [2]: from sympy import symbols
>
> In [3]: x1, y1, z1, x2, y2, z2, x3, y3, z3 = symbols('x1 y1 z1 x2 y2 z2 x3 y3 z3
>     ...: ')
>
> In [4]: x=np.array([[x1,y1,z1], [x2,y2,z2], [x3,y3,z3]])
>
> In [5]: z=np.array([z1,z2,z3])
>
> In [6]: print(np.multiply.outer(z,x))
> [[[x1*z1 y1*z1 z1**2]
>    [x2*z1 y2*z1 z1*z2]
>    [x3*z1 y3*z1 z1*z3]]
>
>   [[x1*z2 y1*z2 z1*z2]
>    [x2*z2 y2*z2 z2**2]
>    [x3*z2 y3*z2 z2*z3]]
>
>   [[x1*z3 y1*z3 z1*z3]
>    [x2*z3 y2*z3 z2*z3]
>    [x3*z3 y3*z3 z3**2]]]
>
> In [7]: np.multiply.outer(z,x).sum()
> Out[7]: x1*z1 + x1*z2 + x1*z3 + x2*z1 + x2*z2 + x2*z3 + x3*z1 + x3*z2 + x3*z3 + y1*z1 + y1*z2 + y1*z3 + y2*z1 + y2*z2 + y2*z3 + y3*z1 + y3*z2 + y3*z3 + z1**2 + 2*z1*z2 + 2*z1*z3 + z2**2 + 2*z2*z3 + z3**2
>
> In [8]:
>
> Sergio
> https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video
> https://github.com/rojassergio/Learning-Scipy
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

Thanks for the reply.

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1

From dyoo at hashcollision.org  Mon Apr 17 13:28:35 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 17 Apr 2017 10:28:35 -0700
Subject: [Tutor] Need help with code
In-Reply-To: <od1p60$bia$1@blaine.gmane.org>
References: <CO2PR04MB826CDB4F99353DDC093B975B3070@CO2PR04MB826.namprd04.prod.outlook.com>
 <od1p60$bia$1@blaine.gmane.org>
Message-ID: <CAGZAPF6iZ3CVU_e2pW49L8sJCMV_moKtUiu9sJGBMD3-6cooHg@mail.gmail.com>

On Mon, Apr 17, 2017 at 12:00 AM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 16/04/17 18:26, Tyler Seacrist wrote:
>
>> I need to draw a stack diagram for print_n
>> called with s = 'Hello' and n=2 and am unsure of how to do so.


Are you referring to this?

http://www.greenteapress.com/thinkpython/html/thinkpython004.html#toc33

From dyoo at hashcollision.org  Mon Apr 17 13:42:14 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 17 Apr 2017 10:42:14 -0700
Subject: [Tutor] bracket issue
In-Reply-To: <CAGC2tijAdCkAybjmnHFk3Ku7fCaD2jNt-boXe-p5sFKC_asvpA@mail.gmail.com>
References: <octbmr$1ql$6@blaine.gmane.org>
 <CAGC2tih6H39QHnkpVNvPMnrhnhSqiu3jObtiexRAs3eG4cN6kg@mail.gmail.com>
 <CAGC2tijAdCkAybjmnHFk3Ku7fCaD2jNt-boXe-p5sFKC_asvpA@mail.gmail.com>
Message-ID: <CAGZAPF6GhLjnDGs66B+wUL466BE2o2etTXN6wdY89xy2D2qiFw@mail.gmail.com>

> coming to recursion well i currently use eval() so everything ok i don't
> have to worry about brackets but i want to write my own parser. a top down
> parser for expressions.


Do *not* use eval to parse expressions.  It is an extremely bad idea to do this.


Instead, you can use ast.parse, which will give you the parse tree
directly.  It uses the grammatical structure described in:

    https://docs.python.org/2/library/ast.html#abstract-grammar


Example:

##############################################################
>>> tree = ast.parse("2*3+3(8-4(5+6+9))+2+3+3(4/4)", mode='eval')
>>> tree
<_ast.Expression object at 0x7f86c447e490>
>>> tree.body
<_ast.BinOp object at 0x7f86c447e450>
>>> tree.body.op
<_ast.Add object at 0x7f86c4487cd0>
>>> tree.body.left
<_ast.BinOp object at 0x7f86c447e390>
>>>
>>> tree.body.left.left.left.left.left
<_ast.Num object at 0x7f86c440ed90>
>>> tree.body.left.left.left.left.left.n
2
>>> tree.body.left.left.left.left.right.n
3
>>> tree.body.left.left.left.left.op
<_ast.Mult object at 0x7f86c4487dd0>
##############################################################

The example shows that we can navigate the structure of the expression
to get at individual nodes.  Because the structure is recursive,
you'll likely be writing recursive functions that do case-analysis on
the 'expr' type described in the abstract grammar.


To get at the "3(8-4(5+6+9))" part of the example expression, we take
a right instead of a left.  We get back a "Call" object,


###################################
>>> tree.body.left.left.left.right
<_ast.Call object at 0x7f86c440ee10>
###################################


which according to the grammar, has a "func" and "args", themselves
being expressions.


###################################
>>> tree.body.left.left.left.right.func
<_ast.Num object at 0x7f86c440ee50>
>>> tree.body.left.left.left.right.func.n
3
>>> tree.body.left.left.left.right.args
[<_ast.BinOp object at 0x7f86c440ee90>]
###################################


I hope this helps to give you a brief overview on navigating the
abstract syntax tree.  Good luck!

From cs16mtech11014 at iith.ac.in  Mon Apr 17 14:41:29 2017
From: cs16mtech11014 at iith.ac.in (Rasika Sapate)
Date: Tue, 18 Apr 2017 00:11:29 +0530
Subject: [Tutor] reg. list update
Message-ID: <CAAGUbnkLi5jDg1GRKGn0yee5fHYZ=XLOL86w72LkYg8v=_HZwQ@mail.gmail.com>

Dear Python group,
I had written following code.

super = []
sub = [""]*3
other = ["a","b","c","d"]
sub[0] = "hi"
sub[1] = "hello"
for item in other:
    sub[2] = item
    super.append(sub)
for item in super:
    print item


Output :
['hi', 'hello', 'd']
['hi', 'hello', 'd']
['hi', 'hello', 'd']
['hi', 'hello', 'd']


Expected output:
['hi', 'hello', 'a]
['hi', 'hello', 'b']
['hi', 'hello', 'c']
['hi', 'hello', 'd']


Is there anything wrong in this code or any feature of python?

Thanks and regards,
Rasika Sapate.

From __peter__ at web.de  Mon Apr 17 16:58:30 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 17 Apr 2017 22:58:30 +0200
Subject: [Tutor] reg. list update
References: <CAAGUbnkLi5jDg1GRKGn0yee5fHYZ=XLOL86w72LkYg8v=_HZwQ@mail.gmail.com>
Message-ID: <od3a9h$7lo$1@blaine.gmane.org>

Rasika Sapate via Tutor wrote:

> Dear Python group,
> I had written following code.
> 
> super = []
> sub = [""]*3
> other = ["a","b","c","d"]
> sub[0] = "hi"
> sub[1] = "hello"
> for item in other:
>     sub[2] = item
>     super.append(sub)
> for item in super:
>     print item
> 
> 
> Output :
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> 
> 
> Expected output:
> ['hi', 'hello', 'a]
> ['hi', 'hello', 'b']
> ['hi', 'hello', 'c']
> ['hi', 'hello', 'd']
> 
> 
> Is there anything wrong in this code or any feature of python?

When you replace an item in a list you don't magically copy that list, so in 
a for loop

>>> outer = []
>>> inner = [1, 2, 3]
>>> for item in "abc":
...    inner[2] = item
...    outer.append(inner)
... 
>>>

You append the same list three time to outer

>>> outer[0] is inner
True
>>> outer[2] is inner
True

and inner[2] holds the last value you assigned to it. What you want is a new 
list on each iteration, and one way to get that when the inner list is long 
is list concatenation with the + operator:

>>> outer = []
>>> inner_start = [1, 2]
>>> for item in "abc":
...     outer.append(inner_start + [item])
... 
>>> outer[0] is outer[2]
False
>>> outer
[[1, 2, 'a'], [1, 2, 'b'], [1, 2, 'c']]

In your case with only three items I recommend that you use a list literal:

>>> outer = []
>>> for item in "abc":
...     outer.append([1, 2, item])
... 
>>> outer
[[1, 2, 'a'], [1, 2, 'b'], [1, 2, 'c']]

Python has a concise way to spell those append-only loops which is called 
list comprehension and looks like this:

>>> [[1, 2, item] for item in "abc"]
[[1, 2, 'a'], [1, 2, 'b'], [1, 2, 'c']]



From jf_byrnes at comcast.net  Mon Apr 17 17:51:28 2017
From: jf_byrnes at comcast.net (Jim)
Date: Mon, 17 Apr 2017 16:51:28 -0500
Subject: [Tutor] Can a virtual environment be renamed?
In-Reply-To: <17dd5b50-2ba4-1be8-2aa7-d3e98771ba8b@wichmann.us>
References: <od0022$rnl$1@blaine.gmane.org>
 <CAMw+j7+jUNs_it0nTPGtyEnn58gtDf+hA1-VvpUMG6D8BbuUiw@mail.gmail.com>
 <od05d7$8na$1@blaine.gmane.org>
 <17dd5b50-2ba4-1be8-2aa7-d3e98771ba8b@wichmann.us>
Message-ID: <od3dcq$s62$1@blaine.gmane.org>

On 04/16/2017 02:18 PM, Mats Wichmann wrote:
> On 04/16/2017 10:16 AM, Jim wrote:
>> On 04/16/2017 10:10 AM, Chris Warrick wrote:
>>> On 16 April 2017 at 16:45, Jim <jf_byrnes at comcast.net> wrote:
>>>> My system python is 2.7.12 so I created a virtual environment using
>>>> venu to
>>>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6
>>>> and
>>>> put it in env36. Is it possible to change env to env35 for 3.5.2 without
>>>> breaking things?
>>>
>>> No. You need to delete your existing virtualenv and create a new one.
>>> You can just use `pip freeze > requirements.txt` in the old one and
>>> run `pip install -r requirements.txt` in the new one to ?move? all the
>>> packages you had.
>>>
>>>
>>
>> Thanks Chris. I thought that would be the answer but wanted to check
>> before I spent a lot of time trying to do something that was not possible.
>>
>> Virtual environments tend to confuse me. My system is Mint 18.1 with
>> 2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6,
>> then build it and then use it's version of venv to create a virtual
>> environment to try 3.6. Is that correct?
>>
>> Thanks,  Jim
>
> It doesn't need to be terribly complicated, something called pyenv can
> manage the install for you (yes, it will build it if needed).
>
> pyenv install --list
>
> to show what's available to install
>
> pyenv install 3.6.0
>
> to install a copy
>
> If you set up the shell helpers, pyenv will let you create the
> virtualenv and launch it:
>
> pyenv virtualenv 3.6.0 test-3.6.0
> pyenv activate test-3.6.0
>

Thanks Mats,

When I get a chance to try 3.6 this looks like the best way for me to 
install it.

Regards, Jim




From jf_byrnes at comcast.net  Mon Apr 17 17:53:39 2017
From: jf_byrnes at comcast.net (Jim)
Date: Mon, 17 Apr 2017 16:53:39 -0500
Subject: [Tutor] Can a virtual environment be renamed?
In-Reply-To: <CAMw+j7+o+8DdyK3MsobcCOKkfxT0jQZs00MmYAyjqo82ONwdXw@mail.gmail.com>
References: <od0022$rnl$1@blaine.gmane.org>
 <CAMw+j7+jUNs_it0nTPGtyEnn58gtDf+hA1-VvpUMG6D8BbuUiw@mail.gmail.com>
 <od05d7$8na$1@blaine.gmane.org>
 <CAMw+j7+o+8DdyK3MsobcCOKkfxT0jQZs00MmYAyjqo82ONwdXw@mail.gmail.com>
Message-ID: <od3dgt$s62$2@blaine.gmane.org>

On 04/16/2017 11:24 AM, Chris Warrick wrote:
> On 16 April 2017 at 18:16, Jim <jf_byrnes at comcast.net> wrote:
>> On 04/16/2017 10:10 AM, Chris Warrick wrote:
>>>
>>> On 16 April 2017 at 16:45, Jim <jf_byrnes at comcast.net> wrote:
>>>>
>>>> My system python is 2.7.12 so I created a virtual environment using venu
>>>> to
>>>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
>>>> put it in env36. Is it possible to change env to env35 for 3.5.2 without
>>>> breaking things?
>>>
>>>
>>> No. You need to delete your existing virtualenv and create a new one.
>>> You can just use `pip freeze > requirements.txt` in the old one and
>>> run `pip install -r requirements.txt` in the new one to ?move? all the
>>> packages you had.
>>>
>>>
>>
>> Thanks Chris. I thought that would be the answer but wanted to check before
>> I spent a lot of time trying to do something that was not possible.
>>
>> Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12
>> & 3.5.2 installed. So I would have to download a tar file of 3.6, then build
>> it and then use it's version of venv to create a virtual environment to try
>> 3.6. Is that correct?
>
> Yes, you need to install the appropriate interpreter first, and
> likewise a virtualenv won?t work if you uninstall an
> interpreter/upgrade it to a new minor version*. You might not need to
> use the source tarball if
> https://launchpad.net/~fkrull/+archive/ubuntu/deadsnakes works on Mint
> (and if you do use tarballs, make sure to install somewhere in /opt or
> whatever not to make a mess ? it?s easy to break your OS if you?re not
> careful)
>
> * eg. 3.5 ? 3.6. Won?t ever happen on Mint or other ?friendly?
> distros, unless you do a dist-upgrade. Happens pretty often on
> rolling-release distros or macOS with homebrew.
>

Chris, thanks for the confirmation and the link.

Regards, Jim


From mats at wichmann.us  Mon Apr 17 16:46:32 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 17 Apr 2017 14:46:32 -0600
Subject: [Tutor] reg. list update
In-Reply-To: <CAAGUbnkLi5jDg1GRKGn0yee5fHYZ=XLOL86w72LkYg8v=_HZwQ@mail.gmail.com>
References: <CAAGUbnkLi5jDg1GRKGn0yee5fHYZ=XLOL86w72LkYg8v=_HZwQ@mail.gmail.com>
Message-ID: <e0d71a95-15cf-2db5-bc5a-f40d43b7b556@wichmann.us>

On 04/17/2017 12:41 PM, Rasika Sapate via Tutor wrote:
> Dear Python group,
> I had written following code.
> 
> super = []
> sub = [""]*3
> other = ["a","b","c","d"]
> sub[0] = "hi"
> sub[1] = "hello"
> for item in other:
>     sub[2] = item
>     super.append(sub)
> for item in super:
>     print item
> 
> 
> Output :
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> 
> 
> Expected output:
> ['hi', 'hello', 'a]
> ['hi', 'hello', 'b']
> ['hi', 'hello', 'c']
> ['hi', 'hello', 'd']
> 
> 
> Is there anything wrong in this code or any feature of python?

yeah, feature of Python.  you could google for "deep copy".

in short, sub[2] ends up with a reference to, not a copy of, the object
referenced by "item" in the first for loop. all four lists hold this
reference. by the time you go to print, that's a reference to the value
"item" held when the first loop exited, or 'd'.  item itself no longer
refers to that, you assign new things to it.

You can see this by adding a couple of debug print lines

super = []
sub = [""]*3
other = ["a","b","c","d"]
sub[0] = "hi"
sub[1] = "hello"
for item in other:
    sub[2] = item
    print "item id:", id(item)
    super.append(sub)
for item in super:
    print item
    print "item[2] id:", id(item[2])

From marilyn at pythontrainer.com  Mon Apr 17 19:36:50 2017
From: marilyn at pythontrainer.com (Marilyn Davis)
Date: Mon, 17 Apr 2017 16:36:50 -0700 (PDT)
Subject: [Tutor] sqlite3 making a spurious duplicate?
Message-ID: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>

#!/usr/bin/env python3
"""
Hello Tutors,

I can't figure out why the FillWithStars() function puts Canopus in the db
twice.

What am I missing?

Thank you for any help.

Marilyn Davis

p.s. That Reset(db_name) is in there so that you can run it over and over
if you want.

---
"""
import os, sqlite3, subprocess

def Reset(db_name):
    os.system("rm " + db_name)
    db_process = subprocess.Popen(("sqlite3", db_name),
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
    for send in (b'.tables', ):
        returned = db_process.communicate(send)
        assert returned == (b'', b'')

def FillWithStars():

    with sqlite3.connect("stars.db") as connection:

        connection.executescript("""
            CREATE TABLE brightest(
            name,
            constellation,
            apparent_magnitude,
            absolute_magnitude,
            distance);
            INSERT INTO brightest VALUES("Canopus", "Carina", -0.72, -2.5,
74);
""")

        connection.executemany("INSERT INTO brightest VALUES(?, ?, ?, ?, ?)",
            [("Arcturus", "Bootes", -0.04, 0.2, 34),])

        stored_stars = connection.execute("SELECT * FROM BRIGHTEST")

    for star in stored_stars:
        print(star)

def main():
    Reset("stars.db")
    FillWithStars()

if __name__ == '__main__':
    main()

"""Output:

bash-3.2$ ./why3.py
('Canopus', 'Carina', -0.72, -2.5, 74)
('Canopus', 'Carina', -0.72, -2.5, 74)
('Arcturus', 'Bootes', -0.04, 0.2, 34)
bash-3.2$
"""


From mats at wichmann.us  Mon Apr 17 18:32:04 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 17 Apr 2017 16:32:04 -0600
Subject: [Tutor] reg. list update
In-Reply-To: <e0d71a95-15cf-2db5-bc5a-f40d43b7b556@wichmann.us>
References: <CAAGUbnkLi5jDg1GRKGn0yee5fHYZ=XLOL86w72LkYg8v=_HZwQ@mail.gmail.com>
 <e0d71a95-15cf-2db5-bc5a-f40d43b7b556@wichmann.us>
Message-ID: <bf36c503-c461-fb69-133c-dd325a43a111@wichmann.us>


>>
>> Is there anything wrong in this code or any feature of python?
> 
> yeah, feature of Python.  you could google for "deep copy".
> 


the reference issue is involved here, but my explanation was off, I
confused myself, listen to Peter instead :)   It's just the same list
four times.





From alan.gauld at yahoo.co.uk  Mon Apr 17 20:19:11 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 18 Apr 2017 01:19:11 +0100
Subject: [Tutor] sqlite3 making a spurious duplicate?
In-Reply-To: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>
References: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>
Message-ID: <od3m1o$q35$1@blaine.gmane.org>

On 18/04/17 00:36, Marilyn Davis wrote:
> #!/usr/bin/env python3
> """
> Hello Tutors,
> 
> I can't figure out why the FillWithStars() function puts Canopus in the db
> twice.
> 
> What am I missing?

I don;t know but I converted your script into the more
conventional form and it worked. it was the fetchall()
line that made the difference... I don't understand
why your code seems to behave oddly, but its too late
to figure out right now, hopefully someone else can
answer... Here is my version:

import os, sqlite3, subprocess

def FillWithStars():

    with sqlite3.connect("stars.db") as connection:

        cursor = connection.cursor()
        cursor.execute("DROP TABLE IF EXISTS brightest")

        cursor.execute("""
            CREATE TABLE brightest(
            name,
            constellation,
            apparent_magnitude,
            absolute_magnitude,
            distance)""")
        cursor.execute("""INSERT INTO brightest
                          VALUES("Canopus", "Carina", -0.72, -2.5, 74)""")

        stored_stars = cursor.execute("SELECT * FROM BRIGHTEST")

        for star in stored_stars:
            print('---> ', star)

        cursor.execute("INSERT INTO brightest VALUES(?, ?, ?, ?, ?)",
                           ("Arcturus", "Bootes", -0.04, 0.2, 34))

        stored_stars = cursor.execute("SELECT * FROM BRIGHTEST")

        for star in stored_stars.fetchall():
            print(star)

def main():
    FillWithStars()

if __name__ == '__main__':
    main()


-- 
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 dvnsarma at gmail.com  Mon Apr 17 20:19:33 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Tue, 18 Apr 2017 05:49:33 +0530
Subject: [Tutor] reg. list update
In-Reply-To: <e0d71a95-15cf-2db5-bc5a-f40d43b7b556@wichmann.us>
References: <CAAGUbnkLi5jDg1GRKGn0yee5fHYZ=XLOL86w72LkYg8v=_HZwQ@mail.gmail.com>
 <e0d71a95-15cf-2db5-bc5a-f40d43b7b556@wichmann.us>
Message-ID: <CAOZcEceGcpbVRvPGPQ+D7P+a56SntZ-1uxu2rHZ94dNpNkeR=g@mail.gmail.com>

This is an aliasing problem. Change the code to

super = []
sub = [""]*3
other = ["a","b","c","d"]
sub[0] = "hi"
sub[1] = "hello"
for item in other:
    l = sub[:]
    l[2] = item
    super.append(l)
for item in super:
    print item

regards,
Sarma.

On Tue, Apr 18, 2017 at 2:16 AM, Mats Wichmann <mats at wichmann.us> wrote:

> On 04/17/2017 12:41 PM, Rasika Sapate via Tutor wrote:
> > Dear Python group,
> > I had written following code.
> >
> > super = []
> > sub = [""]*3
> > other = ["a","b","c","d"]
> > sub[0] = "hi"
> > sub[1] = "hello"
> > for item in other:
> >     sub[2] = item
> >     super.append(sub)
> > for item in super:
> >     print item
> >
> >
> > Output :
> > ['hi', 'hello', 'd']
> > ['hi', 'hello', 'd']
> > ['hi', 'hello', 'd']
> > ['hi', 'hello', 'd']
> >
> >
> > Expected output:
> > ['hi', 'hello', 'a]
> > ['hi', 'hello', 'b']
> > ['hi', 'hello', 'c']
> > ['hi', 'hello', 'd']
> >
> >
> > Is there anything wrong in this code or any feature of python?
>
> yeah, feature of Python.  you could google for "deep copy".
>
> in short, sub[2] ends up with a reference to, not a copy of, the object
> referenced by "item" in the first for loop. all four lists hold this
> reference. by the time you go to print, that's a reference to the value
> "item" held when the first loop exited, or 'd'.  item itself no longer
> refers to that, you assign new things to it.
>
> You can see this by adding a couple of debug print lines
>
> super = []
> sub = [""]*3
> other = ["a","b","c","d"]
> sub[0] = "hi"
> sub[1] = "hello"
> for item in other:
>     sub[2] = item
>     print "item id:", id(item)
>     super.append(sub)
> for item in super:
>     print item
>     print "item[2] id:", id(item[2])
> _______________________________________________
> 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  Mon Apr 17 19:13:21 2017
From: phil_lor at bigpond.com (Phil)
Date: Tue, 18 Apr 2017 09:13:21 +1000
Subject: [Tutor] Tkinter and canvas question
Message-ID: <20170418091321.31b3ac8e@raspberrypi>

Thank you for reading this.

How do I reference the_canvas from my solve() method? Despite hours of searching I haven't been able to solve this or find a similar example. All that I've gained is a headache.

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
    return self.func(*args)
  File "/home/pi/sudoku.py", line 64, in solve
    self.the_canvas.create_text(20,20,text="5")
AttributeError: 'Sudoku' object has no attribute 'the_canvas'

from tkinter import *

class Sudoku(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        parent.title("Sudoku solver")    
        
    	#create canvas
        the_canvas = Canvas(width = 300, height = 300)                                         
        the_canvas.pack(side = TOP, anchor = NW, padx = 10, pady = 10)

    	#create grid
                
        #create solve button
        solve_button = Button(the_canvas, text = "Solve", command = self.solve,
                                                                anchor = W)
        solve_button.configure(width = 5, activebackground = "#33B5E5",
                                                            relief = FLAT)
        solve_button.pack(side = TOP)
        solve_button_window = the_canvas.create_window(250, 250, anchor=NW, window=solve_button)

    def solve(self):
        print("solve called")
        self.the_canvas.create_text(20,20,text="5")
            

def main():
    root = Tk()
    app = Sudoku(root)
    app.mainloop()

if __name__ == '__main__':
    main()


-- 
Regards,
Phil

From robertvstepp at gmail.com  Mon Apr 17 22:05:41 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 17 Apr 2017 21:05:41 -0500
Subject: [Tutor] 
	=?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
	=?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python?=
	=?utf-8?q?=22?=
In-Reply-To: <40b908cc-c537-9f61-7ff3-09499cbe48bd@wichmann.us>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <CANDiX9KU0VXAoP8ykZwr1rk4CixG79OjMAoAu9phQ3B7DcgLZA@mail.gmail.com>
 <40b908cc-c537-9f61-7ff3-09499cbe48bd@wichmann.us>
Message-ID: <CANDiX9LmmBcBxqpvBOWvNVsU3N9f0kfh90822vKwsH1nQ+XdjA@mail.gmail.com>

On Sun, Apr 16, 2017 at 11:50 PM, Mats Wichmann <mats at wichmann.us> wrote:

>
> You got me thinking as well, as I don't much care for unittest, at least
> partly because it forces you to use classes even when it doesn't feel
> all that natural.

I have looked into pytest multiple times, but have decided to stick
with unittest until I feel I have mastered its use.  While it forces
the use of classes, this is an advantage for me as I am still in the
beginning stages of learning OOP.  But if I ever make it through these
learning journeys, I will probably switch to using pytest.  Everything
I have read on it to this point has favorably impressed me.

[snip]

> === reverser.py ==
> def slicerev(collection):
>     return collection[::-1]
>
> if __name__ == "__main__":
>     print slicerev([1,2,3,4])
>     print slicerev((1,2,3,4))
>     print slicerev('abcd')
> ===

[snip]

> The actual test function should be pretty straightforward.
>
> === test_slicerev.py ===
> import pytest
>
> from reverser import slicerev
>
> @pytest.fixture(params=[
>     ([1,2,3,4], [4,3,2,1]),
>     ((1,2,3,4), (4,3,2,1)),
>     ('abcd',    'edcba')
>     ])
> def slicedata(request):
>     return request.param
>
> def test_slicerev(slicedata):
>     input, expected = slicedata
>     output = slicerev(input)
>     assert output == expected
> ===

It's funny you picked this type of example.  Last year I was
struggling with getting unittest to feed in data to my test of a
function (or was it a method?), and almost took the plunge and went
all in on pytest because of the apparent ease of handling these types
of situations while respecting DRY.  I did find a way to do something
similar in unittest, so put off pytest for another day.  I cannot
remember now what I did.  I need to go back and find that code (If I
still have it.) and compare it with this Mixin approach that I started
this whole thread with.  Nonetheless pytest is definitely on my radar
and I will get to it at some point.

Thanks!


-- 
boB

From robertvstepp at gmail.com  Mon Apr 17 22:49:12 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 17 Apr 2017 21:49:12 -0500
Subject: [Tutor] 
	=?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
	=?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python?=
	=?utf-8?q?=22?=
In-Reply-To: <od1urr$bt6$1@blaine.gmane.org>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
 <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
 <alpine.LSU.2.11.1704160850280.2663@qnttre.jbaqresebt.arg>
 <CANDiX9LeDOXcA3oLsEi2dscfYP1ME0QEJmwF+tgLkN-2-ir20A@mail.gmail.com>
 <od1urr$bt6$1@blaine.gmane.org>
Message-ID: <CANDiX9J1+ww_NYp7vxU+5UsVRRnFAksCBUxL_g0VG0_4mer3XQ@mail.gmail.com>

Ah, Peter, if only I could achieve your understanding and mastery!

On Mon, Apr 17, 2017 at 3:37 AM, Peter Otten <__peter__ at web.de> wrote:

> Perhaps it becomes clearer if we build our own class discovery / method
> runner system. Given T as the baseclass for classes that provide foo_...()
> methods that we want to run, and M as the mix-in that provides such methods
> but isn't itself a subclass of T...
>

[snip]

> As you can see, to the discovery algorithm it doesn't matter where the
> method is defined, it suffices that it's part of the class and can be found
> by dir() or vars().
>

[snip]

>
> $ cat discovery6.py
> class T:
>     pass
>
> class M:
>     def foo_one(self):
>         print(self.__class__.__name__, "one")
>     def foo_two(self):
>         print(self.__class__.__name__, "two")
>
> class X(T):
>     def foo_x(self):
>         print(self.__class__.__name__, "x")
>
> class Y(M, T):
>     pass
>
> def safe_issubclass(S, B):
>     try:
>         return issubclass(S, B)
>     except TypeError:
>         return False
>
> def discover_Ts():
>     for C in globals().values():
>         if safe_issubclass(C, T) and C is not T:
>             print("found", C, "with foo_... methods")
>             for name in dir(C):
>                 if name.startswith("foo_"):
>                     yield C, name

So your discover function does not need to instantiate any objects; it
just searches the module's global namespace for class names.  Cool!
And dir(C) gives all attributes of C including _inherited_ attributes!
 This clarifies so much.  Many thanks, Peter!

> def run_method(cls, methodname):
>     inst = cls()
>     method = getattr(inst, methodname)
>     method()
>
> def main():
>     for cls, methodname in discover_Ts():
>         run_method(cls, methodname)
>
> if __name__ == "__main__":
>     main()
> $ python3 discovery6.py
> found <class '__main__.Y'> with foo_... methods
> Y one
> Y two
> found <class '__main__.X'> with foo_... methods
> X x
>
> That was easy. We have replicated something similar to the unit test
> framework with very little code.
>
> Now you can go and find the equivalent parts in the unittest source code :)

But not tonight ~(:>))


-- 
boB

From steve at pearwood.info  Mon Apr 17 23:12:43 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 18 Apr 2017 13:12:43 +1000
Subject: [Tutor] sqlite3 making a spurious duplicate?
In-Reply-To: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>
References: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>
Message-ID: <20170418031243.GO9464@ando.pearwood.info>

On Mon, Apr 17, 2017 at 04:36:50PM -0700, Marilyn Davis wrote:
> #!/usr/bin/env python3
> """
> Hello Tutors,
> 
> I can't figure out why the FillWithStars() function puts Canopus in the db
> twice.


Good question. And thank you for providing a really well-written, 
simple, clear script that we can run unchanged to demonstrate the 
problem.

I get the same results as you, and like you, I'm not too sure why. But 
I'm leading to suspect the blame lies with sqlite, not your code.

If I take your script and add the following lines between the call to 
connection.executescript(...) and connection.executemany(...):

        stored_stars = connection.execute("SELECT * FROM BRIGHTEST")
        for star in stored_stars:
            print(star)
        del stored_stars
        print('-'*30)

I get this output:

[steve at ando ~]$ python3 why4.py
('Canopus', 'Carina', -0.72, -2.5, 74)
----------------------------------------
('Canopus', 'Carina', -0.72, -2.5, 74)
('Canopus', 'Carina', -0.72, -2.5, 74)
('Arcturus', 'Bootes', -0.04, 0.2, 34)


so it looks to me like the initial call to executescript() correctly 
adds Canopus once, and then the call to executemany() mysteriously 
duplicates it.

I tried one more iteration: swap the two stars, so that Acturus 
is added first, then Canopus:


[steve at ando ~]$ python3 why5.py
('Arcturus', 'Bootes', -0.04, 0.2, 34)
----------------------------------------
('Arcturus', 'Bootes', -0.04, 0.2, 34)
('Arcturus', 'Bootes', -0.04, 0.2, 34)
('Canopus', 'Carina', -0.72, -2.5, 74)


At this point, I'm not sure whether this is a bug in sqlite, or a 
misunderstanding that we're doing something wrong. I think this now 
needs an sqlite expert.



-- 
Steve

From steve at pearwood.info  Mon Apr 17 23:30:01 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 18 Apr 2017 13:30:01 +1000
Subject: [Tutor] sqlite3 making a spurious duplicate?
In-Reply-To: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>
References: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>
Message-ID: <20170418033001.GP9464@ando.pearwood.info>

I made one more diagnostic change to your script, changing the 
FillWithStars function to this:


def FillWithStars():
    with sqlite3.connect("stars.db") as connection:
        connection.executescript("""
            CREATE TABLE brightest(
            name,
            constellation,
            apparent_magnitude,
            absolute_magnitude,
            distance);
            INSERT INTO brightest VALUES("Arcturus", "Bootes", -0.04, 0.2, 34);""")

        stored_stars = connection.execute("SELECT * FROM BRIGHTEST")
        for star in stored_stars:
            print(star)
        del stored_stars
        print('-'*40)

        connection.executemany("INSERT INTO brightest VALUES(?, ?, ?, ?, ?)",
            [("Canopus", "Carina", -0.72, -2.5, 74),])

        stored_stars = connection.execute("SELECT * FROM BRIGHTEST")
        print("stars as reported inside the with block")
        for star in stored_stars:
            print(star)
        stored_stars = connection.execute("SELECT * FROM BRIGHTEST")

    print("stars as reported outside the with block")
    for star in stored_stars:
        print(star)




As you can see, this now prints the stars from inside the with 
block, while the database connection is still open, and then a second 
time, when the database connection is closed.

The first prints the expected information, the second does not:

[steve at ando ~]$ python3 why5.py
('Arcturus', 'Bootes', -0.04, 0.2, 34)
----------------------------------------
stars as reported inside the with block
('Arcturus', 'Bootes', -0.04, 0.2, 34)
('Canopus', 'Carina', -0.72, -2.5, 74)
stars as reported outside the with block
('Arcturus', 'Bootes', -0.04, 0.2, 34)
('Arcturus', 'Bootes', -0.04, 0.2, 34)
('Canopus', 'Carina', -0.72, -2.5, 74)



So I now expect that this is a misuse of the stored_stars cursor object. 
(Or, possibly, a bug in the cursor object.) If you want to use the 
cursor object, it appears that the connection to the database must be 
open. If you want to use it after closing the database, I think you need 
to extract the data into a list first:

# untested
stored_stars = list(connection.execute("SELECT * FROM BRIGHTEST")



Last but not least, I tried looking at the sqlite database directly:

[steve at ando ~]$ sqlite3 stars.db
SQLite version 3.3.6
Enter ".help" for instructions
sqlite> .databases
seq  name             file
---  ---------------  ----------------------------------------------------------
0    main             /home/steve/stars.db
sqlite> .dump
BEGIN TRANSACTION;
CREATE TABLE brightest(
            name,
            constellation,
            apparent_magnitude,
            absolute_magnitude,
            distance);
INSERT INTO "brightest" VALUES('Arcturus', 'Bootes', -0.04, 0.2, 34);
INSERT INTO "brightest" VALUES('Canopus', 'Carina', -0.72, -2.5, 74);
COMMIT;




So it looks to me that the right data is stored in the database itself, 
it is just a problem with (mis)using a cursor object after the 
connection is closed.

-- 
Steve

From robertvstepp at gmail.com  Mon Apr 17 23:52:56 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 17 Apr 2017 22:52:56 -0500
Subject: [Tutor] Tkinter and canvas question
In-Reply-To: <20170418091321.31b3ac8e@raspberrypi>
References: <20170418091321.31b3ac8e@raspberrypi>
Message-ID: <CANDiX9K2R1Q7WiQNkc8ttbG8wRhPGdYLkZi3Ucv2YxQTLU_qpw@mail.gmail.com>

On Mon, Apr 17, 2017 at 6:13 PM, Phil <phil_lor at bigpond.com> wrote:
> Thank you for reading this.
>
> How do I reference the_canvas from my solve() method? Despite hours of searching I haven't been able to solve this or find a similar example. All that I've gained is a headache.
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
>     return self.func(*args)
>   File "/home/pi/sudoku.py", line 64, in solve
>     self.the_canvas.create_text(20,20,text="5")
> AttributeError: 'Sudoku' object has no attribute 'the_canvas'
>
> from tkinter import *
>
> class Sudoku(Frame):
>     def __init__(self, parent):
>         Frame.__init__(self, parent)
>         self.parent = parent
>
>         parent.title("Sudoku solver")
>
>         #create canvas
>         the_canvas = Canvas(width = 300, height = 300)
>         the_canvas.pack(side = TOP, anchor = NW, padx = 10, pady = 10)
>
>         #create grid
>
>         #create solve button
>         solve_button = Button(the_canvas, text = "Solve", command = self.solve,
>                                                                 anchor = W)
>         solve_button.configure(width = 5, activebackground = "#33B5E5",
>                                                             relief = FLAT)
>         solve_button.pack(side = TOP)
>         solve_button_window = the_canvas.create_window(250, 250, anchor=NW, window=solve_button)
>
>     def solve(self):
>         print("solve called")
>         self.the_canvas.create_text(20,20,text="5")
>
>
> def main():
>     root = Tk()
>     app = Sudoku(root)
>     app.mainloop()
>
> if __name__ == '__main__':
>     main()
>
>
> --
> Regards,
> Phil
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
boB

From robertvstepp at gmail.com  Mon Apr 17 23:57:41 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 17 Apr 2017 22:57:41 -0500
Subject: [Tutor] Tkinter and canvas question
In-Reply-To: <20170418091321.31b3ac8e@raspberrypi>
References: <20170418091321.31b3ac8e@raspberrypi>
Message-ID: <CANDiX9+_rRobcTYWALw+eK1q3xkUU8Y23E5NjEcb+16s-YRSsA@mail.gmail.com>

Sorry for the unnecessary post with no response -- inadvertent click
on "Send" button which was too near Gmail's "..." button to expand
content.

On Mon, Apr 17, 2017 at 6:13 PM, Phil <phil_lor at bigpond.com> wrote:
> Thank you for reading this.
>
> How do I reference the_canvas from my solve() method? Despite hours of searching I haven't been able to solve this or find a similar example. All that I've gained is a headache.
>

I have yet to do much class writing with tkinter, but if I am
understanding things correctly, in your Sudoku class where you
instantiate a Canvas instance, you assign it to the name "the_canvas".
This will be local to the __init__ method's namespace.  I think you
need to precede each of those "the_canvas" with "self." to get
"self.the_canvas".  This way your solve method will be able to access
it.

> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
>     return self.func(*args)
>   File "/home/pi/sudoku.py", line 64, in solve
>     self.the_canvas.create_text(20,20,text="5")
> AttributeError: 'Sudoku' object has no attribute 'the_canvas'
>
> from tkinter import *
>
> class Sudoku(Frame):
>     def __init__(self, parent):
>         Frame.__init__(self, parent)
>         self.parent = parent
>
>         parent.title("Sudoku solver")
>
>         #create canvas
>         the_canvas = Canvas(width = 300, height = 300)
>         the_canvas.pack(side = TOP, anchor = NW, padx = 10, pady = 10)
>
>         #create grid
>
>         #create solve button
>         solve_button = Button(the_canvas, text = "Solve", command = self.solve,
>                                                                 anchor = W)
>         solve_button.configure(width = 5, activebackground = "#33B5E5",
>                                                             relief = FLAT)
>         solve_button.pack(side = TOP)
>         solve_button_window = the_canvas.create_window(250, 250, anchor=NW, window=solve_button)
>
>     def solve(self):
>         print("solve called")
>         self.the_canvas.create_text(20,20,text="5")
>
>
> def main():
>     root = Tk()
>     app = Sudoku(root)
>     app.mainloop()
>
> if __name__ == '__main__':
>     main()
>
>
> --
> Regards,
> Phil
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
boB

From cs at zip.com.au  Tue Apr 18 03:06:45 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Tue, 18 Apr 2017 17:06:45 +1000
Subject: [Tutor] bracket issue
In-Reply-To: <oct5re$81b$1@blaine.gmane.org>
References: <oct5re$81b$1@blaine.gmane.org>
Message-ID: <20170418070645.GA70428@cskk.homeip.net>

On 15Apr2017 14:05, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 15/04/17 03:17, Palm Tree wrote:
>
>> s="2*3+3(8-4(5+6+9))+2+3+3(4/4)"
>>
>> i want to find expression enclosed in brackets.
>>
>> i want outputs to be like:
>> (8-4(5+6+9))
>> (5+6+9)
>> (4/4)
>>
>
>You probably could do it with some fancy regex but personally
>I'd investigate a proper text parser.

The nested brackets thing is something that regexps generally won't do fully, 
because they don't recurse. You could write a regexp to handle up-to-n nestings 
for some finite n, but as soon as that gets above something like 2 you're 
probably into the "don't use regexps for this" domain.

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

From alan.gauld at yahoo.co.uk  Tue Apr 18 03:39:05 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 18 Apr 2017 08:39:05 +0100
Subject: [Tutor] Tkinter and canvas question
In-Reply-To: <20170418091321.31b3ac8e@raspberrypi>
References: <20170418091321.31b3ac8e@raspberrypi>
Message-ID: <od4fqi$mjp$1@blaine.gmane.org>

On 18/04/17 00:13, Phil wrote:
> Thank you for reading this.
> 
> How do I reference the_canvas from my solve() method? 

> class Sudoku(Frame):
>     def __init__(self, parent):
>         Frame.__init__(self, parent)
>         self.parent = parent
> 
>         parent.title("Sudoku solver")    
>         
>     	#create canvas
>         the_canvas = Canvas(width = 300, height = 300)                                         
>         the_canvas.pack(side = TOP, anchor = NW, padx = 10, pady = 10)

You need to store the_canvas as an instance attribute so you need to
precede it with self:

self.the_canvas = Canvas(width=300, height=300


>     	#create grid
>                 
>         #create solve button
>         solve_button = Button(the_canvas, text = "Solve", command = self.solve,
>                                                                 anchor = W)

Similarly with the button

self.solve_button = ....

>         solve_button.configure(width = 5, activebackground = "#33B5E5",
>                                                             relief = FLAT)
>         solve_button.pack(side = TOP)
>         solve_button_window = the_canvas.create_window(250, 250, anchor=NW, window=solve_button)

Without the self your widgets are attached to local variables
that go out of scope as soon as init() ends. You could find
them by traversing the child widget tree of self.parent,
but that's just making life difficult for the sake of 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 __peter__ at web.de  Tue Apr 18 04:15:24 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 18 Apr 2017 10:15:24 +0200
Subject: [Tutor] sqlite3 making a spurious duplicate?
References: <49889.187.254.92.124.1492472210.squirrel@mail.tigertech.net>
Message-ID: <od4hun$ulu$1@blaine.gmane.org>

Marilyn Davis wrote:

> #!/usr/bin/env python3
> """
> Hello Tutors,
> 
> I can't figure out why the FillWithStars() function puts Canopus in the db
> twice.
> 
> What am I missing?
> 
> Thank you for any help.
> 
> Marilyn Davis
> 
> p.s. That Reset(db_name) is in there so that you can run it over and over
> if you want.
> 
> ---
> """
> import os, sqlite3, subprocess
> 
> def Reset(db_name):
>     os.system("rm " + db_name)
>     db_process = subprocess.Popen(("sqlite3", db_name),
>                                    stdin=subprocess.PIPE,
>                                    stdout=subprocess.PIPE,
>                                    stderr=subprocess.PIPE)
>     for send in (b'.tables', ):
>         returned = db_process.communicate(send)
>         assert returned == (b'', b'')
> 
> def FillWithStars():
> 
>     with sqlite3.connect("stars.db") as connection:
> 
>         connection.executescript("""
>             CREATE TABLE brightest(
>             name,
>             constellation,
>             apparent_magnitude,
>             absolute_magnitude,
>             distance);
>             INSERT INTO brightest VALUES("Canopus", "Carina", -0.72, -2.5,
> 74);
> """)
> 
>         connection.executemany("INSERT INTO brightest VALUES(?, ?, ?, ?,
>         ?)",
>             [("Arcturus", "Bootes", -0.04, 0.2, 34),])
> 
>         stored_stars = connection.execute("SELECT * FROM BRIGHTEST")

At this point the connection is closed, and it looks like stored_stars is 
still iterable but contains garbage. 

>     for star in stored_stars:
>         print(star)

Try and indent the lines above one more level so that they are executed 
inside the with-suite.

> 
> def main():
>     Reset("stars.db")
>     FillWithStars()
> 
> if __name__ == '__main__':
>     main()
> 
> """Output:
> 
> bash-3.2$ ./why3.py
> ('Canopus', 'Carina', -0.72, -2.5, 74)
> ('Canopus', 'Carina', -0.72, -2.5, 74)
> ('Arcturus', 'Bootes', -0.04, 0.2, 34)
> bash-3.2$
> """
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



From guettliml at thomas-guettler.de  Tue Apr 18 06:00:04 2017
From: guettliml at thomas-guettler.de (=?UTF-8?Q?Thomas_G=c3=bcttler?=)
Date: Tue, 18 Apr 2017 12:00:04 +0200
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
Message-ID: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>

I would like to have read-only class properties in Python.

I found this http://stackoverflow.com/questions/128573/using-property-on-classmethods
But there are a lot of discussions of things which I don't understand.

I want to be a user of class properties, not an implementer of the details.

I found this: https://pypi.python.org/pypi/classproperty

But above release is more then ten years old. I am unsure if it's dead or mature.

I am using Python 2.7 and attribute getters would be enough, no attribute setter is needed.

My use case is configuration, not fancy algorithms or loops.

Regards,
   Thomas G?ttler

-- 
Thomas Guettler http://www.thomas-guettler.de/

From __peter__ at web.de  Tue Apr 18 07:17:01 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 18 Apr 2017 13:17:01 +0200
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
Message-ID: <od4sja$enr$1@blaine.gmane.org>

Thomas G?ttler wrote:

> I would like to have read-only class properties in Python.
> 
> I found this
> http://stackoverflow.com/questions/128573/using-property-on-classmethods
> But there are a lot of discussions of things which I don't understand.
> 
> I want to be a user of class properties, not an implementer of the
> details.
> 
> I found this: https://pypi.python.org/pypi/classproperty
> 
> But above release is more then ten years old. I am unsure if it's dead or
> mature.
> 
> I am using Python 2.7 and attribute getters would be enough, no attribute
> setter is needed.
> 
> My use case is configuration, not fancy algorithms or loops.

Like this?

$ cat classproperty.py
class classproperty(object):
    def __init__(self, fget):
        self.fget = fget
    def __get__(self, inst, cls):
        return self.fget(cls)


class Foo(object):
    FOO = 42
    @classproperty
    def foo(cls):
        return cls.FOO

print "Foo.foo =", Foo.foo
print "Foo().foo =", Foo().foo
$ python2 classproperty.py 
Foo.foo = 42
Foo().foo = 42



From phil_lor at bigpond.com  Tue Apr 18 01:55:19 2017
From: phil_lor at bigpond.com (Phil)
Date: Tue, 18 Apr 2017 15:55:19 +1000
Subject: [Tutor] Tkinter and canvas question
In-Reply-To: <CANDiX9+_rRobcTYWALw+eK1q3xkUU8Y23E5NjEcb+16s-YRSsA@mail.gmail.com>
References: <20170418091321.31b3ac8e@raspberrypi>
 <CANDiX9+_rRobcTYWALw+eK1q3xkUU8Y23E5NjEcb+16s-YRSsA@mail.gmail.com>
Message-ID: <20170418155519.42bf8e2b@raspberrypi>

On Mon, 17 Apr 2017 22:57:41 -0500
boB Stepp <robertvstepp at gmail.com> wrote:

> I have yet to do much class writing with tkinter, but if I am
> understanding things correctly, in your Sudoku class where you
> instantiate a Canvas instance, you assign it to the name "the_canvas".
> This will be local to the __init__ method's namespace.  I think you
> need to precede each of those "the_canvas" with "self." to get
> "self.the_canvas".  This way your solve method will be able to access
> it.

Thank you Bob. I was fixated on the error being elsewhere and didn't think about the_canvas being just another attribute of the class. It seem obvious now that I've been shown.

-- 
Regards,
Phil

From alan.gauld at yahoo.co.uk  Tue Apr 18 10:51:32 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 18 Apr 2017 15:51:32 +0100
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
In-Reply-To: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
Message-ID: <od595e$shn$1@blaine.gmane.org>

On 18/04/17 11:00, Thomas G?ttler wrote:
> I would like to have read-only class properties in Python.

Is there a specific reason why? Do you think for example
that users of the class will deliberately try to modify
the attribute? Normally in Python we leave all attributes
public and unprotected (possibly with a naming hint) and
rely on our users being sensible.

> I want to be a user of class properties, not an implementer of the details.

I'm not sure what exactly you mean by that but...

> I am using Python 2.7 and attribute getters would be enough, no attribute setter is needed.
> 

The default for @property is a read only attribute so

class Spam(object):
   @property
   def eggs(self):
       return self._eggs

   def __init__(self,value):
       self._eggs = value   #initialise it

s = Spam(66)

print s.eggs    # ok
s.eggs = 666    # error, read only.
s._eggs = 666  # can be set
print s._eggs  # still 66
print s.eggs    # oops is now 666

Is that sufficient? If so easy.

But if you want to prevent access to _eggs
from outside that's trickier. But you would
need a very good reason to complicate your
life that much...

Or do you really want a class level property?
In which case refer to Peter's comment.

-- 
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 mats at wichmann.us  Tue Apr 18 09:47:27 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 18 Apr 2017 07:47:27 -0600
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
In-Reply-To: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
Message-ID: <4933707a-68ec-801f-ac2f-646a6da34cbb@wichmann.us>

On 04/18/2017 04:00 AM, Thomas G?ttler wrote:
> I would like to have read-only class properties in Python.
> 
> I found this
> http://stackoverflow.com/questions/128573/using-property-on-classmethods
> But there are a lot of discussions of things which I don't understand.
> 
> I want to be a user of class properties, not an implementer of the details.
> 
> I found this: https://pypi.python.org/pypi/classproperty
> 
> But above release is more then ten years old. I am unsure if it's dead
> or mature.
> 
> I am using Python 2.7 and attribute getters would be enough, no
> attribute setter is needed.
> 
> My use case is configuration, not fancy algorithms or loops.
> 
> Regards,
>   Thomas G?ttler
> 

Not clear if you're asking for something more than the standard Python
properties.  The discussion you mention does go into additional
discussion which describes techniques for applying this to a class
attribute. In other words, is this quote a problem for you?

"The get method [of a property] won't be called when the property is
accessed as a class attribute (C.x) instead of as an instance attribute
(C().x). "

If applying to instance attributes is fine for your case, then the
property() call or the related decorators should do the trick, as in:

    def get_temperature(self):
        return self._temperature

    def set_temperature(self, value):
        self._temperature = value

    temperature = property(get_temperature,set_temperature)

or, as is probably preferred:

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        self._temperature = value

(obviously both a getter and setter)

Note it's Python convention to use an underscore-prefixed variable name
to indicate it is "private", and you often see a backing store for the
property written like I did above, but nothing in Python enforces this
privacy, someone could fiddle directly with instance._temperature

Also ask yourself whether you really _need_ a property here?  Or would a
public data member be sufficient.  (Just asking, have no idea what's
inside your use case)


From rafael.knuth at gmail.com  Tue Apr 18 12:55:27 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Tue, 18 Apr 2017 18:55:27 +0200
Subject: [Tutor] Visual Studio Community 2017
Message-ID: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>

I wanted to start my first project using matplotlib (I have never
worked with libraries before). I am trying to get started with VS
Community 2017, and I am having trouble performing the most basic
tasks such as installing matplotlib. Anyone here using VS 2017? Or,
can anyone recommend an alternative to VS for Windows? Thanks!

From alan.gauld at yahoo.co.uk  Tue Apr 18 13:14:28 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 18 Apr 2017 18:14:28 +0100
Subject: [Tutor] Visual Studio Community 2017
In-Reply-To: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>
References: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>
Message-ID: <od5hhd$m0i$1@blaine.gmane.org>

On 18/04/17 17:55, Rafael Knuth wrote:
> I wanted to start my first project using matplotlib (I have never
> worked with libraries before). 

Every time you do an import you are using a library.
eg

import sys
import os
etc

It's no big deal.

> I am trying to get started with VS Community 2017, 
> and I am having trouble performing the most basic
> tasks such as installing matplotlib. Anyone here using VS 2017? 

VS is great for .NET development for Windows but frankly
for anything else I prefer Eclipse or Netbeans as IDEs.
But personally I don't much like big greedy IDEs (unless
I'm writing Java) so I tend to just use a text editor
(vim or notepad++ on windows) and a Python shell
 - possibly even IDLE. I also use the Pythonwin IDE
if I'm doing any COM type work because of its debugger
and built in COM browser.

But editors and IDEs are very personal choices. The best
thing is to download a few and play with them. There is
no shortage of candidates to pick 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 mats at wichmann.us  Tue Apr 18 14:01:46 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 18 Apr 2017 12:01:46 -0600
Subject: [Tutor] Visual Studio Community 2017
In-Reply-To: <od5hhd$m0i$1@blaine.gmane.org>
References: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>
 <od5hhd$m0i$1@blaine.gmane.org>
Message-ID: <73b13e0b-90e7-6409-5743-d3ab7dee72b8@wichmann.us>

On 04/18/2017 11:14 AM, Alan Gauld via Tutor wrote:
> On 18/04/17 17:55, Rafael Knuth wrote:
>> I wanted to start my first project using matplotlib (I have never
>> worked with libraries before). 
> 
> Every time you do an import you are using a library.
> eg
> 
> import sys
> import os
> etc
> 
> It's no big deal.
> 
>> I am trying to get started with VS Community 2017, 
>> and I am having trouble performing the most basic
>> tasks such as installing matplotlib. Anyone here using VS 2017? 
> 
> VS is great for .NET development for Windows but frankly
> for anything else I prefer Eclipse or Netbeans as IDEs.
> But personally I don't much like big greedy IDEs (unless
> I'm writing Java) so I tend to just use a text editor
> (vim or notepad++ on windows) and a Python shell
>  - possibly even IDLE. I also use the Pythonwin IDE
> if I'm doing any COM type work because of its debugger
> and built in COM browser.
> 
> But editors and IDEs are very personal choices. The best
> thing is to download a few and play with them. There is
> no shortage of candidates to pick from!
> 

PyCharm :)

anyway, some thoughts on using VS, which I only recommend if you're
already a dedicated VS user (same general comment as Alan).

"libraries" other than the python standard library do need installation,
which in many cases is done through the PIP tool (on Windows there are
often also pre-built packages installed the normal way, which you can
resort to if something doesn't work using PIP - since you have a full
build environment known to be there with VS 2017, it should work though.

VS has a Python tools addon, which you should install if it's not there
already.

you can then go Tools -> Options -> Python Tools -> Environment Options

look at the paths in the existing environment (matching your installed
Python version) and remember them

create a new environment by clicking Add Environment (the existing one
will probably work, but I don't know how to get around VS's idea it's
fully managing it, and we want to install packages).

in new environment,  fill in the paths.  There's a way to auto-detect
(in a different screen) but on my VS 2015 install at least it seems to
always be greyed out.

You should have a Python Environments on the right, another tab where
there's usually the Solution Explorer.  If it's not open, you can get it
from View -> Other Windows.

pick "pip" from the drop-down, and search for the pkgs you want - just
typing matplotlib should give you a bunch of choices, and that should
also deal with dependencies.  That windo may also offer some existing
pkgs that need updating.


anyway, this sort of thing has worked for me in limited experiments.
Then it's just "import whatever" as Alan says.





From mats at wichmann.us  Tue Apr 18 14:09:18 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 18 Apr 2017 12:09:18 -0600
Subject: [Tutor] Visual Studio Community 2017
In-Reply-To: <od5hhd$m0i$1@blaine.gmane.org>
References: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>
 <od5hhd$m0i$1@blaine.gmane.org>
Message-ID: <36112f4d-0d22-259d-7c14-af31acf3411e@wichmann.us>



...

naturally, far better than what I wrote, is:

https://docs.microsoft.com/en-us/visualstudio/python/python-environments




From joskerc at gmail.com  Tue Apr 18 19:21:47 2017
From: joskerc at gmail.com (Jos Kerc)
Date: Wed, 19 Apr 2017 01:21:47 +0200
Subject: [Tutor] Visual Studio Community 2017
In-Reply-To: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>
References: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>
Message-ID: <CAKs9EsuZQ-udxf_W2_8ohov2OMLDuMiZ6Y6qDvFuDYgLY_rBsQ@mail.gmail.com>

Hi,

you might want to look at things like Anaconda, Enthought, ... They come
with lots of packages/libraries pre-installed and a complete programming
environment. For small project, you could even look at Jupyter. I t allows
you to have your program, data & results (IIRC even pics & vids) in
something like a webpage.
Have fun.
On Apr 18, 2017 7:08 PM, "Rafael Knuth" <rafael.knuth at gmail.com> wrote:

> I wanted to start my first project using matplotlib (I have never
> worked with libraries before). I am trying to get started with VS
> Community 2017, and I am having trouble performing the most basic
> tasks such as installing matplotlib. Anyone here using VS 2017? Or,
> can anyone recommend an alternative to VS for Windows? Thanks!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From martin at linux-ip.net  Wed Apr 19 00:45:23 2017
From: martin at linux-ip.net (Martin A. Brown)
Date: Tue, 18 Apr 2017 21:45:23 -0700
Subject: [Tutor] 
 =?utf-8?q?Do_not_understand_code_snippet_from_=2226=2E8?=
 =?utf-8?q?=2E_test_=E2=80=94_Regression_tests_package_for_Python=22?=
In-Reply-To: <CANDiX9LeDOXcA3oLsEi2dscfYP1ME0QEJmwF+tgLkN-2-ir20A@mail.gmail.com>
References: <CANDiX9+7CdA==d=v1x8NAL4iAqW5mZAxrdLPEkPqES8ZnTbZgA@mail.gmail.com>
 <ocuagv$5im$1@blaine.gmane.org>
 <CANDiX9KVpnOf3urC81uQgVC5sr8_d3-zqAMgNhr2RBq=HhKpig@mail.gmail.com>
 <alpine.LSU.2.11.1704160850280.2663@qnttre.jbaqresebt.arg>
 <CANDiX9LeDOXcA3oLsEi2dscfYP1ME0QEJmwF+tgLkN-2-ir20A@mail.gmail.com>
Message-ID: <alpine.LSU.2.11.1704182104590.2715@znpeba.jbaqresebt.arg>


Greetings,

>Thank you very much Martin; you filled in a lot of details.  I had an
>overall understanding of what unittest does, but you have now enhanced
>that understanding substantially.

Happy to help!  I'll introduce you to my little menagerie below!

>I'm still iffy on how the mixin class gets its test method called 
>when this class does not subclass from unittest.TestCase, but I 
>think I may have an idea now on how it is happening.  Let's get to 
>that part of your response.

Well, the mixin technique is not strictly speaking unittest related, 
but more a matter of understanding multiple inheritance.  Once you 
understand that a bit better, I think you'll understand why this 
technique for using unittest works as it does.

>> I'll make a few observations:
>>
>>   - [on unittest] the unit testing tools use classes because it's a
>>     natural way to accommodate the goal of reproducibly setting up
>>     arguments and/or an environment for each test (note that each
>>     TestCase can have its own setUp() and tearDown() methods; this
>>     allows isolation)
>>
>>   - [on unittest] each test collected by the TestLoader can be any
>>     Python class (as long as it is also derived from
>>     unittest.TestCase)

I'll emphasize this point before going on further.  All 
unittest.TestLoader cares about is that it has found (for example) 
an instance of something that is a unittest.TestCase.  Your class 
can inherit from any number of other classes, but 
unittest.TestLoader will not find it, unless it also derives from 
unittest.TestCase.

Now, on to the MRO bits.

>>   - [on your classes] your classes use a multiple inheritance
>>     model, deriving from TestFuncAcceptsSequencesMixin; when
>>     instantiated, they'll have all of the expected TestCase methods
>>     and the method called 'test_func'
>
>It is here that I am struggling.  If the mixin class does not inherit
>from unittest.TestCase, then how is test_func ever seen?

Your classes (AcceptLists, AcceptTuples, AcceptStrings) specify both 
unittest.TestCase and TestFuncAcceptsSequencesMixin.  This is 
multiple inheritance.  (N.B. I'm not sure where to recommend further 
reading on MRO, but others on the list may know.)

So, how is test_func ever seen?  After your class is defined (and 
instantiated), the instance has access to all of the methods of all 
of the parent classes.

In your case:

  * One of the parent classes of AcceptTuples is 
    TestFuncAcceptsSequencesMixin which defines the method 
    test_func.

  * The method 'test_func' matches the expectation of unittest when 
    it goes looking for any method that matches the name 'test_*'.  

The number of methods on instances of unittest.TestCase class is 
higher (see at bottom of this email), but you will see your 
test_func method exists on each instance of the classes you created.

>This answers one important thing I was wondering about:  How do the
>classes AcceptLists, AcceptStrings, and AcceptTuples get instantiated?
>Apparently the unittest machinery does this for me.

Yes.

>>     - for each method name starting with 'test_' (you have only
>>       'test_func') TestRunner will:
>
>And here is my precise sticking point:  How does the TestRunner 
>find test_func?  The classes it has collected and instantiated 
>(AcceptLists, AcceptStrings and AcceptTuples) do not themselves 
>call and make use of the test_func method they inherit from the 
>mixin class.

It looks for methods whose names match a specific pattern.  The name 
should start with 'test_*' (this is configurable if you wanted your 
tests to begin with 'frobnitz_', but I haven't seen anybody do 
this).

>>       - execute the T.setUp() method if it exists
>>
>>       - TestRunner will execute the method 'test_func'
>
>The only thing that makes sense to me is that the TestRunner 
>follows the MRO of the inherited classes and checks for any 
>test_xxx methods that might exist in those superclasses.  Is this 
>correct or do I have a conceptual misunderstanding?

No misunderstanding.  All that's happening here is that unittest is 
defining your class (which imports / inherits everything it needs) 
and then is looking for the 'test_*' methods.

You may (or may not) benefit from studying the MRO any further, but 
here's a function you could call to see multiple inheritance in 
action.  Feed this function an instance of your class:

  def log_class_method_names(*args):
      import inspect
      for o in args:
          logging.info("Class %s found", o.__class__.__name__)
          for methodname, _ in inspect.getmembers(o, inspect.ismethod):
              logging.info("Class %s has method %s", o.__class__.__name__, methodname)

If you try that with three instances of your classes, you should see all of the
methods that unittest will see after the class is instantiated (see also at the
foot of this email).

See below my signature if you are a chimera aficianado,

-Martin

sample script to identify chimera features
-------------------------------------------

import sys
import unittest
import logging

logging.basicConfig(stream=sys.stderr, level=logging.INFO)
logger = logging.getLogger()


def log_class_method_names(*args):
    import pprint
    import inspect
    for o in args:
        logging.info("Class %s found", o.__class__.__name__)
        for methodname, _ in inspect.getmembers(o, inspect.ismethod):
            logging.info("Class %s has method %s", o.__class__.__name__, methodname)


class Cat(object):

    def meow(self):
        return True


class Snake(object):

    def hiss(self):
        return True


class Plant(object):

    def wilt(self):
        return True


class CatPlant(Cat, Plant):
    pass


class SnakeCat(Snake, Cat):
    pass


class PlantCatSnake(Plant, Cat, Snake):
    pass


if __name__ == '__main__':
    # -- find the things that each of these normal critters can do
    #    and then, the chimeras, too
    log_class_method_names(Cat(), Snake(), Plant(), CatPlant(), SnakeCat(), PlantCatSnake())

-------------


output of log_class_method_names(AcceptLists(), AcceptTuples(), AcceptStrings())
--------------------------------------------------------------------------------
INFO:root:Class AcceptLists found
INFO:root:Class AcceptLists has method __call__
INFO:root:Class AcceptLists has method __eq__
INFO:root:Class AcceptLists has method __hash__
INFO:root:Class AcceptLists has method __init__
INFO:root:Class AcceptLists has method __repr__
INFO:root:Class AcceptLists has method __str__
INFO:root:Class AcceptLists has method _addExpectedFailure
INFO:root:Class AcceptLists has method _addSkip
INFO:root:Class AcceptLists has method _addUnexpectedSuccess
INFO:root:Class AcceptLists has method _baseAssertEqual
INFO:root:Class AcceptLists has method _deprecate
INFO:root:Class AcceptLists has method _feedErrorsToResult
INFO:root:Class AcceptLists has method _formatMessage
INFO:root:Class AcceptLists has method _getAssertEqualityFunc
INFO:root:Class AcceptLists has method _truncateMessage
INFO:root:Class AcceptLists has method addCleanup
INFO:root:Class AcceptLists has method addTypeEqualityFunc
INFO:root:Class AcceptLists has method assertAlmostEqual
INFO:root:Class AcceptLists has method assertAlmostEquals
INFO:root:Class AcceptLists has method assertCountEqual
INFO:root:Class AcceptLists has method assertDictContainsSubset
INFO:root:Class AcceptLists has method assertDictEqual
INFO:root:Class AcceptLists has method assertEqual
INFO:root:Class AcceptLists has method assertEquals
INFO:root:Class AcceptLists has method assertFalse
INFO:root:Class AcceptLists has method assertGreater
INFO:root:Class AcceptLists has method assertGreaterEqual
INFO:root:Class AcceptLists has method assertIn
INFO:root:Class AcceptLists has method assertIs
INFO:root:Class AcceptLists has method assertIsInstance
INFO:root:Class AcceptLists has method assertIsNone
INFO:root:Class AcceptLists has method assertIsNot
INFO:root:Class AcceptLists has method assertIsNotNone
INFO:root:Class AcceptLists has method assertLess
INFO:root:Class AcceptLists has method assertLessEqual
INFO:root:Class AcceptLists has method assertListEqual
INFO:root:Class AcceptLists has method assertLogs
INFO:root:Class AcceptLists has method assertMultiLineEqual
INFO:root:Class AcceptLists has method assertNotAlmostEqual
INFO:root:Class AcceptLists has method assertNotAlmostEquals
INFO:root:Class AcceptLists has method assertNotEqual
INFO:root:Class AcceptLists has method assertNotEquals
INFO:root:Class AcceptLists has method assertNotIn
INFO:root:Class AcceptLists has method assertNotIsInstance
INFO:root:Class AcceptLists has method assertNotRegex
INFO:root:Class AcceptLists has method assertRaises
INFO:root:Class AcceptLists has method assertRaisesRegex
INFO:root:Class AcceptLists has method assertRaisesRegexp
INFO:root:Class AcceptLists has method assertRegex
INFO:root:Class AcceptLists has method assertRegexpMatches
INFO:root:Class AcceptLists has method assertSequenceEqual
INFO:root:Class AcceptLists has method assertSetEqual
INFO:root:Class AcceptLists has method assertTrue
INFO:root:Class AcceptLists has method assertTupleEqual
INFO:root:Class AcceptLists has method assertWarns
INFO:root:Class AcceptLists has method assertWarnsRegex
INFO:root:Class AcceptLists has method assert_
INFO:root:Class AcceptLists has method countTestCases
INFO:root:Class AcceptLists has method debug
INFO:root:Class AcceptLists has method defaultTestResult
INFO:root:Class AcceptLists has method doCleanups
INFO:root:Class AcceptLists has method fail
INFO:root:Class AcceptLists has method failIf
INFO:root:Class AcceptLists has method failIfAlmostEqual
INFO:root:Class AcceptLists has method failIfEqual
INFO:root:Class AcceptLists has method failUnless
INFO:root:Class AcceptLists has method failUnlessAlmostEqual
INFO:root:Class AcceptLists has method failUnlessEqual
INFO:root:Class AcceptLists has method failUnlessRaises
INFO:root:Class AcceptLists has method func
INFO:root:Class AcceptLists has method id
INFO:root:Class AcceptLists has method run
INFO:root:Class AcceptLists has method setUp
INFO:root:Class AcceptLists has method setUpClass
INFO:root:Class AcceptLists has method shortDescription
INFO:root:Class AcceptLists has method skipTest
INFO:root:Class AcceptLists has method subTest
INFO:root:Class AcceptLists has method tearDown
INFO:root:Class AcceptLists has method tearDownClass
INFO:root:Class AcceptLists has method test_func
INFO:root:Class AcceptTuples found
INFO:root:Class AcceptTuples has method __call__
INFO:root:Class AcceptTuples has method __eq__
INFO:root:Class AcceptTuples has method __hash__
INFO:root:Class AcceptTuples has method __init__
INFO:root:Class AcceptTuples has method __repr__
INFO:root:Class AcceptTuples has method __str__
INFO:root:Class AcceptTuples has method _addExpectedFailure
INFO:root:Class AcceptTuples has method _addSkip
INFO:root:Class AcceptTuples has method _addUnexpectedSuccess
INFO:root:Class AcceptTuples has method _baseAssertEqual
INFO:root:Class AcceptTuples has method _deprecate
INFO:root:Class AcceptTuples has method _feedErrorsToResult
INFO:root:Class AcceptTuples has method _formatMessage
INFO:root:Class AcceptTuples has method _getAssertEqualityFunc
INFO:root:Class AcceptTuples has method _truncateMessage
INFO:root:Class AcceptTuples has method addCleanup
INFO:root:Class AcceptTuples has method addTypeEqualityFunc
INFO:root:Class AcceptTuples has method assertAlmostEqual
INFO:root:Class AcceptTuples has method assertAlmostEquals
INFO:root:Class AcceptTuples has method assertCountEqual
INFO:root:Class AcceptTuples has method assertDictContainsSubset
INFO:root:Class AcceptTuples has method assertDictEqual
INFO:root:Class AcceptTuples has method assertEqual
INFO:root:Class AcceptTuples has method assertEquals
INFO:root:Class AcceptTuples has method assertFalse
INFO:root:Class AcceptTuples has method assertGreater
INFO:root:Class AcceptTuples has method assertGreaterEqual
INFO:root:Class AcceptTuples has method assertIn
INFO:root:Class AcceptTuples has method assertIs
INFO:root:Class AcceptTuples has method assertIsInstance
INFO:root:Class AcceptTuples has method assertIsNone
INFO:root:Class AcceptTuples has method assertIsNot
INFO:root:Class AcceptTuples has method assertIsNotNone
INFO:root:Class AcceptTuples has method assertLess
INFO:root:Class AcceptTuples has method assertLessEqual
INFO:root:Class AcceptTuples has method assertListEqual
INFO:root:Class AcceptTuples has method assertLogs
INFO:root:Class AcceptTuples has method assertMultiLineEqual
INFO:root:Class AcceptTuples has method assertNotAlmostEqual
INFO:root:Class AcceptTuples has method assertNotAlmostEquals
INFO:root:Class AcceptTuples has method assertNotEqual
INFO:root:Class AcceptTuples has method assertNotEquals
INFO:root:Class AcceptTuples has method assertNotIn
INFO:root:Class AcceptTuples has method assertNotIsInstance
INFO:root:Class AcceptTuples has method assertNotRegex
INFO:root:Class AcceptTuples has method assertRaises
INFO:root:Class AcceptTuples has method assertRaisesRegex
INFO:root:Class AcceptTuples has method assertRaisesRegexp
INFO:root:Class AcceptTuples has method assertRegex
INFO:root:Class AcceptTuples has method assertRegexpMatches
INFO:root:Class AcceptTuples has method assertSequenceEqual
INFO:root:Class AcceptTuples has method assertSetEqual
INFO:root:Class AcceptTuples has method assertTrue
INFO:root:Class AcceptTuples has method assertTupleEqual
INFO:root:Class AcceptTuples has method assertWarns
INFO:root:Class AcceptTuples has method assertWarnsRegex
INFO:root:Class AcceptTuples has method assert_
INFO:root:Class AcceptTuples has method countTestCases
INFO:root:Class AcceptTuples has method debug
INFO:root:Class AcceptTuples has method defaultTestResult
INFO:root:Class AcceptTuples has method doCleanups
INFO:root:Class AcceptTuples has method fail
INFO:root:Class AcceptTuples has method failIf
INFO:root:Class AcceptTuples has method failIfAlmostEqual
INFO:root:Class AcceptTuples has method failIfEqual
INFO:root:Class AcceptTuples has method failUnless
INFO:root:Class AcceptTuples has method failUnlessAlmostEqual
INFO:root:Class AcceptTuples has method failUnlessEqual
INFO:root:Class AcceptTuples has method failUnlessRaises
INFO:root:Class AcceptTuples has method func
INFO:root:Class AcceptTuples has method id
INFO:root:Class AcceptTuples has method run
INFO:root:Class AcceptTuples has method setUp
INFO:root:Class AcceptTuples has method setUpClass
INFO:root:Class AcceptTuples has method shortDescription
INFO:root:Class AcceptTuples has method skipTest
INFO:root:Class AcceptTuples has method subTest
INFO:root:Class AcceptTuples has method tearDown
INFO:root:Class AcceptTuples has method tearDownClass
INFO:root:Class AcceptTuples has method test_func
INFO:root:Class AcceptStrings found
INFO:root:Class AcceptStrings has method __call__
INFO:root:Class AcceptStrings has method __eq__
INFO:root:Class AcceptStrings has method __hash__
INFO:root:Class AcceptStrings has method __init__
INFO:root:Class AcceptStrings has method __repr__
INFO:root:Class AcceptStrings has method __str__
INFO:root:Class AcceptStrings has method _addExpectedFailure
INFO:root:Class AcceptStrings has method _addSkip
INFO:root:Class AcceptStrings has method _addUnexpectedSuccess
INFO:root:Class AcceptStrings has method _baseAssertEqual
INFO:root:Class AcceptStrings has method _deprecate
INFO:root:Class AcceptStrings has method _feedErrorsToResult
INFO:root:Class AcceptStrings has method _formatMessage
INFO:root:Class AcceptStrings has method _getAssertEqualityFunc
INFO:root:Class AcceptStrings has method _truncateMessage
INFO:root:Class AcceptStrings has method addCleanup
INFO:root:Class AcceptStrings has method addTypeEqualityFunc
INFO:root:Class AcceptStrings has method assertAlmostEqual
INFO:root:Class AcceptStrings has method assertAlmostEquals
INFO:root:Class AcceptStrings has method assertCountEqual
INFO:root:Class AcceptStrings has method assertDictContainsSubset
INFO:root:Class AcceptStrings has method assertDictEqual
INFO:root:Class AcceptStrings has method assertEqual
INFO:root:Class AcceptStrings has method assertEquals
INFO:root:Class AcceptStrings has method assertFalse
INFO:root:Class AcceptStrings has method assertGreater
INFO:root:Class AcceptStrings has method assertGreaterEqual
INFO:root:Class AcceptStrings has method assertIn
INFO:root:Class AcceptStrings has method assertIs
INFO:root:Class AcceptStrings has method assertIsInstance
INFO:root:Class AcceptStrings has method assertIsNone
INFO:root:Class AcceptStrings has method assertIsNot
INFO:root:Class AcceptStrings has method assertIsNotNone
INFO:root:Class AcceptStrings has method assertLess
INFO:root:Class AcceptStrings has method assertLessEqual
INFO:root:Class AcceptStrings has method assertListEqual
INFO:root:Class AcceptStrings has method assertLogs
INFO:root:Class AcceptStrings has method assertMultiLineEqual
INFO:root:Class AcceptStrings has method assertNotAlmostEqual
INFO:root:Class AcceptStrings has method assertNotAlmostEquals
INFO:root:Class AcceptStrings has method assertNotEqual
INFO:root:Class AcceptStrings has method assertNotEquals
INFO:root:Class AcceptStrings has method assertNotIn
INFO:root:Class AcceptStrings has method assertNotIsInstance
INFO:root:Class AcceptStrings has method assertNotRegex
INFO:root:Class AcceptStrings has method assertRaises
INFO:root:Class AcceptStrings has method assertRaisesRegex
INFO:root:Class AcceptStrings has method assertRaisesRegexp
INFO:root:Class AcceptStrings has method assertRegex
INFO:root:Class AcceptStrings has method assertRegexpMatches
INFO:root:Class AcceptStrings has method assertSequenceEqual
INFO:root:Class AcceptStrings has method assertSetEqual
INFO:root:Class AcceptStrings has method assertTrue
INFO:root:Class AcceptStrings has method assertTupleEqual
INFO:root:Class AcceptStrings has method assertWarns
INFO:root:Class AcceptStrings has method assertWarnsRegex
INFO:root:Class AcceptStrings has method assert_
INFO:root:Class AcceptStrings has method countTestCases
INFO:root:Class AcceptStrings has method debug
INFO:root:Class AcceptStrings has method defaultTestResult
INFO:root:Class AcceptStrings has method doCleanups
INFO:root:Class AcceptStrings has method fail
INFO:root:Class AcceptStrings has method failIf
INFO:root:Class AcceptStrings has method failIfAlmostEqual
INFO:root:Class AcceptStrings has method failIfEqual
INFO:root:Class AcceptStrings has method failUnless
INFO:root:Class AcceptStrings has method failUnlessAlmostEqual
INFO:root:Class AcceptStrings has method failUnlessEqual
INFO:root:Class AcceptStrings has method failUnlessRaises
INFO:root:Class AcceptStrings has method func
INFO:root:Class AcceptStrings has method id
INFO:root:Class AcceptStrings has method run
INFO:root:Class AcceptStrings has method setUp
INFO:root:Class AcceptStrings has method setUpClass
INFO:root:Class AcceptStrings has method shortDescription
INFO:root:Class AcceptStrings has method skipTest
INFO:root:Class AcceptStrings has method subTest
INFO:root:Class AcceptStrings has method tearDown
INFO:root:Class AcceptStrings has method tearDownClass
INFO:root:Class AcceptStrings has method test_func

-- 
Martin A. Brown
http://linux-ip.net/

From guettliml at thomas-guettler.de  Wed Apr 19 03:28:26 2017
From: guettliml at thomas-guettler.de (=?UTF-8?Q?Thomas_G=c3=bcttler?=)
Date: Wed, 19 Apr 2017 09:28:26 +0200
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
In-Reply-To: <od4sja$enr$1@blaine.gmane.org>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
Message-ID: <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>

Am 18.04.2017 um 13:17 schrieb Peter Otten:
> Thomas G?ttler wrote:
>
>> I would like to have read-only class properties in Python.
>>
>> I found this
>> http://stackoverflow.com/questions/128573/using-property-on-classmethods
>> But there are a lot of discussions of things which I don't understand.
>>
>> I want to be a user of class properties, not an implementer of the
>> details.
>>
>> I found this: https://pypi.python.org/pypi/classproperty
>>
>> But above release is more then ten years old. I am unsure if it's dead or
>> mature.
>>
>> I am using Python 2.7 and attribute getters would be enough, no attribute
>> setter is needed.
>>
>> My use case is configuration, not fancy algorithms or loops.
>
> Like this?
>
> $ cat classproperty.py
> class classproperty(object):
>     def __init__(self, fget):
>         self.fget = fget
>     def __get__(self, inst, cls):
>         return self.fget(cls)
>
>
> class Foo(object):
>     FOO = 42
>     @classproperty
>     def foo(cls):
>         return cls.FOO
>
> print "Foo.foo =", Foo.foo
> print "Foo().foo =", Foo().foo
> $ python2 classproperty.py
> Foo.foo = 42
> Foo().foo = 42

Nice, if it is that simple.

Is there a reason why this is not in the standard library?

Regards,
   Thomas G?ttler



-- 
Thomas Guettler http://www.thomas-guettler.de/

From marilyn at pythontrainer.com  Tue Apr 18 22:21:49 2017
From: marilyn at pythontrainer.com (Marilyn Davis)
Date: Tue, 18 Apr 2017 19:21:49 -0700 (PDT)
Subject: [Tutor] sqlite3 making a spurious duplicate?
Message-ID: <55142.187.254.92.124.1492568509.squirrel@mail.tigertech.net>

Thank you Alan, Steven and Peter,

So, this call:

connection.execute("SELECT * FROM BRIGHTEST")

returns a <sqlite3.Cursor object at 0x101bda260>, not a regular python
sequence.  I did not know that.  And, the connection must still be alive
when you iterate it.

That is a very important tidbit of info.

The fix is to listify the Cursor object, or iterate while still in the
context.  Interesting.  Closing the context and opening a new one fixes it
too:

    with sqlite3.connect("stars.db") as connection:

        connection.executescript("""
            CREATE TABLE brightest(
            name,
            constellation,
            apparent_magnitude,
            absolute_magnitude,
            distance);
            INSERT INTO brightest VALUES("Canopus", "Carina", -0.72, -2.5,
74);
""")

        connection.executemany("INSERT INTO brightest VALUES(?, ?, ?, ?, ?)",
            [("Arcturus", "Bootes", -0.04, 0.2, 34),])

    with sqlite3.connect("stars.db") as connection:
        stored_stars = connection.execute("SELECT * FROM BRIGHTEST")

    for star in stored_stars:
        print(star)

---
But starting a new context, instead, before the executemany does not fix
it!  We still get the duplicate Canopus in the iterable, even though it
was inserted into the data a different context.

I suspect that this is not an intended behavior.

Another question: is it a good principle to try to only put SQL in the
context, and then regular python outside that context?  It suits my
instinct  but maybe it is just my superstition?

Thank you so much.

Marilyn

p.s.  Thank you, Steven, for liking the post.  You guys prove what I try
to pound into students: pretty code that does not work is much better than
hard-to-read code, even if it works -- because with pretty code, people
are happy to help you, and with working bad code, when it must be
modified, you have a mess.





From alan.gauld at yahoo.co.uk  Wed Apr 19 03:43:09 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Apr 2017 08:43:09 +0100
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
In-Reply-To: <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
Message-ID: <od74e6$2em$1@blaine.gmane.org>

On 19/04/17 08:28, Thomas G?ttler wrote:

> Nice, if it is that simple.
> 
> Is there a reason why this is not in the standard library?

Probably because it is such a rare use case and because
its not that hard to do yourself if you really need it.

But the standard library, like any open source project,
develops as people need things. If nobody needs something
it will never be built and therefore never be added to
the library. I'd guess this falls into that category.


-- 
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 Apr 19 04:35:08 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Apr 2017 09:35:08 +0100
Subject: [Tutor] sqlite3 making a spurious duplicate?
In-Reply-To: <55142.187.254.92.124.1492568509.squirrel@mail.tigertech.net>
References: <55142.187.254.92.124.1492568509.squirrel@mail.tigertech.net>
Message-ID: <od77fm$put$1@blaine.gmane.org>

On 19/04/17 03:21, Marilyn Davis wrote:

> connection.execute("SELECT * FROM BRIGHTEST")
> 
> returns a <sqlite3.Cursor object at 0x101bda260>, not a regular python
> sequence.  

Pretty much everything inn  SQL land uses cursor objects.
It's why best practice creates an explicit cursor for
executing statements rather than the impl8icit one on
the connection. Also of course because you can then
have more than one query active at a time.

A connection based query is fine where you just want
to jump in and pull out some data, in that case a
single, implicit, cursor doesn't cause any issues.

> But starting a new context, instead, before the executemany does not fix
> it!  We still get the duplicate Canopus in the iterable, even though it
> was inserted into the data a different context.
> 
> I suspect that this is not an intended behavior.

Can you show what you mean there?
Provided you use the cursor inside the context
it should still work.

> Another question: is it a good principle to try to only put SQL in the
> context, and then regular python outside that context?  It suits my
> instinct  but maybe it is just my superstition?

No, you often need to put the python that manipulates the
data inside the context, especially if the database is
large. You could (should?) of course put the manipulation
into a function that is defined outside the context and
called from within, but what you probably should not do
is try to pull all your data into memory within the context
then manipulate it outside. This would be particularly
dangerous in a multi-user database context, where the
data may be changing independently of your program.

-- 
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 Apr 19 05:16:30 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 19 Apr 2017 19:16:30 +1000
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
In-Reply-To: <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
Message-ID: <20170419091629.GQ9464@ando.pearwood.info>

On Wed, Apr 19, 2017 at 09:28:26AM +0200, Thomas G?ttler wrote:

[code for a classproperty]

> Nice, if it is that simple.
> 
> Is there a reason why this is not in the standard library?

I haven't had a chance to test Peter's classproperty code yet, but I 
don't expect it to be that simple. People have asked for it before, and 
even Guido himself (the inventor of Python) has agreed that if it 
existed he'd use it, but the proposals have (so far) always stumbled on 
two factors:

- there are not a lot of uses for classproperty that ordinary property 
  isn't "good enough" for;

- its hard to get classproperty to work right.


The *easy* part is to do something like this:


class Spam(object):
    @classproperty
    def x(cls):
        return "some value"


Now you can say:

Spam.x

and it will return "some value". BUT if you say:

Spam.x = "hello world"

the class property doesn't run, and Python just overrides x with the new 
value, and you lose the class property and get just a regular attribute. 
That's bad.

There is a solution to that: use a custom metaclass. And yes, that is 
not just advanced, but Black Magic and Voodoo advanced. But if you do 
it, you can solve the above problem.

However, the metaclass solution creates a *new* problem. We'd like this 
to work too:

obj = Spam()
obj.x  # should call the classproperty and return "some value"


but with the metaclass solution, that doesn't work.

As I said, I haven't had a chance to try Peter's code, so it's possible 
that he's solved all these problems. I'm judging by previous 
discussions.

On the bug tracker there's currently a request for classproperty, but 
its languishing:

https://bugs.python.org/issue24941

See Nick Coghlan's comments in particular:

https://mail.python.org/pipermail/python-ideas/2011-January/008959.html


Here's a previous request that was closed for lack of progress and 
interest:

https://bugs.python.org/issue23586


Here's Guido expressing some interest:

https://mail.python.org/pipermail/python-ideas/2011-January/008955.html


-- 
Steve

From __peter__ at web.de  Wed Apr 19 06:19:05 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 19 Apr 2017 12:19:05 +0200
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <20170419091629.GQ9464@ando.pearwood.info>
Message-ID: <od7dik$t69$1@blaine.gmane.org>

Steven D'Aprano wrote:

> As I said, I haven't had a chance to try Peter's code, so it's possible
> that he's solved all these problems. I'm judging by previous

No, my simple code only "works" for read-only properties and only as long as 
you don't overwrite the property by assigning to the attribute. To disallow 
writing you can define a

def __set__(*args):
    raise AttributeError

method, but that would only be invoked for instances of the class, not the 
class itself. For the same reason the setter of a read/write class property 
following that design would only be invoked in an instance, not in the 
class.

The other simple solution, defining a normal property in the metaclass,
works for the class (as expected, remember that the class is an instance of 
the metaclass), but is invisible to the instance:

>>> class T(type):
...     @property
...     def foo(self): return 42
... 
>>> class Foo:
...     __metaclass__ = T
... 
>>> Foo.foo
42
>>> Foo.foo = "bar"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>> Foo().foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'foo'



From ismail.mohanad at yahoo.ie  Wed Apr 19 06:35:36 2017
From: ismail.mohanad at yahoo.ie (Mohanad Ismail)
Date: Wed, 19 Apr 2017 10:35:36 +0000 (UTC)
Subject: [Tutor] Write Data to Multiple Files
References: <228720762.4863362.1492598136284.ref@mail.yahoo.com>
Message-ID: <228720762.4863362.1492598136284@mail.yahoo.com>

Hello,
I have recently started using python and i have come to a halt while writing a code and i was hoping someone out there can help me.
I am attempting to store a stream of data directly from a serial port onto multiple files in sequence after x amount of time is elapsed.
for example :
Read data from serial and write to file 1 for 15 sec, after the 15 seconds continue writing the data on to file 2 for 15 seconds and vice versa. in essence each file should write for 15 seconds and stop for 15 seconds while the data is written to the other file
at the moment i have managed to write a code to read and write the data to one file (see below). can someone please assist me.
Code:
#!/usr/bin/env python
from datetime import datetimeimport serial
outfile='/home/bogie/Documents/Data/file1.txt'#outfile='/home/bogie/Documents/Data/file2.txt'ser = serial.Serial(? ? port='/dev/ttyS4',? ? baudrate=9600,? ? parity=serial.PARITY_NONE,? ? stopbits=serial.STOPBITS_ONE,? ? bytesize=serial.EIGHTBITS,
)
while ser.isOpen():? ? d = open(outfile,'a')?? ? dataString = ser.read(44)? ? d.write(datetime.utcnow().isoformat()+ '\t' + dataString + '\n')? ? d.flush() #included to force the system to write to disk

ser.close()

Thanks,Mohanad?

From alan.gauld at yahoo.co.uk  Wed Apr 19 07:05:52 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Apr 2017 12:05:52 +0100
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
In-Reply-To: <od74e6$2em$1@blaine.gmane.org>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <od74e6$2em$1@blaine.gmane.org>
Message-ID: <od7ga9$b4f$1@blaine.gmane.org>

On 19/04/17 08:43, Alan Gauld via Tutor wrote:

> Probably because it is such a rare use case and because
> its not that hard to do yourself if you really need it.

Having read Steven's post I'll retract the bit about
it being not that hard! :-)

But I still think its a fairly rare scenario. Until
somebody really has a burning need it will probably
remain a "nice to have"

-- 
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 Apr 19 07:14:50 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Apr 2017 12:14:50 +0100
Subject: [Tutor] Write Data to Multiple Files
In-Reply-To: <228720762.4863362.1492598136284@mail.yahoo.com>
References: <228720762.4863362.1492598136284.ref@mail.yahoo.com>
 <228720762.4863362.1492598136284@mail.yahoo.com>
Message-ID: <od7gr3$8gp$1@blaine.gmane.org>

On 19/04/17 11:35, Mohanad Ismail via Tutor wrote:

> Read data from serial and write to file 1 for 15 sec, 
> after the 15 seconds continue writing the data on to
> file 2 for 15 seconds
>... each file should write for 15 seconds and stop for 15 seconds

> Code:
> #!/usr/bin/env python
> from datetime import datetimeimport serial
> outfile='/home/bogie/Documents/Data/file1.txt'#outfile='/home/bogie/Documents/Data/file2.txt'ser = serial.Serial(    port='/dev/ttyS4',    baudrate=9600,    parity=serial.PARITY_NONE,    stopbits=serial.STOPBITS_ONE,    bytesize=serial.EIGHTBITS,
> )
> while ser.isOpen():    d = open(outfile,'a')     dataString = ser.read(44)    d.write(datetime.utcnow().isoformat()+ '\t' + dataString + '\n')    d.flush() #included to force the system to write to disk
> 
> ser.close()

This is a text only list and as such html formatting tends to
get wrecked so we can't read your code. Please use plain text
in future posts please?

Meanwhile, the hardest bit of what you want to do is checking
that 15s have elapsed. Actually opening two files and writing
to them is straightforward.

For the time bit I'd probably use the simpler time module
and its time() function rather than datetime, since you
are only interested in seconds which is what time() gives you.

Set an initial start counter using time.time() and on every
write iteration set a now value. When now-start >= 15 swap
to the other file and set start to now. repeat until done.

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 eryksun at gmail.com  Wed Apr 19 10:55:27 2017
From: eryksun at gmail.com (eryk sun)
Date: Wed, 19 Apr 2017 14:55:27 +0000
Subject: [Tutor] classproperty for Python 2.7 (read-only enough)
In-Reply-To: <od7dik$t69$1@blaine.gmane.org>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <20170419091629.GQ9464@ando.pearwood.info> <od7dik$t69$1@blaine.gmane.org>
Message-ID: <CACL+1asV+NznhvXemNX72YXnk+nTXqt60fRdPoewfY8duZdmew@mail.gmail.com>

On Wed, Apr 19, 2017 at 10:19 AM, Peter Otten <__peter__ at web.de> wrote:
> Steven D'Aprano wrote:
>
>> As I said, I haven't had a chance to try Peter's code, so it's possible
>> that he's solved all these problems. I'm judging by previous
>
> No, my simple code only "works" for read-only properties and only as long as
> you don't overwrite the property by assigning to the attribute. To disallow
> writing you can define a
>
> def __set__(*args):
>     raise AttributeError
>
> method, but that would only be invoked for instances of the class, not the
> class itself. For the same reason the setter of a read/write class property
> following that design would only be invoked in an instance, not in the
> class.
>
> The other simple solution, defining a normal property in the metaclass,
> works for the class (as expected, remember that the class is an instance of
> the metaclass), but is invisible to the instance:
>
>>>> class T(type):
> ...     @property
> ...     def foo(self): return 42
> ...
>>>> class Foo:
> ...     __metaclass__ = T
> ...
>>>> Foo.foo
> 42
>>>> Foo.foo = "bar"
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: can't set attribute
>>>> Foo().foo
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'Foo' object has no attribute 'foo'

This is a bit awkward, but you can take advantage of property() being
a data descriptor. When the attribute is looked up on the class, the
metaclass __getattribute__ or __setattr__ first searches the metaclass
MRO. If it finds a data descriptor, then it uses it unconditionally.
This means you can add a foo property to the class as well and have it
chain to the metaclass property. For example:

    class T(type):
        @property
        def foo(self):
            return 42

    class C(object):
        __metaclass__ = T
        @property
        def foo(self):
            return type(self).foo

    >>> C.foo
    42
    >>> C.foo = 0
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: can't set attribute
    >>> o = C()
    >>> o.foo
    42
    >>> o.foo = 0
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: can't set attribute

From seacristt at hotmail.com  Mon Apr 17 22:12:33 2017
From: seacristt at hotmail.com (Tyler Seacrist)
Date: Tue, 18 Apr 2017 02:12:33 +0000
Subject: [Tutor] Need help with code
Message-ID: <CO2PR04MB826E2EF13B0CB76B6F07F67B3190@CO2PR04MB826.namprd04.prod.outlook.com>

Hello,


How do I avoid this error message everytime I utilize wordlist = open("words.text") ?

>>> wordlist = open("words.txt")
Traceback (most recent call last):
  File "<pyshell#303>", line 1, in <module>
    wordlist = open("words.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'
>>> def calculate_abecedarian():
total_count = 0
for word in wordlist:
if is_abecedarian(word):
print (word)
total_count += 1
return total_count

or

>>> if __name__ == '__main__':
    fin = open('words.txt', 'r')
    print (no_contain(fin))


Traceback (most recent call last):
  File "<pyshell#213>", line 2, in <module>
    fin = open('words.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'



From alan.gauld at yahoo.co.uk  Wed Apr 19 11:49:26 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Apr 2017 16:49:26 +0100
Subject: [Tutor] Need help with code
In-Reply-To: <CO2PR04MB826E2EF13B0CB76B6F07F67B3190@CO2PR04MB826.namprd04.prod.outlook.com>
References: <CO2PR04MB826E2EF13B0CB76B6F07F67B3190@CO2PR04MB826.namprd04.prod.outlook.com>
Message-ID: <od80tv$nec$1@blaine.gmane.org>

On 18/04/17 03:12, Tyler Seacrist wrote:

> How do I avoid this error message everytime I utilize wordlist = open("words.text") ?
> 
>>>> wordlist = open("words.txt")
> Traceback (most recent call last):
>   File "<pyshell#303>", line 1, in <module>
>     wordlist = open("words.txt")
> FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'

You need to tell Python where the file lives. It is evidently not
in the same folder where you run the program(*) so you need to
provide the path.

(*)You can determine which folder python considers its home folder by
including this code in your program;

import os
print( os.getcwd() )  # get Current Working Directory

and you can see its contents with

print( os.listdir() )

So you need to provide the path. If you are using
Windows you should put an 'r' in front of the path,
like so:

fin = open( r"C:\Path\to\words.txt" )

or use forward slashes:

fin = open( "C:/Path/to/words.txt" )

Either technique will avoid python interpreting the '\'
as an escape character.

-- 
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 joel.goldstick at gmail.com  Wed Apr 19 12:17:09 2017
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 19 Apr 2017 12:17:09 -0400
Subject: [Tutor] Need help with code
In-Reply-To: <CO2PR04MB826E2EF13B0CB76B6F07F67B3190@CO2PR04MB826.namprd04.prod.outlook.com>
References: <CO2PR04MB826E2EF13B0CB76B6F07F67B3190@CO2PR04MB826.namprd04.prod.outlook.com>
Message-ID: <CAPM-O+yUWBeqpMgfANfFqdo-7+VjxKuqAHnHwwtsYUNSRWGY7Q@mail.gmail.com>

You most likely have no file named words.txt in the directory from
which you are running your code.

On Mon, Apr 17, 2017 at 10:12 PM, Tyler Seacrist <seacristt at hotmail.com> wrote:
> Hello,
>
>
> How do I avoid this error message everytime I utilize wordlist = open("words.text") ?
>
>>>> wordlist = open("words.txt")
> Traceback (most recent call last):
>   File "<pyshell#303>", line 1, in <module>
>     wordlist = open("words.txt")
> FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'
>>>> def calculate_abecedarian():
> total_count = 0
> for word in wordlist:
> if is_abecedarian(word):
> print (word)
> total_count += 1
> return total_count
>
> or
>
>>>> if __name__ == '__main__':
>     fin = open('words.txt', 'r')
>     print (no_contain(fin))
>
>
> Traceback (most recent call last):
>   File "<pyshell#213>", line 2, in <module>
>     fin = open('words.txt', 'r')
> FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

From phil_lor at bigpond.com  Wed Apr 19 18:48:42 2017
From: phil_lor at bigpond.com (Phil)
Date: Thu, 20 Apr 2017 08:48:42 +1000
Subject: [Tutor] Tkinter layout question
Message-ID: <20170420084842.2954c647@raspberrypi>

I'm looking for ideas here.

A working solution for my sudoku solver is a 9 x 9 grid of entry boxes but it looks a bit basic. So I created a 9 x 9 grid on a canvas which looks much better. I can display digits in the centre of the squares but entering the digits from the keyboard seems to be beyond me. I experimented with entering a digit at the mouse location but it all seems to be too complicated. Perhaps someone can offer a repetitively simple solution?

A second experiment involved the earlier grid of entry boxes but with a space between every third row and column. This seems to be more achievable, eventually.

Something along these lines:

for i in range(9):
    if i % 4 == 0:
        place a blank text label
    else:
        place an entry box

So, how might I enter digits into a grid on a canvas or how could I create a space between a grid entry boxes?

-- 
Regards,
Phil

From robertvstepp at gmail.com  Wed Apr 19 23:21:28 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 19 Apr 2017 22:21:28 -0500
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170420084842.2954c647@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
Message-ID: <CANDiX9L=iAnLoVm-Hga__5efuXFeuWmHUm_aZt0EeTovLNp4bw@mail.gmail.com>

I don't know (now) how to solve your challenges below.  But if I were
trying to figure this out, I would try to find more complex tkinter
example applications that contain some of the issues I'd be interested
in.  Then I would dig into the code, find the relevant pieces, and
then start playing with them until I understood them.  I know Alan
suggested some resources in one of your earlier threads.  One of the
books he suggested was, "Python and Tkinter Programming" by John E.
Grayson.  It is a fairly old book from the Python 2 days, copyrighted
2000.  However, I own this book and have gotten a lot of use out of
it.  He has _lots_ of complete examples, including such things as a
scientific calculator that looks like something HP sells!  The other
book, "Programming Python" by Mark Lutz has a very large section on
tkinter with plenty of examples.  I have gotten much good use out this
book as well.  It is much more recent, covering Python 3 (and mentions
Python 2 differences as well).  And then there is the Internet.
Surely you could find relevant material out there.  Maybe even the
source code for IDLE would be helpful.  I understand it is written
using tkinter.

On Wed, Apr 19, 2017 at 5:48 PM, Phil <phil_lor at bigpond.com> wrote:
> I'm looking for ideas here.
>
> A working solution for my sudoku solver is a 9 x 9 grid of entry boxes but it looks a bit basic. So I created a 9 x 9 grid on a canvas which looks much better. I can display digits in the centre of the squares but entering the digits from the keyboard seems to be beyond me. I experimented with entering a digit at the mouse location but it all seems to be too complicated. Perhaps someone can offer a repetitively simple solution?
>

Surely doing the keyboard entries isn't a horribly difficult problem?
It sounds like it breaks down to two different types of key bindings:
(1) Binding some keys (perhaps the arrow keys) to change focus from
cell to cell; and, (2) binding keys to do the actual numerical data
entry in each cell.

> A second experiment involved the earlier grid of entry boxes but with a space between every third row and column. This seems to be more achievable, eventually.
>

I think I have done some of this type of "spacing" stuff using empty
narrow frames.  I don't know if would be helpful or not for you in
your use case, but perhaps it is something to think about.  In the
Grayson book he has lots of examples of achieving very precise spacing
and placement of widgets, etc.

Just some thoughts.  Perhaps they might inspire a creative thought or
two.  Of course one of the experienced tkinter pros out there might
chime in with very detailed, specific help.


-- 
boB

From phil_lor at bigpond.com  Wed Apr 19 23:55:50 2017
From: phil_lor at bigpond.com (Phil)
Date: Thu, 20 Apr 2017 13:55:50 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <CANDiX9L=iAnLoVm-Hga__5efuXFeuWmHUm_aZt0EeTovLNp4bw@mail.gmail.com>
References: <20170420084842.2954c647@raspberrypi>
 <CANDiX9L=iAnLoVm-Hga__5efuXFeuWmHUm_aZt0EeTovLNp4bw@mail.gmail.com>
Message-ID: <20170420135550.04b7056f@raspberrypi>

On Wed, 19 Apr 2017 22:21:28 -0500
boB Stepp <robertvstepp at gmail.com> wrote:

Thank you Bob and Palm for your replies. They have given me something more tto think about.
ideas
> I don't know (now) how to solve your challenges below.  But if I were
> trying to figure this out, I would try to find more complex tkinter
> example applications

I have searched the Internet for hours looking for a game example. Most examples demonstrate the use of specific widgets including the canvas and frames but not in a class context. Putting the pieces together is difficult but I will persevere.

A reference book full of examples is the obvious way to go I suppose. However, it is difficult me to manage paper books because the space they take up and their weight. I do have one general Python e-book but following the few examples is tedious to the nth degree because the text of the examples is so small that I need a magnifying glass to read them.

Anyway, maybe I can justify one book, I'll give it some thought. The massive tome by Lutz comes to mind.

I'll give your keyboard entry suggestion some more thought.

-- 
Regards,
Phil

From phil_lor at bigpond.com  Thu Apr 20 01:55:59 2017
From: phil_lor at bigpond.com (Phil)
Date: Thu, 20 Apr 2017 15:55:59 +1000
Subject: [Tutor] Tkinter layout question - solved
In-Reply-To: <CANDiX9L=iAnLoVm-Hga__5efuXFeuWmHUm_aZt0EeTovLNp4bw@mail.gmail.com>
References: <20170420084842.2954c647@raspberrypi>
 <CANDiX9L=iAnLoVm-Hga__5efuXFeuWmHUm_aZt0EeTovLNp4bw@mail.gmail.com>
Message-ID: <20170420155559.4fdcacca@raspberrypi>

On Wed, 19 Apr 2017 22:21:28 -0500

Just to save people answering this question unnecessarily I have solved the immediate problem. I can now enter a digit at the mouse coordinates. Some refinement is still necessary.

-- 
Regards,
Phil

From timeofsands at gmail.com  Wed Apr 19 22:43:45 2017
From: timeofsands at gmail.com (Palm Tree)
Date: Thu, 20 Apr 2017 06:43:45 +0400
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170420084842.2954c647@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
Message-ID: <CAGC2tijD_ntPBC+xaca1-N22X5LMK5B9PGRaL-eVqDLU9RnQvw@mail.gmail.com>

for entering digits on the canva i think better create a sort of sudoku
generator and display it on the canva in a create_text object.

On 20 Apr 2017 05:24, "Phil" <phil_lor at bigpond.com> wrote:

> I'm looking for ideas here.
>
> A working solution for my sudoku solver is a 9 x 9 grid of entry boxes but
> it looks a bit basic. So I created a 9 x 9 grid on a canvas which looks
> much better. I can display digits in the centre of the squares but entering
> the digits from the keyboard seems to be beyond me. I experimented with
> entering a digit at the mouse location but it all seems to be too
> complicated. Perhaps someone can offer a repetitively simple solution?
>
> A second experiment involved the earlier grid of entry boxes but with a
> space between every third row and column. This seems to be more achievable,
> eventually.
>
> Something along these lines:
>
> for i in range(9):
>     if i % 4 == 0:
>         place a blank text label
>     else:
>         place an entry box
>
> So, how might I enter digits into a grid on a canvas or how could I create
> a space between a grid entry boxes?
>
> --
> Regards,
> Phil
> _______________________________________________
> 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 Apr 20 04:27:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 20 Apr 2017 09:27:27 +0100
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170420084842.2954c647@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
Message-ID: <od9rd8$euo$1@blaine.gmane.org>

On 19/04/17 23:48, Phil wrote:
> I created a 9 x 9 grid on a canvas which looks much better.

> I can display digits in the centre of the squares but 
> entering the digits from the keyboard seems to be beyond me.

Eek! that's a recipe for premature baldness!
Canvas is designed to display things not for user input.
Trying to read keypresses and the like is going to be very
hard to get right. Use the widgets that are designed for
that, namely Entry boxes.

As to layout, use Frames. Lots of frames.
Frames are the key to layout in most GUIs and especialy
so in Tkinter.

So, for a Suduko grid put 3x3 Entry boxes into a Frame.
Then put 3x3 such frames into another frame. Personally
I'd create a class to represent the 3x3 Entry frame
and then create 9 instances of these.

As to the spacing between widgets (the frames in
this case) use the various padx/pady and fill options.
You can have incredibly fine grained control over
layout using the tools that Tkinter gives you. If
you combine that with the different layout managers
(pack, grid,place) - which can be mixed and matched
as needed using more Frames - you have hugely
powerful control over layout.

Don't try to reinvent all of that yourself, it will
result in tears. (Think about how you will control
cursor movement, deletions, selections etc etc)

BTW I posted a simple display-only grid here a
few weeks ago. It might prove helpful as a basis
for the 3x3 cells so, here it is again:

try:
  import Tkinter as tk  # v2
except ImportError:
  import tkinter as tk  # v3

class DisplayTable(tk.Frame):
    def __init__(self, parent, headings, data,
                 hdcolor='red', datacolor='black',
                 gridcolor= 'black', cellcolor='white'):
        tk.Frame.__init__(self, parent, bg=gridcolor)

        if len(headings) != len(data[0]): raise ValueError
        self.headings = headings

        for index,head in enumerate(headings):
            width = len(str(head))
            cell = tk.Label(self,text=str(head),
                            bg=cellcolor, fg=hdcolor, width=width)
            cell.grid(row=0,column=index, padx=1, pady=1)

        for index,row in enumerate(data):
            self.addRow(index+1,row,datacolor,cellcolor)

    def addRow(self, row, data, fg='black', bg='white'):
        for index, item in enumerate(data):
            width = len(str(self.headings[index]))
            cell = tk.Label(self,text=str(item),
                            fg=fg, bg=bg, width=width)
            cell.grid(row=row, column=index, padx=1,pady=1)


if __name__ == "__main__":
    top = tk.Tk()
    tab = DisplayTable(top,
                       ["Left","Right"],
                       [[1,2],
                        [3,4],
                        [5,6]],
                       datacolor='green')
    tab.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 phil_lor at bigpond.com  Thu Apr 20 05:33:12 2017
From: phil_lor at bigpond.com (Phil)
Date: Thu, 20 Apr 2017 19:33:12 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <od9rd8$euo$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
Message-ID: <20170420193312.320bf6bb@raspberrypi>

On Thu, 20 Apr 2017 09:27:27 +0100
Alan Gauld via Tutor <tutor at python.org> wrote:

> Eek! that's a recipe for premature baldness!

Baldness is not a problem, however, slowing the onset of dementia is the aim of this project.

> So, for a Suduko grid put 3x3 Entry boxes into a Frame.
> Then put 3x3 such frames into another frame.

OK, so I'll go back to my original idea and use edit boxes. A grid of 9 x 9 edit boxes does actually work and it makes it easy to keep track of the digits. The first digit is [0,0], the first digit on the second line is [1,0] etc. Nine 3 x 3 boxes could add some complication to digit tracking.

> Don't try to reinvent all of that yourself, it will
> result in tears. (Think about how you will control
> cursor movement, deletions, selections etc etc)

I did actually get my canvas version to the point where I could enter digits into the cells but I had to enter them in sequence so that the logic part of the program knew where the digits were. It was all becoming somewhat complicated.

Thank you for the table example. I'm not sure what "tab = DisplayTable" does at the moment, I'll have to run it to find out.

Thank you for your detailed answer, more food for though.

-- 
Regards,
Phil

From guettliml at thomas-guettler.de  Thu Apr 20 04:37:53 2017
From: guettliml at thomas-guettler.de (=?UTF-8?Q?Thomas_G=c3=bcttler?=)
Date: Thu, 20 Apr 2017 10:37:53 +0200
Subject: [Tutor] classproperty, three times in virtualenv
In-Reply-To: <od74e6$2em$1@blaine.gmane.org>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <od74e6$2em$1@blaine.gmane.org>
Message-ID: <2c8f85e2-6daa-8c5b-7cd4-cea6118bfafa@thomas-guettler.de>



Am 19.04.2017 um 09:43 schrieb Alan Gauld via Tutor:
> On 19/04/17 08:28, Thomas G?ttler wrote:
>
>> Nice, if it is that simple.
>>
>> Is there a reason why this is not in the standard library?
>
> Probably because it is such a rare use case and because
> its not that hard to do yourself if you really need it.
>
> But the standard library, like any open source project,
> develops as people need things. If nobody needs something
> it will never be built and therefore never be added to
> the library. I'd guess this falls into that category.

In my virtualenv it looks like it has three implementations. Maybe more with a different name.

user at host> find src/ lib/ -name '*.py'|xargs grep -Ei '(def|class) classproperty'

lib/python2.7/site-packages/logilab/common/decorators.py:class classproperty(object):
lib/python2.7/site-packages/django/utils/decorators.py:class classproperty(object):
lib/python2.7/site-packages/mptt/models.py:class classpropertytype(property):



Regards,
   Thomas


-- 
Thomas Guettler http://www.thomas-guettler.de/

From guettliml at thomas-guettler.de  Thu Apr 20 04:39:57 2017
From: guettliml at thomas-guettler.de (=?UTF-8?Q?Thomas_G=c3=bcttler?=)
Date: Thu, 20 Apr 2017 10:39:57 +0200
Subject: [Tutor] classproperty: readonly and inheritance - not more needed
In-Reply-To: <20170419091629.GQ9464@ando.pearwood.info>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <20170419091629.GQ9464@ando.pearwood.info>
Message-ID: <affc8b3c-c354-0a81-1a08-31c84be4fa28@thomas-guettler.de>



Am 19.04.2017 um 11:16 schrieb Steven D'Aprano:
> On Wed, Apr 19, 2017 at 09:28:26AM +0200, Thomas G?ttler wrote:
>
> [code for a classproperty]
>
>> Nice, if it is that simple.
>>
>> Is there a reason why this is not in the standard library?
>
> I haven't had a chance to test Peter's classproperty code yet, but I
> don't expect it to be that simple. People have asked for it before, and
> even Guido himself (the inventor of Python) has agreed that if it
> existed he'd use it, but the proposals have (so far) always stumbled on
> two factors:
>
> - there are not a lot of uses for classproperty that ordinary property
>   isn't "good enough" for;
>
> - its hard to get classproperty to work right.

What is "righ"?

In my case a read-only classproperty is enough. Inheritance should be supported.

I don't have a usecase for a setter.

Regards,
   Thomas G?ttler

From johnrim20 at gmail.com  Thu Apr 20 06:48:42 2017
From: johnrim20 at gmail.com (John R)
Date: Thu, 20 Apr 2017 16:18:42 +0530
Subject: [Tutor] What are the few senarios of data science testing using
 Python
Message-ID: <CAPocp3Mf-_=M+FvKzRSFUoKLikXgzPaRA4JucW9htn1C=kFSWw@mail.gmail.com>

Hi All,

I am just trying to understand that how it is possible to
frame test cases on data science projcets using python! could anyone
provide few sample real time senarios? I searched in google but couldnot
find anything suitable to my need. If anyone works on this type
of projects they can help me out


Thanks in advance,

John R

From johnrim20 at gmail.com  Thu Apr 20 06:56:18 2017
From: johnrim20 at gmail.com (John R)
Date: Thu, 20 Apr 2017 16:26:18 +0530
Subject: [Tutor] Could anyone provide a complex data processing automation
 testing example
Message-ID: <CAPocp3NiFK_OyAhT5TnXHtzHNVqLnSYF-txR5ZJ9aVAdo4-+kw@mail.gmail.com>

Hi All,

Most of the examples in google are looking simple in automation so I am not
getting an understanding of  how a complex data processing application is
to be tested using python. Can anyone please provide some real time
examples for my
understanding?

Thanks In advance
91-9886754545

From steve at pearwood.info  Thu Apr 20 08:26:20 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 20 Apr 2017 22:26:20 +1000
Subject: [Tutor] classproperty: readonly and inheritance - not more
 needed
In-Reply-To: <affc8b3c-c354-0a81-1a08-31c84be4fa28@thomas-guettler.de>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <20170419091629.GQ9464@ando.pearwood.info>
 <affc8b3c-c354-0a81-1a08-31c84be4fa28@thomas-guettler.de>
Message-ID: <20170420122620.GR9464@ando.pearwood.info>

On Thu, Apr 20, 2017 at 10:39:57AM +0200, Thomas G?ttler wrote:

> >- its hard to get classproperty to work right.
> 
> What is "righ"?
> 
> In my case a read-only classproperty is enough. Inheritance should be 
> supported.
> 
> I don't have a usecase for a setter.

The standard library is not just for you :-)

If Peter's solution is "good enough" for you, then great, go ahead and 
use it. But beware: of the two implementations I know, you cannot have 
both:

- access from instances;
- read-only property;

You can have access from instances, but then the classproperty is not 
read-only. Or you can have read-only access, but only from the class 
object.

Although I haven't studied Eryksun's solution yet, he may have found a 
work-around.

Good luck!


-- 
Steve

From alan.gauld at yahoo.co.uk  Thu Apr 20 08:43:07 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 20 Apr 2017 13:43:07 +0100
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170420193312.320bf6bb@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
Message-ID: <odaacl$a66$1@blaine.gmane.org>

On 20/04/17 10:33, Phil wrote:

>> So, for a Suduko grid put 3x3 Entry boxes into a Frame.
>> Then put 3x3 such frames into another frame.
> 
> OK, so I'll go back to my original idea and use edit boxes. A grid of 9 x 9 edit boxes does actually work and it makes it easy to keep track of the digits. The first digit is [0,0], the first digit on the second line is [1,0] etc. 

Nine 3 x 3 boxes could add some complication to digit tracking.

Its not too bad you can map the large 9x9 table to the smaller units
using divmod()

So the 7th element becomes
divmod(7) -> 2,1

ie. element 7 maps to the 2nd cell, element 1
You can create a simple helper function that takes an x,y pair from
the 9x9 view and returns two pairs identifying the cell coordinates.

And having the smaller 3x3 cells works when checking that each 3x3
cell has the 9 unique numbers too.

> I did actually get my canvas version to the point where I could 
> enter digits into the cells but I had to enter them in sequence

Yes, that's exactly the kind of problems you hit and its a
terrible user experience. Far better to use the facilities
the GUI gives you for free. For example tab will move the
cursor from cell to cell etc.

> Thank you for the table example. I'm not sure what "tab = DisplayTable" 

It creates an instance of the table.

tab = DisplayTable(top,               # the containing widget/frame
                  ["Left","Right"],   # table headings
                  [[1,2],             # The table data, 3x2 items
                   [3,4],
                   [5,6]],
                  datacolor='green')  # the color used to draw the data

Note:
the constructor allows other colours to be specified too
such as the headings the grid lines and the cell background.
You may want to hard code those in a simplified version of
my class.


Hopefully when you run it you'll understand, especially
if you tweak the example instance options. For example
here is a full featured version:

    tab = DisplayTable(top,
                       ["Left","middle","Right"],
                       [[1,2,1],
                        [3,4,3],
                        [5,6,5]],
                       datacolor='blue',
                       cellcolor='yellow',
                       gridcolor='red',
                       hdcolor='black')


If still confused drop a question 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 alan.gauld at yahoo.co.uk  Thu Apr 20 08:49:34 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 20 Apr 2017 13:49:34 +0100
Subject: [Tutor] Could anyone provide a complex data processing
 automation testing example
In-Reply-To: <CAPocp3NiFK_OyAhT5TnXHtzHNVqLnSYF-txR5ZJ9aVAdo4-+kw@mail.gmail.com>
References: <CAPocp3NiFK_OyAhT5TnXHtzHNVqLnSYF-txR5ZJ9aVAdo4-+kw@mail.gmail.com>
Message-ID: <odaaoo$aj0$1@blaine.gmane.org>

On 20/04/17 11:56, John R wrote:

> Most of the examples in google are looking simple in automation so I am not
> getting an understanding of  how a complex data processing application is
> to be tested using python. 

Is this a different question to the other one you posted?
If so in what way?

If not please only post once, remember it is email so can
take several hours to be delivered and the readership is
spread around multiple timezones so it can take more
hours for everyone to see it and respond.

> Can anyone please provide some real time
> examples for my understanding?

What do you mean by "real time"? Data science and real-time
are two disciplines that very rarely go together. Most data
science is done in batch or offline mode, the only real-time
bits might be updates or single point queries.

I don't really understand what you are looking for.

-- 
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 Apr 20 08:45:29 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 20 Apr 2017 13:45:29 +0100
Subject: [Tutor] What are the few senarios of data science testing using
 Python
In-Reply-To: <CAPocp3Mf-_=M+FvKzRSFUoKLikXgzPaRA4JucW9htn1C=kFSWw@mail.gmail.com>
References: <CAPocp3Mf-_=M+FvKzRSFUoKLikXgzPaRA4JucW9htn1C=kFSWw@mail.gmail.com>
Message-ID: <odaah2$a66$2@blaine.gmane.org>

On 20/04/17 11:48, John R wrote:

> I am just trying to understand that how it is possible to
> frame test cases on data science projcets using python! 

Can you clarify what you mean by "data science" projects?
Do you mean projects built in Python and how to use, say, unittest with
that code?

Or do you mean using Python to write a test rig for a project
implemented in some other language - say Javascript or R or SQL?

-- 
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 Apr 20 11:45:42 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 20 Apr 2017 16:45:42 +0100
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odaacl$a66$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org>
Message-ID: <odal2v$6fc$1@blaine.gmane.org>

On 20/04/17 13:43, Alan Gauld via Tutor wrote:

> So the 7th element becomes
> divmod(7) -> 2,1
> 
> ie. element 7 maps to the 2nd cell, element 1

That should of course be the 3rd cell (0 based), oops.


-- 
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 rafael.knuth at gmail.com  Thu Apr 20 12:15:22 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Thu, 20 Apr 2017 18:15:22 +0200
Subject: [Tutor] Visual Studio Community 2017
In-Reply-To: <73b13e0b-90e7-6409-5743-d3ab7dee72b8@wichmann.us>
References: <CAM-E2X4j7jG2SfEXFgQ3RgLY5vaBM3L1axamqBQGGpqzZRPSrg@mail.gmail.com>
 <od5hhd$m0i$1@blaine.gmane.org>
 <73b13e0b-90e7-6409-5743-d3ab7dee72b8@wichmann.us>
Message-ID: <CAM-E2X4Bhi7dub0g5jObL7YmKt19sY+9bNuyjO24O_rkSr_CBg@mail.gmail.com>

> PyCharm :)

I dumped VS 2017, after testing several IDEs I am perfectly happy with
PyCharm EDU :) It comes with Python 3.5 and importing & working with
libraries like matplotlib is really, really easy. PyCharm EDU is a
very nice IDE for me as a student

From badouglas at gmail.com  Thu Apr 20 15:24:35 2017
From: badouglas at gmail.com (bruce)
Date: Thu, 20 Apr 2017 15:24:35 -0400
Subject: [Tutor] using sudo pip install
Message-ID: <CAP16ngrbGVA4ybGN1RH=KKZ6HFdr=5cTb3MYhEuzCxEy5QC-=w@mail.gmail.com>

Hey guys..

Wanted to get thoughts?

On an IRC chat.. someone stated emphatically...

Never do a "sudo pip install --upgrade..."

The claim was that it could cause issues, enought to seriously
(possibly) damage the OS..

So, is this true??

From mats at wichmann.us  Thu Apr 20 15:48:22 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Thu, 20 Apr 2017 13:48:22 -0600
Subject: [Tutor] using sudo pip install
In-Reply-To: <CAP16ngrbGVA4ybGN1RH=KKZ6HFdr=5cTb3MYhEuzCxEy5QC-=w@mail.gmail.com>
References: <CAP16ngrbGVA4ybGN1RH=KKZ6HFdr=5cTb3MYhEuzCxEy5QC-=w@mail.gmail.com>
Message-ID: <48d3aed5-a10d-848f-f5f8-c4baea6752fd@wichmann.us>

On 04/20/2017 01:24 PM, bruce wrote:
> Hey guys..
> 
> Wanted to get thoughts?
> 
> On an IRC chat.. someone stated emphatically...
> 
> Never do a "sudo pip install --upgrade..."
> 
> The claim was that it could cause issues, enought to seriously
> (possibly) damage the OS..
> 
> So, is this true??

It wouldn't be recommended... if your Python is packaged by your
distribution, you really shouldn't mess with the parts that come with
those packages.  The odds of breaking anything badly are probably low
(especially if what you're upgrading are the typical two - pip and
distutils), but still..

But there's an easy workaround if you want to experiment with newer
stuff, as well as isolate one set of installs from another so they don't
end up fighting over conflicting versions (foo wants bar 13.0 while baz
wants bar 14.0): use virtual environments.  You can safely install and
upgrade whatever you want into a virtualenv, because it's an isolated
location; if it messes up, you can just remove the whole thing and
there's no harm done.



From random832 at fastmail.com  Thu Apr 20 16:54:31 2017
From: random832 at fastmail.com (Random832)
Date: Thu, 20 Apr 2017 16:54:31 -0400
Subject: [Tutor] using sudo pip install
In-Reply-To: <48d3aed5-a10d-848f-f5f8-c4baea6752fd@wichmann.us>
References: <CAP16ngrbGVA4ybGN1RH=KKZ6HFdr=5cTb3MYhEuzCxEy5QC-=w@mail.gmail.com>
 <48d3aed5-a10d-848f-f5f8-c4baea6752fd@wichmann.us>
Message-ID: <1492721671.747087.951066368.55FD5E99@webmail.messagingengine.com>

On Thu, Apr 20, 2017, at 15:48, Mats Wichmann wrote:
> On 04/20/2017 01:24 PM, bruce wrote:
> > Hey guys..
> > 
> > Wanted to get thoughts?
> > 
> > On an IRC chat.. someone stated emphatically...
> > 
> > Never do a "sudo pip install --upgrade..."
> > 
> > The claim was that it could cause issues, enought to seriously
> > (possibly) damage the OS..
> > 
> > So, is this true??
> 
> It wouldn't be recommended... if your Python is packaged by your
> distribution, you really shouldn't mess with the parts that come with
> those packages.  The odds of breaking anything badly are probably low
> (especially if what you're upgrading are the typical two - pip and
> distutils), but still..

My mental model of pip had always been that it would maintain a parallel
site-packages directory in /usr/local, rather than messing with anything
in /usr (which belongs to the distribution packaging system). That's
certainly where any *newly*-installed packages seem to end up. Even
learning in general why using pip as root is a bad idea, I had still
thought this was the case. Why isn't it?

From phil_lor at bigpond.com  Fri Apr 21 21:51:03 2017
From: phil_lor at bigpond.com (Phil)
Date: Sat, 22 Apr 2017 11:51:03 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odaacl$a66$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org>
Message-ID: <20170422115103.4db416d1@raspberrypi>

On Thu, 20 Apr 2017 13:43:07 +0100
Alan Gauld via Tutor <tutor at python.org> wrote:

> If still confused drop a question here.

Maybe not totally confused, more a question of best practice.

Using your example table class, I commented out all from, and including, "if __name__ == "__main__":" down and saved the file as table_class.py. I then created test.py as follows:

from table_class import *

top = tk.Tk()

tab = DisplayTable(top,
                    ["Left","middle","Right"],
                    [[1,2,1],
                    [3,4,3],
                    [5,6,5]],
                    datacolor='blue',
                    cellcolor='yellow',
                    gridcolor='red',
                    hdcolor='black')

tab.pack()

Two questions:
I can see where tk comes from but I'm unsure of the origin of Tk() other than a reference to tkinter.
Have I used you table class correctly? It works, of course, but it doesn't look correct.

-- 
Regards,
Phil

From __peter__ at web.de  Sat Apr 22 04:37:19 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 22 Apr 2017 10:37:19 +0200
Subject: [Tutor] Tkinter layout question
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <20170422115103.4db416d1@raspberrypi>
Message-ID: <odf4ns$idm$1@blaine.gmane.org>

Phil wrote:

> On Thu, 20 Apr 2017 13:43:07 +0100
> Alan Gauld via Tutor <tutor at python.org> wrote:
> 
>> If still confused drop a question here.
> 
> Maybe not totally confused, more a question of best practice.
> 
> Using your example table class, I commented out all from, and including,
> "if __name__ == "__main__":" down and saved the file as table_class.py. 

That's unnecessary. The code protected by 'if __name__ == "__main__"' is not 
executed when the module is imported. In fact that's the very purpose of 
this idiom.

> I
> then created test.py as follows:
> 
> from table_class import *

"Best practice" is to avoid star imports which bind every name from 
table_class that does not start with "_", including 'tk' to the same name in 
the importing module.

Instead be explicit:

import tkinter as tk
import table_class

...

tab = table_class.DisplayTable(...)

That way the maintainer of table_class.py only has to be careful to keep 
DisplayTable compatible. A change to the import from

import tkinter as tk

to

import tkinter

or the definition of names that collide with names in other modules leaves 
client code unaffected.

> top = tk.Tk()
> 
> tab = DisplayTable(top,
>                     ["Left","middle","Right"],
>                     [[1,2,1],
>                     [3,4,3],
>                     [5,6,5]],
>                     datacolor='blue',
>                     cellcolor='yellow',
>                     gridcolor='red',
>                     hdcolor='black')
> 
> tab.pack()
> 
> Two questions:
> I can see where tk comes from but I'm unsure of the origin of Tk() other
> than a reference to tkinter. Have I used you table class correctly? It
> works, of course, but it doesn't look correct.
> 



From phil_lor at bigpond.com  Sat Apr 22 16:47:11 2017
From: phil_lor at bigpond.com (Phil)
Date: Sun, 23 Apr 2017 06:47:11 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odf4ns$idm$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org>
 <20170422115103.4db416d1@raspberrypi>
 <odf4ns$idm$1@blaine.gmane.org>
Message-ID: <20170423064711.25ad07c2@raspberrypi>

On Sat, 22 Apr 2017 10:37:19 +0200
Peter Otten <__peter__ at web.de> wrote:

> That's unnecessary. The code protected by 'if __name__ == "__main__"'
> is not executed when the module is imported. In fact that's the very
> purpose of this idiom.

> 
> "Best practice" is to avoid star imports which bind every name from 
> table_class that does not start with "_", including 'tk' to the same
> name in the importing module.
> 

Thank you Petter for explaining these points, most helpful.

-- 
Regards,
Phil

From phil_lor at bigpond.com  Sat Apr 22 20:38:54 2017
From: phil_lor at bigpond.com (Phil)
Date: Sun, 23 Apr 2017 10:38:54 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odaacl$a66$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org>
Message-ID: <20170423103854.3e12cf17@raspberrypi>

On Thu, 20 Apr 2017 13:43:07 +0100
Alan Gauld via Tutor <tutor at python.org> wrote:

> If still confused drop a question here.

I hope I'm not over doing the questions here. I'm only posting after hours of experimenting and Internet searching.

How do I create multiple instances of the table on the one frame? I think the table class as presented is not capable of that. If I create multiple instances like this then, of course, I end up with two instances of the same frame.

import tkinter as tk
import table_class

tab = table_class.DisplayTable(tk.Tk(),
                    ["Left","middle","Right"],
                    [[1,2,1],
                    [3,4,3],
                    [5,6,5]],
                    datacolor='blue',
                    cellcolor='yellow',
                    gridcolor='red',
                    hdcolor='black')


second_tab = table_class.DisplayTable(tk.Tk(),
                    ["Left","middle","Right"],
                    [[1,2,1],
                    [3,4,3],
                    [5,6,5]],
                    datacolor='blue',
                    cellcolor='green',
                    gridcolor='red',
                    hdcolor='black')

second_tab.pack(side = tk.LEFT)
tab.pack()

I've tried different pack options including packing onto the parent frame.

-- 
Regards,
Phil

From robertvstepp at gmail.com  Sun Apr 23 01:02:48 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 23 Apr 2017 00:02:48 -0500
Subject: [Tutor] Button command arguments: Using class to wrap function call
 versus using lambda in tkinter
Message-ID: <CANDiX9JZu-XOQkddnOM_fUtOKH6U_RmJ6voPZGLfDq_X=GjzYg@mail.gmail.com>

Phil's recent postings have motivated me to try studying tkinter more
systematically starting today, so I have been looking over available
web resources.  Playing around with the code in one such resource, I
was looking at a section entitled "Arguments to Callbacks" towards the
bottom of the page at

http://userpages.umbc.edu/~dhood2/courses/cmsc433/spring2012/?section=Notes&topic=Python&notes=92

they have the code snippet:

==========================================================================
import Tkinter


# command class to wrap function call with args
# a.k.a. "currying"
class Command:
    def __init__(self, callback, *args, **kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

    def __call__(self):
        return apply(self.callback, self.args, self.kwargs)


def callback(arg):
    print "You called callback with the following arg: %s" % arg


root = Tkinter.Tk()

Tkinter.Button(root, text="Foo", command=Command(callback, 'Foo')).pack()
Tkinter.Button(root, text="Bar", command=Command(callback, 'Bar')).pack()
Tkinter.Button(root, text="Baz", command=Command(callback, 'Baz')).pack()

root.mainloop()
==========================================================================

This is Python 2 code, so I endeavored to convert it to Python 3.  I
came up with:

==========================================================================
#!/usr/bin/env python3

import tkinter as tk

# Command class to wrap function call with args
# A.K.A. "currying"
class Command:
    def __init__(self, callback, *args, **kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

    def __call__(self):
        return self.callback(*self.args, **self.kwargs)

def callback(arg):
    print('You called callback with the following arg:  %s' % arg)

root = tk.Tk()
tk.Button(root, text='Foo', command=Command(callback, 'Foo')).pack()
tk.Button(root, text='Bar', command=Command(callback, 'Bar')).pack()
tk.Button(root, text='Baz', command=Command(callback, 'Baz')).pack()

root.mainloop()
==========================================================================

This seems to work fine, and got me to wondering about using lambda
instead of this class wrapper approach, which gave me:

==========================================================================
import tkinter as tk

def callback(arg):
    print('You called callback with the following arg:  %s' % arg)

root = tk.Tk()
tk.Button(root, text='Foo', command=lambda arg='Foo': callback(arg)).pack()
tk.Button(root, text='Bar', command=lambda arg='Bar': callback(arg)).pack()
tk.Button(root, text='Baz', command=lambda arg='Baz': callback(arg)).pack()

root.mainloop()
==========================================================================

And this also works well.  Seeing as this approach has fewer lines of
code and reads clearly, what advantages would the class wrapper
approach have?  The only thing that is occurring to me in my current
sleepy state is that the class wrapper is much more flexible with
handling varying passed arguments.  Are there other considerations I
should be aware of?

As usual, many thanks in advance!

Cheers!


-- 
boB

From __peter__ at web.de  Sun Apr 23 03:38:13 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 23 Apr 2017 09:38:13 +0200
Subject: [Tutor] Button command arguments: Using class to wrap function
 call versus using lambda in tkinter
References: <CANDiX9JZu-XOQkddnOM_fUtOKH6U_RmJ6voPZGLfDq_X=GjzYg@mail.gmail.com>
Message-ID: <odhlkv$s5s$1@blaine.gmane.org>

boB Stepp wrote:

> Phil's recent postings have motivated me to try studying tkinter more
> systematically starting today, so I have been looking over available
> web resources.  Playing around with the code in one such resource, I
> was looking at a section entitled "Arguments to Callbacks" towards the
> bottom of the page at
> 
> 
http://userpages.umbc.edu/~dhood2/courses/cmsc433/spring2012/?section=Notes&topic=Python&notes=92
> 
> they have the code snippet:
> 
> ==========================================================================
> import Tkinter
> 
> 
> # command class to wrap function call with args
> # a.k.a. "currying"
> class Command:
>     def __init__(self, callback, *args, **kwargs):
>         self.callback = callback
>         self.args = args
>         self.kwargs = kwargs
> 
>     def __call__(self):
>         return apply(self.callback, self.args, self.kwargs)
> 
> 
> def callback(arg):
>     print "You called callback with the following arg: %s" % arg
> 
> 
> root = Tkinter.Tk()
> 
> Tkinter.Button(root, text="Foo", command=Command(callback, 'Foo')).pack()
> Tkinter.Button(root, text="Bar", command=Command(callback, 'Bar')).pack()
> Tkinter.Button(root, text="Baz", command=Command(callback, 'Baz')).pack()
> 
> root.mainloop()
> ==========================================================================
> 
> This is Python 2 code, so I endeavored to convert it to Python 3.  I
> came up with:
> 
> ==========================================================================
> #!/usr/bin/env python3
> 
> import tkinter as tk
> 
> # Command class to wrap function call with args
> # A.K.A. "currying"
> class Command:
>     def __init__(self, callback, *args, **kwargs):
>         self.callback = callback
>         self.args = args
>         self.kwargs = kwargs
> 
>     def __call__(self):
>         return self.callback(*self.args, **self.kwargs)
> 
> def callback(arg):
>     print('You called callback with the following arg:  %s' % arg)
> 
> root = tk.Tk()
> tk.Button(root, text='Foo', command=Command(callback, 'Foo')).pack()
> tk.Button(root, text='Bar', command=Command(callback, 'Bar')).pack()
> tk.Button(root, text='Baz', command=Command(callback, 'Baz')).pack()
> 
> root.mainloop()
> ==========================================================================
> 
> This seems to work fine, and got me to wondering about using lambda
> instead of this class wrapper approach, which gave me:
> 
> ==========================================================================
> import tkinter as tk
> 
> def callback(arg):
>     print('You called callback with the following arg:  %s' % arg)
> 
> root = tk.Tk()
> tk.Button(root, text='Foo', command=lambda arg='Foo':
> callback(arg)).pack() tk.Button(root, text='Bar', command=lambda
> arg='Bar': callback(arg)).pack() tk.Button(root, text='Baz',
> command=lambda arg='Baz': callback(arg)).pack()
> 
> root.mainloop()
> ==========================================================================
> 
> And this also works well.  Seeing as this approach has fewer lines of
> code and reads clearly, what advantages would the class wrapper
> approach have?  The only thing that is occurring to me in my current
> sleepy state is that the class wrapper is much more flexible with
> handling varying passed arguments.  Are there other considerations I
> should be aware of?

Generally I'd also prefer the lambda or functools.partial(callback, "Foo"), 
but if you want to maintain per-button state a class may be worth 
considering. A simple example:

class Callback:
    def __init__(self, template):
        self.count = 0
        self.template = template

    def __call__(self):
        self.count += 1
        print(self.template.format(self.count))


tk.Button(root, text='Foo', command=Callback("Foo pressed {} times")).pack()



From nulla.epistola at web.de  Sun Apr 23 03:39:54 2017
From: nulla.epistola at web.de (Sibylle Koczian)
Date: Sun, 23 Apr 2017 09:39:54 +0200
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odaacl$a66$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org>
Message-ID: <odhlo2$b6b$1@blaine.gmane.org>

Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
> Its not too bad you can map the large 9x9 table to the smaller units
> using divmod()
>
> So the 7th element becomes
> divmod(7) -> 2,1
>

Should be divmod(7, 3), shouldn't it?




From __peter__ at web.de  Sun Apr 23 03:52:16 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 23 Apr 2017 09:52:16 +0200
Subject: [Tutor] Tkinter layout question
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <20170423103854.3e12cf17@raspberrypi>
Message-ID: <odhmfb$i4i$1@blaine.gmane.org>

Phil wrote:

> On Thu, 20 Apr 2017 13:43:07 +0100
> Alan Gauld via Tutor <tutor at python.org> wrote:
> 
>> If still confused drop a question here.
> 
> I hope I'm not over doing the questions here. I'm only posting after hours
> of experimenting and Internet searching.
> 
> How do I create multiple instances of the table on the one frame? I think
> the table class as presented is not capable of that. If I create multiple
> instances like this then, of course, I end up with two instances of the
> same frame.
> 
> import tkinter as tk
> import table_class
> 
> tab = table_class.DisplayTable(tk.Tk(),
>                     ["Left","middle","Right"],
>                     [[1,2,1],
>                     [3,4,3],
>                     [5,6,5]],
>                     datacolor='blue',
>                     cellcolor='yellow',
>                     gridcolor='red',
>                     hdcolor='black')
> 
> 
> second_tab = table_class.DisplayTable(tk.Tk(),
>                     ["Left","middle","Right"],
>                     [[1,2,1],
>                     [3,4,3],
>                     [5,6,5]],
>                     datacolor='blue',
>                     cellcolor='green',
>                     gridcolor='red',
>                     hdcolor='black')
> 
> second_tab.pack(side = tk.LEFT)
> tab.pack()
> 
> I've tried different pack options including packing onto the parent frame.
> 

If you wrote the above with Buttons instead of DisplayTables you'd encounter 
the same behaviour. The problem is that you call tkinter.Tk() twice (which 
is generally a recipe for disaster; if you want multiple windows use 
tkinter.Toplevel() for all but the first one). 

Once you have fixed that you should be OK:

import tkinter as tk
import table_class

root = tk.Tk()

tab = table_class.DisplayTable(root,
                    ["Left","middle","Right"],
                    [[1,2,1],
                    [3,4,3],
                    [5,6,5]],
                    datacolor='blue',
                    cellcolor='yellow',
                    gridcolor='red',
                    hdcolor='black')

second_tab = table_class.DisplayTable(root,
                    ["Left","middle","Right"],
                    [[1,2,1],
                    [3,4,3],
                    [5,6,5]],
                    datacolor='blue',
                    cellcolor='green',
                    gridcolor='red',
                    hdcolor='black')

tab.pack(side=tk.LEFT)
second_tab.pack()

root.mainloop()





From phil_lor at bigpond.com  Sun Apr 23 04:51:50 2017
From: phil_lor at bigpond.com (Phil)
Date: Sun, 23 Apr 2017 18:51:50 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odhmfb$i4i$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org>
 <20170423103854.3e12cf17@raspberrypi>
 <odhmfb$i4i$1@blaine.gmane.org>
Message-ID: <20170423185150.7fdeb105@raspberrypi>

On Sun, 23 Apr 2017 09:52:16 +0200
Peter Otten <__peter__ at web.de> wrote:

> If you wrote the above with Buttons instead of DisplayTables you'd
> encounter the same behaviour. The problem is that you call
> tkinter.Tk() twice (which is generally a recipe for disaster; if you
> want multiple windows use tkinter.Toplevel() for all but the first
> one). 
> 
> Once you have fixed that you should be OK:
> 
> import tkinter as tk
> import table_class
> 
> root = tk.Tk()
> 
> tab = table_class.DisplayTable(root,
>                     ["Left","middle","Right"],
>                     [[1,2,1],
>                     [3,4,3],
>                     [5,6,5]],
>                     datacolor='blue',
>                     cellcolor='yellow',
>                     gridcolor='red',
>                     hdcolor='black')
> 
> second_tab = table_class.DisplayTable(root,
>                     ["Left","middle","Right"],
>                     [[1,2,1],
>                     [3,4,3],
>                     [5,6,5]],
>                     datacolor='blue',
>                     cellcolor='green',
>                     gridcolor='red',
>                     hdcolor='black')
> 
> tab.pack(side=tk.LEFT)
> second_tab.pack()
> 
> root.mainloop()

Thank you again Peter. Of course your changes worked but at the moment I'm not sure why.

if root = tk.Tk() then why isn't table_class.DisplayTable(root, the same as table_class.DisplayTable(tk.Tk(),. Obviously it isn't but I don't know why.

Also I found that root.mainloop() isn't necessary in that the result is the same with or without. Perhaps it serves some other purpose?

-- 
Regards,
Phil

From __peter__ at web.de  Sun Apr 23 05:28:51 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 23 Apr 2017 11:28:51 +0200
Subject: [Tutor] Tkinter layout question
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <20170423103854.3e12cf17@raspberrypi>
 <odhmfb$i4i$1@blaine.gmane.org> <20170423185150.7fdeb105@raspberrypi>
Message-ID: <odhs4h$dn0$1@blaine.gmane.org>

Phil wrote:

> On Sun, 23 Apr 2017 09:52:16 +0200
> Peter Otten <__peter__ at web.de> wrote:
> 
>> If you wrote the above with Buttons instead of DisplayTables you'd
>> encounter the same behaviour. The problem is that you call
>> tkinter.Tk() twice (which is generally a recipe for disaster; if you
>> want multiple windows use tkinter.Toplevel() for all but the first
>> one).
>> 
>> Once you have fixed that you should be OK:
>> 
>> import tkinter as tk
>> import table_class
>> 
>> root = tk.Tk()
>> 
>> tab = table_class.DisplayTable(root,
>>                     ["Left","middle","Right"],
>>                     [[1,2,1],
>>                     [3,4,3],
>>                     [5,6,5]],
>>                     datacolor='blue',
>>                     cellcolor='yellow',
>>                     gridcolor='red',
>>                     hdcolor='black')
>> 
>> second_tab = table_class.DisplayTable(root,
>>                     ["Left","middle","Right"],
>>                     [[1,2,1],
>>                     [3,4,3],
>>                     [5,6,5]],
>>                     datacolor='blue',
>>                     cellcolor='green',
>>                     gridcolor='red',
>>                     hdcolor='black')
>> 
>> tab.pack(side=tk.LEFT)
>> second_tab.pack()
>> 
>> root.mainloop()
> 
> Thank you again Peter. Of course your changes worked but at the moment I'm
> not sure why.
> 
> if root = tk.Tk() then why isn't table_class.DisplayTable(root, the same
> as table_class.DisplayTable(tk.Tk(),. Obviously it isn't but I don't know
> why.

Consider the function make_a_cake(). If you use it

eat_a_piece_of(make_a_cake())
eat_a_piece_of(make_a_cake())

that's short for

one_cake = make_a_cake()
eat_a_piece_of(one_cake)

another_cake = make_a_cake()
eat_a_piece_of(another_cake)

i. e. you had two pieces of cake, one piece of each of two cakes.

If you write

cake = make_a_cake()
eat_a_piece_of(cake)
eat_a_piece_of(cake)

you have still eaten two pieces of cake but both are taken from the same 
cake.

Likewise when you write

root = tk.Tk()
first_table = DisplayTable(root)
second_table = DisplayTable(root)

both tables share the same instance of the Tk class.
 
> Also I found that root.mainloop() isn't necessary in that the result is
> the same with or without. Perhaps it serves some other purpose?

Try running it from the command line, not in idle. In every tkinter program 
there must be a main loop to respond to events.


From guettliml at thomas-guettler.de  Fri Apr 21 06:51:28 2017
From: guettliml at thomas-guettler.de (=?UTF-8?Q?Thomas_G=c3=bcttler?=)
Date: Fri, 21 Apr 2017 12:51:28 +0200
Subject: [Tutor] classproperty: readonly and inheritance - not more
 needed
In-Reply-To: <20170420122620.GR9464@ando.pearwood.info>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <20170419091629.GQ9464@ando.pearwood.info>
 <affc8b3c-c354-0a81-1a08-31c84be4fa28@thomas-guettler.de>
 <20170420122620.GR9464@ando.pearwood.info>
Message-ID: <2a209a38-683b-2a68-0013-b75e7543c008@thomas-guettler.de>



Am 20.04.2017 um 14:26 schrieb Steven D'Aprano:
> On Thu, Apr 20, 2017 at 10:39:57AM +0200, Thomas G?ttler wrote:
>
>>> - its hard to get classproperty to work right.
>>
>> What is "righ"?
>>
>> In my case a read-only classproperty is enough. Inheritance should be
>> supported.
>>
>> I don't have a usecase for a setter.
>
> The standard library is not just for you :-)
>
> If Peter's solution is "good enough" for you, then great, go ahead and
> use it. But beware: of the two implementations I know, you cannot have
> both:
>
> - access from instances;
> - read-only property;
>
> You can have access from instances, but then the classproperty is not
> read-only. Or you can have read-only access, but only from the class
> object.

I can't follow what you. What do you mean with "... is not read-only".

This snippet works fine:

{{{

class classproperty(object):
     def __init__(self, f):
         self.f = f
     def __get__(self, obj, owner):
         return self.f(owner)

class Foo(object):
     @classproperty
     def my_prop(cls):
         return 42

print Foo.my_prop

print Foo().my_prop
}}}

Regards,
   Thomas

-- 
Thomas Guettler http://www.thomas-guettler.de/

From __peter__ at web.de  Sun Apr 23 15:03:10 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 23 Apr 2017 21:03:10 +0200
Subject: [Tutor] classproperty: readonly and inheritance - not more
 needed
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <20170419091629.GQ9464@ando.pearwood.info>
 <affc8b3c-c354-0a81-1a08-31c84be4fa28@thomas-guettler.de>
 <20170420122620.GR9464@ando.pearwood.info>
 <2a209a38-683b-2a68-0013-b75e7543c008@thomas-guettler.de>
Message-ID: <oditp9$jr6$1@blaine.gmane.org>

Thomas G?ttler wrote:

> 
> 
> Am 20.04.2017 um 14:26 schrieb Steven D'Aprano:
>> On Thu, Apr 20, 2017 at 10:39:57AM +0200, Thomas G?ttler wrote:
>>
>>>> - its hard to get classproperty to work right.
>>>
>>> What is "righ"?
>>>
>>> In my case a read-only classproperty is enough. Inheritance should be
>>> supported.
>>>
>>> I don't have a usecase for a setter.
>>
>> The standard library is not just for you :-)
>>
>> If Peter's solution is "good enough" for you, then great, go ahead and
>> use it. But beware: of the two implementations I know, you cannot have
>> both:
>>
>> - access from instances;
>> - read-only property;
>>
>> You can have access from instances, but then the classproperty is not
>> read-only. Or you can have read-only access, but only from the class
>> object.
> 
> I can't follow what you. What do you mean with "... is not read-only".
> 
> This snippet works fine:
> 
> {{{
> 
> class classproperty(object):
>      def __init__(self, f):
>          self.f = f
>      def __get__(self, obj, owner):
>          return self.f(owner)
> 
> class Foo(object):
>      @classproperty
>      def my_prop(cls):
>          return 42
> 
> print Foo.my_prop
> 
> print Foo().my_prop
> }}}
> 
> Regards,
>    Thomas
> 
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class classproperty(object):
...      def __init__(self, f):
...          self.f = f
...      def __get__(self, obj, owner):
...          return self.f(owner)
... 
>>> class Foo(object):
...      @classproperty
...      def my_prop(cls):
...          print "calculating..."
...          return 42
... 
>>> Foo.my_prop
calculating...
42

Now the "not read-only" part:

>>> Foo.my_prop = "whatever"
>>> Foo.my_prop
'whatever'

You now have a string attribute, the property is lost. Methods behave the 
same way and it's generally not a problem, but you should at least be aware 
of this behaviour.


From phil_lor at bigpond.com  Sun Apr 23 19:24:55 2017
From: phil_lor at bigpond.com (Phil)
Date: Mon, 24 Apr 2017 09:24:55 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odhlo2$b6b$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
Message-ID: <20170424092455.672dc446@raspberrypi>

On Sun, 23 Apr 2017 09:39:54 +0200
Sibylle Koczian <nulla.epistola at web.de> wrote:

> Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
> > Its not too bad you can map the large 9x9 table to the smaller units
> > using divmod()
> >
> > So the 7th element becomes
> > divmod(7) -> 2,1
> >
> 
> Should be divmod(7, 3), shouldn't it?

Thanks Sibylle, I eventually stumbled upon the answer using my usual trial-and-error method. The 3, as in the number of cells, was the key.

-- 
Regards,
Phil

From phil_lor at bigpond.com  Sun Apr 23 20:50:47 2017
From: phil_lor at bigpond.com (Phil)
Date: Mon, 24 Apr 2017 10:50:47 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170424092455.672dc446@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
 <20170424092455.672dc446@raspberrypi>
Message-ID: <20170424105047.14bf00ae@raspberrypi>

On Mon, 24 Apr 2017 09:24:55 +1000
Phil <phil_lor at bigpond.com> wrote:

> On Sun, 23 Apr 2017 09:39:54 +0200
> Sibylle Koczian <nulla.epistola at web.de> wrote:
> 
> > Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
> > > Its not too bad you can map the large 9x9 table to the smaller
> > > units using divmod()
> > >
> > > So the 7th element becomes
> > > divmod(7) -> 2,1
> > >
> > 
> > Should be divmod(7, 3), shouldn't it?
> 
> Thanks Sibylle, I eventually stumbled upon the answer using my usual
> trial-and-error method. The 3, as in the number of cells, was the key.

Actually, that's not correct either.

Say I want the 7th cell in the first line of a 9 x 9 grid, that would be x = 7, y = 1. divmod(7,1) = 2,1 or the first cell in grid 3. So far so good.

Another example, x = 4, y = 3. divmod(4,3) = 1,1. What I need here is grid 2 x = 1 and y = 3.

Further complications are, arrays, or lists in Python, start a 0 and divmod may not be the answer because divide by 0 is not possible. Making adjustments for these two possibilities has resulted in complicated code that does give the desired result. Of course, I may have misunderstood the intention of Alan's mapping method.

So, what I need is a function to map from a 9 x 9 grid to a cell in a 3 x 3 grid.

My feeble simplified attempt is as follows:

def map_cell(x,y):
    return divmod(x,y)

while(True):
    x,y = input().split(" ")
    print (map_cell(int(x), int(y)))

-- 
Regards,
Phil

From phil_lor at bigpond.com  Sun Apr 23 18:49:54 2017
From: phil_lor at bigpond.com (Phil)
Date: Mon, 24 Apr 2017 08:49:54 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odhs4h$dn0$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org>
 <20170423103854.3e12cf17@raspberrypi>
 <odhmfb$i4i$1@blaine.gmane.org>
 <20170423185150.7fdeb105@raspberrypi>
 <odhs4h$dn0$1@blaine.gmane.org>
Message-ID: <20170424084954.526a655a@raspberrypi>

On Sun, 23 Apr 2017 11:28:51 +0200
Peter Otten <__peter__ at web.de> wrote:

> Consider the function make_a_cake(). If you use it
> 
> eat_a_piece_of(make_a_cake())
> eat_a_piece_of(make_a_cake())
> 
> that's short for
> 
> one_cake = make_a_cake()
> eat_a_piece_of(one_cake)
> 
> another_cake = make_a_cake()
> eat_a_piece_of(another_cake)
> 
> i. e. you had two pieces of cake, one piece of each of two cakes.
> 
> If you write
> 
> cake = make_a_cake()
> eat_a_piece_of(cake)
> eat_a_piece_of(cake)
> 
> you have still eaten two pieces of cake but both are taken from the
> same cake.
> 
> Likewise when you write
> 
> root = tk.Tk()
> first_table = DisplayTable(root)
> second_table = DisplayTable(root)
> 
> both tables share the same instance of the Tk class.
>  
> > Also I found that root.mainloop() isn't necessary in that the
> > result is the same with or without. Perhaps it serves some other
> > purpose?
> 
> Try running it from the command line, not in idle. In every tkinter
> program there must be a main loop to respond to events.

Thank you again Peter for taking the time to answer my question.

-- 
Regards,
Phil

From guettliml at thomas-guettler.de  Mon Apr 24 05:23:16 2017
From: guettliml at thomas-guettler.de (=?UTF-8?Q?Thomas_G=c3=bcttler?=)
Date: Mon, 24 Apr 2017 11:23:16 +0200
Subject: [Tutor] classproperty: readonly and inheritance - not more
 needed
In-Reply-To: <oditp9$jr6$1@blaine.gmane.org>
References: <128c6b23-08fb-87ff-5da1-8ecd37133f34@thomas-guettler.de>
 <od4sja$enr$1@blaine.gmane.org>
 <4b941204-b657-9427-2349-c31a8b77ce17@thomas-guettler.de>
 <20170419091629.GQ9464@ando.pearwood.info>
 <affc8b3c-c354-0a81-1a08-31c84be4fa28@thomas-guettler.de>
 <20170420122620.GR9464@ando.pearwood.info>
 <2a209a38-683b-2a68-0013-b75e7543c008@thomas-guettler.de>
 <oditp9$jr6$1@blaine.gmane.org>
Message-ID: <5e5005fc-9431-c282-de01-f6ee6c6614c4@thomas-guettler.de>

>
> Now the "not read-only" part:
>
>>>> Foo.my_prop = "whatever"
>>>> Foo.my_prop
> 'whatever'
>
> You now have a string attribute, the property is lost. Methods behave the
> same way and it's generally not a problem, but you should at least be aware
> of this behaviour.

Yes, now I understand you. Thank you

Regards,
   Thomas G?ttler


-- 
Thomas Guettler http://www.thomas-guettler.de/

From alan.gauld at yahoo.co.uk  Mon Apr 24 15:02:32 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 24 Apr 2017 20:02:32 +0100
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170424105047.14bf00ae@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
 <20170424092455.672dc446@raspberrypi> <20170424105047.14bf00ae@raspberrypi>
Message-ID: <odli42$eet$1@blaine.gmane.org>

On 24/04/17 01:50, Phil wrote:
> On Mon, 24 Apr 2017 09:24:55 +1000
> Phil <phil_lor at bigpond.com> wrote:
>
>> On Sun, 23 Apr 2017 09:39:54 +0200
>> Sibylle Koczian <nulla.epistola at web.de> wrote:
>>
>>> Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
>>>> Its not too bad you can map the large 9x9 table to the smaller
>>>> units using divmod()
>>>>
>>>> So the 7th element becomes
>>>> divmod(7) -> 2,1
>>>>
>>>
>>> Should be divmod(7, 3), shouldn't it?

Yes, of course, sorry about that!
The 3 of course is the number of items per cell (3x3)

> Say I want the 7th cell in the first line of a 9 x 9 grid,
 > that would be x = 7, y = 1.

But you want it mapped to a cell/item pair...

divmod(7,3) -> 2,1


The 3rd cell, 2nd item which is wrong for the item part.
So you need to use:

2, 1-1

Taking item 4 in your 9x9,

divmod(4,3) -> 1,1  cell 1 item 1 so again you need
to subtract 1

So we can write

def map_dimension_to_cell(index):
     cell,item = divmod(index,3)
     return cell,item-1

And luckily for us that works even on exact boundaries
because cell[-1] is the last item in the cell!

Mapping columns is exactly the same.

Now the only problem is to map your notional 9x9 table 9
indexing from 1 to a Python 9x9 indexing from zero.
The easiest way is to add 1 to the input index:

def map_index_to_cell(index):
     cell,item = divmod(index+1,3)
     return cell,item-1

You can now pass in the x or y index from your
python 9x9 table to get the cell/item indexes
in your GUI like so:

cell_x,x = map_index_to_cell(x_index)
cell_y,y = map_index_to_cell(y_index)

cell = sudoku_grid[cell_x,cell_y]
item = cell[x,y]

All untested but I think that should work...
And you could wrap that up as a pair of get/set
functions if you so wished.

def get_sudoku_grid(x,y):
    # code above
    return item

def set_sudoku_grid(x,y,value):
     #code above
     item = value

Sorry for the late response, I'm on a vacation so
not checking mail that often...

HTH

Alan G


From alan.gauld at yahoo.co.uk  Mon Apr 24 15:10:30 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 24 Apr 2017 20:10:30 +0100
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odli42$eet$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
 <20170424092455.672dc446@raspberrypi> <20170424105047.14bf00ae@raspberrypi>
 <odli42$eet$1@blaine.gmane.org>
Message-ID: <odlij0$irc$1@blaine.gmane.org>

On 24/04/17 20:02, Alan Gauld via Tutor wrote:

> And you could wrap that up as a pair of get/set
> functions if you so wished.
>
> def get_sudoku_grid(x,y):
>    # code above
>    return item
>
> def set_sudoku_grid(x,y,value):
>     #code above
>     item = value
>

I should point out that to use my table code for your sudoku you need to
- remove the headings
- change the Labels to Entry widgets
- write get/set methods to access the entry data

Alan G


From phil_lor at bigpond.com  Mon Apr 24 18:40:00 2017
From: phil_lor at bigpond.com (Phil)
Date: Tue, 25 Apr 2017 08:40:00 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odli42$eet$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
 <20170424092455.672dc446@raspberrypi>
 <20170424105047.14bf00ae@raspberrypi>
 <odli42$eet$1@blaine.gmane.org>
Message-ID: <20170425084000.52ffc3c8@raspberrypi>

On Mon, 24 Apr 2017 20:02:32 +0100
Alan Gauld via Tutor <tutor at python.org> wrote:

> On 24/04/17 01:50, Phil wrote:
> > On Mon, 24 Apr 2017 09:24:55 +1000
> > Phil <phil_lor at bigpond.com> wrote:
> >
> >> On Sun, 23 Apr 2017 09:39:54 +0200
> >> Sibylle Koczian <nulla.epistola at web.de> wrote:
> >>
> >>> Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
> >>>> Its not too bad you can map the large 9x9 table to the smaller
> >>>> units using divmod()
> >>>>
> >>>> So the 7th element becomes
> >>>> divmod(7) -> 2,1
> >>>>
> >>>
> >>> Should be divmod(7, 3), shouldn't it?
> 
> Yes, of course, sorry about that!
> The 3 of course is the number of items per cell (3x3)
> 
> > Say I want the 7th cell in the first line of a 9 x 9 grid,
>  > that would be x = 7, y = 1.
> 
> But you want it mapped to a cell/item pair...
> 
> divmod(7,3) -> 2,1
> 
> 
> The 3rd cell, 2nd item which is wrong for the item part.
> So you need to use:
> 
> 2, 1-1

Thank you Alan, problem solved. All this horsing around with adding and subtracting 1 had initially led to a mass of confusing code hence the posting of my second message on this subject. Don't bother with that message, it's complete nonsense.

By the way, I notice that my messages to this list, and not other's, can take up to four hours (sometimes longer) to appear, is that normal? I'm on a bounces list, is that the reason? Probably not since I'm on several bounces lists.

Anyway, enjoy your holiday.

-- 
Regards,
Phil

From robertvstepp at gmail.com  Mon Apr 24 23:41:26 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 24 Apr 2017 22:41:26 -0500
Subject: [Tutor] How to display radiobutton window with no buttons selected?
Message-ID: <CANDiX9Jk2-dHR=iY1L-tTzAxPENEPYp2_fO5cnWokorpBcYL1g@mail.gmail.com>

Win7-64bit, Python 3.6.1

When I run the following code, the radiobutton window initially
displays with *all* buttons apparently selected.  However, when the
"Status" button is clicked on, the status is as expected, an empty
string for the checked_radiobutton StringVar().

================================================================================
#!/usr/bin/env python3

import tkinter as tk

root = tk.Tk()

# Report option selected:
def status():
    print('You selected the radiobutton:  %s' % checked_radiobutton.get())
    print()

languages = ('Perl', 'JavaScript', 'PHP', 'Python 2', 'Python 3')

# Create new variable object to keep track of checked radiobutton:
checked_radiobutton = tk.StringVar()

for language in languages:
    # Create new radiobutton:
    tk.Radiobutton(root, text=language, variable=checked_radiobutton,
            value=language).pack(anchor='w')

checked_radiobutton.set('')

tk.Button(root, text='Status', command=status).pack(fill='x')

root.mainloop()
================================================================================

I wish the displayed window to initially display with no button
selected.  What am I missing here?

Thanks!

-- 
boB

From __peter__ at web.de  Tue Apr 25 03:01:21 2017
From: __peter__ at web.de (Peter Otten)
Date: Tue, 25 Apr 2017 09:01:21 +0200
Subject: [Tutor] How to display radiobutton window with no buttons
 selected?
References: <CANDiX9Jk2-dHR=iY1L-tTzAxPENEPYp2_fO5cnWokorpBcYL1g@mail.gmail.com>
Message-ID: <odms7t$7so$1@blaine.gmane.org>

boB Stepp wrote:

> Win7-64bit, Python 3.6.1
> 
> When I run the following code, the radiobutton window initially
> displays with *all* buttons apparently selected.  However, when the
> "Status" button is clicked on, the status is as expected, an empty
> string for the checked_radiobutton StringVar().
> 
> 
================================================================================
> #!/usr/bin/env python3
> 
> import tkinter as tk
> 
> root = tk.Tk()
> 
> # Report option selected:
> def status():
>     print('You selected the radiobutton:  %s' % checked_radiobutton.get())
>     print()
> 
> languages = ('Perl', 'JavaScript', 'PHP', 'Python 2', 'Python 3')
> 
> # Create new variable object to keep track of checked radiobutton:
> checked_radiobutton = tk.StringVar()
> 
> for language in languages:
>     # Create new radiobutton:
>     tk.Radiobutton(root, text=language, variable=checked_radiobutton,
>             value=language).pack(anchor='w')
> 
> checked_radiobutton.set('')
> 
> tk.Button(root, text='Status', command=status).pack(fill='x')
> 
> root.mainloop()
> 
================================================================================
> 
> I wish the displayed window to initially display with no button
> selected.  What am I missing here?

It looks like the empty string is special. On my (linux) system all buttons 
appear grayed (while a selected button would be black). Any other string 
should give the desired result, probably because every button "thinks" that 
another button is currently selected.


From robertvstepp at gmail.com  Tue Apr 25 07:39:11 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 25 Apr 2017 06:39:11 -0500
Subject: [Tutor] How to display radiobutton window with no buttons
 selected?
In-Reply-To: <odms7t$7so$1@blaine.gmane.org>
References: <CANDiX9Jk2-dHR=iY1L-tTzAxPENEPYp2_fO5cnWokorpBcYL1g@mail.gmail.com>
 <odms7t$7so$1@blaine.gmane.org>
Message-ID: <CANDiX9JqEeRw8dGSF-YEyTNYYrcr6ofMKx_jxF9Lg7hR+WxfEg@mail.gmail.com>

On Tue, Apr 25, 2017 at 2:01 AM, Peter Otten <__peter__ at web.de> wrote:
> boB Stepp wrote:
>
>> Win7-64bit, Python 3.6.1
>>
>> When I run the following code, the radiobutton window initially
>> displays with *all* buttons apparently selected.  However, when the
>> "Status" button is clicked on, the status is as expected, an empty
>> string for the checked_radiobutton StringVar().
>>
>>
> ================================================================================
>> #!/usr/bin/env python3
>>
>> import tkinter as tk
>>
>> root = tk.Tk()
>>
>> # Report option selected:
>> def status():
>>     print('You selected the radiobutton:  %s' % checked_radiobutton.get())
>>     print()
>>
>> languages = ('Perl', 'JavaScript', 'PHP', 'Python 2', 'Python 3')
>>
>> # Create new variable object to keep track of checked radiobutton:
>> checked_radiobutton = tk.StringVar()
>>
>> for language in languages:
>>     # Create new radiobutton:
>>     tk.Radiobutton(root, text=language, variable=checked_radiobutton,
>>             value=language).pack(anchor='w')
>>
>> checked_radiobutton.set('')
>>
>> tk.Button(root, text='Status', command=status).pack(fill='x')
>>
>> root.mainloop()
>>
> ================================================================================
>>
>> I wish the displayed window to initially display with no button
>> selected.  What am I missing here?
>
> It looks like the empty string is special. On my (linux) system all buttons
> appear grayed (while a selected button would be black). Any other string
> should give the desired result, probably because every button "thinks" that
> another button is currently selected.

Interesting.  What you suggest indeed works to create the display I
desired, no radiobuttons selected; however, it does have the undesired
side effect that the status() function reports that value.  So it
looks like the best solution is to set checked_radiobutton to ' ', a
single space.  It is still there in the status() printout, but it does
not look like anything is there.  As this is a toy example, I am not
too concerned.  In something I intended to use, I would probably be
setting a default value for one of the buttons anyway.

Thanks, Peter!

-- 
boB

From rafaelfernandez85 at gmail.com  Tue Apr 25 04:49:59 2017
From: rafaelfernandez85 at gmail.com (Rafael Fernandez)
Date: Tue, 25 Apr 2017 10:49:59 +0200
Subject: [Tutor] install dlib in window and run it with python
Message-ID: <CAKwKSyKyOjszhgHHhfzk0VcLkwO_MVBeNbwmzPgdgoKXSTg52g@mail.gmail.com>

I have been asked to download the dlib library on my windows system. I
have followed the instructions given
here: http://www.paulvangent.com/2016/08/05/emotion-recognition-using-facial-landmarks/

I have already downloaded cmake and Visual Studio. On the dlib folder
command prompt, on running "python setup.py install" I get the problem
that you can see in the picture added.

Thanks in advance[image: Im?genes integradas 1]



-- 

Saludos / Best regards / Mit freundlichen Gr??en

--------------------------------------------------------
Rafael Fern?ndez
 Ph.D and research asst.



-----------------------

*P **Please consider the environment before printing this e-mail*

From alan.gauld at yahoo.co.uk  Tue Apr 25 18:27:05 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 25 Apr 2017 23:27:05 +0100
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170425084000.52ffc3c8@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
 <20170424092455.672dc446@raspberrypi> <20170424105047.14bf00ae@raspberrypi>
 <odli42$eet$1@blaine.gmane.org> <20170425084000.52ffc3c8@raspberrypi>
Message-ID: <odoifj$gb9$1@blaine.gmane.org>

On 24/04/17 23:40, Phil wrote:

> By the way, I notice that my messages to this list,
 > and not other's, can take up to four hours

Your messages come into the moderation queue, I'm
not sure why because the moderation flag is not
set on your account(it is automatically for new
members).

I'll have a closer look next eek when I get back.

Alan G



From phil_lor at bigpond.com  Wed Apr 26 02:56:28 2017
From: phil_lor at bigpond.com (Phil)
Date: Wed, 26 Apr 2017 16:56:28 +1000
Subject: [Tutor] Tkinter layout question
In-Reply-To: <odoifj$gb9$1@blaine.gmane.org>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org>
 <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
 <20170424092455.672dc446@raspberrypi>
 <20170424105047.14bf00ae@raspberrypi>
 <odli42$eet$1@blaine.gmane.org>
 <20170425084000.52ffc3c8@raspberrypi>
 <odoifj$gb9$1@blaine.gmane.org>
Message-ID: <20170426165628.665234f4@raspberrypi>

On Tue, 25 Apr 2017 23:27:05 +0100
Alan Gauld via Tutor <tutor at python.org> wrote:


> Your messages come into the moderation queue, I'm
> not sure why because the moderation flag is not
> set on your account(it is automatically for new
> members).
> 
> I'll have a closer look next eek when I get back.

Thanks Alan, maybe the reason that I'm in the moderation queue is because I'm on the bounces list. I'm on six different bounces lists but I'm still receiving e-mail so I suppose there isn't a real problem.

-- 
Regards,
Phil

From sarika1989.08 at gmail.com  Wed Apr 26 02:43:29 2017
From: sarika1989.08 at gmail.com (Sarika Shrivastava)
Date: Wed, 26 Apr 2017 12:13:29 +0530
Subject: [Tutor]  change the position and updated
Message-ID: <CACB_4S8Rjxuo1bwFUAwVEFHbs7vwSoea59AZkf-zAZfB+RAPFQ@mail.gmail.com>

Input :
c=[(12,45),(1234,567),(12345,0),(678,123456)]

#o/p==1425
#o/p==1526374
#0/p==102345
#o/p===617283456

Question explanation:

in list c we have some tuples so I need to take tuple value one by one and
change the position of value like wise

 first tuple value (12 ,45) then  then 1 we pick up append on 4 So it make
 14 after tat 2 we pick and append on 5 so 25 then final o/p is 1425 ,

Please check output also...

-- 
Best regards,

Sarika Shrivastava
Associate Engineer

Continental Automotive Components (India) Pvt. Ltd.,
8th Floor, Gold Hill Supreme Software Park,
Plot No. 21, 22, 27 & 28, Shanthipura Road,
Electronics City, Phase II, Hosur Road,
Bangalore-560 100

Tel: +919741457409
Mobile: +919741457409
E-Mail: sarika.shrivastava at continental-corporation.com
Web: www.continental-corporation.com

From __peter__ at web.de  Wed Apr 26 05:18:00 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 26 Apr 2017 11:18 +0200
Subject: [Tutor] change the position and updated
References: <CACB_4S8Rjxuo1bwFUAwVEFHbs7vwSoea59AZkf-zAZfB+RAPFQ@mail.gmail.com>
Message-ID: <odpok7$v6l$1@blaine.gmane.org>

Sarika Shrivastava wrote:

> Input :
> c=[(12,45),(1234,567),(12345,0),(678,123456)]
> 
> #o/p==1425
> #o/p==1526374
> #0/p==102345
> #o/p===617283456
> 
> Question explanation:
> 
> in list c we have some tuples so I need to take tuple value one by one and
> change the position of value like wise
> 
>  first tuple value (12 ,45) then  then 1 we pick up append on 4 So it make
>  14 after tat 2 we pick and append on 5 so 25 then final o/p is 1425 ,
> 
> Please check output also...

That looks *a* *lot* like homework, so you're supposed to find the answer 
yourself. A few hints:

- splicing the digits will become easier if you convert the numbers to 
strings first.

- have a look at itertools.zip_longest() (you'll need to specify a 
fillvalue. Which?)

- you can build a string from a sequence of strings with "".join(strings).

If that's not enough to get a working solution you may come back here once 
you have some code.


From neeraj.sh7 at gmail.com  Wed Apr 26 05:31:35 2017
From: neeraj.sh7 at gmail.com (Neeraj Sharma)
Date: Wed, 26 Apr 2017 15:01:35 +0530
Subject: [Tutor] change the position and updated
In-Reply-To: <CACB_4S8Rjxuo1bwFUAwVEFHbs7vwSoea59AZkf-zAZfB+RAPFQ@mail.gmail.com>
References: <CACB_4S8Rjxuo1bwFUAwVEFHbs7vwSoea59AZkf-zAZfB+RAPFQ@mail.gmail.com>
Message-ID: <CANsYMutcLuUgZsGQLuHYusOfaATcYL=8y+GE095zFyKS2DXYKg@mail.gmail.com>

Hi,

Find the code below

c = [(12, 45), (1234, 567), (12345, 0), (678, 123456)]

max_length = 0
for key,value in c:
     list1 = []
     list2 = []
     for i in str(key):
             list1.append(i)
     for j in str(value):
             list2.append(j)
     if (len(list1)>len(list2)): max_length = len(list1)
     else: max_length = len(list2)
     for i in range(0,max_length):
             pass
     result=""
     for i in range(0,max_length):
         try: result = result + list1[i]
         except: pass
         try: result = result + list2[i]
         except: pass
     print int(result)

On Wed, Apr 26, 2017 at 12:13 PM, Sarika Shrivastava <
sarika1989.08 at gmail.com> wrote:

> Input :
> c=[(12,45),(1234,567),(12345,0),(678,123456)]
>
> #o/p==1425
> #o/p==1526374
> #0/p==102345
> #o/p===617283456
>
> Question explanation:
>
> in list c we have some tuples so I need to take tuple value one by one and
> change the position of value like wise
>
>  first tuple value (12 ,45) then  then 1 we pick up append on 4 So it make
>  14 after tat 2 we pick and append on 5 so 25 then final o/p is 1425 ,
>
> Please check output also...
>
> --
> Best regards,
>
> Sarika Shrivastava
> Associate Engineer
>
> Continental Automotive Components (India) Pvt. Ltd.,
> 8th Floor, Gold Hill Supreme Software Park,
> Plot No. 21, 22, 27 & 28, Shanthipura Road,
> Electronics City, Phase II, Hosur Road,
> Bangalore-560 100
>
> Tel: +919741457409
> Mobile: +919741457409
> E-Mail: sarika.shrivastava at continental-corporation.com
> Web: www.continental-corporation.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 

*Thanks & Regards*

*Neeraj Sharma+91-9873741375*

From neeraj.sh7 at gmail.com  Wed Apr 26 05:36:21 2017
From: neeraj.sh7 at gmail.com (Neeraj Sharma)
Date: Wed, 26 Apr 2017 15:06:21 +0530
Subject: [Tutor] change the position and updated
In-Reply-To: <CANsYMutcLuUgZsGQLuHYusOfaATcYL=8y+GE095zFyKS2DXYKg@mail.gmail.com>
References: <CACB_4S8Rjxuo1bwFUAwVEFHbs7vwSoea59AZkf-zAZfB+RAPFQ@mail.gmail.com>
 <CANsYMutcLuUgZsGQLuHYusOfaATcYL=8y+GE095zFyKS2DXYKg@mail.gmail.com>
Message-ID: <CANsYMuu+ofaSay6ZGqCZvpkfdSznCAV_kZ1Sh2Oya7RU_MiDOg@mail.gmail.com>

c = [(12, 45), (1234, 567), (12345, 0), (678, 123456)]

max_length = 0
for key,value in c:
     list1 = []
     list2 = []
     for i in str(key):
             list1.append(i)
     for j in str(value):
             list2.append(j)
     if (len(list1)>len(list2)): max_length = len(list1)
     else: max_length = len(list2)
     result=""
     for i in range(0,max_length):
         try: result = result + list1[i]
         except: pass
         try: result = result + list2[i]
         except: pass
     print int(result)

On Wed, Apr 26, 2017 at 3:01 PM, Neeraj Sharma <neeraj.sh7 at gmail.com> wrote:

> Hi,
>
> Find the code below
>
> c = [(12, 45), (1234, 567), (12345, 0), (678, 123456)]
>
> max_length = 0
> for key,value in c:
>      list1 = []
>      list2 = []
>      for i in str(key):
>              list1.append(i)
>      for j in str(value):
>              list2.append(j)
>      if (len(list1)>len(list2)): max_length = len(list1)
>      else: max_length = len(list2)
>      for i in range(0,max_length):
>              pass
>      result=""
>      for i in range(0,max_length):
>          try: result = result + list1[i]
>          except: pass
>          try: result = result + list2[i]
>          except: pass
>      print int(result)
>
> On Wed, Apr 26, 2017 at 12:13 PM, Sarika Shrivastava <
> sarika1989.08 at gmail.com> wrote:
>
> > Input :
> > c=[(12,45),(1234,567),(12345,0),(678,123456)]
> >
> > #o/p==1425
> > #o/p==1526374
> > #0/p==102345
> > #o/p===617283456
> >
> > Question explanation:
> >
> > in list c we have some tuples so I need to take tuple value one by one
> and
> > change the position of value like wise
> >
> >  first tuple value (12 ,45) then  then 1 we pick up append on 4 So it
> make
> >  14 after tat 2 we pick and append on 5 so 25 then final o/p is 1425 ,
> >
> > Please check output also...
> >
> > --
> > Best regards,
> >
> > Sarika Shrivastava
> > Associate Engineer
> >
> > Continental Automotive Components (India) Pvt. Ltd.,
> > 8th Floor, Gold Hill Supreme Software Park,
> > Plot No. 21, 22, 27 & 28, Shanthipura Road,
> > Electronics City, Phase II, Hosur Road,
> > Bangalore-560 100
> >
> > Tel: +919741457409
> > Mobile: +919741457409
> > E-Mail: sarika.shrivastava at continental-corporation.com
> > Web: www.continental-corporation.com
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> --
>
> *Thanks & Regards*
>
> *Neeraj Sharma+91-9873741375*
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 

*Thanks & Regards*

*Neeraj Sharma+91-9873741375*

From sarika1989.08 at gmail.com  Wed Apr 26 08:44:54 2017
From: sarika1989.08 at gmail.com (Sarika Shrivastava)
Date: Wed, 26 Apr 2017 07:44:54 -0500
Subject: [Tutor] change the position and updated
In-Reply-To: <CANsYMuu+ofaSay6ZGqCZvpkfdSznCAV_kZ1Sh2Oya7RU_MiDOg@mail.gmail.com>
References: <CACB_4S8Rjxuo1bwFUAwVEFHbs7vwSoea59AZkf-zAZfB+RAPFQ@mail.gmail.com>
 <CANsYMutcLuUgZsGQLuHYusOfaATcYL=8y+GE095zFyKS2DXYKg@mail.gmail.com>
 <CANsYMuu+ofaSay6ZGqCZvpkfdSznCAV_kZ1Sh2Oya7RU_MiDOg@mail.gmail.com>
Message-ID: <CACB_4S_RcW=V=ghDR9jZK2ZL=z3gtanVyUrM0WLcHJZH1dZL1g@mail.gmail.com>

Thanks you  Neeraj giving the solution of problem I was trying  as but not
able to find right solution

Thanks to others also for giving a nice advice

On Wed, Apr 26, 2017 at 4:36 AM, Neeraj Sharma <neeraj.sh7 at gmail.com> wrote:

> c = [(12, 45), (1234, 567), (12345, 0), (678, 123456)]
>
> max_length = 0
> for key,value in c:
>      list1 = []
>      list2 = []
>      for i in str(key):
>              list1.append(i)
>      for j in str(value):
>              list2.append(j)
>      if (len(list1)>len(list2)): max_length = len(list1)
>      else: max_length = len(list2)
>      result=""
>      for i in range(0,max_length):
>          try: result = result + list1[i]
>          except: pass
>          try: result = result + list2[i]
>          except: pass
>      print int(result)
>
> On Wed, Apr 26, 2017 at 3:01 PM, Neeraj Sharma <neeraj.sh7 at gmail.com>
> wrote:
>
>> Hi,
>>
>> Find the code below
>>
>> c = [(12, 45), (1234, 567), (12345, 0), (678, 123456)]
>>
>> max_length = 0
>> for key,value in c:
>>      list1 = []
>>      list2 = []
>>      for i in str(key):
>>              list1.append(i)
>>      for j in str(value):
>>              list2.append(j)
>>      if (len(list1)>len(list2)): max_length = len(list1)
>>      else: max_length = len(list2)
>>      for i in range(0,max_length):
>>              pass
>>      result=""
>>      for i in range(0,max_length):
>>          try: result = result + list1[i]
>>          except: pass
>>          try: result = result + list2[i]
>>          except: pass
>>      print int(result)
>>
>> On Wed, Apr 26, 2017 at 12:13 PM, Sarika Shrivastava <
>> sarika1989.08 at gmail.com> wrote:
>>
>> > Input :
>> > c=[(12,45),(1234,567),(12345,0),(678,123456)]
>> >
>> > #o/p==1425
>> > #o/p==1526374
>> > #0/p==102345
>> > #o/p===617283456
>> >
>> > Question explanation:
>> >
>> > in list c we have some tuples so I need to take tuple value one by one
>> and
>> > change the position of value like wise
>> >
>> >  first tuple value (12 ,45) then  then 1 we pick up append on 4 So it
>> make
>> >  14 after tat 2 we pick and append on 5 so 25 then final o/p is 1425 ,
>> >
>> > Please check output also...
>> >
>> > --
>> > Best regards,
>> >
>> > Sarika Shrivastava
>> > Associate Engineer
>> >
>> > Continental Automotive Components (India) Pvt. Ltd.,
>> > 8th Floor, Gold Hill Supreme Software Park,
>> > Plot No. 21, 22, 27 & 28, Shanthipura Road,
>> > Electronics City, Phase II, Hosur Road,
>> > Bangalore-560 100
>> >
>> > Tel: +919741457409 <+91%2097414%2057409>
>> > Mobile: +919741457409 <+91%2097414%2057409>
>> > E-Mail: sarika.shrivastava at continental-corporation.com
>> > Web: www.continental-corporation.com
>> > _______________________________________________
>> > Tutor maillist  -  Tutor at python.org
>> > To unsubscribe or change subscription options:
>> > https://mail.python.org/mailman/listinfo/tutor
>> >
>>
>>
>>
>> --
>>
>> *Thanks & Regards*
>>
>> *Neeraj Sharma+91-9873741375 <+91%2098737%2041375>*
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
>
> *Thanks & Regards*
>
> *Neeraj Sharma+91-9873741375 <+91%2098737%2041375>*
>



-- 
Best regards,

Sarika Shrivastava
Associate Engineer

Continental Automotive Components (India) Pvt. Ltd.,
8th Floor, Gold Hill Supreme Software Park,
Plot No. 21, 22, 27 & 28, Shanthipura Road,
Electronics City, Phase II, Hosur Road,
Bangalore-560 100

Tel: +919741457409
Mobile: +919741457409
E-Mail: sarika.shrivastava at continental-corporation.com
Web: www.continental-corporation.com

From phil_lor at bigpond.com  Wed Apr 26 20:33:16 2017
From: phil_lor at bigpond.com (Phil)
Date: Thu, 27 Apr 2017 10:33:16 +1000
Subject: [Tutor] Sets question
Message-ID: <20170427103316.52152a1c@raspberrypi>

Another question I'm afraid.

If I want to remove 1 from a set then this is the answer:

set([1,2,3]) - set([1])

I had this method working perfectly until I made a change to cure another bug.

So, I have a set represented in the debugger as {1,2,3} and again I want to remove the one. Only this time the one set is represented as {'1'} and, of course {'1'} is not in the set {1,2,3}.

Ideally, I would like {'1'} to become {1}. Try as I may, I have not discovered how to remove the '' marks. How do I achieve that?

-- 
Regards,
Phil

From robertvstepp at gmail.com  Wed Apr 26 21:07:47 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 26 Apr 2017 20:07:47 -0500
Subject: [Tutor] Sets question
In-Reply-To: <20170427103316.52152a1c@raspberrypi>
References: <20170427103316.52152a1c@raspberrypi>
Message-ID: <CANDiX9L_hKqpJY8kODxz-RG1fU-Yf79Y_32bOtghtjt5WBN+Hw@mail.gmail.com>

On Wed, Apr 26, 2017 at 7:33 PM, Phil <phil_lor at bigpond.com> wrote:
> Another question I'm afraid.
>
> If I want to remove 1 from a set then this is the answer:
>
> set([1,2,3]) - set([1])
>
> I had this method working perfectly until I made a change to cure another bug.
>
> So, I have a set represented in the debugger as {1,2,3} and again I want to remove the one. Only this time the one set is represented as {'1'} and, of course {'1'} is not in the set {1,2,3}.
>
> Ideally, I would like {'1'} to become {1}. Try as I may, I have not discovered how to remove the '' marks. How do I achieve that?

I probably don't understand what you are really trying to do, but

{1, 2, 3} - {int('1')}

does the obvious.  But I am guessing that this is not what you want.
Perhaps you can provide more context, or perhaps others can better
discern your needs?

boB

From eryksun at gmail.com  Wed Apr 26 21:15:23 2017
From: eryksun at gmail.com (eryk sun)
Date: Thu, 27 Apr 2017 01:15:23 +0000
Subject: [Tutor] Sets question
In-Reply-To: <20170427103316.52152a1c@raspberrypi>
References: <20170427103316.52152a1c@raspberrypi>
Message-ID: <CACL+1av0dQgDBP5C8c3o_w1OUXDvCjTxk_kGYbC-SwAhKu5mFA@mail.gmail.com>

On Thu, Apr 27, 2017 at 12:33 AM, Phil <phil_lor at bigpond.com> wrote:
> Another question I'm afraid.
>
> If I want to remove 1 from a set then this is the answer:
>
> set([1,2,3]) - set([1])

You can also use set literals here, with the caveat that {} is
ambiguous, and Python chooses to make it an empty dict instead of a
set.

    >>> {1, 2, 3} - {1}
    {2, 3}

related operations:

    >>> s = {1, 2, 3}
    >>> s -= {1}
    >>> s
    {2, 3}
    >>> s.remove(2)
    >>> s
    {3}

> Ideally, I would like {'1'} to become {1}. Try as I may, I have not
> discovered how to remove the '' marks. How do I achieve that?

The quotation marks are the representation of a string object (i.e.
str). If you want an integer object (i.e. int), you have to convert
the value of the string to an integer.

    >>> x = '1'
    >>> {1, 2, 3} - {int(x)}
    {2, 3}

From phil_lor at bigpond.com  Wed Apr 26 21:34:55 2017
From: phil_lor at bigpond.com (Phil)
Date: Thu, 27 Apr 2017 11:34:55 +1000
Subject: [Tutor] Sets question
In-Reply-To: <43fcbb2a-6072-6979-ee84-3d0fc43a1d07@wichmann.us>
References: <20170427103316.52152a1c@raspberrypi>
 <43fcbb2a-6072-6979-ee84-3d0fc43a1d07@wichmann.us>
Message-ID: <20170427113455.1836a7ae@raspberrypi>

On Wed, 26 Apr 2017 18:56:40 -0600
Mats Wichmann <mats at wichmann.us> wrote:

> On 04/26/2017 06:33 PM, Phil wrote:
> > Another question I'm afraid.
> > 
> > If I want to remove 1 from a set then this is the answer:
> > 
> > set([1,2,3]) - set([1])
> > 
> > I had this method working perfectly until I made a change to cure
> > another bug.
> > 
> > So, I have a set represented in the debugger as {1,2,3} and again I
> > want to remove the one. Only this time the one set is represented
> > as {'1'} and, of course {'1'} is not in the set {1,2,3}.
> > 
> > Ideally, I would like {'1'} to become {1}. Try as I may, I have not
> > discovered how to remove the '' marks. How do I achieve that?
> > 
> 
> A little confused... why not just create it the way you want it? How
> do you end up with {'1'} ?

Thank you for your quick replies Mats and erky.

I use .get() to retrieve a number from an entry box, which looks like {1} (no '' marks). If I then turn this number into a set then the result is {'1'}.

num = self.entry_grid[row][col].get()
self.solution[row][col] = set([num])

As I say, my project worked perfectly with just {1} until I discovered a bug further on in the code. Perhaps I should go back to my original version and the fix the bug in some other way?

I did try {int(num)} but that resulted in an error that said something along the lines of int not being iterable. I'll have another look at that idea.

-- 
Regards,
Phil

From eryksun at gmail.com  Wed Apr 26 21:58:39 2017
From: eryksun at gmail.com (eryk sun)
Date: Thu, 27 Apr 2017 01:58:39 +0000
Subject: [Tutor] Sets question
In-Reply-To: <20170427113455.1836a7ae@raspberrypi>
References: <20170427103316.52152a1c@raspberrypi>
 <43fcbb2a-6072-6979-ee84-3d0fc43a1d07@wichmann.us>
 <20170427113455.1836a7ae@raspberrypi>
Message-ID: <CACL+1as-40kaB3++s1fK53t+tKcw5ao1t0k_gnqNk-Vw8mkH1A@mail.gmail.com>

On Thu, Apr 27, 2017 at 1:34 AM, Phil <phil_lor at bigpond.com> wrote:
> I did try {int(num)} but that resulted in an error that said something along
> the lines of int not being iterable. I'll have another look at that idea.

That exception indicates you probably used set(int(num)) instead of
either {int(num)} or set([int(num)]). The set() constructor needs an
iterable container such as a sequence (e.g. range, list, tuple, str).
An integer isn't iterable.

From robertvstepp at gmail.com  Wed Apr 26 22:02:26 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 26 Apr 2017 21:02:26 -0500
Subject: [Tutor] Sets question
In-Reply-To: <20170427113455.1836a7ae@raspberrypi>
References: <20170427103316.52152a1c@raspberrypi>
 <43fcbb2a-6072-6979-ee84-3d0fc43a1d07@wichmann.us>
 <20170427113455.1836a7ae@raspberrypi>
Message-ID: <CANDiX9+XB6aWpbx+ahYdj4mT2HisxNknv4vaSB89-vfUYTK5HQ@mail.gmail.com>

On Wed, Apr 26, 2017 at 8:34 PM, Phil <phil_lor at bigpond.com> wrote:
> On Wed, 26 Apr 2017 18:56:40 -0600
> Mats Wichmann <mats at wichmann.us> wrote:
>
>> On 04/26/2017 06:33 PM, Phil wrote:
>> > Another question I'm afraid.
>> >
>> > If I want to remove 1 from a set then this is the answer:
>> >
>> > set([1,2,3]) - set([1])
>> >
>> > I had this method working perfectly until I made a change to cure
>> > another bug.
>> >
>> > So, I have a set represented in the debugger as {1,2,3} and again I
>> > want to remove the one. Only this time the one set is represented
>> > as {'1'} and, of course {'1'} is not in the set {1,2,3}.
>> >
>> > Ideally, I would like {'1'} to become {1}. Try as I may, I have not
>> > discovered how to remove the '' marks. How do I achieve that?
>> >
>>
>> A little confused... why not just create it the way you want it? How
>> do you end up with {'1'} ?
>
> Thank you for your quick replies Mats and erky.
>
> I use .get() to retrieve a number from an entry box, which looks like {1} (no '' marks). If I then turn this number into a set then the result is {'1'}.
>
> num = self.entry_grid[row][col].get()

I would think that it is here that you would want to do the
string-to-integer conversion.  The contents of an entry box are
strings, not integers or floats.

num = int(self.entry_grid[row][col].get())

It is a similar situation when using input() to get user input.  You
need to convert the 'number-like' strings to integers (or floats).

-- 
boB

From robertvstepp at gmail.com  Wed Apr 26 22:08:16 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 26 Apr 2017 21:08:16 -0500
Subject: [Tutor] Difference between %f and %F string formatting?
Message-ID: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>

My Google-fu must be weak tonight.  I cannot find any discernible
difference between '%f' % <some floating point number> and '%F' %
<some floating point number>.  Is there any or do they duplicate
functionality?  If the latter, why are there two ways of doing the
same thing?

I had a similar question for %d and %i, but googling suggests these
are inherited from differences in handling input in the C language,
though I could not locate a Python example where there is a need for
one or the other.  Are there any relevant Python examples?

-- 
boB

From tim.peters at gmail.com  Wed Apr 26 22:19:48 2017
From: tim.peters at gmail.com (Tim Peters)
Date: Wed, 26 Apr 2017 21:19:48 -0500
Subject: [Tutor] Difference between %f and %F string formatting?
In-Reply-To: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>
References: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>
Message-ID: <CAExdVNmKR1itQTBhyZH+BWAKgPzrw-+HB2Rwe4dkeM9uSQxCVw@mail.gmail.com>

[boB Stepp <robertvstepp at gmail.com>]
> My Google-fu must be weak tonight.

Look here:

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

>  I cannot find any discernible
> difference between '%f' % <some floating point number> and '%F' %
> <some floating point number>.  Is there any or do they duplicate
> functionality?  If the latter, why are there two ways of doing the
> same thing?

They differ only in the capitalization of the strings produced for
NaNs and infinities (math.nan and math.inf in Python 3).

>>> "%f" % math.nan
nan'
>>> "%F" % math.nan
NAN'
>>> "%f" % math.inf
inf'
>>> "%F" % math.inf
INF'


> I had a similar question for %d and %i, but googling suggests these
> are inherited from differences in handling input in the C language,
> though I could not locate a Python example where there is a need for
> one or the other.  Are there any relevant Python examples?

No difference for output in Python or in C.  Python inherited its
format codes from C, and so that's why Python allows both:  just
because C does.

From robertvstepp at gmail.com  Wed Apr 26 22:33:59 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 26 Apr 2017 21:33:59 -0500
Subject: [Tutor] Difference between %f and %F string formatting?
In-Reply-To: <CAExdVNmKR1itQTBhyZH+BWAKgPzrw-+HB2Rwe4dkeM9uSQxCVw@mail.gmail.com>
References: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>
 <CAExdVNmKR1itQTBhyZH+BWAKgPzrw-+HB2Rwe4dkeM9uSQxCVw@mail.gmail.com>
Message-ID: <CANDiX9K8m+ivGNwqG4OP+iQDi4L0WbdOJVCziR7+pTQBkAWi2g@mail.gmail.com>

On Wed, Apr 26, 2017 at 9:19 PM, Tim Peters <tim.peters at gmail.com> wrote:
> [boB Stepp <robertvstepp at gmail.com>]
>> My Google-fu must be weak tonight.
>
> Look here:
>
>     https://en.wikipedia.org/wiki/Printf_format_string

Thanks.  From the %d versus %i links I found, I should have pursued
the C history more diligently for the %f versus %F question.  My bad!

>>  I cannot find any discernible
>> difference between '%f' % <some floating point number> and '%F' %
>> <some floating point number>.  Is there any or do they duplicate
>> functionality?  If the latter, why are there two ways of doing the
>> same thing?
>
> They differ only in the capitalization of the strings produced for
> NaNs and infinities (math.nan and math.inf in Python 3).

Hmm.  I'm surprised this slight distinction was worth keeping two
format codes that otherwise do the same thing.  Is there an actual
need for these due to Python being implemented behind the scenes in C?

-- 
boB

From eryksun at gmail.com  Wed Apr 26 22:38:43 2017
From: eryksun at gmail.com (eryk sun)
Date: Thu, 27 Apr 2017 02:38:43 +0000
Subject: [Tutor] Difference between %f and %F string formatting?
In-Reply-To: <CAExdVNmKR1itQTBhyZH+BWAKgPzrw-+HB2Rwe4dkeM9uSQxCVw@mail.gmail.com>
References: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>
 <CAExdVNmKR1itQTBhyZH+BWAKgPzrw-+HB2Rwe4dkeM9uSQxCVw@mail.gmail.com>
Message-ID: <CACL+1avM2f6EdM88TUUGBciGR_nv85b0K1KGq_VKTBu=gFveDg@mail.gmail.com>

On Thu, Apr 27, 2017 at 2:19 AM, Tim Peters <tim.peters at gmail.com> wrote:
> [boB Stepp <robertvstepp at gmail.com>]
>
>>  I cannot find any discernible
>> difference between '%f' % <some floating point number> and '%F' %
>> <some floating point number>.  Is there any or do they duplicate
>> functionality?  If the latter, why are there two ways of doing the
>> same thing?
>
> They differ only in the capitalization of the strings produced for
> NaNs and infinities (math.nan and math.inf in Python 3).
>
>>>> "%f" % math.nan
> nan'
>>>> "%F" % math.nan
> NAN'
>>>> "%f" % math.inf
> inf'
>>>> "%F" % math.inf
> INF'

In context this can be inferred from the docs, but I think f/F should
indicate the casing difference just like e/E, g/G, and x/X do.

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

From phil_lor at bigpond.com  Wed Apr 26 23:33:40 2017
From: phil_lor at bigpond.com (Phil)
Date: Thu, 27 Apr 2017 13:33:40 +1000
Subject: [Tutor] Sets question
In-Reply-To: <CACL+1as-40kaB3++s1fK53t+tKcw5ao1t0k_gnqNk-Vw8mkH1A@mail.gmail.com>
References: <20170427103316.52152a1c@raspberrypi>
 <43fcbb2a-6072-6979-ee84-3d0fc43a1d07@wichmann.us>
 <20170427113455.1836a7ae@raspberrypi>
 <CACL+1as-40kaB3++s1fK53t+tKcw5ao1t0k_gnqNk-Vw8mkH1A@mail.gmail.com>
Message-ID: <20170427133340.6077f890@raspberrypi>

On Thu, 27 Apr 2017 01:58:39 +0000
eryk sun <eryksun at gmail.com> wrote:


> That exception indicates you probably used set(int(num)) instead of
> either {int(num)} or set([int(num)]).

Thank you Eryl, you are correct. Problem solved.

-- 
Regards,
Phil

From tim.peters at gmail.com  Wed Apr 26 23:51:09 2017
From: tim.peters at gmail.com (Tim Peters)
Date: Wed, 26 Apr 2017 22:51:09 -0500
Subject: [Tutor] Difference between %f and %F string formatting?
In-Reply-To: <CANDiX9K8m+ivGNwqG4OP+iQDi4L0WbdOJVCziR7+pTQBkAWi2g@mail.gmail.com>
References: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>
 <CAExdVNmKR1itQTBhyZH+BWAKgPzrw-+HB2Rwe4dkeM9uSQxCVw@mail.gmail.com>
 <CANDiX9K8m+ivGNwqG4OP+iQDi4L0WbdOJVCziR7+pTQBkAWi2g@mail.gmail.com>
Message-ID: <CAExdVNkaMywzZNbA6T3ztpQOp_5ngVXwDvmOpVrJYfhCaRWjTg@mail.gmail.com>

[boB Stepp <robertvstepp at gmail.com>, on %i/%d and %f/%F]
> Hmm.  I'm surprised this slight distinction was worth keeping two
> format codes that otherwise do the same thing.  Is there an actual
> need for these due to Python being implemented behind the scenes in C?

The implementation is irrelevant to this.  What is relevant:  Python
took its format-string semantics from C.  Because of that alone, any
deviation from what the C docs say has to have very strong
justification.  "It's just like C" saves us from needing to write our
own mountains of tutorials and reference material.   The C world -
which has way more people and money supporting it - did that for us.

Recall that I answered your original question by pointing to an
article on the web about how this stuff works in C ;-)

From __peter__ at web.de  Thu Apr 27 03:09:59 2017
From: __peter__ at web.de (Peter Otten)
Date: Thu, 27 Apr 2017 09:09:59 +0200
Subject: [Tutor] change the position and updated
References: <CACB_4S8Rjxuo1bwFUAwVEFHbs7vwSoea59AZkf-zAZfB+RAPFQ@mail.gmail.com>
 <odpok7$v6l$1@blaine.gmane.org>
Message-ID: <ods5g2$i8k$1@blaine.gmane.org>

Peter Otten wrote:

> Sarika Shrivastava wrote:
> 
>> Input :
>> c=[(12,45),(1234,567),(12345,0),(678,123456)]
>> 
>> #o/p==1425
>> #o/p==1526374
>> #0/p==102345
>> #o/p===617283456

<snip my hints>

> If that's not enough to get a working solution you may come back here once
> you have some code.

OK, won't happen. Here's what I had in mind:

$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import zip_longest
>>> c = [(12, 45), (1234, 567), (12345, 0), (678, 123456)]
>>> for a, b in c:
...     pairs = zip_longest(str(a), str(b), fillvalue="")
...     print("".join(x + y for x, y in pairs))
... 
1425
1526374
102345
617283456



From mats at wichmann.us  Wed Apr 26 20:56:40 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 26 Apr 2017 18:56:40 -0600
Subject: [Tutor] Sets question
In-Reply-To: <20170427103316.52152a1c@raspberrypi>
References: <20170427103316.52152a1c@raspberrypi>
Message-ID: <43fcbb2a-6072-6979-ee84-3d0fc43a1d07@wichmann.us>

On 04/26/2017 06:33 PM, Phil wrote:
> Another question I'm afraid.
> 
> If I want to remove 1 from a set then this is the answer:
> 
> set([1,2,3]) - set([1])
> 
> I had this method working perfectly until I made a change to cure another bug.
> 
> So, I have a set represented in the debugger as {1,2,3} and again I want to remove the one. Only this time the one set is represented as {'1'} and, of course {'1'} is not in the set {1,2,3}.
> 
> Ideally, I would like {'1'} to become {1}. Try as I may, I have not discovered how to remove the '' marks. How do I achieve that?
> 

A little confused... why not just create it the way you want it? How do
you end up with {'1'} ?

Since sets are unordered, you can't use indexing to change a value, but
you can discard a value and add a new value in the form you want.

but Python isn't terribly friendly to identifying if something is a
string... you could do something grotty like this I suppose:


for f in some_set:
    if isinstance(f, str):
        some_set.discard(f)
        some_set.add(int(f))


(top of head, not really experimented with)


From mats at wichmann.us  Wed Apr 26 22:38:06 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 26 Apr 2017 20:38:06 -0600
Subject: [Tutor] Difference between %f and %F string formatting?
In-Reply-To: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>
References: <CANDiX9KPMuG6GPAkS1Sy=TqYrL=y_LoMeJ=1wb3_ipyZCayQMg@mail.gmail.com>
Message-ID: <BB61A3E6-ACB7-4252-BF35-39041A481C26@wichmann.us>

F means print it in uppercase. That's really an edge case for a float, that would only apply to the special values infinity and not-a-number.

On April 26, 2017 8:08:16 PM MDT, boB Stepp <robertvstepp at gmail.com> wrote:
>My Google-fu must be weak tonight.  I cannot find any discernible
>difference between '%f' % <some floating point number> and '%F' %
><some floating point number>.  Is there any or do they duplicate
>functionality?  If the latter, why are there two ways of doing the
>same thing?
>
>I had a similar question for %d and %i, but googling suggests these
>are inherited from differences in handling input in the C language,
>though I could not locate a Python example where there is a need for
>one or the other.  Are there any relevant Python examples?
>
>-- 
>boB
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.

From __peter__ at web.de  Thu Apr 27 05:49:55 2017
From: __peter__ at web.de (Peter Otten)
Date: Thu, 27 Apr 2017 11:49:55 +0200
Subject: [Tutor] Sets question
References: <20170427103316.52152a1c@raspberrypi>
Message-ID: <odses3$jkr$1@blaine.gmane.org>

Phil wrote:

> Another question I'm afraid.
> 
> If I want to remove 1 from a set then this is the answer:
> 
> set([1,2,3]) - set([1])
> 
> I had this method working perfectly until I made a change to cure another
> bug.
> 
> So, I have a set represented in the debugger as {1,2,3} and again I want
> to remove the one. Only this time the one set is represented as {'1'} and,
> of course {'1'} is not in the set {1,2,3}.
> 
> Ideally, I would like {'1'} to become {1}. Try as I may, I have not
> discovered how to remove the '' marks. How do I achieve that?
 
If your code now looks like this

>>> s = {1, 2, 3}
>>> v = "1"
>>> s = s - set([int(v)])
>>> s
{2, 3}

or this

>>> s = {1, 2, 3}
>>> s = s - {int(v)}
>>> s
{2, 3}

I'd like to bring to your attention the discard() method

>>> s = {1, 2, 3}
>>> s.discard(int(v))
>>> s
{2, 3}

which allows you to avoid building the throwaway single-entry set.


From cs at zip.com.au  Thu Apr 27 03:23:19 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Thu, 27 Apr 2017 17:23:19 +1000
Subject: [Tutor] Difference between %f and %F string formatting?
In-Reply-To: <CAExdVNkaMywzZNbA6T3ztpQOp_5ngVXwDvmOpVrJYfhCaRWjTg@mail.gmail.com>
References: <CAExdVNkaMywzZNbA6T3ztpQOp_5ngVXwDvmOpVrJYfhCaRWjTg@mail.gmail.com>
Message-ID: <20170427072319.GA67871@cskk.homeip.net>

On 26Apr2017 22:51, Tim Peters <tim.peters at gmail.com> wrote:
>[boB Stepp <robertvstepp at gmail.com>, on %i/%d and %f/%F]
>> Hmm.  I'm surprised this slight distinction was worth keeping two
>> format codes that otherwise do the same thing.  Is there an actual
>> need for these due to Python being implemented behind the scenes in C?
>
>The implementation is irrelevant to this.  What is relevant:  Python
>took its format-string semantics from C.  Because of that alone, any
>deviation from what the C docs say has to have very strong
>justification.  "It's just like C" saves us from needing to write our
>own mountains of tutorials and reference material.   The C world -
>which has way more people and money supporting it - did that for us.

Another reason for this kind of thing is that if the printf codes are used 
faithfully WRT the C printf codes it makes reproducing specific outputs a bit 
easier.

It is a bit of a niche, but sometimes one wants to write something in Python 
whose output perfectly mimics that of another tool, usually because that output 
is in turn parsed by some utility one wants to use. If the target output was 
generated with printf, and if even better its source is available, one can just 
reuse the formats rather than having to laboriously reproduce special stuff.

Definitely a niche, and probably not the core motivation here. But handy.

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

From phil_lor at bigpond.com  Thu Apr 27 20:52:19 2017
From: phil_lor at bigpond.com (Phil)
Date: Fri, 28 Apr 2017 10:52:19 +1000
Subject: [Tutor] Sets question
In-Reply-To: <odses3$jkr$1@blaine.gmane.org>
References: <20170427103316.52152a1c@raspberrypi>
 <odses3$jkr$1@blaine.gmane.org>
Message-ID: <20170428105219.66fda2ce@raspberrypi>

On Thu, 27 Apr 2017 11:49:55 +0200
Peter Otten <__peter__ at web.de> wrote:


> I'd like to bring to your attention the discard() method
> 
> >>> s = {1, 2, 3}
> >>> s.discard(int(v))
> >>> s
> {2, 3}
> 
> which allows you to avoid building the throwaway single-entry set.

Thank you Peter. I have been using the remove() method which, by the look of it, may do the same thing as discard(). I'll have a play and see.

-- 
Regards,
Phil

From phil_lor at bigpond.com  Fri Apr 28 21:15:43 2017
From: phil_lor at bigpond.com (Phil)
Date: Sat, 29 Apr 2017 11:15:43 +1000
Subject: [Tutor] Another set question
Message-ID: <20170429111543.637b450c@raspberrypi>

I'm trying to implement a conditional branch based on a variable type.
For example, if c is a character and s is a set with only one member.

c = "9"
s ={9}

if type(c) == a string:
	do this
else:
	do that

An alternative that I've attempted is to test if a set contains one member based on len(). However, I then cannot tell if len() is referring to a single character or a single set with one member. So I'm back to square one.

A for loop is indexing mixed lists of characters (one character per list) and lists that a set with one member. I'm only interested in the sets and want to ignore the character lists.

I have come up with a method that will probably work but it's become quite messy with multiple compare statements. Something simple and less prone to cause headaches would be better.
 
-- 
Regards,
Phil

From ben+python at benfinney.id.au  Fri Apr 28 22:01:19 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sat, 29 Apr 2017 12:01:19 +1000
Subject: [Tutor] Another set question
References: <20170429111543.637b450c@raspberrypi>
Message-ID: <854lx86kgg.fsf@benfinney.id.au>

Phil <phil_lor at bigpond.com> writes:

> I'm trying to implement a conditional branch based on a variable type.

This is often (not always) a mistake, in Python. So the question needs
to be asked: What makes you think that condition is a requirement?

In other words, why is the data such that you *need* to know whether it
is a set versus a string, before using it? Can the data be handled
differently such that the condition you describe isn't a prerequisite?

> For example, if c is a character and s is a set with only one member.

Note that ?a character? and ?an empty string? and ?three characters? are
all values that have the exact same type: the ?str? type.

Similarly, ?a set with only one member? and ?a set with two dozen
members? and ?an empty set? are all values that are of the same type:
the ?set? type.

So, I suspect you will need to explain better what larger problem you
are trying to solve, and re-consider whether the condition you're trying
to test is actually going to help that purpose.

-- 
 \         ?Pinky, are you pondering what I'm pondering?? ?I think so, |
  `\        Brain, but this time *you* put the trousers on the chimp.? |
_o__)                                           ?_Pinky and The Brain_ |
Ben Finney


From martin at linux-ip.net  Fri Apr 28 22:42:36 2017
From: martin at linux-ip.net (Martin A. Brown)
Date: Fri, 28 Apr 2017 19:42:36 -0700
Subject: [Tutor] Another set question
In-Reply-To: <854lx86kgg.fsf@benfinney.id.au>
References: <20170429111543.637b450c@raspberrypi>
 <854lx86kgg.fsf@benfinney.id.au>
Message-ID: <alpine.LSU.2.11.1704281908580.2663@qnttre.jbaqresebt.arg>


Hello and greetings Phil,

>> I'm trying to implement a conditional branch based on a variable type.
>
>This is often (not always) a mistake, in Python. So the question needs
>to be asked: What makes you think that condition is a requirement?
>
>So, I suspect you will need to explain better what larger problem you
>are trying to solve, and re-consider whether the condition you're trying
>to test is actually going to help that purpose.

I will echo what Ben has said.  As I thought about your question, I 
began to wonder more about what problem you were trying to solve 
than the question you are actually asking.

Here are some thoughts I can suggest.  We might be able to offer 
other suggestions if we know the problem you were tackling, 
although, of course, sometimes it is most fun/learning/challenging 
to discover these things for yourself.

Anyway, on to the thoughts:

  * Do you know about isinstance? [0] Be careful using this, as it 
    is easy to use it poorly.  Look up duck-typing [1] and see if 
    that helps in your solution.  The main point is to understand 
    what's possible with an object/instance not what type it is.

  * More basically, are you familiar with "in" keyword (reserved 
    word in Python)?  For any Python sequence, a list, tuple, set 
    and other such, you can test membership using "x in mysequence".
    Of course, it works on sequences, and strings are also sequences 
    (as you appear to have discovered), so this would require some 
    care.  See the docs for operations on sequences [2].  You might 
    be able to change your problem to using the "x in y" technique.

  * Finally, are you transforming your data before you operate on 
    it?  Based on your earlier question, I suspect you may not be 
    doing that.  One way to avoid headaches when you are operating 
    on data inside a program is to transform that data to the 
    expected datatypes as early as possible on input and then 
    transform that data as late as possible on output.

    Why do many programmers do this?  This means that inside the 
    program, you have some sort of contract about the datatypes on 
    which your program is operating.  There's no doubt about whether 
    a particular function is operating on an integer or a string.  
    For statically typed languages this is de rigeur.  For 
    dynamically typed languages like Python, you can elect not to do 
    this, but sometimes it will bite you, if you aren't careful. 
    Of course, you should take advantage of the dynamism, but 
    remember to consider either A) puttingthe data into an 
    internally canonical form before passing it around (my 
    preference) or writing your funtions / methods to deal with
    multiple datatypes.

>> For example, if c is a character and s is a set with only one member.
>
>Note that ?a character? and ?an empty string? and ?three characters? are
>all values that have the exact same type: the ?str? type.
>
>Similarly, ?a set with only one member? and ?a set with two dozen
>members? and ?an empty set? are all values that are of the same type:
>the ?set? type.

Simple example using "isinstance":

  # -- create a list of sets and one-character strings
  #
  l = [ set(("9")), "a", "b", "c", set(("q"))]
  
  # -- create a list with only the things that are of type set
  #
  q = [x for x in l if isinstance(x, set)]

  # Now, q = [{'9'}, {'q'}]

Example of using "in":

>In other words, why is the data such that you *need* to know whether it
>is a set versus a string, before using it? Can the data be handled
>differently such that the condition you describe isn't a prerequisite?

And, this is the key question.

Good luck!

-Martin

 [0] https://docs.python.org/3/library/functions.html#isinstance
 [1] http://www.voidspace.org.uk/python/articles/duck_typing.shtml
 [2] https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range

-- 
Martin A. Brown
http://linux-ip.net/

From phil_lor at bigpond.com  Sat Apr 29 00:09:39 2017
From: phil_lor at bigpond.com (Phil)
Date: Sat, 29 Apr 2017 14:09:39 +1000
Subject: [Tutor] Another set question
In-Reply-To: <alpine.LSU.2.11.1704281908580.2663@qnttre.jbaqresebt.arg>
References: <20170429111543.637b450c@raspberrypi>
 <854lx86kgg.fsf@benfinney.id.au>
 <alpine.LSU.2.11.1704281908580.2663@qnttre.jbaqresebt.arg>
Message-ID: <20170429140939.26883c38@raspberrypi>

On Fri, 28 Apr 2017 19:42:36 -0700
"Martin A. Brown" <martin at linux-ip.net> wrote:

> 
> Hello and greetings Phil,
> 
> >> I'm trying to implement a conditional branch based on a variable
> >> type.
> >
> >This is often (not always) a mistake, in Python. So the question
> >needs to be asked: What makes you think that condition is a
> >requirement?
> >
> >So, I suspect you will need to explain better what larger problem you
> >are trying to solve, and re-consider whether the condition you're
> >trying to test is actually going to help that purpose.

Thank you Ben and Martin for your detailed replies. I was debating whether or not to post my question at all because it looked vague, even to me.

This a simplified version of what I had in mind:

alist = [1,2,9,6]

alist[2] = set({4})

for i in range(4):
    if i is a set:
	do this

1, 2 and 6 are given numbers and the set containing 4 is what I want to operate on.

My alternative method that I mentioned in my previous question compares each alist[i] number to another list of given numbers. If alist[i] does not appear in the given number list then it must be a set. At this point of the program I'm only interested in sets that have only have one member. Sets with more than one member are dealt with later.

I'm nearly certain that this is the method that I should continue to pursue, unless someone can offer a cleverer solution.

-- 
Regards,
Phil

From ben+python at benfinney.id.au  Sat Apr 29 06:27:17 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sat, 29 Apr 2017 20:27:17 +1000
Subject: [Tutor] Another set question
References: <20170429111543.637b450c@raspberrypi>
 <854lx86kgg.fsf@benfinney.id.au>
 <alpine.LSU.2.11.1704281908580.2663@qnttre.jbaqresebt.arg>
 <20170429140939.26883c38@raspberrypi>
Message-ID: <85wpa35x16.fsf@benfinney.id.au>

Phil <phil_lor at bigpond.com> writes:

> Thank you Ben and Martin for your detailed replies. I was debating
> whether or not to post my question at all because it looked vague,
> even to me.

That's not the issue; the question was posed clearly enough. The problem
is that your purpose is opaque, and we have a strong suspicion your
approach is not well suited to the purpose.

> This a simplified version of what I had in mind:

Thank you for the example code. However the same issue remains:

Why is the data in such a state that you can't decide how to use it
until you know whether it is a set versus a string? Can the data be
handled differently? We'll need to know what you're trying to achieve,
to answer properly.

-- 
 \      ?Compulsory unification of opinion achieves only the unanimity |
  `\        of the graveyard.? ?Justice Roberts in 319 U.S. 624 (1943) |
_o__)                                                                  |
Ben Finney


From rafael.knuth at gmail.com  Sat Apr 29 13:13:50 2017
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Sat, 29 Apr 2017 19:13:50 +0200
Subject: [Tutor] Working with APIs - understanding the basics (Python 3.5)
Message-ID: <CAM-E2X6=U747hsfBoQbdttP0+nOy0_0c8HuekeAh5KGTuQOhxg@mail.gmail.com>

can anyone recommend good resources? I am primarily in search of
simple, clean code examples & practical usecases (Google APIs for
example). Thanks. Right now, I am learning at Codecademy,
Dataquest.io, Datacamp and from "Python Crash Course" by Eric
Matthews.

I am new to programming, Python is my first language.

From alan.gauld at yahoo.co.uk  Sat Apr 29 14:52:49 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 29 Apr 2017 19:52:49 +0100
Subject: [Tutor] Working with APIs - understanding the basics (Python
 3.5)
In-Reply-To: <CAM-E2X6=U747hsfBoQbdttP0+nOy0_0c8HuekeAh5KGTuQOhxg@mail.gmail.com>
References: <CAM-E2X6=U747hsfBoQbdttP0+nOy0_0c8HuekeAh5KGTuQOhxg@mail.gmail.com>
Message-ID: <oe2ndr$qlr$1@blaine.gmane.org>

On 29/04/17 18:13, Rafael Knuth wrote:
> can anyone recommend good resources? I am primarily in search of
> simple, clean code examples & practical usecases (Google APIs for
> example). 

An API is just a set of classes or functions.
The Python standard library is an API.

You already have lots of examples and documentation
for the standard library.

What exactly is it you are looking for?
If I describe, for example, the API to WxPython (for
building GUIs) that will probably not help you unless
you want to build a GUI.

Similarly if I describe Twisted's API (for writing
networking programs) that won't help unless you want to
write a network server or somesuch.

Is there a specific API you have in mind (you mention
Google - is that because you want to use it or just
because its one you've heard about?)? Or is it just
the concept of APIs?

If the latter stick with the standard library, or a
sub-set of it. For example the os package provides
an API into your operating system. Try exploring that.
Start with the os module documentation.

-- 
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 marc_eymard at hotmail.com  Sat Apr 29 14:26:28 2017
From: marc_eymard at hotmail.com (Marc Eymard)
Date: Sat, 29 Apr 2017 18:26:28 +0000
Subject: [Tutor] Thread Object integration with GPIO
Message-ID: <AM4P191MB0162C9B5CBF3604F71D146BB8B120@AM4P191MB0162.EURP191.PROD.OUTLOOK.COM>

Hello there,

I have hooked up an ultrasonic sensor to my Raspberry Pi-enabled robot 
in order to get continuous distance-to-obstacle reading.

The sensor is properly connected via GPIO and already reads the distance 
properly when running a simple script.

However, I need to integrate the sensor reading logic to an existing 
script provided by PiBorg called YetiBorg.py

The way I have decided to go about implementing the sensor reading is by 
creating a Thread object and update the distance attribute of this very 
same object from the run() function. The idea is to encapsulate the 
distance reading within the sensor object as much as possible by i. 
creating a sensor/thread object and by ii. avoiding global variables.

Attached the script I have come up with, which keeps returning multiple 
run time errors whenever I try to fix it.
I believe there are multiple issues, but at least it gives an idea of 
what I currently want to achieve and how.

Can a charitable soul advise whether my approach makes sense and whether 
I am using the right type of object for the task at hands?

I am looking for guidance and willing try completely different 
approach/objects if necessary.

Thanks in advance for sending me into the right direction.
Marc


From phil_lor at bigpond.com  Sat Apr 29 19:58:47 2017
From: phil_lor at bigpond.com (Phil)
Date: Sun, 30 Apr 2017 09:58:47 +1000
Subject: [Tutor] Another set question
In-Reply-To: <85wpa35x16.fsf@benfinney.id.au>
References: <20170429111543.637b450c@raspberrypi>
 <854lx86kgg.fsf@benfinney.id.au>
 <alpine.LSU.2.11.1704281908580.2663@qnttre.jbaqresebt.arg>
 <20170429140939.26883c38@raspberrypi>
 <85wpa35x16.fsf@benfinney.id.au>
Message-ID: <20170430095847.362a1967@raspberrypi>

On Sat, 29 Apr 2017 20:27:17 +1000
Ben Finney <ben+python at benfinney.id.au> wrote:

> Why is the data in such a state that you can't decide how to use it
> until you know whether it is a set versus a string? Can the data be
> handled differently? We'll need to know what you're trying to achieve,
> to answer properly.

Thank you Ben. A rethink of the problem during the 20 hours since I posted my most recent question has led to a solution.

I'm rewriting a C++ program that I wrote 15 years ago to solve sudoko puzzles. I'm having some difficulty with the translation in part because of my poorly documented code and because Python does some things differently. I've abandoned my original translation attempt and have started afresh which is probably a good idea. It took me months to solve come up with a working solution in C++ whereas I almost have a working solution in Python in a little over a week.

The strings are the given numbers while the sets are the likely candidates.

-- 
Regards,
Phil

From ben+python at benfinney.id.au  Sat Apr 29 20:26:43 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sun, 30 Apr 2017 10:26:43 +1000
Subject: [Tutor] Another set question
References: <20170429111543.637b450c@raspberrypi>
 <854lx86kgg.fsf@benfinney.id.au>
 <alpine.LSU.2.11.1704281908580.2663@qnttre.jbaqresebt.arg>
 <20170429140939.26883c38@raspberrypi> <85wpa35x16.fsf@benfinney.id.au>
 <20170430095847.362a1967@raspberrypi>
Message-ID: <85shkq68qk.fsf@benfinney.id.au>

Phil <phil_lor at bigpond.com> writes:

> It took me months to solve come up with a working solution in C++
> whereas I almost have a working solution in Python in a little over a
> week.

Welcome to Python, we're glad to hear of your success!

-- 
 \      ?[Entrenched media corporations will] maintain the status quo, |
  `\       or die trying. Either is better than actually WORKING for a |
_o__)                  living.? ?ringsnake.livejournal.com, 2007-11-12 |
Ben Finney


From robertvstepp at gmail.com  Sat Apr 29 21:45:47 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sat, 29 Apr 2017 20:45:47 -0500
Subject: [Tutor] Thread Object integration with GPIO
In-Reply-To: <AM4P191MB0162C9B5CBF3604F71D146BB8B120@AM4P191MB0162.EURP191.PROD.OUTLOOK.COM>
References: <AM4P191MB0162C9B5CBF3604F71D146BB8B120@AM4P191MB0162.EURP191.PROD.OUTLOOK.COM>
Message-ID: <CANDiX9JZakbR4ZKrmyPH07g63C+P1_KBwZmx_nHbg6S=F0YUPw@mail.gmail.com>

On Sat, Apr 29, 2017 at 1:26 PM, Marc Eymard <marc_eymard at hotmail.com> wrote:
> Hello there,

> Attached the script I have come up with, which keeps returning multiple
> run time errors whenever I try to fix it.
> I believe there are multiple issues, but at least it gives an idea of
> what I currently want to achieve and how.

This is a plain text only list.  This list does not accept
attachments.  Reduce your code to the minimum necessary to replicate
the problem and put it in the body of your email to Tutor.  Include a
copy and paste of the full error traceback.  Also helpful is what
version of Python you are using and your operating system.  Hopefully
someone here might be able to assist you with your issues.


-- 
boB

From steve at pearwood.info  Sun Apr 30 08:00:24 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 30 Apr 2017 22:00:24 +1000
Subject: [Tutor] Thread Object integration with GPIO
In-Reply-To: <AM4P191MB0162C9B5CBF3604F71D146BB8B120@AM4P191MB0162.EURP191.PROD.OUTLOOK.COM>
References: <AM4P191MB0162C9B5CBF3604F71D146BB8B120@AM4P191MB0162.EURP191.PROD.OUTLOOK.COM>
Message-ID: <20170430120022.GK22525@ando.pearwood.info>

On Sat, Apr 29, 2017 at 06:26:28PM +0000, Marc Eymard wrote:

> The way I have decided to go about implementing the sensor reading is by 
> creating a Thread object and update the distance attribute of this very 
> same object from the run() function. The idea is to encapsulate the 
> distance reading within the sensor object as much as possible by i. 
> creating a sensor/thread object and by ii. avoiding global variables.

That's not a bad approach, but I'd take it one step further: move all 
the logic into another object, and just have the thread call it. That 
lets you change your mind later, and replace threads with an external 
process, or async code, or whatever technology is best. It also allows 
you to add whatever smarts or features you need into the object 
collecting values, without the thread needing to care about it.

Something like this untested code:



from threading import Thread

class Collector(object):
    # Object to collect readings.

    def __init__(self):
        self.values = []

    def store(self, value):
        # If you need any data validation or other processing,
        # put it here.
        self.values.append(value)

    def run(self):
        print("Starting collecting...")
        while True:
            value = ... # collect the data somehow
            if value == -1:
                 # No more data?
                 break
            self.store(value)
        print("...finished collecting.")

    def report(self):
        print("I have %d values" % len(self.values))



Now, you can have your main function create a Collector, pass it to the 
thread, and process it as needed:

def main():
     c = Collector()
     t = Thread(target=c.run, name='my thread')
     t.start()
     t.join()
     c.report()



> Attached the script I have come up with

Alas, this mailing list doesn't accept attachments. You should reduce 
the script to the smallest amount of code you can, and re-post it, 
together with the entire stack trace of the errors.



-- 
Steve

From marc_eymard at hotmail.com  Sun Apr 30 05:14:12 2017
From: marc_eymard at hotmail.com (Marc Eymard)
Date: Sun, 30 Apr 2017 09:14:12 +0000
Subject: [Tutor] Thread Object integration with GPIO
In-Reply-To: <76b3c6ec-806f-b7e2-e357-a79f9a12bfc0@hotmail.com>
References: <76b3c6ec-806f-b7e2-e357-a79f9a12bfc0@hotmail.com>
Message-ID: <AM4P191MB01629D98BDB8214E4663B5558B150@AM4P191MB0162.EURP191.PROD.OUTLOOK.COM>

Hello there,

I have hooked up an ultrasonic sensor to my Raspberry Pi-enabled robot
in order to get continuous distance-to-obstacle reading.

The sensor is properly connected via GPIO and already reads the distance
properly when running a simple script.

However, I need to integrate the sensor reading logic to an existing
script provided by PiBorg called YetiBorg.py

The way I have decided to go about implementing the sensor reading is by
creating a Thread object and update the distance attribute of this very
same object from the run() function. The idea is to encapsulate the
distance reading within the sensor object as much as possible by i.
creating a sensor/thread object and by ii. avoiding global variables.

Below the script I have come up along with the error print.
I believe there are multiple issues, but at least it gives an idea of
what I currently want to achieve and how.

Can a charitable soul advise whether my approach makes sense and whether
I am using the right type of object for the task at hands?

I am looking for guidance and willing try completely different
approach/objects if necessary.

Thanks in advance for sending me into the right direction.
Marc

----Python Shell----

2.7.9

----OS-----

Raspian Pixel on Raspberry Pi Zero



---traceback----



Traceback (most
recent call last):

File
"/home/pi/Desktop/distance sensor class object.py", line
57, in <module>


SensorA = Sensor(interval=1, gpio_trig=23, gpio_echo=24)

File"/home/pi/Desktop/distance sensor class object.py", line
23, in __init__self.start()


RuntimeError:
thread.__init__() not called





------sensor.py-----


import threading
import RPi.GPIO as GPIO
import time

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

class Sensor(threading.Thread):

        """ultrasonic sensor continous distance reading at given interval in seconds"""

    def __init__(self,interval, gpio_trig, gpio_echo):
        self.inter = interval
        self.trig = gpio_trig
        self.echo = gpio_echo

        #set GPIO pins direction (IN / OUT)
        GPIO.setup(gpio_trig, GPIO.OUT)
        GPIO.setup(gpio_echo, GPIO.IN)

        self.dist = 0
        self.terminated = False
        self.start()

    def run(self):
        while not self.terminated:
            # set Trigger to HIGH
            GPIO.output(gpio_trig, True)

            # set Trigger to LOW after 0.01ms
            time.sleep(0.00001)
            GPIO.output(gpio_trig, False)

            StartTime = time.time()
            StopTime = time.time()

            # save StartTime
            while GPIO.input(gpio_echo) == 0:
                StartTime = time.time()

            # save time of arrival
            while GPIO.input(gpio_echo) == 1:
                StopTime = time.time()

            # time difference between start and arrival
            TimeElapsed = StopTime - StartTime
            # multiply by sonic speed (34300 cm/s)
            # and divide by 2, because there and back
            self.dist = (TimeElapsed * 34300) / 2

            time.sleep(self.inter)

    def get_dist(self):
        return self.dist

#Sensor object "instanciated" with GPIO programmable pins 23 and 24
SensorA = Sensor(interval=1, gpio_trig=23, gpio_echo=24)

try:
    while True:
        print("Measured Distance = %.1f cm" % SensorA.get_dist())
except KeyboardInterrupt:
    GPIO.cleanup()
    SensorA.terminated = True




From s.molnar at sbcglobal.net  Sun Apr 30 06:09:12 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Sun, 30 Apr 2017 06:09:12 -0400
Subject: [Tutor] Python 3.6 Extract Floating Point Data from a Text File
Message-ID: <5905B7C8.5090800@sbcglobal.net>


I am using the Spyder v-3.1.2 IDE and porting a FORTRAN program that I 
wrote about 20 years ago to Python  Unfortunately, I am very much a 
novice in Python .

I would have managed to extract input data from another calculation (not 
a Python program) into the following text file.

LOEWDIN ATOMIC CHARGES
  ----------------------
     0 C :   -0.780631
     1 H :    0.114577
     2 Br:    0.309802
     3 Cl:    0.357316
     4 F :   -0.001065

What I need to do is extract the floating point numbers into a Python file

What I need to do is extract the floating point numbers into a Python file.

Googling the problem has not resulted on any insight as to the solution, 
and any help will be much appreciated.

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 alan.gauld at yahoo.co.uk  Sun Apr 30 10:43:02 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 30 Apr 2017 15:43:02 +0100
Subject: [Tutor] How to display radiobutton window with no buttons
 selected?
In-Reply-To: <CANDiX9JqEeRw8dGSF-YEyTNYYrcr6ofMKx_jxF9Lg7hR+WxfEg@mail.gmail.com>
References: <CANDiX9Jk2-dHR=iY1L-tTzAxPENEPYp2_fO5cnWokorpBcYL1g@mail.gmail.com>
 <odms7t$7so$1@blaine.gmane.org>
 <CANDiX9JqEeRw8dGSF-YEyTNYYrcr6ofMKx_jxF9Lg7hR+WxfEg@mail.gmail.com>
Message-ID: <oe4t5f$ijr$1@blaine.gmane.org>

On 25/04/17 12:39, boB Stepp wrote:

>>> I wish the displayed window to initially display with no button
>>> selected.  What am I missing here?
>>
>> It looks like the empty string is special. On my (linux) system all buttons
>> appear grayed (while a selected button would be black). Any other string
>> should give the desired result, probably because every button "thinks" that
>> another button is currently selected.

There is a simple solution.
Use a hidden butrtpon to represent no selection. Here is an example:


###################
from tkinter import *

top = Tk()

rbVar = IntVar()

rb0 = Radiobutton(top, text="hidden", variable=rbVar, value=0)
rb1 = Radiobutton(top, text='one', variable=rbVar, value=1)
rb1.pack()
rb2 = Radiobutton(top, text='two', variable=rbVar, value=2)
rb2.pack()
rb3 = Radiobutton(top, text='three', variable=rbVar, value=3)
rb3.pack()

Button(top,text='reset', command=lambda : rbVar.set(0)).pack()

top.mainloop()

##################

I was going to post this last week but typing it into a
tablet with no way to test it was too much so here is
a belated option...


-- 
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  Sun Apr 30 10:58:13 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 30 Apr 2017 15:58:13 +0100
Subject: [Tutor] Another set question
In-Reply-To: <20170430095847.362a1967@raspberrypi>
References: <20170429111543.637b450c@raspberrypi>
 <854lx86kgg.fsf@benfinney.id.au>
 <alpine.LSU.2.11.1704281908580.2663@qnttre.jbaqresebt.arg>
 <20170429140939.26883c38@raspberrypi> <85wpa35x16.fsf@benfinney.id.au>
 <20170430095847.362a1967@raspberrypi>
Message-ID: <oe4u1v$gsv$1@blaine.gmane.org>

On 30/04/17 00:58, Phil wrote:

> Thank you Ben. A rethink of the problem during the 20 hours since 
> I posted my most recent question has led to a solution.

You don;t say what so i'll go with what you say below...

> The strings are the given numbers while the sets are 
> the likely candidates.

I would probably combine both such that for each cell you
have a tuple containing the given number and the set of
candidates. In some cases the number may be a sentinel
(such as -1) to indicate no number yet, and for some
cells the set will be empty.

But by always having both available your data handling
becomes consistent, you always know that you get a tuple
and you know can easily test the sentinel to see3 if
the value is set or not. And you never need to
test types.

Everything should become much more consistent. (The storage
overhead is minimal for a suduko game - it might be different
if you were doing something with a massive grid...)

-- 
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  Sun Apr 30 11:09:06 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 30 Apr 2017 16:09:06 +0100
Subject: [Tutor] Tkinter layout question
In-Reply-To: <20170426165628.665234f4@raspberrypi>
References: <20170420084842.2954c647@raspberrypi>
 <od9rd8$euo$1@blaine.gmane.org> <20170420193312.320bf6bb@raspberrypi>
 <odaacl$a66$1@blaine.gmane.org> <odhlo2$b6b$1@blaine.gmane.org>
 <20170424092455.672dc446@raspberrypi> <20170424105047.14bf00ae@raspberrypi>
 <odli42$eet$1@blaine.gmane.org> <20170425084000.52ffc3c8@raspberrypi>
 <odoifj$gb9$1@blaine.gmane.org> <20170426165628.665234f4@raspberrypi>
Message-ID: <oe4umc$qgv$1@blaine.gmane.org>

On 26/04/17 07:56, Phil wrote:

>> Your messages come into the moderation queue, I'm
> 
> Thanks Alan, maybe the reason ...is because I'm 
> on the bounces list.

I don;t know what bounces list you mean but it looks
like your messages are going through directly now,
I don't know what changed...

Post a test to see. Messages typically arrive within
5-15 minutes of posting if not moderated.


-- 
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 Apr 30 11:56:59 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 30 Apr 2017 10:56:59 -0500
Subject: [Tutor] Python 3.6 Extract Floating Point Data from a Text File
In-Reply-To: <5905B7C8.5090800@sbcglobal.net>
References: <5905B7C8.5090800@sbcglobal.net>
Message-ID: <CANDiX9KSKNOf84YNoqmazXN3MQfhiDmFZLGh3YWPNErk5w+4Rw@mail.gmail.com>

Hello Stephen!

On Sun, Apr 30, 2017 at 5:09 AM, Stephen P. Molnar
<s.molnar at sbcglobal.net> wrote:
>
> I am using the Spyder v-3.1.2 IDE and porting a FORTRAN program that I wrote
> about 20 years ago to Python  Unfortunately, I am very much a novice in
> Python .
>
> I would have managed to extract input data from another calculation (not a
> Python program) into the following text file.
>
> LOEWDIN ATOMIC CHARGES
>  ----------------------
>     0 C :   -0.780631
>     1 H :    0.114577
>     2 Br:    0.309802
>     3 Cl:    0.357316
>     4 F :   -0.001065
>
> What I need to do is extract the floating point numbers into a Python file
>
> What I need to do is extract the floating point numbers into a Python file.

It is not clear to me what you mean by "Python file" (Twice over!
~(:>)) ).  But I would think a possible outline for your problem would
be:

1)  Open your data file for reading and open another (empty) file for appending.

2)  Loop over each line of your data file, ignoring the first two lines.

3)  Process one line at a time.  Use the split() string method to
split each line on the colon.  Strip all white space from the part you
are interested in.  Append the desired part to your write file.

4)  Close the files, or, better yet, setup the above with the "with"
context manager, which will handle the file closing automatically.

If you are not familiar with file I/O in Python 3, the tutorial has a
section on it:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

It is possible your actual problem is better addressed by the csv
module in the standard library.  The docs for this are at:

https://docs.python.org/3/library/csv.html

For instance, instead of using a comma as the field separator, you
could use a colon.

As to how you want to write the extracted data, that depends on what
you really want.  The above approach suffices for writing to another
text file or  to a binary file.  If you need something different then
you need to let us know what direction you need to go.

Finally, when you need to actually use the extracted string resembling
a float, you will have to convert that string using the float()
function.

Hope that something above is helpful!

Cheers!

-- 
boB

From steve at pearwood.info  Sun Apr 30 14:02:40 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 1 May 2017 04:02:40 +1000
Subject: [Tutor] Python 3.6 Extract Floating Point Data from a Text File
In-Reply-To: <5905B7C8.5090800@sbcglobal.net>
References: <5905B7C8.5090800@sbcglobal.net>
Message-ID: <20170430180240.GL22525@ando.pearwood.info>

On Sun, Apr 30, 2017 at 06:09:12AM -0400, Stephen P. Molnar wrote:
[...]
> I would have managed to extract input data from another calculation (not 
> a Python program) into the following text file.
> 
> LOEWDIN ATOMIC CHARGES
>  ----------------------
>     0 C :   -0.780631
>     1 H :    0.114577
>     2 Br:    0.309802
>     3 Cl:    0.357316
>     4 F :   -0.001065
> 
> What I need to do is extract the floating point numbers into a Python file

I don't quite understand your question, but I'll take a guess. I'm going 
to assume you have a TEXT file containing literally this text:

# ---- cut here ----

LOEWDIN ATOMIC CHARGES
----------------------
   0 C :   -0.780631
   1 H :    0.114577
   2 Br:    0.309802
   3 Cl:    0.357316
   4 F :   -0.001065

# ---- cut here ----


and you want to extract the atomic symbols (C, H, Br, Cl, F) and 
charges as floats. For the sake of the exercise, I'll extract them into 
a dictionary {'C': -0.780631, 'H': 0.114577, ... } then print them.

Let me start by preparing the text file. Of course I could just use a 
text editor, but let's do it with Python:


data = """LOEWDIN ATOMIC CHARGES
----------------------
   0 C :   -0.780631
   1 H :    0.114577
   2 Br:    0.309802
   3 Cl:    0.357316
   4 F :   -0.001065
"""

filename = 'datafile.txt'
with open(filename, 'w') as f:
    f.write(data)


(Of course, in real life, it is silly to put your text into Python just 
to write it out to a file so you can read it back in. But as a 
programming exercise, its fine.)

Now let's re-read the file, processing each line, and extract the data 
we want.

atomic_charges = {}
filename = 'datafile.txt'
with open(filename, 'r') as f:
    # Skip lines until we reach a line made of nothing but ---
    for line in f:
        line = line.strip()  # ignore leading and trailing whitespace
        if set(line) == set('-'):
            break
    # Continue reading lines from where we last got to.
    for line in f:
        line = line.strip()
        if line == '': 
            # Skip blank lines.
            continue
        # We expect lines to look like:
        #   1 C :   0.12345
        # where there may or may not be a space between the 
        # letter and the colon. That makes it tricky to process,
        # so let's force there to always be at least one space.
        line = line.replace(':', ' :')
        # Split on spaces.
        try:
            number, symbol, colon, number = line.split()
        except ValueError as err:
            print("failed to process line:", line)
            print(err)
            continue  # skip to the next line
        assert colon == ':', 'expected a colon but found something else'
        try:
            number = float(number)
        except ValueError:
            # We expected a numeric string like -0.234 or 0.123, but got
            # something else. We could skip this line, or replace it
            # with an out-of-bounds value. I'm going to use an IEEE-754
            # "Not A Number" value as the out-of-bounds value.
            number = float("NaN")
        atomic_charges[symbol] = number

# Finished! Let's see what we have:
for sym in sorted(atomic_charges):
    print(sym, atomic_charges[sym])





There may be more efficient ways to process the lines, for example by 
using a regular expression. But its late, and I'm too tired to go 
messing about with regular expressions now. Perhaps somebody else will 
suggest one.



-- 
Steve

From alan.gauld at yahoo.co.uk  Sun Apr 30 14:47:14 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 30 Apr 2017 19:47:14 +0100
Subject: [Tutor] Fwd: Re: Python 3.6 Extract Floating Point Data from a Text
 File
In-Reply-To: <44dafee1-1d94-586a-b18b-ac48999d47ee@yahoo.co.uk>
References: <44dafee1-1d94-586a-b18b-ac48999d47ee@yahoo.co.uk>
Message-ID: <16087630-63f4-d0ed-e918-71c00aa99d0c@yahoo.co.uk>

How, embarrassing,  I forgot to CC the list! :-)

On 30/04/17 11:09, Stephen P. Molnar wrote:

> I would have managed to extract input data from another calculation (not 
> a Python program) into the following text file.
> 
> LOEWDIN ATOMIC CHARGES
>   ----------------------
>      0 C :   -0.780631
>      1 H :    0.114577
> 
> What I need to do is extract the floating point numbers into a Python file

>From previous posts we know you can extract a line of text so really you
are asking how to extract a floating point number from a string.

>>> s = '     0 C :   -0.780631'
>>> fps = s.split()[-1]   # get the last item from the split string
>>> val = float(fps)
>>> print( val )

Or in one line:

val = float( line.split()[-1] )

Obviously if the number were not at the end you would have to use
the appropriate index instead of -1...

-- 
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 s.molnar at sbcglobal.net  Sun Apr 30 15:56:04 2017
From: s.molnar at sbcglobal.net (Stephen P. Molnar)
Date: Sun, 30 Apr 2017 15:56:04 -0400
Subject: [Tutor] Python 3.6 Extract Floating Point Data from a Text File
In-Reply-To: <20170430180240.GL22525@ando.pearwood.info>
References: <5905B7C8.5090800@sbcglobal.net>
 <20170430180240.GL22525@ando.pearwood.info>
Message-ID: <59064154.2000705@sbcglobal.net>

On 04/30/2017 02:02 PM, Steven D'Aprano wrote:
> On Sun, Apr 30, 2017 at 06:09:12AM -0400, Stephen P. Molnar wrote:
> [...]
>> I would have managed to extract input data from another calculation (not
>> a Python program) into the following text file.
>>
>> LOEWDIN ATOMIC CHARGES
>>   ----------------------
>>      0 C :   -0.780631
>>      1 H :    0.114577
>>      2 Br:    0.309802
>>      3 Cl:    0.357316
>>      4 F :   -0.001065
>>
>> What I need to do is extract the floating point numbers into a Python file
>
> I don't quite understand your question, but I'll take a guess. I'm going
> to assume you have a TEXT file containing literally this text:
>
> # ---- cut here ----
>
> LOEWDIN ATOMIC CHARGES
> ----------------------
>     0 C :   -0.780631
>     1 H :    0.114577
>     2 Br:    0.309802
>     3 Cl:    0.357316
>     4 F :   -0.001065
>
> # ---- cut here ----
>
>
> and you want to extract the atomic symbols (C, H, Br, Cl, F) and
> charges as floats. For the sake of the exercise, I'll extract them into
> a dictionary {'C': -0.780631, 'H': 0.114577, ... } then print them.
>
> Let me start by preparing the text file. Of course I could just use a
> text editor, but let's do it with Python:
>
>
> data = """LOEWDIN ATOMIC CHARGES
> ----------------------
>     0 C :   -0.780631
>     1 H :    0.114577
>     2 Br:    0.309802
>     3 Cl:    0.357316
>     4 F :   -0.001065
> """
>
> filename = 'datafile.txt'
> with open(filename, 'w') as f:
>      f.write(data)
>
>
> (Of course, in real life, it is silly to put your text into Python just
> to write it out to a file so you can read it back in. But as a
> programming exercise, its fine.)
>
> Now let's re-read the file, processing each line, and extract the data
> we want.
>
> atomic_charges = {}
> filename = 'datafile.txt'
> with open(filename, 'r') as f:
>      # Skip lines until we reach a line made of nothing but ---
>      for line in f:
>          line = line.strip()  # ignore leading and trailing whitespace
>          if set(line) == set('-'):
>              break
>      # Continue reading lines from where we last got to.
>      for line in f:
>          line = line.strip()
>          if line == '':
>              # Skip blank lines.
>              continue
>          # We expect lines to look like:
>          #   1 C :   0.12345
>          # where there may or may not be a space between the
>          # letter and the colon. That makes it tricky to process,
>          # so let's force there to always be at least one space.
>          line = line.replace(':', ' :')
>          # Split on spaces.
>          try:
>              number, symbol, colon, number = line.split()
>          except ValueError as err:
>              print("failed to process line:", line)
>              print(err)
>              continue  # skip to the next line
>          assert colon == ':', 'expected a colon but found something else'
>          try:
>              number = float(number)
>          except ValueError:
>              # We expected a numeric string like -0.234 or 0.123, but got
>              # something else. We could skip this line, or replace it
>              # with an out-of-bounds value. I'm going to use an IEEE-754
>              # "Not A Number" value as the out-of-bounds value.
>              number = float("NaN")
>          atomic_charges[symbol] = number
>
> # Finished! Let's see what we have:
> for sym in sorted(atomic_charges):
>      print(sym, atomic_charges[sym])
>
>
>
>
>
> There may be more efficient ways to process the lines, for example by
> using a regular expression. But its late, and I'm too tired to go
> messing about with regular expressions now. Perhaps somebody else will
> suggest one.
>
>
>
Steve

Thanks for your reply to my, unfortunately imprecisely worded, question.

Here are the results of applying you code to my data:

Br 0.309802
C -0.780631
Cl 0.357316
F -0.001065
H 0.114577

I should have mentioned that I already have the file, it's part if the 
output from the Orca Quantum Chemistry Program.

As soon as I understand teh code I'm going to have to get rid of the 
atomic symbols and get the charges in the same order as they are in the 
original LOEWDIN ATOMIC CHARGES file.  The Molecular Transform suite of 
programs depends on the distances between pairs of bonded atoms, hence 
the order is important.

Again, many thanks for your help.

Regards,

	Steve

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1