import json
import discord
from discord.ext import tasks
from discord.ext import commands
import server
import asyncio
import os
import storage.s3 as storage

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.presences = True
bot = commands.Bot(command_prefix='.o ', activity=discord.Activity(name=".o help",type=discord.ActivityType.listening), intents=intents)

s3 = storage.S3(bucket='valheim-worlds-config')
worlds_json = json.loads(s3.get('worlds.json'))

# iterate over the worlds and instantiate Valheim for each
valheim_worlds = {}
for k, v in worlds_json.items():
    cluster_instance = server.Valheim(cluster=v["clustername"])
    valheim_worlds.update({k: cluster_instance})

@bot.event
async def on_ready():
    cleanup_loop.start()
    print('Bot is ready')

@bot.command(name="storage-status", brief="Return storage usage %", help="It runs a df -h inside the container, showing the usage % of every mount")
async def storage_status(ctx):
    v = valheim_worlds[ctx.guild.name].get_storage_details()
    print(v)
    await ctx.send(v)

@bot.command(name="server-status", brief="Return server status", help="Server status: if server is fully loaded, the status will be LOADED")
async def server_status(ctx):
    try:
        sv_status = valheim_worlds[ctx.guild.name].status
        await ctx.send(f"Server {worlds_json[ctx.guild.name]['worldname']} is {sv_status}")
    except Exception as e:
        print(e)
        await ctx.send(f"Error getting status")

@bot.command(name="server-start", brief="Start Valheim", help="It goes thru the following steps: 1- Scale up VM, 2- Scale up Valheim service, 3- Wait for the 'Game connected' on logs to report LOADED state")
async def server_start(ctx):
    valheim_worlds[ctx.guild.name].guild = ctx.guild
    server_loaded = False
    task = valheim_worlds[ctx.guild.name].task_status()
    cur_task_status = task[0]
    print(f"current task status is: {cur_task_status}")
    if valheim_worlds[ctx.guild.name].status == 'LOADED':
        await ctx.send("Server already up and running, enjoy!")
        server_loaded = True

    if not server_loaded:
        valheim_worlds[ctx.guild.name].status = 'STARTING'
        await ctx.send(f"Server {worlds_json[ctx.guild.name]['worldname']} is starting, I'll send updates on every status change")
        async with ctx.typing():
            await valheim_worlds[ctx.guild.name].start()

        last_task_status = None
        while cur_task_status != 'RUNNING':
            task = valheim_worlds[ctx.guild.name].task_status()
            cur_task_status = task[0]
            async with ctx.typing():
                while cur_task_status == last_task_status:
                    task = valheim_worlds[ctx.guild.name].task_status()
                    cur_task_status = task[0]
                    print(f"[{worlds_json[ctx.guild.name]['worldname']}] current task {task[1]} status is: {cur_task_status}")
                    await asyncio.sleep(2)
            await ctx.send(f"Server is starting, status: {cur_task_status}")
            last_task_status = cur_task_status

        await ctx.send(f"Server is running, now loading world, I'll let you know when it's loaded")
        valheim_worlds[ctx.guild.name].status = 'LOADING'
        cur_gameserver_status = valheim_worlds[ctx.guild.name].gameserver_status(task[1])
        print(f"[{worlds_json[ctx.guild.name]['worldname']}] current gameserver status is: {cur_gameserver_status}")
        async with ctx.typing():
            while cur_gameserver_status  != 'LOADED':
                cur_gameserver_status = valheim_worlds[ctx.guild.name].gameserver_status(task[1])
                print(f"current gameserver status is: {cur_gameserver_status}")
                await asyncio.sleep(2)

        await ctx.send("Server is up and running, enjoy!")
        valheim_worlds[ctx.guild.name].status = 'LOADED'
        server_loaded = True

@bot.command(name="server-stop", brief="Stop server", help="It goes thru the following steps: 1- stops Valheim process, 2- Make Valheim bkp, 3- Scale down VM")
async def server_stop(ctx):
    if valheim_worlds[ctx.guild.name].status != 'STOPPED':
        valheim_worlds[ctx.guild.name].stop_valheim_process()
        if valheim_worlds[ctx.guild.name].status == 'LOADED':
            await ctx.send("Making backup before shutdown...")
            async with ctx.typing():
                    await bot.loop.run_in_executor(None, valheim_worlds[ctx.guild.name].make_valheim_bkp)
            valheim_worlds[ctx.guild.name].remove_infra()
            valheim_worlds[ctx.guild.name].status = 'STOPPED'
            await ctx.channel.send(f"server {worlds_json[ctx.guild.name]['worldname']} down, hope you had a great time!")
        else:
            await ctx.channel.send(f"server {worlds_json[ctx.guild.name]['worldname']} is already stopped")

@tasks.loop(seconds=30*60)
async def cleanup_loop():
    for guild in worlds_json:
        if valheim_worlds[guild].status == 'LOADED':
            print(f'{worlds_json[guild]["worldname"]} is loaded, cleaning up old valheim days')
            valheim_worlds[guild].cleanup_old_days(4)
        else:
            print(f'cleanup skipped because {worlds_json[guild]["worldname"]} is {valheim_worlds[guild].status}')

bot.run(os.getenv('ODIN_BOT_TOKEN'))


"""

    preprocess_tweets.py

    Cleans and preprocesses hydrated tweets (from AWS S3 bucket), uploads back to AWS.

"""
import os
import ast
import pandas as pd
import emoji
import re
import nltk
import datetime
from nltk.corpus import stopwords
import aws_helpers
from aws_helpers import save_to_AWS, load_from_AWS

def parse_location(location_dict):
    """
    Looks at location information and determines (1) if the location is in the USA or not and (2) if it
    is in the USA, what state is it in?

    Arg:
        location_dict: value from "place" field from tweet data (dict)
    Returns:
        is_USA: is the location in the USA? (bool)
        country_location: country (str)
        state: if it is in the USA, which state is it in? (str)

    """

    if location_dict is None:
        return ("N/A", "N/A", "N/A")
    elif location_dict["country_code"] != "US":
        return (False, location_dict["country_code"], "N/A")
    else:
        try:
            # e.g., "Los Angeles, CA" --> "CA"
            state = location_dict["full_name"].split(",")[1].strip()
        except Exception as e:
            # sometimes it just denotes the full name as "United States"
            state = location_dict["full_name"].strip()
        finally:
            return (True, "US", state)

def parse_dates(timestamp):
    """
    Processes the date information and extracts date and time information
    Arg:
        timestamp: timestamp of date + time (str)
    Returns:
        date: human-readable date (str) (e.g., "2021-02-09")
        year: calendar year (int)
        month: calendar month (str, "00" to "12")
        day: calendar day (int)
        hour: hour of day (int)

    """
    hour = pd.to_datetime(timestamp).hour
    dt_obj = pd.to_datetime(timestamp).date()
    year = dt_obj.year
    month = dt_obj.month
    day = dt_obj.day

    if month < 10:
        month = f"0{month}"

    month = str(month)

    date = f"{year}-{month}-{day}"

    return (date, year, month, day, hour)

def remove_emoji(text):
    """
    Removes emojis from a text

    Args:
        text: tweet/text to clean (str)
    Returns:
        clean_text: tweet/text without emojis (str)
    """

    text = text.encode("utf-8")
    allchars = [str for str in text.decode('utf-8')]
    emoji_list = [c for c in allchars if c in emoji.UNICODE_EMOJI]
    clean_text = ' '.join([str for str in text.decode(
        'utf-8').split() if not any(i in str for i in emoji_list)])
    return clean_text

def clean_text(text):
    """
    Removes punctuation, does string split (tokenization) and removes links
    Args:
        text: tweet/text to clean (str)
    Returns:
        tokenized_text_arr: tokenized and cleaned text (list of strings)
    """

    PUNCTUATION = '''!()-[]{};:'"\,<>./?@$%^&*_~'''  # keep hashtags
    STOPWORDS = stopwords.words("english")

    # remove punctuation
    text_no_punctuation = ""

    for char in text:
        if char not in PUNCTUATION:
            text_no_punctuation = text_no_punctuation + char

    # remove emojis
    text_no_punctuation = remove_emoji(text_no_punctuation)

    # remove \n and \t
    text_no_punctuation = re.sub(r'\n', '', text_no_punctuation)
    text_no_punctuation = re.sub(r'\t', '', text_no_punctuation)

    # remove escape sequences
    text_no_escape = ""

    for char in text_no_punctuation:
        try:
            char.encode('ascii')
            # this'll catch chars that don't have an ascii equivalent (e.g., emojis)
            text_no_escape = text_no_escape + char
        except:
            pass

    # add space between # and another char before it (e.g., split yes#baseball into yes #baseball)
    text_no_escape = re.sub(r"([a-zA-Z0-9]){1}#", r"\1 #", text_no_escape)

    # string split
    text_arr = text_no_escape.split(' ')

    tokenized_text_arr = []

    for word in text_arr:

        word = word.lower()

        if "http" not in word and word.strip() != '' and word not in STOPWORDS:
            tokenized_text_arr.append(word)

    return tokenized_text_arr

def parse_hashtags(text):
    """
    Extracts both (1) the hashtags in a piece of text as well as
    (2) the parts of the text that don't have a hashtag

    Args:
        text: tweet/piece of text (str)
    Return:
        hashtag_arr: array of hashtags (list of strings)
        non_hashtag_arr: array of non-hashtag words (list of strings)
    """
    hashtag_arr = []
    non_hashtag_arr = []

    tokenized_text_arr = text.split(' ')

    for word in tokenized_text_arr:
        if '#' in word:
            # how many hashtags are in the word?
            num_hashtags = 0
            for char in word:
                if char == '#':
                    num_hashtags += 1

            # if multiple hashtag words are squished together, split them on '#' and return the resulting words
            if num_hashtags > 1:
                word_arr = word.split('#')
                for inner_word in word_arr:
                    if inner_word != '#':
                        hashtag_arr.append("#" + inner_word)
            # else, if only one hashtag, add as is
            else:
                hashtag_arr.append(word)

        else:
            non_hashtag_arr.append(word)

    return (hashtag_arr, non_hashtag_arr)

def count_hashtags(text):
    """
    Counts the number of hashtags in a piece of text
    Args:
        text: tweet/piece of text (str)
    Return:
        count: number of hashtags (#s) in text
    """
    text_arr = text.split(' ')
    count = 0

    for word in text_arr:
        if '#' in word:
            count += 1

    return count

def try_literal_eval(text):
    """
    Tries to use ast's literal_eval function to
    evaluate a string into its literal representation (e.g., 'dict')

    Arg:
        text: string representation
    Returns:
        eval: literal representation of parsed string
    """
    try:
        eval = ast.literal_eval(text)
    except Exception as e:
        eval = None

    return eval

