"""
    * Bump Stalatites con Neat, (Redes neuronales)
"""

# * Declaración de librerías
import pygame
import random
import os
import neat

pygame.font.init()

# * Variables usadas
WIN_WIDTH = 600
WIN_HEIGHT = 800
FLOOR = 730
STAT_FONT = pygame.font.SysFont("Console", 50, bold=True)
END_FONT = pygame.font.SysFont("Console", 70, bold=True)
DRAW_LINES = False

# * Ventana principal
WIN = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
pygame.display.set_caption("Bump Stactite")

# * Llamado de imágenes
pipe_img = pygame.transform.scale2x(pygame.image.load(
    os.path.join("imgs", "pipe.png")).convert_alpha())
bg_img = pygame.transform.scale(pygame.image.load(
    os.path.join("imgs", "bg.png")).convert_alpha(), (600, 900))
bird_images = [pygame.transform.scale2x(pygame.image.load(
    os.path.join("imgs", "bird" + str(x) + ".png"))) for x in range(1, 4)]
base_img = pygame.transform.scale2x(pygame.image.load(
    os.path.join("imgs", "base.png")).convert_alpha())

gen = 0

# * Clase donde se declara la nave

class Pipe():
    """
        * Clase Pipe:
        * Objeto tipo Pipa o estalactita.
    """
    GAP = 200
    VEL = 5

    def __init__(self, x):
        """
            * Inicialización del objeto
        """
        self.x = x
        self.height = 0

        self.top = 0
        self.bottom = 0

        self.PIPE_TOP = pygame.transform.flip(pipe_img, False, True)
        self.PIPE_BOTTOM = pipe_img

        self.passed = False

        self.set_height()

    def set_height(self):
        """
            * Esta función, establece la altura de la Estalactita desde la parte más abajo de la pantalla
        """
        self.height = random.randrange(50, 450)
        self.top = self.height - self.PIPE_TOP.get_height()
        self.bottom = self.height + self.GAP

    def move(self):
        """
            * Mueve la Estalactita en función de la velocidad.
            TODO : Incluir nivel de mas velocidad acorde a la puntuación.
        """
        self.x -= self.VEL * 1.5

    def draw(self, win):
        """
            * Dibuja la parte de arriba y de abajo de la Estalactita
        """
        # Dibuja pipa de arriba.
        win.blit(self.PIPE_TOP, (self.x, self.top))
        # Dibuja pipa de abajo.
        win.blit(self.PIPE_BOTTOM, (self.x, self.bottom))

    def collide(self, bird, win):
        """
            * Función de colisión.
        """
        bird_mask = bird.get_mask()
        top_mask = pygame.mask.from_surface(self.PIPE_TOP)
        bottom_mask = pygame.mask.from_surface(self.PIPE_BOTTOM)
        top_offset = (self.x - bird.x, self.top - round(bird.y))
        bottom_offset = (self.x - bird.x, self.bottom - round(bird.y))

        b_point = bird_mask.overlap(bottom_mask, bottom_offset)
        t_point = bird_mask.overlap(top_mask, top_offset)

        if b_point or t_point:
            return True

        return False

class Bird:
    """
        * Clase Bird que representa el juego
    """
    MAX_ROTATION = 25
    IMGS = bird_images
    ROT_VEL = 20
    ANIMATION_TIME = 5

    def __init__(self, x, y):
        """
            * Inicializando el objeto:
        """
        self.x = x
        self.y = y
        self.tilt = 0  # Inclinación de la nave.
        self.tick_count = 0
        self.vel = 0
        self.height = self.y
        self.img_count = 0
        self.img = self.IMGS[0]

    def jump(self):
        """
            * Hace que la nave salte.
        """
        self.vel = -10.5
        self.tick_count = 0
        self.height = self.y

    def move(self):
        """
            * Movimientos de la nave
        """
        self.tick_count += 1

        # * Ir hacia abajo:
        displacement = self.vel*(self.tick_count) + 0.5 * \
            (3)*(self.tick_count)**2  # * Calcula el desplazamiento.

        # * Velocidad:
        if displacement >= 16:
            displacement = (displacement/abs(displacement)) * 16

        if displacement < 0:
            displacement -= 2

        self.y = self.y + displacement

        if displacement < 0 or self.y < self.height + 50:  # La inclina hacia arriba
            if self.tilt < self.MAX_ROTATION:
                self.tilt = self.MAX_ROTATION
        else:  # Si no, la inclina hacia abajo
            if self.tilt > -90:
                self.tilt -= self.ROT_VEL

    def draw(self, win):
        """
            * Dibujo del la nave (HitBox)
        """

        # * Inclinacion de la nave
        blitRotateCenter(win, self.img, (self.x, self.y), self.tilt)

    def get_mask(self):
        """
            * Obtiene una superficie la imagen y la adapta a la hit box
        """
        return pygame.mask.from_surface(self.img)

class Base:
    """
        * Representa el movimiento de la base de abajo (Especie de superficie marciana)
    """
    VEL = 5
    WIDTH = base_img.get_width()
    IMG = base_img

    def __init__(self, y):
        """
            * Inicialización del objeto.
        """
        self.y = y
        self.x1 = 0
        self.x2 = self.WIDTH

    def move(self):
        """
            * Movimiento del piso.
        """
        self.x1 -= self.VEL
        self.x2 -= self.VEL
        if self.x1 + self.WIDTH < 0:
            self.x1 = self.x2 + self.WIDTH

        if self.x2 + self.WIDTH < 0:
            self.x2 = self.x1 + self.WIDTH

    def draw(self, win):
        """
            * Dibujando la Hitbox de la superficie.
        """
        win.blit(self.IMG, (self.x1, self.y))
        win.blit(self.IMG, (self.x2, self.y))

def blitRotateCenter(surf, image, topleft, angle):
    """
        * Organización de la superficie con respecto a la pantalla.
    """
    rotated_image = pygame.transform.rotate(image, angle)
    new_rect = rotated_image.get_rect(
        center=image.get_rect(topleft=topleft).center)

    surf.blit(rotated_image, new_rect.topleft)

def draw_window(win, birds, pipes, base, score, gen, pipe_ind):
    """
        * Dibujando la pantalla para el la ventana principal main_game loop
    """
    if gen == 0:
        gen = 1
    win.blit(bg_img, (0, 0))

    for pipe in pipes:
        pipe.draw(win)

    base.draw(win)
    for bird in birds:
        # ?
        if DRAW_LINES:
            try:
                pygame.draw.line(win, (255, 0, 0), (bird.x+bird.img.get_width()/2, bird.y + bird.img.get_height(
                )/2), (pipes[pipe_ind].x + pipes[pipe_ind].PIPE_TOP.get_width()/2, pipes[pipe_ind].height), 5)
                pygame.draw.line(win, (255, 0, 0), (bird.x+bird.img.get_width()/2, bird.y + bird.img.get_height(
                )/2), (pipes[pipe_ind].x + pipes[pipe_ind].PIPE_BOTTOM.get_width()/2, pipes[pipe_ind].bottom), 5)
            except:
                pass
        # * Dibuja la hb de la nave en pantalla.
        bird.draw(win)

    # * Texto generaciones
    score_label = STAT_FONT.render("Generación: " + str(gen), 1, (0, 0, 0))
    win.blit(score_label, (10, 10))

    # * Texto de los que aun quedan vivos.
    score_label = STAT_FONT.render(
        "Sobrevivientes: " + str(len(birds)), 1, (0, 0, 0))
    win.blit(score_label, (10, 50))

    # * Puntuación
    score_label = STAT_FONT.render("Puntaje: " + str(score), 1, (0, 0, 0))
    win.blit(score_label, (10, 90))

    pygame.display.update()

def eval_genomes(genomes, config):
    """
        * Ejecuta la simulacion de la población de naves y establece
        * su Fitness basado en la distancia que ellos alcanzan dentro del juego.
    """
    global WIN, gen
    win = WIN
    gen += 1

    # * Inicia con crear listas que contengan su genoma,
    # * la red neuronal asociada con el genoma y
    # * El objeto de tipo nave que usa la red para jugar.
    nets = []
    birds = []
    ge = []
    for genome_id, genome in genomes:
        genome.fitness = 0  # Inicia con un Fitness de 0
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        nets.append(net)
        birds.append(Bird(230, 350))
        ge.append(genome)

    base = Base(FLOOR)
    pipes = [Pipe(700)]
    score = 0

    clock = pygame.time.Clock()

    run = True
    while run and len(birds) > 0:
        clock.tick(30)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        pipe_ind = 0
        if len(birds) > 0:
            # Determina cual usar, ya sea el primero o el segundo
            if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():
                # Estalactita en la pantalla para la entrada input de la red neuronal
                pipe_ind = 1
        # * Le damos a cada nave un Fitness de 0.1 por cada que atraviese el obstaculo
        for x, bird in enumerate(birds):
            ge[x].fitness += 0.1
            bird.move()

            # Envía la posición de la nave, la de la estalactita de arriba y la de abajo y determina desde la red neuronal
            # Sí saltar o no saltar.
            output = nets[birds.index(bird)].activate((bird.y, abs(
                bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom)))

            # Se utiliza una funcion de activacion tanh, así, el resultado será entre -1 y 1. Si es mayor que 0.5, este saltará.
            if output[0] > 0.5:
                bird.jump()

        base.move()

        rem = []
        add_pipe = False
        for pipe in pipes:
            pipe.move()
            # Verifica si hay colisión
            for bird in birds:
                if pipe.collide(bird, win):
                    ge[birds.index(bird)].fitness -= 1
                    nets.pop(birds.index(bird))
                    ge.pop(birds.index(bird))
                    birds.pop(birds.index(bird))

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                rem.append(pipe)

            if not pipe.passed and pipe.x < bird.x:
                pipe.passed = True
                add_pipe = True

        if add_pipe:
            score += 1
            # Esta linea dará más y más recompensa al pasar mediante los obstaculos.
            for genome in ge:
                genome.fitness += 4
            pipes.append(Pipe(WIN_WIDTH))

        for r in rem:
            pipes.remove(r)

        for bird in birds:
            if bird.y + bird.img.get_height() - 10 >= FLOOR or bird.y < -50:
                nets.pop(birds.index(bird))
                ge.pop(birds.index(bird))
                birds.pop(birds.index(bird))

        draw_window(WIN, birds, pipes, base, score, gen, pipe_ind)

        # Esta linea, rompe el programa si este supera el tope máximo de puntos.
        if score > 100:
            print(" Felicidades, ha aprendido satisfactoriamente. ")
            break

def run(config_file):
    """
        * Ejecuta la librería NEAT con su respectiva config-file
    """
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)

    # Creación de la población que se usará para el aprendizaje
    p = neat.Population(config)

    # Estas lineas, muestran información por la terminal de diferentes aspectos del algoritmo
    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    # p.add_reporter(neat.Checkpointer(5))

    # Ejecuta hasta 50 generaciones
    winner = p.run(eval_genomes, 50)

    # Muestra los resultados Finales
    print('\n Mejor genoma:\n{!s}'.format(winner))

if __name__ == '__main__':

    # * Aquí se determina la dirección del archivo de configuración
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config-feedforward.txt')
    run(config_path)


