import os
import random
from optparse import OptionParser

from task4test_glc4 import Task
from utils import logging_utils
from model_param_space import param_space_dict
import datetime
import config
import tensorflow as tf

def parse_args(parser):
    parser.add_option('-m', '--model', dest='model_name', type='string')
    parser.add_option('-d', '--data', dest='data_name', type='string')
    parser.add_option('-p', '--portion', dest='portion', type=int, default=100)
    parser.add_option('-a', '--alpha', dest='alpha', type=float, default=0.)

    # ablation
    parser.add_option('-i', '--reinit', dest='re_init', action='store_true', default=False)
    parser.add_option('-g', '--gt_portion', dest='gt_portion', type='float', default=1.0)

    # sub exp
    parser.add_option('--exp4', dest='exp4', action='store_true', default=False)
    parser.add_option('--pseudo_label', dest='pseudo_label', type='float', default=1.0)

    parser.add_option('-o', '--savename', dest='save_name', type='string', default='')
    parser.add_option('-r', '--runs', dest='runs', type='int', default=5)
    parser.add_option('-s', '--single_run', dest='single', action='store_true', default=False)
    options, args = parser.parse_args()
    return options, args

def try_h_params():
    #以下是
    beta = [0.5]
    alpha = [0.2, 0]
    e_1 = [20]
    e_2 = [60]
    re_init = [False]
    aux_clusters = range(50)
    names = ['beta', 'alpha', 'e_1', 'e_2', 're_init', 'aux_clusters']
    res = []
    for ob in beta:
        for oa in alpha:
            for oe1 in e_1:
                for oe2 in e_2:
                    for orei in re_init:
                        for aux in aux_clusters:
                            c = [ob, oa, oe1, oe2, orei, aux]
                            res.append([(names[i], c[i]) for i in range(len(names))])
    # random.shuffle(res)
    return res

def update_h_params(h_params, options, one_try, logger):
    for one_param, value in one_try:
        if one_param in h_params:
            h_params[one_param] = value
            print(f'set {one_param} to {value}.')
            logger.info(f'set {one_param} to {value}.')
        if hasattr(options, one_param):
            setattr(options, one_param, value)
            print(f'set {one_param} to {value}.')
            logger.info(f'set {one_param} to {value}.')

def main(options):
    time_str = datetime.datetime.now().isoformat()
    if len(options.save_name) == 0:
        log_name = 'Eval_[Model@%s]_[Data@%s]_%s.log' % (options.model_name,
                                                         options.data_name, time_str)
    else:
        log_name = 'Eval_[Model@%s]_[Data@%s]_%s.log' % (options.save_name,
                                                         options.data_name, time_str)
    if os.name == 'nt':
        log_name = log_name.replace(':', '：')
    logger = logging_utils.get_logger(config.LOG_DIR, log_name)
    params_dict = param_space_dict[options.model_name]

    if options.single:
        print('Single run...')
        logger.info('Single run...')
        params_dict['alpha'] = options.alpha
        params_dict['gt_portion'] = options.gt_portion
        logger.info(f'hyper params: {params_dict}\noptions: {options}')
        print(f'hyper params: {params_dict}\noptions: {options}')
        params_dict['num_epochs'] = max(params_dict['e_1'] + params_dict['e_2'] + params_dict['e_3'],
                                        params_dict['num_epochs'])
        params_dict['pseudo_label'] = options.pseudo_label
        params_dict['exp4'] = options.exp4
        print(options.data_name)
        task = Task(model_name=options.model_name, data_name=options.data_name, cv_runs=options.runs,
                    params_dict=params_dict, logger=logger, portion=options.portion,
                    save_name=options.save_name, re_init=options.re_init)

        print('-' * 50 + 'refit' + '-' * 50)
        task.refit()
    else:
        for one_try in try_h_params():
            update_h_params(params_dict, options, one_try, logger)
            logger.info(f'hyper params: {params_dict}\noptions: {options}')
            print(f'hyper params: {params_dict}\noptions: {options}')
            params_dict['num_epochs'] = max(params_dict['e_1'] + params_dict['e_2'] + params_dict['e_3'],
                                            params_dict['num_epochs'])
            params_dict['pseudo_label'] = options.pseudo_label
            params_dict['exp4'] = options.exp4
            print(options.data_name)
            task = Task(model_name=options.model_name, data_name=options.data_name, cv_runs=options.runs,
                        params_dict=params_dict, logger=logger, portion=options.portion,
                        save_name=options.save_name, re_init=options.re_init)

            print('-' * 50 + 'refit' + '-' * 50)
            task.refit()
            del task
            tf.reset_default_graph()

if __name__ == '__main__':
    t_parser = OptionParser()
    opt, _ = parse_args(t_parser)
    main(opt)


import pygame
from settings import TILESIZE
from support import import_csv_layout
from player import Player
from tile import Tile
from ui import UI

class Level:
    def __init__(self):

        # get the display surface
        self.display_surf = pygame.display.get_surface()

        # sprite group setup
        self.visible_sprites = YSortCameraGroup()
        self.obstacle_sprites = pygame.sprite.Group()
        self.objects_sprites = pygame.sprite.Group()

        # create map
        self.create_map()

        self.ui = UI()

    def create_map(self):
        layouts = {
            'boundary': import_csv_layout('../map/map_FloorBlocks.csv'),
            'floor': import_csv_layout('../map/map_Floor.csv'),
            'objects': import_csv_layout('../map/map_Objects.csv')
        }

        objects = {
            'acquaintance': pygame.image.load('../graphics/objects/acquaintance/acquaintance_1.png').convert_alpha(),
            'mushroom': pygame.image.load('../graphics/objects/mushroom.png').convert_alpha(),
            'potion': pygame.image.load('../graphics/objects/potion.png').convert_alpha(),
        }

        for layout_key, layout_value in layouts.items():
            for row_index, row in enumerate(layout_value):
                for col_index, col in enumerate(row):
                    x = col_index * TILESIZE
                    y = row_index * TILESIZE
                    if layout_key == 'boundary':
                        x = col_index * TILESIZE
                        y = row_index * TILESIZE
                        if col == '0':
                            Tile((x,y),[self.obstacle_sprites],surf=pygame.Surface((4,4)))

                    if layout_key == 'objects':
                        if col == '1':  # Acquaintance
                            Tile((x,y),
                                 [self.visible_sprites,self.obstacle_sprites],
                                 objects['acquaintance'])
                        elif col == '2':  # Mushroom
                            Tile((x, y),
                                 [self.visible_sprites],
                                 objects['mushroom'])
                        elif col == '3':  # Potion
                            Tile((x, y),
                                 [self.visible_sprites,self.obstacle_sprites],
                                 objects['potion'])
                            print('potion:',x,y)
                        elif col == '4':  # Player
                            self.player = Player((x,y),
                                                 [self.visible_sprites],
                                                 self.obstacle_sprites)
                            print('player:',x,y)

    def run(self):
        self.visible_sprites.custom_draw(self.player)
        self.visible_sprites.update()
        self.ui.display(self.player)

class YSortCameraGroup(pygame.sprite.Group):
    def __init__(self):

        # general setup
        super().__init__()
        self.display_surface = pygame.display.get_surface()
        self.half_width = self.display_surface.get_width() // 2
        self.half_height = self.display_surface.get_height() // 2
        self.offset = pygame.math.Vector2()

        # creating the floor
        self.floor_surf = pygame.image.load('../graphics/tilemap/ground_2.png').convert()
        self.floor_rect = self.floor_surf.get_rect(topleft = (0,0))

    def custom_draw(self,player):

        # getting the offset
        self.offset.x = player.rect.centerx - self.half_width
        self.offset.y = player.rect.centery - self.half_height

        # drawing the floor
        floor_offset_pos = self.floor_rect.topleft - self.offset
        self.display_surface.blit(self.floor_surf,floor_offset_pos)

        # drawing the sprites
        # for sprite in self.sprites():
        for sprite in sorted(self.sprites(),key = lambda sprite: sprite.rect.centery):
            offset_rect = sprite.rect.topleft - self.offset
            self.display_surface.blit(sprite.image,offset_rect)


import numpy as np

def log_gradient_(x, y_true, y_pred):
	print(type(y_pred))
	print(type(y_true))

	if (isinstance(y_true, (list,np.ndarray)) and isinstance(y_pred, (list,np.ndarray))):
		error = y_pred - y_true
		nabela = [0] * len(x[0])
		print(len(x[0][:]))
		print(x[0])
		for i in range(len(x[0])):
			# print(x[:])
			s = x[i][:]
			nabela[i] = sum([a * b for a,b in zip(s,error)])
		return nabela
	error = y_pred - y_true
	# print(error)
	nabela = [0] * len(x)
	# print(nabela)
	for i in range(len(x)):
		x[i] *= error
	return x

	# 	nabela

	# return sum([(a - b) * c for a, b, c in zip()])

if __name__ == "__main__":
	X = np.array([[ -6, -7, -9],
		[ 13, -2, 14],
		[ -7, 14, -1],
		[ -8, -4, 6],
		[ -5, -9, 6],
		[ 1, -5, 11],
		[ 9, -11, 8]])
	Y = np.array([2, 14, -13, 5, 12, 4, -19])
	Z = np.array([3,0.5,-6])


import string

from ast import *

