#import numpy as np
#import pandas as pd
from pandas import read_excel
from pandas import ExcelWriter
from pandas import DataFrame
from pandas import concat
import os
import enum

#QT GUI
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot

class JP_INDEX(enum.Enum):
    CARD_NO = 0
    CARD_TYPE = 9
    FROM = 11
    CARD_NAME = 13
    HP        = 15
    POKE_TYPE = 17
    SKILL_COST = 29
    SKILL_NAME = 26
    SKILL_TEXT = 32

    POKE_NO = 34
    SKILL_DAMAGE = 30

    CATEGORY = 36
    HEIGHT = 38
    WEIGHT = 40

    WEAK_TYPE = 19
    WEAK_MULTI = 20
    REGI_TYPE = 22
    REGI_MULTI = 23
    RUN_COUNT = 24
    FLAVOR = 41
    ILLUSTRATOR  = 3
    RARITY = 2
    SERIES_MARK = 4
    REGULATION_MARK = 5

class KR_INDEX(enum.Enum):
    WR_COLLECT_NO=3 #1
    WR_POKE_NO=4 #35
    WR_RARITY=5 #3
    WR_CARDTYPE_NUM=6 #신규 1 Pokecard 2 Trainers 3 Energy
    WR_CARDTYPE=7 #37
    WR_NAME=8 #14
    WR_MON_TYPE=9 #18
    WR_HEIGHT=10 #39
    WR_WEIGHT=11 #41
    WR_DOX_INFO=12 #42
    WR_PRE_MON=13 #12

    WR_LEVEL=14

    WR_ILLUSTRATOR=15 #4
    WR_HP=16 #16
    WR_CARDMONTYPE=17 #18
    WR_WEAKNESS=18 #20
    WR_WEAKNESS_LVL=19 #21
    WR_RESISTANCE=20 # 23
    WR_RESISTANCE_LVL=21 #24
    WR_RETREAT=22 #25
    WR_TECHERG1=23 #30-1
    WR_TECHERG2=24 #30-2
    WR_TECHERG3=25 #30-3
    WR_TECHERG4=26 #30-4 #{G}풀,{R}불꽃,{W}물,{L}번개,{P}초,{F}격투,{D}악,{M}강철,{S}페어리,{C}무색,{Y}드래곤

    WR_DAMAGE1=27 #31-1
    WR_DAMAGE2=28 #31-2
    WR_DAMAGE3=29 #31-3
    WR_DAMAGE4=30 #31-4

    WR_AB_LABEL1=31 #27-1
    WR_AB_LABEL2=32 #27-2
    WR_AB_LABEL3=33 #27-3
    WR_AB_LABEL4=34 #27-4

    WR_ABILITY1=35 #33-1
    WR_ABILITY2=36 #33-2
    WR_ABILITY3=37 #33-3
    WR_ABILITY4=38 #33-4

    WR_POWERBODY=39
    WR_LEVEL_RULE=40

    WR_SERIES_MARK = 46
    WR_REGULATION_MARK = 49

class JP_DATA:
    def __init__(self, f_name):
        print("JP_DATA INIT")
        #self.xlsx = pd.read_excel(f_name, encoding='utf-8', keep_default_na=False) #read dataframe
        self.xlsx = read_excel(f_name, encoding='utf-8', keep_default_na=False) #read dataframe
        self.key = self.xlsx.keys()
        self.START_ROW = 0
        self.isLoadOK = False

        EOF = len(self.xlsx.index)
        print("JPDATA INDEX SIZE :", len(self.xlsx.index))

        while(1): #앞 세글자가 숫자일때까지 (1번 CARD위치찾기)
            cell = self.XLS_DATA(0 , self.START_ROW)
            if( (str(type(cell)) == "<class 'str'>") and cell[0:3].isnumeric() ):
                print ("find Card No.", cell[0:3])
                break
            self.START_ROW +=1
            if(self.START_ROW == EOF):
                print("JPDATA return None!!!")
                return None

        self.NOW_ROW = self.START_ROW
        self.isLoadOK = True
        #print(self.xlsx.index.stop)

    def XLS_DATA( self , col , row ):
        return self.xlsx[self.key[col]][row]

    def SetStartPos(self):
        self.NOW_ROW = self.START_ROW

    def Get_Card_Data(self):
        if(self.NOW_ROW >= self.xlsx.index.stop): #End of file
            return "EOF"

        tmp = POKE_CARD()
        depth = 0
        #Get Current Card No

        tmp.CARD_NO = self.XLS_DATA(JP_INDEX.CARD_NO.value,self.NOW_ROW)

        while(self.XLS_DATA(JP_INDEX.CARD_NO.value, self.NOW_ROW + depth) == tmp.CARD_NO[0]):
            depth += 1
            if(self.NOW_ROW + depth == self.xlsx.index.stop):
                break

        #print("depth : %d , NOW_ROW: %d" %(depth, self.NOW_ROW))

        tmp.CARD_TYPE = self.XLS_DATA(JP_INDEX.CARD_TYPE.value,self.NOW_ROW)
        tmp.CARD_NAME = self.XLS_DATA(JP_INDEX.CARD_NAME.value,self.NOW_ROW)
        tmp.HP = self.XLS_DATA(JP_INDEX.HP.value,self.NOW_ROW)
        tmp.POKE_TYPE = self.XLS_DATA(JP_INDEX.POKE_TYPE.value,self.NOW_ROW)

        tmp.WEAK_TYPE = self.XLS_DATA(JP_INDEX.WEAK_TYPE.value,self.NOW_ROW)
        tmp.WEAK_MULTI = self.XLS_DATA(JP_INDEX.WEAK_MULTI.value,self.NOW_ROW)
        tmp.REGI_TYPE = self.XLS_DATA(JP_INDEX.REGI_TYPE.value,self.NOW_ROW)
        tmp.REGI_MULTI = self.XLS_DATA(JP_INDEX.REGI_MULTI.value,self.NOW_ROW)

        tmp.RUN_COUNT = self.XLS_DATA(JP_INDEX.RUN_COUNT.value,self.NOW_ROW)
        tmp.FLAVOR = self.XLS_DATA(JP_INDEX.FLAVOR.value,self.NOW_ROW)
        tmp.ILLUSTRATOR = self.XLS_DATA(JP_INDEX.ILLUSTRATOR.value,self.NOW_ROW)

        tmp.FROM = self.XLS_DATA(JP_INDEX.FROM.value,self.NOW_ROW)
        tmp.POKE_NO = self.XLS_DATA(JP_INDEX.POKE_NO.value,self.NOW_ROW)
        tmp.CATEGORY = self.XLS_DATA(JP_INDEX.CATEGORY.value,self.NOW_ROW)
        tmp.HEIGHT = self.XLS_DATA(JP_INDEX.HEIGHT.value,self.NOW_ROW)
        tmp.WEIGHT = self.XLS_DATA(JP_INDEX.WEIGHT.value,self.NOW_ROW)
        tmp.RARITY = self.XLS_DATA(JP_INDEX.RARITY.value,self.NOW_ROW)

        for i in range(depth):
            tmp.SKILL_COST = self.XLS_DATA(JP_INDEX.SKILL_COST.value, self.NOW_ROW + i)
            tmp.SKILL_NAME = self.XLS_DATA(JP_INDEX.SKILL_NAME.value, self.NOW_ROW + i)
            tmp.SKILL_TEXT = self.XLS_DATA(JP_INDEX.SKILL_TEXT.value, self.NOW_ROW + i)
            tmp.SKILL_DAMAGE = self.XLS_DATA(JP_INDEX.SKILL_DAMAGE.value, self.NOW_ROW + i)

        tmp.SERIES_MARK = self.XLS_DATA(JP_INDEX.SERIES_MARK.value, self.NOW_ROW)
        tmp.REGULATION_MARK = self.XLS_DATA(JP_INDEX.REGULATION_MARK.value, self.NOW_ROW)

        self.NOW_ROW += depth #다음 Card Data로 이동
        return tmp

    def export_txt_files(self, filename):
        f = open(filename, 'w', -1 ,"utf-8")
        while( self.NOW_ROW < self.xlsx.index.stop ):
            print("NOW_CARD : %s" % self.XLS_DATA(JP_INDEX.CARD_NO.value,self.NOW_ROW))
            f.write(self.Get_Card_Data().__str__())
        f.close()