if __name__ == "__main__":

    # change dir to this file's directory
    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    # get env vars
    AWS_BUCKET = os.environ["AWS_BUCKET"]
    AWS_ACCESS = os.environ["AWS_ACCESS"]
    AWS_SECRET = os.environ["AWS_SECRET"]

    # initialize paths
    AWS_TWEET_DIR = "tweet_scrapes/"
    HYDRATED_TWEETS_PATH = "./../../tweets/hydrated_tweets/"
    PREPROCESSED_TWEETS_PATH = "./../../tweets/preprocessed_tweets/"

    # full paths of files
    HYDRATED_TWEETS_FILENAME = "hydrated_tweets_2020-03-20_2021-02-09.csv"
    PREPROCESSED_TWEETS_FILENAME = "preprocessed_tweets_2020-03-20_2021-02-09.csv"
    LOCAL_HYDRATED_TWEETS_PATH = HYDRATED_TWEETS_PATH + HYDRATED_TWEETS_FILENAME
    LOCAL_PREPROCESSED_TWEETS_PATH = PREPROCESSED_TWEETS_PATH + \
        PREPROCESSED_TWEETS_FILENAME

    AWS_HYDRATED_TWEETS_PATH = AWS_TWEET_DIR + \
        "hydrated_tweets/" + HYDRATED_TWEETS_FILENAME
    AWS_PREPROCESSED_TWEETS_PATH = AWS_TWEET_DIR + \
        "preprocessed_tweets/" + PREPROCESSED_TWEETS_FILENAME

    # load tweets from AWS, use subset of cols
    # for now, can choose to use local version of file, rather than manually load it

    use_local = True
    if use_local:
        tweets_df = pd.read_csv(LOCAL_HYDRATED_TWEETS_PATH)
    else:
        tweets_df = pd.read_csv(AWS_HYDRATED_TWEETS_PATH)

    tweets_df = tweets_df[["user", "created_at", "id",
                           "full_text", "geo", "coordinates",
                           "place", "retweet_count", "favorite_count"]]

    print(f"Parsing {tweets_df.shape[0]} tweets today...")

    # change place col to be read as dict, not str
    tweets_df["place"] = tweets_df["place"].apply(
        lambda x: try_literal_eval(x))

    # initialize lists to hold information
    is_USA_list = []
    country_location_list = []
    state_location_list = []
    dates_list = []
    year_list = []
    month_list = []
    day_list = []
    hour_list = []
    tokenized_text_list = []
    hashtags_list = []
    non_hashtags_list = []
    hashtag_counts_list = []

    # loop through the location column, get location information
    for idx, location_dict in enumerate(tweets_df["place"]):

        try:
            is_USA, country, state = parse_location(location_dict)

            is_USA_list.append(is_USA)
            country_location_list.append(country)
            state_location_list.append(state)
        except Exception as e:
            print("Error in looping through locations column and getting locations")
            print(f"Error happened at index {idx}\n")
            print(f"The location was: {location_dict}\n")
            print(f"The error was: {e}\n")
            if type(location_dict) == int:
                is_USA_list.append("N/A")
                country_location_list.append("N/A")
                state_location_list.append("N/A")
                continue
            else:
                raise ValueError(
                    "Please address error in looping through locations column")

    # loop through the dates column, get date info
    for idx, timestamp in enumerate(tweets_df["created_at"]):

        try:
            date, year, month, day, hour = parse_dates(timestamp)

            dates_list.append(date)
            year_list.append(year)
            month_list.append(month)
            day_list.append(day)
            hour_list.append(hour)
        except Exception as e:
            print("Error in looping through dates column and getting dates")
            print(f"Error happened at index {idx}\n")
            print(f"The timestamp was: {timestamp}\n")
            print(f"The error was: {e}\n")

            dates_list.append("N/A")
            year_list.append("N/A")
            month_list.append("N/A")
            day_list.append("N/A")
            hour_list.append("N/A")

    # loop through the text column, get parsed text
    for idx, text in enumerate(tweets_df["full_text"]):

        try:
            # cleaned, tokenized text
            tokenized_text_arr = clean_text(text)
            tokenized_text_list.append(tokenized_text_arr)

            # get hashtags
            hashtag_arr, non_hashtag_arr = parse_hashtags(text)
            hashtags_list.append(hashtag_arr)
            non_hashtags_list.append(non_hashtag_arr)

            # get hashtag counts
            hashtag_count = count_hashtags(text)
            hashtag_counts_list.append(hashtag_count)

        except Exception as e:
            print("Error in looping through text column and getting parsed text")
            print(f"Error happened at index {idx}\n")
            print(f"The text was: {text}\n")
            print(f"The error was: {e}\n")
            raise ValueError(
                "Please address error in looping through text column")

    # add lists as columns to our df
    tweets_df["is_USA"] = is_USA_list
    tweets_df["country"] = country_location_list
    tweets_df["state"] = state_location_list
    tweets_df["date"] = dates_list
    tweets_df["year"] = year_list
    tweets_df["month"] = month_list
    tweets_df["day"] = day_list
    tweets_df["hour"] = hour_list
    tweets_df["tokenized_text"] = tokenized_text_list
    tweets_df["hashtags_list"] = hashtags_list
    tweets_df["non_hashtags_list"] = non_hashtags_list
    tweets_df["hashtag_count"] = hashtag_counts_list

    # export df as local .csv file
    try:
        tweets_df.to_csv(LOCAL_PREPROCESSED_TWEETS_PATH)
    except Exception as e:
        print("Problem with exporting tweets df as local file")
        print(e)
        raise ValueError(
            "Please address issue with exporting tweets df as local file")

    # export df to AWS bucket
    try:
        # save to AWS
        save_to_AWS(LOCAL_PREPROCESSED_TWEETS_PATH,
                    AWS_PREPROCESSED_TWEETS_PATH,
                    "s3",
                    AWS_BUCKET,
                    AWS_ACCESS,
                    AWS_SECRET)

        # remove local version
        os.remove(LOCAL_PREPROCESSED_TWEETS_PATH)
    except Exception as e:
        print("Error in exporting the local files to AWS")
        print(e)
        print("------------------")
        raise ValueError(
            "Please fix the error in exporting the local files to AWS")
    finally:
        print(
            f"Finished with the execution of 'preprocess_tweets.py' at (in UTC time): {datetime.datetime.utcnow()}")


# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Check Reference Points
# Author: Timm Nawrocki, Alaska Center for Conservation Science
# Created on: 2016-11-12
# Usage: Must be executed as an ArcPy Script.
# Description: This tool creates a csv file comparing a reference field in a point feature class to a field in a raster dataset for the purpose of assessing raster attribute accuracy.
# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy, os, numpy, pandas, xlsxwriter
from arcpy.sa import *

# Set overwrite option
arcpy.env.overwriteOutput = True

# Define reference point feature class
Reference_Points = arcpy.GetParameterAsText(0)

# Define target field from reference points
ReferenceField = arcpy.GetParameterAsText(1)

# Define input raster
Input_Raster = arcpy.GetParameterAsText(2)

# Define target field from raster
RasterField = arcpy.GetParameterAsText(3)

# Define location of a workspace folder
Workspace = arcpy.GetParameterAsText(4)

# Define output csv
Pivot_Table = arcpy.GetParameterAsText(5)

# Define intermediate files for user selected workspace
Reference_Points_Extract = os.path.join(Workspace, "Reference_Points_Extract.shp")
Reference_CSV = os.path.join(Workspace, "Reference.csv")

# Extract values from raster to points
ExtractValuesToPoints(Reference_Points, Input_Raster, Reference_Points_Extract, "NONE", "ALL")

# Add quotes to reference field
ReferenceExpression = "AddQuotes(!" + ReferenceField + "!)"
codeBlock = "def AddQuotes(Field):\\n    QuoteBlock = \"\\\"\" + Field + \"\\\"\"\\n    return QuoteBlock"
arcpy.CalculateField_management(Reference_Points_Extract, ReferenceField, ReferenceExpression, "PYTHON", codeBlock)

# Add quotes to raster field
RasterExpression = "AddQuotes(!" + RasterField + "!)"
arcpy.CalculateField_management(Reference_Points_Extract, RasterField, RasterExpression, "PYTHON", codeBlock)

# Add and calculate a value field
ValueField = "Count"
ValueExpression = 1
arcpy.AddField_management(Reference_Points_Extract, ValueField, "Long")
arcpy.CalculateField_management(Reference_Points_Extract, ValueField, ValueExpression, "PYTHON")

# Export raster field and reference field to csv
Value_Field = "\"" + ReferenceField + ";" + RasterField + ";" + ValueField + "\""
arcpy.ExportXYv_stats(Reference_Points_Extract, Value_Field, "COMMA", Reference_CSV, "ADD_FIELD_NAMES")

# Read output CSV into data frame
dataFrame = pandas.read_csv(Reference_CSV)
dataFrame.head()

# Generate pivot table from data frame
pivotTable = pandas.pivot_table(dataFrame, index=RasterField.upper(), columns=[ReferenceField.upper()], values=ValueField.upper(), aggfunc=numpy.sum, fill_value="")

# Generate an excel file to store pivot table
writer = pandas.ExcelWriter(Pivot_Table, engine='xlsxwriter')
pivotTable.to_excel(writer, sheet_name='ReferenceData')
writer.save()

# Delete intermediate data
arcpy.Delete_management(Reference_Points_Extract)
os.remove(Reference_CSV)
XML = os.path.join(Workspace, "Reference.txt.xml")
if os.path.exists(XML) == True:
    os.remove(XML)


from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='index'),
    path('create_profile/', views.create_profile, name='create_profile'),
    path('profile/', views.profile, name='profile'),
    path('update_profile/<int:id>', views.update_profile, name='update_profile'),
    path('upload/project/', views.upload, name="upload"),
    path('accounts/profile/', views.home, name='profile'),
    path('project/<int:project_id>', views.project, name='project'),
    path('search/', views.search_project, name='search_project'),
    path('rate/<int:id>', views.rate, name='rate'),
    path('api/projects/', views.ProjectList.as_view()),
    path('api/profiles/', views.ProfileList.as_view()),
]


import time
import cv2
import numpy as np
import onnxruntime
from .blazeFaceUtils import gen_anchors, AnchorsOptions
import json
import time
import os

