import sys
import joblib
import pandas as pd
from functools import partial
from functools import reduce
from sklearn.preprocessing import StandardScaler
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import (
    QApplication,
    QGridLayout,
    QLineEdit,
    QMainWindow,
    QPushButton,
    QVBoxLayout,
    QHBoxLayout,
    QComboBox,
    QWidget,
    QLabel,
    QScrollArea,
    QGroupBox,
)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

WINDOW_WIDTH = 1000
WINDOW_HEIGHT = 700
DISPLAY_HEIGHT = 35
BUTTON_HEIGHT = 30
BUTTON_WIDTH = 120

class AppWindow(QMainWindow):
    ###Main window GUI/View###
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Predicting Match Outcomes")
        self.setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT)
        self.generalLayout = QVBoxLayout()
        centralWidget = QWidget(self)
        centralWidget.setLayout(self.generalLayout)
        self.setCentralWidget(centralWidget)
        self._createMainTitle()
        self._createTeamSelection()
        self._createOutputButton()
        self._createOutput()
        self._createHistoryButton()

    def _createMainTitle(self):
        self.mainTitle = QLabel("
Predicting Match Outcomes
")
        self.mainTitle.setFixedHeight(DISPLAY_HEIGHT)
        self.mainTitle.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        self.generalLayout.addWidget(self.mainTitle)

    def _createTeamSelection(self):
        teamsLayout = QHBoxLayout()
        currentyeardata = pd.read_csv('project\data\currentyeardata.csv')
        teams = currentyeardata.loc[:, 'Squad']

        self.teamSelection1 = QComboBox(self)
        for col, val in enumerate(teams):
            self.teamSelection1.addItem(val)
        teamsLayout.addWidget(self.teamSelection1)

        self.teamSelection2 = QComboBox(self)
        for col, val in enumerate(teams):
            self.teamSelection2.addItem(val)
        teamsLayout.addWidget(self.teamSelection2)

        self.generalLayout.addLayout(teamsLayout)

    def _createOutputButton(self):
        self.outputButton = QPushButton("Predict Outcome")
        self.outputButton.setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT)
        self.generalLayout.addWidget(self.outputButton)

    def _createOutput(self):
        outputLayout = QVBoxLayout()

        self.outputDisplay = QLineEdit()
        self.outputDisplay.setFixedHeight(DISPLAY_HEIGHT)
        self.outputDisplay.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.outputDisplay.setReadOnly(True)
        outputLayout.addWidget(self.outputDisplay)

        fig = Figure(figsize=(4,4))
        self.axes = fig.add_subplot()
        self.canvas = FigureCanvas(fig)
        outputLayout.addWidget(self.canvas)

        self.generalLayout.addLayout(outputLayout)

    def _createHistoryButton(self):
        self.historyButton = QPushButton("History")
        self.historyButton.setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT)
        self.generalLayout.addWidget(self.historyButton)

    def _createSeasonsButton(self):
        self.seasonButton = QPushButton("Season")
        self.seasonButton.setFixedSize(BUTTON_WIDTH, BUTTON_HEIGHT)
        self.generalLayout.addWidget(self.seasonButton)

    def setOutputDisplay(self, result):
        if (result == '[0]') :
            text = "Home Win"
        elif (result == '[1]'):
            text = "Draw"
        elif (result == '[2]'):
            text = "Away Win"
        else :
            text = result;

        self.outputDisplay.setText(text)
        self.outputDisplay.setFocus()

    def updateOutputGraph(self, probas):
        labels = ["Home Win", "Draw", "Away Win"]
        self.axes.cla()
        self.axes.pie(probas, labels=labels, autopct='%1.1f%%')
        self.canvas.draw()