class POKE_CARD:

    def __init__(self):
        #print("POKE_CARD_INIT")
        self._CARD_NO = []
        self._CARD_TYPE = []
        self._CARD_NAME = []
        self._HP       = []
        self._POKE_TYPE = []
        self._SKILL_COST = []
        self._SKILL_NAME = []
        self._SKILL_TEXT = []
        self._WEAK_TYPE = []

        self._WEAK_MULTI = []
        self._REGI_TYPE = []
        self._RUN_COUNT = []
        self._FLAVOR = []
        self._ILLUSTRATOR  = []
        self._SKILL_DAMAGE = []
        self._FROM = []
        self._POKE_NO = []
        self._CATEGORY = []
        self._HEIGHT = []
        self._WEIGHT = []
        self._RARITY = []
        self._REGI_MULTI = []

        self._SERIES_MARK = []
        self._REGULATION_MARK = []

    def _get_CARD_NO(self):
        return self._CARD_NO
    def _get_CARD_TYPE(self):
        return self._CARD_TYPE
    def _get_CARD_NAME (self):
        return self._CARD_NAME
    def _get_HP(self):
        return self._HP
    def _get_POKE_TYPE (self):
        return self._POKE_TYPE
    def _get_SKILL_COST (self):
        return self._SKILL_COST
    def _get_SKILL_NAME (self):
        return self._SKILL_NAME
    def _get_SKILL_TEXT (self):
        return self._SKILL_TEXT
    def _get_WEAK_TYPE (self):
        return self._WEAK_TYPE
    def _get_WEAK_MULTI(self):
        return self._WEAK_MULTI
    def _get_REGI_TYPE (self):
        return self._REGI_TYPE
    def _get_RUN_COUNT  (self):
        return self._RUN_COUNT
    def _get_FLAVOR(self):
        return self._FLAVOR
    def _get_ILLUSTRATOR(self):
        return self._ILLUSTRATOR
    def _get_SKILL_DAMAGE(self):
        return self._SKILL_DAMAGE

    def _set_CARD_NO (self , _CARD_NO = None):
        self._CARD_NO.append(_CARD_NO)
    def _set_CARD_TYPE (self , _CARD_TYPE = None):
        self._CARD_TYPE.append(_CARD_TYPE)
    def _set_CARD_NAME  (self , _CARD_NAME  = None):
        self._CARD_NAME.append(_CARD_NAME )
    def _set_HP (self , _HP = None):
        self._HP.append(_HP)
    def _set_POKE_TYPE  (self , _POKE_TYPE  = None):
        self._POKE_TYPE.append(_POKE_TYPE )
    def _set_SKILL_COST  (self , _SKILL_COST  = None):
        self._SKILL_COST.append(_SKILL_COST )
    def _set_SKILL_NAME  (self , _SKILL_NAME  = None):
        self._SKILL_NAME.append(_SKILL_NAME )
    def _set_SKILL_TEXT  (self , _SKILL_TEXT  = None):
        self._SKILL_TEXT.append(_SKILL_TEXT )
    def _set_WEAK_TYPE  (self , _WEAK_TYPE  = None):
        self._WEAK_TYPE.append(_WEAK_TYPE )
    def _set_WEAK_MULTI (self , _WEAK_MULTI = None):
        self._WEAK_MULTI.append(_WEAK_MULTI)
    def _set_REGI_TYPE  (self , _REGI_TYPE  = None):
        self._REGI_TYPE.append(_REGI_TYPE )
    def _set_RUN_COUNT   (self , _RUN_COUNT   = None):
        self._RUN_COUNT.append(_RUN_COUNT  )
    def _set_FLAVOR (self , _FLAVOR = None):
        self._FLAVOR.append(_FLAVOR)
    def _set_ILLUSTRATOR (self, _ILLUSTRATOR = None):
        self._ILLUSTRATOR.append(_ILLUSTRATOR)
    def _set_SKILL_DAMAGE (self , _SKILL_DAMAGE = None):
        self._SKILL_DAMAGE.append(_SKILL_DAMAGE)

    def _set_FROM (self , _FROM = None):
        self._FROM.append(_FROM)
    def _get_FROM(self):
        return self._FROM

    def _set_POKE_NO (self , _POKE_NO = None):
        self._POKE_NO.append(_POKE_NO)
    def _get_POKE_NO(self):
        return self._POKE_NO

    def _set_CATEGORY (self , _CATEGORY = None):
        self._CATEGORY.append(_CATEGORY)
    def _get_CATEGORY(self):
        return self._CATEGORY

    def _set_HEIGHT (self , _HEIGHT = None):
        self._HEIGHT.append(_HEIGHT)
    def _get_HEIGHT(self):
        return self._HEIGHT

    def _set_WEIGHT (self , _WEIGHT = None):
        self._WEIGHT.append(_WEIGHT)
    def _get_WEIGHT(self):
        return self._WEIGHT

    def _set_RARITY (self , _RARITY = None):
        self._RARITY.append(_RARITY)
    def _get_RARITY(self):
        return self._RARITY

    def _set_REGI_MULTI (self , _REGI_MULTI = None):
        self._REGI_MULTI.append(_REGI_MULTI)
    def _get_REGI_MULTI(self):
        return self._REGI_MULTI

    def _set_SERIES_MARK (self , _SERIES_MARK = None):
        self._SERIES_MARK.append(_SERIES_MARK)
    def _set_REGULATION_MARK (self , _REGULATION_MARK = None):
        self._REGULATION_MARK.append(_REGULATION_MARK)
    def _get_SERIES_MARK(self):
        return self._SERIES_MARK
    def _get_REGULATION_MARK(self):
        return self._REGULATION_MARK

    CARD_NO = property(_get_CARD_NO, _set_CARD_NO)
    CARD_TYPE = property(_get_CARD_TYPE, _set_CARD_TYPE)
    CARD_NAME  = property(_get_CARD_NAME , _set_CARD_NAME )
    HP = property(_get_HP, _set_HP)
    POKE_TYPE  = property(_get_POKE_TYPE , _set_POKE_TYPE )
    SKILL_COST  = property(_get_SKILL_COST , _set_SKILL_COST )
    SKILL_NAME  = property(_get_SKILL_NAME , _set_SKILL_NAME )
    SKILL_TEXT  = property(_get_SKILL_TEXT , _set_SKILL_TEXT )
    WEAK_TYPE  = property(_get_WEAK_TYPE , _set_WEAK_TYPE )
    WEAK_MULTI = property(_get_WEAK_MULTI, _set_WEAK_MULTI)
    REGI_TYPE  = property(_get_REGI_TYPE , _set_REGI_TYPE )
    RUN_COUNT   = property(_get_RUN_COUNT  , _set_RUN_COUNT  )
    FLAVOR = property(_get_FLAVOR, _set_FLAVOR)
    ILLUSTRATOR = property(_get_ILLUSTRATOR, _set_ILLUSTRATOR)
    SKILL_DAMAGE = property(_get_SKILL_DAMAGE, _set_SKILL_DAMAGE)
    FROM = property(_get_FROM, _set_FROM)
    POKE_NO = property(_get_POKE_NO, _set_POKE_NO)
    CATEGORY = property(_get_CATEGORY, _set_CATEGORY)
    HEIGHT = property(_get_HEIGHT, _set_HEIGHT)
    WEIGHT = property(_get_WEIGHT, _set_WEIGHT)
    RARITY = property(_get_RARITY, _set_RARITY)
    REGI_MULTI = property(_get_REGI_MULTI, _set_REGI_MULTI)
    SERIES_MARK = property(_get_SERIES_MARK, _set_SERIES_MARK)
    REGULATION_MARK = property(_get_REGULATION_MARK, _set_REGULATION_MARK)

    def __str__(self):
        temp = ""
        temp += "-----------------------------------------------------------------------\n"

        temp += self._CARD_TYPE[0] #10
        temp += '\t'
        temp += self._CARD_NAME[0]  #14

        if((self._CARD_TYPE[0]!="Item")and(self._CARD_TYPE[0]!="Supporter")and(self._CARD_TYPE[0]!="Stadium")and(self._CARD_TYPE[0]!="Special Energy")):#Item과 Suppandter는 HP, self._POKE_TYPE을 입력하지않음
            #temp += "bbbbbbbbbbbbbbbbbbbbbbbbbbb"
            temp += '\t'
            temp += "HP"
            temp += str(self._HP[0]) #16
            temp += '\t'
            temp += self._POKE_TYPE[0]#18
            temp += "\n"
        #print(str(self._FROM[0]))
        #print("check")

        if(str(self._FROM[0]) != ""): #From 값이 있을때만 입력
            temp += str(self._FROM[0]) #12
            temp += "에서 진화"
        temp += "\n"

        #GX , TAG, Item, Suppoter, Stadium, Special Energy는 기본정보 출력하지 않음

        if((self._CARD_TYPE[0][-2:]!="GX") and (self._CARD_TYPE[0][-3:]!="TAG") and (self._CARD_TYPE[0]!="Item")and(self._CARD_TYPE[0]!="Supporter")and(self._CARD_TYPE[0]!="Stadium")and(self._CARD_TYPE[0]!="Special Energy")): #번호,키,몸무게는 GX가아닌경우만 출력
            temp += "전국도감 NO."
            temp += str(self._POKE_NO[0]) #35
            temp += "  "
            temp += str(self._CATEGORY[0]) #37
            temp += "  키: "
            temp += str(self._HEIGHT[0]).replace("m", " m") #39 #원본 m에서 공백 추가
            temp += "  몸무게: "
            temp += str(self._WEIGHT[0]).replace("kg", " kg")#41
        temp += '\n'

        for i in range(len(self._SKILL_NAME)):
            #print (("str(self._SKILL_COST[%d] : %s") % (i ,str(self._SKILL_COST[i])))
            if(str(self._SKILL_COST[i]) != ""): # attack cost가 비어있지 않을때만
                temp += str(self._SKILL_COST[i]) #30
                temp += '\t'
            if(self._SKILL_NAME[i] != "n/a"):
                if(self._SKILL_NAME[i][:9] == "[Ability]"):
                    temp += "{AB}\t"
                    temp += self._SKILL_NAME[i][10:] #10번재부터 공백한칸제거
                else:
                    temp += self._SKILL_NAME[i] #27
                temp += '\t'
            if(str(self._SKILL_DAMAGE[i]) != "n/a"):
                if( (str(self._SKILL_DAMAGE[i])[-1:] == "+") or (str(self._SKILL_DAMAGE[i])[-1:] == "-") or (str(self._SKILL_DAMAGE[i])[-1:] == "×") ):
                    temp += str(self._SKILL_DAMAGE[i]).replace(str(self._SKILL_DAMAGE[i])[-1:], "\t"+str(self._SKILL_DAMAGE[i])[-1:])
                else:
                    temp += str(self._SKILL_DAMAGE[i]) #30

            temp += '\n' #attack text출력전 줄바꿈필요
            if(self._SKILL_TEXT[i] != "n/a"):
                temp += self._SKILL_TEXT[i] #33
                temp += '\n'

        if((self._CARD_TYPE[0]!="Item")and(self._CARD_TYPE[0]!="Supporter")and(self._CARD_TYPE[0]!="Stadium")and(self._CARD_TYPE[0]!="Special Energy")): #Item Suppandter는 약점 관련 정보필요없음
            temp += "\n\t"
            temp += self._WEAK_TYPE[0]#20
            temp += self._WEAK_MULTI[0]#21
            temp += '\t'
            temp += self._REGI_TYPE[0]#23
            #print("regi type")
            #print(str(self._REGI_TYPE[0]))
            temp += str(self._REGI_MULTI[0])#24
            #print("regi multi")
            #print(str(self._REGI_MULTI[0]))
            temp += '\t'
            if(self._RUN_COUNT[0] != "n/a"):
                cnt = int(self._RUN_COUNT[0])#25
                for i in range(cnt):
                    temp += "{C}"
            temp += '\n'

        temp += "Illus. "
        temp += self._ILLUSTRATOR[0] #4
        temp += "\n\n"
        temp += self._CARD_NO[0] #1
        temp += '\t'
        temp += self._RARITY[0] #3
        temp += "\n\n"

        if((self._CARD_TYPE[0][-2:]!="GX")and(self._CARD_TYPE[0]!="Item")and(self._CARD_TYPE[0]!="Supporter")and(self._CARD_TYPE[0]!="Stadium")and(self._CARD_TYPE[0]!="Special Energy")): #Item Suppandter는 Flavand Text필요없음

            temp += str(self._FLAVOR[0])#42
            temp += '\n'

        temp += "-----------------------------------------------------------------------\n"
        return temp

