import csv
from ipaddress import ip_address
from .report import Host, Port

ALLOWED_COLUMNS = [
    'ipv4',
    'hostname',
    'os_name',
    'port',
    'state',
    'protocol',
    'service',
    'software_banner',
    'version',
    'cpe',
    'other_info',
    ]

class CSVFileParser:

    def load_hosts(self, file):

        reader = csv.DictReader(file)

        current_host = None
        hosts = []
        for row in reader:
            if len(hosts) == 0 or hosts[-1].ipv4.exploded != row['ipv4']:
                hosts.append(Host(ipv4=ip_address(row.get('ipv4', None)),
                                  hostname=row.get('hostname', None),
                                  os_info={'name': row.get('os_name', None)}))

            if row.get('port', None) not in ['', None]:
                hosts[-1].ports.append(Port(
                    port=int(float(row.get('port', None))),
                    protocol=row.get('protocol', None),
                    state=row.get('state', None),
                    service=row.get('service', None),
                    software=row.get('software_banner', None),
                    version=row.get('version', None),
                    cpe=row.get('cpe', None)
                ))
        return hosts


"""
Faça um programa que leia nome e peso de várias pessoas,
guardando tudo em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas.
B) Uma listagem com as pessoas mais pesadas.
C) Uma listagem com as pessoas mais leves.
"""

lista = list()
dados = list()
tot = 0
mai = men = 0
while True:
    dados.append(str(input('Nome: ')))
    dados.append(float(input('peso: ')))
    if len(lista) == 0:
        mai = men = dados[1]
    else:
        if dados[1] > mai:
            mai = dados[1]
        if dados[1] < men:
            men = dados[1]
    lista.append(dados[:])
    dados.clear()
    tot = tot + 1
    cont = str(input('Deseja continuar [s/n]: '))
    if cont in 'Nn':
        break
print("-="*30)
print(f'Foram cadastradas {tot} pessoas na lista.')
print(f'O maior peso foi de {mai}Kg')
for p in lista:
    if p[1] == mai:
        print(f'[{p[0]}]')
print()
print(f'O menor peso foi de {men}Kg')
for p in lista:
    if p[1] == men:
        print(f'[{p[0]}]')
print()


import os
import re
import glob
import datetime
from prettytable import PrettyTable
from matplotlib import pyplot as plt

NUM_MOST_RECENT_RUNS = 100

te_path = os.getenv("TE_PATH", "/opt/transformerengine")
mlm_log_dir = os.path.join(te_path, "ci_logs")
te_ci_log_dir = "/data/transformer_engine_ci_logs"
te_ci_plot_dir = os.path.join(te_ci_log_dir, "plots")

convergence_pattern = (
    "validation loss at iteration \d* on validation set | lm loss"
    " value: ([\d.]*)E\+(\d*) | lm loss PPL: ([\d.]*)E\+(\d*)"
)

perf_pattern = "elapsed time per iteration \(ms\): ([\d.]*)"

def get_output_file():
    now = datetime.datetime.now()
    default_fname = f"unknown_pipeline_id_{now.month}_{now.day}_{now.year}_{now.hour}_{now.minute}"
    fname = f"{os.getenv('CI_PIPELINE_ID', default_fname)}.txt"
    return os.path.join(te_ci_log_dir, fname)

def get_run_metrics(filename):
    """Return the loss, perplexity, and step time for a given megatron-LM logfile."""

    with open(filename, "r") as f:
        data = f.read()

    # Loss and PPL
    convergence_matches = re.findall(convergence_pattern, data)
    loss = round(float(convergence_matches[1][0]) * (10 ** int(convergence_matches[1][1])), 2)
    ppl = round(float(convergence_matches[2][2]) * (10 ** int(convergence_matches[2][3])), 2)

    step_times_str = re.findall(perf_pattern, data)
    step_times = [float(x) for x in step_times_str]
    avg_step_time = round(sum(step_times) / len(step_times), 2)
    return loss, ppl, avg_step_time

def print_run_logs():
    tables = []
    raw_logs = []
    for model_config in os.listdir(mlm_log_dir):
        model_config_dir = os.path.join(mlm_log_dir, model_config)
        table = PrettyTable()
        table.title = model_config
        table.field_names = ["Config", "Loss", "Perplexity", "Avg time per step (ms)"]
        for exp in os.listdir(model_config_dir):
            filename = os.path.join(model_config_dir, exp)
            loss, ppl, time_per_step = get_run_metrics(filename)
            exp_name = exp[:-4]
            table.add_row([exp_name, loss, ppl, time_per_step])
            raw_logs.append(f"{model_config} {exp_name} {loss} {ppl} {time_per_step}\n")
        tables.append(table)

    with open(get_output_file(), "w") as f:
        for raw_log in raw_logs:
            f.write(raw_log)
    for table in tables:
        print(table)

def save_plot(title, legend, data, filename, ylabel):
    x = list(range(1, len(data[0]) + 1))
    plt.figure()
    for label, y in zip(legend, data):
        plt.plot(x, y, "-o", label=label)
    plt.title(title)
    plt.legend()
    plt.xlabel(f"Last {NUM_MOST_RECENT_RUNS} runs")
    plt.ylabel(ylabel)
    plt.savefig(os.path.join(te_ci_plot_dir, filename))

def perf_and_loss_plots():
    files = glob.glob(os.path.join(te_ci_log_dir, "*.txt"))
    files.sort(key=os.path.getctime)
    files = files[-NUM_MOST_RECENT_RUNS:]
    data = {}
    for filename in files:
        with open(filename) as file:
            for line in file:
                line = line.strip()
                model_config, exp_name, loss, _, time_per_step = line.split(" ")
                if model_config not in data:
                    data[model_config] = {}
                if exp_name not in data[model_config]:
                    data[model_config][exp_name] = {"loss": [], "perf": []}
                data[model_config][exp_name]["loss"].append(float(loss))
                data[model_config][exp_name]["perf"].append(float(time_per_step))

    for model_config, experiments in data.items():
        lm_loss_data = []
        lm_perf_data = []
        legend = []
        for exp_name, lm_data in experiments.items():
            legend.append(exp_name)
            lm_loss_data.append(lm_data["loss"])
            lm_perf_data.append(lm_data["perf"])
        save_plot(
            model_config + " loss", legend,
            lm_loss_data, model_config + "_loss.png",
            "LM-Loss",
        )
        save_plot(
            model_config + " perf",
            legend, lm_perf_data, model_config + "_perf.png",
            "Time per step (ms)",
        )

if __name__ == "__main__":
    print_run_logs()
    perf_and_loss_plots()


def RemoveDups(str):
    l1={}
    for i in str:
        if i not in l1:
            l1[i]=1
        if i in l1:
            continue
    str=""
    for x,y in l1.items():
        str+=x

    return str

str = "helllomanvvith"
print(RemoveDups(str))


# Copyright 2020 University of Basel, Center for medical Image Analysis and Navigation
#
# Licensed under the Apache License, Version 2.0 (the “License”);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an “AS IS” BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import argparse

default_dataset = './dataset/warp_set/'

def main(config):
    dataset = config.dataset
    mode=config.mode
    print(mode)
    if mode=='train':

        from model.DeScarGAN import Solver

        solver = Solver(config.dataset_path, config.dataset)
        solver.train()
    else:
        if dataset == 'Synthetic':
            from Evaluation.Evaluation_Synthetic_Dataset import Solver
        else:
            from Evaluation.Evaluation_Chexpert import Solver

        solver = Solver(config.dataset_path, config.choose_net)
        solver.test()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    #
    #     # Training configuration.
    parser.add_argument('--dataset_path', type=str,
                      default='/home/juliawolleb/PycharmProjects/Python_Tutorials/Reversible/Chexpert/2classes_effusion')
                    #    default='/home/juliawolleb/PycharmProjects/Python_Tutorials/warp/warp_set')
    parser.add_argument('--dataset', type=str, default='Chexpert')
    parser.add_argument('--mode',type=str, default='train')
    parser.add_argument('--choose_net',type=str, default='./save_nets')

    #
    #
    #
    config = parser.parse_args()
    print(config)
    main(config)
#


from .deltakere import Deltakere
from .lyd import Uro

import tkinter as Vindu
import random
import time

