import struct
import math
import mathutils

UINT32 = {"format": "<L", "size": 4}
SINT32 = {"format": "<l", "size": 4}
UINT16 = {"format": "<H", "size": 2}
SINT16 = {"format": "<h", "size": 2}
FLOAT  = {"format": "<f", "size": 4}
BYTE  = {"format": "b", "size": 1}

class Vertex_Data:
    def __init__(self):
        self.references = []
        self.uv_pos = []
        self.pos = None
        self.normals = []
        self.bones = []
        self.bone_offsets = {}
        self.bone_weights = {}

class Bone_Data:
    def __init__(self):
        self.parent = None
        self.name = ""
        self.transform = None
        self.pos = None
        self.local_pos = None
        self.local_transform = None
        self.vertices = []
        self.vertex_offsets = []
        self.vertex_weights = []
        self.children = []

class Model_Data: # used for both SMS and MDL files since they have similar formats
    def __init__(self):
        self.texture_names = {}
        self.material_names = {}
        self.object_names = []
        self.user_data = {}
        self.uvs = []
        self.vertices = []
        self.triangles = []
        self.materials = []
        self.textures = []
        self.normals = []
        self.vertex_colors = []
        self.uv_references = []
        self.normal_references = []
        self.vertex_references = []

        self.active_object = None
        self.active_mesh = None

        self.model_scale = 1.0
        self.object_count = 0
        self.lights_count = 0
        self.points_count = 0
        self.paths_count = 0
        self.material_count = 0
        self.texture_count = 0
        self.total_vertex_count = 0
        self.total_face_count = 0

        #SMS stuff
        self.tag_count = 0
        self.version = ""
        self.tag_names = []
        self.tag_user_data = []
        self.bones = []
        self.vertex_dict = {}
        return

class Reader:
    def __init__(self, p_input):
        self.file_position = 0
        self.txt_data = p_input
        self.mdl_data = Model_Data()
        self.show_logs = True

    def read_num(self, p_type = UINT32):
        output = []
        for i in range(p_type["size"]):
            output.append(self.txt_data[self.file_position + i])

        self.file_position += p_type["size"]
        output = struct.unpack(p_type["format"], bytes(output))[0]
        if self.show_logs:
            print("Read " + str(p_type["size"]) + " bytes: " + str(output))
        return output

    def read_str(self, p_delim = '\0'):
        output = ""
        current_char = None
        while current_char != p_delim:
            current_char = bytes([self.txt_data[self.file_position]]).decode("utf-8")
            output += current_char
            self.file_position += 1
        if self.show_logs:
            print("Read string:", output)
        return output

    def read_block(self, p_len):
        output = ""
        current_char = None
        for i in range(p_len):
            current_char = bytes([self.txt_data[self.file_position]]).decode("utf-8")
            output += current_char
            self.file_position += 1
        print("Read block: " + output + "(len", len(output), ")")
        return output

class Writer:
    def __init__(self, p_context):
        self.txt_data = [] #bytes([])
        self.pos = 0 #position in txt_data in bytes
        self.context = p_context
        self.mdl_data = Model_Data()

    def FILE_END(self):
        return len(self.txt_data)

    def extend(self, p_len):
        self.txt_data += [0 for i in range(p_len)]

    def seek(self, p_pos):
        if p_pos > self.FILE_END():
            self.extend(p_pos - self.FILE_END())
        self.pos = p_pos

    def write(self, p_content):
        self.txt_data[self.pos:self.pos+(len(p_content))] = p_content
        self.pos += len(p_content)

    def write_num(self, p_input, p_type = UINT32):
        print("Writing ", p_input)
        output = struct.pack(p_type["format"], p_input)
        #if self.pos == self.FILE_END():
        #    self.extend(len(output))
        self.write(output)
        print("Wrote " + str(p_type["size"]) + " bytes: " + str(list(output)))

    def write_str(self, p_input, term = True):
        if term:
            p_input += '\0'
        output = p_input.encode("utf-8")
        self.write(list(output))
        print("Wrote string: " + str(output) + " of length", len(output))

def clamp(p_num, p_min=-1.0, p_max=1.0):
    if p_num <= p_min:
        return p_min
    elif p_num >= p_max:
        return p_max
    return p_num

def compress_normal(p_x, p_y, p_z):
    multiplier = (3.14159 / 255.0) * 2.0
    alpha = math.acos(p_y)
    AU = math.floor(alpha / multiplier)
    beta = math.acos(clamp(p_x / math.sin(alpha)))
    AV = math.floor(beta / multiplier)
    return AU, AV

def decompress_normal(AU, AV):
    multiplier = (3.14159 / 255.0) * 2.0 # convert from 0-255 to radians
    alpha = AU * multiplier
    beta = AV * multiplier
    x = math.cos(beta) * math.sin(alpha)
    y = math.cos(alpha)
    z = math.sin(beta) * math.sin(alpha)
    return x, y, z

def approx(p_input, p_precision = 0.02):
    rounded_input = round(p_input)
    if abs(rounded_input - p_input) < p_precision:
        return rounded_input
    return p_input

#def sort_vector(p_bone_vec):
#    vec = p_bone_vec.to_tuple()
#    absvec = (abs(vec[0]), abs(vec[1]), abs(vec[2]))
#    x, y, z = 0,0,0
#    y = vec[abs_vec.index(max(absvec))]

def get_axis(p_vector):
    vec = p_vector.to_tuple()
    axis = vec.index(max(vec))
    return axis

bone_export_order = [
    "malePlayer01_Root Spine2",
    "malePlayer01 R UpperArm",
    "malePlayer01 Spine1",
    "malePlayer01 R ForeArm",
    "malePlayer01 R Hand",
    "malePlayer01 Pelvis",
    "malePlayer01 Spine",
    "malePlayer01 R Thigh",
    "malePlayer01 R Clavicle",
    "malePlayer01 L Thigh",
    "malePlayer01 L UpperArm",
    "malePlayer01 Neck",
    "malePlayer01 L Clavicle",
    "malePlayer01 Head",
    "malePlayer01 L ForeArm",
    "malePlayer01 L Hand",
    "malePlayer01_Root"
]

#def convert_matrix(p_matrix):
#    mat_copy = p_matrix.copy()
#    mat_copy[2] *= -1
#    #for i in range(len(mat_copy)):
#    #    mat_copy[i][i] *= -1
#    return mat_copy

##this class is meant to allow for easy conversions between two
##-sets of values, e.g names to indices, and vice versa.
##-this way they can be accessed by either
#class Double_Dict:
#    def __init__(self, p_id1=1, p_id2=2):
#        self.id1 = p_id1
#        self.id2 = p_id2
#        self.dict1 = {}
#        self.dict2 = {}
#    def get_item(self, p_dict_id, p_item_key):
#        if p_dict_id == self.id1:
#            return self.dict2[p_item_key]
#        elif p_dict_id == self.id2:
#            return self.dict1[p_item_key]
#        else:
#            return None
#    def set_item(self, p_value1, p_value2):
#        self.dict1[p_value2] = p_value1
#        self.dict2[p_value1] = p_value2
#


from gnuradio_core import *
from exceptions import *
#from hier_block2 import *
#from top_block import *
from gateway import basic_block, sync_block, decim_block, interp_block
from tag_utils import tag_to_python, tag_to_pmt

import gras

RT_OK = 0
RT_NOT_IMPLEMENTED = 1
RT_NO_PRIVS = 2
RT_OTHER_ERROR = 3

def enable_realtime_scheduling():
    """
    This call is for backward compat purposes.
    See gras/thread_pool.hpp for greater options.
    """

    #any prio greater than 0 means realtime scheduling
    prio_value = 0.5

    #test that prio
    if not gras.ThreadPool.test_thread_priority(prio_value):
        return RT_NO_PRIVS

    #create a new thread pool with thread priority set
    config = gras.ThreadPoolConfig()
    config.thread_priority = prio_value
    tp = gras.ThreadPool(config)
    tp.set_active()

    return RT_OK

class top_block(gras.TopBlock):
    def __init__(self, name="Top"):
        gras.TopBlock.__init__(self, name)

    def lock(self):
        pass

    def unlock(self):
        self.commit()

    def start(self, *args):
        if args: self.global_config().maximum_output_items = args[0]
        gras.TopBlock.start(self)

    def run(self, *args):
        if args: self.global_config().maximum_output_items = args[0]
        gras.TopBlock.run(self)

class hier_block2(gras.HierBlock):
    def __init__(self, name="Hier", in_sig=None, out_sig=None):
        gras.HierBlock.__init__(self, name)

        self.__in_sig = in_sig
        self.__out_sig = out_sig

        #backwards compatible silliness
        import weakref
        self._hb = weakref.proxy(self)

    def lock(self):
        pass

    def unlock(self):
        self.commit()

    def input_signature(self): return self.__in_sig
    def output_signature(self): return self.__out_sig

# create a couple of aliases
serial_to_parallel = stream_to_vector
parallel_to_serial = vector_to_stream

# Force the preference database to be initialized
prefs = gr_prefs.singleton

#alias old gr_add_vXX and gr_multiply_vXX
add_vcc = add_cc
add_vff = add_ff
add_vii = add_ii
add_vss = add_ss
multiply_vcc = multiply_cc
multiply_vff = multiply_ff
multiply_vii = multiply_ii
multiply_vss = multiply_ss


import logging
try:
    from settings import DEBUG
except ImportError:
    DEBUG = True
from raven.handlers.logging import SentryHandler
from clean.infra.log.utils.colors import color_style

class RequireDebugFalse(logging.Filter):
    def filter(self, record):
        return not DEBUG

class RequireDebugTrue(logging.Filter):
    def filter(self, record):
        return DEBUG

class ColorsFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super(ColorsFormatter, self).__init__(*args, **kwargs)
        self.style = self.configure_style(color_style())

    def configure_style(self, style):
        style.DEBUG = style.HTTP_NOT_MODIFIED
        style.INFO = style.HTTP_INFO
        style.WARNING = style.HTTP_NOT_FOUND
        style.ERROR = style.ERROR
        style.CRITICAL = style.HTTP_SERVER_ERROR
        return style

    def format(self, record):
        message = logging.Formatter.format(self, record)
        colorizer = getattr(self.style, record.levelname, self.style.HTTP_SUCCESS)
        return colorizer(message)

class CaptureError(SentryHandler):

    def emit(self, record):
        return super(CaptureError, self).emit(record)


"""
学员管理系统
系统简介
需求：进⼊系统显示系统功能界⾯，功能如下：
添加学员
删除学员
修改学员信息
    完善修改学员信息: 可全部修改，也可单独修改
查询学员信息
    完善查找学员信息: 根据姓名查找(如果有两个张三，则全部显示，如果只有一个，则显示一个)
显示所有学员信息
退出系统
"""
"""
这是宠物信息管理系统的主程序
"""

# 导入学员管理系统的功能模块
from student_tools import *

def main():
    # 1. 显示系统功能界面
    while True:
        show_menu()
        # 2. 获取用户的选择
        action_str = input("请选择希望执行的操作：")
        print(f"您选择的操作是【{action_str}】")
        # 3. 根据用户的数据执行相应的功能
        if action_str in ["1", "2", "3", "4", "5", "6"]:
            # 添加学员
            if action_str == "1":
                add_student()
            # 删除学员
            elif action_str == "2":
                del_student()
            # 修改学员信息
            elif action_str == "3":
                modify_student()
            # 查询学员信息
            elif action_str == "4":
                search_student()
            # 显示所有学员信息
            elif action_str == "5":
                show_all_student()
            # 退出系统
            elif action_str == "6":
                print("欢迎再次使用【学习信息管理系统】")
                break
        else:
            print("您输入的不正确，请重新选择")