class KR_DATA:
    def __init__(self, f_name):
        self.file_name = f_name
        #self.writer = pd.ExcelWriter('pandas_xlsxWriter.xlsx', engine='openpyxl', mode='a')
        self.format = {}

    def Card_Type_Number(self, type):
        if(type == "Item"):
            return 21
        elif(type == "Supporter"):
            return 22
        elif(type == "Stadium"):
            return 23
        elif(type == "Energy" ):
            return 31
        elif(type == "Special Energy"):
            return 32
        elif(type == "Basic"):
            return 11 #포켓몬
        elif(type == "Stage 1"):
            return 12
        else:
            return 13

    def CardType_Eng_to_Kor(self, ENG):
        ENG = ENG.replace("Basic","기본 포켓몬")
        ENG = ENG.replace("Stage 1","1진화 포켓몬")
        ENG = ENG.replace("Stage 2","2진화 포켓몬")
        ENG = ENG.replace("Stage V","V진화")
        ENG = ENG.replace("/GX/TAG",", TAG TEAM GX")
        ENG = ENG.replace("/GX",", 포켓몬 GX")
        ENG = ENG.replace("/VMAX",", 포켓몬 VMAX") #0220 s1대응
        ENG = ENG.replace("/V",", 포켓몬 V") #0220 s1대응

        #기타
        ENG = ENG.replace("/◇Prismstar", ", 프리즘스타")

        #아이템류
        ENG = ENG.replace("Item","아이템")
        ENG = ENG.replace("Supporter","서포트")
        ENG = ENG.replace("Stadium","스타디움")
        ENG = ENG.replace("/EX",", 포켓몬 EX") #??? Sample필요

        #에너지
        ENG = ENG.replace("Special Energy","특수 에너지")
        ENG = ENG.replace("Energy","기본 에너지")

        #복원

        #포켓몬의 도구
        return ENG
    def Properties_Eng_to_Kor(self, ENG):
        #{G}풀,{R}불꽃,{W}물,{L}번개,{P}초,{F}격투,{D}악,{M}강철,{S}페어리,{C}무색,{Y}드래곤
        #강철
        ENG = ENG.replace("{M}","강철");
        #강철,격투
        #격투
        ENG = ENG.replace("{F}","격투")
        #드래곤
        ENG = ENG.replace("{Y}","드래곤")
        #무색
        #?? 무색이무속성?
        ENG = ENG.replace("{C}","무색")
        #물
        ENG = ENG.replace("{W}","물")
        #번개
        ENG = ENG.replace("{L}","번개")
        #번개,풀
        #불꽃
        ENG = ENG.replace("{R}","불꽃")
        #불꽃,물
        #악
        ENG = ENG.replace("{D}","악")
        #악,강철
        #초
        ENG = ENG.replace("{P}","초")
        #페어리
        ENG = ENG.replace("{S}","페어리")
        #페어리,물
        #페어리,초
        #풀
        ENG = ENG.replace("{G}","풀")
        #풀,불꽃
        #풀,악
        ENG = ENG.replace("{X}","0코스트") #0220 s1대응

        return ENG

    def SpecialTextCheck(self, text):
        text = text.replace("[자신]","자신")
        text = text.replace("[상대]","상대")
        text = text.replace("[독]","독")
        text = text.replace("[화상]","화상")
        text = text.replace("[마비]","마비")
        text = text.replace("[잠듦]","잠듦")
        text = text.replace("[혼란]","혼란")
        text = text.replace("[기절]","기절")
        text = text.replace("[기본]","기본")
        text = text.replace("[1진화]","1진화")
        text = text.replace("[2진화]","2진화")
        text = text.replace("[후퇴]","후퇴")
        text = text.replace("[포켓몬 GX 룰]","포켓몬 GX 룰")
        text = text.replace("[TAG TEAM 룰]","TAG TEAM 룰")
        text = text.replace("[아이템 룰]","아이템 룰")
        text = text.replace("[서포트 룰]","서포트 룰")
        text = text.replace("[스타디움 룰]","스타디움 룰")
        text = text.replace("[포켓몬 EX 룰]","포켓몬 EX 룰")
        text = text.replace("[M진화(메가진화) 룰]","M진화 룰")
        text = text.replace("[포켓몬의 도구 룰]","포켓몬의 도구 룰")
        text = text.replace("[Ability]","[특성]")
        text = text.replace("n/a","")

        return text

    def BoldTextCheck(self,text):
        text = text.replace("[기본]","[i]기본[/i]")
        text = text.replace("[1진화]","[i]1진화[/i]")
        text = text.replace("[2진화]","[i]2진화[/i]")
        text = text.replace("[기절]","[i]기절[/i]")
        text = text.replace("[후퇴]","[i]후퇴[/i]")
        text = text.replace("[독]","[i]독[/i]")
        text = text.replace("[화상]","[i]화상[/i]")
        text = text.replace("[마비]","[i]마비[/i]")
        text = text.replace("[잠듦]","[i]잠듦[/i]")
        text = text.replace("[혼란]","[i]혼란[/i]")
        text = text.replace("[VMAX 룰]","[i]VMAX 룰[/i]") #0220 s1대응
        text = text.replace("[VMAX]","[i]VMAX[/i]") #0220 s1대응
        text = text.replace("[V 룰]","[i]V 룰[/i]") #0220 s1대응
        text = text.replace("[V]","[i]V[/i]") #0220 s1대응
        text = text.replace("[GX]","[i]GX[/i]") #0220 s1대응
        text = text.replace("{G}","[s]풀[/s]")
        text = text.replace("{R}","[s]불꽃[/s]")
        text = text.replace("{W}","[s]물[/s]")
        text = text.replace("{L}","[s]번개[/s]")
        text = text.replace("{P}","[s]초[/s]")
        text = text.replace("{C}","[s]무색[/s]")
        text = text.replace("{F}","[s]격투[/s]")
        text = text.replace("{D}","[s]악[/s]")
        text = text.replace("{M}","[s]강철[/s]")
        text = text.replace("{Y}","[s]페어리[/s]")
        text = text.replace("{N}","[s]드래곤[/s]")

        return text

    def Remove_null_Data (self, token, method, null_val = ""):
        tmp = self.format[token][0]
        if("n/a" in str(tmp)):
            self.format[token]=[null_val]
        else:
            if(method == int):
                if(str(tmp).find('₋')>=0): #JP Minus '₋' replace to KR '-' for int() funtion
                    tmp = str(tmp).replace('₋','-')
            self.format[token]=[method(tmp)]

    def InputCardData(self, card):

        self.format = {}
        self.format = {
        "WR_COLLECT_NO" : [card.CARD_NO[0]] ,
        "WR_POKE_NO" : [card.POKE_NO[0]],
        "WR_RARITY" : [card.RARITY[0]],
        "WR_CARDTYPE_NUM" : [""], #Function item support poke stage 에 따라 2자리 숫자
        "WR_CARDTYPE" : [card.CARD_TYPE[0]],
        "WR_NAME" : [card.CARD_NAME[0]],
        "WR_MON_TYPE" : [card.CATEGORY[0]],
        "WR_HEIGHT" : [card.HEIGHT[0]],
        "WR_WEIGHT" : [card.WEIGHT[0]],
        "WR_DOX_INFO" : [card.FLAVOR[0]],
        "WR_PRE_MON" : [card.FROM[0]],
        "WR_LEVEL" : [""],
        "WR_ILLUSTRATOR" : [card.ILLUSTRATOR[0]],
        "WR_HP" : [card.HP[0]],
        "WR_CARDMONTYPE" : [card.POKE_TYPE[0]],
        "WR_WEAKNESS" : [card.WEAK_TYPE[0]],
        "WR_WEAKNESS_LVL" : [card.WEAK_MULTI[0]],
        "WR_RESISTANCE" : [card.REGI_TYPE[0]],
        "WR_RESISTANCE_LVL" : [card.REGI_MULTI[0]],
        "WR_RETREAT" : [card.RUN_COUNT[0]],

        "WR_TECHERG1" : [""],
        "WR_TECHERG2" : [""],
        "WR_TECHERG3" : [""],
        "WR_TECHERG4" : [""],

        "WR_DAMAGE1" : [""],
        "WR_DAMAGE2" : [""],
        "WR_DAMAGE3" : [""],
        "WR_DAMAGE4" : [""],

        "WR_AB_LABEL1" :[""],
        "WR_AB_LABEL2" :[""],
        "WR_AB_LABEL3" :[""],
        "WR_AB_LABEL4" :[""],

        "WR_ABILITY1" :[""],
        "WR_ABILITY2" :[""],
        "WR_ABILITY3" :[""],
        "WR_ABILITY4" :[""],

        "WR_POWERBODY" : [""],
        "WR_LEVEL_RULE" : [""],

        "WR_GOODS_NAME" : [""],
        "WR_GOODS_NAME2" : [""],
        "WR_GOODS_NAME3" : [""],
        "WR_GOODS_NAME4" : [""],
        "WR_GOODS_NAME_SHORT" : [""],
        "WR_GOODS_NAME_IMAGE" : [card.SERIES_MARK[0]],
        "WR_CARDTYPE_ORDER" : [""],
        "WR_RAR_LVL_ORDER" : [""],
        "WR_REGULATION_MARK" :  [card.REGULATION_MARK[0]]
        }

        for i in range(4):
            if( i < len(card.SKILL_NAME) ):
                self.format["WR_TECHERG"+str(i+1)] = self.Properties_Eng_to_Kor(card.SKILL_COST[i]).replace("{+}","플러스")

                if( str(type(card.SKILL_DAMAGE[i])) == "<class 'int'>" ):
                    self.format["WR_DAMAGE"+str(i+1)] = card.SKILL_DAMAGE[i]
                else:
                    self.format["WR_DAMAGE"+str(i+1)] = card.SKILL_DAMAGE[i].replace("n/a","")

                self.format["WR_AB_LABEL"+str(i+1)] = self.BoldTextCheck(self.SpecialTextCheck(card.SKILL_NAME[i]))
                self.format["WR_ABILITY"+str(i+1)] = self.BoldTextCheck(card.SKILL_TEXT[i].replace("n/a",""))

        self.format["WR_CARDTYPE_NUM"] = self.Card_Type_Number(self.format["WR_CARDTYPE"][0])
        self.format["WR_CARDTYPE"] = self.CardType_Eng_to_Kor(self.format["WR_CARDTYPE"][0])

        index = self.format["WR_NAME"][0].find("[울트라비스트]")
        if( index >= 0 ):#울트라 비스트인경우
            self.format["WR_NAME"][0] = [ self.format["WR_NAME"][0][0:index-1] ]

        #210127 신규Label대응 [일격] , [다이맥스/일격], [거다이맥스/일격], [아이템/일격], [포켓몬의 도구/일격], [서포트/일격], [스타디움/일격], [특수 에너지/일격]
        #210127 신규Label대응 [연격] , [다이맥스/연격], [거다이맥스/연격], [아이템/연격], [포켓몬의 도구/연격], [서포트/연격], [스타디움/연격], [특수 에너지/연격]
        index=self.format["WR_NAME"][0].find("격]")
        if( index >= 0 ):#일격,연격 카드인경우
            index = self.format["WR_NAME"][0].find("[")
            if( self.format["WR_NAME"][0].find("연격]") > 0):
                self.format["WR_NAME"][0] = self.format["WR_NAME"][0][0:index-1]+"[yk]연격[/yk]"  #210221 CardType ,연격추가 및 yk변경
                self.format["WR_CARDTYPE"] = self.format["WR_CARDTYPE"] + ",연격"
            else:
                self.format["WR_NAME"][0] = self.format["WR_NAME"][0][0:index-1]+"[ik]일격[/ik]"  #210221 CardType ,일격추가 및 ik변경
                self.format["WR_CARDTYPE"] = self.format["WR_CARDTYPE"] + ",일격"

        self.format["WR_NAME"][0] = self.format["WR_NAME"][0].replace("[다이맥스]","") #210127 불필요 Label제거
        self.format["WR_NAME"][0] = self.format["WR_NAME"][0].replace("[거다이맥스]","") #210127 불필요 Label제거

        self.format["WR_NAME"][0] = self.Properties_Eng_to_Kor(self.format["WR_NAME"][0]) #0905 CardName 영문 한글변환 적용

        self.Remove_null_Data("WR_POKE_NO" , int , 0)

        self.format["WR_RARITY"]=self.format["WR_RARITY"][0][1:-1] #remove ( )

        if(self.format["WR_MON_TYPE"][0] == 0): #GX인경우 Data가 0으로 들어가있으며 공백으로 전환필요
            self.format["WR_MON_TYPE"] = ""

        self.format["WR_HEIGHT"] = self.format["WR_HEIGHT"][0].replace("m", "")
        if( self.format["WR_HEIGHT"] == ""): #GX인경우 0으로 입력
            self.format["WR_HEIGHT"] = 0
        elif (  self.format["WR_HEIGHT"].find(".") > 0):
            self.format["WR_HEIGHT"] = float(self.format["WR_HEIGHT"])
        else:
            self.format["WR_HEIGHT"] = int(self.format["WR_HEIGHT"])

        self.format["WR_WEIGHT"] = self.format["WR_WEIGHT"][0].replace("kg", "")
        if( self.format["WR_WEIGHT"] == ""): #GX인경우 0으로 입력
            self.format["WR_WEIGHT"] = 0
        elif (  self.format["WR_WEIGHT"].find(".") > 0):
            self.format["WR_WEIGHT"] = float(self.format["WR_WEIGHT"])
        else:
            self.format["WR_WEIGHT"] = int(self.format["WR_WEIGHT"])

        self.format["WR_DOX_INFO"] = self.format["WR_DOX_INFO"][0].replace("\n"," ")

        self.format["WR_ILLUSTRATOR"] = self.format["WR_ILLUSTRATOR"][0].replace("n/a","")

        self.Remove_null_Data("WR_HP", int, null_val=0) #200221 Null Value 0으로 변경

        self.format["WR_CARDMONTYPE"] = self.Properties_Eng_to_Kor(self.format["WR_CARDMONTYPE"][0]) #한글변경
        self.format["WR_WEAKNESS"][0] = self.Properties_Eng_to_Kor(self.format["WR_WEAKNESS"][0])

        self.Remove_null_Data("WR_WEAKNESS_LVL",str)

        self.format["WR_RESISTANCE"] = self.Properties_Eng_to_Kor(self.format["WR_RESISTANCE"][0])

        self.Remove_null_Data("WR_RESISTANCE_LVL",int)

        self.Remove_null_Data("WR_RETREAT",int, null_val=0)

        #Make Data frame , Append to Excel File
        #df = pd.DataFrame( self.format )
        df = DataFrame( self.format )

        return df
        #self.append_df_to_excel(df , startcol = 2, index = False,  header = False)

        #df.to_excel(self.writer, sheet_name='Sheet1', startrow = 0, startcol = 2, index = False,  header = False)
        #df.to_excel(self.writer, sheet_name='Sheet1')

    def close_writer(self):
        #self.writer.close()
        return 0

class ConverterThread(QThread):

    isFinish = pyqtSignal(list)

    def __init__(self):
        super().__init__()
        self.finish = False
        self.MsgSlot = None
        self.r_fileName = None
        self.r_data = 0 #read data (JP Excel file)
        self.w_data = 0 #write data (KR Excel file)

    @pyqtSlot(list)
    def ConvertMsgSlot(self, Msg):
        self.MsgSlot = Msg[0]
        if(len(Msg) > 1): #Load Case
            self.r_fileName = Msg[1]

    def run(self):
        while True:
            #print("[ConverterThread] Wait MSG")
            if(self.MsgSlot == "LOAD"):
                print("[ConverterThread] LOAD!!")
                self.Load_JP()
                if(self.r_data.isLoadOK):
                    self.isFinish.emit([True, self.r_data]) #Read Fail case self.r_data == None
                else:
                    self.isFinish.emit([True, None]) #Read Fail casee
                self.MsgSlot = None
            elif(self.MsgSlot == "CVT_KR"):
                print("[ConverterThread] CVT_KR")
                self.Convert_KR()
                self.MsgSlot = None
                self.isFinish.emit([True])
            elif(self.MsgSlot == "CVT_TXT"):
                print("[ConverterThread] CVB_TXT")
                self.Convert_Txt()
                self.MsgSlot = None
                self.isFinish.emit([True])
            elif(self.MsgSlot == "FINISH"):
                self.MsgSlot = None
                self.isFinish.emit([True])
                break
            self.msleep(500)

        print("[ConverterThread] Thread Finish")

    def Load_JP(self):
        print ("[ConverterThread] LOAD_JP")
        print(self.r_fileName)
        self.r_data = JP_DATA(self.r_fileName)

    def Convert_KR(self):
        print ("[ConverterThread] CONVERT_KR")
        write_name = os.path.splitext(self.r_fileName)[0]+"_KOR.xlsx"
        self.w_data = KR_DATA(write_name)
        self.file_name = write_name
        df = DataFrame()
        while(True):
            card = self.r_data.Get_Card_Data()
            if(card == "EOF"):
                break
            print("NOW_CARD : %s" % card.CARD_NO[0])
            df = concat([df, self.w_data.InputCardData(card)])

        self.append_df_to_excel(df , startcol = 2, index = False,  header = False)

    def Convert_Txt(self):
        print ("[ConverterThread] CONVERT_TXT")
        write_name = os.path.splitext(self.r_fileName)[0]+".txt"
        self.r_data.SetStartPos() #ready to convert again
        self.r_data.export_txt_files(write_name)

    def closeEvent(self, event):
        print("[ConverterThread] closeEvent!!!")
        self.terminate()

    def append_df_to_excel(self, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False,
                       **to_excel_kwargs):
        '''
        Append a DataFrame [df] to existing Excel file [filename]
        into [sheet_name] Sheet.
        If [filename] doesn't exist, then this function will create it.

        Parameters:
          filename : File path or existing ExcelWriter
                     (Example: '/path/to/file.xlsx')
          df : dataframe to save to workbook
          sheet_name : Name of sheet which will contain DataFrame.
                       (default: 'Sheet1')
          startrow : upper left cell row to dump data frame.
                     Per default (startrow=None) calculate the last row
                     in the existing DF and write to the next row...
          truncate_sheet : truncate (remove and recreate) [sheet_name]
                           before writing DataFrame to Excel file
          to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                            [can be dictionary]

        Returns: None
        '''
        from openpyxl import load_workbook

        # ignore [engine] parameter if it was passed
        if 'engine' in to_excel_kwargs:
            to_excel_kwargs.pop('engine')

        #writer = pd.ExcelWriter(self.file_name, engine='openpyxl')
        writer = ExcelWriter(self.file_name, engine='openpyxl')

        try:
            # try to open an existing workbook
            writer.book = load_workbook(self.file_name)

            # get the last row in the existing Excel sheet
            # if it was not specified explicitly
            if startrow is None and sheet_name in writer.book.sheetnames:
                startrow = writer.book[sheet_name].max_row

            # truncate sheet
            if truncate_sheet and sheet_name in writer.book.sheetnames:
                # index of [sheet_name] sheet
                idx = writer.book.sheetnames.index(sheet_name)
                # remove [sheet_name]
                writer.book.remove(writer.book.worksheets[idx])
                # create an empty sheet [sheet_name] using old index
                writer.book.create_sheet(sheet_name, idx)

            # copy existing sheets
            writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
        except FileNotFoundError:
            # file does not exist yet, we will create it
            pass

        if startrow is None:
            startrow = 0

        # write out the new sheet
        df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

        # save the workbook
        writer.save()


from calico import Magic
from IPython.display import Javascript

