import os
import logging
import argparse
from tqdm import tqdm
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
from skimage import io
import glob
from pathlib import Path

import torch
from torchvision import transforms
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from torch.optim import Adam

def make_savedirs(root):
    savepath = []
    for i in range(10):
        savepath.append(os.path.join(root, f"{i:02}-{i+1:02}"))
        os.makedirs(savepath[i], exist_ok=True)
        pass
    return savepath

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def generate_cmap(colors):
    """自分で定義したカラーマップを返す"""
    values = range(len(colors))

    vmax = np.ceil(np.max(values))
    color_list = []
    for v, c in zip(values, colors):
        color_list.append( ( v/ vmax, c) )
    return LinearSegmentedColormap.from_list('custom_cmap', color_list)

def select_color(input, cm):
    assert all((0 < input) & (input < 1)), "input in (0, 1)"

    return list(map(lambda x: cm(int(x*255)), input))

def make_patch_bound(peak, img, r):
    xmin, xmax, ymin, ymax = peak[0]-r, peak[0]+r+1, peak[1]-r, peak[1]+r+1
    if peak[0] < r:
        xmin = 0
        xmax = 2*r+1
    elif peak[0] > img.shape[0] - 1 - r:
        xmax = img.shape[0]
        xmin = img.shape[0] - (2*r+1)
    if peak[1] < r:
        ymin = 0
        ymax = 2*r+1
    elif peak[1] > img.shape[1] - 1 - r:
        ymax = img.shape[1]
        ymin = img.shape[0] - (2*r+1)
    return int(xmin), int(xmax), int(ymin), int(ymax)

def plot_patch(frame, peak, image, value, label, patch, r, color):
    left, right, top, bottom = make_patch_bound(peak[[1, 0]], image, r)
    # PU = "P" if label == 1 else "U"
    if label == 1: PUN = "PP"
    elif label == 0: PUN = "UP"
    elif label == -1: PUN = "UN"
    fig = plt.figure(figsize=(15, 10))
    ax = fig.add_subplot(1, 2, 1)
    plt.imshow(image)
    plt.gray()
    plt.axis("off")
    rect = patches.Rectangle((left, top), right - left, bottom - top, linewidth=1, edgecolor=color, facecolor='none')
    ax.add_patch(rect)

    if image.shape[0]/2 < peak[1]:
        tx, ha = right, "right"
    else:
        tx, ha = left, "left"
    if image.shape[1]/2 < peak[0]:
        ty, va = top, "bottom"
    else:
        ty, va = bottom, "top"

    bbox_props = dict(boxstyle="square,pad=0", linewidth=1, facecolor=color, edgecolor=color)
    text = f"frame{frame:02}:{value:.6f}, " + PUN
    ax.text(tx, ty, text, ha=ha, va=va, rotation=0, size=10, bbox=bbox_props)

    ax = fig.add_subplot(1, 2, 2)
    plt.imshow(patch)
    plt.gray()
    plt.axis("off")

    plt.subplots_adjust(0, 0, 1, 1, 0, 0)

    # plt.show()

    value = int(value*10)
    save_path_vector = os.path.join(savepaths[value], f"check-id{id:04}.png")
    plt.savefig(save_path_vector, bbox_inches = 'tight', pad_inches = 0, dpi=300)

    plt.close()

def plot_image(frame, peak, image, value, label, color):
    peak_PP = np.array([p for i, p in enumerate(peak) if label[i] == 1])
    peak_UP = np.array([p for i, p in enumerate(peak) if label[i] == 0])
    peak_UN = np.array([p for i, p in enumerate(peak) if label[i] == -1])
    value_PP = [v for i, v in enumerate(value) if label[i] == 1]
    value_UP = [v for i, v in enumerate(value) if label[i] == 0]
    value_UN = [v for i, v in enumerate(value) if label[i] == -1]

    fig = plt.figure(figsize=(15, 10))
    ax = fig.add_subplot(1, 1, 1)
    plt.imshow(image)
    plt.gray()
    plt.axis("off")

    ax.scatter(peak_PP[:, 1], peak_PP[:, 0], marker="*", c=value_PP, cmap=cm, vmin=0, vmax=1, label="PP")
    ax.scatter(peak_UP[:, 1], peak_UP[:, 0], marker=".", c=value_UP, cmap=cm, vmin=0, vmax=1, label="UP")
    sc = ax.scatter(peak_UN[:, 1], peak_UN[:, 0], marker="x", c=value_UN, cmap=cm, vmin=0, vmax=1, label="UN")
    fig.colorbar(sc)

    # plt.subplots_adjust(0, 0, 1, 1, 0, 0)
    plt.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0), borderaxespad=0.)

    # plt.show()

    save_path_vector = os.path.join(savepath_image, f"check-f{frame:02}.png")
    plt.savefig(save_path_vector, bbox_inches = 'tight', pad_inches = 0, dpi=300)

    plt.close()

def plot_hist(value, label):
    fig = plt.figure(figsize=(15, 10))
    ax = fig.add_subplot(1, 1, 1)

    PP_value = value[label == 1]
    UP_value = value[label == 0]
    UN_value = value[label == -1]

    plt.hist([PP_value, UP_value, UN_value], color=["red", "purple", "blue"], label=["PP", "UP", "UN"],
            bins=20, range=(0, 1), log=True, rwidth=0.9, align="mid", stacked=True)
    # plt.hist(value, bins=10, range=(0, 1), log=True, rwidth=0.9, align="mid")
    # plt.subplots_adjust(0, 0, 1, 1, 0, 0)
    plt.legend(loc='upper right')
    plt.title(f"range(0 - 1) prior = {prior}")

    # plt.show()

    save_path_vector = os.path.join(savepath, f"check_hist.png")
    plt.savefig(save_path_vector, bbox_inches = 'tight', pad_inches = 0, dpi=300)

    plt.close()

def plot_hist_highlow(value, label):

    # PP_value = value_tmp[label_tmp == 1]
    UP_value = value[label == 0]
    UN_value = value[label == -1]

    U_min = int(value[label != 1].min() * 100) / 100
    U_min100 = int(value[label != 1][value[label != 1].argsort()[100]] * 100) / 100 + 0.01

    plt.hist([UP_value, UN_value], color=["red", "blue"], label=["UP", "UN"],
            bins=20, range=(U_min, U_min100), rwidth=0.9, align="mid", stacked=True)
    plt.legend(loc='upper left')
    plt.title(f"range({U_min} - {U_min100}) prior = {prior}")

    save_path_vector = os.path.join(savepath, f"check_hist_low.png")
    plt.savefig(save_path_vector, bbox_inches = 'tight', pad_inches = 0, dpi=300)

    plt.close()

    U_max = int(value[label != 1].max() * 100) / 100 + 0.01
    U_max100 = int(value[label != 1][value[label != 1].argsort()[-100]] * 100) / 100

    plt.hist([UP_value, UN_value], color=["red", "blue"], label=["UP", "UN"],
            bins=20, range=(U_max100, U_max), rwidth=0.9, align="mid", stacked=True)
    plt.legend(loc='upper left')
    plt.title(f"range({U_max100} - {U_max}) prior = {prior}")

    save_path_vector = os.path.join(savepath, f"check_hist_high.png")
    plt.savefig(save_path_vector, bbox_inches = 'tight', pad_inches = 0, dpi=300)

    plt.close()

peak_path = "/home/fujii/hdd/BF-C2DL-HSC/02/train_data/precheck1/peak"
image_path = "/home/fujii/hdd/BF-C2DL-HSC/02/train_data/cellimage"
label_PU_path = "/home/fujii/hdd/BF-C2DL-HSC/02/train_data/precheck1/patch/label.txt"
label_PN_path = "/home/fujii/hdd/BF-C2DL-HSC/02/train_data/precheck1/patch/label-allGT.txt"
patch_path = "/home/fujii/hdd/BF-C2DL-HSC/02/train_data/precheck1/patch/patch-r13.npz"
check_num = 20
prior = 0.975

predict_path = f"/home/fujii/hdd/BF-C2DL-HSC/02/train_data/precheck1/PU-learning/checks/check{check_num}/predict.txt"
savepath = f"/home/fujii/hdd/BF-C2DL-HSC/02/train_data/precheck1/PU-learning/checks/check{check_num}"
savepath_image = os.path.join(savepath, "image_plot")
savepath_patch = os.path.join(savepath, "patch_plot")
os.makedirs(savepath, exist_ok=True)
os.makedirs(savepath_image, exist_ok=True)
os.makedirs(savepath_patch, exist_ok=True)
savepaths = make_savedirs(savepath_patch)

peak_files = sorted(Path(peak_path).glob("*.txt"))
image_files = sorted(Path(image_path).glob("*.tif"))
predict = np.loadtxt(predict_path)
label_PU = np.loadtxt(label_PU_path)
label_PN = np.loadtxt(label_PN_path)
label = (label_PU + label_PN) / 2  #PP = 1, UP = 0, UN = -1
patch = io.imread(patch_path)

value = sigmoid(predict)

cm = generate_cmap(["blue", "red"])
color = select_color(value, cm)

plot_hist(value, label)
plot_hist_highlow(value, label)

r = 13
id = 0
with tqdm(total=len(peak_files), leave=False, position=0) as pbar0:
    for frame, (fn) in enumerate(zip(peak_files, image_files)):
        pbar0.set_description(f"frame:{frame:02}")
        pbar0.update(1)

        peaks = np.loadtxt(str(fn[0]))
        image = io.imread(str(fn[1]))

        val = value[id:id+peaks.shape[0]]
        lab = label[id:id+peaks.shape[0]]
        col = color[id:id+peaks.shape[0]]
        plot_image(frame, peaks, image, val, lab, col)

        with tqdm(total=peaks.shape[0], leave=False, position=1) as pbar1:
            for cell, peak in enumerate(peaks):
                pbar1.set_description(f"cell:{cell:03}")
                pbar1.update(1)
                plot_patch(frame, peak, image, value[id], label[id], patch[id], r, color[id])

                id += 1
                pass
        pass


import tensorflow as tf
import numpy as np
import cv2
import os
import matplotlib.pyplot as plt
from tensorflow.keras.models import load_model
from src import constants
from COCO_utils import process_data_utils

def show_train_set_and_gt(model, path):
    data, masks = process_data_utils.read_h5(path)
    predicted_ = model.predict(data[0:100])

    for i, mask in enumerate(predicted_):
        mask = np.argmax(mask, axis=-1)
        plt.imshow(mask)
        plt.show()