if __name__ == '__main__':
    main()


from dataclasses import dataclass, field
from typing import List

from frater.component import ComponentState, IOComponent, IOComponentConfig, ComponentBuilder
from frater.stream import InputStream, OutputStream, StreamConfig, StreamState

@dataclass
class SummationComponentState(ComponentState):
    total: int = 0

class SummationComponent(IOComponent):
    def __init__(self, config: IOComponentConfig, input_stream: InputStream, output_stream: OutputStream):
        super(SummationComponent, self).__init__(config, input_stream, output_stream)

    def init_state(self):
        return SummationComponentState()

    def process(self, data):
        self.state.total += data
        return self.state.total

@dataclass
class IterableInputStreamConfig(StreamConfig):
    data: List[int] = field(default_factory=list)

class IterableInputStream(InputStream):
    def __init__(self, config: IterableInputStreamConfig):
        super(IterableInputStream, self).__init__(config)

    def __iter__(self):
        yield StreamState.START
        yield from self.config.data
        yield StreamState.END

class PrintOutputStream(OutputStream):
    def send(self, data):
        print(data)

def main():
    input_stream = IterableInputStream(
        IterableInputStreamConfig.from_dict({'data': list(range(10))}))
    output_stream = PrintOutputStream()
    component = ComponentBuilder.build(SummationComponent, IOComponentConfig(), input_stream, output_stream)

    component.run()

if __name__ == '__main__':
    main()


import threading

from flask import jsonify

from dophon_cloud import enhance, micro_cell_list

a = enhance(import_name=__name__,
            properties={'111': 'aaa', 'service_name': 'dxh-service', 'host': '0.0.0.0', 'port': 80,
                        'reg_url': 'http://127.0.0.1:8301/reg/service/'})

m_c_list = micro_cell_list(a, properties={
    'dxh-service': [
        {
            '/test': [
                '/test1'
            ]
        }
    ],
    'xxx-service': [
        {
            '/c/test': [
                '/another/test'
            ]
        }
    ]
})

@a.route('/b')
def enter_b():
    result = m_c_list.request('dxh-service', ['/test', '/test1'])
    print(result)
    return jsonify(result)

@a.route('/c')
def enter_c():
    result = m_c_list.request('xxx-service', ['/c/test', '/another/test'])
    print(result)
    return jsonify(result)

threading.Thread(target=a.run).start()


import numpy as np
import pickle
import scipy.signal as sp
import matplotlib.pyplot as plt
with open('datasave', 'rb') as file:
    datasym =pickle.load(file)
dataf = np.zeros((91, 1024, 1024))
ref = np.mean(datasym[:17, :, :],axis=0)
for z1 in range(1024):
    for z2 in range(1024):
        value1 =datasym[30:121, z1, z2]
        value2 = np.multiply(np.ones((91,)),ref[z1, z2])
        dataf[:, z1, z2] = np.abs(np.fft.fft(value1-value2, axis=0))

for z in range(6):
    f = sp.medfilt2d(
        np.log(np.mean(dataf[z*3-2:z*3, :, :],axis=0)), kernel_size=11)
    plt.figure()
    plt.imshow(f)
    plt.show()


# Loay Mohamed
# Challeng 6:

matrix = input("Input your binary n*m matrix:")
#matrix = [[0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1]]
# matrix = [[1, 0], [0, 1]]
n = len(matrix)
m = len(matrix[0])
# check and validate matrix dimensions:
if m == 0 or n == 0:
    print("Invalid Matrix with dimensions " + str(n) + " , " + str(m))
for i in range(n):
    if len(matrix[i]) != m:
        print("Invalid Matrix with dimensions " + str(n) + " , " + str(m))

def swapRows(row1, row2):
    matrix[[row1, row2]] = matrix[[row2, row1]]

def swapCols(col1, col2):
    matrix[:, [col1, col2]] = matrix[:, [col2, col1]]