class Lek:
    def __init__(self,
                 wait_time,
                 playlist,
                 directory,
                 music,
                 volume):
        """
        Hovedklasse.

        Parameters
        ----------
        wait_time : int or tuple
            Minutes between each game.
        playlist : str
            Spotify-URI for the playlist.
        directory : str
            Folder to place and play the sound files.
        music : tuple
            Spotify Client ID, Spotify Client Secret and Spotify-URI for the redirect-page.
        volume : int
            Volume of the music (percentage, 0-100).
        """

        self.Lyd = Uro(playlist, directory, music, volume)
        self.modes = [self.musikk_quiz,
                      self.drink_bitch,
                      self.kategorileken,
                      self.mest_sannsynlig,
                      self.waterfall,
                      self.lyric_masteren,
                      self.siste_som,
                      self.beste_grimase,
                      self.mime,
                      self.tommelkrig,
                      self.capture_the_mini]
        self.active_modes = [self.musikk_quiz,
                             self.musikk_quiz,
                             self.drink_bitch,
                             self.kategorileken,
                             self.mest_sannsynlig,
                             self.waterfall,
                             self.lyric_masteren,
                             self.siste_som,
                             self.beste_grimase,
                             self.mime,
                             self.tommelkrig,
                             self.capture_the_mini]

        if type(wait_time) != tuple:
            wait_time = (wait_time, wait_time)
        self.wait_time = (wait_time[0] * 60000, wait_time[1] * 60000)
        self.directory = directory

        self._fortsetter = None
        self._knapp = None

        self.kategorier = []
        with open('../src/norsk_personlig/tekstfiler/kategorier.txt', 'r',
                  encoding='utf-8') as file:
            for line in file:
                line = line.strip()
                self.kategorier.append(line)

        self.mest_sannsynlig_til = []
        with open('../src/norsk_personlig/tekstfiler/sannsynlig_til.txt', 'r',
                  encoding='utf-8') as file:
            for line in file:
                line = line.strip()
                self.mest_sannsynlig_til.append(line)

        self.sangtekster = []
        with open('../src/norsk_personlig/tekstfiler/sangtekster.txt', 'r',
                  encoding='utf-8') as file:
            for line in file:
                info, tekst = line.split(" [] ")
                artist, sang = info.split(", ")
                self.sangtekster.append((artist, sang, tekst))

        # Add players
        start = Deltakere()
        self.deltakere = start.deltakere

        # Main window
        self.vindu = Vindu.Tk()
        self.vindu.geometry("1920x720+0+0")
        Vindu.Label(self.vindu, text='Hobozz Drikkelek', font=('Helvetica bold', 40)).place(x=0,
                                                                                y=0)

        # Pause Button
        Vindu.Button(self.vindu, text='PAUSE MUSIKK',
                     command=lambda: self.Lyd.pause_music()).place(x=0, y=80)

        # Play Button
        Vindu.Button(self.vindu, text='SPILL MUSIKK',
                     command=lambda: self.Lyd.unpause_music()).place(x=150, y=80)

        # Play Button
        Vindu.Button(self.vindu, text='SKIP SANG',
                     command=lambda: self.Lyd.skip_music()).place(x=300, y=80)

        # Players
        Vindu.Label(self.vindu, text='Deltakere:', font=('Helvetica', 30)).place(x=0, y=160)

        player_lable_distance = 200
        for player in self.deltakere:
            Vindu.Label(self.vindu, text=f" >  {player}",
                        font=('Helvetica', 16)).place(x=0, y=player_lable_distance)
            player_lable_distance += 30

        # Starting the game
        Vindu.Button(self.vindu, text='START',
                     command=lambda: self._start_game(), fg='Green').place(x=500, y=80)

        # Adding a new mode
        Vindu.Label(self.vindu, text="LEGG TIL").place(x=700, y=80)

        pos = 80
        for mode in self.modes:
            pos += 50
            Vindu.Button(self.vindu, text=mode.__name__,
                          command=lambda mode=mode: self._add_mode(mode)).place(x=700, y=pos)

        # Removing a mode
        Vindu.Label(self.vindu, text="FJERN").place(x=850, y=80)

        pos = 80
        for mode in self.modes:
            pos += 50
            Vindu.Button(self.vindu, text=mode.__name__,
                          command=lambda mode=mode: self._remove_mode(mode)).place(x=850, y=pos)

        # Active modes
        Vindu.Label(self.vindu, text="AKTIVE:").place(x=1000, y=80)

        pos = 110
        self.active_labels = []
        for mode in self.active_modes:
            pos += 20
            label = Vindu.Label(self.vindu, text=mode.__name__,
                                 font=("Helvetica", 10))
            label.place(x=1000, y=pos)
            self.active_labels.append(label)

        self.vindu.mainloop()

    def _add_mode(self, mode):
        """Adds a game mode."""

        self.active_modes.append(mode)

        for label in self.active_labels:
            label.destroy()

        pos = 110
        self.active_labels = []
        for game in self.active_modes:
            pos += 20
            label = Vindu.Label(self.vindu, text=game.__name__,
                                 font=("Helvetica", 10))
            label.place(x=1000, y=pos)
            self.active_labels.append(label)

    def _remove_mode(self, mode):
        """Removes a game mode."""

        while mode in self.active_modes:
            self.active_modes.remove(mode)

        for label in self.active_labels:
            label.destroy()

        pos = 110
        self.active_labels = []
        for game in self.active_modes:
            pos += 20
            label = Vindu.Label(self.vindu, text=game.__name__,
                                 font=("Helvetica", 10))
            label.place(x=1000, y=pos)
            self.active_labels.append(label)

        self.vindu.mainloop()

    def _start_game(self):
        """Starts the game."""

        self.Lyd.pause_music()

        self.Lyd.read('Velkommen til hobozzz drikkeleken, dette blir gay!')

        self.Lyd.read('Deltakerne i dag er')
        self.Lyd.read(", ".join(self.deltakere))

        self.Lyd.read('Let the games begin!')

        self.Lyd.unpause_music()

        self._game_loop()

    def _game_loop(self):
        """The game loop."""

        random.choice(self.active_modes)()

        vent = random.randint(self.wait_time[0], self.wait_time[1])
        self.vindu.after(vent, self._game_loop)

    def drink_bitch(self):
        """Drink bitch game mode."""

        the_bitch = random.choice(self.deltakere)

        self.Lyd.pause_music()

        self.Lyd.read(f'Kan jeg få oppmerksomheten')

        time.sleep(2)

        self.Lyd.read(f'{the_bitch} DRINK, BITCH')
        self.Lyd.read('Takk for meg')

        self.Lyd.unpause_music()

    def musikk_quiz(self):
        """Music quiz game mode."""

        self.Lyd.pause_music()

        self.Lyd.read('Velkommen til musikkquiz')
        t = 'Her kommer 3 sanger. Førstemann til å rope ut sangens navn eller artist kan dele ut 1 til 2 slurker'
        self.Lyd.read(t)

        songs = self.Lyd.music.playlist_tracks("2sbw07iogIXbWpmOz0U66W")["items"]
        random.shuffle(songs)

        for i in range(1, 4):
            if i != 3:
                self.Lyd.read(f'Sang nummer {i}')
            else:
                self.Lyd.read(f'Siste sang')

            song = songs[i]["track"]
            song_id = song["id"]
            song_name = song["name"]
            artist_name = song["artists"][0]["name"]

            self.Lyd.music.add_to_queue(song_id)
            self.Lyd.skip_music()

            time.sleep(25)

            self.Lyd.pause_music()

            time.sleep(1)

            self.Lyd.read_english(f'{song_name} by, {artist_name}')

        burn = random.choice(["at du ser lesbisk ut",
                              "at du er dritflink til å drikke",
                              "at du er en god venn",
                              "at du ikke har et liv",
                              "at du er god i senga",
                              "at du kan mye",
                              "at du får dele ut 3 slurker",
                              "at du får drikke 3 slurker",
                              "at du får dele ut 1 slurk",
                              "at du får drikke 1 slurk",
                              "at du får dele ut 2 slurker",
                              "at du får drikke 2 slurker"])
        t = f'Det var sang quizen, takk for deltakelsen, Bull hvis du klarte alle sangene kan du trøste deg med {burn}.'
        self.Lyd.read(t)

        self.Lyd.skip_music()
        self.Lyd.unpause_music()

    def _fortsett(self):
        """Continues the game."""

        self._fortsetter = True
        self._knapp.destroy() if self._knapp else None
        self.vindu.update()

    def kategorileken(self):
        """Category game mode."""

        self.Lyd.pause_music()

        kategori = random.choice(self.kategorier)
        startperson = random.choice(self.deltakere)

        self.Lyd.read('Dette er kategori leken')
        self.Lyd.read("Trykk for å fortsette")

        self.Lyd.read('Kategorien er:')
        self.Lyd.read(f'{kategori}, {startperson} starter')

        self._fortsetter = False
        self._knapp = Vindu.Button(self.vindu, text='FORTSETT', command=self._fortsett)
        self._knapp.place(x=800, y=80)
        while not self._fortsetter:
            self.vindu.update()

        time.sleep(1)
        self.Lyd.read('Den som tapte må drikke.')

        time.sleep(1)
        self.Lyd.unpause_music()

    def mest_sannsynlig(self):
        """Most likely to game mode."""

        self.Lyd.pause_music()
        self.Lyd.read('Hold kjeftene deres, dette er mest sannsynlig leken')
        t = 'dere stemmer på om den stemmer. Hvis den stemmer må personen drikke, hvis ikke må alle andre drikke.'
        self.Lyd.read(f"Jeg kommer med tre påstander, {t}")

        for i in range(3):
            person = random.choice(self.deltakere)
            handling = random.choice(self.mest_sannsynlig_til)

            self.Lyd.read(f'{person} er den av dere som er mest sannsynlig til {handling}')

            time.sleep(10)

        self.Lyd.unpause_music()

    def waterfall(self):
        """Waterfall game mode."""

        self.Lyd.pause_music()

        self.Lyd.read('Hold de stygge munnene deres og lytt, neste lek er waterfall')

        person = random.choice(self.deltakere)
        self.Lyd.read(f'{person} starter og bestemmer hvilken retning det skal gå')

        time.sleep(2)

        self.Lyd.unpause_music()

    def lyric_masteren(self):
        """Lyric master game mode."""

        self.Lyd.pause_music()
        self.Lyd.read('Velkommen til lyrikkmesteren')
        self.Lyd.read('Jeg skal lese opp en sang for dere. Hvis ingen klarer å gjette sangen må dere drikke')

        artist, sang, tekst = random.choice(self.sangtekster)

        self.Lyd.read_english(tekst.strip())

        time.sleep(5)

        self.Lyd.read(f'Sangen var {sang} av {artist}')

        self.Lyd.unpause_music()

    def siste_som(self):
        """Last person to game."""

        self.Lyd.pause_music()

        self.Lyd.read('Siste som')
        aktivitet = random.choice(["Reiser seg",
                                   "Tar en slurk",
                                   "Tar en high five",
                                   "Tar en shot",
                                   "Snurrer rundt",
                                   "Tar en pushup",
                                   "Tar en situp",
                                   "Rekker opp hånden",
                                   "Dabber"])
        self.Lyd.read(f'{aktivitet}')

        self.Lyd.unpause_music()

    def beste_grimase(self):
        """Best grimace game."""

        self.Lyd.pause_music()

        self.Lyd.read('Pek på den som lager best grimase')

        time.sleep(20)

        aktivitet = random.choice(["Dele ut to slurker",
                                   "Drikke to slurker",
                                   "Ta en shot",
                                   "Dele ut en slurk",
                                   "Drikke en slurk",
                                   "Dele ut en shot",
                                   "Dele ut tre slurker",
                                   "Drikke tre slurker"])

        self.Lyd.read(f"Vinneren får {aktivitet}")

        time.sleep(2)

        self.Lyd.unpause_music()

    def bygge_bokser(self):
        """Den som bygger høyest frittstående vinner."""

        self.Lyd.pause_music()

        self.Lyd.read('Den som bygger høyest frittstående tårn av SINE EGNE tomme ølbokser vinner')

        tid = random.choice([5, 10, 15, 20, 25, 30])

        self.Lyd.read(f'Dere har {tid} sekunder')

        time.sleep(tid)

        self.Lyd.read('Stopp!')

        time.sleep(2)

        aktivitet = random.choice(["Dele ut en slurk",
                                   "Dele ut to slurker",
                                   "Dele ut tre slurker",
                                   "Dele ut like mange slurker som antall bokser"])
        self.Lyd.read(f"Vinneren får {aktivitet}")

        time.sleep(2)

        self.Lyd.unpause_music()

    def karin_henter(self):
        """Karin er tjener!"""

        self.Lyd.pause_music()

        self.Lyd.read('Øl runde!')
        self.Lyd.read('Karin henter drikke til alle som vil ha!')

        time.sleep(15)

        self.Lyd.unpause_music()

    def kaste_snacks(self):
        """Første til å treffe munnen!"""

        self.Lyd.pause_music()

        self.Lyd.read('En og en skal kaste snacks i munnen')
        self.Lyd.read('Første til å kaste og treffe munnen med snacks vinner')
        self.Lyd.read(f"{random.choice(self.deltakere)} starter")
        self.Lyd.read("Trykk for å fortsette")

        self._fortsetter = False
        self._knapp = Vindu.Button(self.vindu, text='FORTSETT', command=self._fortsett)
        self._knapp.place(x=800, y=80)
        while not self._fortsetter:
            self.vindu.update()

        handling = random.choice(["Vinneren får dele ut en slurk",
                                  "Vinneren får dele ut to slurker",
                                  "Vinneren får dele ut tre slurker",
                                  "De som ikke traff munnen må drikke!",
                                  "Alle må drikke antall slurker det tok før vinneren traff",
                                  "Alle unntatt vinneren må drikke antall slurker det tok",
                                  "Alle må drikke like mange slurker som de selv bommet"])

        self.Lyd.read(handling)

        time.sleep(5)

        self.Lyd.unpause_music()

    def mime(self):
        """Mime game."""

        self.Lyd.pause_music()

        self.Lyd.read('Mimelek, tenk på hva du skal mime!')

        time.sleep(5)

        self.Lyd.read(f'{random.choice(self.deltakere)} skal mime, og har 30 sekunder på seg.')

        time.sleep(30)

        self.Lyd.read('Stopp!')
        self.Lyd.read('De som ikke klarte å gjette må drikke. Hvis ingen klarte det må mimeren drikke.')

        time.sleep(2)

        self.Lyd.unpause_music()

    def tommelkrig(self):
        """Thumb war game."""

        self.Lyd.pause_music()

        person_1, person_2 = random.sample(self.deltakere, 2)

        self.Lyd.read(f'Tommelkrig mellom {person_1} og {person_2}!')

        aktivitet = random.choice(["Dele ut to slurker",
                                   "Drikke to slurker",
                                   "Ta en shot",
                                   "Dele ut en slurk",
                                   "Drikke en slurk",
                                   "Dele ut en shot",
                                   "Dele ut tre slurker",
                                   "Drikke tre slurker"])
        self.Lyd.read(f'Den som taper må {aktivitet}')

        time.sleep(20)

        self.Lyd.unpause_music()

    def andreas_round(self):
        """Andreas game."""

        self.Lyd.pause_music()

        self.Lyd.read('Andreas sin runde!')

        time.sleep(2)

        self.Lyd.read("Hvilken sang er dette?")

        time.sleep(1)

        self.Lyd.unpause_music()

    def capture_the_mini(self):
        """Dwarf game."""

        self.Lyd.pause_music()

        self.Lyd.read('Klask den nærmeste minien!')

        time.sleep(2)

        handling = random.choice(["Drikk en slurk",
                                  "Dele ut en slurk",
                                  "Drikke antall klask hen fikk",
                                  "Ingenting, fordi Karin skal drikke to slurker uansett"])

        self.Lyd.read(f'Den som flest klaska får {handling}')

        self.Lyd.unpause_music()