def evaluate_single(model, path):
    valid_files = os.listdir(path)
    data_arr = np.zeros((len(valid_files), constants.HEIGHT, constants.WIDTH, constants.CHANNELS), dtype=np.float64)

    for i, f in enumerate(valid_files):
        print(f)
        f = os.path.join(path, f)

        img = cv2.imread(f)
        data_arr[i] = cv2.resize(img, (constants.HEIGHT, constants.WIDTH))

        predicted_results = model.predict(data_arr)
        result_decode = np.argmax(predicted_results[i], axis=-1)
        print(result_decode)

        plt.figure(f)
        plt.imshow(result_decode)
        plt.show()

if __name__ == '__main__':
    model_path = '../model/basic_U_net_model/202007281101.h5'

    #
    valid_path = r'E:\extracted_data\COCO\images\val2017'

    train_path = '../data/train_car_truck_bus_128_128.h5'

    model = load_model(model_path)

    model.summary()

    # evaluate one by one
    # evaluate_single(model, valid_path)

    # test evaluate on training set
    show_train_set_and_gt(model, train_path)


# This class will determine what action to take, and keep track of winrates/games

# Each node has a gamestate, number of games ran, and winrate from that node

from allmoves import ALLMOVES
from multiset import FrozenMultiset as fms
import random
import copy
import math
import pickle
import torch
import os
from transformer import Transformer
from bot import NeuralNetwork
from mycopy import trueCopy
import _pickle as cPickle

import sys
#sys.path.insert(0, './botModels/')
sys.path.insert(0, './..')
from amulet import Amulet

def setCurrNN(mct, currOrNew = "curr"):
    mct.currNN = NeuralNetwork()
    if (currOrNew == "new"):
        dire = "./AI/botModels/nextbot.bot"
    else:
        dire = "./AI/botModels/currbot.bot"
    temp1 = torch.load(dire, map_location=torch.device('cpu'))
    mct.currNN.load_state_dict(temp1)
    mct.currNN.eval()

def moveCmp(item):
    #print(item)
    if (item[0][0] == 4):
        return 100000
    val1 = 100*item[0][0]
    val1 += 10*item[0][1][0]
    if (len(item[0][1]) > 1):
        val1 += (item[0][1][1] + 2)
    return val1

class AZMCTS():
    def __init__(self, gameState, head=None):
        self.gameState = gameState
        self.moveArr = []
        self.totalSims = 0
        self.exploreParam = 1.4
        self.head = head
        self.mask = 0
        self.currNN = 0
        self.transformer = 0
        self.val = 0
        self.truePath = 0
        self.hashtable = {}
        moves = gameState.generateLegalMoves()

        self.children = []

        rollIndex = 0
        # each element of moveArr is [move, childIndex, timesTaken, totalValue, meanValue, moveProb (according to NN),
        #                             move indices (for training)]
        for ele in moves:
            #FOR V2
            if ele[0] == 4:
                self.moveArr.append([ele,rollIndex, 0, 0., 0., 1/max(1,len(moves)-1)])
            else:
                self.moveArr.append([ele, rollIndex, 0, 0., 0., 0.])
            self.children.append(0)
            rollIndex += 1

    # the moveProbs are generated when the node is created during tree descent, but this doesnt occur for the root
    # so we do it manually here
    def rootInit(self, hashtable, new = "curr"):
        self.transformer = Transformer()
        nnInput = self.transformer.gameDataToNN(self.gameState)
        nnInput = nnInput.unsqueeze(dim=0)

        setCurrNN(self, new)
        logits = self.currNN(nnInput)[0]
        val = self.currNN(nnInput)[1]
        self.val = val
        self.head = self
        self.hashtable = hashtable
        self.truePath = 1
        #for ele in self.moveArr:
        #    ele[4] += val/4
        #print(logits)

        probabilitiesNN, mask = self.transformer.normalizedVector(logits[0], self.gameState)

        #print(mask)
        self.mask = mask
        self.setProbabilities(probabilitiesNN)

        return val

    def runSimulations(self, simulations):
        for _ in range(simulations):
            self.descendTree()
        #self.shuffleHandBoard()

    def descendTree(self):
        self.totalSims += 1

        # dont need to select action if game is over
        if self.gameState.winner != 0:
            if self.gameState.winner == self.gameState.activePlayer.playerNum:
                return 1
            else:
                return -1
        actionIndex = self.selectAction()
        #input(self.printTree())
        updateValue = self.takeAction(actionIndex, self.moveArr[actionIndex][1])
        # if the previous action was a pass, then we invert the valuation
        if self.moveArr[actionIndex][0][0] == 4:
            updateValue = -1 * updateValue

        # update the action info
        self.moveArr[actionIndex][2] += 1
        self.moveArr[actionIndex][3] += updateValue
        self.moveArr[actionIndex][4] = self.moveArr[actionIndex][3] / self.moveArr[actionIndex][2]
        return updateValue

    def selectAction(self):
        if (len(self.moveArr) == 1): #or (self.totalSims == 0):
            return 0
        currMaxIndex = 0
        currMax = -1
        currActionIndex = 0
        for ele in self.moveArr:
            currVal = ele[4] + (self.exploreParam * ele[5] * (math.sqrt(float(self.totalSims)) / (1 + float(ele[2]))))
            if currMax < currVal:
                currMax = currVal
                currMaxIndex = currActionIndex
            currActionIndex += 1
            #input("")
        return currMaxIndex

    def takeAction(self, actionIndex, childIndex):
        # We are at a leaf node, time to create a new leaf then climb, unless we are already at a game end state
        if self.gameState.winner != 0:
            if self.gameState.winner == self.gameState.activePlayer.playerNum:
                return 1
            else:
                return -1

        if (self.children[childIndex] == 0):
            #z = cPickle.loads(cPickle.dumps(self.gameState, -1))
            z = copy.deepcopy(self.gameState)
            z.initiateAction(self.moveArr[actionIndex][0])
            z.clearQueue()
            z.sortGame()
            gameStateVal = createGameStateVal(z)
            hashval = hash(gameStateVal)
            if hashval in self.hashtable:
                if z.winner != 0:
                    if z.winner == z.activePlayer.playerNum:
                        return 1
                    else:
                        return -1
                #print("PEPEGA")
                self.children[childIndex] = self.hashtable[hashval]
                #TODO: the below line is for debugging purposes. The bug atm is that even though we end up in symmetric
                #      positions, our hand order (and thus legal moves that generated at the time of creation of AZMCTS)
                #      may not be the same. Consider playing maestro -> vampy or vampy -> maestro for ex.
                #self.children[childIndex].gameState = z
                #print("PEPEGA")
                #self.hashtable[hashval].printTree()
                return self.hashtable[hashval].descendTree()

            newAZMCTS = AZMCTS(z, self.head)
            self.children[childIndex] = newAZMCTS
            self.children[childIndex].hashtable = self.hashtable
            self.children[childIndex].currNN = self.currNN
            self.children[childIndex].transformer = self.transformer
            #self.children[childIndex].gameState.printGameState()

            # game has ended
            if self.children[childIndex].gameState.winner != 0:
                if self.children[childIndex].gameState.winner == self.children[childIndex].gameState.activePlayer.playerNum:
                    return 1
                else:
                    return -1
            # game is still in progress, return NN eval
            nnInput = self.transformer.gameDataToNN(self.gameState)
            nnInput = nnInput.unsqueeze(dim=0)
            self.hashtable[hashval] = newAZMCTS

            logits = self.currNN(nnInput)
            logitsProb = logits[0][0]
            logitsValuation = logits[1][0]
            #for ele in self.children[childIndex].moveArr:
            #    ele[4] += logitsValuation/4

            probabilitiesNN, mask = self.transformer.normalizedVector(logitsProb, self.children[childIndex].gameState)
            self.children[childIndex].mask = mask
            self.children[childIndex].setProbabilities(probabilitiesNN)
            self.val = logitsValuation
            return logitsValuation

        return self.children[actionIndex].descendTree()

    def printTree(self):
        for ele in self.moveArr:
            bonusExploreParam = self.exploreParam * 0.01 * math.sqrt(1+float(self.totalSims)) / (1+float(ele[2]))
            currVal = ele[4] + (self.exploreParam * ele[5] * (math.sqrt(1 + float(self.totalSims)) / (1 + float(ele[2]))))
            currVal += bonusExploreParam
            print(ele)
            print(currVal)
            print(self.totalSims)

    def setProbabilities(self, probabilities):
        #this happens in V2 when pass action is the only action
        #if (len(probabilities) == 0):
        #    return
        currIndex = 0
        for ele in self.moveArr:
            if (ele[0] == [4]):
                continue
            ele[5] = probabilities[currIndex]
            currIndex += 1
        #moveInd = 0
        #allMoveInd = 0
        #while (moveInd < len(self.moveArr)):
        #    if ALLMOVES[allMoveInd] == self.moveArr[moveInd][0]:
        #        self.moveArr[moveInd][5] = probabilities[allMoveInd]
        #        moveInd += 1
        #    allMoveInd += 1

        if (self.moveArr[len(self.moveArr) - 1] == 0):
            print("ERROR")
            self.printTree()
            input(probabilities)

    def recordResults(self, result, posnum):
        self.gameState.clearQueue()
        for _ in range(10):
            self.shuffleHandBoard()

            _, mask = self.transformer.normalizedVector(0, self.gameState)
            MCTSRes = []
            for ele in self.moveArr:
                # commented out for V2
                # MCTSRes.append(float(ele[2]) / max(1., float(self.totalSims)))
                MCTSRes.append(float(ele[2]) / max(1., float(self.totalSims - self.moveArr[len(self.moveArr)-1][2])))

            if (result == self.gameState.activePlayer.playerNum):
                gameResult = 1
            else:
                gameResult = -1
            condensedResult = [self.transformer.gameDataToNN(self.gameState), MCTSRes, self.mask, gameResult]
            currDir = len(os.listdir("./AI/trainingData")) - 1

            with open("./AI/trainingData/trainingDataSubfolder" + str(currDir) + "/pos" + str(posnum) + ".pickle", "wb") as f:
                pickle.dump(condensedResult, f)
            posnum += 1

        for child in self.children:
            if child != None and isinstance(child,AZMCTS) and child.truePath == 1 and child.gameState.winner == 0:
                return child.recordResults(result, posnum)

    # shuffles hand and board positions to eliminate biases, changes mask and mcts array accordingly
    def shuffleHandBoard(self):
        handShuffle = list(range(len(self.gameState.activePlayer.hand)))
        random.shuffle(handShuffle)
        boardShuffle1 = list(range(len(self.gameState.board.fullBoard[0])))
        boardShuffle2 = list(range(len(self.gameState.board.fullBoard[1])))
        random.shuffle(boardShuffle1)
        random.shuffle(boardShuffle2)

        for action in self.moveArr:
            if (action[0][0] == 1):
                if (len(handShuffle) <= action[0][1][0]):
                    print(handShuffle)
                    print(action)
                    print(":)")
                    continue
                action[0][1][0] = handShuffle[action[0][1][0]]
            if (action[0][0] == 2) or (action[0][0] == 3):
                if (self.gameState.activePlayer.playerNum == 1):
                    action[0][1][0] = boardShuffle1[action[0][1][0]]
                else:
                    action[0][1][0] = boardShuffle2[action[0][1][0]]

        newHand = []
        for handIndex in range(len(self.gameState.activePlayer.hand)):
            for i in range(len(self.gameState.activePlayer.hand)):
                if (handShuffle[i] == handIndex):
                    newHand.append(self.gameState.activePlayer.hand[i])

        newBoardp1 = []
        for boardIndex in range(len(self.gameState.board.fullBoard[0])):
            for i in range(len(self.gameState.board.fullBoard[0])):
                if (boardShuffle1[i] == boardIndex):
                    newBoardp1.append(self.gameState.board.fullBoard[0][i])

        newBoardp2 = []
        for boardIndex in range(len(self.gameState.board.fullBoard[1])):
            for i in range(len(self.gameState.board.fullBoard[1])):
                if (boardShuffle2[i] == boardIndex):
                    newBoardp2.append(self.gameState.board.fullBoard[1][i])

        self.gameState.board.player1side = newBoardp1
        self.gameState.board.player2side = newBoardp2
        self.gameState.board.updateFullBoard()
        self.gameState.activePlayer.hand = newHand
        self.moveArr.sort(key=moveCmp)

    def cleanTreeExceptAction(self, action):
        for move in self.moveArr:
            if move[0] != action:
                if (self.children[move[1]] != 0):
                    self.children[move[1]].cleanTree()
                    self.children[move[1]] = None

    def cleanTree(self):
        for child in self.children:
            if child != 0:
                child.cleanTree()
                child = None