class JavascriptMagic(Magic):
    name = "javascript"
    help_lines = [" %javascript CODE - send code as JavaScript",
                  "%%javascript - send contents of cell as JavaScript"]

    def line(self, args):
        jscode = Javascript(args)
        self.kernel.Display(jscode)

    def cell(self, args):
        if self.code.strip():
            jscode = Javascript(self.code)
            self.kernel.Display(jscode)
            self.evaluate = False

def register_magics(magics):
    magics[JavascriptMagic.name] = JavascriptMagic


#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
basepath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))

import time
import pytest
import csv
from seleniumbase import BaseCase
from parameterized import parameterized
from PageObject.DepositPricingPage import DepositPricingPage
from PageObject.HomePage import HomePage
with open(basepath + "/Config/depositpricing.csv", "r", encoding="utf-8") as rf:
    myread = csv.reader(rf)
    keylist = list(myread)

class MyTestdepositpricing(BaseCase):
    '''
    @parameterized.expand(data)
    '''

    @parameterized.expand(keylist)
    # @pytest.mark.run(order=1)
    def test_case_mrflut(self,user,password,CuNo,CuNo1,TPACuTe,TPACuTe1,NewFund,TPAAm,FundArr):
        self.open(HomePage.html)
        self.type(HomePage.username_login, user)
        self.type(HomePage.pwd_login, password)
        self.click(HomePage.submit_login)
        self.wait_for_element_visible(DepositPricingPage.DepositPricingPage_link)
        self.click(DepositPricingPage.DepositPricingPage_link)
        self.assert_text("Application Details")
        # yield filter()
        self.click(DepositPricingPage.Single_Case)
        self.type(DepositPricingPage.Customer_No, CuNo)
        self.type(DepositPricingPage.Customer_No1, CuNo1)
        self.type(DepositPricingPage.TPA_Currency_Tenor, TPACuTe)
        self.type(DepositPricingPage.TPA_Currency_Tenor1,TPACuTe1)
        self.type(DepositPricingPage.New_Fund, NewFund)
        self.type(DepositPricingPage.TPA_Amount, TPAAm)
        time.sleep(2)
        if FundArr == "资金未到账":
            self.click(DepositPricingPage.Funds_not_arrived)
            # self.click(DepositPricingPage.Calculate)
            # self.click(DepositPricingPage.Reset)
            time.sleep(2)
            self.assert_text("TMD Preference Recommendation")
            self.assert_element(DepositPricingPage.TMD_Recommendation)
            self.assert_text(DepositPricingPage.Bulletin_Board)
            self.assert_text(DepositPricingPage.Bulletin_Board_Text1)
            self.assert_text(DepositPricingPage.Bulletin_Board_Text2)
            self.assert_text(DepositPricingPage.TPA_application_process)
            self.assert_text(DepositPricingPage.TPA_application_process1)
            self.assert_text(DepositPricingPage.TPA_application_process2)
            self.assert_text(DepositPricingPage.TPA_application_process3)
            self.assert_text(DepositPricingPage.TPA_application_process4)
            self.assert_element(DepositPricingPage.Useful_Info)
            time.sleep(1)
            self.click(DepositPricingPage.Useful_Info)
            self.click(DepositPricingPage.TPA_application_process5)
            time.sleep(3)

        else:
            self.click(DepositPricingPage.Funds_not_arrived)
            self.click(DepositPricingPage.Calculate)
            time.sleep(1)
            # self.click(DepositPricingPage.Reset)
            self.click(DepositPricingPage.Back_HomePage)


from __future__ import print_function

import sys
import os

from xml.etree import ElementTree

FIELDS = {  # SQLDeveloper name -> (DBeaver name, default)
    'port': ('port', '1521'),
    'hostname': ('host', None),
    'sid': ('database', 'orcl'),
    'user': ('user', None)
}

def indent_xml(elem, level=0):  # https://stackoverflow.com/a/33956544
    tab = 4 * ' '
    i = os.linesep + level * tab
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + tab
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent_xml(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

def get_field_value(node, fieldname):
    fields = node.find('RefAddresses').findall('StringRefAddr')
    matching_field = next((x for x in fields if x.get('addrType') == fieldname), None)

    if matching_field is None:
        default = FIELDS[fieldname][1]
        name = node.get('name')
        sys.stdout.write("Missing value of '" + fieldname + "' for [ " + name + ' ]. ')

        if default is None:
            print('Could not insert default value.')
            return None

        print("Using default value ('", default, "')", sep='')
        return default

    return matching_field.find('Contents').text

if __name__ == '__main__':
    assert len(sys.argv) > 2, 'Provide input file and default password.'

    fname = sys.argv[1]
    output_fname = os.path.join(os.path.dirname(os.path.abspath(fname)), 'dbeaver-import.xml')

    input_root = ElementTree.parse(fname).getroot()
    output_root = ElementTree.Element('connections')

    for conn in input_root:
        connection_params = {FIELDS[fieldname][0]: get_field_value(conn, fieldname) for fieldname in FIELDS}
        if any(v is None for v in connection_params.values()):
            print('Connection [', conn.get('name'), '] skipped.')
            continue
        print('    Adding connection [', conn.get('name'), ']')
        connection_params['name'] = conn.get('name')
        connection_params['password'] = sys.argv[2]

        ElementTree.SubElement(output_root, 'connection', **connection_params)

    indent_xml(output_root)
    output_tree = ElementTree.ElementTree(output_root)
    output_tree.write(output_fname, encoding="utf-8", xml_declaration=True)


import pygame
from pygame.locals import *
import sys
from urllib.request import urlopen
import io
import requests
import time

pygame.init()
WIDTH = 800
HEIGHT = 600
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)

def getImages():
    r = requests.get('http://192.168.0.12:3002/images')
    print("Status: " + str(r.status_code))
    return r.json()

images = getImages()
imageCount = len(images)
print("There are " + str(imageCount) + " images")
counter = 0

while True:
   if counter == imageCount:
       counter = 0
       print(counter)

   currentImage = images[counter]['signedUrl'][0]
   image_str = urlopen(currentImage).read()
   image_file = io.BytesIO(image_str)
   screen = pygame.display.set_mode((WIDTH, HEIGHT))
   screen.fill((0, 0, 1))
   img = pygame.image.load(image_file)
   x, y = img.get_size()
   rx = WIDTH / x
   ry = HEIGHT / y
   ratio = rx if rx < ry else ry
   img = pygame.transform.scale(img, (int(x*rx), int(y*rx)))
   img_rect = img.get_rect()
   img_rect.centerx = WIDTH/2
   img_rect.centery = HEIGHT/2

   windowSurface.blit(img, img_rect)
   pygame.display.flip()

   counter += 1

   for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == K_x:  # PRESS X TO QUIT
                pygame.quit()
                sys.exit()

        if event.type == QUIT:
            pygame.quit()
            sys.exit()

   time.sleep(1)


"""Test the HF solver."""

import pytest

from forte.solvers import solver_factory, HF, SpinAnalysis

def test_solver():
    """Test RHF on H2."""

    ref_energy = -1.10015376479352

    # define a molecule
    xyz = """
    H 0.0 0.0 0.0
    H 0.0 0.0 1.0
    """

    # create a molecular model
    input = solver_factory(molecule=xyz, basis='cc-pVDZ')

    # create a HF object and run
    with pytest.raises(AssertionError):
        spin = SpinAnalysis(input)

if __name__ == "__main__":
    test_solver()


n,m, b_color = input().split()
office = []
for _ in range(int(n)):
    office.append(list(input()))
x,y = [-1,1,0,0], [0,0,1,-1]
lis=  []
for i in range(int(n)):
    for j in range(int(m)):
        if office[i][j] == b_color:
            for k in range(4):
                if i+x[k] not in [-1,int(n)] and j+y[k] not in [-1,int(m)] and office[i+x[k]][j+y[k]] not in [b_color,'.'] and (office[i+x[k]][j+y[k]] not in lis):
                    lis.append(office[i+x[k]][j+y[k]])
print(len(lis))


from pprint import pprint
from scratch.linear_algebra import distance
from collections import Counter

def raw_majority_vote(labels):
    votes = Counter(labels)
    winner, _ = votes.most_common(1)[0]
    return winner

def majority_vote(labels):
    """assumes that labels are ordered from nearest to farthest"""
    vote_counts = Counter(labels)
    winner, winner_count = vote_counts.most_common(1)[0]
    num_winners = len([count
                       for count in vote_counts.values()
                       if count == winner_count])

    if num_winners == 1:
        return winner  # unique winner, so return it
    else:
        return majority_vote(labels[:-1])  # try again without the farthest

def knn_classify(k, labeled_points, new_point):
    """each labeled point should be a pair (point, label)"""

    # order the labeled points from nearest to farthest
    by_distance = sorted(labeled_points,
                         key=lambda point_label: distance(point_label[0], new_point))

    # find the labels for the k closest
    k_nearest_labels = [label for _, label in by_distance[:k]]

    # and let them vote
    return majority_vote(k_nearest_labels)

#dataframe을 사용하지 못하므로 2차원배열로 불러옴
with open('data2.csv') as file:
    data2 = []
    for line in file.readlines():
        line = line.strip()
        data2.append(line.split(','))

#data2의 전체 데이터 출력
pprint(data2,width=220)

import random
from typing import TypeVar, List, Tuple
X = TypeVar('X')  # generic type to represent a data point
Y = TypeVar('Y')  # generic type to represent output variables
Z = TypeVar('Z')

#기존 split_data는 랜덤으로 데이터를 섞기때문에
#저장된 순서대로 데이터를 나누기위해 새로 만드는 함수
def split_data(data: List[X], prob: float) -> Tuple[List[X], List[X]]:
    """Split data into fractions [prob, 1 - prob]"""
    data = data[:]                    # Make a shallow copy
    #random.shuffle(data)
    cut = int(len(data) * prob)       # Use prob to find a cutoff
    return data[:cut], data[cut:]     # and split the shuffled list there.

#airquality컬럼도 7:3으로 나누기위해 수정하는 함수
#반환리스트가 6개
def train_test_split_edit(xs: List[X],ys: List[Y],zs: List[Z],
                     test_pct: float) -> Tuple[List[X], List[X], List[Y], List[Y], List[Z],List[Z]]:
    # Generate the indices and split them.
    idxs = [i for i in range(len(xs))]
    train_idxs, test_idxs = split_data(idxs, 1 - test_pct)

    return ([xs[i] for i in train_idxs],  # x_train
            [xs[i] for i in test_idxs],   # x_test
            [ys[i] for i in train_idxs],  # y_train
            [ys[i] for i in test_idxs],
            [zs[i] for i in train_idxs],
            [zs[i] for i in test_idxs])

# 각 컬럼에 따라 precision, recall, f1score 뽑아주는 함수
def set_dataset(pridict_data, str):
    print('\n\n<<{}의 경우>>'.format(str))
    '''good라고 한 경우 tp는 num_correct된 경우중 good의 숫자
                       fn은 good인데 good이 아닌걸로 예측(prrdict했지만 good이 아닌경우)
                       fp는 good이 아닌데 good이라고 pridict(good이리고 예측한 횟수에서 num_correct뺌)
                       tn는 아닌걸 아닌걸로 표현함 good이 아닌걸(correct_num중 good이 아닌갯수)'''

    # airquality에 대한 true positive값
    # str은 airquality의 이름
    tp = pridict_data.count((str, 'T'))

    # pridict_data.count(('good','F'))
    count = 0
    for i in range(len(pridict_data)):
        if pridict_data[i][1] == 'F':
            count += 1
    # 예상결과가 f인것중 예측값이 good이 아닌경우
    fn = count - pridict_data.count((str, 'F'))

    fp = pridict_data.count((str, 'F'))

    count = 0
    for i in range(len(pridict_data)):
        if pridict_data[i][1] == 'T':
            count += 1
    tn = count - pridict_data.count((str, 'T'))

    print('tp_{} :'.format(str), tp, 'tn_{} :'.format(str), tn, 'fp_{} :'.format(str), fp, 'fn_{} :'.format(str), fn)

    try:
        print('{}_precision : '.format(str), precision(tp, fp, fn, tn))
    except:
        print('TP와 FP값이 모두 0이기때문에 precision을 구할수 없습니다.')
    try:
        print('{}_recall : '.format(str), recall(tp, fp, fn, tn))
    except:
        print('TP와 FN값이 모두 0이기때문에 recall을 구할수 없습니다.')
    try:
        print('{}_f1score : '.format(str), f1_score(tp, fp, fn, tn))
    except:
        print('precision와 recall값이 모두 0이기때문에 f1score를 구할수 없습니다.')

cdate = []
scode = []
airquality = []

for i in range(1,len(data2)):
    cdate.append(data2[i][1]) #cdate컬럼

for i in range(1,len(data2)):
    scode.append(data2[i][4]) #측정소 코드

for i in range(1,len(data2)):
    airquality.append(data2[i][11]) #airquality 컬럼

cdate = list(map(int, cdate) )
scode = list(map(int, scode) )

#좌표는 scode,cdate 2개로 하고, 7:3으로 나눔 airquality도 7:3
cdate_train, cdate_test, scode_train, scode_test, air_train ,air_test = train_test_split_edit(cdate,scode,airquality,0.3)
labeled_points = list(zip(cdate_train,scode_train,air_train))
labeled_points = [([cdate, scode], airquality) for cdate, scode, airquality in labeled_points]
print('학습할 데이터의 갯수 : ',len(labeled_points))

#테스트 데이터 남은 30퍼센트
new_points = list(zip(cdate_test,scode_test,air_test))
new_points = [([cdate, scode], airquality) for cdate, scode, airquality in new_points]
print('테스트데이터 갯수 : ',len(new_points))