from django.conf import settings
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^user_profile/', include('user_profile.urls')),
    url(r'^wd2csv/', include('wd2csv.urls')),
    url(r'', include('homepage.urls')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns


"""
Creator:
Dhruuv Agarwal
Github: Dhr11

Reference used for iou calculation:
https://github.com/warmspringwinds/pytorch-segmentation-detection/blob/master/pytorch_segmentation_detection/metrics.py
"""
import numpy as np
from sklearn.metrics import confusion_matrix

class custom_conf_matrix():
    def __init__(self, lbl,n_class):
        self.lbl = lbl
        self.n_class = n_class
        self.conf_mat = np.zeros((self.n_class, self.n_class))
    def update_step(self,truth_lbl,pred_lbl):
        if (truth_lbl == 255).all():
            return

        curr_conf_mat = confusion_matrix(y_true=truth_lbl,
                                                    y_pred=pred_lbl,
                                                    labels=self.lbl)
        self.conf_mat += curr_conf_mat

    def compute_mean_iou(self):

        intersection = np.diag(self.conf_mat)
        ground_truth_set = self.conf_mat.sum(axis=1)
        predicted_set = self.conf_mat.sum(axis=0)
        union =  ground_truth_set + predicted_set - intersection

        return np.mean(intersection / union.astype(np.float32))
    def reset(self):
        self.conf_mat = np.zeros((self.n_class, self.n_class))


import ply.yacc as yacc
from Parser.Lexer import Lexer

class Parser:
    tokens = Lexer.tokens

    def __init__(self):
        self.input = None
        self.symbolList = {'globalSymbol': {}, 'subFuncSymbol': {}, 'funcID': {}}
        self.isInSubFunc = False
        self.error = []
        self.warning = []
        self.symbolTable = {}
        self.parser = None

    def p_programstruct(self, p):
        '''programstruct : program_head ';' program_body '.' '''
        p[0] = {
            'p_length': len(p),
            'p_type': 'programstruct',
            'child_nodes': [p[1], p[3]],
            'info': {}
        }
        self.symbolTable = {
            'constTable': p[3]['st']['ct'],
            'varTable': p[3]['st']['vt'],
            'subFuncTable': p[3]['st']['sft']
        }

    def p_program_head(self, p):
        '''program_head : PROGRAM ID '(' idlist ')'
                        | PROGRAM ID'''
        if len(p) == 6:
            p[0] = {
                'p_length': len(p),
                'p_type': 'program_head',
                'child_nodes': [p[4], ],
                'info': {'ID': p[2]}
            }

        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'program_head',
                'child_nodes': [],
                'info': {
                    'ID': p[2],
                }
            }

    def p_program_body(self, p):
        '''program_body : const_declarations var_declarations subprogram_declarations compound_statement'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'program_body',
            'child_nodes': [p[1], p[2], p[3], p[4]],
            'info': {}
        }
        p[0]['st'] = {
            'ct': p[1]['st'],
            'vt': p[2]['st'],
            'sft': p[3]['st']
        }

    def p_idlist(self, p):
        '''idlist : ID
                  | idlist ',' ID'''
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'idlist',
                'info': {
                    'id_l': p[1]['info']['id_l'] + [p[3]]
                }
            }
            self.isRepeatedDefine(p[3], p.slice[3].lineno, p.slice[3].lexpos)
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'idlist',
                'child_nodes': [],
                'info': {
                    'id_l': [p[1]]
                }
            }
            self.isRepeatedDefine(p[1], p.slice[1].lineno, p.slice[1].lexpos)

    def p_const_declarations(self, p):
        '''const_declarations : empty
                              | CONST const_declaration ';' '''
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'const_declarations',
                'child_nodes': [p[2], ],
                'info': {}
            }
            p[0]['st'] = p[2]['st']
        else:
            p[0] = {'st': []}

    def p_const_declaration(self, p):
        '''const_declaration : ID RELOP const_value
                             | const_declaration ';' ID RELOP const_value'''  # RELOP只能为'='
        if len(p) == 6:
            p[0] = {
                'p_length': len(p),
                'p_type': 'const_declaration',
                'child_nodes': [p[1], p[5]],
                'info': {
                    'values': p[1]['info']['values'] + [{'ID': p[3], 'const_value': p[5]}]
                }
            }
            newST = {
                'id': p[3],
                'type': p[5]['info']['true_type'],
                'value': p[5]['info']['value']
            }
            p[0]['st'] = p[1]['st'] + [newST]
            self.isRepeatedDefine(p[3], p.slice[3].lineno, p.slice[3].lexpos)
            if self.isInSubFunc:
                self.symbolList['subFuncSymbol'][p[3]] = newST.copy()
                self.symbolList['subFuncSymbol'][p[3]]['isConst'] = True
            else:
                self.symbolList['globalSymbol'][p[3]] = newST.copy()
                self.symbolList['globalSymbol'][p[3]]['isConst'] = True
            if p[4] != '=':
                self.error.append({
                    'error': 'illegal syntax',
                    'value': p[4],
                    'line': p.slice[4].lineno,
                    'column': self.getColumn(self.input,  p.slice[4].lexpos)
                })
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'const_declaration',
                'child_nodes': [p[3], ],
                'info': {
                    'values': [{'ID': p[1], 'const_value': p[3]}]
                }
            }
            newST = {
                'id': p[1],
                'type': p[3]['info']['true_type'],
                'value': p[3]['info']['value']
            }
            p[0]['st'] = [newST]
            self.isRepeatedDefine(p[1], p.slice[1].lineno, p.slice[1].lexpos)
            if self.isInSubFunc:
                self.symbolList['subFuncSymbol'][p[1]] = newST.copy()
                self.symbolList['subFuncSymbol'][p[1]]['isConst'] = True
            else:
                self.symbolList['globalSymbol'][p[1]] = newST.copy()
                self.symbolList['globalSymbol'][p[1]]['isConst'] = True
            if p[2] != '=':
                self.error.append({
                    'error': 'illegal syntax',
                    'value': p[2],
                    'line': p.slice[2].lineno,
                    'column': self.getColumn(self.input,  p.slice[2].lexpos)
                })

    def p_const_value(self, p):
        '''const_value : ADDOP NUM
                       | NUM
                       | LETTER'''  # ADDOP只能为'+'、'-'
        if len(p) == 3:
            p[0] = {
                'p_length': len(p),
                'p_type': 'const_value',
                'child_nodes': [],
                'info': {
                    '_type': 'NUM',
                    'true_type': 'INTEGER' if type(p[2]) == int else 'REAL',
                    'value': -p[2] if p[1] == '-' else p[2]
                }
            }
            if p[1].upper() == 'OR':
                self.error.append({
                    'error': 'illegal syntax',
                    'value': p[1],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input,  p.slice[1].lexpos)
                })
        elif type(p[1]) != str:
            p[0] = {
                'p_length': len(p),
                'p_type': 'const_value',
                'child_nodes': [],
                'info': {
                    '_type': 'NUM',
                    'true_type': 'INTEGER' if type(p[1]) == int else 'REAL',
                    'value': p[1]
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'const_value',
                'child_nodes': [],
                'info': {
                    '_type': 'LETTER',
                    'true_type': 'CHAR',
                    'value': p[1]
                }
            }

    def p_var_declarations(self, p):
        '''var_declarations : empty
                            | VAR var_declaration ';' '''
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'var_declarations',
                'child_nodes': [p[2], ],
                'info': {}
            }
            p[0]['st'] = p[2]['st']
        else:
            p[0] = {'st': []}

    def p_var_declaration(self, p):
        '''var_declaration : idlist ':' type
                           | var_declaration ';' idlist ':' type'''
        if len(p) == 6:
            p[0] = {
                'p_length': len(p),
                'p_type': 'var_declaration',
                'child_nodes': [p[1], p[3], p[5]],
                'info': {
                    'values': p[1]['info']['values'] + [{'id_l': p[3], 'type': p[5]}]
                }
            }
            p[0]['st'] = p[1]['st']
            for i in p[3]['info']['id_l']:
                newST = {
                    'id': i,
                    'type': p[5]['st']['type'],
                    'array': {
                        'isArray': p[5]['st']['array']['isArray'],
                        'dimension': p[5]['st']['array']['dimension'],
                        'size': p[5]['st']['array']['size'],
                        'start': p[5]['st']['array']['start'],
                    }
                }
                p[0]['st'] += [newST]
                if self.isInSubFunc:
                    self.symbolList['subFuncSymbol'][i] = newST.copy()
                    self.symbolList['subFuncSymbol'][i]['isConst'] = False
                else:
                    self.symbolList['globalSymbol'][i] = newST.copy()
                    self.symbolList['globalSymbol'][i]['isConst'] = False
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'var_declaration',
                'child_nodes': [p[1], p[3]],
                'info': {
                    'values': [{'id_l': p[1], 'type': p[3]}]
                }
            }
            p[0]['st'] = []
            for i in p[1]['info']['id_l']:
                newST = {
                    'id': i,
                    'type': p[3]['st']['type'],
                    'array': {
                        'isArray': p[3]['st']['array']['isArray'],
                        'dimension': p[3]['st']['array']['dimension'],
                        'size': p[3]['st']['array']['size'],
                        'start': p[3]['st']['array']['start'],
                    }
                }
                p[0]['st'] += [newST]
                if self.isInSubFunc:
                    self.symbolList['subFuncSymbol'][i] = newST.copy()
                    self.symbolList['subFuncSymbol'][i]['isConst'] = False
                else:
                    self.symbolList['globalSymbol'][i] = newST.copy()
                    self.symbolList['globalSymbol'][i]['isConst'] = False

    def p_type(self, p):
        '''type : basic_type
                | ARRAY '[' period ']' OF basic_type'''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': 'type',
                'child_nodes': [p[1], ],
                'info': {
                    '_type': p[1]
                }
            }
            p[0]['st'] = {
                'type': p[1]['st'],
                'array': {
                    'isArray': False,
                    'dimension': 0,
                    'size': [],
                    'start': [],
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'type',
                'child_nodes': [p[3], p[6]],
                'info': {
                    '_type': 'ARRAY',
                }
            }
            p[0]['st'] = {
                'type': p[6]['st'],
                'array': {
                    'isArray': True,
                    'dimension': p[3]['st']['dimension'],
                    'size': p[3]['st']['size'],
                    'start': p[3]['st']['start'],
                }
            }

    def p_basic_type(self, p):
        '''basic_type : INTEGER
                      | REAL
                      | BOOLEAN
                      | CHAR'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'basic_type',
            'child_nodes': [],
            'info': {
                '_type': p[1].upper()
            }
        }
        p[0]['st'] = p[1].upper()

    def p_period(self, p):
        '''period : NUM DOUBLEDOT NUM
                  | period ',' NUM DOUBLEDOT NUM'''
        if len(p) == 4:
            # NUM只能为整数
            if type(p[1]) == float:
                self.error.append({
                    'error': 'The number representing array bounds should be integer',
                    'value': p[1],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input,  p.slice[1].lexpos)
                })
            if type(p[3]) == float:
                self.error.append({
                    'error': 'The number representing array bounds should be integer',
                    'value': p[3],
                    'line': p.slice[3].lineno,
                    'column': self.getColumn(self.input,  p.slice[3].lexpos)
                })
            # 左边界不能大于右边界
            if p[1] > p[3]:
                self.error.append({
                    'error': 'The lower limit cannot be greater than the upper limit',
                    'value': [p[1], p[3]],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input,  p.slice[1].lexpos)
                })
            p[0] = {
                'p_length': len(p),
                'p_type': 'period',
                'child_nodes': [],
                'info': {
                    'values': [{'start': p[1], 'end': p[3]}]
                }
            }
            p[0]['st'] = {
                'dimension': 1,
                'start': [p[1]],
                'size': [p[3] - p[1] + 1]
            }
        else:
            # NUM只能为整数
            if type(p[3]) == float:
                self.error.append({
                    'error': 'The number representing array bounds should be integer',
                    'value': p[3],
                    'line': p.slice[3].lineno,
                    'column': self.getColumn(self.input,  p.slice[3].lexpos)
                })
            if type(p[5]) == float:
                self.error.append({
                    'error': 'The number representing array bounds should be integer',
                    'value': p[5],
                    'line': p.slice[5].lineno,
                    'column': self.getColumn(self.input,  p.slice[5].lexpos)
                })
            # 左边界不能大于右边界
            if p[3] > p[5]:
                self.error.append({
                    'error': 'The lower limit cannot be greater than the upper limit',
                    'value': [p[3], p[5]],
                    'line': p.slice[3].lineno,
                    'column': self.getColumn(self.input,  p.slice[3].lexpos)
                })
            p[0] = {
                'p_length': len(p),
                'p_type': 'period',
                'child_nodes': [p[1], ],
                'info': {
                    'values': p[1]['info']['values'] + [{'start': p[3], 'end': p[5]}]
                }
            }
            p[0]['st'] = {
                'dimension': p[1]['st']['dimension'] + 1,
                'start': p[1]['st']['start'] + [p[3]],
                'size': p[1]['st']['size'] + [p[5] - p[3] + 1]
            }

    def p_subprogram_declarations(self, p):
        '''subprogram_declarations : empty
                                   | subprogram_declarations subprogram ';' '''
        self.isInSubFunc = False
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'subprogram_declarations',
                'child_nodes': [p[1], p[2]],
                'info': {
                    'subprograms': p[1]['info']['subprograms'] + [p[2]] if 'info' in p[1].keys() else [p[2]]
                }
            }
            p[0]['st'] = p[1]['st'] + [p[2]['st']]
        else:
            p[0] = {'st': []}

    def p_subprogram(self, p):
        '''subprogram : subprogram_head ';' subprogram_body'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'subprogram',
            'child_nodes': [p[1], p[3]],
            'info': {
            }
        }
        p[0]['st'] = {
            'id': p[1]['st']['id'],
            'type': p[1]['st']['type'],
            'size': p[1]['st']['size'],
            'isReference': p[1]['st']['isReference'],
            'constTable': p[3]['st']['constTable'],
            'varTable': p[1]['st']['varTable'] + p[3]['st']['varTable']
        }

    def p_subprogram_head(self, p):
        '''subprogram_head : procedure ID formal_parameter
                           | function ID formal_parameter ':' basic_type'''
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'subprogram_head',
                'child_nodes': [p[3], ],
                'info': {
                    'ID': p[2],
                    '_type': 'PROCEDURE'
                }
            }
            p[0]['st'] = {
                'id': p[2],
                'type': None,
                'size': p[3]['st']['size'],
                'isReference': p[3]['st']['isReference'],
                'varTable': p[3]['st']['varTable']
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'subprogram_head',
                'child_nodes': [p[3], p[5]],
                'info': {
                    'ID': p[2],
                    '_type': 'FUNCTION'
                }
            }
            p[0]['st'] = {
                'id': p[2],
                'type': p[5]['st'],
                'size': p[3]['st']['size'],
                'isReference': p[3]['st']['isReference'],
                'varTable': p[3]['st']['varTable']
            }
        if p[2] in self.symbolList['funcID'].keys():
            self.error.append({
                'error': 'Define function_ID repeatedly',
                'value': p[2],
                'line': p.slice[2].lineno,
                'column': self.getColumn(self.input,  p.slice[2].lexpos)
            })
        self.symbolList['funcID'][p[2]] = p[0]['st'].copy()
        self.symbolList['subFuncSymbol'][p[2]] = p[0]['st'].copy()
        self.symbolList['subFuncSymbol'][p[2]]['isConst'] = False

    def p_procedure(self, p):
        '''procedure : PROCEDURE'''
        self.isInSubFunc = True
        self.symbolList['subFuncSymbol'].clear()

    def p_function(self, p):
        '''function : FUNCTION'''
        self.isInSubFunc = True
        self.symbolList['subFuncSymbol'].clear()

    def p_formal_parameter(self, p):
        '''formal_parameter : empty
                            | '(' parameter_list ')' '''
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'formal_parameter',
                'child_nodes': [p[2], ],
                'info': {}
            }
            p[0]['st'] = {
                'size': p[2]['st']['size'],
                'isReference': p[2]['st']['isReference'],
                'varTable': p[2]['st']['varTable']
            }
        else:
            p[0] = {'st': {
                'size': None,
                'isReference': None,
                'varTable': None
            }}

    def p_parameter_list(self, p):
        '''parameter_list : parameter
                          | parameter_list ';' parameter'''
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'parameter_list',
                'child_nodes': [p[1], p[3]],
                'info': {
                    'parameters': p[1]['info']['parameters'] + [p[3]]
                }
            }
            p[0]['st'] = {
                'size': p[1]['st']['size'] + p[3]['st']['size'],
                'isReference': p[1]['st']['isReference'] + p[3]['st']['isReference'],
                'varTable': p[1]['st']['varTable'] + p[3]['st']['varTable']
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'parameter_list',
                'child_nodes': [p[1], ],
                'info': {
                    'parameters': [p[1]]
                }
            }
            p[0]['st'] = {
                'size': p[1]['st']['size'],
                'isReference': p[1]['st']['isReference'],
                'varTable': p[1]['st']['varTable']
            }

    def p_parameter(self, p):
        '''parameter : var_parameter
                     | value_parameter'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'parameter',
            'child_nodes': [p[1], ],
            'info': {
                'value': p[1]
            }
        }
        p[0]['st'] = p[1]['st']

    def p_var_parameter(self, p):
        '''var_parameter : VAR value_parameter'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'var_parameter',
            'child_nodes': [p[2], ],
            'info': {}
        }
        p[0]['st'] = {
            'isReference': [True for i in range(len(p[2]['child_nodes'][0]['info']['id_l']))],
            'size': p[2]['st']['size'],
            'varTable': p[2]['st']['varTable']
        }

    def p_value_parameter(self, p):
        '''value_parameter : idlist ':' basic_type'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'value_parameter',
            'child_nodes': [p[1], p[3]],
            'info': {
                'basic_type': p[3]
            }
        }
        p[0]['st'] = {
            'isReference': [False for i in range(len(p[1]['info']['id_l']))],
            'size': len(p[1]['info']['id_l']),
            'varTable': []
        }
        for i in p[1]['info']['id_l']:
            newST = {
                'id': i,
                'type': p[3]['st'],
                'array': {
                    'isArray': False,
                    'dimension': 0,
                    'size': [],
                    'start': []
                }
            }
            p[0]['st']['varTable'] += [newST]
            self.symbolList['subFuncSymbol'][i] = newST.copy()
            self.symbolList['subFuncSymbol'][i]['isConst'] = False

    def p_subprogram_body(self, p):
        '''subprogram_body : const_declarations var_declarations compound_statement'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'subprogram_body',
            'child_nodes': [p[1], p[2], p[3]],
            'info': {}
        }
        p[0]['st'] = {
            'constTable': p[1]['st'],
            'varTable': p[2]['st']
        }

    def p_compound_statement(self, p):
        '''compound_statement : BEGIN statement_list END'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'compound_statement',
            'child_nodes': [p[2], ],
            'info': {}
        }

    def p_statement_list(self, p):
        '''statement_list : statement
                          | statement_list ';' statement'''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': 'statement_list',
                'child_nodes': [p[1], ],
                'info': {
                    'statements': [p[1]]
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'statement_list',
                'child_nodes': [p[1], p[3]],
                'info': {
                    'statements': p[1]['info']['statements'] + [p[3]]
                }
            }

    def p_statement(self, p):
        '''statement : empty
                     | variable ASSIGNOP expression
                     | procedure_call
                     | compound_statement
                     | IF expression THEN statement else_part
                     | FOR ID ASSIGNOP expression TO expression DO statement
                     | READ '(' variable_list ')'
                     | WRITE '(' expression_list ')' '''
        if type(p[1]) == str:
            if p[1].upper() == 'IF':
                p[0] = {
                    'p_length': len(p),
                    'p_type': "statement",
                    'child_nodes': [p[2], p[4], p[5]],
                    'info': {
                        '_type': 'IF'
                    }
                }
                if p[2]['info']['exp_type'] != 'BOOLEAN':
                    self.error.append({
                        'error': 'The type of the conditional judgment expression should be Boolean',
                        'value': 'The conditional judgment expression in IF statement',
                        'line': p.slice[1].lineno,
                        'column': self.getColumn(self.input, p.slice[1].lexpos + 3)
                    })
            elif p[1].upper() == 'FOR':
                p[0] = {
                    'p_length': len(p),
                    'p_type': "statement",
                    'child_nodes': [p[4], p[6], p[8]],
                    'info': {
                        '_type': 'FOR',
                        'ID': p[2],
                        'ASSIGNOP': p[3]
                    }
                }
                if not self.findSymbol(p[2]):
                    self.error.append({
                        'error': 'Undefined identifier',
                        'value': p[2],
                        'line': p.slice[2].lineno,
                        'column': self.getColumn(self.input,  p.slice[2].lexpos)
                    })
                elif self.findSymbol(p[2])['isConst']:
                    self.error.append({
                        'error': 'Constant cannot be assigned',
                        'value': p[2],
                        'line': p.slice[2].lineno,
                        'column': self.getColumn(self.input,  p.slice[2].lexpos)
                    })
                elif p[4]['info']['exp_type'] != 'Undefined' and not self.isSafeAssign(p[4]['info']['exp_type'], self.findSymbol(p[2])['type']):
                    self.warning.append({
                        'warning': 'Unsafe assignment',
                        'value': p[4]['info']['exp_type'] + ' assign to ' + self.findSymbol(p[2])['type'],
                        'line': p.slice[2].lineno,
                        'column': self.getColumn(self.input,  p.slice[2].lexpos)
                    })
            elif p[1].upper() == 'READ':
                p[0] = {
                    'p_length': len(p),
                    'p_type': "statement",
                    'child_nodes': [p[3], ],
                    'info': {
                        '_type': 'READ'
                    }
                }
            elif p[1].upper() == 'WRITE':
                p[0] = {
                    'p_length': len(p),
                    'p_type': "statement",
                    'child_nodes': [p[3], ],
                    'info': {
                        '_type': 'WRITE'
                    }
                }
        elif p[1]['p_type'] == 'empty':
            p[0] = []
        elif p[1]['p_type'] == 'variable':
            p[0] = {
                'p_length': len(p),
                'p_type': 'statement',
                'child_nodes': [p[1], p[3]],
                'info': {
                    '_type': 'variable',
                    'ASSIGNOP': p[2]
                }
            }
            if self.findSymbol(p[1]['info']['ID']):
                if self.findSymbol(p[1]['info']['ID'])['isConst']:
                    self.error.append({
                        'error': 'Constant cannot be assigned',
                        'value': p[1]['info']['ID'],
                        'line': p.slice[2].lineno,
                        'column': self.getColumn(self.input, p.slice[2].lexpos)
                    })
                else:
                    var_type = p[1]['info']['var_type']
                    exp_type = p[3]['info']['exp_type']
                    if var_type is None:
                        self.error.append({
                            'error': 'Procedure has no return value',
                            'value': p[1]['info']['ID'],
                            'line': p.slice[2].lineno,
                            'column': self.getColumn(self.input, p.slice[2].lexpos)
                        })
                    elif exp_type and exp_type != 'Undefined' and not self.isSafeAssign(exp_type, var_type):
                        self.warning.append({
                            'warning': 'Unsafe assignment',
                            'value': exp_type + ' assign to ' + var_type,
                            'line': p.slice[2].lineno,
                            'column': self.getColumn(self.input,  p.slice[2].lexpos)
                        })
        elif p[1]['p_type'] == 'procedure_call':
            p[0] = {
                'p_length': len(p),
                'p_type': "statement",
                'child_nodes': [p[1], ],
                'info': {
                    '_type': 'procedure_call'
                }
            }
        elif p[1]['p_type'] == 'compound_statement':
            p[0] = {
                'p_length': len(p),
                'p_type': "statement",
                'child_nodes': [p[1], ],
                'info': {
                    '_type': 'compound_statement'
                }
            }

    def p_variable_list(self, p):
        '''variable_list : variable
                         | variable_list ',' variable'''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': "variable_list",
                'child_nodes': [p[1], ],
                'info': {
                    'variables': [p[1]]
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': "variable_list",
                'child_nodes': [p[1], p[3]],
                'info': {
                    'variables': p[1]['info']['variables'] + [p[3]]
                }
            }

    def p_variable(self, p):
        '''variable : ID id_varpart'''
        p[0] = {
            'p_length': len(p),
            'p_type': 'variable',
            'child_nodes': [p[2], ],
            'info': {
                'ID': p[1],
                'var_type': self.findSymbol(p[1])['type'] if self.findSymbol(p[1]) else 'UNDEFINED'
            }
        }
        if p[0]['info']['var_type'] == 'UNDEFINED':  # 判断id是否被定义
            self.error.append({
                'error': 'Undefined identifier',
                'value': p[1],
                'line': p.slice[1].lineno,
                'column': self.getColumn(self.input, p.slice[1].lexpos)
            })
        if p[2] is not None:
            if not self.findSymbol(p[1])['array']['isArray']:  # 判断若id有下标，id是否为array
                self.error.append({
                    'error': 'subscripted value is not an array',
                    'value': p[1],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input, p.slice[1].lexpos)
                })
            elif len(p[2]['child_nodes'][0]['info']['exp_type']) != self.findSymbol(p[1])['array']['dimension']:  # 维度是否一致
                self.error.append({
                    'error': 'Dimension different',
                    'value': p[1],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input, p.slice[1].lexpos)
                })
        elif 'array' in self.findSymbol(p[1]).keys() and self.findSymbol(p[1])['array']['isArray']:  # 维度是否一致
            self.error.append({
                'error': 'Dimension different',
                'value': p[1],
                'line': p.slice[1].lineno,
                'column': self.getColumn(self.input, p.slice[1].lexpos)
            })

    def p_id_varpart(self, p):
        '''id_varpart : empty
                      | '[' expression_list ']' '''
        if len(p) == 4:
            p[0] = {
                'p_length': len(p),
                'p_type': 'id_varpart',
                'child_nodes': [p[2], ],
                'info': {}
            }
        else:
            p[0] = None

    def p_procedure_call(self, p):
        '''procedure_call : ID
                          | ID '(' expression_list ')' '''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': 'procedure_call',
                'child_nodes': [],
                'info': {
                    'ID': p[1]
                }
            }
            if p[1] not in self.symbolList['funcID'].keys():
                self.error.append({
                    'error': 'Undefined identifier',
                    'value': p[1],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input,  p.slice[1].lexpos)
                })
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'procedure_call',
                'child_nodes': [p[3], ],
                'info': {
                    'ID': p[1]
                }
            }
            self.errorInProcedureCall(p)

    def p_else_part(self, p):
        '''else_part : empty
                     | ELSE statement'''
        if len(p) == 3:
            p[0] = {
                'p_length': len(p),
                'p_type': 'else_part',
                'child_nodes': [p[2], ],
                'info': {}
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'else_part',
                'child_nodes': [],
                'info': {}
            }

    def p_expression_list(self, p):
        '''expression_list : expression
                           | expression_list ',' expression'''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': 'expression_list',
                'child_nodes': [p[1], ],
                'info': {
                    'exp_type': [p[1]['info']['exp_type']],
                    'expressions': [p[1]]
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'expression_list',
                'child_nodes': [p[1], p[3]],
                'info': {
                    'exp_type': p[1]['info']['exp_type'] + [p[3]['info']['exp_type']],
                    'expressions': p[1]['info']['expressions'] + [p[3]]
                }
            }

    def p_expression(self, p):
        '''expression : simple_expression
                      | simple_expression RELOP simple_expression'''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': 'expression',
                'child_nodes': [p[1], ],
                'info': {
                    'exp_type': p[1]['info']['exp_type']
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'expression',
                'child_nodes': [p[1], p[3]],
                'info': {
                    'RELOP': p[2],
                    'exp_type': 'BOOLEAN'
                }
            }

    def p_simple_expression(self, p):
        '''simple_expression : term
                             | simple_expression ADDOP term'''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': 'simple_expression',
                'child_nodes': [p[1], ],
                'info': {
                    'exp_type': p[1]['info']['exp_type']
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'simple_expression',
                'child_nodes': [p[1], p[3]],
                'info': {
                    'ADDOP': p[2]
                }
            }
            self.getExpType(p)

    def p_term(self, p):
        '''term : factor
                | term MULOP factor'''
        if len(p) == 2:
            p[0] = {
                'p_length': len(p),
                'p_type': 'term',
                'child_nodes': [p[1], ],
                'info': {
                    'exp_type': p[1]['info']['exp_type']
                }
            }
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'term',
                'child_nodes': [p[1], p[3]],
                'info': {
                    'MULOP': p[2]
                }
            }
            self.getExpType(p)

    def p_factor(self, p):
        '''factor : NUM
                  | variable
                  | '(' expression ')'
                  | ID '(' expression_list ')'
                  | NOT factor
                  | ADDOP factor'''  # ADDOP只能为'-'
        if type(p[1]) == int or type(p[1]) == float:
            p[0] = {
                'p_length': len(p),
                'p_type': 'factor',
                'child_nodes': [],
                'info': {
                    '_type': 'NUM',
                    'exp_type': 'INTEGER' if type(p[1]) == int else 'REAL',
                    'NUM': p[1]
                }
            }
        elif type(p[1]) == dict:
            p[0] = {
                'p_length': len(p),
                'p_type': 'factor',
                'child_nodes': [p[1], ],
                'info': {
                    '_type': 'variable',
                    'exp_type': p[1]['info']['var_type']
                }
            }
        elif p[1] == '(':
            p[0] = {
                'p_length': len(p),
                'p_type': 'factor',
                'child_nodes': [p[2], ],
                'info': {
                    '_type': 'expression',
                    'exp_type': p[2]['info']['exp_type'],
                }
            }
        elif p[1].upper() == 'NOT':
            p[0] = {
                'p_length': len(p),
                'p_type': 'factor',
                'child_nodes': [p[2], ],
                'info': {
                    '_type': 'NOT',
                    'exp_type': p[2]['info']['exp_type'],
                }
            }
        elif p[1] == '+' or p[1] == '-' or p[1].upper == 'OR':
            p[0] = {
                'p_length': len(p),
                'p_type': 'factor',
                'child_nodes': [p[2], ],
                'info': {
                    '_type': 'UMINUS' if p[1] == '-' else 'NORMAL',
                    'exp_type': p[2]['info']['exp_type'],
                }
            }
            if p[1].upper == 'OR':
                self.error.append({
                    'error': 'illegal syntax',
                    'value': p[1],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input,  p.slice[1].lexpos)
                })
        else:
            p[0] = {
                'p_length': len(p),
                'p_type': 'factor',
                'child_nodes': [p[3], ],
                'info': {
                    '_type': 'procedure_id',
                    'exp_type': self.symbolList['funcID'][p[1]]['type'] if p[1] in self.symbolList['funcID'].keys() else 'Undefined',
                    'ID': p[1]
                }
            }
            if p[0]['info']['exp_type'] is None:
                self.error.append({
                    'error': 'Procedure has no return value',
                    'value': p[1],
                    'line': p.slice[1].lineno,
                    'column': self.getColumn(self.input, p.slice[1].lexpos)
                })
            self.errorInProcedureCall(p)

    def p_empty(self, p):
        'empty :'
        p[0] = {
            'p_length': len(p),
            'p_type': 'empty',
            'child_nodes': [],
            'info': {}
        }
        pass

    def p_error(self, p):
        if p:
            self.error.append({
                'error': 'illegal syntax',
                'value': p.value,
                'line': p.lineno,
                'column': self.getColumn(self.input,  p.lexpos)
            })

    def isRepeatedDefine(self, id, line, lexpos):
        if self.isInSubFunc:
            if id in self.symbolList['subFuncSymbol'].keys():
                self.error.append({
                    'error': 'Define ID repeatedly',
                    'value': id,
                    'line': line,
                    'column': self.getColumn(self.input,  lexpos)
                })
        else:
            if id in self.symbolList['globalSymbol'].keys():
                self.error.append({
                    'error': 'Define ID repeatedly',
                    'value': id,
                    'line': line,
                    'column': self.getColumn(self.input,  lexpos)
                })

    def getExpType(self, p):
        if p[1]['info']['exp_type'] == 'UNDEFINED' or p[3]['info']['exp_type'] == 'UNDEFINED':
            p[0]['info']['exp_type'] = 'UNDEFINED'
        elif p[1]['info']['exp_type'] == "REAL" or p[3]['info']['exp_type'] == "REAL":
            p[0]['info']['exp_type'] = "REAL"
        elif p[1]['info']['exp_type'] == "INTEGER" or p[3]['info']['exp_type'] == "INTEGER":
            p[0]['info']['exp_type'] = "INTEGER"
        elif p[1]['info']['exp_type'] == "CHAR" or p[3]['info']['exp_type'] == "CHAR":
            p[0]['info']['exp_type'] = "CHAR"
        elif p[1]['info']['exp_type'] == "BOOLEAN" or p[3]['info']['exp_type'] == "BOOLEAN":
            p[0]['info']['exp_type'] = "BOOLEAN"

    def findSymbol(self, id):
        if self.isInSubFunc and id in self.symbolList['subFuncSymbol'].keys():
            return self.symbolList['subFuncSymbol'][id]
        elif id in self.symbolList['globalSymbol'].keys():
            return self.symbolList['globalSymbol'][id]
        else:
            return False

    def isSafeAssign(self, sour, des):
        if (
                (sour == 'INTEGER' and (des == 'INTEGER' or des == 'REAL')) or
                (sour == 'REAL' and des == 'REAL') or
                (sour == 'CHAR' and (des == 'CHAR' or des == 'INTEGER' or des == 'REAL')) or
                (sour == 'BOOLEAN' and (des == 'BOOLEAN' or des == 'INTEGER' or des == 'REAL' or des == 'CHAR'))
        ):
            return True
        return False

    def errorInProcedureCall(self, p):
        if p[1] not in self.symbolList['funcID'].keys():
            self.error.append({
                'error': 'Undefined identifier',
                'value': p[1],
                'line': p.slice[1].lineno,
                'column': self.getColumn(self.input,  p.slice[1].lexpos)
            })
        elif len(p[3]['info']['expressions']) != self.symbolList['funcID'][p[1]]['size']:
            self.error.append({
                'error': 'The number of parameters does not match in function call',
                'value': p[1],
                'line': p.slice[1].lineno,
                'column': self.getColumn(self.input,  p.slice[1].lexpos)
            })
        else:
            for i in range(len(p[3]['info']['expressions'])):
                var_type = p[3]['info']['exp_type'][i]
                para_type = self.symbolList['funcID'][p[1]]['varTable'][i]['type']
                if var_type != 'Undefined' and para_type != 'Undefined' and not self.isSafeAssign(var_type, para_type):
                    self.warning.append({
                        'warning': 'Unsafe assignment',
                        'value': str(i + 1) + 'th parameter: ' + var_type + ' assign to ' + para_type,
                        'line': p.slice[1].lineno,
                        'column': self.getColumn(self.input,  p.slice[1].lexpos)
                    })
                elif self.symbolList['funcID'][p[1]]['isReference'][i] and not (
                        p[3]['info']['expressions'][i]['child_nodes'][0]['p_length'] == 2 and
                        p[3]['info']['expressions'][i]['child_nodes'][0]['child_nodes'][0]['p_length'] == 2 and
                        p[3]['info']['expressions'][i]['child_nodes'][0]['child_nodes'][0]['child_nodes'][0]['info']['_type'] == 'variable'
                ):
                    self.error.append({
                        'error': 'Unable to call by reference',
                        'value': str(i + 1) + 'th parameter',
                        'line': p.slice[1].lineno,
                        'column': self.getColumn(self.input,  p.slice[1].lexpos)
                    })

    def getColumn(self, input, lexpos):
        last_cr = input.rfind('\n', 0, lexpos)
        if last_cr < 0:
            last_cr = -1
        column = lexpos - last_cr
        return column

    def run(self, input, **kwargs):
        self.symbolTable.clear()
        self.warning.clear()
        self.error.clear()
        self.symbolList['globalSymbol'].clear()
        self.symbolList['subFuncSymbol'].clear()
        self.symbolList['funcID'].clear()
        self.input = input
        lexer = Lexer()
        lexer.build(input)
        self.parser = yacc.yacc(module=self, **kwargs)
        ast = self.parser.parse(input)
        return [ast, self.symbolTable, self.warning, lexer.error + self.error]

