Programs And Scripts

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.

Third-Party Dependencies
Show Code
import PIL
import pytesseract
import tkinter as tk
from tkinter import filedialog
import pyperclip

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()
open_image = image.open(file_path)
image_description = pytesseract.image_to_string(open_image)
pyperclip.copy(image_description)
print(image_description)
or Last Updated on April 22, 2020

MergeUtil

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

Third Party Dependencies
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:
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:
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:
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!

Third Party Dependencies
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.

Third-Party Dependancies: Notes:
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) <html> <head> <title>New Download -- Save For Later</title> </head> <form action="/code.php" method ="post"> <h1>File Download</h1> <p>If you'd like to autamate a new download, you can do so from this page. Enter the download link in the box below and click "Download On PC."</p> <h2>Enter link</h2> <p>Enter the URL of the file you wish for your computer to download later:</p> <br> <input name="link" type="text" title ="Link" autocomplete="off" size="200" maxlength="200"><br> <input type="submit" value="Download On PC"> </form> </body> </html>
Last Update Date: Wednesday September 16, 2020 Changes:
  • added exception handling for links that couldn't be opened by the requests module
  • added a new log function to save those errors

    PySpam

    If you're ever feeling deviase, this is the program for you. It's a script that will continually spam an input number with an input message for an input number of times. It leverages an applescript via command line, so you must have a mac to run it. But don't worry, you won't have to download the extra script. If PySpam doesn't find it in the working directory, it will be generated. Have fun, and use responsibly.

    Notes:
    • You must run this app with python3. Python 2.7 comes installed on macs by default, but you'll need to download the newest version and use that instead.
    Show Code #PySpam, automated message spamming in python """This is a program designed to continually send messages via applescript on your mac after you enter a phone number, message, and amount of times you'd like to send the message. You are currently working with PySpam 0.8. Known errors are: typing no in at the final confirmation prompt does not work properly, as it continues to send messages with the input information anyway Planned improvements: add network connectivity checking rewrite the main function more cleanly and with less looping fix errors Improvements from PySpam 0.7 are: added an init function that makes sure the applescript file is available, reduces the need for an additional file in the package as it will be created if nonexistent added a function to return a properly formatted phone number for easier readability """ import os #Define some global variables we'll be needing throughout the script global amount amount = "" global number number = "" global message message = "" #making sure everything is ready to go before sending the messages def init(): #checking for the applescript to send messages with try: #creating the file f = open("sendMessage.applescript", "x") #append the script into the file script = """on run {targetBuddyPhone, targetMessage} tell application "Messages" set targetService to 1st service whose service type = iMessage set targetBuddy to buddy targetBuddyPhone of targetService send targetMessage to targetBuddy end tell end run""" f.write(script) f.close() #ok, we're good except FileExistsError: #user already has this script pass #to be added: check for internet connectivity before continuing def format(arg): #to return formatted phone numbers arg = str(arg) n1 = arg[0:3] n2 = arg[3:6] n3 = arg[6:10] return f"{n1}-{n2}-{n3}" def main(): while True: while True: #Loop until a break command is encountered so we can factor in all possible input conditions and prompt for revised input if any of them fail to be met global number number = input("Enter a number to text\n") if (number.isdigit()): #making sure the number entered is an actual number and not text number = int(number) #type casting to integer for length comparison if len(str(number)) < 10: #if there are less than ten digits print("that doesn't seem like a 10 digit phone number. Try entering it again") else: break elif "-" in number: #if somebody used dashes print("Oh that's okay, you don't have to use dashes.") else: #the entered string was not a number or equal to done print("Sorry, but there was an error.") global message message = input("Enter the message you'd like to spam\n") while True: global amount amount = input("Enter the amount of messages to spam\n") if (amount.isdigit()): amount = int(amount) break else: print("Please type a number") while True: print(f"""Ok. So, just to make sure, you would like to send {message} to {format(number)} {amount} times?""") confirm = input("Type yes or no""") if confirm == "yes": print("all right, cool") break elif confirm == "no": print("Ok, sorry, something got messed up. Try typing the information you want again.") break else: print("please type yes or no") break init() main() while True: times_sent = 0 print("Here we go") while times_sent < amount: command = f"osascript sendMessage.applescript {number} \"{message}\"" os.system(command) times_sent += 1 print(times_sent,"messages sent") print("Ok. Done.") break a = "" while a.upper() != "NO": a = input("Would you like to spam somebody else now?") if a.upper() == "YES": main() else: print("Please type yes or no")

    Speaking Stopwatch

    As previously mentioned, I'm somewhat athletic, and as such attempt to keep in shape by exercising. I run on treadmills and outside frequently, and it's always good to know how I'm doing while I'm working out. Sighted people can glance down at their smartwatch, phone, or what have you to determine their distance, time, etc, but I can't. While yes, I have an apple watch that does have a built-in screenreader, it takes way too long to try to gather the information I'm looking for while I'm running. I'd rather it just be spoken aloud. So, I developed this stopwatch, which I can have running in the background on my phone via an python IDE for my iPhone. It speaks the time at a user specified interval so I don't have to slow down and look at my watch to see how long I've been going. As of now, it only prints the elapsed time to the screen and relies on VoiceOver to be focused on the element being updated to provide me with announcements, but I plan on adding calls to the system's speech API later so that's not something you have to do.

    Show Code #Speaking Stopwatch from time import sleep #function to format output correctly def display(time): if time < 60: output = f"{time} Seconds" elif time%60 == 0: #time is perfectly divisible by 60 output = f"{time//60} minutes" #output the number of minutes else: min = time//60 sec = time%60 output = f"{min} minutes {sec} seconds" return output #ask the user for their desired interval announcement while True: try: interval = int(input("Enter an interval you'd like the running time to be announced")) except: print("That's not a number. Please try again") continue #jump directly back to the top of the loop and try again break elapsed = 0 while True: print(display(elapsed)) #formatted output of the elapsed variable sleep(interval) #pause for the specified amount of time elapsed += interval #add the amount of time just paused for to the amount of time elapsed

    Today (previously NationalDays)

    Today is a script that will email you all kinds of information about today. So far, I have added those weird national holidays, plus today in history, but there is definitely more to come. This program ventures out into the web and scrapes, parses, and then sends all of the information it gathered to you nicely and concisely. I actually have it texted to me, via my cellular provider's sms2txt service (make sure the one you're using doesn't cut you off at 160 characters).

    Third party dependencies:
    Show Code
    #Today.py, keeping you informed about all things today
    import requests
    from bs4 import BeautifulSoup
    import smtplib, ssl
    from email.message import EmailMessage
    import datetime 
    import ics
    
    #function to retrieve national holidays
    def national_days():
        url = "https://www.checkiday.com/ical.php"
    #download the iCalendar file and store it in an ics object
        c = ics.Calendar(requests.get(url, allow_redirects=True).text) 
    #get list of events
        e = list(c.timeline)
        holidays = """ """
    #filter out events that are from previous and future days since the calendar contains more than just one day
        for i in range(0, len(e)):
            f = list(c.timeline)[i]
            readable = "Event '{}' started {}".format(f.name, f.begin.humanize()) #turn iCalendar to text
    #if the event name has hours, as in: event x, y hours from now
            if "hours" in readable:
    #and if y number of hours minus 12 is nonnegative
                if (readable[-12].isdigit()):
    #the event is happening today, so append it to the holiday string
                    readable = readable.split("'")
                    holidays += f"{readable[1]}, \n"
        return holidays
    
    #function to scrape history events that happened today from a website
    def history():
    #get the page with all the info on it
        page = requests.get("https://www.history.com/this-day-in-history")
        soup = BeautifulSoup(page.content, 'html.parser')
    #get the first event, located at the first heading level
        events = f"{soup.find('h1').get_text()}\n"
    #locate the other events, at heading level 2
        headings = soup.find_all("h2")
    #convert headings to a list for easier processing
        headings = list(headings)
    #Remove the first few headings because they are not related to history
        del headings[0:2]
    #add the remaining heading titles to the event string
        for i in range(0, len(headings)):
            events += headings[i].get_text() + "\n"
        return events
    
    #function to email all the info acquired
    def send(content, type):
        date = datetime.datetime.now()
    #define all email settings
        port = 465
        smtp_server = "smtp.gmail.com"
        sender = "youremail"
        to = "anemail"
        password = "yourpassword"
    #compose the email
        message = EmailMessage()
        message.set_content(content)
        message["From"] = sender
        message["To"] = to
    #separate emails for holidays and history events
        if type == "holiday":
            message["Subject"] = f"Holidays celebrated on {date.strftime('%B %d')} are:"
    #send the email
            context = ssl.create_default_context()
            with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
                server.login(sender, password)
                server.sendmail(sender, to, message.as_string())
        elif type == "event":
            message["Subject"] = f"things that happened today in history include:"
            context = ssl.create_default_context()
            with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
                server.login(sender, password)
                server.sendmail(sender, to, message.as_string())
    
    #the main function
    def main():
    #try getting and sending the national days email, (separated for easier debugging)
            try:
                nationalDays = national_days()
            except:
                print(e)
            try:
                send(nationalDays, type="holiday")
            except Exception as e:
                print(e)
    #now attempt the history function
            try:
                historical = history()
            except Exception as e:
                print(e)
            try:
                send(historical, type="event")
            except Exception as e:
                print(e)
    
    
    
    main()
    

    Quick And Dirty File Generator

    This is just something I kind of scripted quickly, just because there was a whole lot of files I needed to generate but I didn't want to manually create them one by one. So instead, I made this tool, which you can select a folder to generate files into and it just makes them one after another. It will just keep asking you to enter a new file name until you type done. Simple as that. Enjoy

    Show Code
    #File Generator, quickly generate empty files. 
    from time import sleep
    import tkinter as tk
    from tkinter.filedialog import askdirectory
    
    print("Select a folder to generate files into.")
    sleep(1)
    #open native folder selection dialog
    root = tk.Tk()
    root.withdraw()
    path = askdirectory(title="Select Folder For Generated Files")
    #continually prompt for file creation
    while True:
        filename = input("Enter a filename or done to quit")
        if filename.upper() == "DONE":
            break #exit the loop
        elif filename == "":
            print("Please enter a filename")
            continue #jump back to the top of the loop
        try:
            f = open(path+"/"+filename, "x") #Creating the file with user specified filename
            f.close()
            print(f"{filename} generated successfully")
        except FileExistsError:
            print(f"{filename} already exists")
        except Exception as e: #handle all other exceptions
            print(f"Error creating {filename}. {e}")
    print("Ok, exiting...")
    sleep(1)
    

    Creddit Card Generator

    This is a script I wrote to generate totally valid Visa creddit card numbers. Creddit card validity is actually determined by something called the Luhn algorithm, and I thought it would be fun to put that into code. Of course, it's very unlikely you'll actually be able to generate a number that matches a real card, and you don't get an expiration date or security code. This is just comes up with a 16 digit number using Luhn. You can also check if a card is valid or not, but that feature is not quite perfected yet.

    Show Code from random import randint #Program to generate or validate totally lajit looking Visa creddit card numbers using the luhn algorithm #luhn algorithm to determine and return the check digit, if equal to the last number on a card that card is valid def luhn(card): #copy the list because python lists are weird and if we don't do that we'll be modifying the original card number in this function credditcard = card.copy() #some processing depending on the amount of digits in the number if len(credditcard) == 16: credditcard.remove(credditcard[-1]) credditcard.reverse() #multiply every other digit by 2 index = 0 while index < len(credditcard): credditcard[index] = credditcard[index]*2 index += 2 #separate any double digit numbers into single digits for i in credditcard: number = str(i) if len(number) > 1: credditcard[credditcard.index(i)] = int(number[1]) credditcard.insert(credditcard.index(int(number[1])), int(number[0])) #inserts the first digit before the second #find the check digit, start by adding all numbers together sum = 0 for i in credditcard: sum += i #divide by 10 and subtract the remainder from 10 check = sum%10 check = 10-check return check while True: print("""Would you like to: 1. Generate a fake real-looking Visa Creddit Card number 2. Validate a fake real-looking Visa card number""") choice = input(">>>") if choice == "1": #first generating 15 random numbers card = [4] #visa cards start with 4 for i in range(1, 15): card.append(randint(0,9)) #only single digit numbers #find the check digit and append it to the end of the number digit = luhn(card) card.append(digit) #convert to a string to pretty print cardNumber = "" for i in card: cardNumber += str(i) print(f"{cardNumber[0:4]} {cardNumber[4:8]} {cardNumber[8:12]} {cardNumber[12:]}") print("Make up the mm/yyyy experation date and security code yourself, and use responsibly!") elif choice == "2": #make sure you have a valid number while True: card = input("Enter a card number (no spaces or dashes)") if card.isdigit(): #convert to list and change digits to integers card = list(card) for i in card: card[card.index(i)] = int(i) digit = luhn(card) if card[-1] == digit: print("Yep, this looks like a valid card number") break else: print("Nope, that doesn\'t look like a valid card number") break else: print("There\'s something wrong with your input. Enter it with no spaces, dashes, or letters") continue else: print("That's not a valid option.") continue break

    Record Timer

    This script simply records from a defined input source for a set amount of time and saves the output to an mp3 file. I wrote this so that I could set my computer to record replays of sports broadcasts. I look at the time of the broadcast, set it in the script, enter a filename, plug my phone into the line-in jack on my pc, and record. After the timer expires the recording stops.

    Third party dependencies:
    • sounddevice
    • pydub
    Show Code import sounddevice as sd import time import numpy as np from pydub import AudioSegment def record_audio(duration, filename, sample_rate=44100): print(f"Recording...") audio_data = sd.rec(int(duration * sample_rate), samplerate=sample_rate, channels=2, dtype='int32', device=1) sd.wait() # sd.play(audio_data, sample_rate) print("Finished. Processing...") normalized_audio_data = (audio_data / np.max(np.abs(audio_data)) * 32767).astype(np.int16) audio_segment = AudioSegment(normalized_audio_data.tobytes(), frame_rate=sample_rate, sample_width=2, channels=2) audio_segment.export(filename, format="mp3") print(f"Processing complete. Audio saved to {filename}") # Utility function to convert hh:mm:ss to just seconds def seconds(time): hours, minutes, seconds = map(int, time.split(':')) total_seconds = hours * 3600 + minutes * 60 + seconds return total_seconds # Set the recording duration in seconds recording_duration = input("Enter the time for which you'd like to record, in hh:mm:ss format") recording_duration = seconds(recording_duration) output_filename = input("Enter the name of the file to save to") input("Press enter to start recording") # Record audio record_audio(recording_duration, filename=output_filename)