def checkMatrix():
    # if any row in the matrix not equal to the first row or reverse of it..
    for i in range(0, n):
        for j in range(0, n):
            if(matrix[0][0] ^ matrix[0][j] ^ matrix[i][0] ^ matrix[i][j] != 0):
                return -1
    rowSum = 0
    colSum = 0
    rowSwap = 0
    colSwap = 0
    for i in range(0, n):
        rowSum = rowSum + matrix[i][0]
        colSum = colSum + matrix[0][i]
        rowSwap += matrix[i][0] == i % 2
        colSwap += matrix[0][i] == i % 2

    # count of 1's in each row must equal count 0's or at most differ by 1 (in case odd number matrix board)
    if(rowSum != n//2 and rowSum != (n + 1)//2):
        return -1
    if(colSum != n//2 and colSum != (n + 1)//2):
        return -1
    if(n % 2 == 1):
        if(colSwap % 2):
            colSwap = n - colSwap
        if(rowSwap % 2):
            rowSwap = n - rowSwap
    else:
        colSwap = min(colSwap, n - colSwap)
        rowSwap = min(rowSwap, n - rowSwap)
    return (rowSwap + colSwap) // 2

print(checkMatrix())


# -*- coding: utf-8 -*-
import pygame, os, sys
import pygame_functions as pyf
import constants as c
import time
import shuffle
import bfs
import dfs
import it_dfs
import a_star
import utils

class Game_Interface:
    def __init__(self, nmax, filename):
        # Variaveis de Controle
        self.nmax = nmax
        self.mouse_state_plus = False
        self.mouse_state_minus = False
        #self.alg
        self.sprite_list = []
        self.shuffler = shuffle.Shuffle(self.nmax)
        self.imagesize = c.IMAGE_SIZE
        self.time_elapsed = 0

        # Inicializacao Pygame
        pyf.screenSize(c.SCREEN_WIDTH, c.SCREEN_HEIGHT)
        pyf.setBackgroundColour(c.GRAY)

        # Instancia lista de sprites
        for i in range (0, nmax*nmax):
            self.sprite_list.append(pyf.makeSprite("images/" + filename + str(i) + ".png"))

        # Carrega sprites padroes
        self.plus = pyf.makeSprite("images/plus.png")
        self.minus = pyf.makeSprite("images/minus.png")
        self.shuffle_button = pyf.makeSprite("images/shuffle.png")
        self.BFS_button = pyf.makeSprite("images/BFS.png")
        self.DFS_button = pyf.makeSprite("images/DFS.png")
        self.DFS_IT_button = pyf.makeSprite("images/BFS_IT.png")
        self.A1_button = pyf.makeSprite("images/A_H1.png")
        self.A2_button = pyf.makeSprite("images/A_H2.png")
        self.text_shuffler_label = pyf.makeLabel(u"Número de iterações: ", 30, 50, 690, "black", "Arial", "clear")
        self.text_time = pyf.makeLabel(u"Tempo de execução: ", 30, 700, 400, "black", "Arial", "clear")
        self.text_time2 = pyf.makeLabel("segundos", 30, 980, 400, "black", "Arial", "gray")
        self.text_memory = pyf.makeLabel(u"Memória utilizada: ", 30, 735, 450, "black", "Arial", "clear")
        #self.text_moves = pyf.makeLabel("Movimentos Realizados: ", 30, 735, 500, "black", "Arial", "clear")
        #self.text_moves2 = pyf.makeLabel("", 30, 735, 500, "black", "Arial", "gray")
        self.text_memory2 = pyf.makeLabel("bytes", 30, 980, 450, "black", "Arial", "gray")
        self.number_shuffler_label = pyf.makeLabel(str(c.IT), 30, 332, 692, "black", "Arial", "clear")

        # Transforma sprites para tamanhos maiores que 3x3
        if self.nmax > 3:
            self.initial_transformation()

        # Posiciona Sprites
        self.initial_position()
        pyf.moveSprite(self.shuffle_button, 570, 710, True)
        pyf.moveSprite(self.plus, 515, 710, True)
        pyf.moveSprite(self.minus, 460, 710, True)
        pyf.moveSprite(self.BFS_button, 800, 100, True)
        pyf.moveSprite(self.DFS_button, 1010, 100, True)
        pyf.moveSprite(self.DFS_IT_button, 900, 210, True)
        pyf.moveSprite(self.A1_button, 800, 320, True)
        pyf.moveSprite(self.A2_button, 1010, 320, True)

        # Mostra sprites na tela
        for i in range(0, nmax*nmax):
            pyf.showSprite(self.sprite_list[i])
            # print(i)
        pyf.showSprite(self.shuffle_button)
        pyf.showSprite(self.plus)
        pyf.showSprite(self.minus)
        pyf.showLabel(self.text_shuffler_label)
        pyf.showLabel(self.number_shuffler_label)
        pyf.showLabel(self.BFS_button)
        pyf.showLabel(self.DFS_button)
        pyf.showLabel(self.DFS_IT_button)
        pyf.showLabel(self.A1_button)
        pyf.showLabel(self.A2_button)
        pyf.showLabel(self.text_time)
        pyf.showLabel(self.text_time2)
        pyf.showLabel(self.text_memory)
        pyf.showLabel(self.text_memory2)
        #pyf.showLabel(self.text_moves)
        #pyf.showLabel(self.text_moves2)
        pyf.transformSprite(self.shuffle_button, 0, 0.25)
        pyf.transformSprite(self.plus, 0, 0.25)
        pyf.transformSprite(self.minus, 0, 0.1)

    def initial_position(self):
        ini_pos = self.imagesize/2 + c.SPRITE_BORDER
        count_index = 1
        for i in range (0, self.nmax):
            for j in range(0, self.nmax):
                pyf.moveSprite(self.sprite_list[count_index], ini_pos + (j * self.imagesize), ini_pos + (i * self.imagesize), True)
                count_index += 1
                if count_index == self.nmax*self.nmax:
                    break

        pyf.moveSprite(self.sprite_list[0], ini_pos + ((self.nmax - 1) * self.imagesize), ini_pos + ((self.nmax - 1) * self.imagesize), True)

    def initial_transformation(self):
        factor = (600.0/self.nmax) / self.imagesize
        self.imagesize = self.imagesize * factor
        for i in range(0, self.nmax * self.nmax):
            pyf.transformSprite(self.sprite_list[i], 0, factor)

    def run(self):
        # RODA ATE A TECLA ESC SER PRESSIONADA
        keys = pygame.key.get_pressed()
        current_time = pygame.time.get_ticks()
        waittime = 0
        while not keys[pygame.K_ESCAPE]:
            current_time = pygame.time.get_ticks()
            if current_time > waittime:
                pygame.event.clear()
                keys = pygame.key.get_pressed()
                waittime += 20

            # Incrementa Iteracoes
            if pyf.spriteClicked(self.plus):
                if not self.mouse_state_plus:
                    self.mouse_state_plus = True
                    if c.IT >= 1000:
                        c.IT += 1000
                    elif c.IT >= 100:
                        c.IT += 100
                    elif c.IT >= 10:
                        c.IT += 10
                    else:
                        c.IT += 1
                pyf.changeLabel(self.number_shuffler_label, str(c.IT))
            else:
                self.mouse_state_plus = False
            # Decrementa Iteracoes
            if pyf.spriteClicked(self.minus):
                if not self.mouse_state_minus:
                    self.mouse_state_minus = True
                    if c.IT > 1000:
                        c.IT -= 1000
                    elif c.IT > 100:
                        c.IT -= 100
                    elif c.IT > 10:
                        c.IT -= 10
                    elif c.IT > 0:
                        c.IT -= 1
                pyf.changeLabel(self.number_shuffler_label, str(c.IT))
            else:
                self.mouse_state_minus = False
            # Botao Shuffle
            if pyf.spriteClicked(self.shuffle_button): # ao clicar o sprite do shuffler chama o metodo para embaralhar
                self.initial_position()
                self.shuffler_method(c.IT)

            # Botoes Algoritmos
            move_list = []

            # BFS
            if pyf.spriteClicked(self.BFS_button):
                bfs_alg = bfs.BFS(self.shuffler.get_matrix(), self.nmax)
                start = time.time()
                bfs_alg.BFS_algorithm()
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format((end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(self.text_memory2, "{0:.0f}".format(bfs_alg.get_memory_usage()) + " bytes")
                move_list = bfs_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # DFS
            if pyf.spriteClicked(self.DFS_button):
                dfs_alg = dfs.DFS(self.shuffler.get_matrix(), self.nmax)
                start = time.time()
                dfs_alg.DFS_algorithm()
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format((end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(self.text_memory2, "{0:.0f}".format(dfs_alg.get_memory_usage()) + "bytes")
                move_list = dfs_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # DFS_IT
            if pyf.spriteClicked(self.DFS_IT_button):
                # modificar manualmente a profundidade máxima inicial
                dfs_it_alg = it_dfs.IT_DFS(self.shuffler.get_matrix(), self.nmax)
                start = time.time()
                dfs_it_alg.IT_DFS_algorithm()
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format((end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(self.text_memory2, "{0:.0f}".format(dfs_it_alg.get_memory_usage()) + "bytes")
                move_list = dfs_it_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # A_STAR H1
            if pyf.spriteClicked(self.A1_button):
                astar_alg = a_star.A_STAR(self.shuffler.get_matrix(), self.nmax)
                start = time.time()
                astar_alg.a_star_algorithm(utils.chessboard_heuristic)
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format((end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(self.text_memory2, "{0:.0f}".format(astar_alg.get_memory_usage()) + "bytes")
                move_list = astar_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

            # A_STAR H2
            if pyf.spriteClicked(self.A2_button):
                astar_alg = a_star.A_STAR(self.shuffler.get_matrix(), self.nmax)
                start = time.time()
                astar_alg.a_star_algorithm(utils.manhattan_heuristic)
                end = time.time()

                if end - start < 1:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format((end - start) * 1000) + "ms")
                else:
                    pyf.changeLabel(self.text_time2, "{0:.3f}".format(end - start) + "s")

                pyf.changeLabel(self.text_memory2, "{0:.0f}".format(astar_alg.get_memory_usage()) + "bytes")
                move_list = astar_alg.get_solution_path()
                self.move_numbers(move_list, True)
                self.shuffler.reset_matrix()

        pyf.endWait()

    def shuffler_method(self, n_moves):
        self.shuffler.shuffle_algorithm(n_moves)
        moves_list = self.shuffler.get_moves_list()
        self.move_numbers(moves_list, False)

    def change_position(self, m, flag): #m=n?
        pos_correction = self.imagesize/2
        n0_x, n0_y = self.sprite_list[0].getPosition()  # X e Y do zero
        x_pos, y_pos = self.sprite_list[m].getPosition()  # X e Y da posicao que sera trocada com 0
        x_temp, y_temp = self.sprite_list[m].getPosition()  # Temporario
        n0_y += pos_correction
        n0_x += pos_correction
        y_temp = y_temp+pos_correction
        x_temp = x_temp+pos_correction
        y_pos += pos_correction
        x_pos += pos_correction

        pyf.moveSprite(self.sprite_list[0], x_pos, y_pos, True) # muda posição do 0
        if flag:
            if n0_y > y_temp:
                for x in range(0, int(self.imagesize/5)):
                    y_pos += 5
                    pyf.moveSprite(self.sprite_list[m], x_pos, y_pos, True)
                    if flag:
                         time.sleep(c.TIME_CONST)
            elif n0_y < y_temp:
                for x in range(0, int(self.imagesize/5)):
                    y_pos -= 5
                    pyf.moveSprite(self.sprite_list[m], x_pos, y_pos, True)
                    if flag:
                        time.sleep(c.TIME_CONST)
            elif n0_x > x_temp:
                for x in range(0, int(self.imagesize/5)):
                    x_pos += 5
                    pyf.moveSprite(self.sprite_list[m], x_pos, y_pos, True)
                    if flag:
                        time.sleep(c.TIME_CONST)
            elif n0_x < x_temp:
                for x in range(0, int(self.imagesize/5)):
                    x_pos -= 5
                    pyf.moveSprite(self.sprite_list[m], x_pos, y_pos, True)
                    if flag:
                        time.sleep(c.TIME_CONST)
        else:
            if n0_y > y_temp:
                pyf.moveSprite(self.sprite_list[m], x_pos, y_pos + self.imagesize, True)
            elif n0_y < y_temp:
                pyf.moveSprite(self.sprite_list[m], x_pos, y_pos - self.imagesize, True)
            elif n0_x > x_temp:
                pyf.moveSprite(self.sprite_list[m], x_pos + self.imagesize, y_pos, True)
            else:
                pyf.moveSprite(self.sprite_list[m], x_pos - self.imagesize, y_pos, True)

    def move_numbers(self, moves, flag):
        for move in moves:
            self.change_position(move, flag)

    def text_objects(self, text, font, color_text):
        text_surface = font.render(text, True, color_text)
        return text_surface, text_surface.get_rect()

game = Game_Interface(3, c.FILENAME_MAT)
#game = Game_Interface(3, c.FILENAME_JAC)
#game = Game_Interface(3, c.FILENAME_STD)
#game = Game_Interface(4, c.FILENAME_STD)
#game = Game_Interface(5, c.FILENAME_STD)
game.run()


from typing import TYPE_CHECKING, Any, Dict, List, Self, Union, cast

from attrs import define as _attrs_define
from attrs import field as _attrs_field

from ..types import UNSET, Unset

if TYPE_CHECKING:
    from ..schemas.deposit import Deposit
    from ..schemas.recent_2_result_type_1 import Recent2ResultType1

@_attrs_define
class Recent2:
    """
    Attributes:
        result (Union['Deposit', 'Recent2ResultType1', Unset]):
        error (Union[Unset, List[str]]):
    """

    result: Union["Deposit", "Recent2ResultType1", Unset] = UNSET
    error: Union[Unset, List[str]] = UNSET
    additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        from ..schemas.deposit import Deposit

        result: Union[Dict[str, Any], Unset]
        if isinstance(self.result, Unset):
            result = UNSET

        elif isinstance(self.result, Deposit):
            result = UNSET
            if not isinstance(self.result, Unset):
                result = self.result.to_dict()

        else:
            result = UNSET
            if not isinstance(self.result, Unset):
                result = self.result.to_dict()

        error: Union[Unset, List[str]] = UNSET
        if not isinstance(self.error, Unset):
            error = self.error

        field_dict: Dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update({})
        if result is not UNSET:
            field_dict["result"] = result
        if error is not UNSET:
            field_dict["error"] = error

        return field_dict

    @classmethod
    def from_dict(cls: Self, src_dict: Dict[str, Any]) -> Self:
        from ..schemas.deposit import Deposit
        from ..schemas.recent_2_result_type_1 import Recent2ResultType1

        d = src_dict.copy()

        def _parse_result(
            data: object,
        ) -> Union["Deposit", "Recent2ResultType1", Unset]:
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                _result_type_0 = data
                result_type_0: Union[Unset, Deposit]
                if isinstance(_result_type_0, Unset):
                    result_type_0 = UNSET
                else:
                    result_type_0 = Deposit.from_dict(_result_type_0)

                return result_type_0
            except:  # noqa: E722
                pass
            if not isinstance(data, dict):
                raise TypeError()
            _result_type_1 = data
            result_type_1: Union[Unset, Recent2ResultType1]
            if isinstance(_result_type_1, Unset):
                result_type_1 = UNSET
            else:
                result_type_1 = Recent2ResultType1.from_dict(_result_type_1)

            return result_type_1

        result = _parse_result(d.pop("result", UNSET))

        error = cast(List[str], d.pop("error", UNSET))

        recent_2 = cls(
            result=result,
            error=error,
        )

        recent_2.additional_properties = d
        return recent_2

    @property
    def additional_keys(self) -> List[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties


from cleverhans.attacks import CarliniWagnerL2

from tools.cleverhans.adversarial_attack import AdversarialAttack

class CarliniWagnerAttack(AdversarialAttack):
    def __init__(self, model, targeted=False, confidence=0, batch_size=1, learning_rate=5e-3, binary_search_steps=5,
                 max_iterations=1000, abort_early=True, initial_const=1e-2, clip_min=-1, clip_max=1):
        super().__init__(model=model, clip_min=clip_min, clip_max=clip_max)
        self._targeted = targeted
        self._confidence = confidence
        self._batch_size = batch_size
        self._learning_rate = learning_rate
        self._binary_search_steps = binary_search_steps
        self._max_iterations = max_iterations
        self._abort_early = abort_early
        self._initial_const = initial_const

        with self.graph.as_default():
            self._method = CarliniWagnerL2(self._model, sess=self.session, confidence=self._confidence,
                                           batch_size=self._batch_size, learning_rate=self._learning_rate,
                                           binary_search_steps=self._binary_search_steps,
                                           max_iterations=self._max_iterations, abort_early=self._abort_early,
                                           initial_const=self._initial_const, clip_min=self._clip_min,
                                           clip_max=self._clip_max, targeted=self._targeted)

    def get_name(self):
        return "{}_{}".format(self.TOOL_NAME, "C&W")

    def attack_method(self, labels):
        if labels is not None:
            if self._targeted:
                return self._method.generate(x=self._x_clean, y_target=labels)
            else:
                return self._method.generate(x=self._x_clean, y=labels)
        return self._method.generate(x=self._x_clean)


#
# Lendo arquivos com funções do Python
#

def leitura_arquivo():
    arquivo = open("novo_arquivo.txt", "r")
    if arquivo.mode == "r":
        conteudo = arquivo.read()
        print(conteudo)
    arquivo.close()

leitura_arquivo()

def leitura_arquivo_grande():
    arquivo = open("novo_arquivo.txt", "r")
    if arquivo.mode == "r":
        conteudo_total = arquivo.readlines()

        for conteudo in conteudo_total:
            print(conteudo)

    arquivo.close()

leitura_arquivo_grande()


import math
import time
def isPrimeOptimal(n):
    sa = int(math.sqrt(n))
    count = 0
    for i in range(2, sa+1):
        if n % i == 0:
            count += 1
    if count == 0:
        return True
    else:
        return False

def isPrimeJoke(n):

    count = 0
    for i in range(2, n+1):
        if n % i == 0:
            count += 1
    if count == 1:
        return True
    else:
        return False

num = int(input("enter a num: "))
def timeElapsed(func, *args):
    st = time.time()

    a = func(*args)
    et = time.time()
    return a, et - st
print(timeElapsed(isPrimeJoke,num))
# print(timeElapsed(isPrimeOptimal,num))


import nextcord
from nextcord.ext import commands, application_checks
from nextcord import Interaction, SlashOption

from config.config_handler import ConfigHandler
from middlewares.server_verification import ServerVerification
from components.modals.nuke_model import NukeModel
from middlewares.bot_permissions import BotPermissions
from utils.server_utils import ServerUtils

class Nuke(commands.Cog):

    config_handler = ConfigHandler()
    verifications = ServerVerification()
    permissions = BotPermissions()
    utils = ServerUtils()

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @nextcord.slash_command(
        name = "nuke",
        description = "Ataque total sobre un servidor.",
        guild_ids = config_handler.get_CaC_server_id()
    )

    @application_checks.has_role(config_handler.get_executor_rol_id())
    async def nuke_command(self, ctx: Interaction,
                    id: str = SlashOption(required = True, description = "Id del servidor objtivo.")):

        guild = self.utils.get_server(int(id), self.bot)

        self.verifications.check_command_execution_in_allowed_server(guild.id)
        self.verifications.check_bag(guild)

        if (not self.permissions.has_nuke_permissions(guild)
            and not self.permissions.has_administrator_permission):

            raise commands.BotMissingPermissions(["8"])

        modal = NukeModel(guild, self.bot)
        await ctx.response.send_modal(modal)

def setup(client):
    client.add_cog(Nuke(client))


import multiprocessing
import time
import os

'''
import os
print("work进程编号",os.getpid())
'''

def dance(nums,names):
    print("dance进程id:"+str(os.getpid()))
    print("dance父进程id:"+str(os.getppid()))
    for i in range(nums):
        print(names+"跳舞")
        time.sleep(0.5)

def sing(nums,names):
    print("sing进程id:"+str(os.getpid()))
    print("sing进程父id:"+str(os.getppid()))
    for i in range(nums):
        print(names+"唱歌")
        time.sleep(0.5)

if __name__ == "__main__":
    print("多进程")
    sing_process = multiprocessing.Process(target=sing,args=(5,"小米"))
    dance_process = multiprocessing.Process(target=dance,kwargs={"names":"小茗","nums":6})

    print("主进程id:"+str(os.getpid()))
    sing_process.start()
    dance_process.start()


import time
#i had ChatGPT3 help me a bit, know i need to apply this to my original code, for all my story. as well as i need to remove the prints i used to start new lines. I need
#to put /n at the start of all my input commands. Finally, I need to remove the time.sleeps becuase i can instead just use the typing_print to have the player read
#it in time. i think 0.03 is the best time, let me know what you think if you read this could help. I may want to add a less punishing gameplay, where instead of
#ending the code every time someone types soemthing in wrong, it asks them again, but idk, someone pls help me.
def typing_print(text, delay=0.03, end=''):
    for letter in text:
        print(letter, end=end, flush=True)
        time.sleep(delay)

def game_intro():
    typing_print("MESSAGE FROM CREATOR: PLEASE ONLY TYPE THINGS WHEN YOU ARE ASKED TO, OR WHEN THE CURSOR AUTO-MOVES TO THE TYPE POSITION, OR THE STORY WILL MESS UP.\n")

def get_player_info():
    name = input("system: what is your name? ")
    age = input("system: how old are you? ")
    gender = input("system: are you a, boy, or girl, or other? ")
    if gender == "boy":
        Pronoun = "he"
    elif gender == "girl":
        Pronoun = "she"
    elif gender == "other":
        Pronoun = "they/them"
    else:
        typing_print("pick an option please")
        exit()
    return name, age, gender, Pronoun

def game_start(name, gender, Pronoun):
    typing_print("MESSAGE FROM CREATOR: ocassionally words double space, due to you placing a space before the word when you type it, please ignore. also eventually in the story, glitches may happen. please tell creator to fix.")
    typing_print(" ")
    typing_print(" ")

    Continue= input("\n system: Begin story? y/n ")
    typing_print(" ")

    if Continue == "y" or "yes":
        typing_print("Story Starting... ")
        time.sleep(3)
        hello = input(f"\n computer: Hello {name} ")
        typing_print(" ")
    elif Continue == "n" or "no":
        typing_print("Ending 1: don't want to play.")
        exit()
    else:
        typing_print("system: You're lucky you messed up so early, your options here are to input y or n no capital letters, or spaces this is your warning, this story is very unforgining to people who misspell their options or answers so if you need to copy and paste the option.")

def game_play(name, Pronoun):
    typing_print("You look around you for the first time, and notice you are floating, in blackness, all you can see is black. occasionally words appear in front of you. you are in a console, one of many, in which your world is controlled by your actions.")
    typing_print(" ")
    typing_print(" ")

    GAME = input(f"\n computer: now {name}, do you want to play a game? y/n ")
    if GAME == "n":
        computer_opinion1 = -1
        #opinion system?
        typing_print(" ")
        typing_print("computer: ...")
        time.sleep(1)
        typing_print(" ")
    if GAME == "y":
        typing_print(f"computer: HA don't care, entertain yourself, plus we have more important things to do. ")
        typing_print(" ")
    else:
        typing_print(" ")
        typing_print("please select a given option.")
        typing_print("Ending 0, the failure, answer a question properly.")
        time.sleep(5)
        game_over()

def game_over():
    exit()

def meaning_of_life(name):
    time.sleep(5)
    typing_print(" ")
    typing_print(f"\n computer: so {name} what is the meaning of life?")
    time.sleep(2)
    life = input(f" system: {name} what do you think? #this should be a verb# ")
    time.sleep(2)
    typing_print(" ")
    typing_print(f"computer: ahh you think it is {life}")
    time.sleep(2)
    typing_print(" ")
    typing_print(f"computer: your opinion is valid {name}.")
    time.sleep(2)
    typing_print(" ")
    typing_print(f"computer: updating databanks to add the definition {life} as the meaning of life.")

def main():
    game_intro()
    name, age, gender, Pronoun = get_player_info()
    game_start(name, gender, Pronoun)
    game_play(name, Pronoun)
    meaning_of_life(name)

main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Alex on 2016/10/18

class A(object):
    a = 'a'

    def __init__(self, b):
        self.b = b

if __name__ == '__main__':
    a = A('test a')
    print (a.b)
    print (a.a)
    a.a = 'asdasdf'
    b = A('test b')
    print (b.b)
    print (b.a)


def detectCycleInGraph(edges: list[list[int]], node: int) -> bool:
    if edges is None or node == 0:
        return False
    stack = []
    visited = [0 for i in range(0, node)]
    graph = [[] for i in range(0, node)]
    for edge in edges:
        _from = edge[0]
        _to = edge[1]
        graph[_from].append(_to)

    current_node = 0
    visited[current_node] = 1
    stack.append(current_node)
    while len(stack) > 0:
        current_node = stack[-1]
        node_found = False
        for j in graph[current_node]:
            if j in stack:
                print("Cycle found: ", current_node, j)
                return True
            if visited[j] == 0:
                node_found = True
                visited[j] = 1
                stack.append(j)
                break
        if not node_found:
            stack.pop()
    return False

def main():
    arr = [[0, 1], [0, 2], [1, 3], [3, 0], [3, 4]]
    # arr = [[0, 1], [1, 2], [2, 3], [3, 4]]
    print(detectCycleInGraph(arr, 5))

if __name__ == '__main__':
    main()


# encoding: utf-8

import pdb, time, sys, os, codecs, random, re, math
import numpy as np

emotion_idx = dict(zip(['neutral','anger', 'disgust', 'fear', 'joy', 'sadness', 'surprise'], range(7)))

def print_time():
    print('\n----------{}----------'.format(time.strftime("%Y-%m-%d %X", time.localtime())))

def batch_index(length, batch_size, test=False):
    index = list(range(length))
    if not test: np.random.shuffle(index)
    for i in range(int( (length + batch_size -1) / batch_size ) ):
        ret = index[i * batch_size : (i + 1) * batch_size]
        if not test and len(ret) < batch_size : break
        yield ret

def list_round(a_list):
    a_list = list(a_list)
    return [float('{:.4f}'.format(i)) for i in a_list]

def token_seq(text):
    return text.split()

def load_w2v(embedding_dim, embedding_dim_pos, data_file_path, embedding_path):
    print('\nload embedding...')
    words = []
    speakers = []
    speaker_dict = {}
    i = 0
    inputFile = open(data_file_path, 'r', encoding='utf-8')
    while True:
        line = inputFile.readline()
        if line == '':
            break
        line = line.strip().split()
        d_len = int(line[1])
        inputFile.readline()
        for i in range(d_len):
            i += 1
            new_line = inputFile.readline().strip().split(' | ')
            speaker, emotion, utterance = new_line[1], new_line[2], new_line[3]

            if speaker in speaker_dict:
                speaker_dict[speaker] += 1
            else:
                speaker_dict[speaker] = 1
            speakers.append(speaker)

            words.extend([emotion] + token_seq(utterance))

    words = set(words)
    word_idx = dict((c, k + 1) for k, c in enumerate(words))
    word_idx_rev = dict((k + 1, c) for k, c in enumerate(words))

    speaker_dict = sorted(speaker_dict.items(), key=lambda x: x[1], reverse=True)
    speakers = [item[0] for item in speaker_dict]
    spe_idx = dict((c, k + 1) for k, c in enumerate(speakers))
    spe_idx_rev = dict((k + 1, c) for k, c in enumerate(speakers))

    # main_speakers = ['Monica', 'Ross', 'Chandler', 'Rachel', 'Phoebe', 'Joey']
    # spe_idx = dict((c, k + 1) for k, c in enumerate(main_speakers))
    # spe_idx_rev = dict((k + 1, c) for k, c in enumerate(main_speakers))
    # print('all_speakers: {}'.format(len(spe_idx)))

    w2v = {}
    inputFile = open(embedding_path, 'r', encoding='utf-8')
    emb_cnt = int(inputFile.readline().split()[0])
    for line in inputFile.readlines():
        line = line.strip().split()
        w, ebd = line[0], line[1:]
        w2v[w] = ebd

    embedding = [list(np.zeros(embedding_dim))]
    hit = 0
    for item in words:
        if item in w2v:
            vec = list(map(float, w2v[item]))
            hit += 1
        else:
            vec = list(np.random.rand(embedding_dim) / 5. - 0.1)
        embedding.append(vec)
    print('data_file: {}\nw2v_file: {}\nall_words_emb {} all_words_file: {} hit_words: {}'.format(data_file_path, embedding_path, emb_cnt, len(words), hit))

    embedding_pos = [list(np.zeros(embedding_dim_pos))]
    embedding_pos.extend( [list(np.random.normal(loc=0.0, scale=0.1, size=embedding_dim_pos)) for i in range(200)] )

    embedding, embedding_pos = np.array(embedding), np.array(embedding_pos)

    print("embedding.shape: {} embedding_pos.shape: {}".format(embedding.shape, embedding_pos.shape))
    print("load embedding done!\n")
    return word_idx_rev, word_idx, spe_idx_rev, spe_idx, embedding, embedding_pos

def load_embedding_from_npy(video_id_mapping_file, video_emb_file, audio_emb_file, path_dir = ''):
    def normalize(x):
        x1 = x[1:,:]
        min_x = np.min(x1, axis=0, keepdims=True)
        max_x = np.max(x1, axis=0, keepdims=True)
        x1 = (x1-min_x)/(max_x-min_x+1e-8)
        x[1:,:] = x1
        return x

    v_id_map = eval(str(np.load(video_id_mapping_file, allow_pickle=True))) # dia1utt1: 1
    v_emb = normalize(np.load(video_emb_file, allow_pickle=True)) # (13620, 4096)
    a_emb = normalize(np.load(audio_emb_file, allow_pickle=True)) # (13620, 6373)

    print('\nload video_emb_file: {}\nload audio_emb_file: {}\n'.format(video_emb_file, audio_emb_file))
    return v_id_map, v_emb, a_emb

def bert_word2id_hier(words, tokenizer, i, x_bert_tmp, x_mask_bert_tmp, x_type_bert_tmp, s_idx_bert_tmp):
    tokens_a = tokenizer.tokenize(words)
    tokens_a = ["[CLS]"] + tokens_a + ["[SEP]"]
    input_ids = tokenizer.convert_tokens_to_ids(tokens_a)

    start_idx = s_idx_bert_tmp[i]
    sen_len_tmp = len(input_ids)
    s_idx_bert_tmp[i+1] = start_idx + sen_len_tmp  # 每个utt第一个词在dia中的序号
    for j in range(sen_len_tmp):
        x_bert_tmp[start_idx+j] = input_ids[j]  # dia所有词对应id
        x_mask_bert_tmp[start_idx+j] = 1  # 有词为1
        x_type_bert_tmp[start_idx+j] = i % 2  # 输出0/1，第偶数个utt的词位为1

def bert_word2id_ind(words, max_sen_len_bert, tokenizer, i, x_bert_sen_tmp, x_mask_bert_sen_tmp):
    tokens_a, ret = tokenizer.tokenize(words), 0
    if len(tokens_a) > max_sen_len_bert - 2:
        ret += 1
        tokens_a = tokens_a[0:(max_sen_len_bert - 2)]
    tokens_a = ["[CLS]"] + tokens_a + ["[SEP]"]
    input_ids = tokenizer.convert_tokens_to_ids(tokens_a)
    for j in range(len(input_ids)):
        x_bert_sen_tmp[i][j] = input_ids[j]
        x_mask_bert_sen_tmp[i][j] = 1
    return ret

def cut_by_max_len(x_bert_tmp, x_mask_bert_tmp, x_type_bert_tmp, s_idx_bert_tmp, d_len, max_len=512):
    if s_idx_bert_tmp[d_len] > max_len:
        new_s_idx_bert_tmp = np.array(s_idx_bert_tmp)
        clause_max_len = max_len // d_len
        j = 0
        for i in range(d_len):
            start, end = s_idx_bert_tmp[i], s_idx_bert_tmp[i+1]
            if end-start <= clause_max_len:
                for k in range(start, end):
                    x_bert_tmp[j] = x_bert_tmp[k]
                    x_type_bert_tmp[j] = x_type_bert_tmp[k]
                    j+=1
                new_s_idx_bert_tmp[i+1] = new_s_idx_bert_tmp[i] + end - start
            else :
                for k in range(start, start+clause_max_len-1):
                    x_bert_tmp[j] = x_bert_tmp[k]
                    x_type_bert_tmp[j] = x_type_bert_tmp[k]
                    j+=1
                x_bert_tmp[j] = x_bert_tmp[end-1]
                x_type_bert_tmp[j] = x_type_bert_tmp[end-1]
                j+=1
                new_s_idx_bert_tmp[i+1] = new_s_idx_bert_tmp[i] + clause_max_len
        x_bert_tmp[j:] = 0
        x_mask_bert_tmp[j:] = 0
        x_type_bert_tmp[j:] = 0
        s_idx_bert_tmp = new_s_idx_bert_tmp
    x_bert_tmp = x_bert_tmp[:max_len]
    x_mask_bert_tmp = x_mask_bert_tmp[:max_len]
    x_type_bert_tmp = x_type_bert_tmp[:max_len]
    return x_bert_tmp, x_mask_bert_tmp, x_type_bert_tmp, s_idx_bert_tmp

def load_data_utt_step1(input_file, tokenizer, word_idx, video_idx, spe_idx, max_doc_len, max_sen_len, max_doc_len_bert, max_sen_len_bert, model_type='', choose_emocate=''):
    print('\nload data_file: {}\n'.format(input_file))
    doc_id, y_emotion, y_cause, x_bert_sen, x_mask_bert_sen, x_bert, x_mask_bert, x_type_bert, s_idx_bert, x, x_v, sen_len, doc_len, speaker, y_pairs, num_token = [[] for _ in range(16)]
    cut_num, cut_num_sen, cut_num_bert_sen, num_emo, num_emo_cause, num_pairs = [0 for _ in range(6)]

    inputFile = open(input_file, 'r', encoding='utf-8')
    while True:
        line = inputFile.readline()
        if line == '':
            break
        line = line.strip().split()
        d_id, d_len = line[0], int(line[1])
        doc_id.append(d_id)
        doc_len.append(d_len)

        pairs = eval('[' + inputFile.readline().strip() + ']')
        pair_emo, cause = [], []
        if pairs != []:
            if len(pairs[0]) > 2:
                pairs = [(p[0],p[1]) for p in pairs]
                pairs = sorted(list(set(pairs)))
            pair_emo, cause = zip(*pairs)
        y_pairs.append(pairs)
        num_pairs += len(pairs)
        num_emo_cause += len(list(set(pair_emo)))

        y_emotion_tmp, y_cause_tmp = np.zeros((max_doc_len, 2)), np.zeros((max_doc_len, 2))
        if choose_emocate:
            y_emotion_tmp = np.zeros((max_doc_len, 7))
        x_tmp = np.zeros((max_doc_len, max_sen_len),dtype=np.int32)
        x_v_tmp, sen_len_tmp, spe_tmp = [np.zeros(max_doc_len, dtype=np.int32) for _ in range(3)]
        x_bert_sen_tmp, x_mask_bert_sen_tmp = [np.zeros((max_doc_len, max_sen_len_bert), dtype=np.int32) for _ in range(2)]
        s_idx_bert_tmp = np.zeros(max_doc_len, dtype=np.int32)
        x_bert_tmp, x_mask_bert_tmp, x_type_bert_tmp = [np.zeros(1024, dtype=np.int32) for _ in range(3)]

        for i in range(d_len):
            x_v_tmp[i] = video_idx['dia{}utt{}'.format(int(doc_id[-1]), i+1)]
            line = inputFile.readline().strip().split(' | ')

            spe = line[1]
            if spe in spe_idx:
                spe_tmp[i] = int(spe_idx[spe])
            else:
                print('speaker {} error!'.format(spe))

            emo_id = emotion_idx[line[2]]
            if emo_id>0:
                num_emo += 1
            if choose_emocate:
                y_emotion_tmp[i][emo_id] = 1
            else:
                y_emotion_tmp[i] = [1,0] if line[2] == 'neutral' else [0,1]
            y_cause_tmp[i][int(i+1 in cause)] = 1

            words = line[3].replace('|', '')
            words_seq = token_seq(words)
            num_token.append(len(words_seq))
            sen_len_tmp[i] = min(len(words_seq), max_sen_len)
            for j, word in enumerate(words_seq):
                if j >= max_sen_len:
                    cut_num_sen += 1
                    break
                x_tmp[i][j] = int(word_idx[word])

            bert_word2id_hier(words, tokenizer, i, x_bert_tmp, x_mask_bert_tmp, x_type_bert_tmp, s_idx_bert_tmp)
            cut_num_bert_sen += bert_word2id_ind(words, max_sen_len_bert, tokenizer, i, x_bert_sen_tmp, x_mask_bert_sen_tmp)

        cut_num = cut_num + int(s_idx_bert_tmp[d_len]>max_doc_len_bert) # 总词数超出最大长度的dia数量
        x_bert_tmp, x_mask_bert_tmp, x_type_bert_tmp, s_idx_bert_tmp = cut_by_max_len(x_bert_tmp, x_mask_bert_tmp, x_type_bert_tmp, s_idx_bert_tmp, d_len, max_len=max_doc_len_bert) # 长的截断，max_doc_len_bert // d_len

        y_emotion.append(y_emotion_tmp)
        y_cause.append(y_cause_tmp)
        x.append(x_tmp)
        x_v.append(x_v_tmp)
        sen_len.append(sen_len_tmp)
        speaker.append(spe_tmp)
        x_bert_sen.append(x_bert_sen_tmp)
        x_mask_bert_sen.append(x_mask_bert_sen_tmp)
        x_bert.append(x_bert_tmp)
        x_mask_bert.append(x_mask_bert_tmp)
        x_type_bert.append(x_type_bert_tmp)
        s_idx_bert.append(s_idx_bert_tmp)

    print('cut_num: {} cut_num_sen: {} cut_num_bert_sen: {}\n'.format(cut_num, cut_num_sen, cut_num_bert_sen))
    print('num_dia: {}  num_utt: {}  avg_utt_token: {:.2f}  num_emo: {} ({:.2%})  num_emo_cause: {} ({:.2%})  num_pairs: {} \n'.format(len(doc_id), sum(doc_len), sum(num_token)/len(num_token), num_emo, num_emo/sum(doc_len),  num_emo_cause, num_emo_cause/num_emo, num_pairs))

    x_bert_sen, x_mask_bert_sen, x_bert, x_mask_bert, x_type_bert, s_idx_bert, x, sen_len, doc_len, speaker, x_v, y_emotion, y_cause = map(np.array, [x_bert_sen, x_mask_bert_sen, x_bert, x_mask_bert, x_type_bert, s_idx_bert, x, sen_len, doc_len, speaker, x_v, y_emotion, y_cause])
    for var in ['x_bert_sen', 'x_mask_bert_sen', 'x_bert', 'x_mask_bert', 'x_type_bert', 's_idx_bert', 'x', 'sen_len', 'doc_len', 'speaker', 'x_v', 'y_emotion', 'y_cause']:
        print('{}.shape {}'.format(var, eval(var).shape))
        # print('{}:\n {}'.format(var, eval(var)[:1]))
    print('load data done!\n')

    return x_bert_sen, x_mask_bert_sen, x_bert, x_mask_bert, x_type_bert, s_idx_bert, x, sen_len, doc_len, speaker, x_v, y_emotion, y_cause, doc_id, y_pairs

def load_data_utt_step2(input_file, word_idx, video_idx, max_sen_len=45, choose_emocate = '', pred_future_cause=1, test_bound=''):
    print('\nload data_file: {}\n'.format(input_file))
    max_doc_len = 35
    x, sen_len, distance, x_emocate, x_v, y, y_pairs, pair_id_all, pair_id, doc_id_list = [[] for i in range(10)]

    n_cut = 0
    inputFile = open(input_file, 'r', encoding='utf-8')
    while True:
        line = inputFile.readline()
        if line == '': break
        line = line.strip().split()
        doc_id, d_len = int(line[0]), int(line[1])
        doc_id_list.append(doc_id)

        pairs = eval(inputFile.readline().strip())
        if pairs != []:
            if len(pairs[0]) > 2:
                pairs = [(p[0],p[1])  for p in pairs]
                pairs = sorted(list(set(pairs))) # If the pair contains the indexes of cause span (len(p)=4), we need to remove duplicates when taking the utterance pairs.
        if not pred_future_cause:
            pairs = [(p[0],p[1])  for p in pairs  if (p[1]-p[0])<=0]
        y_pairs.append(pairs)
        true_cause_list = sorted(list(set([p[1] for p in pairs])))

        x_tmp = np.zeros((max_doc_len, max_sen_len),dtype=np.int32)
        sen_len_tmp, y_emo_tmp, predy_emo_tmp = [np.zeros(max_doc_len,dtype=np.int32) for _ in range(3)]
        emo_list, cause_list, true_emo_list = [[] for _ in range(3)]

        for i in range(d_len):
            line = inputFile.readline().strip().split(' | ')
            predy_emo_tmp[i] = int(line[1].strip())

            if int(line[1].strip())>0:
                emo_list.append(i+1)
            if int(line[2].strip())>0:
                cause_list.append(i+1)
            if int(emotion_idx[line[4].strip()])>0:
                true_emo_list.append(i+1)

            y_emo_tmp[i] = emotion_idx[line[4].strip()]

            words = line[5]
            words_seq = token_seq(words)
            sen_len_tmp[i] = min(len(words_seq), max_sen_len)
            for j, word in enumerate(words_seq):
                if j >= max_sen_len:
                    n_cut += 1
                    break
                x_tmp[i][j] = int(word_idx[word])

        for p in pairs:
            new_p = [doc_id, p[0], p[1], y_emo_tmp[p[0]-1]]
            pair_id_all.append(new_p)

        if test_bound=='EC':
            emo_list = true_emo_list
        if test_bound=='CE':
            cause_list = true_cause_list

        pair_flag = False
        for i in emo_list:
            for j in cause_list:
                if pred_future_cause:
                    pair_flag = True
                else:
                    if i>=j:
                        pair_flag = True
                    else:
                        pair_flag = False

                if pair_flag:
                    if choose_emocate:
                        pair_id_cur = [doc_id, i, j, predy_emo_tmp[i-1]]
                        if test_bound=='EC':
                            pair_id_cur = [doc_id, i, j, y_emo_tmp[i-1]]
                    else:
                        pair_id_cur = [doc_id, i, j, y_emo_tmp[i-1]]
                    pair_id.append(pair_id_cur)
                    y.append([0,1] if pair_id_cur in pair_id_all else [1,0])
                    x.append([x_tmp[i-1],x_tmp[j-1]])
                    sen_len.append([sen_len_tmp[i-1], sen_len_tmp[j-1]])
                    distance.append(j-i+100)
                    if test_bound=='EC':
                        x_emocate.append(y_emo_tmp[i-1])
                    else:
                        x_emocate.append(predy_emo_tmp[i-1])
                    x_v_i = video_idx['dia{}utt{}'.format(doc_id, i)]
                    x_v_j = video_idx['dia{}utt{}'.format(doc_id, j)]
                    x_v.append([x_v_i, x_v_j])

    x, sen_len, distance, x_emocate, x_v, y = map(np.array, [x, sen_len, distance, x_emocate, x_v, y])
    for var in ['x', 'sen_len', 'distance', 'x_emocate', 'x_v', 'y']:
        print('{}.shape {}'.format( var, eval(var).shape ))
    print('n_pairs: {}, n_cut: {}, (y-negative, y-positive): {}'.format(len(pair_id_all), n_cut, y.sum(axis=0)))
    print('load data done!\n')

    return x, sen_len, distance, x_emocate, x_v, y, pair_id_all, pair_id, doc_id_list, y_pairs

def cal_prf(pred_y, true_y, doc_len, average='binary'):
    pred_num, acc_num, true_num = 0, 0, 0
    for i in range(pred_y.shape[0]):
        for j in range(doc_len[i]):
            if pred_y[i][j]:
                pred_num += 1
            if true_y[i][j]:
                true_num += 1
            if pred_y[i][j] and true_y[i][j]:
                acc_num += 1
    p, r = acc_num/(pred_num+1e-8), acc_num/(true_num+1e-8)
    f = 2*p*r/(p+r+1e-8)
    return p, r, f

def cal_prf_emocate(pred_y, true_y, doc_len):
    conf_mat = np.zeros([7,7])
    for i in range(pred_y.shape[0]):
        for j in range(doc_len[i]):
            conf_mat[true_y[i][j]][pred_y[i][j]] += 1
    p = np.diagonal( conf_mat / np.reshape(np.sum(conf_mat, axis = 0) + 1e-8, [1,7]) )
    r = np.diagonal( conf_mat / np.reshape(np.sum(conf_mat, axis = 1) + 1e-8, [7,1]) )
    f = 2*p*r/(p+r+1e-8)
    weight = np.sum(conf_mat, axis = 1) / np.sum(conf_mat)
    w_avg_f = np.sum(f * weight)
    return np.append(f, w_avg_f)

def prf_2nd_step_emocate(pair_id_all, pair_id, pred_y):
    pair_id_filtered = []
    for i in range(len(pair_id)):
        if pred_y[i]:
            pair_id_filtered.append(pair_id[i])
    keep_rate = len(pair_id_filtered)/(len(pair_id)+1e-8)

    def cal_prf_emocate(pair_id_all, pair_id):
        conf_mat = np.zeros([7,7])
        for p in pair_id:
            if p in pair_id_all:
                conf_mat[p[3]][p[3]] += 1
            else:
                conf_mat[0][p[3]] += 1
        for p in pair_id_all:
            if p not in pair_id:
                conf_mat[p[3]][0] += 1
        p = np.diagonal( conf_mat / np.reshape(np.sum(conf_mat, axis = 0) + 1e-8, [1,7]) )
        r = np.diagonal( conf_mat / np.reshape(np.sum(conf_mat, axis = 1) + 1e-8, [7,1]) )
        f = 2*p*r/(p+r+1e-8)
        weight0 = np.sum(conf_mat, axis = 1)
        weight = weight0[1:] / np.sum(weight0[1:])
        w_avg_p = np.sum(p[1:] * weight)
        w_avg_r = np.sum(r[1:] * weight)
        w_avg_f = np.sum(f[1:] * weight)

        # 不考虑占比较小的disgust/fear ['neutral','anger', 'disgust', 'fear', 'joy', 'sadness', 'surprise']
        idx = [1,4,5,6]
        weight1 = weight0[idx]
        weight = weight1 / np.sum(weight1)

        w_avg_p_part = np.sum(p[idx] * weight)
        w_avg_r_part = np.sum(r[idx] * weight)
        w_avg_f_part = np.sum(f[idx] * weight) # 4个情绪的加权f1

        results = list(f[1:]) + [w_avg_p, w_avg_r, w_avg_f, w_avg_p_part, w_avg_r_part, w_avg_f_part]
        return results
        # return list(np.append(f[1:], [w_avg_f, w_avg_f_part]))

    return cal_prf_emocate(pair_id_all, pair_id_filtered) + cal_prf_emocate(pair_id_all, pair_id) + [keep_rate]

def prf_2nd_step(pair_id_all, pair_id, pred_y):
    pair_id_filtered = []
    for i in range(len(pair_id)):
        if pred_y[i]:
            pair_id_filtered.append(pair_id[i])

    def cal_prf(pair_id_all, pair_id):
        acc_num, true_num, pred_num = 0, len(pair_id_all), len(pair_id)
        for p in pair_id:
            if p in pair_id_all:
                acc_num += 1
        p, r = acc_num/(pred_num+1e-8), acc_num/(true_num+1e-8)
        f1 = 2*p*r/(p+r+1e-8)
        return [p, r, f1]
    keep_rate = len(pair_id_filtered)/(len(pair_id)+1e-8)
    return cal_prf(pair_id_all, pair_id_filtered) + cal_prf(pair_id_all, pair_id) + [keep_rate]


import os
import six
import logging

from django.utils import timezone

logger = logging.getLogger(__name__)

def queryset_csv_export(qs, fields, cache_funcs=None, filepath=None, fileobj=None, delimiter='|'):
    import csv
    import inspect
    from django.db.models.query import QuerySet

    if not filepath:
        raise Exception("expecting a filepath")
    file_dir = os.path.dirname(filepath)
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    csvfile = fileobj or open(filepath, 'w')  # will write to disk by default
    writer = csv.writer(csvfile, delimiter=delimiter)

    def to_string(val):
        if val is None:
            val = ""
        if callable(val):
            val = val()
        if not isinstance(val, six.string_types):
            val = str(val)
        # try:
        #     val = ascii_encode(val)
        # except:
        #     val = str(val)

        return ("%r" % val)[1:-1]

    def get_arg_count(fn):
        from functools import partial
        if type(fn) == partial:
            return len(inspect.getargspec(fn.func)[0]) - len(fn.args)
        return len(inspect.getargspec(fn)[0])

    header_names = []

    rows = []
    import types
    if isinstance(qs, list):
        total_count = len(qs)
    elif isinstance(qs, QuerySet):
        total_count = qs.count()
    elif isinstance(qs, types.GeneratorType):
        total_count = "unknown (generator)"
    else:
        raise Exception("No one has shown me how to get the count of a %s" % type(qs))
    logger.debug("# of rows in qs = %s" % total_count)
    count = 0
    for obj in qs:
        count += 1
        start_time = timezone.now()
        row = []
        cache_dict = {}
        if cache_funcs:
            def is_cache_evaluated():
                all_cache_keys = [cache_func[0] for cache_func in cache_funcs]
                return all([cache_key in cache_dict for cache_key in all_cache_keys])
            while not is_cache_evaluated():
                for cache_func_tpl in cache_funcs:
                    cache_key, cache_func = cache_func_tpl[0], cache_func_tpl[1]
                    cache_dependency = cache_func_tpl[2] if len(cache_func_tpl) > 2 else None
                    if cache_key in cache_dict or (cache_dependency is not None and cache_dependency not in cache_dict):
                        continue
                    cache_func_arg_count = get_arg_count(cache_func)
                    if cache_func_arg_count == 1:
                        cache_dict[cache_key] = cache_func(obj)
                    elif cache_func_arg_count == 2:
                        cache_dict[cache_key] = cache_func(obj, cache_dict)
                    else:
                        raise Exception("invalid number of args for cache function")
        for field in fields:
            if isinstance(field, six.string_types):
                if field not in header_names:
                    header_names.append(field)
                if isinstance(obj, dict):
                    val = obj.get(field, "")
                else:
                    val = getattr(obj, field, "")
                row.append(to_string(val))  # append the value as a raw text value to keep linebreaks \r\n on a single line
            elif isinstance(field, tuple):
                if len(field) != 2:
                    raise Exception("invalid computed field length of %s. Field value = %s" % (len(field), field))
                computed_header_name, fn = field
                if computed_header_name not in header_names:
                    header_names.append(computed_header_name)
                fn_arg_count = get_arg_count(fn)
                if fn_arg_count == 1:
                    row.append(to_string(fn(obj)))
                elif fn_arg_count == 2:
                    row.append(to_string(fn(obj, cache_dict)))
                else:
                    raise Exception("expecting 1 or 2 args. actual # = %s" % fn_arg_count)
            else:
                raise Exception("invalid field type of %s, field value = %s" % (type(field), field))

        rows.append(row)
        end_time = timezone.now()
        logger.debug("finished %s of %s. time = %s" % (count, total_count, str(end_time - start_time)))

    writer.writerow(header_names)
    writer.writerows(rows)

    if fileobj:
        return fileobj

# def ascii_encode(string):
#     import unicodedata
#     return unicodedata.normalize('NFKD', unicode(string)).encode('ascii', 'ignore')


# 你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字： '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转：例如把 '9' 变为  '0'，'0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。

# 锁的初始数字为 '0000' ，一个代表四个拨轮的数字的字符串。

# 列表 deadends 包含了一组死亡数字，一旦拨轮的数字和列表里的任何一个元素相同，这个锁将会被永久锁定，无法再被旋转。

# 字符串 target 代表可以解锁的数字，你需要给出最小的旋转次数，如果无论如何不能解锁，返回 -1。

class Solution(object):
    def openLock(self, deadends, target):
        """
        :type deadends: List[str]
        :type target: str
        :rtype: int
        """
        self.visited = set()
        q = ['0000']
        res = 0
        while(q):
            size = len(q)
            for i in range(0, size):
                cur = q.pop(0)
                if cur in deadends:
                    continue
                if cur == target:
                    return res

                for j in range(0, 4):
                    up = self.plusone(cur, j)
                    if up not in self.visited:
                        self.visited.add(up)
                        q.append(up)

                    down = self.minusone(cur,j)
                    if down not in self.visited:
                        self.visited.add(down)
                        q.append(down)
            res += 1

        return -1

    def plusone(self, s, j):
        ch = list(s)
        if ch[j] == '9':
            ch[j] == '0'
        else:
            ch[j] = chr(ord(ch[j]) + 1)

        return "".join(ch)

    def minusone(self, s, j):
        ch = list(s)
        if ch[j] == '0':
            ch[j] = '9'
        else:
            ch[j] = chr(ord(ch[j]) - 1)

        return "".join(ch)

a = Solution()
deadends = ["0201","0101","0102","1212","2002"]
target = "0202"
print(a.openLock(deadends, target))


temp = 0
Average = 0
Ratings = {'A+':4.5, 'A0':4.0,'B+':3.5, 'B0':3.0,'C+':2.5, 'C0':2.0,'D+':1.5, 'D0':1.0,'F':0.0}

for _ in range(20):
  Subject, Grade, Rating = map(str, input().split())
  if Rating == 'P':
    continue
  Average += int(Grade[0]) * Ratings[Rating]
  temp += int(Grade[0])

print(Average/temp)

백준 단계별로 풀어보기/심화1/25206.py


# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import _, api, fields, models

class ProjectScrumRelease(models.Model):
    _inherit = "project.scrum.release"

    @api.depends(
        "total_planned_hours",
        "total_planned_hours_edit",
        "sprint_ids",
        "sprint_ids.progress",
        "sprint_ids.expected_hours",
        "sprint_ids.state",
    )
    def _compute_progress(self):
        """ This method used to calculate progress based on planned hours,
            sprint progress, sprint expected hours etc """
        for release in self:
            total_planned_hours = release.total_planned_hours
            if not release.sprint_ids:
                total_planned_hours = release.total_planned_hours_edit
            release.progress = sum(
                sprint.progress * sprint.expected_hours / total_planned_hours
                for sprint in release.sprint_ids
                if sprint.state != "cancel" and sprint.expected_hours > 0
            )

    @api.depends("sprint_ids", "sprint_ids.expected_hours", "sprint_ids.state")
    def _compute_hours(self):
        """ This method used to calculate milestone planned hours based on
            sprint details and sprint detail's expected hours """
        for release in self:
            release.total_planned_hours = sum(
                sprint.expected_hours
                for sprint in release.sprint_ids
                if sprint.state != "cancel"
            )

    @api.depends("total_planned_hours", "total_planned_hours_edit")
    def _compute_weightage(self):
        """ This method used to calculate weightage of release based on
            milestone planned hours """
        for release in self:
            total_m_h = 0
            weightage = 0
            for rel in release.project_id.release_ids:
                if not rel.sprint_ids:
                    total_m_h += rel.total_planned_hours_edit
                else:
                    total_m_h += rel.total_planned_hours

            if not release.sprint_ids:
                if release.total_planned_hours_edit > 0 and total_m_h > 0:
                    weightage = release.total_planned_hours_edit / total_m_h
            else:
                if release.total_planned_hours > 0 and total_m_h > 0:
                    weightage = release.total_planned_hours / total_m_h
            release.weightage = weightage

    name = fields.Char("Name", required=True, size=128)
    release_number = fields.Char(
        "Release Number", copy=False, size=150, help="Sequence of the release number"
    )
    progress = fields.Float(
        compute="_compute_progress",
        string="Progress (0-100)",
        help="Computed as avg. progress of related sprints",
    )
    total_planned_hours = fields.Float(
        compute="_compute_hours",
        string="Milestone Planned Hour",
        help="Estimated time to do the sprints.",
    )
    total_planned_hours_edit = fields.Float(
        string="Milestone Planned Hours", help="Estimated time to do the sprints.",
    )
    weightage = fields.Float(compute="_compute_weightage")

    def _valid_field_parameter(self, field, name):
        return name == 'size' or super()._valid_field_parameter(field, name)

    @api.model
    def create(self, vals):
        """ This method used to manage release details log in
            project used in release """
        result = super(ProjectScrumRelease, self).create(vals)
        if vals.get("project_id", ""):
            if result.project_id:
                msg = (
                    _(
                        """

Release Added by:  %s

                    Release Number:  %s

                    Release Name:  %s
"""
                    )
                    % (self.env.user.name, result.release_number, result.name)
                )
                result.project_id.message_post(body=msg)
        return result

    def write(self, vals):
        """ This method used to update release details in project
            used in release """
        if vals.get("project_id", ""):
            for rec in self:
                if rec.project_id:
                    msg = (
                        _(
                            """

Release Removed by:  %s

                        Release Number:  %s

                        Release Name:  %s
"""
                        )
                        % (self.env.user.name, rec.release_number, rec.name)
                    )
                    rec.project_id.message_post(body=msg)
        res = super(ProjectScrumRelease, self).write(vals)
        if vals.get("project_id", ""):
            for rec in self:
                if rec.project_id:
                    msg = (
                        _(
                            """

Release Added by:  %s

                        Release Number:  %s

                        Release Name:  %s
"""
                        )
                        % (self.env.user.name, rec.release_number, rec.name)
                    )
                    rec.project_id.message_post(body=msg)
        return res


import os
import sys
FULL_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
sys.path.insert(0, FULL_PATH+'/lib')
from errors import error

class reRefine():

    # the aim of this class is to allow later datasets within a damage
    # series to be rigid body refined (using REFMAC), using the coordinate
    # model from the first dataset coupled with the observed Fobs columns
    # from the higher dataset mtz files

    def __init__(
        self, inputFile='untitled.txt', makeNewRIDLfile=True,
            numCycles=10):

        self.inputFile = inputFile
        self.printPurpose()
        self.parseInputFile()

        newPDBs = []
        for mtz, cols in zip(self.mtzList, self.mtzCols):
            self.runREFMAC(
                pdbIn=self.initialPDB, mtzIn=mtz,
                mtzCols=cols, rFree=self.rFree,
                numCycles=numCycles)

            newPDBs.append(self.refmacPDBout)

            # check the output log indicates success
            with open(self.outputLogfile, 'r') as log:
                for ln in log.readlines():
                    if 'Refmac:  Error' in ln:
                        error(text='refmac did not run to completion. ' +
                                   'Please refer to the log file for ' +
                                   'refmac "{}"'.format(self.outputLogfile))

            # check if required files from refinement are present
            self.checkFileExists(self.refmacPDBout)

        if makeNewRIDLfile:
            self.createNewRIDLfile(newPDBs)

    def printPurpose(self):

        # print purpose of script

        ln = 'Running refmac rigid body refinement to generate ' +\
             'higher dose pdb coordinate files specified in RIDL ' +\
             'input file "{}".\nInitial dataset coordiate model and '.format(
                self.inputFile) +\
             'higher dose structure factor information have been used'
        print(ln)

    def runREFMAC(
        self, refineType='RIGID', pdbIn='untitled.pdb',
        mtzIn='untitled.mtz', numCycles=1, mtzCols='FP',
            rFree='FreeR_Flag', inputDir='./'):

        # run n = 'numCycles' cycles of 'refineType'
        # refinement in refmac to get phases

        print('Running refmac ({} {} cycles)...'.format(refineType, numCycles))
        print('---> mtz: "{}"'.format(mtzIn.split('/')[-1]))

        # check if input files exist and stop if not
        print('--> checking that all files for rigid-body refinement are present')
        self.checkFileExists(str(pdbIn))
        self.checkFileExists(str(mtzIn))
        print('--> success')

        self.jobName = 'refmac'
        if refineType == 'RIGID':
            bref = 'over'
            numCycString = 'rigid ncycle {}'.format(numCycles)
        elif refineType == 'REST':
            bref = 'ISOT'
            numCycString = 'ncyc {}'.format(numCycles)
        else:
            print('Warning: unreadable refinement type.. ' +
                  'selecting 0 cycles of rigid body refinement')
            bref = 'over'
            numCycString = 'rigid ncycle 0'
            refineType = 'RIGID'
            numCycles = 0

        # make a refinement type id to append to file names from current job
        fileInd = '_{}_{}cycles'.format(refineType, numCycles)

        self.refmacPDBout = '{}_refmac{}.pdb'.format(
            mtzIn.replace('.mtz', ''), fileInd)
        self.refmacMTZout = '{}_refmac{}.mtz'.format(
            mtzIn.replace('.mtz', ''), fileInd)
        self.refmacLIBout = '{}_refmac{}.cif'.format(
            mtzIn.replace('.mtz', ''), fileInd)

        self.commandInput1 = 'refmac5 ' +\
                             'XYZIN {} '.format(pdbIn) +\
                             'XYZOUT {} '.format(self.refmacPDBout) +\
                             'HKLIN {} '.format(mtzIn) +\
                             'HKLOUT {} '.format(self.refmacMTZout) +\
                             'LIBOUT {} '.format(self.refmacLIBout)
        self.commandInput2 = 'make check NONE\n' +\
                             'make -\n' +\
                             '    hydrogen ALL -\n' +\
                             '     hout NO -\n' +\
                             '     peptide NO -\n' +\
                             '    cispeptide YES -\n' +\
                             '    ssbridge YES -\n' +\
                             '    symmetry YES -\n' +\
                             '    sugar YES -\n' +\
                             '    connectivity NO -\n' +\
                             '    link NO\n' +\
                             'refi -\n' +\
                             '    type {} -\n'.format(refineType) +\
                             '    resi MLKF -\n' +\
                             '    meth CGMAT -\n' +\
                             '    bref {}\n'.format(bref) +\
                             '{}\n'.format(numCycString) +\
                             'scal -\n' +\
                             '    type SIMP -\n' +\
                             '    LSSC -\n' +\
                             '    ANISO -\n' +\
                             '    EXPE\n' +\
                             'solvent YES\n' +\
                             'weight -\n' +\
                             '    AUTO\n' +\
                             'monitor MEDIUM -\n' +\
                             '    torsion 10.0 -\n' +\
                             '    distance 10.0 -\n' +\
                             '    angle 10.0 -\n' +\
                             '    plane 10.0 -\n' +\
                             '    chiral 10.0 -\n' +\
                             '    bfactor 10.0 -\n' +\
                             '    bsphere 10.0 -\n' +\
                             '    rbond 10.0 -\n' +\
                             '    ncsr 10.0\n' +\
                             'labin  FP={} SIGFP=SIG{} -\n'.format(mtzCols, mtzCols) +\
                             '   FREE={}\n'.format(rFree) +\
                             'labout  FC=FC FWT=FWT PHIC=PHIC PHWT=PHWT DELFWT=DELFWT PHDELWT=PHDELWT FOM=FOM\n' +\
                             'PNAME {}\n'.format(pdbIn.strip('.pdb')) +\
                             'DNAME 1\n' +\
                             'RSIZE 80\n' +\
                             'EXTERNAL WEIGHT SCALE 10.0\n' +\
                             'EXTERNAL USE MAIN\n' +\
                             'EXTERNAL DMAX 4.2\n' +\
                             'END'
        self.outputLogfile = '{}REFMAClogfile{}.txt'.format(
            self.inputDir, fileInd)

        # run REFMAC job
        print('--> running refmac')
        self.runCCP4program()

    def runCCP4program(self):

        # generic method to run a ccp4 program on command line

        textinput = open('{}{}inputfile.txt'.format(
            self.inputDir, self.jobName), 'w')
        textinput.write(self.commandInput2)
        textinput.close()
        os.system('{} < {}{}inputfile.txt > {}'.format(
            self.commandInput1, self.inputDir, self.jobName,
            self.outputLogfile))

    def checkFileExists(
            self, filename='untitled.pdb'):

        # method to check if file exists

        if not os.path.isfile(filename):
            error(text='file "{}" could not be located'.format(filename),
                  type='error')
            return False
        else:
            return True

    def parseInputFile(self):

        # information of mtz list and columns
        # can be extracted from an input file

        print('Reading input file...')

        fileIn = open(self.inputFile, 'r')
        for l in fileIn.readlines():
            try:
                l.split()[0]
            except IndexError:
                continue
            if l.split()[0] == 'pdb1':
                self.initialPDB = l.split()[1]
            if l.split()[0] == 'mtz2':
                self.mtzList = (''.join(l.split()[1:])).split(',')
            if l.split()[0] == 'mtzlabels2':
                self.mtzCols = (''.join(l.split()[1:])).split(',')
            if l.split()[0] == 'RfreeFlag1':
                self.rFree = l.split()[1]
        fileIn.close()

        self.inputDir = '/'.join(
            self.initialPDB.replace('.pdb', '').split('/')[0:-1])+'/'

        # perform basic checks here
        if len(self.mtzList) != len(self.mtzCols):
            error(text='Inconsistent number of comma-separated entries in ' +
                       'input file for line "mtz2" and "mtzlabels2"')

        try:
            self.rFree
        except AttributeError:
            error('"RfreeFlag1" has not been specified in input file')

        try:
            self.initialPDB
        except AttributeError:
            error('"pdb1" has not been specified in the input file')

        self.checkFileExists(self.initialPDB)
        for mtz in self.mtzList:
            self.checkFileExists(mtz)

    def createNewRIDLfile(
            self, newPDBs=[]):

        # create a new updated RIDL input file which will
        # use the new coordinate models for the higher dose
        # datasets in the damage series

        print('Writing updated RIDL input file...')

        newFile = self.inputFile.replace('.txt', '-RigidBodyRefine.txt')

        fileIn = open(self.inputFile, 'r')
        fileOut = open(newFile, 'w')
        for l in fileIn.readlines():
            try:
                l.split()[0]
            except IndexError:
                continue
            if l.split()[0] == 'pdb2':
                continue
            if l.split()[0] == 'mtzlabels2':
                ln = l+'pdb2 {}\n'.format(','.join(newPDBs))
            elif l.split()[0] == 'dir':
                ln = 'dir {}_rigidBodyRefine/\n'.format(l.split()[1][0:-1])
            else:
                ln = l
            fileOut.write(ln)

        # explicitly must specify the following to use each new pdb file
        fileOut.write('\nuseLaterCellDims true')

        fileIn.close()
        fileOut.close()

        print('\nNew input file has been generated: "{}"'.format(newFile))

        self.newInputFile = newFile


from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Pokemon

def pokemon_list(request):
    pokemon = Pokemon.objects.all()
    data = {"results": list(pokemon.values(
        "name",
        "apiId",
        "chainId",
        "healtPoint",
        "attack",
        "defense",
        "specialAttack",
        "specialDefense",
        "speed",
        "height",
        "weight",
        "evolution"
    ))
    }
    return JsonResponse(data)

def pokemon_detail(request, name):
    pokemon = get_object_or_404(Pokemon, name=name)
    chain = Pokemon.objects.values('name', 'apiId', 'evolution').filter(
        chainId=pokemon.chainId).exclude(name=pokemon.name)

    data = {"Pokemon": {
        "name": pokemon.name,
        "apiId": pokemon.apiId,
        "chainId": pokemon.chainId,
        "healtPoint": pokemon.healtPoint,
        "attack": pokemon.attack,
        "defense": pokemon.defense,
        "specialAttack": pokemon.specialAttack,
        "specialDefense": pokemon.specialDefense,
        "speed": pokemon.speed,
        "height": pokemon.height,
        "weight": pokemon.weight,
        "evolution": pokemon.evolution
    },
        "evolution": []
    }

    for i in chain:
        et = ""
        if i["evolution"] > pokemon.evolution:
            et = "Evolution"
        elif i["evolution"] < pokemon.evolution:
            et = "Preevolution"
        else:
            et = "Alternate"
        related = {
            "apiId": i["apiId"],
            "name": i["name"],
            "type": et
        }
        data['evolution'].append(related)

    return JsonResponse(data)


class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        distance = 0
        while True:
            rx, ry = x % 2, y % 2
            print(rx, ry)
            if rx != ry:
                distance += 1
            x, y = x // 2, y // 2
            if x == 0 and y == 0:
                break
        return distance

if __name__ == '__main__':
    s = Solution()
    print(s.hammingDistance(4, 1))


from typing import TYPE_CHECKING, List, NamedTuple, Optional

import boto3

if TYPE_CHECKING:
    from mypy_boto3_ec2.type_defs import FilterTypeDef

from typing_extensions import TypedDict

from aec.util.config import Config

class Image(TypedDict, total=False):
    Name: Optional[str]
    ImageId: str
    CreationDate: str
    RootDeviceName: Optional[str]
    Size: int
    # optional
    SnapshotId: str

class AmiMatcher(NamedTuple):
    owner: str
    match_string: str

amazon_base_account_id = "137112412989"
canonical_account_id = "099720109477"

ami_keywords = {
    "amazon2": AmiMatcher(amazon_base_account_id, "amzn2-ami-hvm*x86_64-gp2"),
    "ubuntu1604": AmiMatcher(canonical_account_id, "ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64"),
    "ubuntu1804": AmiMatcher(canonical_account_id, "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64"),
    "ubuntu2004": AmiMatcher(canonical_account_id, "ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64"),
}

def fetch(config: Config, ami: str) -> Image:
    ami_matcher = ami_keywords.get(ami, None)
    if ami_matcher:
        try:
            # lookup the latest ami by name match
            ami_details = describe(config, owner=ami_matcher.owner, name_match=ami_matcher.match_string)[0]
        except IndexError:
            raise RuntimeError(
                f"Could not find ami with name matching {ami_matcher.match_string} owned by account {ami_matcher.owner}"
            )
    else:
        try:
            # lookup by ami id
            ami_details = describe(config, ami=ami)[0]
        except IndexError:
            raise RuntimeError(f"Could not find {ami}")
    return ami_details

def describe(
    config: Config,
    ami: Optional[str] = None,
    owner: Optional[str] = None,
    name_match: Optional[str] = None,
    show_snapshot_id: bool = False,
) -> List[Image]:
    """List AMIs."""

    ec2_client = boto3.client("ec2", region_name=config.get("region", None))

    if ami:
        response = ec2_client.describe_images(ImageIds=[ami])
    else:
        if owner:
            owners_filter = [owner]
        else:
            describe_images_owners = config.get("describe_images_owners", None)

            if not describe_images_owners:
                owners_filter = ["self"]
            elif isinstance(describe_images_owners, str):
                owners_filter = [describe_images_owners]
            else:
                owners_filter: List[str] = describe_images_owners

        if name_match is None:
            name_match = config.get("describe_images_name_match", None)

        filters: List[FilterTypeDef] = [] if name_match is None else [{"Name": "name", "Values": [f"*{name_match}*"]}]

        print(f"Describing images owned by {owners_filter} with name matching {name_match if name_match else '*'}")
        response = ec2_client.describe_images(Owners=owners_filter, Filters=filters)

    images = []
    for i in response["Images"]:
        image: Image = {
            "Name": i.get("Name", None),
            "ImageId": i["ImageId"],
            "CreationDate": i["CreationDate"],
            "RootDeviceName": i["RootDeviceName"] if "RootDeviceName" in i else None,
            "Size": i["BlockDeviceMappings"][0]["Ebs"]["VolumeSize"],
        }
        if show_snapshot_id:
            image["SnapshotId"] = i["BlockDeviceMappings"][0]["Ebs"]["SnapshotId"]
        images.append(image)

    return sorted(images, key=lambda i: i["CreationDate"], reverse=True)

def delete(config: Config, ami: str) -> None:
    """Deregister an AMI and delete its snapshot."""

    ec2_client = boto3.client("ec2", region_name=config.get("region", None))

    response = describe(config, ami, show_snapshot_id=True)

    ec2_client.deregister_image(ImageId=ami)

    ec2_client.delete_snapshot(SnapshotId=response[0]["SnapshotId"])

def share(config: Config, ami: str, account: str) -> None:
    """Share an AMI with another account."""

    ec2_client = boto3.client("ec2", region_name=config.get("region", None))

    ec2_client.modify_image_attribute(
        ImageId=ami,
        LaunchPermission={"Add": [{"UserId": account}]},
        OperationType="add",
        UserIds=[account],
        Value="string",
        DryRun=False,
    )


import os
import random
from os import listdir
from os.path import splitext
from tqdm import tqdm
import numpy as np
import cv2
from utils.FileOperator import *

# img_tf_flip(r'E:\Project\Unet-vanilla\data\img_backup',r'E:\Project\Unet-vanilla\data\mask_backup')

# img_tf_flip(r'../data/backup/img', r'../data/backup/mask')
def dir_bit_or(img_dir, mask_dir,dst_dir):
    '''
    将CPU生成图所在文件夹与GPU生成图所在文件夹中所有的图对应地进行按位或操作
    :param img_dir: CPU生成图路径
    :param mask_dir: GPU生成图路径
    :return:
    '''
    img_ids = get_files_name(img_dir)
    mask_ids = get_files_name(mask_dir)
    length = len(img_ids)
    for i in tqdm(range(0, length)):
        img = cv2.imread(fr'{img_dir}/{img_ids[i]}.png')
        t,img = cv2.threshold(img,210,255,cv2.THRESH_BINARY)
        mask = cv2.imread(fr'{mask_dir}/{mask_ids[i]}.png')
        dst = cv2.bitwise_or(img, mask)
        pth = os.path.join(dst_dir,f'{img_ids[i]}_bitor.png')
        ret = cv2.imwrite(pth, dst)
        assert ret, 'save failed'

def copy_mask():
    '''
    复制mask
    :return:
    '''
    img_ids = get_files_name(r'..\data\masks-backup')
    length = len(img_ids)
    for i in tqdm(range(0, length)):
        # print(img_ids[i])
        img = cv2.imread(fr'../data/masks-backup/{img_ids[i]}.png')
        ret = cv2.imwrite(fr'../data/masks/{img_ids[i]}_scratch.png', img)
        assert ret, 'save failed'
        ret = cv2.imwrite(fr'../data/masks/{img_ids[i]}_stain.png', img)
        assert ret, 'save failed'
        ret = cv2.imwrite(fr'../data/masks/{img_ids[i]}_dot.png', img)
        # img = cv2.imread(fr'../data/masks-backup/background.png')
        # ret = cv2.imwrite(fr'../data/temp/{i}_background.png', img)
        assert ret, 'save failed'
        # print(i)
    print('done')

import PIL #'6.2.1'
import cv2 #'4.1.1'

def patchit(root_dir,dst_dir):
    auto_make_directory(dst_dir)
    file_paths = get_files_pth(root_dir)
    for pth in file_paths:
        img = cv2.imread(pth,0)

        auto_make_directory(dst_dir)
        _,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
        cv2.imwrite(os.path.join(dst_dir,os.path.basename(pth)),img, [cv2.IMWRITE_PNG_BILEVEL, 1])