import urllib3
import json, requests
from functionality import Functionality
import tkinter as tk
from tkinter import *
from urllib.request import urlopen, Request
import io
from PIL import Image, ImageTk
from tkinter import messagebox, filedialog, font

class ImageToShow:
    def __init__(self):
        self.image = None
        self.imageIconPath = 'icons/ok_image.png'

image_to_show = ImageToShow()

class MainGui():
    def __init__(self, root):
        self.root = root
        root.title('Recepie application')

        root.geometry("450x400")
        myFont = font.Font(size=30)
        Grid.columnconfigure(root, 0, weight=1)
        Grid.columnconfigure(root, 1, weight=1, minsize=200)
        ##################################
        self.dietLebel = Label(root, text="Your recepie")
        self.dietLebel['font'] = myFont
        self.dietLebel.grid(column=0, row=0, sticky="e", padx=(5, 0), pady=(0, 10))

        self.imgOk = PhotoImage(file=r'icons/ok-icon.png')
        self.labelWithImage = Label(root, image=self.imgOk)
        self.labelWithImage.grid(column=1, row=0, sticky="w", padx=(0, 5), pady=(0, 10))

        self.dietLebel = Label(root, text="Choose your diet:")
        self.dietLebel.grid(column=0, row=1, sticky="w", padx=(5, 0))

        self.clickedDiet = StringVar()
        self.clickedDiet.set("none")
        self.dietChoose = OptionMenu(root, self.clickedDiet, "none", "paleo", "vegetarian", "katogenic", "vegan",
                                     "pescetarian",
                                     "primal").grid(row=2, column=0, columnspan=2, padx=5, sticky='we')

        self.cusineLabel = Label(root, text="Choose cuisine:")
        self.cusineLabel.grid(column=0, row=3, sticky="w", padx=(5, 0))
        self.clickedCuisine = StringVar()
        self.clickedCuisine.set("none")
        self.cuisineChoose = OptionMenu(root, self.clickedCuisine, "none", "chinese", "greek", "irish", "thai",
                                        "british",
                                        "mexican").grid(row=4,
                                                        column=0,
                                                        columnspan=2,
                                                        sticky='we', padx=5)
        self.intoleranceLabel = Label(root, text="Intolerances:")
        self.intoleranceLabel.grid(row=5, column=0, sticky="w", padx=(5, 0))

        self.ifNuts = StringVar()
        self.ifEggs = StringVar()
        self.ifGluten = StringVar()
        self.ifDairy = StringVar()
        self.ifGrain = StringVar()
        self.ifSeafood = StringVar()
        self.checkbox1 = Checkbutton(root, text="Nuts", variable=self.ifNuts, onvalue=",+nuts", offvalue="")
        self.checkbox1.grid(row=6, column=0, sticky="w", padx=(5, 0))

        self.checkbox2 = Checkbutton(root, text="Egg", variable=self.ifEggs, onvalue=",+egg", offvalue="")
        self.checkbox2.grid(row=7, column=0, sticky="w", padx=(5, 0))

        self.checkbox3 = Checkbutton(root, text="Gluten", variable=self.ifGluten, onvalue=",+gluten", offvalue="")
        self.checkbox3.grid(row=6, column=1, sticky="w")

        self.checkbox4 = Checkbutton(root, text="Dairy", variable=self.ifDairy, onvalue=",+dairy", offvalue="")
        self.checkbox4.grid(row=7, column=1, sticky="w")

        self.checkbox5 = Checkbutton(root, text="Grain", variable=self.ifGrain, onvalue=",+grain", offvalue="")
        self.checkbox5.grid(row=8, column=0, sticky="w", padx=(5, 0))

        self.checkbox6 = Checkbutton(root, text="Seafood", variable=self.ifSeafood, onvalue=",+seafood", offvalue="")
        self.checkbox6.grid(row=8, column=1, sticky="w")

        self.timeLabel = Label(root, text="Max time of cooking (in minutes):")
        self.timeLabel.grid(column=0, row=9, sticky="w", padx=(5, 0))
        self.timeEntry = Entry(root)
        self.timeEntry.grid(column=1, row=9, sticky="we", padx=(0, 5))

        self.foodLabel = Label(root, text="What would you like to eat?:")
        self.foodLabel.grid(column=0, row=10, sticky="w", padx=(5, 0))
        self.foodEntry = Entry(root)
        self.foodEntry.grid(column=1, row=10, sticky="we", padx=(0, 5))

        self.numberLabel = Label(root, text="How many recepies?:")
        self.numberLabel.grid(column=0, row=11, sticky="w", padx=(5, 0))
        self.numberEntry = Entry(root)
        self.numberEntry.grid(column=1, row=11, sticky="we", padx=(0, 5))

        def processData():
            functionality = Functionality()

            intolerances = self.ifNuts.get() + self.ifEggs.get() + self.ifGluten.get() + self.ifDairy.get() + self.ifGrain.get() + self.ifSeafood.get()

            if self.clickedDiet.get() == 'none':
                diet = ''
            else:
                diet = self.clickedDiet.get()
            if self.clickedCuisine.get() == 'none':
                cuisine = ''
            else:
                cuisine = self.clickedCuisine.get()
            intolerance = intolerances
            time = self.timeEntry.get()
            food = self.foodEntry.get()
            number = self.numberEntry.get()

            functionality.chooseDiet(diet)
            functionality.chooseCuisine(cuisine)
            functionality.searchByIntolerance(intolerance)
            functionality.searchMaxCookingTime(time)
            functionality.howManyRecepies(number)
            functionality.serchWhatToEat(food)
            resultBox = functionality.getRecepieList()

            if not resultBox:
                messagebox.showinfo("Sorry", "Sorry we do not have this kind of recepies, try different combination")

            else:
                windowList = tk.Toplevel()
                windowList.geometry("400x300")

                frameTitle = Frame(windowList, width=400, height=50)
                frameTitle.pack()
                ######################
                myFont = font.Font(size=20)

                foundRecepiesLabel = Label(frameTitle, text="Found recepies:")
                foundRecepiesLabel['font'] = myFont
                foundRecepiesLabel.grid(column=0, row=0, columnspan=2, sticky="we", padx=(5, 0), pady=(0, 5))

                ############################
                frameListBox = Frame(windowList, width=400, height=0)

                scrollbar = Scrollbar(frameListBox, orient="vertical")

                listBox = Listbox(frameListBox, yscrollcommand=scrollbar.set)
                scrollbar.pack(side=RIGHT, fill=Y)
                frameListBox.pack()
                listBox.pack()
                #############################
                # listBox=Listbox(windowList)
                # listBox.pack()

                dictListRowId = []
                max_len = 0
                for elem in functionality.getRecepieListDict():
                    for idElem, titleElem in elem.items():
                        listBox.insert(END, idElem)
                        index = listBox.get(0, END).index(idElem)
                        dictListRowId.append({str(index): (str(idElem), titleElem)})
                        if len(idElem) > max_len:
                            max_len = len(idElem)

                listBox.configure(width=max_len)
                scrollbar.config(command=listBox.yview)

                def getIdSelectedItem():
                    name = listBox.get(listBox.curselection())
                    id_item = None
                    for elem in dictListRowId:
                        for elementList, value in elem.items():
                            if value[0] == name:
                                id_item = value[1]
                    openRecepieWindow(id_item)

                frameButtons=Frame(windowList)
                frameButtons.pack()
                buttonGoToRecepie = Button(frameButtons, text="select", command=getIdSelectedItem)
                buttonGoToRecepie.grid(column=0, row=0)
                buttonHelpList= Button(frameButtons, text="help", command=openHelpForListBox)
                buttonHelpList.grid(column=1, row=0)

                label = Label(windowList, text='')
                label.pack()

        buttonShowRecepies = Button(root, text="get recepies", command=processData)
        buttonShowRecepies.grid(column=1, row=12, sticky="we", padx=(0, 5), pady=(2, 0))

        buttonSavedRecepies = Button(root, text="get saved recepies", command=showRecepiesSaved)
        buttonSavedRecepies.grid(column=0, row=12, sticky="we", padx=(5, 0), pady=(2, 0))

        buttonHelp = Button(root, text="help", command=openHelp)
        buttonHelp.grid(column=1, row=13, padx=(0, 5), sticky="we", pady=(2, 0))

def showRecepiesSaved():
    functionality=Functionality()
    windowSaved=tk.Toplevel()
    windowSaved.geometry('400x300')

    frameTitle = Frame(windowSaved, width=400, height=50)
    frameTitle.pack()
    ######################
    myFont = font.Font(size=20)

    savedLebel = Label(frameTitle, text="Your saved recepies:")
    savedLebel['font'] = myFont
    savedLebel.grid(column=0, row=0, columnspan=2,sticky="we", padx=(5, 5), pady=(0, 10))

    ######################
    frameListBox=Frame(windowSaved, width=400, height=0)

    scrollbar = Scrollbar(frameListBox, orient="vertical")

    listBox = Listbox(frameListBox, yscrollcommand = scrollbar.set)
    scrollbar.pack(side=RIGHT, fill=Y)
    frameListBox.pack()
    listBox.pack()

    dictListRowId = []
    max_len=0
    for elem in functionality.getSavedList():
        for idElem, titleElem in elem.items():
            listBox.insert(END, idElem)
            index = listBox.get(0, END).index(idElem)
            dictListRowId.append({str(index): (str(idElem), titleElem)})
            if len(idElem)>max_len:
                max_len=len(idElem)

    listBox.configure(width=max_len)
    scrollbar.config(command=listBox.yview)

    def getIdSelectedItem():
        name = listBox.get(listBox.curselection())
        id_item = None
        for elem in dictListRowId:
            for elementList, value in elem.items():
                if value[0] == name:
                    id_item = value[1]
        openRecepieWindow(id_item)

    frameForInformation=Frame(windowSaved)
    frameForInformation.pack()

    buttonChose = Button(frameForInformation, text="select", command=getIdSelectedItem)
    buttonChose.grid(column=2, row=0, sticky='we')

    buttonHelp = Button(frameForInformation, text="help", command=openHelpForSavedWindow)
    buttonHelp.grid(column=3, row=0, sticky='we')

    labelInfo=Label(frameForInformation, text="Get the name of recepie : ")
    labelInfo.grid(column=0, row=1)

    recepieWanted = StringVar()
    labelRecepie = Label(frameForInformation, textvariable=recepieWanted).grid(column=0, row=2, columnspan=4)

    def guickLabelUpdate():
        recepieWanted.set(functionality.getTheQuickestSavedRecepie())
    def healthyLabelUpdate():
        recepieWanted.set(functionality.getTheHealthiestSavedRecepie())
    def lastLabelUpdate():
        recepieWanted.set(functionality.getLastSaved())

    buttonTime=Button(frameForInformation, text="the quickest", command=guickLabelUpdate).grid(column=1, row=1)
    buttonHealty=Button(frameForInformation, text="the healthiest", command=healthyLabelUpdate).grid(column=2, row=1)
    buttonLast=Button(frameForInformation, text="the last added", command=lastLabelUpdate).grid(column=3, row=1)

    windowSaved.mainloop()

def openNutritionRecepie(id):
    nutritionWindow = tk.Toplevel()

    myFont = font.Font(size=30)
    labelTitleNutrition = Label(nutritionWindow, text="Nutrition")
    labelTitleNutrition['font'] = myFont
    labelTitleNutrition.grid(row=0, column=0, sticky='we', padx=10)

    functionality = Functionality()
    nutritientsTuple = functionality.getRecepieNutritionDictById(id)  # tuple(bad, good)  do tupli kuła jak do listy[1]
    bad = nutritientsTuple[0]
    listOfBad = []
    for everyDict in bad:
        listOfBad.append(
            everyDict['title'] + ": " + str(everyDict['amount']) + ", daily percent need: " + str(
                everyDict['percentOfDailyNeeds']) + "%")
    good = nutritientsTuple[1]
    for everyDict in good:
        listOfBad.append(
            everyDict['title'] + ": " + str(everyDict['amount']) + ", daily percent need: " + str(
                everyDict['percentOfDailyNeeds']) + "%")
    separator = '\n'
    ingredients = separator.join(listOfBad)
    ingredientsLabel = Label(nutritionWindow, text=ingredients)
    ingredientsLabel.grid(column=0, row=1, sticky="we", padx=10)
    nutritionWindow.title("Nutrition")
    nutritionWindow.mainloop()