class Reader:
    def __init__(self, source, filename=None):
        self.filename = filename
        self.lineno = 1
        self.source = source + '\n'
        self.index = -1

    def current(self):
        try:
            return self.source[self.index]
        except IndexError:
            raise EOFError("unexpected EOF")

    def next(self):
        self.index += 1
        return self.current()

    def prev(self):
        self.index -= 1
        return self.current()

    def read(self):
        exprs = []
        while self.index + 1 < len(self.source):
            self.next()
            if self.current() in string.whitespace:
                if self.current() == '\n':
                    self.lineno += 1
                # Ignore
                continue
            elif self.current() == ';':
                # Comment until EOL
                while self.next() != '\n':
                    pass
                self.lineno += 1
                continue
            elif self.current() == '(':
                exprs.append(self.read_list())
            elif self.current() == ')':
                raise SyntaxError("unexpected right parenthesis")
            elif self.current() == '"':
                exprs.append(self.read_string())
            elif self.current() in string.digits:
                self.prev()
                exprs.append(self.read_number())
            elif self.current() == '-':
                if self.next() in string.digits:
                    self.prev()
                    self.prev()
                    exprs.append(self.read_number())
                else:
                    self.prev()
                    self.prev()
                    exprs.append(self.read_symbol())
            elif self.current() in "'`,":
                exprs.append(self.read_quote())
            elif self.current() == ':':
                exprs.append(self.read_keyword())
            elif self.current() == '\\':
                exprs.append(self.read_character())
            else:
                self.prev()
                exprs.append(self.read_symbol())
            exprs[-1].meta["file"] = self.filename
            exprs[-1].meta["line"] = self.lineno
        return exprs

    def read_list(self):
        list = []
        proper = True
        while self.next() != ')':
            if self.current() in string.whitespace:
                if self.current() == '\n':
                    self.lineno += 1
                # Ignore
                continue
            elif self.current() == ';':
                # Comment until EOL
                while self.next() != '\n':
                    pass
                self.lineno += 1
                continue
            elif self.current() == '(':
                # List in a list in a list in a list
                list.append(self.read_list())
            elif self.current() == '.':
                # Improper list
                proper = False
            elif self.current() == '"':
                list.append(self.read_string())
            elif self.current() in string.digits:
                self.prev()
                list.append(self.read_number())
            elif self.current() == '-':
                if self.next() in string.digits:
                    self.prev()
                    self.prev()
                    list.append(self.read_number())
                else:
                    self.prev()
                    self.prev()
                    list.append(self.read_symbol())
            elif self.current() in "'`,":
                list.append(self.read_quote())
            elif self.current() == ':':
                list.append(self.read_keyword())
            elif self.current() == '\\':
                list.append(self.read_character())
            else:
                self.prev()
                list.append(self.read_symbol())
            list[-1].meta["file"] = self.filename
            list[-1].meta["line"] = self.lineno
        if proper and len(list):
            return List(list + [[]])
        else:
            return List(list)
        return l

    def read_string(self):
        string = ""
        while self.next() != '"':
            # Escape codes
            if self.current() == '\\':
                escape = self.next()
                if escape == 'n':
                    string += '\n'
                elif escape == 'r':
                    string += '\r'
                elif escape == '"':
                    string += '"'
                # TODO: Add more escape codes
                else:
                    string += '\\' + escape
            else:
                string += self.current()
        return String(string)

    def read_number(self):
        number = ""
        while self.next() not in string.whitespace + ')':
            number += self.current()
        if '.' in number:
            try:
                number = float(number)
            except ValueError:
                raise
        else:
            try:
                number = int(number)
            except ValueError:
                raise
        self.prev()
        return Number(number)

    def read_quote(self):
        if self.current() == "'":
            expr = [Symbol("quote")]
        elif self.current() == '`':
            expr = [Symbol("syntax-quote")]
        elif self.current() == ',':
            if self.next() == '@':
                expr = [Symbol("unquote-splice")]
            else:
                self.prev()
                expr = [Symbol("unquote")]
        self.next()
        if self.current() == '(':
            expr.append(self.read_list())
        else:
            self.prev()
            expr.append(self.read_symbol())
        return List(expr + [[]])

    def read_keyword(self):
        keyword = ""
        while self.next() not in string.whitespace + ')':
            keyword += self.current()
        self.prev()
        return Keyword(keyword)

    def read_character(self):
        return Character(self.next())

    def read_symbol(self):
        symbol = ""
        while self.next() not in string.whitespace + ')':
            if self.current() == '|':
                while self.next() != '|':
                    symbol += self.current()
            else:
                symbol += self.current()
        self.prev()
        return Symbol(symbol)


import sys
import requests
import random
import argparse
from bs4 import BeautifulSoup
from collections import defaultdict
from hashlib import md5

def ydapi(q, fromLang='zh-CHS', toLang='EN'):
    """
    youdao translation api interface
    q: string type encoding utf-8
    language: ['zh-CHS', 'EN', 'ja', 'ko', 'fr', 'ru', 'pt', 'es']
    """
    appKey = '**************'
    secretKey = '********************'
    url = 'http://openapi.youdao.com/api'
    salt = random.randint(1, 65536)
    sign = appKey+q+str(salt)+secretKey
    m = md5(sign.encode('utf-8'))
    sign = m.hexdigest()
    params = {'q':q, 'from':fromLang, 'to':toLang,\
         'appKey': appKey, 'salt': str(salt), 'sign': sign}
    try:
        r = requests.get(url, params=params)
        r.raise_for_status()
        dic = r.json()
    except:
        return None
    return dic