if __name__ == '__main__':
    data = open('../input.txt').read()
    m = Parser()
    import json as js
    fw=open("../input.out_const", "w+")
    ret=m.run(data)
    print(type(ret[1]))
    js.dump(ret,fw,indent=2)


from pydicm import *

# import logging
# logging.basicConfig(level=0)

fn = "/tmp/input.dcm"

with open(fn, "rb") as f:
    parser = Parser()
    parser.set_input(f)
    done = False
    while not done:
        ret = parser.next_event()
        etype = ret
        # print(etype)
        if etype == Parser.EventType.ELEMENT_KEY:
            key = parser.key()
            print(key)
        elif etype == Parser.EventType.ELEMENT_VALUE:
            vl = parser.value_length()
            buflen = 4096
            while vl != 0:
                length = vl if vl < buflen else buflen
                ba = parser.read_value(length)
                vl -= length
        done = etype == Parser.EventType.STREAM_END


pkgname = "gnome-settings-daemon"
pkgver = "45.0"
pkgrel = 0
build_style = "meson"
configure_args = ["-Dsystemd=false"]
hostmakedepends = [
    "meson",
    "pkgconf",
    "glib-devel",
    "xsltproc",
    "docbook-xsl-nons",
    "perl",
    "gettext",
]
makedepends = [
    "glib-devel",
    "geocode-glib-devel",
    "gnome-desktop-devel",
    "gtk+3-devel",
    "gsettings-desktop-schemas-devel",
    "libgweather-devel",
    "lcms2-devel",
    "libcanberra-devel",
    "geoclue-devel",
    "libnotify-devel",
    "libpulse-devel",
    "pango-devel",
    "upower-devel",
    "libx11-devel",
    "libxfixes-devel",
    "libgudev-devel",
    "wayland-devel",
    "cups-devel",
    "udev-devel",
    "networkmanager-devel",
    "colord-devel",
    "polkit-devel",
    # actually pulseaudio is used, alsa is only used to query hw info
    "modemmanager-devel",
    "gcr-devel",
    "alsa-lib-devel",
    "libwacom-devel",
    "nss-devel",
]
checkdepends = [
    "elogind",
    "udev",
    "libnotify",
    "python-dbusmock",
    "python-gobject",
    "python-pycodestyle",
    "hwdata",
]
pkgdesc = "GNOME settings daemon"
maintainer = "q66 <q66@chimera-linux.org>"
license = "GPL-2.0-or-later AND LGPL-2.1-or-later"
url = "https://gitlab.gnome.org/GNOME/gnome-settings-daemon"
source = f"$(GNOME_SITE)/{pkgname}/{pkgver[:-2]}/{pkgname}-{pkgver}.tar.xz"
sha256 = "bb4dc46950e2a90f38f23225848856d2a7b1b718c89d0285ce197b7016bb1dc8"
tool_flags = {"CFLAGS": ["-UG_DISABLE_ASSERT"]}
# unpackaged checkdepends
options = ["!check"]