def openSummaryRecepie(id):
    summaryWindow = tk.Toplevel()
    functionality = Functionality()

    titleLabel = Label(summaryWindow, text="Summary:")
    titleLabel.config(font=("Courier", 30))
    titleLabel.pack(padx=5, pady=5)

    listSummary = functionality.getRecepieDictSummaryById(id)
    listSummaryToPrint = listSummary.replace("<b>", " ").replace("</b>", " ")
    newString = re.sub('<[^>]+>', '', listSummaryToPrint)
    summaryLabel = Label(summaryWindow, text=newString, wraplength=400)
    summaryLabel.pack(fill=BOTH, expand=1, padx=15, pady=(0, 15))
    summaryWindow.title("Summary")
    summaryWindow.mainloop()

def openHelp():
    winowHelp = tk.Toplevel()
    titleLabel = Label(winowHelp, text="Help")
    titleLabel.config(font=15)
    titleLabel.grid(column=0, row=0, padx=5, pady=5, sticky='w')

    firstParagraphLabel = Label(winowHelp, text=" This app is made to find the best recepie for you.")
    firstParagraphLabel.grid(row=1, column=0, padx=5, pady=10, sticky='w')

    secondParagraphLabel = Label(winowHelp,
                                 text="In first window you can choose your diet, cuisine, intolerances, maximum time of prepering dish, how many recepies you want and kind of food you want",
                                 wraplength=400)
    secondParagraphLabel.grid(row=2, column=0, padx=5, pady=10, sticky='w')

    firstInputLabel = Label(winowHelp,
                            text="If you want to choose diet, click on drop-down list under the words 'Choose your diet', you will see list of available diets. If you do not want any diet leave 'none'",
                            wraplength=400)
    firstInputLabel.grid(row=3, column=0, padx=5, pady=10, sticky='w')

    secondInputLabel = Label(winowHelp,
                             text="If you want to choose cuisine, click on drop-down list under the words 'Choose cuisine', you will see kind of available diets. If you do not want any diet leave 'none'",
                             wraplength=400)
    secondInputLabel.grid(row=3, column=0, padx=5, pady=10, sticky='w')

    thirdInputLabel = Label(winowHelp,
                            text="If you have any food intolerances, select them by clicking. Recepies will not include any of them",
                            wraplength=400)
    thirdInputLabel.grid(row=4, column=0, padx=5, pady=10, sticky='w')

    fourthInputLabel = Label(winowHelp,
                             text="If you want to set time of cooking fill the box next to word 'max time of cooking'",
                             wraplength=400)
    fourthInputLabel.grid(row=5, column=0, padx=5, pady=10, sticky='w')

    fifthInputLabel = Label(winowHelp,
                            text="If you know what would you like to eat you can write it in next box for example: chicken, soup",
                            wraplength=400)
    fifthInputLabel.grid(row=6, column=0, padx=5, pady=10, sticky='w')

    sixthInputLabel = Label(winowHelp,
                            text="You can set how many recepis you want in last input",
                            wraplength=400)
    sixthInputLabel.grid(row=7, column=0, padx=5, pady=10, sticky='w')

    informationLabel = Label(winowHelp,
                             text="IMPORTANT!\nThis app has limited list of recepies if your search is too complex the list might be shortened or will not appear, try to change your preferences then",
                             wraplength=400)
    informationLabel.grid(row=8, column=0, padx=5, pady=10, sticky='w')

def openHelpForListBox():
    winowHelp = tk.Toplevel()
    titleLabel = Label(winowHelp, text="Help")
    titleLabel.config(font=15)
    titleLabel.grid(column=0, row=0, padx=5, pady=5, sticky='w')

    whatToDoLabel = Label(winowHelp,
                          text="This window has your every recepie according to your preferences. If you want to open recepie, click on which you want and click button 'select'",
                          wraplength=250)
    whatToDoLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')

def openHelpForRecepieWindow():
    winowHelp = tk.Toplevel()
    titleLabel = Label(winowHelp, text="Help")
    titleLabel.config(font=15)
    titleLabel.grid(column=0, row=0, padx=5, pady=5, sticky='w')

    whatToDoLabel = Label(winowHelp,
                          text="In this window you see a recepie, you can save it by clicking on 'save recepie', then you can see it by clicking in first window in button 'get saved recepies'.\n If you click nutrition you will see window with nutrition for this recepie. By clicking in summary you will see summary of this recepie.",
                          wraplength=250)
    whatToDoLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')

def openHelpForSavedWindow():
    winowHelp = tk.Toplevel()
    titleLabel = Label(winowHelp, text="Help")
    titleLabel.config(font=15)
    titleLabel.grid(column=0, row=0, padx=5, pady=5, sticky='w')

    whatToDoLabel = Label(winowHelp,
                          text="This window has your every saved recepie. If you want to open recepie, click on which you want and click button 'select'",
                          wraplength=400)
    whatToDoLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')

    informationLabel = Label(winowHelp,
                             text="Next buttons are made to show you the title of your saved the quickest or the healtiest or last saved recepie. The title of recepie will occure right under the buttons"
                             , wraplength=400)
    informationLabel.grid(column=0, row=2, padx=5, pady=5, sticky='w')

def openRecepieWindow(id):
    windowRecepie = tk.Toplevel()
    functionality = Functionality()

    Grid.columnconfigure(windowRecepie, 0, weight=1)
    Grid.columnconfigure(windowRecepie, 1, weight=1)
    frameLeft = Frame(windowRecepie)
    frameLeft.grid(row=2, column=0)

    title = Label(frameLeft, text=functionality.getRecepieTitleById(id),  wraplength=300)
    title.config(font=( 15))
    title.grid(column=0, row=0, padx=(10, 5), pady=5, sticky='we')

    titleLabelFrameLeft = Label(frameLeft, text="Ingredients:", wraplength=300)
    titleLabelFrameLeft.config(font= 12)
    titleLabelFrameLeft.grid(column=0, row=1, padx=(10,5), pady=5, sticky='we')
    #
    frameRight = Frame(windowRecepie)
    frameRight.grid(row=2, column=1, padx=(10,5), pady=5)

    list = functionality.getRecepieIngredientsById(id)

    separator = '\n'
    ingredients = separator.join(list)
    ingredientsLabel = Label(frameLeft, text=ingredients, wraplength=300)
    ingredientsLabel.grid(column=0, row=2, padx=5, pady=5, sticky='w')

    frameBottom = Frame(windowRecepie, width=450, height=200)
    frameBottom.grid(row=3, column=0, columnspan=2)
    titleLabelFrameBottom = Label(frameBottom, text="Instructions:")
    titleLabelFrameBottom.config(font=12)
    titleLabelFrameBottom.grid(column=0, columnspan=2, row=0, padx=10, pady=(5, 15), sticky='we')

    listSummary = functionality.getRecepieStepsAnalyzedById(id)
    separator = ''
    steps = separator.join(listSummary)
    instructionsLabel = Label(frameBottom, text=steps, wraplength=500)
    instructionsLabel.grid(column=0, columnspan=2, row=1, padx=5, pady=5, stick='we')

    ####################

    imageRecepie = functionality.getRecepieImageAdresById(id)
    displayImages(imageRecepie, frameRight, 200, 200)

    ####################

    def saveAndInform(id):
        messagebox.showinfo("Information", "New record saved")
        functionality.saveToNormalFile(id)

    toolbar = Frame(windowRecepie, bd=1, relief=RAISED)
    toolbar.config(bg="beige")

    buttonSaveQuestion = Button(toolbar, text="Summary",
                                command=lambda: openSummaryRecepie(id))  # , command=lambda: openSummaryRecepie(id)
    buttonSaveQuestion.pack(side=tk.LEFT, padx=2, pady=2)
    buttonManageQuestions = Button(toolbar, text="Nutrition", command=lambda: openNutritionRecepie(
        id))  # , command=lambda: openNutritionRecepie(id)
    buttonManageQuestions.pack(side=tk.LEFT, padx=2, pady=2)
    buttonShowQuestions = Button(toolbar, text="Save Recepie", command=lambda: saveAndInform(id))
    buttonShowQuestions.pack(side=tk.LEFT, padx=2, pady=2)
    buttonHelp=Button(toolbar, text="help", command=openHelpForRecepieWindow)
    buttonHelp.pack(side=tk.LEFT, padx=2, pady=2)
    buttonExit = Button(toolbar, text="Exit application", command=windowRecepie.quit)
    buttonExit.pack(side=tk.LEFT, padx=2, pady=2)

    toolbar.grid(column=0, columnspan=2, row=0, sticky="we", pady=(0, 5))

    windowRecepie.title("Choosen Recepie")
    #windowRecepie.geometry("600x500")

def displayImages(url_request_image, root, destination_image_box_height, destination_image_box_width):
    request = Request(url_request_image, headers={'User-Agent': 'Mozilla/5.0'})
    image_bytes = urlopen(request).read()
    data_stream = io.BytesIO(image_bytes)

    pil_image = Image.open(data_stream)

    original_image_width, original_image_height = pil_image.size

    pil_image_resized = resize(original_image_width, original_image_height, destination_image_box_width,
                               destination_image_box_height,
                               pil_image)

    # Convert PIL image object to Tkinter's PhotoImage object
    image_to_show.image = ImageTk.PhotoImage(pil_image_resized)

    # fill frame with image
    wiki_image_canvas = tk.Label(root, image=image_to_show.image, width=destination_image_box_width,
                                 height=destination_image_box_height)
    wiki_image_canvas.configure(background="white")
    wiki_image_canvas.pack(padx=5, pady=5)

def resize(original_image_width, original_image_height, destination_image_box_width, destination_image_box_height,
           pil_image):
    f1 = 1.0 * destination_image_box_width / original_image_width
    f2 = 1.0 * destination_image_box_height / original_image_height
    factor = min([f1, f2])
    new_image_width = int(original_image_width * factor)
    new_image_height = int(original_image_height * factor)
    return pil_image.resize((new_image_width, new_image_height), Image.ANTIALIAS)

if __name__ == '__main__':
    root = Tk()
    my_gui = MainGui(root)
    root.mainloop()


import os
import sys
import logging
import shutil
from datetime import datetime, timedelta
from logger import get_logger
from config import LOG_LEVEL_STDOUT, LOG_LEVEL_FILE, SAVED_DIR_PATH, BACKUP_DIR_PATH, FILES_TO_BACKUP

# catch unhandled exceptions
logger = get_logger('backup.log', log_level_stdout=LOG_LEVEL_STDOUT, log_level_file=LOG_LEVEL_FILE)

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

sys.excepthook = handle_exception

# save current time
now = datetime.utcnow()
if LOG_LEVEL_STDOUT > logging.INFO:
    print("Checking if backup is required...")
logger.info("Checking if backup is required...")

# try getting the date of the last entry of the logfile
logfile = os.path.join(SAVED_DIR_PATH, 'Logs', 'ConanSandbox.log')
try:
    with open(logfile, 'r') as f:
        lines = f.readlines()
        log_dt = datetime.strptime(lines[-1][1:20], '%Y.%m.%d-%H.%M.%S')

# if file doesn't, exist exit with error message
except Exception as e:
    logger.error("Error:", e)
    sys.exit()

