Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #A-Level Courswork
- #Resultant Forces Calculator
- import datetime
- import math
- import sqlite3
- import string
- import random
- conn = sqlite3.connect('UserBaseV3.db')
- conn.execute("PRAGMA foreign_keys=ON")
- #turn on foreign keys
- # change this for what you are modifying
- c = conn.cursor()
- """Creates tables for the database"""
- ##c.execute('''CREATE TABLE Users
- ## (UserID INTEGER PRIMARY KEY AUTOINCREMENT,
- ## FirstName TEXT NOT NULL,
- ## Surname TEXT NOT NULL,
- ## UserName TEXT NOT NULL)''')
- ###Autoincrement automatically assigns a chronological number for the userID
- ##
- ##c.execute('''CREATE TABLE Passwords
- ## (PasswordID INTEGER PRIMARY KEY AUTOINCREMENT,
- ## PasswordKey TEXT NOT NULL,
- ## Password TEXT NOT NULL,
- ## UserID INTEGER,
- ## FOREIGN KEY(UserID) REFERENCES Users(UserID) ON DELETE CASCADE)''')
- ## #Delete on cascade ereases all user info if one piece of data is lost
- ##
- ##c.execute('''CREATE TABLE Saves
- ## (SaveID INTEGER PRIMARY KEY AUTOINCREMENT,
- ## SaveName TEXT NOT NULL,
- ## UserID INTEGER,
- ## FOREIGN KEY(UserID) REFERENCES Users(UserID) ON DELETE CASCADE)''' )
- ##
- ##c.execute('''CREATE TABLE SaveInfo
- ## (SimID INTEGER PRIMARY KEY AUTOINCREMENT,
- ## Force1 INTEGER NOT NULL,
- ## Bearing1 INTEGER NOT NULL,
- ## Force2 INTEGER NOT NULL,
- ## Bearing2 INTEGER NOT NULL,
- ## Force3 INTEGER NOT NULL,
- ## Bearing3 INTEGER NOT NULL,
- ## Force4 INTEGER NOT NULL,
- ## Bearing4 INTEGER NOT NULL,
- ## SaveID INTEGER,
- ## FOREIGN KEY(SaveID) REFERENCES Saves(SaveID) ON DELETE CASCADE)''' )
- ##
- ##conn.commit()
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- """Create New Account"""
- def CreateAccount():
- from datetime import datetime
- import time
- NewUser = True
- print("Please fill all of the fields")
- FirstName = input("First Name: ").format(str)
- Surname = input("Surname: ").format(str)
- UserNameCheck = False
- """While loop prevents multiple users with the same User Name"""
- while UserNameCheck == False:
- UserName = input("User Name: ").format(str)
- c.execute("SELECT * FROM Users WHERE UserName = '"+UserName+"'")
- fetch = c.fetchall()
- if len(fetch)>0:
- print("That user name is already taken :(")
- print("Please enter a new username: ")
- else:
- UserNameCheck = True
- date_entry = input("Please enter your Date of Birth in the format DD/MM/YYYY")
- #print(date_entry)
- Day, Month, Year = map(int, date_entry.split("/"))
- DOB = Day,Month,Year
- #print(DOB)
- #DOB = datetime.date(Year, Month, Day)
- #print(DOB)
- """Check the Password is correct"""
- check = False
- while check == False:
- password = input("\nPassword: ").upper()
- passcheck = input("\nPlease re-enter your password: ").upper()
- if passcheck == password:
- check = True
- else:
- print("Passwords did not match")
- username = 0
- EncryptedPassword, key = EncryptPassword(password,username,NewUser)
- #print(EncryptedPassword, key)
- """Insert the four fields into the table"""
- c.execute("INSERT INTO Users VALUES (NULL,?,?,?)", (FirstName,Surname,UserName))
- conn.commit()
- data = c.execute("SELECT UserID FROM Users WHERE UserName=?",(UserName,))
- UserID = c.fetchone()[0]
- #print(UserID)
- c.execute("INSERT INTO Passwords VALUES (NULL,?,?,?)", (key, EncryptedPassword, UserID))
- print("Account Created!")
- time1 = time.strftime("%H:%M")
- date1 = time.strftime("%d/%b/%Y")
- f = open("Log.txt",'a')
- #Records which user logged in and the time and ate of their login
- f.write(("User: {0}\n"
- +"Created account at: {1}\n"
- +"Date: {2}\n\n").format(UserName, time1, date1))
- f.close()
- conn.commit()
- #conn.close()
- CurrentUser = UserName
- return CurrentUser
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- """Encrypts users password with a key"""
- def EncryptPassword(word,username,NewUser):
- if NewUser == True:
- key = id_generator()
- else:
- #print(username)
- GetUID = c.execute("SELECT UserID FROM Users WHERE UserName =?",(username,))
- #print(GetUID)
- UserID = c.fetchone()[0]
- #print(UserID)
- GetKey = c.execute("SELECT PasswordKey FROM Passwords WHERE UserID =?",(UserID,))
- key = c.fetchone()[0]
- #uses a 26 character key
- #print(key)
- EncryptedPassword = "" # the Cypher text
- p = 0 # pointer for the key
- for char in word:
- EncryptedPassword += chr(ord(char) ^ ord(key[p]))
- p += 1
- if p==len(word):
- p = 0
- return EncryptedPassword, key
- def id_generator(size=26, chars=string.ascii_uppercase + string.digits):
- return ''.join(random.choice(chars) for _ in range(size))
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- """Existing user Login function"""
- def Login():
- import time
- LogPass = False
- NewUser = False
- while LogPass == False:
- username = input("Username: ")
- password = input("\nPassword: ").upper()
- #print(username,password,shiftPass)
- shiftPass = EncryptPassword(password,username,NewUser)
- #print(shiftPass[0])
- GetID = c.execute("SELECT UserID FROM Users WHERE UserName =?",(username,))
- UserID = str(c.fetchone()[0])
- #print(UserID)
- GetPword = c.execute("SELECT Password FROM Passwords WHERE UserID =?",(UserID,))
- PwordCheck = c.fetchone()[0]
- #print(PwordCheck)
- #Checks User info against database info
- #print(shiftPass[0])
- #print(PwordCheck)
- if PwordCheck == shiftPass[0]:
- print("login Successfull!")
- LogPass = True
- time1 = time.strftime("%H:%M")
- date1 = time.strftime("%d/%b/%Y")
- f = open("Log.txt",'a')
- #Records which user logged in and the time and ate of their login
- f.write(("User: {0}\n"
- +"logged in at: {1}\n"
- +"Date: {2}\n\n").format(username, time1, date1))
- f.close()
- """if the login is sucessful, the Current User' username is
- kept in the system for further use"""
- CurrentUser = username
- return CurrentUser
- else:
- print("Login not successful, please try again")
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- def GetValues():
- ForceCheck = False
- while ForceCheck == False:
- try:
- Force1 = int(input("Enter the magnitude of Force 1: "))
- Force2 = int(input("Enter the magnitude of Force 2: "))
- Force3 = int(input("Enter the magnitude of Force 3: "))
- Force4 = int(input("Enter the magnitude of Force 4: "))
- Forces = [Force1,Force2,Force3,Force4]
- ForceCheck = True
- except ValueError:
- print("That is not a number!")
- BearingCheck = False
- while BearingCheck == False:
- ExceptBearing1 = False
- while ExceptBearing1 == False:
- try:
- Bearing1 = int(input("Enter the bearing of Force 1 (0 =< x =< 360)"))
- if Bearing1 > 360:
- print("Bearing 1 is too big")
- elif Bearing1 < 0:
- print("Bearing 1 is too small")
- else:
- ExceptBearing1 = True
- except ValueError:
- print("That is not a number!")
- ExceptBearing2 = False
- while ExceptBearing2 == False:
- try:
- Bearing2 = int(input("Enter the bearing of Force 2 (0 =< x =< 360)"))
- if Bearing2 > 360:
- print("Bearing 2 is too big")
- elif Bearing2 < 0:
- print("Bearing 2 is too small")
- else:
- ExceptBearing2 = True
- except ValueError:
- print("That is not a number!")
- ExceptBearing3 = False
- while ExceptBearing3 == False:
- try:
- Bearing3 = int(input("Enter the bearing of Force 3 (0 =< x =< 360)"))
- if Bearing3 > 360:
- print("Bearing 3 is too big")
- elif Bearing3 < 0:
- print("Bearing 3 is too small")
- else:
- ExceptBearing3 = True
- except ValueError:
- print("That is not a number!")
- ExceptBearing4 = False
- while ExceptBearing4 == False:
- try:
- Bearing4 = int(input("Enter the bearing of Force 4 (0 =< x =< 360)"))
- if Bearing4 > 360:
- print("Bearing 4 is too big")
- elif Bearing4 < 0:
- print("Bearing 4 is too small")
- else:
- ExceptBearing4 = True
- except ValueError:
- print("That is not a number!")
- Bearings = [Bearing1,Bearing2,Bearing3,Bearing4]
- BearingCheck = True
- Calculations(Forces,Bearings)
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- def Calculations(Forces, Bearings):
- F = Forces
- B = Bearings
- V1 = [F[0]*math.degrees(math.cos(B[0])),F[0]*math.degrees(math.sin(B[0]))]
- V2 = [F[1]*math.degrees(math.cos(B[1])),F[1]*math.degrees(math.sin(B[1]))]
- V3 = [F[2]*math.degrees(math.cos(B[2])),F[2]*math.degrees(math.sin(B[2]))]
- V4 = [F[3]*math.degrees(math.cos(B[3])),F[3]*math.degrees(math.sin(B[3]))]
- VR = [(V1[0]+V2[0]+V3[0]+V4[0]),(V1[0]+V2[1]+V3[1]+V4[1])]
- RFMagnitude = round(math.sqrt((VR[0]**2)+(VR[1]**2)),2)
- RFBearing = round(math.degrees(math.atan(VR[1]/VR[0])),2)
- print(RFMagnitude)
- print(RFBearing)
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- def SaveSim(CurrentUserID):
- complete = False
- """While loop stops a program crash for save errors (e.g Poor save names)"""
- while complete == False:
- print("Would you like to save your simulation?")
- save = input("Save Simulation? (Y/N)").upper()
- if save == 'N':
- print("Simulation not saved")
- complete = True
- elif save == 'Y':
- print("Please name your save")
- NameOk = False
- """While loop prevents multiple saves with the same name"""
- while NameOk == False:
- SaveName = input("Save Name: ")
- """Checks new save name with prexisting saves of current user"""
- c.execute("SELECT * FROM Saves WHERE UserID = (?) AND SaveName = (?)",(CurrentUserID, SaveName))
- fetch = fetchall()
- if len(fetch)>0:
- print("You already have a simulation with that name\n")
- print("Would you like to overwrite?\n")
- """User chooses which simulation to save"""
- Overwrite = input("Overwrite? (Y/N)").upper()
- if Overwrite == 'Y':
- print("Saving Simulation")
- """Deletes old save and writes new one"""
- c.execute("DELETE FROM Saves WHERE UserID = (?) AND SaveName = (?)",(CurrentUserID, SaveName))
- c.execute("INSERT INTO Saves VALUES (NULL,?,?)",(SaveName,CurrentUserID))
- c.execute("INSERT INTO SaveInfo VALUES (NULL,?,?,?,?,?,?,?,?,?)",(Forces[0],Bearing[0],Forces[1],Bearing[1],Forces[2],Bearing[2],Forces[3],Bearing[3],))
- print("Simulation saved!")
- conn.commit()
- #conn.close()
- NameOk = True
- complete = True
- elif Overwrite == 'N':
- Discard = input("Discard save? (Y/N)").upper()
- if Discard == 'Y':
- NameOk = True
- else:
- print("Please change the save name:")
- else:
- print("input not recogonised")
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- def loadSim(CurrentUserID):
- load = False
- while load == False:
- print("Please enter the save name: ")
- savename = input("Save name: ").title()
- """Takes user save name and cross references it in the database against the current user's name"""
- c.execute("SELECT * FROM Saves WHERE UserID = '"+CurrentUserID+"' AND SaveName = '"+savename+"'")
- fetch = c.fetchall()
- if len(fetch) >0:
- conn.commit()
- Forces = c.execute("SELECT Force1, Force2, Force3 AND Force4 FROM SaveInfo WHERE UserID = (?)",(CurrentUserID))
- Bearings = c.execute("SELECT Bearing1, Bearing2, Bearing3, Bearing4 FROM SaveInfo Where UserID = (?)",(CurrentUserID))
- return Forces, Bearings
- load = True
- else:
- print("Save name not recogonised, would you like to try again?")
- TryAgain = input("Y/N")
- if TryAgain == 'N':
- load = True
- if TryAgain == 'Y':
- print("")
- #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Add Comment
Please, Sign In to add comment