#훈련데이터에 대해
#최적의 k를 찾기위해 다 돌려봄
'''
for k in range(1,20,2):
    num_correct = 0
    for location, actual_airquality in labeled_points:
        other_points = [other_point
                for other_point in labeled_points
                        if other_point != (location, actual_airquality)]
        predicted_language = knn_classify(k, other_points, location)
        if predicted_language == actual_airquality:
                        num_correct += 1
    print(k, "neighbor[s]:", num_correct, "correct out of", len(labeled_points))

'''
'''
*훈련데이터에 대한 k값 결과
1 neighbor[s]: 2205 correct out of 5276
3 neighbor[s]: 2359 correct out of 5276
5 neighbor[s]: 2402 correct out of 5276
7 neighbor[s]: 2326 correct out of 5276
9 neighbor[s]: 2248 correct out of 5276
11 neighbor[s]: 2263 correct out of 5276
13 neighbor[s]: 2323 correct out of 5276
15 neighbor[s]: 2340 correct out of 5276
17 neighbor[s]: 2348 correct out of 5276
19 neighbor[s]: 2412 correct out of 5276

1위는 19 2위는 5였으므로 2개의 k에 대해 더 높은값을 test데이터에 입력한다
'''

pridict_data=[]             #예측한 데이터
pridict_correct_flag=[]     #예측한 데이터가 맞았을경우 T 틀리면 F

print('k=5의 경우에 대해 구하는중...')
for k in [5]:
    num_correct = 0
    for location, actual_airquality in new_points:
        other_points = [other_point
                for other_point in new_points
                        if other_point != (location, actual_airquality)]
        predicted_airquality = knn_classify(k, other_points, location)
        pridict_data.append(predicted_airquality)
        if predicted_airquality == actual_airquality:
                        #print(predicted_language,actual_language)
                        pridict_correct_flag.append('T')
                        num_correct += 1
        else : pridict_correct_flag.append('F')
    print(k, "neighbor[s]:", num_correct, "correct out of", len(new_points))

'''
* 19와 5에대한 testdata의 결과
19 neighbor[s]: 881 correct out of 2262
5 neighbor[s]: 924 correct out of 2262

'''

from scratch.machine_learning import precision,recall,f1_score

'''good라고 한 경우 tp는 num_correct된 경우중 good의 숫자
                   fn은 good인데 good이 아닌걸로 예측(prrdict했지만 good이 아닌경우)
                   fp는 good이 아닌데 good이라고 pridict(good이리고 예측한 횟수에서 num_correct뺌)
                   tn는 아닌걸 아닌걸로 표현함 good이 아닌걸(correct_num중 good이 아닌갯수)'''

print(pridict_data)             #예측한 공기질
print(pridict_correct_flag)     #예측한 공기질이 맞았는지 확인

#위 두개를 합쳐줌
pridict_data = list(zip(pridict_data,pridict_correct_flag))

#set_dataset함수를 통해 precision과 recall과 f1-score을 뽑아줌

set_dataset(pridict_data,'best')

set_dataset(pridict_data,'better')

set_dataset(pridict_data,'good')

set_dataset(pridict_data,'normal')

set_dataset(pridict_data,'bad')

set_dataset(pridict_data,'worse')

set_dataset(pridict_data,'serious')

set_dataset(pridict_data,'worst')


"""problems and contests table

Revision ID: 6e50a673f778
Revises: f1cfb4662273
Create Date: 2021-12-01 00:18:35.135278

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '6e50a673f778'
down_revision = 'f1cfb4662273'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('contest',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('title', sa.String(length=50), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('problem',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('title', sa.String(length=50), nullable=True),
    sa.Column('statement', sa.String(length=400), nullable=True),
    sa.Column('answer', sa.Integer(), nullable=True),
    sa.Column('contest_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['contest_id'], ['contest.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('problem')
    op.drop_table('contest')
    # ### end Alembic commands ###


# Testcase definition file.

import pdb
import copy

import types_pb2                as types_pb2
import internal_pb2          as internal_pb2
#import internal_pb2_grpc     as internal_pb2_grpc

from iris.config.store               import Store
from infra.common.objects import ObjectDatabase as ObjectDatabase
from infra.common.logging import logger
from infra.common.glopts import GlobalOptions

rnmdr = 0
ipseccbq = 0
ipseccb = 0
iv = 0
seq = 0

def Setup(infra, module):
    print("Setup(): Sample Implementation")
    elem = module.iterator.Get()
    module.testspec.selectors.flow.Extend(elem.flow)
    return

def Teardown(infra, module):
    print("Teardown(): Sample Implementation.")
    return

def TestCaseSetup(tc):
    global ipseccbq
    global ipseccb
    global rnmdr
    global iv
    global seq

    tc.pvtdata = ObjectDatabase()
    print("TestCaseSetup(): Sample Implementation.")
    # 1. Configure IPSECCB in HBM before packet injection
    ipseccb = tc.infra_data.ConfigStore.objects.db["IPSECCB0000"]
    key_type = types_pb2.CRYPTO_KEY_TYPE_AES128
    key_size = 16
    key = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    ipseccb.crypto_key.Update(key_type, key_size, key)

    ipseccb.tunnel_sip4               = 0x0A010001
    ipseccb.tunnel_dip4               = 0x0A010002
    ipseccb.iv_size                   = 8
    ipseccb.icv_size                  = 16
    ipseccb.block_size                = 16
    ipseccb.key_index                 = 0
    ipseccb.barco_enc_cmd             = 0x30000000
    ipseccb.iv                        = 0xaaaaaaaaaaaaaaaa
    ipseccb.iv_salt                   = 0xbbbbbbbb
    ipseccb.esn_hi                    = 0
    ipseccb.esn_lo                    = 0
    ipseccb.spi                       = 0
    ipseccb.is_nat_t                  = 1
    ipseccb.is_v6                     = 0
    ipseccb.vrf_vlan                  = 0x0005
    ipseccb.key_index                 = ipseccb.crypto_key.keyindex
    ipseccb.SetObjValPd()

    seq = ipseccb.esn_lo
    iv = ipseccb.iv

    # 2. Clone objects that are needed for verification
    rnmdr = copy.deepcopy(tc.infra_data.ConfigStore.objects.db["IPSEC_RNMDR"])
    rnmdr.GetMeta()
    rnmdr.GetRingEntries([rnmdr.pi, rnmdr.pi + 1])
    rnmdr.GetRingEntryAOL([rnmdr.pi, rnmdr.pi + 1])
    ipseccbq = copy.deepcopy(tc.infra_data.ConfigStore.objects.db["IPSECCB0000_IPSECCBQ"])
    ipseccb = tc.infra_data.ConfigStore.objects.db["IPSECCB0000"]

    rnmpr = copy.deepcopy(tc.infra_data.ConfigStore.objects.db["IPSEC_RNMPR"])
    rnmpr.GetMeta()
    rnmpr.GetRingEntries([rnmpr.pi])
    tnmdr = copy.deepcopy(tc.infra_data.ConfigStore.objects.db["IPSEC_TNMDR"])
    tnmdr.GetMeta()
    tnmdr.GetRingEntries([tnmdr.pi])
    tnmpr = copy.deepcopy(tc.infra_data.ConfigStore.objects.db["IPSEC_TNMPR"])
    tnmpr.GetMeta()
    tnmpr.GetRingEntries([tnmpr.pi])

    brq = copy.deepcopy(tc.infra_data.ConfigStore.objects.db["BRQ_ENCRYPT_GCM"])
    brq.GetMeta()
    brq.GetRingEntries([brq.pi])

    tc.pvtdata.Add(rnmdr)
    tc.pvtdata.Add(rnmpr)
    tc.pvtdata.Add(tnmdr)
    tc.pvtdata.Add(tnmpr)
    tc.pvtdata.Add(brq)
    return

def TestCaseVerify(tc):
    global ipseccbq
    global ipseccb

    # 1. Verify pi/ci got update got updated
    ipseccb_cur = tc.infra_data.ConfigStore.objects.db["IPSECCB0000"]
    print("pre-sync: ipseccb_cur.pi %d ipseccb_cur.ci %d" % (ipseccb_cur.pi, ipseccb_cur.ci))
    ipseccb_cur.GetObjValPd()
    print("post-sync: ipseccb_cur.pi %d ipseccb_cur.ci %d" % (ipseccb_cur.pi, ipseccb_cur.ci))
    if (ipseccb_cur.pi != ipseccb.pi or ipseccb_cur.ci != ipseccb.ci):
        print("serq pi/ci not as expected")
        return False
    # 3. Fetch current values from Platform
    ipseccbqq_cur = tc.infra_data.ConfigStore.objects.db["IPSECCB0000_IPSECCBQ"]
    ipseccbqq_cur.Configure()

    rnmdr = tc.pvtdata.db["IPSEC_RNMDR"]
    rnmpr = tc.pvtdata.db["IPSEC_RNMPR"]
    tnmdr = tc.pvtdata.db["IPSEC_TNMDR"]
    tnmpr = tc.pvtdata.db["IPSEC_TNMPR"]

    rnmdr_cur = tc.infra_data.ConfigStore.objects.db["IPSEC_RNMDR"]
    rnmdr_cur.GetMeta()
    rnmdr_cur.GetRingEntries([rnmdr_cur.pi, rnmdr_cur.pi + 1])
    rnmdr_cur.GetRingEntryAOL([rnmdr_cur.pi, rnmdr_cur.pi + 1])

    rnmpr_cur = tc.infra_data.ConfigStore.objects.db["IPSEC_RNMPR"]
    rnmpr_cur.GetMeta()
    rnmpr_cur.GetRingEntries([rnmpr.pi,rnmpr_cur.pi])

    tnmdr_cur = tc.infra_data.ConfigStore.objects.db["IPSEC_TNMDR"]
    tnmdr_cur.GetMeta()
    tnmdr_cur.GetRingEntries([tnmdr.pi,tnmdr_cur.pi])

    tnmpr_cur = tc.infra_data.ConfigStore.objects.db["IPSEC_TNMPR"]
    tnmpr_cur.GetMeta()
    tnmpr_cur.GetRingEntries([tnmpr.pi,tnmpr_cur.pi])

    # 2. Verify PI for IPSEC_RNMDR got incremented by 1
    if (rnmdr_cur.pi - rnmdr.pi > 2):
        print("IPSEC_RNMDR pi check failed old %d new %d" % (rnmdr.pi, rnmdr_cur.pi))
        return False

    # 4. Verify pi/ci got update got updated for BRQ
    brq = tc.pvtdata.db["BRQ_ENCRYPT_GCM"]
    brq_cur = tc.infra_data.ConfigStore.objects.db["BRQ_ENCRYPT_GCM"]
    print("pre-sync: brq_cur.pi %d brq_cur.ci %d" % (brq_cur.pi, brq_cur.ci))
    brq_cur.GetMeta()
    brq_cur.GetRingEntries([brq.pi, brq_cur.pi])
    print("post-sync: brq_cur.pi %d brq_cur.ci %d" % (brq_cur.pi, brq_cur.ci))
    if (brq_cur.pi != (brq.pi+1)):
        print("brq pi/ci not as expected")
        #needs fix in HAL and support in model/p4+ for this check to work/pass
        return False

    print("BRQ:")
    print("ilist_addr 0x%x" % brq_cur.ring_entries[brq.pi].ilist_addr)
    print("olist_addr 0x%x" % brq_cur.ring_entries[brq.pi].olist_addr)
    print("command 0x%x" % brq_cur.ring_entries[brq.pi].command)
    print("key_desc_index 0x%x" % brq_cur.ring_entries[brq.pi].key_desc_index)
    print("iv_addr 0x%x" % brq_cur.ring_entries[brq.pi].iv_addr)
    print("status_addr 0x%x" % brq_cur.ring_entries[brq.pi].status_addr)
    # There is an offset of 64 to go past scratch when queuing to barco. Pls modify
    # this when this offset is removed.
    #maxflows check should be reverted when we remove the hardcoding for idx 0 with pi/ci for BRQ
    # 5. Verify brq input desc and rnmdr
    print("IPSEC_RNMDR Entry: 0x%x, BRQ ILIST: 0x%x" % (rnmdr.ringentries[rnmdr.pi].handle, brq_cur.ring_entries[brq.pi].ilist_addr))
    if (rnmdr.ringentries[rnmdr.pi].handle != (brq_cur.ring_entries[brq.pi].ilist_addr - 0x40)):
        print("Descriptor handle not as expected in ringentries  for ilist 0x%x 0x%x" % (rnmdr.ringentries[rnmdr.pi].handle, brq_cur.ring_entries[brq.pi].ilist_addr))
        return False

    # 8. Verify PI for IPSEC_TNMDR got incremented by 1
    if (tnmdr_cur.pi != tnmdr.pi+1):
        print("IPSEC_TNMDR pi check failed old %d new %d" % (tnmdr.pi, tnmdr_cur.pi))
        return False
    print("Old IPSEC_TNMDR PI: %d, New IPSEC_TNMDR PI: %d" % (tnmdr.pi, tnmdr_cur.pi))

    # 9. Verify PI for IPSEC_TNMPR got incremented by 1
    if (tnmpr_cur.pi != tnmpr.pi+1):
        print("IPSEC_TNMPR pi check failed old %d new %d" % (tnmpr.pi, tnmpr_cur.pi))
        return False
    print("Old IPSEC_TNMPR PI: %d, New IPSEC_TNMPR PI: %d" % (tnmpr.pi, tnmpr_cur.pi))

    return True

def TestCaseTeardown(tc):
    print("TestCaseTeardown(): Sample Implementation.")
    return


import pickle
import pandas as pd
from scipy.io import loadmat

NNpredict = pd.read_pickle('Data/NNpickle.pickle')
data = loadmat('Data/ex3data1.mat')

X = data['X']
y = data['y']

correct = [1 if a == b else 0 for (a, b) in zip(NNpredict, y)]
accuracy = (sum(map(int, correct)) / float(len(correct)))
print ('accuracy = {0}%'.format(accuracy * 100))


from __future__ import print_function
import time
import numpy as np
from . import constants

def clamp(value, min, max):
    if value < min:
        return min
    elif value > max:
        return max
    else:
        return value

def point_in(point, rect):
    return point[0] > rect[0] and point[0] < (rect[0]+rect[2]) and point[1] > rect[1] and point[1] < (rect[1]+rect[3])

def close_to_wall(robot):
    return min(robot.left_long_ir.distInches, robot.right_long_ir.distInches) < constants.close_to_wall

class Profiler(object):
    ENABLED = True
    def __init__(self, name, indent=''):
        self.name = name
        self.indent = indent
        self.has_children = False

    def __enter__(self):
        self.t = time.time()
        if self.ENABLED:
            print(self.indent +'Timing {}... '.format(self.name), end='')
        return self

    def __exit__(self, *args):
        if not self.ENABLED: return
        if self.has_children:
            print()
            print(self.indent + '  ' + str(time.time() - self.t))
        else:
            print(str(time.time() - self.t))

    def __call__(self, name):
        if self.ENABLED:
            print()
        self.has_children = True
        return Profiler(name, self.indent + '  ')

class PID(object):
    def __init__(self, kP, kI=0, kD=0, setpoint=0):
        self.kP = kP
        self.kI = kI
        self.kD = kD
        self.setpoint = setpoint
        self.reset()

    def reset(self):
        self._last_err = 0
        self._last_time = None
        self._integral = 0
        self._last_derror = 0

    @property
    def error(self):
        return self._last_err

    @property
    def derror(self):
        return self._last_derror

    def at_goal(self, err_t, derr_t=None):
        ok = abs(self.error) < err_t
        if derr_t is not None:
            ok = ok and abs(self.derror) < derr_t
        return ok

    def iterate(self, val, dval=None):
        this_time = time.time()

        # P
        err = self.setpoint - val

        # I
        if self._last_time is not None and np.isfinite(val).all():
            self._integral += err*(this_time - self._last_time)

        # D
        if dval is not None:
            # TODO: include d/dt(setpoint)?
            derr = -dval
        elif self._last_time is not None and np.isfinite(val).all():
            derr = (err - self._last_err)/(this_time - self._last_time)
        else:
            derr = 0

        self._last_time = this_time
        self._last_err = err
        self._last_derror = derr
        return self.kP * err + self.kI * self._integral + self.kD * derr


#!/usr/bin/python
import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt
from numpy.polynomial.laguerre import lagval
from scipy import optimize

def solve_disp_eqn(xs,ws,lmbda):
    """Construct integral equation and find where it has a solution
    """
    eqtn = np.zeros((len(xs),len(xs)))
    # Compute the kernel of integral equation
    def IE_kernel(k_,kk_,lambda_,p_):
        """Kernel of integral equation is integral itself
        """
        res = 1./np.pi/(k_**2+kk_**2+p_**2)
        def kern_fun(kkk_):
            """Function to integrate
            """
            ans = 1./(k_**2+(k_-kkk_)**2+p_**2)/(kk_**2+(kk_-kkk_)**2+p_**2)
            sqrt_ = np.sqrt(2.*p_**2+kkk_**2)
            ans *= sqrt_/(sqrt_+lambda_)
            return ans
        ks = (1.+xs)/(1.-xs)
        dkdx = 2./(1.-xs)**2
        integr = sum(ws*kern_fun( ks )* dkdx) + sum(ws*kern_fun( -ks )* dkdx)
        res -= 2.*lambda_/np.pi**2 * integr
        return res
    # Define the matrix of integral equation
    def det_eqtn(p):
        def phi(k_):
            return 1.-1./(k_*k_+p*p)**0.5
        for i in range(len(xs)):
            ki = (1.+xs[i])/(1.-xs[i])
            for j in range(len(xs)):
                kj = (1.+xs[j])/(1.-xs[j])
                dkdx = 2./(1.-xs[j])**2
                eqtn[i,j] = ws[j]*IE_kernel(ki,kj,lmbda,p)*dkdx
                eqtn[i,j] += ws[j]*IE_kernel(ki,-kj,lmbda,p)*dkdx
            eqtn[i,i] -= phi(ki)
        return la.det(eqtn)

    return optimize.brenth(det_eqtn,1.,np.sqrt(2))

    """
    Решение Диракиума методом Хартри - Фока
    """
def solve_HF(lambd):

    #нулевое приближение концентрации
    n = np.exp(-2*abs(x))
    Lag = np.zeros((G,L))
    for i in range(L):
        Lag[:,i] = lagval(x, np.eye(1, i+1,i)[0])
    i = 0
    #итерационная процедура
    while i<=M:
        T = matrix_T()
        V = matrix_V(lambd,n,Lag)
        H = T+V
        E1,C1 = np.linalg.eigh(H)
        C = C1[:,0]
        e = E1[0]
        F = find_F(C,x,Lag)
        F = F/np.sqrt(intg(F**2))
        n = F**2*ksi+n*(1-ksi)
        i = i+1
    J = lambd*intg(F**4)
    E = 2*e-J
    return E

def find_F(K,x,Lag):
    "вычисление в.ф"
    F = np.zeros(G)
    for i in range(L):
        F = F+K[i]*Lag[:,i]*np.exp(-x/2)
    return F

def matrix_T():
    "матрица кинетической энергии"
    T = np.zeros((L,L))
    for k in range(L):
        for l in range(L):
            if k<l:
                T[k,l] = 0.5*(0.5 + k)
            if k>l:
                T[k,l] = 0.5*(0.5 + l)
            if k==l:
                T[k,l] = 0.5*(0.25 + k )
    return T

def matrix_V(lambd,n,Lag):
    "матрица потенциальной энергии"
    V = np.zeros((L,L))
    A = np.multiply(w,n)
    for i in range(L):
        for j in range(L):
            B = np.multiply(Lag[:,i],Lag[:,j])
            V[i,j] = -1/2+lambd*np.dot(A,B)

    return V

def intg(F):
    "взятие интеграла"
    I=0
    for i in range(L):
        I=I+w[i]*np.exp(x[i])*F[i]
    return 2*I

"""
Задача 9.1
"""
# Диапазон lambda
N = 15
lambd = np.linspace(0.1,2.6,N)
# Число функций Лагера
L = 10
# Число итераций для  нелинейной задачи на собственные значения
M = 100
# Демпфер (для сходимости итерационной процедуры)
ksi = 0.25
# Число корней полиномов Гаусса-Лаггера для взятия интегралов от концентрации
G = 30
x, w = np.polynomial.laguerre.laggauss(G)
E = np.empty_like(lambd)
for k in range(N):
    E[k] = solve_HF(lambd[k])
plt.figure(1)
plt.plot(lambd, E ,'x', color = 'r')
plt.xlabel("lambda")
plt.ylabel("E")
lambd1 = np.linspace(0.01,2.6,30)
E1 = -1 + 0.5*lambd1 - lambd1**2/12
plt.plot(lambd1,E1, color = 'b')
plt.title(" Хартри-Фок (red), аналитическое(blue)")

"""
Задача 9.2
"""
polyorder = 10
X, W = np.polynomial.legendre.leggauss(polyorder)
#Дмапазон именения lambda
ll = np.linspace(0.1,2.6,N)
E1 = np.empty_like(ll)
for k in range(N):
    E1[k] = -1/2*solve_disp_eqn(X,W,ll[k])**2
plt.figure(2)
plt.plot(ll, E1 ,'o', color = 'b')
plt.plot(lambd, E ,'x', color = 'r')
plt.xlabel("lambda")
plt.ylabel("E")
plt.title("Численное из семинара 8(blue), Хартри-Фок(red)")
plt.show()


import pandas as pd

class GetData():
    excelFormats = ('.xlsx', '.xls', '.xlsm') # type: tuple
    csvFormats = ('.csv', '.txt') # type: tuple
    def __init__(self, directory, separator=None):
        # type: (str, str) -> None
        self._directory = directory

        if self._directory.lower().endswith(self.excelFormats):
            self._dataFame = pd.read_excel(self._directory)
        elif self._directory.lower().endswith(self.csvFormats):
            if separator is None:
                raise ValueError('CSV/Text file provided but no separator given')
            self._dataFame = pd.read_csv(self._directory, delimiter=separator)
        else:
            raise TypeError('Unrecognized file type, please use ' + self._acceptableFormats() + ' files')

    def _acceptableFormats(self):
        # type: () -> str
        extensionList = list(self.excelFormats)
        extensionList.extend(list(self.csvFormats))
        return  str(extensionList).strip('[').strip(']')

    @property
    def Data(self):
        # type: () -> DataFrame
        return self._dataFame
    @property
    def SetData(self,dataFrame):
        # type: (DataFrame) -> None
        self._dataFame = dataFrame


#!/usr/bin/env python
"""
This script uses Essentia in order to extract a set of features to be used
as input for the segmentation algorithms.