import numpy as np
from geopy.distance import lonlat, distance

def accuracy_topN(dist_array, topN):
    accuracy = 0.0
    data_amount = 0.0
    for i in range(dist_array.shape[0]):
        gt_dist = dist_array[i, i]
        prediction = np.sum(dist_array[:, i] < gt_dist)
        if prediction < topN:
            accuracy += 1.0
        data_amount += 1
    accuracy /= data_amount
    accuracy *= 100.0
    return accuracy

def compute_accuracy(dist_array):
    topN = 10
    top10_accuracy = accuracy_topN(dist_array, topN)
    print('Accuracy for top ' + str(topN) + ': ', top10_accuracy)
    topN = 1
    top1_accuracy = accuracy_topN(dist_array, topN)
    print('Accuracy for top ' + str(topN) + ': ', top1_accuracy)

    return top10_accuracy, top1_accuracy

def accuracy_topN_4gsv(dist_array, topN):
    accuracy = 0.0
    data_amount = 0.0
    for i in range(dist_array.shape[0]):
        gt_dist = dist_array[i, i]
        prediction = np.sum(dist_array[:, i] < gt_dist)
        if prediction < topN:
            accuracy += 1.0
        data_amount += 1
    accuracy /= data_amount
    accuracy *= 100.0
    return accuracy

def compute_accuracy_4gsv(dist_array):
    topN = 10
    top10_accuracy = accuracy_topN(dist_array, topN)
    print('Accuracy for top ' + str(topN) + ': ', top10_accuracy)
    topN = 1
    top1_accuracy = accuracy_topN(dist_array, topN)
    print('Accuracy for top ' + str(topN) + ': ', top1_accuracy)
    return top10_accuracy, top1_accuracy

def denormalize_lat_lon_coordinates(x, minmax_x_y):
    for j in range(x.shape[0]):
        for i in range(x.shape[1]):
            x[j][i][0] = float(minmax_x_y[0]) + x[j][i][0] * (float(minmax_x_y[1]) - float(minmax_x_y[0]))
            x[j][i][1] = float(minmax_x_y[2]) + x[j][i][1] * (float(minmax_x_y[3]) - float(minmax_x_y[2]))
    return x