def createGameStateVal(gameState):
    board1 = []
    board2 = []
    currPlayer = gameState.activePlayer
    if (currPlayer.playerNum == 1):
        enemyPlayer = gameState.player2
    else:
        enemyPlayer = gameState.player1
    for ele in gameState.board.fullBoard[0]:
        if (isinstance(ele, Amulet)):
            board1.append((ele.encoding, ele.countdown))
        else:
            board1.append((ele.encoding, ele.currHP, ele.currAttack, ele.hasBane, ele.canAttack, ele.hasWard))
    for ele in gameState.board.fullBoard[1]:
        if (isinstance(ele,Amulet)):
            board2.append((ele.encoding, ele.countdown))
        else:
            board2.append((ele.encoding, ele.currHP, ele.currAttack, ele.hasBane, ele.canAttack, ele.hasWard))

    activedeck = []
    for ele in gameState.activePlayer.deck.cards:
        activedeck.append(ele.encoding)
    for ele in enemyPlayer.deck.cards:
        activedeck.append(ele.encoding)
    index = 0
    for ele in gameState.activePlayer.hand:
        activedeck.append((ele.encoding, index))
        index += 1
    index = 0
    for ele in enemyPlayer.hand:
        activedeck.append((ele.encoding, index))
        index += 1

    board1 = fms(board1)
    board2 = fms(board2)
    activedeck = tuple(activedeck)

    return (currPlayer.currHP, enemyPlayer.currHP, len(currPlayer.hand), len(enemyPlayer.hand), enemyPlayer.currEvos, currPlayer.currEvos, currPlayer.currPP, board1, board2, 3*gameState.currTurn+currPlayer.playerNum, activedeck, len(currPlayer.leaderEffects.turnEndEffects), len(enemyPlayer.leaderEffects.turnEndEffects))


import cv2
import pytesseract

from image_gw_api.cascade_classifiers import DEFAULT_CLASSIFIER
import numpy as np

pytesseract.pytesseract.tesseract_cmd = r"/usr/local/Cellar/tesseract/4.1.1/bin/tesseract"

