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


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


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 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


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


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 

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-17 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


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


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


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%2Ftutordata=01%7C01%7Csydney.shall%40kcl.ac.uk%7C185332cee28f49ed465108d6214ce8ab%7C8370cf1416f34c16b83c724071654356%7C0sdata=GBAb%2FdY2zrBqSwOl33ejT%2BzzknQx5RYNXsNEqZQXCX4%3Dreserved=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%2Ftutordata=01%7C01%7Csydney.shall%40kcl.ac.uk%7Cb9cbdce8c20e45dd3ff508d621390143%7C8370cf1416f34c16b83c724071654356%7C0sdata=yNo7hMVl7dYmH6d74MBaab5e5g6bPoWoqkza5TS1bXY%3Dreserved=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%2Fdata=01%7C01%7Csydney.shall%40kcl.ac.uk%7C77fe09364c79190308d61f4d4112%7C8370cf1416f34c16b83c724071654356%7C0sdata=DAhLxDli1vM%2BBcRXKemRo0sa%2BVJErJPZ%2Bwy5UHvUR4s%3Dreserved=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%2Ftutordata=01%7C01%7Csydney.shall%40kcl.ac.uk%7C77fe09364c79190308d61f4d4112%7C8370cf1416f34c16b83c724071654356%7C0sdata=Benb%2BsxqZr1Rhdj8jG81KRurndfNVnBGx0%2B3z9VXd54%3Dreserved=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


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


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


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


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


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" 

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


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


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


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


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


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


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


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


Re: [Tutor] Fwd: Re: SciPy Optimize-like calling function as string

2017-02-25 Thread Alan Gauld via Tutor
On 25/02/17 17:24, Alan Gauld via Tutor wrote:

>> If you don't know that you need to optimize then your
>> time is usually better spent elsewhere. Dictionaries
>> are pretty fast in Python and I'd suggest you try
>> that first before shaving milliseconds in places
>> that may not be where you need to make savings.
> 
> Honestly, that method makes no sense to me whatsoever. 

Sorry, what I meant is: try the simpler dictionary
based technique first. Dictionaries are what Python
uses internally for almost everything so they
are very fast. Only if you know you need to improve
on their performance should you try using other
techniques (and that's an extremely rare scenario).

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


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


Re: [Tutor] Fwd: Re: GUI for ANSI colors

2017-02-13 Thread Alan Gauld via Tutor
On 14/02/17 00:58, Alan Gauld forwarded:

> red = '\033[91m'
> yel = '\033[93m'
> blu = '\033[34m'
> grn = '\033[32m'

These are indeed the ANSI codes for the colours but ANSI
codes only work in an ANSI terminal and GUIs are not
ANSI terminals. Instead they have their own ideas on
colours and you need to use those. They all support
the standard 16 colours used in ANSI however, so in
your case (for Tkinter at least) just use the names
'red', 'yellow', 'blue' and 'green'

> colors = [red, yel, blu, grn]

colors = ['red', 'yellow', 'blue', 'green']


> final_word = ''.join(choice(colors) + char for char in word)

But again that won't work in a GUI, you need to use the GUIs
way of colouring. In Tkinter that's via tags as per my
previous post, reproduced here).

> ###
> from Tkinter import *
> 
> n = 0
> top = Tk()
> t = Text(top, width=25, height=2)
> t.pack()
> 
> # set up tags for the colors
> colors = ['red','blue','green']
> for col in colors:
> t.tag_config(col, foreground=col)
> 
> def addWords():
> n = 0
> for word in "Hello ", "bright ", "world ":
> t.insert(END,word,colors[n])  #use the color tags
> n +=1
>

You need to change the loop to iterate over the letters
instead of words and choose the tags at random. But that
should be fairly straightforward.

> Button(top,text="Add words",command=addWords).pack()
> 
> top.mainloop()
> ##


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


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


Re: [Tutor] Fwd: Question about selenium with python

2016-12-22 Thread Alan Gauld via Tutor
On 21/12/16 01:29, Fazal Khan wrote:

> Im a new programmer and this is my first time posting here. I have a
> question about using selenium with python. 

I notice you haven't had an answer yet.
That may be because Selenium is not part of the
standard Python library and this list is for questions
about the core language and its standard library.

You may be better off asking on a selenium specific
list or forum. This page lists several options:

http://www.seleniumhq.org/support/

Meanwhile, this page may help with your specific
question:

http://selenium-python.readthedocs.io/navigating.html

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: IndentationError: unexpected indent

2016-11-09 Thread Joaquin Alzola
>Subject: [Tutor] Fwd: IndentationError: unexpected indent

You are using a mixture of space and tabs or number of spaces.
The exception give you the line that has the problem.

---
Joaquin
This email is confidential and may be subject to privilege. If you are not the 
intended recipient, please do not copy or disclose its content but contact the 
sender immediately upon receipt.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: IndentationError: unexpected indent

2016-11-08 Thread Alan Gauld via Tutor
On 08/11/16 14:47, Palanikumar Gopalakrishnan wrote:
> Hi Guys,
>  I tried this code from internet, Its returns following please
> guide me to solve this error