def compute_error_distance(ref_db_lat, ref_db_lon, val_lat, val_lon, idx_sorted):
    distarray = []
    for i in range(idx_sorted.shape[0]):
        distarray.append(compute_distance_in_meters(val_lat[i], val_lon[i], ref_db_lat[idx_sorted[i][0]],
                                       ref_db_lon[idx_sorted[i][0]]))
    dists = [ sum(distarray[i*30:(i+1)*30])/30 for i in range(len(distarray)//30)]
    return dists

def compute_distance_in_meters(x1, y1, x2, y2):
    return distance(lonlat(*(y1, x1)), lonlat(*(y2, x2))).m


import os
import csv
import json
import re
import argparse
from get_dbp_predlist import get_dbp_set
from get_wd_predlist import get_wd_set
from get_fb_predlist import get_fb_set

def main(kb_list):
	set_path = '../alignment/'
	files = ['counting_filtered.csv', 'enumerating_filtered.csv', 'enumerating_inv_filtered.csv']
	predlist = {}

	for kb in kb_list:
		path = '../flask_app/static/data/'+kb
		if not os.path.exists(path):
			os.mkdir(path)

		if kb == 'dbpedia_raw':
			predlist['dbpedia_raw'] = {}
			predlist['dbpedia_raw']['predC'] = get_dbp_set(set_path+files[0], 'property', kb)
			predlist['dbpedia_raw']['predE'] = get_dbp_set(set_path+files[1], 'property', kb)
			predlist['dbpedia_raw']['predE_inv'] = get_dbp_set(set_path+files[2], 'property', kb)
		elif kb == 'dbpedia_mapped':
			predlist['dbpedia_mapped'] = {}
			predlist['dbpedia_mapped']['predC'] = get_dbp_set(set_path+files[0], 'ontology', kb)
			predlist['dbpedia_mapped']['predE'] = get_dbp_set(set_path+files[1], 'ontology', kb)
			predlist['dbpedia_mapped']['predE_inv'] = get_dbp_set(set_path+files[2], 'ontology', kb)
		elif kb == 'wikidata':
			predlist['wikidata'] = {}
			predlist['wikidata']['predC'] = get_wd_set(set_path+files[0], kb)
			predlist['wikidata']['predE'] = get_wd_set(set_path+files[1], kb)
			predlist['wikidata']['predE_inv'] = get_wd_set(set_path+files[2], kb)
		elif kb == 'freebase':
			predlist['freebase'] = {}
			predlist['freebase']['predC'] = get_fb_set(set_path+files[0], kb)
			predlist['freebase']['predE'] = get_fb_set(set_path+files[1], kb)
			predlist['freebase']['predE_inv'] = get_fb_set(set_path+files[2], kb)

		with open(path+'/'+kb+'.json', 'w') as fp:
			fp.write('jsonCallback(')
			json.dump(predlist[kb], fp)
			fp.write(')')

if __name__ == '__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument('kb_names', metavar='KB', type=str, nargs='+', help='KB names containing the set predicate lists. For e.g. dbpedia_raw, dbpedia_mapped, wikidata, freebase')
	args = parser.parse_args()
	main(args.kb_names)


"""
Levi`s parcer
"""

from typing import List
from selenium import webdriver
from item.detail import Detail
from item.size import Size
from shop.shop_interface import ShopInterface

class Levi(ShopInterface):
    """Levi`s parcer class"""

    def __init__(self, item_code: str, isset_thumbnail: bool = False):
        self.item_code = item_code
        self.isset_thumbnail = isset_thumbnail

    @staticmethod
    def find_color(driver: webdriver) -> str:
        clothe_color = driver.find_element_by_xpath(
            '//*[@id="pdpRootInstance"]/div/div/div[1]/div/div/div[3]/div[3]/div[2]/div/div[1]/span[2]')
        return clothe_color.get_attribute("innerHTML")

    @staticmethod
    def find_sizes(driver: webdriver) -> List[Size]:
        clothe_sizes = driver.find_element_by_css_selector("div.tiles-outer-grid-container")
        sizes_list = clothe_sizes.text
        return sizes_list.splitlines()

    def run(self) -> Detail:
        """Запускает задачу на сбор данных"""
        chrome_driver_path = 'chromedriver/chromedriver'  # путь до драйвера в проекте
        levis = 'https://www.levi.com/RU/ru_RU/'  # сайт для парсинга
        # item_code = 'p/269860002'
        options = webdriver.ChromeOptions()
        options.add_argument('headless')  # для браузера
        driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)
        driver.get(levis + self.item_code)
        driver.implicitly_wait(10)
        reference = driver.current_url
        product_img_list = driver.find_element_by_class_name('image-gallery')
        thumbnail = product_img_list.find_element_by_tag_name('img').get_attribute('src')
        price = driver.find_element_by_xpath(
            '//*[@id="pdpRootInstance"]/div/div/div[1]/div/div/div[3]/div[2]/div[1]/div/span[3]')
        clothes = Detail('', reference, thumbnail, self.find_color(
            driver), self.find_sizes(driver), price)

        return clothes


if __name__ == '__main__':
    N = int(raw_input())
    nList = raw_input().split()
    wList = raw_input().split()
    nList = map(int, nList)
    wList = map(int, wList)

    nSum = 0
    wSum = 0
    wSum = sum(wList)
    for i in range(N):
        nSum += nList[i]*wList[i]

    weightedMean = float(nSum)/wSum
    print ('%.1f' %weightedMean)


game_list = [['_','_','_'],['_','_','_'],['_','_','_']]
sample_list = ['_','_','_']

def display_gamelist(game_list):
    for i in range(len(game_list)):
        for j in range(len(game_list[i])):
            print(game_list[i][j], end = ' ')
        print()
#display the userinput board
def inital_display():
    print("Welcome to TicTacToe PVP")
    print('First the user must pick their choice of x or o')
    print("You will first be asked to pick a row num (0-2)")
    print("Then you'll have to pick a colum num (0-2)")
    print('Here are the positions you can refrence')
    print(['0 0','0 1','0 2'])
    print(['1 0','1 1','1 2'])
    print(['2 0','2 1','2 2'])

def position_display():
        print('Here are the positions you can refrence')
        print(['0 0','0 1','0 2'])
        print(['1 0','1 1','1 2'])
        print(['2 0','2 1','2 2'])

def game_win(game_list):
    #check horizontal
    if (game_list[0][0] == game_list [0][1] == game_list [0][2] and game_list[0][0] != '_' ) or (game_list[1][0] == game_list [1][1] == game_list [1][2]  and game_list[1][1] != '_' ) or (game_list[2][0] == game_list [2][1] == game_list [2][2] and game_list[2][2] != '_'):
        return True
        print('Game Won')
    else:
        return False
    #check vertical
    if (game_list[0][0] == game_list [1][0] == game_list [2][0]) or (game_list[0][1] == game_list [1][1] == game_list [2][1]) or (game_list[0][2] == game_list [1][2] == game_list [2][2]):
        return True
        print('Game Won')
    else:
        return False
    #check diagnol
    if (game_list[0][0] == game_list [1][1] == game_list [2][2]) or (game_list[0][2] == game_list [1][1] == game_list [2][0]):
        return True
        print('Game Won')
    else:
        return False

def get_row():
    choice = 'Incorrect'
    while choice not in ['0','1','2']:
        choice = input("Please pick which row you would play your turn in [0, 1, 2] ")
        if choice not in ['0','1','2']:
            print("Invalid choice, please enter only the numbers from [0,1,2] ")
    return int(choice)

def get_col():
    choice = 'Incorrect'
    while choice not in ['0','1','2']:
        choice = input('You have chosen the row, please pick the col you would like to play in [0, 1, 2] ')
        if choice not in ['0','1','2']:
            print("Please only enter numbers from [0,1,2] ")
    return int(choice)

def position_replace():
    print('Please chose what to play either x or o: ')
    choice = 'incorrect'
    while choice not in ['x', 'X', 'o', 'O']:
        choice = input ('Enter either x or o ')
        if choice not in ['x', 'X', 'o', 'O']:
            print('Please pick either o or x')
    return choice

def replace_game(game_list, row, col, choice):
    game_list[row][col] = choice
    return game_list

#this function will take the row and col and check if the given position has already been filled
def precheck_position(game_list, row, col, choice, moves_list):
    if game_list[row][col] != '_' or moves_list[-1] == choice:
        return False
    else:
        return True

def draw(game_list):
    for i in range(len(game_list)):
        for j in range(len(game_list[i])):
            if game_list[i][j] != '_':
                return True
            else:
                 return False

#get the inital move from the player
inital_display()
moves_list = []
choice = position_replace()
row = get_row()
col = get_col()
game_list = replace_game(game_list,row,col,choice)
moves_list.append(choice)
display_gamelist(game_list)

game_draw = False
game_fini = False
while game_fini == False:
    position_display()
    choice = position_replace()
    row = get_row()
    col = get_col()
    pre_check = precheck_position(game_list, row, col, choice, moves_list)
    if pre_check == True:
        game_list = replace_game(game_list,row,col,choice)
        moves_list.append(choice)
    else:
        print("You can not over ride a position")
        print("You can not play the same character twice in a row")
    display_gamelist(game_list)
    game_fini = game_win(game_list)
    game_draw = draw(game_list)

    if game_draw == True:
        game_fini = True
        print("Its a draw")

    if game_fini == True and game_draw == False:
        winner = moves_list[-1]
        print(f'Player {winner} won!')

print(moves_list)


from openerp.tools.translate import _
from openerp.osv import fields, osv
import openerp.netsvc
import openerp.addons.decimal_precision as dp

class hr_expense_expense(osv.osv):
    _name = "hr.expense.expense"
    _inherit = 'hr.expense.expense'

    _columns = {
                'budget_move_id': fields.many2one('budget.move', 'Budget move', readonly=True, ),
                }

    def create_budget_move_line(self, cr, uid, line_id, context=None):
        exp_obj = self.pool.get('hr.expense.expense')
        exp_line_obj = self.pool.get('hr.expense.line')
        bud_move_obj = self.pool.get('budget.move')
        bud_line_obj = self.pool.get('budget.move.line')
        fixed_amount = 0.0
        expense_line = exp_line_obj.browse(cr, uid, [line_id], context=context)[0]
        expense = exp_obj.browse(cr, uid, [expense_line.expense_id.id], context=context)[0]
        move_id = expense.budget_move_id.id
        fixed_amount = expense_line.total_amount
        bud_line = bud_line_obj.create(cr, uid, {'budget_move_id': move_id,
                                         'origin' : expense_line.name,
                                         'program_line_id': expense_line.program_line_id.id,
                                         'fixed_amount': fixed_amount ,
                                         'expense_line_id': line_id,
                                          }, context=context)
        return bud_line

    def create(self, cr, uid, vals, context=None):
        bud_move_obj = self.pool.get('budget.move')
        exp_id = super(hr_expense_expense,self).create(cr, uid, vals, context=None)
        move_id = self.create_budget_move(cr, uid, [exp_id], context)
        self.write(cr, uid, [exp_id], {'budget_move_id':move_id }, context)
        expense_amount=0.0
        for expense in self.browse(cr, uid, [exp_id], context):
            expense_amount = expense.amount
            for line in expense.line_ids:
                created_line_id = self.create_budget_move_line(cr, uid, line.id, context=context)
        bud_move_obj.write(cr, uid, [move_id], {'fixed_amount': expense_amount})
        bud_move_obj.signal_workflow(cr, uid, [move_id], 'button_reserve', context=context)
        return exp_id

    def write(self, cr, uid, ids, vals, context=None):
        bud_move_obj = self.pool.get('budget.move')
        result = super(hr_expense_expense, self).write(cr, uid, ids, vals, context=context)
        for exp in self.browse(cr, uid, ids, context=context):
            if exp.budget_move_id and exp.budget_move_id.state !='draft':
                bud_move_obj.write(cr, uid, [exp.budget_move_id.id], {'fixed_amount':exp.amount})
                bud_move_obj.recalculate_values(cr, uid, [exp.budget_move_id.id], context=context)
        return result

    def create_budget_move(self,cr, uid, ids, context=None):
        bud_move_obj = self.pool.get('budget.move')
        move_id = bud_move_obj.create(cr, uid, { 'type': 'expense' }, context=context)
        return move_id

    def expense_confirm(self, cr, uid, ids, context=None):
        bud_move_obj = self.pool.get('budget.move')
        for exp in self.browse(cr, uid, ids, context=context) :
            super(hr_expense_expense,self).expense_confirm(cr, uid, [exp.id], context=context)

            move_id = exp.budget_move_id.id
            self.write(cr, uid, [exp.id], {'budget_move_id' : move_id})

    def expense_canceled(self, cr, uid, ids, context=None):
        bud_move_obj = self.pool.get('budget.move')
        exp_id = super(hr_expense_expense,self).expense_canceled(cr, uid, ids, context=context)
        for expense in self.browse(cr, uid, ids, context=context):
            bud_move_obj.signal_workflow(cr, uid, [expense.budget_move_id.id], 'button_cancel', context=context)
            bud_move_obj.recalculate_values(cr, uid, [expense.budget_move_id.id], context=context)

    def expense_draft(self, cr, uid, ids, context=None):
        bud_move_obj = self.pool.get('budget.move')
        self.write(cr, uid, ids, {'state': 'draft'},context=context)
        for expense in self.browse(cr, uid, ids, context=context):
            if expense.budget_move_id:
                bud_move_obj.signal_workflow(cr, uid, [expense.budget_move_id.id], 'button_draft', context=context)
                bud_move_obj.signal_workflow(cr, uid, [expense.budget_move_id.id], 'button_reserve', context=context)
                bud_move_obj.recalculate_values(cr, uid, [expense.budget_move_id.id], context=context)

    def action_receipt_create(self, cr, uid, ids, context=None):
        mov_line_obj = self.pool.get('budget.move.line')
        bud_move_obj = self.pool.get('budget.move')
        acc_move_obj = self.pool.get('account.move')

        result = super(hr_expense_expense, self).action_receipt_create(cr, uid, ids, context=context)
        for exp in self.browse(cr, uid, ids, context=context):
            acc_move_id = exp.account_move_id.id
            acc_move_obj.write(cr , uid, [acc_move_id], {'budget_type': 'budget'}, context=context)
            for bud_mov_line in exp.budget_move_id.move_lines:
                mov_line_obj.write(cr, uid, [bud_mov_line.id], {'account_move_id' : acc_move_id}, context=context)
            bud_move_obj.signal_workflow(cr, uid, [exp.budget_move_id.id], 'button_compromise', context=context)
            bud_move_obj.signal_workflow(cr, uid, [exp.budget_move_id.id], 'button_execute', context=context)

            exp_lines = exp.line_ids
            taxes_per_line = self.tax_per_exp_line(cr, uid, exp_lines, context=context)
            acc_move = exp.account_move_id
            assigned_exp_lines = [] #list of associated expense lines with account move lines
            assigned_tax_exp_lines = [] #list of expense lines whose tax has been associated with account move lines
            for acc_move_line in acc_move.line_id:
                for exp_line in exp_lines:
                    exp_acc = exp_line.product_id.property_account_expense or exp_line.product_id.categ_id.property_account_expense_categ
                    exp_name = exp_line.name
                    exp_amount = exp_line.total_amount
                    acc_move_line_amount = abs(acc_move_line.debit - acc_move_line.credit) or abs(acc_move_line.amount_currency)

                    if exp_name.find(acc_move_line.name) != -1 and exp_amount == acc_move_line_amount and \
                    exp_acc.id == acc_move_line.account_id.id  and exp_line.id not in assigned_exp_lines:
                        bud_move_id = mov_line_obj.search(cr, uid, [('expense_line_id','=',exp_line.id)], context=context)[0]
                        if bud_move_id:
                            mov_line_obj.write(cr ,uid, [bud_move_id], {'move_line_id':acc_move_line.id})
                            assigned_exp_lines.append(exp_line.id)
                    if not acc_move_line.product_id:
                        if exp_line.id not in assigned_tax_exp_lines:
                            exp_line_taxes = taxes_per_line.get(exp_line.id,[])
                            for tax_amount in exp_line_taxes:
                                fixed_amount = abs(acc_move_line.debit - acc_move_line.credit) or abs(acc_move_line.amount_currency)
                                if fixed_amount == tax_amount:
                                    bud_line = mov_line_obj.create(cr, uid, {'budget_move_id': exp_line.expense_id.budget_move_id.id,
                                                 'origin' : _('Tax of: ') + exp_line.name[:54],
                                                 'program_line_id': exp_line.program_line_id.id,
                                                 'fixed_amount': abs(acc_move_line.debit - acc_move_line.credit) or abs(acc_move_line.amount_currency),
                                                 #'expense_line_id': line_id,
                                                 'move_line_id': acc_move_line.id,
                                                 'account_move_id': acc_move.id
                                                  }, context=context)
                                    assigned_tax_exp_lines.append(exp_line.id)

        return result

    def tax_per_exp_line(self, cr, uid, expense_lines, context=None):
        res = []
        tax_obj = self.pool.get('account.tax')
        cur_obj = self.pool.get('res.currency')
        mapping = {}

        if context is None:
            context = {}

        for line in expense_lines:
            exp = line.expense_id
            company_currency = exp.company_id.currency_id.id
            ###
            mres = self.move_line_get_item(cr, uid, line, context)
            if not mres:
                continue
            res.append(mres)
            ###
            tax_code_found= False

            #Calculate tax according to default tax on product
            taxes = []
            #Taken from product_id_onchange in account.invoice
            if line.product_id:
                fposition_id = False
                fpos_obj = self.pool.get('account.fiscal.position')
                fpos = fposition_id and fpos_obj.browse(cr, uid, fposition_id, context=context) or False
                product = line.product_id
                taxes = product.supplier_taxes_id
                #If taxes are not related to the product, maybe they are in the account
                if not taxes:
                    a = product.property_account_expense.id
                    if not a:
                        a = product.categ_id.property_account_expense_categ.id
                    a = fpos_obj.map_account(cr, uid, fpos, a)
                    taxes = a and self.pool.get('account.account').browse(cr, uid, a, context=context).tax_ids or False
                tax_id = fpos_obj.map_tax(cr, uid, fpos, taxes)
            if not taxes:
                continue
            #Calculating tax on the line and creating move?
            for tax in tax_obj.compute_all(cr, uid, taxes,
                    line.unit_amount ,
                    line.unit_quantity, line.product_id,
                    exp.user_id.partner_id)['taxes']:

                line_tax_amounts =[]

                tax_code_id = tax['base_code_id']
                tax_amount = line.total_amount * tax['base_sign']
                if tax_code_found:
                    if not tax_code_id:
                        continue
                    res.append(self.move_line_get_item(cr, uid, line, context))
                    res[-1]['price'] = 0.0
                    res[-1]['account_analytic_id'] = False
                elif not tax_code_id:
                    continue
                tax_code_found = True
                res[-1]['tax_code_id'] = tax_code_id
                res[-1]['tax_amount'] = cur_obj.compute(cr, uid, exp.currency_id.id, company_currency, tax_amount, context={'date': exp.date_confirm})
                ##
                is_price_include = tax_obj.read(cr,uid,tax['id'],['price_include'],context)['price_include']
                if is_price_include:
                    ## We need to deduce the price for the tax
                    res[-1]['price'] = res[-1]['price']  - (tax['amount'] * tax['base_sign'] or 0.0)
                assoc_tax = {
                             'type':'tax',
                             'name':tax['name'],
                             'price_unit': tax['price_unit'],
                             'quantity': 1,
                             'price':  tax['amount'] * tax['base_sign'] or 0.0,
                             'account_id': tax['account_collected_id'] or mres['account_id'],
                             'tax_code_id': tax['tax_code_id'],
                             'tax_amount': tax['amount'] * tax['base_sign'],
                             }
                line_tax_amounts.append(assoc_tax['tax_amount'])
                res.append(assoc_tax)
            mapping[line.id]=line_tax_amounts
        return mapping

    def on_change_currency(self, cr, uid, ids, currency_id, context=None):
        if ids:
            return {'value': {},
                    'warning':{'title':'Warning','message':'Budget uses the currency of the company, if you use other, you should change the unit price'}}
        else:
            return {'value': {}}

class hr_expense_line(osv.osv):
    _name = "hr.expense.line"
    _inherit = 'hr.expense.line'

    def on_change_program_line(self, cr, uid, ids, program_line, context=None):
        if program_line:
            for line in self.pool.get('budget.program.line').browse(cr, uid,[program_line], context=context):
                return {'value': {'line_available':line.available_budget},}
        return {'value': {}}

    def _check_no_taxes(self, cr, uid, ids, context=None):
        for line in self.browse(cr,uid,ids,context=context):
            product = line.product_id
            if product.supplier_taxes_id:
                return False
            if product.property_account_expense and product.property_account_expense.tax_ids:
                return False
            elif product.categ_id.property_account_expense_categ and product.categ_id.property_account_expense_categ.tax_ids:
                return False
        return True

    def _check_available(self, cr, uid, ids, field_name, args, context=None):
        bud_line_obj = self.pool.get('budget.move.line')
        result ={}
        if ids:
            for exp_line_id in ids:
                bud_line_ids = bud_line_obj.search(cr, uid, [('expense_line_id','=', exp_line_id)], context=context)
                for bud_line in bud_line_obj.browse(cr, uid,bud_line_ids, context=context):
                    result[exp_line_id] = bud_line.program_line_id.available_budget
        return result

    _columns = {'program_line_id': fields.many2one('budget.program.line', 'Program line', ),
                'line_available': fields.function(_check_available,  type='float', method=True, string='Line available',readonly=True),
                }

    _constraints=[
        (_check_no_taxes, 'Error!\n There is a tax defined for this product, its account or the account of the product category. \n The tax must be included in the price of the expense product.', []),
        ]

    def create_budget_move_line(self, cr, uid, line_id, context=None):
        exp_obj = self.pool.get('hr.expense.expense')
        exp_line_obj = self.pool.get('hr.expense.line')
        bud_move_obj = self.pool.get('budget.move')
        bud_line_obj = self.pool.get('budget.move.line')
        fixed_amount = 0.0
        expense_line = exp_line_obj.browse(cr, uid, [line_id], context=context)[0]
        expense = exp_obj.browse(cr, uid, [expense_line.expense_id.id], context=context)[0]
        move_id = expense.budget_move_id.id
        fixed_amount = expense_line.total_amount
        bud_line = bud_line_obj.create(cr, uid, {'budget_move_id': move_id,
                                         'origin' : expense_line.name,
                                         'program_line_id': expense_line.program_line_id.id,
                                         'fixed_amount': fixed_amount ,
                                         'expense_line_id': line_id,
                                          }, context=context)
        bud_move_obj.recalculate_values(cr, uid, [move_id], context=context)
        return bud_line

    def create(self, cr, uid, vals, context=None):
        bud_move_obj = self.pool.get('budget.move')
        exp_obj = self.pool.get('hr.expense.expense')
        exp_line_id = super(hr_expense_line,self).create(cr, uid, vals, context=None)
        exp_id = vals['expense_id']
        for expense in exp_obj.browse(cr, uid, [exp_id], context=context):
            if expense.budget_move_id:
                bud_line_id = self.create_budget_move_line(cr, uid, exp_line_id, context)
        return exp_line_id

    def write(self, cr, uid, ids, vals, context=None):
        bud_line_obj = self.pool.get('budget.move.line')
        bud_move_obj = self.pool.get('budget.move')
        write_result = True
        bud_line_dict = {}
        if 'unit_amount' in vals.keys() or 'program_line_id' in vals.keys() or 'name' in vals.keys():

            if 'unit_amount' in vals.keys():
                bud_line_dict['fixed_amount'] = vals['unit_amount']
            if 'program_line_id' in vals.keys():
                bud_line_dict['program_line_id'] = vals['program_line_id']
            if 'name' in vals.keys():
                bud_line_dict['origin'] = vals['name']

            for exp_line_id in ids:
                write_result = super(hr_expense_line,self).write(cr, uid, [exp_line_id], vals, context=None)
                bud_line_ids = bud_line_obj.search(cr, uid, [('expense_line_id','=',exp_line_id)])
                for bud_line in bud_line_obj.browse(cr, uid, bud_line_ids,context=context):
                    bud_line_obj.write(cr, uid, [bud_line.id], bud_line_dict, context=None)
                    result = bud_move_obj._check_values(cr, uid, [bud_line.budget_move_id.id], context=context)
                    if not result[0]:
                        raise osv.except_osv(_('Error!'), result[1])

        else:
            write_result=super(hr_expense_line,self).write(cr, uid, ids, vals, context=None)
        return write_result


#!/usr/bin/python

import json
from . import trello
import requests
import sys
from cork import Cork

def getBoards():
    url = 'https://api.trello.com/1/members/me{}'.format(trello.getSecurity())
    userJson = requests.get(url).json()

    url = 'https://api.trello.com/1/members/{}/boards{}'.format(userJson['id'],trello.getSecurity())
    response = requests.get(url)

    boards = response.json()
    print ('Please select a board id and add it to the config from the following list:')
    for board in boards:
        print (" * {}: {}".format(board['id'], board['name']))

def getLists(boardId):
    if not boardId:
        getBoards()
        raise EnvironmentError("Please select a board.")

    url = 'https://api.trello.com/1/boards/{}/lists{}&cards=none&fields=name'.format(boardId, trello.getSecurity())
    listsJson = requests.get(url).json()
    nameList = {}
    idList = {}
    for trelloList in listsJson:
        nameList[trelloList['name']] = trelloList['id']
        idList[trelloList['id']] = trelloList['name']

    return (nameList, idList) # return lists both ways, one with name as key and one id as a key

def getListDetail(boardId):
    url = 'https://api.trello.com/1/boards/{}/lists?cards=none&fields=all'.format(boardId)
    response = trello.get(url)
    #print(json.dumps(response.json(),indent=4))
    return response.json()

def addList(boardId, name):
    url = "https://api.trello.com/1/boards/{}/lists?name={}&pos=bottom".format(boardId, name)

    response = trello.post(url)
    if not response.ok:
        print ("Failed to add list due to {}: {}".format(response.status_code, response.text))

    return response

def getLabels(boardId):
    url = "https://api.trello.com/1/boards/{}/labels{}".format(boardId, trello.getSecurity())
    querystring = {"fields":"all","limit":"0"}
    response = requests.request("GET", url, params=querystring)

    labels = {}
    for label in response.json():
        labels[label['name']] = label['id']

    return labels

def getLabelDetail(boardId):
    url = "https://api.trello.com/1/boards/{}/labels?fields=all".format(boardId)
    response = trello.get(url)
    print(json.dumps(response.json(),indent=4))
    return response.json()

def addLabel(boardId, name, colour):
    url = "https://api.trello.com/1/boards/{}/labels?name={}&color={}".format(boardId, name, colour)

    response = trello.post(url)
    if not response.ok:
        print ("Failed to add label due to {}: {}".format(response.status_code, response.text))
    return response

if __name__ == "__main__":
    ## create user json
    board_id = '5c4adffeb3561e33298068b6'


# Optim SGD
# define the LeNet
import torch
from torch import nn
from torch.autograd import Variable

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 6, 5),
            nn.ReLU(),
            nn.MaxPool2d(2, 2),
            nn.Conv2d(6, 16, 5),
            nn.ReLU(),
            nn.MaxPool2d(2, 2)
        )

        self.classifier = nn.Sequential(
            nn.Linear(16*5*5, 120),
            nn.ReLU(),
            nn.Linear(120, 84),
            nn.ReLU(),
            nn.Linear(84, 10)
        )

    def forward(self, x):
        x = self.features(x)
        x = x.view(-1, 16*5*5)
        x = self.classifier(x)
        return x