class BlazeFaceDetector:

    def __init__(self, typ = "front", scoreThreshold = 0.7, iouThreshold = 0.3):
        BASE_DIR = os.path.dirname(__file__)
        self.type = typ
        self.scoreThreshold = scoreThreshold
        self.iouThreshold = iouThreshold
        self.sigmoidScoreThreshold = np.log(self.scoreThreshold/(1-self.scoreThreshold))
        self.initModel(typ,BASE_DIR)

        self.generateAnchorBoxes(typ)

    def initModel(self, typ, BASE_DIR):
        """
        Read and initialize the model
        """
        front_model_path = os.path.join(BASE_DIR , "face_detection_front_128x128.onnx")
        back_model_path = os.path.join(BASE_DIR , "face_detection_back_256x256.onnx")
        if typ == "front":
            self.session = onnxruntime.InferenceSession(front_model_path, None)
        elif typ =="back":
            self.session = onnxruntime.InferenceSession(back_model_path, None)

        self.getModelInputDetails()
        self.getModelOutputDetails()

    def detectFaces(self, image, maxFaces = 2):
        """
        This function aims to detect faces in image
        input: [image] a numpy cv2 array (i.e. BGR image)
        returns:
        """
        preprocessed_image = self.detectionPreprocessing(image)
        result = self.inference(preprocessed_image)

        scores, goodDetections = self.filterDetections(result[1])

        faces_locations = self.extractDetections(result[0], goodDetections)
        faces_locations = self.nms(faces_locations, scores, maxFaces)
        return faces_locations

    def __call__(self, image, maxFaces=2):
        return self.detectFaces(image, maxFaces)

    def getModelInputDetails(self):
        """
        This function aims to get inlut node details for onnx inference
        """
        self.input_details = self.session.get_inputs()[0]
        self.input_name = self.input_details.name
        input_shape = self.input_details.shape
        self.inputHeight = input_shape[1]
        self.inputWidth = input_shape[2]
        self.channels = input_shape[3]

    def getModelOutputDetails(self):
        """
        this funtion aims to get the output nodes details (mainly we need the names only) for onnx inference
        """
        self.output_details = self.session.get_outputs()

    def generateAnchorBoxes(self, typ):
        """
        This function aims to generate anchor boxes depends on the type of the model (front model or back model)

        """
        if typ == "front":
		# Options to generate anchors for SSD object detection models.
            anchors_options = AnchorsOptions(input_size_width=128, input_size_height=128, min_scale=0.1484375, max_scale=0.75
                , anchor_offset_x=0.5, anchor_offset_y=0.5, num_layers=4
                , feature_map_width=[], feature_map_height=[]
                , strides=[8, 16, 16, 16], aspect_ratios=[1.0]
                , reduce_boxes_in_lowest_layer=False, interpolated_scale_aspect_ratio=1.0
                , fixed_anchor_size=True)

        elif typ == "back":
            # Options to generate anchors for SSD object detection models.
            anchors_options = AnchorsOptions(input_size_width=256, input_size_height=256, min_scale=0.15625, max_scale=0.75
                    , anchor_offset_x=0.5, anchor_offset_y=0.5, num_layers=4
                    , feature_map_width=[], feature_map_height=[]
                    , strides=[16, 32, 32, 32], aspect_ratios=[1.0]
                    , reduce_boxes_in_lowest_layer=False, interpolated_scale_aspect_ratio=1.0
                    , fixed_anchor_size=True)
        self.anchors = gen_anchors(anchors_options)

    def detectionPreprocessing(self, image):
        """
        This function aims to preproccess the image before feeding it to the onnx model
        input: [image] image loaded with cv2.imread (i.e. BGR image)
        returns: [data] processed image for onnx model feeding
        """
        img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        self.img_height, self.img_width, self.img_channels = img.shape
        # Input values should be from -1 to 1 with a size of 128 x 128 pixels for the fornt model
        # and 256 x 256 pixels for the back model
        img = img / 255.0
        """ img_resized = tf.image.resize(img, [self.inputHeight,self.inputWidth],
                                    method='bicubic', preserve_aspect_ratio=False)
         """
        img_resized = cv2.resize(img, (self.inputHeight,self.inputWidth), interpolation=cv2.INTER_CUBIC)
        img_input = (img_resized - 0.5) / 0.5

        # Adjust matrix dimenstions
        reshape_img = img_input.reshape(1,self.inputHeight,self.inputWidth,self.channels)

        data = reshape_img.astype('float32')

        return data

    def inference(self, data):
        """
        This function takes the data from detectionPreprocessing function and passes it to BlazeFace model using onnx
        input: [data] data we got from detectionPreprocessing which is image as a numpy array
        return: [boxes] bounding boxes (including face landmarks)
                [scores] confidence of each output [boxes]
        """

        result = self.session.run([self.output_details[0].name,self.output_details[1].name,self.output_details[2].name,self.output_details[3].name], {self.input_name: data})

        scores = np.squeeze(np.concatenate((result[0], result[1]), axis = 1), axis =0)
        boxes = np.squeeze(np.concatenate((result[2], result[3]), axis = 1), axis = 0)

        return boxes, scores

    def filterDetections(self, scores):
        """
        This function aims to filter the bounding boxes by there confidence level
        input: [scores] numpy array with shape (num_boxes, 1) holds the confidence level of each box
        returns: numpy array scores after being filtered, and indices of those scores
        """
		# Filter based on the score threshold before applying sigmoid function
        goodDetections = np.where(scores > self.sigmoidScoreThreshold)[0]

		# Convert scores back from sigmoid values
        scores = 1.0 /(1.0 + np.exp(-scores[goodDetections]))

        return scores, goodDetections

    def extractDetections(self, predections, selectedIndices):
        """
        This function aims to extract the outputs from the anchor boxes
        inputs: [predections] numpy array holds the predicted outputs (boxes and keypoints), but we will use here the boxes only shape (num_of_boxes, 16)
                [selectedIndices] numpy array holds the indices of selected boxes
        returns: numpy array of boxes extracted from generated anchors shape (num_of_boxes, 4)
        """

        numGoodDetections = selectedIndices.shape[0]

        boxes = np.zeros((numGoodDetections, 4))
        for idx, detectionIdx in enumerate(selectedIndices):
            anchor = self.anchors[detectionIdx]

            sx = predections[detectionIdx, 0]
            sy = predections[detectionIdx, 1]
            w = predections[detectionIdx, 2]
            h = predections[detectionIdx, 3]

            cx = sx + anchor.x_center * self.inputWidth
            cy = sy + anchor.y_center * self.inputHeight

            cx /= self.inputWidth
            cy /= self.inputHeight
            w /= self.inputWidth
            h /= self.inputHeight

            # The next section is for facial keypoints detected from BlazeFace model
            # commented it for speed concerns

            """ for j in range(KEY_POINT_SIZE):
                lx = output0[detectionIdx, 4 + (2 * j) + 0]
                ly = output0[detectionIdx, 4 + (2 * j) + 1]
                lx += anchor.x_center * self.inputWidth
                ly += anchor.y_center * self.inputHeight
                lx /= self.inputWidth
                ly /= self.inputHeight
                keypoints[idx,j,:] = np.array([lx, ly])
 """
            boxes[idx,:] = np.array([cx - w * 0.5, cy - h * 0.5, cx + w * 0.5, cy + h * 0.5])

        return boxes

    def nms(self, boxes, probs=None, max_num_outputs = 1, iouThreshold=0.3):
        """
        This a fast non max suppression (NMS) implementation
        inputs: [boxes] numpy array conatins bounding boxes in format of [x1, y1, x2, y2] with shape (num_boxes, 4)
                , [probs] numpy array holds the confidence level of each box from 0-1 with shape (num_boxes, 1)
                , [max_num_outputs] an intger holds the maximum number of ouputs needed
                , [iouThrshold] an integer from 0-1 represents the intersection over union threshold
        returns: numpy array of boxes after applying NMS
        """
	# if there are no boxes, return an empty list
        if len(boxes) == 0:
            return []

        # if the bounding boxes are integers, convert them to floats -- this
        # is important since we'll be doing a bunch of divisions
        if boxes.dtype.kind == "i":
            boxes = boxes.astype("float")

        # initialize the list of picked indexes
        pick = []

        # grab the coordinates of the bounding boxes
        x1 = boxes[:, 0]
        y1 = boxes[:, 1]
        x2 = boxes[:, 2]
        y2 = boxes[:, 3]

        # compute the area of the bounding boxes and grab the indexes to sort
        # (in the case that no probabilities are provided, simply sort on the
        # bottom-left y-coordinate)
        area = (x2 - x1 + 1) * (y2 - y1 + 1)
        idxs = y2

        # if probabilities are provided, sort on them instead
        if probs is not None:
            idxs = probs.squeeze()

        # sort the indexes
        idxs = np.argsort(idxs)
        face_counter = 0
        # keep looping while some indexes still remain in the indexes list
        while len(idxs) > 0:
            # grab the last index in the indexes list and add the index value
            # to the list of picked indexes
            if face_counter == max_num_outputs:
                break
            face_counter +=1
            last = len(idxs) - 1
            i = idxs[last]

            pick.append(i)

            # find the largest (x, y) coordinates for the start of the bounding
            # box and the smallest (x, y) coordinates for the end of the bounding
            # box
            xx1 = np.maximum(x1[i], x1[idxs[:last]])
            yy1 = np.maximum(y1[i], y1[idxs[:last]])
            xx2 = np.minimum(x2[i], x2[idxs[:last]])
            yy2 = np.minimum(y2[i], y2[idxs[:last]])

            # compute the width and height of the bounding box
            w = np.maximum(0, xx2 - xx1 + 1)
            h = np.maximum(0, yy2 - yy1 + 1)

            # compute the ratio of overlap
            overlap = (w * h) / area[idxs[:last]]

            # delete all indexes from the index list that have overlap greater
            # than the provided overlap threshold
            idxs = np.delete(idxs, np.concatenate(([last],
                np.where(overlap > iouThreshold)[0])))
        # return only the bounding boxes that were picked

        boxes = boxes[pick]
        boxes[:,0] = self.img_width * boxes[:,0]
        boxes[:,2] = self.img_width * boxes[:,2]
        boxes[:,1] = self.img_height * boxes[:,1]
        boxes[:,3] = self.img_height * boxes[:,3]

        # convert from X1y1x2y2 to xywh
        boxes[:,2] = boxes[:,2] - boxes[:,0]
        boxes[:,3] = boxes[:,3] - boxes[:,1]

        return boxes.astype("int")


from typing import ClassVar

from .customer import _get_next_id

class Equipment:
    name: str
    _counter: ClassVar[int] = 1

    def __init__(self, name: str):
        self.name = name

        self.id = self._counter
        self.__class__._counter += 1

    get_next_id = _get_next_id

    def __repr__(self):
        return f"Equipment <{self.id}> {self.name}"

Customer = dataclass({
    'name': 'str'
}, "Equipment <{self.id}> {self.name}")


def fatorial(num, show=False):
    fat = 1
    for f in range(num, 1, -1):
        fat *= f
        if show is True:
            print(f'{f} x ', end=' ')
    if show is True:
        print(f'= {fat}')
    else:
        print(f'O fatorial de {num} é {fat}')

n = int(input('N° para fatorial: '))
sow = bool(input('Mostrar calculo[True/False]: '))
fatorial(n, sow)


# https://codecombat.com/play/level/cannon-landing-force
# We should send some soldiers to defend the mountain village.
# Also we need clear out old fire traps.
# For both of those goals we'll use the artillery!
# The artillery can launch soldiers and anti-trap shells over the mountains.

# The scout prepared a map of the landing zone.
# The map is 2 dimensional array, where cells are strings.
landingMap = hero.findNearest(hero.findFriends()).landingMap

# The cannons need to know the row, the column, and what's there.
# To get the element in row i and column j, use 'array[i][j]'.
# First, let's look at row 0 and column 0.
cell = landingMap[0][0]
# Next, say the coordinates and what's there.
hero.say("row 0 column 0 " + cell)

# Next cell is the 3rd row and the 2nd column.
hero.say("row 3 column 2 " + landingMap[3][2])

# Now do it yourself for the next point:
# The 2nd row and 1st column.
hero.say("row 2 column 1 " + landingMap[2][1])
# The 1st row and 0th column.
hero.say("row 1 column 0 " + landingMap[1][0])
# The 0th row and 2nd column.
hero.say("row 0 column 2 " + landingMap[0][2])
# The 1st row and 3rd column.
hero.say("row 1 column 3 " + landingMap[1][3])


import pkg_resources
import six

# Use collections on py2, collections.abc on py3
if six.PY2:
    import collections as abc
else:
    from collections import abc

__all__ = ['EntrypointList', 'EntrypointDict', 'eps']

class AttrGroup(object):
    """
    Allows attribute-type access to sub-groups.
    """

    def __init__(self, prefix):
        """
        Initialize an ``AttrGroup`` instance.

        :param str prefix: The group name prefix.  This will be
                           prepended to the group name provided to
                           subordinate ``EntrypointDict`` objects.
        """

        # Save the prefix
        self._prefix = prefix

        # Initialize the attribute cache
        self._attr_cache = {}

    def __getattr__(self, name):
        """
        Get a subordinate ``EntrypointDict`` object.

        :param str name: The name of the subordinate
                         ``EntrypointDict`` object.  This name may not
                         begin with '_', but any other characters,
                         including '.', are permitted.

        :returns: A subordinate ``EntrypointDict`` object.
        :rtype: ``EntrypointDict``

        :raises AttributeError:
            An attempt was made to access an internal attribute.
        """

        # Prohibit internal names
        if name.startswith('_'):
            raise AttributeError(
                "'%s' object has no attribute '%s'" %
                (self.__class__.__name__, name)
            )

        # If '.' is in the name, treat it specially
        if '.' in name:
            parts = name.split('.')
            obj = self
            for part in parts:
                obj = getattr(obj, part)
            return obj

        # Dynamically create an EntrypointDict as needed
        if name not in self._attr_cache:
            self._attr_cache[name] = EntrypointDict(self._prefix + name)

        return self._attr_cache[name]