# get the list of files and directories at the configured backup path
try:
    directories = os.listdir(BACKUP_DIR_PATH)

# if path doesn't, exist exit with error message
except Exception as e:
    logger.error("Error:", e)
    sys.exit()

# check if an entry for the date of the crash exists starting from the last directory
backupdir = None
directories.sort(reverse=True)
for directory in directories:
    try:
        dir_d = datetime.strptime(directory, '%Y.%m.%d')
    except Exception:
        # not a date, skip over
        continue

    # directory for the date in the logfile already exists
    if dir_d.date() == log_dt.date():
        backupdir = os.path.join(BACKUP_DIR_PATH, directory)
        break

    # if the last directory is older than the logfile, a new directory has to be created
    elif dir_d < log_dt:
        backupdir = os.path.join(BACKUP_DIR_PATH, log_dt.strftime('%Y.%m.%d'))
        os.mkdir(backupdir)
        break

# if no backup directory was either found or created, exit script
if not backupdir:
    logger.error(f"Couldn't find or create backup folder {log_dt.strftime('%Y.%m.%d')} in {BACKUP_DIR_PATH}.")
    sys.exit()

# get the list of files and directories at the path matching the date
directories = os.listdir(backupdir)
directories.sort(reverse=True)
dir_t = None
for directory in directories:
    try:
        dir_t = datetime.strptime(directory, '%H.%M.%S').time()
        break
    except Exception:
        # not a date, skip over
        continue

# if no directory with a valid time is in backupdir, one has to be created
if not dir_t:
    dir_t = log_dt.strftime('%H.%M.%S')
    backupdir = os.path.join(backupdir, dir_t)
    os.mkdir(backupdir)
# if the latest valid timestamp is not within 5 minutes of the time of the log, create a new directory as well
elif (log_dt - timedelta(minutes=5)) > datetime.combine(dir_d, dir_t):
    dir_t = log_dt.strftime('%H.%M.%S')
    backupdir = os.path.join(backupdir, dir_t)
    os.mkdir(backupdir)
# a valid timestamp was found an it's within 5 minutes of the time of the log, DSL backup worked correctly
else:
    backupdir = None

# if a new folder was created, copy all the relevant files there
if backupdir:
    for file in FILES_TO_BACKUP:
        try:
            shutil.copy2(file, backupdir)
            logger.info(f"Copying {os.path.basename(file)} to backup folder.")
        except Exception as error:
            # Errno 2 is 'No such file or directory'
            if error.args[0] == 2:
                pass
            else:
                logger.error(str(error))

execTime = datetime.utcnow() - now
execTimeStr = str(execTime.seconds) + "." + str(execTime.microseconds)
if LOG_LEVEL_STDOUT > logging.INFO:
    print(f"Done! Required time: {execTimeStr} sec.")
logger.info(f"Done! Required time: {execTimeStr} sec.")


import dash
import dash_bootstrap_components as dbc

# meta_tags are required for the app layout to be mobile responsive
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.FLATLY], suppress_callback_exceptions=True,  # NOQA E501
                meta_tags=[{'name': 'viewport',
                            'content': 'width=device-width, "background-color": "#D1CBC9", initial-scale=1.0'}]  # NOQA E501
                )
app.title = 'Floor Plan'
server = app.server


from rest_framework import serializers

from ....core.api.serializers import BaseSerializer
from ... import models

class PaymentObjectDataSerializer(serializers.Serializer):
    """Serializer present payment object data for `Payment` model."""

    client_secret = serializers.CharField(allow_null=True)
    status = serializers.CharField()

class PaymentSerializer(BaseSerializer):
    """Serializer for `Payment` model."""

    payment_object_data = PaymentObjectDataSerializer()

    class Meta:
        model = models.Payment
        fields = (
            'id',
            'payer',
            'recipient',
            'amount',
            'application_fee_amount',
            'description',
            'status',
            'payment_object_data',
        )

class StartPaymentParamsSerializer(serializers.Serializer):
    """Serializer for model retrieval for payments."""

    object_type = serializers.ChoiceField(choices=(
        'invoice', 'support'
    ))
    object_id = serializers.IntegerField()


import tkinter as tk
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfile

from PIL import ImageTk, Image
import socket
from fileinput import filename
import os
import socket,cv2, pickle,struct

HEADER = 1024
FORMAT = "utf-8"
port = 1010
ip_addr = ''
cn = 0
filename = ''

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print("socket creartion failed with error %s"%(err))

def send(str):
    s.sendall(str.encode(FORMAT))
    msg = s.recv(HEADER)
    if msg == b"Msg received":
        return 1
    return 1

def connect():
    global ip_addr
    global cn
    ip_addr = textIp.get()
    try:
        s.connect((ip_addr,port))
        messagebox.showinfo("Message", "Connected susseccfully")
        cn = 1
    except socket.error as err:
        messagebox.showinfo("Message", "Error connecting to server.")

def disconnect():
    send('EXIT')

def keystroke_keylock():
    def hook():
        send("HOOK")

    def unhook():
        send("UNHOOK")

    def print_kb():
        send("PRINT KEYBOARD")
        msg = s.recv(HEADER).decode(FORMAT)
        if msg != "None!!!":
            text_keystroke.insert(END,msg)
    def lock():
        send("LOCK")

    def unlock():
        send("UNLOCK")

    def clear_kb():
        text_keystroke.delete("1.0","end")

    def on_closing_ks():
            send("QUIT")
            ks.destroy()

    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    rt = send("KEYLOG")
    if rt == 0:
      messagebox.showinfo("Message", "Can't send data to server")
      return

    ks = Toplevel(gui)
    ks.title("Keylogger")
    button_lock = Button(ks, text="Lock", width=10, command=lock)
    button_unlock = Button(ks, text="Unlock", width=10, command=unlock)
    button_hook = Button(ks, text="Hook", width=10, command=hook)
    button_unHook = Button(ks, text="Unhook", width=10, command=unhook)
    button_print = Button(ks, text="Print", width=10, command=print_kb)
    button_clear = Button(ks, text="Clear", width =10, command=clear_kb)

    button_lock.grid(row=0,column=0,padx=5,pady=5,sticky='NSEW')
    button_unlock.grid(row=1,column=0,padx=5,pady=5,sticky='NSEW')
    button_hook.grid(row=2,column=0,padx=5,pady=5,sticky='NSEW')
    button_unHook.grid(row=3,column=0,padx=5,pady=5,sticky='NSEW')
    button_print.grid(row=4,column=0,padx=5,pady=5,sticky='NSEW')
    button_clear.grid(row=5,column=0,padx=5,pady=5,sticky='NSEW')

    text_frame = Frame(ks)
    text_frame.grid(rowspan=6,row=0, column=1,pady=5,sticky='NSEW')
    text_keystroke = Text(text_frame, width=48)
    text_keystroke.grid(rowspan=6,row=0, column=0,padx=5,pady=5,sticky='NSEW')

    bar = Scrollbar(text_frame, orient="vertical", command=text_keystroke.yview)
    bar.grid(rowspan=6, row=0, column=2, sticky='NS')
    text_keystroke.configure(yscrollcommand=bar.set)

    ks.protocol("WM_DELETE_WINDOW", on_closing_ks)

def shutdown():
    global cn
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    send("SHUTDOWN")
    disconnect()
    cn = 0

def logout():
    global cn
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    send("LOGOUT")
    disconnect()
    cn = 0

def app_running():
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    rt = send("APPLICATION")
    if rt == 0:
      messagebox.showinfo("Message", "Can't send data to server")
      return

    def xem():
        send("XEM")
        full_msg = ''
        msg = s.recv(HEADER).decode(FORMAT)
        splits = msg.split('\n')
        data = []
        for e in splits:
            t = e.split(' ')
            data.append((t[0], t[len(t)-1]))
        x = data.pop(0)
        x = data.pop(0)

        for i in app_tree.get_children():
            app_tree.delete(i)

        for setA in data:
            app_tree.insert('', END, values = setA)

    def kill():
        def on_closing_kill():
            send("QUIT")
            kill.destroy()
        def killID():
            send("KILLID")
            msg = inputID.get()
            send(msg)
            req = s.recv(HEADER).decode(FORMAT)
            if req == 'Done!!!':
                messagebox.showinfo("Message", "App was killed")
            if req == 'Error!!!':
                messagebox.showinfo("Message", "App not found")

        msg = send("KILL")
        kill = Toplevel(ar)
        kill.title("Kill")

        inputID = Entry(kill, width=30)
        button_killid = tk.Button(kill, text="Kill",width=15,command=killID)

        inputID.grid(row=0,column=0,padx=10,pady=10,sticky='NSEW')
        button_killid.grid(row=0,column=1,padx=10,pady=10,sticky='NSEW')
        inputID.insert(END,"Input ID")

        kill.protocol("WM_DELETE_WINDOW", on_closing_kill)

    def xoa():
        for i in app_tree.get_children():
            app_tree.delete(i)

    def start():
        def on_closing():
            send("QUIT")
            start.destroy()
        def startID():
            send("STARTID")
            msg = inputID.get()
            send(msg)
            req = s.recv(HEADER).decode(FORMAT)
            if req == 'Done!!!':
                messagebox.showinfo("Message", "App was started")
            if req == 'Error!!!':
                messagebox.showinfo("Message", "Error")

        msg = send("START")
        start = Toplevel(ar)
        start.title("Start")

        inputID = Entry(start, width=30)
        button_killid = tk.Button(start, text="Start", width=15,command=startID)

        inputID.grid(row=0,column=0,padx=10,pady=10,sticky='NSEW')
        button_killid.grid(row=0,column=1,padx=10,pady=10,sticky='NSEW')
        inputID.insert(END,"Input name")
        start.protocol("WM_DELETE_WINDOW", on_closing)

    def on_closing_ar():
            send("QUIT")
            ar.destroy()

    ar = Toplevel(gui)
    ar.title("App")
    button_kill = Button(ar, text="Kill", width=10, command=kill)
    button_xem = Button(ar, text="View", width=10, command=xem)
    button_xoa = Button(ar, text="Clear", width=10, command=xoa)
    button_start = Button(ar, text="Start", width =10, command=start)

    button_kill.grid(row=0,column=0,padx=5,pady=5,sticky='NSEW')
    button_xem.grid(row=0,column=1,padx=5,pady=5,sticky='NSEW')
    button_xoa.grid(row=0,column=2,padx=5,pady=5,sticky='NSEW')
    button_start.grid(row=0,column=3,padx=5,pady=5,sticky='NSEW')

    list_frame = Frame(ar)
    list_frame.grid(columnspan=4,row=1, column=0,pady=5,sticky='NSEW')

    columns = ('namea', 'id')
    app_tree = ttk.Treeview(list_frame, columns=columns, show='headings')

    app_tree.heading('namea', text='Name')
    app_tree.heading('id', text='ID')

    app_tree.grid(columnspan=4,row=0, column=0,padx=5,pady=5,sticky='NSEW')

    bar = Scrollbar(list_frame, orient="vertical", command=app_tree.yview)
    bar.grid(row=0, column=4, sticky='NS')
    app_tree.configure(yscrollcommand=bar.set)

    ar.protocol("WM_DELETE_WINDOW", on_closing_ar)