class ImageProcessor:

    def __init__(self, image):
        self.image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        self.car_plate_cascade_classifier = DEFAULT_CLASSIFIER
        self.car_plate = None

    def _extract_car_plate(self):
        car_plate_rects = self.car_plate_cascade_classifier.detectMultiScale(
            self.image, scaleFactor=1.1, minNeighbors=5
        )
        car_plate_img = None

        for x, y, w, h in car_plate_rects:
            car_plate_img = self.image[y + 15:y + h - 10, x + 15:x + w - 20]

        return car_plate_img

    @staticmethod
    def _enlarge_img(image, scale_percent):
        width = int(image.shape[1] * scale_percent / 100)
        height = int(image.shape[0] * scale_percent / 100)
        dim = (width, height)
        resized_image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
        return resized_image

    def process_image(self):
        car_plate_img = self._enlarge_img(self._extract_car_plate(), 150)
        car_plate_gray = cv2.cvtColor(car_plate_img, cv2.COLOR_RGB2GRAY)
        blurred_car_plate = cv2.medianBlur(car_plate_gray, 3)

        binary_image = cv2.threshold(blurred_car_plate, 130, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
        inverted_bin = cv2.bitwise_not(binary_image)

        kernel = np.ones((2, 2), np.uint8)
        processed_img = cv2.erode(inverted_bin, kernel, iterations=1)
        processed_img = cv2.dilate(processed_img, kernel, iterations=1)

        self.car_plate = pytesseract.image_to_string(
            processed_img, config=f'--psm 8 --oem 3 -c tessedit_char_whitelist=0123456789ЙЦУКЕНГШЩЗХЇФІВАПРОЛДЖЯЧСМИТЬ'
                                  f'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        ).rstrip("\n\f")

        return self.car_plate


from Final import climate
from Final import precip_amount
from Final import train_data, train_labels, test_data, test_labels
import pandas as pd
import numpy as np

import time
import datetime as dt

import sklearn as sk
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.experimental import enable_halving_search_cv
from sklearn.model_selection import HalvingGridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

'''
#We need to convert our labels to someting RandomForestClassifier can understand.
# It does not understand continuious, so while I could convert it to an int, I dont
# think that is statistically the best way to do that. Sklearn as a preprocessing
# model for label encoding, which I used below to relabel the labels into something
# it understands and can read in on.
'''

# rf_labels = le.fit_transform(rf_labels)

RFC = RandomForestClassifier(verbose = 0, warm_start = False, max_features = None,
                             max_depth = None, criterion = 'gini',
                             min_samples_split = 35, n_estimators = 80)

# Beautiful, so I got my best parameters from the grid search, you can see the
# best parameters in the RFC call. Lets fit it now.

# parameters = {'n_estimators': [50, 100, 150, 200],
#               'max_depth': [None, 25, 50, 100],
#               'max_features': [None, 4, 6, 8, 10],
#               'min_samples_split': [2, 4, 10, 25, 75, 125, 150, 200],
#               'criterion': ['gini']
#               }

# I JUST found out about halving grid search which gives as good or  better
# results quicker, so we are DEFINITELY going to use this from now on.

# grid = HalvingGridSearchCV(RFC, parameters)
# results = grid.fit(train_data, train_labels)
# print(results.best_params_)
# print(results.best_estimator_)
# print(results.best_score_)

# print(climate.head())
RFC.fit(train_data, train_labels)
score = RFC.score(test_data, test_labels)
# print(score)

# Lets give it a shot to see it it will predict a past date correctly.
avg_max_temp_july = climate.loc[climate.month == 7]\
    .loc[climate.year == 1996].max_temp.mean()
avg_min_temp_july = climate.loc[climate.month == 7]\
    .loc[climate.year == 1996].min_temp.mean()
pred_x = np.array([1996, 7, 29, avg_max_temp_july, avg_min_temp_july]).reshape(1, -1)

# print(climate.loc[climate.month == 7].loc[climate.year == 1996]\
    # .loc[climate.day == 29])
# print(RFC.predict(pred_x))
# print(RFC.predict_proba(pred_x))

# Now lets try a future date, but lets build a function for it
# (and also a fun printout).
def rf_predict(df, year, month, day):
    avg_max_temp = df.loc[df.month == month].loc[df.day == day].max_temp.mean()
    avg_min_temp = df.loc[df.month == month].loc[df.day == day].min_temp.mean()
    pred_x = np.array([year, month, day, avg_max_temp, avg_min_temp]).reshape(1, -1)
    return pred_x
pred_x = rf_predict(climate, 2022, 5, 28)

date = [int(pred_x[0][1]), int(pred_x[0][2]), int(pred_x[0][0])]

prediction = RFC.predict(pred_x)
probability = RFC.predict_proba(pred_x)

# print(prediction)
# print(probability)
proba_of_rain = round(probability[0][1], 2) * 100
if prediction == 1:
    print(f'On {date[0]}-{date[1]}-{date[2]}:\nI predict it will rain!')
    print(f'There is a {proba_of_rain} percent chance of rain!')
else:
    print(f'On {date[0]}-{date[1]}-{date[2]}:\nI do not think it will rain!')
    print(f'There is a {proba_of_rain} percent chance of rain!')

'''
This model predict there was a 58 %\ chance it did rain and a 41%\ chance it did not
rain on July 29th, 1996 (as requested by my friend for the day he was born).
Historical records show that it DID in fact rain on that day, therefore we can
say the the model predicted correctly that it rained.

For the future prediction, the model is predicting that it has a 76 %\ chance
of not raining and a 24 %\ chance of raining tomorrow (at the time of writing),
and weather data for tomorrow shows that there is a 24%\ chance of rain. For the
day after tomorrow, it is showing there is a 80.2%\ chance of not raining and a
19.8%\ chance of raining. The Weather Channel shows there is an 18%\ chance of
raining. That is about 2%\ off of what the Weather Channel states it will be.

So it looks like the RFC has a 75%\ likelihood that it is correct, based on the raw
score of the model. I want to try and also fit a Random Forest Regressor,
so I am going to do that below with the
same steps as above. I will have to change the labels because the regressor
runs on a quantative basis, so it needs all numbers instead of a bool.
'''

climate['raw_precip'] = precip_amount
# print(climate.head())
# print(climate.raw_precip.unique())
climate.raw_precip.fillna(climate.raw_precip.mean())

features = climate[['year', 'month', 'day', 'max_temp', 'min_temp']].to_numpy()
labels = climate['raw_precip'].to_numpy().reshape(-1, 1)

minmax = MinMaxScaler()
labels = minmax.fit_transform(labels)

train_data, test_data,\
train_labels, test_labels = train_test_split(features, labels, test_size = 0.2)

RFR = RandomForestRegressor(verbose = 1, warm_start = True,
                            criterion = 'absolute_error', random_state = 11,
                            bootstrap = True)

# RFR.fit(train_data, train_labels)
# score = RFR.score(test_data, test_labels)
# print(score)

# parameters = {'max_depth': [None],
#               'min_samples_split': [None],
#               'max_features': [None, 1],
#               'n_estimators': [100]}

# grid = HalvingGridSearchCV(RFR, parameters)
# results = grid.fit(train_data, train_labels)
# score = grid.score(test_data, test_labels)
# print(score)
# print(results.best_params_)
# print(results.best_score_)


import base64
import zlib

import numpy as np
from pycocotools import _mask as coco_mask

def encode_binary_mask(mask: np.ndarray) -> str:
    """Converts a binary mask into OID challenge encoding ascii text.

    The original implemantation is below.
    https://gist.github.com/pculliton/209398a2a52867580c6103e25e55d93c
    """

    # check input mask --
    if mask.dtype != np.bool8:
        raise ValueError("encode_binary_mask expects a binary mask, received dtype == %s" % mask.dtype)

    mask = np.squeeze(mask)
    if len(mask.shape) != 2:
        raise ValueError("encode_binary_mask expects a 2d mask, received shape == %s" % mask.shape)

    # convert input mask to expected COCO API input --
    mask_to_encode = mask.reshape(mask.shape[0], mask.shape[1], 1)
    mask_to_encode = mask_to_encode.astype(np.uint8)
    mask_to_encode = np.asfortranarray(mask_to_encode)

    # RLE encode mask --
    encoded_mask = coco_mask.encode(mask_to_encode)[0]["counts"]

    # compress and base64 encoding --
    binary_str = zlib.compress(encoded_mask, zlib.Z_BEST_COMPRESSION)
    base64_str = base64.b64encode(binary_str)
    return base64_str.decode()


from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)

from hbdeal.services import deal_service
from hbdeal.core.models.deal import User
from hbdeal.core.hb_api import HBEmptyApiTokenError

bp = Blueprint('deals', __name__, url_prefix='/deals')

@bp.route('/<user_id>', methods=('GET',))
def user_deal_list(user_id):
    user = deal_service.get_user(user_id)
    deals = deal_service.get_user_deals(user)

    return render_template('deals_list.html', user=user, deals=deals)

@bp.route('/<user_id>/update', methods=('GET',))
def user_deals_update(user_id):
    user = deal_service.get_user(user_id)
    try:
        deals = deal_service.update_last_deals(user)
    except HBEmptyApiTokenError:
        # If User has not a TOKEN it will redirected to get a new token from Hubspot
        return redirect(deal_service.get_user_hb_api_auth_url(user))

    return redirect("/deals/{}".format(user.id))


from linebot.models import (
    TemplateSendMessage, ConfirmTemplate, PostbackTemplateAction,
)

def confirm(cat, i, DB):
    questions = DB.get_category(cat)
    #这里i 不用 -= 1 是因为data[userid][cat]是从 0开始计算
    return   TemplateSendMessage(
                alt_text='Confirm template',
                template=ConfirmTemplate(
                    text = str(questions[i][2]) + ' Q' + str(questions[i][3]) + ' : ' + questions[i][1],
                    actions=[
                        PostbackTemplateAction(
                            label='没问题',
                            text=str(questions[i][2]) + ' 第' + str(questions[i][3]) + '题已回复没问题',  #给使用者看相对题号
                            data='cat=%s&no=%d&answer=OK' % (questions[i][2], questions[i][3]) #questions是整份问卷第几题 绝对题号
                        ),
                        PostbackTemplateAction(
                            label='待改进',
                            text=str(questions[i][2]) + ' 第' + str(questions[i][3]) + '题已回复待改进', #给使用者看相对题号
                            data='cat=%s&no=%d&answer=NO' % (questions[i][2], questions[i][3])
                        )
                    ]
                ))

    # 功能：从DB抓问题，编织成confirm tempate
    # 输入：1.cat ： 类别
    #      2. i  ： 相对题号
    # 输出：ConfirmTemplate with question


import speech_recognition as sr
import pyaudio
p = pyaudio.PyAudio()

# Initialize the recognizer
r = sr.Recognizer()

for i in range(p.get_device_count()):
    dev = p.get_device_info_by_index(i)
    if dev['maxInputChannels'] > 0:
        print('Found microphone: {} {}'.format(i, dev['name']))

# Function to convert text to
# speech
def SpeakText(command):
    pass
    # Initialize the engine
    #import pyttsx3
    #engine = pyttsx3.init()
    #engine.say(command)
    #engine.runAndWait()

while True:
    try:

        # use the microphone as source for input.
        with sr.Microphone(device_index=1) as source2:

            # wait for a second to let the recognizer
            # adjust the energy threshold based on
            # the surrounding noise level
            r.adjust_for_ambient_noise(source2, duration=0.2)

            #listens for the user's input
            audio2 = r.listen(source2)

            # Using google to recognize audio
            MyText = r.recognize_google(audio2, language="ZH")
            MyText = MyText.lower()

            print("Did you say ",MyText)
            #SpeakText(MyText)

    except sr.RequestError as e:
        print("Could not request results; {0}".format(e))

    except sr.UnknownValueError:
        print("unknown error occurred")


#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import datetime
from collections import Counter

def arguments():
    # Handle command line arguments
    parser = argparse.ArgumentParser(description='Adventofcode.')
    parser.add_argument('-f', '--file', required=True)

    args = parser.parse_args()

    return args

class Guard: # pylint: disable=too-few-public-methods, too-many-instance-attributes
    guards_dict = {}

    def __init__(self, name):
        self.name = name
        self.sleep_schedule = []
        self.time_asleep = 0
        Guard.guards_dict[name] = self
        self.minutes_asleep = []
        self.most_minutes_asleep = None
        self.most_common_minute_sleeping = None
        self.part1_result = None
        self.part2_result = None

    def log_sleep_schedule(self, schedule):
        self.sleep_schedule.append(schedule)

    def calculate_sleep(self):
        datetime_format = '%H:%M'
        last_falling_asleep = None
        for minutes in self.sleep_schedule:
            if "falls asleep" in minutes:
                last_falling_asleep = minutes[12:17]
            elif "wakes up" in minutes:
                time_sleeping = datetime.datetime.strptime(minutes[12:17], datetime_format) - datetime.datetime.strptime(last_falling_asleep, datetime_format)
                self.time_asleep = self.time_asleep + time_sleeping.seconds

                sleep_dt = datetime.datetime.strptime(last_falling_asleep, datetime_format)
                wake_dt = datetime.datetime.strptime(minutes[12:17], datetime_format)
                for specific_minute in range(sleep_dt.minute, wake_dt.minute):
                    self.minutes_asleep.append(specific_minute)
        if self.minutes_asleep == []:
            self.minutes_asleep = [0, 0]

        self.minutes_asleep = Counter(self.minutes_asleep)
        self.most_minutes_asleep = self.minutes_asleep.most_common()[0][0]
        self.most_common_minute_sleeping = self.minutes_asleep.most_common()[0]

    def calculate_part1_result(self):
        self.part1_result = int(self.name[1:]) * self.most_minutes_asleep

    def calculate_part2_result(self):
        self.part2_result = int(self.name[1:]) * self.most_common_minute_sleeping[0]

def main():
    args = arguments()

    with open(args.file) as file:
        input_file = file.read().strip().splitlines()
    sorted_schedule = (sorted(input_file))

    #part1
    guards = []
    guard_id = -1
    for row in sorted_schedule:
        if row.split()[3] in Guard.guards_dict:
            guard = Guard.guards_dict[row.split()[3]]
            guard.log_sleep_schedule(row)
        else:
            if guard_id != row.split()[3]:
                if "Guard" in row:
                    guard_id = row.split()[3]
                    guard = Guard(guard_id)
                    guards.append(guard)
                else:
                    guard.log_sleep_schedule(row)

    time_asleep = -1
    times_asleep_per_minute = -1
    for row in guards:
        row.calculate_sleep()
        #part1
        if row.time_asleep > time_asleep:
            time_asleep = row.time_asleep
            most_sleepy_guard = row
        #part2
        if row.most_common_minute_sleeping[1] > times_asleep_per_minute:
            times_asleep_per_minute = row.most_common_minute_sleeping[1]
            most_sleepy_guard_part2 = row

    most_sleepy_guard.calculate_part1_result()
    most_sleepy_guard_part2.calculate_part2_result()

    print("part1 result:", most_sleepy_guard.part1_result)
    print("part2 result:", most_sleepy_guard_part2.part2_result)

if __name__ == '__main__':
    main()


from flask import Flask
from flask_restful import Api
from resources.tracker import Tracker, TrackerCount, TrackerInsert

app = Flask(__name__)
api = Api(app)

api.add_resource(Tracker, '/tracker')
api.add_resource(TrackerCount, '/tracker/count')
api.add_resource(TrackerInsert, '/tracker/insert')

if __name__ == '__main__':
    app.run(port=3000, debug=True)


import math

def binary_con(opt, value):
    '''
    @param opt: 'bd' or 'db', binary to decimal or decimal to binary
    @param value: the value to be converted, integer
    @return: the converted value

    example binary_con('bd', 1001) should return 9 as int value, and binary_con('db', 8) should return 1000 as int.
    '''
    ...
    #Error handling
    if opt.upper() != "BD" and opt.upper() != "DB":
        return "error 404"
    try: int(value)
    except ValueError:
        return "error 404"
    if value < 0:
        return "error 404"
    # Calulation
    result = []
    if opt.upper() == "DB":
        n = int(bin(value)[2:])
        return n
    elif opt.upper()== "BD":
        string = str(value)
        length = len(string)
        for i in str(value):
            str2 = int(i)
            re = str2 * (2**(length-1))
            result.append(re)
            length -= 1
        return sum(result)

print(binary_con("bd",101 ))


# -*- coding: utf-8 -*-
"""
Created on Thu May 14 18:55:59 2020

@author: 许继元
"""

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget

class UserCenter(QWidget):
    def __init__(self, user, num, label):
        super(UserCenter, self).__init__()  # 使用super函数可以实现子类使用父类的方法
        self.setWindowTitle("个人主页")
        self.setWindowIcon(QIcon('../Data/douban.jpg'))  # 设置窗口图标
        self.resize(500, 150)

        self.user_label = QLabel(self)
        self.num_label = QLabel(self)
        self.label_label = QLabel(self)

        self.user_label.setText("
您好!" + user + "
")
        self.num_label.setText("
您在豆瓣评论过" + num + "部电影
")
        try:
            self.label_label.setText("
您喜欢的电影类型是:" + label + "
")
        except:
            self.label_label.setText("")

        self.v_layout = QVBoxLayout()

        self.v_layout.addWidget(self.user_label)
        self.v_layout.addWidget(self.num_label)
        self.v_layout.addWidget(self.label_label)

        self.setLayout(self.v_layout)


from flask import Flask, render_template
from data import title, departures, tours, subtitle, description

app = Flask(__name__)

@app.route('/')
def render_index_html():
    tour = []
    for i in range(1, 7):
        tour.append(tours[i])
    return render_template('index.html', title_page=title, nav=departures, sub_title=subtitle, des=description, tour=tour)

@app.route('/departure/<departure>')
def render_departure(departure):
    list_departure = []
    list_tour = []
    for i in tours:
        if tours[i]['departure'] == departure:
            list_departure.append(i)
    for j in list_departure:
        list_tour.append(tours[j])
    temp_price = []
    temp_night = []
    for pn in list_tour:
        temp_price.append(pn['price'])
        temp_night.append(pn['nights'])
    description_content = []
    description_content.append(min(temp_price))
    description_content.append(max(temp_price))
    description_content.append((min(temp_night)))
    description_content.append((max(temp_night)))

    return render_template('departure.html', title_page=title, nav=departures, tour=list_tour, tour_id=list_departure, departure_id=departure, content=description_content)

@app.route('/tour/<id>/')
def render_tour(id):
    return render_template('tour.html', title_page=title, nav=departures, tour=tours[int(id)])

if __name__ == '__main__':
    app.run()


small = None
large = None
while True:
    sval = input('Please enter a number: ')
    if sval == 'done':
        break
    try:
        fval = int(sval)
    except:
        print('Invalid input')
        continue
    if small == None:
        small = fval
        large = fval
    else:
        if fval < small:
            small = fval
        elif fval > large:
            large = fval
print('Maximum is '+str(large))
print('Minimum is '+str(small))


# Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)

# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"

# try:
#     # %tensorflow_version only exists in Colab.
#     %tensorflow_version 2.x
#     IS_COLAB = True
# except Exception:
#     IS_COLAB = False

# TensorFlow ≥2.0 is required
import tensorflow as tf
from tensorflow import keras
assert tf.__version__ >= "2.0"

# if not tf.config.list_physical_devices('GPU'):
#     print("No GPU was detected. CNNs can be very slow without a GPU.")
#     if IS_COLAB:
#         print("Go to Runtime > Change runtime and select a GPU hardware accelerator.")

# Common imports
import numpy as np
import os

# to make this notebook's output stable across runs
np.random.seed(42)
tf.random.set_seed(42)

# To plot pretty figures
#%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)

# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "cnn"
IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID)
os.makedirs(IMAGES_PATH, exist_ok=True)

def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
    path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format=fig_extension, dpi=resolution)

def plot_image(image):
    plt.imshow(image, cmap="gray", interpolation="nearest")
    plt.axis("off")

def plot_color_image(image):
    plt.imshow(image, interpolation="nearest")
    plt.axis("off")

import numpy as np

(X_train_full, y_train_full), (X_test, y_test) = keras.datasets.fashion_mnist.load_data()
X_train, X_valid = X_train_full[:-5000], X_train_full[-5000:]
y_train, y_valid = y_train_full[:-5000], y_train_full[-5000:]

X_mean = X_train.mean(axis=0, keepdims=True)
X_std = X_train.std(axis=0, keepdims=True) + 1e-7
X_train = (X_train - X_mean) / X_std
X_valid = (X_valid - X_mean) / X_std
X_test = (X_test - X_mean) / X_std

X_train = X_train[..., np.newaxis]
X_valid = X_valid[..., np.newaxis]
X_test = X_test[..., np.newaxis]

from functools import partial

DefaultConv2D = partial(keras.layers.Conv2D, kernel_size=3, strides=1,
                        padding="SAME", use_bias=False)

class ResidualUnit(keras.layers.Layer):
    def __init__(self, filters, strides=1, activation="relu", **kwargs):
        super().__init__(**kwargs)
        self.activation = keras.activations.get(activation)
        self.main_layers = [
            DefaultConv2D(filters, strides=strides),
            keras.layers.BatchNormalization(),
            self.activation,
            DefaultConv2D(filters),
            keras.layers.BatchNormalization()]
        self.skip_layers = []
        if strides > 1:
            self.skip_layers = [
                DefaultConv2D(filters, kernel_size=1, strides=strides),
                keras.layers.BatchNormalization()]

    def call(self, inputs):
        Z = inputs
        for layer in self.main_layers:
            Z = layer(Z)
        skip_Z = inputs
        for layer in self.skip_layers:
            skip_Z = layer(skip_Z)
        return self.activation(Z + skip_Z)

model = keras.models.Sequential()
model.add(DefaultConv2D(64, kernel_size=7, strides=2,
                        input_shape=[224, 224, 3]))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.Activation("relu"))
model.add(keras.layers.MaxPool2D(pool_size=3, strides=2, padding="SAME"))
prev_filters = 64
for filters in [64] * 3 + [128] * 4 + [256] * 6 + [512] * 3:
    strides = 1 if filters == prev_filters else 2
    model.add(ResidualUnit(filters, strides=strides))
    prev_filters = filters
model.add(keras.layers.GlobalAvgPool2D())
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(10, activation="softmax"))