net = Net()

from torch import optim
# the optim part
optimizer = optim.SGD(params=net.parameters(), lr=0.01)
optimizer.zero_grad() # equal to net.zero_grad()

input = Variable(torch.randn(1, 3, 32, 32))
output = net(input)
output.backward(output)

optimizer.step()

# set different learning rate for different parts of networks
optimizer = optim.SGD([
    {'params':net.features.parameters()}, # 学习率为1e-5
    {'params':net.classifier.parameters(), 'lr':1e-2}
], lr=1e-2)

# futher more
special_layers = nn.ModuleList([net.classifier[0],net.classifier[3]])
special_layers_params = list(map(id, special_layers.parameters()))
base_params = filter(lambda  p: id(p) not in special_layers_params, net.parameters())

optimizer = torch.optim.SGD([
    {'params':base_params},
    {'params':special_layers.parameters(), 'lr':0.01}
], lr=0.001)


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

import argparse
import logging
import typing as t
from importlib import import_module
from os import listdir, stat
from os.path import abspath, exists
from re import match
from stat import S_ISDIR

import flask
from magic import Magic

from .utils import json_answer

logging.basicConfig(format='')
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

class Core:
    def __init__(self, args: argparse.Namespace):
        self.app = flask.Flask(__name__)
        self.app.add_url_rule('/', view_func=self.index)
        self.app.add_url_rule(
            '/upload', view_func=self.upload, methods=['PUT'])
        self.app.add_url_rule('/download/<path:path>', view_func=self.download)

        # Параметры запуска.
        self.app.args = args
        self.host = args.host
        self.port = args.port
        self.debug = args.debug
        self.upload_dir = args.upload_dir
        self.middleware = args.middleware.replace(' ', '').split(',')

        # Регистрация middleware.
        self.import_middleware()

    def run(self) -> None:
        log.info(f' * Upload dir: {self.upload_dir}')
        self.app.run(host=self.host, port=self.port,
                     debug=self.debug, threaded=True)

    def import_middleware(self) -> None:
        """ Регистрация middleware. """
        # Регистрируем внешние middleware.
        middleware_list = []
        for middleware in self.middleware:
            result = match(r'(.*)\.(.*)', middleware)
            if result:
                module_name, func_name = result.groups()
                module = import_module(module_name)
                middleware_list.append(getattr(module, func_name))
        self.app.before_request_funcs = {None: middleware_list}

    def index(self) -> t.Union[flask.Response, str]:
        """ Возвращает список объектов. """
        path = abspath(self.upload_dir)
        magic = Magic(mime=True, uncompress=True)

        files = []
        for filename in listdir(path):
            filepath = f'{path}/{filename}'
            filestat = stat(filepath)
            if not S_ISDIR(filestat.st_mode):
                files.append({
                    'name': filename,
                    'size': filestat.st_size,
                    'modify_time': filestat.st_mtime,
                    'content_type': magic.from_file(filepath)
                })

        if flask.request.is_json:
            return json_answer(files)
        return flask.render_template('default.html', files=files)

    def upload(self) -> flask.Response:
        """ Загружает объект на сервер. """

        def gen(chunk_size: int = 8192) -> str:
            while True:
                chunk = flask.request.stream.read(chunk_size)
                if len(chunk) == 0:
                    break
                yield chunk

        buffer = bytes()
        for i in gen():
            buffer += i

        filename = flask.request.headers.get('X-Name')
        path = abspath(self.upload_dir)

        f = open(f'{path}/{filename}', mode='wb')
        f.write(buffer)
        f.close()

        return flask.Response("upload success")

    def download(self, path: str) -> flask.Response:
        """ Отдаёт содержимое объекта. """
        path = f'{abspath(self.upload_dir)}/{path}'

        if not exists(path):
            flask.abort(404)

        try:
            return flask.send_file(path)
        except Exception as error:
            flask.abort(flask.Response(str(error), 503))

