Welcome to my page of code, in which you'll find utilities to applications which really serve no purpose. Some I wrote for fun, some I wrote to make my life easier, some are assignments, some are just snippets. Nonetheless, enjoy them all.
Projects In Progress
DescribeMe
A small utility which you can enter an image path to and have a program return you a description of it. Useful if you're blind. Currently, it doesn't work, but here is what I have so far.
This is actually a fully completed utility that allows you to merge an audio track of choice to a video track of choice. It needs some work before I can compile it into a Windows executable, but for now it works just fine as a python script
Show Code>
from moviepy.editor import *
import tkinter as tk
from tkinter import filedialog
from time import sleep
from os import getlogin
from sys import exit
import msvcrt
def main():
root = tk.Tk()
videopath = filedialog.askopenfilename(title="select your video track")
audiopath = filedialog.askopenfilename(title="Select your audio track of filetype WAV, MP3, or OGG")
root.withdraw()
exportname = input("Enter Name Of File To Save To")
extention = ".mp4"
exportname = "/music/" + exportname + extention
user = getlogin()
fullpath = "c:/users/" + user + exportname
print("Merging tracks...")
videotrack = VideoFileClip(videopath)
audiotrack = AudioFileClip(audiopath)
merged = videotrack.set_audio(audiotrack)
merged.write_videofile(fullpath, temp_audiofile="c:/users/public/gay.mp3")
sleep(5)
print("Merge complete. This file has been saved in your Music folder")
sleep(2)
main()
print("Press Q to quit or M to merge more tracks")
while True:
if msvcrt.kbhit():
close = msvcrt.getch()
if close == b'q':
exit()
elif close == b'm':
main()
Last Update Date: April 22, 2020
Stations
I used to be on a track team, and during snow days or days when we couldn't go to school, I'd still have to work out in some way. I looked into various interval timers from the app store but most of them were payed in some way. What I wanted was a program that would run me through a set of stations for what we call high intensity interval training. So, say I had a format such as: pushups, squats, planks, situps, mountain climbers, exploding lunges, russian twists, burpees. I would enter that, and I'd enter how long I wanted one station to last. Then I'd run the workout. Check it out.
notes:
The code that checks for user administrator rights was not written by me
Sounds not included
You can only program up to eight different stations as of now, but I plan on rewriting a large portion of this program to make it run without such restrictions.
Show Code
import time
from playsound import playsound
import sys
import os
import webbrowser
import sys, os, traceback, types
def isUserAdmin():
"""@return: True if the current user is an 'Admin' whatever that
means (root on Unix), otherwise False.
Warning: The inner function fails unless you have Windows XP SP2 or
higher. The failure causes a traceback to be printed and this
function to return False.
"""
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print("Admin check failed, assuming not an admin.")
return False
else:
# Check for root on Posix
return os.getuid() == 0
def runAsAdmin(cmdLine=None, wait=True):
"""Attempt to relaunch the current script as an admin using the same
command line parameters. Pass cmdLine in to override and set a new
command. It must be a list of [command, arg1, arg2...] format.
Set wait to False to avoid waiting for the sub-process to finish. You
will not be able to fetch the exit code of the process if wait is
False.
Returns the sub-process return code, unless wait is False in which
case it returns None.
@WARNING: this function only works on Windows.
"""
if os.name != 'nt':
raise RuntimeError("This function is only implemented on Windows.")
import win32api, win32con, win32event, win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType,types.ListType):
raise ValueError("cmdLine is not a sequence.")
cmd = '"%s"' % (cmdLine[0],)
# XXX TODO: isn't there a function or something we can call to massage command line params?
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
showCmd = win32con.SW_SHOWNORMAL
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
else:
rc = None
return rc
def test():
"""A simple test function; check if we're admin, and if not relaunch
the script as admin.""",
rc = 0
if not isUserAdmin():
rc = runAsAdmin()
else:
rc = 0
return rc
if __name__ == "__main__":
test()
def set_stations():
print("Creating workout:")
global stat_1
stat_1 = input("enter name of Station 1:")
global stat_2
stat_2 = input("enter Name Of station 2:")
global stat_3
stat_3 = input("enter name of station 3:")
global stat_4
stat_4 = input("enter name of station 4:")
global stat5
stat_5 = input("enter name of station 5:")
global stat_6
stat_6 = input("enter name of station 6:")
global stat_7
stat_7 = input("enter name of station 7:")
global stat_8
stat_8 = input("enter name of station 8")
while True:
stat_time = input(" how many seconds would you like for each station to be? Enter a number:")
if (stat_time.isdigit()):
break
else:
print("Sorry, but you have to enter a number.")
global sets
while True:
sets = input("how many rotations would you like to do? Enter a number:")
if (sets.isdigit()):
break
else:
print("Sorry, you must enter a number.")
global rest
while True:
rest = input("How many seconds would you like to rest between stations? Enter a number:")
if (rest.isdigit()):
break
else:
print("sorry, you must enter a number")
global save
save = input("enter name of workout. If you do not wish to save, press enter to skip:")
if len(save) > 0:
save_workout()
else:
stat_time = int(stat_time)
global new_time
new_time = stat_time / 2
sets = int(sets)
rest = int(rest)
print("Successfully created workout")
def workout():
endstart = os.path.join(sys.path[0], "endstart.wav")
halfway = os.path.join(sys.path[0], "halfway.wav")
print(stat_1)
playsound(endstart, False)
time.sleep(new_time)
print("You're halfway done! Great job!")
playsound(halfway, False)
time.sleep(new_time)
print("rest")
playsound(endstart, False)
time.sleep(rest)
print(stat_2)
playsound(endstart, False)
time.sleep(new_time)
print("You're halfway done! Great job!")
playsound(halfway, False)
time.sleep(new_time)
print("rest")
playsound(endstart, False)
time.sleep(rest)
print(stat_3)
playsound(endstart, False)
time.sleep(new_time)
print("You're halfway done! Great job!")
playsound(halfway, False)
time.sleep(new_time)
print("rest")
playsound(endstart, False)
time.sleep(rest)
print(stat_4)
playsound(endstart, False)
time.sleep(new_time)
print("You're halfway done! Great job!")
playsound(halfway, False)
time.sleep(new_time)
print("rest")
playsound(endstart, False)
time.sleep(rest)
print(stat_5)
playsound(endstart, False)
time.sleep(new_time)
print("You're halfway done! Great job!")
playsound(halfway, False)
time.sleep(new_time)
print("rest")
playsound(endstart, False)
time.sleep(rest)
print(stat_6)
playsound(endstart, False)
time.sleep(new_time)
print("You're halfway done! Keep it up!")
playsound(halfway, False)
time.sleep(new_time)
print("rest")
playsound(endstart, False)
time.sleep(rest)
print(stat_7)
playsound(endstart, False)
time.sleep(new_time)
print("Keep pushing, your halfway there!")
playsound(halfway, False)
time.sleep(new_time)
print("rest")
playsound(endstart, False)
time.sleep(rest)
print(stat_8)
playsound(endstart, False)
time.sleep(new_time)
print("Give it your all! This is your last station!")
playsound(halfway, False)
time.sleep(new_time)
playsound(endstart, False)
def save_workout():
print("saving...")
extention = ".sst"
filename = save + extention
f = open(filename, "x")
f.close()
f.open(filename, "w")
data = f"{stat_1} \n {stat_2} \n {stat_3} \n {stat_4} \n {stat_5} \n {stat_6} \n {stat_7} \n {stat_8} \n {new_time} \n {sets} \n {rest}"
f.write(data)
f.close()
print("workout",save,"has been saved")
print("Welcome To SimplyStations! for a list of commands, type help.")
while True:
terminal = input(">>>")
if terminal == "help":
print("Stations command list: \n create. Creates a new stations workout. \n start. Starts the workout. \n Load. Loads a saved workout \n about. Information about the Stations program \n settings. Starts the settings wizzard \n documentation. Opens online documentation")
elif terminal == "about":
print("Stations, Beta 1. \n This program was developed and is distributed by Mason Tilley. \n It is licensed under the General Public License, version 2.0. \n It was created during a statewide sports dead period at the time of the CorronaVirus pandemic of 2020 as a utility to help keep the developer in shape. \n For more information, please see www.that-domain.com \n Or type documentation to view additional help for this program.")
elif terminal == "create":
set_stations()
elif terminal == "start":
try:
sets
except NameError:
sets = "none"
if sets == "none":
print("You have not loaded or created a workout.")
else:
print("Starting workout")
time.sleep(2)
sets_completed = 0
sets_completed = int(sets_completed)
while sets_completed < sets:
workout()
print("Rest for five minutes")
time.sleep(300)
elif terminal == "load":
print("feature not available yet")
elif terminal == "documentation":
webbrowser.open("https://www.that-domain.com/ssdocs.html")
else:
print("Invalid command")
PowerSaver.py
I know I shouldn't, but I keep my laptop plugged in constantly. That isn't good for it at all. So, I wrote a script to tell me how long I had kept my battery charged for in a system tray icon, and when unplugged, notify me when my battery level was between 15 and 90 percent. The system tray part still needs some working on, and the fix is pretty simple, I just need to do it. Here's what I got so far.
notes:
The image for the system tray icon is from windows itself.
Show Code
#Powersaver: a script to remind you to exercise your battery
#normal lines that are commented out are reserved for later updates and when I can test them more
import psutil
import os
import time
from win10toast import ToastNotifier
import pystray
from PIL import Image
def check_battery():
#defining and getting all of our battery info\
battery = psutil.sensors_battery()
global plugged
plugged = battery.power_plugged
global percent
percent = battery.percent
if plugged==False:
plugged="Not Plugged In"
else:
plugged = "Plugged In"
def check_charger():
#to be executed after battery is below fifteen percent
#waiting five minutes after the notification
time.sleep(300)
check_battery()
if plugged == "Plugged In":
#if the user plugged in the charger, then exit the function
return
else:
#if they didn't, then put the computer to sleep
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
def notify():
#to be run once the battery reaches 15 percent or below
toaster = ToastNotifier()
toaster.show_toast("Battery Low","Your Battery is below 15 percent. If you do not plug in your charger within five minutes, PowerSaver will put your computer to sleep")
def log():
#tracks the amount of time the charger has been plugged in
global message
message = " "
time = 0
time += 30
if time < 86400:
pass
if time > 86400 and time < 172800:
message = "Your battery has not been discharged for over a day."
elif time > 172800 and time < 259200:
message = "You have not unplugged your laptop for over two days."
elif time > 259200 and time < 345600:
message = "Your battery has been full for more than three days."
elif time > 345600:
message = "You have left your pc pluggged in for over four days running. Consider giving your battery some exercise."
#def system_tray(message):
image = Image.open("C:/Windows/WinSxS/x86_netfx4-aspnet_webadmin_images_b03f5f7f11d50a3a_4.0.15788.0_none_78cd9d6ad18ae0c1/ASPdotNET_logo.jpg")
display = "powerSaver" + message
icon = pystray.Icon("Charge INFO", image, display)
icon.run()
def main():
#looping to see if the charger is plugged in or not
while True:
#Running our check battery function to update the battery info that may have changed since we checked last
check_battery()
if plugged == "Plugged In":
#call the log function to keep track of how long this has been the case
log()
#check if the charger is plugged in just because the user is charging or it's because they just like to have their computer plugged in all the time
while True:
check_battery()
if percent > 90:
#they just like it plugged in
#stop looping
break
elif percent == 90:
#let them know they can unplug now
toaster = ToastNotifier()
toaster.show_toast("Battery Almost Full","Your battery level has reached 90 percent. you may unplug your charger now")
break
else:
#they're still charging, so wait 30 seconds then loop again to check on percents
time.sleep(30)
#Now returning to the first loop to see if the charger is still plugged in and if it is, wait 30 seconds then check again
time.sleep(30)
else:
#the charger is absent so stop checking for it
break
#Now that we know the charger is gone, we'll check every minute if the battery is at 15 percent
while True:
check_battery()
if percent > 15:
system_tray(percent)
time.sleep(30)
else:
notify()
check_charger()
#Now loop main forever
while True:
main()
Speedinfo
This is a script I'm working on that will use
speedtest.net
to check the speed of the network you are connected to and show the results in your system tray. It runs quietly in the background, updating your system tray icon to reflect each new test it runs. Currently, this script suffers from one major flaw, it doesn't run more than once. But, for the one time it does run successfully, it does great. Check it out
Notes:
The image for the system tray icon comes from windows itself.
Relies on
Pystray
for displaying system tray icons and "speedtest" (pip install speedtest) for testing networks.
Show Code
import systray
from time import sleep
import speedtest
import pystray
from PIL import Image
def display_tray(message):
image = Image.open("C:/Windows/WinSxS/x86_netfx4-aspnet_webadmin_images_b03f5f7f11d50a3a_4.0.15788.0_none_78cd9d6ad18ae0c1/ASPdotNET_logo.jpg")
icon = pystray.Icon("tray", image, message)
icon.run()
return
def check_speed():
print("Getting ping")
st = speedtest.Speedtest()
servernames =[]
st.get_servers(servernames)
ping_ms = st.results.ping
print("getting download")
dl = st.download()
dl /= 1000000
dl = str(round(dl, 2))
print(dl)
print("getting upload")
ul = st.upload()
ul /= 1000000
ul = str(round(ul, 2))
print(ul)
message = f"SpeedInfo -- DL: {dl} MB/S, UL: {ul} MB/S, Ping: {ping_ms} MS"
print("updating system tray")
display_tray(message)
while True:
check_speed()
Password Generator
This is a really early draft of a password generator that I threw together rather quickly and which works well enough for the time being. You currently are just asked to enter a password length, and then that many characters are chosen randomly from a string of all characters. Currently the only requirements I have built into it are making sure you can only generate keys of reasonable length, as well as ensuring that at least one number is present in the end result. Other than that it's really not very dynamic, you can't specify characters you'd like to include or specify any password rules the program needs to follow, but like I said, it's a draft. Enjoy!
Show Code
#Password generator
import pyperclip #to copy passwords to the clipboard
import random #for randomly choosing characters
import string #instead of defining a list of characters
password = "" #to be appended to later
#define string of all characters and convert it to a list
pass_chars = list(string.ascii_letters + string.digits + string.punctuation)
while True:
try:
length = int(input("how many characters would you like your password to be?"))
except:
print("That... is not a number. Type one and you can proceed.")
continue #Jump back to the top of the loop and try again
if length > 128:
print("It is highly unlikely you'll need a password more than 128 characters long.\nEnter a smaller number")
continue
elif length < 8:
print("Come on man, your password needs to be secure.\nType in a bigger number")
continue
break
for x in range(0,length): #Loop for the user specified length
random.shuffle(pass_chars) #Shuffle the list in place
x = random.choice(pass_chars) #Pick a character
password += x #Append it to password
#Try to find out if any of the chars in password are numbers or not
num = False
for i in password:
if i.isdigit():
num = True
if num == False:
password = password[:-1] #remove the last character
password += random.choice(string.digits) #replace it with a number
print("Your password is:\n",password)
pyperclip.copy(password)
print("It has been copied to your clipboard.\nPaste it somewhere safe as this program does not save generated password results")
Projects That Are More or Less Finished
Save For Later
This is actually a very cool program. It's a service that I wrote because I do a lot of web surfing on my phone, and a lot of the time I come across links that I want to download, but obviously doing it on mobile is kinda not the way to go. So instead, I developed this script, which runs in the background on your PC and checks for new downloads, which you can send to it via a serverside php page. It works well, but is not without its flaws. For instance, anyone in the world could go to that page and post links to the script, and download anything they wanted to your machine: viruses, malware, etc. Protecting the page with http o auth or similar is up to you as a user. This script also cannot download from links that redirect to files, yet, which is a feature I plan to add. Check it all out below.
For testing purposes, all program data is saved to c:\users\public\saveforlater so as to cause the least amount of errors when debugging file creation
Show Code (Client)
import datetime
import os
import requests
from time import sleep
from win10toast import ToastNotifier
#Define a function to be run at program execution
def initialize():
#Check For the current link
url = 'https://www.that-domain.com/saveforlater/links.linkdata'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
filecontent = requests.get(url, headers=headers)
#write it to link 0, which will always be the link last retrieved
global link0
link0 = filecontent.content.decode()
print(link0)
#Now open up the file that had the last link retrieved before the program shut down in it
try:
os.mkdir("c:/users/public/saveforlater")
except FileExistsError:
pass
try:
f = open("c:/users/public/SaveForLater/lastlink.txt", "x")
except FileExistsError:
pass
f = open("c:/users/public/SaveForLater/lastlink.txt", "r")
saved_url = f.read()
f.close()
#compare link 0, the current link, to the link we got from the file
if link0 == saved_url:
pass
else:
#since our download function downloads the url in the link1 variable, set link 0 to link1
global link1
link1 = 0
link1 = link0
download()
#now that we've checked to make sure we got the most recent link downloaded, define the function to check for new urls which we'll run later
def check_for_new():
#access the file with links in it and append the last one to link one
print("checking for new URL's")
url = 'https://www.that-domain.com/saveforlater/links.linkdata'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
filecontent = requests.get(url, headers=headers)
global link1
link1 = filecontent.content.decode()
global link0
#compare link 0, our last link to link1, the link we just got
if link0 == link1:
pass
else:
download()
save()
def log(err):
current = datetime.datetime.now()
global link1
logmessage = f"On {current}, there was an error while attempting to download the file found at\n{link1}\nThe program error was: \n{err}"
try:
f = open("c:/users/public/SaveForLater/saveforlater.log", "x")
except FileExistsError:
pass
f = open("c:/users/public/SaveForLater/saveforlater.log", "a")
f.write(logmessage)
f.close()
def download():
global link1
if link1.find('/'):
filename = link1.rsplit('/', 1)[1]
filepath = 'c:/users/mason/downloads/'
location = filepath + filename
filename_message = f"Now downloading {filename}"
toaster = ToastNotifier()
toaster.show_toast("New Download Detected!",filename_message)
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
dl = open(location,'wb')
try:
r = requests.get(link1, headers=headers, stream=True)
except Exception as err:
log(err)
toaster.show_toast("Error downloading!","Unfortunately, there was an error while attempting to download this file. Please consult the \"SaveForLater\" program log found at: \"c:\\users\\public\\saveforlater\\saveforlater.log\" for more details.")
return
for chunk in r.iter_content(1024):
dl.write(chunk)
dl.close
toaster.show_toast("Your download has finished!","SaveForLater has finished downloading your file")
def save():
global link0
global link1
f = open("c:/users/public/SaveForLater/lastlink.txt", "w")
f.write(link1)
f.close()
link0 = link1
initialize()
while True:
check_for_new()
sleep(30)
Show Code (Server)New Download -- Save For Later