> 
> * passwordFile = open('File.txt') secretPassword =
> passwordFile.read() print('Enter your password.') typedPassword = input()
> if typedPassword == secretPassword:print('Access granted')if
> typedPassword == '12345':   print('That password is one that an idiot
> puts on their luggage.')  else:print('Access denied')*

Since the code has no indentation at all I assume you
have posted in HTML or somesuch. You need to post using
plain text so we can see the indentation.

Also do not summarize the error but post the full error text.


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


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


Re: [Tutor] Fwd: Re: need help

2016-08-12 Thread Alan Gauld via Tutor

> -- Forwarded message --
> From: "Pallab Amway" 
>> Respected sir,lots of thanks for your advice,but while i am compiling
>> those programe with python 2.7 no output is coming only showing the
>> masage "expected indented block"

The first thing is to point out that you are getting an output - an
error message. Error messages are output.

The error tells you that it expects an indented block.
Do you understand what that means? Indentation refers
to the amount of spacing before the text. specifically
there must be more space before the lines after a control
statement (like your 'if') than there is on the control
line.

In most programming languages this is a matter of good
style to make the code easier for humans to read.
But it is a fundamental principle in python because
the compiler uses the spacing to figure out how much
code is influenced by the control statement.

So an if statement should look like:


if :
an indented line
another indented line
end of if block
elif  can you sugest any ebook?and please

I am biased but you can try my tutorial (see .sig below)
or there is a full page for beginners on the python.org
web site

https://www.python.org/about/gettingstarted/


-- 
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: Help me out please

2016-07-21 Thread Alan Gauld via Tutor
On 21/07/16 21:17, Danny Yoo wrote:

> Well, I have two scripts. One in Python and the other one in html.
> Inside the html's script you can find out these lines:
> 
> 
> initLatencymon(
> '#latencyMON',
> {},
> { measurements:[*3679333, 3793762*]}
> );
> 
> 
> I need to change these *bold *variables from the Python's script. 

That's technically not too difficult at a file level, especially if
you use an html parser like Beautiful Soup. But whether that's the
best way depends on how the files are used.

How is the html file accessed? Is it independent of the python script?
In other words doers the python script run as a batch job that only
updates the values occasionally? Or regularly? (How often?) or is it on
demand - some other trigger starts the Python script?
Or does the Python script somehow start from an action by the html script?

Its all very vague just saying you have two files.
WE need to understand the intended interaction between them.

If it is just a daily or hourly update then the html parser
route is probably adequate. If its driven by an external
trigger then it might be ok but might not.

And if its driven by the html script itself then we almost
certainly need a redesign of how you are doing things.

So can you start by explaining the use case scenario
for these interactions. How do the file get executed?
What triggers them?

How do they interact (if, indeed, they do)?

-- 
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: 10+ Different Python Script?

2016-07-13 Thread Steven D'Aprano
On Wed, Jul 13, 2016 at 05:03:41AM -0700, Crusier wrote:


> I have a python script which is used for downloading Real Time Stocks.
> Currently, there is over a 1000 stocks in the Portfolio.
>
> If I download the market info during market hours, it would take over
> 40 minutes to finish downloading all the market info.

That's only 2.4 seconds per stock. Depending on how much data each stock 
provides, that doesn't sound like much time to me.

(1) How much data is downloaded? Perhaps you are downloading as fast 
as your internet conection will allow.

(2) How long does it take to download outside of market hours? Perhaps 
the supplier throttles the speed that you can download during market 
hours, or perhaps they're just overloaded with requests and can't supply 
information any faster.


> Since I am
> trading stock real time, I am thinking of breaking it down into 100
> stocks per group, so I could make the download time shorter.

Why do you think that downloading 10*100 stocks will take less time 
than downloading 1000 stocks? Either way, you still have to download the 
same amount of information.


> For the
> market info, I will put into database and for data analysis.
> 
> My Question is as follows:
> 
> Please advise if I should put the portfolio and split it into 10
> different scripts, so each scripts consists a list of 100+ number of
> stocks. Or is there any Pythonic way to approach this problem??

Absolutely not. You shouldn't have the portfolio inside the script. You 
should have one script, and ten portfolios. Then you give the name of 
the portfolio as an argument to the script:

myscript.py portfolio1
myscript.py portfolio2
myscript.py portfolio3
...
myscript.py portfolio10

or possibly:

myscript.py portfolio1 portfolio2 portfolio3 ... portfolio10

> I am currently using Multi Thread but there is an Operational Error

What sort of error?


> I am having a hard time to approach OOP. I just can't grasp the
> understanding of it as it seems so abstract. Please advise.

One related question per email please. It makes it easier to follow the 
conversations if you put unrelated questions in different emails.



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


Re: [Tutor] Fwd: Fwd: : Turtle

2016-06-24 Thread Alan Gauld via Tutor
On 24/06/16 08:51, Hershel Millman wrote:
> Python didn't come installed on my Mac, my dad had to install it. 

Nope, it definitely would have been on there because MacOS uses it.
So you definitely have two versions of python installed and it looks
like one of them (probably the default) is v2.5 and uses the older
turtle module and the other is v2.6 and has the latest version of turtle.

Your challenge is going to be making sure you are running the right
version. One way to check this is to print it out at the start of your
program (as a debug step) by adding these lines:

import sys
print(sys.version)

If it isn't v2.6 then that is your problem.

As for pycharm... These pages may help. You can apparently set
the interpreter version Pycharm uses both at a default level
and on an individual project level.

https://www.jetbrains.com/help/pycharm/2016.1/configuring-available-python-interpreters.html

http://stackoverflow.com/questions/19679150/how-to-set-default-pycharm-interpreter

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: Fwd: : Turtle

2016-06-24 Thread Alan Gauld via Tutor
On 24/06/16 03:02, Hershel Millman wrote:
> It tells me:
> Trace back (most recent call last):
> File "", line 1, in 
> NameError: name 'turtle' is not defined

As I recall, the default install of Python on a Mac
does not include Tkinter. Turtle uses Tkinter so I
suspect turtle is not installed either.

To confirm that try

import Tkinter

and see if that also gives an error.

If I'm right you will need to ensure you use the
2.6 version for all your turtle 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: : Turtle

2016-06-24 Thread Joaquin Alzola
I tested with 2.6 and it works.

>/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5 
>"/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py"
>Traceback (most recent call last):
 > File "/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py", 
 > line 2, in 
 >  turtle.pendown()
>AttributeError: 'module' object has no attribute 'pendown'

Cannot access the documentation of the 2.5 to check if the pendown() is there.
This email is confidential and may be subject to privilege. If you are not the 
intended recipient, please do not copy or disclose its content but contact the 
sender immediately upon receipt.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: : Turtle

2016-06-23 Thread Steven D'Aprano
On Thu, Jun 23, 2016 at 02:13:56PM -0700, Hershel Millman wrote:
> What I typed was:
> 
> import turtle
> turtle.pendown()

What do you get if you print turtle.__file__?

> (And pendown was highlighted in pycharm, indicating that it was not a valid 
> command.)
> 
> The error message I received was:
> 
> /System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5 

Look at the version number: you are running Python 2.5. 

Now look at the result you got earlier:

> >> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/turtle.py

Look at the version number: you are running Python 2.6.

So you have AT LEAST two different Python versions on your computer. 
That's fine, I have *nine* versions on mine. But it does mean you have 
to be a little more careful to ensure you are using the right one.

My *guess* is that your Mac has pre-installed version 2.5 with the 
operating system, and you have installed version 2.6 next to it, and now 
you sometimes get 2.5 and sometimes 2.6 depending on which icon you 
double-click. Or something like that. Or maybe PyCharm let's you pick a 
different version, and you haven't noticed.

You can check the version from inside Python:

import sys
print sys.version

My prediction is:

* when you run Python 2.6, turtle will work fine, including the pendown 
command (but remember to use round brackets/parentheses):

turtle.pendown()  # okay in 2.6

* when you run Python 2.5, turtle will import, but there is no 
turtle.pendown command. Instead, it is called turtle.down.

Documentation for 2.5:

https://docs.python.org/release/2.5.4/lib/module-turtle.html

Documentation for 2.6:

https://docs.python.org/release/2.6/library/turtle.html



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


Re: [Tutor] Fwd: : Turtle

2016-06-23 Thread Alan Gauld via Tutor
On 23/06/16 22:13, Hershel Millman wrote:
> What I typed was:
> 
> import turtle
> turtle.pendown()
> 
> (And pendown was highlighted in pycharm, indicating that it was not a valid 
> command.)

Don't use pycharm. We need to eliminate as many variables as possible.
Start python in a Terminal and just type the commands into the raw
Python interpreter. Send a paste of the transcript.
I expect to see something like:

agauld@ubuntu:~$ python2
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import turtle
>>> turtle.__file__
'/usr/lib/python2.7/lib-tk/turtle.pyc'
>>> turtle.pendown

>>> turtle.pendown()
>>>

Can you reproduce that on your Mac? (Except maybe with an
error message somewhere along the line?)

> /System/Library/Frameworks/Python.framework/Versions/2.5/bin/python2.5 
> "/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py"
> Traceback (most recent call last):
>   File "/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py", 
> line 2, in 
> turtle.pendown()
> AttributeError: 'module' object has no attribute 'pendown'

I notice that this says you are using Python 2.5 but your
last message suggested the module was in 2.6.

I don't think that should make a difference for the turtle
module but it might be significant... Lets see your
transcript 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


Re: [Tutor] Fwd: Fwd: Turtle

2016-06-19 Thread Steven D'Aprano
On Sun, Jun 19, 2016 at 04:21:28PM -0700, Hershel Millman wrote:

> I entered "import turtle" instead of "from turtle import * ", but it 
> looks as if it did not import the pendown command. Why is that?

Good question.

Try this:

import turtle
print(turtle.__file__)

That should print something like

'/usr/local/lib/python3.3/turtle.py'

or wherever you have installed Python to. If it is something like this:

/Users/Hershel/PycharmProjects/Project 1/turtle.py

then you have (accidentally) saved a new file called "turtle.py" and it 
is shadowing the standard library file and blocking it from being 
loading. Instead of importing the real turtle module, Python is 
importing your fake turtle module.

To fix that, delete or rename your turtle.py module, quit PyCharm, and 
start it up again.

Then you'll need to fix a small bug in your code:

> import turtle
> 
> def drawSquare(size=100):
> turtle.pendown

Add round brackets (parentheses) to the pendown:

turtle.pendown()

Without the brackets, it just names the function, it doesn't call it. In 
your case, it probably doesn't matter, since the turtle starts with the 
pen down by default.



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


Re: [Tutor] Fwd: Turtle

2016-06-19 Thread Steven D'Aprano
On Sat, Jun 18, 2016 at 08:46:53PM -0700, Hershel Millman wrote:

> > I followed your instruction and typed "import turtle" into the terminal on 
> > my mac, and nothing happened.

If you're talking about the Python prompt, that's good. That means 
turtle is installed. Importing a module either succeeds, or gives a 
traceback. Compare the difference between these two imports:

py> import turtle
py> import octopus
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named 'octopus'


[...]
> > In pycharm, when I enter the following, it replies with the 
> > following error message:
> > 
> > from turtle import *
> > 
> > def drawSquare(size=100):
> >turtle.pendown()
[...]

> > Traceback (most recent call last):
> >  File "/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py", 
> > line 14, in 
> >drawSquare(50)
> >  File "/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py", 
> > line 4, in drawSquare
> >turtle.pendown()
> > NameError: global name 'turtle' is not defined

This is the difference between plain "import" and "from ... import".

Here is a simplified example that hopefully will be clear:


py> import math
py> math.pi
3.141592653589793
py> pi
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'pi' is not defined



With a regular import, the math module is loaded and made available 
using the module name. To see inside the module, you have to use the dot 
operator (it's not really an operator, but I'll call it that) to get 
access to functions and variables inside the math module. Hence you must 
say "math.pi".

If you say "pi" on its own, Python looks for a variable called pi, 
doesn't find one, and complains.


If I quit out of Python and start again, in a fresh session:

py> from math import pi
py> math.pi
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'math' is not defined
py> pi
3.141592653589793


"from ... import" works the opposite way. It still loads the math 
module, but this time it DOESN'T make it available under that name, so 
"math.pi" fails. Instead, it cretaes a new variable called pi, set to 
math.pi.


Finally:

from math import *

doesn't just import pi, but ALL the functions and variables from the 
math module. That is generally not a good idea. There are very 
occasional times were it is useful, but in general you should only 
import what you need:

from math import pi, sin, cos

or import the entire module:

import math




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


Re: [Tutor] Fwd: Turtle

2016-06-19 Thread Alan Gauld via Tutor
On 19/06/16 04:46, Hershel Millman wrote:

>> In pycharm, when I enter the following, it replies with the following error 
>> message:
>>
>> from turtle import *
>>

Change that to

import turtle

and it should work.



>> def drawSquare(size=100):
>>turtle.pendown()
>>turtle.forward(size)
>>turtle.left(90)
>>turtle.forward(size)
>>turtle.left(90)
>>turtle.forward(size)
>>turtle.left(90)
>>turtle.forward(size)
>>turtle.left(90)
>>
>> drawSquare(50)
>>
>> input ()


-- 
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: Loop in pre-defined blocks

2016-06-11 Thread Peter Otten
Alan Gauld via Tutor wrote:

> Forwarding to tutor list. Always use Reply All when responding to list
> mail.
> 
>> Sorry, to be a little bit more descriptive. I'd like to loop from 1 to 35
>> but within this loop there are divisions which I need to prefix that
>> particular division number.
> 
>> My output would look like this:

> 1 1
> 1 2
> 1 3
> 1 4
> 1 5
> 1 6
> 1 7
> 1 8
> 1 9
> 1 10
> 1 11
> 1 12
> 2 13
> 2 14
> 2 15
> 2 16
> 2 17
> 2 18
> 2 19
> 2 20
> 3 25
> 3 26
> 3 27
> 3 28
> 3 29
> 3 30
> 3 31
> 3 32
> 3 33
> 3 34
> 3 35

> 
> You can't specify the blocks as just (12,20,.35) since you are using
> non-contiguous blocks - you have a gap between 20 and 25.
> 
> So your definition needs to be (1,12),(13,20),(25,35) to specify
> the missing rows. But you can arguably simplify the code a little:
> 
> blocks = ((1,13),(13,21),(25,36))
> for prefix, block in enumerate(blocks):
>  for n in range(*block):
>   print prefix+1, n
> 
> its very similar to your code but using tuple expansion in range()
> cleans it up a little bit and the names hopefully make the intent
> clearer.

As Alan says, you need to specify the gaps. A simple if hackish way is to 
use negative numbers:

def expand(ends):
start = 1
for end in ends:
if end < 0:
start = -end
else:
end += 1
yield (start, end)
start = end

blocks = [12, 20, -25, 35]
for index, span in enumerate(expand(blocks), 1):
for x in xrange(*span):
print index, x


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


Re: [Tutor] Fwd: Re: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-25 Thread Alan Gauld via Tutor
On 25/05/16 17:19, Alan Gauld via Tutor wrote:

> Here is an actual session using a public telnet site:
> 
 import telnetlib
 tn = telnetlib.Telnet('telehack.com')
 response = tn.read_some()
 b'\r\nConnected to TELEH'

Oops! a cut n paste error. That line should be:

>>> print(response[:20])
b'\r\nConnected to TELEH'


 tn.close()


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


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


Re: [Tutor] Fwd: Re: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-25 Thread Alan Gauld via Tutor
On 25/05/16 14:11, Angelia Spencer wrote:
> in your code below you're telnet-ing to a website,

No, I'm telnetting to a server with the IP address mysite.com
(which is obviously fictitious, but could be any valid IP address).
There is nothing that says it's a web site. (And even some web
sites might allow telnet access, that's just an admin thing)

> I am not and when I type, >>> response = tn.read(). I get an error.
>
> >>> response=tn.read()
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: Telnet instance has no attribute 'read'
> >>>

Sorry, I misremembered the method name.
Here is an actual session using a public telnet site:

>>> import telnetlib
>>> tn = telnetlib.Telnet('telehack.com')
>>> response = tn.read_some()
>>>b'\r\nConnected to TELEH'
b'\r\nConnected to TELEH'
>>> tn.close()
>>>


There are a bunch of other read_() methods, you
need to read the help page to find out how they differ.
-- 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: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-25 Thread Alan Gauld via Tutor

> I do get the >>> in the python IDLE but within my python script/file can
> I telnet to my controller? Keep in mind when I do log into my controller
> it's command line driven.

One thing that occurred to me is that you may be better off using the
subprocess module to start an interactive telnet process. It's less easy
to control the session programmatically than with telnetlib
but it would give you the interactive element you seem to want.

It just depends on what you are trying to achieve...

-- 
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: Issue with Code

2016-04-30 Thread Alan Gauld via Tutor
On 30/04/16 22:32, Olaoluwa Thomas wrote:

> I sent this forwarded email earlier but hadn't subscribed to the mailing
> list so I guess that's why I didn't get a response.

When you first subscribe all messages are moderated so there
is a delay. Plus remember that email is pretty much the lowest
priority message type on the internet so mail can be delayed
for up to 24 hours, so you may not always get an instant
response even when everything is working as it should.

I have now taken you off moderation which should speed
things up a bit...

-- 
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: Newbie trying to get pip run on windows 7

2016-04-20 Thread eryk sun
On Tue, Apr 19, 2016 at 11:26 PM, Gustavo Davis via Tutor
 wrote:
>  But for some reason after I made the changes and saved them they wont
>  run. I mean once I go to the file and right click on them and click run
>  the cmd prompt pops up for a moment and then it just closes down and the
>  pip module never runs in python.

When you run a .py script from Explorer, Windows creates a new console
for the script's standard input and output, but this console closes as
soon as the script exits (i.e. when the python.exe process exits).
Instead you can run the script from an existing cmd shell to inherit
the shell's console.

> ;C:\Python34\Scripts\pip

There's no "Scripts\pip" directory.

Only add fully qualified directories to PATH, separated by a
semicolon, without quotes, and with no spaces between entries. You can
reference another environment variable in PATH, but only if the
variable doesn't reference other environment variables.

Add ;.PY to PATHEXT to allow running "command" instead of "command.py".

> >>> import pyperclip
> Traceback (most recent call last):
>   File "", line 1, in 
> import pyperclip
> ImportError: No module named 'pyperclip'

With PATH set up correctly, you can install this module from a cmd
shell using "pip install pyperclip".

pip searches for packages on pypi.python.org. This should work fine
for pure-Python packages and those with a WHL or EGG that's built for
your version of Python. Some source-only packages require building
extension modules. If your system isn't configured to build
extensions, look for an unofficial WHL on Christoph Gohlke's site:

http://www.lfd.uci.edu/~gohlke/pythonlibs
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: List of tuples

2016-04-20 Thread Alan Gauld via Tutor
On 20/04/16 06:52, isaac tetteh wrote:

>> Thanks things are working good now. The only problem is 
>> i want to print the for loop output on one line instead of on each line.
>> Example [1,2,3,4,5]
>> Output 
>> 1 2 3 4 5 
>> I would to do this in Jinja 

I don;t know what Jinja is but...

When you say 'print', where do you want to print it?
It seems you are using Flask so presumably the output goes to a web
page? So presumably you really want to output a string? Or do you
literally want to print to the console?

If you want a string from a list of values you can use join():

s = ' '.join([str(n) for n in outputList])

If you want to print to console you can use

for n in outputList:
   print n, # note the comma

in Python v2 or

for n in outputList:
print (n, end=' '))

