Re: [Tutor] Fwd: Re: HELP PLEASE

2019-08-12 Thread Alan Gauld via Tutor
On 12/08/2019 19:35, Alan Gauld via Tutor wrote:

> To save some typing convert the?? int conversion loop into a function:
> 
> 
> def?? to_ints(strings):
> ?? num_copy = []
> ?? for num in nums:
>  num_copy.append(float(num))
> 
> ?? return num_copy
#

No idea where all the ? came from, however I made a bad error
in that code...

It should read:

def to_ints(strings):
num_copy = []
for num in strings:   # strings not nums!
num_copy.append(float(num))
return num_copy

Apologies.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: HELP PLEASE

2019-08-12 Thread Alan Gauld via Tutor
Forwarding to tutorblist for info...



 Forwarded Message 
Subject:Re: [Tutor] HELP PLEASE
Date:   Mon, 12 Aug 2019 19:34:48 +0100
From:   Alan Gauld 
Reply-To:   alan.ga...@yahoo.co.uk
To: Marissa Russo 



On 12/08/2019 19:17, Marissa Russo wrote:
> I fixed some things up???


OK, But please use ReplyAll when responding to list mails otherwise
it just comes to me (or whoever posted) instead of the whole list.
(And I might be busy. at the time..)

> import math
>
> def get_numbers():
> print("This program will compute the mean and standard deviation")
> file1 = input("Please enter the first filename: ")
> file2 = input("Please enter the second filename: ")
> x = open(file1, "r")
> y = open(file2, "r")
> nums = x.readlines()
> nums2 = y.readlines()
>
> num_copy = []
> for num in nums:
> num_copy.append(float(num))
> nums = num_copy
>
> return nums

You are only returning one list of numbers. you need to convert nums2 as
well and then return both.


To save some typing convert the?? int conversion loop into a function:


def?? to_ints(strings):
?? num_copy = []
?? for num in nums:
 num_copy.append(float(num))

?? return num_copy

then call that on both list of strings.


 return to_ints(nums), to_ints(nums2)


> def mean():
> _sum = 0
> return(sum(nums)/len(nums))

Notice you don't pass any values to mean so you are relying on
the function seeing the values of nums outside the function
somewhere. It is beter where you passs in the values as you did originally:

def mean(numbers):




> def main():
> data = get_numbers()
> m = mean(data[0])
> m2 = mean2(data[1])

You call mean2() but don't have a mean2() function anymore.

You only need mean() so call it both times but with different input data.



> print("The mean of the first file is: ", m)
> print("The mean of the second file is: ", m2)
> main()
>
> This is now the output error:
> Traceback (most recent call last):
> File "/Applications/Python 3.7/exercises .py", line 34, in 
> main()
> File "/Applications/Python 3.7/exercises .py", line 30, in main
> m = mean(data[0])
> TypeError: mean() takes 0 positional arguments but 1 was given


See the comment above.

You removed the input parameter to the mean() function.

But then you call it as if it was still there. You must be consistent
between your function definitions and function calls..


You need to start thinking like the interpreter as you walk through the
code.
Think about what it knows at any given point and how the various functions
communicate?? - usually by storing intermediate results in variables. (Many
find it convenient to jot down the variables and their values as they walk
through the code, updating the values as they go). So check what those
variables contain - using print statements to debug it if necessary.


-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: RE: pointers or references to variables or sub-sets of variables query.

2019-07-15 Thread Alan Gauld via Tutor
Forwarding to list



 Forwarded Message 
Subject:RE: [Tutor] pointers or references to variables or sub-sets of
variables query.
Date:   Mon, 15 Jul 2019 17:13:23 +1000
From:   mhysnm1...@gmail.com
To: 'Alan Gauld' 



All,

Sorry for the late response. I have moved my program to SQLite. AS I
found I was going down the rabbit hole of wasting time. As allan said,
the select statement and other SQL statements are far easier to work
with then writing the code yourself. What I did I learn a lot and
started my road on OOPS.

The first program I programmed on was an Apple IIE using Applesoft
basic. Tried to learn assembly 6802 myself. But never got there. In the
90's I learnt C Clipper 68 and Turbo Pascal. Never became very strong
with these languages as my roles were never programming focused. Late
90's, early 2000 forget, I learnt some basic Visual Basic 6. Again,
didn't do much with it. I learnt the basic of PERL or enough to get by.

I haven't really touched programming for years and there is a lot I have
forgotten. Never had the need to do tree's, link-lists or any complex
data structures. This time, I am trying to learn Python beyond what I
used to know.

I have used just about every type of PC since the early 80's. Even used
DEC VAX, IBM 3270's as well. Yes, been around for a while now. 







-Original Message-
From: Tutor  On Behalf Of
Alan Gauld via Tutor
Sent: Monday, 8 July 2019 8:55 AM
To: tutor@python.org
Subject: Re: [Tutor] pointers or references to variables or sub-sets of
variables query.

On 07/07/2019 20:54, David L Neil wrote:

> (However, some of us grew-up at a time when RAM was expensive and even
> in our relaxed state, such 'costs' still impinge on our consciousness -

Indeed, my first computer was at the local university and had 64KB.

My second computer was a Sinclair ZX81 (Timex in the USA?) with 16K

My third, a CP/M machine with 64K and 256K RAM disk and dual floppies -
such luxury! :-)

So I agree, it is hard to get out of that mode of thinking. But today
the minimum RAM is typically 4GB or more. My desktop boxes all have 16GB
and even my ancient Netbook has 4G.
My 20 year old iBook has 640M and even that is enough to run Python with
many thousands of data objects instantiated.

> particularly temporary, DB tables into MySQL's MEMORY storage (and
> with almost zero code-change/risk)!

Yes, I use SQLite's MEMORY facility reguilarly. Not for managing high
volumes but where I need flexible search capability.
A SQL SELECT statement is much more flexible and faster than any Python
search I could cobble together.

> (appreciating that I have no difficulty moving from (Python)
> procedural programming to (SQL) declarative, but many of our
> colleagues hate such, and with a passion)

Yes, I've never quite understood why some programmers are reluctant to
use SQL. For complex structured data it is by far the simplest approach
and usually very efficient, especially with big volumes. But simple
searches on small datasets are easier (or as easy) in native Python.

--
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Unexpected result when running flask application.

2019-06-28 Thread Albert-Jan Roskam
Ooops, forgot to 'reply all'
-- Forwarded message --
From: Albert-Jan Roskam 
Date: 28 Jun 2019 21:31
Subject: Re: [Tutor] Unexpected result when running flask application.
To: Cameron Simpson 
Cc:



On 20 Jun 2019 00:56, Cameron Simpson  wrote:

On 19Jun2019 09:54, Alan Gauld  wrote:
>On 19/06/2019 05:18, Cravan wrote:
>> I am experiencing an unexpected result when I try to
>> run my flask application.
>> The movie.html page prints out nothing except those in the . This 
>> appears on my webpage:
>
>Note that the mail server does not allow (for security reasons)
>binary attachments so we lost your image.

Cravan, you might find it useful to "View Source" of that page in your
browser.

You can also use command line tools like "curl" or "wget" to directly
fetch the page content.

>However, your html files are not in HTML.
>I'm not a Flask expert but every time I've used Flask the
>html pages have been real HTML. Yours appear to be in some
>strange pseudo markup language.

It is very common in Flask to write HTML pages using Jinja templates,
which is what his examples look like.

Of course this adds more complexity, if he forgets to use Jinja to
render the content to HTML before returning it.

>If this is something unique to Flask then I suspect you will
>need to ask on a Flask support page or list. It doesn't seem
>to be a Python language related issue at this point.

==》 I haven't seen the templates, but your view function should probably retun 
flas.render_template('some.html', **kwargs), where kwargs will be e.g. your 
database values that are going to be displayed/{{interpolated}}.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Hii

2019-06-21 Thread Steven D'Aprano
On Fri, Jun 21, 2019 at 05:18:02PM -0500, Antonio Arizpe wrote:

> i only need this to function on windows 7 and 10, 32 and 64 bits
> i dont need any specificity to the counter other than the numeric sum of
> clicks pressed on the local machine.
> as far as this idea goes its very fair to make it as simple as possible.
> no VMs, single user, no key logging other than just a number at the end of
> the day.

https://www.geeksforgeeks.org/design-a-keylogger-in-python/

which was the first result here:

https://duckduckgo.com/?q=python+key+logger

Here's another one:

http://dalelane.co.uk/blog/?p=1760

which I found here:

https://www.google.com/search?q=python+count+keystrokes


-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Hii

2019-06-21 Thread Antonio Arizpe
if it cannot escape the simplicity of logging the keyboard as a individual
mechanical entity i can understand that better now because you are right it
all comes down to the OS or the driver handling to even be able to begin
the register of a device.

but i am more than willing to be as basic implementation as i need to be

i only need this to function on windows 7 and 10, 32 and 64 bits
i dont need any specificity to the counter other than the numeric sum of
clicks pressed on the local machine.
as far as this idea goes its very fair to make it as simple as possible.
no VMs, single user, no key logging other than just a number at the end of
the day.

i would just really appreciate it if before shutting down i can open a text
file and it says

2552




On Fri, Jun 21, 2019 at 5:09 PM Alan Gauld via Tutor 
wrote:

> On 21/06/2019 14:59, Antonio Arizpe wrote:
>
> > i just need help with a script thats registers keystrikes and adds up all
> > the times you've struck a key and gives a number of the total amount of
> > times the keyboard was struck. nothing specific about characters. just
> how
> > many times it was struck in a real number.
>
> If you only wanted to do this for your own application it would be
> relatively simple but since it seems you want to do it for the
> computer as a whole that raises a whole extra level of complexity.
>
> Some issues to consider:
>
> 1) If this is not just installed on your own personal computer it could
> be illegal - breach of personal privacy legislation in many countries
> prohibits key logging.
>
> 2) Do you care about users logging in remotely? Do you need to just log
> the current user logged in for the current GUI session or do you also
> want to record activity by other remote hosts logging in?
>
> 3) What about virtual machines running on the computer? Do you want to
> capture keystrokes within those VMs? That might be tricky as it may not
> show up in the native OS. It may even depend on the VM the user is running.
>
> 4) Do you care about which user is logged in or do you want to record
> keystrokes for every user of the computer?
>
> 5) Is it only counting for a single session or  for multiple sessions?
> This is more of an application design question that keylogging per se...
>
> Leaving those issues aside and looking only at the keylogging aspects.
> Your best bet is to find a third party module that does it for you.
> Failing that you will need to use the OS facilities which is never a
> trivial exercise. It is also the kind of low level feature that can
> change between OS versions (especially between 32bit and 64bit versions)
>
> If you plan to use it on multiple OS then the technique will likely
> differ between OS - MacOS and Linux may be similar but windows will
> be different.
>
> Let's assume the simplest case where you only want this for personal use
> on a computer where you are the only user and don't run any other OS
> either dual boot or in a VM. in that case you could write a Python
> application that does keylogging and put it in your startup group.
> How you notify it to stop recording before the computer shuts down is
> another issue and how it records/displays its results needs thought too.
>
> On Windows you might need to use ctypes to access the raw Win32 API or
> the PyWwin32 Python package may include functions that will do the job
> for you.
>
> HTH
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Hii

2019-06-21 Thread Alan Gauld via Tutor
On 21/06/2019 14:59, Antonio Arizpe wrote:

> i just need help with a script thats registers keystrikes and adds up all
> the times you've struck a key and gives a number of the total amount of
> times the keyboard was struck. nothing specific about characters. just how
> many times it was struck in a real number.

If you only wanted to do this for your own application it would be
relatively simple but since it seems you want to do it for the
computer as a whole that raises a whole extra level of complexity.

Some issues to consider:

1) If this is not just installed on your own personal computer it could
be illegal - breach of personal privacy legislation in many countries
prohibits key logging.

2) Do you care about users logging in remotely? Do you need to just log
the current user logged in for the current GUI session or do you also
want to record activity by other remote hosts logging in?

3) What about virtual machines running on the computer? Do you want to
capture keystrokes within those VMs? That might be tricky as it may not
show up in the native OS. It may even depend on the VM the user is running.

4) Do you care about which user is logged in or do you want to record
keystrokes for every user of the computer?

5) Is it only counting for a single session or  for multiple sessions?
This is more of an application design question that keylogging per se...

Leaving those issues aside and looking only at the keylogging aspects.
Your best bet is to find a third party module that does it for you.
Failing that you will need to use the OS facilities which is never a
trivial exercise. It is also the kind of low level feature that can
change between OS versions (especially between 32bit and 64bit versions)

If you plan to use it on multiple OS then the technique will likely
differ between OS - MacOS and Linux may be similar but windows will
be different.

Let's assume the simplest case where you only want this for personal use
on a computer where you are the only user and don't run any other OS
either dual boot or in a VM. in that case you could write a Python
application that does keylogging and put it in your startup group.
How you notify it to stop recording before the computer shuts down is
another issue and how it records/displays its results needs thought too.

On Windows you might need to use ctypes to access the raw Win32 API or
the PyWwin32 Python package may include functions that will do the job
for you.

HTH

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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Hii

2019-06-21 Thread Antonio Arizpe
  Hey ive looked everywhere and i would really appreciate the guidance
i know its not too complicated by google search results dodge my real
question


i just need help with a script thats registers keystrikes and adds up all
the times youve struck a key and gives a number of the total amount of
times the keyboard was struck. nothing specific about characters. just how
many times it was struck in a real number.

it is for windows 7 64 bits but i will be targeting windows 7 and 10 32 and
64 bits
it does not mean to be application specific.

just a +1 rule every time the keyboard is pressed so i can run it get a
real number at the end of the day

im just resending this because i recieved a updated mail to please select
respond all when responding to these emails which i had not been

On Thu, Jun 20, 2019 at 4:59 PM Antonio Arizpe  wrote:

