import random

rules = (
    [0, 2], [2, 0], [2, 1], [1, 2], [1, 1], [2, 2], [0, 0]
)

"""
A Slot class handling collapsing, updating

Patterns are superpositions of all possible room patterns
"""
class Slot:
    def __init__(self, possibilities):
        self.patterns = possibilities.copy()
        self.dependencies = []

        self.neighbors = {
            "n": None,
            "w": None,
            "s": None,
            "e": None
        }

    def get_result(self):
        if len(self.patterns) == 1:
            return self.patterns[0]
        else:
            return [3, 3, 3, 3]

    def is_collapsed(self):
        return self.get_result()[0] != 3

    """
    Parameters
    ----------
    off : list
        2D Vector offset (list of len == 2) which describes  where the neighbor is be placed (in 2D array space)
        according to this slot position (in 2D array space)
    neighbor : Slot
    """
    def add_neighbor(self, off, neighbor):
        side = ""
        if off == [-1, 0]:
            side = "n"
        if off == [0, 1]:
            side = "w"
        if off == [1, 0]:
            side = "s"
        if off == [0, -1]:
            side = "e"
        self.neighbors[side] = neighbor

    def generate_dependencies(self):
        for pattern in self.patterns:
            self.dependencies.append(self.get_pattern_dependencies(pattern))

    def  get_pattern_dependencies(self, pattern):
        dependencies = Dependencies()

        for i in range(4):
            side = list(self.neighbors.keys())[i]

            if self.neighbors[side]:
                for rule in rules:
                    if pattern[i] == rule[0] and rule[1] not in dependencies.get(side):
                        dependencies.add(side, rule[1])

        return dependencies

    """
    Parameters
    ----------
    side : str
        Where according to this slot is new collapsed neighbor
    collapsed_side : int
        What wall type is facing this slot
    """
    def remove_wrong(self, side, collapsed_side):
        #print(side, collapsed_side)
        for i in range(len(self.patterns) - 1, -1, -1):
            if collapsed_side not in self.dependencies[i].get(side):
                self.patterns.remove(self.patterns[i])
                self.dependencies.remove(self.dependencies[i])

    def update_neighbors(self, collapsed):
        #print("Updating neighbors with", collapsed)
        for side, comming_from, i in zip(["n", "w", "s", "e"], ["s", "e", "n", "w"], [0, 1, 2, 3]):
            if self.neighbors[side] and not self.neighbors[side].is_collapsed():
                self.neighbors[side].remove_wrong(comming_from, collapsed[i])

    def collapse(self):
        pick_index = random.randint(0, len(self.patterns) - 1)

        #print(pick_index, self.patterns[pick_index])

        self.patterns = [self.patterns[pick_index]]
        self.dependencies = [self.dependencies[pick_index]]

        self.update_neighbors(self.get_result())

    def __repr__(self):
        return "<Slot patterns: {0}>".format(len(self.patterns))

"""
A class holding dependencies from all sides for specific room pattern

Dependencies are arrays of possible wall states for each side
"""
class Dependencies:
    def __init__(self):
        self.dependencies = {
            "n": [],
            "w": [],
            "s": [],
            "e": []
        }

    def add(self, side, pattern_side):
        self.dependencies[side].append(pattern_side)

    def get(self, side):
        return self.dependencies[side]

    def __repr__(self):
        return "<Dependencies {0}>".format(self.dependencies)


import time
import pandas as pd
import numpy as np

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze bike sharing data.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    cities =['chicago', 'new york city', 'washington']
    months = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
    days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']

    print('Hello! Let\'s explore some US bikeshare data!')
    # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    while True:
        city = input('\n''Would you like to get data for Chicago, New York City, or Washington?\n').lower()
        if city not in cities:
            print('\nIncorrect input. Please type in a city from the given options.\n')
            continue
        else:
            print('\nYou have chosen {}. If this is not the case, restart the program now!\n'.format(city.title()))
            break

    # get user input for month (all, january, february, ... , june)

    while True:
        time_filter = input('\nWould you like to filter the data by month, day, both, or not at all? Type "none" for no time filter.\n').lower()
        if time_filter == 'month':
            #print('\nAlright. We will filter by month.\n')
            month = input('\nWhich month? January, February, March, April, May, June, or all? Please type the month name in full.\n').lower()
            day = 'all'
            if month not in months:
                print('\nIncorrect input. Please type in a month from the given options.\n')
                continue
        elif time_filter == 'day':
            #print('\nAlright. We will filter by day.\n')
            day = input('\nWhich day? Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, or all? Please type the name of the day in full.\n').lower()
            month = 'all'
            if day not in days:
                print('\nIncorrect input. Please type in a day from the given options.\n')
                continue
        elif time_filter == 'both':
            print('\nYou have chosen both.\n')
            month = input('\nWhich month? January, February, March, April, May, June, or all? Please type the month name in full.\n').lower()
            if month not in months:
                print('\nIncorrect input. Please type in a month from the given options.\n')
            day = input('\nWhich day? Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, or all? Please type the name of the day in full.\n').lower()
            if day not in days:
                print('\nIncorrect input. Please type in a day from the given options.\n')
                continue
        elif time_filter == 'none':
            print('\nYou have chosen no time filter.\n')
            month = 'all'
            day = 'all'
        else:
            print('\nUnrecognized input. Please restart the program now!')
        break
    # get user input for day of week (all, monday, tuesday, ... sunday)

    print('-'*40)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """
    df = pd.read_csv(CITY_DATA[city])

    df['Start Time'] = pd.to_datetime(df['Start Time'])
    df['month'] = df['Start Time'].dt.month
    df['day'] = df['Start Time'].dt.weekday_name
    df['hour'] = df['Start Time'].dt.hour
    if month != 'all':
        months = ['january', 'february', 'march', 'april', 'may', 'june']
        month = months.index(month)+1
        df = df[df['month'] == month]
    if day!= 'all':
        df = df[df['day'] == day.title()]

    return df

def time_stats(df):
    """Displays statistics on the most frequent times of travel."""

    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()

    # display the most common month
    popular_month = df['month'].mode()[0]
    months = ['January', 'February', 'March', 'April', 'May', 'June']
    print('The most common month:', months[popular_month-1])

    # display the most common day of week
    popular_day = df['day'].mode()[0]
    print('The most common day:', popular_day)

    # display the most common start hour
    popular_hour = df['hour'].mode()[0]
    print('The most common start hour:', popular_hour)

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()

    # display most commonly used start station
    popular_start_station = df['Start Station'].mode()[0]
    print('\nThe most commonly used start station:', popular_start_station)

    # display most commonly used end station
    popular_end_station = df['End Station'].mode()[0]
    print('\nThe most commonly used end station:', popular_end_station)

    # display most frequent combination of start station and end station trip

    popular_station_combination = df.groupby(['Start Station', 'End Station']).size().nlargest(1)
    print('\nThe most frequent combination of start station and end station trip:', popular_station_combination)

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""

    print('\nCalculating Trip Duration...\n')
    start_time = time.time()

    # display total travel time
    total_travel_time = df['Trip Duration'].sum().astype(int)
    print('\nTotal travel time:', total_travel_time)

    # display mean travel time
    mean_travel_time = df['Trip Duration'].mean().astype(int)
    print('\nMean travel time:', mean_travel_time)

    # display maximum travel time
    max_travel_time = np.nanmax(df['Trip Duration']).astype(int)
    print('\nMaximum travel time:', max_travel_time)

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def user_stats(df):
    """Displays statistics on bikeshare users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # Display counts of user types
    if 'User Type' in df.columns:
        counts_user_type = df['User Type'].value_counts()
        print('\nCounts of user types:', counts_user_type)
    else:
        print('\nUser Type column does not exist.\n')
    # Display counts of gender
    if 'Gender' in df.columns:
        counts_gender = df['Gender'].value_counts()
        print('\nCounts of gender:', counts_gender)
    else:
        print('\nGender column does not exist.\n')

    # Display earliest, most recent, and most common year of birth
    if 'Birth Year' in df.columns:
        earliest_birth_year = np.nanmin(df['Birth Year']).astype(int)
        print('\nEarliest year of birth:', earliest_birth_year)
        most_recent_birth_year = np.nanmax(df['Birth Year']).astype(int)
        print('\nMost recent year of birth:', most_recent_birth_year)
        most_common_birth_year = df['Birth Year'].mode().astype(int)
        print('\nMost common year of birth:', most_recent_birth_year)
    else:
        print('\nBirth Year column does not exist.\n')

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def raw_data(df):
    """Display 6 lines of raw data upon request."""
    data = input('\nWould you like to see individual trip data? Please type "yes" or "no".\n').lower()
    if data == 'yes':
        index1 = 0
        index2 = 6
        while True:
            print(df.iloc[index1: index2])
            index1 += 6
            index2 += 6
            more_data = input('\nWould you like to see more data? Please type "yes" or "no".\n').lower()
            if more_data != 'yes':
                break
def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)
        raw_data(df)

        restart = input('\nWould you like to restart? Enter yes or no.\n')
        if restart.lower() != 'yes':
            break

if __name__ == "__main__":
	main()


import time
from contextlib import contextmanager

from .hooks import PTDEHook
from ..controller import KeyPress, KeySequence, print_press
from ..exceptions import GameNotRunningError