model.summary()


from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import mysql.connector
import cv2
import os
import numpy as np

class Train:
  def __init__(self,root):

    self.root = root
    self.root.title("Attendance Manager")
    self.root.state('zoomed')

    screen_width = self.root.winfo_screenwidth()
    screen_height = self.root.winfo_screenheight()
    self.root.configure(bg="#cbf3f0")

    # screen_width = self.root.winfo_screenwidth()
    # screen_height = self.root.winfo_screenheight()

    background_frame = Frame(self.root,bg="#cbf3f0")
    background_frame.place(x=0,y=0,width=screen_width,height=screen_height)

    self.train_classifier()
    self.root.destroy()

  def train_classifier(self):
    data_dir=("Data")
    path=[os.path.join(data_dir,file) for file in os.listdir(data_dir)]

    faces=[]
    ids=[]

    for image in path:
      img=Image.open(image).convert('L') #grey scale convertion
      imageNp=np.array(img,'uint8')
      id=int(os.path.split(image)[1].split('.')[1])

      faces.append(imageNp)
      ids.append(id)
      cv2.imshow("Training",imageNp)
      cv2.waitKey(1)==13
    ids=np.array(ids)

    #======================= training the classifier and storing data =================
    clf=cv2.face.LBPHFaceRecognizer_create()
    clf.train(faces,ids)
    clf.write("classifier.xml")
    cv2.destroyAllWindows()
    messagebox.showinfo("Result","Training data set completed!",parent = self.root)

if __name__=="__main__":
  root=Tk()
  obj=Train(root)
  root.mainloop()


import sys

def foo(x):
    lista = list(str(x).replace('\n', ''))
    lista.reverse()
    dictio = {}
    key = 1
    for x in range(len(lista)):
        dictio[key] = lista[x]
        key *= 10

    return dictio

print("Podaj liczbę całkowitą: ")
liczba = sys.stdin.readline()

dictio = foo(liczba)
keys = list(dictio.keys())
keys.reverse()
adds = [f'{key} * {dictio[key]}' for key in keys]
print(adds)
text = ' + '.join(adds)
text = text + "."

sys.stdout.write(f'Podaną liczbę można zapisać jako: ')
sys.stdout.write(text)

# TAK, WIDZE JAK BARDZO ŁOPATOLOGICZNE TO JEST
# ALE NA PRAWDE NIE MAM CZASU SZUKAĆ OPTYMALNEGO ROZWIĄZANIA
# ZROBIŁEM PIERWSZE LEPSZE DZIAŁAJĄCE


import precompiler._impl.pc_define as _impl_pc_define
import precompiler._impl.pc_iterator as _impl_pc_iterator
import precompiler._impl.pc_output as _impl_pc_output
import precompiler._impl.pc_default_macros as _pc_macros
import precompiler._utils.pc_utils as _pc_utils

import timeit
import datetime

_token_flags = _pc_utils.token_flags
_primitive_toks = _pc_utils.primitive_tokens
_cmd_tokens = _pc_utils.precompiler_tokens

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