def process_running():
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    rt = send("PROCESS")
    if rt == 0:
      messagebox.showinfo("Message", "Can't send data to server")
      return
    def xem():
        msg = send("XEM")
        full_msg = ''
        while True:
            msg = s.recv(HEADER).decode(FORMAT)
            if msg == "Complete!":
                break
            full_msg += msg
        text_process.delete("1.0","end")
        text_process.insert(END,full_msg)

    def kill():
        def on_closing_kill():
            send("QUIT")
            kill.destroy()
        def killID():
            send("KILLID")
            msg = inputID.get()
            send(msg)
            req = s.recv(HEADER).decode(FORMAT)
            if req == 'Done!!!':
                messagebox.showinfo("Message", "Process was killed")
            if req == 'Error!!!':
                messagebox.showinfo("Message", "Error")

        msg = send("KILL")
        kill = Toplevel(process)
        kill.title("Kill")
        inputID = Entry(kill, width =30)
        button_killid = Button(kill, text="Kill", width=15,command=killID)

        inputID.grid(row=0,column=0,padx=10,pady=10,sticky='NSEW')
        button_killid.grid(row=0,column=1,padx=10,pady=10,sticky='NSEW')
        inputID.insert(END,"Input ID")

        kill.protocol("WM_DELETE_WINDOW", on_closing_kill)

    def xoa():
        text_process.delete("1.0","end")

    def start():
        def on_closing():
            send("QUIT")
            start.destroy()
        def startID():
            send("STARTID")
            msg = inputID.get()
            send(msg)
            req = s.recv(HEADER).decode(FORMAT)
            if req == 'Done!!!':
                messagebox.showinfo("Message", "Process was started")
            if req == 'Error!!!':
                messagebox.showinfo("Message", "Error")

        msg = send("START")
        start = Toplevel(process)
        start.title("Start")
        inputID = Entry(start, width =30)
        button_killid = Button(start, text="Start", width=15,command=startID)

        inputID.grid(row=0,column=0,padx=10,pady=10,sticky='NSEW')
        button_killid.grid(row=0,column=1,padx=10,pady=10,sticky='NSEW')
        inputID.insert(END,"Input name")
        start.protocol("WM_DELETE_WINDOW", on_closing)

    def on_closing_pr():
            send("QUIT")
            process.destroy()

    process = Toplevel(gui)
    process.title("Process")
    button_kill = Button(process, text="Kill", width=10, command=kill)
    button_xem = Button(process, text="View", width=10, command=xem)
    button_xoa = Button(process, text="Clear", width=10, command=xoa)
    button_start = Button(process, text="Start", width =10, command=start)

    button_kill.grid(row=0,column=0,padx=5,pady=5,sticky='NSEW')
    button_xem.grid(row=0,column=1,padx=5,pady=5,sticky='NSEW')
    button_xoa.grid(row=0,column=2,padx=5,pady=5,sticky='NSEW')
    button_start.grid(row=0,column=3,padx=5,pady=5,sticky='NSEW')

    text_frame = Frame(process)
    text_frame.grid(columnspan=4,row=1, column=0,pady=5,sticky='NSEW')
    text_process = Text(text_frame, width=48)
    text_process.grid(columnspan=4,row=0, column=0,padx=5,pady=5,sticky='NSEW')

    bar = Scrollbar(text_frame, orient="vertical", command=text_process.yview)
    bar.grid(row=0, column=4, sticky='NS')
    text_process.configure(yscrollcommand=bar.set)

    process.protocol("WM_DELETE_WINDOW", on_closing_pr)

def screenshot():
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return

    def take():
        send('SCREENSHOT')
        img = open("img_short.png", "wb")
        msg = s.recv(HEADER)
        while msg != b'Complete!':
            img.write(msg)
            s.sendall("rc".encode(FORMAT))
            msg = s.recv(HEADER)
        img.close()
        img = Image.open("img_short.png")
        resize_img = img.resize((710,400))
        img_show = ImageTk.PhotoImage(resize_img)
        img_label.config(image=img_show)
        img_label.update()
        scr.mainloop()

    def save():
        send('SCREENSHOT')
        files = [('Image', '*.png*'),('All Files', '*.')]
        file = asksaveasfile(mode = "wb", filetypes = files, defaultextension = files)
        print(file)
        msg = s.recv(HEADER)
        while msg != b'Complete!':
            file.write(msg)
            s.sendall("rc".encode(FORMAT))
            msg = s.recv(HEADER)
        file.close()

    send('SCREENSHOT')
    img = open("img_short.png", "wb")
    msg = s.recv(HEADER)
    while msg != b'Complete!':
        img.write(msg)
        s.send("rc".encode(FORMAT))
        msg = s.recv(HEADER)
    img.close()

    scr = Toplevel(gui)
    scr.title("Screen shot")

    button_take = Button(scr, text="Take", width=9, font=('Arial',13), height=6, command=take)
    button_save = Button(scr, text="Save", width=9, font=('Arial',13), height=6, command=save)

    button_take.grid(row=0, column=1, padx=10, pady=10, sticky = 'EW')
    button_save.grid(row=1, column=1, padx=10, pady=10, sticky = 'EW')

    img_frame = Frame(scr)
    img_frame.grid(row=0, column=0, rowspan=2, padx=5, pady=5, sticky = 'NSEW')

    img = Image.open("img_short.png")
    resize_img = img.resize((710,400))
    img_show = ImageTk.PhotoImage(resize_img)

    img_label = Label(img_frame, image=img_show)
    img_label.grid(rowspan=2, row=0, column=0, padx=5, pady=10, sticky='NSEW')
    scr.mainloop()

def videostream():
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    rt = send('VIDEO')
    if rt == 0:
      messagebox.showinfo("Message", "Can't send data to server")
      return

    data = b""
    payload_size = struct.calcsize("Q")
    while True:
        while len(data) < payload_size:
            packet = s.recv(4*1024) # 4K
            s.send(" ".encode(FORMAT))
            if not packet: break
            data+=packet

        packed_msg_size = data[:payload_size]
        data = data[payload_size:]
        msg_size = struct.unpack("Q",packed_msg_size)[0]
        while len(data) < msg_size:
            data += s.recv(4*1024)
            s.send(" ".encode(FORMAT))
        frame_data = data[:msg_size]
        data  = data[msg_size:]
        frame = pickle.loads(frame_data)
        cv2.imshow("RECEIVING VIDEO",frame)
        if cv2.waitKey(1) == 27:
            msg = s.recv(HEADER*HEADER*HEADER)
            s.sendall("Complete!Complete!Complete!".encode(FORMAT))
            cv2.destroyAllWindows()
            break

def registry():
    def browser():
        global filename
        filename = filedialog.askopenfilename(initialdir = "/", title= "Select a file", filetype=(("registry files","*.reg"),("all files","*.*")))
        show_addr.delete(0, END)
        show_addr.insert(END, filename)
        file_reg = open(filename,"r")
        r_reg = file_reg.read(HEADER*4)
        text_reg.delete("1.0","end")
        text_reg.insert(END, r_reg)
        file_reg.close()

    def send_f():
        send("send file")
        file_reg = open(filename,"rb")
        r_reg = file_reg.read(HEADER*4)
        s.sendall(r_reg)
        file_reg.close()
        msg = s.recv(HEADER).decode(FORMAT)
        if msg == 'done':
            messagebox.showinfo("Message", "Sửa thành công.")
        else:
            messagebox.showinfo("Message", "Sửa thất bại.")

    def def_chosen(event):
        choo = reg_choosen.get()
        if choo == 'Get value':
            input_name.delete(0, END)
            input_name.insert(END,"Name value")
            input_name.grid(row=2, column=0,padx = 5,pady=10,sticky='W')

            input_value.grid_forget()
            type_value_choosen.grid_forget()
        if choo == 'Set value':
            input_name.delete(0, END)
            input_name.insert(END,"Name value")
            input_name.grid(row=2, column=0,padx = 5,pady=10, sticky='W')

            input_value.delete(0, END)
            input_value.insert(END,"Value")
            type_value_choosen.delete(0, END)

            input_value.grid(row=2, column=1,padx = 2,pady=5, sticky='W')
            type_value_choosen.set('Kiểu dữ liệu')
            type_value_choosen.grid(row=2, column=2,padx=5, sticky='EW')
        if choo == 'Delete value':
            input_name.delete(0, END)
            input_name.insert(END,"Name value")
            input_name.grid(row=2, column=0,padx = 5,pady=10, sticky='W')

            input_value.grid_forget()
            type_value_choosen.grid_forget()
        if choo == 'Create key':
            input_name.grid_forget()
            input_value.grid_forget()
            type_value_choosen.grid_forget()
        if choo == 'Delete key':
            input_name.grid_forget()
            input_value.grid_forget()
            type_value_choosen.grid_forget()

    def send_request():
        choo = reg_choosen.get()
        if choo == 'Get value':
            send('Get value')
            path = input_addr.get()
            valueName = input_name.get()
            send(path)
            send(valueName)
            msg = s.recv(HEADER).decode(FORMAT)
            if msg != 'error':
                text_reg2.insert(END, msg + '\n')
            else:
                text_reg2.insert(END, 'Lỗi \n')

        if choo == 'Set value':
            send('Set value')
            path = input_addr.get()
            valueName = input_name.get()
            value = input_value.get()
            typeValue = type_value_choosen.get()
            send(path)
            send(valueName)
            send(value)
            send(typeValue)
            msg = s.recv(HEADER).decode(FORMAT)
            if msg == 'done':
                text_reg2.insert(END, 'Set value thành công.\n')
            else:
                text_reg2.insert(END, 'Set value thất bại.\n')

        if choo == 'Delete value':
            send('Delete value')
            path = input_addr.get()
            valueName = input_name.get()
            send(path)
            send(valueName)
            msg = s.recv(HEADER).decode(FORMAT)
            if msg == 'done':
                text_reg2.insert(END, 'Delete value thành công.\n')
            else:
                text_reg2.insert(END, 'Delete value thất bại.\n')

        if choo == 'Create key':
            send('Create key')
            path = input_addr.get()
            send(path)
            msg = s.recv(HEADER).decode(FORMAT)
            if msg == 'done':
                text_reg2.insert(END, 'Create key thành công.\n')
            else:
                text_reg2.insert(END, 'Create key thất bại.\n')

        if choo == 'Delete key':
            send('Delete key')
            path = input_addr.get()
            send(path)
            msg = s.recv(HEADER).decode(FORMAT)
            if msg == 'done':
                text_reg2.insert(END, 'Delete key thành công.\n')
            else:
                text_reg2.insert(END, 'Delete key thất bại.\n')

    def del_text():
        text_reg2.delete("1.0","end")

    def on_closing_reg():
        send("QUIT")
        reg.destroy()

    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    rt = send("REGISTRY")
    if rt == 0:
      messagebox.showinfo("Message", "Can't send data to server")
      return
    reg = Toplevel(gui)
    reg.title("Registry")

    #frame top
    frame_top = LabelFrame(reg,padx=20,pady=10)

    frame_top.grid(row=0,column=0)
    button_browser = Button(frame_top, text="Browser...", width=15, height = 1, command=browser)
    button_browser.grid(row=0, column=1)

    button_send = tk.Button(frame_top, text="Gởi nội dung", width=15, height=5, command=send_f)
    button_send.grid(row=1, column=1)

    show_addr = Entry(frame_top, width=80)
    show_addr.insert(END,"Đường dẫn...")
    show_addr.grid(row=0, column=0,padx = 5, pady=1)

    text_reg = Text(frame_top, width=60, height=8)
    text_reg.insert(END, "Nội dung")
    text_reg.grid(row=1,column=0,padx=5, pady=5)

    #frame bot
    frame_bot = LabelFrame(reg,text="Sửa giá trị trực tiếp", padx=20,pady=10)
    frame_bot.grid(row=1,column=0, columnspan=1)

    n=tk.StringVar()
    reg_choosen = ttk.Combobox(frame_bot,width = 97,textvariable = n)
    reg_choosen['values'] = ('Get value',
                          'Set value',
                          'Delete value',
                          'Create key',
                          'Delete key')

    reg_choosen.grid(row=0, column=0,padx=5, pady=5, columnspan=3)
    reg_choosen.set('Chọn chức năng')
    reg_choosen.bind("<<ComboboxSelected>>", def_chosen)

    input_addr = Entry(frame_bot, width=100)
    input_addr.insert(END,"Đường dẫn...")
    input_addr.grid(row=1, column=0,padx=5, pady=5, columnspan=3)

    input_name = Entry(frame_bot, width=30)
    input_name.insert(END,"Name value")
    input_name.grid(row=2, column=0,padx = 5,pady=10, sticky='W')

    input_value = Entry(frame_bot, width=30)
    input_value.insert(END,"Value")
    input_value.grid(row=2, column=1,padx = 2,pady=5, sticky='W')

    n1=tk.StringVar()
    type_value_choosen = ttk.Combobox(frame_bot,textvariable = n1, width=30)
    type_value_choosen['values'] = ('String',
                'Binary',
                'DWORD',
                'QWORD',
                'Multi-String',
                'Expandable String')

    type_value_choosen.set('Kiểu dữ liệu')
    type_value_choosen.grid(row=2, column=2,padx=5, sticky='EW')

    text_reg2 = Text(frame_bot, width=70, height=8)
    text_reg2.grid(row=4,column=0,padx=5, pady=5, columnspan=3, sticky='NSEW')

    button_send2 = tk.Button(frame_bot, text="Gởi", width=15, command=send_request)
    button_send2.grid(row=5, column=0, padx = 5, sticky=E)

    button_del = tk.Button(frame_bot, text="Xóa", width=15, command=del_text)
    button_del.grid(row=5, column=2, padx = 5, sticky=W)
    reg.protocol("WM_DELETE_WINDOW", on_closing_reg)
    reg.mainloop()