@subpackage("gnome-settings-daemon-devel")
def _devel(self):
    self.depends += [f"{pkgname}={pkgver}-r{pkgrel}"]

    return self.default_devel()


#!/bin/env python3.9

import sys
from base45 import b45decode
import zlib
from cbor2 import loads
from cose.messages import Sign1Message
from pyzbar.pyzbar import decode
from PIL import Image
import argparse

# Initialize components
CLI_PARSER = argparse.ArgumentParser()

def unpack_qr(qr_text):
    compressed_bytes = b45decode(qr_text[4:])
    cose_bytes = zlib.decompress(compressed_bytes)
    cose_message = Sign1Message.decode(cose_bytes)
    cbor_message = loads(cose_message.payload)
    return {
        "COSE": cose_message,
        "JSON": cbor_message[-260][1]
    }

def read_qr_pyzbar(file):
    barcode = decode(Image.open(file))[0]
    return barcode.data.decode("utf-8")

CLI_PARSER.add_argument(
    '--file',
    type=str,
    help='QR file')

args = CLI_PARSER.parse_args()

if args.file is None:
    CLI_PARSER.print_help()
    sys.exit()

print()
print()
data = read_qr_pyzbar(args.file)
print("Raw QR data")
print(data)
json = unpack_qr(data)
print()
print("Hcert")
print(data)
print()
print("JSON")
print(json["JSON"])
print()
print("COSE")
print(json["COSE"])
print()