# parser state that reads expanded define arguments
class _pc_argument_parser(_impl_pc_iterator.PrecompilerExecController):
	def __init__(self,vm,parent_state,source_define,expanded_token):
		_impl_pc_iterator.PrecompilerExecController.__init__(self,vm)
		self.parent_state = parent_state
		self.define = source_define
		self.expanded_token = expanded_token

		self.scope_stack = []

		self.next_arguments = source_define.GetRequiredArguments().copy()

		self.target_argument_name = None
		self.target_aquired_content = False

		self.arg_map = {}

		self._shift_first()

	def push_to_argument(self,tok):

		#we must have an argument assigned here
		if self.target_argument_name == None:
			lh = self._get_look_ahead_arg_token()
			assert lh != None, "Missing lookahead token!"
			(_,_,expected_value,_) = lh
			self.precompiler.RaiseErrorOnToken(tok,"Invalid arguments!","Expected [" + expected_value[0] + "]")

		self.arg_map[self.target_argument_name].append(tok)

		(tok_flags,tok_type,val,_) = tok

		#measure non important tokens
		if (tok_type != _primitive_toks.kWhitespace) and (tok_type != _primitive_toks.kWhitespace):
			self.target_aquired_content = True #added one more argument

		if tok_type == _cmd_tokens.k_scope_push:
			self.scope_stack.append(tok_flags)
		elif tok_type == _cmd_tokens.k_scope_pop:
			if len(self.scope_stack) == 0:
				self.precompiler.RaiseErrorOnToken(tok,"Unexpected token!","[" + val[0] + "]")
			if (self.scope_stack[-1] & _token_flags.k_first_mask) != (tok_flags & _token_flags.k_first_mask):
				self.precompiler.RaiseErrorOnToken(tok,"Mismatched token!","[" + val[0] + "]")
			self.scope_stack.pop()

	def _get_look_ahead_arg_token(self):
		if len(self.scope_stack) > 0:
			return None
		if len(self.next_arguments) == 0:
			return None
		return self.next_arguments[0]

	def _shift_first(self):
		while len(self.next_arguments) > 0:
			(_,expected_type,expected_value,_) = self.next_arguments[0]
			if expected_type != _primitive_toks.kIdentifier:
				break;

			self.target_argument_name = expected_value[0]
			self.target_aquired_content = False

			self.arg_map.setdefault(expected_value[0],[])
			self.next_arguments.pop(0)

	def shift(self):
		self.target_argument_name = None
		self.target_aquired_content = False
		self.next_arguments.pop(0)
		self._shift_first()

	def get_exit_state(self):
		if len(self.next_arguments) == 0 and len(self.scope_stack) == 0:
			#we are done parsing arguments, expand macro and exit
			self.precompiler._expand_define_with_evaluation(self.expanded_token,self.define,self.arg_map)
			return self.parent_state
		return self

	def Advance(self,tok):

		(_,toktype,value,_) = tok

		lh = self._get_look_ahead_arg_token()

		if lh == None:
			#last token from arg list, push to argument and than exit
			self.push_to_argument(tok)
			if(self.target_aquired_content == False):
				return self #because we did not get any valuable content, we wait

		else:
			(_,expected_type,expected_value,_) = lh

			if toktype == expected_type and value == expected_value:
				#if we match the expected stuff we advance to next one
				self.shift()
			else:
				self.push_to_argument(tok)

		return self.get_exit_state()

	def Finish(self):
		self.precompiler.RaiseErrorOnToken(self.source_token,"Incomplete arguments",None)

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

# global state parser. works with the vm states also
class _pc_root_parser(_impl_pc_iterator.PrecompilerExecController):
	def __init__(self,vm,builder):
		_impl_pc_iterator.PrecompilerExecController.__init__(self,vm)

		self.assembler = builder

	def Finish(self):
		self.assembler.Close()

	def _create_file_info(self,tok):
		_fi = self.precompiler.file_interface
		active_file_path = self.precompiler.input_state.GetActiveSourceFile()
		file_handle = _fi.GetOrLoadFile(active_file_path)
		lines = [
			"--------------------------------------------------------------------------------------------------------------------------------------------",
			"-- ! Preprocessed file, CHANGES WILL BE DISCARDED ! ----------------------------------------------------------------------------------------",
			"--------------------------------------------------------------------------------------------------------------------------------------------",
			"-- Time: " + _pc_utils.GetNowTimeString(),
			"-- Src path: " + active_file_path,
			"-- Preprocessor version:" + str(_pc_macros._PCVER_HIGH_) + "." + str(_pc_macros._PCVER_LOW0_) + "." + str(_pc_macros._PCVER_LOW1_),
			"--------------------------------------------------------------------------------------------------------------------------------------------"
		]
		return "\n".join([_fi.CreateOutputComment(l) for l in lines]);

	def _evaluate_source_id(self,tok,_id):
		if _id == 'once':
			source_file = self.precompiler.input_state.GetActiveSourceFile()
			self.precompiler.file_interface.StashFileContent(source_file)
		elif _id == 'dup':
			source_file = self.precompiler.input_state.GetActiveSourceFile()
			self.precompiler.file_interface.StashFileContent(source_file)
		elif _id == 'break':
			self.precompiler._break_file_unit();
		elif _id == 'info':
			file_info = self._create_file_info(tok);
			self.assembler.Write((_token_flags.k_trivial_flag,_primitive_toks.kInlined,[file_info],_pc_utils.TokSource(tok)))
		else:
			self.precompiler.RaiseErrorOnToken(tok,"Unknown #source token!","Value `" + _id + "`")

	def _evaluate_functions_with_string_arg(self,tok,toktype,unboxed_str):

		if toktype == _cmd_tokens.k_include:
			self.precompiler.open_file_and_include(unboxed_str,tok)
		elif toktype == _cmd_tokens.k_inline_include:
			self.assembler.Write((_token_flags.k_trivial_flag,_primitive_toks.kInlined,[self.precompiler.open_file_and_get_str(unboxed_str,tok)],_pc_utils.TokSource(tok)))
		elif toktype == _cmd_tokens.k_inline_str:
			self.assembler.Write((_token_flags.k_trivial_flag,_primitive_toks.kInlined,[unboxed_str],_pc_utils.TokSource(tok)))
		elif toktype == _cmd_tokens.k_error:
			self.precompiler.RaiseErrorOnToken(tok,"User #error!",unboxed_str)
		else:
			assert False, "Internal Error"

		return self

	def _expand_define(self,def_inst,tok):
		if def_inst.GetRequiredArguments() != None:
			result = _pc_argument_parser(self.precompiler,self,def_inst,tok)
			return result
		else:
			self.precompiler._expand_define_with_evaluation(tok,def_inst,None)
			return self

	def _end_colapse(self):
		next_assembler = self.assembler.NextAssembler()
		assert next_assembler != None, "Internal error on _end_colapse"
		self.assembler.Close()
		self.assembler = next_assembler

	def _colapse_macro(self,tok):
		_tok_value = tok[2]
		df = self.precompiler.get_required_define(tok,_tok_value[1])

		if df.IsBuiltin() == True:
			self.precompiler.RaiseErrorOnToken(tok,"#colapse does not work on builtin macros!",df.name)
		if df.GetRequiredArguments() != None:
			self.precompiler.RaiseErrorOnToken(tok,"#colapse does not work on macros that require arguments!",df.name)

		tokens = df.GetValueAsTokens(tok)
		df.ClearValue();

		self.assembler = _impl_pc_output.VarDefineValueAssembler(df).SetNextAssembler(self.assembler)
		self.precompiler.open_colapse(_impl_pc_iterator.ColapsedTokenInterator(tok,tokens,self.precompiler))

	def _run_command(self,tok,inline_content):
		result = self.precompiler._evaluate_tok(tok);
		if(result != None):
			if inline_content == True:
				self.assembler.Write((_token_flags.k_trivial_flag,_primitive_toks.kInlined,[str(result)],_pc_utils.TokSource(tok)))
			else:
				#todo: make function in pre
				tokens = self.precompiler.file_interface.RetokenizeContent(str(result),tok)
				next_iterator = _impl_pc_iterator.GeneratedTokenInterator(tokens)

				if self.precompiler.input_state.PushState(next_iterator,None) == False:
					self.precompiler.RaiseErrorOnToken(tok,"Stack overflow while executin #run!",None)

	def Advance(self,tok):

		_prep = self.precompiler

		_is_executed = _prep.is_evaluating() #true/false if the

		tokflags = tok[0]

		#strings, characters, comments, whitespaces, etc
		if (tokflags & _token_flags.k_trivial_flag) != 0:
			if _is_executed:

				self.assembler.Write(tok)
			return self

		toktype = tok[1]
		_tok_value = tok[2]

		#check for defines with same name
		if toktype == _primitive_toks.kIdentifier:
			if _is_executed:
				df = _prep.input_state.FindVarDefineWithName(_tok_value[0])
				if df != None:
					return self._expand_define(df,tok)
				else:
					self.assembler.Write(tok)
			return self

		#conditional tokens, no output
		if (tokflags & _token_flags.k_conditional_flag) != 0:
			if toktype == _cmd_tokens.k_if_defined:
				if _is_executed:
					_prep.push_execution_state(_prep.is_defined(_tok_value[1]))
				else:
					_prep.push_execution_state(None)
			elif toktype == _cmd_tokens.k_if_not_defined:
				if _is_executed:
					cond = _prep.is_defined(_tok_value[1])
					_prep.push_execution_state(True if (cond == False) else False)
				else:
					_prep.push_execution_state(None)
			elif toktype == _cmd_tokens.k_if:
				if _prep.is_evaluating():
					_prep.push_execution_state(_prep.evaluate_if_condition(tok))
				else:
					_prep.push_execution_state(None)
			elif toktype == _cmd_tokens.k_else_if:
				_prep.negate_execution_state(tok)
				if _prep.is_evaluating():
					_prep.pop_execution_state(tok)
					_prep.push_execution_state(_prep.evaluate_if_condition(tok))
				else:
					_prep.pop_execution_state(tok)
					_prep.push_execution_state(None)
			elif toktype == _cmd_tokens.k_else:
				_prep.negate_execution_state(tok)
			elif toktype == _cmd_tokens.k_endif:
				_prep.pop_execution_state(tok)

			#end of conditional
			return self

		#non conditionals statements, no output
		if _is_executed:
			#all this commands should have k_command_flag
			if (tokflags & _token_flags.k_id_str_argument_flag) != 0:
				(_,name_or_str,type_of_argument) = _tok_value

				if type_of_argument == _token_flags.k_identifier_flag:
					string_value = _prep.get_required_define(tok,name_or_str).GetValueAsString(tok)
					return self._evaluate_functions_with_string_arg(tok,toktype,string_value)

				elif type_of_argument == _token_flags.k_string_flag:
					return self._evaluate_functions_with_string_arg(tok,toktype,_pc_utils.UnboxString(name_or_str))

			elif toktype == _cmd_tokens.k_define:
				(_,name,content) = _tok_value
				(arguments,value) = _prep.parse_define_content(tok,content);
				if (tokflags & _token_flags.k_no_error) != 0:
					_prep.add_new_define(tok,_impl_pc_define.VarDefine(name,arguments,value,tok,_prep),False)
				else:
					_prep.add_new_define(tok,_impl_pc_define.VarDefine(name,arguments,value,tok,_prep),True)

			elif toktype == _cmd_tokens.k_colapse:
				self._colapse_macro(tok)

			elif toktype == _cmd_tokens.k_run:
				self._run_command(tok,False)
			elif toktype == _cmd_tokens.k_inline_eval:
				self._run_command(tok,True)

			elif toktype == _cmd_tokens.k_cwstrip:
				_prep.get_required_define(tok,_tok_value[1]).CwStrip()

			elif toktype == _cmd_tokens.k_undefine:
				if _prep.input_state.RemoveDefineRecursive(_tok_value[1]) == False:
					_prep.RaiseErrorOnToken(tok,"Failed to execute #undef statement!","Searching for `" + tok[2] + "`")
			elif toktype == _cmd_tokens.k_source:
				self._evaluate_source_id(tok,_tok_value[1])

			return self

		elif (tokflags & _token_flags.k_command_flag) != 0:
			#cmd tokens that are on a not evaluated, are skipped
			return self

		#should never reach this place
		assert False, "Internal execution error!"

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