def macaddress():
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    rt = send("MAC")
    if rt == 0:
      messagebox.showinfo("Message", "Can't send data to server")
      return
    msg = s.recv(HEADER).decode(FORMAT)

    mac = Toplevel(gui)
    mac.title("Mac address")

    frameMA = LabelFrame(mac,bg = "black", padx=0,pady=0)
    frameMA.grid(row=0,column=0)

    text_mac = Text(frameMA, background = "black",fg = "white",font = ("Arial", 12), width=50, height=3)
    text_mac.insert(END, "\n  Physical Adress..........: " + msg)
    text_mac.grid(row=0,column=0,padx=0, pady=0)

    mac.mainloop()

def folderstructure():
    if cn == 0:
        messagebox.showinfo("Message", "Not connect to server")
        return
    rt = send("FOLDER")
    if rt == 0:
      messagebox.showinfo("Message", "Can't send data to server")
      return

    f_name = ""

    def double_click(event):
        for click_item in tree.selection():
            item = tree.item(click_item)
            record = item['values']
            if record[1] != "File folder":
                messagebox.showinfo("Message", "This is not a folder, can not access")
                return
            send("GOTO")
            s.sendall(str(record[0]).encode(FORMAT))
            msg = s.recv(HEADER)
            data = pickle.loads(msg)

            files = splitListFile(data)

            for i in tree.get_children():
                tree.delete(i)
            for file in files:
                tree.insert('', END, values = file)

    def right_click(event):
        for click_item in tree.selection():
            item = tree.item(click_item)
            global f_name
            f_name = item['values']
            try:
                filemenu.tk_popup(event.x_root, event.y_root)
            finally:
                filemenu.grab_release()

    def recvf():
        global f_name
        fileadrr = filedialog.askopenfilename(initialdir = "/", title= "Select a file",
                                                filetype=(("all files","*.*"),("jpeg files","*.jpg")))
        filename = fileadrr.split("/")
        send("RECEIVE")
        s.send((str(f_name[0]) + "\\" + filename[len(filename) - 1]).encode(FORMAT))
        file_s = open(fileadrr,"rb")
        dataf = file_s.read(HEADER)
        while (dataf):
            s.send(dataf)
            msg = s.recv(HEADER)
            dataf = file_s.read(HEADER)
        file_s.close()
        s.send("Done!".encode(FORMAT))

    def deletef():
        global f_name
        send("DELETE")
        if f_name[1] == "File folder":
            s.send(str(f_name[0]).encode(FORMAT))
        else:
            s.send((str(f_name[0]) + '.' + str(f_name[1])).encode(FORMAT))
        selected_item = tree.selection()[0]
        tree.delete(selected_item)

    def on_closing_fol():
        send("QUIT")
        fol.destroy()

    def splitListFile(data):
        files = []
        i = 0
        for f in data:
            if "." in f:
                splits = f.split(".")
                files.append(splits)
                i += 1
            else:
                files.append((f, "File folder"))
                i += 1
        return files

    def back():
        send("BACK")
        msg = s.recv(HEADER)
        data = pickle.loads(msg)

        files = splitListFile(data)
        print(files)
        for i in tree.get_children():
            tree.delete(i)
        for file in files:
            tree.insert('', END, values = file)

    msg = s.recv(HEADER)
    data = pickle.loads(msg)

    fol = Toplevel(gui)
    fol.title("Folder")

    files = splitListFile(data)

    frame = Frame(fol)
    frame.grid(row=0, column=0, pady=5,sticky='NSEW')

    columns = ('namef', 'type')
    tree = ttk.Treeview(frame, columns=columns, show='headings')

    tree.heading('namef', text='Name')
    tree.heading('type', text='Type')

    for file in files:
        tree.insert('', END, values = file)

    menubar = Menu(gui)

    filemenu = Menu(menubar, tearoff=0)
    filemenu.add_command(label="Receive", command=recvf)
    filemenu.add_command(label="Delete", command=deletef)

    tree.bind('<Double-1>', double_click)
    tree.bind('<Button-3>', right_click)

    tree.grid(row=0, column=0, sticky='NSEW')
    scrollbar = ttk.Scrollbar(frame, orient = "vertical", command=tree.yview)
    tree.configure(yscroll=scrollbar.set)
    scrollbar.grid(row=0, column=1, sticky='NS')

    button_back=Button(fol, text="Back",width=10, bg="BLACK", fg="WHITE", command = back)
    button_back.grid(columnspan=2, row=2, column=0, padx=10, pady=5, sticky='NS')

    fol.protocol("WM_DELETE_WINDOW", on_closing_fol)
    fol.mainloop()

def close():
    global cn
    if cn == 0:
        gui.destroy()
        return

    disconnect()
    s.shutdown(2)
    s.close()
    cn = 0
    gui.destroy()

gui = tk.Tk()
gui.title("Client")
textIp = Entry(gui,text="Input", width =32)
textIp.insert(END,"Nhập địa chỉ IP")
textIp.grid(row=0, column=0, columnspan=6, padx=5, pady=10, sticky='NSEW')

button_connect=Button(gui, text="Connect",width=7, bg="BLACK", fg="WHITE", command = connect)
button_connect.grid(columnspan=2, row=0, column=4, padx=5, pady=10, sticky='E')

button_process=Button(gui,text="Folder",width=18,height=3, command = folderstructure)
button_process.grid(columnspan=2, row=1, column=0, padx=5, pady=5, sticky='NSEW')

button_video=Button(gui,text="Video screen",width=35,height=3, command = videostream)
button_video.grid(columnspan=4, row=1, column=2, padx=5, pady=5, sticky='NSEW')

button_process=Button(gui,text="Process\nRunning",width=10,height=3, command = process_running)
button_process.grid(rowspan=3, row=2, column=0, padx=5, pady=5, sticky='NSEW')

button_app=Button(gui,text="App Running",width=20,height=4, command = app_running)
button_app.grid(columnspan=2, row=2, column=1, padx=5, pady=5, sticky='NSEW')

button_shutdown=Button(gui,text="Shutdown",width=8,height=4, command=shutdown)
button_shutdown.grid(columnspan=1, row=2, column=3, padx=5, pady=5, sticky='NSEW')

button_shutdown=Button(gui,text="Logout",width=8,height=4, command=logout)
button_shutdown.grid(columnspan=1, row=3, column=1, padx=5, pady=5, sticky='NSEW')

button_screenshot=Button(gui,text="ScreenShot",width=20,height=4, command=screenshot)
button_screenshot.grid(columnspan=2, row=3, column=2, padx=5, pady=5, sticky='NSEW')

button_keystroke=Button(gui,text="Keystroke\n&\nKeylock",width=15,height=4, command=keystroke_keylock)
button_keystroke.grid(columnspan=2, rowspan=2, row=2, column=4, padx=5, pady=5, sticky='NSEW')

button_registry=Button(gui,text="Registry",width=40,height=3, command=registry)
button_registry.grid(columnspan=4, row=4, column=1, padx=5, pady=5, sticky='NSEW')

button_close=Button(gui,text="Mac\nAdress",width=7,height=3, command=macaddress)
button_close.grid(columnspan=1, row=4, column=5, padx=5, pady=5, sticky='NSEW')

gui.protocol("WM_DELETE_WINDOW", close)
gui.mainloop()


import os
import json
import logging
from typing import Dict, List, Union

from cpdupload.csvingest import CsvIngest, CsvIngestException
from cpdupload.jsonbuilder import JSONBuilder, JSONBuilderException
from cpdupload.api import API, APIException

class Loader:
    """
    The Loader class unifies the API load workflow. It has a method to accept a filename
    and attempt to upload it to the API.
    """

    def __init__(self, input_filename: str, api: str, token: str):
        """
        This constructor accepts an input filename as a parameter and checks to
        ensure the filename exists before any load operation happens.

        Parameters
        ----------
        input_filename: str
            The input filename for the load operation.

        api: str
            The base URL of the CPD API server.

        token: str
            The bearer token to use for API authentication.

        Raises
        ------
        LoaderException
            Raises a LoaderException if the filename is not found or the API health check
            endpoint cannot be contacted.
        """
        if not os.path.isfile(input_filename):
            raise LoaderException(
                f"Cannot import {input_filename} because the file was not found."
            )

        self.input_filename = input_filename
        self.token = token
        self.logger = logging.getLogger(__name__)

        try:
            api_check = API(api, token)
            api_check.health_check()
            self.api = api
        except APIException as e:
            raise LoaderException(str(e))

    def send_adsorption_measurement_to_api(self):
        """
        send_file_to_api loads the file given, checks to see if it
        is JSON or CSV, parses a CSV if necessary, and then sends the JSON payload
        to the API.

        Raises
        ------
        LoaderException
            Raises an exception if something goes wrong with the file parsing or
            upload to the API.
        """
        try:
            api = API(self.api, self.token)

            if self.input_filename.endswith(".csv"):
                self.logger.info(f"Loading {self.input_filename} as a CSV.")
                ingest = CsvIngest(self.input_filename)
                rows: List[Dict[str, Union[int, str, float]]] = ingest.load_csv()
                self.logger.info(
                    f"Attempting to build JSON from {len(rows)} CSV row(s)."
                )
                builder = JSONBuilder()
                json_for_upload = builder.parse_rows(rows)
            else:
                # Attempt to parse as JSON, throw errors for others
                self.logger.info(f"Loading {self.input_filename} as a JSON.")
                with open(self.input_filename, "r") as file:
                    json_for_upload = json.loads(file.read())

            api.adsorption_measurement_load(json_for_upload)

        except CsvIngestException as err:
            raise LoaderException(f"Error while parsing CSV file: {err}")
        except JSONBuilderException as err:
            raise LoaderException(f"Error while building the JSON: {err}")
        except APIException as err:
            raise LoaderException(f"Error connecting to the CPD API: {err}")

class LoaderException(Exception):
    """
    The LoaderException class is for exceptions raised during a load operation. It is
    raised as part of the exception handling of the Loader class. Use of this exception
    generally follows a two step process:

    1. A JSONBuilderException, CsvIngestException, or APIException is caught by an
    instance of the Loader class.

    2. That original exception is reported to the user with a print statement.

    3. A loader exception is raised that contains the original message as well as
    any additional context information of for the Loader exception.

    4. The code calling the instance of this Loader class can then catch the
    LoaderException and report it to the user.

    Additionally, a LoaderException can be raised on its own by the Loader class
    for errors that fall outside the scope of the other three exceptions.

    For the message in the exception, emphasis should be placed on an error message
    that can be shown to a user with some actionable meaning.
    """

    def __init__(self, message: str):
        """
        Accepts a message that should be descriptive for display to a user.

        Parameters
        ----------
        message: str
            An error message useful to an end user.
        """
        super(LoaderException, self).__init__(message)