@six.python_2_unicode_compatible
class EntrypointList(abc.Sequence):
    """
    A lazy list of entrypoints.  This ``list`` class is designed to
    only query as many entrypoints as are necessary to accomplish the
    required task.  For instance, asking for ``obj[0]`` will find and
    return only the first loadable entrypoint, without exploring any
    others, yet a subsequent ``obj[1]`` will load the rest of the
    entrypoints.
    """

    def __init__(self, group, name):
        """
        Initialize an ``EntrypointList`` instance.

        :param str group: The name of the entrypoint group.
        :param str name: The name of the entrypoint itself.
        """

        # Save the entrypoint group and name
        self._group = group
        self._name = name

        # List of all found entrypoints
        self._eps = []

        # Have we found 1?
        self._found = False

        # Have we found all of them?
        self._explored = False

        # Set of EntryPoint object IDs that we can skip
        self._entries = set()

    def __str__(self):
        """
        Return a string representation of this object.

        :returns: A string containing a representation of the object.
        :rtype: ``str``
        """

        return '[%s]' % ', '.join(str(item) for item in self)

    def __repr__(self):
        """
        Return a representation of this object.  This variant ensures that
        no entrypoints are explored.

        :returns: A string containing a representation of the object.
        :rtype: ``str``
        """

        return '<%s.%s object at 0x%x>' % (
            self.__class__.__module__, self.__class__.__name__, id(self)
        )

    def __len__(self):
        """
        Determine the number of entrypoints available.

        :returns: The number of loadable entrypoints.
        :rtype: ``int``
        """

        # Make sure we've fully explored the space
        self._find()

        return len(self._eps)

    def __getitem__(self, idx):
        """
        Obtain the specified entrypoint.

        :param idx: An integer or ``slice`` that specifies the
                    entrypoint or entrypoints to return.

        :returns: The designated entrypoint.

        :raises TypeError:
            The ``idx`` is not an integer or slice.

        :raises IndexError:
            The ``idx`` does not exist.
        """

        # Sanity-check the index value
        if not isinstance(idx, (six.integer_types, slice)):
            raise TypeError('list indices must be integers, not str')

        # If it's identically 0, only look for one entry
        if idx == 0:
            self._find(True)
            return self._eps[idx]  # will raise IndexError if empty

        # OK, have to make sure we have the full space
        self._find()
        return self._eps[idx]

    def __bool__(self):
        """
        Determine if the entrypoint list is empty.

        :returns: A ``False`` value if the entrypoint list is empty,
                  ``True`` otherwise.
        :rtype: ``bool``
        """

        # Only look for 1
        self._find(True)

        return bool(self._eps)

    # Alias for Python 2 functionality
    __nonzero__ = __bool__

    def _find(self, one=False):
        """
        Explore the entrypoint space.  This fills ``self._eps`` with the
        entrypoints that can be loaded.

        :param bool one: If ``True``, exploration stops after the
                         first loadable entrypoint is found.  Defaults
                         to ``False``.
        """

        # If we've found what's required, we're done
        if self._explored or (one and self._found):
            return

        # Look up entrypoints
        for ep in pkg_resources.iter_entry_points(self._group, self._name):
            # Skip entrypoints we know about
            if id(ep) in self._entries:
                continue

            # OK, we don't know about it; mark it so we don't try again
            self._entries.add(id(ep))

            # See if we can load it
            try:
                obj = ep.load()
            except (ImportError, AttributeError, pkg_resources.UnknownExtra):
                continue

            # OK, we can load it
            self._eps.append(obj)
            self._found = True

            # Was that all?
            if one:
                return

        # We've fully explored the entrypoint space
        self._found = True
        self._explored = True

    @property
    def group(self):
        """
        Retrieve the entrypoint group.
        """

        return self._group

    @property
    def name(self):
        """
        Retrieve the name of the entrypoint.
        """

        return self._name

@six.python_2_unicode_compatible
class EntrypointDict(AttrGroup, abc.Mapping):
    """
    A lazy dictionary of entrypoints.  This ``dict`` class is designed
    to only query as many entrypoints as are necessary to accomplish
    the required task.  For instance, asking for ``obj['name']`` will
    find and return only the first loadable entrypoint having the name
    ``'name'``, without exploring any others, yet a ``len(obj)`` will
    explore the entire entrypoint space and return the total number of
    unique entrypoint names within the entrypoint group.
    """

    def __init__(self, group):
        """
        Initialize an ``EntrypointDict`` instance.

        :param str group: The name of the entrypoint group.
        """

        # Save the group name
        self._group = group

        # Cache of the entrypoints we've found
        self._entries = {}

        # Have we explored the whole space?
        self._explored = False

        # Initialize the attribute group
        super(EntrypointDict, self).__init__(group + '.')

    def __str__(self):
        """
        Return a string representation of this object.

        :returns: A string containing a representation of the object.
        :rtype: ``str``
        """

        return '{%s}' % ', '.join('%r: %s' % (k, v)
                                  for k, v in self._entries.items())

    def __repr__(self):
        """
        Return a representation of this object.  This variant ensures that
        no entrypoints are explored.

        :returns: A string containing a representation of the object.
        :rtype: ``str``
        """

        return '<%s.%s object at 0x%x>' % (
            self.__class__.__module__, self.__class__.__name__, id(self)
        )

    def __getitem__(self, key):
        """
        Retrieve an entrypoint.

        :param str key: The name of the entrypoint.

        :returns: The requested entrypoint.

        :raises KeyError:
            The designated entrypoint does not exist.
        """

        # Skip if it's not a string
        if not isinstance(key, six.string_types):
            raise KeyError(key)

        # Look up the entrypoint if we don't have it in the cache
        if key not in self._entries:
            self._entries[key] = EntrypointList(self._group, key)

        # We've looked it up but couldn't find one
        if not self._entries[key]:
            raise KeyError(key)

        # Return the first entrypoint
        return self._entries[key][0]

    def __len__(self):
        """
        Determine the number of entrypoints in this entrypoint group.

        :returns: The number of unique entrypoint names in this
                  entrypoint group.
        :rtype: ``int``
        """

        # Make sure we've explored the entrypoint space
        self._find()

        # Subtract out the empty entries
        return (
            len(self._entries) -
            sum(1 for v in self._entries.values() if not v)
        )

    def __iter__(self):
        """
        Iterate through all the entrypoints in this entrypoint group.

        :returns: An iterator that yields entrypoint names.
        """

        # Make sure we've explored the entrypoint space
        self._find()

        for key, value in self._entries.items():
            # Skip entries that weren't found
            if not value:
                continue

            yield key

    def _find(self):
        """
        Explore the entrypoint space.  This fills ``self._entries`` with
        the entrypoints that can be loaded.  Note that this will
        explore the whole space, and update the entrypoint lists to
        reflect this.
        """

        # If we've already explored the space, we're done
        if self._explored:
            return

        # Iterate through the entrypoints
        encountered = set()
        for ep in pkg_resources.iter_entry_points(self._group):
            # We'll want to set the caching attributes later
            encountered.add(ep.name)

            # Is it an entrypoint we've seen already?
            if (ep.name in self._entries and
                    id(ep) in self._entries[ep.name]._entries):
                continue

            # Mark it so we don't try again
            if ep.name not in self._entries:
                self._entries[ep.name] = EntrypointList(self._group, ep.name)
            self._entries[ep.name]._entries.add(id(ep))

            # See if we can load it
            try:
                obj = ep.load()
            except (ImportError, AttributeError, pkg_resources.UnknownExtra):
                continue

            # OK, we can load it
            self._entries[ep.name]._eps.append(obj)

        # Mark that we've fully explored the entrypoint space
        self._explored = True
        for epname in encountered:
            self._entries[epname]._found = True
            self._entries[epname]._explored = True

    # Alias keys_all() so it exists
    keys_all = __iter__

    def items_all(self):
        """
        Like ``items()``, but returns the full list of entrypoints instead
        of just the first entrypoint.

        :returns: An iterator yielding tuples of the entrypoint name
                  and the list of entrypoints with that name.
        """

        # Make sure we've explored the entrypoint space
        self._find()

        for key, value in self._entries.items():
            # Skip entries that weren't found
            if not value:
                continue

            yield (key, value)

    def values_all(self):
        """
        Like ``values()``, but returns the full list of entrypoints instead
        of just the first entrypoint.

        :returns: An iterator yielding the list of entrypoints with a
                  given name.
        """

        # Make sure we've explored the entrypoint space
        self._find()

        for key, value in self._entries.items():
            # Skip entries that weren't found
            if not value:
                continue

            yield value

    def get_all(self, key, default=None):
        """
        Like ``get()``, but returns the full list of entrypoints instead
        of just the first entrypoint.

        :param str key: The name of the entrypoint.
        :param default: A value to return if no entrypoints with the
                        specified name exist.  Defaults to ``None``.

        :returns: A list of entrypoints, or the specified ``default``.
        :rtype: ``EntrypointList``
        """

        # Skip if it's not a string
        if not isinstance(key, six.string_types):
            return default

        # Look up the entrypoint if we don't have it in the cache
        if key not in self._entries:
            self._entries[key] = EntrypointList(self._group, key)

        # We've looked it up but couldn't find one
        if not self._entries[key]:
            return default

        # Return all the entrypoints
        return self._entries[key]

    @property
    def group(self):
        """
        Retrieve the entrypoint group.
        """

        return self._group

# A place to get all the endpoints
eps = AttrGroup('')


import pandas as pd
def getBooksDF(books):

     ret_df = pd.DataFrame()
     title = list()
     published_date = list()
     publisher = list()
     pages = list()
     recommendation = list()
     column_name = ['title', 'published_date', 'publisher', 'pages',
    'recommendation']

     for book in books:
         title.append(book[0])
         published_date.append(book[1])
         publisher.append(book[2])
         pages.append(book[3])
         recommendation.append(book[4])

     data = {
         'title': title,
         'published_date': published_date,
         'publisher': publisher,
         'pages': pages,
         'recommendation': recommendation
     }

     ret_df = pd.DataFrame(data, columns=column_name)
     return ret_df


import json
from google.cloud.pubsublite.cloudpubsub import PublisherClient
from google.cloud.pubsublite.types import MessageMetadata
from google.cloud import storage
from random import randrange
import time,datetime
bucket_name = "bucket-name"
topic = "your-topic-path"

storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob("events.json")
data = json.loads(blob.download_as_string(client=None))

with PublisherClient() as publisher_client:
    for row in data:
        now = datetime.datetime.now()
        row['event_date']= now.strftime("%Y-%m-%d %H:%M:%S")
        data = json.dumps(row).encode("utf-8")
        api_future = publisher_client.publish(
            topic,
            data=data
        )
        message_id = api_future.result()
        message_metadata = MessageMetadata.decode(message_id)
        print(
            f"Published {data} to partition {message_metadata.partition.value} and offset {message_metadata.cursor.offset}."
        )
        time.sleep(randrange(1,10))


# -*- coding: utf-8 -*-
"""
Created on Tue Oct  2 20:57:32 2018

@author: USER
"""

# coding: utf-8

# In[1]:
from __future__ import division
from itertools import groupby

import pandas as pd
import operator
import matplotlib.pyplot as plt
import matplotlib.cm
import numpy as np

    # In[2]:
def openwindow8():

    data = pd.read_csv("india-districts-census-2011.csv")

    # In[3]:

    data.shape

    # In[4]:

    young=data["Age_Group_0_29"]

    # In[5]:

    young

    # In[6]:

    total_young=young.sum()

    # In[7]:

    total_young

    # In[8]:

    middle=data["Age_Group_30_49"]
    middle

    # In[9]:

    total_middle=middle.sum()
    total_middle

    # In[10]:

    old=data["Age_Group_50"]

    # In[11]:

    old=data["Age_Group_50"]

    # In[12]:

    old

    # In[13]:

    total_old=old.sum()

    # In[14]:

    total_old

    # In[15]:

    populations1=data["Population"]

    # In[16]:

    total_population=populations1.sum()

    # In[17]:

    total_population

    # In[18]:

    young_per=(total_young/total_population)*100

    # In[19]:

    young_per

    # In[20]:

    old_per=(total_old/total_population)*100

    # In[21]:

    old_per

    # In[22]:

    middle_per=(total_middle/total_population)*100

    # In[23]:

    middle_per

    # In[24]:

    age_groups=[young_per,middle_per,old_per]

    # In[25]:

    age_groups

    # In[26]:

    colors=["green","blue","red"]

    # In[27]:

    label=["Age Group 0 to 29","Age group 30 to 49","Age Group above 50"]
    explode=[0,0.1,0.1]

    # In[31]:

    fig, ax = plt.subplots()
    plt.pie(age_groups,colors=colors,explode=explode,autopct='%1.1f%%', shadow=True, startangle=200,labels=label)
    plt.show()
    fig.savefig('age.png')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# @author : YF
# @date : octobre 2022

### Correction de l'exercice 3 sur les listes - trouver le minimum dans une liste

# Déclaration de la liste
MaListe = [9,19,23,8,10,31,2,13]