>
>
> On Thu, Jun 20, 2019 at 12:36 PM Alan Gauld via Tutor 
> wrote:
>
>> Forwarding to list.
>> Please use Reply-All or Reply-List when responding to list emails.
>>
>>
>>
>>  Forwarded Message 
>> Subject:Re: [Tutor] Hii
>> Date:   Thu, 20 Jun 2019 08:50:31 -0500
>> From:   Antonio Arizpe 
>> To: Alan Gauld 
>>
>>
>>
>> i am using python 3.7
>>
>> On Thu, Jun 20, 2019 at 8:43 AM Antonio Arizpe > > wrote:
>>
>> it is for windows 7 64 bits but i will be targeting windows 7 and 10
>> 32 and 64 bits
>>
>> i currently use a script i was able to work together and its for
>> automated screenshots
>> i imagined for the key strike counter for it to be similar because i
>> imagined it as defining keystrikes as x = 1 and for every new key
>> strike would apply x+=1 and saving it in a text file in a directory.
>> im sorry im a little new for third party libraries im using im
>> really just using the default script that comes with python
>> installation
>> to make example here is the code i use for automated screenshots
>>
>> import sys
>> import os
>> from datetime import date
>> import pyautogui
>> import time
>> import shutil
>>
>>
>> today = str(date.today())
>>
>> os.chdir ('C:\\Program Files\\Python37\\tll')
>> os.mkdir (today)
>>
>>
>> x=1
>> while x<1080:
>> pyautogui.screenshot('/Program
>> Files/Python37/tll/'+str(today)+'/image'+str(x)+'.png')
>> x+=1
>> time.sleep(30)
>>
>> On Thu, Jun 20, 2019 at 3:30 AM Alan Gauld via Tutor
>> mailto:tutor@python.org>> wrote:
>>
>> On 19/06/2019 23:30, Antonio Arizpe wrote:
>>
>> > i just need help with a script thats registers keystrikes and
>> adds up all
>> > the times youve struck a key and gives a number of the total
>> amount of
>> > times the keyboard was struck. nothing specific about
>> characters. just how
>> > many times it was struck in a real number.
>>
>> It is possible, but it will likely be OS specific so you need to
>> tell us which OS you are using/targeting.
>>
>> Also any code that you've tried always helps along with any error
>> messages. Also tell us about any 3rd party libraries you are
>> using.
>>
>>
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>> http://www.amazon.com/author/alan_gauld
>> Follow my photo-blog on Flickr at:
>> http://www.flickr.com/photos/alangauldphotos
>>
>>
>> ___
>> Tutor maillist?? -?? Tutor@python.org 
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Hii

2019-06-20 Thread Antonio Arizpe
On Thu, Jun 20, 2019 at 12:36 PM Alan Gauld via Tutor 
wrote:

> Forwarding to list.
> Please use Reply-All or Reply-List when responding to list emails.
>
>
>
>  Forwarded Message 
> Subject:Re: [Tutor] Hii
> Date:   Thu, 20 Jun 2019 08:50:31 -0500
> From:   Antonio Arizpe 
> To: Alan Gauld 
>
>
>
> i am using python 3.7
>
> On Thu, Jun 20, 2019 at 8:43 AM Antonio Arizpe  > wrote:
>
> it is for windows 7 64 bits but i will be targeting windows 7 and 10
> 32 and 64 bits
>
> i currently use a script i was able to work together and its for
> automated screenshots
> i imagined for the key strike counter for it to be similar because i
> imagined it as defining keystrikes as x = 1 and for every new key
> strike would apply x+=1 and saving it in a text file in a directory.
> im sorry im a little new for third party libraries im using im
> really just using the default script that comes with python
> installation
> to make example here is the code i use for automated screenshots
>
> import sys
> import os
> from datetime import date
> import pyautogui
> import time
> import shutil
>
>
> today = str(date.today())
>
> os.chdir ('C:\\Program Files\\Python37\\tll')
> os.mkdir (today)
>
>
> x=1
> while x<1080:
> pyautogui.screenshot('/Program
> Files/Python37/tll/'+str(today)+'/image'+str(x)+'.png')
> x+=1
> time.sleep(30)
>
> On Thu, Jun 20, 2019 at 3:30 AM Alan Gauld via Tutor
> mailto:tutor@python.org>> wrote:
>
> On 19/06/2019 23:30, Antonio Arizpe wrote:
>
> > i just need help with a script thats registers keystrikes and
> adds up all
> > the times youve struck a key and gives a number of the total
> amount of
> > times the keyboard was struck. nothing specific about
> characters. just how
> > many times it was struck in a real number.
>
> It is possible, but it will likely be OS specific so you need to
> tell us which OS you are using/targeting.
>
> Also any code that you've tried always helps along with any error
> messages. Also tell us about any 3rd party libraries you are using.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist?? -?? Tutor@python.org 
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Hii

2019-06-20 Thread Alan Gauld via Tutor
Forwarding to list.
Please use Reply-All or Reply-List when responding to list emails.



 Forwarded Message 
Subject:Re: [Tutor] Hii
Date:   Thu, 20 Jun 2019 08:50:31 -0500
From:   Antonio Arizpe 
To: Alan Gauld 



i am using python 3.7

On Thu, Jun 20, 2019 at 8:43 AM Antonio Arizpe mailto:aarizpe...@gmail.com>> wrote:

it is for windows 7 64 bits but i will be targeting windows 7 and 10
32 and 64 bits

i currently use a script i was able to work together and its for
automated screenshots
i imagined for the key strike counter for it to be similar because i
imagined it as defining keystrikes as x = 1 and for every new key
strike would apply x+=1 and saving it in a text file in a directory.
im sorry im a little new for third party libraries im using im
really just using the default script that comes with python installation
to make example here is the code i use for automated screenshots

import sys
import os
from datetime import date
import pyautogui
import time
import shutil


today = str(date.today())

os.chdir ('C:\\Program Files\\Python37\\tll')
os.mkdir (today)


x=1
while x<1080:
pyautogui.screenshot('/Program
Files/Python37/tll/'+str(today)+'/image'+str(x)+'.png')
x+=1
time.sleep(30)

On Thu, Jun 20, 2019 at 3:30 AM Alan Gauld via Tutor
mailto:tutor@python.org>> wrote:

On 19/06/2019 23:30, Antonio Arizpe wrote:

> i just need help with a script thats registers keystrikes and
adds up all
> the times youve struck a key and gives a number of the total
amount of
> times the keyboard was struck. nothing specific about
characters. just how
> many times it was struck in a real number.

It is possible, but it will likely be OS specific so you need to
tell us which OS you are using/targeting.

Also any code that you've tried always helps along with any error
messages. Also tell us about any 3rd party libraries you are using.


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


___
Tutor maillist?? -?? Tutor@python.org 
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: would someone please explain this concept to me

2019-06-06 Thread Alan Gauld via Tutor
On 06/06/2019 00:57, Alan Gauld via Tutor wrote:

> But in the second example you actially change the object
> that checklimit refers to.
> 
> checklimit = 22   # immutable value assigned
> feeds['bar'] = checklimit   # both refer to same immutable value
> base_var = 66   # now feeds refers to original object: 22
> # and checklimit refers to new object: 66

Oops, base_var should of course be checklimit!
I started out using base_var then changed it to checklimit
to match the original code.
But this one slipped through unchanged.
Sorry.


-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: would someone please explain this concept to me

2019-06-06 Thread nathan tech
Hi alan,

thanks so much for clearing that up.

Now you've explained it in that way, I understand what it is doing and 
how it went wrong.

Thank you so much!

Nathan

On 06/06/2019 00:57, Alan Gauld via Tutor wrote:
> On 05/06/2019 20:47, nathan tech wrote:
>
>> so for example if I do:
>>
>> feeds[feed1]["limit"]=g.checklimit
>>
>> And later did g.checklimit=7000
>>
>> Would it change feeds[feed1]["limit"] too?
> No, because the feeds value is still referencing the
> original value object. The issue arises when you modify a mutable
> object that is references by two (or more) variables. If the value
> is immutable then the references will retain the original value.
>
> Specifically, in your case.
> The first example you set the feeds value to a dictionary. Then you
> modified the contents of the dictionary but did not change the
> dictionary itself.
>
> base_dict = {}   # create object
> feeds['foo'] = base_dict   # reference to same dict object
> base_dict['x'] = bar   # modified dict referred to by both variables
>
>
> But in the second example you actially change the object
> that checklimit refers to.
>
> checklimit = 22   # immutable value assigned
> feeds['bar'] = checklimit   # both refer to same immutable value
> base_var = 66   # now feeds refers to original object: 22
>  # and checklimit refers to new object: 66
>
> In the first case you do not change the object that base_dict refers to,
> you only change its content. In the second case you make checklimit
> refer to a completely new object.
>
> Does that make sense?
>
> PS. Notice that the use of a globals module, g, is completely irrelevant
> to this issue. It has nothing to do with the values being in a module,
> the issue is purely about references to objects and whether you modify
> the referenced object or its contents.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: would someone please explain this concept to me

2019-06-05 Thread Alan Gauld via Tutor
On 05/06/2019 20:47, nathan tech wrote:

> so for example if I do:
> 
> feeds[feed1]["limit"]=g.checklimit
> 
> And later did g.checklimit=7000
> 
> Would it change feeds[feed1]["limit"] too?

No, because the feeds value is still referencing the
original value object. The issue arises when you modify a mutable
object that is references by two (or more) variables. If the value
is immutable then the references will retain the original value.

Specifically, in your case.
The first example you set the feeds value to a dictionary. Then you
modified the contents of the dictionary but did not change the
dictionary itself.

base_dict = {}   # create object
feeds['foo'] = base_dict   # reference to same dict object
base_dict['x'] = bar   # modified dict referred to by both variables


But in the second example you actially change the object
that checklimit refers to.

checklimit = 22   # immutable value assigned
feeds['bar'] = checklimit   # both refer to same immutable value
base_var = 66   # now feeds refers to original object: 22
# and checklimit refers to new object: 66

In the first case you do not change the object that base_dict refers to,
you only change its content. In the second case you make checklimit
refer to a completely new object.

Does that make sense?

PS. Notice that the use of a globals module, g, is completely irrelevant
to this issue. It has nothing to do with the values being in a module,
the issue is purely about references to objects and whether you modify
the referenced object or its contents.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: would someone please explain this concept to me

2019-06-05 Thread nathan tech
hi there,

Thanks for that, I never thought of those options, though now you 
mention them, I'm going, duh!

I also, defined in globals, have a variable called checklimit.

EG: g.checklimit.

Am I ok to assign that to values?

so for example if I do:

feeds[feed1]["limit"]=g.checklimit


And later did g.checklimit=7000

Would it change feeds[feed1]["limit"] too?

Thanks

Nathan


On 05/06/2019 19:45, Alan Gauld via Tutor wrote:
>> That is why I was going to use g.blank-feed as the template,
>> assign that to d["feed 1's link"] then just update the feed part.
> The simplest way is just to assign a new blank dictionary. Don;t assign
> the same dictionary to each feed. (Incidentally your description above
> is much clearer than the one you initially posted!)
>
> feeds[link] = {key1:value1, key2:value2}
>
> If you need to pre-populate the dictionary with many values when
> you assign it (or need to compute  the values) I'd recommend
> writing a small function that creates a new dictionary,
> and adds the values then returns the dictionary.
>
> Or maybe, better still, use a class and populate the feeds
> dictionary with instances of the class.
>
> class Feed:
> def __init__(self, val1=default1, val2=default2, val3=default3):
> self.key1 = val1
> self.key2 = val2
> self.key3 = val3
>
> feeds[link1] = Feed(v1,v2,v3)
> feeds[link2] = Feed()   # use default values
>
> After all that's exactly what a class is - a template for an object.
>
> What you definitely don't want to do is what you have been
> doing and assigning the same single dictionary object to each
> link entry.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: would someone please explain this concept to me

2019-06-05 Thread Alan Gauld via Tutor


> That is why I was going to use g.blank-feed as the template, 
> assign that to d["feed 1's link"] then just update the feed part.

The simplest way is just to assign a new blank dictionary. Don;t assign
the same dictionary to each feed. (Incidentally your description above
is much clearer than the one you initially posted!)

feeds[link] = {key1:value1, key2:value2}

If you need to pre-populate the dictionary with many values when
you assign it (or need to compute  the values) I'd recommend
writing a small function that creates a new dictionary,
and adds the values then returns the dictionary.

Or maybe, better still, use a class and populate the feeds
dictionary with instances of the class.

class Feed:
   def __init__(self, val1=default1, val2=default2, val3=default3):
   self.key1 = val1
   self.key2 = val2
   self.key3 = val3

feeds[link1] = Feed(v1,v2,v3)
feeds[link2] = Feed()   # use default values

After all that's exactly what a class is - a template for an object.

What you definitely don't want to do is what you have been
doing and assigning the same single dictionary object to each
link entry.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: would someone please explain this concept to me

2019-06-05 Thread nathan tech
Thought I addressed this to the list... Aparrently my mail client hates me.


 Forwarded Message 
Subject:Re: [Tutor] would someone please explain this concept to me
Date:   Wed, 5 Jun 2019 02:37:49 +0100
From:   nathan tech 
To: Steven D'Aprano 


Hiya,

Thanks, first, for being able to understand what I was asking.

I admit I read over my own email and went, uh... I think I need to rewrite that.


So, I see what you are saying there, and it makes sense.

I want to actually do the following though:

d={} # a dict of some kind

feed1=somefeed

feed2=another feed of some kind

d["feed 1's url"]=feed1

d["feed 2's url"]=feed2


The way I do this is there are certain properties, if you were, that also need 
to be included, I.e, each entry should be its own dict containing feed, last 
check, check regularity, ETC.

That is why I was going to use g.blank-feed as the template, assign that to 
d["feed 1's link"] then just update the feed part.



Is there a way to do this?

Thanks

Nathan

On 05/06/2019 02:08, Steven D'Aprano wrote:
On Tue, Jun 04, 2019 at 11:37:23PM +, nathan tech wrote:

globals.py:

feeds={}
blank_feed={}
blank_feed["checked"]=1
blank_feed["feed"]=0
That is more easily, and better, written as:

feeds = {}
blank_feed = {"checked": 1, "feed": 0}


main file:

import globals as g
# some code that loads a feed into the variable knm
Do you mean something like this? If so, you should say so.

knm = "some feed"


g.feeds[link]=g.blank_feed;
What's "link" here? And there is no need for the semi-colon.

g.feeds[link]["feed"]=knm
Right... what the above line does is *precisely* the same as

g.blank_feed["feed"] = knm

Follow the program logic. I'm inserting 1970s BASIC style line numbers
to make it easier to discuss the code, remember that you can't actually
do that in Python.

10: g.feeds[link] = g.blank_feed
20: g.feeds[link]["feed"] = knm

Line 10 sets g.feeds[link] to the dict "blank_feed". *Not* a copy: you
now have two ways of referring to the same dict:

"g.blank_feed" and "g.feeds[link]"

both refer to the one dict, just as "Nathan" and "Mr Tech" are two ways
of referring to the same person (you).

So line 20 does this:

- look for the name "g", which gives the "globals.py" module;

- inside that module, look for the name "feeds", which gives
the "feeds" dict;

- look inside that dict for the key "link" (whatever value
that currently holds), which by line 10 has been set to
the same dict "blank_feed".

- inside the blank_feed dict, set key "feed" to "knm".



#in the below code, the variable link has a different value:
# load a feed into the variable r
Something like this?

r = "a different feed"

g.feeds[link]=g.blank_feed
Now you have *three* ways of naming the same dict:

"g.blank_feed", "g.feeds[link]", "g.feeds[different_link]"

but they all point to the same dict.

g.feeds[link]["feed"]=r


Now at this point, python would set the first loaded feed to the same
thing as the second loaded feed. It also set g.blank_feed to the second
feed, as well.
No, there is only one feed in total. You just keep updating the same
feed under different names.


I replaced the last three lines with this:

# load a feed into the variable r
g.feeds[link]=g.blank_feed;
g.feeds[link]["feed"]=r

And it works.
I don't see any difference between the replacement code and the original
code. The code you show does exactly the same thing.


but why does it work?

Why does that semi unlink all the variables?
Semi-colon?

It doesn't. You must have made other changes as well, semi-colons don't
have any runtime effect. They are *purely* syntax to tell the parser to
seperate multiple statements on one line.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Setting Command Line Arguments in IDLE

2019-05-26 Thread Mats Wichmann


> On 26/05/2019 02:55, Richard Damon wrote:
>> I am working on a python script that will be provided arguments when run
>> from the system command line. Is there any place in IDLE to provide
>> equivalent arguments for testing while developing in IDLE?
>>
> 
> There used to be a dialog for that but in the latest version
> of IDLE I can't find it. I wonder when it disappeared and why?
> 
> The best place to ask is probably on the IDLE-dev list.
> 
> It can be found here:
> 
> https://mail.python.org/mailman/listinfo/idle-dev

I've seen this question come up on stack overflow, can't recall I've
seen a completely satisfactory answer.

I would suggest, however, that doing the testing you're considering
should be written as unit tests.  You can invoke unit tests from inside
the program by adding something like this (I'm a pytest fan, but it
could be unittest as well of course):

import pytest

# your code here

if __name__ == "__main__":
pytest.main(["--capture=sys", "name-of-unittest-script.py"])

You can write your own argument array by fiddling with sys.argv; pytest
also provides a mechansim for injecting arguments (I think it's called
pytest_addoption).

The somewhat hacky way for a script to find out that it's running inside
IDLE (note: every time someone asks how to do this, a crowd of people
pop up and say "you don't want to be doing that".  But enabling a
testing scenario might actually be a time you want to?):

import sys

if "idlelib" in sys.modules:
print("We're running in IDLE")



These aren't really an answer to what you're asking for, but maybe some
tools you might use to think further about the problem?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Setting Command Line Arguments in IDLE

2019-05-26 Thread Alan Gauld via Tutor
Oops, Forgot to include the list!



 Forwarded Message 
Subject:Re: Setting Command Line Arguments in IDLE
Date:   Sun, 26 May 2019 09:03:36 +0100
From:   Alan Gauld 
To: Richard Damon 



On 26/05/2019 02:55, Richard Damon wrote:
> I am working on a python script that will be provided arguments when run
> from the system command line. Is there any place in IDLE to provide
> equivalent arguments for testing while developing in IDLE?
>

There used to be a dialog for that but in the latest version
of IDLE I can't find it. I wonder when it disappeared and why?

The best place to ask is probably on the IDLE-dev list.

It can be found here:

https://mail.python.org/mailman/listinfo/idle-dev

> Is there any way to define the working directory for the program, 

os.getcwd() # read current dir
os.chdir() # set current dir

> If not, is there an easy way to detect that I am running in IDLE so I
> can fake the command line arguments when testing?

Not that I'm aware, but the idle-dev gurus may have some ideas.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: RE: regular expressions query

2019-05-24 Thread Alan Gauld via Tutor


Forwarding to the list, plase use reply-all or reply-list when
responding to list mails.

Alan G.
 Forwarded Message 
Subject:RE: [Tutor] regular expressions query
Date:   Fri, 24 May 2019 20:10:48 +1000
From:   mhysnm1...@gmail.com
To: 'Alan Gauld' 



Allan,

I have gone back to the drawing board as I found to many problems with the
approach I was using. As the original data has multiple spaces between
words. I want to find unique phrases in the strings such as "Hello World"
regardless of the number of spaces that might be in the string.

I have used the following lines of code which finds the number of unique
complete strings.

transaction = [item for item, count in
collections.Counter(narration).items() if count > 1]
none-dup-narration = [item for item, count in
collections.Counter(narration).items() if count < 2]

So I end up with two lists one containing complete unique strings with more
than one occurrence and another with only one. As there is common words in
the none-dup-narration list of strings. I am trying to find a method of
extracting this information. I am still reading collections as this could
help. But wanted to understand if you can inject variables into the pattern
of regular expression which was the intent of the original question. Each
time the regular expression is executed, a different word would be in the
pattern.

In Python 3.7, I want to understand Unions and Maps. I have read information
on this in different places and still don't understand why, how and when you
would use them. Something else I have been wondering.

Goal here is to grow my knowledge in programming.

# end if
# end for
print (count)
# end for
input ()
# end for

-Original Message-
From: Tutor  On Behalf Of
Alan Gauld via Tutor
Sent: Friday, 24 May 2019 7:41 PM
To: tutor@python.org
Subject: Re: [Tutor] regular expressions query

On 24/05/2019 01:15, mhysnm1...@gmail.com wrote:

> Below I am just providing the example of what I want to achieve, not
> the original strings that I will be using the regular expression against.

While I'm sure you understand what you want I'm not sure I do.
Can you be more precise?

> The original strings could have:
> "Hello world"
> "hello World everyone"
> "hello everyone"
> "hello world and friends"

> I have a string which is "hello world" which I want to identify by
> using regular expression how many times:
>
> * "hello" occurs on its own.

Define "on its own" Is the answer for the strings above 4?
Or is it 1 (ie once without an accompanying world)?

> * "Hello world" occurs in the list of strings regardless of the number
> of white spaces.

I assume you mean the answer above should be 3?

Now for each scenario how do we treat

"helloworldeveryone"?
"hello to the world"
"world, hello"
"hello, world"

> Splitting the string into an array ['hello', 'world'] and then
> re-joining it together and using a loop to move through the strings
> does not provide the information I want. So I was wondering if this is
> possible via regular expressions matching?

It is probably possible by splitting the strings and searching, or even just
using multiple standard string searches. But regex is possible too. A lot
depends on the complexity of your real problem statement, rather than the
hello world example you've given. I suspect the real case will be trickier
and therefore more likely to need a regex.

> Modifying the original string is one option. But I was wondering if
> this could be done?

I'm not sure what you have in mind. For searching purposes you shouldn't
need to modify the original string. (Of course Python strings are immutable
so technically you can never modify a string, but in practice you can
achieve the same
effect.)

--
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: feedparser in python

2019-04-30 Thread Alan Gauld via Tutor
Sharing with the list, comments later. Busy right now.



 Forwarded Message 
Subject:Re: [Tutor] feedparser in python
Date:   Tue, 30 Apr 2019 14:14:35 +
From:   nathan tech 
To: Alan Gauld 



Hi Alan,

Thanks for your emails.

I considered what you said, and came up with a couple of possibilities,
listed below.

Before that, I wanted to clarify what I meant when I said "not working."
I kept meaning to do it, and kept forgetting.

According to the docs:

?? f=feedparser.parse(url)

Will download a feed, parse it into xml, and return a dict of that feed,
which it does. There are obviously some special things going on with
tha,t because it allows, for instance, f.entries[0].title, rather than
f["entries"][0]["title"].

Anyway.

The docs then say that feedparser will have elements of etag and
modified, which you can then pass in an update, like so:

?? newfeed=feedparser.parse(url, etag=f.etag, modified=f.modified)

To that end, it would check the headers, and if the feed was not
updated, set newfeed.status to 304.


Which is great, accept... My feeds never have a .etag or a .modified
anywhere.

Even f.get("etag") returns None. which while I could pass it that way,
would mean the feed gets downloaded over and over and over again.

In an example of an rss feed of size 10 MB, that's 240 MB a day, and by
3 days you're over a GIG.


To that end, when I said not working, I meant, nothing I parsed in place
of f.etag and or f.modified seemed to work in that it juts downloaded
the entire feed agai


Now, onto some solutions:

I considered what you said and realised actually, logic says all we need
to know is: is file on local hard drive older than file on web server,
right?

Which lead me briefly to, would os.path.getfilemtime work? Probably not,
but I am curious if there are alternatives to thhat.


In any case, finally I thought, what about f.entries

This is a list of entries in an rss feed.

Even without an update key, which they usually have:

?? date=f.entries[0].updated = "Fri, August 20th 2009"

We could simply do:

?? if(downlaoded_first_entry==f.entries[0]):

 # feed is jup to date, so quit.


This is where I got stuck.

urllib2.urlopen() from my calculations, seems to download the file, then
open it?

Is that correct, or is that wrong?

I wrote up this function below:

?? import urllib2

?? import time

?? url="https://www.bigfinish.com/podcasts.rss";

?? start_time=time.time()

?? j=urllib2.urlopen(url)

?? j.close() # lets not be messy

?? print time.time()-start_time

That came out at 0.8 seconds.

perhaps that is just network connectivity?

but if we remember back to the tests run with the tim function, the
difference in time there was around 1.1 seconds.

The similarities were.. worrying is all.

If urllib2.urlopen doesn't download the file, and merely opens a link
up, as it were, then great.


My theory here is to:

open the web file,

discard any data up to ""

until "" is reached, save the data to a list.

Covnert that list using an xml parser into a dictionary, and then
compare either updated, title, or the whole thing.

If one of them says, this isn't right, download the feed.

If they match, the feed on local drive is up to date.

To be fair, I could clean this up further, and simply have:

until  or  is reached save to a list, but that's a
refinement for later.


I'm looking forward to hear your thoughts on this.

I picked up python myself over the course of a year, so am not quite
used to having back and forth like these yet. Especially not with
someone who knows what they're talking about. :)

Thanks

Nate


On 30/04/2019 08:47, Alan Gauld via Tutor wrote:
> On 30/04/2019 00:23, nathan tech wrote:
>
>> The results were as follows:
>>
>> ?? tim( a url): 2.9 seconds
>>
>> ?? tim(the downoaded file(: 1.8 seconds
>>
>>
>> That tells me that roughly 1.1 seconds is network related, fair enough.
> Or about 30% of the time.
> Since the network element will increase as data
> size increases as will the parse time it may be
> a near linear relationship. Only more extensive
> tests would tell.
>
>> entire thing again, they all say use ETAG and Modified, but my feeds
>> never, have them.
>>
>> I've tried feeds from several sources, and none have them in the http
>> header.
> Have you looked at the headers to see what they do have?
>
>> To that end, that is why I mentioned in the previous email about .date,
>> because that seemed the most likely, but even that failed.
> Again you tell us that something failed. But don't say
> how it failed. Do you mean that date did not exist?
> Why did you think it would if you had already inspected
> the headers?
>
> Can you share some actual code that you used to check
> these fields? And sow us the actual headers you are
> reading?
>
>> 1, download a feed to the computer.
>>
>> 2. Occasionally, check the website to see if the donloaded feed is out
>> of date if it is, redownload it.

Re: [Tutor] Fwd: uploading images in pygame

2019-04-17 Thread Alan Gauld via Tutor
On 17/04/2019 10:14, fatima butt wrote:
> the python version is 3.7.3
> computer is acer SWIFT
> The error I get is following:
> Traceback (most recent call last):
>   File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py
> ", line 84, in 
> background = pygame.image.load(path.join(img_dir,"ship1.jpg")).convert()
> pygame.error: Couldn't open
> C:\Users\ammah\OneDrive\Documents\project1\ship1.jpg

In addition to checking that the file exists in that location
you should also check the permissions to make sure you are
allowed to open it.


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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: uploading images in pygame

2019-04-17 Thread Peter Otten
fatima butt wrote:

> the python version is 3.7.3
> computer is acer SWIFT
> The error I get is following:
> Traceback (most recent call last):
>   File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py
> ", line 84, in 
> background =
> pygame.image.load(path.join(img_dir,"ship1.jpg")).convert()
> pygame.error: Couldn't open
> C:\Users\ammah\OneDrive\Documents\project1\ship1.jpg

Are you sure you have an image called 'ship1.jpg' in the
"C:\Users\ammah\OneDrive\Documents\project1" folder?

Double-check before you take other less likely problems into consideration.

If you can see the above file in your filemanager -- does the following 
script succeed?

with open(r"C:\Users\ammah\OneDrive\Documents\project1"), "rb"):
pass

If it doesn't, what does the traceback show?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: uploading images in pygame

2019-04-17 Thread fatima butt
the python version is 3.7.3
computer is acer SWIFT
The error I get is following:
Traceback (most recent call last):
  File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py
", line 84, in 
background = pygame.image.load(path.join(img_dir,"ship1.jpg")).convert()
pygame.error: Couldn't open
C:\Users\ammah\OneDrive\Documents\project1\ship1.jpg
>>>

The code that I entered in my Python shell is as following:
# Pygame template - skeleton for a new pygame project
import pygame
import random
from os import path

img_dir = path.dirname(__file__)


WIDTH = 480
HEIGHT = 600
FPS = 60

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255,255,0)

pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()


class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((80,70))
self.image.fill(GREEN)
self.rect =self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT -10
self.speedx = 0

def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = 5
if keystate[pygame.K_RIGHT]:
self.speedx = -5
self.rect.x += self.speedx

def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)

class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface ((40,30))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(1,8)

def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT +10:
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(1,8)

class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10,20))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10