in Python v3

or just combine the techniques:

s = ' '.join([str(n) for n in outputList])
print(s)


-- 
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 to source a shell script through python to set the environment variables.

2016-02-26 Thread Alan Gauld
On 26/02/16 04:49, Aneeque Khan wrote:
> The problem is that virtually any method of running a shell script
> will involve starting a separate process and setting the variables in
> that process' environment. So far as I can tell the only way to do
> what you want would be to run your shell script first then launch your
> python script from the shell script. That would mean breaking your
> current python script in two, and if you do a lot of work prior to
> launching the shell, that's probably not practical. 

Is it possible to adopt the approach described above?
Can you split your Python processing into two(or more)
parts, one before and one after the shell  script?
That will be the easiest way I suspect.

> I have recently started with python, can you direct me how we can achieve
> this by parsing the shell as a text file.

While parsing a shell script is not impossible, especially since you are
only
looking to trap the environment variables it's far from trivial.
Especially for
a beginner. I'd treat that as a last resort.

Also if the shell script does more than just set the variables its not
going
to work since you still need to run the script.

Do you have any control of the shell script content?
Or is that generated outside of your influence?
If you can control it you might be able to get the script to
dump it's environment vars to a temp file and read that.

The next question is what do you plan on doing with these once you
have them? They won't be of any value to the shell script or any other
script unless you set them again locally? Or are the just path locators?