def ydword(word):
    url = "http://dict.youdao.com/search"
    header = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \
                (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36"
    headers = {'user-agent': header}
    word = {'q':word}
    try:
        r = requests.get(url=url, params=word, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

def ydparser(html):
    translate_dict = defaultdict(list)
    soup = BeautifulSoup(html, 'html.parser')
    try:
        keyword = soup.find('span', class_='keyword').get_text()
        trans = soup.find('div', class_='trans-container')
        if ord(keyword[0]) > 127:
            direction = True
        else:
            direction = False
    except:
        return None
    if direction:
        for group in trans.find_all('p', class_='wordGroup'):
            pos = group.find('span').get_text().strip()
            if not '.' in pos:
                pos = '.'
            english = []
            for wd in group.find_all('a'):
                english.append(wd.get_text())
            translate_dict[pos] = english
    else:
        for group in trans.find_all('li'):
            text_str = group.get_text()
            if not '.' in text_str:
                pos = '.'
                chinese = text_str
            else:
                text_str = text_str.split('.')
                pos = text_str[0]
                chinese = text_str[-1]
            translate_dict[pos].append(chinese)
    return translate_dict

def ydprint(res_dict, out_file='stdout'):
    if type(res_dict) == type({}):
        if res_dict['errorCode'] == '0':
            print(res_dict['query'])
            print('-'*80)
            trans_str = ''.join(res_dict['translation'])
            print(trans_str)
            if out_file != 'stdout':
                with open(out_file, 'w') as fw:
                    fw.write(trans_str)
        else:
            print('API.errorCode:', ''.join(res_dict['errorCode']))
    else:
        for key in res_dict:
            value = res_dict[key]
            if key != '.':
                format_str = key + '\t' + ', '.join(value)
            else:
                format_str = ', '.join(value)
            print(format_str)

def main():
    parser = argparse.ArgumentParser(description="Youdao Translation CLI. Author: claylau")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-w", dest="word", type=str, \
                        help="the word to translate using yd-dict web interface.")
    group.add_argument("-t", dest="text", type=str, \
                        help="the text to translate using yd-fanyi api.")
    group.add_argument("-f", dest="file", type=str, \
                        help="the file path of text to translate using yd-fanyi api.")
    parser.add_argument("-o", dest="output", type=str, \
                        help="to save the translatin file when -f effects.")
    args = parser.parse_args()
    if args.word:
        word = args.word
        html = ydword(word)
        if html != "":
            result = ydparser(html)
            if result:
                ydprint(result)
            else:
                print("Word translate error.")
        else:
            print("Web request falied.")
    if args.text:
        text = args.text
        if ord(text[0]) <= 127:
            fromLang = 'EN'
            toLang = 'zh-CHS'
            dic = ydapi(text, fromLang, toLang)
        else:
            dic = ydapi(text)
        if args.output:
            out_file = args.output
        else:
            out_file = 'stdout'
        ydprint(dic, out_file)
    if args.file:
        file = args.file
        with open(file, 'r') as fr:
            txt = fr.read()
            if len(txt) >= 5000:
                txt = txt[:5000]
            if ord(txt[0]) <= 127:
                fromLang = 'EN'
                toLang = 'zh-CHS'
                dic = ydapi(txt, fromLang, toLang)
            else:
                dic = ydapi(txt)
        if args.output:
            out_file = args.output
        else:
            out_file = 'stdout'
        ydprint(dic, out_file)

if __name__ == '__main__':
    main()


import os
import shutil
import string
from datetime import datetime
import random

import discord.ext.commands
from PIL import Image
from docx2pdf import convert
from pdf2docx import parse

# Variable Definitions
queues = {}

# Function Definitions
# Current Datetime
def getCurrentDateTime():
    return f'{datetime.now().strftime("%m/%d/%Y")} at {(datetime.strptime(datetime.now().strftime("%H:%M:%S"), "%H:%M:%S")).strftime("%r")}'

# Current Time
def getTime(chosenDelimiter: str):
    output = f'%I{chosenDelimiter}%M{chosenDelimiter}%S'
    return f'{datetime.now().strftime(output)}'

# To lowercase
def to_lower(arg: str):
    return arg.lower()

# To uppercase
def to_upper(arg: str):
    return arg.upper()

# Checks if the queue is populated and removes the current item in queue
def check_queue(ctx: discord.ext.commands.Context, id):
    try:
        if queues[id] != []:
            voice = ctx.guild.voice_client
            source = queues[id].pop(0)
            voice.play(source)
    except:
        pass

# Determines the method of which to convert files based on inputted type and desired type
def file_conversion(input_file, desired_outfile_type):
    # Set desired_outfile_type to include '.'
    desired_outfile_type = f'.{desired_outfile_type}'

    # Supported file types
    pdf_file = ['.pdf']
    docx_file = ['.docx']
    jpeg_file = ['.jpeg', '.jpg']
    png_file = ['.png']

    # Need to get file extensions of the input files
    input_file_type = (os.path.splitext(str(input_file))[1])
    input_file_name = (os.path.splitext(str(input_file))[0])

    # Input conditional variable definitions
    input_is_pdf = input_file_type in pdf_file
    input_is_docx = input_file_type in docx_file
    input_is_jpeg = input_file_type in jpeg_file
    input_is_png = input_file_type in png_file

    # Output conditional variable definitions
    output_is_pdf = desired_outfile_type in pdf_file
    output_is_docx = desired_outfile_type in docx_file
    output_is_jpeg = desired_outfile_type in jpeg_file
    output_is_png = desired_outfile_type in png_file

    # .pdf to .docx (utilizes pdf2docx.parse)
    if input_is_pdf and output_is_docx:
        # infile is .pdf
        infile = input_file
        # outfile is .docx
        outfile = f'{input_file_name}{desired_outfile_type}'
        parse(infile, outfile)
        return outfile

    # .docx to .pdf (utilizes docx2pdf.convert)
    elif input_is_docx and output_is_pdf:
        # infile is .docx
        infile = input_file
        # outfile is .pdf
        outfile = f'{input_file_name}{desired_outfile_type}'
        convert(infile, outfile)
        return outfile

    # .jpeg to .pdf (utilizes PIL.Image)
    elif input_is_jpeg and output_is_pdf:
        # infile is .jpeg
        infile = Image.open(input_file)
        # outfile is .pdf
        outfile_path = f'{input_file_name}{desired_outfile_type}'
        outfile = infile.convert('RGB')
        outfile.save(outfile_path)
        return outfile_path

    elif input_is_png and output_is_pdf:
        # infile is .png
        infile = Image.open(input_file)
        # outfile is .pdf
        outfile_path = f'{input_file_name}{desired_outfile_type}'
        outfile = infile.convert('RGB')
        outfile.save(outfile_path)
        return outfile_path

    elif input_is_png and output_is_jpeg:
        # infile is .png
        infile = Image.open(input_file)
        # outfile is .jpeg
        outfile_path = f'{input_file_name}{desired_outfile_type}'
        outfile = infile.convert('RGB')
        outfile.save(outfile_path)
        return outfile_path

    else:
        not_supported = None
        return not_supported

def removeFilesFromDirectory(working_directory):
    for file in os.scandir(working_directory):
        os.remove(file.path)

def removeDirectory(working_directory):
    shutil.rmtree(working_directory)

def checkDirectoryExists(directory):
    path = directory
    directory_exists = os.path.exists(path)
    if directory_exists is False:
        os.mkdir(path)

def checkDirectoryExistsDelete(directory):
    path = directory
    directory_exists = os.path.exists(path)
    if directory_exists is True:
        shutil.rmtree(path)

def ensureTicketingJSON_Exists():
    filepath = 'WorkingFiles/Databases/TicketingJSON.json'
    file_exists = os.path.exists(filepath)
    if file_exists is False:
        shutil.copyfile('Templates/TicketingJSON.json', filepath)

def randomChar(amount: int):
    return ''.join(random.choice(string.ascii_letters) for x in range(amount))


from typing import Callable, List, Tuple, Optional
from logging import info, warning, error

import torch

from deep_opt import Property
from nn_repair.repair import RepairStatus
from nn_repair.backends.repair_network_delegate_base import RepairNetworkDelegateBase
from nn_repair.backends.constraints import ConstraintFunctionFactory, BarrierFunction
from nn_repair.training import TrainingLoop, TrainingLossValue

class BarrierFunctionRepairDelegate(RepairNetworkDelegateBase):
    """
    A RepairNetworkDelegate that tries to fix counterexamples of a network
    by trying to archive feasibility first and then optimising the task loss with barriers
    that hinder the optimiser from leaving the feasible region.

    The algorithm tries to archive feasibility by minimising counterexample violation alone.
    """

    def __init__(self, training_loop: TrainingLoop, loss: Optional[Callable[[], torch.Tensor]] = None,
                 barrier_function: BarrierFunction = BarrierFunction.RECIPROCAL, barrier_factor: float = 0.25,
                 satisfaction_eps: float = 1, keep_all_counterexamples: bool = True):
        """
        Creates a new RepairNetworkDelegate that uses the barrier function method for repair.

        :param training_loop: The training loop to use for training. The loss function of this training loop
         will be updated during execution of this repair backend first with a loss function that
         only minimises property violation for the counterexamples and
         then with the task loss function with additional barrier terms.
         If the parameter loss is not supplied / supplied as None, the loss function of the training loop is used
         as task loss function.
        :param loss: The loss function that measures the performance of a network on the original machine learning
         task. This loss function needs to support gradient computation with torch.
         If None (default value) is passed for this parameter, the repair backend uses the current loss function of the
         training_loop as task loss function.
        :param barrier_function: The barrier function to use.
        :param barrier_factor: A factor for all barrier terms. Smaller values lead to better task loss results, but
         too small values can lead to numerical instability.
        :param satisfaction_eps: The actual constant of an inequality constraint for a counterexamples is shifted by a
         certain amount to guarantee termination of the penalty function method. This parameter gives this constant.
         This value assures that in the feasibility step, enough space to the feasibility boundary is created.
         Otherwise the training algorithm might quickly leave the feasible region.
        :param keep_all_counterexamples: Whether only the most up to date counterexample for each property should be
         used during repair or if all previously obtained counterexamples should be used.
        """
        super().__init__(keep_all_counterexamples)

        self.training_loop = training_loop
        assert loss is not None or training_loop.loss_function is not None, "No task loss function available"
        if loss is not None:
            self.task_loss = loss
        else:
            self.task_loss = training_loop.loss_function
        self.barrier_function = barrier_function
        self.barrier_factor = barrier_factor
        self.sat_eps = satisfaction_eps

    def repair(self) -> RepairStatus:
        """
        Repair the network to no longer violate the specification for the previously registered counterexamples.
        :return: The final status of the repair. Return SUCCESS if all counterexamples no longer
        violate the specification. Return FAILURE if this could not be archived.
        Return ERROR if any other error occurred, from which recovery is possible, otherwise raise
        an exception.
        """
        constr_factory = ConstraintFunctionFactory()\
            .with_network(self.network)\
            .with_satisfaction_eps(self.sat_eps)  # the l1 penalty used for feasibility uses the satisfaction eps

        unfolded_counterexamples: List[Tuple[Property, torch.Tensor]] = self.unfolded_counterexamples

        info(f'Find feasible point by minimising violation.')
        # a vector function of violations
        violation_functions = constr_factory.create_vector_l1_penalty(self.counterexamples)

        def violation_loss():
            return torch.sum(violation_functions())

        orig_termination_criterion = self.training_loop.termination_criterion
        # we also want to make sure counterexamples are satisfied with sufficient slack (satisfaction eps)
        self.training_loop.termination_criterion = orig_termination_criterion | TrainingLossValue(0.0)

        self.training_loop.loss_function = violation_loss
        self.training_loop.execute()

        # restore original termination criterion
        self.training_loop.termination_criterion = orig_termination_criterion

        num_violations = self.count_violations(unfolded_counterexamples)
        if num_violations > 0:
            warning(f"Feasibility step failed: {num_violations} remaining.")
            return RepairStatus.FAILURE
        info("Feasibility step successful.")

        info(f'Using {self.barrier_function} barrier functions.')
        barrier_functions = constr_factory.create_vector_barrier_function(
            unfolded_counterexamples,
            self.barrier_function
        )

        def barrier_loss():
            return self.task_loss() + self.barrier_factor * torch.sum(barrier_functions())

        self.training_loop.loss_function = barrier_loss
        self.training_loop.execute()

        num_violations = self.count_violations(unfolded_counterexamples)
        if num_violations > 0:
            error("Counterexamples re-introduced after training with barrier objective")
            return RepairStatus.ERROR

        return RepairStatus.SUCCESS


import os
import xml.etree.ElementTree as ET
import movis.model as Model

# ---WORKSPACE DIR---
ROOT_DIR = 'D:/PY_PROJECT/TOOL/movis'
RES_DIR = 'D:/PY_PROJECT/TOOL/movis/resource'
PUBLIC_PATH = 'log/public.xml'
# ------------------------------------------------------------------

# ---INIT CACHE DATA---
res_id = {}
SMALI_FILE_MAPPER = {}
RESOUCE_DATA = []
CHECK_ID = []
CHECKED_FILE = []
# ------------------------------------------------------------------

# ---TYPE MAPPER---
ResANIM = 'anim'
ResATTR = 'animator'
ResARRAY = 'array'
ResBOOL = 'bool'
ResCOLOR = 'color'
ResDIMEN = 'dimen'
ResDRAWABLE = 'anim'
ResFONT = 'font'
ResID = 'id'
ResMIPMAP = 'mipmap'
ResPLURALS = 'plurals'
ResLAYOUT = 'layout'
ResRAW = 'raw'
ResSTRING = 'string'
ResSTYLE = 'style'
ResSTYLEABLE = 'styleable'
ResXML = 'xml'
ResVALUE = 'values'

# ------------------------------------------------------------------

def get_file_name_without_extension(file_path):
    file_name = os.path.basename(file_path)
    file_name_without_extension = os.path.splitext(file_name)[0]
    return file_name_without_extension

def get_parent_directory_name(file_path):
    parent_directory = os.path.dirname(file_path)
    parent_directory_name = os.path.basename(parent_directory)
    return parent_directory_name

def get_file_extension(file_path):
    _, file_extension = os.path.splitext(file_path)
    return file_extension

if __name__ == '__main__':
    for r, d, f in os.walk(ROOT_DIR):
        for file in f:
            if '.smali' in file:
                typekey = file.replace('R$', '').replace('.smali', '')
                SMALI_FILE_MAPPER[typekey] = file

    # print(SMALI_FILE_MAPPER)
    tree = ET.parse(PUBLIC_PATH)
    root = tree.getroot()
    for i in root.findall('public'):
        if res_id.get(i.attrib['type']) is None:
            res_id[i.attrib['type']] = {}
            res_id[i.attrib['type']][i.attrib['id']] = i.attrib['name']
        else:
            res_id[i.attrib['type']][i.attrib['id']] = i.attrib['name']

    for typekey in res_id:
        smalicode = open(SMALI_FILE_MAPPER[typekey]).readlines()
        for line in smalicode:
            if line.__contains__(':I'):
                orgname = line[:line.index(':')].replace('.field public static final ', '')
                hexid = line[(line.index('=') + 1):].strip()
                encrypname = res_id[typekey][hexid]
                CHECK_ID.append(hexid)
                RESOUCE_DATA.append(Model.ResourceData(org=orgname, encrypt=encrypname, hid=hexid, restype=typekey))

    # ---create mapper---
    # for data in RESOUCE_DATA:
    #     print(data.restype + ': ' + data.encrypt + ' -> ' + data.org)
    # ------------------------------------------------------------------

    # ---check unknow id---
    # for typekey in res_id:
    #     for hexid in res_id[typekey]:
    #         if not CHECK_ID.__contains__(hexid):
    #             print(hexid)
    # ------------------------------------------------------------------

    for r, d, f in os.walk(RES_DIR):
        for file in f:
            src_file_path = (os.path.join(r, file).replace('\\', '/'))
            # print('browsing: ' + src_file_path)
            if src_file_path.__contains__(ResVALUE):
                pass
            else:
                print()
                parentfile = get_parent_directory_name(src_file_path)
                filename = get_file_name_without_extension(src_file_path)
                for data in RESOUCE_DATA:
                    if parentfile.__contains__(data.restype) and filename.replace('.9', '') == data.encrypt:
                        dst_file_path = r.replace('\\', '/') + '/' + data.org + get_file_extension(src_file_path)
                        if filename.__contains__('.9'):
                            dst_file_nine_path = r.replace('\\', '/') + '/' + data.org + '.9' + get_file_extension(
                                src_file_path)
                            print(file + ' -> ' + dst_file_nine_path)
                            os.rename(src_file_path, dst_file_nine_path)
                        else:
                            print(file + ' -> ' + dst_file_path)
                            os.rename(src_file_path, dst_file_path)
                        CHECKED_FILE.append(file)
                        break

print('---Done---')


MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

profit = 0
resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

def enought_resources(enought):
    for item in enought:
        if enought >= resources:
            print(f"Sorry there is not enough water {item}.")
            return False
    return True

def coins():
    """Return the total calculator"""
    print("pleace insert a coin")
    total = int(input("How many Quarter?")) * 0.25
    total += int(input("How many dimes?")) * 0.10
    total += int(input("How many nickeles?")) * 0.05
    total += int(input("How many pennies?")) * 0.01
    return total

def transation_sucessfull(received, cost):
    """return true when the payment is accetable or false when money is insuficient"""
    if received >= cost:
        change = round(received - cost, 2)
        print(f"Here is {change} in change")
        global profit
        cost += profit
        return True
    else:
        print("Sorry that's not enough money. Money refunded")
        return False

def coffe(name, ingredient):
    for item in ingredient:
        resources[item] -= ingredient[item]

successfull = True

while successfull:
    user_choice = input("What would you like? (espresso/latte/cappuccino): ")
    if user_choice == "off":
        successfull = False
    elif user_choice == "report":
        print("the current resource values. e.g. ")
        print(f"watter: 1000ml{resources['water']}")
        print(f"milk: {resources['milk']}")
        print(f"Coffee: {resources['coffee']}")
        print(f"Money: {profit}")

    else:
        drink = MENU[user_choice]
        enought_resources(drink['ingredients'])
        payment = coins()
        transation_sucessfull(payment, drink['cost'])
        coffe(user_choice, drink['ingredients'])


# Manages questions.

import discord
import random
import bot_prefix
import re # Regex functions, used to find if a string matches a pattern and such
from action import action

@action("question", description = "Marks content as a question so that others can tag answers to it and view it in the future.")
async def question_input(message): # manages new questions

    text = message.content[9:].strip()
    await message.delete()
    id = random.randrange(start=0, stop=9999)
    text = "**" + bot_prefix.prefix + "q{:0>4}** " + text
    await message.channel.send(text.format(id))

async def get_past_questions(channel): # Returns questions from the past 500 messages in the provided channel. The questions are message objects.
    past = await channel.history(limit=500).flatten()
    question_messages = []
    for message in past:
        if re.search(bot_prefix.prefix + "q([0-9]{4})", message.content): #Finds a result if the tag matches a question with ID tag.
            question_messages.append(message)
    return question_messages

async def get_past_question(channel, question_id): # Returns question with specified id. Not to be confused with the plural questions function. Returns as message object or nothing.
    questions = await get_past_questions(channel)
    for q in questions:
        idx = q.content.find(str(question_id))
        if idx >= 2 and q.content[idx-2:idx] == bot_prefix.prefix + "q":
            return q

async def answer_input(message): # manages answers to questions
    # finds the #a0000 (prefix + a + four digit number) pattern and gets the specified message
    # if no message is found, reply back that that message is either out of range or non existent.
    # if the message is found, add the answer onto the question message and mark the message as pending verification

    return


import math
import numpy as np
import matplotlib.pyplot as pyplot
from graphviz import Digraph, Source

class Value:
    def __init__(self, data, _children=(), _op='', label=''):
        self.data = data
        self.grad = 0.0
        self._backward = lambda: None
        self._prev = set(_children)
        self._op = _op
        self.label = label

    def __repr__(self):
        return f"Value(node={self.label})"

    def __add__(self, other):
        out = Value(self.data + other.data, (self, other), '+')

        def _backward():
            self.grad += 1.0 * out.grad
            other.grad += 1.0 * out.grad

        out._backward = _backward
        return out

    def __mul__(self, other):
        out = Value(self.data * other.data, (self, other), '*')

        def _backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad

        out._backward = _backward
        return out

    def tanh(self):
        x = self.data
        t = (math.exp(2*x) - 1) / (math.exp(2*x) + 1)
        out = Value(t, (self, ), 'tanh')

        def _backward():
            self.grad += (1 - t**2) * out.grad

        out._backward = _backward
        return out

    def backward(self):
        topo = []
        visited = set()
        def build_topo(v):
            if v not in visited:
                visited.add(v)
                for child in v._prev:
                    build_topo(child)
                topo.append(v)
        build_topo(self)

        self.grad = 1.0
        for node in reversed(topo):
            node._backward()

def f(x):
    return 3*x**2 - 4*x + 5

def trace(root):
    nodes, edges = set(), set()
    def build(v):
        if v not in nodes:
            nodes.add(v)
            for child in v._prev:
                edges.add((child, v))
                build(child)
    build(root)
    return nodes, edges

def draw_dot(root):
    dot = Digraph(format='svg', graph_attr={'rankdir': 'LR'})

    nodes, edges = trace(root)
    for n in nodes:
        uid = str(id(n))
        dot.node(name = uid, label = "{ %s | data %.4f | grad %.4f }" % (n.label, n.data, n.grad), shape='record')
        if n._op:
            dot.node(name = uid + n._op, label = n._op)
            dot.edge(uid + n._op, uid)

    for n1, n2 in edges:
        dot.edge(str(id(n1)), str(id(n2)) + n2._op)

    return dot

def save_and_display_dot(dot, file_path):
    dot.format = 'svg'
    dot.render(file_path, view=True)

# example #1
a = Value(2.0, label='a')
b = Value(-3.0, label='b')
c = Value(10.0, label='c')
e = a*b; e.label = 'e'
d = e + c; d.label = 'd'
f = Value(-2.0, label='f')
L = d*f; L.label = 'L'
# dot = draw_dot(L)
# save_and_display_dot(dot, "output_graph")

# example #2 with tanh squash + backward propagation for gradients
x1 = Value(2.0, label="x1")
x2 = Value(0.0, label="x2")

w1 = Value(-3.0, label="w1")
w2 = Value(1.0, label="w2")

b = Value(6.8813735870195432, label="b")

x1w1 = x1*w1; x1w1.label = 'x1*w1'
x2w2 = x2*w2; x2w2.label = 'x2*w2'

x1w1x2w2 = x1w1 + x2w2; x1w1x2w2.label = 'x1*w1 + x2*w2'

n = x1w1x2w2 + b; n.label = 'n'
o = n.tanh(); o.label = 'o'

o.backward()

dot = draw_dot(o)
save_and_display_dot(dot, "output_graph")


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# --------------------------------------------------
# Description:
# --------------------------------------------------
# Author: Konfido <konfido.du@outlook.com>
# Created Date : April 4th 2020, 17:45:05
# Last Modified: April 4th 2020, 17:45:05
# --------------------------------------------------
import nltk
nltk.download('names')
nltk.download('brown')
nltk.download('punkt')

from nltk.classify.maxent import MaxentClassifier
from sklearn.metrics import (accuracy_score, fbeta_score, precision_score,
                             recall_score)
import os
import pickle
from nltk.tokenize import word_tokenize
from nltk.corpus import names, brown

NAMES = set(names.words())
BROWN = set(brown.words())

class MEMM():
    def __init__(self):
        self.train_path = "./starter_codes/data/train"
        self.dev_path = "./starter_codes/data/dev"
        self.beta = 0
        self.max_iter = 0
        self.classifier = None

    def features(self, words, previous_label, position):
        """
        Note: The previous label of current word is the only visible label.

        :param words: a list of the words in the entire corpus
        :param previous_label: the label for position-1 (or O if it's the start
                of a new sentence)
        :param position: the word you are adding features for
        """

        features = {}
        """ Baseline Features """
        current_word = words[position]
        features[f'has_{current_word}'] = 1
        features['prev_label'] = previous_label
        if current_word[0].isupper():
            features['Titlecase'] = 1

        # Baseline score
        # f_score = 0.8715
        # accuracy = 0.9641
        # recall = 0.7143
        # precision = 0.9642

        #===== TODO: Add your features here =======#
        # When whole word is capitalized
        if current_word.isupper():
            features['current_allcap'] = 1

		# When whole word is lower case
        # if current_word.islower():
        #     features['current_lower'] = 1

        # Using NLTK Names corpus
        if current_word in NAMES:
            features["name"] = 1

		# Use NLTK Brown corpus
        elif current_word not in BROWN:
            features['brown_oov'] = 1

        # Previous word
        # if position > 0:
        #     features[f"prev_word_{words[position-1]}"] = 1

        # If camelcase
        if [x.isupper for x in current_word].count(True) > 1:
            features["camel_case"] = 1

		# If initial
        if len(current_word) == 2:
            if current_word[0].isupper() and current_word[1] == '.':
                features["initial"] = 1

        # if contains hyphen
        # if '-' in current_word:
        #     features["hyphen"] = 1

        # if underscore
        # if '_' in current_word:
        #     features["underscore"] = 1

        # Previous two word
        # if position > 1:
        #     features[f"prev_two_word{words[position-2]}"] = 1

        # Next word
        # if position + 1 != len(words):
        #     features[f"next_word_{words[position+1]}"] = 1

        #=============== TODO: Done ================#
        return features

    def load_data(self, filename):
        words = []
        labels = []
        for line in open(filename, "r", encoding="utf-8"):
            doublet = line.strip().split("\t")
            if len(doublet) < 2:     # remove emtpy lines
                continue
            words.append(doublet[0])
            labels.append(doublet[1])
        return words, labels

    def train(self):
        print('Training classifier...')
        words, labels = self.load_data(self.train_path)
        previous_labels = ["O"] + labels
        features = [self.features(words, previous_labels[i], i)
                    for i in range(len(words))]
        train_samples = [(f, l) for (f, l) in zip(features, labels)]
        classifier = MaxentClassifier.train(
            train_samples, max_iter=self.max_iter)
        self.classifier = classifier

    def test(self):
        print('Testing classifier...')
        words, labels = self.load_data(self.dev_path)
        previous_labels = ["O"] + labels
        features = [self.features(words, previous_labels[i], i)
                    for i in range(len(words))]
        results = [self.classifier.classify(n) for n in features]

        f_score = fbeta_score(labels, results, average='macro', beta=self.beta)
        precision = precision_score(labels, results, average='macro')
        recall = recall_score(labels, results, average='macro')
        accuracy = accuracy_score(labels, results)

        print("%-15s %.4f\n%-15s %.4f\n%-15s %.4f\n%-15s %.4f\n" %
              ("f_score=", f_score, "accuracy=", accuracy, "recall=", recall,
               "precision=", precision))

        return True

    def predict_sentence(self, sentence):
        self.load_model()
        # Tokenize the sentence
        words = word_tokenize(sentence)
        # Insert some dummy label
        labels = ["O"] * len(words)
        # Add one more dummy label to extract features
        previous_labels = ["O"] + labels
        # Extract features for given sentence.
        features = [self.features(words, previous_labels[i], i)
                    for i in range(len(words))]
        # Get classification result (result labels)
        results = [self.classifier.classify(n) for n in features]
        # Return words and classification result
        return words, results

    def show_samples(self, bound):
        """Show some sample probability distributions.
        """
        words, labels = self.load_data(self.train_path)
        previous_labels = ["O"] + labels
        features = [self.features(words, previous_labels[i], i)
                    for i in range(len(words))]
        (m, n) = bound
        pdists = self.classifier.prob_classify_many(features[m:n])

        print('index    Words          P(PERSON)  P(O)\n' + '-' * 40)
        for i, (word, label, pdist) in enumerate(list(zip(words[m:n], labels[m:n], pdists))):
            if pdist.prob("PERSON") > pdist.prob("O"):
                if label != "PERSON":
                    pass
                    print(f"{i:07d} {word:15s} {pdist.prob('PERSON'):6.4f}    *{pdist.prob('O'):6.4f}")
            else:
                if label != "O":
                    pass
                    print(f"{i:07d} {word:15s} *{pdist.prob('PERSON'):6.4f}     {pdist.prob('O'):6.4f}")

            """
            if label == 'PERSON':
                fmt = '  %-15s *%6.4f   %6.4f'
            else:
                fmt = '  %-15s  %6.4f  *%6.4f'
            print(fmt % (word, pdist.prob('PERSON'), pdist.prob('O'))) """

    def dump_model(self):
        with open('./starter_codes/model.pkl', 'wb') as f:
            pickle.dump(self.classifier, f)

    def load_model(self):
        with open('starter_codes/model.pkl', 'rb') as f:
            self.classifier = pickle.load(f)


import time

from chocs import Application, HttpRequest, HttpResponse, serve
from chocs.middleware import MiddlewareHandler

def time_load_middleware(request: HttpRequest, next: MiddlewareHandler) -> HttpResponse:
    started_at = time.time()
    response = next(request)
    total_time = (time.time() - started_at) * 100

    response.write(f"\nTotal time taken for generating response: {total_time}")

    return response

app = Application(time_load_middleware)

@app.get("/hello/{name}")
def hello(request: HttpRequest) -> HttpResponse:
    return HttpResponse(body=f"Hello {request.attributes['name']}!")

serve(app)


class TextSenseProposer:
    def __init__(self, sense_inventory):
        self._sense_inventory = sense_inventory

    def _assign_multi_word_possibilities(
        self, token_tags, token_senses, compound_indices, length
    ):
        for i in range(len(token_tags) - length + 1):
            span = token_tags[i : i + length]
            span_tokens = [ token for token, _ in span ]
            senses_from_tokens = self._sense_inventory.get_senses_from_tokens(span_tokens)
            span_senses = set.intersection(*[ set(senses) for _, senses in token_senses[i:i + length] ])
            # If the compound sense was already added in a previous iteration, ignore.
            # Ex: If "The Amazing Spider-Man" has already been added, then ignore "Spider-Man"
            senses_from_tokens = list(set(senses_from_tokens).difference(span_senses))

            for _, senses in token_senses[i : i + length]:
                senses += senses_from_tokens

            for sense in senses_from_tokens:
                compound_indices.append((sense, (i, i + length)))

    def _assign_single_word_possibilities(self, token_tags, token_senses):
        for i, (token, tag) in enumerate(token_tags):
            if tag is None:
                continue
            _, senses = token_senses[i]
            senses += self._sense_inventory.get_senses_from_lemma(token, tag)

    def _get_proper_chunks(self, token_tags):
        proper_chunks = []
        current_start = None
        for i, (_, tag) in enumerate(token_tags):
            if tag != "proper":
                if current_start is not None:
                    proper_chunks.append((current_start, i))
                    current_start = None
            else:
                if current_start is None:
                    current_start = i
        if current_start is not None:
            proper_chunks.append((current_start, len(token_tags)))
        return proper_chunks

    def _unassign_proper_fragments(self, token_tags, token_senses):
        proper_chunks = self._get_proper_chunks(token_tags)
        for begin, end in proper_chunks:
            senses_list = [ set(senses) for _, senses in token_senses[begin:end] ]
            tokens_list = [ token for token, _ in token_senses[begin:end] ]
            filtered_senses = set.intersection(*senses_list)
            token_senses[begin:end] = zip(tokens_list, [list(filtered_senses)] * (end - begin))

    def propose_senses(self, token_tags):
        token_senses = [(token, []) for token, _ in token_tags]
        compound_indices = []

        for length in range(5, 1, -1):
            # Iterate backwards since short versions of a compound should not be added if the long version of the compound has already been added.
            self._assign_multi_word_possibilities(
                token_tags, token_senses, compound_indices, length
            )
        self._assign_single_word_possibilities(
            token_tags, token_senses
        )

        self._unassign_proper_fragments(token_tags, token_senses)

        # Tokens that are stop words should not have any senses.
        # Otherwise compound words that conatin stop words will always have the stop word assigned to that sense.
        # Ex: The sense for "come to" will always have "to" disambiguated to that sense, even if "come to" is not the right sense for "come".
        for i, (token, tag) in enumerate(token_tags):
            if tag == "STOP":
                token_senses[i] = (token, [])

        # Remove duplicates
        # Sort sense ids so that proposed senses are deterministic.
        token_senses = [(token, sorted(list(set(senses)))) for token, senses in token_senses]

        return token_senses, compound_indices


__all__ = [
    'tokenize_dsl_code',
    'tokenize_html_code',
]

def tokenize_dsl_code(code):
    tokens = code.split()
    final_tokens = []

    for token in tokens:
        if ',' in token:
            final_tokens.append(token.split(',')[0])
            final_tokens.append(',')
        else:
            final_tokens.append(token)

    return final_tokens

def tokenize_html_code(code):
    html_tags = []
    closing_bound = 0

    while True:
        closing_idx = code.find('>', closing_bound)
        if closing_idx == -1:
            break

        tag = code[closing_bound:closing_idx+1]
        tag = tag[tag.find('<'):tag.find('>')+1]

        html_tags.append(tag)
        closing_bound = closing_idx+1

    return html_tags


from multiprocessing import parent_process
import torch
import pandas
import cv2
import time
import numpy as np

value=[]
def detectx (frame, model):
    frame = [frame]
    print(f"[INFO] Detecting. . . ")
    results = model(frame)

    labels, cordinates = results.xyxyn[0][:, -1], results.xyxyn[0][:, :-1]

    return labels, cordinates

#plot the BBox and results
def plot_boxes(results, frame,classes):

    labels, cord = results
    n = len(labels)
    x_shape, y_shape = frame.shape[1], frame.shape[0]

    print(f"[INFO] Total {n} detections. . . ")
    print(f"[INFO] Looping through all detections. . . ")
    print(f"[INFO] Enter q for the result... ")

    ### looping through the detections
    pathole_aera_value=[]
    for i in range(n):
        row = cord[i]
        if row[4] >= 0.1: ### threshold value for detection. We are discarding everything below this value
            # print(f"[INFO] Extracting BBox coordinates. . . ")
            x1, y1, x2, y2 = int(row[0]*x_shape), int(row[1]*y_shape), int(row[2]*x_shape), int(row[3]*y_shape) ## BBOx coordniates
            # print(x1, y1, x2, y2)
            x_diff=x2-x1
            y_diff=y2-y1
            area_pathole=x_diff*y_diff
            pathole_aera_value.append(area_pathole)
            # print(x_diff,y_diff,area_pathole)

            text_d = classes[int(labels[i])]

            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) ## BBox
            cv2.rectangle(frame, (x1, y1-20), (x2, y1), (0, 255,0), -1) ## for text label background

            cv2.putText(frame, text_d + f" {round(float(row[4]),2)}", (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.7,(255,255,255), 2)

            total_pathole_area=sum(pathole_aera_value)
            # print(total_pathole_area)
    value.append(total_pathole_area)

    return frame

#Main function
def main(img_path=None, vid_path=None,vid_out = None):

    print(f"[INFO] Loading model... ")
    ## loading the custom trained model
    model =  torch.hub.load('./yolov5', 'custom', source ='local', path='./best.pt',force_reload=True)

    classes = model.names ### class names in string format
    print(classes)

    if img_path != None:
        print(f"[INFO] Working with image: {img_path}")
        frame = cv2.imread(img_path)
        frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

        results = detectx(frame, model = model) ### DETECTION HAPPENING HERE

        frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
        frame = plot_boxes(results, frame,classes = classes)

        cv2.namedWindow("img_only", cv2.WINDOW_NORMAL) ## creating a free windown to show the result
        #results.pandas().xyxy[0]

        while True:
            # frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)

            cv2.imshow("img_only", frame)

            # if cv2.waitKey(5) & 0xFF == 27:
            if cv2.waitKey(0) & 0xFF == ord('q'):
                print(f"[INFO] Exiting. . . ")
                cv2.imwrite("final_output.jpg",frame) ## if you want to save he output result.
                break

    elif vid_path !=None:
        print(f"[INFO] Working with video: {vid_path}")

        ## reading the video
        cap = cv2.VideoCapture(vid_path)

        if vid_out: ### creating the video writer if video output path is given

            # by default VideoCapture returns float instead of int
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            fps = int(cap.get(cv2.CAP_PROP_FPS))
            codec = cv2.VideoWriter_fourcc(*'mp4v') ##(*'XVID')
            out = cv2.VideoWriter(vid_out, codec, fps, (width, height))

        # assert cap.isOpened()
        frame_no = 1

        cv2.namedWindow("vid_out", cv2.WINDOW_NORMAL)

main(img_path="./yolov5/image-rode2.jpg") ## for image

# point=np.array([[129,92],[420,79],[623,159],[631,352],[4,356],[9,168]])
point=np.array([[8,7],[7,322],[262,322],[576,327],[585,17],[280,8]])
road_area=cv2.contourArea(point)
# #return road_area
print("road_area", road_area)
print("value_area", value)
# print(total_pathole_area)

# global total_pathole_area
precentage_faulty_road=(int(value[0])/road_area)
print("precentage_faulty_road%", round(precentage_faulty_road*100))
print(f"[INFO] Clening up. . . ")


import torch
import torch.nn as nn
from models.u_net import UNet
from tqdm import tqdm
from config import ModelConfig
from utils import (
    compute_print_val_metrics,
    save_samples_predicted,
    save_checkpoint,
    get_loaders,
    get_train_transform,
    get_valid_transform,
)
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

def train_fn(
    loader: DataLoader,
    model: torch.nn.Module,
    optimizer: torch.optim.Optimizer,
    loss_fn: torch.nn.Module,
    device: str,
) -> float:
    loop = tqdm(loader)
    total_loss = 0

    for batch_idx, (data, targets) in enumerate(loop):
        data = data.to(device)
        targets = targets.float().unsqueeze(1).to(device)

        predictions = model(data)
        loss = loss_fn(predictions, targets)
        total_loss += loss.item()

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        loop.set_postfix(loss=loss.item())

    return total_loss / len(loader)

def main():
    cfg = ModelConfig()
    cfg.print_config()

    writer = SummaryWriter()

    train_transform = get_train_transform(cfg.image_height, cfg.image_width)
    valid_transform = get_valid_transform(cfg.image_height, cfg.image_width)

    model = UNet(in_channel=3, out_channel=1).to(cfg.device)
    loss_fn = nn.BCEWithLogitsLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=cfg.learning_rate)

    trn_loader, val_loader = get_loaders(train_transform, valid_transform)

    for epoch in range(cfg.num_epoch):
        train_loss = train_fn(trn_loader, model, optimizer, loss_fn, device=cfg.device)

        checkpoint = {
            "state_dict": model.state_dict(),
            "optimizer": optimizer.state_dict(),
        }
        save_checkpoint(checkpoint)
        valid_loss, valid_accuracy, valid_dice_score = compute_print_val_metrics(
            val_loader, model, loss_fn=loss_fn, device=cfg.device
        )
        save_samples_predicted(val_loader, model, device=cfg.device)

        writer.add_scalars(
            "Loss", {"train_loss": train_loss, "valid_loss": valid_loss}, epoch
        )
        writer.add_scalars("Accuracy", {"valid_accuracy": valid_accuracy}, epoch)
        writer.add_scalars("Dice Score", {"valid_dice_score": valid_dice_score}, epoch)

    torch.save(model, "road_segmentation.pt")

if __name__ == "__main__":
    main()


from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivymd.uix.filemanager import MDFileManager
from kivymd.uix.textfield import MDTextField
from kivymd.uix.label import MDLabel
from kivy.uix.image import Image
from bisviz_interface import bisviz
from kivymd.uix.pickers import MDDatePicker, MDTimePicker

class MyApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        layout = BoxLayout(orientation='vertical', padding=20)
        logo = Image(source='UI_Logo_1.png', size_hint=(1, 0.5))
        layout.add_widget(logo)

        start_date_button = Button(text="Choose Start Date")
        start_date_button.bind(on_press=self.show_start_date_picker)
        layout.add_widget(start_date_button)

        end_date_button = Button(text="Choose End Date")
        end_date_button.bind(on_press=self.show_end_date_picker)
        layout.add_widget(end_date_button)

        start_time_button = Button(text="Choose Start Time")
        start_time_button.bind(on_press=self.show_start_time_picker)
        layout.add_widget(start_time_button)

        end_time_button = Button(text="Choose End Time")
        end_time_button.bind(on_press=self.show_end_time_picker)
        layout.add_widget(end_time_button)

        bis_thresh_box = BoxLayout(orientation='horizontal')
        bis_thresh_label = MDLabel(text='Enter BIS Threshold value : ')
        bis_thresh_box.add_widget(bis_thresh_label)
        self.bis_thresh_input = MDTextField()
        bis_thresh_box.add_widget(self.bis_thresh_input)
        layout.add_widget(bis_thresh_box)

        time_thresh_box = BoxLayout(orientation='horizontal')
        time_thresh_label = MDLabel(text='Enter Time Threshold value : ')
        time_thresh_box.add_widget(time_thresh_label)
        self.time_thresh_input = MDTextField()
        time_thresh_box.add_widget(self.time_thresh_input)
        layout.add_widget(time_thresh_box)

        csv_spa_box = BoxLayout(orientation='horizontal')
        csv_spa_label = MDLabel(text='CSV or SPA : ')
        csv_spa_box.add_widget(csv_spa_label)
        self.csv_spa_input = MDTextField()
        csv_spa_box.add_widget(self.csv_spa_input)
        layout.add_widget(csv_spa_box)

        button = Button(text='Choose File')
        button.bind(on_press=self.choose_file)
        layout.add_widget(button)
        self.file_manager = MDFileManager()
        self.file_manager.exit_manager = self.exit_manager
        self.file_manager.select_path = self.select_path

        return layout

    def show_start_date_picker(self, instance):
        date_dialog = MDDatePicker()
        date_dialog.bind(on_save=self.on_start_date_save)
        date_dialog.open()

    def on_start_date_save(self, instance, value, date_range):
        self.start_date = str(value.strftime('%m/%d/%Y'))
        print(str(self.start_date))

    def show_end_date_picker(self, instance):
        date_dialog = MDDatePicker()
        date_dialog.bind(on_save=self.on_end_date_save)
        date_dialog.open()

    def on_end_date_save(self, instance, value, date_range):
        self.end_date = str(value.strftime('%m/%d/%Y'))
        print(str(self.end_date))

    def show_start_time_picker(self, instance):
        time_dialog = MDTimePicker()
        time_dialog.bind(time=self.on_start_time_save)
        time_dialog.open()

    def on_start_time_save(self, instance, value):
        self.start_time = str(value.strftime('%H:%M'))
        print(str(self.start_time))

    def show_end_time_picker(self, instance):
        time_dialog = MDTimePicker()
        time_dialog.bind(time=self.on_end_time_save)
        time_dialog.open()

    def on_end_time_save(self, instance, value):
        self.end_time = str(value.strftime('%H:%M'))
        print(str(self.end_time))

    def choose_file(self, instance):
        self.file_manager.show('/')

    def exit_manager(self, *args):
        self.file_manager.close()

    def select_path(self, path):
        self.file_path = path
        bisviz(self.start_date, self.start_time, self.end_date, self.end_time, self.bis_thresh_input.text, self.time_thresh_input.text, self.file_path, self.csv_spa_input.text)
        self.exit_manager()

MyApp().run()


"""https://www.acmicpc.net/problem/15658"""

"""연산자 끼워넣기"""

from itertools import permutations

import sys

N = int(input())

numbers = list(map(int,input().split()))

op_num = list(map(int,input().split()))

op = []

for i in range(4):
    if i == 0:
        op = op+[1 for _ in range(op_num[i])]
    elif i == 1:
        op = op+[2 for _ in range(op_num[i])]
    elif i == 2:
        op = op+[3 for _ in range(op_num[i])]
    elif i == 3:
        op = op+[4 for _ in range(op_num[i])]

possible_op_list = list(set(permutations(op,N-1)))

def cal(N,numbers,op_list):

    result = numbers[0]

    for i in range(1,len(numbers)):
        if op_list[i-1] == 1:
            result += numbers[i]
        elif op_list[i-1] == 2:
            result -= numbers[i]
        elif op_list[i-1] == 3:
            result *= numbers[i]
        else:
            if result < 0:
                result = (result*-1)//numbers[i]
                result *= -1
            else:
                result //= numbers[i]

    return result

max_ = -sys.maxsize
min_ = sys.maxsize

for opers in possible_op_list:

    tmp = cal(N,numbers,opers)

    max_ = max(max_,tmp)
    min_ = min(min_,tmp)

print(max_)
print(min_)


import io
import logging
from typing import List

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

file = "day8/input.txt"

displays = [[]]
number_of_uniques = 0
with open(file) as f:
    displays = [ x.split("|")[1].split() for x in f.readlines()]

for digits in displays:
    for digit in digits:
        if len(digit) != 5 and len(digit) != 6:
            number_of_uniques += 1

log.info(f"Number of unique digits: {number_of_uniques}")


from collections import deque
import sys

N, d, k, c = map(int, input().split())

sushis = deque()
for _ in range(N):
    sushis.append(int(sys.stdin.readline()))

count = 0
result = 0
sushi_count = {i:0 for i in range(1, d+1)}

# 초기화 (처음부터 쿠폰 스시는 넣고 계산)
sushi_count[c] += 1
count += 1

for _ in range(k):
    s = sushis.popleft()
    if sushi_count[s] == 0:
        count += 1
    sushi_count[s] += 1
    sushis.append(s)

result = count

# 투 포인터로 탐색
for _ in range(N-1):
    sta = sushis[-k]
    sushi_count[sta] -= 1
    if sushi_count[sta] == 0:
        count -= 1

    s = sushis.popleft()
    if sushi_count[s] == 0:
        count += 1
    sushi_count[s] += 1
    sushis.append(s)

    if result < count:
        result = count
    if result == k + 1:
        break

print(result)

# print(sushi_count)
# print(save_count)
# print(sushis)


#Date created: October 27, 2022
#Program for flipping two coins

import random
heads_tails = 0
two_heads = 0
two_tails = 0

number_of_flips = int(input("How many times should we flip?: "))

for x in range (1,number_of_flips+1):
    coinA_result = random.randint(0,1)
    coinB_result = random.randint(0,1)
    flip_result = (coinA_result, coinB_result)
    if (flip_result == (1,0) or flip_result == (0,1)):
        heads_tails += 1
    elif flip_result == (0,0):
        two_heads += 1
    else:
        two_tails += 1

comboDict = {"1H1T":heads_tails, "2H":two_heads, "2T":two_tails}

for combo in comboDict:
    print(combo, ":", comboDict[combo])


from __future__ import unicode_literals

############## USER CONFIGURATION START ##############

HIGHLIGHT_BY_DEFAULT = True
HOTKEY_HIGHLIGHT_TOGGLE = "Ctrl+T, H"

##############  USER CONFIGURATION END  ##############

from aqt.qt import *
from aqt.browser import Browser
from anki.hooks import wrap, addHook

from anki import version as anki_version
anki21 = anki_version.startswith("2.1.")

if anki21:
    find_flags = QWebEnginePage.FindFlags(0)
else:
    find_flags = QWebPage.HighlightAllOccurrences

# ignore search token specifiers, search operators, and wildcard characters
excluded_tags = ("deck:", "tag:", "card:", "note:", "is:", "prop:", "added:",
                "rated:", "nid:", "cid:", "mid:", "seen:")
excluded_vals = ("*", "_", "_*")
operators = ("or", "and", "+")

def onRowChanged(self, current, previous):
    """
    Highlight search results in Editor pane on searching
    """
    if not self._highlightResults:
        return
    txt = self.form.searchEdit.lineEdit().text().strip()
    if not txt:
        return
    tokens = txt.split()
    vals = []
    for token in tokens:
        if (token in operators or token.startswith("-")
                or token.startswith(excluded_tags)):
            continue
        if ":" in token:
            frags = token.split(":")
            tag = frags[0]
            val = "".join(frags[1:])
            if not val or val in excluded_vals:
                continue
        else:
            val = token
        val = val.strip('''",*;''')
        vals.append(val)
    if not vals:
        return
    for val in vals:
        self.editor.web.findText(val, find_flags)

def onCustomSearch(self, onecard=False):
    """Extended search functions"""
    txt = self.form.searchEdit.lineEdit().text().strip()
    cids = self.col.findCards(txt, order=True)

    if onecard:
        # jump to next card, while wrapping around at the end
        if self.card:
            cur = self.card.id
        else:
            cur = None

        if cur and cur in cids:
            idx = cids.index(cur) + 1
        else:
            idx = None

        if not idx or idx >= len(cids):
            idx = 0
        cids = cids[idx:idx+1]

    self.form.tableView.selectionModel().clear()
    self.model.selectedCards = {cid: True for cid in cids}
    self.model.restoreSelection()

def toggleSearchHighlights(self, checked):
    """Toggle search highlights on or off"""
    self._highlightResults = checked
    if not checked:
        # clear highlights
        self.editor.web.findText("", find_flags)
    else:
        onRowChanged(self, None, None)

def onSetupSearch(self):
    """Add extended search hotkeys"""
    s = QShortcut(QKeySequence(_("Shift+Return")), self.form.searchEdit)
    s.activated.connect(lambda: self.onCustomSearch(True))
    s = QShortcut(QKeySequence(_("Ctrl+Return")), self.form.searchEdit)
    s.activated.connect(self.onCustomSearch)

def onSetupMenus(self):
    """Setup menu entries and hotkeys"""
    self._highlightResults = HIGHLIGHT_BY_DEFAULT
    try:
        # used by multiple add-ons, so we check for its existence first
        menu = self.menuView
    except:
        self.menuView = QMenu(_("&View"))
        self.menuBar().insertMenu(
            self.mw.form.menuTools.menuAction(), self.menuView)
        menu = self.menuView
    menu.addSeparator()
    a = menu.addAction('Highlight Search Results')
    a.setCheckable(True)
    a.setChecked(HIGHLIGHT_BY_DEFAULT)
    a.setShortcut(QKeySequence(HOTKEY_HIGHLIGHT_TOGGLE))
    a.toggled.connect(self.toggleSearchHighlights)

if anki21:
    Browser._onRowChanged = wrap(Browser._onRowChanged, onRowChanged, "after")
else:
    Browser.onRowChanged = wrap(Browser.onRowChanged, onRowChanged, "after")

addHook("browser.setupMenus", onSetupMenus)
Browser.onCustomSearch = onCustomSearch
Browser.toggleSearchHighlights = toggleSearchHighlights
Browser.setupSearch = wrap(Browser.setupSearch, onSetupSearch, "after")


#!/usr/bin/env python3
"""A tool to plot cumulative time taken for each planner to solve a collection
of problems. Really needs to be renamed to avoid confusion with
solution_time_plot.py."""

from argparse import ArgumentParser
from collections import OrderedDict
from json import load

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

from asnets.scripts.solution_time_plot import add_common_parser_opts

parser = ArgumentParser(
    description="plots of total running time for ICAPS/JFPDA slides (and "
    "maybe JAIR too)")
parser.add_argument('--save',
                    metavar='PATH',
                    type=str,
                    default=None,
                    help="destination file for graph")
parser.add_argument('--no-legend',
                    dest='add_legend',
                    default="brief",
                    action='store_false',
                    help='disable legend')
parser.add_argument('--dims',
                    nargs=2,
                    type=float,
                    metavar=('WIDTH', 'HEIGHT'),
                    default=[7, 3],
                    help="dimensions (in inches) for saved plot")
parser.add_argument('--xmax',
                    type=int,
                    help='maximum time to show along x-axis')
parser.add_argument('--title', help='title for the plot')
parser.add_argument(
    '--presentation',
    default=False,
    action='store_true',
    help='use typeface/display choices appropriate for presentation (rather '
    'than printed work)')

add_common_parser_opts(parser)

def _load_inner_df(expt_str, args):
    """Load single experiment outcome as dataframe."""
    try:
        label, path = expt_str.split(':', 1)
    except ValueError as e:
        print('Could not parse label:path pair "%s"' % expt_str)
        raise e

    # this is for data that we don't have because one method took forever to
    # solve anything :(
    no_data = path == 'EMPTY'
    if no_data:
        data = {'eval_names': [], 'eval_sizes': [], 'eval_runs': []}
    else:
        # load data
        with open(path, 'r') as fp:
            data = load(fp)

    # sometimes we have more names than sizes for some reasons (probably
    # collate_data is broken)
    num_runs_set = set(
        map(len, [data['eval_sizes'], data['eval_runs'], data['eval_names']]))
    assert len(num_runs_set), "inconsistent sizes (%s)" % (num_runs_set, )

    # this is used for ASNets
    train_time = data.get('train_time', 0)

    # These are sometimes used by the calling code. name_arch is the name of
    # the architecture module (e.g. actprop_2l), and name_expt is the name of
    # the experiment module (e.g. ex_blocksworld).
    name_arch = data.get('name_arch', 'EMPTY')
    name_expt = data.get('name_expt', 'EMPTY')

    # record format:
    # {
    #   "problem": <problem-name>,
    #   "problem_size": <problem-size>,
    #   "method": <algorithm-name>,
    #   "goal_reached": <goal-reached>,
    #   "cost": <cost-or-deadend-cost>,
    #   "time": <time-or-timeout>,
    #   "time_raw": <ray-time-maybe-none>,
    #   "run_seq_num": <run-num-in-sequence>,
    # }
    # We'll make a DataFrame out of those!
    records = []
    for name, size, data_dict in zip(data['eval_names'], data['eval_sizes'],
                                     data['eval_runs']):
        for seq_num, (goal_reached, cost, time) in enumerate(
                zip(data_dict['goal_reached'], data_dict['cost'],
                    data_dict['time'])):
            if time is None:
                time_or_timeout = args.timeout
            else:
                # always add in training time
                time_or_timeout = time + train_time
            record = {
                "problem": name,
                "problem_size": size,
                "method": label,
                "goal_reached": goal_reached,
                "cost": cost,
                "time": time_or_timeout,
                # use nans instead of None to hint to Pandas that this series
                # should be float, and not object
                "time_raw": time if time is not None else float('nan'),
                "train_time": train_time,
                "run_seq_num": seq_num,
                "name_arch": name_arch,
                "name_expt": name_expt,
            }
            records.append(record)

    frame = pd.DataFrame.from_records(records)

    return label, frame

def load_labels_frames(args):
    """Load an entire collection of experiments as a big DataFrame. Also return
    labels, which I suspect I'll need at some point (I could get them out of
    the DataFrame, but that'll only work for the methods where I have at least
    some data)."""
    frames = []
    labels = []
    for label_path in args.jsons:
        label, frame = _load_inner_df(label_path, args)
        labels.append(label)
        frames.append(frame)
    mega_frame = pd.concat(frames)
    return labels, mega_frame

def main():
    args = parser.parse_args()

    if args.presentation:
        sns.set(context='talk', style='whitegrid')
        matplotlib.rcParams.update({
            'font.family': 'sans',
            'font.serif': 'sans',
            'pgf.rcfonts': False,
            'pgf.texsystem': 'pdflatex',
            # 'xtick.labelsize': 'x-small',
            # 'ytick.labelsize': 'x-small',
            'legend.fontsize': 10,
            # 'axes.labelsize': 'x-small',
            # 'axes.titlesize': 'medium'
        })
    else:
        # Make the plot look like LaTeX
        sns.set(context='paper', style='whitegrid')
        matplotlib.rcParams.update({
            'font.family': 'CMU Serif',
            'font.serif': 'CMU Serif',
            'pgf.rcfonts': False,
            'pgf.texsystem': 'pdflatex',
            'xtick.labelsize': 'x-small',
            'ytick.labelsize': 'x-small',
            'legend.fontsize': 6.5,
            'axes.labelsize': 'small',
            'axes.titlesize': 'medium',
            # ensures that we have only type 42/type 1 fonts, and *no* type
            # 3---important for AAAI (type 42 = TrueType)
            # 'pdf.fonttype': 42,
            # 'ps.fonttype': 42,
            'text.usetex': True,
        })

    all_labels, data_frame = load_labels_frames(args)
    size_mask = (data_frame['problem_size'] >= args.min_size) \
        & (data_frame['problem_size'] <= args.max_size)
    data_frame = data_frame[size_mask]

    # Now we plot cumulative time
    # record format:
    # {
    #    "method":
    #    "ctime":
    #    "coverage":
    # }
    cumul_records = []
    max_covs = OrderedDict()
    max_ctime = 0.0
    for method in data_frame['method'].unique():
        selection = data_frame[data_frame['method'] == method]
        grouped = selection.groupby('problem')
        sol_times = grouped['time_raw'].mean().to_numpy()
        sol_times[~np.isfinite(sol_times)] = 0.0
        sol_coverages = grouped['goal_reached'].mean().to_numpy()\
            .astype('float')
        train_time = grouped['train_time'].mean().mean()
        # append empty initial record
        cumul_records.append({
            "method": method,
            "coverage": 0,
            "ctime": 0,
        })
        if train_time > 0:
            # record for train time is important
            cumul_records.append({
                "method": method,
                "coverage": 0,
                "ctime": train_time,
            })
        # want to sort by gradient, which is sol_coverages / sol_times (with
        # 0/0=0)
        gradients = np.divide(sol_coverages,
                              sol_times,
                              out=np.zeros_like(sol_coverages),
                              where=sol_times > 0)
        correct_order = np.argsort(gradients)[::-1]
        ctime = train_time
        ccov = 0
        for prob_num in correct_order:
            this_cov = sol_coverages[prob_num]
            if this_cov == 0:
                break
            ccov += this_cov
            this_time = sol_times[prob_num]
            ctime += this_time
            cumul_records.append({
                "method": method,
                "coverage": ccov,
                "ctime": ctime,
            })
        max_covs[method] = ccov
        max_ctime = max(ctime, max_ctime)

    right_point = max(max_ctime, args.xmax or 0)
    for method, max_cov in max_covs.items():
        cumul_records.append({
            "method": method,
            "coverage": max_cov,
            "ctime": right_point,
        })

    ctime_frame = pd.DataFrame.from_records(cumul_records)
    ctime_frame['hours'] = ctime_frame['ctime'] / 3600.0
    ctime_frame['Method'] = ctime_frame['method']  # capitalise legend title :)
    sns.lineplot(data=ctime_frame,
                 x="hours",
                 y="coverage",
                 hue="Method",
                 drawstyle='steps-pre',
                 legend=args.add_legend and 'brief')
    num_problems = len(data_frame['problem'].unique())
    plt.axhline(num_problems, ls='--', color='maroon')
    plt.xlabel("Cumulative time (hours)")
    plt.ylabel("Cumulative coverage")
    max_secs = args.xmax or ctime_frame['ctime'].max()
    max_h = max_secs / 3600.0
    plt.xlim(left=-0.025 * max_h, right=max_h)
    plt.ylim(bottom=-num_problems * 0.01, top=num_problems * 1.05)

    # title
    plt.title(args.title)

    # save or show
    if args.save is None:
        plt.show()
    else:
        print('Saving figure to', args.save)
        plt.gcf().set_size_inches(args.dims)
        plt.tight_layout()
        plt.savefig(
            args.save,
            bbox_inches='tight',
            dpi=400,
            # bbox_extra_artists=[legend],
            transparent=True)

if __name__ == '__main__':
    main()


import os
import importlib
import json

from queue import Empty
from urllib.parse import urljoin

import requests

def publish_batch(config, queue):
    result_list = []
    try:
        try:
            while not queue.empty() and len(result_list) < config.BUFFER_LENGTH:
                payload = queue.get_nowait()
                result_list.append(payload)
        except Empty:
            pass

        if len(result_list) == 0:
            return

        version = importlib.import_module(__package__).__version__
        url = urljoin(
            os.getenv("README_METRICS_SERVER", config.METRICS_API), "/v1/request"
        )

        readme_result = requests.post(
            url,
            auth=(config.README_API_KEY, ""),
            data=json.dumps(result_list),
            headers={
                "Content-Type": "application/json",
                "User-Agent": f"readme-metrics-python@{version}",
            },
            timeout=config.METRICS_API_TIMEOUT,
        )
        config.LOGGER.info(
            f"POST to {url} with {len(result_list)} items returned {readme_result.status_code}"
        )
        if not readme_result.ok:
            config.LOGGER.exception(readme_result.text)
            raise Exception(f"POST to {url} returned {readme_result.status_code}")
    except Exception as e:
        # Errors in the Metrics SDK should never cause the application to
        # throw an error. Log it but don't re-raise.
        config.LOGGER.exception(e)
    finally:
        for _ in result_list:
            queue.task_done()


import re

"""
#1

txt1 = 'abcd axyz xyz abbbbbbbbbbbbb dac ab'

t = re.findall("ab*", txt1)

print(t)

#2
y = re.findall("ab{2,3}", txt1)

print(y)

#3
txt2 = 'abc ab_cd xyz z_w'

t = re.findall("[a-z]+_[a-z]+", txt2)

print(t)

#4

y = re.findall("[A-Z][a-z]+",txt2)

print(y)

#5

txt3 = 'abcd abe xyz abbcd ab'

t = re.findall('ab.*b', txt3)

print(t)
"""

#6

string = "My name is Dimash. And i'm studying in KBTU "
new_string = re.sub('[ ,.]', ':', string)
print(new_string)

"""
#8

txt4 = "AbbCdfsVgbnDfrt"
d = re.findall('[A-Z][^A-Z]*', txt4)
print(d)

"""
"""#9

txt5 = "AdcfHfgrTyjhUrel"
f = re.sub('(?<!^)(?=[A-Z])', ' ', txt5)
print(f)
"""
"""
#10

camel_case_string = "HoDatBoi"
snake_case_string = re.sub(r'(?<!^)(?=[A-Z])', '_', camel_case_string).lower()
print(snake_case_string)
"""


#!/usr/bin/python3.6

import random

regA = random.randint(0,3)
regB = random.randint(0,3)
regInit = random.sample(range(0,256), 4)

# print(regInit)

regOut = (regInit[regA] + regInit[regB]) % 256

# output bitwidths expected
# this should be of length 1
inputwidths = [2, 2, 8, 8, 8, 8]
outputwidths = [8]

allVals = [regA, regB] + regInit + [regOut]
widths = inputwidths + outputwidths

zipped = list(zip(allVals, widths))

print(' '.join(['(_ bv{} {})'.format(i[0], i[1]) for i in zipped]))


# list=[24,32,34,14,36,92,89,55]
# count=40
# i=0
# j=[]
# while i<len(list):
#     if list[i]>40:
#         j.append(list[i])
#     i=i+1
# print(j)

# 40 se bada no.dusre list me aajaye

# a=5
# b=8
# c=5
# a=b
# b=c
# print(a)
# print(b)

# def func1(*args):
#     for i in args:
#         print(i)

# func1(20, 40, 60)
# func1(80, 100)

# dic={"name":"manisha","place":"pune","country":"india"}
# dic.update({"n":"k"})
# print(dic)

list=[[12, 18, 23, 25, 45], [7, 12, 18, 24, 28], [1, 5, 8, 12, 15, 16, 18]]
i=0
list1=[]
list2=[]
while i<len(list):
    k=list[i][0]
    i=i+1
    print(k)

# number=int(input("enter the number"))
# i=1
# sum=0
# while i<number:
#     if number%i==0:
#         sum=sum+i
#     i=i+1
# if sum==number:
#     print("perfect number")
# else:
#     print("not perfect number")


import random
import re

command = input("Dice Command: ")
pattern = "(\d*)d(\d*)"
regexMatch = re.match(pattern, command)
total = 0
if regexMatch != None:
    for i in range(int((regexMatch).group(1))):
        a = random.randint(0, int(regexMatch.group(2)))
        print(a)
        total += a
    print("------")
    print(total)
    print("END")
else:
    print("Unrecognized Input")


import autodynatrace
from fastapi import APIRouter, Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from shared.infrastructure import HttpResponse
from shared.infrastructure.settings import get_settings
from worker.domain import UserLogin, UserRegistration
from worker.infrastructure import WorkerController

settings = get_settings()

version = settings.API_VERSION
namespace = settings.NAMESPACE
prefix = f'/{namespace}/api/{version}'

descriptions = {
    'liveness': 'Verifica que el servicio se encuentre disponible.',
    'readiness': 'Verifica que existan conexiones activas a MONGO/REDIS/FIREBASE.',
    'signup': 'Registra un nuevo usuario en base de datos.',
    'login': 'Verifica si un usuario existe en base de datos.',
    'keys': 'Valida si el token es correcto y retorna el payload'
}

router = APIRouter(prefix=prefix)

@router.get('/liveness', tags=['Health Checks'],
            summary=descriptions['liveness'])
@autodynatrace.trace(f'{prefix}/liveness')
def liveness() -> dict:
    return {'status': 'success'}

@router.get('/readiness', tags=['Health Checks'],
            summary=descriptions['readiness'])
@autodynatrace.trace(f'{prefix}/readiness')
def readiness() -> HttpResponse:
    return WorkerController.readiness()

@router.post('/signup', tags=['Auth'],
             summary=descriptions['signup'])
@autodynatrace.trace(f'{prefix}/signup')
def signup(user: UserRegistration) -> HttpResponse:
    return WorkerController.signup(user)

@router.post('/login', tags=['Auth'],
             summary=descriptions['login'])
@autodynatrace.trace(f'{prefix}/login')
def login(user: UserLogin) -> HttpResponse:
    return WorkerController.login(user)

@router.get('/keys', tags=['Auth'],
            summary=descriptions['keys'])
@autodynatrace.trace(f'{prefix}/keys')
def keys(authorization: HTTPAuthorizationCredentials = Depends(HTTPBearer())) -> HttpResponse:
    token = authorization.credentials
    return WorkerController.keys(token)


import tqdm
import os

if __name__ == '__main__':
    path = '/Users/apple/Documents/gs_info/'
    with open(path+'gs_id.txt', 'r') as f:
        lines = f.readlines()

    id2str = {}
    str2id = {}
    for line in lines:
        conn = line.strip().split(" ")
        idnode, strnode = int(conn[0]), conn[1]
        id2str[idnode] = strnode
        str2id[strnode] = idnode

    print('OK')