def run(args: argparse.Namespace):
    """ Запуск веб-сервера. """
    server = Core(args)
    server.run()


#Enormous input test

#input
#n
#k

#output
#how many integers of n are divisible by k

n,k = map(int, input().split())
res = 0
for i in range(n):
    i = int(input())
    if i%k == 0:
        res += 1
print(res)


from PIL import Image
import imagehash
from bellutils.getfromdb import getfromdb
from tqdm import tqdm
import hashlib
import sqlite3

global md5
global PUF_GROESSE
md5 = hashlib.md5()
PUF_GROESSE = 1000000     # Puffergröße wird festgelegt

def hashfunc(pfad):

    datei = open("resized/" + pfad , "rb") # Datei wird geöffnet

    # Datei wird stückchenweise gelesen und in einen Hash convertiert
    # https://stackoverflow.com/questions/1131220/get-md5-hash-of-big-files-in-python
    while True:
        daten = datei.read(PUF_GROESSE)
        if not daten:
            break
        md5.update(daten)

    return md5.hexdigest() # hexadezimalzahl als String wird zurückgegeben

conn = sqlite3.connect("database.db")
c = conn.cursor()
c.execute("SELECT filename FROM artworks WHERE used = True AND corrupt = False")
pathlist = c.fetchall()

hashlist = []
duplicates = []
for p in tqdm(pathlist):
    hash = hashfunc(p[0])
    # print(hash)
    if hash in hashlist:
        duplicates.append(p)
        print("duplicate found")
    else:
        hashlist.append(hash)

print(duplicates)
print(len(hashlist))


"""
This file defines a set of built-in agents that can be used as opponent in
training and evaluation.

Usages:
Get policy (compute_action_function) by get_compute_action_function(agent_name)

Nothing you need to implement in this file, unless you wish to implement a
custom policy or introduce a custom agent as opponent in training and
evaluation.

-----
2019-2020 2nd term, IERG 6130: Reinforcement Learning and Beyond. Department
of Information Engineering, The Chinese University of Hong Kong. Course
Instructor: Professor ZHOU Bolei. Assignment author: PENG Zhenghao.
"""
from competitive_rl import make_envs

from core.ppo_trainer import PPOTrainer, ppo_config
from core.utils import FrameStackTensor

class PolicyAPI:
    """
    This class wrap an agent into a callable function that return action given
    an raw observation or a batch of raw observations from environment.

    This function maintain a frame stacker so that the user can securely use it.
    A reset function is provided so user can refresh the frame stacker when
    an episode is ended.

    Note that if you have implement other arbitrary custom agent, you are
    welcomed to implement a function-like API by yourself. You can write
    another API function or class and replace this one used in evaluation or
    even training.

    Your custom agent may have different network structure and different
    preprocess techniques. Remember that the API take the raw observation with
    shape (num_envs, 1, 42, 42) as input and return an single or a batch of
    integer(s) as action in [0, 1, 2]. Custom agent worth plenty of extra
    credits!
    """

    def __init__(self, num_envs=1, log_dir="", suffix=""):
        self.resized_dim = 42
        env = make_envs(num_envs=1, resized_dim=self.resized_dim)
        self.obs_shape = env.observation_space.shape
        self.agent = PPOTrainer(env, ppo_config)
        if log_dir:  # log_dir is None only in testing
            self.agent.load_w(log_dir, suffix)
        self.num_envs = num_envs
        self.frame_stack = FrameStackTensor(
            self.num_envs, self.obs_shape, 4, self.agent.device
        )

    def reset(self):
        # A potential bug is that, the frame stack is not properly reset in
        # a vectorized environment. We assume this will not impact the
        # performance significantly.
        self.frame_stack.reset()

    def __call__(self, obs):
        self.frame_stack.update(obs)
        action = self.agent.compute_action(self.frame_stack.get(), True)[1]
        if self.num_envs == 1:
            action = action.item()
        else:
            action = action.cpu().numpy()
        return action


def countAndSay(n: int) -> str:
    if n == 0 or n == 1:
        return "1"

    ss = ""
    s = countAndSay(n-1)
    pre = None
    count = 0
    for i, _s in enumerate(s):
        if not pre:
            pre = _s
            count += 1
        else:
            if _s != pre:
                ss += "{}{}".format(count, pre)
                pre = _s
                count = 1
            else:
                count += 1

    ss += "{}{}".format(count, pre)
    return ss

if __name__ == "__main__":
    n = 10
    print(countAndSay(n))


import torch
import torch.nn.functional as F
from torch import nn

class LuongAttention(nn.Module):
    def __init__(self, units: int):
        super().__init__()
        self.attn = nn.Linear(units, units, bias=False)

    def forward(self, hidden: torch.Tensor, encoder_outputs: torch.Tensor, mask: torch.Tensor, mask_value: float = -1e9) -> torch.Tensor:
        """Calculate attention weights

        :param hidden: [batch size; embedding size]
        :param encoder_outputs: [batch size; seq len; embedding size]
        :param mask: [batch size; seq len]
        :return: [batch size; seq len]
        """
        mask = mask.T
        batch_size, seq_len = mask.shape
        # [batch size; units]
        attended_hidden = self.attn(hidden)
        # [batch size; seq len]
        score = torch.bmm(encoder_outputs, attended_hidden.view(batch_size, -1, 1)).squeeze(-1)
        mask_atten = score.new_ones(score.size())*mask_value
        score = torch.where((mask==False), score, mask_atten)

        # [batch size; seq len]
        weights = F.softmax(score, dim=1)
        return weights

class LocalAttention(nn.Module):
    def __init__(self, units: int):
        super().__init__()
        self.attn = nn.Linear(units, 1, bias=False)

    def forward(self, encoder_outputs: torch.Tensor, mask: torch.Tensor, mask_value: float = -1e9) -> torch.Tensor:
        """Calculate attention weights

        :param encoder_outputs: [seq len; batch size; units]
        :param mask: [seq len; batch size]
        :return: [seq len; batch size; 1]
        """
        # [seq len; batch size; 1]
        attended_encoder_outputs = self.attn(encoder_outputs)
        mask_atten = attended_encoder_outputs.new_ones(attended_encoder_outputs.size())*mask_value
        attended = torch.where((mask.unsqueeze(2)==False), attended_encoder_outputs, mask_atten)

        # [seq len; batch size; 1]
        weights = torch.softmax(attended, dim=1)

        return weights


import streamlit.web.cli as stcli
import os, sys

def resolve_path(path):
    resolved_path = os.path.abspath(os.path.join(os.getcwd(), path))
    return resolved_path

if __name__ == "__main__":
    dir_home = os.path.dirname(__file__)

    # pip install protobuf==3.20.0

    sys.argv = [
        "streamlit",
        "run",
        resolve_path(os.path.join(dir_home,"greensight.py")),
        "--global.developmentMode=false",
        "--server.port=8519",

    ]
    sys.exit(stcli.main())


"""Unit tests the Statuses Module.

Classes:

    Test_Status: Unit tests the Status Class.
"""

from narcotics_tracker.items.statuses import Status

class Test_Status:
    """Unit tests the Status Class.

    Behaviors Tested:
        - Statuses class can be accessed.
        - Statuses return expected id.
        - Statuses return expected status_code.
        - Statuses return expected status_name.
        - Statuses return expected description.
        - Statuses return expected string.
        - Statuses return expected dictionary.
    """

    test_status = Status(
        table="statuses",
        id=-1,
        status_code="BROKEN",
        status_name="Broken",
        description="Used for testing purposes.",
        created_date=1666061200,
        modified_date=1666061200,
        modified_by="Systems",
    )

    def test_status_class_can_be_accessed(self) -> None:
        assert Status.__doc__ != None

    def test_status_returned_expected_id(self) -> None:
        assert self.test_status.id == -1

    def test_statuses_return_expected_status_code(self) -> None:
        assert self.test_status.status_code == "BROKEN"

    def test_statuses_return_expected_status_name(self) -> None:
        assert self.test_status.status_name == "Broken"

    def test_statuses_return_expected_description(self) -> None:
        assert self.test_status.description == "Used for testing purposes."

    def test_adjustments_return_expected_string(self) -> None:
        assert (
            str(self.test_status)
            == "Status #-1: Broken (BROKEN) Used for testing purposes."
        )

    def test_adjustments_return_expected_dictionary(self) -> None:
        assert vars(self.test_status) == {
            "table": "statuses",
            "id": -1,
            "created_date": 1666061200,
            "modified_date": 1666061200,
            "modified_by": "Systems",
            "status_code": "BROKEN",
            "status_name": "Broken",
            "description": "Used for testing purposes.",
        }


import time
import numpy as np
from pynx import scattering
from pynx.scattering import fthomson
from pandas import read_csv
from misc import rotate_coords, file_nb

def RSM(f_name, cation, anion, h, k, l, acryst, rot_angles, outpath, sublattices=False):
    # Read data file
    nb = file_nb(f_name)  # fluence = (nb+1)*0.0875
    coord = read_csv(f_name, delim_whitespace=True, header=None, names=["x", "y", "z", "Name"], skiprows=2)

    cat = cation[:-2]
    an = anion[:-2]
    print(cat,an)
    # Extract coordinates and convert to fractional
    xU = coord[coord.Name == cat].x.values / acryst
    yU = coord[coord.Name == cat].y.values / acryst
    zU = coord[coord.Name == cat].z.values / acryst
    xO = coord[coord.Name == an].x.values / acryst
    yO = coord[coord.Name == an].y.values / acryst
    zO = coord[coord.Name == an].z.values / acryst

    xU, yU, zU = rotate_coords(xU, yU, zU, rot_angles)
    xO, yO, zO = rotate_coords(xO, yO, zO, rot_angles)

    # Compute scattering for each sub-lattice
    print("Computing scattering for the cationic sub-lattice...")
    fhklU, dt = scattering.Fhkl_thread(h, k, l, xU, yU, zU, verbose=False, gpu_name="P5000", language="opencl")
    print("Computing time:", dt)
    print("Computing scattering for the anionic sub-lattice...")
    fhklO, dt = scattering.Fhkl_thread(h, k, l, xO, yO, zO, verbose=False, gpu_name="P5000", language="opencl")
    print("Computing time:", dt)

    # Compute atomic scattering factor for CuKa1
    print("Computing full scattering...")
    t0 = time.time()
    s = np.sqrt(h ** 2 + k ** 2 + l ** 2) / acryst
    fU = fthomson.f_thomson(s, cation)# - 4.173 + 13.418j
    fO = fthomson.f_thomson(s, anion) #+ 0.050 + 0.032j

    # Full scattering
    if sublattices:
        FU = fhklU * fU
        iU = (abs(FU) ** 2).sum(axis=1)
        FO = fhklO * fO
        iO = (abs(FO) ** 2).sum(axis=1)
        FUO2 = FU + FO
        iUO2 = (abs(FUO2) ** 2).sum(axis=1)
    else:
        FUO2 = fhklU * fU + fhklO * fO
        iUO2 = (abs(FUO2) ** 2).sum(axis=1)
        iU = 0
        iO = 0
    print("Computing time: %5.4f" %(time.time()-t0))
    # Save and plot
    print("Saving RSM data...")
    rotx, roty, rotz = rot_angles[0], rot_angles[1], rot_angles[2]
    np.savetxt(outpath + "RSM_UO2-"+str(rotx)+"-"+ str(roty)+"-"+str(rotz)+"."+str(nb), iUO2, fmt="%10.8f")
    if sublattices:
        np.savetxt(outpath + "RSM_U-"+str(rotx)+"-"+ str(roty)+"-"+str(rotz)+"."+str(nb), iU, fmt="%10.8f")
        np.savetxt(outpath + "RSM_O-"+str(rotx)+"-"+ str(roty)+"-"+str(rotz)+"."+str(nb), iO, fmt="%10.8f")

    return iUO2, iU, iO


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