import logging
import platform
from PySide6 import QtWidgets
from os.path import expanduser
from src.Controller.PathHandler import resource_path
import pandas as pd

pd.options.mode.chained_assignment = None  # default='warn'

class MachineLearningDataSelectionOptions(QtWidgets.QWidget):
    def __init__(self):
        """
        Initialise the class
        """
        QtWidgets.QWidget.__init__(self)

        # Create the main layout
        self.main_layout = QtWidgets.QVBoxLayout()

        # Get the stylesheet
        if platform.system() == 'Darwin':
            self.stylesheet_path = "res/stylesheet.qss"
        else:
            self.stylesheet_path = "res/stylesheet-win-linux.qss"
        self.stylesheet = open(resource_path(self.stylesheet_path)).read()

        label_dvh = QtWidgets.QLabel(
            "Please choose the input CSV file location for DVH Data:"
        )
        label_dvh.setStyleSheet(self.stylesheet)

        label_pyrad = QtWidgets.QLabel(
            "Please choose the input CSV file location for Pyradiomics Data:"
        )
        label_pyrad.setStyleSheet(self.stylesheet)

        self.directory_layout = QtWidgets.QFormLayout()

        # Directory text box for DVH Data
        self.directory_input_dvh_data = QtWidgets.QLineEdit(
            "No file selected")
        self.directory_input_dvh_data.setStyleSheet(self.stylesheet)
        self.directory_input_dvh_data.setEnabled(False)

        # Button For DVH Data to set location
        self.change_button_dvh_data = QtWidgets.QPushButton("Change")
        self.change_button_dvh_data.setMaximumWidth(100)
        self.change_button_dvh_data.clicked.connect(
            self.show_file_browser_dvh_data)
        self.change_button_dvh_data.setObjectName("NormalButton")
        self.change_button_dvh_data.setStyleSheet(self.stylesheet)

        # Directory text box for Pyradiomics Data
        self.directory_input_pyrad = QtWidgets.QLineEdit(
            "No file selected")
        self.directory_input_pyrad.setStyleSheet(self.stylesheet)
        self.directory_input_pyrad.setEnabled(False)

        # Button For Pyradiomics Data to set location
        self.change_button_pyradiomics_data = QtWidgets.QPushButton(
            "Change")
        self.change_button_pyradiomics_data.setMaximumWidth(100)
        self.change_button_pyradiomics_data.clicked.connect(
            self.show_file_browser_pyrad)
        self.change_button_pyradiomics_data.setObjectName("NormalButton")
        self.change_button_pyradiomics_data.setStyleSheet(self.stylesheet)

        # Set DVH data
        self.directory_layout.addWidget(label_dvh)
        self.directory_layout.addRow(self.directory_input_dvh_data)
        self.directory_layout.addRow(self.change_button_dvh_data)

        # Set Pyradiomics data
        self.directory_layout.addWidget(label_pyrad)
        self.directory_layout.addRow(self.directory_input_pyrad)
        self.directory_layout.addRow(self.change_button_pyradiomics_data)

        # create dropdown menu for dvh values to select from
        self.dvh_dropdown_menu = QtWidgets.QComboBox()
        self.dvh_dropdown_menu.setStyleSheet(self.stylesheet)
        self.dvh_dropdown_menu.setEditable(True)
        self.dvh_dropdown_menu.lineEdit().setReadOnly(True)

        # create dropdown menu for dvh values to select from
        self.pyrad_dropdown_menu = QtWidgets.QComboBox()
        self.pyrad_dropdown_menu.setStyleSheet(self.stylesheet)
        self.pyrad_dropdown_menu.setEditable(True)
        self.pyrad_dropdown_menu.lineEdit().setReadOnly(True)

        # create labels for dropdown menus
        self.dvh_dropdown_label = QtWidgets.QLabel(
            "Please select the DVH ROI to filter by:")
        self.dvh_dropdown_label.setStyleSheet(self.stylesheet)
        self.pyrad_dropdown_label = QtWidgets.QLabel(
            "Please select the PyRad ROI to filter by:")
        self.pyrad_dropdown_label.setStyleSheet(self.stylesheet)

        # add dropdowns to main_layout
        self.directory_layout.addRow(self.dvh_dropdown_label)
        self.directory_layout.addRow(self.dvh_dropdown_menu)
        self.directory_layout.addRow(self.pyrad_dropdown_label)
        self.directory_layout.addRow(self.pyrad_dropdown_menu)

        self.main_layout.addLayout(self.directory_layout)
        self.setLayout(self.main_layout)

    def set_dvh_dropdown_menu_data(self, options):
        self.dvh_dropdown_menu.clear()
        self.dvh_dropdown_menu.addItems(options)

    def set_pyrad_dropdown_menu_data(self, options):
        self.pyrad_dropdown_menu.clear()
        self.pyrad_dropdown_menu.addItems(options)

    def read_in_dvh_data(self):
        if self.get_csv_input_location_dvh_data() is not None:
            data_dvh = pd.read_csv(
                f'{self.get_csv_input_location_dvh_data()}',
                on_bad_lines='skip')
            return list(
                data_dvh[data_dvh['ROI'].str.contains('PTV')]['ROI'].unique()
            )
        else:
            return "-"

    def read_in_pyrad_data(self):
        if self.get_csv_input_location_pyrad() is not None:
            data_Py = pd.read_csv(
                f'{self.get_csv_input_location_pyrad()}')
            return list(
                data_Py[data_Py['ROI'].str.contains('GTV')]['ROI'].unique()
            )
        else:
            return "-"

    def _on_dvh_path_changed(self):
        options = self.read_in_dvh_data()
        self.set_dvh_dropdown_menu_data(options)

    def _on_pyrad_path_changed(self):
        options = self.read_in_pyrad_data()
        self.set_pyrad_dropdown_menu_data(options)

    # Function for DVH Data
    def set_csv_input_location_dvh_data(self, path, enable=True,
                                        change_if_modified=False):
        """
        Set the location for the dvh .csv file.
        :param path: desired path.
        :param enable: Enable the directory text bar.
        :param change_if_modified: Change the directory if already been
                                   changed.
        """
        if not self.directory_input_dvh_data.isEnabled():
            self.directory_input_dvh_data.setText(path)
            self.directory_input_dvh_data.setEnabled(enable)
        elif change_if_modified:
            self.directory_input_dvh_data.setText(path)
            self.directory_input_dvh_data.setEnabled(enable)

        self._on_dvh_path_changed()

    def get_csv_input_location_dvh_data(self):
        """
        Get the location of the desired output directory.
        """
        if (self.directory_input_dvh_data.text() != 'No file selected'
                and self.directory_input_dvh_data.text() != expanduser("~")):
            return self.directory_input_dvh_data.text()
        else:
            return None

    def show_file_browser_dvh_data(self):
        """
        Show the file browser for selecting a folder for the Onko
        default directory.
        """
        # Open a file dialog and return chosen directory
        path = QtWidgets.QFileDialog.getOpenFileName(
            None, "Open DVH File", "",
            "CSV data files (*.csv *.CSV)")[0]

        # If chosen directory is nothing (user clicked cancel) set to
        # user home
        if path == "" and \
                self.directory_input_dvh_data.text() == 'No file selected':
            path = expanduser("~")
        elif (path == ""
              and
              (self.directory_input_dvh_data.text() != 'No file selected'
               or self.directory_input_dvh_data.text() != expanduser("~"))):
            path = self.directory_input_dvh_data.text()

        # Update file path
        self.set_csv_input_location_dvh_data(path, change_if_modified=True)

    # Function for Pyrad Data
    def set_csv_input_location_pyrad(self, path, enable=True,
                                     change_if_modified=False):
        """
        Set the location for the pyradiomics .csv file.
        :param path: desired path.
        :param enable: Enable the directory text bar.
        :param change_if_modified: Change the directory if already been
                                   changed.
        """
        if not self.directory_input_pyrad.isEnabled():
            self.directory_input_pyrad.setText(path)
            self.directory_input_pyrad.setEnabled(enable)
        elif change_if_modified:
            self.directory_input_pyrad.setText(path)
            self.directory_input_pyrad.setEnabled(enable)

        self._on_pyrad_path_changed()

    def get_csv_input_location_pyrad(self):
        """
        Get the location of the desired output directory.
        """
        if (self.directory_input_pyrad.text() != 'No file selected'
                and self.directory_input_pyrad.text() != expanduser("~")):
            return self.directory_input_pyrad.text()
        else:
            return None

    def show_file_browser_pyrad(self):
        """
        Show the file browser for selecting a folder for the Onko
        default directory.
        """
        # Open a file dialog and return chosen directory
        path = QtWidgets.QFileDialog.getOpenFileName(
            None, "Open PyRad Data File", "",
            "CSV data files (*.csv *.CSV)")[0]

        # If chosen directory is nothing (user clicked cancel) set to
        # user home
        if path == "" and \
                self.directory_input_pyrad.text() == 'No file selected':
            path = expanduser("~")
        elif (path == ""
              and
              (self.directory_input_pyrad.text() != 'No file selected'
               or self.directory_input_pyrad.text() != expanduser("~"))):
            path = self.directory_input_pyrad.text()

        # Update file path
        self.set_csv_input_location_pyrad(path, change_if_modified=True)

    def get_selected_dvh_value(self):
        return self.dvh_dropdown_menu.currentText()

    def get_selected_pyrad_value(self):
        return self.pyrad_dropdown_menu.currentText()

    def get_selected_options(self):
        selected_options = {
            "dvh_path": self.get_csv_input_location_dvh_data(),
            "pyrad_path": self.get_csv_input_location_pyrad(),
            "dvh_value": self.get_selected_dvh_value(),
            "pyrad_value": self.get_selected_pyrad_value()
        }

        logging.debug("MachineLearningDataSelectionOptions"
                      ".get_selected_options() called")
        logging.debug(f"returning: {selected_options}")
        return selected_options


# -*- coding: utf-8 -*-

import sys
#import os
#import time
#import shutil
import fix_qt_import_error

from PyQt5 import QtWidgets
from mainwnd import Ui_MainWindow
from PyQt5 import QtGui

from test2 import perceptron