def update(self):
self.rect.y += self.speedy
if self.rect.bottom<0:
self.kill()

#Load all game graphics
background = pygame.image.load(path.join(img_dir,"ship1.jpg")).convert()
background_rect = background.get_rect()



all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
# Update
all_sprites.update()
#check to see if a bullet hit a mob
#check to see if a mob hit the player
hits = pygame.sprite.spritecollide(player,mobs,False)
if hits:
running = False

# Draw / render
screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()

pygame.quit()


On Tue, 16 Apr 2019 at 23:34, Alan Gauld via Tutor  wrote:

> On 16/04/2019 20:54, fatima butt wrote:
> > please i am getting error..
>
> Hi, we need to be quite specific here about the details
> because it is not clear exactly what you are trying to do.
>
> > i am trying to upload image from openspaceart
> > from internet .
>
> Just to be clear.
> Uploading means going from your computer onto a server
> on the internet. So, I'm assuming what you are trying
> to do is download an image from openspaceart to your
> computer. Is that correct?
>
> Or are you in fact trying to upload an image from your
> computer to the openspaceart server?
>
> There is a big difference between the two.
>
> > I have downloaded the image on my desktop
>
> So it sounds like you have succeeded in downloading
> the image from the server and now have a copy on
> your local computer? Is that correct?
>
> > and i am trying
> > to upload this to the pygame.
>
> But pygame is not on a network it is on your computer
> so you don't need to upload the image, you should
> just need to access it from within pygame.
>
> To help with that we need to know exactly what you
> are trying to do

Re: [Tutor] Fwd: IDLE Terminal

2019-04-17 Thread fatima butt
Its IDLE python version 3.7.3
ITs Subprocess Startup Error.
IDLE startupprocess didnt make connection.Either IDLE cant start a process
or personal firewall software is blocking the connection.

the computer i am using is swift acer


On Tue, 16 Apr 2019 at 23:40, Alan Gauld via Tutor  wrote:

> On 16/04/2019 20:54, fatima butt wrote:
> > [image: image.png]please I need help with IDLE teminal..its giving me
> error.
>
> The mail server drops attachments because they are a potential
> security threat.
>
> Please post the error text (cut 'n paste if possible)
> Also describe what you are trying to do.
> Which OS you are using and which Python version.
> The more detail you give s the easier it is to give
> you the correct answer.
>
> --
> 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@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: IDLE Terminal

2019-04-17 Thread fatima butt
hi
the python version is 3.7.3
computer is acer SWIFT
The error I get is following:
Traceback (most recent call last):
  File "C:\Users\ammah\OneDrive\Documents\project1\myCode.py.py", line 84,
in 
background = pygame.image.load(path.join(img_dir,"ship1.jpg")).convert()
pygame.error: Couldn't open
C:\Users\ammah\OneDrive\Documents\project1\ship1.jpg
>>>

The code that I entered in my Python shell is as following:
# Pygame template - skeleton for a new pygame project
import pygame
import random
from os import path

img_dir = path.dirname(__file__)


WIDTH = 480
HEIGHT = 600
FPS = 60

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255,255,0)

pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()


class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((80,70))
self.image.fill(GREEN)
self.rect =self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT -10
self.speedx = 0

def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = 5
if keystate[pygame.K_RIGHT]:
self.speedx = -5
self.rect.x += self.speedx

def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)

class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface ((40,30))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(1,8)

def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT +10:
self.rect.x =random.randrange(WIDTH-self.rect.width)
self.rect.y=random.randrange(-100,-40)
self.speedy=random.randrange(1,8)

class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10,20))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10

def update(self):
self.rect.y += self.speedy
if self.rect.bottom<0:
self.kill()

#Load all game graphics
background = pygame.image.load(path.join(img_dir,"ship1.jpg")).convert()
background_rect = background.get_rect()



all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
# Update
all_sprites.update()
#check to see if a bullet hit a mob
#check to see if a mob hit the player
hits = pygame.sprite.spritecollide(player,mobs,False)
if hits:
running = False

# Draw / render
screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()

pygame.quit()



On Tue, 16 Apr 2019 at 23:40, Alan Gauld via Tutor  wrote:

> On 16/04/2019 20:54, fatima butt wrote:
> > [image: image.png]please I need help with IDLE teminal..its giving me
> error.
>
> The mail server drops attachments because they are a potential
> security threat.
>
> Please post the error text (cut 'n paste if possible)
> Also describe what you are trying to do.
> Which OS you are using and which Python version.
> The more detail you give s the easier it is to give
> you the correct answer.
>
> --
> 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@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: IDLE Terminal

2019-04-16 Thread Tobiah




On 4/16/19 12:54 PM, fatima butt wrote:

[image: image.png]please I need help with IDLE teminal..its giving me error.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



Please copy the error text into your message.
The list won't accept attachments.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: IDLE Terminal

2019-04-16 Thread Alan Gauld via Tutor
On 16/04/2019 20:54, fatima butt wrote:
> [image: image.png]please I need help with IDLE teminal..its giving me error.

The mail server drops attachments because they are a potential
security threat.

Please post the error text (cut 'n paste if possible)
Also describe what you are trying to do.
Which OS you are using and which Python version.
The more detail you give s the easier it is to give
you the correct answer.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: uploading images in pygame

2019-04-16 Thread Alan Gauld via Tutor
On 16/04/2019 20:54, fatima butt wrote:
> please i am getting error..

Hi, we need to be quite specific here about the details
because it is not clear exactly what you are trying to do.

> i am trying to upload image from openspaceart
> from internet .

Just to be clear.
Uploading means going from your computer onto a server
on the internet. So, I'm assuming what you are trying
to do is download an image from openspaceart to your
computer. Is that correct?

Or are you in fact trying to upload an image from your
computer to the openspaceart server?

There is a big difference between the two.

> I have downloaded the image on my desktop 

So it sounds like you have succeeded in downloading
the image from the server and now have a copy on
your local computer? Is that correct?

> and i am trying
> to upload this to the pygame.

But pygame is not on a network it is on your computer
so you don't need to upload the image, you should
just need to access it from within pygame.

To help with that we need to know exactly what you
are trying to do with the image in pygame. Are you
displaying it as a background? Creating sprites?
Using it as part of a GUI, maybe on a button?

It would really help if you can show us some code.
Even if it doesn't work it will help us understand
what you are trying to do.

Also if you get any error messages send them too.
But send it as text, the list does not accept
attachments since they pose a security risk.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: uploading images in pygame

2019-04-16 Thread Mats Wichmann
On 4/16/19 1:54 PM, fatima butt wrote:
> please i am getting error..i am trying to upload image from openspaceart
> from internet . I have downloaded the image on my desktop and i am trying
> to upload this to the pygame.

Please provide us with more information. What are you trying (hint:
*code*), what kind of errors are you getting, etc.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: IDLE Terminal

2019-04-16 Thread fatima butt
[image: image.png]please I need help with IDLE teminal..its giving me error.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: uploading images in pygame

2019-04-16 Thread fatima butt
please i am getting error..i am trying to upload image from openspaceart
from internet . I have downloaded the image on my desktop and i am trying
to upload this to the pygame.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: [Tkinter-discuss] New docs: using tkinter GUIs on Android

2019-02-10 Thread boB Stepp
I thought that this might be of interest to the group for those who do
not follow the Tkinter mailing list as I have seen questions here
about how to do Python GUIs in Android where the usual response is to
try Kivy.  Perhaps there is now a tkinter solution?

-- Forwarded message -
From: Mark Lutz 
Date: Sun, Feb 10, 2019 at 10:07 AM
Subject: [Tkinter-discuss] New docs: using tkinter GUIs on Android
To: , 


I've just posted guides for running Python tkinter programs on
Android in the Pydroid 3 app's IDE.  The first covers multiple
programs, and the second focuses on a content-sync program:

  https://learning-python.com/using-tkinter-programs-on-android.html
  https://learning-python.com/mergeall-android-scripts/_README.html

And yes, you read that right: Python tkinter GUIs, including
the calendar, calculator, text editor, and incremental backup
tool described in these docs, now work on your smartphone in
addition to your PC, though they come with a few rough edges
(and advertising) on Android today.

And there was much rejoicing,
--M. Lutz (http://learning-python.com)
___
Tkinter-discuss mailing list
tkinter-disc...@python.org
https://mail.python.org/mailman/listinfo/tkinter-discuss


-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Doubt in Python

2019-01-17 Thread Steven D'Aprano
On Thu, Jan 17, 2019 at 09:57:03AM +, Alan Gauld via Tutor wrote:

> The algorithm is probably described somewhere in the documentation
> but my understanding is that it looks something like this(in pdeudo code):

List, tuple and string comparisons are defined as lexicographical order:

http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types

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

That's a fancy way of saying "dictionary order". That means that lists 
are ordered in the same way that words are ordered in the dictionary:

- match up letters in the word (items in the list) in pairs;

- so long as the pairs of letters (items) are equal, keep going;

- as soon as you hit a pair that aren't equal, the order of that pair 
determines the order of the words (lists);

- if one word runs out of letters (list runs out of items), then it 
comes first;

- if all the pairs are equal, the words (lists) are equal.


Some examples:

[0, 1, 2] < [1, 2, 3] because 0 < 1

[0, 1, 2] < [0, 1, 2, 3] because the first three items are equal 
but the first list is shorter.

[0, 1, 2, 3, 4, 5] < [0, 1, 999] because 2 < 999

[0, 999, 999, 999] < [1, 2] because 0 < 1


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Doubt in Python

2019-01-17 Thread Alan Gauld via Tutor


CCing the list. Please use Reply All or Reply List on responses to the list.

On 17/01/2019 07:24, Maninath sahoo wrote:
 a=[100,50,30]
 b=[100,90,3]
 a True
 a>b
> False
>
>
> How it compares between two lists
>
The algorithm is probably described somewhere in the documentation
but my understanding is that it looks something like this(in pdeudo code):

def isEqual(X,Y):

    if len(X) != len(Y): return False

    if X[0] != Y[0]: return False

    return X[1:] == Y[1:]


def isGreater(X,Y):

   if len(X) <= len(Y) return False

   if X[0] < Y[0] return False

   if X[0] == Y[0] return X[1:] > Y[1:]

   return True


And similarly for the other operators.

But that's just based on playing with the interpreter and exploring
different values...

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Data pattern query.

2019-01-07 Thread Alan Gauld via Tutor
Sending to list. Please use reply-all when responding to the list.

 Original Message 
 Subject: RE: [Tutor] Data pattern query.
 From: mhysnm1...@gmail.com
 Sent: Monday, 7 January 2019 11:58
 To: 'Alan Gauld' 
 CC: 

Alan,

Thanks for responding. I am storing the spreadsheet into a dictionary using
a two dimension list. The key for the dictionary is the sheet name. Possibly
in the future I might just have a simple list. 6 columns across with
variable rows. Max is over 1000 rows.

Below is the code:

import openpyxl # module to import spreadsheet.
# module found on the net to remove duplicates.
from  more_itertools import unique_everseen 

# Loding the workbook and names for the sheets.
wb = openpyxl.load_workbook("test.xlsx")
# Storing sheet names into a list for the loop.
wss = wb.get_sheet_names()

# defining variables for data structure
transaction = {} # dictionary of bank transactions.
description = [] # the descriptions of transactions

for ws_name in wss:
# sheet being worked upon.
ws = wb.get_sheet_by_name(ws_name) 
data = []# temp variable to store 2 dimension list.
for column in ws.columns:
c = [] # temp variable for current column 
for cell in column:
c.append(cell.value) # is this correct?
# end for cell loop 
if c[0] == "Description":
#Populating the description list
description.extend(c)
data.append(c)  # creating two dimension list
# end for for column 
# creating dictionary with 2 dimension list 
transaction[ws_name] = data 
#end for 

/*** the below code is not working ***/

If I sort the description list. I get untyped errors. When I use the debug.
The items (elements) in the description list at the end are 'None" value.
Not sure if this is due to the location of defining the empty list or the
method of using append with the list c. If the below code could sort, then
the remaining lines would perform the duplicate on the whole value of the
item. While I want to identify duplicates with the vendor name only.
 
description.sort()
for result in unique_everseen (description):
print (result)

Some example data structure. I have modified for privacy reasons.

PAY/SALARY FROM vendor-name 
EFTPOS vendor-name HORNSBY  country-code
bank-name BANKING FUNDS TFER TRANSFER ##  TO ##
vendor-name suburb state 
vendor-name  suburb 
DEPOSIT vendor-name PAYMENT state-name
WITHDRAWAL BY EFTPOS  vendor-name  suburb 12/06 
DEPOSIT-vendor-name Aust organisation_name #



-Original Message-
From: Tutor  On Behalf Of
Alan Gauld via Tutor
Sent: Monday, 7 January 2019 8:20 PM
To: tutor@python.org
Subject: Re: [Tutor] Data pattern query.

On 07/01/2019 02:38, mhysnm1...@gmail.com wrote:

> All the descriptions of the transactions are in a single column. I am 
> trying to work out the easiest method of identifying the same pattern 
> of text in the fields.

What does a singe column mean? That presumably is how it appears in the
spreadsheet? But how is it stored in your Python code? A list? a list of
lists? a dictionary?

We don't know what your data looks like.
Post a sample along with an explanation of how it is structured.

In general when looking for patterns in text a regular expression is the
tool of choice. But only if you know what the pattern looks like.
Identifying patterns as you go is a much more difficult challenge

> Then I am going to group these vendors by categories. 

And how do you categorize them? Is the category also in the data or is it
some arbitrary thing that you have devised?

> In the field, there is the vendor name, suburb/town, type of transaction,
etc.

etc is kind of vague!
Show us some data and tel;l us which field is which.
Without that its difficult to impossible to tell you how to extract
anything!

The important thing is not how it looked in the spreadsheet but how it looks
now you have it in Python.

> How can I teach the program to learn new vendor names? 

Usually you would use a set or dictionary and add new names as you find
them.

> I was thinking of removing all the duplicate entries

Using a set would do that for you automatically

> Was thinking of using dictionaries for this. 
> But not sure if this is the best approach. 

If you make the vendor name the key of a dictionary then it has the same
effect as using a set. But whether a set or dict is best depends on what
else you need to store. If its only the vendor names then a set is best. If
you want to store associated data then a dict is better.

You need to be much more specific about what your data looks like, how you
identify the fields you want, and how you will categorize 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 Flick

Re: [Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?

2018-10-23 Thread Avi Gross
Since this topic is not focused on efficiency, why exactly does it matter if
your function should check if a file exists and then avoid a collision?

What you are describing sounds a bit like a hash function. In many cases,
when you perform the computations you may find the slot you hash to is
already occupied. A common solution is to check and if needed make some
adjustment like adding 1 or using a second hash function or changing the
thing being hashed in a deterministic way like changing "key" to "keykey"
and even "keykeykey" before hashing till you get an empty slot. Note in
Python, you can simply use a dictionary and have no idea how the hash is
done.

Since you are describing a need for a permanent file, many suggested ways of
making a unique file name can repeat and thus not be unique. The process ID
wraps around and maybe restarts every time the machine boots, I suspect.
Dates repeat unless they include the year as in 2018101903 to the
nearest second. If you are concerned about two files being created in the
same second, there is a trivial solution. Before or after creating the file,
sleep for a time period like a second so any "second" saved file is
guaranteed to come at least a second later, in the above scheme. 

I heard a concern about what happens if you just use sequence numbers as in
file3 then file4 if the user later deletes some. The concern was
subtle about what happens if a file is later deleted and your algorithm
later will search for the first available empty slot. To each their own but
it strikes me as fairly easy in Python to not check EVERY filename but skip
past the last one.

You have functions that return a list of filenames in a directory as a list
of strings. In my example, you could take the list and replace "file" with
nothing to get [ "1", "2", "4", ... ]

Then in memory, efficiently, without opening a single file, you can sort the
strings, pop off the last one, convert it to an int, add one, make a new
file name like "file00111" that is guaranteed not to exist unless some other
program sneaks it in, and continue.

There are lots of ideas you can try. This would only need to happen perhaps
once per game and you can encapsulate the logic in your own function so all
your code will say is something like:
save_game_info(...)

Of course if someone else had already come up with similar functionality,
use it. 

Oddly, you may not be aware that your method indicates thinking too much
inside the box. Instead of saving files on your own, consider creating a
data structure and letting known modules save it in the file system and
retrieve it later. There are packages like pickle and shelve.

https://docs.python.org/3/library/pickle.html
https://docs.python.org/3/library/shelve.html

So if you load an existing object, such as a dictionary or list before a
game starts, and after each game extend the object and then save it to disk
this way, then you don't need to deal with details as long as the program
knows where it is stored. The person running the program may not trivially
be able to access the data and is not likely to delete easily. The actual
file names may depend on what the package does and you may find other such
packages better fit your needs and let you easily save all kinds of info
like scores and time elapsed and number of moves as you are saving entire
data structures you create and control.

Just some thoughts.

Avi

-Original Message-
From: Tutor  On Behalf Of boB
Stepp
Sent: Monday, October 22, 2018 8:31 PM
To: tutor 
Subject: Re: [Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be
used to create *permanent* uniquely named files?

On Mon, Oct 22, 2018 at 11:57 AM Mats Wichmann  wrote:
>
> On 10/22/18 8:24 AM, boB Stepp wrote:
> > Forwarding to the Tutor list.  Herr Maier offers a good idea that 
> > would take away much of a remaining issue -- the name "Temporary".  
> > I need to look into the functools library to see what "partial" does.
>
>
> if you really don't care what the file is called because you will 
> maintain a map which leads you to the filename, you might as well use 
> a uuid.

Wouldn't I have to write a check to ensure such a named file (However
unlikely that would be.) did not exist before creating it?  And if yes,
would not that get into the same potential security issue that cause
tempfile.mktemp() to be deprecated?


--
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?

2018-10-22 Thread William Ray Wing via Tutor


> On Oct 22, 2018, at 8:30 PM, boB Stepp  wrote:
> 
> On Mon, Oct 22, 2018 at 11:57 AM Mats Wichmann  wrote:
>> 
>> On 10/22/18 8:24 AM, boB Stepp wrote:
>>> Forwarding to the Tutor list.  Herr Maier offers a good idea that
>>> would take away much of a remaining issue -- the name "Temporary".  I
>>> need to look into the functools library to see what "partial" does.
>> 
>> 
>> if you really don't care what the file is called because you will
>> maintain a map which leads you to the filename, you might as well use a
>> uuid.
> 
> Wouldn't I have to write a check to ensure such a named file (However
> unlikely that would be.) did not exist before creating it?  And if
> yes, would not that get into the same potential security issue that
> cause tempfile.mktemp() to be deprecated?
> 

The whole point of UUIDs is to make the probability of a UUID collision so 
infinitesimally small as to make that hypothetical collision simply not worth 
worrying about, even when they are created on different systems.  Since a big 
chunk of a UUID is a high precision time stamp, any UUIDs created on a single 
system are pretty much guaranteed to be unique.

Bill 

> -- 
> boB
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?

2018-10-22 Thread boB Stepp
On Mon, Oct 22, 2018 at 11:57 AM Mats Wichmann  wrote:
>
> On 10/22/18 8:24 AM, boB Stepp wrote:
> > Forwarding to the Tutor list.  Herr Maier offers a good idea that
> > would take away much of a remaining issue -- the name "Temporary".  I
> > need to look into the functools library to see what "partial" does.
>
>
> if you really don't care what the file is called because you will
> maintain a map which leads you to the filename, you might as well use a
> uuid.

Wouldn't I have to write a check to ensure such a named file (However
unlikely that would be.) did not exist before creating it?  And if
yes, would not that get into the same potential security issue that
cause tempfile.mktemp() to be deprecated?


-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?

2018-10-22 Thread Mats Wichmann
On 10/22/18 8:24 AM, boB Stepp wrote:
> Forwarding to the Tutor list.  Herr Maier offers a good idea that
> would take away much of a remaining issue -- the name "Temporary".  I
> need to look into the functools library to see what "partial" does.


if you really don't care what the file is called because you will
maintain a map which leads you to the filename, you might as well use a
uuid.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?

2018-10-22 Thread boB Stepp
Forwarding to the Tutor list.  Herr Maier offers a good idea that
would take away much of a remaining issue -- the name "Temporary".  I
need to look into the functools library to see what "partial" does.

-- Forwarded message -
From: Wolfgang Maier 
Date: Mon, Oct 22, 2018 at 5:25 AM
Subject: Re: Can tempfile.NamedTemporaryFile(delete=False) be used to
create *permanent* uniquely named files?
To: boB Stepp 


On 21.10.18 08:13, boB Stepp wrote:
> Use case:  I want to allow a user of my Solitaire Scorekeeper program
> to be able to give any name he wants to each game of solitaire he
> wishes to record.  My thought for permanent storage of each game's
> parameters is to use a dictionary to map the user-chosen game names to
> a unique json filename.  This way I hope no shenanigans can occur with
> weird characters/non-printing characters.
>
> My initial thought was to just have a sequence of game names with
> incrementing numerical suffixes:  game_0, game_1, ... , game_n.  But
> this would require the program to keep track of what the next
> available numerical suffix is.  Additionally, if a user chooses to
> delete a game, then there would be a gap in the numerical sequence of
> the game filenames.  I find such a gap aesthetically displeasing and
> would probably go to additional efforts to reuse such deleted
> filenames, so there would be no such "gaps".
>
> So I am now wondering if using
> tempfile.NamedTemporaryFile(delete=False) would solve this problem
> nicely?  As I am not very familiar with this library, are there any
> unforeseen issues I should be made aware of?  Would this work equally
> well on all operating systems?
>
> TIA!
>

This sounds like a good though surprising use case. The only odd thing
about this is the misleading name then of the function, plus there is
the (vague) possibility that the stdlib module might evolve and no
longer support this undocumented (given that the first sentence in the
module description reads: "This module creates temporary files and
directories.") use case.
I would probably address these issues and the handling of the dir
parameter via a partial function like this:

from functools import partial

SavedGameFile = partial(
 tempfile.NamedTemporaryFile, dir=my_saved_games_dir
 ) # if you like also set the suffix here
SavedGameFile.__doc__ = """\
Create and return a saved game file, ...
"""

This way you have a good name for the function, and you can redefine the
function, if you ever want/need to move away from NamedTemporaryFile,
without having to rewrite every function call.

Wolfgang


-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: How to roughly associate the values of two numpy arrays, or python lists if necessary

2018-09-23 Thread Shall, Sydney via Tutor

On 23/09/2018 13:04, Peter Otten wrote:

Peter Otten wrote:


Maybe you could sort the already-sorted property_b again, with some random
offset:


import itertools
def wiggled(items, sigma):

... counter = itertools.count()
... def key(item): return random.gauss(next(counter), sigma)
... return sorted(items, key=key)
...


One more example:


s = """\

... But my actual scientific problem requires that the correlation should be
... only approximate and I do not know how close to to a perfect correlation
... it should be. So, I need to introduce some lack of good correlation when
... I set up the correlation. How to do that is my problem.
... """

print(textwrap.fill(" ".join(wiggled(s.split(), 2

But actual my scientific the requires that problem should only
correlation approximate be and not do I know how close to a perfect to
correlation should it So, be. I to lack need some introduce
correlation I of good when set correlation. up How to the that do
problem. is my

:)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=01%7C01%7Csydney.shall%40kcl.ac.uk%7C185332cee28f49ed465108d6214ce8ab%7C8370cf1416f34c16b83c724071654356%7C0&sdata=GBAb%2FdY2zrBqSwOl33ejT%2BzzknQx5RYNXsNEqZQXCX4%3D&reserved=0


Thanks. Most useful.

Sydney

--

_

Professor Sydney Shall
Department of Haematology/Oncology
Phone: +(0)2078489200
E-Mail: sydney.shall
[Correspondents outside the College should add @kcl.ac.uk]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: How to roughly associate the values of two numpy arrays, or python lists if necessary

2018-09-23 Thread Shall, Sydney via Tutor

On 23/09/2018 10:42, Peter Otten wrote:

Shall, Sydney via Tutor wrote:


What I want is the following.

I have:

property_a = [1, 6, 2, 4]
property_b = [62, 73, 31 102]


Result should approximately be:

property_b = [31, 102, 62, 73]


That is both lists change in value in exactly the same order.

Now, this is easy to achieve. I could simply sort both lists is
ascending order and I would then have an exact alignment of values is
ascending order. The correlation would be a perfect linear relationship,
I suppose.

But my actual scientific problem requires that the correlation should be
only approximate and I do not know how close to to a perfect correlation
it should be. So, I need to introduce some lack of good correlation when
I set up the correlation. How to do that is my problem.

I hope this helps to clarify what my problem is.


Maybe you could sort the already-sorted property_b again, with some random
offset:


import itertools
def wiggled(items, sigma):

... counter = itertools.count()
... def key(item): return random.gauss(next(counter), sigma)
... return sorted(items, key=key)
...

wiggled(range(20), 3)

[0, 5, 2, 4, 1, 6, 7, 8, 3, 9, 11, 10, 13, 14, 16, 12, 18, 17, 19, 15]

wiggled([31, 102, 62, 73], .8)

[102, 31, 62, 73]

wiggled([31, 102, 62, 73], .8)

[31, 102, 62, 73]

wiggled([31, 102, 62, 73], .8)

[31, 102, 62, 73]

wiggled([31, 102, 62, 73], .8)

[31, 62, 102, 73]


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=01%7C01%7Csydney.shall%40kcl.ac.uk%7Cb9cbdce8c20e45dd3ff508d621390143%7C8370cf1416f34c16b83c724071654356%7C0&sdata=yNo7hMVl7dYmH6d74MBaab5e5g6bPoWoqkza5TS1bXY%3D&reserved=0




Thanks to Oscar and to Pater for their help. They have set me on the 
correct path.
The crucial advice to was to look at the randomisation procedures. I 
have used a procedure similar to that suggested by Peter and it works well.


Cheers,

Sydney

_

Professor Sydney Shall
Department of Haematology/Oncology
Phone: +(0)2078489200
E-Mail: sydney.shall
[Correspondents outside the College should add @kcl.ac.uk]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: How to roughly associate the values of two numpy arrays, or python lists if necessary

2018-09-23 Thread Peter Otten
Peter Otten wrote:

> Maybe you could sort the already-sorted property_b again, with some random
> offset:
> 
 import itertools
 def wiggled(items, sigma):
> ... counter = itertools.count()
> ... def key(item): return random.gauss(next(counter), sigma)
> ... return sorted(items, key=key)
> ...

One more example:

>>> s = """\
... But my actual scientific problem requires that the correlation should be 
... only approximate and I do not know how close to to a perfect correlation 
... it should be. So, I need to introduce some lack of good correlation when 
... I set up the correlation. How to do that is my problem.
... """
>>> print(textwrap.fill(" ".join(wiggled(s.split(), 2
But actual my scientific the requires that problem should only
correlation approximate be and not do I know how close to a perfect to
correlation should it So, be. I to lack need some introduce
correlation I of good when set correlation. up How to the that do
problem. is my

:)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: How to roughly associate the values of two numpy arrays, or python lists if necessary

2018-09-23 Thread Peter Otten
Shall, Sydney via Tutor wrote:

> What I want is the following.
> 
> I have:
> > property_a = [1, 6, 2, 4]
> > property_b = [62, 73, 31 102]
> 
> Result should approximately be:
> > property_b = [31, 102, 62, 73]
> 
> That is both lists change in value in exactly the same order.
> 
> Now, this is easy to achieve. I could simply sort both lists is
> ascending order and I would then have an exact alignment of values is
> ascending order. The correlation would be a perfect linear relationship,
> I suppose.
> 
> But my actual scientific problem requires that the correlation should be
> only approximate and I do not know how close to to a perfect correlation
> it should be. So, I need to introduce some lack of good correlation when
> I set up the correlation. How to do that is my problem.
> 
> I hope this helps to clarify what my problem is.

Maybe you could sort the already-sorted property_b again, with some random 
offset:

>>> import itertools
>>> def wiggled(items, sigma):
... counter = itertools.count()
... def key(item): return random.gauss(next(counter), sigma)
... return sorted(items, key=key)
... 
>>> wiggled(range(20), 3)
[0, 5, 2, 4, 1, 6, 7, 8, 3, 9, 11, 10, 13, 14, 16, 12, 18, 17, 19, 15]
>>> wiggled([31, 102, 62, 73], .8)
[102, 31, 62, 73]
>>> wiggled([31, 102, 62, 73], .8)
[31, 102, 62, 73]
>>> wiggled([31, 102, 62, 73], .8)
[31, 102, 62, 73]
>>> wiggled([31, 102, 62, 73], .8)
[31, 62, 102, 73]


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: How to roughly associate the values of two numpy arrays, or python lists if necessary

2018-09-23 Thread Shall, Sydney via Tutor

On 21/09/2018 00:01, Oscar Benjamin wrote:

Sydney wrote and Alan forwarded:



I have, I suspect, an elementary problem that I am too inexperienced to
resolve.

I have two numpy arrays, each representing the values of a specific
property of a set of cells.

Now, I want to associate the two values for each cell, that is for each
index of the numpy array. But I want to associate them ROUGHLY, that
means, APPROXIMATELY, so that there is a weak, linear correlation
between the values representing one property and the values representing
the second property of each individual cell.

Up to now I have used the following procedure.
I have divided each population of values into four segments based on the
value of the standard deviation thus.

1. values > mean + 1 std (sigma)
2. values > mean but < mean + 1 std (sigma)
3. values < mean but > mean + 1 std (sigma)
4. values < mean + 1 std (sigma).

Then I randomly select a value from group 1 for the first property and I
associate it with a randomly selected sample of the second property from
its group 1. And so on through the total population. This gave me a very
rough linear association between the two properties, but I am wondering
whether I can do it in a simpler and better way.



Hi Sydney,

I feel like I would definitely be able to solve your problem if I
understood what you're talking about (I'm sure others here could as well).
Please don't be put off by this but I don't think you've explained it very
well.

Perhaps if you give an example of what the input and output of this
operation is supposed to look like then you would get a response. The
example might look like:

I have these arrays as input:


property_a = [1, 6, 2, 4]
property_b = [6, 3, 4, 6]


Then I want a function that gives me this output


associated_values = myfunction(a, b)
associated_values

[1, 3, 5, 2]

Some explanation why you want this, how you know that's the output you
want, and what any of it means would likely help...

If you already have something that does what you want then it would make
sense to show it but if your code is complicated then please try to
simplify it and use only a small amount of data when showing it here. There
is some advice for posting this kind of thing to a mailing list here:
https://emea01.safelinks.protection.outlook.com/?url=http%3A%2F%2Fsscce.org%2F&data=01%7C01%7Csydney.shall%40kcl.ac.uk%7C77fe09364c79190308d61f4d4112%7C8370cf1416f34c16b83c724071654356%7C0&sdata=DAhLxDli1vM%2BBcRXKemRo0sa%2BVJErJPZ%2Bwy5UHvUR4s%3D&reserved=0

--
Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=01%7C01%7Csydney.shall%40kcl.ac.uk%7C77fe09364c79190308d61f4d4112%7C8370cf1416f34c16b83c724071654356%7C0&sdata=Benb%2BsxqZr1Rhdj8jG81KRurndfNVnBGx0%2B3z9VXd54%3D&reserved=0


Thank you Oscar. Fair comment.

What I want is the following.

I have:
> property_a = [1, 6, 2, 4]
> property_b = [62, 73, 31 102]

Result should approximately be:
> property_b = [31, 102, 62, 73]

That is both lists change in value in exactly the same order.

Now, this is easy to achieve. I could simply sort both lists is 
ascending order and I would then have an exact alignment of values is 
ascending order. The correlation would be a perfect linear relationship, 
I suppose.


But my actual scientific problem requires that the correlation should be 
only approximate and I do not know how close to to a perfect correlation 
it should be. So, I need to introduce some lack of good correlation when 
I set up the correlation. How to do that is my problem.


I hope this helps to clarify what my problem is.

Sydney

--

_

Professor Sydney Shall
Department of Haematology/Oncology
Phone: +(0)2078489200
E-Mail: sydney.shall
[Correspondents outside the College should add @kcl.ac.uk]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: How to roughly associate the values of two numpy arrays, or python lists if necessary

2018-09-20 Thread Oscar Benjamin
Sydney wrote and Alan forwarded:

>
> I have, I suspect, an elementary problem that I am too inexperienced to
> resolve.
>
> I have two numpy arrays, each representing the values of a specific
> property of a set of cells.
>
> Now, I want to associate the two values for each cell, that is for each
> index of the numpy array. But I want to associate them ROUGHLY, that
> means, APPROXIMATELY, so that there is a weak, linear correlation
> between the values representing one property and the values representing
> the second property of each individual cell.
>
> Up to now I have used the following procedure.
> I have divided each population of values into four segments based on the
> value of the standard deviation thus.
>
> 1. values > mean + 1 std (sigma)
> 2. values > mean but < mean + 1 std (sigma)
> 3. values < mean but > mean + 1 std (sigma)
> 4. values < mean + 1 std (sigma).
>
> Then I randomly select a value from group 1 for the first property and I
> associate it with a randomly selected sample of the second property from
> its group 1. And so on through the total population. This gave me a very
> rough linear association between the two properties, but I am wondering
> whether I can do it in a simpler and better way.
>

Hi Sydney,

I feel like I would definitely be able to solve your problem if I
understood what you're talking about (I'm sure others here could as well).
Please don't be put off by this but I don't think you've explained it very
well.

Perhaps if you give an example of what the input and output of this
operation is supposed to look like then you would get a response. The
example might look like:

I have these arrays as input:

>>> property_a = [1, 6, 2, 4]
>>> property_b = [6, 3, 4, 6]

Then I want a function that gives me this output

>>> associated_values = myfunction(a, b)
>>> associated_values
[1, 3, 5, 2]

Some explanation why you want this, how you know that's the output you
want, and what any of it means would likely help...

If you already have something that does what you want then it would make
sense to show it but if your code is complicated then please try to
simplify it and use only a small amount of data when showing it here. There
is some advice for posting this kind of thing to a mailing list here:
http://sscce.org/

--
Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: How to roughly associate the values of two numpy arrays, or python lists if necessary

2018-09-19 Thread Alan Gauld via Tutor
Forwarded to list



I have, I suspect, an elementary problem that I am too inexperienced to 
resolve.

I have two numpy arrays, each representing the values of a specific 
property of a set of cells.

Now, I want to associate the two values for each cell, that is for each 
index of the numpy array. But I want to associate them ROUGHLY, that 
means, APPROXIMATELY, so that there is a weak, linear correlation 
between the values representing one property and the values representing 
the second property of each individual cell.

Up to now I have used the following procedure.
I have divided each population of values into four segments based on the 
value of the standard deviation thus.

1. values > mean + 1 std (sigma)
2. values > mean but < mean + 1 std (sigma)
3. values < mean but > mean + 1 std (sigma)
4. values < mean + 1 std (sigma).

Then I randomly select a value from group 1 for the first property and I 
associate it with a randomly selected sample of the second property from 
its group 1. And so on through the total population. This gave me a very 
rough linear association between the two properties, but I am wondering 
whether I can do it in a simpler and better way.


-- 

Sydney


_

Professor Sydney Shall
Department of Haematology/Oncology
Phone: +(0)2078489200
E-Mail: sydney.shall
[Correspondents outside the College should add @kcl.ac.uk]

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Alan Gauld via Tutor
On 05/09/18 18:12, Chip Wachob wrote:

> In your examples name1 and name2 could be anything that is contained
> in that module.. a variable, function, class, etc..  correct?

Correct. They are just names.

Again a difference between Python and C.
In C a name is a label associated with a memory address
which in turn is associated with a specified data type.

In Python a name is just a name, a key in a dictionary.
It's value is any kind of object and can change throughout
the program's lifetime. A string now, an integer later,
then a list and maybe even a class or instance. Of course,
it's probably not a good idea to change a variables type
too often but it is possible.


-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Chip Wachob
This helps tremendously!

One last question.

In your examples name1 and name2 could be anything that is contained
in that module.. a variable, function, class, etc..  correct?





On Wed, Sep 5, 2018 at 12:58 PM, Alan Gauld via Tutor  wrote:
> On 05/09/18 15:06, Chip Wachob wrote:
>
>> Okay, I think I'm starting to get a handle on the visibility of
>> things.  As you said, much different than C.
>
> Yes. The significant thing is to remember that in
> Python you are importing names. In C you include
> the contents of the file.
>
> #include 
>
> Lets you access everything in the stdio.h file
> as if it were part of your own file.
>
> import sys
>
> Lets you see the sys module but not whats inside it.
> To access whats inside you must use the name as
> a prefix.
>
> The Pytho import idiom
>
> from sys import *
>
> is similar in effect to the C style include
> (although by an entirely different mechanism)
> but is considered bad practice (for the same
> reasons C++ has its scope operator(::))
>
>> Even through the import Adafruit_GPIO as GPIO line exists in the
>> AdafruitInit.py file, which is imported by the import AdafruitInit
>> line in main.py,
>
> The critical conceptual error here is that the
> file is not imported(*), only the name. Importing
> in Python is all about visibility control
>
> (*)In practice although the module is not
> imported into your file it is executed, so any
> new variables, classes and functions are created,
> but their names are not visible in your code
> except via the module name.
>
> Let me revisit the different import styles
> in more detail. Remember we are discussing visibility
> of names not code.
>
>
> ##
> import modulename
>
> This makes modulename visible to the importing module.
> Nothing inside modulename is visible. To access the
> contents you must use modulename as a prefix.
>
> x = modulename.name1
>
> ###
> import modulename as alias
>
> Exactly the same except that you can refer to
> modulename using the (usually shorter) alias.
>
> x = alias.name1
>
> There are a few community standard aliases such as
>
> import numpy as np
> import tkinter as tk
>
> But they are purely conventions, you can use
> any alias you like. For those who enjoy typing
> they could even do
>
> import os as operating_system
>
> And access the functions as
>
> operating_system.listdir('.')
>
> instead of
>
> os.listdir('.')
>
> if they really wanted to...
>
> 
> from module import name1, name2
>
> This imports specific names from within module.
>
> You can now access name1 and name2 directly:
>
> x - name1  # accesses module.name1
>
> But it does NOT import module itself,
> only name1, name2, etc. If you try
>
> x = module.name3
>
> You will get an error about module (not name3!)
> not being recognised.
>
>
> 
> from module import name1 as n1
>
> Same as above but use the alias n1 instead of
> the longer name1.
>
> x = n1   # like x = module.name1
>
> This is very like you doing the following:
>
> from module import name1
> n1 = name1
>
> 
> from module import *
>
> This makes all the names defined in module visible
> within the importing module. Again it does not make
> module itself visible, only the names inside.
>
> This is considered bad practice because if you have
> multiple modules containing the same name (things
> like open() and write() are common then only the
> last name imported will be visible and that can
> lead to unexpected errors.
>
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Alan Gauld via Tutor
On 05/09/18 15:06, Chip Wachob wrote:

> Okay, I think I'm starting to get a handle on the visibility of
> things.  As you said, much different than C.

Yes. The significant thing is to remember that in
Python you are importing names. In C you include
the contents of the file.

#include 

Lets you access everything in the stdio.h file
as if it were part of your own file.

import sys

Lets you see the sys module but not whats inside it.
To access whats inside you must use the name as
a prefix.

The Pytho import idiom

from sys import *

is similar in effect to the C style include
(although by an entirely different mechanism)
but is considered bad practice (for the same
reasons C++ has its scope operator(::))

> Even through the import Adafruit_GPIO as GPIO line exists in the
> AdafruitInit.py file, which is imported by the import AdafruitInit
> line in main.py, 

The critical conceptual error here is that the
file is not imported(*), only the name. Importing
in Python is all about visibility control

(*)In practice although the module is not
imported into your file it is executed, so any
new variables, classes and functions are created,
but their names are not visible in your code
except via the module name.

Let me revisit the different import styles
in more detail. Remember we are discussing visibility
of names not code.


##
import modulename

This makes modulename visible to the importing module.
Nothing inside modulename is visible. To access the
contents you must use modulename as a prefix.

x = modulename.name1

###
import modulename as alias

Exactly the same except that you can refer to
modulename using the (usually shorter) alias.

x = alias.name1

There are a few community standard aliases such as

import numpy as np
import tkinter as tk

But they are purely conventions, you can use
any alias you like. For those who enjoy typing
they could even do

import os as operating_system

And access the functions as

operating_system.listdir('.')

instead of

os.listdir('.')

if they really wanted to...


from module import name1, name2

This imports specific names from within module.

You can now access name1 and name2 directly:

x - name1  # accesses module.name1

But it does NOT import module itself,
only name1, name2, etc. If you try

x = module.name3

You will get an error about module (not name3!)
not being recognised.



from module import name1 as n1

Same as above but use the alias n1 instead of
the longer name1.

x = n1   # like x = module.name1

This is very like you doing the following:

from module import name1
n1 = name1


from module import *

This makes all the names defined in module visible
within the importing module. Again it does not make
module itself visible, only the names inside.

This is considered bad practice because if you have
multiple modules containing the same name (things
like open() and write() are common then only the
last name imported will be visible and that can
lead to unexpected errors.


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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Chip Wachob
Thank you!

Okay, I think I'm starting to get a handle on the visibility of
things.  As you said, much different than C.

Just to confirm that I'm understanding correctly:

Even through the import Adafruit_GPIO as GPIO line exists in the
AdafruitInit.py file, which is imported by the import AdafruitInit
line in main.py, main.py does not automatically inherit the
Adafruit_GPIO.  Which is why you indicate that I need to also import
it in main.py





On Wed, Sep 5, 2018 at 9:42 AM, Alan Gauld  wrote:
> On 05/09/18 14:05, Chip Wachob wrote:
>> # module AdafruitInit.py
>> # from the Adafruit tutorials..
>> import Adafruit_GPIO.FT232H as FT232H
>> import Adafruit_GPIO as GPIO
>>
>> FT232H.use_FT232H()
>>
>> ft232h = FT232H.FT232H()
>>
>> # config settings for the SPI 'machine'
>> spi = FT232.SPI(ft232h, 4, 2, 2, FT232H.MSBFIRST)
>>
>
> That last line created a new variable inside the AdafruitInit module.
> It is not visible anywhere else.
>
>> # module RSI.py
>> import AdafruitInit
>>
>> def write(byte):
>>spi.write(byte)
>
> You use spi but it is not visible. It is inside AdafriuitInit
> so you need to prefix the name (I'd suggest importing
> as an alias!)
>
>AdafruitInit.spi.write(byte)
>
>> # toggle the latch signal
>>ft232h.output(5, GPIO.LOW)
>>ft232h.output(5, GPIO.HIGH)
>
> And the same here. ft232h is a variable inside AdafriotInit,
> so you must prefix it.
>
> BUT GPIO is defined in some other module which
> you will also need to import that
>
> import Adafruit_GPIO as GPIO
>
> adafruitInit.ft232h.output(5, GPIO.LOW)
>
>
> Any name that you try to use must be
> - defined in this module or
> - imported or
> - prefixed with the name of a module that you imported.
>
> If you do not define it in this module you must import
> or prefix.
>
>
>> ---module separator 
>>
>> # module main.py
>> import RSI
>> import AdafruitInit
>>
>> ft232h.setup(5, GPIO.OUT)
>>
>> write(0xAA)
>
> Again you need to use the prefixes (and import GPIO)
>
> AdafruitInit.ft232h.setup(...)
> RSI.write(...)
>
>> The actual error message for the ft232h... line is:
>>
>> NameError: global name 'ft232h' is not defined
>
> Please send the full error text, they contain a lot of useful
> information. In this case the summary line is enough but in
> future we really need the full text.
>
> The name error is because your main module cannpt see
> ft232h defined anywhere - it is inside the other module.
>
> So, my write line should have read?
>> RSI.write(0xAA)
>>
>> Does this mean that I need to call the ft232h like this?
>>
>> AdafruitInit.ft232h.setup(5, GPIO.OUT)
>
> Exactly. And import GPIO too.
>
>> Earlier in the thread you mentioned that there are several ways to
>> import.  Obviously there's small differences between the methods.  If
>> you know of a good resource I can use to get a better understanding /
>
> Since you know C already you should probably just read the official
> tutorial.
> It covers all the different styles.
>
> The only guidance i'll add is to avoid the
>
> from foo import *
>
> style since it easily leads to hard to spot name collisions.
> Only use it for experiments in the >>> prompt.
>
>
> --
> 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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Alan Gauld via Tutor
On 05/09/18 14:05, Chip Wachob wrote:
> # module AdafruitInit.py
> # from the Adafruit tutorials..
> import Adafruit_GPIO.FT232H as FT232H
> import Adafruit_GPIO as GPIO
>
> FT232H.use_FT232H()
>
> ft232h = FT232H.FT232H()
>
> # config settings for the SPI 'machine'
> spi = FT232.SPI(ft232h, 4, 2, 2, FT232H.MSBFIRST)
>

That last line created a new variable inside the AdafruitInit module.
It is not visible anywhere else.

> # module RSI.py
> import AdafruitInit
>
> def write(byte):
>spi.write(byte)

You use spi but it is not visible. It is inside AdafriuitInit
so you need to prefix the name (I'd suggest importing
as an alias!)

   AdafruitInit.spi.write(byte)

> # toggle the latch signal
>ft232h.output(5, GPIO.LOW)
>ft232h.output(5, GPIO.HIGH)

And the same here. ft232h is a variable inside AdafriotInit,
so you must prefix it.

BUT GPIO is defined in some other module which
you will also need to import that

import Adafruit_GPIO as GPIO

adafruitInit.ft232h.output(5, GPIO.LOW)


Any name that you try to use must be
- defined in this module or
- imported or
- prefixed with the name of a module that you imported.

If you do not define it in this module you must import
or prefix.


> ---module separator 
>
> # module main.py
> import RSI
> import AdafruitInit
>
> ft232h.setup(5, GPIO.OUT)
>
> write(0xAA)

Again you need to use the prefixes (and import GPIO)

AdafruitInit.ft232h.setup(...)
RSI.write(...)

> The actual error message for the ft232h... line is:
>
> NameError: global name 'ft232h' is not defined

Please send the full error text, they contain a lot of useful
information. In this case the summary line is enough but in
future we really need the full text.

The name error is because your main module cannpt see
ft232h defined anywhere - it is inside the other module.

So, my write line should have read?
> RSI.write(0xAA)
>
> Does this mean that I need to call the ft232h like this?
>
> AdafruitInit.ft232h.setup(5, GPIO.OUT)

Exactly. And import GPIO too.

> Earlier in the thread you mentioned that there are several ways to
> import.  Obviously there's small differences between the methods.  If
> you know of a good resource I can use to get a better understanding /

Since you know C already you should probably just read the official
tutorial.
It covers all the different styles.

The only guidance i'll add is to avoid the

from foo import *

style since it easily leads to hard to spot name collisions.
Only use it for experiments in the >>> prompt.


-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Chip Wachob
Alan,

Once again, thank you for the feedback and comments.

Revised code snips: Sorry they were not complete.  Several typos while
trying to create the SSCCE version.

# module AdafruitInit.py
# from the Adafruit tutorials..
import Adafruit_GPIO.FT232H as FT232H
import Adafruit_GPIO as GPIO

FT232H.use_FT232H()

ft232h = FT232H.FT232H()

# config settings for the SPI 'machine'
spi = FT232.SPI(ft232h, 4, 2, 2, FT232H.MSBFIRST)

---module separator 

# module RSI.py
import AdafruitInit

def write(byte):
   spi.write(byte)

# toggle the latch signal
   ft232h.output(5, GPIO.LOW)
   ft232h.output(5, GPIO.HIGH)

---module separator 

# module main.py
import RSI
import AdafruitInit

ft232h.setup(5, GPIO.OUT)

write(0xAA)




The actual error message for the ft232h... line is:

NameError: global name 'ft232h' is not defined


So, my write line should have read?

RSI.write(0xAA)

Does this mean that I need to call the ft232h like this?

AdafruitInit.ft232h.setup(5, GPIO.OUT)

And, this is why it is not visible?

I feel like I _thought_ I understood the import statements, but I
guess I didn't and that's what is getting me into trouble.

Earlier in the thread you mentioned that there are several ways to
import.  Obviously there's small differences between the methods.  If
you know of a good resource I can use to get a better understanding /
contrast of the different import types I'll read over it and make sure
I'm using the right one for my situation.

And, at this point, I'm pretty clear on the fact that the script that
runs leaves no trace behind when I exit the call to the interpreter
from the command line.

I appreciate your patience with my questions and foibles.




On Wed, Sep 5, 2018 at 4:53 AM, Alan Gauld via Tutor  wrote:
> On 05/09/18 04:12, Chip Wachob wrote:
>
>> # module RSI.py
>> def write(byte):
>>spi.write(byte)
>
> You don't have any import statements here.
> You need to import spi to use it.
>
>> # toggle the latch signal
>>ft232h.output(5, GPIO.LOW)
>>ft232h.output(5, GPIO.HIGH)
>
> And the same for ft232h
>
>>
>> # module main.py
>> import RSI
>> import AdafruitInit.py
>
> Note you do NOT use the .py extension when
> importing, just the base name.
>
>> ft232.setup(5, GPIO.OUT)
>
> But again you have not imported ft232
> Also I note that you use ft232 here but ft232h elsewhere.
> Is that correct?
>
> You must import any external names that
> you intend to use.
>
>> write(0xAA)
>
> And here you need to prefix with RSI:
>
> import RSI
>
> 
>
> RSI.write()
>
> A Python import is very different to a C include.
> In C you actually include the source text in your
> file so everything inside the file becomes visible.
> In a Python import you add names to a dictionary.
> In this case the only name added is RSI. The code
> inside the RSI module is effectively invisible to
> your main.py, only the name of the module is seen.
> So you must prefix the RSI contents before you use it.
>
>
>> "write()" tells me that
>>
>> "global name 'ft232h' is not defined"
>
> Please always post full error texts, never summarize.
>
>> Regarding permissions.  I'm not sure about the need for sudo, but that
>> was used in the example.
>
> I suspect it's needed because you are accessing
> privileged IO ports. It would not normally be
> needed to run a Python script.
>
>> I had been working most of the day on Friday and the scripts were
>> running fine.
>
> That is the real mystery since the above code
> should not have worked.
>
>> Does some of the FTDI (AdafruitInit.py) remain resident
>
> No, it will be deleted.
>
> --
> 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@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Alan Gauld via Tutor
On 05/09/18 04:12, Chip Wachob wrote:

> # module RSI.py
> def write(byte):
>spi.write(byte)

You don't have any import statements here.
You need to import spi to use it.

> # toggle the latch signal
>ft232h.output(5, GPIO.LOW)
>ft232h.output(5, GPIO.HIGH)

And the same for ft232h

> 
> # module main.py
> import RSI
> import AdafruitInit.py

Note you do NOT use the .py extension when
importing, just the base name.

> ft232.setup(5, GPIO.OUT)

But again you have not imported ft232
Also I note that you use ft232 here but ft232h elsewhere.
Is that correct?

You must import any external names that
you intend to use.

> write(0xAA)

And here you need to prefix with RSI:

import RSI



RSI.write()

A Python import is very different to a C include.
In C you actually include the source text in your
file so everything inside the file becomes visible.
In a Python import you add names to a dictionary.
In this case the only name added is RSI. The code
inside the RSI module is effectively invisible to
your main.py, only the name of the module is seen.
So you must prefix the RSI contents before you use it.


> "write()" tells me that
> 
> "global name 'ft232h' is not defined"

Please always post full error texts, never summarize.

> Regarding permissions.  I'm not sure about the need for sudo, but that
> was used in the example.  

I suspect it's needed because you are accessing
privileged IO ports. It would not normally be
needed to run a Python script.

> I had been working most of the day on Friday and the scripts were
> running fine.  

That is the real mystery since the above code
should not have worked.

> Does some of the FTDI (AdafruitInit.py) remain resident

No, it will be deleted.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Accessing variables from other modules

2018-09-05 Thread Chip Wachob
My apologies.  I hit reply and not reply to all.

Alan,

I think I answered many of your questions in this message to Steven.




-- Forwarded message --
From: Chip Wachob 
Date: Tue, Sep 4, 2018 at 1:48 PM
Subject: Re: [Tutor] Accessing variables from other modules
To: Steven D'Aprano 


Steven,

Thank you.

Responding to your comments in order:

# module AdafruitInit.py
# from the Adafruit tutorials..
import Adafruit_GPIO.FT232H as FT232H
import Adafruit_GPIO as GPIO

FT232H.use_FT232H()

ft232h = FT232H.FT232H()

# config settings for the SPI 'machine'
spi = FT232.SPI(ft232h, 4, 2, 2, FT232H.MSBFIRST)



# module RSI.py
def write(byte):
   spi.write(byte)

# toggle the latch signal
   ft232h.output(5, GPIO.LOW)
   ft232h.output(5, GPIO.HIGH)



# module main.py
import RSI
import AdafruitInit.py

ft232.setup(5, GPIO.OUT)

write(0xAA)


"write()" tells me that

"global name 'ft232h' is not defined"


Regarding permissions.  I'm not sure about the need for sudo, but that
was used in the example.  The script will fail to run without it.  I
can't say for certain that I understand why sudo is required.  It may
have something to do with disabling the "built in" FTDI driver and
enabling the Adafruit version.  I had hoped to just get things
'working' before worrying about trying to get rid of the sudo
requirement.

I had been working most of the day on Friday and the scripts were
running fine.  I was running the scripts from the command line as
noted above (and related to your question re: sudo).  I powered off
the machine Friday night, and started it back up this morning.

Does some of the FTDI (AdafruitInit.py) remain resident even though
I've exited out of the script.  My menu has an entry that will permit
breaking the while() loop and ending the script.



...



On Tue, Sep 4, 2018 at 1:19 PM, Steven D'Aprano  wrote:
> Hi Chip, and welcome!
>
> On Tue, Sep 04, 2018 at 11:10:36AM -0400, Chip Wachob wrote:
>
>> I'll refrain from posting a bunch of code, but here is the 5000 foot view:
>
> Not posting a mountain of code is a great idea, but from 5000 ft away
> we can't see what is going on.
>
> Try posting *a little bit of code*. This is written for Java programmers
> but the principle is the same for Python:
>
> http://sscce.org/
>
> If I had to make a *wild guess* as to what is going on, it would be that
> you have a couple of modules like this:
>
> # Module spam.py
> x = 1  # global variable
> def foo():
> print(x)
>
>
> # Module eggs.py
> import spam
> from spam import x
> foo()  # prints 1, as you expect
> x = 999
> foo()  # still prints 1, instead of 999
>
>
> Is that what is going on? On something different?
>
>
> A few more comments:
>
>> execution looks like this:
>>
>> $ sudo python main.py
>
> Do you really need this to be run with root permissions?
>
>> So, the important questions are:
>>
>> - Was I mislead by the fact that there was a power cycle on the
>> machine and it has now forgotten something that was staying resident
>> when I tested the code on Friday?  Or, does each 'run' of the script
>> start fresh?
>
> Um, yes no maybe?
>
> Was there a power cycle? How were you running the scripts?
>
>
>> - What approach do I need to use to be able to initialize the
>> interface in spi.py and have it be something that is accessible to all
>> the other modules in my project?
>
>
>
>
>>
>> Thank you in advance for your time.
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Argparse Error

2018-08-13 Thread Alan Gauld via Tutor
Forwarding to list since I seem to have messed up the address last time...

 Forwarded Message 
Subject:Re: [Tutor] Argparse Error
Date:   Sun, 12 Aug 2018 23:44:04 +0100
From:   Alan Gauld 
Reply-To:   tutor 
To: Nathan Johnson 



On 12/08/18 19:58, Nathan Johnson wrote:
> Here is the full script that was provided, but I don't know what else
> I'm supposed to do with it except save it in the folder on my D:
> drive, and run in in the cmd prompt like you said.
>

OK, It seems as if there are some other arguments that you need
to provide. The one causing the issue here is fileout - ie the output
filename.

Now, its not clear what else needs to be specified, you probably
should ask the author. We are not really best qualified to decipher
another coders code!

But it looks like values for interval, shift and skip are required
too - although I've no idea what they mean!

What the code does tell us are the options you need to use,
so the command should look like:


python D:\Python\bytsh.py -o output.mp4 -i ??? -s ??? -k ???
D:\Video\test.mp4

Where you will need to figure out what kind of values to use for the ???
parts.

>
> import argparse
>
>
> parser = argparse.ArgumentParser(description="Shift bytes in a file")
>
> parser.add_argument("file", help="input file")
>
> parser.add_argument("-o", "--output", help="output file")
>
> parser.add_argument("-i", "--interval", help="byte interval",
> default=1000)
>
> parser.add_argument("-s", "--shift", help="size of shift", default=4)
>
> parser.add_argument("-k", "--skip", help="size of initial skip
> offset", default=128)
>
> args = parser.parse_args()
>
>
> filein = args.file
>
> fileout = args.output
>
> interval = int(args.interval)
>
> shift = int(args.shift)
>
> skip = int(args.skip)
>
>
> f = open(filein, "rb")
>
> out = open(fileout, "w+b")
>
>
> out.write( f.read1(skip) )
>
>
> while True:
>
> byte = f.read1(1)
>
> if byte == b'':
>
> break
>
>

I suspect the three lines above should be indented under the whilew like
this:

while True:
    byte = f.read1(1)
    if byte == "b":
 break


But I don't know if any of the lines below should be indented too...
The next 3 could be. And maybe they are in the original and its
the mail system thats destroyed them?

You need to post in plain text for us to accurately see the
original indentation levels (which are critically important in Python)


> lbfr = f.read(shift)
>
> rbfr = f.read(interval-shift)
>
> out.write(lbfr + byte + rbfr)
>
>
> f.close()
>
> out.close()
>
>
> This is what the cmd prompt says when I type in the new command
>
> C:\Users\natha> python D:\Python\bytsh.py D:\Video\test.mp4
> Traceback (most recent call last):
>   File "D:\Python\bytsh.py", line 18, in 
>     out = open(fileout, "w+b")
> TypeError: expected str, bytes or os.PathLike object, not NoneType
>
HTH

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

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Syntax question

2018-08-09 Thread Abdur-Rahmaan Janhangeer
missed reply all

Abdur-Rahmaan Janhangeer
https://github.com/Abdur-rahmaanJ
Mauritius

-- Forwarded message -
From: Abdur-Rahmaan Janhangeer 
Date: Thu, 9 Aug 2018, 11:56
Subject: Re: [Tutor] Syntax question
To: Matthew Polack 


wheatbutton = Button(root, text="Wheat", fg="black", bg="yellow",
command=wheatwords)

Abdur-Rahmaan Janhangeer
https://github.com/Abdur-rahmaanJ
Mauritius
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: File handling Tab separated files

2018-04-19 Thread Brian Lockwood

>> 
>> Here are some fixes
>> 
>> filename is a variable and hence should not be in quotes.
>> file_ is then called ‘f’ on the next line.
>> The indenting is a bit wrong but this may just be your email.
>> 
>> the line read_data … should be followed by something that appends the 
>> read_data to “object” which should be declared earlier.
>> 
>>> On 19 Apr 2018, at 09:45, Niharika Jakhar >> > wrote:
>>> 
>>> Hi
>>> I want to store a file from BioGRID database (tab separated file, big data)
>>> into a data structure(I prefer lists, please let me know if another would
>>> be better) and I am trying to print the objects.
>>> Here’s my code:
>>> class BioGRIDReader:
>>>   def __init__(self, filename):
>>>   with open('filename', 'r') as file_:
>>>   read_data = f.read()
>>>   for i in file_ :
>>>   read_data = (i.split('\t'))
>>>   return (objects[:100])
>>> 
>>> a = BioGRIDReader
>>> print (a.__init__(test_biogrid.txt))
>>> 
>>> 
>>> 
>>> 
>>> Here's what the terminal says:
>>> Traceback (most recent call last):
>>> File "./BioGRIDReader.py", line 23, in 
>>>   print (a.__init__(test_biogrid.txt))
>>> NameError: name 'test_biogrid' is not defined
>>> 
>>> The file named test_biogrid.txt do exist in the same folder as this program.
>>> 
>>> I am unable to go further with this code. Kindly help me out.
>>> 
>>> 
>>> Thanks and regards
>>> NIHARIKA
>>> ___
>>> Tutor maillist  -  Tutor@python.org 
>>> To unsubscribe or change subscription options:
>>> https://mail.python.org/mailman/listinfo/tutor 
>>> 
>> 
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: How to Load Every Revised Wikipedia Page Revision

2018-02-21 Thread dbosah




Sent from my T-Mobile 4G LTE Device
 Original message From: Daniel Bosah  Date: 
2/19/18  3:50 PM  (GMT-05:00) To: tutor@python.org Subject: How to Load Every 
Revised Wikipedia Page Revision 
Good day,
I'm doing research for a compsci group. I have a script that is supposed to 
load every revised page of a wikipedia article on FDR.
This script is supposed to, in while loop access the wikipedia api and using 
the request library, access the apiif the continue is in the requestsupdate the 
query dict with continuekeep updating until there are no more 'continue' ( or 
until the API load limit is reached )elsebreak
Here is the code:


def GetRevisions():    url = "https://en.wikipedia.org/w/api.php"; #gets the api 
and sets it to a variable    query = {    "format": "json",    "action": 
"query",    "titles": "Franklin D. Roosevelt",    "prop": "revisions",    
"rvlimit": 500,    }# sets up a dictionary of the arguments of the query 
    while True: # in  a while loop        r = requests.get(url, params = 
query).json() # does a request call for the url in the parameters of the query  
      print repr(r) #repr gets the "offical" string output of a object        
if 'continue' in r: ## while in the loop, if the keyword is in "r"            
query.update(r['continue']) # updates the dictionary to include continue in it, 
and keeps on printing out all instances of 'continue"        else: # else       
    break # quit loop


I want to load every page version with the revisions of the wikipedia page, not 
just the info about the page revision. How can I go about that?

Thanks

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: fractions from Fractions

2018-02-06 Thread Wolfgang Maier

On 06.02.2018 10:53, Alan Gauld via Tutor wrote:


You would have needed something like

fraction = Fraction(input('>'))

Assuming Fraction has a string based constructor which
I don't think it does. I really don't think Fraction
helps you here.


Oh, most certainly it has - though it may accept more forms of input 
than the OP needs/wants:


>>> from fractions import Fraction
>>> Fraction('2/3')
Fraction(2, 3)
>>> Fraction('2.3')
Fraction(23, 10)
>>> Fraction('2e-3')
Fraction(1, 500)
>>>

Since fractions is pure Python it may also be instructive to study its 
source:

https://github.com/python/cpython/blob/master/Lib/fractions.py

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: fractions from Fractions

2018-02-06 Thread Alan Gauld via Tutor
On 06/02/18 09:26, Alan Gauld via Tutor wrote:
> Forwarding to list, please always use Reply ALL or Reply LIst to send
> mail to the list.
> 

> What input did you use and what output did you get?
> 
> Input 239/30  --->  7 1 29
> Input 415/93  --->  4 2 6 7
> 
> So far as I can tell your algorithm is correct, although
> I'm not sure why you limit it to values greater than 1?
> 
> The problem suggests to do so and the wiki on Finite simple continued
> fractions showed examples also greater than one.  Upon consideration, i
> suppose that being greater than one is not a requirement but really is
> not of consequence to the insight I am seeking.

It depends on how the PyCharm "checker" works.
If it uses a test value less than 1 it will fail the test.

> But is it perhaps the format of the output that Pycharm
> objects to?
> 
> No, the format required is for the elements of the list to appear on one
> line separated by a space.

Do you have the exact wording of the requirements?
Or even a url to the PyCharm site for this specific problem?

>> I think I know the source of the trouble.
> Would you like to tell us?
> 
> My input is a string which I convert to num and den.  The problem ask
> specifically that the input format be "A line with an fraction in the
> "numerator/denominator" format and I am interpreting this to mean some
> kind of application of the Fraction module.  But that is just a wild
> guess and is what I was hoping I could get some insight on.

I don't think so, your conversion is doing the same job.

Personally I'd have used split() rather than finding
the index and slicing

num,den = [int(n) for n in fraction.split('/')]

But under the covers its doing much the same as your code.

>> I have tried importing fractions from Fraction
> 
> And what happened?
> 
> Not much.  I just bungled something:
> fraction = input(Fraction(numerator, denominator)

You would have needed something like

fraction = Fraction(input('>'))

Assuming Fraction has a string based constructor which
I don't think it does. I really don't think Fraction
helps you here.

>> while num > den and den != 0:

I'd let it handle numbers less than 1 by converting
the while loop:

while den > 0


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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: fractions from Fractions

2018-02-06 Thread Alan Gauld via Tutor
Forwarding to list, please always use Reply ALL or Reply LIst to send
mail to the list.



-Original Message-
From: Alan Gauld via Tutor 
To: tutor 
Sent: Mon, Feb 5, 2018 4:50 am
Subject: Re: [Tutor] fractions from Fractions

On 05/02/18 04:11, Rex Florian via Tutor wrote:

> The problem is one of the PyCharm problems and when I
> use the check feature it tells me my answer is incorrect.

What input did you use and what output did you get?

Input 239/30  --->  7 1 29
Input 415/93  --->  4 2 6 7

So far as I can tell your algorithm is correct, although
I'm not sure why you limit it to values greater than 1?

The problem suggests to do so and the wiki on Finite simple continued
fractions showed examples also greater than one.  Upon consideration, i
suppose that being greater than one is not a requirement but really is
not of consequence to the insight I am seeking.

But is it perhaps the format of the output that Pycharm
objects to?

No, the format required is for the elements of the list to appear on one
line separated by a space.

> I think I know the source of the trouble.

Would you like to tell us?

My input is a string which I convert to num and den.  The problem ask
specifically that the input format be "A line with an fraction in the
"numerator/denominator" format and I am interpreting this to mean some
kind of application of the Fraction module.  But that is just a wild
guess and is what I was hoping I could get some insight on.

So, is there away with using the Fraction module to input a fraction
without having to go through the int conversions that my code employees?

> I have tried importing fractions from Fraction

And what happened?

Not much.  I just bungled something:
fraction = input(Fraction(numerator, denominator)
Please don't scold me.  It was late and I was fighting the flu and  
and ...

(I assume you mean you tried importing Fraction from fractions)
Although you don't really need it for this problem.

I agree I do not really need to for this problem but am just trying to
see if I could input a fraction that would not need to be processed like
my program does.

> fraction = input()
> # define list for holding coefficients
> coef = []
>
> # find the index where the / is
> slash = fraction.find('/')
> # extract the string num and den and convert them to integers
> num = int(fraction[0:slash])
> den = int(fraction[slash + 1:])
>
> while num > den and den != 0:
> mod = num % den
> a = num // den
> coef.append(a)
> num = den
> den = mod
> for i in coef:
> print(i, end=' ')


-- 
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@python.org 
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Need help with reading and cleaning CSV files for a class

2018-01-29 Thread Neil Cerutti
On 2018-01-28, Geoff Hancock  wrote:
> Good day-
> I'm in a difficult situation.
> I have been asked to help teach students how to clean up a CSV
> file in Python.

Can you give an example of the kind of thing you need to teach?

It is malformed csv that has to be changed into well-formed?

That's sounds like a fun and challenging problem.

-- 
Neil Cerutti

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Need help with reading and cleaning CSV files for a class

2018-01-28 Thread Alan Gauld via Tutor
On 28/01/18 13:36, Geoff Hancock wrote:
> Good day-

> I have been asked to help teach students how to clean up a CSV file in
> Python.

I'm not sure what you mean by "clean up" a CSV file.
If the file is malformed then turning it into a well
formed CSV file is a non trivial text processing task.

> Tomorrow I have to show students how to get a CSV file and write code to
> clean and parse it.

Parsing it is easy, and the python.org CSV module documentation
includes many examples, so I'd start there. (I'd also show your
students that page as a starter too, since learning to go to the
documentation is a good thing.)

Maybe structure the class around analyzing those examples
then trying some of your own?

The easiest way to generate a non trivial CSV file is probably
to save a spreadsheet from Excel...

> I understand the process--BUT I don't know how to do it!
> What I'm looking for is a simple
> Step 1
> Step 2
> Step 3 etc

Umm, I'm not sure what you need here.
A CSV file is opened as per a normal file - do you know how to do that?

Don't forget to include the DictReader too because it is often
better for extracting a sub set of the CSV fields.

If you are covering writing CSV files too - although thats
less common from Python, you also have the writer and
DictWriter classes, and although they do have examples
there isn't as much there.

Finally a fun thing todo in a classroom environment is to
get the students to buddy up and create a CSV file, then
pass it to their buddy and get them to decode it.

You could also try getting them to read a CSV file the hard
way using string handling methods alone, that way the advantages
of the CSV tools are more obvious to them!

It depends how much time you have. FOr a single study session
I'd go with reviewing the CSV module plus a "real world" example.

This assumes they even know what a CSV file is. If not, half
the lesson could be taken up on the file structure etc before
you even get to the code stuff.


-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Need help with reading and cleaning CSV files for a class

2018-01-28 Thread leam hall
On Sun, Jan 28, 2018 at 8:36 AM, Geoff Hancock  wrote:
> Good day-
> I'm in a difficult situation.
> I have been asked to help teach students how to clean up a CSV file in
> Python.
> The job has fallen to me because the teacher of the course is out on
> emergency leave and I just found out.
> Tomorrow I have to show students how to get a CSV file and write code to
> clean and parse it.
>
> I understand the process--BUT I don't know how to do it!
> What I'm looking for is a simple
> Step 1
> Step 2
> Step 3 etc
> I'm running the latest version of Python and am running on Windows
> Can anyone assist?
>
> Much appreciate the time
> JGH


Geoff, I'm not that great a coder but here's where I would start.
Assume a file name "gang_draft.csv" that is colon delimited since I'm
working on stuff for an RPG session.  :)



file = open('gang_draft.csv', 'r')
for line in file:
  line = line.strip()
  line_array = line.split(':')
  print(line_array[1])



Where I have print you can do whatever cleanup you like. Then either
print specific columns or join them back into a string.

Hope that helps start you in the right direction. Others here will
likely come up with better solutions.

Leam
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Need help with reading and cleaning CSV files for a class

2018-01-28 Thread Geoff Hancock
Good day-
I'm in a difficult situation.
I have been asked to help teach students how to clean up a CSV file in
Python.
The job has fallen to me because the teacher of the course is out on
emergency leave and I just found out.
Tomorrow I have to show students how to get a CSV file and write code to
clean and parse it.

I understand the process--BUT I don't know how to do it!
What I'm looking for is a simple
Step 1
Step 2
Step 3 etc
I'm running the latest version of Python and am running on Windows
Can anyone assist?

Much appreciate the time
JGH
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: print a for loop system call

2018-01-20 Thread Alan Gauld via Tutor
On 20/01/18 18:26, Derek Smith wrote:

> import os
> import sys
> from subprocess import Popen, PIPE
> 
> pipe = Popen('lsdev -c tape', shell=True, stdout=PIPE)
> 
> for dev in pipe.stdout :
> print ( dev.strip().split()[0].decode() )## A ##

This is OK

> # print ( dev.strip().split().decode()[0] ) ## B ##

This tries to decode a list which won't work.
split() returns a list.
You want to apply decode to a string,
specifically the first string that split produces,
so it is correct as in option A.

If in doubt split the line up and print each
component as you create it:

for dev in pipe.stdout :
print( dev.strip() )
print( dev.strip().split())
print( devb.strip().split()[0])
print( dev.strip().split()[0].decode() )



> And if I try to store in an array using
> 
> rmts = [ dev.strip().split()[0].decode() ]
> 
> it only stores the last line when there are over 100 lines.

Wrong, it stores every line as it comes to it.
But, since you create a new list each time you
throw way the previous one. Only the last list
is preserved, but they were all stored, albeit
briefly...

You need to append() to a list, something like:

aList = []
for dev in
   process dev
   aList.append(result)

Or as a list comprehension:

aList = [process(dev) for dev in ]

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: print a for loop system call

2018-01-20 Thread Derek Smith


Sent from my iPhone

Begin forwarded message:

From: Derek Smith 
mailto:dereksm...@racksquared.com>>
Date: January 19, 2018 at 4:01:58 PM EST
To: "tutor-requ...@python.org" 
mailto:tutor-requ...@python.org>>
Subject: print a for loop system call

Why does A work but B does not?


#!/usr/bin/env python3

import os
import sys
from subprocess import Popen, PIPE

pipe = Popen('lsdev -c tape', shell=True, stdout=PIPE)

for dev in pipe.stdout :
print ( dev.strip().split()[0].decode() )## A ##
# print ( dev.strip().split().decode()[0] ) ## B ##


And if I try to store in an array using

rmts = [ dev.strip().split()[0].decode() ]

it only stores the last line when there are over 100 lines.

Sample line looks like

rmt144 Available 04-T1-01 LTO Ultrium Tape Drive (FCP)

thank you!

Derek Smith  |  Unix/TSM Administrator  | Racksquared Data Centers
':  614-437-4983 * 325 East Spring Street, Columbus, OH 43215
::  dereksm...@racksquared.com  *: 
www.racksquared.com |  
www.racksquared.jobs

[cid:image003.png@01D2E9AA.1B9CF8F0]

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: checking connection to internet until success

2018-01-02 Thread Alan Gauld via Tutor
Forwarding to list...



 Forwarded Message 
Subject:Re: [Tutor] checking connection to internet until success
Date:   Wed, 3 Jan 2018 01:35:18 +0100
From:   Pi 
To: Alan Gauld 



10 months ago i wrote application using time from OS (Windows 7), but my 
alpha tester found how to trick my app. Thats why i need to use date 
from web. And success of new application is when code will know, that 
computer is connected to web and can get actual date.


On 02.01.2018  17:36, Alan Gauld via Tutor wrote:
> On 01/01/18 21:38, Pi wrote:
>> with this code i am getting actual date from internet. I need correct
>> date, because i am not sure this set on computer is right.
> The first obvious pointto make is that all modern OS come
> with an option to read the date/time from an internet time
> server so this is the correct solution to your problem
> rather than writing a web scraper. At the very least you
> should access a time server directly rather than scrape
> a web site. (try the ntplib module)
>
> But if you do want to try doing it yourself...
>
>> import requests, time
>>
>> try:
>>       OnLineDate = requests.get("http://just-the-time.appspot.com";).text[:10]
>>       OffLineDate = time.strftime("%Y-%m-%d")>
>>       if OnLineDate == OffLineDate:
>>           do_something
>>       else:
>>           do_something_else
>> except requests.ConnectionError:
>>       print("Can not connect.")
>>
>>
>> But this code is run once. And i am stuck. Tries with while loop doesnt
>> took any advance.
> WE need to see what doesn't work to comment. A while loop
> with a suitable sleep() should work.
>
> But again it's probably better to use the OS to set up
> a timed job.
>
> On Unix this is done either with 'cron' or 'at'.
> On Windows I believe 'at' is the tool.
> There are other schedulers available too with GUIs etc.
>
>> how check connection to internet to check for every lets say 30 seconds
>> until success?
> What is success? When the times match? Or when they don't?
> Or just whenever you succesfully connect?
>


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: (no subject)

2017-11-12 Thread Alan Gauld via Tutor
Forwarding to the list...






From:   RRRoy BBBean 
Organisation:   DDDead MMMail
To: Alan Gauld , tutor@python.org



On Sun, 2017-11-12 at 23:06 +, Alan Gauld via Tutor wrote:
> On 12/11/17 15:54, 劉權陞 wrote:
...
> Can you tell us what language this is?
> Or better still post an English translation?
> That's what most of us speak on this list...
...
It's Chinese. Google Translate does a decent job with Chinese, much
better than Korean at least.

> I encountered some problems when using closure.
> For example, a simple example,
>
> def f1 (a):
> def f2 (b):
> return a + b
> return f2
>
> f1 = f1 (10)
>
> This time f1 conflict, is this normal?

It appears to be a question about currying in Python?


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Python programming for the absolute beginner

2017-10-01 Thread boB Stepp
-- Forwarded message --
From: Howard B 
Date: Sun, Oct 1, 2017 at 2:20 PM
Subject: Re: [Tutor] Python programming for the absolute beginner
To: boB Stepp 


The 2010 copyright version, ISBN 978-1-4354-5500-9, discusses installing
Python 3.1 (main text on page 5, and Appendix A on page 405).  You will be
able to follow the book using any Python 3.x.

Consider installing Python 3.6 (the latest version) from Anaconda --
available completely free and for all operating systems.  This is a well
supported and commonly used package.
https://www.anaconda.com/download/

The installation also includes the Spyder and Jupyter development
environments, which you may find useful.

On Sat, Sep 30, 2017 at 7:59 AM, boB Stepp  wrote:

> On Fri, Sep 29, 2017 at 1:20 PM, Alan Gauld via Tutor 
> wrote:
> > On 29/09/17 08:51, Peter Collidge wrote:
> >> I have borrowed the above book from my local library but I believe it
> was
> >> written in 2010 and as a result I am having difficulty in deciding which
> >> version of Python to download.
> >> Can anyone help?
> >
> > If you want to follow the book use the version the book
> > uses - probably 2.6 or something close?
>
> I no longer have a copy of this book, but I am fairly certain it uses
> an early version of Python 3.  The main problem, though, is it uses a
> customized version of Pygame for its later gaming code called
> Livewires, so that would have to be Python-version-compatible.  IIRC,
> the author had a download site where you could get the whole package
> together:  correct Python version used in book, correct Livewires
> version, etc., and that this was addressed in the book (Maybe an
> appendix?  Or the first get things setup chapter?  Can't remember for
> sure.)
>
> If the OP goes on to use the sequel to this book, named "More Python
> Programming for the Absolute Beginner" (By a different author.),
> *that* book uses straight-up Pygame, again with an early version of
> Python 3.  Again, I don't think there will be any problems with the
> exact version of Python 3 used as long as the version of Pygame is
> compatible with the chosen Python.
>
>
>
> --
> boB
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>




-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: "Path tree"

2017-08-14 Thread Martin A. Brown

Hello and good afternoon,

The image:

> http://imgur.com/a/CwA2G

To me, this looks like a 'graph', which is a more general data 
structure -- it does not look like a 'tree' (in the computer-science 
meaning of the term, anyway).

For purposes of all of my comments and answers below, I confess that 
I completely ignored the (x, y) in the image, because it seemed like 
every node ('dot') in your image was decorated with that.  See 
question(s) at the bottom of my message.

>> So in modeling this in your program you need to describe not just the
>> x,y coordinates, but also the connections. point 1 can only reach point
>> 2, so it has one link.  point 2 can reach 3 and 5, so two links.
>>
>> How can you describe this in your data model?

>I dont know what a data model is :(

'Data model' is a term to describe how you represent the world in 
your computer program.  Clearly, you have a question about the world 
and you want to use the computer to solve that question.  How do you 
do this?  Well, you create something in a computer language that 
tries to capture the important parts of the world for solving your 
problem.

Defining the data model in any problem is one of the great 
challenges of this game with computers that many of us play.  You 
gain experience simply by trying to solve problems.  (Sometimes, 
modelling the problem is harder than solving the problem.)

>I am thinking with one entry, I can have (x,y,z). Z is probably a 
>list and it says to what point it connects to. so it's a list of 
>lists. The problem then becomes: how do I generate a list of 
>possible routes? So I'll potentially have a very big list of routes 
>and then I choose the shortest one?

With your description of what you are looking to solve, my eye was 
drawn to the terms "list of possible routes" and "shortest [path]", 
it seems (that somebody has given you or) you have a classic graph 
problem.

>Please look at the picture attached: Those dots are coordinates of 
>(x,y), and this tree can be thought of as a list of tuples, with 
>each tuple consisting of (x,y).

I found this sentence the most confusing part of your description of 
the problem that you posted a day or two ago.  I'm still a bit 
confused, but if I ignore the above sentence entirely and focus on 
the rest of your questions, I think I know what you are asking.



Here are some things that confused me:

  * you used the word 'tree' which has a special meaning when 
talking about data structures; a tree is a special form of 
one class of graph
  * you used the word 'dots' because you were looking at a drawing 
on a whiteboard, where many of us were thinking in more 
abstract terms (well, I was, at least); so the word 'dots' meant 
nothing to me until I saw your picture and realized that, to 
you, these represented 'nodes' or 'vertices' (plural of 
'vertex') in a 'graph' (data structure terminology)
  * you talked about 'coordinates' which suggests a measurable 
geometric space -- I think you actually were trying to express 
the notion of graph 'edges' (but I'm not sure! see below)

I was interested in your question (when you originally posted it), 
but couldn't figure out what you were actually trying to do and also 
did not understand what your real question was, so I would not have 
understood except that you posted the picture.

So, your follow-ups helped clarify that you are actually searching 
for data structure tools like the third-party graph library called 
networkx [0].

And, of course, I'll readily admit that sometimes expressing the 
problem in domain-specific or domain-relevant language is harder 
than solving the actual problem.



>Now I am trying to make a function go through this list of tuples 
>and then return the "path." to go from, say, 4 to 8. If I simply 
>compute for the dot for shortest distance, then the solution would 
>be to go from 4 to 8 direct, but that doesn't work, because the 
>correct solution should have been 4,3,2,5,6,8.

OK, so if the solution is 4,3,2,5,6,8, then your problem is a 
shortest path sort of graph theory problem and you can use the 
networkx library which has a huge number of tools for dealing with 
graphs (of many forms).

Below is a tailor-made example of how to model your picture in graph 
form using the networkx library.  My solution creates a data model 
representation of your graph (from your image) and then lists out 
the nodes ('dots'), the edges (lines connecting the dots) and then 
tries to find whether there's a path from node 4 to node 8.  Since 
there is a path from node 4 to node 8, it will print out the 
shortest such path.  You should recognize the answer:

Printed to STDOUT from my function below:

  Graph has nodes: [1, 2, 3, 4, 5, 6, 7, 8]
  Graph has edges: [(1, 2), (2, 3), (2, 5), (3, 4), (5, 6), (5, 7), (6, 8)]
  If there is a path in this graph from node 4 to node 8: True
  Path from 4 to 8: [4, 3, 2, 5, 6, 8]

>I am trying to formulate a "path-finding" fu

Re: [Tutor] Fwd: Re: "Path tree"

2017-08-14 Thread Michael C
I dont know what a data model is :(
I am thinking with one entry, I can have (x,y,z). Z is probably a list and
it says to what point it connects to. so it's a list of lists.
The problem then becomes: how do I generate a list of possible routes?
So I'll potentially have a very big list of routes and then I choose the
shortest one?



On Mon, Aug 14, 2017 at 3:31 PM, Mats Wichmann  wrote:

> On 08/14/2017 03:06 PM, Alan Gauld via Tutor wrote:
> >
> > Forwarding to the list.
> >
> >  Forwarded Message 
> >
> >
> >
> >
> > pic
> > http://imgur.com/a/CwA2G
> >
> > On Mon, Aug 14, 2017 at 8:55 AM, Alan Gauld via Tutor  > > wrote:
> >
> > On 13/08/17 21:07, Michael C wrote:
> >
> > > Please look at the picture attached:
>
>
> So in modeling this in your program you need to describe not just the
> x,y coordinates, but also the connections. point 1 can only reach point
> 2, so it has one link.  point 2 can reach 3 and 5, so two links. How can
> you describe this in your data model?
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: "Path tree"

2017-08-14 Thread Mats Wichmann
On 08/14/2017 03:06 PM, Alan Gauld via Tutor wrote:
> 
> Forwarding to the list.
> 
>  Forwarded Message 
> 
> 
> 
> 
> pic
> http://imgur.com/a/CwA2G
> 
> On Mon, Aug 14, 2017 at 8:55 AM, Alan Gauld via Tutor  > wrote:
> 
> On 13/08/17 21:07, Michael C wrote:
> 
> > Please look at the picture attached:


So in modeling this in your program you need to describe not just the
x,y coordinates, but also the connections. point 1 can only reach point
2, so it has one link.  point 2 can reach 3 and 5, so two links. How can
you describe this in your data model?


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: "Path tree"

2017-08-14 Thread Alan Gauld via Tutor

Forwarding to the list.

 Forwarded Message 




pic
http://imgur.com/a/CwA2G

On Mon, Aug 14, 2017 at 8:55 AM, Alan Gauld via Tutor mailto:tutor@python.org>> wrote:

On 13/08/17 21:07, Michael C wrote:

> Please look at the picture attached:

This is a text mailing list, no binary attachments allowed.
The server strips them off.

You need to put it on a web site and provide a link.


> consisting of (x,y).  Now I am trying to make a function go
through this
> list of tuples and then return the "path." to go from, say, 4 to 8.

> How do I do this?

Do you know how to do it mathematically - eg with pen and paper?
If so its a matter of transcribing the algorithm into python
code. But if you don't know the background math, that's
where you need to start. Find the algorithm first.



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld

Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



___
Tutor maillist  -  Tutor@python.org 
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: basic decorator question

2017-07-24 Thread Alan Gauld
Bah, Forgot to ReplyAll...



 Forwarded Message 

On 24/07/17 15:33, bruce wrote:

> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? 

Yes and classes too if you want. A decorator is just a
standard function in all respects. The only thing that makes
it a decorator is that it takes a function as input and returns
a function as a result (ie it observes the decorator protocol).
Internally it can do anything that is legal in any function,
including creating as many inner functions and data structures
and classes as it wants.

> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?

The calling sequence is just like any other code, it starts
at the top and follows the program control logic until it
either hits a return statement of falls off the bottom
(implicitly returning None). Note that the inner functions
do not need to be part of the returned function, they could
just be there to create some fixed value that is then stored
and used in the returned function.

eg:

def f(g):
 def h(): return 42
 myValue = h()
 def z():
   return myValue
 return z

f() is a decorator that takes a function g. It uses an
internal function h() to calculate a value. It then creates
a second inner function z() which returns that value.
Finally the decorator returns z. Notice that neither g()
nor h() are used in the returned function z().

You would use it like so:

def aFunc():
   return 666

always42 = f(aFunc)
print( always42() )

OR

@f
def aFunc() :return 666

print(aFunc())   # --> prints 42 !

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

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Python Help

2017-07-23 Thread Alan Gauld via Tutor
Forwarding to list



 Forwarded Message 

I did use the pip command and am attempting to add the files to my
python path. I used
 import sys
sys.path.append("/Users/Jim/Documents/illustris_python")

and that worked. I even checked to make sure the files were there 


import sys
print (sys.path)

['', '/Users/Jim/anaconda/lib/python36.zip',
'/Users/Jim/anaconda/lib/python3.6',
'/Users/Jim/anaconda/lib/python3.6/lib-dynload',
'/Users/Jim/anaconda/lib/python3.6/site-packages',
'/Users/Jim/anaconda/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',
'/Users/Jim/anaconda/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
'/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']

the file is clearly there but when i try to do import illustris_python
as il it still can't find the module. 

I also figured that I need to manually export to python path so i tried:
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
  File "", line 1
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
^
SyntaxError: invalid syntax

I got invalid syntax... using a mac os x

I tried typing in terminal open .bash_profile and telling it to export
the python path in there like some others recommended but in terminal it
is giving me an error message for that... it must not be the right
command for the shell.

Winonah

On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson mailto:c...@zip.com.au>> wrote:

On 23Jul2017 00:20, Alan Gauld mailto:alan.ga...@yahoo.co.uk>> wrote:

On 22/07/17 19:14, Winonah Ojanen wrote:

using python with anaconda in jupiter notebook. However, I
am having


Usual caveat: The tutor list is targeted at the standard library
so any help for non standard library modules is best sought from
the library support fora. In this case that includes the SciPy forum
and any illustris one.


Though arguably the OP's problem is an import issue, not really
module specific.

That having been said, I'll take a guess...

$ mkdir Illustris-3
$ mkdir Illustris-3/groups_135

Are these folders in your PYTHONPATH? If not Python will not
find them.

import illustris_python as il

---
ModuleNotFoundError   Traceback (most
recent call last)


The OP cded into the new dir; I'd normally expect things to be found
if the module was a local file/dir. However...

For some reason the computer is not recognizing this as a
file on my
computer. The CCA folks says this is a coding problem and
not an illustris
problem. any ideas to get me past this? I may also need help
getting
farther into the download process.


I just ran the OP's download command:

 wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
--content-disposition --header="API-Key:
d522db2e1b33e36d3b365cc9ac1c2c5d"

"http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api

"

This doesn't seem to download any Python code at all. It does get a
couple of HDF files, presumably with data to work with.

So the issue is initially that the module isn't present anywhere.
Looking at the instructions cited
>, they only
cover fetching som data and working; they presume the software is
already present. I don't immediately see actual software
installation instructions, and it is not presented in PyPI.

Most like the OP will have to install the software directly from:

 https://bitbucket.org/illustris/illustris_python


This command:

 hg clone
https://bitbucket.org/illustris/stris_pythonillustris_python


should produce an "illustris_python" in the current directory, and
then her import command will find it.

However, there are other prerequisites. This pip command:

 pip install h5py numpy

seems to resolve them. The OP will need to use Python 2 because the
module seems to rely on a relative import (for its "util.py" file).

Cheers,
Cameron Simpson mailto:c...@zip.com.au>>

___
Tutor maillist  -  Tutor@python.org 
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Python Help

2017-07-23 Thread Alan Gauld via Tutor

Forwarding to list,
please use ReplyAll or ReplyList when responding to the list.


 Forwarded Message 

I also tried the correct command for the mac ox s in terminal shell,
running:

Jims-MacBook-Pro-2:~ Jim$
PYTHONPATH="/Users/Jim/Documents/illustris_python:$PYTHONPATH

> export PYTHONPATH


no error messages there but it is still not finding the module through
python.

Winonah


On Sun, Jul 23, 2017 at 1:34 PM, Winonah Ojanen mailto:winonah1...@gmail.com>> wrote:

I did use the pip command and am attempting to add the files to my
python path. I used
 import sys
sys.path.append("/Users/Jim/Documents/illustris_python")

and that worked. I even checked to make sure the files were there 


import sys
print (sys.path)

['', '/Users/Jim/anaconda/lib/python36.zip',
'/Users/Jim/anaconda/lib/python3.6',
'/Users/Jim/anaconda/lib/python3.6/lib-dynload',
'/Users/Jim/anaconda/lib/python3.6/site-packages',
'/Users/Jim/anaconda/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',

'/Users/Jim/anaconda/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
'/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']

the file is clearly there but when i try to do import
illustris_python as il it still can't find the module.


Note that only shows the folder is in the path.

What does an 'ls' listing reveal as to the contents of the folder?
Is there a file called illustris_python.py? or maybe illustris_python.pyc?



I also figured that I need to manually export to python path so i tried:
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
  File "", line 1
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
^
SyntaxError: invalid syntax

I got invalid syntax... using a mac os x

I tried typing in terminal open .bash_profile and telling it to
export the python path in there like some others recommended but in
terminal it is giving me an error message for that... it must not be
the right command for the shell.

Winonah

On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson mailto:c...@zip.com.au>> wrote:

On 23Jul2017 00:20, Alan Gauld mailto:alan.ga...@yahoo.co.uk>> wrote:

On 22/07/17 19:14, Winonah Ojanen wrote:

using python with anaconda in jupiter notebook. However,
I am having


Usual caveat: The tutor list is targeted at the standard library
so any help for non standard library modules is best sought from
the library support fora. In this case that includes the
SciPy forum
and any illustris one.


Though arguably the OP's problem is an import issue, not really
module specific.

That having been said, I'll take a guess...

$ mkdir Illustris-3
$ mkdir Illustris-3/groups_135

Are these folders in your PYTHONPATH? If not Python will not
find them.

import illustris_python as il

---
ModuleNotFoundError   Traceback
(most recent call last)


The OP cded into the new dir; I'd normally expect things to be
found if the module was a local file/dir. However...

For some reason the computer is not recognizing this as
a file on my
computer. The CCA folks says this is a coding problem
and not an illustris
problem. any ideas to get me past this? I may also need
help getting
farther into the download process.


I just ran the OP's download command:

 wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
--content-disposition --header="API-Key:
d522db2e1b33e36d3b365cc9ac1c2c5d"

"http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api

"

This doesn't seem to download any Python code at all. It does
get a couple of HDF files, presumably with data to work with.

So the issue is initially that the module isn't present
anywhere. Looking at the instructions cited
>, they
only cover fetching som data and working; they presume the
software is already present. I don't immediately see actual
software installation instructions, and it is not presented in PyPI.

Most like the OP will have to install the software directly fr

Re: [Tutor] Fwd: Re: call key on_press event multiple times when key is held down

2017-07-10 Thread Alan Gauld via Tutor
On 04/07/17 13:45, Carlton Banks wrote:

> Any suggestion on any GUI solutions?

Here is a Tkinter solution that increments a counter
while the mouse button is pressed. It should give you the idea...
Obviously you need to replace the counter increment
with your desired processing. And the print statements
are just to show the events being processed.

##
import tkinter as tk

display = "count: "
flag = False
counter = 0

def do_down(e):
global flag
print('Key down')
flag = True
after_loop()

def do_up(e):
global flag
print('key up')
flag = False

def after_loop():
print('looping')
global counter
counter += 1
l['text'] = display +str(counter)
if flag:
   top.after(10,after_loop)


top = tk.Tk()
l = tk.Label(top,text=display+'0')
l.pack()
l.bind("",do_down)
l.bind("",do_up)
top.mainloop()

###

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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: call key on_press event multiple times when key is held down

2017-07-04 Thread Carlton Banks
> 
>> Interesting solution, but still find a bit "dirty hackish”
>> to involve a timer in this..  I guess it just would be neat if 
>> it just worked as i thought it to be.  But i guess i have to look into 
>> curses.
> 
> A timer based loop is actually the standard pattern for
> implementing a loop in an event driven environment (the
> main alternative is to launch a background thread).
> It's how most GUIs handle such scenarios.
> 
> The problem in a CLI solution is that you have to build your
> own timer event system (usually based on time.sleep() or
> similar). Hence the suggestion to use a GUI.
> 

Any suggestion on any GUI solutions?


Regards 
Carl

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: call key on_press event multiple times when key is held down

2017-07-04 Thread Alan Gauld via Tutor
On 04/07/17 12:00, Alan Gauld via Tutor wrote:

>> the library you are using, I normally just use the standard
>> library for such things, or build a simple GUI…
> 
> Standard library being?.. 

The Python standard library that ships with Python and
is documented on python.org. As in:

>> There are several but it depends on your OS.
>> In the standard library
>> Unix variants can use curses.
>> Windows users have msvcrt.


> Interesting solution, but still find a bit "dirty hackish”
> to involve a timer in this..  I guess it just would be neat if 
> it just worked as i thought it to be.  But i guess i have to look into curses.

A timer based loop is actually the standard pattern for
implementing a loop in an event driven environment (the
main alternative is to launch a background thread).
It's how most GUIs handle such scenarios.

The problem in a CLI solution is that you have to build your
own timer event system (usually based on time.sleep() or
similar). Hence the suggestion to use a GUI.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: call key on_press event multiple times when key is held down

2017-07-04 Thread Alan Gauld via Tutor
Forwarding to Tutor list


Please always use reply-All or reply-List to respond to tutor posts.



 Forwarded Message 

> Den 4. jul. 2017 kl. 11.35 skrev Alan Gauld via Tutor :
> 
> On 04/07/17 09:50, Carlton Banks wrote:
>> I am trying to record from my microphone while i press down a button,
> 
> First question is which OS?
> That makes a big difference in this kind of scenario.

I am currently testing it on OS X, but should also be working on a ubuntu 
machine.  

>> the library I am using is not able to detect on hold event. 
> 
> There isn't really any concept of a hold event, you usually
> have to detect repeated press events. However I don;t know
> the library you are using, I normally just use the standard
> library for such things, or build a simple GUI…

Standard library being?.. 

> 
>> It only detect on press, which happens once, 
> 
> That's unusual, usually you get a repeated stream of
> press events when you hold a key down. But it does
> depend on the OS and environment. Your library may
> indeed just be detecting the initial key down and
> be waiting for the key up event.

Hmm.. interesting but again it is currently being tested on OSX,
as it was the only machine available atm. 
> 
>> So does any of you know any libraries that monitor> state of the keyboard,
> 
> There are several but it depends on your OS.
> In the standard library
> Unix variants can use curses.
> Windows users have msvcrt.
> 
> And there are several 3rd party libraries that try
> to do in a platform independent way - I'm guessing
> the one you are using is one such.
> 
> Another way to tackle it is to switch your code so
> it works with a toggle. Set the toggle to on in
> the on_press handler. Set it to off in the
> on_release handler
> 
> Then trigger a timer loop that runs for as long
> as the toggle is set. This is probably easiest
> done within a GUI.
> 

Interesting solution, but still find a bit "dirty hackish”
to involve a timer in this..  I guess it just would be neat if 
it just worked as i thought it to be.  But i guess i have to look into curses.



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Ubuntu install [was: Re: Fwd: Re: program code for Python Programming for the Absolute Beginner, 3rd ed.?]

2017-07-03 Thread Alan Gauld via Tutor
Forwarding to group.

Please always use ReplyAll (or ReplyList) when responding to list emails.





 Forwarded Message 


I have a fresh install of Ubuntu 16.04.2, on which I try to install
Python 3.6.1. I have done this multiple times in the past, but for some
reason I tried it 3 times since yesterday but I kept having the same
error message. Here are the steps that i have taken for my installation:

|$ sudo apt-get update $ sudo apt-get upgrade $ wget
https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz $ tar xvf
Python-3.6.1.tar.xz $ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev
libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev $ cd
Python-3.6.1$ ./configure $ sudo make altinstall|

After the last command the following message will popup at some point:

The directory '/home/mariejosv/.cache/pip/http' or its parent
directory is not owned by the current user and the cache has been
disabled. Please check the permissions and owner of that directory.
If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/mariejosv/.cache/pip' or its parent directory
is not owned by the current user and caching wheels has been
disabled. check the permissions and owner of that directory. If
executing pip with sudo, you may want sudo's -H flag.

How can I fix this?



Sent from my T-Mobile 4G LTE Device


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: program code for Python Programming for the Absolute Beginner, 3rd ed.?

2017-07-03 Thread Cameron Simpson

On 03Jul2017 09:13, Alan Gauld  wrote:
[...]

Sorry,
I still have no idea what you are trying to do and what you want help with?
 Forwarded Message 
Alan,
my bad, here is the error message.
*The directory '/home/mariejosv/.cache/pip/http' or its parent directory
is not owned by the current user and the cache has been disabled. Please
check the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag.


I would guess that the poster has done some pip installs as root, but with 
$HOME still as their personal home directory, and is now doing some pip install 
stuff as themselves.


My advice would be to simply remove the .cache/pip directory.

Then in future, do your pip work from a proper login shell as whichever user.  
So either as yourself, or if you become root, do an "su -" to get a root login 
shell before proceeding.


Personally my practice is to mostly use pip only with virtualenvs, as myself.

Using pip as root tends to conflict with Python packages supplied by the OS 
vendor/supplier; better to stay out of the way of that and work as oneself on 
data the OS vendor doesn't want to own.


Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: program code for Python Programming for the Absolute Beginner, 3rd ed.?

2017-07-03 Thread Alan Gauld via Tutor
forwarding to list.

Sorry,
I still have no idea what you are trying to do and what you want help with?

 Forwarded Message 

Alan,
my bad, here is the error message.
*The directory '/home/mariejosv/.cache/pip/http' or its parent directory
is not owned by the current user and the cache has been disabled. Please
check the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag.
The directory '/home/mariejosv/.cache/pip' or its parent directory is
not owned by the current user and caching wheels has been disabled.
check the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag. *


On Sunday, July 2, 2017, 5:36:34 PM EDT, Alan Gauld via Tutor
 wrote:


On 02/07/17 11:03, Richard Grose wrote:
>
https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiw1tD3qurUAhULKlAKHWMOAPMQFggkMAA&url=https%3A%2F%2Fgithub.com%2FCWade3051%2FPy%2Ftree%2Fmaster%2FAbsolute%2520Book%2Fpy3e_source&usg=AFQjCNG36WhZfh5ftqWncjtgZy3z6xgh6g&cad=rjt
>
> Py/Absolute Book/py3e_source at master · CWade3051/Py · GitHub
> 
> Richard G

Your subject line ends with a question mark so, are you asking
us something? Or telling us something?

Its not very clear which...

If you are asking you need to ask again, being a bit more specific.

-- 
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@python.org 
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Using files to read data

2017-06-27 Thread Mats Wichmann
On 06/27/2017 05:01 AM, Alan Gauld via Tutor wrote:
> Forwarding to list
> 
> Please always use ReplyAll or ReplyList when responding to list mail.
> 
> 
> 
>  Forwarded Message 
> 
> i apologize.  i guess it didn’t attach correctly.
> my issue is how do i get it out of my file and use it. 
> 
> *the json file, its only about a fifth of it but it should serve its
> purpose*
> [
> 0.9889,
> 0.02,
> "Mon Jun 26 20:37:34 2017"
> ]


A few thoughts here...

suggest storing the time not as a datetime string, but as a time value.
That is, use time.time() to generate it; you can always convert that
value to a string later if needed.

if you're going to write as json, then you should read as json, don't
create your own reader.

in order to get data serialized in a more usable form, you could define
a class, and serialize the class instances, this way you get the
variable name stored along with the data. Since json only understands a
limited number of data types, one cheap approach is to fish out the
dictionary of data from the instance object - json does understand
dicts. I'm using vars() for that.  So here's a cheap example, not
fleshed out to use any of your code:

import time
import json

class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.time = time.time()

# create a few points
A = Point(0.03, 0.9777)
B = Point(0.02, 0.9889)

print(json.dumps(vars(A)))
print(json.dumps(vars(B)))

You'll see you get formatted data that json.loads() ought to be able to
make use of:

{"y": 0.9777, "x": 0.03, "time":
1498577730.524801}
{"y": 0.9889, "x": 0.02, "time":
1498577730.524802}

You don't need a class for that, you can just build the dict yourself,
it was just a cheap way to illustrate.

Simulated read:

 >>> import json
 >>> point = json.loads('{"y": 0.9777, "x":
0.03, "time": 1498577980.382325}')
 >>> print(point['x'])
 0.0
 >>> print(point['y'])
 0.9778
 >>> print(point(['time'])
 1498577980.38
 >>>


I wouldn't open/close the json file you're writing to each time, that
seems a bit wasteful.

And do take on board some of the refactoring suggestions already made.

Dividing the heading by 90 using integer division (//) will give you
four possible values, 0-3, you can then base your definitions/decisions
on that, instead of your "if heading in range(1, 91):"  selections.
range actually generates the values, which you don't really need.

Best of luck!



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Using files to read data

2017-06-27 Thread Peter Otten
Alan Gauld via Tutor wrote:

> Forwarding to list
> 
> Please always use ReplyAll or ReplyList when responding to list mail.
> 
> 
> 
>  Forwarded Message 
> 
> i apologize.  i guess it didn’t attach correctly.
> my issue is how do i get it out of my file and use it.
> 
> *the json file, its only about a fifth of it but it should serve its
> purpose*

> [
> 0.9889,
> 0.02,
> "Mon Jun 26 20:37:34 2017"
> ]
> [
> 0.9777,
> 0.03,
> "Mon Jun 26 20:37:34 2017"
> ]

The problem with this data is that it's not proper json which allows only 
one toplevel data structure, e. g.

[
> [
> 0.9889,
> 0.02,
> "Mon Jun 26 20:37:34 2017"
> ]
,
> [
> 0.9777,
> 0.03,
> "Mon Jun 26 20:37:34 2017"
> ]
]

If you stick to that file format you need to split it into parts that are 
valid json before you can process them with the standard library's json 
module.

If you can rely on your records always consisting of five lines the 
following should work


import json

records = []

def read_five_lines(f):
return "".join(f.readline() for i in range(5))

with open("xyz_save.json") as f:
while True:
chunk = read_five_lines(f)
if not chunk:  # empty string --> reached end of file
break
records.append(json.loads(chunk))

print(records)

Another option would be to change your writing script so that it writes one 
record per line, e. g.

[0.24446, 0.8556, "Tue Jun 27 14:21:44 2017"]
[-0.29333, 1.907, "Tue Jun 27 14:21:44 2017"]

This can be achieved by omitting the indent=0 argument in your json.dump() 
calls. Then your reader can be simplified:

import json

records = []

with open("xyz_save.json") as f:
for line in f:
records.append(json.loads(line))

print(records)



> if heading in range(1, 91):

Did you know that

>>> 1.5 in range(1, 91)
False

? If you want to accept non-integral values you better write the above as

if 0 <= heading < 90:  # swap operators if want to exclude the lower 
   # and include the upper bound
...

or similar.

> north = heading
> east = 90 - heading
> y = (north / 90) * forward_time
> x = (east / 90) * forward_time
> now_time = time.ctime()
> 
> xyz = [x, y, now_time]
> 
> xyz_save = "xyz_save.json"
> 
> 
> with open(xyz_save, "a") as stamp:
> json.dump(xyz, stamp, indent=0)
> stamp.write("\n")
> 
> return xyz
> 
> elif heading in range(91, 181):
> east = heading - 90
> south = 180 - heading
> y = (south / 90) * forward_time
> x = (east / -90) * forward_time
> now_time = time.ctime()
> 
> xyz = [x, y, now_time]
> 
> xyz_save = "xyz_save.json"
> 
> 
> with open(xyz_save, "a") as stamp:
> json.dump(xyz, stamp, indent=0)
> stamp.write("\n")
> 
> return xyz

There's *a* *lot* of repetition here. At the very least you should move the 
parts that are completely identical to the end of the if ... elif ... chain:

if heading in range(1, 91):
north = heading
east = 90 - heading
y = (north / 90) * forward_time
x = (east / 90) * forward_time
elif heading in range(91, 181):
east = heading - 90
south = 180 - heading
y = (south / 90) * forward_time
x = (east / -90) * forward_time
 ...

else: 
# handling the case where no condition matches
print("unhandled heading", heading, file=sys.stderr)
return

now_time = time.ctime()
xyz = [x, y, now_time]
xyz_save = "xyz_save.json"

with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp)
stamp.write("\n")

return xyz

PS:

> north = heading
> east = 90 - heading
> y = (north / 90) * forward_time
> x = (east / 90) * forward_time

I wonder whether there should be a sin() and cos() somewhere...

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Using files to read data

2017-06-27 Thread Alan Gauld via Tutor
Forwarding to list

Please always use ReplyAll or ReplyList when responding to list mail.



 Forwarded Message 

i apologize.  i guess it didn’t attach correctly.
my issue is how do i get it out of my file and use it. 

*the json file, its only about a fifth of it but it should serve its
purpose*
[
0.9889,
0.02,
"Mon Jun 26 20:37:34 2017"
]
[
0.9777,
0.03,
"Mon Jun 26 20:37:34 2017"
]
[
0.9667,
0.0,
"Mon Jun 26 20:37:34 2017"
]
[
0.9556,
0.06,
"Mon Jun 26 20:37:34 2017"
]
[
0.9444,
0.0,
"Mon Jun 26 20:37:34 2017"
]
[
0.9333,
0.06667,
"Mon Jun 26 20:37:34 2017"
]
[
0.9223,
0.07778,
"Mon Jun 26 20:37:34 2017"
]
[
0.9111,
0.08889,
"Mon Jun 26 20:37:34 2017"
]
[
0.9,
0.1,
"Mon Jun 26 20:37:34 2017"
]
[
0.,
0.,
"Mon Jun 26 20:37:34 2017"
]
[
0.8778,
0.1,
"Mon Jun 26 20:37:34 2017"
]
[
0.8667,
0.1,
"Mon Jun 26 20:37:34 2017"
]
[
0.8555,
0.14443,
"Mon Jun 26 20:37:34 2017"
]
[
0.8444,
0.15556,
"Mon Jun 26 20:37:34 2017”

*the code that creates it*

import json
import time

def xyz(heading, forward_time):
"""get x and y increments of 360 degrees"""

if heading in range(1, 91):
north = heading
east = 90 - heading
y = (north / 90) * forward_time
x = (east / 90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz

elif heading in range(91, 181):
east = heading - 90
south = 180 - heading
y = (south / 90) * forward_time
x = (east / -90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz

elif heading in range(181, 271):
south = heading - 180
west = 270 - heading
y = (south / -90) * forward_time
x = (west / -90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz

elif heading in range(271, 361):
west = heading - 270
north = 360 - heading
y = (north / -90) * forward_time
x = (west / 90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz
 

*One of multiple loads I’ve got. *
*
*
', '0', ':', '3', '7', ':', '3', '4', ' ', '2', '0', '1', '7', '"',
'\n', ']', '\n', '[', '\n', '0', '.', '0', '2', '2', '2', '2', '2', '2',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', ',', '\n', '0',
'.', '9', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'7', '7', '7', ',', '\n', '"', 'M', 'o', 'n', ' ', 'J', 'u', 'n', ' ',
'2', '6', ' ', '2', '0', ':', '3', '7', ':', '3', '4', ' ', '2', '0',
'1', '7', '"', '\n', ']', '\n', '[', '\n', '0', '.', '0', '1', '1', '1',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2',
',', '\n', '0', '.', '9', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'8', '8', '8', '8', '8', '9', ',', '\n', '"', 'M', 'o', 'n', ' ', 'J',
'u', 'n', ' ', '2', '6', ' ', '2', '0', ':', '3', '7', ':', '3', '4', '
', '2', '0', '1', '7', '"', '\n', ']', '\n', '\n’]
*
*
*
*
*
*
*the closest i have got is this*
*
*
[
0.07778,
0.9223,
"Mon Jun 26 20:37:34 2017"
]
[
0.06667,
0.9333,
"Mon Jun 26 20:37:34 2017"
]
[
0.0,
0.9444,
"Mon Jun 26 20:37:34 2017"
]
[
0.06,
0.9556,
"Mon Jun 26 20:37:34 2017"
]
[
0.0,
0.9667,
"Mon Jun 26 20:37:34 2017"
]
[
0.03,
0.9777,
"Mon Jun 26 20:37:34 2017"
]
[
0.02,
0.9889,
"Mon Jun 26 20:37:34 2017”

*with this code*

filename = "xyz_save.json"
with open(filename) as f_obj:
lines = f_obj.read()

print(lines)
*
*
*
*
*
*
*i guess my ultimate question is how do i take all the x and y values
and use them.*
*i apologize for my ignorance as this is my first post about something
very new to me.*
*i also appreciate your patience*
*
*
*
*
*
*








> On Jun 27, 2017, at 1:56 AM, Alan Gauld 

[Tutor] Fwd: Re: bottle: request.form.get()

2017-06-23 Thread Alan Gauld


Please always use ReplyAll when responding to the tutor list.
(Or ReplyList if your mail client supports it)

(Having said that I forgot to add the list - oops! :)


On 22/06/17 19:48, adil gourinda wrote:
> 1) I expected a well made documentaion that your

The Python web site provides documentation for the full standard library,
which includes some basic web programming tools. But those are not as easy
to use as others such as bottle.

Bottle provides full documentation (including a tutorial) on their web site

Between the two you should find what you need. If not send us (or the
bottle support group)  your code  and some sample data and we can
try to help.

The bottle support is at:

A mailing list

https://groups.google.com/forum/#!forum/bottlepy

and a chat channel:

https://webchat.freenode.net/?channels=bottlepy


Both are linked on the main bottle web site.

> 2) My problem is that I don't know how to retrieve data from 
> tag, but in general I don't know how to connect between python and
> html in script. I am new in web-framework, if you can advise me to a
> more easy framework than bottle
>

I don't know bottle personally but I believe it's based on Flask and as
such
should be as easy to use as any of the (many) other web frameworks. In
other
words you should probably persevere with it rather than jump to another
framework that won't be any easier to learn.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: How do I display a picture?

2017-05-17 Thread Alan Gauld via Tutor
On 18/05/17 00:38, Alan G via Tutor wrote:
>Please always use reply all, or reply list when responding to list

Oops, it seems like you did that already, my apologies.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: How do I display a picture?

2017-05-17 Thread Alan G via Tutor
   Please always use reply all, or reply list when responding to list
   messages. I think eryksun may have already answered your question, if not
   give more info about how you run your code.

    Original Message 
   Subject: Re: [Tutor] How do I display a picture?
   From: Michael C 
   To: Alan Gauld 
   CC: tutor@python.org

   I use python image library and apparently when I do
   im = Image.open('1.png')
   im.show()
   show() actually opens a empty console window that doesn't do anything and
   as long as it's around the script hangs.
   Currently I have to close it by clicking on the close button and it makes
   my script useless.
   so **i am trying find either a way to prevent that from poping up or to
   close it automatically somehow
   or to find another way to display the picture without using python image
   library.
   On Wed, May 17, 2017 at 4:13 PM, Alan Gauld via Tutor
   <[1]tutor@python.org> wrote:

 On 17/05/17 21:33, Michael C wrote:

 > How do I display a picture?

 What do you mean? What kind of picture?
 Where do you want it displayed (what kind
 of window/screen)?

 There are a dozen possible ways to "display a picture"
 depending on what you specifically want.

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

 ___
 Tutor maillist** -** [5]Tutor@python.org
 To unsubscribe or change subscription options:
 [6]https://mail.python.org/mailman/listinfo/tutor

References

   Visible links
   1. mailto:tutor@python.org
   2. http://www.alan-g.me.uk/
   3. http://www.amazon.com/author/alan_gauld
   4. http://www.flickr.com/photos/alangauldphotos
   5. mailto:Tutor@python.org
   6. https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: While Loop Question

2017-05-11 Thread Rafael Skovron
Thank you all I finally understood that the while code traps j and runs
independently of the for loop until while is false and a new i is picked.



On Thu, May 11, 2017 at 10:19 AM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:

> sorry j is set to zero. grave typo
>
> Abdur-Rahmaan Janhangeer,
> Mauritius
> https://abdurrahmaanjanhangeer.wordpress.com
>
> On 11 May 2017 12:29 pm, "Abdur-Rahmaan Janhangeer" 
> wrote:
>
> >
> >
> > -- Forwarded message --
> > From: "Abdur-Rahmaan Janhangeer" 
> > Date: 11 May 2017 12:26 pm
> > Subject: Re: [Tutor] While Loop Question
> > To: "Rafael Skovron" 
> > Cc:
> >
> > i modified your code to make it look like that :
> >
> > for i in range(1, 5):
> >
> > j=0
> > print("outer,  i=",i)
> > while j < i:
> >  print("inner, j=",j)
> >
> >  j += 1
> >
> > so it shows that each time the outer loop is reexecuted, i is set to
> zero.
> >
> > putting j at the begining completely, it is not reset to zero
> >
> > Abdur-Rahmaan Janhangeer,
> > Mauritius
> > https://abdurrahmaanjanhangeer.wordpress.com
> >
> >
> >
> >
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: While Loop Question

2017-05-11 Thread Abdur-Rahmaan Janhangeer
sorry j is set to zero. grave typo

Abdur-Rahmaan Janhangeer,
Mauritius
https://abdurrahmaanjanhangeer.wordpress.com

On 11 May 2017 12:29 pm, "Abdur-Rahmaan Janhangeer" 
wrote:

>
>
> -- Forwarded message --
> From: "Abdur-Rahmaan Janhangeer" 
> Date: 11 May 2017 12:26 pm
> Subject: Re: [Tutor] While Loop Question
> To: "Rafael Skovron" 
> Cc:
>
> i modified your code to make it look like that :
>
> for i in range(1, 5):
>
> j=0
> print("outer,  i=",i)
> while j < i:
>  print("inner, j=",j)
>
>  j += 1
>
> so it shows that each time the outer loop is reexecuted, i is set to zero.
>
> putting j at the begining completely, it is not reset to zero
>
> Abdur-Rahmaan Janhangeer,
> Mauritius
> https://abdurrahmaanjanhangeer.wordpress.com
>
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: While Loop Question

2017-05-11 Thread Abdur-Rahmaan Janhangeer
-- Forwarded message --
From: "Abdur-Rahmaan Janhangeer" 
Date: 11 May 2017 12:26 pm
Subject: Re: [Tutor] While Loop Question
To: "Rafael Skovron" 
Cc:

i modified your code to make it look like that :

for i in range(1, 5):

j=0
print("outer,  i=",i)
while j < i:
 print("inner, j=",j)

 j += 1

so it shows that each time the outer loop is reexecuted, i is set to zero.

putting j at the begining completely, it is not reset to zero

Abdur-Rahmaan Janhangeer,
Mauritius
https://abdurrahmaanjanhangeer.wordpress.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: Python 3.6 Extract Floating Point Data from a Text File

2017-05-01 Thread Alan Gauld via Tutor
On 01/05/17 15:54, Stephen P. Molnar wrote:
> Unfortunately, I'm still missing something. Here is my latest attempt
> to incorporate your solution:
> name = input("Enter Molecule ID: ")
> name = str(name)
you don't need the str() since input() always returns whatever string
the user enters.

> name_in = []
> name_in = name[:]+'.lac.dat'

You don't need the [:] either since that just makes a copy of name.
So you can just use

name_in = name + '.lac.dat'

But notice that you have lost the list you created. name_in
is now just a string.
> atm_chg = []

This creates a new empty list.
But...

> with open(name_in) as f:
>  # skip two lines
>  f.readline()
>  f.readline()
>  for line in f.readlines():
You don't need readlines, you can just iterate over f:

for line in f:
atm_chg = float(line.split()[-1])

This loses the list you created earlier and replaces it with a float.
I suspect you want to append this to your list?

atm_chg.append(float(line.split()[-1])

> The error this attempt give me is attached.
>
> IndexError: list index out of range

That's only the last line of the error. Please always post the
full error text. There is a lot of useful data in there that we
can't see. As a debug step you could try printing line to
make sure it always contains multiple fields.

But are you sure that you only want a list of floats out?
Steven's solution based on a dictionary seemed like it
might be more useful for you?

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: Python 3.6 Extract Floating Point Data from a Text File

2017-04-30 Thread Alan Gauld via Tutor
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

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Startup Python

2017-04-14 Thread Wim Berrelkamp
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 
Date: 2017-04-12 14:47 GMT+02:00
Subject: Startup Python
To: tutor@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 
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
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: RE: Fwd: Re: Sklearn

2017-03-11 Thread Alan Gauld via Tutor

> I want libraries that contain algorithms to check for relationships
> within a dataset. For example, I want to parse through a SES dataset to
> see any possible connections between student achievement and
> socioeconomic standing, and correlate that to neighborhood wealth.

Ok, With that background I now return to your original
question:

> Can someone explain sklearns to me? I'm a novice at Python,
> and I would like to use machine learning in my coding.
> But aren't there libraries like matplotlib I can already
> use? Why use sklearns?

Starting at the end first...
matplotlib is a plotting library, you give it some raw
data and it plots a nice graphical image in any style
you choose. Think of it like a programmatic version
of the plotting feature in a spreadsheet.

sklearn doesn't do that, it will generate the data
for you to p[lot with matplotlib if you wish. (At least
thats how I interpret the information on the sklearn
web page.)

So its not either/or - you need both. sklearn, as the
sk in the name suggests, is part of SciKit which is a
set of add-ons to SciPy, which includes matplotlib.

What sklearn brings to the picture, again based on
a very quick skim through the introductory material
 - is a framework for doing machine learning. If you
just want to play with its standard datasets then
its very easy to use. If you want to use it on your
own data it gets harder - you need to format your
data into the shape sklearn expects. You then need
to specify/select or write the algorithms needed
for sklearn to do its learning. Don't underestimate
how much preparatory work you will need to do to
feed the engine. Its not magic.

For what you want, Pandas or Rpy might be able to
do it just as easily - but since you don't seem
to already know either of those then sklearn would
seem to be a reasonable alternative/complementary choice.
But if you don't know basic Python well that might
be a bigger challenge.

Given my level of ignorance about both sklearn
and your problem, domain I can't say more than that.
I would suggest asking again on the SciPy forum
since you are likely to find a lot more people
there who have experience of both - and alternatives
like Pandas and Rpy.

> And I know I should learn R, but I'm also learning 
> Python as my primary language now, and R isn't
> really a programming language as Python, Java,

It's not quite as general - I wouldn't try writing
games or GUIs or web apps in R. But you can write
fully self-contained applications in it if you wish.
And for traditional statistical number crunching
it's better than either Python or Java. Fortunately
you can use R from either language via libraries.

-- 
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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: RE: Fwd: Re: Sklearn

2017-03-11 Thread Matt Williams
Having done similar, the options are (depending on the dataset):

1: Python to read, clean and classify data, then R to do the analysis (e.g.
regression analysis)

2: Python to read, clean and classify data, and python for the analysis

3: All in R

If you want to use Python for the analysis, most people would probably use
Pandas for the data cleaning and SciPy for the stats. However, there are
alternatives.

There is a tutorial that describes almost exactly the same problem as yours
here, using Pandas and some other packages:

http://blog.yhat.com/posts/logistic-regression-and-python.html

HTH,
Matt


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: RE: Fwd: Re: Sklearn

2017-03-10 Thread Alan Gauld via Tutor
Forwarding to list...

---


Statistical analysis of datasets.

I want libraries that contain algorithms to check for relationships
within a dataset. For example, I want to parse through a SES dataset to
see any possible connections between student achievement and
socioeconomic standing, and correlate that to neighborhood wealth.



And I know I should learn R, but I'm also learning Python as my primary
language now, and R isn't really a programming language as Python, Java,
C++, etc., so I'm not placing it as a primary language to learn at the
moment.

 Original message 
From: Alan Gauld via Tutor 
Date: 3/10/17 8:13 PM (GMT-05:00)
To: tutor 
Subject: [Tutor] Fwd: Re:  Sklearn

Forwarding to list...

Please use ReplyAll or ReplyList when responding to the tutor list.

--

> I would like to carry statistical analyses of populations .
> I've been that it's the best package for that sort of thing in Python,
> but I'm new to machine learning,  so I'm not quite sure.

Can you describe what you mean by "machine learning"?
This is one of those current buzzwords that has almost as
many meanings as there are people using it.

If you can give a practical example of the kind of thing you
can see yourself using this stuff for then we can advise on
whether a library might be suitable or not. And if we don't
know (we are focused on the standard library not 3rd party
add-ons)  where you might get a better response.

> Also, I don't want to bother learning R.

That's a separate issue, but R is almost a defacto standard
in the world of statistics so if you are seriously involved there
you probably should make the effort.

Alan G

On 10/03/17 23:12, Daniel Bosah wrote:
> Can someone explain sklearns to me?

Not me, I've never heard of it till now.

> I'm a novice at Python, and I would
> like to use machine learning in my coding.

Why?
What do you know about machine learning?
What other platforms support it?

> But aren't there libraries like
> matplotlib I can already use?

Probably, but what do you know about matplotlib?
How does it relate to machine learning?

> Why use sklearns?

Because it does what you want to do.
What do you want to do?
Does sklearns do that?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   6   7   8   >