from dataclasses import is_dataclass
from datetime import date, datetime, time
from enum import Enum
from inspect import isclass
from typing import (
    Any,
    Dict,
    Iterable,
    Mapping,
    MutableMapping,
    MutableSequence,
    Optional,
    Tuple,
    Type,
    TypeVar,
    Union,
    get_args,
    get_origin,
    get_type_hints,
)

from type_serialize.driver.numpy import (
    HAS_NUMPY,
    is_ndarray_subclass,
    numpy_deserialize,
)
from type_serialize.inspect.init_signature import required_init_parameters
from type_serialize.inspect.member import get_public_attributes
from type_serialize.inspect.types import (
    MAPPING_METHOD_ITEMS,
    MAPPING_METHOD_KEYS,
    SEQUENCE_METHOD_INSERT,
    compatible_iterable,
    is_none,
    is_serializable_pod_cls,
)
from type_serialize.obj.errors import DeserializeError
from type_serialize.obj.interface import DESERIALIZE_METHOD_NAME, is_deserialize_cls
from type_serialize.types.string.to_boolean import string_to_boolean

_T = TypeVar("_T")
_K = TypeVar("_K")
_V = TypeVar("_V")
_MM = TypeVar("_MM", bound=MutableMapping)
_MS = TypeVar("_MS", bound=MutableSequence)

FIRST_INDEX_KEY_STR = "0"
DEFAULT_ROOT_KEY = "<root>"

def _deserialize_interface(data: Any, cls: Type[_T]) -> _T:
    result = cls()
    getattr(result, DESERIALIZE_METHOD_NAME)(data)
    return result

def _deserialize_mapping_by_keys(
    data: Any,
    cls: Type[_MM],
    keys: Iterable[str],
    elem_hint: Optional[Any] = None,
) -> _MM:
    assert issubclass(cls, MutableMapping)
    result = cls()
    for key in keys:
        serialize_value = getattr(data, key, None)
        attr_cls = elem_hint if elem_hint else type(serialize_value)
        attr_value = _deserialize_any(serialize_value, attr_cls, key)
        setattr(result, key, attr_value)
    return result

def _deserialize_mapping_by_items(
    cls: Type[_MM],
    items: Iterable[Tuple[str, _V]],
    elem_hint: Optional[Any] = None,
) -> _MM:
    assert issubclass(cls, MutableMapping)
    result = cls()
    for key, serialize_value in items:
        attr_cls = elem_hint if elem_hint else type(serialize_value)
        attr_value = _deserialize_any(serialize_value, attr_cls, key)
        result.setdefault(key, attr_value)
    return result

def _deserialize_mapping(
    data: Mapping,
    cls: Type[_MM],
    elem_hint: Optional[Any] = None,
) -> _MM:
    assert issubclass(cls, MutableMapping)
    if hasattr(data, MAPPING_METHOD_ITEMS):
        items_func = getattr(data, MAPPING_METHOD_ITEMS)
        items = items_func()
        return _deserialize_mapping_by_items(cls, items, elem_hint)
    elif hasattr(data, MAPPING_METHOD_KEYS):
        keys_func = getattr(data, MAPPING_METHOD_KEYS)
        keys = keys_func()
        return _deserialize_mapping_by_keys(data, cls, keys, elem_hint)
    else:
        members = get_public_attributes(data)
        return _deserialize_mapping_by_items(cls, members, elem_hint)

def _deserialize_mapping_any(
    data: Mapping,
    cls: Type[_MM],
    elem_hint: Optional[Any] = None,
) -> _MM:
    assert issubclass(cls, MutableMapping)
    if isinstance(data, Mapping):
        return _deserialize_mapping(data, cls, elem_hint)
    elif compatible_iterable(data):
        mapping = {str(i): v for i, v in enumerate(data)}
        return _deserialize_mapping(mapping, cls, elem_hint)
    else:
        mapping = {FIRST_INDEX_KEY_STR: data}
        return _deserialize_mapping(mapping, cls, elem_hint)

def _deserialize_iterable(
    data: Iterable,
    cls: Type[_MS],
    elem_hint: Optional[Any] = None,
) -> _MS:
    assert issubclass(cls, MutableSequence)
    result = cls()
    if not hasattr(result, SEQUENCE_METHOD_INSERT):
        raise DeserializeError(f"Not found `{SEQUENCE_METHOD_INSERT}` method")

    for i, serialize_value in enumerate(data):
        attr_cls = elem_hint if elem_hint else type(serialize_value)
        attr_value = _deserialize_any(serialize_value, attr_cls, f"[{i}]")
        result.insert(len(result), attr_value)
    return result

def _deserialize_iterable_any(
    data: Any,
    cls: Type[_MS],
    elem_hint: Optional[Any] = None,
) -> _MS:
    assert issubclass(cls, MutableSequence)
    if compatible_iterable(data):
        return _deserialize_iterable(data, cls, elem_hint)
    else:
        return _deserialize_iterable([data], cls, elem_hint)

def _deserialize_data_to_dict(data: Any, cls: Type[_T]) -> Dict[str, Any]:
    result: Dict[str, Any] = dict()
    result_hints = get_type_hints(cls)
    for key, serialize_value in get_public_attributes(data):
        hint = result_hints.get(key)
        origin = get_origin(hint)

        if origin:
            attr_cls = origin
        elif hint:
            assert origin is None
            attr_cls = hint
        else:
            assert origin is None
            assert hint is None
            attr_cls = type(serialize_value)

        result[key] = _deserialize_any(serialize_value, attr_cls, key, hint)
    return result

def _deserialize_dataclass(data: Any, cls: Type[_T]) -> _T:
    deserialize_datas = _deserialize_data_to_dict(data, cls)
    return cls(**deserialize_datas)  # type: ignore[call-arg]

def _deserialize_object(data: Any, cls: Type[_T]) -> _T:
    result = cls()
    for key, value in _deserialize_data_to_dict(data, cls).items():
        setattr(result, key, value)
    return result

def _deserialize_any(
    data: Any,
    cls: Type[_T],
    key: Optional[str] = None,
    hint: Optional[Any] = None,
) -> Any:
    try:
        if data is None:
            return None

        type_origin = get_origin(hint)
        type_args = get_args(hint)
        assert isinstance(type_args, tuple)

        if type_origin is None:
            pass  # If there is no hint, it is deduced by the class.
        elif type_origin is Union:
            # Strip the Union hint.
            union_types = list(type_args)
            assert len(union_types) >= 2
            if type(None) in union_types:
                union_types.remove(type(None))
            if len(union_types) >= 2:
                raise DeserializeError("Two or more UNION types can not be deduced.")
            assert len(union_types) == 1
            return _deserialize_any(data, union_types[0], None, union_types[0])
        elif issubclass(type_origin, bytes):
            return bytes(data)
        elif issubclass(type_origin, bytearray):
            return bytearray(data)
        elif is_deserialize_cls(type_origin):
            return _deserialize_interface(data, type_origin)
        elif is_serializable_pod_cls(type_origin):
            return type_origin(data)
        elif issubclass(type_origin, MutableMapping):
            elem_type = None
            if len(type_args) == 2:
                elem_type = type_args[1]
            return _deserialize_mapping_any(data, type_origin, elem_type)
        elif issubclass(type_origin, MutableSequence):
            elem_type = None
            if len(type_args) == 1:
                elem_type = type_args[0]
            return _deserialize_iterable_any(data, type_origin, elem_type)

        # Deduced by class.

        if not is_none(cls) and cls is not Any:
            cls_origin = get_origin(cls)
            if cls_origin is not None:
                return _deserialize_any(data, cls_origin, key, cls)

            # [IMPORTANT]
            # Do not change if-else order (Reason: `issubclass(bool, int) == True`)
            if issubclass(cls, bytes):
                return bytes(data)
            elif issubclass(cls, bytearray):
                return bytearray(data)
            elif issubclass(cls, bool):
                if isinstance(data, str):
                    return string_to_boolean(data)
                else:
                    return bool(data)
            elif issubclass(cls, int):
                return int(data)
            elif issubclass(cls, float):
                return float(data)
            elif issubclass(cls, str):
                return str(data)
            elif HAS_NUMPY and is_ndarray_subclass(cls):
                if isinstance(data, (tuple, list)):
                    return numpy_deserialize(data)
                else:
                    src_type = f"`{type(data).__name__}` type"
                    dest_type = "`numpy.ndarray` type"
                    msg = f"{src_type} cannot be converted to {dest_type}."
                    raise DeserializeError(msg)
            elif issubclass(cls, datetime):
                if isinstance(data, float):
                    return datetime.fromtimestamp(data)
                elif isinstance(data, int):
                    return datetime.fromordinal(data)
                elif isinstance(data, str):
                    return datetime.fromisoformat(data)
                else:
                    src_type = f"`{type(data).__name__}` type"
                    dest_type = "`datetime` type"
                    msg = f"{src_type} cannot be converted to {dest_type}."
                    raise DeserializeError(msg)
            elif issubclass(cls, date):
                if isinstance(data, float):
                    return date.fromtimestamp(data)
                elif isinstance(data, int):
                    return date.fromordinal(data)
                elif isinstance(data, str):
                    return date.fromisoformat(data)
                else:
                    src_type = f"`{type(data).__name__}` type"
                    dest_type = "`date` type"
                    msg = f"{src_type} cannot be converted to {dest_type}."
                    raise DeserializeError(msg)
            elif issubclass(cls, time):
                if isinstance(data, str):
                    return time.fromisoformat(data)
                else:
                    src_type = f"`{type(data).__name__}` type"
                    dest_type = "`time` type"
                    msg = f"{src_type} cannot be converted to {dest_type}."
                    raise DeserializeError(msg)
            elif issubclass(cls, Enum):
                return cls(data)
            elif issubclass(cls, tuple):
                return cls(*data)
            elif is_deserialize_cls(cls):
                return _deserialize_interface(data, cls)
            elif issubclass(cls, MutableMapping):
                return _deserialize_mapping_any(data, cls)
            elif issubclass(cls, MutableSequence):
                return _deserialize_iterable_any(data, cls)
            elif is_dataclass(cls):
                return _deserialize_dataclass(data, cls)
            elif isclass(cls):
                if required_init_parameters(cls):
                    return _deserialize_dataclass(data, cls)
                else:
                    return _deserialize_object(data, cls)

        # Deduced by data.

        if isinstance(data, (bytes, bytearray, bool, int, float, str)):
            return data
        elif isinstance(data, Mapping):
            return _deserialize_mapping(data, dict)
        elif isinstance(data, Iterable):
            return _deserialize_iterable(data, list)
        elif isclass(type(data)):
            return _deserialize_object(data, dict)

        raise DeserializeError(
            f"The data(`{type(data)}`) and class(`{cls}`) are not compatible."
        )
    except DeserializeError as e:
        e.insert_first(key)
        raise
    except BaseException as e:
        raise DeserializeError(str(e), key) from e

