Tuesday, January 28, 2020

Project #3 - Website Blocker

For my third project I built a program that blocks selective websites during certain times of day. This is accomplished by having the program write to the hosts file. In my example below the website Facebook.com will not open during working hours, and will open on non-working hours.

import time
from datetime import datetime as dt

hosts_path = r"/filepath/hosts"redirect = "127.0.0.1"website_lists = ["www.Facebook.com", "Facebook.com"]

while True:
    if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 16):
        print("Can't access during working hours...")
        with open(hosts_path, 'r+') as file:
            content = file.read()
            for website in website_lists:
                if website in content:
                    pass                else:
                    file.write(redirect + " " + website + "\n")
    else:
        with open(hosts_path, 'r+') as file:
            content = file.readlines()
            file.seek(0)
            for line in content:
                if not any(website in line for website in website_lists):
                    file.write(line)
            file.truncate()
        print("Non-working hours, have fun...")
    time.sleep(5)

Monday, January 27, 2020

Project #2 - Mapping Volcanos and Populations

My second project is a program that maps all of the volcanoes in the United States. The data is pulled from a .txt file that has the gps coordinates of each volcano. In addition, when the pin that denotes the location is clicked it will show the name and elevation of that volcano. The pins are also colored according to the elevation of the volcano. The name of the volcano is a hyperlink that when click opens a new tab with a Google search of that volcanoes name. I added another layer to the map that overlays each country with a different color based on population size. The data for the population size is pulled from a .json file.

import folium
import pandas

data = pandas.read_csv("Volcanoes.txt")
lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])
name = list(data["NAME"])

html = """Volcano name:<br><a href="https://www.google.com/search?q=%%22%s%%22" 
target="_blank">%s</a><br>Height: %s feet"""

def color_producer(elevation):
    if elevation < 1000:
        return 'green'    elif 1000 <= elevation < 3000:
        return 'orange'    else:
        return 'red'

map = folium.Map(location=[38.58, -99.09], zoom_start=5, tiles="Stamen Terrain")

fgv = folium.FeatureGroup(name="Volcanoes")

for lt, ln, el, name in zip(lat, lon, elev, name):
    iframe = folium.IFrame(html=html % (name, name, (el*3.28084)), width=200, height=100)
    fgv.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe), 
icon=folium.Icon(color=color_producer(el))))

fgp = folium.FeatureGroup(name="Population")

fgp.add_child(folium.GeoJson(data = (open("world.json", "r", encoding = "utf-8-sig").read()),
style_function = lambda x: {"fillColor":"green" if x["properties"]["POP2005"] < 10000000else "orange" 
if 10000000 <= x["properties"]["POP2005"] < 20000000 else "red"}))


map.add_child(fgv)
map.add_child(fgp)
map.add_child(folium.LayerControl())

map.save("Map_html_popup_advanced.html")

Saturday, January 25, 2020

Project #1 - Dictionary Program

Here is the first project for my portfolio.

This is a program that functions as a dictionary.

When a word is typed into the prompt the program will return the definition.

The program is pulling data from a json file.

If the word is typed incorrectly the program will find a closely spelled word match and ask you if it is the word you are looking for. It will ask yes or no. If you type "Y" it will return the definition of the word. If you type "N" it will return a string that says the word does not exist and to double check it.

There are some additional features added, like the program will know to look for words with capitals even if the entered word was not capitalized.

import json
from difflib import get_close_matches

# Loading Data into a Python data type.
data = json.load(open("data.json"))


def translate(w):
    w = w.lower()
    if w in data:
        return data[w]
    elif w.title() in data:  # If user entered "texas" this will check for "Texas" as well.        return data[w.title()]
    elif w.upper() in data:  # In case user enters words like USA or NATO        return data[w.upper()]
    elif len(get_close_matches(w, data.keys())) > 0:
        yn = input("Did you mean %s? Enter Y if yes and N if no: " % get_close_matches(w, data.keys())[0])
        if yn == "Y":
            return data[get_close_matches(w, data.keys())[0]]
        elif yn == "y":
            return data[get_close_matches(w, data.keys())[0]]
        elif yn == "N":
            return "The word doesn't exist. Please double check it."        
        elif yn == "n":
            return "The word doesn't exist. Please double check it."        
        else:
            return "We didn't understand your entry."    
    else:
        return "That word doesn't exist. Please check your spelling."


# User input.
word = input("Enter word: ")
output = translate(word)
if type (output) == list:
    for item in output:
        print(item)

else:
    print(output)

Say Something Program

Here is my second program:

def sentence_maker(phrase):
    interrogatives = ("how", "what", "why")
    capitalized = phrase.capitalize()
    if phrase.startswith(interrogatives):
        return "{}?".format(capitalized)
    else:
        return"{}.".format(capitalized)

results = []
while True:
    user_input = input("Say something: ")
    if user_input == "\end":
        break    else:
        results.append(sentence_maker(user_input))

print(" ".join(results))

When the program is run the console will ask for user input in the form of "Say something: "

If the user types in any sentences that start with the keywords "how, what, or why" the program will add a question mark to the end of the sentence.

Otherwise, if the sentence does not start with any of the keywords then it will insert a period at the end of the sentence.

The the variable "capitalized' will capitalize the first letter of each sentence.

The where clause will have the console repeatedly ask for user input until the user types in "\end".

When sentences are typed into the console they will be strung together into one sting and printed after the program has ended.

Here is an example of what the program will do:

Say something: hello
Say something: how are you going today 
Say something: That's good 
Say something: what are you doing today 
Say something: sounds fun 
Say something: \end Hello. 
How are you going today? That's good. What are you doing today? Sounds fun.



Friday, January 24, 2020

Super Simple Date Time Program

This is my first simple program of the night.

First I started with:

import datetime
print(datetime.datetime.now())

Then I added some text and a variable:

import datetime
dtn = datetime.datetime.now()
print("The date and time is:", dtn)

When run the program will print:

The date and time is: 2020-01-24 13:10:11.983919

Project #8 - Stock Tracking Graph

For my 8th project, I made a program that pulls stock data from Yahoo Finance and displays it in a graph. For this example, I chose GOOG whi...