def openfile():
	import json
	f = open('bonus.txt', 'r')
	val = json.load(f)
	return val

def viewfile(content):
	print(content)

def binarySearch(alist,item):
	alist.sort()
	first = 0
	last = len(alist)-1
	found = False
	print(alist)

	while first<=last and not found:
		middle = (first+last)//2
		if alist[middle] == item:
			found = True
		else:
			if item < alist[middle]:
				last=middle-1
			else:
				first=middle+1

	if found:
		print('Item found : ', item)
	else:
		print("Item not found!")


#!/usr/bin/env python
#mapper

import sys
import csv

reader = csv.reader(sys.stdin, delimiter='\t')

for line in reader:
    if len(line) == 19:
        if not line[0].isdigit():  # skip header
            continue

        node_id, title, tag_names, author_id, body, node_type, parent_id, abs_parent_id, added_at, score, = line[0:10]
        state_string, last_edited_id, last_activity_by_id, last_activity_at, active_revision_id, extra, = line[10:16]
        extra_ref_id, extra_count, marked = line[16:]

        if node_type == "question":
            print("{0}\t{1}".format(node_id, author_id))
        else:
            print("{0}\t{1}".format(abs_parent_id, author_id))

#!/usr/bin/env python
#reducer
import sys

old_key = None
users = []

