Wednesday, December 6, 2017

Deck class python

this is the Deck class that works with the Card class we created earlier.

#Import the Card and the Random
#classes
from CardClass import Card
import random

class Deck:
    def __init__(self):
        #initialize the suits
        self.suits=["d","h","c","s"]
        #initialize the card list
        self.cards=[]
        #call the initializeDeck method
        self.initializeDeck()
        
        
    def initializeDeck(self):
        #this method populates the cards List
        #with cards
        #loop through the suits
        for i in range(1,4):
            suit=self.suits[i]
            #loop through the ranks
            for x in range(1,13):
                rank=x
                #create a card
                c=Card(rank,suit)
                #add to list of cards
                self.cards.append(c)
                
    def getDeck(self):
        #return a deck
        return self.cards

    def shuffleDeck(self):
        #suffle the deck
        randDeck=self.getDeck()
        random.shuffle(randDeck)
        return randDeck

    def deal(self,number):
        #get a shuffled deck
        self.newDeck=self.shuffleDeck()
        #create an empty list for the hand
        self.hand=[]
        #if there are more cards in the deck
        #than the number requestd
        if number < len(self.newDeck):
            #get that number of cards
            #and put them in the hand list
            for i in range(number):
                self.hand.append(self.newDeck[i])
            #remove those cards from the
                #suffled deck
            for c in self.hand:
                self.newDeck.remove(c)
        #return the hand      
        return self.hand


  
    
                             
        

here is the code to test the deck:

from Deckclass import Deck

d=Deck()
numberOfHands = 3
for i in range(1, numberOfHands +1):
    hand=d.deal(5)
    for c in hand:
        print("hand " + str(i),c)
       

Here are the results

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
====== RESTART: C:/Users/sconger/Documents/Python Programs/TestDeck.py ======
hand 1 3 of spades
hand 1 3 of clubs
hand 1 8 of spades
hand 1 the ace of clubs
hand 1 the queen of spades
hand 2 4 of clubs
hand 2 8 of clubs
hand 2 8 of hearts
hand 2 the jack of spades
hand 2 the ace of spades
hand 3 7 of clubs
hand 3 10 of spades
hand 3 9 of spades
hand 3 5 of clubs
hand 3 10 of hearts
>>> 

Tuesday, December 5, 2017

tkinter assigning a value to a label on a button click

So I finally figured out how to assign new text to a label on a button click. It requires a pack() command at the label and and a reconfigure() command in the button code

from tkinter import *

class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        #these set the minimum and maximum size
        #for the parent frame
        master.maxsize(width=200, height=200)
        master.minsize(width=200, height=200)
        self.master=master
        self.init_window()
        
    def init_window(self):
        
        self.myLabel=Label(self.master,text="not pressed")
        self.myLabel.place(x=10,y=10)
        #in order to be able to change the label
        #you have to pack it, though packing it seems
        #to disable the placement
        self.myLabel.pack()

        self.submit=Button(self.master,text="submit", command=self.click)
        self.submit.place(x=10,y=35)
        self.submit.pack()
        

    def click(self):
        #the configure command allows the label
        #to be changed
        self.myLabel.configure(text="button pressed")


root=Tk()
root.geometry=("800x800")

app=Window(root)
root.mainloop()

More tkinter

here is the modification of the first simple tkinter

# this makes a basic window

import tkinter

top=tkinter.Tk()
greeting = tkinter.Label(top, text="Hello World")
greeting.place(x=10, y=25)
top.mainloop()

here is the mileage class

from tkinter import *
from tkinter import messagebox