class TAS:
    """
    The high level TAS engine - provides more user friendly functions
    than working directly with the hook.

    This class handles the keypresses and sequences and the command
    queue.

    Initialise with a hook to work with remaster - creating with no
    arguments will attempt to create a hook to Dark Souls PTDE.

    :param hook: TAS Hook type to hook into the game.
    """
    def __init__(self, hook=None):
        if hook is None:
            hook = PTDEHook

        self.h = hook()
        self.queue = []

    def igt(self):
        """
        Get the raw in game time (alias for h.igt)

        :return: In game time in ms(?)
        """
        return self.h.igt()

    def rehook(self):
        """
        Make the TAS Hook reconnect

        :return:
        """
        self.h.rehook()

    def check_and_rehook(self):
        """
        Check if the game is running, if not try to rehook.

        :return:
        """
        self.h.check_and_rehook()

    def force_quit(self):
        self.h.force_quit()

    def frame_count(self):
        return self.h.frame_count()

    @contextmanager
    def tas_control(self):
        """
        Give control of the game to the TAS Engine for commands
        and return control after.
        """
        try:
            self.h.controller(False)
            self.h.background_input(True)
            self.h.disable_mouse(True)
            yield
        except PermissionError:
            raise GameNotRunningError(
                'TAS Hook has lost connection to the game. '
                'Call tas.rehook() to reconnect.'
            )
        finally:
            self.h.disable_mouse(False)
            self.h.background_input(False)
            self.h.controller(True)

    def _clear(self):
        """
        Clear the keypress queue
        """
        self.queue.clear()

    def _push(self, i):
        """
        Add an input to the queue
        Expects a list of 20 integers.

        Or a Keypress or a KeySequence

        index: meaning (values)
        0: dpad_up (0 or 1)
        1: dpad_down (0 or 1)
        2: dpad_left (0 or 1)
        3: dpad_right (0 or 1)
        4: start (0 or 1)
        5: back (0 or 1)
        6: left_thumb (0 or 1)
        7: right_thumb (0 or 1)
        8: left_shoulder (0 or 1)
        9: right_shoulder (0 or 1)
        10: a (0 or 1)
        11: b (0 or 1)
        12: x (0 or 1)
        13: y (0 or 1)
        14: l_trigger (0 to 255)
        15: r_trigger (0 to 255)
        16: l_thumb_x (-32,768 to 32,767)
        17: l_thumb_y (-32,768 to 32,767)
        18: r_thumb_x (-32,768 to 32,767)
        19: r_thumb_y (-32,768 to 32,767)
        """
        if isinstance(i[0], list) and len(i[0]) == 20:
            self.queue.extend(i)
        elif isinstance(i[0], int) and len(i) == 20:
            self.queue.append(i)
        else:
            raise ValueError(f'Invalid Input: {i}')

    def _execute(self, igt_wait=True, side_effect=None):
        """
        Execute the sequence of commands that have been pushed
        to the TAS object

        Show Commands will ignore 'wait' commands

        :param igt_wait: wait for the igt to tick before performing the first input
        :param side_effect: Call this method on each keypress if it is defined
        """
        with self.tas_control():
            igt = self.igt()
            if igt_wait:
                # Wait for IGT to tick before running the first input
                while igt == self.igt():
                    time.sleep(0.002)
            else:
                # If not waiting for IGT, sleep for 1/20th of a second
                # Otherwise the first input often gets eaten.
                time.sleep(0.05)

            # Loop over the queue and then clear it
            for command in self.queue:
                self.h.write_input(command)
                if side_effect:
                    side_effect(command)
                igt = self.igt()
                while igt == self.igt():
                    time.sleep(0.002)
            self.queue.clear()

    def keystate(self):
        """
        Get the current input state as a keypress
        :return:
        """
        state = self.h.read_input()
        return KeyPress.from_list(state)

    def record(self, start_delay=5, record_time=None, button_wait=True):
        """
        Record the inputs for a time or indefinitely

        Exit out and save by pressing start and select/back at the same time.

        use:
            >>> tas = TAS()
            >>> seq = tas.record(start_delay=10)

        playback:
            >>> tas.run(seq, start_delay=10)

        :param start_delay: Delay before recording starts in seconds
        :param record_time: Recording time
        :param button_wait: Wait for a button press to start recording
        :return: recorded tas data
        """
        print(f'Preparing to record in {start_delay} seconds')
        recording_data = []
        igt_diffs = set()

        if start_delay is None:
            start_delay = 0

        if start_delay >= 5:
            time.sleep(start_delay - 5)
            print('Countdown')
            for i in range(5, 0, -1):
                print(f'{i}')
                time.sleep(1)
        else:
            time.sleep(start_delay)

        print('Recording Started')
        start_time = time.clock()
        end_time = start_time + record_time if record_time else None
        first_input = True

        # Special code for waiting for first input
        if first_input and button_wait:
            print('Press a button to resume recording.')
            keypress = self.h.read_input()
            while not sum(keypress[4:6] + keypress[10:14]):
                time.sleep(0.002)
                keypress = self.h.read_input()
            print('Recording Resumed')
            print('Press start and select simultaneously to stop recording.')

        while True:
            keypress = self.h.read_input()
            # Exit if start and select are held down
            if keypress[4] and keypress[5]:
                break
            recording_data.append(keypress)

            igt = self.h.igt()
            # Wait until next igt time
            while igt == self.h.igt():
                time.sleep(0.002)
            igt_diffs.add(self.h.igt() - igt)

            # Check if record time complete
            if end_time and time.clock() > end_time:
                break

        print('Recording Finished')
        print(f'Frame Lengths: {sorted(igt_diffs)}')

        recording = KeySequence.from_list(recording_data)

        return recording

    def run(self, keyseq, start_delay=None, igt_wait=True, display=True):
        """
        Queue up and execute a series of controller commands

        :param keyseq: KeySequence or KeyPress of inputs to execute
        :param start_delay: Delay before execution starts in seconds
        :param igt_wait: Wait for IGT to tick before performing the first input
        :param display: Display the game inputs as they are pressed
        """
        if len(keyseq) > 0:
            effect = print_press if display else None
            if start_delay:
                print(f'Delaying start by {start_delay} seconds')
                if start_delay >= 5:
                    time.sleep(start_delay - 5)
                    for i in range(5, 0, -1):
                        print(f'{i}')
                        time.sleep(1)
                else:
                    time.sleep(start_delay)

            print('Executing sequence')
            self._clear()
            self._push(keyseq.keylist)
            self._execute(igt_wait=igt_wait, side_effect=effect)
            print('Sequence executed')
        else:
            print('No Sequence Defined')


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 18:12:59 2020

Functions dealing with zip code api

@author: gshre
"""

# Dependencies
import requests
import pandas as pd
import os.path
from config import zipcode_url

def get_state_zips_api(state_code):
    '''
    Returns zip codes data frame for a state using API

    Parameters
    ----------
    state_code : TYPE: string
        DESCRIPTION. State Code abbreviation; ex: NC

    Returns
    -------
    TYPE: DataFrame
        DESCRIPTION. Zip Codes data frame

    '''
    url=zipcode_url.replace("{state_code}", state_code)
    response = requests.get(url)
    zip_code_data = response.json()
    return pd.DataFrame(zip_code_data)

def get_state_zips(state_code):
    '''
    Returns zip coes data frame for a state using csv if available
    otherwise it calls API

    Parameters
    ----------
    state_code : TYPE: string
        DESCRIPTION. State Code abbreviation; ex: NC

    Returns
    -------
    df : TYPE: DataFrame
        DESCRIPTION. Zip Codes data frame

    '''
    csv_filename = f"Resources/{state_code}_ZipCodes.csv"
    # try to open file...if it does not exist, then create it
    df = ''
    try:
        df = pd.read_csv(csv_filename)
    except:
        print("Loading zip codes with API")
        df = get_state_zips_api(state_code)
        df.rename(columns = {"zip_codes" : "Zip Codes"}, inplace=True)
        df.to_csv(csv_filename, index=False)
    return df


import os
import requests
import json
import getpass
from cryptography.fernet import Fernet
import base64

course_id = '164'
get_item1 = requests.get('https://gitlab.com/ga-cyberworkforceacademy/labtainer/-/raw/master/item1')
item1 = base64.b64decode(get_item1.content)
item2 = 'MkFuYk4wYjJCX25nbUdULWxCZHBCNktCZmptRklsREVobk5OQVQ4SjV5Zz0='
item2 = item2.encode('utf8')
item2 = base64.b64decode(item2)
f = Fernet(item2)
access_token = f.decrypt(item1).decode('utf8')
working_dir = '/home/{}/labtainer_xfer'.format(getpass.getuser())
auth_header = {'Authorization': 'Bearer {}'.format(access_token)}

def parseUserName():
    # Parse json activity file for username information
    with open(activity_file, 'r') as read_json:
        user_name = json.load(read_json)
    user_name = list(user_name.keys())[0]
    # Clean up output for user email
    user_name = user_name.replace('_at_','@')
    # user_name = user_name.split('.', 2)[:1]
    user_email= "".join(user_name)
    user_email = user_email.split('@')[0]
    return user_email

def getUserID():
    #Query Canvas API endpoint for user ID using user_email
    response = requests.get('https://gacybercenter.instructure.com/api/v1/accounts/self/users?search_term={}'.format(user_email), headers=auth_header)
    user_data = json.loads(response.text)[0]
    user_id = user_data['id']
    return str(user_id)

def getAssignments():
    # Pull assignment data and create dictionary for reference
    get_assignments = requests.get('https://gacybercenter.instructure.com/api/v1/courses/{}/assignments'.format(course_id), headers=auth_header)
    assignment_data = json.loads(get_assignments.text)
    assignment_dict = [d.get('name') for d in assignment_data]
    assignment_dict2 = [d.get('id') for d in assignment_data]
    global assignment_data_dict
    assignment_data_dict = dict(zip(assignment_dict, assignment_dict2))
    return assignment_data_dict

def getAssignmentID():
    # Associate ID with assignment name
    # Parse json activity file for assignment name information
    with open(activity_file, 'r') as read_json:
        activity_name = json.load(read_json)
    activity_name = list(activity_name.keys())[0]
    # Clean up output for user email
    activity_name = activity_name.replace('_at_','@')
    activity_name = activity_name.rsplit('.', 1)[1]
    assignment_id = ""
    if activity_name in assignment_data_dict:
        assignment_id = assignment_data_dict[activity_name]
    return assignment_id, activity_name

def gradeAssignment():
    # Parse activity for grade information
    with open(activity_file, 'r') as read_json:
        activity_data = json.load(read_json)
    dict_name = list(activity_data.keys())[0]
    grade_dict = activity_data['{}'.format(dict_name)]['grades']
    if True in grade_dict.values():
        grade_pts = 100
        return grade_pts
    else:
        grade_pts = 0
        return grade_pts

def uploadGrade():
    # Upload grade to Canvas API endpoint
    # Check if grade already exists
        grade_data = 'grade_data[{}][posted_grade]={}'.format(user_id, grade_pts)
        requests.post('https://gacybercenter.instructure.com/api/v1/courses/{}/assignments/{}/submissions/update_grades'.format(course_id, assignment_id), data=grade_data, headers=auth_header)

def checkGradeExists():
    #Check Canvas API endpoint for existing grade data
    get_assignments = requests.get('https://gacybercenter.instructure.com/api/v1/courses/{}/assignments/{}/submissions/{}'.format(course_id, assignment_id, user_id), headers=auth_header)
    graded_data = json.loads(get_assignments.text)
    grade_exists = ''
    grade = graded_data.get('grade')
    if grade == '100':
        grade_exists = True
    elif grade == '0':
        grade_exists = True
    else:
        grade_exists = False
    return grade, grade_exists

# Pull current assignments from Canvas and create a dictionary for the values
getAssignments()

# Loop through json files in the assignment directory

for root, dirs, files in os.walk(working_dir):
    for json_file in files:
        activity_file = os.path.join(root, json_file)
        if activity_file.endswith('.json'):
            # Determine user Email
            try:
                user_email = parseUserName()
            # Determine UserID from Canvas API Call
                user_id = getUserID()
            # Determine assignment ID
                assignment_data = getAssignmentID()
                assignment_id = assignment_data[0]
                assignment_name = assignment_data[1]
            # Grade Assignment
                grade_pts = gradeAssignment()
            except:
                pass
            # Check for existing grade and push grade to assignment data if equal to 100
            try:
                grade_query = checkGradeExists()
                grade_exists = grade_query[1]
                grade = grade_query[0]
                if (grade_exists != True) and (grade_pts == 100):
                    uploadGrade()
                    print('{} assignment with a grade of {} submitted!'.format(assignment_name, grade_pts))
                elif (grade_exists == True) and (grade_pts != 100):
                    uploadGrade()
                    print(f'{assignment_name} with a grade of {grade_pts} currently exists, try the lab again for a better grade!')
                elif (grade_exists == True) and (grade == 0) and (grade_pts == 100):
                    uploadGrade()
                    print(f'{assignment_name} with a grade of {grade_pts} has been updated!')
                else:
                    print('{} assignment has already been submitted with a grade of {}!'.format(assignment_name, grade))
            except:
                print(f"{assignment_name} doesn't exist on Canvas as a graded item")
                pass


import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import linregress

def draw_plot():
    # Read data from file
    df = pd.read_csv('epa-sea-level.csv', delimiter=',')
    df2 = df[df['Year'] >= 2000]
    x = df['Year']
    y = df['CSIRO Adjusted Sea Level']
    x2 = df2['Year']
    y2 = df2['CSIRO Adjusted Sea Level']

    # Create scatter plot
    plt.scatter(x, y)

    # Create first line of best fit
    slope, intercept, r_value, p_value, std_err = linregress(x, y)
    sr1 = pd.Series([int(i) for i in range(1880, 2050)])
    plt.plot(sr1, intercept + slope*sr1, 'r')

    # Create second line of best fit
    slope, intercept, r_value, p_value, std_err = linregress(x2, y2)
    sr2 = pd.Series([int(i) for i in range(2000, 2050)])
    plt.plot(sr2, intercept + slope*sr2, 'r')

    # Add labels and title
    plt.xlabel('Year')
    plt.ylabel('Sea Level (inches)')
    plt.title('Rise in Sea Level')

    # Save plot and return data for testing (DO NOT MODIFY)
    plt.savefig('sea_level_plot.png')
    return plt.gca()


# coding=utf-8
"""
Meta elements for modeling operations