class HistoryWindow(QWidget):
    def __init__(self, history):
        super().__init__()
        self.setWindowTitle("Prediction History")
        self.setFixedSize(WINDOW_WIDTH-350, WINDOW_HEIGHT)
        self.generalLayout = QVBoxLayout(self)
        self._createHistoryLabel(history)
        scroll = QScrollArea()
        scroll.setWidget(self.groupBox)
        scroll.setWidgetResizable(False)
        self.generalLayout.addWidget(scroll)

    def _createMainTitle(self):
        self.mainTitle = QLabel("
Prediction History
")
        self.mainTitle.setFixedHeight(DISPLAY_HEIGHT)
        self.mainTitle.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        self.generalLayout.addWidget(self.mainTitle)

    def _createHistoryLabel(self, history):
        self.groupBox = QGroupBox("Prediction History")
        if not history:
            self.historyLabel = QLabel("No prediction history.")
            tempLayout = QHBoxLayout()
            tempLayout.addWidget(self.historyLabel)
            self.groupBox.setLayout(tempLayout)
        else:
            self.historyStack = {}
            self.graphStack = {}
            historyLayout = QGridLayout()
            for i in range(len(history)):
                # Label
                key = history[i]['HomeTeam'] + history[i]['AwayTeam']
                if (history[i]['Pred'][0] == 0):
                    result = "Home Win"
                elif (history[i]['Pred'][0] == 1):
                    result = "Draw"
                elif (history[i]['Pred'][0] == 2):
                    result = "Away Win"
                self.historyStack[key] = QLabel(f"Home Team: {history[i]['HomeTeam']}, Away Team: {history[i]['AwayTeam']}, Result: {result}")
                historyLayout.addWidget(self.historyStack[key], i, 0)

                # Graph
                fig = Figure(figsize=(2,1))
                self.axes = fig.add_subplot()
                self.graphStack[key] = FigureCanvas(fig)
                probas = history[i]["Proba"][0]
                labels = ["Home Win", "Draw", "Away Win"]
                self.axes.pie(probas, labels=labels, autopct='%1.1f%%')
                self.graphStack[key].draw()
                historyLayout.addWidget(self.graphStack[key], i, 1)

            self.groupBox.setLayout(historyLayout)

class PredModel:
    ###Model###
    def __init__(self):
        rawdata = self.retrieveData()
        matchesData = self.storeData(rawdata)
        self.currentYearData = self.scaleData(matchesData)
        print("Data Loaded")

        self.predictingModel = joblib.load('project\models\\randomtree.sav')
        # self.predictingModel = joblib.load('project\models\\logisticreg.sav')
        print("Model loaded")

        self.history = [] #stack of history

    def retrieveData(self) :
        # Get from data source
        yearURL = 'https://fbref.com/en/comps/9/2022-2023/2022-2023-Premier-League-Stats'
        year = pd.read_html(yearURL)

        # Calculate the average number of games played in the season so far
        temp = pd.DataFrame(year[0])
        averageGamesPlayed = temp.loc[:, 'MP'].mean()

        # Clean standard stats
        standard = year[2].drop(columns=['Unnamed: 1_level_0','Unnamed: 2_level_0','Unnamed: 3_level_0','Playing Time','Expected', 'Per 90 Minutes'], axis=1, level=0)
        standard.columns = standard.columns.droplevel()
        standard = standard.drop(columns=['G+A','G-PK','PK','PKatt'])
        standard[['Gls','Ast','CrdY','CrdR','PrgC','PrgP']] = standard[['Gls','Ast','CrdY','CrdR','PrgC','PrgP']].div(averageGamesPlayed)

        # Clean goalkeeping stats
        goalkeeping = year[4]
        goalkeeping.columns = goalkeeping.columns.droplevel()
        goalkeeping = goalkeeping[['Squad','Saves']]
        goalkeeping[['Saves']] = goalkeeping[['Saves']].div(averageGamesPlayed)

        # Clean shooting stats
        shooting = year[8].drop(columns=['Unnamed: 1_level_0','Unnamed: 2_level_0','Expected'], axis=1, level=0)
        shooting.columns = shooting.columns.droplevel()
        shooting = shooting[['Squad','Sh','SoT']]
        shooting[['Sh','SoT']] = shooting[['Sh','SoT']].div(averageGamesPlayed)

        # Clean pass types stats
        passtypes = year[12].drop(columns=['Unnamed: 1_level_0','Unnamed: 2_level_0','Unnamed: 3_level_0','Corner Kicks','Outcomes'], axis=1, level=0)
        passtypes.columns = passtypes.columns.droplevel()
        passtypes = passtypes[['Squad','FK','TB','Sw','Crs','CK']]
        passtypes[['FK','TB','Sw','Crs','CK']] = passtypes[['FK','TB','Sw','Crs','CK']].div(averageGamesPlayed)

        # Clean creativity stats
        creativity = year[14].drop(columns=['Unnamed: 1_level_0','Unnamed: 2_level_0','SCA Types','GCA Types'], axis=1, level=0)
        creativity.columns = creativity.columns.droplevel()
        creativity = creativity[['Squad','SCA','GCA']]
        creativity[['SCA','GCA']] = creativity[['SCA','GCA']].div(averageGamesPlayed)

        # Clean defensive stats
        defensive = year[16].drop(columns=['Unnamed: 1_level_0','Unnamed: 2_level_0','Challenges','Unnamed: 16_level_0'],axis=1,level=0)
        defensive.columns = defensive.columns.droplevel()
        defensive = defensive[['Squad','TklW','Blocks','Int','Clr','Err']]
        defensive[['TklW','Blocks','Int','Clr','Err']] = defensive[['TklW','Blocks','Int','Clr','Err']].div(averageGamesPlayed)

        # Clean possesion stats
        possession = year[18].drop(
            columns=['Unnamed: 1_level_0','Unnamed: 3_level_0','Touches','Take-Ons','Carries','Receiving'],axis=1,level=0)
        possession.columns = possession.columns.droplevel()

        # Clean misc stats
        misc = year[22].drop(columns=['Unnamed: 1_level_0','Unnamed: 2_level_0','Aerial Duels'],axis=1,level=0)
        misc.columns = misc.columns.droplevel()
        misc = misc[['Squad','Fls','Fld','Off','PKwon','PKcon','Recov']]
        misc[['Fls','Fld','Off','PKwon','PKcon','Recov']] = misc[['Fls','Fld','Off','PKwon','PKcon','Recov']].div(averageGamesPlayed)

        currentYear = {'standard' : standard, 'goalkeeping' : goalkeeping, 'shooting' : shooting, 'passtypes' : passtypes,
            'creativity' : creativity, 'defensive' : defensive, 'possession' : possession, 'misc' : misc}

        dataframe = [currentYear['standard'],currentYear['goalkeeping'],currentYear['shooting'],
                    currentYear['passtypes'],currentYear['defensive'],currentYear['possession'],currentYear['misc']]

        df_merged = reduce(lambda  left,right: pd.merge(left,right,on=['Squad'],how='outer'), dataframe)
        return df_merged

    def storeData(self, rawdata):
        matchesData = pd.DataFrame()
        teams = rawdata.loc[:, 'Squad']
        for i in range(len(teams)):
            temp = list(teams)
            temp.remove(teams[i])
            for j in range(len(temp)):
                data = self.cleanAndProcessData(teams[i], temp[j], rawdata)
                matchesData = pd.concat([matchesData, data], ignore_index=True, axis=0)

        return matchesData

    def scaleData(self, matchesData):
        matchups = matchesData[['HomeTeam','AwayTeam']].copy()
        matchstats = matchesData.drop(columns=['HomeTeam', 'AwayTeam'])

        scaler = StandardScaler()
        scaler.fit(matchstats)
        scaledMatchstats = pd.DataFrame(scaler.transform(matchstats))

        scaledData = pd.merge(matchups, scaledMatchstats, left_index=True, right_index=True)

        return scaledData

    def cleanAndProcessData(self, homeTeam, awayTeam, rawdata):
        # Retrieve corresponding team stats from data and rename variables `home_'
        homeTeamStats = rawdata.loc[rawdata['Squad'] == homeTeam]
        homeTeamStats = homeTeamStats.drop(columns=['CrdY','CrdR'])
        homeTeamStats = homeTeamStats.rename(columns={c: 'home_'+ c for c in homeTeamStats.columns if c not in ['Squad']})
        homeTeamStats = homeTeamStats.rename(columns={'Squad':'HomeTeam'})

        # Retrieve corresponding team stats from data and rename variables `away_'
        awayTeamStats = rawdata.loc[rawdata['Squad'] == awayTeam]
        awayTeamStats = awayTeamStats.drop(columns=['CrdY','CrdR'])
        awayTeamStats = awayTeamStats.rename(columns={c: 'away_'+ c for c in awayTeamStats.columns if c not in ['Squad']})
        awayTeamStats = awayTeamStats.rename(columns={'Squad':'AwayTeam'})

        # temporary merge key
        homeTeamStats['key'] = 1
        awayTeamStats['key'] = 1

        # merge records together for one match-up record
        teamStats = pd.merge(homeTeamStats, awayTeamStats, on=['key'])
        temp = teamStats['AwayTeam']
        teamStats = teamStats.drop(columns=['AwayTeam'])
        teamStats.insert(loc=1, column='AwayTeam', value=temp)
        teamStats = teamStats.drop(columns=['key'])

        return teamStats

    def predict(self, homeTeam, awayTeam):
        if (homeTeam == awayTeam):
            return ["ERROR", "NULL"]
        else:
            teamstats = self.currentYearData.loc[(self.currentYearData['HomeTeam'] == homeTeam) &
                                     (self.currentYearData['AwayTeam'] == awayTeam)]
            pureData = teamstats.drop(columns=['HomeTeam', 'AwayTeam'])
            # Predict outcome and probas
            pred = self.predictingModel.predict(pureData)
            proba = self.predictingModel.predict_proba(pureData)

            # Add predictions to new dictionary
            predResult = {'HomeTeam' : homeTeam,
                          'AwayTeam' : awayTeam,
                          'Pred' : pred,
                          'Proba' : proba}

            self.history.append(predResult)

            return [pred, proba]

class Controller:
    ###Controller Class###
    def __init__(self, model, view):
        self._predModel = model
        self._view = view
        self.historyWindow = None
        self._connectSignalsAndSlots()

    def _predictResult(self):
        result = self._predModel.predict(
            homeTeam=str(self._view.teamSelection1.currentText()),
            awayTeam=str(self._view.teamSelection2.currentText())
            )

        self._view.setOutputDisplay(str(result[0]))
        if (str(result[1])!="NULL"):
            self._view.updateOutputGraph(result[1][0])

    def _showHistoryWindow(self):
        # if self.historyWindow is None:
        self.historyWindow = HistoryWindow(self._predModel.history)
        self.historyWindow.show()

    def _connectSignalsAndSlots(self):
        self._view.outputButton.clicked.connect(partial(self._predictResult))
        self._view.historyButton.clicked.connect(partial(self._showHistoryWindow))

def main():
    ###Main function for app###
    predModel = PredModel()
    app = QApplication([])
    appWindow = AppWindow()
    appWindow.show()
    Controller(model=predModel, view=appWindow)
    sys.exit(app.exec())

### Entry point ###
if __name__ == "__main__":
    main()


__author__ = 'napalmbrain'

from setuptools import setup

setup(
    name='tornado-jwt',
    version='0.0.1',
    author='napalmbrain',
    author_email='github@napalmbrain.sugarush.io',
    url='https://github.com/sugarush/tornado-jwt',
    packages=['tornado_jwt'],
    description='An asynchronous JWT authentication module for Tornado.',
    install_requires=[
        'pyjwt',
        'tornado',
        'tornado-json==0.0.1'
    ],
    dependency_links=[
        'git+https://github.com/sugarush/tornado-json.git@941d78a6bda7df92f84a534bafac48f759be695b#egg=tornado-json-0.0.1'
    ]
)


import torch
import torch.nn as nn
import numpy as np

from . import neuralnet

def loadMlpFromPytorch(net, layersNamesToBeExtracted = [], layerTypes = []):
    """ Extract a pytorch model its MLP part to form a network suitable for formal analysis.

        Usage: loadMlpFromPytorch(net, ["fc1", "fc2", "fc3", "fc4"], ["relu", "relu", "relu", "linear"])

        Keyword arguments:
        net -- network for analysis
        layersNamesToBeExtracted -- sequence of layers where the engine should follow and extract. Default value implies that the network is directly a MLP.
        layerTypes -- for the layers, what are their type. Currently it can be relu, linear, BN, elu

    """

    # TODO(CH): Add a mechanism to detect if the structure of the network is MLP, with hidden layers using ReLU and last using linear.

    nNet = neuralnet.NeuralNetwork()

    if len(layersNamesToBeExtracted) == 0 :
        # Extract all layers

        lastLayerName = None
        # Derive the name of the last layer
        for name, param in net.named_parameters():
            if name.endswith(".bias"):
                lastLayerName = name[:-5]

        #print(lastLayerName)

        for name, param in net.named_parameters():
            if name.endswith(".bias"):
                print("Processing layer "+name.replace(".bias", ""))
                weights = None
                bias = None

                # Find the associated weights
                for name2, param2 in net.named_parameters():
                    if(name2 == name.replace(".bias", ".weight")):
                        weights = param2.detach().numpy()

                bias = param.detach().numpy()
                numberOfOutputs = weights.shape[0]
                numberOfInputs = weights.shape[1]

                if name[:-5] == lastLayerName:
                    # Should be linear
                    nNet.addLinearLayer(weights, bias)
                else:
                    # Should be ReLU
                    nNet.addReLULayer(weights, bias)

        # Finally, do a sanity check if the dimension is right
        nNet.checkConsistency()
        return nNet

    else:
        for layerIndex in range(len(layersNamesToBeExtracted)):
            print("Processing layer "+layersNamesToBeExtracted[layerIndex])
            if layerTypes[layerIndex] != "BN":

                weights = None
                bias = None
                for name, param in net.named_parameters():
                    if name == layersNamesToBeExtracted[layerIndex]+".weight":
                        weights = param.detach().numpy()

                for name, param in net.named_parameters():
                    if name == layersNamesToBeExtracted[layerIndex]+".bias":
                        bias = param.detach().numpy()

                if layerTypes[layerIndex] == "linear":
                    nNet.addLinearLayer(weights, bias)
                elif  layerTypes[layerIndex] == "relu":
                    nNet.addReLULayer(weights, bias)
                elif  layerTypes[layerIndex] == "elu":
                    nNet.addELULayer(weights, bias)
                else:
                    raise Exception("Unknown layer type")

            else:
                weights = None
                bias = None
                for name, param in net.named_parameters():
                    if name == layersNamesToBeExtracted[layerIndex]+".weight":
                        weights = param.detach().numpy()

                for name, param in net.named_parameters():
                    if name == layersNamesToBeExtracted[layerIndex]+".bias":
                        bias = param.detach().numpy()

                # Moving mean and moving variance can't be accessed from named_parameters.
                # FIXME: Change the below code by accessing the moving mean and moving variance of the network.
                movingMean = 0
                movingVar = 1
                epsilon = 0.00001
                nNet.addBatchNormLayer(movingMean, movingVar, weights, bias)
                #raise NotImplementedError("Encountered BN whose implementation is still WiP")

        nNet.checkConsistency()
        return nNet

def loadMlpFromTensorFlow(net, layersNamesToBeExtracted, layerTypes):
    raise NotImplementedError


import torch
from torch import nn
from torchsummary import summary
from torchvision.models import mobilenet_v2

import numpy as np

class SenceMobilenetV2(nn.Module):

    def __init__(self, n_classes, pretrained=False):
        super(SenceMobilenetV2, self).__init__()

        self.model_ = mobilenet_v2(pretrained=pretrained)
        for param in self.model_.parameters():
            param.requires_grad = True #False
        self.ft_mobilenetv2 = nn.Sequential(
            nn.Linear(in_features=np.int(1000), out_features=n_classes, bias=True)
        )

    def forward(self, input):

        midlevel_features = self.model_(input)
        output = self.ft_mobilenetv2(midlevel_features)
        return output

if __name__ == "__main__":
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = SenceMobilenetV2().to(device)
    # print(str(model))
    summary(model, (3, 240, 320))


print("you have five chance to guess the numbrer")
print("you have enter the number from 1 to 10")
i=1
while i<=5:
    num=int(input("enter the number"))
    if num==7:
        print("wow,exelent you guess correct number")
        break
    elif num<7:
        print("entered your number is small,try one more time")
    elif num>7:
        print("entered your number is greater,try one more time")
    i+=1
else:
    print("game over")


arq = open("teste.txt", "r")
arq2 = open("saida.txt", "w")

texto = arq.readlines()

cont = 0
for line in texto:
    for letra in line:
        arq2.write(letra)
        print (letra, end = "")
        cont+=1

print("\nO numero de caracteres e: %d" %cont)

arq.close()
arq2.close()


# Prediction interface for Cog ⚙
# Reference: https://github.com/replicate/cog/blob/main/docs/python.md

import os
from dataclasses import dataclass
from typing import Dict, List
import tempfile
from pathlib import Path

import cog

from essentia.standard import MonoLoader, TensorflowPredictMusiCNN, TensorflowPredictVGGish
import numpy as np

MODELS_HOME = "/models"

@dataclass
class Model:
    name: str
    labels: List[str]
    model_files: Dict[str, str]

class Predictor(cog.Predictor):
    def setup(self):
        """Load the model into memory to make running multiple predictions efficient"""

    def predict_single_model(self, audio: str, model: Model):
        sr = 16000
        audio = MonoLoader(filename=str(audio), sampleRate=sr)()

        all_results = {}
        for name, file in model.model_files.items():
            if 'musicnn' in name.lower():
                classifier = TensorflowPredictMusiCNN(graphFilename=os.path.join(MODELS_HOME, file))
            elif 'vggish' in name.lower():
                classifier = TensorflowPredictVGGish(graphFilename=os.path.join(MODELS_HOME, file))
            else:
                classifier = None
            if not classifier:
                raise Exception("Unknown classifier")

            results = classifier(audio)
            averaged_predictions = np.mean(results, axis=0)
            all_results[name] = averaged_predictions

        result_order = list(all_results.keys())
        header = "|  | " + " | ".join(result_order)
        bar = "|---|" + "|".join(["---"] * len(all_results.keys()))
        table = header + "\n" + bar + "\n"
        for i, label in enumerate(model.labels):
            line = f"{label} | "
            for classifier in result_order:
                line += f" {all_results[classifier][i]:.2f} | "
            table += line + "\n"

        return table

    @cog.input("audio", type=cog.Path, help="Audio file to process")
    def predict(self, audio):

        models = [
            Model(name="Genre Dortmund", labels=["alternative", "blues", "electronic", "folkcountry", "funksoulrnb", "jazz", "pop", "raphiphop", "rock"],
                model_files={'MusiCNN MSD': 'genre_dortmund-musicnn-msd-2.pb',
                             'MusiCNN MTT': 'genre_dortmund-musicnn-mtt-2.pb',
                             'VGGish': 'genre_dortmund-vggish-audioset-1.pb'}),
            Model(name="Genre Rosamerica", labels=["classic", "dance", "hip hop", "jazz", "pop", "rhythm and blues", "rock", "speech"],
                    model_files={'MusiCNN MSD': 'genre_rosamerica-musicnn-msd-2.pb',
                                'MusiCNN MTT': 'genre_rosamerica-musicnn-mtt-2.pb',
                                'VGGish': 'genre_rosamerica-vggish-audioset-1.pb'}),
            Model(name="Genre Tzanetakis", labels=["blues", "classic", "country", "disco", "hip hop", "jazz", "metal", "pop", "reggae", "rock"],
                model_files={'MusiCNN MSD': 'genre_tzanetakis-musicnn-msd-2.pb',
                                'MusiCNN MTT': 'genre_tzanetakis-musicnn-mtt-2.pb',
                                'VGGish': 'genre_tzanetakis-vggish-audioset-1.pb'}),
            Model(name="Genre Electronic", labels=["ambient", "dnb", "house", "techno", "trance"],
                model_files={'MusiCNN MSD': 'genre_electronic-musicnn-msd-2.pb',
                                'MusiCNN MTT': 'genre_electronic-musicnn-mtt-2.pb',
                                'VGGish': 'genre_electronic-vggish-audioset-1.pb'})
        ]

        results = ""
        for model in models:
            results += f"# {model.name}\n\n"
            model_table = self.predict_single_model(audio, model)
            results += model_table + "\n\n"

        out_path = Path(tempfile.mkdtemp()) / "out.md"
        with open(out_path, "w") as f:
            f.write(results)
        return out_path


def islower(time1, time2):
    h1 = int(time1.split(':')[0])
    m1 = int(time1.split(':')[1])
    h2 = int(time2.split(':')[0])
    m2 = int(time2.split(':')[1])
    if h1 < h2:
        return True
    elif h1 == h2 and m1 <= m2:
        return True
    else:
        return False

def time_plus_time(time1, time2):
    h1 = int(time1.split(':')[0])
    m1 = int(time1.split(':')[1])
    h2 = int(time2.split(':')[0])
    m2 = int(time2.split(':')[1])
    h = h1 + h2 + ((m1 + m2) // 60)
    m = (m1 + m2) % 60
    return f'{h}:{m}'

def time_minus_time(time1, time2):
    h1 = int(time1.split(':')[0])
    m1 = int(time1.split(':')[1])
    h2 = int(time2.split(':')[0])
    m2 = int(time2.split(':')[1])
    h = h1 - h2
    m = m1 - m2
    if m < 0:
        h -= 1
        m = 60 - abs(m)
    return f'{h}:{m}'

def late(now: str, classes: str, buses: list[int]):
    buses.sort(reverse=True)
    for bus in buses:
        mins = time_plus_time(f'00:{bus}', '00:15')
        time = time_plus_time(now, mins)
        if islower(time, classes) and bus >= 5:
            return f'Выйти через {bus - 5} минут'
    return 'Опоздание'

# print(late('12:00', '12:40', [0, 1, 4, 6, 25]))
# print(late('9:20', '9:35', [4, 25, 30]))
# print(late('13:50', '14:30', [7, 17, 35, 48]))

Lesson 22. Function (return)/additional_7_delay.py


import sys

from alignfree.fastafileopener import parseFasta
from alignfree.spectracalculator import calculateSpectra
from alignfree.distancematrix import getDistanceMatrix, getMatrixStringFromMatrix, getColumnStringFromMatrix
from alignfree.neighborjoining import calculateNJ
from alignfree.userinterface import getParameter

def main():

    fastaFile, targetPath, kmerLength = getParameter(sys.argv)

    print('Open Fasta File')
    sequences = parseFasta(fastaFile)
    print('Calculate Spectra')
    labelList, spectra = calculateSpectra(sequences, kmerLength)

    print('Get distance-matrix')
    distanceMatrix = getDistanceMatrix(spectra)

    csvString = getColumnStringFromMatrix(distanceMatrix, labelList)
    print('Calculate NJ')
    newickString = calculateNJ([frozenset({label}) for label in labelList], distanceMatrix) + ';'

    targetCSV = open(targetPath + '.csv', 'w')
    targetCSV.write(csvString)

    targetTree = open(targetPath + '.tre', 'w')
    targetTree.write(newickString)

if __name__ == '__main__':
    main()


#Knights tour

X = [2, 1, -1, -2, -2, -1, 1, 2]
Y = [1, 2, 2, 1, -1, -2, -2, -1]

def isSafe(b,r,c):
	if (r>-1 and c>-1 and r<N and c<N and b[r][c]==0):
		return True
	else:
		return False

def solveKT(b,step,r,c):
	if step>=N*N:
		return True
	if isSafe(b,r,c):
		step+=1
		b[r][c] = step
		for i in range(8):
			if solveKT(b,step,r+X[i],c+Y[i]):
				return True
		b[r][c] = 0
		step -= 1
	return False

def showBoard(b):
	for r in b:
		r = [str(x) for x in r]
		print(" ".join(r))

if __name__=='__main__':
	try:
		N=int(input("Enter board size: "))
	except:
		print("Only integers allowed")
	else:
		board = [[0 for x in range(N)] for y in range(N)]
		feasible = solveKT(board,0,0,0)
		if feasible:
			showBoard(board)
		else:
			print("Cannot do a complete tour")


# -*- coding: utf-8 -*-
"""Tool to load program from YAML and print out progression for lifting."""
from __future__ import absolute_import, division, print_function

from dataclasses import dataclass
from typing import Any, Iterable, List, Optional, Mapping, Union, Sequence, Text, TextIO

# third party
import yaml

from contracts import check, contract, new_contract  # type: ignore

# TYPES ##########

Numeric = Union[float, int]
ProgramData = Sequence[Mapping[str, Any]]

# CONTRACTS ##########

new_contract('program_data', 'seq(map(str: *))')

# DATA CLASSES ##########

@dataclass(frozen=True)
class WorkingSet:
    percent: float
    reps: int

    # optional
    amrap: bool = False

    def calculate_weight(self, tm: Optional[Numeric] = None, rounding: Optional[Numeric] = None) -> Numeric:
        """Calculate weight based on optional training max.

        >>> WorkingSet(percent=0.5, reps=10).calculate_weight()
        0.5

        >>> WorkingSet(percent=0.5, reps=10).calculate_weight(205, 10.0)
        100.0
        """
        return mround(float(tm) * self.percent, rounding) if tm else self.percent

    def stringify(self, tm: Optional[Numeric] = None, rounding: Optional[Numeric] = None) -> Text:
        """Pretty-print string representation for working set with optional training max.

        >>> WorkingSet(percent=0.5, reps=10).stringify()
        '0.5 x 10'

        >>> WorkingSet(amrap=True, percent=0.5, reps=10).stringify(215, 10.0)
        '100.0 x 10+'
        """
        weight = self.calculate_weight(tm, rounding=rounding)
        reps = f'{self.reps}+' if self.amrap else self.reps
        return f'{weight:.1f} x {reps}'

@dataclass(frozen=True)
class Session:
    __slots__ = ('name', 'sets')
    name: str
    sets: List[WorkingSet]

@dataclass(frozen=True)
class MicroCycle:
    __slots__ = ('name', 'sessions')
    name: str
    sessions: List[Session]

@dataclass(frozen=True)
class MesoCycle:
    name: str
    micros: List[MicroCycle]

    # optional
    tm_inc: Numeric = 0

    def effective_tm(self, tm: Optional[Numeric] = None) -> Optional[Numeric]:
        """Get effective training max for this mesocycle.

        >>> MesoCycle('m1', []).effective_tm(100)
        100.0

        >>> MesoCycle('m1', [], tm_inc=5).effective_tm(100)
        105.0
        """
        return float(tm) + float(self.tm_inc) if tm else None

@dataclass(frozen=True)
class Program:
    __slots__ = ('mesos', 'name')
    name: str
    mesos: List[MesoCycle]

    def present(self, rounding: Optional[Numeric] = None, tm: Optional[int] = None) -> None:
        """Pretty print program."""
        header = '=' * max(20, len(self.name))
        print(header, self.name, header)
        flattened = ((s, u, m) for m in self.mesos for u in m.micros for s in u.sessions)
        for session, micro, meso in flattened:
            flattened_name = '.'.join([meso.name, micro.name, session.name]).upper()
            banner = '-' * min(10, len(flattened_name))

            etm = meso.effective_tm(tm)
            if tm:
                print(banner, flattened_name, f'[TM: {etm}]', banner)
            else:
                print(banner, flattened_name, banner)

            for ws in session.sets:
                print(ws.stringify(meso.effective_tm(tm), rounding))

    def present_table(self, rounding: Optional[Numeric] = None, tm: Optional[int] = None) -> None:
        """Pretty print program as tabular data."""
        try:
            from tabulate import tabulate
        except ImportError:
            raise ImportError('Need to pip install tabulate!')

        header = '=' * max(20, len(self.name))
        print(header, self.name, header)

        for meso in self.mesos:
            headers: List[str] = []
            table: List[List[str]] = []
            for micro_number, micro in enumerate(meso.micros):
                headers.append('.'.join([meso.name, micro.name]))
                for session_number, session in enumerate(micro.sessions):
                    value = '\n'.join(ws.stringify(meso.effective_tm(tm), rounding) for ws in session.sets)
                    if len(table) <= session_number:
                        table.append([])
                    if len(table[session_number]) <= micro_number:
                        table[session_number].append(value)
                    else:
                        table[session_number][micro_number] = value
            print(tabulate(table, headers=headers, tablefmt='grid'))

# PUBLIC FUNCTIONS ##########

@contract(mesos='program_data')
def generate_mesos(mesos: ProgramData) -> Iterable[MesoCycle]:
    """Generate mesocycles from data."""
    for meso in mesos:
        micros = [micro for micro in generate_micros(meso['micros'])]
        options = {k: v for k, v in meso.items() if k in ('tm_inc',)}
        yield MesoCycle(meso['name'], micros, **options)

@contract(micros='program_data')
def generate_micros(micros: ProgramData) -> Iterable[MicroCycle]:
    """Generate microcycles from data."""
    for micro in micros:
        sessions = [session for session in generate_sessions(micro['sessions'])]
        yield MicroCycle(micro['name'], sessions)

@contract(sessions='program_data')
def generate_sessions(sessions: ProgramData) -> Iterable[Session]:
    """Generate sessions from data."""
    for session in sessions:
        workingsets = [ws for ws in generate_workingsets(session['sets'])]
        yield Session(session['name'], workingsets)

@contract(workingsets='program_data')
def generate_workingsets(workingsets: ProgramData) -> Iterable[WorkingSet]:
    """Generate workingsets from data for session."""
    for ws in workingsets:
        workingset = WorkingSet(amrap=ws.get('amrap', False), percent=ws['percent'], reps=ws['reps'])
        for _ in range(ws.get('sets', 1)):
            yield workingset

def load_program(handle: TextIO) -> Program:
    """Load program from YAML file handle."""
    program: Mapping[str, Any] = yaml.safe_load(handle)
    check('map(str: str|program_data)', program)
    mesos = [meso for meso in generate_mesos(program['mesos'])]
    return Program(program['name'], mesos)

def mround(value: Numeric, rounding: Optional[Numeric] = None) -> Numeric:
    """Round to nearest rounding value.

    >>> mround(103, 2.5)
    102.5
    """
    if not rounding:
        rounding = 5.0
    return (float(value) // rounding) * rounding


"""
ConsoleController: User interface for manually solving
Anne Hoy's problems from the console.
"""

from toah_model import TOAHModel, IllegalMoveError

def move(model, origin, dest):
    """ Apply move from origin to destination in model.

    May raise an IllegalMoveError.

    @param TOAHModel model:
        model to modify
    @param int origin:
        stool number (index from 0) of cheese to move
    @param int dest:
        stool number you want to move cheese to
    @rtype: None
    """
    try:
        model.move(origin, dest)
    except IllegalMoveError:
        print("You have entered an illegal move.")

class ConsoleController:
    """ Controller for text console.
    """

    def __init__(self, number_of_cheeses, number_of_stools):
        """ Initialize a new ConsoleController self.

        @param ConsoleController self:
        @param int number_of_cheeses:
        @param int number_of_stools:
        @rtype: None
        """
        self.tm = TOAHModel(number_of_stools)
        self.tm.fill_first_stool(number_of_cheeses)
        self.number_of_stools = number_of_stools
        self.number_of_cheeses = number_of_cheeses

    def choose_valid_stool(self, stool_type):
        """ Prompts the user to enter a valid stool selection.
        according to what stool the user is looking at.
        If the input is valid, then the stool index will be
        returned.

        @type self: ConsoleController
        @type stool_type: str
        @rtype: int
        """
        while True:
            try:
                stool_selection = int(input('Type in a valid ' + stool_type +
                                            ' stool: \n'))
            except ValueError:
                print('That is not a valid ' + stool_type + ' stool!')
                continue
            else:
                if stool_selection > self.number_of_stools \
                        or stool_selection < 1:
                    print('Stool index out of range!')
                else:
                    return stool_selection - 1

    def play_loop(self):
        """ Play Console-based game.

        @param ConsoleController self:
        @rtype: None

        TODO:
        -Start by giving instructions about how to enter moves (which is up to
        you). Be sure to provide some way of exiting the game, and indicate
        that in the instructions.
        -Use python's built-in function input() to read a potential move from
        the user/player. You should print an error message if the input does
        not meet the specifications given in your instruction or if it denotes
        an invalid move (e.g. moving a cheese onto a smaller cheese).
        You can print error messages from this method and/or from
        ConsoleController.move; it's up to you.
        -After each valid move, use the method TOAHModel.__str__ that we've
        provided to print a representation of the current state of the game.
        """
        playing = True
        print(self.tm)
        while playing:
            origin_stool = self.choose_valid_stool('origin')
            destination_stool = self.choose_valid_stool('destination')
            move(self.tm, origin_stool, destination_stool)
            print(self.tm)
            if len(self.tm.get_stool_list()[-1]) == self.number_of_cheeses:
                print('\nYou have won the game!')
                print('Your total move count is: ' +
                      str(self.tm.get_move_seq().length()))
                print('The game will now exit.')
                playing = False
            else:
                keep_playing = input("\nPress enter to "
                                     "continue or type e to exit: \n")
                if keep_playing == 'e':
                    print("The game will now exit.")
                    playing = False

def prompt_number(item):
    """ Prompts the user to input a valid integer
    greater than 0 to be used for the inputed item.

    @type item: str
    @rtype: int
    """
    while True:
        try:
            num_selection = int(input("Enter a valid number of "
                                      + item + ':\n'))
        except ValueError:
            print("You have inputed an invalid number!")
            continue
        else:
            if num_selection > 0:
                return num_selection
            else:
                print('You have inputed an invalid number!')

if __name__ == '__main__':
    INSTRUCTIONS0 = "The goal of this game is to move the entire stack of "\
                    "cheese rounds from the first stool to the last stool."
    INSTRUCTIONS1 = "Each move consists of choosing an origin stool and then"\
                    " a destination stool.\nThe very top cheese of the origin"\
                    " stool is moved on top of the destination stool."
    INSTRUCTIONS2 = "The id of the stools are in the order of how they are "\
                    "displayed, with 1 being the first stool."
    INSTRUCTIONS3 = "A move is only valid if you pick from a non empty stool"\
                    " or if you choose an origin stool with a smaller " \
                    "cheese block."\
                    " than its destination stool."
    INSTRUCTIONS4 = "Each stool choice must be a valid natural number between "\
                    "1 and the total number of stools in the game."
    INSTRUCTIONS5 = "At the end of each move, you will be given the option to "\
                    "exit the game by simply typing e."
    INSTRUCTIONS6 = "Good luck and have fun!"
    print("Hello, welcome to the Tower of Anne Horton!"
          "\nPlease select one of the following numbers below.")
    MENU = None
    while True:
        try:
            MENU = int(input("\nChoose one of the following numbers "
                             "below:\n1: Instructions \n2: Begin game \n3: "
                             "Exit \n"))
        except ValueError:
            print("Invalid Menu selection.")
        else:
            if MENU in range(1, 4):
                break
            else:
                print("Invalid Menu selection.")

    if MENU == 1:
        print("Press enter to skip through the instructions.")
        NEXT = input('')
        print(INSTRUCTIONS0)
        NEXT = input('')
        print(INSTRUCTIONS1)
        NEXT = input('')
        print(INSTRUCTIONS2)
        NEXT = input('')
        print(INSTRUCTIONS3)
        NEXT = input('')
        print(INSTRUCTIONS4)
        NEXT = input('')
        print(INSTRUCTIONS5)
        NEXT = input('')
        print(INSTRUCTIONS6)
        NEXT = input('')
        MENU = 2
    if MENU == 2:
        STOOLS = prompt_number('stools')
        while STOOLS == 1:
            print("\nYou cannot play with one stool!")
            STOOLS = prompt_number('stools')
        CHEESES = prompt_number('cheeses')
        CC = ConsoleController(CHEESES, STOOLS)
        CC.play_loop()
    elif MENU == 3:
        print('\nThe game will now exit.')

    import python_ta
    python_ta.check_all(config="consolecontroller_pyta.txt")


#!/usr/bin/env python
# coding: utf-8

# In[3]:

from functools import reduce
def function_one():
    print("I am function one")

def function_two():
    return function_one

def function_three(x):
    return x, x**2, x**3

def function_four(x):
    return abs(x)

def function_five(a,b,c):
    return a+b+c

def function_six(x):
    if x%2 ==0:
        return False
    return True

def function_seven(a,b):
    return a+b

def main():
    """
    another_name = fuction_one
    another_name()
    my_list = [1,"string",function_one]
    my_list[2]()
    print(function_one)
    # function composition
    (function_two())()
    my_list_2 = ["ram", "rohit", "ansari", "aman", "surabhi"]
    print(sort(my_list_2))
    print(sorted(my_list_2, key=len))
    """
    #lamda
    lambda_ex = (lambda x: x**2)
    print(lambda_ex(5))
    print((lambda x: x + 10)(90))
    my_list_2 = ["ran", "rohit", "ansari", "aman", "surabhi"]
    print(sorted(my_list_2, key=lambda x: -len(x)))

    #multiple values
    print(function_three(3))

    lambda_multiple = (lambda x: [x, x * 2, x * 3])
    print(lambda_multiple(4))
    lambda_multiple = (lambda x: (x, x*2,x*3))
    print(lambda_multiple(4))

    #map:(map(function/operation, list/iterable))
    my_list_3 = [1,-4,7,-10,101,-123]
    map_lambda_obj = map(function_four, my_list_3)
    print("Lambda method abs: ",list(map_lambda_obj))
    for item in map_lambda_obj:
        print(item)
    map_output =list(map(function_four, my_list_3))
    print(map_output)

    #map multiple iterables
    list1 = [1,2,3,4,5]
    list2 = [6,7,8,9,10]
    list3 = [11,12,13,14,15]
    print(map(function_five, list1,list2,list3))
    print(list(map(lambda x1,x2,x3: x1 + x2 + x3, list1, list2, list3)))

    #filter
    list4 = []
    for i in range(1,101,1):
        list4.append(i)
    #print(list4)
    print(list(filter(function_six, list4)))
    print(list(filter(lambda x: x%2 == 1, list4)))

    #reduce
    list5 = []
    for i in range(1,11,1):
        list5.append(i)
    print(list5)
    print(reduce(function_seven, list5))
    print(reduce(function_seven, list5, 10))
    print("List5 is: ", list5)
    print(sum(list5))

    #List comprehension
    list6 = []
    for i in range(1, 51, 1):
        list6.append(i)
    print(list6)
    list7 = [itr for itr in range(1,51,1)]
    print(list7)
    list8 = [i + j for i in range(1,10) for j in range(1,10) if i == j]
    print(list8)

    #dictionary comprehension
    my_dict ={i: i ** 3 for i in range(1,10) if i%2 ==0}
    print(my_dict)

    #set comprehension
    duplicates_list = [1,2,3,4,4,5,5,5]
    my_set = {i for i in duplicates_list if i%2 ==1}
    print(my_set)
    my_tuple = (i for i in range(1,10))
    for i in my_tuple:
        print(i)
    #print(my_tuple)

if __name__=="main__":
    main()

# # Practise

# In[17]:

#1.Define any class of your choice and use these keywords to introspect your object:
#dir, id, type, hasattr(), getattr(), __repr__, __doc__, __name__
class Car:
    def __init__(self,company_name,model,year_of_release,price):
        self.company_name=company_name
        self.model=model
        self.year_of_release=year_of_release
        self.price=price

    def print_car_details(self):
        print("Company name: ",self.company_name,"\tModel: ",self.model,"\tYear of market release: ",self.year_of_release,"\tPrice: ",self.price)

    def __repr__(self):
        return "Car attributes: ",self.company_name,self.model,self.year_of_release,self.price

def main():
    c1=Car("Tata","Punch",2020,600000)
    c1.print_car_details()
    print(dir(c1))
    print(id(c1))
    print(type(c1))
    print(hasattr(c1,"print_car_details"))
    print(getattr(c1,"model"))
    #print(repr(c1))
    #print(c1)
    print(Car.__doc__)
    print(Car.__name__)

if __name__=="__main__":
    main()

# In[22]:

#2.Define 1 parent class and 3 child classes of your choice. The parent class should be an abstract class and you must
#create 3 abstractmethods in it which should be overridden in the child classes
from abc import ABC, abstractmethod
class Laptop(ABC):
    @abstractmethod
    def __init__(self):
        pass

    @abstractmethod
    def print_laptop_details(self):
        pass

class Dell(Laptop):
    def __init__(self,model,ram,storage,price):
        self.model=model
        self.ram=ram
        self.storage=storage
        self.price=price

    def print_laptop_details(self):
        print("Dell Laptop have, Model no: ",self.model,"\tRAM: ",self.ram,"\tStorage: ",self.storage,"\tPrice: ",self.price)

class HP(Laptop):
    def __init__(self,model,ram,storage,price):
        self.model=model
        self.ram=ram
        self.storage=storage
        self.price=price

    def print_laptop_details(self):
        print("HP Laptop have, Model no: ",self.model,"\tRAM: ",self.ram,"\tStorage: ",self.storage,"\tPrice: ",self.price)

class Lenovo(Laptop):
    def __init__(self,model,ram,storage,price):
        self.model=model
        self.ram=ram
        self.storage=storage
        self.price=price

    def print_laptop_details(self):
        print("Lenovo Laptop have, Model no: ",self.model,"\tRAM: ",self.ram,"\tStorage: ",self.storage,"\tPrice: ",self.price)

def main():
    d1=Dell("Dell1","4GB","250GB HDD",35000)
    d1.print_laptop_details()
    h1=HP("HP4","8GB","512GB HDD",55000)
    h1.print_laptop_details()
    l1=Lenovo("GamerX","16GB","2TB SSD",87000)
    l1.print_laptop_details()

if __name__=="__main__":
    main()

# In[30]:

#3.Create 3 classes in which 2 are parent child and 1 is completely different and utilise the isinstance and issubclass
#keywords to show  their usage.
class Language:
    def __init__(self,name,level):
        self.name=name
        self.level=level

    def print_details(self):
        print("Programming language name: ",self.name,"\tLevel: ",self.level)

class Programming(Language):
    def __init__(self,name,level,applications):
        super().__init__(name,level)
        self.applications=applications

    def print_details(self):
        print("Programming language name: ",self.name,"\tLevel: ",self.level,"\tApplications: ",self.applications)

class Speaking:
    def __init__(self,name,applications):
        self.name=name
        self.applications=applications

    def print_details(self):
        print("Speaking language name: ",self.name,"\tApplications: ",self.applications)

def main():
    l1=Language("Java","High Level")
    l1.print_details()
    p1=Programming("Python","High Level","AI")
    p1.print_details()
    s1=Speaking("English","Communication")
    s1.print_details()
    print(issubclass(Programming,Language))
    print(issubclass(Speaking,Language))
    print(issubclass(Speaking,Programming))
    print(issubclass(Language,Programming))
    print(issubclass(Language,Speaking))

if __name__=="__main__":
    main()

# In[ ]:

# In[ ]:

# In[ ]:


#%%
#!/usr/bin/env python
import os, sys, json, argparse, math
import cv2
import numpy as np
from flask import Flask, render_template, Response
from camera_opencv import Camera
import tensorflow as tf
from datetime import datetime
sys.path.insert(0, os.path.abspath(''))
from segment.display import DrawFeatures

parser = argparse.ArgumentParser()

parser.add_argument('-debug', action='store_true',help='Wait for debugge attach')

#parser.add_argument('-model_dir', type=str, default='./trainings/unetcoco',help='Directory to store training model')
parser.add_argument('-model_dir', type=str, default=None,help='Directory to store training model')
parser.add_argument('-loadsavedmodel', type=str, default='./saved_model/2020-09-07-16-16-50-dl3', help='Saved model to load if no checkpoint')

parser.add_argument('-record_dir', type=str, default='./record', help='Path training set tfrecord')
parser.add_argument('-devices', type=json.loads, default=["/gpu:0"],  help='GPUs to include for training.  e.g. None for all, [/cpu:0], ["/gpu:0", "/gpu:1"]')
parser.add_argument('-image_size', type=json.loads, default='[480, 640]', help='Training crop size [height, width]/  [90, 160],[120, 160],[120, 160], [144, 176],[288, 352], [240, 432],[480, 640],[576,1024],[720, 960], [720,1280],[1080, 1920]')
parser.add_argument('-image_depth', type=int, default=3, help='Number of input colors.  1 for grayscale, 3 for RGB')

FLAGS, unparsed = parser.parse_known_args()

config = {
      'input_shape': [FLAGS.image_size[0], FLAGS.image_size[1], FLAGS.image_depth],
      'area_filter_min': 250,
      'size_divisible': 32,
      }

app = Flask(__name__)

model = None
infer = None
lut = None

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')

def PadValid(image, divisible=config['size_divisible']):
    [height, width, depth] = image.shape
    newwidth = int(divisible*math.ceil(float(width)/divisible))
    newheight = int(divisible*math.ceil(float(height)/divisible))
    pad = [[0,newheight-height],[0,newwidth-width], [0,0]]
    if np.max(pad) > 0:
        image = np.pad(image, pad)
    return image
    #return tf.image.pad_to_bounding_box(image, 0, 0, height, width)

def CropOrigonal(image, height, width):
    return image[:height,:width,:]
    #return tf.image.crop_to_bounding_box(image, 0, 0, height, width

def gen(camera):
    """Video streaming generator function."""

    #loaded = tf.saved_model.load_v2(FLAGS.model)
    #loaded = tf.saved_model.load(FLAGS.savedmodel)
    #print(list(loaded.signatures.keys()))
    #infer = loaded.signatures["serving_default"]
    #print(infer.structured_outputs)
    #print (infer.inputs[0])

    while True:
        img = camera.get_frame()
        [height, width, depth] = img.shape
        #print('img.shape={}'.format(img.shape))
        #img = cv2.flip(img, +1)
        tbefore = datetime.now()
        img = PadValid(img)

        if model is not None:
            seg = model.predict(np.expand_dims(img, axis=0))
            seg = tf.squeeze(seg).astype(np.uint8) # Drop batch dimension
        elif infer is not None:
            outputs = infer(tf.constant(np.expand_dims(img.astype(np.float32), axis=0)))
            seg = tf.math.argmax(outputs['logits'], axis=-1, output_type=tf.int32)
            seg = tf.squeeze(seg).numpy().astype(np.uint8)

        tPredict = datetime.now()
        #imseg = img
        #imseg = DrawFeatures(img, seg, config)

        seg = [cv2.LUT(seg, lut[:, i]) for i in range(3)]
        seg = np.dstack(seg)
        imseg = (img*seg).astype(np.uint8)
        #imseg = (img).astype(np.uint8)

        imseg = CropOrigonal(imseg, height, width)

        tAfter = datetime.now()
        dInfer = tPredict-tbefore
        dImAn = tAfter-tPredict

        #outputs['pred_age'].numpy()

        font = cv2.FONT_HERSHEY_COMPLEX_SMALL
        resultsDisplay = 'infer:{:.3f}s display:{:.3f}s'.format(dInfer.total_seconds(), dImAn.total_seconds())
        cv2.putText(imseg, resultsDisplay, (10,25), font, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
        # encode as a jpeg image and return it
        frame = cv2.imencode('.jpg', imseg)[1].tobytes()

        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(Camera(config)), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    FLAGS, unparsed = parser.parse_known_args()

    if FLAGS.debug:
        # https://code.visualstudio.com/docs/python/debugging#_remote-debugging
        # Launch applicaiton on remote computer:
        # > python3 -m ptvsd --host 0.0.0.0 --port 3000 --wait predict_imdb.py
        import ptvsd
        # Allow other computers to attach to ptvsd at this IP address and port.
        ptvsd.enable_attach(address=('0.0.0.0', 3000), redirect_output=True)
        # Pause the program until a remote debugger is attached
        print("Wait for debugger attach")
        ptvsd.wait_for_attach()
        print("Debugger Attached")

    print(tf.version)

    trainingsetDescriptionFile = '{}/description.json'.format(FLAGS.loadsavedmodel)
    trainingsetDescription = json.load(open(trainingsetDescriptionFile))['config']['trainingset']

    config['ignore_label'] = trainingsetDescription['classes']['ignore']
    config['classes'] = trainingsetDescription['classes']['classes']
    config['background'] = trainingsetDescription['classes']['background']
    config['trainingset'] = trainingsetDescription

    if FLAGS.model_dir is not None:
        try:
            model = tf.keras.models.load_model(FLAGS.model_dir) # Load from checkpoint
        except:
            print('Unable to load weghts from {}'.format(FLAGS.model_dir))

    if not model and FLAGS.loadsavedmodel:
        try:
            # model = tf.keras.models.load_model(FLAGS.loadsavedmodel) # Load from checkpoint

            loaded = tf.saved_model.load(FLAGS.loadsavedmodel)
            print(list(loaded.signatures.keys()))
            infer = loaded.signatures["serving_default"]
            print(infer.structured_outputs)
            print (infer.inputs[0])

            lut = np.zeros([256,3], dtype=np.uint8)
            for obj in config['trainingset']['classes']['objects']: # Load RGB colors as BGR
                lut[obj['trainId']][0] = obj['color'][2]
                lut[obj['trainId']][1] = obj['color'][1]
                lut[obj['trainId']][2] = obj['color'][0]
            lut = lut.astype(np.float) * 1/255. # scale colors 0-1
            lut[config['background']] = [1.0,1.0,1.0] # Pass Through

        except:
            print('Unable to load weghts from {}'.format(FLAGS.loadsavedmodel))

    app.run(host='0.0.0.0', threaded=True)


EXAMPLE = """\
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6\
"""

class BootCode:

    def __init__(self, data):
        # Parsing
        instructions = []
        for line in data.splitlines():
            op, _, val = line.partition(" ")
            val = int(val)
            instructions.append((op, val))
        self.__instructions = instructions
        self.reset()

    def reset(self):
        """Resets the instructions list and the accumulator"""
        self.instructions = self.__instructions.copy()
        self.accumulator = 0

    def run(self):
        """Run the program and returns True if successful.

        Returns False if an infinite loop is detected.
        """
        self.accumulator = 0
        pointer = 0
        seen = set()
        while pointer < len(self.instructions):
            # Unpack operation
            operation, value = self.instructions[pointer]

            # Check if the operation already was executed once
            if pointer in seen:
                return False
            else:
                seen.add(pointer)

            # Execute the operation
            if operation == "nop":
                pass
            elif operation == "acc":
                self.accumulator += value
            elif operation == "jmp":
                pointer += value
                continue
            else:
                raise ValueError(f"unknown operation: {operation}")

            pointer += 1
        return True

def test():
    test_bc = BootCode(EXAMPLE)
    exit_code = test_bc.run()
    assert exit_code == False
    assert test_bc.accumulator == 5

    test_bc.instructions[-2] = ("nop", -4)
    exit_code = test_bc.run()
    assert exit_code == True
    assert test_bc.accumulator == 8

def main1():
    with open("day08/input.txt") as f:
        inputs = f.read()
    bc = BootCode(inputs)
    bc.run()
    print("The accumulator holds", bc.accumulator) # expect 5

def main2():
    with open("day08/input.txt") as f:
        inputs = f.read()
    bc = BootCode(inputs)
    i = 0
    remember = tuple()

    while not bc.run():
        # Restore old opcode, if one has been replaced
        if remember:
            bc.reset()
        # Replace nop or jmp with jmp or nop
        op, val = bc.instructions[i]
        if op == "jmp":
            bc.instructions[i] = ("nop", val)
            remember = (i, "jmp")
        elif op == "nop":
            bc.instructions[i] = ("jmp", val)
            remember = (i, "nop")
        i += 1

    print(f"Replaced {remember[1]} in line {remember[0]}.")
    print(f"The accumulator holds {bc.accumulator}.")

if __name__ == "__main__":
    test()
    print("Part1:")
    main1()
    print("Part2:")
    main2()


import base64
import gzip
import json

def unciv_save(savename, mode='r', preview=False, savedict=None):
    def unciv_decode(text: str):
        text = base64.b64decode(text)
        gzip_text = gzip.decompress(text)
        result = str(gzip_text, "utf-8")
        return result

    def unciv_encode(text: str):
        text = text.encode(encoding="utf-8")
        gzip_text = gzip.compress(text)
        result = base64.b64encode(gzip_text)
        return str(result, encoding='utf-8')

    def read(file: str):
        f = open(file, 'r')
        text = f.read()
        f.close()
        return text

    def write(file: str, text: str):
        f = open(file, 'w')
        f.write(text)
        f.close()

    def save2dict(save: str):
        return json.loads(save)

    def dict2save(dict: dict):
        return json.dumps(dict)
    if mode == "r":
        if preview == True:
            save_read = read(f"files/{savename}_Preview")
        else:
            save_read = read(f"files/{savename}")
        save_decode = unciv_decode(save_read)
        save = save2dict(save_decode)
        return save
    if mode == "w":
        savetext = dict2save(savedict)
        saveencode = unciv_encode(savetext)
        if preview == True:
            write(f"files/{savename}_Preview", saveencode)
        else:
            write(f"files/{savename}", saveencode)

def autowriter(savename, savedict):
    for i in [True, False]:
        print(i)

def initializer():
    pass

save_preview = unciv_save(
    "1ce48a9f-3b8c-403f-8681-73699a2da954", preview=True)

for i in save_preview:
    print(i)
print(save_preview)


from datetime import datetime, timezone
from functools import partial
import struct
from enum import Enum

from demo_analyzer.constants import FormatStrings

class Field:
    _creation_counter = 0

    def __init__(self, flag=None):
        self._creation_counter = Field._creation_counter
        Field._creation_counter += 1

        self.flag = flag

        self.field_name = None

    def bind(self, field_name):
        self.field_name = field_name

        if self.flag is None:
            self.flag = field_name

    def get_attribute(self, data):
        return data.get(self.field_name, None)

    def encode(self, value):
        raise NotImplementedError

    def get_value(self, raw_value):
        return raw_value

    def decode(self, buffer):
        raise NotImplementedError

FMT_BYTE_ORDERS = ('@', '=', '<', '>', '!')

class StructField(Field):
    fmt = None
    size = None

    def __init__(self, fmt=None, **kwargs):
        super().__init__(**kwargs)

        if fmt:
            self.fmt = fmt

        if isinstance(self.fmt, Enum):
            self.fmt = self.fmt.value

        if self.fmt[0] not in FMT_BYTE_ORDERS:
            self.fmt = '<' + self.fmt

        self.size = struct.calcsize(self.fmt)

    def encode(self, value):
        return struct.pack(
            self.fmt,
            value
        )

    def decode(self, buffer):
        return struct.unpack(
            self.fmt,
            buffer.read(self.size)
        )[0]

class ByteField(StructField):
    fmt = FormatStrings.BYTE

class Int8Field(StructField):
    fmt = FormatStrings.INT8

class UInt8Field(StructField):
    fmt = FormatStrings.UINT8

class Int16Field(StructField):
    fmt = FormatStrings.INT16

class UInt16Field(StructField):
    fmt = FormatStrings.UINT16

class Int32Field(StructField):
    fmt = FormatStrings.INT32

class UInt32Field(StructField):
    fmt = FormatStrings.UINT32

class Int64Field(StructField):
    fmt = FormatStrings.INT64

class UInt64Field(StructField):
    fmt = FormatStrings.UINT64

class FloatField(StructField):
    fmt = FormatStrings.FLOAT

class BoolField(StructField):
    fmt = FormatStrings.BOOL

class TimestampField(StructField):
    def get_attribute(self, data):
        return super().get_attribute(data).timestamp()

    def get_value(self, raw_value):
        return datetime.fromtimestamp(raw_value, timezone.utc)

class StringField(Field):
    @staticmethod
    def encode(value):
        return value + '\x00'

    @staticmethod
    def decode(buffer):
        slist = []

        while True:
            try:
                val = buffer.read(1)[0]
            except ValueError:
                break
            if val == 0:
                break
            slist.append(chr(val))

        return ''.join(slist)

class FlagsField(StructField):
    def __init__(self, flags, **kwargs):
        super().__init__(**kwargs)

        self.flags = flags

    def get_attribute(self, data):
        flags = super().get_attribute(data)
        if flags is None:
            flags = self.generate_flags(data)
        return flags

    def encode(self, flags):
        flags_int = sum(
            (getattr(self.flags, name) for name, value in flags if value is True)
        )
        return super().encode(flags_int)

    def get_value(self, raw_value):
        return {
            name: self.bitwise_check(raw_value, member)
            for name, member in self.flags.__members__.items()
        }

    def generate_flags(self, data):
        return {
            name: True if data.get(name, None) is not None else False
            for name in self.flags.__members__
        }

    @staticmethod
    def bitwise_check(bits, bit_to_check):
        return True if (bits & bit_to_check) == bit_to_check else False


'''VPT, Vantage Point Tree'''

import math
import statistics
from datetime import timedelta
from typing import Generic, TypeVar, List, Tuple, Dict, Set, Union, Optional, Callable, Final, Iterator, Any, Counter, Sequence, Literal, Deque, Iterable
from dataclasses import dataclass, field
import numpy as np
import json
from multiprocessing import Pool, pool

from .abstract_similarity_tree import AbstractSimilarityTree, K, V
from .caches import FunctionCache, DistanceCache, MinFinder
from .. import lib
from ..lib import PriorityQueue, ProgressBar, Timing

ZERO_ELEMENT = '-'
# TOLERANCE = 0.0

@dataclass
class _MVPFork(Generic[K]):
    parent: Optional['_MVPFork[K]'] = field(repr=False)
    pivot: K
    radii: List[float] = field(default_factory=list)
    children: List['_MVPNode[K]'] = field(default_factory=list)

@dataclass
class _MVPLeaf(Generic[K]):
    parent: Optional['_MVPFork[K]'] = field(repr=False)
    elements: List[K] = field(default_factory=list)

_MVPNode = Union[_MVPFork[K], _MVPLeaf[K]]

class MVPTree(AbstractSimilarityTree[K, V]):
    _K: int  # arity
    _leaf_size: int
    # _distance_function: Callable[[V, V], float]
    _distance_cache: DistanceCache[K, V]
    _elements: Set[K]
    _home_leaves: Dict[K, _MVPLeaf[K]]
    _root: _MVPNode[K]

    def __init__(self, distance_function: Callable[[V, V], float], keys_values: Sequence[Tuple[K, V]] = (), arity: int = 4, leaf_size: int = 8,
                 n_processes: int = 1, root_element: Optional[Tuple[K, V]] = None) -> None:
        assert leaf_size >= 1
        self._K = arity
        self._leaf_size = leaf_size
        self._distance_function = distance_function
        self._distance_cache = DistanceCache(distance_function)
        self._elements = set()  # keys of elements currently present in the tree (pivot is not necessarily element)
        # self._home_leaves = {}  # mapping of elements to their accommodating leaves
        self._root = _MVPLeaf(parent=None)
        self._bulk_load(keys_values, with_progress_bar=True, n_processes=n_processes, root_element=root_element)

    def __len__(self) -> int:
        '''Return number of elements'''
        return len(self._elements)

    def __contains__(self, element) -> bool:
        '''Decide if element is present in the tree'''
        return element in self._elements

    def _bulk_load(self, keys_values: Sequence[Tuple[K, V]], with_progress_bar: bool = False, n_processes: int = 1, root_element: Optional[Tuple[K, V]] = None) -> None:
        elements = [k for k, v in keys_values]
        n = len(elements)
        assert len(self) == 0, 'Bulk-load only works on an empty tree'
        assert len(set(elements)) == n, 'Duplicate keys are not allowed'
        if n == 0:
            return
        self._elements.update(elements)
        if root_element is not None:
            self._distance_cache.insert(*root_element)
            root_pivot: Optional[K] = root_element[0]
        else:
            root_pivot = None
        for k, v in keys_values:
            self._distance_cache.insert(k, v)
        bar = ProgressBar(len(elements), title=f'Bulk-loading {n} elements into {self._K}-way MVPTree').start() if with_progress_bar else None
        if n_processes == 1:
            self._root = self._create_node_from_bulk(elements, pivot=root_pivot, progress_bar=bar)
        else:
            with Pool(n_processes) as pool:
                self._root = self._create_node_from_bulk(elements, pivot=root_pivot, progress_bar=bar, pool=pool)
        if bar is not None:
            bar.finalize()

    def _create_node_from_bulk(self, elements: List[K], pivot: Optional[K] = None, parent_pivot: Optional[K] = None, progress_bar: Optional[ProgressBar] = None, pool: Optional[pool.Pool] = None) -> _MVPNode[K]:
        if len(elements) <= self._leaf_size:
            new_leaf = _MVPLeaf(parent=None, elements=elements)
            if progress_bar is not None:
                progress_bar.step(len(elements))
            return new_leaf
        else:
            if pivot is None:
                pivot = self._select_pivot0(elements, parent_pivot)
                # pivot = self._select_pivot1(elements, parent_pivot)
                elements.remove(pivot)
            bins, rs = self._partition(pivot, elements, pool=pool)
            new_fork = _MVPFork(parent=None, pivot=pivot, radii=rs)
            for bin in bins:
                subtree = self._create_node_from_bulk(bin, parent_pivot=pivot, progress_bar=progress_bar, pool=pool)
                new_fork.children.append(subtree)
                subtree.parent = new_fork
            return new_fork

    def _select_pivot0(self, elements: List[K], parent_pivot: Optional[K]) -> K:
        return elements[0]

    def _select_pivot1(self, elements: List[K], parent_pivot: Optional[K]) -> K:
        if parent_pivot is None:
            parent_pivot = elements[0]
        d_max, pivot = max((self.get_distance(parent_pivot, k), k) for k in elements)
        return pivot

    def _partition(self, pivot: K, elements: List[K], pool: Optional[pool.Pool] = None) -> Tuple[List[List[K]], List[float]]:
        bins: list[list[K]] = [[] for i in range(self._K)]
        self._distance_cache.calculate_distances([(pivot, elem) for elem in elements], pool=pool)
        distances = [self.get_distance(pivot, elem) for elem in elements]
        rs = statistics.quantiles(distances, n=self._K)
        rs.insert(0, min(distances))
        rs.append(max(distances))
        # print('distances', sorted(distances))
        # print('rs', rs)
        for elem, dist in zip(elements, distances):
            for i_bin in range(self._K):
                if dist < rs[i_bin+1]:
                    the_bin = i_bin
                    break
                elif dist == rs[i_bin+1]:
                    if i_bin == self._K - 1:
                        # end od last bin
                        the_bin = i_bin
                        break
                    else:
                        # tie
                        if len(bins[i_bin]) <= len(bins[i_bin+1]):
                            the_bin = i_bin
                            break
                        else:
                            the_bin = i_bin+1
                            break
            else:
                raise AssertionError('No bin selected')
            bins[the_bin].append(elem)
        return bins, rs

    def _get_distance_to_value(self, key1: K, value2: V) -> float:
        # if key1 == ZERO_ELEMENT:
        #     return self._distance_from_zero(value2)
        # else:
        #     return self._distance_cache.get_distance_to_value(key1, value2)
        return self._distance_cache.get_distance_to_value(key1, value2)

    def get_distance(self, key1: K, key2: K) -> float:
        # if key1 == key2 == ZERO_ELEMENT:
        #     return 0.0
        # elif key1 == ZERO_ELEMENT:
        #     return self._distance_from_zero(self._distance_cache._elements[key2])
        # elif key2 == ZERO_ELEMENT:
        #     return self._distance_from_zero(self._distance_cache._elements[key1])
        # else:
        #     return self._distance_cache.get_distance(key1, key2)
        return self._distance_cache.get_distance(key1, key2)

    def get_statistics(self):
        n_elements = len(self._elements)
        forks, leaves = self.get_forks_and_leaves()
        n_forks = len(forks)
        n_leaves = len(leaves)
        result = f'''{self._K}-way MVPT tree statistics:
        Elements: {n_elements}, Forks: {n_forks}, Leaves: {n_leaves}
        {self._distance_cache.get_statistics()}'''
        return result

    def leaf_diameters(self, leaves: List[_MVPLeaf]) -> str:
        diameters = []
        for leaf in leaves:
            n = len(leaf.elements)
            diameter = max((self.get_distance(leaf.elements[i], leaf.elements[j]) for i in range(n) for j in range(i)), default=0.0)
            diameters.append(diameter)
        return f'leaf diameters: {min(diameters):.3f}-{max(diameters):.3f}, mean: {statistics.mean(diameters):.3f} median: {statistics.median(diameters):.3f}'

    def leaf_distances(self, leaves: List[_MVPLeaf]) -> str:
        dists: list[float] = []
        for leaf in leaves:
            n = len(leaf.elements)
            dists.extend(self.get_distance(leaf.elements[i], leaf.elements[j]) for i in range(n) for j in range(i))
        min_dist = min(dists, default=math.nan)
        max_dist = max(dists, default=math.nan)
        mean = statistics.mean(dists) if len(dists) > 0 else math.nan
        median = statistics.median(dists) if len(dists) > 0 else math.nan
        return f'in-leaf distances: {min_dist:.3f}-{max_dist:.3f}, mean: {mean:.3f} median: {median:.3f}'

    def get_forks_and_leaves(self) -> Tuple[List[_MVPFork], List[_MVPLeaf]]:
        forks: List[_MVPFork[K]] = []
        leaves: List[_MVPLeaf[K]] = []
        self._collect_nodes(self._root, forks, leaves)
        return forks, leaves

    def _collect_nodes(self, node: _MVPNode[K], out_forks: List[_MVPFork[K]], out_leaves: List[_MVPLeaf[K]]):
        if isinstance(node, _MVPLeaf):
            out_leaves.append(node)
        elif isinstance(node, _MVPFork):
            out_forks.append(node)
            for subtree in node.children:
                self._collect_nodes(subtree, out_forks, out_leaves)
        else:
            raise AssertionError

    def kNN_query_by_value(self, query_value: V, k: int, distance_low_bounds: List[Callable[[V, V], float]] = [], the_range: float = math.inf) -> List[Tuple[float, K]]:
        besties = MinFinder[K](n=k)
        query_dist = FunctionCache[K, float](lambda key: self._get_distance_to_value(key, query_value))
        queue = PriorityQueue[float, _MVPNode]()
        queue.add(0.0, self._root)
        current_range = min(besties.top_size(), the_range)
        seen = set()
        QAE = True
        n_leaves = 0
        while not queue.is_empty():
            best = queue.pop_min()
            assert best is not None
            dmin, node = best
            if dmin >= current_range:
                continue
            if isinstance(node, _MVPLeaf):
                n_leaves += 1
                ancestors = list(self._gen_ancestors_of_leaf(node))
                for elem in node.elements:
                    assert elem not in seen
                    if elem in seen:
                        continue
                    if QAE:
                        if not self._can_be_under(elem, query_dist, ancestors, current_range):
                            continue
                    elem_value = self._distance_cache._elements[elem]
                    if any(d(elem_value, query_value) >= current_range for d in distance_low_bounds):
                        continue
                    current_range = min(besties.bubble_in(query_dist[elem], elem), the_range)
                    seen.add(elem)
            elif isinstance(node, _MVPFork):
                d_p_q = query_dist[node.pivot]
                assert node.pivot not in seen
                if node.pivot != ZERO_ELEMENT and node.pivot not in seen:
                    current_range = min(besties.bubble_in(d_p_q, node.pivot), the_range)
                    seen.add(node.pivot)
                for i in range(self._K):
                    dmin_child = max(dmin, node.radii[i] - d_p_q, d_p_q - node.radii[i+1])
                    if dmin_child < current_range:
                        queue.add(dmin_child, node.children[i])
            else:
                raise AssertionError('node must be one of: _MVPFork, _MVPLeaf')
        result = besties.pop_all_not_none()
        return result

    def _gen_ancestors(self, node: _MVPFork[K], include_self: bool = False) -> Iterator[K]:
        if include_self:
            yield node.pivot
        ancestor_node = node.parent
        while ancestor_node is not None:
            yield ancestor_node.pivot
            ancestor_node = ancestor_node.parent

    def _gen_ancestors_of_leaf(self, leaf: _MVPLeaf[K]) -> Iterator[K]:
        if leaf.parent is not None:
            yield from self._gen_ancestors(leaf.parent, include_self=True)

    def _can_be_under(self, elem: K, query_distance: FunctionCache[K, float], through: Iterable[K], limit: float) -> float:
        '''Decide if the distance between elem and query can be less than limit, using elements from through as pivots.'''
        # d_p_q = query_distance[node.pivot]
        for t in through:
            if t in query_distance:
                d_e_t = self.get_distance(elem, t)
                d_t_q = query_distance[t]
                d_e_q_low = abs(d_e_t - d_t_q)
                # assert d_p_q_low <= d_p_q, f'{d_p_q_low} <= {d_p_q}'
                if d_e_q_low >= limit:
                    return False
        return True

    def _node_to_json(self, node: _MVPNode[K]) -> object:
        if isinstance(node, _MVPLeaf):
            return node.elements
        elif isinstance(node, _MVPFork):
            return {
                'pivot': node.pivot,
                'radii': node.radii,
                'children': [self._node_to_json(child) for child in node.children]
            }
        else:
            raise AssertionError

    def _node_from_json(self, js: object) -> _MVPNode[K]:
        if isinstance(js, list):
            return _MVPLeaf(parent=None, elements=js)
        elif isinstance(js, dict):
            fork = _MVPFork(parent=None, pivot=js['pivot'], radii=js['radii'], children=[])
            for c in js['children']:
                child = self._node_from_json(c)
                fork.children.append(child)
                child.parent = fork
            return fork
        else:
            raise AssertionError

    def save(self, file: str, with_cache: bool = False, **json_kwargs) -> None:
        js = {
            'TYPE': 'MVPT',
            'ARITY': self._K,
            'LEAF_SIZE': self._leaf_size,
            'root': self._node_to_json(self._root),
            'distance_cache': self._distance_cache.json() if with_cache else []
        }
        kwargs = {'indent': 1}
        kwargs.update(json_kwargs)
        with open(file, 'w') as w:
            json.dump(js, w, **kwargs)  # type: ignore

    @staticmethod
    def load(file: str, distance_function: Callable[[V, V], float], get_value: Callable[[K], V]) -> 'MVPTree[K, V]':
        with open(file) as r:
            js = json.load(r)
        assert isinstance(js, dict)
        leaf_size = js['LEAF_SIZE']
        arity = js['ARITY']
        result = MVPTree[K, V](distance_function, arity=arity, leaf_size=leaf_size)
        root = result._node_from_json(js['root'])
        result._root = root
        forks, leaves = result.get_forks_and_leaves()
        for fork in forks:
            if fork.pivot != ZERO_ELEMENT:
                result._elements.add(fork.pivot)
        for leaf in leaves:
            for elem in leaf.elements:
                result._elements.add(elem)
        for elem in result._elements:
            result._distance_cache.insert(elem, get_value(elem))
        for k1, k2, dist in js['distance_cache']:
            result._distance_cache.set_distance(k1, k2, dist)
        return result


import os
from shutil import copy
from shutil import rmtree

#jenkins项目目录
JENKINS_PATH='C:/Users/EDZ/.jenkins/workspace/wdove_42_incremDeploy'
#待增量复制的文件所在目录
copyFileCommonPath=JENKINS_PATH+'/copyFiles'
#存放svn中更改文件的文件路径
changedFile='D:/Apache-Subversion-1.10.0/bin/changedfiles.txt'

#在操作前，将上一次生成的待复制文件删除
if os.path.exists(copyFileCommonPath):
    rmtree(copyFileCommonPath)
#再次创建放置需要更新文件的文件夹
if not os.path.exists(copyFileCommonPath):
    os.makedirs(copyFileCommonPath)

if os.path.exists(JENKINS_PATH+'/ove1.0_deleteFiles.txt'):
    os.remove(JENKINS_PATH+'/ove1.0_deleteFiles.txt')
# if not os.path.exists(JENKINS_PATH+'/ove1.0_deleteFiles.txt'):
#     f=open(JENKINS_PATH+'/ove1.0_deleteFiles.txt','w')
#     f.close()

#将文件的路径和svn项目路径进行分离，得到更新文件的相对路径
def splitStr(str):
    file=str.split("whu")[1]
    return file

f=open(changedFile,'r')
for line in f.readlines():
    str=line.strip()
    #print(str[0])
    #判断得到的changefiles中，对文件的操作是否是删除；若是删除操作则忽略该文件，不对该文件进行后续的复制操作
    if str[0]=='D':
        # 分离得到要复制文件的相对路径
        file=splitStr(str)
        print(file)
        with open(JENKINS_PATH+'/ove1.0_deleteFiles.txt', 'a') as f1:
            f1.writelines(file+'\n')
    else :
        # 分离得到要复制文件的相对路径
        file=splitStr(str)
        #得到要复制的文件在Jenkins项目中的绝对路径
        filePath = JENKINS_PATH + file
        #print(file)
        #得到要复制文件的上一级目录p
        p,f1=os.path.split(file)
        #print(p)
        #print(f1)
        #得到要将文件复制到的目标文件夹
        copyFilePath=copyFileCommonPath+p
        #创建目标文件夹
        if not os.path.exists(copyFilePath):
            os.makedirs(copyFilePath)
        #print(filePath)
        #判断得到的对象是文件还是文件夹，若是文件夹则不进行复制操作
        if os.path.isdir(filePath):
            continue
        #将Jenkins中对应的文件复制到目标文件夹下
        copy(filePath,copyFilePath)
#关闭文件
f.close()


import pandas as pd

#import csv as dataframe
df = pd.read_csv("train.csv", delimiter = ",",encoding = "utf-8")
print(df)

#rslt_df = df[df["Artist Name"] == "Eyal Golan"]
#print(rslt_df)

#check_df = df[df["Track Name"].str.contains("◊")]
#print(check_df)
#check2_df = df[df["Track Name"].str.contains("√")]
#print(check2_df)

#delete track names containing strange character
df_new = df.drop(df[(df["Track Name"].str.contains("◊")) | (df["Track Name"].str.contains("√"))].index)
print(df_new)

#check if removed
#check_df_new = df_new[df_new["Track Name"].str.contains("◊")]
#check2_df_new = df_new[df_new["Track Name"].str.contains("√")]
#print(check2_df_new)
#print(check_df_new)

#select rows
#print(df_new.iloc[8000:8030,])

#result = df[["Artist Name", "Track Name","tempo"]]
#result

#tempo180 = df[df["tempo"]>= 180]
#tempo180

#check NaN values columns
df.isna().any()

#check NaN values rows
df_new[df_new.isna().any(axis=1)]
df_new["Artist Name"] = df_new["Artist Name"].str.lower()
df_new["Track Name"] = df_new["Track Name"].str.lower()

print(df_new)

def select_artist():
    x_artist = input("name artist: ")
    contain_values = df_new[df_new["Artist Name"].str.contains(x_artist.lower())]
    return contain_values

select_artist()

def select_song():
    x_song = input("please name a song title: ")
    contain_song = df_new[df_new["Track Name"].str.contains(x_song.lower())]
    return contain_song

select_song()


"""update education table

Revision ID: 0b8c43888e5d
Revises: 938fb3ecfe60
Create Date: 2019-06-28 10:58:32.189750

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '0b8c43888e5d'
down_revision = '938fb3ecfe60'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('seeker', 'education',
               existing_type=mysql.VARCHAR(length=12),
               nullable=True)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('seeker', 'education',
               existing_type=mysql.VARCHAR(length=12),
               nullable=False)
    # ### end Alembic commands ###


notenumber=int(input("How many notes will you enter"))
i=1
total=0
while i<=notenumber:
    note=int(input("Please Enter Note"))
    if note>=1 and note<=100:
        total += note
        i += 1
    else:
        print("Note must be 1-100")
        print("Program will stop")
        break

result=total//notenumber
if result>=1 and result<=49:
    print("") #Sınıfta Kaldınız
elif result>=50 and result<=59:
    print("") #Sınıfı Kötü Not ile Geçtiniz
elif result>=60 and result<=69:
    print("") #Sınıfı Ortalama Not ile Geçtiniz
elif result>=70 and result<=84:
    print("") #Sınıfı Teşekkür Belgesi ile Geçtiniz
elif result>=85 and result<=100:
    print("") #Sınıfı Takdir Belgesi ile Geçtiniz
else:
    print("Result must be 1-100")


# -*- coding: utf-8 -*-
"""
@author: anishukla
"""

#Level: Easy

import math

def strangeGrid(r, c):
    a = math.ceil(r/2)
    count = 0
    if r%2==0:
        count = 1
    val = (a-1)*10 + count

    res = val + 2*(c-1)

    return res

if __name__ == '__main__':
    rc = input().split()
    r = int(rc[0])
    c = int(rc[1])

    result = strangeGrid(r, c)
    print(result)


from time import sleep

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.service import Service

def get_full_page(driver: webdriver, url: str, out_path_png: str) -> None:
    driver.get(url)

    for _ in range(1000):
        driver.execute_script("window.scrollBy(0,10);")
        sleep(0.0001)

    for _ in range(1000):
        driver.execute_script("window.scrollBy(0,-20);")
        sleep(0.0001)

    driver.find_element(By.TAG_NAME, "body").screenshot(out_path_png)

def get_short_page(driver: webdriver, url: str, out_path_png: str) -> None:
    driver.get(url)
    driver.execute_script("window.scrollBy(0,0);")
    sleep(1)
    driver.get_screenshot_as_file(out_path_png)

def get_driver_firefox():
    options = Options()
    options.headless = True
    options.binary = "/usr/bin/firefox"
    return webdriver.Firefox(
        service=Service(GeckoDriverManager().install()),
        options=options,
    )

def get_driver_chrome():
    options = Options()
    options.headless = True

    linux_chrome_path = {
        "binary_location": "/opt/chrome-linux/chrome",
        "executable_path": "/opt/chrome-linux/chromedriver",
    }

    options.binary = linux_chrome_path["binary_location"]
    return webdriver.Chrome(
        executable_path=linux_chrome_path["executable_path"],
        options=options,
    )

if __name__ == "__main__":
    domain = "https://example.com"

    driver = get_driver_firefox()
    driver.get(domain)
    get_full_page(driver, domain + "/", "/home/user/results/example-full.png")
    get_short_page(driver, domain + "/", "/home/user/results/example-short.png")

    driver.close()


from django.urls import path

from app_shop import views

urlpatterns = [
    path(
        "",
        views.MainView.as_view(),
        name="main",
    ),
    path(
        "faker/",
        views.FakerView.as_view(),
        name="faker",
    ),
    path(
        "products/",
        views.ProductListView.as_view(),
        name="products",
    ),
    path(
        "product/<int:pk>/",
        views.ProductDetailView.as_view(),
        name="product_detail",
    ),
    path(
        "new-collection/",
        views.NewCollectionListView.as_view(),
        name="new_collection",
    ),
    path(
        "cart/",
        views.CartView.as_view(),
        name="cart",
    ),
    path(
        "add_quantity/<int:product_id>/",
        views.add_quantity_view,
        name="add_quantity",
    ),
    path(
        "remove_quantity/<int:product_id>/",
        views.remove_quantity_view,
        name="remove_quantity",
    ),
    path(
        "add_cart/<int:product_id>/",
        views.add_to_cart_view,
        name="add_cart",
    ),
    path(
        "remove_cart/<int:product_id>/",
        views.remove_from_cart_view,
        name="remove_cart",
    ),
    path(
        "recommended/",
        views.RecommendedProductView.as_view(),
        name="recommended",
    ),
]


'''
Leetcode: 871. Minimum Number of Refueling Stops
Educative: https://www.educative.io/courses/grokking-coding-interview-patterns-python/qVRq9mQnqV7

A car travels from a starting position to a destination which is target miles east of the starting position.

There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.

The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.

Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can not reach the target (or even the first gas station).

Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation: We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.

'''
from heapq import heappush, heappop
from typing import List

def minRefuelStops(target: int, startFuel: int, stations: List[List[int]]) -> int:
    # target = 100 miles .. startFuel = 10
    # stations = [[10,60], [20,30], [30,30], [60,40]] ,, [[position, fuel]]
    # start(10)-------(10+60)-----------------------(70+40)--->Target=100
    #                    +1                           +2

    if startFuel >= target:
        return 0

    max_heap = []
    max_distance = startFuel #Max miles that we can reach, starting with startFuel
    min_refuel = 0

    i = 0
    while max_distance < target: #Loop until car reach the target or it's out of fuel
        if i < len(stations) and max_distance >= stations[i][0]: #There are still stations
            '''
            Sice, I am already ahead of or at this station (i.e.
            max_distance >= stations[i][0]) we don't use this station and try to move ahead but I store this station in maxheap to use in future
            '''
            heappush(max_heap, -stations[i][1]) #So, add its fuel capacity to the heap
            i += 1

        elif not max_heap: #If there are no more stations and we can't reach the target
            return -1

        else: #Otherwise, fill up at the station with the highest fuel capacity
            max_distance += -heappop(max_heap)
            min_refuel += 1 #And increment stops

    return min_refuel

def main():
    input = [
        (1, 1, []),
        (100, 1, [[10, 100]]),
        (59, 14, [[9, 12], [11, 7], [13, 16], [21, 18], [47, 6]]),
        (15, 3, [[2, 5], [3, 1], [6, 3], [12, 6]]),
        (570, 140, [[140, 200], [160, 130], [310, 200], [330, 250]]),
        (1360, 380, [[310, 160], [380, 620], [700, 89], [850, 190],[990, 360]])
    ]
    num = 1
    for i in input:
        print(num, '.\tStations =', i[2])
        print('\tTarget =', i[0])
        print('\tStarting fuel =', i[1])
        print('\n\tMinimum number of refueling stops is:', minRefuelStops(i[0], i[1], i[2]))
        num += 1
        print('-' * 85, '\n')

if __name__ == '__main__':
    main()

'''
TC -> O(nlogn), where n is the number of stations. The while loop runs until the car reaches the target or runs out of fuel, which takes O(target/startFuel) iterations in the worst case. The inner while loop runs until all the stations that can be reached from the current fuel level are added to the heap, which takes O(n) iterations in the worst case. The heappush and heappop operations take O(logn) time each, and they are performed for each station, so the total time complexity of the heap operations is O(nlogn). Therefore, the overall time complexity of the function is O(nlogn)
SC -> O(n), since there will be maximum n fuel capacities in the heap.
'''


import tensorflow as tf
import numpy as np
import uproot
from array import array
#from tensorflow.python.keras.utils.data_utils import Sequence
from my_classes import DataGenerator

partition = {'train': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18'], 'validation': ['19', '20']}
#print(partition)

params = {'dim': 8,
          'batch_size': 1,
          'num_of_labels': 3,
          'shuffle': True}

def create_model():
    model = tf.keras.Sequential()
    model.add(
        tf.keras.layers.Dense(100, activation=tf.keras.activations.relu, input_shape=(8,)) #change input shape to 8, was 12 before
    )
    model.add(
        tf.keras.layers.Dropout(0.1) #try lower dropout for input layer
    )

    #Hidden layer 1
    model.add(
        tf.keras.layers.Dense(100, activation=tf.keras.activations.relu)
    )
    model.add(
        tf.keras.layers.Dropout(0.5)
    )

    #Hidden layer 2
    model.add(
        tf.keras.layers.Dense(100, activation=tf.keras.activations.relu)
    )
    model.add(
        tf.keras.layers.Dropout(0.5)
    )

    #Hidden layer 3
    model.add(
        tf.keras.layers.Dense(100, activation=tf.keras.activations.relu)
    )
    model.add(
        tf.keras.layers.Dropout(0.5)
    )

    #Hidden layer 4
    model.add(
        tf.keras.layers.Dense(100, activation=tf.keras.activations.relu)
    )
    model.add(
        tf.keras.layers.Dropout(0.5)
    )

    #Hidden layer 5
    model.add(
        tf.keras.layers.Dense(100, activation=tf.keras.activations.relu)
    )
    model.add(
        tf.keras.layers.Dropout(0.5)
    )

    model.add(
        tf.keras.layers.Dense(3) #only change to architecture will be to make this output 3 not 4
    )

    model.compile(
        optimizer=tf.keras.optimizers.Adam(lr=0.001, decay=0.0001),
        loss=tf.keras.losses.mean_squared_error
    )
    return model

big_model = create_model()

training_generator = DataGenerator(partition['train'],  **params)
validation_generator = DataGenerator(partition['validation'], **params)

big_model.fit_generator(generator=training_generator,
                    validation_data=validation_generator,
                    use_multiprocessing=True
                  )

# tau_model = create_model()
# antitau_model = create_model()

# big_model = create_model()
# big_model.fit(
#       big_features_train,
#       big_labels_train,
#       batch_size=20,
#       epochs=400,
#      validation_data=(big_features_test, big_labels_test)
#  )
#
# big_model.evaluate(
#     big_features_test,
#     big_labels_test,
#      batch_size=10
#  )

# big_model.save('new_arch_big_local_model_noPiPtCut_nomMass_fromOtto_constantInputFeatureEliminated_2March2020.hdf5')
# # antitau_model.save('antitau_model_reproduce_WSO_my_own_no_norm.hdf5')
# print ('big_model summary is:', big_model.summary())
# # print ('antitau_model summary is:', antitau_model.summary())


# coding=utf-8
from rest_framework import viewsets, mixins
from halls.models import Hall, SubHall, ContentSubHall, SubHallTag
from halls.serializers import HallSerializer, SubHallSerializer
from django.shortcuts import get_object_or_404
from rest_framework.response import Response

class HallsViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    queryset = Hall.objects.filter()
    serializer_class = HallSerializer

    def list(self, request, *args, **kwargs):
        serializer = self.serializer_class(self.queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        hall = get_object_or_404(Hall.objects.all(), name=kwargs.get('pk', ''))
        serializer = self.serializer_class(hall)
        return Response(serializer.data)

class SubHallsViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    queryset = SubHall.objects.filter()
    serializer_class = SubHallSerializer

    def list(self, request, *args, **kwargs):
        serializer = self.serializer_class(self.queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        hall = get_object_or_404(SubHall.objects.all(), name=kwargs.get('pk', ''))
        serializer = self.serializer_class(hall)
        return Response(serializer.data)

class ContentSubHallViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    queryset = ContentSubHall.objects.filter()
    serializer_class = HallSerializer

    def retrieve(self, request, *args, **kwargs):
        sub_hall = get_object_or_404(SubHallTag.objects.all(), tag=kwargs.get('pk', '')).parent_hall

        contents = []

        for p in ContentSubHall.objects.filter(sub_hall=sub_hall):
            entry = {
                "media": str(p.media),
                "url": str(p.url)
            }
            contents.append(entry)

        return Response(contents)


def maximo_valor(n1,n2,n3,n4):
    for x in range (n1,n2,n3,n4):
        valor1 = n1*n2
        valor2 = n1*n3
        valor3 = n1*n4
        valor4 = n2*n3
        valor5 = n2*n4
        valor6 = n3*n4
    print()
print ("Dime 4 números")
n1 = int(input())
n2 = int(input())
n3 = int(input())
n4 = int(input())

print ("El mayor producto es" + str(maximo_valor(n1,n2,n3,n4)))


class Solution:
    def maxSatisfaction(self, satisfaction: List[int]) -> int:
        satisfaction.sort(reverse=True)
        ans, prem = 0, 0
        for num in satisfaction:
            prem += num
            if prem<0:
                return ans
            ans +=prem

        return ans


plants = {}

n = int(input())
for i in range(n):
    plant_info = input().split("<->")
    plant = plant_info[0]
    rarity = int(plant_info[1])
    plants[plant] = {"rarity": rarity, "ratings": []}

command = input()
while command != "Exhibition":
    tokens = command.split()
    if tokens[0] == "Rate:":
        plant = tokens[1]
        if plant in plants:
            rating = int(tokens[3])
            plants[plant]["ratings"].append(rating)
        else:
            print("error")
    elif tokens[0] == "Update:":
        plant = tokens[1]
        if plant in plants:
            rarity = int(tokens[3])
            plants[plant]["rarity"] = rarity
        else:
            print("error")
    elif tokens[0] == "Reset:":
        plant = tokens[1]
        if plant in plants:
            plants[plant]["ratings"] = []
        else:
            print("error")
    else:
        print("error")
    command = input()

print("Plants for the exhibition:")
for plant, info in plants.items():
    if info["ratings"]:
        avg_rating = sum(info["ratings"]) / len(info["ratings"])
        avg_rating = f'{avg_rating:.2f}'
    else:
        avg_rating = f"0.00"
    print(f"- {plant}; Rarity: {info['rarity']}; Rating: {avg_rating}")


from Tkinter import *
import time

root = Tk()
root.minsize(600, 480)
a = root.winfo_screenheight()
b = root.winfo_screenwidth()
cv = Canvas(root, width=a, height=b, bg='white')
rt = cv.create_text(200, 200, text='+', fill='red', font=("Fixdsys", 36, "bold"))
cv.pack()
root.after(2000, lambda: cv.itemconfig(rt, text='start'))
rtags = []
for i in range(10):
    cv.create_rectangle(300, 100 + i * 30, 500, 130 + i * 30, outline='blue', fill='white', tags='r' + str(i+1))
    rtags.append('r' + str(i + 1))

# main()

for num in range(10):
    cv.itemconfig(cv.find_withtag(rtags[num]), fill='red')
    root.update()
    time.sleep(1)

root.after(4900, lambda: cv.itemconfig(rt, text='stop'))
#root.after(5000, lambda:root.destroy())
root.mainloop()