for line in sys.stdin:
    data_mapped = line.strip().split("\t")
    if len(data_mapped) != 2:
        continue

    this_key, this_user = data_mapped

    if old_key is not None and old_key != this_key:
        print("{0}\t{1}".format(old_key, "\t".join(users)))
        users = list()

    old_key = this_key
    users.append(this_user)

if old_key is not None:
    print("{0}\t{1}".format(old_key, "\t".join(users)))


import sys
sys.setrecursionlimit(10**4)

def calcinterest(a,b,c):
    bee = b
    global count
    interest = b * a
    interest = round(interest*100) / 100
    bee += interest
    bee = round(bee*100) / 100
    bee -= c
    # print(addon)
    # print(temp)
    # print(count)
    if count >= 1200:
        return
    elif bee > 0.0001:
        count += 1
        calcinterest(a,bee,c)
    else:
        count += 1

nums = int(input())
for x in range(nums):
    count = 0
    a,b,c = [float(y) for y in input().split()]
    a /= 100
    calcinterest(a,b,c)
    if count >= 1200:
        print("impossible")
    else:
        print(count)


from tir import Webapp
import unittest

class OGAA580(unittest.TestCase):

    @classmethod
    def setUpClass(inst):

        from datetime import datetime
        DateSystem = datetime.today().strftime('%d/%m/%Y')

        inst.oHelper = Webapp()
        inst.oHelper.Setup('SIGAADV',DateSystem,'T1','D MG 01 ','67')

    def test_OGAA580_CT001(self):
        self.oHelper.SetLateralMenu("Atualizações > Comercialização > Cadastros Básicos > Tabela de Índice")
        self.oHelper.SetButton("Incluir")
        self.oHelper.SetValue("N9H_INDICE", "INDICE000123212",name_attr=True)
        self.oHelper.SetValue("N9H_PROD", "AGR-SOJA GRANEL",name_attr=True)
        self.oHelper.SetValue("N9H_CODSAF", "1920",name_attr=True)
        self.oHelper.SetValue("N9H_UFORIG", "AC",name_attr=True)
        self.oHelper.SetValue("N9H_UFDEST", "AL",name_attr=True)
        self.oHelper.SetValue("N9H_DTINVG", "31/10/2019",name_attr=True)
        self.oHelper.SetValue("N9H_DTFNVG", "31/10/2021",name_attr=True)
        self.oHelper.SetButton("Confirmar")
        self.oHelper.SetButton("Sim")
        self.oHelper.SetButton("Fechar")
        self.oHelper.SearchBrowse("INDICE000123212"+"AGR-SOJA GRANEL")
        self.oHelper.SetButton("Visualizar")
        self.oHelper.CheckResult("N9H_INDICE", user_value = "INDICE000123212")
        self.oHelper.SetButton("Fechar")
        self.oHelper.AssertTrue()

    @classmethod
    def tearDownClass(inst):
            inst.oHelper.TearDown()

if __name__ == '__main__':
    unittest.main()


# import packages / libraries
import numpy
import torch

# import functions
from metrics import FOSC

class TemplatesHandler():
    """ handles target updating and retrieving for the LOTS attack """
    def __init__(self, template_size, num_classes, device):
        self.templates = {i: [] for i in range(num_classes)}
        self.template_size = template_size
        self.device = device

    def add_to_templates(self, labels, representations):
        """ adds a representation as a target """
        for label, representation in zip(labels, representations):
            label = label.item()
            self.templates[label].append(representation)
            if len(self.templates[label]) > self.template_size:
                self.templates[label] = self.templates[label][1:]

    def get_targets(self, labels, target_classes, target_shape):
        """ returns a target representation """
        targets = []
        for label, target_class in zip(labels, target_classes):
            label, target_class = label.item(), target_class.item()
            if len(self.templates[target_class]) == 0:
                target = torch.rand(target_shape)
            else:
                images_sum = sum(self.templates[target_class])
                target = images_sum / len(self.templates[target_class])
            targets.append(target.to(self.device))
        return torch.stack(targets).detach().to(self.device)

def get_lots_templates(model, images, labels, num_classes=10):
    """ forms templates for evaluation """
    with torch.no_grad():
        logits = model(images)
    correct_predictions_mask = torch.max(logits, dim=1)[1] == labels
    class_logits = {i: [] for i in range(num_classes)}
    for i in range(len(labels)):
        if correct_predictions_mask[i].item():
            class_logits[labels[i].item()].append(logits[i])

    return {i: sum(t) / len(t) for i, t in class_logits.items()}

def get_lots_targets(templates, target_classes):
    """ returns targets from templates and given target classes """
    return torch.stack([templates[i.item()] for i in target_classes])

def get_random_target_classes(num_classes, labels):
    """ returns a tensor of random target classes """
    label_list, target_classes = set(range(num_classes)), []
    for label in labels:
        available_targets = list(label_list - {label.item()})
        target_classes.append(numpy.random.choice(available_targets))

    return torch.tensor(target_classes, device=labels.device)

def perturb(images, adversarials, logits, targets, gradient_treatment,
            step_size, p, eps, control_vector, iterations):
    """ perturbs a batch of images to decrease loss w.r.t. targets """
    p = float(p)
    device = images.device
    if gradient_treatment == 'max_scaling':
        adversarial_loss = torch.nn.MSELoss()(logits, targets)
    elif gradient_treatment == 'sign':
        adversarial_loss = torch.nn.CrossEntropyLoss()(logits, targets)
    else:
        raise NotImplementedError('only max scaling and sign.')
    adversarial_loss.backward()
    gradients = adversarials.grad.detach()
    if p == float('inf'):
        perturbations = torch.zeros(adversarials.shape).to(device)
        for i, indicator in enumerate(control_vector):
            if indicator.item():
                if gradient_treatment == 'max_scaling':
                    perturbations[i] = gradients[i] / gradients[i].abs().max()
                elif gradient_treatment == 'sign':
                    perturbations[i] = gradients[i].sign()
                else:
                    raise NotImplementedError('only max scaling and sign.')
        adversarials = adversarials - step_size * perturbations
        if eps != 'none' and step_size * iterations > eps:
            eps = float(eps)
            adversarials = adversarials.min(images + eps).max(images - eps)
        adversarials = torch.clamp(adversarials, 0, 1)
    else:
        raise NotImplementedError('currently only supporting max norm')

    return adversarials.detach()

def attack(model, images, labels, config, round_values, templates_handler=None,
           target_classes=None, epoch=None, data_name=None, lots_targets=None):
    """ creates adversarial examples using the specified attack """
    attack_type = config.pop('attack_type')
    num_classes = model.num_classes
    if target_classes is None:
        target_classes = get_random_target_classes(num_classes, labels)
    adversarials = images.clone().detach()

    # handle attack type
    logits = model(adversarials)
    if attack_type == 'pgd':
        targets = target_classes
        gradient_treatment = 'sign'
    elif attack_type == 'lots':
        if templates_handler is not None:
            targets = templates_handler.get_targets(
                labels, target_classes, logits[0].shape
            )
            templates_handler.add_to_templates(
                labels=labels, representations=logits.clone().detach()
            )
        else:
            targets = lots_targets
        gradient_treatment = 'max_scaling'
    else:
        raise NotImplementedError('Only LOTS and PGD attacks are implemented.')

    # handle stopping criterion via control vector
    additional_stopping_criterion = 'none'
    control_vector = torch.ones(images.shape[0]).bool()
    if 'additional_stopping_criterion' in config:
        additional_stopping_criterion = config['additional_stopping_criterion']
        if additional_stopping_criterion == 'success':
            with torch.no_grad():
                predicted_labels = torch.max(model(adversarials), dim=1)[1]
            control_vector = predicted_labels != target_classes

    # perturb until stopping criterion is met
    iterations, nb_iter = 0, float(config['nb_iter'])
    while control_vector.any() and iterations < nb_iter:
        adversarials.requires_grad = True
        logits = model(adversarials)
        adversarials = perturb(
            images=images, adversarials=adversarials,
            logits=logits, targets=targets,
            gradient_treatment=gradient_treatment, p=config['p'],
            eps=config['eps'], step_size=config['step_size'],
            control_vector=control_vector, iterations=iterations
        )
        if additional_stopping_criterion == 'success':
            rounded_adversarials = adversarials.mul(255.0).round().div(255.0)
            with torch.no_grad():
                predicted_labels = torch.max(
                    model(rounded_adversarials), dim=1
                )[1]
            control_vector = predicted_labels != target_classes
        elif additional_stopping_criterion == 'fosc_threshold':
            fosc_values = FOSC(
                model=model, originals=images, adversarials=adversarials,
                targets=target_classes, eps=config['eps']
            )
            path = 'results/{}/fosc_values/{}'.format(data_name, attack_type)
            torch.save(fosc_values, '{}/{}.pt'.format(path, epoch))
            control_vector = fosc_values >= config['fosc']
        iterations += 1
    if round_values:
        adversarials = adversarials.mul(255.0).round().div(255.0)

    return adversarials.detach(), target_classes

def create_adversarials(model, data, config, name, path, save,
                        target_classes, lots_targets):
    """ creates and saves adversarials given a model, dataset and attack """
    num_classes, device = model.num_classes, data.tensors[0].device
    images = data.tensors[0].to(device)
    labels = data.tensors[1].to(device)
    adversarial_images, _ = attack(
        model=model, images=images, labels=labels, config=dict(config),
        round_values=True, target_classes=target_classes,
        lots_targets=lots_targets
    )
    adversarials = {
        'images': adversarial_images,
        'labels': labels,
        'targets': target_classes
    }
    if save:
        for tensor_name in adversarials.keys():
            filename = '{}_adversarial_{}.pt'.format(name, tensor_name)
            file_path = '{}{}'.format(path, filename)
            torch.save(adversarials[tensor_name], file_path)

    return adversarials


import os
import sqlite3
import unittest
from fastapi.testclient import TestClient

from main import  app, create_table, increment_count, DB_FILE

class FastAPITest(unittest.TestCase):
    def setUp(self):
        self.client = TestClient(app)
        self.db_file = DB_FILE
        create_table()

    def tearDown(self):
        conn = sqlite3.connect(self.db_file)
        conn.execute("DROP TABLE IF EXISTS access_count")
        conn.commit()
        conn.close()

    def test_example_endpoint(self):
        response = self.client.get("/example")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"message": "¡Hola! Has accedido al endpoint /example."})

        conn = sqlite3.connect(self.db_file)
        c = conn.cursor()
        c.execute("SELECT count FROM access_count WHERE endpoint = 'example'")
        result = c.fetchone()
        conn.close()

        self.assertEqual(result[0], 1)

    def test_count_endpoint(self):
        increment_count("test_endpoint")

        response = self.client.get("/count/test_endpoint")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"endpoint": "test_endpoint", "count": 1})

    def test_count_endpoint_not_found(self):
        response = self.client.get("/count/nonexistent_endpoint")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"endpoint": "nonexistent_endpoint", "count": 0})