#Main vm processing functions
class _precompiler_backend(object):
	def __init__(self, user_file_handler, options):

		self.parser_state = None #token processor and writer
		self.input_state = None #input reader

 		#if/else state
		self.active_condition = None
		self.condition_stack = []

		#reading and writing files
		self.file_interface = user_file_handler

		self.options = options if options != None else {}

		#eval and if eval context
		self.eval_user_context = self.options.get("EvalContext",None)

		self._cached_eval_tok = None
		self._cached_eval_ctx = None

		self._default_macros = None

		self._dependency_list = None
		if self.options.get("MakeDependencyTree",False) == True:
			self._dependency_list = []

	def push_execution_state(self,is_condition_true):
		self.condition_stack.append(is_condition_true)
		self.active_condition = None

	def negate_execution_state(self,tok):
		if len(self.condition_stack) == 0:
			self.RaiseErrorOnToken(tok,"Unexpected #else statement!",None)

		if self.condition_stack[ -1 ] == True:
			self.condition_stack[ -1 ] = False
		elif self.condition_stack[ -1 ] == False:
			self.condition_stack[ -1 ] = True

		self.active_condition = None

	def pop_execution_state(self,tok):
		if len(self.condition_stack) == 0:
			self.RaiseErrorOnToken(tok,"Unexpected #end! statement",None)
		self.condition_stack.pop()
		self.active_condition = None

	def is_evaluating(self):
		if self.active_condition is None:
			self.active_condition = True
			for x in self.condition_stack:
				if x != None:
					self.active_condition = self.active_condition and x
				else:
					self.active_condition = False
					break

		return self.active_condition

	def _invalidate_eval_ctx(self):
		self._cached_eval_ctx = None

	def prepare_eval_context(self,tok):
		self._cached_eval_tok = tok
		if self._cached_eval_ctx != None:
			return self._cached_eval_ctx

		self._cached_eval_ctx = {}
		self._cached_eval_ctx["defined"] = lambda name_str: self.is_defined(name_str)
		self._cached_eval_ctx["value"] = lambda name_str: self._ev_value(name_str)
		self._cached_eval_ctx["tokens"] = lambda name_str: self._ev_tokens(name_str)

		if self.eval_user_context != None:
			self._cached_eval_ctx.update(self.eval_user_context)

		return self._cached_eval_ctx

	def _ev_tok(self):
		return self._cached_eval_tok

	def _ev_value(self,name):
		et = self._ev_tok()
		return self.get_required_define(et,name).GetValueAsString(et);

	def _ev_tokens(self,name):
		et = self._ev_tok()
		return self.get_required_define(et,name).GetValueAsTokens(et);

	def run_python_eval(self,tok,raw_code):
		eval_ctx = self.prepare_eval_context(tok)

		try:
			#the context is passed as local because we don't want it to be poluted by `eval` function
			result = eval(raw_code,None,eval_ctx)
			return result
		except SyntaxError as e:
			self.RaiseErrorOnToken(tok,"SyntaxError!",str(e))
		except ZeroDivisionError as e:
			self.RaiseErrorOnToken(tok,"ZeroDivisionError!",str(e))
		except NameError as e:
			self.RaiseErrorOnToken(tok,"NameError!",str(e))
		except TypeError as e:
			self.RaiseErrorOnToken(tok,"TypeError!",str(e))

	def evaluate_if_condition(self,tok):
		_tok_value = tok[2]
		result = self.run_python_eval(tok,_tok_value[1]);
		if result == "True":
			return True
		elif result == "False":
			return False
		else:
			try:
				v = int(result)
				if v != 0:
					return True
				return False
			except ValueError:
				return False

		return False

	def open_colapse(self,token_iterator):
		self.input_state.PushState(token_iterator,None)

	def close_colapse(self,original_token):
		if isinstance(self.parser_state,_pc_argument_parser):
			self.RaiseErrorOnToken(original_token,"#colapse requires some arguments for a macro",None)

		self.parser_state._end_colapse()

	def get_required_define(self,tok,define_name):
		result = self.input_state.FindVarDefineWithName(define_name)
		if result == None:
			self.RaiseErrorOnToken(tok,"No define found!","Search name [" + define_name + "]")

		return result

	def is_defined(self,name):
		if self.input_state.FindVarDefineWithName(name) != None:
			return True
		return False

	def add_new_define(self,def_token,def_instance,fail_if_defined):
		if self.input_state.FindVarDefineWithName(def_instance.name) != None:
			if(fail_if_defined == True):
				self.RaiseErrorOnToken(def_token,"Redefinition is not allowed!","Define name: `" + def_instance.name + "`")
			self.input_state.RemoveDefineRecursive(def_instance.name)

		self.input_state.AddGlobalDefine(def_instance)

	def evaluate_file_path(self,strval,tok):
		current_compilation_unit = self.input_state.GetActiveSourceFile()
		abs_path = self.file_interface.FindFileWithPath(strval,current_compilation_unit)
		if abs_path == None:
			self.RaiseErrorOnToken(tok,"Could not locate file!","Path: `" + strval + "`")
		return abs_path

	def open_file_and_get_str(self,strval,tok):
		abs_file_path = self.evaluate_file_path(strval,tok)
		return self.file_interface.GetFileStr(abs_file_path)

	def _break_file_unit(self):
		self.condition_stack = self.input_state.BreakFileUnit();
		self.active_condition = None

	def open_file_and_include(self,strval,tok):

		abs_file_path = self.evaluate_file_path(strval,tok)

		depdendency_handle = self.file_interface.GetOrLoadFile(abs_file_path)
		content = depdendency_handle.tokens()

		if self._dependency_list != None:
			self._dependency_list.append((self.input_state.GetActiveSourceFile(),abs_file_path,depdendency_handle.hash()))

		if self.options.get("SourceOnceByDefault",False) == True:
			self.file_interface.StashFileContent(abs_file_path)

		push_result = self.input_state.PushState(_impl_pc_iterator.FileTokenInterator(content,abs_file_path,self.condition_stack.copy()),None)
		if push_result == False:
			self.RaiseErrorOnToken(tok,"Stack overflow!","Current include `" + abs_file_path + "`.")

	def _evaluate_tok(self,tok):
		_tok_value = tok[2]
		return self.run_python_eval(tok,_tok_value[1]);

	def _expand_define_with_evaluation(self,expanded_tok,def_to_expand,arg_map):
		next_define_map = None
		tokens = def_to_expand.GetValueAsTokens(expanded_tok)

		if arg_map != None:
			next_define_map = _impl_pc_define.VarDefineMap()
			for (name,toklist) in arg_map.items():
				arg_def = _impl_pc_define.VarDefineStatic(name,toklist,expanded_tok,self)
				next_define_map.TryAddLocalDefine(arg_def)

		next_iterator = _impl_pc_iterator.GeneratedTokenInterator(tokens)

		if self.input_state.PushState(next_iterator,next_define_map) == False:
			self.RaiseErrorOnToken(expanded_tok,"Stack overflow while expanding identifier!",None)

	def parse_define_content(self,tok,content):
		if content == None or content == "":
			return (None,[])

		token_list = self.file_interface.RetokenizeContent(content,tok)

		first_list = []
		second_list = None

		split_lists = False
		for ( tok_flags, tok_tp, tok_value, tok_loc ) in token_list:
			if (tok_flags & _token_flags.k_blank) != 0:
				#encountered blank
				if split_lists == False:
					#first blank
					split_lists = True
					second_list = []
					continue;

			if split_lists == False:
				#no blank separator encountered
				first_list.append(( tok_flags, tok_tp, tok_value, tok_loc ))
			else:
				second_list.append(( tok_flags, tok_tp, tok_value, tok_loc ))

		if second_list == None:
			return (None,first_list)
		if len(first_list) == 0:
			return (None,second_list)

		arg_list = [( tok_flags, tok_tp, tok_value, tok_loc ) for ( tok_flags, tok_tp, tok_value, tok_loc ) in first_list if tok_tp != _primitive_toks.kWhitespace or (tok_flags & _token_flags.k_impostor) != 0]

		return (arg_list,second_list)

	def _add_builtin_macro(self,mc):
		self._default_macros[mc.name] = mc
		self.input_state.AddGlobalDefine(mc)

	def init_default_macros(self):
		if self._default_macros != None:
			return
		self._default_macros = {}
		self._add_builtin_macro(_pc_macros.macro__FILE__(self))
		self._add_builtin_macro(_pc_macros.macro__FILENAME__(self))
		self._add_builtin_macro(_pc_macros.macro__FILEROOT__(self))
		self._add_builtin_macro(_pc_macros.macro__PCVER__(self))
		self._add_builtin_macro(_pc_macros.macro__PCVER_HIGH__(self))
		self._add_builtin_macro(_pc_macros.macro__PCVER_LOW__(self))
		self._add_builtin_macro(_pc_macros.macro__LINE__(self))
		self._add_builtin_macro(_pc_macros.macro__NOW_TIME__(self))

	def RaiseErrorOnToken(self,tok_tuple,message,variable_message):
		_pc_utils.RaiseErrorAtToken(tok_tuple,message,variable_message)

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


import torch
import cv2
import time
from threading import Thread

# model = torch.hub.load('yolov7', 'custom', 'YOLOv7pt/best.pt', source="local")
# model = torch.hub.load('yolov7', 'custom', 'YOLOv7pt/yolov7.onnx', source="local")

# For YOLO Tiny Model
model = torch.hub.load('yolov7', 'custom', 'YOLOv7 Tiny/best.pt', source="local")
# model = model.zero_grad()
class VideoStream:
    """Camera object that controls video streaming from the Picamera"""

    def __init__(self, resolution=(640, 480), framerate=30):
        # Initialize the PiCamera and the camera image stream
        self.stream = cv2.VideoCapture(0)
        ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
        ret = self.stream.set(3, resolution[0])
        ret = self.stream.set(4, resolution[1])

        # Read first frame from the stream
        (self.grabbed, self.frame) = self.stream.read()

        # Variable to control when the camera is stopped
        self.stopped = False

    def start(self):
        # Start the thread that reads frames from the video stream
        Thread(target=self.update, args=()).start()
        return self

    def update(self):
        # Keep looping indefinitely until the thread is stopped
        while True:
            # If the camera is stopped, stop the thread
            if self.stopped:
                # Close camera resources
                self.stream.release()
                return

            # Otherwise, grab the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
        # Return the most recent frame
        return self.frame

    def stop(self):
        # Indicate that the camera and thread should be stopped
        self.stopped = True