class Main_Window(QtWidgets.QMainWindow):
	def __init__(self):
		QtWidgets.QMainWindow.__init__(self)#QMainWindow的初始化
		self.mainwnd = Ui_MainWindow()#主窗口的实例化
		self.mainwnd.setupUi(self)

	def start(self):
		self.image = QtGui.QPixmap()

		pic_path = "dataset/pic.png"

		txtname = self.mainwnd.chooseTXT.currentText()

		txtname =  "dataset/"+txtname

		try:
		    LR_condition = float(self.mainwnd.lineEdit.text())
		except:
		    LR_condition = 0.01
		else:
		    LR_condition = float(self.mainwnd.lineEdit.text())

		try:
		    train_steps = int(self.mainwnd.lineEdit_2.text())
		except:
		    train_steps = 100
		else:
		    train_steps = int(self.mainwnd.lineEdit_2.text())

		perceptron(txtname,LR_condition,train_steps)

		self.image.load(pic_path)
		self.show_image()

		"""
		w = open('dataset/test.txt','r')

		tst_accuracy = w.read()
		tst_accuracy = float(tst_accuracy)*100
		#print(accuracy)
		self.mainwnd.textBrowser_6.setText(str(tst_accuracy))
		"""
		#############
		count = 0
		w = open('dataset/test.txt','r')
		for line in w:
			if count == 0 :
				tra_accuracy = float(line)*100
				self.mainwnd.textBrowser_8.setText(str(tra_accuracy))
			elif count == 1 :
				tst_accuracy = float(line)*100
				self.mainwnd.textBrowser_6.setText(str(tst_accuracy))
			elif count == 2 :
				w_0 = float(line)
				self.mainwnd.textBrowser_12.setText(str(w_0))
			elif count == 3 :
				w_1 = float(line)
				self.mainwnd.textBrowser_13.setText(str(w_1))
			elif count == 4 :
				w_2 = float(line)
				self.mainwnd.textBrowser_14.setText(str(w_2))
			count +=1

		"""
		m = open('dataset/test2.txt','r')
		tra_accuracy = m.read()
		tra_accuracy = float(tra_accuracy)*100
		#print(accuracy)
		self.mainwnd.textBrowser_8.setText(str(tra_accuracy))
		#self.comboBox.clear()  # 清空items

		#self.comboBox.clear()  # 清空items
		"""
	def show_image(self):
		self.mainwnd.Graphic.scene = QtWidgets.QGraphicsScene()
		item = QtWidgets.QGraphicsPixmapItem(self.image)
		self.mainwnd.Graphic.scene.addItem(item)
		self.mainwnd.Graphic.setScene(self.mainwnd.Graphic.scene)
		self.mainwnd.Graphic.fitInView(item)

app = QtWidgets.QApplication(sys.argv)

window = Main_Window()

btn=window.mainwnd.start_Button
btn.clicked.connect(window.start)

window.show()
sys.exit(app.exec_())


from selenium.webdriver.common.by import By
from tests.commons.pages.automation_practice_order_my_store import Xpath as automation_practice_order_my_store_xpath

class AutomationPracticeOrderMyStorePage:

    def __init__(self, driver):
        self.driver = driver
        self.page = "http://automationpractice.com/index.php?controller=order"
        self.title = "Order - My Store"

    def open_page(self):
        self.driver.get(self.page)
        title = self.driver.title
        assert self.title == title, f"Expected title: {self.title} is different than current title: {title}."

    def find_and_click(self, locator: str):
        if locator.startswith("//"):
            element = self.driver.find_element(By.XPATH, locator)
            element.click()
        else:
            element = self.driver.find_element(By.ID, locator)
            element.click()
        return element

    def find_element(self, locator: str):
        if locator.startswith("//"):
            element = self.driver.find_element(By.XPATH, locator)
        else:
            element = self.driver.find_element(By.ID, locator)
        return element

    def find_elements(self, locator: str):
        if locator.startswith("//"):
            elements = self.driver.find_elements(By.XPATH, locator)
        else:
            elements = self.driver.find_elements(By.ID, locator)
        return elements

    def confirm_address(self):
        self.find_and_click(locator=automation_practice_order_my_store_xpath.PROCEED_TO_CHECKOUT_BUTTON)


from logging.handlers import SMTPHandler

class MailHandler(SMTPHandler):
  def __create_message(self, from_addr, to_addr, message_subject, message_body):
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    message = MIMEMultipart('alternative')
    message['Subject'] = message_subject
    message['From'] = from_addr
    message['To'] = to_addr
    message.attach(MIMEText(message_body, 'plain'))
    return message.as_string()

  def emit(self, record):
    try:
      import string
      from smtplib import SMTP, SMTP_PORT
      from ssl import create_default_context

      port = self.mailport
      if not port:
        port = SMTP_PORT

      smtp = SMTP(self.mailhost, port)
      context = create_default_context()
      message = self.__create_message(
        self.fromaddr,
        ' , '.join(self.toaddrs),
        self.getSubject(record),
        self.format(record)
      )

      if self.username:
        smtp.ehlo()
        smtp.starttls(context=context)
        smtp.ehlo()
        smtp.login(self.username, self.password)

      smtp.sendmail(self.fromaddr, self.toaddrs, message)
      smtp.quit()

    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        self.handleError(record)


from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport
import datetime

transport = AIOHTTPTransport(url='http://127.0.0.1:80/')

client = Client(transport=transport)

query = gql('''
  mutation SingleUpload($file: Upload!, $datetime: String!) {
    singleUpload(file: $file, datetime: $datetime) {
      filename
      mimetype
      encoding
    }
  }
''')

with open("Starship_SN8.mp4", "rb") as f:

    x = datetime.datetime.now()

    params = {
        "file": f,
        "datetime": x.strftime("%Y-%m-%d %H:%M:%S")
    }

    result = client.execute(
        query, variable_values=params, upload_files=True
    )

    print(result)


from typing import List

import pandas as pd
from pandas._config import display
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style="darkgrid")
SAVE_PATH = "output/"

class EDA():
    def __init__(self, df, num_cols, cat_cols, display=True, prefix=""):
        self.df = df
        self.num_cols = num_cols
        self.cat_cols = cat_cols
        self.display = display
        self.prefix = prefix

        print(num_cols)
        print(cat_cols)

    def label_count_plot(self, cat_col) -> None:
        """

        :param df: The pd.DataFrame
        :param cat_col: The name of the columns containing the
                          categorical data to count.
        :return:
        """
        df = self.df

        sns.countplot(y=cat_col, data=df, palette="Set2",
                      order=df[cat_col].value_counts().index)
        plt.savefig(SAVE_PATH + self.prefix + "label_count.png")

        plt.show()

    def get_pairplot(self) -> None:
        df = self.df
        num_cols = self.num_cols

        sns.pairplot(df[num_cols], diag_kind="kde")
        plt.savefig(SAVE_PATH + self.prefix + "pairplot.png")

        plt.show()

    def get_corr_matrix(self) -> None:
        df = self.df
        num_cols = self.num_cols

        sns.heatmap(df[num_cols].corr(), annot=True, cmap='viridis')
        plt.savefig(SAVE_PATH + self.prefix + "correlation_matrix.png")

        plt.show()

    def numerical_analysis(self, hue: str) -> None:
        """

        :param df: The pd.DataFrame

        :param num_columns: The list of all numerical columns
                            that will be taken into account for
                            analysis.

        :param hue: A string containing the name of the column
                    that will be used as hue for sns.kdeplot

        :return: None
        """

        self.get_corr_matrix()
        self.get_pairplot()

        df = self.df
        num_columns = self.num_cols

        for idx in range(len(num_columns)):
            sns.kdeplot(data=df, x=num_columns[idx], hue=hue,
                        fill=True, palette="Set2")
            plt.show()

    def categorical_analysis(self, hue: str) -> None:
        """
        :param df: pd.DataFrame

        :param cat_columns: A string list containing the
                            categorical columns of the
                            pd.DataFrame

        :param hue: The hue for the sns.countplot

        :return: None
        """
        df = self.df
        cat_columns = self.cat_cols

        for idx in range(len(cat_columns)):
            sns.countplot(data=df, x=cat_columns[idx], hue=hue,
                          palette="Set2")
            plt.tick_params(axis='x', rotation=70)
            plt.show()

    def explore_data(self) -> None:
        """
        :param df: A pd.DataFrame containing all the data.
                   The DataFrame needs to have a column named `label`
                   containing all the categorical labels.

        :param num_columns: The list of all the numerical columns
                            in the df DataFrame.

        :param cat_columns: The list of all the categorical columns
                            inf the df DataFrame

        :return: None, plots the data analysis
        """
        self.label_count_plot("label")
        self.numerical_analysis("label")
        self.categorical_analysis("label")


# La clase HttpResponse es una respuesta HTTP básica que se utiliza para devolver
# contenido al cliente desde una vista de Django. Permite enviar datos en forma de texto,
# HTML, JSON u otros formatos compatibles con HTTP.
from django.http import HttpResponse,JsonResponse # el jsonreponse convierte a formato json para poder mostrar una lista
from .models import project, task,alumnos
from django.shortcuts import get_object_or_404 # si no hay un objeto muestra el error 404
from django.shortcuts import render # render es para renderixar archivos html
from .form import *
from django.shortcuts import redirect

# Create your views here.
def index(request):
    title = "welcome to django"
    return render(request,"index.html",{
        "title": title
    })