-- 
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 to source a shell script through python to set the environment variables.

2016-02-26 Thread Aneeque Khan
Hi guys, any suggestions on this.

-Original Message-
From: Tutor [mailto:tutor-bounces+aneeque.khan=ericsson@python.org] On 
Behalf Of Alan Gauld
Sent: Tuesday, February 23, 2016 5:39 PM
To: tutor
Subject: [Tutor] Fwd: RE: How to source a shell script through python to set 
the environment variables.

Forwarding to list.
Please always use ReplyAll (or replyList) when responding to tutor.


 Forwarded Message 
Subject:RE: [Tutor] How to source a shell script through python to set
the environment variables.
Date:   Tue, 23 Feb 2016 11:14:02 +
From:   Aneeque Khan 
To: Alan Gauld 



Please see my comments with [AK]

-Original Message-
From: Tutor [mailto:tutor-bounces+aneeque.khan=ericsson@python.org] On 
Behalf Of Alan Gauld
Sent: Tuesday, February 23, 2016 4:16 PM
To: tutor@python.org
Subject: Re: [Tutor] How to source a shell script through python to set the 
environment variables.

On 23/02/16 07:29, Aneeque Khan wrote:

> env_test.sh looks like this :-
> #!/bin/bash
> export OS_AK="Aneeque"
> export OS_KHAN="KHAN"
> 
> echo "Please enter your Stack Password: "
> read -sr OS_PWD_INPUT
> export OS_PWD=$OS_PWD_INPUT
> 
> Now I want to execute the above script through python file named 
> "ak_test.py", to set these variables and access them further in the code.

Can I first ask why you are trying to do it via a shell script rather than 
using Python directly? Is this part of a bigger workflow?

[AK] :- this is the part of bigger workflow, where I get the shell script as a 
output of some processing.
 
The problem is that virtually any method of running a shell script will involve 
starting a separate process and setting the variables in that process' 
environment.

So far as I can tell the only way to do what you want would be to run your 
shell script first then launch your python script from the shell script. That 
would mean breaking your current python script in two, and if you do a lot of 
work prior to launching the shell, that's probably not practical.