frame_rate_calc = 1
freq = cv2.getTickFrequency()

videostream = VideoStream().start()
time.sleep(1)
while True:
    t1 = cv2.getTickCount()
    frame = videostream.read()

    with torch.no_grad(): #this i added to check
        results = model(frame)
    image = frame
    print(results.pandas().xyxy[0])

    if len(results.pandas().xyxy[0]) != 0:
        rows = results.pandas().xyxy[0].shape[0]
        for i in range(rows):
            xmin = int(results.pandas().xyxy[0].iloc[i].xmin)
            xmax = int(results.pandas().xyxy[0].iloc[i].xmax)
            ymin = int(results.pandas().xyxy[0].iloc[i].ymin)
            ymax = int(results.pandas().xyxy[0].iloc[i].ymax)

            cv2.rectangle(image,(xmin, ymin),(xmax, ymax),(0,255,0),3)
            cv2.putText(image,str(results.pandas().xyxy[0].confidence.get(i)),(xmin, ymin - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(255,255,255),2,cv2.LINE_AA)

    cv2.putText(image, 'FPS: {0:.2f}'.format(frame_rate_calc), (30, 50), cv2.FONT_HERSHEY_SIMPLEX,
                1, (255, 255, 0), 2,
                cv2.LINE_AA)
    cv2.imshow("LP Image", image)
    t2 = cv2.getTickCount()
    time1 = (t2 - t1) / freq
    frame_rate_calc = 1 / time1

    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyAllWindows()
videostream.stop()


# -*- coding: utf-8 -*-
import unittest
from Functions.seleniumFunctions import seleniumFunctions as Selenium
from Functions.Inicializar import  Inicializar
from Pages.Menu_MercadoLibre import Menu_Meli
from Pages.Login_MercadoLibre import Login_Meli

class MeliAppium(unittest.TestCase):

    def setUp(self):
        self.driver = Inicializar.IniciarApp(self, 'http://127.0.0.1:4725', 'android', '5.0.1', 'GT-I9500', '4d00261bbbe450a3', True)

    def test_007(self):
        driver = self.driver

        #Menu-->Ingresar
        Selenium.Esperar_xpath(self, driver, Menu_Meli.btn_Menu_xpath)
        Selenium.AccID_elements_click(self, driver, Menu_Meli.btn_menu_accid)
        Inicializar.capturarPantalla(self, driver)
        Selenium.ID_elements_click(self, driver, Menu_Meli.lbl_ingresar_id)

        #Seleccionar tipo de Login
        Selenium.Esperar_ID(self, driver, Login_Meli.btn_already_id)
        self.assertEqual("¿Aún no tienes cuenta?", Selenium.Get_to_text_Element_ID(self, driver, Login_Meli.lbl_Registro_Titulo))

        self.assertEqual(True, Selenium.Esperar_ID(self, driver, Login_Meli.btn_facebook_id))
        self.assertEqual(True, Selenium.Esperar_ID(self, driver, Login_Meli.btn_email_id))

        Selenium.ID_elements_click(self, driver, Login_Meli.btn_already_id)

        #Ingreso de Usuario
        Selenium.Esperar_ID(self, driver, Login_Meli.lbl_avisoTitulo_id)
        self.assertTrue(True, Login_Meli.lbl_avisoTitulo_id)
        Selenium.ID_elements_click(self, driver, Login_Meli.txt_usuario_id)
        Selenium.sendkeys_id(self, driver, Login_Meli.txt_usuario_id, "devbaires")
        Inicializar.capturarPantalla(self, driver)
        Selenium.ID_elements_click(self, driver, Login_Meli.btn_continuar_id)

        #Ingreso de clave
        Selenium.Esperar_ID(self, driver, Login_Meli.btn_ingresar_id)
        Selenium.sendkeys_id(self, driver, Login_Meli.txt_Clave_id, "298258233")
        Selenium.AccID_elements_click(self, driver, Login_Meli.btn_verClave_Accid)
        Selenium.ID_elements_click(self, driver, Login_Meli.btn_ingresar_id)

        #Validar el usuario logueado
        Selenium.AccID_elements_click(self, driver, Login_Meli.btn_menu_accid)
        self.assertEqual("¡Hola Mervin!", Selenium.Get_to_text_Element_ID(self, driver, Login_Meli.lbl_UsuarioLogueado_id))
        Inicializar.capturarPantalla(self, driver)

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(MeliAppium)
    unittest.TextTestRunner(verbosity=2).run(suite)


import os
import sys
import datetime
import logging

def setup_logger(name, save_dir, experiment_name,
                 trial_num=0, save_log=False):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler(stream=sys.stdout)
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        "%(asctime)s %(name)s %(levelname)s: %(message)s")
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    if save_log:
        now_time = datetime.datetime.now()
        now_time = str(now_time)[:19]
        log_name = experiment_name + '_' + 'trial_{}_'.format(trial_num) \
                   + now_time + '_log.txt'
        log_path = os.path.join(save_dir, log_name)

        fh = logging.FileHandler(log_path, mode='w')
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(formatter)
        logger.addHandler(fh)
    else:
        log_path = None

    return logger, log_path


n, k, x = map(int, input().strip().split())
persons = list(range(1, n + 1))
while len(persons) > 1:
    i = persons.index(x)
    pre = persons[:i]
    del persons[:i]
    persons.extend(pre)
    i = persons.index(x)
    i += 1
    del persons[i:i + x % k]
    if len(persons) > 1:
        x = persons[i]
print(persons[0])

hackerearth/Basic Programming/Implementation/Basics of Implementation/Round Table Killers/solution.py


##
# Tharin Dresher-Hurst
# hw01_age.py
# 2018 - 02 - 14
# Created the if elif chain
# 2018 - 02 - 15
# Fixed minor issues
##

def ageClass(x):
    if x <= 1:
        print("You are an infant.")
    elif x > 1 and x < 13:
        print("You are a child.")
    elif x >= 13 and x < 20:
        print("You are a teenager.")
    else:
        print("You are an adult.")

def main():
    userAgeInput=int(input("Enter your age in years:\t"))
    ageClass(userAgeInput)

main()


from django.urls import path

from .views import ContactView, InstagramView, MailChimpSubscription

app_name = 'basic'
urlpatterns = [
    path('contact/', ContactView.as_view(), name='contact'),
    path('instagram/', InstagramView.as_view(), name='instagram'),
    path('mailchimp/', MailChimpSubscription.as_view(), name='mailchimp'),
]


from typing import Union

class MyUnion(type): ...

class Meta(type):

    def __or__(self, other) -> MyUnion: ... # type: ignore

class Foo(metaclass=Meta): ...

reveal_type(Foo | Foo) # line 12
isinstance(object(), Foo | Foo)
Bar = Foo | Foo
reveal_type(Bar) # line 14
isinstance(object(), Bar) # line 15

class A: ...
class B: ...
C = A | B
reveal_type(C) # Revealed type is "builtins.object"
isinstance(object(), C) # error: Parameterized generics cannot be used with class or instance checks
                        # error: Argument 2 to "isinstance" has incompatible type "object"; expected "Union[type, UnionType, Tuple[Union[type, UnionType, Tuple[Any, ...]], ...]]"

isinstance(object(), int | list[int]) # no error (should be "error: Parameterized generics cannot be used with class or instance checks")


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 13:43:49 2019

@author: shirhe-lyh
"""

import numpy as np
import os
import PIL
import torch

from core import dataset
from core import preprocess_utils
from data import utils

class MattingDataset(dataset.SegDataset):
    """Read dataset for Matting_Human_Half datas."""

    def __init__(self, annotation_path, root_dir=None, transforms=None,
                 output_height=513, output_width=513):
        """Constructor."""
        super(MattingDataset, self).__init__(
            annotation_path=annotation_path,
            root_dir=root_dir,
            transforms=transforms,
            output_height=output_height,
            output_width=output_width)

    def __getitem__(self, index):
        """For Matting_Human_Half datasets, just resize to desired size"""
        image_path, mask_path = self._image_mask_paths[index]
        image = PIL.Image.open(image_path)
        mask = PIL.Image.open(mask_path)

        # Resize
        image = image.resize((self._output_width, self._output_height),
                             PIL.Image.ANTIALIAS)
        mask = mask.resize((self._output_width, self._output_height),
                            PIL.Image.NEAREST)
        # Flip
        image, mask = preprocess_utils.random_flip(image, mask)

        image = PIL.Image.fromarray(np.array(image))
        mask = torch.LongTensor(np.array(mask))
        image_preprocessed = self._transforms(image)
        return image_preprocessed, mask

    def get_image_mask_paths(self, annotation_path, root_dir=None):
        """Get the paths of images and masks.

        Args:
            annotation_path: A file contains the paths of images and masks.

        Returns:
            A list [[image_path, mask_path], [image_path, mask_path], ...].

        Raises:
            ValueError: If annotation_file does not exist.
        """
        # Format: [[image_path, matting_path, alpha_path, mask_path], ...]
        image_matting_alpha_mask_paths = utils.provide(annotation_path)
        # Remove matting_paths, alpha_paths
        image_mask_paths = []
        for image_path, _, _, mask_path in image_matting_alpha_mask_paths:
            if root_dir is not None:
                if not image_path.startswith(root_dir):
                    image_path = os.path.join(root_dir, image_path)
                    mask_path = os.path.join(root_dir, mask_path)
                    image_path = image_path.replace('\\', '/')
                    mask_path = mask_path.replace('\\', '/')
            image_mask_paths.append([image_path, mask_path])
        return image_mask_paths


largest = None
smallest = None

while True:
    num = input("Enter a number: ")

    try:
        n=float(num)

    except:
        print("Invalid input")
        continue

    if num == "done" : break

print("Maximum", largest)
print("Minimum", smallest)


class PluginManager():

    def __init__(self, path=None, plugin_init_args={}):
        if path:
            self.plugin_dir = path
        else:
            self.plugin_dir = os.path.dirname(__file__) + '/plugins/'

        self.plugins = []
        self._load_plugins()

        self._register_plugins(**plugin_init_args)

    def _load_plugins(self):
        sys.path.append(self.plugin_dir)
        plugin_files = [fn for fn in os.listdir(self.plugin_dir) if
                       fn.startswitch('plugin_') and
                       fn.endswitch('.py')]
        plugin_modules = [m.split('.')[0] for m in plugin_files]
        for module in plugin_modules:
            m = __import__(module)