if __name__ == '__main__':
    unittest.main()


import requests
from datetime import date, timedelta
import os
from twilio.rest import Client

STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_ENDPOINT_API = "https://www.alphavantage.co/support/#api-key"
NEWS_ENDPOINT_API = "https://newsapi.org/"

parameters = {
    "function": "TIME_SERIES_DAILY",
    "symbol": STOCK_NAME,
    "apikey": STOCK_ENDPOINT_API
}

response_stock = requests.get("https://www.alphavantage.co/query", parameters)
stock_data = response_stock.json()

# Dates
now = date.today()
yesterday = str(now - timedelta(days=1))
before_yesterday = str(now - timedelta(days=2))

yesterday_closes = float(stock_data["Time Series (Daily)"][yesterday]["4. close"])
print(yesterday_closes)
before_yesterday_closes = float(stock_data["Time Series (Daily)"][before_yesterday]["4. close"])
print(before_yesterday_closes)

difference_closing = abs(yesterday_closes - before_yesterday_closes)
percentage_stock = float(before_yesterday_closes * .015)

url = ('http://newsapi.org/v2/everything?'
       f'q={COMPANY_NAME}&'
       f'from={now}&'
       'sortBy=popularity&'
       f'apiKey={NEWS_ENDPOINT_API}'
       )

response = requests.get(url)
news_data = response.json()
news_list = news_data["articles"][:3]

account_sid = 'https://www.twilio.com/'
auth_token = 'https://www.twilio.com/'
client = Client(account_sid, auth_token)
print(f"{news_list[1]['title']}\n{news_list[1]['description']}")

if percentage_stock < difference_closing:
    message = client.messages \
        .create(
            body=f"{news_list[1]['title']}\n{news_list[1]['description']}",
            from_='Your Twilio number',
            to='Number to send'
            )
    print(message.sid)


class Solution:
    def selfDividingNumbers(self, left: int, right: int) -> List[int]:

        def self_dividing(x: int) -> bool:
            for i in str(x):
                if i == '0':
                    return False
                if x % int(i) != 0:
                    return False
            return True

        ans = []

        for i in range(left, right + 1):
            if self_dividing(i):
                ans.append(i)
        return ans


#!/usr/bin/env python3

import sys

from ete3 import NCBITaxa

ncbi = NCBITaxa()

def get_desired_ranks(taxid):
    desired_ranks = ['phylum', 'genus', 'species']
    try:
        lineage = ncbi.get_lineage(taxid)
    except ValueError:
        lineage = []
    lineage2ranks = ncbi.get_rank(lineage)
    ranks2lineage = dict(
        (rank, taxid) for (taxid, rank) in lineage2ranks.items()
    )
    return {
        '{}_id'.format(rank): ranks2lineage.get(rank, '<not present>') for
        rank in desired_ranks
    }

def main(taxid):
    rank_ids = get_desired_ranks(taxid)
    names = []
    for i in rank_ids.values():
        if isinstance(i, int):
            names.append(ncbi.translate_to_names([i])[0])
        else:
            names.append(i)
    return names

if __name__ == '__main__':
    names = main(sys.argv[1])
    print(','.join(names))


import uuid
from personal_okrs import db
from personal_okrs.data_model.objective import Objective
from personal_okrs.data_model.goal import Goal

    # id = db.Column(db.String(255), primary_key=True)
    # title = db.Column(db.String(512))
    # description = db.Column(db.Text())
    # type = db.Column(db.Enum(GoalType))
    # direction_of_progress = db.Column(db.Enum(ProgressDirection))
    # due_date = db.Column(db.DateTime())
    # current_value = db.Column(db.Numeric())
    # start_value = db.Column(db.Numeric())

class ObjectiveRepo(object):
    def __init__(self):
        pass

    def create(self, data):
        goal_id = uuid.uuid4()
        objective_id = uuid.uuid4()

        goal = Goal(
            id=goal_id,
            title=data['title'],
            description = data['description'],
            type = data['type'],
            direction_of_progress = data['direction_of_progress'],
            due_date = data['due_date'],
            current_value = data['current_value'],
            start_value = data['start_value']
        )

        objective = Objective(
            id=objective_id,
            goal=goal
        )

        db.session.add(objective)
        db.session.commit()

        return objective.dict()

    def list(self):
        return self.objectives


import torch
import matplotlib.pyplot as plt
from pathlib import Path

import sys
sys.path.append("../")
import diffoptics as do

# initialization
# device = do.init()
device = torch.device('cpu')

# load target lens
lens = do.Lensgroup(device=device)
lens.load_file(Path('./lenses/Thorlabs/ACL5040U.txt'))
print(lens.surfaces[0])

# generate array of rays
wavelength = torch.Tensor([532.8]).to(device) # [nm]
R = 15.0 # [mm]
def render():
    ray_init = lens.sample_ray(wavelength, M=31, R=R)
    ps = lens.trace_to_sensor(ray_init)
    return ps[...,:2]

def trace_all():
    ray_init = lens.sample_ray_2D(R, wavelength, M=15)
    ps, oss = lens.trace_to_sensor_r(ray_init)
    return ps[...,:2], oss
ps, oss = trace_all()
ax, fig = lens.plot_raytraces(oss)

ax, fig = lens.plot_setup2D_with_trace([0.0], wavelength, M=5, R=R)
ax.axis('off')
ax.set_title("")
fig.savefig("layout_trace_asphere.pdf", bbox_inches='tight')

# show initial RMS
ps_org = render()
L_org = torch.mean(torch.sum(torch.square(ps_org), axis=-1))
print('original loss: {:.3e}'.format(L_org))
lens.spot_diagram(ps_org, xlims=[-50.0e-3, 50.0e-3], ylims=[-50.0e-3, 50.0e-3])

diff_names = [
    'surfaces[0].c',
    'surfaces[0].k',
    'surfaces[0].ai'
]

# optimize
out = do.LM(lens, diff_names, 1e-4, option='diag') \
        .optimize(render, lambda y: 0.0 - y, maxit=300, record=True)

# show loss
plt.figure()
plt.semilogy(out['ls'], '-o')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.show()

# show spot diagram
ps = render()
L = torch.mean(torch.sum(torch.square(ps), axis=-1))
print('final loss: {:.3e}'.format(L))
lens.spot_diagram(ps, xlims=[-50.0e-3, 50.0e-3], ylims=[-50.0e-3, 50.0e-3])
print(lens.surfaces[0])
# lens.plot_setup2D()


from typing import (
    List,
    Tuple,
    Dict,
    Optional,
    Callable,
)

import os
import sys

import unittest

from allennlp.data import Vocabulary
from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder
from allennlp.modules import TextFieldEmbedder, TokenEmbedder
from allennlp.data.token_indexers.elmo_indexer import ELMoTokenCharactersIndexer
from allennlp.modules.token_embedders import ElmoTokenEmbedder
from allennlp.data.token_indexers import TokenIndexer

from dpd.dataset import BIODataset, BIODatasetReader
from dpd.models.embedder import NERElmoTokenEmbedder, CachedTextFieldEmbedder
from dpd.models import LinearType
from dpd.weak_supervision.contextual_functions import CWRLinear, CWRkNN
from dpd.constants import GLOVE_DIR

SHOULD_RUN = os.path.exists(GLOVE_DIR)

class CWRFuncTest(unittest.TestCase):
    @classmethod
    def get_embedder_info(cls) -> Tuple[TokenEmbedder, TokenIndexer]:
        return NERElmoTokenEmbedder(), ELMoTokenCharactersIndexer()

    @classmethod
    def create_entry(cls, sentence: List[str], labels: List[str], entry_id: int, weight: float) -> Dict[str, object]:
        assert len(sentence) == len(labels)
        return {
            'id': entry_id,
            'input': sentence,
            'output': labels,
            'weight': weight,
        }

    @classmethod
    def create_fake_data(cls, binary_class: Optional[str] = None) -> BIODataset:
        data = [
            cls.create_entry(['single'], ['B-Tag'], 0, 1.0),
            cls.create_entry(['single', 'double'], ['B-Tag', 'I-Tag'], 1, 1.0),
            cls.create_entry(['single', 'double', 'triple'], ['B-Tag', 'I-Tag', 'O'], 2, 1.0),
            cls.create_entry(['no_label'], ['O'], 3, 1.0),
        ]

        dataset = BIODataset(0, 'fake_file.txt', binary_class)

        # hack around reading a file
        dataset.data = data

        return dataset

    @classmethod
    def setup_embedder(cls, cache: bool = True) -> CachedTextFieldEmbedder:
        token_embedder, token_indexer = CWRFuncTest.get_embedder_info()
        train_bio = CWRFuncTest.create_fake_data('Tag')
        train_reader = BIODatasetReader(
            bio_dataset=train_bio,
            token_indexers={
                'tokens': token_indexer,
            },
        )

        train_data = train_reader.read('temp.txt')
        vocab = Vocabulary.from_instances(train_data)
        text_field_embedder = BasicTextFieldEmbedder({"tokens": token_embedder})
        cached_embedder = CachedTextFieldEmbedder(
            text_field_embedder=text_field_embedder,
        )

        cached_embedder.cache(
            dataset_id=train_bio.dataset_id,
            dataset=train_data,
            vocab=vocab,
        )

        return cached_embedder

    @classmethod
    def _exec_test(cls, test: callable):
        if SHOULD_RUN:
            test()

    def test_cwr_linear(self):
        def _test():
            dataset = CWRFuncTest.create_fake_data('Tag')
            embedder = CWRFuncTest.setup_embedder()
            cwr_linear = CWRLinear(
                positive_label='Tag',
                embedder=embedder,
                linear_type=LinearType.SVM_LINEAR,
            )
            cwr_linear.train(dataset, dataset_id=dataset.dataset_id)
            annotations = cwr_linear.evaluate(dataset)
        CWRFuncTest._exec_test(_test)

    def test_cwr_knn(self):
        def _test():
            dataset = CWRFuncTest.create_fake_data('Tag')
            embedder = CWRFuncTest.setup_embedder()
            cwr_linear = CWRkNN(
                positive_label='Tag',
                embedder=embedder,
                k=5,
                resolve_mode='weighted',
                threshold=0.7,
            )
            cwr_linear.train(dataset, dataset_id=dataset.dataset_id)
            annotations = cwr_linear.evaluate(dataset)
        CWRFuncTest._exec_test(_test)


class Person:
    name = "John"
    country = "Norway"

setattr(Person, 'age', 40)

# The age property will now have the value: 40

x = getattr(Person, 'age')
print(x)

p = Person()
print(p.age)