The structure of this package is the following::

    Operation
    <|-- ReadOperation
        <|-- Query (soil command '?' and '??')
        <|-- Check (soil command 'check')
    <|-- UpdateOperation
        <|-- ObjectCreation (soil commands '!new' and '!create'
        <|-- ObjectDestruction (soil command )
        <|-- LinkCreation (soil command '! insert')
        <|-- LinkDestruction (soil command )
        <|-- LinkObjectCreation (soil command '! new between')
        <|-- AttributeAssignment (soil command '! :=' )

"""
from abc import ABCMeta

from typing import Optional, List, Text

from modelscripts.megamodels.elements import SourceModelElement
from modelscripts.metamodels.classes import (
    Class,
    Association,
    AssociationClass,
    Attribute,
)
from modelscripts.metamodels.permissions.sar import Subject

META_CLASSES=[
    'Operation',
    'ReadOperation',
    'UpdateOperation',
    'ObjectCreation',
    'ObjectDestruction',
    'LinkCreation',
    'LinkDestruction',
    'LinkObjectCreation',
    'AttributeAssignment',
    'Query',
    'Check'
]
__all__=META_CLASSES

#--------------------------------------------------------------
#   Abstract classes
#--------------------------------------------------------------

class Operation(SourceModelElement, Subject):
    __metaclass__ = ABCMeta

    META_COMPOSITIONS=[
        'operationEvaluation',
    ]

    def __init__(self,
        block,
        name=None,
        code=None, lineNo=None, docComment=None, eolComment=None):
        SourceModelElement.__init__(self,
            model=block.model,
            name=name,
            code=code, lineNo=lineNo,
            docComment=docComment, eolComment=eolComment)
        self.block=block
        self.block.operations.append(self)

        # evaluation
        self.operationEvaluation=None #filled if evaluated
        #type: Optional['OperationEvaluation']

    @property
    def superSubjects(self):
        return [self.block]

    @property
    def subjectLabel(self):
        return 'operation'

class ReadOperation(Operation):
    __metaclass__ = ABCMeta

    def __init__(self,
                 block, name=None,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(ReadOperation, self).__init__(block, name, code, lineNo, docComment, eolComment)

class UpdateOperation(Operation):
    __metaclass__ = ABCMeta

    def __init__(self,
        block, name=None,
        code=None, lineNo=None, docComment=None, eolComment=None):
        super(UpdateOperation, self).__init__(block, name, code, lineNo, docComment, eolComment)

#--------------------------------------------------------------
#   Update operations
#--------------------------------------------------------------

class ObjectCreation(UpdateOperation):
    """
    """
    def __init__(self, block,
                 variableName, class_, id=None,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(ObjectCreation, self).__init__(block, variableName, code, lineNo, docComment, eolComment)

        self.class_=class_
        # type: Class

        self.id=id
        # type: Optional[str]

class ObjectDestruction(UpdateOperation):
    """
    Destruction of a regular object OR of a link object.
    """
    def __init__(self, block,
                 variableName,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(ObjectDestruction, self).__init__(block, variableName, code, lineNo, docComment, eolComment)

class LinkCreation(UpdateOperation):
    def __init__(self, block,
                 names, association, id=None,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(LinkCreation, self).__init__(block, None, code, lineNo, docComment, eolComment)

        self.names=names #type:List[Text]

        self.association=association
        # type: Association

        self.id=id #type:Optional[Text]

class LinkDestruction(UpdateOperation):
    def __init__(self, block,
                 names, association,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(LinkDestruction, self).__init__(block, None, code, lineNo, docComment, eolComment)

        self.names=names

        self.association = association
        # type: Association

class LinkObjectCreation(UpdateOperation):
    def __init__(self, block,
                 variableName=None, names=(), id=None, associationClass=None,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(LinkObjectCreation, self).__init__(block, variableName, code, lineNo, docComment, eolComment)
        # self.name can be None
        self.names = names
        self.id = id

        self.associationClass = associationClass  # this is indeed an association class
        # type: AssociationClass

class AttributeAssignment(UpdateOperation):
    def __init__(self, block,
                 variableName,
                 attributeName,
                 expression,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(AttributeAssignment, self).__init__(block, None, code, lineNo, docComment, eolComment)

        self.variableName = variableName
        self.attributeName = attributeName
        # type: Attribute

        self.expression = expression

#--------------------------------------------------------------
#   Read operations
#--------------------------------------------------------------

class Query(ReadOperation):
    def __init__(self, block,
                 expression,
                 verbose=False,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(Query, self).__init__(
            block=block,
            name=None,
            code=code,
            lineNo=
            lineNo,
            docComment=docComment, eolComment=eolComment)

        self.expression = expression
        self.verbose = verbose

class AssertQuery(Query):
    def __init__(self, block,
                 expression,
                 verbose=False,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(AssertQuery, self).__init__(
            block=block,
            expression=expression,
            verbose=verbose,
            code=code, lineNo=lineNo,
            docComment=docComment, eolComment=eolComment)

class Check(ReadOperation):
    def __init__(self, block,
                 verbose=False,
                 showFaultyObjects=False,
                 all=True,
                 code=None, lineNo=None, docComment=None, eolComment=None):
        super(Check, self).__init__(block, None, code, lineNo, docComment, eolComment)

        self.verbose = verbose
        self.showFaultyObjects = showFaultyObjects
        self.all=all


'''particle module'''
import numpy as np
import math

class particle(object):
    '''particle object'''
    def __init__(self, prev, nex, vector, bearing, threshold, direction):
        self.prev = prev
        self.nex = nex
        self.vector = vector
        self.bearing = bearing
        self.threshold = threshold
        self.direction = direction
        self.death = False
        self.birth = False
'''
    def setVector(self, x, y):
        self.vector = (x,y)

    def setBearing(self, new_bearing):
        self.bearing = new_bearing

    def space2Next(self):

        if self.nex is not None:

            return self.nex.vector[0] - self.vector[0]

        else:
            return self.vector[0] - self.prev.vector[0]
    def merge(self):
        #particles merge into one
        pass

    def split(self):
        #one paticle split to two
        pass'''


import numpy as np
import pickle
import random
import argparse
if __name__=="__main__":
    parser = argparse.ArgumentParser(description = 'Graph Preprocessor .',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('graph',help = 'File containing the graph')
    parser.add_argument('out',help = 'File to store the permutated graph')
    parser.add_argument('size',type=int,help='Graph size')
    parser.add_argument('--scale',type=float, default=0.001,help='The standard deviation of noise..')
    snap_group = parser.add_mutually_exclusive_group(required=False)
    snap_group.add_argument('--fromsnap', dest='fromsnap', action='store_true',help="Inputfiles are from SNAP")
    snap_group.add_argument('--notfromsnap', dest='fromsnap', action='store_false',help="Inputfiles are pre-formatted")
    parser.set_defaults(fromsnap=True)

    parser.add_argument('--noise', choices=['normal', 'laplace', 'both'], help="Noise type")
    parser.add_argument('--mix_noise_weight', type=float, default=0.5, help="The coeff. of normal distributed weights, only relevant if noise is set to 'both'.")

    args = parser.parse_args()

    weights = {}

    #generate weights
    for i in range(args.size):
        for j in range(args.size):
            if (j,i) in weights or (i,j) in weights:
                continue

            if args.noise == 'normal':
                weights[(i,j)] = np.random.normal(loc=0.0,scale=args.scale)
            elif args.noise == 'laplace':
                weights[(i,j)] = np.random.laplace(loc=0.0,scale=args.scale)
            elif args.noise == 'both':
                weights[(i,j)] = args.mix_noise_weight * np.random.normal(loc=0.0,scale=args.scale) + (1-args.mix_noise_weight) * np.random.laplace(loc=0.0,scale=args.scale)

            weights[(j,i)] = weights[(i,j)]

    print (weights[(22, 55)], weights[(55, 22)])

    out_file_name = args.out + '_weights_' + args.noise + str(args.scale)
    if args.noise == 'both':
        out_file_name += '_mixcoeff' + str(args.mix_noise_weight)

    with open(out_file_name, 'wb') as fW:
        pickle.dump(weights, fW)


import pandas as pd
import csv
import json
import requests

url = "https://api.hospitalpriceindex.com/itemList/list"

payload = "{\"defId\":8149,\"priceStatus\":\"published\",\"page\":{\"from\":1,\"size\":50000},\"sortInput\":[{\"reverse\":false,\"by\":\"description\"}],\"listName\":\"priceList\",\"filters\":[{\"property\":\"description\",\"value\":\"\",\"type\":\"all\"}]}"
headers = {
    'authority': 'api.hospitalpriceindex.com',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
    'accept': 'application/json, text/plain, */*',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
    'content-type': 'application/json',
    'origin': 'https://search.hospitalpriceindex.com',
    'sec-fetch-site': 'same-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://search.hospitalpriceindex.com/',
    'accept-language': 'en-US,en;q=0.9'
}

response = requests.request("POST", url, headers=headers, data=payload)

# print(response.text)

# response_text = response.text

#
northsideData = response.json()
df = pd.json_normalize(northsideData['result'], record_path=['items'])
# df.transpose
json_data_path = 'C:\\Users\\jackb\\Desktop\\FileOpen\\geraldChampionRegionalMC\\northside\\northsideCherokee.json'
csv_write = r'C:\\Users\\jackb\\Desktop\\FileOpen\\northside\\northsideCherokee.csv'
df.to_csv(csv_write, index=False)

json_data_path = 'C:\\Users\\jackb\\Desktop\\FileOpen\\geraldChampionRegionalMC\\northside\\northsideCherokee.json'
csv_write = r'C:\\Users\\jackb\\Desktop\\FileOpen\\northside\\northsideCherokee.csv'

# json_data.to_csv(csv_write, index=False)
# print(json_data.head)


import tkinter

class Calculator:
    def __init__(self, master):
        self.master = master

        self.display_number = []
        self.starter_int = 0
        self.operation = []

        self.build_grid()
        self.nums_for_calc()
        self.number_display()
        self.add_button()
        self.subtract_button()
        self.equals_button()

    def build_grid(self):
        # creates a larger parent grid with a label for the calculator
        self.calc = tkinter.LabelFrame(self.master, text='Calculator')
        self.calc.pack(fill=tkinter.BOTH, expand=True)

        # Makes three seperate grids to hold; numbers, operators, and display
        self.answer_frame = tkinter.Frame(self.calc, bg='yellow')
        self.answer_frame.grid(row=0, column=0, columnspan=2)
        self.number_frame = tkinter.Frame(self.calc, bg='blue')
        self.number_frame.grid(row=1, column=0)
        self.operator_frame = tkinter.Frame(self.calc, bg='red')
        self.operator_frame.grid(row=1, column=1)

    def add_button(self):
        add_button = tkinter.Button(self.operator_frame, text='+')
        add_button.grid(row=0, column=0, padx=2)
        add_button.config(command=self.convert_int_list)

    def subtract_button(self):
        sub_button= tkinter.Button(self.operator_frame, text='-')
        sub_button.grid(row=1, column=0, padx=2)

    def equals_button(self):
        equals_button = tkinter.Button(self.operator_frame, text='=')
        equals_button.grid(row=2, column=0, padx=2)

    def nums_for_calc(self):
        # creates a list of buttons that need to be put into a grid
        butts = map(self.map_for_nums, range(10))

        # puts buttons into grid using a for loop and place holder variables
        # only lets width go to three buttons before starting new row
        row1 = 0
        column1 = 0
        for item in butts:
            if column1 <= 2:
                item.grid(row=row1, column=column1)
                column1 += 1
            if column1 > 2:
                row1 += 1
                column1 = 0

    def map_for_nums(self, num):
        # helper function that creates a number button and assigns its value to click
        return tkinter.Button(self.number_frame, text=num,
                             command=lambda: self.add_num_to_text(num))

    def number_display(self):
        # creates a display for numbers when number buttons are pressed
        self.text_widget = tkinter.Text(self.answer_frame, bg='yellow',
                                        state='normal', height=2, width=20)
        self.text_widget.grid(row=0, column=0, sticky='ew')

    def add_num_to_text(self, num):
        # function that adds a number to the text field at the top of the calculator
        self.text_widget.insert('end', num)
        # appends numbers entered to display_number list
        self.display_number.append(num)
        print(self.display_number)

    def convert_int_list(self):
        # converts the list of nums we're tracking in display_number into an int
        # sets starter_int to that number
        str_integer = ''.join(str(item) for item in self.display_number)
        self.starter_int = int(str_integer)

        # deletes the text in the frame
        self.text_widget.delete(1.0, 'end')
        print(self.starter_int)

if __name__ in '__main__':
    root = tkinter.Tk()
    Calculator(root)
    root.mainloop()


#!/usr/bin/env python3

import os.path, time
import sys

# sourceDir = "/home/guynaftaly/temp"
# destinationDir = "/home/guynaftaly/temp"

def list_files(sourceDir):
        # Get a list of all files in the source directory.
    fileList = os.listdir(sourceDir)
        # Start a list for all the pictures and videos.
    jpegFiles =[]
    for file in fileList:
        if file.endswith(".jpeg") | file.endswith(".jpg") | file.endswith(".mp4"):
            filePath = str(os.path.abspath(sourceDir + "/" + file))
            jpegFiles.extend([filePath])
        # Return a list of all the pictures and videos.
    return jpegFiles

def creation_time(filePath):
    fileCreationTime = time.ctime(os.path.getmtime(filePath))
    data = fileCreationTime.split()
        # Return creation time of each file on the list.
    return data

def create_dir(dir):
    if not os.path.exists(dir):
        try:
            os.mkdir(dir)
        except OSError:
            print ("Creation of the directory %s failed" % dir)
        else:
            print ("Successfully created the directory %s " % dir)

    # Get all pictures and videos.

sourceDir = sys.argv[1]
destinationDir = sys.argv[2]
pictures = list_files(sourceDir)
for pic in pictures:
        # Create new directories if needed.
    month =  (creation_time(pic))[1]
    year = (creation_time(pic))[4]
    yearDir = destinationDir + "/" + year
    monthDir = destinationDir + "/" + year + "/" + month
        # If the new dir don't exist then create it.
    create_dir(yearDir)
    create_dir(monthDir)
        # Move pic to remote path
    fileLeaf = os.path.basename(pic)
    os.rename(pic , monthDir + "/" + fileLeaf )


# from matplotlib import pyplot as plt
from vision import VisionModule
import cv2
import samples

WIDTH = 640
HEIGHT = 480

COLORS = {
    "obstacle": (255, 0, 0),
    "cube": (0, 0, 255),
    "green": (0, 255, 0),
    "yellow": (255, 255, 0),
    "base": (0, 255, 255)
}

def load(tgt):

    return cv2.resize(samples.load(int(tgt)), (WIDTH, HEIGHT))

def draw(img, objects):
    cv2.line(img, (0, 240), (640, 240), (255, 255, 255), 2)
    for c in objects:
        cv2.rectangle(
            img,
            (c.rect[0], c.rect[1]),
            (c.rect[0] + c.rect[2], c.rect[1] + c.rect[3]),
            COLORS.get(c.meta), 3)
        cv2.putText(
            img, "{:.2f}".format(c.dist), (c.rect[0], c.rect[1]),
            cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255))

def in_the_way(objs):

    right = 0

    for obj in objs:
        if (
                obj.dist > 0 and
                obj.dist < 25 and
                obj.rect[0] < 300 and
                obj.rect[0] + obj.rect[2] > 340):
            right = max(right, obj.rect[0] + obj.rect[2] - 320)

    return right

def test(target, pause=True):

    import time
    import os

    mod = VisionModule(width=WIDTH, height=HEIGHT)

    total = 0
    n = 0

    srcs = os.listdir(target)
    srcs.sort()

    for img in srcs:
        src = cv2.imread(os.path.join(target, img))

        start = time.time()
        objects, mask, cvxhull = mod.process(src)
        dur = (time.time() - start)

        n += 1
        total += dur

        src = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
        draw(src, objects)
        itw = in_the_way(objects)
        if cvxhull is not None:
            cv2.drawContours(
                src, [cvxhull], -1, (255, 255, 255), 3, cv2.LINE_8)
        cv2.line(src, (itw + 320, 0), (itw + 320, 480), (0, 0, 0), 3)

        src = cv2.cvtColor(src, cv2.COLOR_RGB2BGR)

        cv2.putText(
            src, '{:.1f}fps'.format(n / total), (0, 20),
            cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255))

        cv2.imshow('test_01', src)
        if cv2.waitKey(0 if pause else 1) & 0xFF == ord('q'):
            break

    if pause:
       cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    # import sys
    test('tests_02')
    # test(sys.argv[1])


#!/usr/bin/python3
#
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
import sqlite3
import jetson.inference
import jetson.utils
import os
import argparse
import sys
import time
import datetime
import schedule
import csv
#import schelude_folder_file_delete as file_cleanup
import numpy as np

video_output = ' '
image_output = ' '
image_folder = ' '
image_name = ' '
get_image_time = ' '
image_folder_label = 'imageNet_'
image_date = ' '
image_file_label = 'imageNet_'
record_video_ext = '.jpg'
image_capture_ext = '.jpg'
image_capture = ' '
v_out = ' '
img_out = ' '
storege_location = ' '

#camera_1_folder = 'test_camera'
camera_1_folder = 'camera_1'
camera_2_folder = 'camera_2'
camera_3_folder = 'camera_3'
camera_4_folder = 'camera_4'
camera_sub_dir = ' '
make_directory = ' '

time_stamp = 0
location = 0
description = 0
description_id = 0
confidence = 0
color = 0
axel_count = 0
license_plate = 0
rfid = 0
speed = 0
image_path = 0
lane_id = 0
take_action = ' '
conn = 0

detection_out = 0
FILTER1 = 'vehicle'
FILTER2 = 'bike'
FILTER3 = 'pickup truck'
START_MESS1 = 0
START_MESS2 = 400
EXIT_MESS1 = 900
EXIT_MESS2 = 1000
EXIT_COUNT = 0
distance = 0
center_l = 0
center_r = 0
count = 0
counter = 0

width = 1280 ## rtsp stream camera
height = 720 ## rtsp stream camera

MODEL = 'vehicleModel'
STORAGE_DIRECTORY = '/media/bob/ssd128/' # Storage database, images
if os.path.exists(STORAGE_DIRECTORY):
    pass
else:
    os.mkdir(STORAGE_DIRECTORY)

os.chdir(STORAGE_DIRECTORY)

#CREATE TABLE
#Following Python program will be used to create a table in previously created database:
def createTable():
    conn.execute('''CREATE TABLE DATA_AQUISITION2
    (TIMESTAMP TEXT  PRIMARY KEY NOT NULL,
    LOCATION TEXT NOT NULL,
    DESCRIPTION TEXT NOT NULL,
    DESCRIPTION_ID TEXT NOT NULL,
    CONFIDENCE TEXT NOT NULL,
    COLOR TEXT NOT NULL,
    AXEL_COUNT TEXT NOT NULL,
    LICENSE_PLATE TEXT NOT NULL,
    RFID TEXT NOT NULL,
    SPEED TEXT NOT NULL,
    LANE_ID TEXT NOT NULL,
    IMAGE_PATH TEXT NOT NULL);''')
    print ("Table created successfully")

if os.path.exists('Dbox_3.db'):
    conn = sqlite3.connect('Dbox_3.db')
else:
    conn = sqlite3.connect('Dbox_3.db')
    createTable()

print ("Opened database successfully")
print ('data acqusition started....')

def image_folder_name():
    get_image_time = datetime.datetime.now()
    camera_sub_dir = get_image_time.strftime("%Y_%m_%d")
    return camera_sub_dir

class cameraDirectory: #camera_root_dir, camera_sub_dir
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getCameraDirectory(self):
        os.chdir(self.x)
        path = (os.getcwd())
        if os.path.exists(self.y):
            pass
        else:
            os.mkdir(os.path.join(path, self.y))
            return

class imageDirectory: #STORAGE_DIRECTORY, camera_sub_dir
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getImageDirectory(self):
        os.chdir(STORAGE_DIRECTORY)
        os.chdir(self.x)
        path = (os.getcwd())
        if os.path.exists(self.y):
            pass
        else:
            os.mkdir(os.path.join(path, self.y))
            return

#test image root directory
image_directory = cameraDirectory(STORAGE_DIRECTORY, camera_1_folder)
image_directory.getCameraDirectory()
image_directory = cameraDirectory(STORAGE_DIRECTORY, camera_2_folder)
image_directory.getCameraDirectory()
image_directory = cameraDirectory(STORAGE_DIRECTORY, camera_3_folder)
image_directory.getCameraDirectory()
image_directory = cameraDirectory(STORAGE_DIRECTORY, camera_4_folder)
image_directory.getCameraDirectory()

#test image sub-directory
image_sub_directory = imageDirectory(camera_1_folder, image_folder_name())
image_sub_directory.getImageDirectory()
#os.chdir(STORAGE_DIRECTORY)
image_sub_directory = imageDirectory(camera_2_folder, image_folder_name())
image_sub_directory.getImageDirectory()
#os.chdir(STORAGE_DIRECTORY)
image_sub_directory = imageDirectory(camera_3_folder, image_folder_name())
image_sub_directory.getImageDirectory()
#os.chdir(STORAGE_DIRECTORY)
print('STORAGE_DIRECTORY IS: ', STORAGE_DIRECTORY)
image_sub_directory = imageDirectory(camera_4_folder, image_folder_name())
image_sub_directory.getImageDirectory()

boxes = []
confidence = []
class_id = []
classes = []

def getVideo():
    get_image_time = datetime.datetime.now()
    get_image_time = get_image_time.strftime("%Y-%m-%d-%H%M%S%f")
    #image_date, image_time = get_image_time.split('_')
    #image_name = '{}{}{}'.format(image_file_label, get_image_time, record_video_ext)
    video_out_1 = '{}{}'.format(get_image_time, record_video_ext)
    video_out_2 = '{}{}{}'.format(camera_2_folder, get_image_time, image_capture_ext)
    video_out_3 = '{}{}{}'.format(camera_3_folder, get_image_time, image_capture_ext)
    video_out_4 = '{}{}{}'.format(camera_4_folder, get_image_time, image_capture_ext)
    #image_folder = str(image_folder)
    #image_name = str(image_name)
    os.chdir(STORAGE_DIRECTORY)
    path = (os.getcwd())
    #time.sleep(.02)
    video_output = (os.path.join(path, camera_1_folder, image_folder_name(), video_out_1))
    #video_output = (os.path.join(path, image_folder, image_name))
    return video_output, get_image_time

#net = jetson.inference.imageNet('alexnet')
net = jetson.inference.imageNet('googlenet-12')
#net_detect = jetson.inference.detectNet("ssd-mobilenet-v2", threshold=0.4) ## default is 0.5 higher number less sensitive
net_detect = jetson.inference.detectNet('ssd-mobilenet-v2',['--model=/jetson-inference/python/training/detection/ssd/models/{}/ssd-mobilenet.onnx'.format(MODEL),'--labels=/jetson-inference/python/training/detection/ssd/models/{}/labels.txt'.format(MODEL),'--input-blob=input_0','--output-cvg=scores','--output-bbox=boxes'])
LABELS_FILE = '/jetson-inference/python/training/detection/ssd/models/{}/labels.txt'.format(MODEL)
#LABELS_FILE = '/ssd500/jetson-inference/data/networks/SSD-Mobilenet-v2/ssd_coco_labels.txt'
#net_detect = jetson.inference.detectNet("ssd-inception-v2", threshold=0.5)
#net = jetson.inference.imageNet('resnet-152',['--model=/home/rdl-xavier/jetson-inference/python/training/classification/MyTrainedCars/resnet18.onnx','--input_blob=input_0','--output_blob=output_0','--labels=/home/rdl-xavier/jetson-inference/my_models/MyTrainedCars/labels.txt'])
#net = jetson.inference.imageNet('googlenet',['--model=~/jetson-inference/python/training/classification/people/resnet18.onnx','--input_blob=input_0','--output_blob=output_0','--lables=~/jetson-inference/people/labels.txt'])
#net = jetson.inference.imageNet('googlenet')
#net = jetson.inference.imageNet('resnet-18') ## 18, 50, 101, and 152
#net = jetson.inference.imageNet('vgg-19')  ## 16, 19
#net = jetson.inference.imageNet('inception-v4')

VIDEO_DIRECTORY = '/media/bob/my_ext_ssd' #'/'

DIR_LIST = os.listdir(VIDEO_DIRECTORY)
os.system('clear')
print('AI AUDITOR')

#    print('DATA-SET LIST: ',DIR_LIST)
print()
print('File List')
for line in range(len(DIR_LIST)):
        print('{} {} {}'.format(line, '-'*50, DIR_LIST[line]))

print()
print('Select video from the file list above: ')
#print('1 ---------------------------- Enter search date ')
#print('2 ---------------------------------- Select file ')
print()
VIDEO_FILE = int(input('Select number for VIDEO from the File List above: '))
VIDEO_FILE = '{}/{}'.format(VIDEO_DIRECTORY, DIR_LIST[VIDEO_FILE])
print('video file: ', VIDEO_FILE)

#v_out = getVideo()
#input = jetson.utils.videoSource('csi://0')
#input = jetson.utils.videoSource('rtsp://root:TTItest1@10.4.0.190:554/axis-media/media.amp?videocodec=h264')
#input = jetson.utils.videoSource('rtsp://root:AVCaudit1@10.4.0.187:554/axis-media/media.amp?videocodec=h264')
#input = jetson.utils.videoSource('/dev/video0') ## USB camera
#input = jetson.utils.videoSource('/media/robert/ssd128/axis_2021-03-10_08_59_44_325.mp4') #/ssd500/cars17.mp4') #'/dev/video1')
input = jetson.utils.videoSource(VIDEO_FILE)

def speedTime():
    speed_time = datetime.datetime.now()
    speed_time = speed_time.strftime("%f")
    #print('speed time: ', speed_time)
    return float(speed_time)

def newVideo():
    v_out = getVideo()
    #output = jetson.utils.videoOutput(v_out) ##is_headless
    return v_out

font = jetson.utils.cudaFont()
def collectData():
    location = ' '
    count = 0
    #capture the next image
    img = input.Capture()
    #detections = net.Detect(img, overlay=opt.overlay) overlay options (--overlay=box,labels,conf, and overlay=none)
    #detections  = net_detect.Detect(img, overlay='none')
    detections  = net_detect.Detect(img)
    #print("detected {:d} objects in image".format(len(detections)))
    objects = (len(detections))
    objects = int(objects)
    detection = detections
    #perameter = jetson.inference.detectNet.Detection()
    #print (perameter)
    #print (objects)
    for detection in detections:
        #print('detections: ',detection)
        #net_detect.PrintProfilerTimes()
        class_id_detectNet = int(detection.ClassID)
        Confidence = detection.Confidence
        Left = int(detection.Left)
        Top = int(detection.Top)
        Right = int(detection.Right)
        Bottom = int(detection.Bottom)
        Width = int(detection.Width)
        Height = int(detection.Height)
        Area = int(detection.Area)
        center_x, center_y = detection.Center
        center_x = int(center_x)
        center_y = int(center_y)
        #if objects > 0:
        if class_id_detectNet > 0:
            class_id, confidence = net.Classify(img)
            # find the object description
            class_desc = net.GetClassDesc(class_id)

            #overlay the result on the image
            confidence = int(confidence * 100)
            Confidence = int(Confidence * 100)
            class_id = int(class_id)
            w  = Width
            h = Height
            # In odrer to get the positions of the upper left corner
            x = int(center_x - w/2)
            y = int(center_y - h/2)
            #print ('x_position:{} y_position:{}'.format(x, y))

            #Set trigger x or y trigger position here
            if 100 < x < 300:
                MESSAGE = 'START_ENTRY'
                print(MESSAGE)
            if 400 < x < 600:
                MESSAGE = 'STOP_ENTRY'
                print(MESSAGE)
            if 600 < x < 800:
                MESSAGE = 'START_EXIT'
                print(MESSAGE)
            if 800 < x < 1000:
                MESSAGE = 'STOP_EXIT'
                print(MESSAGE)

                if class_desc == FILTER1:
                    if confidence >= 1:
                        t1 = time.time()
                        #t1 = speedTime()
                        v_out, time_stamp = getVideo()
                        font.OverlayText(img, img.width, img.height, "Time:{} |{:05.2f}% {:s}".format(time_stamp, confidence, class_desc, net.GetNetworkFPS()), 5, 5, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Top:{}".format(Top), 5, 45, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Left:{}".format(Left), 5, 85, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Right:{}".format(Right), 5, 120, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Bottom:{}".format(Bottom), 5, 160, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Height:{}".format(Height), 5, 195, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Width:{}".format(Width), 5, 235, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Area:{}".format(Area), 5, 270, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Center_X:{}".format(x), 5, 305, font.White, font.Gray40)
                        font.OverlayText(img, img.width, img.height, "Center_Y:{}".format(y), 5, 345, font.White, font.Gray40)
                        jetson.utils.saveImageRGBA(v_out, img, width, height)
                        #time.sleep(0.0050)

                    if 700 < x < 900:
                        t2 = time.time()
                        #t2 = speedTime()
                        t1 = float(t1)
                        t2 = float(t2)
                        t_delta = t2 - t1
                        #print('time delta: ', t_delta)
                        #CALCULATE SPEED
                        #SPEED = D/T
                        distance = float(300)
                        #speed = int(distance/t_delta) #meters per second
                        speed = float((distance/t_delta)*2.236936) ##mph
                        #print('speed-time delta: ', t_delta)
                    else:
                        speed = 'UNKOWN'
                    os.chdir(STORAGE_DIRECTORY)
                    path = (os.getcwd())

                    object_names = open(LABELS_FILE)
                    #for line in enumerate(pvr):
                    object_name = object_names.readlines()
                    object_name = object_name[class_id_detectNet]
                    #print('Object name: ',object_name)

                    location = 'TP2' #GPS
                    description =  class_desc
                    description_id = object_name
                    #confidence = int(confidence * 100)
                    color = 0          #vehicle color
                    axle_count = MESSAGE #objects ##
                    license_plate = 0 #######
                    rfid = 0 ################
                    image_path = v_out
                    lane_id = 0
                    speed = 0
                    #INSERT INTO DATABASE
                    data =  (time_stamp, location, description, description_id, Confidence, color, axle_count, license_plate, rfid, speed, lane_id, image_path)
                    conn.execute('INSERT INTO DATA_AQUISITION2 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', data)
                    conn.commit()
                    #class_id_detectNet = 0
                    #return description  #testing only

#SELECT DATA
def selectData():
    #SELECT Operation
    #Following Python program shows how we can fetch and display records from our DATA_AQUISITION table
    #created in above example:
    #!/usr/bin/python
    #import sqlite3
    conn = sqlite3.connect('Dbox_3.db')
    #print ("Opened database successfully")
    cursor = conn.execute('SELECT TIMESTAMP, DESCRIPTION, DESCRIPTION_ID, CONFIDENCE from DATA_AQUISITION2')
    for row in cursor:
        print ("Time stamp: ", row[0])
        print ("Description: ", row[1])
        take_action = row[1]
        print ("Description_ID: ", row[2])
        print ("Confidence: ", row[3], "\n")

def runInference():
    collectData()

while True:
    runInference()
    #time.sleep(2)


"""
This file is used for running scalability experiments by varying dataset size and measuring overall __repr__ performance
"""
import sys, os

sys.path.append(os.path.abspath("."))
from utils import data_utils
from accuracy.rank_utils import *

result_dir = "result/"

import time
import numpy as np
import lux
import pandas as pd
import utils

################################################################
############### Custom Experiment Setting  #####################
control = "early_pruning"
# trial_range = np.geomspace(50000, 1e5, num=3) # airbnb test
dataset = "communities"
# trial_range = np.geomspace(5e4, 1.2e6, num=10) # airbnb
# trial_range = np.geomspace(1e5, 9e5, num=5) # communities
trial_range = np.geomspace(5001, 1.9e5, num=10)
# trial_range = np.geomspace(1e5, 7e5, num=5)
################################################################

timing = []  # [cell count, duration]
accuracy = []
# Must turn off sampling, otherwise maintain_rec constant cost
lux.config.sampling = False

if dataset == "airbnb":
    downsample_func = data_utils.downsample_airbnb
elif dataset == "communities":
    downsample_func = data_utils.downsample_communities
# Warm start (somehow this warm start helps 1st datapoint not be extremely high, unclear why)
df = downsample_func(100)
df._repr_html_()

for nPts in trial_range:
    on_off = False
    if control == "early_pruning":
        lux.config.early_pruning = on_off
    elif control == "lazy_maintain":
        lux.config.lazy_maintain = on_off
    elif control == "sampling":
        lux.config.sampling = on_off

    nPts = int(nPts)
    df = downsample_func(nPts)
    df.intent = ["RentHighQ"]
    ################
    start = time.perf_counter()
    df.maintain_metadata()
    end = time.perf_counter()
    t_meta = end - start
    ################
    start = time.perf_counter()
    df.maintain_recs(render=False)
    end = time.perf_counter()
    t_recs = end - start
    ################
    ground_truth = df.recommendation
    print(f"Completed {nPts}")
    # df.expire_recs()
    # df.expire_metadata()
    timing.append([nPts, on_off, t_meta, t_recs])

    on_off = True
    if control == "early_pruning":
        lux.config.early_pruning = on_off
    elif control == "lazy_maintain":
        lux.config.lazy_maintain = on_off
    elif control == "sampling":
        lux.config.sampling = on_off

    nPts = int(nPts)
    df = downsample_func(nPts)
    df.intent = ["RentHighQ"]
    ################
    start = time.perf_counter()
    df.maintain_metadata()
    end = time.perf_counter()
    t_meta = end - start
    ################
    start = time.perf_counter()
    df.maintain_recs(render=False)
    end = time.perf_counter()
    t_recs = end - start
    ################
    timing.append([nPts, on_off, t_meta, t_recs])
    results = df.recommendation

    for action in ground_truth.keys():
        l1 = ground_truth[action]
        l2 = results[action]
        for k in [3, 5, 10, 15]:
            ndcg = compute_ndcg_between_vislists(l1, l2, k)
            accuracy.append([nPts, action, ndcg, k])
    print(f"Completed {nPts}")
timing_df = pd.DataFrame(
    timing,
    columns=["nPts", control, "t_meta", "t_recs"],
)
timing_df.to_csv(f"{result_dir}{control}_time_q2.csv", index=None)

accuracy_df = pd.DataFrame(
    accuracy,
    columns=["nPts", "action", "NDCG", "@k"],
)
accuracy_df.to_csv(f"{result_dir}{control}_accuracy_q2.csv", index=None)


import re
import itertools
from functools import reduce
from operator import mul
import pandas as pd

# DATA
other_tickets = []
rules = {}
my_ticket = []
with open("Data - Day16.txt") as file:
    oth_marker = False
    rule_marker = True
    my_maker = False
    for line in file:
        if oth_marker:
            other_tickets.append(line.strip().split(","))
        elif "nearby tickets" in line:
            oth_marker = True
        elif line == "\n":
            rule_marker = False
            my_maker = False
        elif rule_marker:
            r = re.search(r"(^[ a-z]+): ([a-z-0-9 ]+)", line)
            k = r.group(1)
            v = r.group(2)
            rules[k] = v
        elif my_maker:
            my_ticket.extend(line.strip().split(","))
        elif "your ticket" in line:
            my_maker = True

# GOAL 1
"""
The rules for ticket fields specify a list of fields that exist somewhere on the ticket and the valid ranges of values for each field.
Adding together all of the invalid values produces your ticket scanning error rate.
"""
valid_ranges = {"valid_from": [], "valid_to": [], "category": []}

for i in rules:
    rule = re.findall(r"[0-9]+", rules[i])
    rule = [int(j) for j in rule]
    valid_ranges["valid_from"].extend([rule[0], rule[2]])
    valid_ranges["valid_to"].extend([rule[1], rule[3]])
    valid_ranges["category"].extend([i, i])

valid_ranges = pd.DataFrame(valid_ranges)

def check_valid(valid, tickets):
    invalid = []

    for ticket in tickets:
        for num in ticket:
            num = int(num)
            between = False
            for idx in valid.index:
                if valid["valid_from"][idx] <= num <= valid["valid_to"][idx]:
                    between = True
                    break
            if not between:
                invalid.append(num)

    return sum(invalid)

print(f"The ticket scanning error rate equals: {check_valid(valid_ranges, other_tickets)} for part 1")

# GOAL 2
"""
Now that you've identified which tickets contain invalid values, discard those tickets entirely.
Use the remaining valid tickets to determine which field is which.

Once you work out which field is which,
look for the six fields on your ticket that start with the word departure.
What do you get if you multiply those six values together?
"""
def only_valid(valid, tickets):
    invalid = []
    for ticket in tickets:
        for num in ticket:
            num = int(num)
            between = False
            for idx in valid.index:
                if valid["valid_from"][idx] <= num <= valid["valid_to"][idx]:
                    between = True
                    break
            if not between:
                invalid.append(ticket)

    valid_tickets = [i for i in tickets if i not in invalid]

    return valid_tickets

def create_from_to_except(valid_ranges):
    new_df = {"cat": [], "fro": [], "to": [], "ex_fro": [], "ex_to": []}

    uni_cats = valid_ranges["category"].unique()
    for i in uni_cats:
        temp = valid_ranges[valid_ranges["category"] == i].reset_index(drop=True)

        new_df["cat"].append(i)
        new_df["fro"].append(temp["valid_from"][0])
        new_df["to"].append(temp["valid_to"][1])
        new_df["ex_fro"].append(temp["valid_to"][0])
        new_df["ex_to"].append(temp["valid_from"][1])

    return pd.DataFrame(new_df)

def check_category(rule_row, tickets, ticket_values):
    for tic in tickets:
        for idx in ticket_values:
            if (
                rule_row["fro"] <= int(tic[idx]) <= rule_row["to"] and not
                rule_row["ex_fro"] < int(tic[idx]) < rule_row["ex_to"]
                ):
                pass
            else:
                ticket_values[idx].remove(rule_row["cat"])

    return ticket_values

def find_idx_cat(ticket_values):
    final = []
    rem = "placeholder"
    while len(ticket_values) > 0:
        for i in ticket_values:
            if len(ticket_values[i]) == 1:
                final.append((i, ticket_values[i][0]))
                rem = ticket_values[i][0]
                del ticket_values[i]
                break

        for i in ticket_values:
            if rem in ticket_values[i]:
                ticket_values[i].remove(rem)

    return final

def prod(iterable): # default function in the math module in python 3.9
    return reduce(mul, iterable, 1)

df_ranges = create_from_to_except(valid_ranges)
tickets = only_valid(valid_ranges, other_tickets)
tickets.append(my_ticket)

ticket_values = {}
for i in range(len(my_ticket)):
    ticket_values[i] = list(rules.keys())

for row in df_ranges.index:
    ticket_values = check_category(df_ranges.iloc[row], tickets, ticket_values)

comb = find_idx_cat(ticket_values)

indices = [i for i,j in comb if "departure" in j]

print(f"The multiplication answer is {prod([int(j) for i,j in enumerate(my_ticket) if i in indices])}")


import urllib.request
from bs4 import BeautifulSoup
from time import sleep
from send_server import get_time, send_data, play_sound
import webbrowser

def run_scraper(drug, site):
    webpage = urllib.request.urlopen(site)
    xml = BeautifulSoup(webpage, 'xml')
    for entry in xml.findAll('li'):
        for item in entry.findAll('a'):
            title = item.get('title')
            link = item.get('href')
            if title != None and drug.lower() in title.lower() and title not in old_titles:
                title = title.replace('Click to view ', '')
                new_link = 'https://www.accessdata.fda.gov/' + link
                new_link = new_link.replace('.process=', '.process&ApplNo=')
                send_data('Drug Approval', title, get_time(), new_link)
                webbrowser.open(new_link)
                print('Drug Approval', title, get_time(), new_link)
                play_sound('approval.mp3')
                old_titles.append(title)

old_titles = []
drugs = ['Qbrexza']

while True:
    try:
        for drug in drugs:
            first_letter = drug[0]
            site = 'https://www.accessdata.fda.gov/scripts/cder/daf/index.cfm?event=browseByLetter.page&productLetter='
            site = site + first_letter
            run_scraper(drug, site)
            sleep(.8)
    except:
        play_sound('error.mp3')


import gym
import numpy as np
from operator import itemgetter
env = gym.make('CartPole-v0')

ninputs = env.observation_space.shape[0]
if (isinstance(env.action_space, gym.spaces.box.Box)):
 noutputs = env.action_space.shape[0]
else:
 noutputs = env.action_space.n
nhiddens=10
pvariance = 0.1 # variance of initial parameters
ppvariance = 0.02 # variance of perturbations
# initialize the training parameters randomly by using a gaussian distribution with average 0.0 and variance 0.1
# biases (thresholds) are initialized to 0.0
W1 = np.random.randn(nhiddens,ninputs) * pvariance # first layer
W2 = np.random.randn(noutputs, nhiddens) * pvariance # second layer
b1 = np.zeros(shape=(nhiddens, 1)) # bias first layer
b2 = np.zeros(shape=(noutputs, 1)) # bias second layer
def initialize_weights(n,ninputs,nhiddens,noutputs):
    par_dic=[]
    for i in range(n):
        par_dic.append( {"W1": np.random.randn(nhiddens,ninputs),
                    "W2": np.random.randn(noutputs, nhiddens),
                    "b1": np.zeros((nhiddens, 1)),
                    "b2": np.zeros((noutputs, 1))})

    return par_dic

def predict(observation,W1,W2,b1,b2):
    Z1 = np.dot(W1, observation) + b1
    A1 = np.tanh(Z1)
    Z2 = np.dot(W2, A1) + b2
    A2 = np.tanh(Z2)
    if (A2[0] < 0):
        action = 0
    else:
        action = 1
    return action

def add_noise(dic,n):
    for i in range(int(n/2)):
        dic[i]['W1']=dic[int(n/2)+i]['W1']+np.random.randn(nhiddens,ninputs)*ppvariance
        dic[i]['W2']=dic[int(n/2)+i]['W2']+np.random.randn(noutputs, nhiddens)*ppvariance
        dic[i]['b1']=dic[int(n/2)+i]['b1']+np.random.randn(nhiddens, 1)*ppvariance
        dic[i]['b2']=dic[int(n/2)+i]['b2']+np.random.randn(noutputs, 1)*ppvariance
    return dic

reward1=0
popul = 10
par_dic = initialize_weights(popul,ninputs,nhiddens,noutputs)
t1 = 0
flag = 1
while(flag):
    for i in range(popul):
        observation = env.reset()
        reward1 = 0
        for t in range(200):
            observation.resize(ninputs, 1)
            W1 = par_dic[i]['W1']
            W = par_dic[i]['W2']
            b1 = par_dic[i]['b1']
            b2 = par_dic[i]['b2']
            action = predict(observation,W1,W2,b1,b2)
            observation, reward, done, info = env.step(action)
            reward1=reward1+reward
            if done == True:
                    t1 = t
                    par_dic[i]['reward']=reward1
                    break
    par_dic = sorted(par_dic,key=itemgetter('reward'))
    print(par_dic[len(par_dic)-1]['reward'])
    par_dic = add_noise(par_dic,popul)
    if par_dic[len(par_dic)-1]['reward']>199.0:
        print('we are done now!!!')
        flag = 0
        break


'''
Created on 17 Jun 2014

@author: Kari
'''
from random import randint
import sys

class BlackJackGame:

    def BlackJack(self):
        playerCards = []
        computerCards = []
        print(" *** Welcome To Blackjack. The player goes first..... *** ")
        computerPlaying = False
        playerCards.append(self.shuffle(computerPlaying))
        playerCards.append(self.shuffle(computerPlaying))
        print("The cards values you received in the shuffle are %s and %s " % (playerCards[0],playerCards[1]))
        playerCards =  self.hitOrStay(playerCards,computerPlaying)
        print("The computer is taking it's turn")
        computerPlaying = True
        computerCards.append(self.shuffle(computerPlaying))
        computerCards.append(self.shuffle(computerPlaying))
        print("The computer cards received are %s and %s " % (computerCards[0],computerCards[1]))
        computerCards = self.computerLogic(computerCards,computerPlaying)
        print("Computer has chosen to stay")
        computerPlaying = False

        playerTotal = self.total(playerCards)
        computerTotal = self.total(computerCards)
        print("Player card total %s" % playerTotal)
        print("Computer card total %s" % computerTotal)
        self.checkWin(playerTotal,computerTotal)

    def checkWin(self,playerTotal,computerTotal):
        if playerTotal > computerTotal:
            print("Player wins")
        elif computerTotal > playerTotal:
            print("Computer wins")
        else:
            print("It's a draw")
        self.playAgain();

    def total(self,lists):
        sum = 0
        for i in range(len(lists)):
            sum += int(lists[i])
        return sum

    def computerLogic(self,computerCards,computerPlaying):

        sum = 0
        for i in range(len(computerCards)):
            sum += int(computerCards[i])
        if(sum > 21):
            print("Computer went bust")
            self.playAgain()
        if(sum <= 16):
            print("Computer has choosen to hit")
            computerCards.append(self.shuffle(computerPlaying))
            self.computerLogic(computerCards,computerPlaying)
        return computerCards

    def hitOrStay(self,playerCards,computerPlaying):
        choice = input("Would you like to hit or stay : ")
        if choice == "hit":
            playerCards.append(self.shuffle(computerPlaying))
            print("Your current cards values are : ")
            for i in range(len(playerCards)):
                print(playerCards[i])
            bust = self.checkForBust(playerCards)
            if(bust == True):
                print("You went bust - Game over")
                self.playAgain();
            else:
               self.hitOrStay(playerCards,computerPlaying)

        return playerCards

    def playAgain(self):
         userInput = input("Would you like to play again (yes/no) ? ")
         if userInput == "yes":
             self.BlackJack()
         elif userInput == "no":
             sys.exit()

    def checkForBust(self,list):
        sum = 0
        for i in range(len(list)):
            sum += int(list[i])
        if(sum > 21):
            return True

        else:
            return False

    def shuffle(self,computerPlaying):
        card = randint(1,11)
        if card == 11:
            if computerPlaying == True:
                card = randint(1,2)
                if card == 2:
                    card = 1
            else:
                ui = input("You recieved an ace ! Do you want the value to be 11 or 1 ? ")
                card = int(ui)

        return card

e = BlackJackGame()
e.BlackJack()


#! /usr/bin/env python3

# Nucleotide Counter
#
# Given a sequence consisting only of the characters 'A', 'C', 'T', and 'G',
# return a count of how frequently each one occurs.
#

import sys

def parse_sequence_argument(args):
    if len(args) < 2:
        raise ValueError("Argument missing")

    return args[1]

def count(sequence):
    totals = {'A': 0, 'C': 0, 'T': 0, 'G': 0}

    for nucleotide in sequence:
        nucleotide = nucleotide.upper()  # normalise the value before using it
        totals[nucleotide] += 1

    return totals

def show_totals(totals, out):
    for nucleotide, count in totals.items():
        print("{0} total is {1}".format(nucleotide, count), file=out)

# Entry point for invocation as a script, expects one command line argument
if __name__ == "__main__":
    sequence = parse_sequence_argument(sys.argv)
    totals = count(sequence)
    show_totals(totals, sys.stdout)


#!/usr/bin/env python3

from setuptools import find_packages, setup

INSTALL_REQUIRES = ['numpy', 'statsmodels', 'numba', 'matplotlib',
                    'pandas', 'xarray', 'scipy', 'scikit-learn',
                    'regularized_glm', 'dask', 'patsy', 'networkx', 'joblib']
TESTS_REQUIRE = ['pytest >= 2.7.1']

setup(
    name='replay_trajectory_classification',
    version='0.7.7.dev0',
    license='MIT',
    description=('Classify replay trajectories.'),
    author='Eric Denovellis',
    author_email='edeno@bu.edu',
    url='https://github.com/Eden-Kramer-Lab/replay_trajectory_classification',
    packages=find_packages(),
    install_requires=INSTALL_REQUIRES,
    tests_require=TESTS_REQUIRE,
)


""" Katie Lunceford and Jon Li

This is a plotter class that was used in an old
checkpoint but not implemented in the final project.

The initialization takes in two lists and puts these
lists in the attributes self.y and self.x.

It has two methods: scatterPlot and barGraph which
make the appropriate plots out of self.y and self.x
"""

import matplotlib.pyplot as plt
import numpy as np

class Plotter:
    def __init__(self, list1, list2 = []):
        if list2 == []:
            self.y = list1
            self.x = [i + 1 for i in range(len(list1))]
        else:
            self.x = list1
            self.y = list2

    def scatterPlot(self):
        area = np.pi*15
        plt.scatter(self.x, self.y, s = area)
        plt.show()

    def barGraph(self):
        plt.bar(self.x, self.y, width = 0.5, align = 'center')
        plt.show()


import pandas as pd
import matplotlib.pyplot as plt

def analysis():

    #df['Timeseries'] = pd.date_range(start='09:30:00',end=None,periods=20)

    #Load CSV Data into a DF
    df = pd.read_csv("Data/Quandl_Intraday_Prices.csv")

    #Get a timeseries
    #range = df[(df['Timestamp'] >= '09:30:00') & (df['Timestamp'] <= '09:45:00')]
    range = df[(df.Timestamp >= '09:30:00') & (df.Timestamp <= '09:45:00')]

    #Get data for one security from the DF
    df2 = range.loc[range.Ticker == 'TSS']

    #Filter certain columns
    usecols = df2[['Timestamp','HighPrice','LowPrice']]

    #Plot data
    ax = usecols.plot(title='Tick Data', fontsize=12)
    ax.set_xlabel("Minutes")
    ax.set_ylabel("Price")

    plt.show()

if __name__ == "__main__":
    analysis()


import mlflow
import logging
from itertools import cycle

import torch
import torch.nn as nn
import torch.optim as optim

from nni.nas.pytorch import mutables
from nni.nas.pytorch.trainer import Trainer
from nni.nas.pytorch.utils import AverageMeterGroup, to_device

# my thing
from model.NASutils import get_batch_jacobian, eval_score,  FactorizedReduce, ConvBranch, PoolBranch, FactorizedUpsample, EnasMutator, ResidualConvBranch

logger = logging.getLogger(__name__)

class ENASLayer(mutables.MutableScope):
    def __init__(self, key, prev_labels, in_filters, out_filters):
        super().__init__(key)
        self.in_filters = in_filters
        self.out_filters = out_filters
        self.mutable = mutables.LayerChoice([
#             ConvBranch(in_filters, out_filters, kernel_size=3, stride=1, separable=False),
#             ConvBranch(in_filters, out_filters, kernel_size=3, stride=1, separable=True),
            ConvBranch(in_filters, out_filters, kernel_size=5, stride=1, separable=False),
#             ConvBranch(in_filters, out_filters, kernel_size=5, stride=1, separable=True),
#             ConvBranch(in_filters, out_filters, kernel_size=7, stride=1, separable=False),
#             ConvBranch(in_filters, out_filters, kernel_size=7, stride=1, separable=True),
#             ConvBranch(in_filters, out_filters, kernel_size=9, stride=1, separable=False),
            ConvBranch(in_filters, out_filters, kernel_size=41, stride=1, separable=True),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=3, stride=1, separable=False),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=3, stride=1, separable=True),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=5, stride=1, separable=False),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=5, stride=1, separable=True),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=7, stride=1, separable=False),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=7, stride=1, separable=True),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=9, stride=1, separable=False),
#             ResidualConvBranch(in_filters, out_filters, kernel_size=9, stride=1, separable=True),
#             PoolBranch('avg', in_filters, out_filters, kernel_size=3, stride=1),
#             PoolBranch('max', in_filters, out_filters, kernel_size=3, stride=1),
        ])
        if len(prev_labels) > 0:
            self.skipconnect = mutables.InputChoice(choose_from=prev_labels, n_chosen=None)
        else:
            self.skipconnect = None
        self.batch_norm = nn.BatchNorm1d(out_filters, affine=False)

    def forward(self, prev_layers):
        out = self.mutable(prev_layers[-1])
        if self.skipconnect is not None:
            connection = self.skipconnect(prev_layers[:-1])
            if connection is not None:
                out += connection
        return self.batch_norm(out)

class GeneralNetwork(nn.Module):
    def __init__(self, num_layers=12, out_filters=24, in_channels=1,
                 dropout_rate=0.0):
        super().__init__()
        self.num_layers = num_layers
        self.out_filters = out_filters

        self.stem = nn.Sequential(
            nn.Conv1d(in_channels, out_filters, 25, 1, 1, bias=False),
            nn.BatchNorm1d(out_filters)
        )
        # when to downsample
        pool_distance = self.num_layers // 6
        self.pool_layers_idx = [pool_distance - 1, 2 * pool_distance - 1]
        # when to upsample
        upsample_distance = self.num_layers // 6
        self.upsample_layers_idx = [3 * pool_distance - 1, 4 * pool_distance - 1]

        self.dropout_rate = dropout_rate
        self.dropout = nn.Dropout(self.dropout_rate)

        self.layers = nn.ModuleList()
        self.pool_layers = nn.ModuleList()
        self.upsample_layers = nn.ModuleList()
        labels = []
        for layer_id in range(self.num_layers):
            labels.append("layer_{}".format(layer_id))

            if layer_id in self.pool_layers_idx:
#                 self.pool_layers.append(FactorizedReduce(self.out_filters, self.out_filters))
                self.pool_layers.append(nn.MaxPool1d(2))

            if layer_id in self.upsample_layers_idx:
                self.upsample_layers.append(FactorizedUpsample(self.out_filters, self.out_filters))

            self.layers.append(ENASLayer(labels[-1], labels[:-1], self.out_filters, self.out_filters))

    def forward(self, x):
        bs = x.size(0)
        cur = self.stem(x)

        layers = [cur]

        for layer_id in range(self.num_layers):
            cur = self.layers[layer_id](layers)
            layers.append(cur)
            if layer_id in self.pool_layers_idx:
                for i, layer in enumerate(layers):
                    layers[i] = self.pool_layers[self.pool_layers_idx.index(layer_id)](layer)
                cur = layers[-1]

#         cur = self.gap(cur).view(bs, -1)
#         cur = self.dropout(cur)
#         logits = self.dense(cur)
        return cur #logits

class EnasTrainer(Trainer):
    '''
     model, metrics,
                 optimizer, num_epochs, dataloader_train, dataloader_valid,
                 mutator=None, batch_size=64, device=None, log_frequency=None, callbacks=None,
                 entropy_weight=0.0001, skip_weight=0.8, baseline_decay=0.999, child_steps=500,
                 mutator_lr=0.00035, mutator_steps_aggregate=20, mutator_steps=50, aux_weight=0.4,
                 test_arc_per_epoch=1
     '''
#     self.previous_lr = 0.00035
    def __init__(self, model, mutator,
                 optimizer, num_epochs, dataloader_train, dataloader_valid,
                 batch_size=64, device=None, log_frequency=None, callbacks=None,
                 entropy_weight=0.0001, skip_weight=0.8, baseline_decay=0.999, child_steps=500,
                 mutator_lr=0.00035, mutator_steps_aggregate=20, mutator_steps=50, aux_weight=0.4,
                 test_arc_per_epoch=1):
        super().__init__(model, mutator, nn.CrossEntropyLoss(), None, optimizer, num_epochs,
                 dataloader_train, dataloader_valid, batch_size, None, device, log_frequency, callbacks)
        self.model = model.to(device)
        self.log_frequency = log_frequency
        self.optimizer = optimizer
        self.device = device
        self.callbacks = callbacks
        self.num_epochs = num_epochs
        self.dataloader_train = dataloader_train
        self.dataloader_valid = dataloader_valid
        self.mutator = mutator
        self.mutator_optim = optim.Adam(self.mutator.parameters(), lr=mutator_lr)
        self.batch_size = batch_size
#         self.metrics = metrics
        self.entropy_weight = entropy_weight
        self.skip_weight = skip_weight
        self.baseline_decay = baseline_decay
        self.baseline = 0.
        self.mutator_steps_aggregate = mutator_steps_aggregate
        self.mutator_steps = mutator_steps
        self.child_steps = child_steps
        self.aux_weight = aux_weight
        self.test_arc_per_epoch = test_arc_per_epoch

        self.init_dataloader()

    def init_dataloader(self):
        self.train_loader = cycle(self.dataloader_train)
        self.valid_loader = cycle(self.dataloader_valid)

    def train_one_epoch(self, epoch):
        # Train sampler (mutator)
        self.model.eval()
        self.mutator.train()
        total_loss=0
        meters = AverageMeterGroup()
        for mutator_step in range(1, self.mutator_steps + 1):
            self.mutator_optim.zero_grad()
            for step in range(1, self.mutator_steps_aggregate + 1):
                x, y = next(self.valid_loader)
                x, y = to_device(x, self.device), to_device(y, self.device)

                self.mutator.reset()
                with torch.no_grad():
                    logits = self.model(x)
                self._write_graph_status()
                jacobian = get_batch_jacobian(self.model, x)
                jacobian = jacobian.reshape(jacobian.size(0), -1)

                reward = eval_score(jacobian)
                total_loss += reward.item()

                if self.entropy_weight:
                    reward += self.entropy_weight * self.mutator.sample_entropy.item()
                # https://arxiv.org/pdf/1707.06347.pdf
                self.baseline = self.baseline * self.baseline_decay + reward * (1 - self.baseline_decay)
                loss = self.mutator.sample_log_prob * (reward - self.baseline)
                if self.skip_weight:
                    loss += self.skip_weight * self.mutator.sample_skip_penalty

                loss /= self.mutator_steps_aggregate
                loss.backward()

                cur_step = step + (mutator_step - 1) * self.mutator_steps_aggregate
                if self.log_frequency is not None and cur_step % self.log_frequency == 0:
                    logger.info("RL Epoch [%d/%d] Step [%d/%d] [%d/%d]  %s", epoch + 1, self.num_epochs,
                                mutator_step, self.mutator_steps, step, self.mutator_steps_aggregate,
                                reward.int())

            nn.utils.clip_grad_norm_(self.mutator.parameters(), 5.)
            self.mutator_optim.step()
        mlflow.log_metric('Total reward', -total_loss/(self.mutator_steps*self.mutator_steps_aggregate), epoch)
        torch.save({
        'model':self.mutator.state_dict(),
        'optimizer':self.mutator_optim.state_dict()
        }, 'mutator_run_stats.pyt')
        mlflow.log_artifact('mutator_run_stats.pyt')

    def validate_one_epoch(self, epoch):
        pass


from matplotlib import pyplot as plt
from fitness import *
import sys

import random
from math import *
import numpy as np
import sympy as sy
from math import sin, cos, sqrt, floor
random.seed()

CONDITION = True
GENERATIONS = 20
POPULATION_SIZE = 20
MUTATION_CHANCE = 1.0  # mutation between 0 and 100 percent
if MUTATION_CHANCE > 100:
        MUTATION_CHANCE = 100.0
if MUTATION_CHANCE < 0:
        MUTATION_CHANCE = 0.0
NOTE="GA - random recomb."

print(NOTE)
print("PARAMETERS\n")
print("Generations: ", GENERATIONS)
print("Population size: ", POPULATION_SIZE)
print("Mutation chance: ", MUTATION_CHANCE, "%")
print("\n\n")

def genPopulation(geneList):
    for i in range(POPULATION_SIZE):
        g = Gene()
        geneList.append(g)

genes = []
best_fit = []

#generate the beginning population
genPopulation(genes)

for i in range(GENERATIONS):

    print(int(((i+1)/GENERATIONS)*100), "%", "DONE", end="\r")
    #genes[:] = []
    #sort

    #for x in genes:
    #    print(x.fitness)
    #store best

    #delete worse half of survivors
    del genes[-floor(len(genes)/2):]

    #refill the population
    for i in range(POPULATION_SIZE-len(genes)):
        (geneA, geneB) = random.sample(genes, 2)
        #print("A", geneA.a1, geneA.a2)
        #print("B",geneB.a1, geneB.a2)
        g = Gene()
        g.setParameters(a1=random.choice([geneA.a1, geneB.a1]), a2=random.choice([geneA.a1, geneB.a1]))
        #random mutation
        if random.random() < MUTATION_CHANCE/100:
                #print("RANDOM MUTATION")
                g.setParameters(a1=random.choice(populationValues),
                                a2=random.choice(populationValues))
        genes.append(g)

    genes.sort(key=lambda x: x.fitness, reverse=False)
    best_fit.append(genes[0].fitness)
DELTA = best_fit[0]-best_fit[GENERATIONS-1]

#PLOTTING

plt.figure()
plt.title("Change of q1 and q2, "+NOTE)

plt.plot(genes[0].q1)
plt.plot(genes[0].q2)
plt.scatter(np.arange(0, len(genes[0].q1)), genes[0].q1, label="q1")
plt.scatter(np.arange(0, len(genes[0].q2)), genes[0].q2, label="q2")
plt.xlabel("Time [s]")
plt.ylabel("Joint angle [rad]")
plt.legend(loc="upper left")
plt.show()

plt.figure()
plt.title("Change of torques, "+NOTE)
plt.plot(genes[0].tau1)
plt.plot(genes[0].tau2)
plt.plot(genes[0].tau3)
plt.plot(genes[0].tau4)
plt.scatter(np.arange(0, len(genes[0].q1)), genes[0].tau1, label="$\\tau_1$")
plt.scatter(np.arange(0, len(genes[0].q1)), genes[0].tau2, label="$\\tau_2$")
plt.scatter(np.arange(0, len(genes[0].q1)), genes[0].tau3, label="$\\tau_3$")
plt.scatter(np.arange(0, len(genes[0].q1)), genes[0].tau4, label="$\\tau_4$")
plt.xlabel("Time [s]")
plt.ylabel("Joint Torque [Nm]")
plt.legend(loc="upper left")
plt.show()

plt.figure()
plt.title(NOTE+"\nPopulation = "+str(POPULATION_SIZE) +
          ", $\\Delta = $" + str(DELTA)[0:4])

plt.xlabel("Generation")
plt.ylabel("Fitness")
plt.plot(
    best_fit, label="$\sum \sqrt{\\tau_1^2+\\tau_2^2+\\tau_3^2+\\tau_4^2}$")
plt.legend(loc='upper right')

plt.show()