def _deserialize_root(data: Any, cls: Type[_T], hint: Optional[Any] = None) -> _T:
    return _deserialize_any(data, cls, DEFAULT_ROOT_KEY, hint)

def deserialize(data: Any, cls_or_hint: Optional[Any] = None) -> Any:
    if cls_or_hint is None:
        origin = get_origin(type(data))
        if origin is None:
            return _deserialize_root(data, type(data))
    else:
        origin = get_origin(cls_or_hint)
        if origin is None:
            return _deserialize_root(data, cls_or_hint)

    assert origin is not None

    if origin is Union:
        # Strip the Union hint.
        type_args = get_args(cls_or_hint)
        union_types = list(type_args)
        assert len(union_types) >= 2
        if type(None) in union_types:
            union_types.remove(type(None))
        if len(union_types) >= 2:
            raise DeserializeError("Two or more UNION types can not be deduced.")
        assert len(union_types) == 1
        return _deserialize_root(data, union_types[0], union_types[0])

    elif issubclass(origin, list):
        # maybe typing.List[_V]
        return _deserialize_root(data, list, cls_or_hint)
    elif issubclass(origin, dict):
        # maybe typing.Dict[_K, _V]
        return _deserialize_root(data, dict, cls_or_hint)
    else:
        raise TypeError(f"Unsupported origin: {origin.__name__}")


import os
from warnings import warn
from collections.abc import Mapping
from .. import yaml_io
import numpy as np

from .. Error import GroupMissingDataError
from . Group import Group, Descriptor
from . Scheme import GroupAdditivityScheme
from . DataDir import get_data_dir

class GroupLibrary(Mapping):
    """Represent library of contributing properties organized by group.

    The set of properties that may be represented in a :class:`GroupLibrary` is
    extensible.  Contributing properties are represented by *property sets*
    organized by group.  See the manual for a list of available property sets.

    .. note::
        Because the *property set* system is extensible, the module within
        which a particular *property set* is defined and registered must be
        imported before loading a group library that contains data for that
        type of *property set*.

    To estimate properties, call :meth:`GroupLibrary.estimate()` with the
    *property set* `name` and  set of groups contained in the chemical
    structure of interest.  The properties estimate will be returned as an
    object whose type depends on the particular *property set*.

    To determine which groups are present in a particular chemical structure,
    use :meth:`GroupLibrary.match_groups()`.

    Data in multiple group libraries can be combined so long as the groups
    they contain are defined within compatible schemes.  See
    :meth:`GroupLibrary.update()`.

    """
    _property_set_estimator_types = {}
    _property_set_group_yaml_types = {}

    @classmethod
    def register_property_set_type(cls, name, group_yaml_type, estimator_type):
        """(class method) Register new property set type.

        Parameters
        ----------
        name : str
            Name of new property set type.
        group_yaml_type : str
            Name of property set type in the YAML type namespace.
        estimator_type : class
            The provided class is instantiated when an estimate is to be made
            for a particular set of groups.  The constructor should accept the
            following parameters:

                library : :class:`GroupLibrary`
                    library which is to be used to estimate these properties.
                groups : mapping
                    Map from :class:`Group` to int or float specifying counts
                    of each group in the chemical structure.
        """
        if name in cls._property_set_group_yaml_types:
            raise KeyError('Property set %r already registered.' % name)
        cls._property_set_group_yaml_types[name] = group_yaml_type
        cls._property_set_estimator_types[name] = estimator_type

    def __init__(self, scheme, contents={}, uq_contents={}, path=None):
        """Initialize library of contributing properties organized by group.

        Parameters
        ----------
        scheme : :class:`GroupScheme`
            Specify group-additivity scheme to use.
        contents : mapping or list
            Define initial contents of the library either as mapping or list of
            (`key`, `value`) pairs.  See the last paragraph of the class
            documentation for information on the format.

        Other Parameters
        ----------------
        path : str
            File-system path library was loaded from or should be saved to by
            default.
        """
        self.scheme = scheme
        self.path = path
        if isinstance(contents, Mapping):
            contents = list(contents.items())
        self.contents = dict((group, property_sets)
                             for (group, property_sets) in contents)
        self.uq_contents = uq_contents

    def GetDescriptors(self, mol):
        """Determine groups appearing in chemical structure `chem`.

        Parameters
        ----------
        mol : :class:`rdkit.mol`
            Specify chemical structure to match groups for.
        manual_descriptors : mapping, optional
            Specify value(s)/degree(s) of influence of additional descriptors
            to include.

        Returns
        -------
        groups : mapping
            Map from :class:`Group` to int or float identifying groups and
            their number of occurence in the structure.
        """
        self.name = mol
        return self.scheme.GetDescriptors(mol)

    def Estimate(self, groups, property_set_name):
        """Estimate set of properties for chemical.

        Parameters
        ----------
        groups : mapping (dictionary)
            Map from :class:`Group` to int or float specifying counts of each
            group in the chemical structure.
        property_set_name : str
            Name of property set to estimate.

        Returns
        -------
        estimated_properties : (varies)
            The estimated properties, an object whose type depends on the
            particular property set.
        """
        if property_set_name not in self._property_set_estimator_types:
            raise KeyError('Invalid property_set name: %r' % property_set_name)
        # Verify groups present.
        missing_groups = [group for group in groups
                          if property_set_name not in self[group]]
        if missing_groups:
            raise GroupMissingDataError(missing_groups, property_set_name)
        estimator_type = self._property_set_estimator_types[property_set_name]
        return estimator_type(self, groups)

    def __contains__(self, group):
        """Test if this library contains contributing properties for `group`.

        Parameters
        ----------
        group : :class:`Group`
            Group whose membership is being tested.

        Returns
        -------
        result : bool
            True if this library has properties for `group`.
        """
        return group in self.contents

    def __iter__(self):
        """Return iterator over all groups with property data in this library.
        """
        return iter(self.contents)

    def __len__(self):
        """Return number of groups with properties in this library."""
        return len(self.contents)

    def __getitem__(self, group):
        """Return contributing properties sets for `group`.

        If no properties exist for `group`, then return ``{}`` instead of
        raising an exception.

        Parameters
        ----------
        group : :class:`Group`
            Identify group whose property sets are to be retrieved.

        Returns
        -------
        property_sets : dict
            Sets of contributing properties for `group`.
        """
        return self.contents.get(group, {})

    @classmethod
    def Load(cls, path):
        """(class method) Load group-additivity library from file-system
        `path` or builtin.

        Parameters
        ----------
        path : str
            Specify either the path to a file containing the data or a symbolic
            name of a builtin library to load (*e.g.* ``gas_benson`` to load
            gas phase Benson groups.)

        Returns
        -------
        lib : :class:`GroupLibrary`
            Group library containing the loaded data.
        """
        if os.sep not in path and '.' not in path and not os.path.exists(path):
            # [JTF] where's our data directory?
            base_path = os.path.join(get_data_dir(), path)
            # We want to load the library.yaml in that directory:
            path = os.path.join(base_path, 'library.yaml')
        else:
            # The base path is the directory containing whatever file/directory
            # is referenced by path:
            base_path = os.path.dirname(path)

        # Load the scheme.yaml from the selected data directory:
        scheme = GroupAdditivityScheme.Load(os.path.join(base_path,
                                                         'scheme.yaml'))

        # Use that scheme to load the rest of the library:
        return cls._do_load(path, base_path, scheme)

    @classmethod
    def _Load(cls, path, scheme):
        if os.sep not in path and '.' not in path and not os.path.exists(path):
            # [JTF] where's our data directory?
            base_path = os.path.join(get_data_dir(), path)
            # We want to load the library.yaml in that directory:
            path = os.path.join(base_path, 'library.yaml')
        else:
            # The base path is the directory containing whatever file/directory
            # is referenced by path:
            base_path = os.path.dirname(path)

        # Use the scheme passed to us to load the rest of the library:
        return cls._do_load(path, base_path, scheme)

    @classmethod
    def _do_load(cls, path, base_path, scheme):
        # Read data from file.
        context = {'base_path': base_path}
        with open(path) as f:
            lib_data = yaml_io.load(
                yaml_io.parse(f.read()), context, loader=cls._yaml_loader)

        context['units'] = lib_data.units

        group_properties = lib_data.groups
        other_descriptor_properties = lib_data.other_descriptors
        UQ = lib_data.UQ

        if cls._property_set_group_yaml_types:
            # Prepare property_sets loader.
            property_sets_loader = yaml_io.make_object_loader(yaml_io.parse(
                '\n'.join(('%r:\n    type: %r\n    optional: true'
                          % (str(name),
                             str(cls._property_set_group_yaml_types[name])))
                          for name in cls._property_set_group_yaml_types)))
            # Read all properties.
            lib_contents = {}
            for name in group_properties:
                group = Group.parse(scheme, name)
                if group in lib_contents:
                    raise KeyError('Multiple definitions of group %s' % group)
                property_sets = yaml_io.load(
                    group_properties[name], context,
                    loader=property_sets_loader)
                lib_contents[group] = property_sets
            for name in other_descriptor_properties:
                descriptor = Descriptor(scheme, name)
                if descriptor in lib_contents:
                    raise KeyError('Multiple definitions of descriptor %s' %
                                   descriptor)
                property_sets = yaml_io.load(
                    other_descriptor_properties[name], context,
                    loader=property_sets_loader)
                lib_contents[descriptor] = property_sets

            # Read UQ data
            uq_contents = {}
            if UQ:
                uq_contents['RMSE'] = yaml_io.load(
                    UQ['RMSE'], context,
                    loader=property_sets_loader)
                uq_contents['descriptors'] = UQ['InvCovMat']['groups']
                uq_contents['mat'] = np.array(UQ['InvCovMat']['mat'])
                uq_contents['dof'] = UQ['DOF']
        else:
            # No property sets defined.
            warn('GroupLibrary.load(): No property sets defined.')
            lib_contents = {}
            uq_contents = {}

        new_lib = cls(scheme, lib_contents, uq_contents, path=path)
        # Update with included content.
        for include_path in lib_data.include:
            new_lib.Update(cls._Load(os.path.join(base_path,
                                                  include_path), scheme))
        return new_lib

    def Update(self, lib, overwrite=False):
        """Add complete contents of `lib` into this library.

        Parameters
        ----------
        lib : :class:`GroupLibrary`
            Library to import from.
        overwrite : bool
            If True, then existing data may be overwritten by data from `lib`.
        """
        for (group, other_property_sets) in list(lib.items()):
            if group not in self.contents:
                self.contents[group] = {}
            property_sets = self.contents[group]

            for name in other_property_sets:
                if name not in property_sets:
                    property_sets[name] = other_property_sets[name].copy()
                else:
                    property_sets[name].update(
                        other_property_sets[name], overwrite)
        # UQ stuff can only be loaded once
        if self.uq_contents and lib.uq_contents:
            raise ValueError('More than one uncertainty quantification',
                             'information provided')
        if not self.uq_contents:
            self.uq_contents = lib.uq_contents
    _yaml_loader = yaml_io.make_object_loader(yaml_io.parse("""
units:
    type: mapping
    default: {}

include:
    type: list
    item_type: string
    default: []

groups:
    type: mapping
    default: {}

other_descriptors:
    type: mapping
    default: {}

UQ:
    type: mapping
    default: {}
"""))