[AK] :- I can`t set the variables from outside the python script as our 
workflow requires to process no. of such shell scripts. We have to process each 
shell script to set the environment and work on further.
You can assume that overall workflow have large no. of users each 
having its own values for certain environment variables. While performing any 
task for that particular user we require to set the environment first.


> def update_env(script_path):
>if "--child" in sys.argv: # executed in the child environment
>   pprint(dict(os.environ))
>else:
>   python, script = quote(sys.executable), quote(sys.argv[0])
>   os.execl("/bin/bash", "/bin/bash", "-c", "source %s; %s %s 
> --child" % (script_path, python, script))
> 
> with this approach some variables set while others not.

That surprises me since calling execl() overwrites the calling process with the 
called process, so I would not expect you to see anything in your calling 
script.

How are you testing the results?
Are you checking os.environ?
Or are you using os.getenv()?

[AK] :- I am checking like this :- 
 os.getenv("OS_AK")
os.getenv("OS_PWD")
and getting None as the result.

> Another approach used :-
> def update_env2(script):
> #pipe1 = subprocess.Popen(". %s; env -0" % script, 
> stdout=subprocess.PIPE, shell=True, executable="/bin/bash")
> pipe1 = subprocess.Popen(". %s; env" % script, 
> stdout=subprocess.PIPE, shell=True, executable="/bin/bash")
> 
> output = pipe1.communicate()[0]
> #env = dict((line.split("=", 1) for line in output.splitlines()))
> env = dict((line.split("=", 1) for line in output.split('\0')))
> 
> os.environ.update(env)

While this could work you are not really reading the environment variables you 
are simply reading the stdout. You could achieve the same by parsing the script 
as a text file.

So can you explain why you need to load these values from a shell script rather 
than setting os.environ directly?
Maybe we can solve the bigger issue.

[AK] :- In workflow neither variable names nor their values are known in 
advance. We only came to know about these at run time through the generated 
shell scripts.
I have recently started with python, can you direct me how we can achieve this 
by parsing the shell as a text file.

--
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: Finding the max value from a dictionary that does not exceed a variable's value.

2016-02-01 Thread Steven D'Aprano
On Mon, Feb 01, 2016 at 12:00:47PM -0800, Danny Yoo wrote:
> Here's a response I sent to Srinivas yesterday to further explain why
> a balanced binary tree is probably overkill for the "largest
> denomination" selection problem.  (I didn't realize that I had not
> sent the following to the list.)
[...]
> So there are several crazy avenues we can take to over-optimize this
> problem.  Just to make it clear: I think sticking to a simple linear
> scan makes the most sense.  Everything else just seems to try to make
> the problem harder than it deserves to be, akin to trying to take the
> size of a rectangle via integration.
> 
> http://homepage.usask.ca/~blb230/Math_Comics/Calculus_Comic_files/image001.gif

I'm glad you've forwarded the message to the list, because I love that 
comic. The clever thing is that it actually gets the maths right too. 
Some of the notation is a bit strange compared to what I'm used to 
(I've never seen anyone use a bare integral sign before, with no 
integrand), and I think he skipped a line, but that's definitely one to 
keep.


Thanks,



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


Re: [Tutor] Fwd:

2016-01-19 Thread Danny Yoo
My apologies for this ugliness.  Followup to the mailing list: I've
contacted the organizers of the Amrita InCTF competition and told them
that one of their members was trying to use us for cheat for answers.
I'll follow up if I hear back from the organizers.


Apparently, this is an endemic problem, if one can generalize from the
multiple posts the organizers have made about folks breaking the
rules:

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


Re: [Tutor] Fwd:

2016-01-19 Thread Danny Yoo
No.  This is definitely wrong.
On Jan 19, 2016 2:51 AM, "Deepak Nn"  wrote:

> Finding the answer is very important that's why for the competition .
>
> On Tue, Jan 19, 2016 at 4:19 PM, Deepak Nn 
> wrote:
>
>> This is for an online competition i am now participating in Amrita InCTF
>> Junior  .Please don't misunderstand and sent
>> me the code .
>>
>> On Tue, Jan 19, 2016 at 12:29 AM, Danny Yoo 
>> wrote:
>>
>>> > Please provide a python program to run a program (.exe) and get Hash
>>> > *exactly* as :
>>> >
>>> >  160 106 182 190 228 64 68 207 248 109 67 88 41 .The username to be
>>> > used is admin
>>> > .The *password* is what to be found out .The hash provided is of the
>>> > correct password .Mostly the password will be *13 char long *and has a
>>> > small chance of being all alpha characters .
>>>
>>>
>>> Hi Deepak,
>>>
>>> This doesn't seem like a beginner-level question.  If I had a guess,
>>> it sounds more like something out of a shady rent-a-coder kind of
>>> thing.
>>>
>>> Unfortunately, I don't think we can help with this.  Even if we did
>>> have the technical expertise, I still don't think we should help on
>>> this in the first place.  If I'm understanding the question correctly,
>>> you're asking for brute password breaking, which goes against most
>>> professional codes of conduct.  Example:
>>> https://www.acm.org/about-acm/acm-code-of-ethics-and-professional-conduct
>>> .
>>>
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd:

2016-01-18 Thread Danny Yoo
> Please provide a python program to run a program (.exe) and get Hash
> *exactly* as :
>
>  160 106 182 190 228 64 68 207 248 109 67 88 41 .The username to be
> used is admin
> .The *password* is what to be found out .The hash provided is of the
> correct password .Mostly the password will be *13 char long *and has a
> small chance of being all alpha characters .


Hi Deepak,

This doesn't seem like a beginner-level question.  If I had a guess,
it sounds more like something out of a shady rent-a-coder kind of
thing.

Unfortunately, I don't think we can help with this.  Even if we did
have the technical expertise, I still don't think we should help on
this in the first place.  If I'm understanding the question correctly,
you're asking for brute password breaking, which goes against most
professional codes of conduct.  Example:
https://www.acm.org/about-acm/acm-code-of-ethics-and-professional-conduct.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: creating a mspaint utility

2016-01-15 Thread Alan Gauld
On 15/01/16 08:34, Alan Gauld wrote:

> maybe you can get the mouse positions and put them in order to draw a
> line,etc.

Yes, that's a valid approach to building a multi-segment line.
Normally you store the points in a list somewhere.

> I did not want to use global variable because I am not used to this
> function in python or any lambda function because it's quite hard. 

You can avoid lambdas but I think you need to use globals to
get this to work.

You are already using some global variables in your code,
you just need to identify which ones you want to change
in your functions. That's simply done using the global
keyword, so your function would look like:

def some_function(event):
   global widget_name
   etc...
   widget_name = new_value
   etc...

It is really quite easy and allows you to store information
from inside a function so that other functions can see it.

The alternative strategy involves creating classes and
objects but that is possibly too advanced for you
just now.

The problem with your existing code is that you are
creating the widgets inside functions. But when the
function ends you lose all references to those widgets
so you cannot modify them or even read them  in any
way. (Although the variables all currently refer to
None because you use pack() in the same line as
you create them.)

>> def mouse_position():
>>show_event=app.winfo_pointerxy()
>>(X,Y)=show_event
>>if ''!=show_event :
>>show_event=app.winfo_pointerxy()
>>(X,Y)=show_event
>>print("Current mouse are on: X:{0} Y:{1}".format(X,Y))
>>label2=Label(frame1,text=str(show_event),
> relief=GROOVE).pack(side=RIGHT)
> 
> And you are right that I have to call the same code to find the
> mouse-position again and again. 

Actually you don't really need a function there, I just
realized you can simplify it by just rewriting it as a
single line:

X,Y = app.winfo_pointerxy()

> Then again I don't know what got me but I thought that I could write a
> function for mouse pressed which will print(Right Click has been
> pressed.) and take a variable to store the mouse position. Now I think I
> can modify the code to use separetely to find the coordinates but I
> don't know how to do that. Because in each right click the initialpos
> and finalpos of the mouse will change and they would have the same
> value. Should not they??

Sorry, I'm not sure what you mean there.
Can you try explaining again please?

> If you had tested the code you might have notice that each time I am
> pressing the show button the command keep printing or making a label to
> the right. How do I keep only a single label and delele the old label.

You need to create a global variable and then update that label.

> So any idea how should I store the initial and final position e.g.
> inside a function or as global value.?? 

Anything that you do  in one function that you want to be visible
in another function (or even the same one called a second time)
will need to be stored in a global variable. Variables inside
functions get deleted as soon as the function exits so you cannot
refer to them again. Each time the function gets called it creates
a new set of variables it does not use the same ones as the last
time.

> about mouse position functions? Should I reduce any of them? Is it a
> problem to put labels inside them?

Its OK to create labels inside but they will always be new
labels unless you  use global variables.


[Note 1:
Strictly speaking there are some other ways to maintain data
between function calls but I'm pretty sure they are too
esoteric for your purposes. Globals or classes are by far
the simplest solutions

Note 2:
Technically the widgets you are creating do have references
outside the function, otherwise they would be destroyed, but
to reach them involves traversing the app object's containment
tree which is relatively complicated and error prone
]

-- 
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: creating a mspaint utility

2016-01-15 Thread wolfrage8...@gmail.com
Might I also recommend Kivy as the GUI. It has a nice tutorial that is
actually on this subject.
https://kivy.org/docs/tutorials/firstwidget.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: RE: Thread output to GUI Text Field

2016-01-12 Thread Alan Gauld
On 12/01/16 09:44, Alan Gauld wrote:

> You didn't mention earlier that you were using threads!
> That significantly complicates matters.

Apologies, I just noticed that the subject line does,
although it wasn't clear that you were trying to output
between threads.

> I have found that I need to use slots and signal to pass data between Threads 
> and hence 

Does that mean you have solved the problem?
Or are you still looking for help?
If so what exactly do you want to know?
Do you have some code that doesn't work for example?

> class Panel(QtGui.QWidget):
> def __init__(self,master,parent=None):
> .
> .
> self.initUI()
> 
> 
> def initUI(self):
> #Build layout
> self.tcpControlMessages = QtGui.QPlainTextEdit()
> 
> def startThreadedProcess(self):
> self. tcpControlMessage.clear()
> self.thread.start()
> 
> @QtCore.Slot()
>  def updateMessages(self, message):
> print message
> self. tcpControlMessages.appendPlainText(message)

We can help with the threading aspects but for Qt specifics
you will probably do better on a PyQt forum.


-- 
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: Read from large text file, find string save 1st string of each line where it appeared.

2015-12-28 Thread Mark Lawrence

On 28/12/2015 15:56, sutanu bhattacharya wrote:

suppose 115160371 is my facebook id. 6174625 is the id of one of my
friends. If i give an id ,the output will be the id of those people who are
friend of 6174625.


-- Forwarded message --
From: Joel Goldstick 
Date: Mon, Dec 28, 2015 at 9:20 PM
Subject: Re: [Tutor] Read from large text file, find string save 1st string
of each line where it appeared.
To: sutanu bhattacharya 


Please don't write me.  Write to the mailing list

On Mon, Dec 28, 2015 at 10:43 AM, sutanu bhattacharya <
totaibhattacha...@gmail.com> wrote:


Hi Joel,

suppose 115160371 is my facebook id. 6174625 is the id of one of my
friends. If i give an id ,the output will be the id of those people who are
friend of 6174625.

thanking you,
Sutanu



On Mon, Dec 28, 2015 at 7:00 PM, Joel Goldstick 
wrote:




On Mon, Dec 28, 2015 at 6:20 AM, sutanu bhattacharya <
totaibhattacha...@gmail.com> wrote:


{'115160371': [45349980, 22477811, 40566595, 26947037, 16178191,
12984002,
20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
16113331, 12414642]} 

suppose 61746245  is my searching string. so o/p will
be
115160371  (1st string). Area in between third
bracket ([
]) is the searching area...


kindly help me to solve this problem..

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



def problem(6174625):
 return 115160371

You haven't really described your problem, so above is a solution for
what you asked.  What have you tried so far, and what was your result?

--
Joel Goldstick
http://joelgoldstick.com/stats/birthdays





--
Sutanu Bhattacharya








Suppose that you stop top posting?  Then it would be far easier for 
people to follow the thread.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] Fwd: Kivy Install

2015-12-18 Thread Mark Lawrence

On 17/12/2015 18:06, peter mcfarlane wrote:

Hi,
  I don't know if this is the correct forum, I am new to Python and
trying to install Kivy.  I keep getting the following error message.
Can you help?

thanks,
pete

pip install --user Kivy



[snip attempted Windows build]

I've given up trying to build anything on Windows, it's just too much 
like hard work.  So go to http://www.lfd.uci.edu/~gohlke/pythonlibs/ and 
download Kivy-1.9.0+sdl2-cp27-none-win32.whl or 
Kivy-1.9.0+sdl2-cp27-none-win_amd64.whl as appropriate.  Then use "pip 
install" against the local file name.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] Fwd: Kivy Install

2015-12-17 Thread wolfrage8...@gmail.com
 This is a general Python mailing list. For Kivy please reference:
https://groups.google.com/forum/#!forum/kivy-users
or find the developers on freenode IRC in #kivy
This is the official Kivy repository here:
https://github.com/kivy/kivy
The official Kivy site is here:
http://kivy.org/

But you are in luck I am a Kivy User too.
However I am a Linux OS user so your luck just became a little less.
For Windows I do not believe installing via Python's PIP is not
supported. However their are pre-built binaries for windows with
executable installers here:
http://kivy.org/#download

So what exactly are you trying to do? Install Kivy on your windows
machine for development or Install Kivy on other peoples computers
that use your software which is built on Kivy?

On Thu, Dec 17, 2015 at 1:06 PM, peter mcfarlane
 wrote:
> Hi,
>  I don't know if this is the correct forum, I am new to Python and
> trying to install Kivy.  I keep getting the following error message.
> Can you help?
>
> thanks,
> pete
>
>
>
>
> pip install --user Kivy
>
>
> Collecting Kivy
>   Using cached Kivy-1.9.0.tar.gz
> Requirement already satisfied (use --upgrade to upgrade):
> Kivy-Garden==0.1.1 in c:\python27\lib\site-packages (from Kivy)
> Requirement already satisfied (use --upgrade to upgrade): requests in
> c:\python27\lib\site-packages (from Kivy-Garden==0.1.1->Kivy)
> Building wheels for collected packages: Kivy
>   Running setup.py bdist_wheel for Kivy
>   Complete output from command C:\Python27\python.exe -c "import
> setuptools;__file__='C:\\Users\\edge\\AppData\\Local\\Temp\\pycharm-packaging0.tmp\\Kivy\\setup.py';exec(compile(open(__file__).read().replace('\r\n',
> '\n'), __file__, 'exec'))" bdist_wheel -d
> c:\users\edge\appdata\local\temp\tmps896gmpip-wheel-:
>   [INFO  ] [Logger  ] Record log in
> C:\Users\edge\.kivy\logs\kivy_15-12-17_35.txt
>   [INFO  ] [Kivy] v1.9.0
>   [INFO  ] [Python  ] v2.7.11 (v2.7.11:6d1b6a68f775, Dec  5
> 2015, 20:32:19) [MSC v.1500 32 bit (Intel)]
>
>   Detected Cython version 0.21.2
>   Windows platform detected, force GLEW usage.
>   Using this graphics system: OpenGL
>   WARNING: A problem occured while running pkg-config --libs --cflags
> gstreamer-1.0 (code 1)
>
>   'pkg-config' is not recognized as an internal or external command,
>   operable program or batch file.
>
>
>   WARNING: A problem occured while running pkg-config --libs --cflags sdl2
> SDL2_ttf SDL2_image SDL2_mixer (code 1)
>
>   'pkg-config' is not recognized as an internal or external command,
>   operable program or batch file.
>
>
>   running bdist_wheel
>   running build
>   running build_py
>   creating build
>   creating build\lib.win32-2.7
>   creating build\lib.win32-2.7\kivy
>   copying kivy\animation.py -> build\lib.win32-2.7\kivy
>   copying kivy\app.py -> build\lib.win32-2.7\kivy
>   copying kivy\atlas.py -> build\lib.win32-2.7\kivy
>   copying kivy\base.py -> build\lib.win32-2.7\kivy
>   copying kivy\cache.py -> build\lib.win32-2.7\kivy
>   copying kivy\clock.py -> build\lib.win32-2.7\kivy
>   copying kivy\compat.py -> build\lib.win32-2.7\kivy
>   copying kivy\config.py -> build\lib.win32-2.7\kivy
>   copying kivy\context.py -> build\lib.win32-2.7\kivy
>   copying kivy\event.py -> build\lib.win32-2.7\kivy
>   copying kivy\factory.py -> build\lib.win32-2.7\kivy
>   copying kivy\factory_registers.py -> build\lib.win32-2.7\kivy
>   copying kivy\geometry.py -> build\lib.win32-2.7\kivy
>   copying kivy\gesture.py -> build\lib.win32-2.7\kivy
>   copying kivy\interactive.py -> build\lib.win32-2.7\kivy
>   copying kivy\lang.py -> build\lib.win32-2.7\kivy
>   copying kivy\loader.py -> build\lib.win32-2.7\kivy
>   copying kivy\logger.py -> build\lib.win32-2.7\kivy
>   copying kivy\metrics.py -> build\lib.win32-2.7\kivy
>   copying kivy\multistroke.py -> build\lib.win32-2.7\kivy
>   copying kivy\parser.py -> build\lib.win32-2.7\kivy
>   copying kivy\resources.py -> build\lib.win32-2.7\kivy
>   copying kivy\support.py -> build\lib.win32-2.7\kivy
>   copying kivy\utils.py -> build\lib.win32-2.7\kivy
>   copying kivy\vector.py -> build\lib.win32-2.7\kivy
>   copying kivy\weakmethod.py -> build\lib.win32-2.7\kivy
>   copying kivy\__init__.py -> build\lib.win32-2.7\kivy
>   creating build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\adapter.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\args_converters.py ->
> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\dictadapter.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\listadapter.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\models.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\simplelistadapter.py ->
> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\__init__.py -> build\lib.win32-2.7\kivy\adapters
>   creating build\lib.win32-2.7\kivy\core
>   copying kivy\core\__init__.py -> 

Re: [Tutor] Fwd: Kivy Install

2015-12-17 Thread Alan Gauld
On 17/12/15 18:06, peter mcfarlane wrote:
> Hi,
>  I don't know if this is the correct forum, 

Not really, this is for folks learning the python language
and its standard library. kivy is a bit outside that remit.
But pip isn't so...

> ...I am new to Python and
> trying to install Kivy.  I keep getting the following error message.
> Can you help?

I'm no expert on Kivy and only a basics guy on pip but...

> c:\users\edge\appdata\local\temp\pycharm-packaging0.tmp\kivy\kivy\graphics\gl_redirect.h(8)
> : fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or
> directory
>error: command
> 'C:\\Users\\edge\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++
> for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2

Do you have Visual C++ installed?

It looks like its trying to use it to compile something...
But thats just a guess.

I've just noticed another reply saying there are binary
versions of kivy. If so I'd also recommend that route.

-- 
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: IDLE: Integrated Development and Learning Environment?

2015-10-05 Thread Wolf Halton
That is informative. I am glad the acronym is de-kluged. 

Wolf Halton
Atlanta Cloud Technology
Business Continuity Solutions 
678-687-6104
--
Sent from my iPhone. Creative word completion courtesy of Apple, Inc. 

> On Oct 5, 2015, at 2:38 PM, Alan Gauld  wrote:
> 
> I thought this might be of interest to the tutor community.
> 
> IDLE gets a new definition (with Guido's approval)...
> Also he explains why its IDLE and not Idle.
> 
> The definition has now changed from:
> 
> Integrated DeveLopment Environment
> to
> Integrated Development and Learning Environment
> 
> Partly to reflect several funky new features being added
> to help Learners.
> 
> The top posting(shock!) is by Guido so not my fault! ;-)
> 
> Alan G
> 
>  Forwarded Message 
> Subject:Re: IDLE: Integrated Development and Learning Environment?
> Date:Fri, 2 Oct 2015 17:16:42 -0700
> From:Guido van Rossum 
> Reply-To:gu...@python.org
> To:Terry Reedy 
> CC:idle 
> Newsgroups:gmane.comp.python.idle
> References:<560ef3e2.1060...@udel.edu>
> 
> <560f0c5f.4030...@udel.edu>
> 
> 
> 
> I think I was reluctant to name it after a living person. I like the
> idea of keeping it all caps and changing the interpretation.
> 
> On Fri, Oct 2, 2015 at 3:59 PM, Terry Reedy  > wrote:
> 
>On 10/2/2015 6:45 PM, Guido van Rossum wrote:
> 
>I like it. Though of course it's really named after Eric Idle. :-)
> 
> 
>Until a couple of days ago, I was planning to propose changing
>'IDLE' to 'Idle', which is what I have writen.  I am willing to go
>with that change instead.  But I presumed that you must have
>preferred the all-caps version, or perhaps not directly naming it
>after Eric, and then I thought of how to make 'IDLE' an informative
>acronym rather than a clumbsy semi-acronyn.  So now I prefer to
>change the interpretation than the spelling.
> 
>--
>Terry Jan Reedy
> 
> 
> 
> 
> -- 
> --Guido van Rossum (python.org/~guido )
> 
> 
> 
> ___
> 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: find second occurance of string in line

2015-09-09 Thread Laura Creighton
Peter Otten
>Those who regularly need different configurations probably use virtualenv, 
>or virtual machines when the differences are not limited to Python.

Use tox for this.
https://testrun.org/tox/latest/

However for development purposes it often helps to have a
--force the_one_that_I_want option (for command lines) or
a global variable, or a config file for modules.

How badly you want this depends on your own personal development
style, and how happy you are popping in and out of virtualenvs.  Many
people prefer to write their whole new thing for one library (say
elementtree) and then test it/port it against the other 2, one at a
time, making a complete set of patches for one adaptation at a time.
Other people prefer to write their code so that, feature by feature
they first get it to work with one library, and then with another, and
then with the third, and then they write the next new bit of code, so
that they never have to do a real port.

Life is messy enough that you often do a bit of this and a bit of the
other thing, even if you would prefer to not need to, especially if
hungry customers are demanding exactly what they need (and we don't
care about the other ways it will eventually work for other people).

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


Re: [Tutor] Fwd: find second occurance of string in line

2015-09-08 Thread Peter Otten
Albert-Jan Roskam wrote:

>> import lxml.etree
>>
>> tree = lxml.etree.parse("example.xml")
>> print tree.xpath("//objectdata/general/timestamp/text()")
> 
> Nice. I do need to try lxml some time. Is the "text()" part xpath as well?
 
Yes. I think ElementTree supports a subset of XPath.

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


Re: [Tutor] Fwd: find second occurance of string in line

2015-09-08 Thread Peter Otten
richard kappler wrote:

>> Do you want to find just the second occurence in the *file* or the second
> occurence within a given tag in the file (and there could be multiple such
> tags)?
> 
> There are multiple objectdata lines in the file and I wish to find the
> second occurence of timestamp in each of those lines.
> 
>> Is objectdata within a specific tag? Usually when parsing XML its the
> tags you look for first since "lines" can be broken over multiple lines
> and multiple tags can exist on one literal line.
> 
> objectdata is within a tag as is timestamp. Here's an example:
> 
> http://www.w3.org/2001/XMLSchema-instance;
> xsi:noNamespaceSchemaLocation="Logging.xsd"
> version="1.0">0381UDI132
> 2015-06-18T14:28:06.570
> 531630381UDI12015-06-18T14:27:50379
> 1306 oi="607360" on="379" ox="02503" oc="0" 
is="49787" ie="50312" lftf="N"
> lfts="7" errornb="0"
> iostate="DC00">2015-06-18T14:27:50.811 unit="inch">51.45 unit="ms">0... part.

Here's a way to get these (all of them) with lxml:

import lxml.etree

tree = lxml.etree.parse("example.xml")
print tree.xpath("//objectdata/general/timestamp/text()")


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


Re: [Tutor] Fwd: Re: Parsing/Crawling test College Class Site.

2015-06-02 Thread Alan Gauld

On 02/06/15 08:27, Alan Gauld wrote:


The following is a sample of the test code, as well as the url/posts
of the pages as produced by the Firefox/Firebug process.


I'm not really answering your question but addressing some
issues in your code...


execfile('/apps/parseapp2/ascii_strip.py')
execfile('dir_defs_inc.py')


I'm not sure what these do but usually its better to
import the files as modules then execute their
functions directly.


appDir=/apps/parseapp2/

# data output filename
datafile=unlvDept.dat


# global var for the parent/child list json
plist={}


cname=unlv.lwp

#

if __name__ == __main__:
# main app


It makes testing (and reuse) easier if you put the main code
in a function called main() and then just call that here.

Also your code could be broken up into smaller functions
which again will make testing and debugging easier.


  #
  # get the input struct, parse it, determine the level
  #

  cmd=echo ''  +datafile
  proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE)
  res=proc.communicate()[0].strip()


Its easier and more efficient/reliable to create the
file directly from Python. Calling the subprocess modyule
each time starts up extra processes.

Also you store the result but never use it...


  cmd=echo ''  +cname
  proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE)
  res=proc.communicate()[0].strip()


See above



  cmd='curl -vvv  '
  cmd=cmd+'-A  Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11)
Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11'
  cmd=cmd+'   --cookie-jar '+cname+' --cookie '+cname+''
  cmd=cmd+'-L http://www.lonestar.edu/class-search.htm;'


You build up strings like this many times but its very inefficient. 
There are several better options:

1) create a list of substrings then use join() to convert
   the list to a string.
2) use a triple quoted string to  create the string once only.

And since you are mostly passing them to Popen look at the
docs to see how to pass a list of args instead of one large
string, its more secure and generally better practice.


  cmd='curl -vvv  '
  cmd=cmd+'-A  Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11)
Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11'
  cmd=cmd+'   --cookie-jar '+cname+' --cookie '+cname+''
  cmd=cmd+'-L https://campus.lonestar.edu/classsearch.htm;'

   #initial page
  cmd='curl -vvv  '
  cmd=cmd+'-A  Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11)
Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11'
  cmd=cmd+'   --cookie-jar '+cname+' --cookie '+cname+''
  cmd=cmd+'-L
https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL;'

  proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE)
  res2=proc.communicate()[0].strip()

  print res2

  sys.exit()


Since this is non conditional you always exit here so nothing
else ever gets executed. This may be the cause of your problem?


  # s contains HTML not XML text
  d = libxml2dom.parseString(res2, html=1)

  #---Form

  selpath=//input[@id='ICSID']//attribute::value

  sel_ = d.xpath(selpath)


  if (len(sel_) == 0):
sys.exit()

  val=
  ndx=0
  for a in sel_:
val=a.textContent.strip()

  print val
  #sys.exit()

  if(val==):
sys.exit()


  #build the 1st post

  ddd=1

  post=


This does nothing since you immediately replace it with the next line.


  post=ICAJAX=1
  post=post+ICAPPCLSDATA=
  post=post+ICAction=DERIVED_CLSRCH_SSR_EXPAND_COLLAPS%24149%24%241
  post=post+ICActionPrompt=false
  post=post+ICAddCount=
  post=post+ICAutoSave=0
  post=post+ICBcDomData=undefined
  post=post+ICChanged=-1
  post=post+ICElementNum=0
  post=post+ICFind=
  post=post+ICFocus=
  post=post+ICNAVTYPEDROPDOWN=0
  post=post+ICResubmit=0
  post=post+ICSID=+urllib.quote(val)
  post=post+ICSaveWarningFilter=0
  post=post+ICStateNum=+str(ddd)
  post=post+ICType=Panel
  post=post+ICXPos=0
  post=post+ICYPos=114
  post=post+ResponsetoDiffFrame=-1
  post=post+SSR_CLSRCH_WRK_SSR_OPEN_ONLY$chk$3=N
  post=post+SSR_CLSRCH_WRK_SUBJECT$0=ACC
  post=post+TargetFrameName=None


Since these are all hard coded strings you might as well
have just hard coded the final string and saved a lot
of processing. (and code space)


  cmd='curl -vvv  '
  cmd=cmd+'-A  Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11)
Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11'
  cmd=cmd+'   --cookie-jar '+cname+' --cookie '+cname+''
  cmd=cmd+'-e
https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL?;


This looks awfully similar to the code up above. Could you have reused 
the command? Maybe with some parameters - check out string formatting 
operations. eg: 'This string takes %s as a parameter % 'a string'


I'll stop here, its all getting  a bit repetitive.
Which is, in itself a sign that you need to create some functions.

--
Alan G
Author of the Learn to Program web site

Re: [Tutor] Fwd: Re: Adding consecutive numbers

2015-05-06 Thread Dave Angel

On 05/06/2015 07:51 AM, Alan Gauld wrote:

Please use ReplyAll to include the list members.


 Forwarded Message 
Subject: Re: [Tutor] Adding consecutive numbers
Date: Wed, 6 May 2015 21:13:15 +1000
From: Whom Isac wombing...@gmail.com
To: Alan Gauld alan.ga...@btinternet.com



Thanks for the reply. I am sorry that I did not notice the mail. I am
actually using the latest version of python (3.5) in windows 7 operating
system. I have already made certain changes in the code. I understood my
mistake. The correction's are not finished yet,though. You can have a
look at it, because, I donot know what I have written is already in
right syntax or not.

Here are my code:
##Goal: Building a math program.
## two nums will be asked by the user
## they will be added
## condition: num =o:
## num will continue to be added into a list untill the second number
## For your information, a consequitive sequence of num : num--1
num1-- num+1...+n

if __name__=='__main__':
 interact()


You get an error right there, since interact() isn't defined yet.  Move 
the above two lines to the end of the file.




def interact():
 print('''Welcome to My new Math program!!
 With this program, you can find the sum of any consequitive
numbers.''')
 print('So Just add your numbers in following spaces')
 ## If anybody complaining about this function. I will have to say,
that the coding is incomplete so
 ## I will first define all my function then def interact() when I
am finishing.


def getting_numbers(first_num, second_num):
 x = [] #This is a empty list to store data
 y = [] #This is a empty list to store data
 Getting the user values:
 first_num =int(input('Please enter your first number: '))
 x.append(first_num) # adding the input in x#
 second_num =int(input('Please enter your second number: '))
 y.append(second_num) # adding the input in x#
 z =(x,y) # This is a touple containing both x and y value.
 return z


Why are you so enamored with lists?  You're returning a tuple containing 
two lists each of which has exactly one value?  Why not just return a 
tuple of first_num and second_num ?





def adding_all(x):
 total = 0
 for num in x:
 total +=num
 return total


Good function.


def remove_letter(x):
 if x != len(x):


What do you think that statement does?  It can't possibly do anything 
useful since the right side assumes that x is a collection or 
equivalent, and the left side assumes that x is a number.



 print('You did not enter a number')
 elif x != adding_all(x):
 print(Please, donot include letters)
 else:
 return x
 ## I think using a while True function to iterate all item in x
would be better.



Considering that after you call each input() function, you immediately 
call int(), I'd figure that checking for you did not enter a number is 
superfluous.






def adding_number(x,y):
 start = x[0]
 end = y[0]
 new_x = 0
 new_x_1 = 0
 while x[0]=y[0] or x[0]= 0:
 if x[0]==0:
 new_x+=1
 return new_x
 elif x[0]0 or x[0]y[0]:
 new_x_1+=x[0]
 return new_x_1
 else:
 pass
 print(You have not input a digit in order, check your
digits\n)
 print(I donot know what you mean?)



I can't make any sense out of anything in this function.

I think you need to write one function and include descriptive comments 
in it, and write code that tests it against those comments.  Then when 
you have one function that successfully runs, write a second one.





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


  1   2   3   4   >