# fonction qui prend en paramètre une liste et renvoie son minimum
def minimum_liste(liste):
    # au début le minimum est le premier élément de la liste
    min = liste[0]
    # parcours de la liste
    for i in range(len(liste)):
        # on compare chaque élément de la liste à min
        # on remplace min si l'élément de la liste est plus petit
        if (liste[i]) < min:
            min = liste[i]
    return min

# fonction qui prend en paramètre une liste et renvoie son maximum
# même fonctionnement que la fonction précédente
def maximum_liste(liste):
    max = liste[0]
    for i in range(len(liste)):
        if liste[i] > max:
            max = liste[i]
    return max

# main
# on affiche le min et le max de notre liste en utilisant les fonctions précédemment créées
print("Nombre le plus petit dans cette liste : {}".format(minimum_liste(MaListe)))
print("Nombre le plus grand dans cette liste : {}".format(maximum_liste(MaListe)))


'''
Sunday is market day. Early in the morning many people move to the Parangaba square where happens a fair, known to be the largest in the city. At the fair the Parangaba you can find everything.

Every Sunday, Bino make purchases at the fair. He always mark with his friend Cino, they met at the bus terminal of Parangaba at 8 am to go together to buy at the fair. But often Bino wake up too late and is late for the meeting with his friend.

Knowing that Bino takes 30-60 minutes to reach the terminal. Tell the maximum delay Bino.

Input

The input consists of multiple test cases. Each case contains a single line containing a time H (5:00 ≤ H ≤ 9:00) that Bino woken up. The input ends with the final file (EOF).

Output

For each test case, print "Atraso maximo: X" (without quotes), X indicates the maximum delay (in minutes) of Bino in the encounter with Cino.

Input Sample	Output Sample
7:10
5:00
                Atraso maximo: 10
                Atraso maximo: 0
'''
def minuto(n):
    tempo = 60 * n
    return tempo

while True:
    try:
        h = input()
        data = h.split(sep=":")
        n = int(data[0])
        m = int(data[1])
        tempo = minuto(n)

        valor = tempo+m+60
        horario = minuto(8)
        if horario>valor:
            print("Atraso maximo: 0")
        else:
            horario = horario - valor
            print("Atraso maximo: %d" % abs(horario))

    except EOFError:
        break


""" kalman.py

    Contains the iterative kalman filter. But in multiple dimensions :0
"""

import csv
import numpy as np
import matplotlib.pyplot as plt
import time

class Kalman():
    ''' Implementation of the Kalman Filter. Multi dimensional :-)

        Arguments:
            var_p: process noise variance, equal for each acceleration axis
            var_m: measurement uncertainty, equal for each acceleration axis
            var_s: initial state uncertainty, equal each for acceleration axis

        This specific implementation has the state of the system be a nine dimensional vector, x, xdot, xdoubledot, ... , z, zdot, zdoubledot
        i.e., where the first entry is position x, the second entry is x component of velocity, the third entry is the x component of acceleration, and
        the repeat for y and z. The measurements it uses to estimate of the system is accelerometer data (a_x, a_y, a_z).
    '''

    # Initialize
    def __init__(self, var_p, var_m, var_s):
        self.var_p = var_p
        self.var_m = var_m
        self.var_s = var_s

        self.R = np.array([[var_m**2, 0, 0], [0, var_m**2, 0], [0, 0, var_m**2]]) # measurement uncertainty

        # Initial states
        self.x_hat = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0])
        self.x_hatminus = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0])

        # Initial Kalman gain
        self.K = np.zeros((9, 9))

        # Initial size of dataset
        self.sz = 0

        # Initial covariances
        self.Pminus = np.zeros((9, 9))
        self.P = np.zeros((9, 9))

        # Set diagonal entries of covariance to var_s
        for i in range(9):
            self.P[i, i] = var_s

        # transformation matrix from state to measured, i.e.   z = H @ x, where x is a vector of the stae of the matrix
        self.H = np.array([[0, 0, 1, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 1, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 1]])

    # Method to update step
    def update_state(self, z, dt):
        ''' z in this case is acceleration data
        '''
        # Process noise variance
        self.Q = self.var_p * np.array([[dt**4/4, dt**3/2, dt**2/2, 0, 0, 0, 0, 0, 0],
                           [dt**3/2, dt**2, dt, 0, 0, 0, 0, 0, 0],
                           [dt**2/2, dt, 1, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, dt**4/4, dt**3/2, dt**2/2, 0, 0, 0],
                           [0, 0, 0, dt**3/2, dt**2, dt, 0, 0, 0],
                           [0, 0, 0, dt**2/2, dt, 1, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, dt**4/4, dt**3/2, dt**2/2],
                           [0, 0, 0, 0, 0, 0, dt**3/2, dt**2, dt],
                           [0, 0, 0, 0, 0, 0, dt**2/2, dt, 1]])

        # State transition
        self.F = np.array([[1, dt, dt**2/2, 0, 0, 0, 0, 0, 0],
                           [0, 1, dt, 0, 0, 0, 0, 0, 0],
                           [0, 0, 1, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 1, dt, dt**2/2, 0, 0, 0],
                           [0, 0, 0, 0, 1, dt, 0, 0, 0],
                           [0, 0, 0, 0, 0, 1, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, 1, dt, dt**2/2],
                           [0, 0, 0, 0, 0, 0, 0, 1, dt],
                           [0, 0, 0, 0, 0, 0, 0, 0, 1]])

        # Extrapolate state
        self.x_hatminus = self.F@self.x_hat

        # Extrapolate uncertainty
        self.Pminus = self.F@self.P@np.transpose(self.F) + self.Q

        # Calculate Kalman gain
        self.K = self.Pminus@np.transpose(self.H)@ np.linalg.inv((self.H@self.Pminus@np.transpose(self.H)+self.R))

        # Correct estimation using measurement
        self.x_hat = self.x_hatminus + self.K@(np.array(z) - self.H@self.x_hatminus)

        # Update estimate uncertainty
        self.P = (np.identity(9) - self.K@self.H)@self.Pminus@np.transpose((np.identity(9)-self.K@self.H)) + self.K@self.R@np.transpose(self.K)

        self.sz += 1

    # Return prediction
    def current_state(self):
        return self.x_hat

    # Initialize to generic state
    def initialize_state(self, x):
        self.x_hat = x

# Abstraction of kalman filter to a midflight filter
class MidflightFilter():
    def __init__(self, state_init, var_p, var_m, var_s):
        self.kfilter = Kalman(var_p, var_m, var_s)
        self.kfilter.initialize_state(state_init)
        self.timestamp = time.time()

    def process_data(self, state, data, dt):
        ''' Data  in this case is a np array, where first element is a_x, second is a_y, and third
        is a_z

        State is nine dimensional array of the n-1 state of the system
        '''

        self.kfilter.update_state(data, dt)
        x = self.kfilter.current_state()
        return x