Features to be computed:

- MFCC: Mel Frequency Cepstral Coefficients
- HPCP: Harmonic Pithc Class Profile
- Beats
"""

__author__ = "Oriol Nieto"
__copyright__ = "Copyright 2014, Music and Audio Research Lab (MARL)"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "oriol@nyu.edu"

import argparse
import datetime
import essentia
import essentia.standard as ES
from essentia.standard import YamlOutput
from joblib import Parallel, delayed
import logging
import numpy as np
import os
import time

# Local stuff
import msaf
from msaf import jams2
from msaf import utils
from msaf import input_output as io

class STFTFeature:
    """Class to easily compute the features that require a frame based
        spectrum process (or STFT)."""
    def __init__(self, frame_size, hop_size, window_type, feature, sample_rate,
                 beats=None):
        """STFTFeature constructor."""
        self.frame_size = frame_size
        self.hop_size = hop_size
        self.window_type = window_type
        self.w = ES.Windowing(type=window_type)
        self.spectrum = ES.Spectrum()
        self.feature = feature  # Essentia feature object
        self.beats = beats
        self.sample_rate = sample_rate

    def compute_features(self, audio):
        """Computes the specified Essentia features from the audio array."""
        features = []

        for frame in ES.FrameGenerator(audio,
                frameSize=self.frame_size, hopSize=self.hop_size):
            if self.feature.name() == "MFCC":
                bands, coeffs = self.feature(self.spectrum(self.w(frame)))
            elif self.feature.name() == "HPCP":
                spectral_peaks = ES.SpectralPeaks()
                freqs, mags = spectral_peaks(self.spectrum(self.w(frame)))
                coeffs = self.feature(freqs, mags)
            features.append(coeffs)

        # Convert to Essentia Numpy array
        features = essentia.array(features)

        # Make beat-synchronous if we have the beats
        if self.beats is not None and self.beats != []:
            framerate = self.sample_rate / float(self.hop_size)
            tframes = np.arange(features.shape[0]) / float(framerate)
            features = utils.resample_mx(features.T, tframes, self.beats).T

        return features

def double_beats(beats):
    """Double the beats."""
    new_beats = []
    for i, beat in enumerate(beats[:-1]):
        new_beats.append(beat)
        new_beats.append((beat + beats[i + 1]) / 2.0)
    return essentia.array(new_beats)

def compute_beats(audio):
    """Computes the beats using Essentia."""
    logging.info("Computing Beats...")
    conf = 1.0
    beats, conf = ES.BeatTrackerMultiFeature()(audio)
    # beats = ES.BeatTrackerDegara()(audio)
    beats *= 44100 / msaf.Anal.sample_rate  # Essentia requires 44100 input

    # Double the beats if found beats are too little
    th = 0.9  # 1 would equal to at least 1 beat per second
    while beats.shape[0] / (audio.shape[0] / float(msaf.Anal.sample_rate)) < th \
            and beats.shape[0] > 2:
        beats = double_beats(beats)
    return beats, conf

def compute_features(audio, beats=None):
    """Computes the HPCP and MFCC beat-synchronous features given a set
        of beats (beats)."""
    beatsync_str = ""
    if beats is not None:
        beatsync_str = "Beat-synchronous "

    MFCC = STFTFeature(msaf.Anal.frame_size, msaf.Anal.hop_size,
                       msaf.Anal.window_type,
                       ES.MFCC(numberCoefficients=msaf.Anal.mfcc_coeff),
                       msaf.Anal.sample_rate, beats)
    HPCP = STFTFeature(msaf.Anal.frame_size, msaf.Anal.hop_size,
                       msaf.Anal.window_type, ES.HPCP(), msaf.Anal.sample_rate,
                       beats)
    logging.info("Computing %sMFCCs..." % beatsync_str)
    mfcc = MFCC.compute_features(audio)
    logging.info("Computing %sHPCPs..." % beatsync_str)
    hpcp = HPCP.compute_features(audio)
    #plt.imshow(hpcp.T, interpolation="nearest", aspect="auto"); plt.show()
    logging.info("Computing %sTonnetz..." % beatsync_str)
    tonnetz = utils.chroma_to_tonnetz(hpcp)
    return mfcc, hpcp, tonnetz

def save_features(key, pool, mfcc, hpcp, tonnetz):
    """Saves the features into the specified pool under the given key."""
    [pool.add(key + ".mfcc", essentia.array(mfcc_coeff))
        for mfcc_coeff in mfcc]
    [pool.add(key + ".hpcp", essentia.array(hpcp_coeff))
        for hpcp_coeff in hpcp]
    [pool.add(key + ".tonnetz", essentia.array(tonnetz_coeff))
        for tonnetz_coeff in tonnetz]

def read_audio(audio_file, sample_rate):
    """Reads the audio file using Essentia."""
    audio = ES.MonoLoader(filename=audio_file,
                          sampleRate=sample_rate)()
    return audio

def compute_features_for_audio_file(audio_file):
    # Load Audio
    logging.info("Loading audio file %s" % os.path.basename(audio_file))
    audio = read_audio(audio_file, msaf.Anal.sample_rate)

    # Output features dict
    features = {}

    # Compute framesync features
    features["mfcc"], features["hpcp"], features["tonnetz"] = \
        compute_features(audio)

    # Estimate Beats
    features["beats"], features["beats_conf"] = compute_beats(audio)

    # Compute Beat-sync features
    features["bs_mfcc"], features["bs_hpcp"], features["bs_tonnetz"] = \
        compute_features(audio, features["beats"])

    # Analysis parameters
    features["anal"] = {}
    features["anal"]["frame_rate"] = msaf.Anal.frame_size
    features["anal"]["hop_size"] = msaf.Anal.hop_size
    features["anal"]["mfcc_coeff"] = msaf.Anal.mfcc_coeff
    features["anal"]["sample_rate"] = msaf.Anal.sample_rate
    features["anal"]["window_type"] = msaf.Anal.window_type
    features["anal"]["dur"] = audio.shape[0] / float(msaf.Anal.sample_rate)

    return audio, features

def compute_all_features(file_struct, audio_beats=False, overwrite=False):
    """Computes all the features for a specific audio file and its respective
        human annotations. It creates an audio file with the estimated
        beats if needed."""

    # Output file
    out_file = file_struct.features_file

    if os.path.isfile(out_file) and not overwrite:
        return  # Do nothing, file already exist and we are not overwriting it

    # Compute the features for the given audio file
    audio, features = compute_features_for_audio_file(file_struct.audio_file)

    # Save output as audio file
    if audio_beats:
        logging.info("Saving Beats as an audio file")
        marker = ES.AudioOnsetsMarker(onsets=features["beats"], type='beep',
                                      sampleRate=msaf.Anal.sample_rate)
        marked_audio = marker(audio)
        ES.MonoWriter(filename='beats.wav',
                      sampleRate=msaf.Anal.sample_rate)(marked_audio)

    # Read annotations if they exist in path/references_dir/file.jams
    if os.path.isfile(file_struct.ref_file):
        jam = jams2.load(file_struct.ref_file)

        # If beat annotations exist, compute also annotated beatsyn features
        if jam.beats != []:
            logging.info("Reading beat annotations from JAMS")
            annot = jam.beats[0]
            annot_beats = []
            for data in annot.data:
                annot_beats.append(data.time.value)
            annot_beats = essentia.array(np.unique(annot_beats).tolist())
            annot_mfcc, annot_hpcp, annot_tonnetz = compute_features(
                audio, annot_beats)

    # Save output as json file
    logging.info("Saving the JSON file in %s" % out_file)
    yaml = YamlOutput(filename=out_file, format='json')
    pool = essentia.Pool()
    pool.add("beats.times", features["beats"])
    pool.add("beats.confidence", features["beats_conf"])
    pool.set("analysis.sample_rate", msaf.Anal.sample_rate)
    pool.set("analysis.frame_rate", msaf.Anal.frame_size)
    pool.set("analysis.hop_size", msaf.Anal.hop_size)
    pool.set("analysis.window_type", msaf.Anal.window_type)
    pool.set("analysis.mfcc_coeff", msaf.Anal.mfcc_coeff)
    pool.set("timestamp",
             datetime.datetime.today().strftime("%Y/%m/%d %H:%M:%S"))
    save_features("framesync", pool, features["mfcc"], features["hpcp"],
                  features["tonnetz"])
    save_features("est_beatsync", pool, features["bs_mfcc"],
                  features["bs_hpcp"], features["bs_tonnetz"])
    if os.path.isfile(file_struct.ref_file) and jam.beats != []:
        save_features("ann_beatsync", pool, annot_mfcc, annot_hpcp,
                      annot_tonnetz)
    yaml(pool)

def process(in_path, audio_beats=False, n_jobs=1, overwrite=False):
    """Main process."""

    # If in_path it's a file, we only compute one file
    if os.path.isfile(in_path):
        compute_all_features(in_path, audio_beats, overwrite)

    elif os.path.isdir(in_path):
        # Check that in_path exists
        utils.ensure_dir(in_path)

        # Get files
        file_structs = io.get_dataset_files(in_path)

        # Compute features using joblib
        Parallel(n_jobs=n_jobs)(delayed(compute_all_features)(
            file_struct, audio_beats, overwrite)
            for file_struct in file_structs)

def main():
    """Main function to parse the arguments and call the main process."""
    parser = argparse.ArgumentParser(description=
        "Extracts a set of features from the Segmentation dataset or a given "
        "audio file and saves them into the 'features' folder of the dataset",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("in_path",
                        action="store",
                        help="Input dataset dir or audio file")
    parser.add_argument("-a",
                        action="store_true",
                        dest="audio_beats",
                        help="Output audio file with estimated beats",
                        default=False)
    parser.add_argument("-j",
                        action="store",
                        dest="n_jobs",
                        type=int,
                        help="Number of jobs (threads)",
                        default=4)
    parser.add_argument("-ow",
                        action="store_true",
                        dest="overwrite",
                        help="Overwrite the previously computed features",
                        default=False)
    args = parser.parse_args()
    start_time = time.time()

    # Setup the logger
    logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',
        level=logging.INFO)

    # Run the algorithm
    process(args.in_path, args.audio_beats, n_jobs=args.n_jobs,
            overwrite=args.overwrite)

    # Done!
    logging.info("Done! Took %.2f seconds." % (time.time() - start_time))

if __name__ == '__main__':
    main()


import os
import re
import json
import requests
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
import matplotlib.pyplot as plt

from config import covid_path

class DayStatistic:

    def __init__(self, active, active_new, cured, cured_new, dead, dead_new, cases,
                 cases_new: int):
        self.active = active
        self.active_new = active_new
        self.cured = cured
        self.cured_new = cured_new
        self.dead = dead
        self.dead_new = dead_new
        self.cases = cases
        self.cases_new = cases_new

class Encoder(json.JSONEncoder):
    def default(self, o):
        return o.__dict__

class Coronavirus:
    url = 'https://coronavirusstat.ru/country/russia/'

    REGEX_DATES = r''
    REGEX_COL_DATA = r'\d*\.\d+|\d+'

    def __init__(self):
        self.__last_update = None
        self.__message = None

    def get_data(self):
        page = requests.get(self.url)
        soup = BeautifulSoup(page.text, 'html.parser')
        table = soup.findAll('table')[0]
        table_body = table.find('tbody')

        data = {}
        rows = table_body.findAll('tr')

        for row in rows:
            cols = row.find_all('td')
            cols = [ele.text.strip() for ele in cols]
            active_data = re.findall(self.REGEX_COL_DATA, cols[0])
            cured_data = re.findall(self.REGEX_COL_DATA, cols[1])
            dead_data = re.findall(self.REGEX_COL_DATA, cols[2])
            cases_data = re.findall(self.REGEX_COL_DATA, cols[3])

            date = str(row.find('th').contents[0])
            data.update({date: DayStatistic(
                int(active_data[0]), int(active_data[1]),
                int(cured_data[0]), int(cured_data[1]),
                int(dead_data[0]), int(dead_data[1]),
                int(cases_data[0]), int(cases_data[1])
            )})

        dates = list(data.keys())
        dates.reverse()

        y1 = [data[date].active for date in dates]
        y2 = [data[date].cured for date in dates]
        y3 = [data[date].dead for date in dates]

        labels = ['Активных', 'Вылечено', 'Умерло']

        fig, ax = plt.subplots()
        ax.stackplot(dates, y1, y2, y3, labels=labels)
        ax.legend(loc='upper left')
        plt.title('Россия - детальная статистика - коронвирус')
        fig.autofmt_xdate()

        page = requests.get(self.url)
        soup = BeautifulSoup(page.text, 'html.parser')
        update = soup.find('h6').find('strong').contents[0]
        today = dates[9]

        message = 'По состоянию на {}\nСлучаев: {} (+{} за сегодня)\nАктивных: {} (+{} за сегодня)\nВылечено: {} (+{} за сегодня)\nУмерло: {} (+{} за сегодня)'.format(
            update,
            data[today].cases, data[today].cases_new,
            data[today].active, data[today].active_new,
            data[today].cured, data[today].cured_new,
            data[today].dead, data[today].dead_new
        )

        if not os.path.exists(covid_path):
            os.makedirs(covid_path)

        fig.savefig(covid_path + 'covid.png')

        file = open(covid_path + 'data.json', 'w')
        file.write(json.dumps(data, ensure_ascii=False, indent=4, cls=Encoder))
        file.close()

        self.update_info(today, message)

    def get_message(self):
        if self.__last_update is not None and self.__message is not None:
            if not self.check_update(self.__last_update):
                return self.__message

        if not os.path.exists(covid_path + 'info.json') or not os.path.exists(covid_path + 'covid.png'):
            self.get_data()

        file = open(covid_path + 'info.json', 'r')
        data = json.load(file)
        file.close()

        if self.check_update(str(data['last_update'])):
            self.get_data()
            file = open(covid_path + 'info.json', 'r')
            data = json.load(file)
            file.close()

        self.__last_update = data['last_update']
        self.__message = data['message']
        return self.__message

    @staticmethod
    def get_image():
        if os.path.exists(covid_path + 'covid.png'):
            return covid_path + 'covid.png'

    @staticmethod
    def check_update(last_update):
        now = datetime.now() - timedelta(days=1)
        last_updated_date = datetime.strptime(last_update + ' 10:45', '%d.%m.%Y %H:%M')
        return now > last_updated_date

    @staticmethod
    def update_info(last_update, message):
        info = {'last_update': last_update, 'message': message}
        file = open(covid_path + 'info.json', 'w')
        file.write(json.dumps(info, ensure_ascii=False, indent=4))
        file.close()


import pandas as pd
import numpy as np
import json
from datetime import datetime as dt
import plotly.graph_objects as go
import plotly.express as px
import os
import argparse

aparser = argparse.ArgumentParser(description="Generate weekly contact blob")
aparser.add_argument(
    "--output-dir",
    nargs="?",
    default="postcovid_plots",
    help="Output directory where the files will be saved",
)
args = aparser.parse_args()

# Import and sort data
healthcare_contacts = pd.read_excel(
    "https://www.socialstyrelsen.se/globalassets/sharepoint-dokument/dokument-webb/statistik/statistik-postcovid.xlsx",
    sheet_name="Postcovid - diagnoser över tid",
    header=4,
    engine="openpyxl",
    keep_default_na=False,
)

healthcare_contacts = healthcare_contacts.replace(
    {
        "v1": "1",
        "v2": "2",
        "v3": "3",
        "v4": "4",
        "v5": "5",
        "v6": "6",
        "v7": "7",
        "v8": "8",
        "v9": "9",
        "X": "",
        "2020 ": "",
        "2021 ": "",
        "2022 ": "",
        "2023 ": "",
    },
    regex=True,
)

healthcare_contacts["Year"] = np.nan
healthcare_contacts.loc[:32, "Year"] = 2020
healthcare_contacts.loc[32:84, "Year"] = 2021
healthcare_contacts.loc[84:136, "Year"] = 2022
healthcare_contacts.loc[136:188, "Year"] = 2023
# if this is still being used in 2024, we will need to add (written week 2 of 2022)

# Need to drop last 3 rows because notes are included in the datafile.
# remove/edit if this changes in future, but without it, you get an error generating the date.
healthcare_contacts.drop(index=healthcare_contacts.index[-3:], axis=0, inplace=True)

healthcare_contacts["day"] = 1

# generate a 'real' date from week info
healthcare_contacts["date"] = healthcare_contacts.apply(
    lambda row: dt.fromisocalendar(
        int(row["Year"]), int(row["Vecka"]), int(row["day"])
    ),
    axis=1,
)

healthcare_contacts.rename(
    columns={"U08.9": "U089", "U09.9": "U099", "Z86.1A": "Z861A"}, inplace=True
)

healthcare_contacts = healthcare_contacts.replace(r"^\s*$", np.nan, regex=True)

fig = go.Figure(
    data=[
        go.Scatter(
            name="U08.9",
            x=healthcare_contacts.date,
            y=healthcare_contacts.U089,
            mode="lines+markers",
            marker=dict(color=px.colors.diverging.RdBu[0], size=3),
            marker_symbol="square",
            line=dict(color=px.colors.diverging.RdBu[0], width=1),
        ),
        go.Scatter(
            name="U09.9",
            x=healthcare_contacts.date,
            y=healthcare_contacts.U099,
            mode="lines+markers",
            marker=dict(color=px.colors.diverging.RdBu[8], size=3),
            marker_symbol="square",
            line=dict(color=px.colors.diverging.RdBu[8], width=1),
        ),
        go.Scatter(
            name="Z86.1A",
            x=healthcare_contacts.date,
            y=healthcare_contacts.Z861A,
            mode="lines+markers",
            marker=dict(color="gold", size=3),
            marker_symbol="square",
            line=dict(color="gold", width=1),
        ),
    ]
)
fig.update_layout(
    plot_bgcolor="white",
    autosize=True,
    font=dict(size=12),
    margin=dict(r=0, t=50, b=0, l=0),
    legend=dict(
        orientation="h",
        # title="Sex:",
        yanchor="bottom",
        y=1,
        xanchor="left",
        x=-0.1,
    ),
    hovermode="x unified",
    hoverdistance=1,
)
fig.update_xaxes(
    title="
Date (Week Commencing)",
    showgrid=True,
    linecolor="black",
    tickangle=45,
)
fig.update_yaxes(
    title="Contacts with healthcare
",
    showgrid=True,
    gridcolor="lightgrey",
    linecolor="black",
    range=[0, (max(healthcare_contacts.U089) * 1.15)],
    rangemode="tozero",
)
# fig.show()
if not os.path.isdir(args.output_dir):
    os.mkdir(args.output_dir)
fig.write_json(os.path.join(args.output_dir, "weeklycontacts_healthcare.json"))


#coding:utf8
import nuke
import os
import pathapi
from PySide2.QtWidgets import *

class MakeWrite(QWidget):
	formats = ["2048x1152","1920x1080","2048x872","2048x968"]
	exts = [".exr",".dpx",".jpg",".mov"]

	def __init__(self):
		super(MakeWrite, self).__init__()
		self.ok = QPushButton("OK")
		self.cancel = QPushButton("Cancel")
		self.ext = QComboBox()
		self.ext.addItems(self.exts)
		self.fm = QComboBox()
		self.fm.addItems(self.formats)
		self.reformat = QCheckBox("&reformat",self)
		self.reformat.setChecked(True)
		self.slate = QCheckBox("&slate",self)
		self.slate.setChecked(True)
		self.addtimecode = QCheckBox("&AddTimecode",self)
		self.addtimecode.setChecked(False)
		self.startframe = QLineEdit(str(int(nuke.Root()["first_frame"].value())))
		self.starttimecode = QLineEdit("00:00:00:00")

		#event
		self.ok.clicked.connect(self.bt_ok)
		self.cancel.clicked.connect(self.close)

		#set layout
		layout = QGridLayout()
		layout.addWidget(self.reformat, 0, 0)
		layout.addWidget(self.fm, 0,1)
		layout.addWidget(self.addtimecode,1, 0)
		layout.addWidget(self.startframe, 1, 1)
		layout.addWidget(self.starttimecode, 1, 2)
		layout.addWidget(self.slate, 2, 0)
		layout.addWidget(QLabel("Ext"), 3, 0)
		layout.addWidget(self.ext, 3, 1)
		layout.addWidget(self.cancel, 4, 0)
		layout.addWidget(self.ok, 4, 1)

		self.linkOrder = []
		self.setLayout(layout)

	def genReformat(self):
		reformat = nuke.nodes.Reformat()
		reformat["type"].setValue("to box")
		reformat["box_fixed"].setValue(True)
		width, height = self.fm.currentText().split("x")
		reformat["box_width"].setValue(int(width))
		reformat["box_height"].setValue(int(height))
		self.linkOrder.append(reformat)

	def genAddTimeCode(self):
		timecode = nuke.nodes.AddTimeCode()
		timecode["startcode"].setValue(str(self.starttimecode.text()))
		timecode["useFrame"].setValue(True)
		timecode["frame"].setValue(int(self.startframe.text()))
		self.linkOrder.append(timecode)

	def genSlate(self):
		slate = nuke.nodes.slate()
		self.linkOrder.append(slate)

	def genWrite(self):
		write = nuke.nodes.Write()
		write["file_type"].setValue("to box")
		write["file"].setValue("/test/test.####%s" % (self.ext.currentText()))
		write["create_directories"].setValue(True)
		self.linkOrder.append(write)

# 이걸 어케 수정할까
	def bt_ok(self):
		if self.reformat.isChecked():
			self.genReformat()
		if self.addtimecode.isChecked():
			self.genAddTimeCode()
		if self.slate.isChecked():
			self.genSlate()
		self.genWrite()

		tail = nuke.selectedNode()
		for n in self.linkOrder:
			n.setInput(0,tail)
			tail = n
		self.close()

def main():
	if len(nuke.selectedNodes()) != 1:
		nuke.message("노드를 하나만 선택해주세요.")
		return
	if len(nuke.selectedNodes()) == 0:
		nuke.message("노드를 선택하세요.")
		return
	global customApp
	try:
		customApp.close()
	except:
		pass
	customApp = MakeWrite()
	try:
		customApp.show()
	except:
		pass


import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia

listener = sr.Recognizer()
bolt = pyttsx3.init()
voices = bolt.getProperty('voices')
bolt.setProperty('voice',voices[1].id)

def talk(text):
    bolt.say(text)
    bolt.runAndWait()

def command_recieved():
    try:
        with sr.Microphone() as source:
            print("Speak Boss")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if "bolt" in command:
                command = command.replace('bolte','')
                command = command.replace('bolt','')

    except:
        print("Please Speak again BOSS")
    return command

def bolt_msg():
    command = command_recieved()
    print(command)
    if 'play' in command:
        song = command.replace('play','')
        talk('playing'+song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk(time)
    elif 'search' in command:
        searching = command.replace('search','')
        info = wikipedia.summary(searching,2)
        talk('Searching' + searching + 'for you')
        talk('We got the result boss')
        talk('It is'+info)

bolt_msg()


from django import forms
from django.core.exceptions import ValidationError
from backend.api.models import MiembroSprint, UserStory

class PlanificarUserStoryForm(forms.Form):
    """
    PlanificarUserStoryForm Valida los datos al Planificar un User Story

    Args:
        forms (Form): Form del módulo Django
    """
    user_story = forms.IntegerField(
        error_messages={
            "required": "No se especificó ningún User Story"
        }
    )
    horas_estimadas = forms.IntegerField(
        min_value=0,
        error_messages={
            "required": "No se especificó ninguna hora estimada",
            "min_value": "La hora no puede ser negativa"
        }
    )
    desarrollador = forms.IntegerField(
        error_messages={
            "required": "No se especificó ningún desarrollador"
        }
    )

    def clean_user_story(self):
        try:
            cleaned_data = super().clean()
            id = cleaned_data.get("user_story")
            if id is None:
                raise ValidationError("Hubo problemas para recibir el User Story")
            UserStory.objects.get(pk=id)
            return id
        except UserStory.DoesNotExist:
            raise ValidationError("No se encontró un User Story en la base de datos")

    def clean_desarrollador(self):
        try:
            cleaned_data = super().clean()
            id = cleaned_data.get("desarrollador")
            if id is None:
                raise ValidationError("Hubo problemas para recibir el Desarrollador")
            MiembroSprint.objects.get(pk=id)
            return id
        except MiembroSprint.DoesNotExist:
            raise ValidationError("No se encontró un Miembro de Sprint en la base de datos")


from functools import lru_cache
from typing import List

def findLength(nums1: List[int], nums2: List[int]) -> int:
    m, n = len(nums1), len(nums2)
    dp = [[0] * (m + 1) for _ in range(n + 1)]
    maxlen = 0
    for i in range(m):
        for j in range(n):
            if nums1[i] == nums2[j]:
                dp[i + 1][j + 1] = 1 + dp[i][j]
                maxlen = max(maxlen, dp[i + 1][j + 1])
    return maxlen

if __name__ == "__main__":
    print(findLength(nums1=[1, 2, 3, 2, 1], nums2=[3, 2, 1, 4, 7]))
    print(findLength(nums1=[0, 0, 0, 0, 0], nums2=[0, 0, 0, 0, 0]))


from typing_extensions import Self
import numpy as np
import scipy.io as scio
import os

# S_mu = []
# S_std = []

root = '/home/sureshbs/Desktop/TeXNet/Dataset/HADAR_database/'
root = '/research/hal-sreekum1/HADAR_Fanglin/'
# path = '/home/sureshbs/Desktop/TeXNet/Dataset/HADAR_database/Scene14/'

# S_data = scio.loadmat(path+'HeatCubes/HSI.mat')["HSI"]
# print(np.shape(S_data))
# S_data = np.transpose(S_data, (2, 0, 1))
# # S_data = S_data[4:53] # last 39 channels)
# for i in  range(49):
#     mu = np.mean(S_data[i], (0, 1))
#     std = np.std(S_data[i], (0, 1), dtype=np.float64)
#     S_mu.append(mu)
#     S_std.append(mu)
# np.save(path+'HeatCubes/S_mu.npy', np.asarray(S_mu))
# np.save(path+'HeatCubes/S_std.npy', np.asarray(S_std))

# T_data = scio.loadmat(path+'GroundTruth/tMap/tMap.mat')["tMap"]
# T_mu = np.mean((T_data), (0, 1))
# T_std = np.std((T_data), (0, 1))
# np.save(path+'GroundTruth/tMap/T_mu.npy', np.asarray(T_mu))
# np.save(path+'GroundTruth/tMap/T_std.npy', np.asarray(T_std))

################ eList Processing #######################
ids = [f"L_{i:04d}" for i in range(1, 6)]
ids += [f"R_{i:04d}" for i in range(1, 6)]
SUBFOLDERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
SUBFOLDERS = ["Scene"+str(_) for _ in SUBFOLDERS]

print("eMap preprocessing")
for subfolder in SUBFOLDERS:
    print("Processing subfolder", subfolder)
    e_files = []
    elist_file = os.path.join(root, subfolder, 'GroundTruth',
                                            'eMap', f"eList.mat")
    for id in ids:
        e_files.append(os.path.join(root, subfolder, 'GroundTruth',
                                            'eMap', f"eMap_{id}.mat"))
    for i in range(10):
        e_list = np.squeeze(np.asarray(scio.loadmat(elist_file)["eList"]))
        e_data = scio.loadmat(e_files[i])["eMap"]

        data = ((e_list[e_data - 1] - 1))
        if i<5:
            np.save(os.path.join(root, subfolder, "GroundTruth", "eMap", "new_eMap_L_000"+str(i+1)+".npy"),
                    np.asarray(data))
        else:
            np.save(os.path.join(root, subfolder, "GroundTruth", "eMap", "new_eMap_R_000"+str(i-4)+".npy"),
                    np.asarray(data))

ids = [f"L_{i:04d}" for i in range(1, 5)]
ids += [f"R_{i:04d}" for i in range(1, 5)]
SUBFOLDERS = [11]
SUBFOLDERS = ["Scene"+str(_) for _ in SUBFOLDERS]
for subfolder in SUBFOLDERS:
    print("Processing subfolder", subfolder)
    e_files = []
    elist_file = os.path.join(root, subfolder, 'GroundTruth',
                                            'eMap', f"eList.mat")
    for id in ids:
        e_files.append(os.path.join(root, subfolder, 'GroundTruth',
                                            'eMap', f"eMap_{id}.mat"))
    for i in range(8):
        e_list = np.squeeze(np.asarray(scio.loadmat(elist_file)["eList"]))
        e_data = scio.loadmat(e_files[i])["eMap"]

        data = ((e_list[e_data - 1]-1))
        if i<4:
            np.save(os.path.join(root, subfolder, "GroundTruth", "eMap", "new_eMap_L_000"+str(i+1)+".npy"),
                    np.asarray(data))
        else:
            np.save(os.path.join(root, subfolder, "GroundTruth", "eMap", "new_eMap_R_000"+str(i-3)+".npy"),
                    np.asarray(data))

################### S_beta Processing ###################################################
import torch.nn.functional as F
import torch

# Separate for Scene 11
S_files = [os.path.join(root, "Scene11", "Radiance_EnvObj", f"S_EnvObj_{i:04d}.mat") for i in range(1, 5)]

for j in range(4):
    data = scio.loadmat(S_files[j])["S_EnvObj"]
    data = np.transpose(data)[np.newaxis, ..., np.newaxis]
    np.save(os.path.join(root, "Scene11", "HeatCubes", f"S_EnvObj_L_{j+1:04d}.npy"), data)
    np.save(os.path.join(root, "Scene11", "HeatCubes", f"S_EnvObj_R_{j+1:04d}.npy"), data)

SUBFOLDERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
SUBFOLDERS = ["Scene"+str(_) for _ in SUBFOLDERS]
ids = [f"L_{i:04d}" for i in range(1, 6)]
ids += [f"R_{i:04d}" for i in range(1, 6)]

print("S_beta preprocessing")
for subfolder in SUBFOLDERS:
    S_files = []
    print("processing subfolder", subfolder)
    for id in ids:
        S_files.append(os.path.join(root, subfolder, 'HeatCubes',
                                                 f"{id}_heatcube.mat"))

    for j in range(10):
        img = torch.tensor(np.asarray(scio.loadmat(S_files[j])["S"]))
        img = torch.permute(img, (2, 0, 1))
        img = torch.reshape(img, (1, 54, 1080, 1920))
        [b, c, h, w] = img.shape
        quadratic_split = F.avg_pool2d(img, (h//2, w))
        mean = quadratic_split.numpy()

        if j < 5:
            np.save(os.path.join(root, subfolder, "HeatCubes", "S_EnvObj_L_000"+str(j+1)+".npy"),
                    np.asarray(mean))
        else:
            np.save(os.path.join(root, subfolder, "HeatCubes", "S_EnvObj_R_000"+str(j-4)+".npy"),
                    np.asarray(mean))


from flask import Flask
from flask_restful import Api

from resources.news import News, NewsEntities, NewsTags

app = Flask(__name__)
api = Api(app)

api.add_resource(News, '/get_news')
api.add_resource(NewsEntities, '/get_entities')
api.add_resource(NewsTags, '/get_tags')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=False)