#!/usr/bin/env python
import cv2
import torch
import random

import rospy

from cv_bridge import CvBridge

from ultralytics import RTDETR

from sensor_msgs.msg import Image
from vision_msgs.msg import Detection2D
from vision_msgs.msg import ObjectHypothesisWithPose
from vision_msgs.msg import Detection2DArray
from std_srvs.srv import SetBool

class RT_DETR():

    def __init__(self) -> None:

        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        # params
        # self.model = rospy.get_param("model", "rtdetr-l.pt")

        # self.img_topic = rospy.get_param("img_topic", "/airsim_node/Drone_1/camera_1/Scene")

        # self.threshold = rospy.get_param("threshold", 0.5)

        # self.enable = rospy.get_param("enable", True)

        # # params
        self.model1 = "rtdetr-l.pt"
        self.model2 = "rtdetr-x.pt"
        self.bool_rtdetr_l = True

        self.img_topic = "/airsim_node/Drone_1/camera_1/Scene"

        self.threshold =  0.5

        self.enable =  True

        self._class_to_color = {}
        self.cv_bridge = CvBridge()
        if self.bool_rtdetr_l:
            self.rtdetr = RTDETR(self.model1)

        else:
            self.rtdetr = RTDETR(self.model2)

        rospy.sleep(1)

        # topics
        self._pub = rospy.Publisher("detections",Detection2DArray, queue_size= 10)
        self._detection_image_pub = rospy.Publisher("detection_image", Image, queue_size= 10)
        rospy.sleep(1)
        self._sub = rospy.Subscriber(self.img_topic, Image, self.image_cb)

        self.coco_names = {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck',
                           8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird',
                           15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe',
                           24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard',
                           32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard',
                           38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl',
                           46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza',
                           54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet',
                           62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven',
                           70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear',
                           78: 'hair drier', 79: 'toothbrush'}

    def image_cb(self, msg: Image) -> None:

        if self.enable:

            # convert image + predict
            cv_image = self.cv_bridge.imgmsg_to_cv2(msg)

            results = self.rtdetr.predict(source = cv_image, verbose = False, show = False, save = False)

            # create detections msg
            detections_msg = Detection2DArray()
            detections_msg.header = msg.header

            results = results[0].cpu()

            for b in results.boxes:

                label = self.coco_names[int(b.cls)]
                score = float(b.conf)

                if score < self.threshold:
                    continue

                detection = Detection2D()

                detection.header = msg.header

                detection.source_img = msg

                box = b.xywh[0]

                # get boxes values
                detection.bbox.center.x = float(box[0])
                detection.bbox.center.y = float(box[1])
                detection.bbox.size_x = float(box[2])
                detection.bbox.size_y = float(box[3])

                # get track id
                track_id = 0
                if not b.id is None:
                    track_id = int(b.id)
                #detection.id = track_id

                # get hypothesis
                hypothesis = ObjectHypothesisWithPose()
                hypothesis.id = int(b.cls)
                hypothesis.score = score
                detection.results.append(hypothesis)

                # draw boxes for debug
                if label not in self._class_to_color:
                    r = random.randint(0, 255)
                    g = random.randint(0, 255)
                    b1 = random.randint(0, 255)
                    self._class_to_color[label] = (r, g, b1)
                color = self._class_to_color[label]

                min_pt = (round(detection.bbox.center.x - detection.bbox.size_x / 2.0),
                          round(detection.bbox.center.y - detection.bbox.size_y / 2.0))
                max_pt = (round(detection.bbox.center.x + detection.bbox.size_x / 2.0),
                          round(detection.bbox.center.y + detection.bbox.size_y / 2.0))
                cv_image = cv2.rectangle(cv_image, min_pt, max_pt, color, 2)

                label = "{}:({}) {:.3f}".format(label, str(track_id), score)
                pos = (min_pt[0], max(15, int(min_pt[1] - 10)))
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv_image = cv2.putText(cv_image, label, pos, font,
                            0.5, color, 1, cv2.LINE_AA)

                # append msg
                detections_msg.detections.append(detection)

            # publish detections and dbg image
            self._pub.publish(detections_msg)

            self._detection_image_pub.publish(self.cv_bridge.cv2_to_imgmsg(cv_image,
                                                            encoding=msg.encoding))
            cv2.imshow("Real-Time Detection with RTDETR",cv_image)
            cv2.waitKey(1)

            if rospy.is_shutdown():
                cv2.destroyAllWindows()

if __name__ == "__main__":
    rospy.init_node("RTDETR_Sea", anonymous= True)
    RT_DETR()
    rospy.spin()


# returns index of array/list that add up to target
# Approach used -> HashMap (Dict)
nums = [2,1,3,5]
target = 4

def twoSum(nums, target):
    prevMap = {}  # Hashmap with val -> index

    for i, n in enumerate(nums):
        diff = target - n
        if diff in prevMap:
            return [prevMap[diff], i]
        prevMap[n] = i
    return []

print(twoSum(nums,target))


from django.db import models
from django.conf import settings
from django.core.validators import MinValueValidator

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Categories"

class Drink(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    price = models.FloatField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Order(models.Model):
    customer_name = models.CharField(max_length=128, default="guest")
    order_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    drinks = models.ManyToManyField(
        Drink,
        through='OrderDrink',
        through_fields=('order', 'drink')
    )

    def __str__(self):
        return f'{self.id} - {self.customer_name}'

class OrderDrink(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    drink = models.ForeignKey(Drink, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1, validators=[MinValueValidator(1)])
    item_price = models.FloatField(null=True)
    total_price = models.FloatField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if self.drink is not None:
            self.item_price = self.drink.price
            self.total_price = self.item_price * self.quantity
        super().save(force_insert, force_update, using, update_fields)


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from .serializers import CategorySerializer, ProductSerializer
from .models import Category, Product
from .paginations import CustomPagination

class ListCategories(APIView):

    permission_classes = [permissions.BasePermission]

    def get(self, request, format=None):
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        return Response({"results": serializer.data}, status=200)

class ListProducts(APIView, CustomPagination):

    #authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.BasePermission]
    serializer_class = ProductSerializer
    pagination_class = CustomPagination

    def get(self, request, format=None):
        if request.GET.get('categoryId') is not None:
            category_id = request.GET.get('categoryId')
            try:
                category_id = int(category_id)
            except ValueError:
                return Response({"error": "categoryId invalid"}, status=400)
            products = Product.objects.filter(categoryId=category_id).order_by('id')
        else:
            products = Product.objects.all().order_by('id')
        results = self.paginate_queryset(products, request, view=self)
        serializer = ProductSerializer(results, many=True)
        return self.get_paginated_response(serializer.data)


def strobogrammaticInRange(low, high):
    pairs = [('8','8'), ('1','1'), ('0','0'), ('6','9'), ('9','6')]
    count = 0
    def dfs(low, high, left, right, s):
        ins = int(''.join(s))
        if (left > right):
            if low <= ins <= high:
                self.count += 1
            return
        for x, y in pairs:
            if len(s) != 1 and left == 0 and x == '0': continue
            if left == right and x != y: continue
            s[left] = x
            s[right] = y
            dfs(low, high, left + 1, right - 1,s)

    for i in range(len(low), len(high)+1):
        s = ['0'] * i #initiate an array to store the number
        dfs(int(low), int(high), 0, i - 1, s)
    return count


import time
import numpy as np
import pandas as pd
import scipy as sp
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import accuracy_score, roc_auc_score
from Utils import pickle

np.random.seed(123)
time_0 = time.time()

X_train = sp.sparse.load_npz("Objects/X_train.npz")  # [1000:1050,:40]
Y_train = np.load("Objects/Y_train.npy")  # [1000:1050]

X_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size=0.5, random_state=456)
#X_test = sp.sparse.load_npz("Objects/X_train.npz")[3000:3050,:40]
#Y_test = np.load("Objects/Y_train.npy")[3000:3050]

num_tasks = Y_train.shape[1]
time_1 = time.time()
classifier = OneVsRestClassifier(LinearSVC())
classifier.fit(X_train, Y_train)
time_2 = time.time()

results = {}
results.update({"train_time": time_2-time_1})
pred = classifier.predict(X_train)
results.update({"acc": np.array([accuracy_score(Y_train[:,i], pred[:,i]) for i in range(num_tasks)])})
results.update({"acc_mean": np.mean(results["acc"])})
results.update({"roc": np.array([roc_auc_score(Y_train[:,i], pred[:,i]) for i in range(num_tasks)])})
results.update({"roc_mean": np.mean(results["roc"])})
pred = classifier.predict(X_test)
results.update({"val_acc": np.array([accuracy_score(Y_test[:,i], pred[:,i]) for i in range(num_tasks)])})
results.update({"val_acc_mean": np.mean(results["val_acc"])})
results.update({"val_roc": np.array([roc_auc_score(Y_test[:,i], pred[:,i]) for i in range(num_tasks)])})
results.update({"val_roc_mean": np.mean(results["val_roc"])})

#nrows = 10
X_test = sp.sparse.load_npz("Objects/X_test.npz")  # [:nrows,:X_train.shape[1]]
Y_test = classifier.predict(X_test)
submission = pd.read_csv("../Data/sample_submission.csv")  # , nrows=nrows)
submission.iloc[:,1:] = Y_test
submission.to_csv("Objects/submission.csv", index=False)

results.update({"script_time": time.time()-time_0})

pickle.save("Objects/results.dict", results)


import socket
import tqdm
import os

SERVER_HOST = socket.gethostbyname(socket.gethostname())
SERVER_PORT = 50002
SEPARATOR = "<1111>"
BUFFER_SIZE = 4096

s= socket.socket()

s.bind((SERVER_HOST, SERVER_PORT))

s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
conn, addr = s.accept()
print(f"[+] {addr} is connected.")

received = conn.recv(BUFFER_SIZE).decode()
print(received)
filename, filesize = received.split(SEPARATOR)

filename = os.path.basename(filename)

filesize = int(filesize)
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)

with open("C:/Users/huy123/OneDrive/Desktop/file_server/"+filename,"wb") as f:
	while True:
		bytes_read = conn.recv(BUFFER_SIZE)
		if not bytes_read:
			break
		f.write(bytes_read)
		progress.update(len(bytes_read))

conn.close()
s.close()