class ExtendedKalman():
    ''' In this specific implementation of the EKF, the state vector is (x, vx, ax, y, vy, ay, z, vz, az, u, v, w), where
    u, v, and w are the Euler angles describing the vehicle's orientation with respect to a space reference frame
    '''
    def __init__(self, var_p, var_m_a, var_m_g, var_s):
        self.var_p = var_p
        self.var_m_a = var_m_a
        self.var_s = var_s
        self.var_m_g = var_m_g

        self.R = np.array([[var_m_a**2, 0, 0],
                           [0, var_m_a**2, 0],
                           [0, 0, var_m_a**2]]) # measurement uncertainty

        # Initial states
        self.x_hat = np.zeros(12)
        self.x_hatminus = np.zeros(12)

        # Initial Kalman gain
        self.K = np.zeros((12, 12))

        # Initial size of dataset
        self.sz = 0

        # Initial covariances
        self.Pminus = np.zeros((12, 12))
        self.P = np.zeros((12, 12))

        # Set diagonal entries of covariance to var_s
        for i in range(12):
            self.P[i, i] = var_s

        # Initialize observation Jacobian
        self.J_h = self.get_H_j()

    def Ffunc(self, state, gyro, dt):
        ''' The transformation function

        x_k = Ffunc(x_k-1, u_k)

        where in this case x_k-1 is state and u_k is gyro
        '''

        # Find changes in Euler angles using gyroscope
        du = gyro[0]*dt
        dv = gyro[1]*dt
        dw = gyro[2]*dt

        c = lambda x: np.cos(x)
        s = lambda x: np.sin(x)

        x_k = np.zeros(12)

        x_0 = state[0]
        v_x0 = state[1]
        a_x0 = state[2]
        y_0 = state[3]
        v_y0 = state[4]
        a_y0 = state[5]
        z_0 = state[6]
        v_z0 = state[7]
        a_z0 = state[8]

        u = state[9]
        v = state[10]
        w = state[11]

        x_k[0] = x_0 + v_x0*dt + a_x0* dt**2 / 2    # x = x_0 + v_x*dt + a_x*dt^2 / 2
        x_k[1] = c(dw)*c(dv)*v_x0 + ( c(dw)*s(dv)*s(du) - s(dw)*c(du) )*v_y0 + ( c(dw)*s(dv)*c(du) + s(dw)*s(du) )*v_z0 + a_x0*dt
        x_k[2] = c(dw)*c(dv)*a_x0 + ( c(dw)*s(dv)*s(du) - s(dw)*c(du) )*a_y0 + ( c(dw)*s(dv)*c(du) + s(dw)*s(du) )*a_z0

        x_k[3] = y_0 + v_y0*dt + a_y0* dt**2 / 2
        x_k[4] = s(dw)*c(dv)*v_x0 + ( s(dw)*s(dv)*s(du) + c(dw)*c(du) )*v_y0 + ( s(dw)*s(dv)*c(du) - c(dw)*s(du) )*v_z0 + a_y0*dt
        x_k[5] = s(dw)*c(dv)*a_x0 + ( s(dw)*s(dv)*s(du) + c(dw)*c(du) )*a_y0 + ( s(dw)*s(dv)*c(du) - c(dw)*s(du) )*a_z0

        x_k[6] = z_0 + v_z0*dt + a_z0* dt**2 / 2
        x_k[7] = -s(dv)*v_x0 + ( c(dv)*s(du) )*v_y0 + ( c(dv)*c(du) )*v_z0 + a_z0*dt
        x_k[8] = -s(dv)*a_x0 + ( c(dv)*s(du) )*a_y0 + ( c(dv)*c(du) )*a_z0

        x_k[9] = u + du
        x_k[10] = v + dv
        x_k[11] = w + dw

        return x_k

    def get_H_f(self, gyro, dt):
        ''' Get the Jacobian approximating the transformation function J_f
        '''

        c = lambda x: np.cos(x)
        s = lambda x: np.sin(x)

        du = gyro[0]*dt
        dv = gyro[1]*dt
        dw = gyro[2]*dt

        J_f = np.array([[1, dt, dt**2/2, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                       [0, c(dw)*c(dv), dt, 0, c(dw)*s(dv)*s(du) - s(dw)*c(du), 0, 0, c(dw)*s(dv)*c(du) + s(dw)*s(du), 0, 0, 0, 0],
                       [0, 0, c(dw)*c(dv), 0, 0, c(dw)*s(dv)*s(du) - s(dw)*c(du), 0, 0, c(dw)*s(dv)*c(du) + s(dw)*s(du), 0, 0, 0],
                       [0, 0, 0, 1, dt, dt**2/2, 0, 0, 0, 0, 0, 0],
                       [0, s(dw)*c(dv), 0, 0, s(dw)*s(dv)*s(du) + c(dw)*c(du), dt, 0, s(dw)*s(dv)*c(du) - c(dw)*s(du), 0, 0, 0, 0],
                       [0, 0, s(dw)*c(dv), 0, 0, s(dw)*s(dv)*s(du) + c(dw)*c(du), 0, 0, s(dw)*s(dv)*c(du) - c(dw)*s(du), 0, 0, 0],
                       [0, 0, 0, 0, 0, 0, 1, dt, dt**2/2, 0, 0, 0],
                       [0, -s(dv), 0, 0, c(dv)*s(du), 0, 0, c(dv)*c(du), dt, 0, 0, 0],
                       [0, 0, -s(dv), 0, 0, c(dv)*s(du), 0, 0, c(dv)*c(du), 0, 0, 0],
                       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
                       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=float)

        return J_f

    def hfunc(self, state):
        ''' The observation function

        z = h(x_)

        where z is the measurement vector and x_ is the state of the system vector
        '''

        z = np.zeros(3)

        c = lambda x: np.cos(x)
        s = lambda x: np.sin(x)

        ax_s = state[2]
        ay_s = state[5]
        az_s = state[8]

        u = state[9]
        v = state[10]
        w = state[11]

        z[0] = c(w)*c(v)*ax_s + ( c(w)*s(v)*s(u) - s(w)*c(u) )*ay_s + ( c(w)*s(v)*c(u) + s(w)*s(u) )*az_s
        z[1] = s(w)*c(v)*ax_s + ( s(w)*s(v)*s(u) + c(w)*c(u) )*ay_s + ( s(w)*s(v)*c(u) - c(w)*s(u) )*az_s
        z[2] = -s(v)*ax_s + ( c(v)*s(u) )*ay_s + ( c(v)*c(u) )*az_s

        return z

    def get_H_j(self):
        ''' Get the Jacobian of the observation function

        u: roll
        v: pitch
        w: yaw
        Sweet-faced ones with nothing left inside

        J is the Jacobian where the rows span over the measurement variables

        ax
        ay
        az
        u
        v
        w

        and the columns span over the entries of state vector. I.e., the 0, 0 entry is
        (d/dx)*(ax)
        the 0, 11 entry is
        (d/dw)*(ax)
        and the 11, 11 entry is
        (d/dw)*(w)
        Does this make sense? My brain is gloop. To be good about, here is the h transformation function.

        ax = c(u)*c(v)*xddot
        '''

        # Turn negative is ax, ay, az are the acceleration in the body frame, while the acceleration in the
        # state vector is acceleration in the space frame
        u = self.x_hatminus[9]
        v = self.x_hatminus[10]
        w = self.x_hatminus[11]

        # Get acceleration in space reference frame
        ax_s = self.x_hatminus[2]
        ay_s = self.x_hatminus[5]
        az_s = self.x_hatminus[8]

        c = lambda x: np.cos(x)
        s = lambda x: np.sin(x)

        # Calculate Jacobian components with respect to u, v, and w separately for readibility?. OMG have i actually finished?
        ax_u = s(u)*( ay_s * s(w) - az_s * s(v) * c(w)) + c(u)*( ay_s * s(v) * c(w) + az_s * s(w) )
        ax_v = c(w)*( ay_s*s(u)*c(v) + az_s*c(u)*c(v) - ax_s*s(v) )
        ax_w = -s(w)*( ay_s*s(u)*s(v) + ax_s*c(v)) - c(u)*(az_s*s(v)*s(w) + ay_s*c(w)) + az_s*s(u)*c(w)

        ay_u = c(u)*( ay_s*s(v)*s(w) - az_s*c(w)) - s(u)*( az_s*s(v)*s(w) + ay_s*c(w) )
        ay_v = s(w)*( ay_s*s(u)*c(v) + az_s*c(u)*c(v) - ax_s*s(v))
        ay_w = c(u)*( az_s*s(v)*c(w) - ay_s*s(w) ) + s(u)*( ay_s*s(v)*c(w) + az_s*s(w) ) + ax_s*c(v)*c(w)

        az_u = c(v)*( ay_s*c(u) - az_s*s(u))
        az_v = -s(v)*( ay_s*s(u) + az_s*c(u)) - ax_s*c(v)
        az_w = 0

        J = np.array([[0, 0, c(w)*c(v), 0, 0, c(w)*s(v)*s(u) - s(w)*c(u), 0, 0, c(w)*s(v)*c(u) + s(w)*s(u), ax_u, ax_v, ax_w],
                      [0, 0, s(w)*c(v), 0, 0, s(w)*s(v)*s(u) + c(w)*c(u), 0, 0, s(w)*s(v)*c(u) - c(w)*s(u), ay_u, ay_v, ay_w],
                      [0, 0, -s(v), 0, 0, c(v)*s(u), 0, 0, c(v)*c(u), az_u, az_v, az_w]])

        return J

    # Correct for gravity
    def correct_z(self, z):
        c = lambda x: np.cos(x)
        s = lambda x: np.sin(x)

        g = 9.8

        u = -self.x_hatminus[9]
        v = -self.x_hatminus[10]
        w = -self.x_hatminus[11]

        ax_s = z[0]
        ay_s = z[1]
        az_s = z[2]

        z_new = np.zeros(3)

        z_new[0] = c(w)*c(v)*ax_s + ( c(w)*s(v)*s(u) - s(w)*c(u) )*ay_s + ( c(w)*s(v)*c(u) + s(w)*s(u) )*az_s
        z_new[1] = s(w)*c(v)*ax_s + ( s(w)*s(v)*s(u) + c(w)*c(u) )*ay_s + ( s(w)*s(v)*c(u) - c(w)*s(u) )*az_s
        z_new[2] = -s(v)*ax_s + ( c(v)*s(u) )*ay_s + ( c(v)*c(u) )*az_s - g

        z_corr = np.zeros(3)

        ax_s = z_new[0]
        ay_s = z_new[1]
        az_s = z_new[2]

        u *= -1
        v *= -1
        w *= -1

        z_corr[0] = c(w)*c(v)*ax_s + ( c(w)*s(v)*s(u) - s(w)*c(u) )*ay_s + ( c(w)*s(v)*c(u) + s(w)*s(u) )*az_s
        z_corr[1] = s(w)*c(v)*ax_s + ( s(w)*s(v)*s(u) + c(w)*c(u) )*ay_s + ( s(w)*s(v)*c(u) - c(w)*s(u) )*az_s
        z_corr[2] = -s(v)*ax_s + ( c(v)*s(u) )*ay_s + ( c(v)*c(u) )*az_s

        return z_corr

    # Method to update step
    def update_state(self, z, gyro, dt):
        ''' z in this case is acceleration data and gyro is (du/dt, dv/dt, and dw/dt), i.e. the readings from the
        gyroscope
        '''
        # Process noise variance
        self.Q = self.var_p * np.array([[dt**4/4, dt**3/2, dt**2/2, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [dt**3/2, dt**2, dt, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [dt**2/2, dt, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, dt**4/4, dt**3/2, dt**2/2, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, dt**3/2, dt**2, dt, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, dt**2/2, dt, 1, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, dt**4/4, dt**3/2, dt**2/2, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, dt**3/2, dt**2, dt, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, dt**2/2, dt, 1, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 1*self.var_m_g, 0, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1*self.var_m_g, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1*self.var_m_g]])

        # Extrapolate next state
        self.x_hatminus = self.Ffunc(self.x_hat, gyro, dt)

        # Get J_f matrix
        self.F = self.get_H_f(gyro, dt)

        # Extrapolate uncertainty
        self.Pminus = self.F@self.P@np.transpose(self.F) + self.Q

        # Recalculate Jacobian
        self.J_h = self.get_H_j()

        # Calculate Kalman gain
        self.K = self.Pminus@ np.transpose(self.J_h) @ np.linalg.inv(self.J_h @ self.Pminus @ np.transpose(self.J_h) + self.R)

        # Correct z for gravity
        z = self.correct_z(z)

        # Correct estimation using measurement
        print(f'Observation trans: {self.hfunc(self.x_hatminus)}')
        print(f'Corrected z: {z}')
        self.x_hat = self.x_hatminus + self.K@(np.array(z) - self.hfunc(self.x_hatminus))

        # Update estimate uncertainty
        self.P = (np.identity(12) - self.K@self.J_h)@self.Pminus

        self.sz += 1

    # Return prediction
    def current_state(self):
        return self.x_hat

    # Initialize to generic state
    def initialize_state(self, x):
        self.x_hat = x

# A test case
if (__name__ == "__main__"):

    ##################################
    #   Extended Test Case           #
    ##################################

    pf_filter = ExtendedKalman(1e-4, 5.0, 3.0, 10)
    pf_filter.initialize_state([0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    x_estimate_states = []
    y_estimate_states = []
    z_estimate_states = []
    true_states= []
    times = []
    t = 0

    for i in range(600):
        w_rate = 1.0

        z = np.array([0.0, 0, 1]) + (np.random.rand(1) - np.random.rand(1))*np.random.rand(3)/6
        z = z*9.8
        gyro = np.array([0, 0, w_rate]) #+  (np.pi/180.0)*(np.random.rand(1) - np.random.rand(1))*np.random.rand(3)/8
        dt = 0.2

        pf_filter.update_state(z, gyro, dt)
        state = pf_filter.current_state()

        print(f'Measured z: {z}')
        print(f'Measured gyro: {gyro}')
        print(state)
        x_estimate_states.append(state[0])
        y_estimate_states.append(state[3])
        z_estimate_states.append(state[6])

        times.append(t)

        t += dt

    print(f'Time: {t}')

    # convert to np arrays
    x_estimate_states = np.array(x_estimate_states)
    y_estimate_states = np.array(y_estimate_states)
    z_estimate_states = np.array(z_estimate_states)

    times = np.array(times)

    # Plotting
    figure1 = plt.figure()
    ax = plt.axes(projection='3d')
    ax.plot3D(x_estimate_states, y_estimate_states, z_estimate_states, label="Filtered Measurements")
    ax.axes.set_xlim3d(-5, 5)
    ax.axes.set_ylim3d(-5, 5)
    ax.axes.set_zlim3d(-2, 5)

    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()

    plt.show()


import _thread
import cv2
#import cv2.cv as cv
import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
from tensorflow.contrib.layers import flatten
import skimage.data
import skimage.transform
import pandas as pd

sign_names = pd.read_csv("signnames.csv")

#path = "/home/pi/traffic-lenet5/new-img/"
path = "D:/luanvan/roadsign_classifier_Lenet5/new_img/img1"

#traffic_sign = cv2.CascadeClassifier('traffic_cascade.xml')

def load_data(data_dir):
	images = []
	file_names = [os.path.join(data_dir,f)for f in os.listdir(data_dir) if f.endswith(".jpg")]
	for f in file_names:
		images.append(skimage.data.imread(f))
	return images

images = load_data(path)

#images = np.asarray(images)

saver = tf.train.import_meta_graph("lenet/EdLeNet_Color_Norm_5x5_Dropout_0.40.chkpt.meta")

graph = tf.get_default_graph()
for op in graph.get_operations():
    print(op.name)
x = graph.get_tensor_by_name("EdLeNet_Color_Norm_5x5_Dropout_0.40/x:0")
y = graph.get_tensor_by_name("EdLeNet_Color_Norm_5x5_Dropout_0.40/y:0")
prediction = graph.get_tensor_by_name("EdLeNet_Color_Norm_5x5_Dropout_0.40/pre:0")
dropout_placeholder_conv = graph.get_tensor_by_name("EdLeNet_Color_Norm_5x5_Dropout_0.40/drop_conv:0")
dropout_placeholder_fc = graph.get_tensor_by_name("EdLeNet_Color_Norm_5x5_Dropout_0.40/drop_fc:0")
#prediction = graph.get_tensor_by_name("prediction:0")

with tf.Session() as sess:
	saver.restore(sess,tf.train.latest_checkpoint("lenet/./"))
	#x = graph.get_tensor_by_name("x:0")
	#prediction = graph.get_tensor_by_name("prediction:0")
	for i,img in enumerate(images):
		img = skimage.transform.resize(img,(32,32,3), mode = 'constant')
		pred = sess.run(prediction,feed_dict = {x: np.array([img]),dropout_placeholder_conv: 1.0,dropout_placeholder_fc: 1.0 })
		plt.subplot(6,3,i+1)
		plt.subplots_adjust(hspace=0.3)
		plt.axis("off")
		plt.title("Prediction: " +str(sign_names["SignName"][pred[0]]))
		plt.imshow(img)
	plt.show()

'''

font = cv2.FONT_HERSHEY_SIMPLEX
cap = cv2.VideoCapture(0)
#cap.set(cv.CV_CAP_PROP_FRAME_WIDTH,640);
#cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT,480);
def transform_image(frame):
    return skimage.transform.resize(frame,(32,32),mode = "constant")
while (True):
    ret,frame = cap.read()

    #signs = traffic_sign.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in signs:
        print("Ddddddddxxdfxdfxdfxdf")
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    #frame = np.asarray(frame)
	#print(frame)
    img = _thread.start_new_thread(transform_image,(frame,))
    print ("xxx:" )
    print(img)
    #img = skimage.transform.resize(frame,(32,32),mode="constant")
    with tf.Session() as sess:
        saver.restore(sess,tf.train.latest_checkpoint("lenet/./"))
        pred = sess.run(prediction, feed_dict={x: np.array([img]), dropout_placeholder_conv: 1.0,
											   dropout_placeholder_fc: 1.0})

    cv2.putText(frame,str(sign_names["SignName"][pred[0]]),(100,100) ,font, 2 ,(0,0,255), 3 )
    cv2.imshow ("traffic",frame)
    if cv2.waitKey(1) == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()

'''


import math

def find_longest_common_postfix(str1, str2):
    i = 1
    while i <= min(len(str1), len(str2)):
        if str1[-i] == str2[-i]:
            i += 1
        else:
            break
    return i - 1

def max_similarity(str0, start, end):
    new_str = 'x' + str0
    max_length = 0
    for i in range(end, start, -1):
        for j in range(i - 1, start - 1, -1):
            temp = find_longest_common_postfix(new_str[:i+1], new_str[:j+1])
            if temp > max_length:
                max_length = temp
        if max_length == i - 1:
            break
    return max_length

times = int(input().split(' ')[1])
raw_str = input()
arr = []
for i in range(times):
    period = input().split(' ')
    arr.append(max_similarity(raw_str, int(period[0]), int(period[1])))
for i in range(times):
    print(arr[i])


import torch
import importlib
import yaml
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
from pytorch_lightning import Trainer
from torch.nn.utils.rnn import pad_sequence
from schedulers import *
from .module import Model

class DownstreamSystem(pl.LightningModule):
    def __init__(self, args, training_config, **kwargs):
        super(DownstreamSystem, self).__init__()
        self.args = args
        self.training_config = training_config
        self.accumulated_step = training_config['trainer_config']['accumulate_grad_batches']
        self.logging_step = training_config['trainer_config']['log_every_n_steps']
        self.optimizer_config = training_config['optimizer']
        self.modelrc = training_config['modelrc']

        if training_config.get("scheduler", None):
            self.scheduler_config = training_config['scheduler']
        else:
            self.scheduler_config = None

        self.upstream = self.get_upstream(args)
        self.downstream = self.get_downstream(self.modelrc)
        self.objective_loss = eval(f"nn.{self.modelrc['loss_function']}")()
        self.save_hyperparameters()

    def get_upstream(self, args):
        with open(args.model_config,"r") as f:
           model_config = yaml.safe_load(f)
        with open(args.upstream_training_config, "r") as f:
           upstream_config = yaml.safe_load(f)

        upstream_config['datarc']['input']['config_path'] = "/".join(args.upstream_training_config.split("/")[:-1]) + "/" + "input_config.yaml"
        upstream_config['datarc']['target'][0]['config_path'] = "/".join(args.upstream_training_config.split("/")[:-1]) + "/" + "target_config.yaml"

        module_path = f'upstream.{args.upstream}'
        system = importlib.import_module(module_path +'.system')
        PretrainedSystem = system.PretrainedSystem.load_from_checkpoint(args.ckpt, args={}, model_config=model_config, training_config=upstream_config)
        return PretrainedSystem

    def get_downstream(self, modelrc):
        input_dim = self.upstream.get_output_dim()
        modelrc['input_dim'] = input_dim
        modelrc.update(modelrc[modelrc['model_select']])
        return eval(modelrc['model_select'])(**modelrc)

    def forward(self, batch):
        wav, label = batch
        rep, feat_input ,_ = self.upstream.forward(wav)
        length = [len(feat) for feat in feat_input]
        predict = self.downstream(rep, length)
        return predict

    def training_step(self, batch, batch_idx):
        wav, label = batch
        rep, feat_input ,_ = self.upstream.forward(wav)
        length = [len(feat) for feat in feat_input]
        predict = self.downstream(rep, length)
        loss = self.objective_loss(predict,torch.LongTensor(label).to(self.device))
        if (batch_idx+1) % self.accumulated_step == 0:
            if (self.global_step+1) % self.logging_step == 0:
                self.log("train_loss", loss, on_step=True)
                self.print(f"global_step={self.global_step+1}, loss = {loss}")

        return loss

    def validation_step(self, batch, batch_idx):
        wav, label = batch
        rep, feat_input ,_ = self.upstream.forward(wav)
        length = [len(feat) for feat in feat_input]
        predict = self.downstream(rep, length)

        predicted_classid = predict.max(dim=-1).indices
        loss = self.objective_loss(predict,torch.LongTensor(label).to(predict.device))

        return {'val_loss': loss, 'val_pred': predicted_classid, "val_label": torch.LongTensor(label).to(predict.device)}

    def validation_epoch_end(self, validation_step_outputs):
        predicts = []
        labels = []
        total_loss = 0
        for out in validation_step_outputs:
           predicts.extend(out['val_pred'])
           labels.extend(out['val_label'])
           total_loss += out['val_loss'].item()
        total_loss /= len(validation_step_outputs)
        predicts = torch.IntTensor(predicts)
        labels = torch.IntTensor(labels)
        accuracy = torch.sum((predicts == labels).view(-1)) / len(predicts)

        metrics = {'val_acc': accuracy, 'val_total_loss': total_loss}
        self.log('val_acc', accuracy)
        self.log('val_total_loss', total_loss)
        self.log_dict(metrics)
        self.print(f'Validation Accuracy is {accuracy:.2f} ..')
        self.print(f'Validation Loss is {total_loss:.5f} ..')

    def test_step(self, batch, batch_idx):
        wav, label = batch
        rep, feat_input ,_ = self.upstream.forward(wav)
        length = [len(feat) for feat in feat_input]
        predict = self.downstream(rep, length)
        predicted_classid = predict.max(dim=-1).indices
        loss = self.objective_loss(predict,torch.LongTensor(label).to(self.device))
        return {'test_loss': loss, 'test_pred': predicted_classid, "test_label": label}

    def test_epoch_end(self, test_step_outputs):
        predicts = []
        labels = []
        total_loss = 0
        for out in validation_step_outputs:
           predicts.extend(out['pred'])
           labels.extend(out['label'])
           total_loss += out['loss'].item()
        total_loss /= len(validation_step_outputs)
        predicts = torch.IntTensor(predicts)
        labels = torch.IntTensor(labels)
        accuracy = torch.sum((predicts == labels).view(-1)) / len(predicts)

        metrics = {'test_acc': accuracy, 'test_total_loss':total_loss}
        self.log('test_acc', accuracy)
        self.log('test_total_loss', total_loss)
        self.log_dict(metrics)
        self.print(f'Test Accuracy is {accuracy:.2f} ..')
        self.print(f'Test Loss is {total_loss:.5f} ..')

    def get_progress_bar_dict(self):
        # don't show the version number
        items = super().get_progress_bar_dict()
        items.pop("v_num", None)
        return items

    def configure_optimizers(self):

        no_decay = ["LayerNorm", "bias"]

        downstream_model_decay_parameters = [
            p for n, p in self.downstream.named_parameters() if not any(nd in n for nd in no_decay)]
        downstream_model_nodecay_parameters = [
            p for n, p in self.downstream.named_parameters() if any(nd in n for nd in no_decay)]

        all_decay_parameters = downstream_model_decay_parameters
        all_nodecay_parameters = downstream_model_nodecay_parameters

        if self.args.finetune:
            pretrained_model_decay_parameters = [
                p for n, p in self.pretrained_model.named_parameters() if not any(nd in n for nd in no_decay)]
            pretrained_model_nodecay_parameters = [
                p for n, p in self.pretrained_model.named_parameters() if any(nd in n for nd in no_decay)]
            all_decay_parameters += pretrained_model_decay_parameters
            all_nodecay_parameters += pretrained_model_nodecay_parameters

        if not self.optimizer_config.get('weight_decay', None):
            self.optimizer_config['weight_decay'] = 0.01

        all_parameters = [
            {
                "params": all_decay_parameters,
                "weight_decay": self.optimizer_config['weight_decay'],
            },
            {
                "params": all_nodecay_parameters,
                "weight_decay": 0.0
            },
        ]

        optimizer_config = copy.deepcopy(self.optimizer_config)
        optimizer = eval(f"torch.optim.{optimizer_config.pop('name')}")(
            params=all_parameters, **optimizer_config)

        if self.scheduler_config:
            scheduler_config = copy.deepcopy(self.scheduler_config)
            scheduler = eval(f"get_{scheduler_config.pop('name')}")(
                optimizer=optimizer, **scheduler_config, num_training_steps=len(self.train_dataloader())*self.training_config['trainer_config']['max_epochs'])
            return [optimizer], [scheduler]
        else:
            return [optimizer]


import pytest
#
import sys
sys.path.append("..")
from ps1 import SystemDriveFinder

from Level6.db1connect import FileSearcher

class Test_Drive:
    def test_DriveCase(self):
        obj=SystemDriveFinder()
        self.expected=obj.find_drives()
        self.actual='C'
        assert self.expected==self.actual

    def test_searchfile(self):
        obj=FileSearcher()
        d=obj.task2('C:\\','one.txt')
        print(d)
        self.expected_filename=d
        self.actual_res='C:\\capstone\\one.txt'
        assert self.expected_filename==self.actual_res


def search(self, nums: List[int], target: int) -> int:

    s, e = 0, len(nums) - 1
    while s <= e < len(nums):
        m = (s + e) // 2
        if nums[m] == target:
            return m
        elif nums[m] >= nums[s]:
            if target >= nums[s] and target < nums[m]:
                e = m - 1
            else:
                s = m + 1
        else:
            if target <= nums[e] and target > nums[m]:
                s = m + 1
            else:
                e = m - 1
    return -1

"""
Now there could be two situations:
\\start<mid<small<end
     - If the target is located in the non-rotated subarray:
  go left: `end = mid - 1`.

  - Otherwise: go right: `start = mid + 1`.

\\start<small<mid<end
      - If the target is located in the non-rotated subarray:
  go right: `start = mid + 1`.

  - Otherwise: go left: `end = mid - 1`.

"""


from __future__ import print_function
import re, os, sys, multiprocessing, zipfile
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from urlparse import urlparse
import networkx as nx
#https://pypi.python.org/pypi/etaprogress/
from etaprogress.progress import ProgressBar

#337304 total HTML files, some are actually NOT in either the training or testing set
#process_zips = ["./data/0.zip", "./data/1.zip", "./data/2.zip", "./data/3.zip", "./data/4.zip"]
process_zips = ["./data/0.zip"]

def parseFile(contents, filename, sponsored):
	header = [sponsored, filename]
	urls = []

	#use lxml parser for faster speed
	cleaned = BeautifulSoup(contents, "lxml")
	for anchor in cleaned.findAll('a', href=True):
		if anchor['href'].startswith("http"):
			try:
				parsedurl = urlparse(anchor['href'])
				parsedurl = parsedurl.netloc.replace("www.", "", 1)
				parsedurl = re.sub('[^0-9a-zA-Z\.]+', '', parsedurl) #remove non-alphanumeric and non-period literals
				urls.append(parsedurl)
			except ValueError:
				print("IPv6 URL?")
	#remove duplicate URLS (this will change the order)
	urls = list(set(urls))
	return header + urls #combine to single list

def addNodes(nodes):
	G.add_node(nodes[1]) #filename
	if nodes[0] == 1:
		G.add_edge("Sponsored", nodes[1])
	elif nodes[0] == 0:
		G.add_edge("NotSponsored", nodes[1])
	else:
		G.add_edge("Testing", nodes[1])
	for n in nodes[2:]:
		if n not in G:
			G.add_node(n)
		G.add_edge(nodes[1], n)

train = pd.read_csv("./data/train.csv", header=0, delimiter=",", quoting=3)
sample = pd.read_csv("./data/sampleSubmission.csv", header=0, delimiter=",", quoting=3)

print("Starting processing...")

G = nx.DiGraph()
G.add_node("Sponsored")
G.add_node("NotSponsored")
G.add_node("Testing")

for i, zipFile in enumerate(process_zips):
	archive = zipfile.ZipFile(zipFile, 'r')
	file_paths = zipfile.ZipFile.namelist(archive)
	bar = ProgressBar(len(file_paths), max_width=40)
	pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()-1 or 1)
	for k, file_path in enumerate(file_paths):
		data = archive.read(file_path)
		openfile = file_path[2:] #filename
		sponsored = train.loc[train['file'] == openfile]
		res = None
		if not sponsored.empty:
			res = pool.apply_async(parseFile, args = (data, openfile, int(sponsored['sponsored']), ), callback = addNodes)
		testing = sample.loc[sample['file'] == openfile]
		if not testing.empty:
			res = pool.apply_async(parseFile, args = (data, openfile, 2, ), callback = addNodes)

		if res is not None and len(pool._cache) > 1000:
			print("Waiting for cache to clear...")
			res.wait()
		bar.numerator = k
		print("Folder:", i, bar, end='\r')
		sys.stdout.flush()
	pool.close()
	pool.join()

print()

print(nx.info(G))


def analyze_starcraft():
    # Detect automation or macro usage by analyzing player APM and unit production
    query_automation = (g.V()
                        .hasLabel('player')
                        .has('apm', gt(500)))  # Set a threshold for suspiciously high APM

    # Detect match-fixing or collusion by analyzing in-game communication and player interactions
    query_match_fixing = (g.V()
                          .hasLabel('player')
                          .where(__.out('interacted_with')
                                 .has('interaction_type', 'suspicious')))  # Define criteria for suspicious interactions

    # Execute the queries and get the results
    automation_results = query_automation.toList()
    match_fixing_results = query_match_fixing.toList()


import sys
import copy

def knapsack(values, number_items, knapsack_size):
    a = [[0 for _ in range(knapsack_size + 1)] for _ in range(number_items)]

    for i in range(number_items):
        for x in range(knapsack_size + 1):
            value = values[i][0]
            weight = values[i][1]
            if weight > x:
                a[i][x] = a[i-1][x]
            else:
                a[i][x] = max(a[i-1][x], a[i-1][x - weight] + value)

    return a[number_items-1][knapsack_size]

def knapsack_fast(values, number_items, knapsack_size):
    a = [0 for _ in range(knapsack_size + 1)]
    b = [0 for _ in range(knapsack_size + 1)]
    for i in range(number_items):
        weight = values[i][1]
        b[:weight] = a[:weight]

        for x in range(weight, knapsack_size + 1):
            value = values[i][0]
            not_added = a[x]
            added = a[x - weight] + value
            if added > not_added:
                b[x] = added
        a = copy.copy(b)

    return a[-1]

def main():
    data = sys.stdin.read()
    data_set = data.split()
    values = []
    info = list(map(int, data_set[0].split()))
    number_items = info[1]
    knapsack_size = info[0]
    for values in data_set[1:]:
        int_values = list(map(int, values.split()))
        values.append(int_values)

    print("knapsack:", knapsack(values, number_items, knapsack_size))
    print("knapsack fast:", knapsack_fast(values, number_items, knapsack_size))

if __name__ == '__main__':
    main()


"""
ConditionalLRGAN
----------------
Implements the conditional variant of the latent regressor GAN well described in the BicycleGAN paper[1].

It introduces an encoder network which maps the generator output back to the latent
input space. This should help to prevent mode collapse and improve image variety.

Losses:
    - Generator: Binary cross-entropy + L1-latent-loss (Mean Absolute Error)
    - Discriminator: Binary cross-entropy
    - Encoder: L1-latent-loss (Mean Absolute Error)
Default optimizer:
    - torch.optim.Adam
Custom parameter:
    - lambda_z: Weight for the reconstruction loss for the latent z dimensions.

References
----------
.. [1] https://arxiv.org/pdf/1711.11586.pdf
"""

import torch

from vegans.models.unconditional.LRGAN import LRGAN
from vegans.utils.networks import Generator, Adversary, Encoder
from vegans.models.conditional.AbstractConditionalGANGAE import AbstractConditionalGANGAE

class ConditionalLRGAN(AbstractConditionalGANGAE, LRGAN):
    """
    Parameters
    ----------
    generator: nn.Module
        Generator architecture. Produces output in the real space.
    adversary: nn.Module
        Adversary architecture. Produces predictions for real and fake samples to differentiate them.
    encoder: nn.Module
        Encoder architecture. Produces predictions in the latent space.
    x_dim : list, tuple
        Number of the output dimensions of the generator and input dimension of the discriminator / critic.
        In the case of images this will be [nr_channels, nr_height_pixels, nr_width_pixels].
    z_dim : int, list, tuple
        Number of the latent dimensions for the generator input. Might have dimensions of an image.
    y_dim : int, list, tuple
        Number of dimensions for the target label. Might have dimensions of image for image to image translation, i.e.
        [nr_channels, nr_height_pixels, nr_width_pixels] or an integer representing a number of classes.
    optim : dict or torch.optim
        Optimizer used for each network. Could be either an optimizer from torch.optim or a dictionary with network
        name keys and torch.optim as value, i.e. {"Generator": torch.optim.Adam}.
    optim_kwargs : dict
        Optimizer keyword arguments used for each network. Must be a dictionary with network
        name keys and dictionary with keyword arguments as value, i.e. {"Generator": {"lr": 0.0001}}.
    lambda_z: float
        Weight for the reconstruction loss for the latent z dimensions.
    adv_type: "Discriminator", "Critic" or "Autoencoder"
        Indicating which adversarial architecture will be used.
    feature_layer : torch.nn.*
        Output layer used to compute the feature loss. Should be from either the discriminator or critic.
        If `feature_layer` is not None, the original generator loss is replaced by a feature loss, introduced
        [here](https://arxiv.org/abs/1606.03498v1).
    fixed_noise_size : int
        Number of images shown when logging. The fixed noise is used to produce the images in the folder/images
        subdirectory, the tensorboard images tab and the samples in get_training_results().
    device : string
        Device used while training the model. Either "cpu" or "cuda".
    ngpu : int
        Number of gpus used during training if device == "cuda".
    folder : string
        Creates a folder in the current working directory with this name. All relevant files like summary, images, models and
        tensorboard output are written there. Existing folders are never overwritten or deleted. If a folder with the same name
        already exists a time stamp is appended to make it unique.
    """

    #########################################################################
    # Actions before training
    #########################################################################
    def __init__(
            self,
            generator,
            adversary,
            encoder,
            x_dim,
            z_dim,
            y_dim,
            optim=None,
            optim_kwargs=None,
            lambda_z=10,
            adv_type="Discriminator",
            feature_layer=None,
            fixed_noise_size=32,
            device=None,
            ngpu=0,
            folder="./veganModels/cLRGAN",
            secure=True):

        super().__init__(
            generator=generator, adversary=adversary, encoder=encoder,
            x_dim=x_dim, z_dim=z_dim, y_dim=y_dim, optim=optim, optim_kwargs=optim_kwargs, adv_type=adv_type,
            feature_layer=feature_layer, fixed_noise_size=fixed_noise_size, device=device, folder=folder, ngpu=ngpu, secure=secure
        )
        self.lambda_z = lambda_z
        self.hyperparameters["lambda_z"] = lambda_z

        if self.secure:
            assert (self.encoder.output_size == self.z_dim), (
                "Encoder output shape must be equal to z_dim. {} vs. {}.".format(self.encoder.output_size, self.z_dim)
            )

    #########################################################################
    # Actions during training
    #########################################################################
    def _calculate_generator_loss(self, X_batch, Z_batch, y_batch):
        fake_images = self.generate(y=y_batch, z=Z_batch)
        fake_concat = self.concatenate(fake_images, y_batch)
        real_concat = self.concatenate(X_batch, y_batch)
        return LRGAN._calculate_generator_loss(self, X_batch=real_concat, Z_batch=Z_batch, fake_images=fake_concat)

    def _calculate_encoder_loss(self, X_batch, Z_batch, y_batch):
        fake_images = self.generate(y=y_batch, z=Z_batch).detach()
        fake_concat = self.concatenate(fake_images, y_batch)
        return LRGAN._calculate_encoder_loss(self, X_batch=None, Z_batch=Z_batch, fake_images=fake_concat)

    def _calculate_adversary_loss(self, X_batch, Z_batch, y_batch):
        fake_images = self.generate(y=y_batch, z=Z_batch).detach()
        fake_concat = self.concatenate(fake_images, y_batch)
        real_concat = self.concatenate(X_batch, y_batch)
        return LRGAN._calculate_adversary_loss(self, X_batch=real_concat, Z_batch=Z_batch, fake_images=fake_concat)


#Importing the reader

import csv
import os

#setting up lists

Votes = []
county = []
candidate = []

#Open csv file and split it to three lists.
with open(r'C:\Users\Nick\Documents\School\Python-Challenge\PyPoll\Resources\election_data.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    next(reader)
    for rows in reader:
        candidate.append(rows[2])
        Votes.append(rows[0])
        county.append(rows[1])

 #Counting the votes
Kahn = candidate.count("Khan")

Li = candidate.count("Li")

Correy = candidate.count("Correy")

Otooley = candidate.count("O'Tooley")

total_votes = len(Votes)

#Counting the percentages of votes for each candidate
Percentage_of_vote_Kahn = round((Kahn/total_votes)*100,2)

Percentage_of_vote_Li = round((Li/total_votes)*100,2)

Percentage_of_vote_Correy = round((Correy/total_votes)*100,2)

Percentage_of_vote_Otooley = round((Otooley/total_votes)*100,2)

Total_vote_list = [Percentage_of_vote_Li,Percentage_of_vote_Correy,Percentage_of_vote_Kahn,Percentage_of_vote_Otooley]

#Finding who won.
if Kahn > Li and Kahn > Correy  and Kahn > Otooley:
    Winner= "Kahn"

elif  Li > Kahn and Li > Correy and Li > Otooley:
    Winner= "Li"

elif  Correy > Kahn and Correy > Li and Correy > Otooley:
    Winner= "Correy"

elif  Otooley > Kahn and Otooley > Correy and Otooley > Li:
    Winner= "O'tooley"

#Printing all the values to the terminal.
print ("Total Votes: " + str(total_votes))

print ('Kahn: ' + str(Percentage_of_vote_Kahn) + '%' + ' (' + str(Kahn) + ')')

print ('Correy: ' + str(Percentage_of_vote_Correy) + '%' + ' (' + str(Correy) + ')')

print ('Li: ' + str(Percentage_of_vote_Li) + '%' + ' (' + str(Li) + ')')

print ("O'tooley: " + str(Percentage_of_vote_Otooley) + '%' + ' (' + str(Otooley) + ')')

print ("Winner: " + Winner)

 #Creating txt file with the finished data.
Export = r'C:\Users\Nick\Documents\School\Python-Challenge\PyPoll\Analysis\Analysis.txt'
Analysis_txt = open(Export,"w", newline="")
Analysis_txt.write(f"PyPoll\n")
Analysis_txt.write(f"--------------------------\n")
Analysis_txt.write(f"Total Votes: " + str(total_votes) + "\n")
Analysis_txt.write(f"--------------------------\n")
Analysis_txt.write(f"Khan:" + str(Percentage_of_vote_Kahn) + "%" + " (" + str(Kahn) + ")" "\n")
Analysis_txt.write(f"Correy:" + str(Percentage_of_vote_Correy) + "%" + " (" + str(Correy) + ")" "\n")
Analysis_txt.write(f"Li:" + str(Percentage_of_vote_Li) + "%" + " (" + str(Li) + ")" "\n")
Analysis_txt.write(f"O'tooley:" + str(Percentage_of_vote_Otooley) + "%" + " (" + str(Otooley) + ")" "\n")
Analysis_txt.write(f"--------------------------\n")
Analysis_txt.write(f"Winner: " +Winner + "\n")
Analysis_txt.write(f"--------------------------\n")