def hello(request,username):
    print(username)
    #
    return HttpResponse("
Hello %s
"% username)
# El parámetro request en una función de vista de Django es un objeto que representa la
# solicitud HTTP realizada por un cliente. Proporciona información sobre la solicitud,
# como los datos enviados por el cliente, los encabezados de la solicitud, la URL solicitada
# y otros detalles relevantes.
def about(request):
    username = "ewar"
    return render(request,"about.html",{
        "username": username
    })

def projects(request):
    projects = project.objects.all()
    return render(request,"projects/projects.html",{
        "projects":projects
    })

def tasks(request):
    tasks = task.objects.all()
    return render(request,"tasks/tasks.html",{
        "tasks":tasks
    })

def mostraralumnos(request):
    alumno = alumnos.objects.all()
    return render(request,"alumnos.html",{
        "alumnos": alumno
    })

def createtask(request):
    # este primer if envia a la pagina de create task
    if request.method == "GET":
        return render(request, "tasks/create_task.html", {"form": createnewtask()})
    # esto valida y envia los datos al formulario para crear la tarea
    else:
        form = createnewtask(request.POST)
        if form.is_valid():
            print(form.cleaned_data['title'],form.cleaned_data['description'], form.cleaned_data['project'])
            task.objects.create(title=form.cleaned_data['title'], description=form.cleaned_data['description'], project_id=form.cleaned_data['project'].id)
            return redirect("tasks")

def create_project(request):
    if request.method == "GET":
        return render(request,"projects/create_projects.html",{
            "form":createproject()
        })
    else:
        project.objects.create(name = request.POST["name"])
        return redirect("projects")

def projectdetail(request,id):
    projects = get_object_or_404(project, id = id)
    tareas = task.objects.filter(project_id=id)
    print(projects)
    return render(request,"projects/detail.html",{
        "project":projects,
        "tareas" : tareas
    })


import numpy as np
import pyNSATlib as nsat
import matplotlib.pylab as plt
import timeit
import os

def setup():
    print('Begin %s:setup()' % (os.path.splitext(os.path.basename(__file__))[0]))
    sim_ticks = 5000        # Simulation time
    N_CORES = 1             # Number of cores
    N_NEURONS = [2]         # Number of neurons per core (list)
    N_INPUTS = [0]          # Number of inputs per core (list)
    N_STATES = [4]          # Number of states per core (list)

    # Constants
    XMAX = nsat.XMAX
    XMIN = nsat.XMIN
    OFF = -16
    MAX = nsat.MAX
    MIN = nsat.XMIN

    # Main class instance
    cfg = nsat.ConfigurationNSAT(sim_ticks=sim_ticks,
                                 N_CORES=N_CORES,
                                 N_INPUTS=N_INPUTS,
                                 N_NEURONS=N_NEURONS,
                                 N_STATES=N_STATES,
                                 monitor_states=True,
                                 ben_clock=True)

    # Transition matrix A
    cfg.core_cfgs[0].A[0] = [[-6,  OFF, OFF, OFF],
                             [0, -11, OFF, OFF],
                             [0, OFF, -8, OFF],
                             [OFF, OFF, OFF, OFF]]

    # Sign matrix sA
    cfg.core_cfgs[0].sA[0] = [[-1, 1, 1, 1],
                              [-1, -1, 1, 1],
                              [1, 1, -1, 1],
                              [1, 1, 1, -1]]

    # Bias
    cfg.core_cfgs[0].b[0] = np.array([600, 0, 0, 1], dtype='int')
    # Threshold
    cfg.core_cfgs[0].Xth[0] = XMAX
    # Reset value
    cfg.core_cfgs[0].Xreset[0] = np.array([0, XMAX, XMAX, XMAX], 'int')
    # Turn reset on
    cfg.core_cfgs[0].XresetOn[0] = np.array([True, False, False, False],
                                            'bool')
    # Global modulator state (e.g. Dopamine)
    cfg.core_cfgs[0].modstate[0] = 3

    # Synaptic weights
    N_UNITS = N_INPUTS[0] + N_NEURONS[0]        # Total number of units
    W = np.zeros([N_UNITS, N_UNITS, N_STATES[0]], 'int')
    W[0, 0, 1] = 115
    W[0, 1, 2] = 125
    W[1, 1, 1] = 115
    W[1, 0, 2] = 125
    cfg.core_cfgs[0].W = W

    # Adjacent matrix
    CW = np.zeros(W.shape, dtype='int')
    CW[0, 0, 1] = 1
    CW[0, 1, 2] = 1
    CW[1, 1, 1] = 1
    CW[1, 0, 2] = 1
    cfg.core_cfgs[0].CW = CW

    # Mapping between neurons and NSAT parameters groups
    cfg.core_cfgs[0].nmap = np.zeros((N_NEURONS[0],), dtype='int')

    # Write C NSAT parameters binary files
    c_nsat_writer = nsat.C_NSATWriter(cfg, path='/tmp', prefix='test_adapting')
    c_nsat_writer.write()

    # Write Intel FPGA parameters hex files
#    intel_fpga_writer = nsat.IntelFPGAWriter(cfg, path='.',
#                                             prefix='test_adapting')
#    intel_fpga_writer.write()
#    intel_fpga_writer.write_globals()
    print('End %s:setup()' % (os.path.splitext(os.path.basename(__file__))[0]))
    return c_nsat_writer.fname

def run(fnames):
    # Call the C NSAT
    print('Begin %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))
    cfg = nsat.ConfigurationNSAT.readfileb(fnames.pickled)

    print("Running C NSAT!")
    nsat.run_c_nsat(fnames)

    # Load the results (read binary files)
    c_nsat_reader = nsat.C_NSATReader(cfg, fnames)
    states = c_nsat_reader.read_c_nsat_states()
    time_core0, states_core0 = states[0][0], states[0][1]

    # Plot the results
    fig = plt.figure(figsize=(10, 10))
    for i in range(1, 5):
        ax = fig.add_subplot(4, 1, i)
        ax.plot(states_core0[:-1, 0, i-1], 'b', lw=3)

    plt.savefig('/tmp/%s.png' % (os.path.splitext(os.path.basename(__file__))[0]))
    plt.close()
    print('End %s:run()' % (os.path.splitext(os.path.basename(__file__))[0]))

if __name__ == '__main__':
    print('Begin %s:main()' % (os.path.splitext(os.path.basename(__file__))[0]))
    start_t = timeit.default_timer()

    fnames = setup()
    run(fnames)

    print("End %s:main() , running time: %f seconds" % (os.path.splitext(os.path.basename(__file__))[0], timeit.default_timer()-start_t))


from twitterscraper import query_tweets
import datetime as dt
import pandas as pd
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from langdetect import detect
import matplotlib.pyplot as plt

analyser = SentimentIntensityAnalyzer()
begin_date = dt.date(2019,12,1)
end_date = dt.date(2020,3,18)

limit = 1000

def detector(x):
    try:
        return detect(x)
    except:
        None

tweets = query_tweets('COVID-19 or corona virus', begindate= begin_date, enddate= end_date, limit = limit)

df = pd.DataFrame(t.__dict__ for t in tweets)
df['lang'] = df['text'].apply(lambda x:detector(x))
df = df[df['lang'] == 'en']

df2 = df['text']

x = []
y = []
pos = 0
neg = 0
neut = 0
all = []
for i in range(0,len(df2)):
    x.append(i)
for num in range (0,len(df2)):
    sentence = df2.iloc[num]
    score = analyser.polarity_scores(sentence)
    com_score = score.get('compound')
    if com_score >= 0.05:
        pos+=1
        all.append(1)
    elif com_score > -0.05 and com_score <0.05:
        neut+=1
        all.append(0)
    elif com_score <= -0.05 :
        neg+=1
        all.append(-1)
    y.append(com_score)

plt.plot(x, all)
plt.xlabel('Sentence')
plt.ylabel('Score Sentiment')
plt.title('COVID-19 Sentiment Analysis')
plt.show()

print("Number of Positive Statement : ", pos)
print("Number of Negative Statement : ", neg)
print("Number of Neutral Statement : ", neut)

if pos>neg:
    print("The overall statement are POSITIVE!")
else:
    print('The overall statement are NEGATIVE...')


from random import random, randint
import sys
import matplotlib.pyplot as plt
from openpyxl import load_workbook
import unittest

retain = 0.500
random_select = 0.05
mutate = 0.001

def main(argv=None):
    if argv is None:
        argv = sys.argv

    listOfStocks = allStocks()
    numOfStocks = len(listOfStocks)

    # print(listOfStocks)

    # indiList = individual(listOfStocks, 1, numOfStocks)
    # print("indiList is ", indiList)
    # print("indiList is of length ", len(indiList))

    # popList = population(10, listOfStocks, 1, numOfStocks)
    # print("popList is ", popList)
    # print("popList is of length ", len(popList))

    # fitnessScore = fitness(indiList, 100)
    # print("fitnessScore is ", fitnessScore)

    # gradeScore = grade(popList, 100)
    # print("gradeScore is ", gradeScore)

    # evolveFunc = evolve(popList, 100, retain, random_select, mutate)
    # print("my evolveFunc is ", evolveFunc)
    # print("evolveFunc is of length ", len(evolveFunc))

    # Budget and population count
    budget = 1000
    p_count = 100

    # Create an initial population
    p = population(p_count, listOfStocks, 1, numOfStocks)

    # Record initial population grade
    fitness_history = [grade(p, budget), ]

    # Repeat for 100 generations
    for i in range(1, 100):

        # Evolve the population
        p = evolve(p, budget, retain, random_select, mutate)

        # Record grade of new population
        fitness_history.append(grade(p, budget))
        # print("Currently on generation: ", i, )

    # Print out final generation and cumulative price of stocks in final generation
    finalList = p[0]
    finalPrice = 0
    for indi in finalList:
        finalPrice = finalPrice + indi[1]

    print("p[0] is ", p[0])
    print("And final price is: ", finalPrice)
    print('\n')

    # Print out and graph fitness history
    i = 0
    xAxis = []
    for gen in fitness_history:
        i = i + 1
        xAxis.append(i)

    print("fitness_history is ", fitness_history)

    # Uncomment to see data points on graph
    # plt.plot(xAxis, fitness_history, 'ro', )

    plt.plot(xAxis, fitness_history, 'r--', )
    plt.ylabel('Fitness')
    plt.xlabel('Generation')
    plt.show()

def allStocks():
    # print("Gathering prospective stocks\n")

    ####################################################
    ## Creating excel document here and include columns
    ####################################################
    wb = load_workbook('futureStocks.xlsx')

    ####################################################
    ## Declaring the letters to be used in the writing to the excel sheet
    ####################################################

    letter = 'A'
    letter2 = 'B'
    letter3 = 'C'
    letter4 = 'E'

    ####################################################
    ## While i is not greater than number of elements find a break up title into cells.
    ####################################################

    count = 1
    stockList = []

    # Go through every stock in column A starting with A1 until the cell value is none
    while True:
        sheet = wb.get_sheet_by_name('Sheet1')
        ws = wb.active

        # Start count at 1 and iterate
        count = count + 1

        # Look at the cells in each column, using count as the row number
        stock = sheet[letter + str(count)]

        currPrice = sheet[letter2 + str(count)]

        dividendPer = sheet[letter3 + str(count)]

        fiveYearPer = sheet[letter4 + str(count)]

        if stock.value == None or currPrice.value == None or dividendPer.value == None \
                or fiveYearPer.value == None:
            break

        combinedPer = (5 * float(dividendPer.value)) + float(fiveYearPer.value)
        combinedPer = round(combinedPer, 3)

        tempPrice = currPrice.value

        if type(tempPrice) is str:
            tempPrice = tempPrice.replace("$", "")

            print("tempPrice is now ", tempPrice)

        stockList.append([stock.value, tempPrice, combinedPer])

    return stockList

#### Evolution...muahahaha
def evolve(givenPopulation, budget, retain, random_select, mutate):

    myGraded = []

    # Iterate through population and determine fitness of individuals
    # Append fitness and individual to myGraded list
    for x in givenPopulation:
        myGraded.append((fitness(x, budget), x))

    myGraded2 = []

    # Sort through population by fitness and add to new list
    for x in sorted(myGraded):
        myGraded2.append(x[1])

    # Determine index of retained list, given retain percentage
    myRetainLength = int(len(myGraded2) * retain)

    # Keep percentage of fittest individuals
    myParents = myGraded2[:myRetainLength]

    # Randomly add other individuals from the culled list to promote genetic diversity
    for x in myGraded2[myRetainLength:]:

        randomNum = random()

        # Everytime the random number is less than the random_select variable, add individual
        if random_select > randomNum:
            myParents.append(x)

    # Mutate some individuals in the parent list
    for x in myParents:
        randomNum2 = random()

        # Every time the random number generated is less than the mutate percentage, replace
        # one of the stocks in that parent individual with a random stock
        if mutate > randomNum2:
            pos_to_mutate = randint(0, len(x) - 1)
            listOfStocks = allStocks()
            x[pos_to_mutate] = listOfStocks[randint(0, len(listOfStocks) - 1)]

    # Refill population given surviving parents
    parents_length = len(myParents)
    desired_length = len(givenPopulation) - parents_length
    children = []

    # Breed parents to create children
    while len(children) < desired_length:

        # Choose two parents
        parent1 = randint(0, parents_length - 1)
        parent2 = randint(0, parents_length - 1)

        # Make sure they are not the same parent
        if parent1 != parent2:
            parent1 = myParents[parent1]
            parent2 = myParents[parent2]

            # Create a child by adding the second half of the first parent and the first half
            # of the second parent
            half = len(parent1) / 2
            child = parent1[:int(half)] + parent2[int(half):]
            children.append(child)

    # Add children to parents and return the population of the next generation
    myParents.extend(children)
    return myParents

#### Given a population list of individual lists and a budget,
#### this computes the fitness of each individual in the population and sums these together.
#### Returns the average of the sum of fitness scores
def grade(givenPopulation, budget):

    mySummed = 0

    for x in givenPopulation:
        tempFitness = fitness(x, budget)
        mySummed = tempFitness + mySummed

    return mySummed / len(givenPopulation)

#### Given an individual list and a budget
#### Returns the sum of the individual list subtracted from the target sum
def fitness(givenIndividual, budget):

    totalPrice = 0
    totalPercent = 0
    numberOfStocks = len(givenIndividual)

    for stocks in givenIndividual:
        totalPrice = totalPrice + float(stocks[1])
        totalPercent = totalPercent + float(stocks[2])

    fitnessLvl = abs(budget - totalPrice - numberOfStocks - totalPercent)

    return fitnessLvl

#### Population of individual lists, count is number of individual lists.
####  Returns a list of individual lists
def population(count, stockList, minLen, maxLen):
    # Create a number of individuals (i.e. a population).
    #
    # count: the number of individuals in the population
    # stockList: list of all stocks
    # minLen: the minimum length of an individual list
    # maxLen: the maximum length of an individual list

    tempPop = []

    for x in range(count):
        tempPop.append(individual(stockList, minLen, maxLen))

    return tempPop

#### Individual list of random stocks
#### Returns list of stocks, picked from all stocks, with a length in the range between min to max.
def individual(stockList, minLen, maxLen):

    tempIndi = []

    length = randint(minLen, maxLen)
    for x in range(length):
        tempIndi.append(stockList[randint(1, (len(stockList) - 1))])

    return tempIndi

if __name__ == '__main__':
    main()