class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master=master
        self.init_window()
    def init_window(self):
        self.master.title("Mileage Calculator")
        
        self.milesLabel=Label(self.master, text="Enter the total Miles")
        self.milesLabel.place(x=10, y=10)

        self.milesEntry=Entry(self.master)
        self.milesEntry.place(x=10, y=30)

        self.gasLabel=Label(self.master, text="Enter the total gallons")
        self.gasLabel.place(x=10, y=50)

        self.gasEntry=Entry(self.master)
        self.gasEntry.place(x=10, y=75)

        self.submit=Button(self.master, text="Submit", command=self.calculate)
        self.submit.place(x=10, y=100)

        #self.message = ""
        #self.resultLabel=Label(self.master, text=self.message)

    def calculate(self):
        miles=float(self.milesEntry.get())
        gallons=float(self.gasEntry.get())
        self.mpg=miles/gallons
        self.message="Your MPG is " + str(self.mpg)
        messagebox.showinfo("Miles Per Gallon", self.message)




root=Tk()
root.geometry=("800x800")

app=Window(root)
root.mainloop()

Monday, December 4, 2017

Tip class with tkinter form

First I have created the tip class. It should be saved to the same directory as the form. Also to import it the __init__.py file must be in the directory. (just the name it doesn't need any content.). Here is the Tip class:

class Tip:
    def __init__(self, amount, tipPercent, taxPercent):
        self.amount=amount
        self.tipPercent=tipPercent
        self.taxPercent=taxPercent

    def calculateTax(self):
        if self.taxPercent >= 1:
            self.taxPercent=self.taxPercent / 100.0
        self.tax=self.amount * self.taxPercent

    def calculateTip(self):
        if self.tipPercent >=1:
            self.tipPercent=self.tipPercent / 100.0
        self.tip=self.amount * self.tipPercent

    def calculateTotal(self):
        self.total=self.amount + self.tip + self.tax
    

    def getTax(self):
        return self.tax

    def getTip(self):
        return self.tip

    def getTotal(self):
        return self.total

    def __str__(self):
        self.calculateTax()
        self.calculateTip()
        self.calculateTotal()
        return ("Amount: " + str(self.amount) + 
               " Tax: " + str(self.tax) + " Tip: " + str(self.tip) + 
               " Total: " + str(self.total))



    
        

Now here is the form class. It calls tkinter and the Tip class. I used the message box for the ouput, because it is surprisingly difficult to write to the labels.

from tkinter import *
from Tip import Tip
from tkinter import messagebox

class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master=master
        self.init_window()

    def init_window(self):
        self.master.title("Tip Calculator")
        
        self.amountLabel=Label(self.master, text="Enter Amount")
        self.amountLabel.place(x=10, y=15)

        self.amountEntry=Entry(self.master)
        self.amountEntry.place(x=10, y=35)

        self.taxLabel=Label(self.master, text="Enter tax Percent (no % sign)")
        self.taxLabel.place(x=10,y=55)
        
        self.taxEntry=Entry(self.master)
        self.taxEntry.place(x=10, y=75)

        self.tipLabel=Label(self.master, text="Enter tip Percent (no % sign)")
        self.tipLabel.place(x=10,y=105)
        
        self.tipEntry=Entry(self.master)
        self.tipEntry.place(x=10, y=125)

        self.submit=Button(self.master, text="Submit", command=self.onClick)
        self.submit.place(x=10,y=150)

    def onClick(self):
        amount=float(self.amountEntry.get())
        taxPerc=float(self.taxEntry.get())
        tipPerc=float(self.tipEntry.get())
        t=Tip(amount, tipPerc, taxPerc)
        #message = print(t)
        messagebox.showinfo("total due", t)
            

        
        


root=Tk()
root.geometry=("800x800")

app=Window(root)
root.mainloop()

There are many many improvements and refinements that could be made on this form, but it provides a basic template. I used absolute positioning, but grid positioning is more flexible. You should look it up and try to implement it.

Sunday, December 3, 2017

Tkinter

The following code is all that is needed to make a simple window

# this makes a basic window

import tkinter

top=tkinter.Tk()
top.mainloop()

Here is the form it makes.

Let's do a simple hello world. We will make the window a class that inherits from Frame. The __init__ function calls the parent __init__function. We add a Label, an Entry (text box) and a Button. When clicked the button produces a message box that says "Hello," plus the name entered into the Entry control. Here is the complete code with comments:

# this makes a basic window

from tkinter import *
from tkinter import messagebox


class Window(Frame):
    #we are inheriting from frame
    #and calling its init function
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master=master
        self.init_window()
    
    #set up the window
    def init_window(self):
        #set title of the window
        self.master.title("Hello")
        #self.pack(fill=BOTH, expand=1)
        # a label to prompt the user
        self.prompt=Label(self.master, text="Enter your name")
        #using absolute placement
        self.prompt.place(x=10,y=25)
        #creating a text box
        self.nameEntry=Entry(self.master)
        self.nameEntry.place(x=10,y=55)
        #adding a button
        self.submit=Button(self.master, text="submit", command=self.hello)
        self.submit.place(x=10,y=100)
        #self.result = Label(self.master,text="")
        #self.result.place(x=10, y=360)
        #self.result.pack()
        
    def hello(self):
        greeting = "Hello, " + self.nameEntry.get()
        messagebox.showinfo("hello", greeting)
        

     

        


root=Tk()
root.geometry=("500x400")

app=Window(root)
root.mainloop()



     

Here is the form with a name entered.

Here is the Messagebox

Thursday, November 30, 2017

dictionary

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> myList=[1,2,3,4,5]
>>> import random
>>> random.shuffle(myList)
>>> print (myList)
[2, 4, 3, 5, 1]
>>> #dictionary
>>> #hash
>>> #key value pair
>>> products={"IPad" : 850, "Surface" : 1200, "Kindle" : 100, "Galaxy" : 500}
>>> print(products["Kindle"])
100
>>> 

Wednesday, November 29, 2017

Security SQL from Afternoon Class

select * from Person

Create login bob with password='password'
use Community_Assist
Create user bobuser for login bob
Create role grantapplicationrole
Grant select, insert on GrantRequest to grantapplicationRole
Grant exec on usp_Register to grantapplicationrole
Grant exec on usp_login to grantApplicationrole
Grant select on GrantType to grantApplicationrole
alter role grantApplicationrole add member bobuser

Tuesday, November 28, 2017

Classes and lists

This shows a partial deck class using the Card class from earlier in this blog

from CardClass import Card

class deck:
    def __init__ (self):
        self.cards=[]
        self.populateDeck()

    def populateDeck(self):
        suits=["h","d", "c", "s"]
        for s in suits:
            for i in range(1,14):
                card=Card(i,s)
                self.cards.append(card)

    def getDeck(self):
        return self.cards


def main():
    d=deck()
    myDeck=d.getDeck()
    for c in myDeck:
        print(c)

main();
    

        

here are the grade, and student classes.

#Get GPA
#The grade class stores the information
#for a grade
class grade:
    def __init__(self,course,gpoint,credit):
        self.course=course
        self.gpoint=gpoint
        self.credit=credit
    #allow another class to get the values
    def getCourse(self):
        return self.course
    def getGradePoint(self):
        return self.gpoint
    def getCredits(self):
        return self.credit
    def __str__(self):
        return self.course + " " + str(self.gpoint) + " " + str(self.credits)

#student class includes GPA generated from a list of grades
class student:
    def __init__(self,sid,name,email):
        self.sid=sid
        self.name=name
        self.email=email
        self.grades=[]#empty list for grades

    #this method adds grade objects to the grades list
    def addGrades(self, gradepoint):
        self.grades.append(gradepoint)

    def calculateGPA(self):
        #initialize variables
        self.gpa=0
        weight=0
        total=0
        #make sure the list is not empty
        if len(self.grades) != 0:
            #loop throug the objects in the grades list
            #get the weight by multiplying credits and grades
            for g in self.grades:
               weight += g.credit * g.gpoint
               total += g.credit #get total credits
            #caluclate GPA
            self.gpa=weight / total

    def __str__(self):
        self.calculateGPA() #call the calculate method
        #string to be output if you print the class
        return self.sid + " " + self.name + " " + self.email + " " + str(self.gpa)


def main():
    #initialize the student object
    s=student("122453","John Depp",'jd@gmail.com')
    stop="n"
    #loop to enter grades
    while stop=="n":
        course = input("Enter the course name: ")
        gp = float(input("Enter the final grade: "))
        cr=int(input("Enter the number credits: "))
        #create a grade object
        g=grade(course, gp, cr)
        #add it to the student's grade list
        s.addGrades(g)
        stop = input("Do you want to stop? 'n' to continue ")
    print(s)#print the __str__ from student
        
            
main() 














    

Monday, November 20, 2017

Mongo Creating the Database and adding records--morning

Here are the JSON records we created

zoo
animals
[{
  name : "Zack the Zebra",
  type : "Zebra",
  habitat : "African Savannah",
  age : "5 years",
  diet : "grass"
},
{
  name : "Ellie the Elephant",
  type : "Indian Elephant",
  habitat : "East Asian Jungle",
  age : "22 years",
  diet : "Peanuts"
},
{
  name : "Gennie the Giraff",
  type : "Giraff",
  habitat : "African Savannah",
  diet : "leaves"
}]

habitats
[{
   name : "African Savanah",
   description : "grass trees and exotic animals",
   inhabitants : ["Zack the Zebra", "Gennie the Giraff"]
},
  
{
   name : "East Asian Jungle",
   description : "Wet tropical, palms and ferns",
   inhabitants : "Ellie the Elephant"
}]
  

A picture of the insert of animals

Afternoon class

productReviews
products
[
{
   name : "Ipad",
   maker : "Apple",
   price : 830.99,
   color : "silver",
   quantity : 14, 
   rating : [4,3,5,3, 5]
},
{
   name : "Apple Watch",
   maker : "Apple",
   price : 400.99,
   color : ["silver","white", "black"],
   quantity : 20,
   rating : [4,3,5,3,5,2,5]
},
{
   name : "Surface",
   maker : "Microsoft",
   price : 1200.99,
   color : ["blue","white", "black"],
   quantity : 5 
}
]

reviews
[{
    email : "spconger@gmail.com",
    product : "Ipad",
    date : "11/20/2017",
    rating : 4,
    review : "Ipads are fun but hard to do real work on" 
},
{
   email : "Joe@msn.com",
   product : "Surface",
   date : "11/20/2017",
   rating : 4
}]

Thursday, November 16, 2017

Mileage and Card Classes

Mileage class

#miles per gallon
# as class

class Mileage:
    def __init__(self, miles, gallons):
        self.miles=miles
        self.gallons=gallons
        

    def setMiles(self, miles):
        self.miles=miles

    def mpg(self):
        self.milesPerGallon=self.miles / self.gallons

    def getMPG(self):
        return self.milesPerGallon

    def __str__(self):
        self.mpg()
        return "Your mpg is " + str(self.getMPG())
    

def main():
    mls = float(input("How many total miles "))
    gals = float(input("How many gallons "))
    mileage=Mileage(mls, gals)
    print (mileage)

main()











    

Class version of Card Class

#Card
class Card:
    def __init__(self, rank, suit):
        self.rank=rank
        self.suit=suit
        self.value=0
        
    def getRank(self):
        return self.rank

    def getSuit(self):
        return self.suit

    def getValue(self):
        if self.rank > 10:
            self.value=10
        else:
            self.value=self.rank
        return self.value
    
    def __str__(self):
        self.name=""
        su=""
        if self.suit =="d":
            su="diamonds"
        elif self.suit=="h":
            su="hearts"
        elif self.suit=="s":
            su="spades"
        else:
            su ="clubs"
        if self.rank >1 and self.rank< 11:
            self.name=str(self.rank) + " of " + su
        if self.rank==1:
            self.name="the ace of " + su
        if self.rank==11:
            self.name="the jack of " + su
        if self.rank==12:
             self.name="the queen of " + su
        if self.rank==13:
             self.name="the king of " + su
        return self.name
        
        
def main():
    
    c=Card(13,"h")
    print(c)
    print(c.getValue())

main()

    
    





    

Modified version of Card Class

#Card
class Card:
    def __init__(self, rank, suit):
        self.rank=rank
        self.suit=suit
        self.value=0
       
        
    def getRank(self):
        return self.rank

    def getSuit(self):
        return self.suit

    def getValue(self):
        if self.rank > 10:
            self.value=10
        else:
            self.value=self.rank
        return self.value

    def getSuit(self):
        self.su=""
        if self.suit =="d":
            self.su="diamonds"
        elif self.suit=="h":
            self.su="hearts"
        elif self.suit=="s":
            self.su="spades"
        else:
            self.su ="clubs"
        return self.su

    
    
    def __str__(self):
        
        if self.rank >1 and self.rank< 11:
            self.name=str(self.rank) + " of " + self.getSuit()
        if self.rank==1:
            self.name="the ace of " + self.getSuit()
        if self.rank==11:
            self.name="the jack of " + self.getSuit()
        if self.rank==12:
             self.name="the queen of " + self.getSuit()
        if self.rank==13:
             self.name="the king of " + self.getSuit()
        return self.name
        
        
def main():
    
    c=Card(13,"h")
    print(c)
    print(c.getValue())

main()

    
    





    

Wednesday, November 15, 2017

json Examples

--Books and Book reviews-Reviewer Registered
Books, Authors, Reviewers, Reviews, publishers

Books
{
  _id : 1,
  title : "Grapes of Wrath",
  author : "John Steinbeck",
  pubYear : "1939",
  descript : "A story of one family's journey to  California during the dustbowl"
}
{
  _id : 2,
  title : "Best Scifi and Fantasy 2015",
  author : ["Neil Gaimen", "C. S. Lewis", "Ray Bradbury"],
  pubYear : "2015",
  descript : "A collection of classic scifi stories"
}

Author
{
   _id : 1,
   authorName : "Neil Gaimen",
   nationality : "English",
   book : [
            {
      title : "Neverwhere",
             descript: "A man becomes lost in the London underground"
      },
             {
               title : "American Gods",
               descript : "Ancient gods try to survive in modern America"
       }
            ]
}

  

Afternoon Example

movie
{
  _id : 1,
  title : "Step Brothers",
  year : 2008,
  actor : ["John C. Riley", "Will Ferrell"],
  director : "Adam McKay"
}

actor
{
   _id : 1,
   actor_name : "Will Ferrell",
   movies :[
            {title: "Step Brothers", year : 2008},
            {title: "Elf", year : 2003},
            {title: "Anchorman", year : 2004}
           ]

}

Thursday, November 9, 2017

First Classes

#First class example
#dice

from random import randrange

class die:
    def __init__(self, sides):
        self.sides=sides
        self.value=1

    def roll(self):
        self.value=randrange(1,self.sides+1)

    def getValue(self):
        return self.value

    def setValue(self, value):
        self.value=value


def main():
    again="y"
    num=int(input("How many sides "))
    while again=="y":
    
        die1=die(num)
        die1.roll()
        die2=die(num)
        die2.roll()
        print (die1.getValue(),die2.getValue())
        again=input("Enter y to roll again ")

main()
                            
    
    

Two classes

#item and sale and receipt

class item:
    def __init__(self, name, price):
        self.name=name
        self.price=price
        
    def getName(self):
        return self.name

    def getPrice(self):
        return self.price
    

class cart:
    def __init__(self):
        self.items=[]
        
    def addItem(self, product):
        self.items.append(product)

    def getTotal(self):
        total=0
        for i in self.items:
            total+=i.price
        return total

def main():
    more = "y"
    c=cart()
    while more=="y":
        name = input("Item Name ")
        price = float(input("Item Price "))
        product=item(name, price)
        c.addItem(product)
        more = input("y to continue")
    print (c.getTotal())

main()