import pickle
from collections import defaultdict
import numpy as np
import time
import sys
#print("preprocessing/util.py print sys.path")
#print(sys.path)
import os
import string

# import preprocessing.config as config
import model.config as config

# methods below are executed every time because they are fast or because their result
# depend on the args

def load_entities_universe():
    entities_universe = set()
    # TODO this path is hardcoded. these mapping files should be transfered in ./data folder
    with open("/home/other_projects/deep_ed/data/generated/nick/"
              "wikiid2nnid.txt") as fin:
        for line in fin:
            ent_id = line.split('\t')[0]
            entities_universe.add(ent_id)
    return entities_universe

def load_wikiid2nnid(extension_name=None):
    """returns a map from wiki id to neural network id (for the entity embeddings)"""
    wikiid2nnid = dict()   # wikiid is string,   nnid is integer
    with open(config.base_folder+"data/entities/wikiid2nnid/wikiid2nnid.txt") as fin:
        for line in fin:
            ent_id, nnid = line.split('\t')
            wikiid2nnid[ent_id] = int(nnid) - 1  # torch starts from 1 instead of zero
        assert(wikiid2nnid["1"] == 0)
        assert(-1 not in wikiid2nnid)
        wikiid2nnid[""] = 0
        del wikiid2nnid["1"]
        #print(len(wikiid2nnid))

    if extension_name:
        load_entity_extension(wikiid2nnid, extension_name)
    return wikiid2nnid

def load_entity_extension(wikiid2nnid, extension_name):
    filepath = config.base_folder + "data/entities/" + extension_name + "/wikiid2nnid/additional_wikiids.txt"
    max_nnid = max(wikiid2nnid.values())
    assert(len(wikiid2nnid) - 1 == max_nnid)
    with open(filepath) as fin:
        line_cnt = 1
        for line in fin:
            ent_id = line.strip()
            if ent_id in wikiid2nnid:   # if extension entities has overlap with the normal entities set
                wikiid2nnid[ent_id + "dupl"] = max_nnid + line_cnt    # this vector is duplicate and is never going to be used
            else:
                wikiid2nnid[ent_id] = max_nnid + line_cnt
            line_cnt += 1
    print("original entities: ", max_nnid + 1, " extension entities: ", len(wikiid2nnid) - (max_nnid+1))

def reverse_dict(d, unique_values=False):
    new_d = dict()
    for k, v in d.items():
        if unique_values:
            assert(v not in new_d)
        new_d[v] = k
    return new_d

#def p_e_m_disamb_redirect_wikinameid_maps():
def load_redirections(lowercase=None):
    if lowercase is None:
        lowercase = config.lowercase_maps
    wall_start = time.time()
    redirections = dict()
    with open(config.base_folder + "data/basic_data/wiki_redirects.txt") as fin:
        redirections_errors = 0
        for line in fin:
            line = line.rstrip()
            try:
                old_title, new_title = line.split("\t")
                if lowercase:
                    old_title, new_title = old_title.lower(), new_title.lower()
                redirections[old_title] = new_title
            except ValueError:
                redirections_errors += 1

    print("load redirections. wall time:", (time.time() - wall_start)/60, " minutes")
    print("redirections_errors: ", redirections_errors)
    return redirections

def load_disambiguations():
    wall_start = time.time()
    disambiguations_ids = set()
    #disambiguations_titles = set()
    disambiguations_errors = 0
    with open(config.base_folder + "data/basic_data/wiki_disambiguation_pages.txt") as fin:
        for line in fin:
            line = line.rstrip()
            try:
                article_id, title = line.split("\t")
                disambiguations_ids.add(article_id)
                #disambiguations_titles.add(title)
            except ValueError:
                disambiguations_errors += 1
    print("load disambiguations. wall time:", (time.time() - wall_start)/60, " minutes")
    print("disambiguations_errors: ", disambiguations_errors)
    return disambiguations_ids

def load_persons():
    wiki_name_id_map, _ = load_wiki_name_id_map()
    persons_wikiids = set()
    not_found_cnt = 0
    with open(config.base_folder + "data/basic_data/persons.txt") as fin:
        for line in fin:
            line = line.strip()
            if line in wiki_name_id_map:
                persons_wikiids.add(wiki_name_id_map[line])
            else:
                not_found_cnt += 1
                #print("not found:", repr(line))
    print("persons not_found_cnt:", not_found_cnt)
    return persons_wikiids

def load_wiki_name_id_map(lowercase=False, filepath=None):
    wall_start = time.time()
    wiki_name_id_map = dict()
    wiki_id_name_map = dict()
    wiki_name_id_map_errors = 0
    duplicate_names = 0    # different lines in the doc with the same title
    duplicate_ids = 0      # with the same id
    if filepath is None:
        filepath = config.base_folder + "data/basic_data/wiki_name_id_map.txt"
    disambiguations_ids = load_disambiguations()
    with open(filepath) as fin:
        for line in fin:
            line = line.rstrip()
            try:
                wiki_title, wiki_id = line.split("\t")
                if wiki_id in disambiguations_ids:
                    continue
                if lowercase:
                    wiki_title = wiki_title.lower()

                if wiki_title in wiki_name_id_map:
                    duplicate_names += 1
                if wiki_id in wiki_id_name_map:
                    duplicate_ids += 1

                wiki_name_id_map[wiki_title] = wiki_id
                wiki_id_name_map[wiki_id] = wiki_title
            except ValueError:
                wiki_name_id_map_errors += 1
    print("load wiki_name_id_map. wall time:", (time.time() - wall_start)/60, " minutes")
    print("wiki_name_id_map_errors: ", wiki_name_id_map_errors)
    print("duplicate names: ", duplicate_names)
    print("duplicate ids: ", duplicate_ids)
    return wiki_name_id_map, wiki_id_name_map

class FetchCandidateEntities(object):
    """takes as input a string or a list of words and checks if it is inside p_e_m
    if yes it returns the candidate entities otherwise it returns None.
    it also checks if string.lower() inside p_e_m and if string.lower() inside p_e_m_low"""
    def __init__(self, args):
        self.lowercase_spans = args.lowercase_spans
        self.lowercase_p_e_m = args.lowercase_p_e_m
        self.p_e_m, self.p_e_m_low, self.mention_total_freq = custom_p_e_m(
            cand_ent_num=args.cand_ent_num,
            lowercase_p_e_m=args.lowercase_p_e_m)

    def process(self, span):
        """span can be either a string or a list of words"""
        if isinstance(span, list):
            span = ' '.join(span)
        title = span.title()
        # 'obama 44th president of united states'.title() # 'Obama 44Th President Of United States'
        title_freq = self.mention_total_freq[title] if title in self.mention_total_freq else 0
        span_freq = self.mention_total_freq[span] if span in self.mention_total_freq else 0

        if title_freq == 0 and span_freq == 0:
            if self.lowercase_spans and span.lower() in self.p_e_m:
                return map(list, zip(*self.p_e_m[span.lower()]))
            elif self.lowercase_p_e_m and span.lower() in self.p_e_m_low:
                return map(list, zip(*self.p_e_m_low[span.lower()]))
            else:
                return None, None

        else:
            if span_freq > title_freq:
                return map(list, zip(*self.p_e_m[span]))
            else:
                return map(list, zip(*self.p_e_m[title]))

                # from [('ent1', 0.4), ('ent2', 0.3), ('ent3', 0.3)] to
                # ('ent1', 'ent2', 'ent3')  and (0.4, 0.3, 0.3)
                # after map we have lists i.e. ['ent1', 'ent2', 'ent3']   , [0.4, 0.3, 0.3]

class FetchFilteredCoreferencedCandEntities(object):
    def __init__(self, args):
        self.args = args
        self.fetchCandidateEntities = FetchCandidateEntities(args)
        self.el_mode = True
        if args.persons_coreference:
            self.persons_wikiids = load_persons()
            self.persons_mentions_seen = list()

    def init_coref(self, el_mode):
        self.persons_mentions_seen = list()
        self.el_mode = el_mode

    def process(self, left, right, chunk_words):
        left_right_words = [chunk_words[left-1] if left - 1 >= 0 else None,
                            chunk_words[right] if right <= len(chunk_words)-1 else None] if self.el_mode else None
        span_text = ' '.join(chunk_words[left:right])
        cand_ent, scores = self.fetchCandidateEntities.process(span_text)
        if self.args.persons_coreference:
            coreference_supermention = self.find_corefence_person(span_text, left_right_words)
            if coreference_supermention:
                #print("original text:", chunk_words[max(0, left-4):min(len(chunk_words), right+4)])
                if not self.args.persons_coreference_merge:
                    cand_ent, scores = self.fetchCandidateEntities.process(coreference_supermention)
                else:  # merge with cand_ent and scores
                    cand_ent2, scores2 = self.fetchCandidateEntities.process(coreference_supermention)
                    temp1 = list(zip(scores, cand_ent)) if scores and cand_ent else []
                    temp2 = list(zip(scores2, cand_ent2)) if scores2 and cand_ent2 else []
                    temp3 = sorted(temp1 + temp2, reverse=True)
                    scores, cand_ent = map(list, zip(*temp3[:self.args.cand_ent_num]))

        if cand_ent is not None and scores is not None:
            if self.args.persons_coreference and not coreference_supermention and \
                            cand_ent[0] in self.persons_wikiids and len(span_text) >= 3:
                if not self.el_mode or span_text == span_text.title() or span_text == string.capwords(span_text):
                    self.persons_mentions_seen.append(span_text)
        return cand_ent, scores

    def find_corefence_person(self, span_text, left_right_words):
        """if span_text is substring of another person's mention found before. it should be
        substring of words. so check next and previous characters to be non alphanumeric"""
        if len(span_text) < 3:
            return None
        if left_right_words:  # this check is only for allspans mode not for gmonly.
            if left_right_words[0] and left_right_words[0][0].isupper() or \
                            left_right_words[1] and left_right_words[1][0].isupper():
                # if the left or the right word has uppercased its first letter then do not search for coreference
                # since most likely it is a subspan of a mention.
                # This condition gives no improvement to Gerbil results even a very slight decrease (0.02%)
                return None
        for mention in reversed(self.persons_mentions_seen):
            idx = mention.find(span_text)
            if idx != -1:
                if len(mention) == len(span_text):
                    continue   # they are identical so no point in substituting them
                if idx > 0 and mention[idx-1].isalpha():
                    continue
                if idx + len(span_text) < len(mention) and mention[idx+len(span_text)].isalpha():
                    continue
                #print("persons coreference, before:", span_text, "after:", mention)
                return mention
        return None

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

    def init_compatible_ent_id(self):
        self.wiki_name_id_map, self.wiki_id_name_map = load_wiki_name_id_map(lowercase=False)

    def init_gerbil_compatible_ent_id(self):
        self.wiki_name_id_map, self.wiki_id_name_map = load_wiki_name_id_map(lowercase=False)
        self.redirections = load_redirections(lowercase=False)

    def init_hyperlink2id(self):
        self.wiki_name_id_map, self.wiki_id_name_map = load_wiki_name_id_map(lowercase=False)
        self.wiki_name_id_map_l, _ = load_wiki_name_id_map(lowercase=True)
        self.redirections = load_redirections(lowercase=False)
        self.disambiguations = load_disambiguations()
        self.hyperlinks_to_dismabiguation_pages = 0

    def hyperlink2id(self, line):
        """ gets as input the raw line:
        \n
        '\n'
        """
        #line = '\n'
        line = line.rstrip()
        hyperlink_text = line[9:-2]
        #print(repr(hyperlink_text))
        hyperlink_text = hyperlink_text.replace('\xa0', ' ').strip()

        for title in [hyperlink_text, hyperlink_text.title()]:
            #look for redirection
            if title in self.redirections:
                title = self.redirections[title]
            if title in self.wiki_name_id_map:
                return self.wiki_name_id_map[title]

        if hyperlink_text.lower() in self.wiki_name_id_map_l:
            return self.wiki_name_id_map_l[hyperlink_text.lower()]
        else:
            return config.unk_ent_id

    def is_valid_entity_id(self, ent_id):
        return ent_id in self.wiki_id_name_map

    def compatible_ent_id(self, name=None, ent_id=None):
        """takes as input the name and the entity id found in the dataset. If the entity id
        is also in our wiki_name_id_map then this means that this concept-entity also exist in
        out world and with the same id. If the id is not found in our world then we search for
        the name if it is inside the wiki_name_id_map. if yes then we have the same concept
        in our world but with different id so we return and use our own id from now on.
        if neither the id nor the name is in wiki_name_id_map then we return None i.e.
        unknown concept so skip it from the dataset."""
        if ent_id is not None and ent_id in self.wiki_id_name_map:
            return ent_id
        elif name is not None and name in self.wiki_name_id_map:
            return self.wiki_name_id_map[name]
        else:
            return None

    def gerbil_compatible_ent_id(self, uri):
        from urllib.parse import unquote
        title = unquote(uri)
        title = title[len("http://en.wikipedia.org/wiki/"):].replace('_', ' ')
        if title in self.redirections:
            title = self.redirections[title]
        if title in self.wiki_name_id_map:
            return self.wiki_name_id_map[title]
        else:
            print("unknown entity. title_searched:", repr(title), " original uri:", repr(uri))
            return None

def custom_p_e_m(cand_ent_num=15, allowed_entities_set=None,
                 lowercase_p_e_m=False):
    """Args:
    cand_ent_num: how many candidate entities to keep for each mention
    allowed_entities_set: restrict the candidate entities to only this set. for example
    the most frequent 1M entities. First this restiction applies and then the cand_ent_num."""
    wall_start = time.time()
    p_e_m = dict()  # for each mention we have a list of tuples (ent_id, score)
    mention_total_freq = dict()   # for each mention of the p_e_m we store the total freq
                                # this will help us decide which cand entities to take
    p_e_m_errors = 0
    entityNameIdMap = EntityNameIdMap()
    entityNameIdMap.init_compatible_ent_id()
    incompatible_ent_ids = 0
    with open(config.base_folder + 'data/basic_data/prob_yago_crosswikis_wikipedia_p_e_m.txt') as fin:
        duplicate_mentions_cnt = 0
        clear_conflict_winner = 0  # both higher absolute frequency and longer cand list
        not_clear_conflict_winner = 0  # higher absolute freq but shorter cand list
        for line in fin:
            line = line.rstrip()
            try:
                temp = line.split("\t")
                mention, entities = temp[0],  temp[2:]
                absolute_freq = int(temp[1])
                res = []
                for e in entities:
                    if len(res) >= cand_ent_num:
                        break
                    ent_id, score, _ = map(str.strip, e.split(',', 2))
                    #print(ent_id, score)
                    if not entityNameIdMap.is_valid_entity_id(ent_id):
                        incompatible_ent_ids += 1
                    elif allowed_entities_set is not None and \
                                    ent_id not in allowed_entities_set:
                        pass
                    else:
                        res.append((ent_id, float(score)))
                if res:
                    if mention in p_e_m:
                        duplicate_mentions_cnt += 1
                        #print("duplicate mention: ", mention)
                        if absolute_freq > mention_total_freq[mention]:
                            if len(res) > len(p_e_m[mention]):
                                clear_conflict_winner += 1
                            else:
                                not_clear_conflict_winner += 1
                            p_e_m[mention] = res
                            mention_total_freq[mention] = absolute_freq
                    else:
                        p_e_m[mention] = res    # for each mention we have a list of tuples (ent_id, score)
                        mention_total_freq[mention] = absolute_freq

            except Exception as esd:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                print(exc_type, fname, exc_tb.tb_lineno)
                p_e_m_errors += 1
                print("error in line: ", repr(line))

    print("duplicate_mentions_cnt: ", duplicate_mentions_cnt)
    print("end of p_e_m reading. wall time:", (time.time() - wall_start)/60, " minutes")
    print("p_e_m_errors: ", p_e_m_errors)
    print("incompatible_ent_ids: ", incompatible_ent_ids)

    if not lowercase_p_e_m:   # do not build lowercase dictionary
        return p_e_m, None, mention_total_freq

    wall_start = time.time()
    # two different p(e|m) mentions can be the same after lower() so we merge the two candidate
    # entities lists. But the two lists can have the same candidate entity with different score
    # we keep the highest score. For example if "Obama" mention gives 0.9 to entity Obama and
    # OBAMA gives 0.7 then we keep the 0.9 . Also we keep as before only the cand_ent_num entities
    # with the highest score
    p_e_m_lowercased = defaultdict(lambda: defaultdict(int))

    for mention, res in p_e_m.items():
        l_mention = mention.lower()
        # if l_mention != mention and l_mention not in p_e_m:
        #   the same so do nothing      already exist in dictionary
        #   e.g. p(e|m) has Obama and obama. So when i convert Obama to lowercase
        # I find that obama already exist so i will prefer this.
        if l_mention not in p_e_m:
            for r in res:
                ent_id, score = r
                p_e_m_lowercased[l_mention][ent_id] = max(score, p_e_m_lowercased[l_mention][ent_id])

    print("end of p_e_m lowercase. wall time:", (time.time() - wall_start)/60, " minutes")

    import operator
    p_e_m_lowercased_trim = dict()
    for mention, ent_score_map in p_e_m_lowercased.items():
        sorted_ = sorted(ent_score_map.items(), key=operator.itemgetter(1), reverse=True)
        p_e_m_lowercased_trim[mention] = sorted_[:cand_ent_num]

    return p_e_m, p_e_m_lowercased_trim, mention_total_freq

def get_immediate_files(a_dir):
    return [name for name in os.listdir(a_dir)
            if os.path.isfile(os.path.join(a_dir, name))]

if __name__ == "__main__":
    #load_wikiid2nnid()
    load_persons()
    pass
    #pass
    # vocabulary_count_wiki()

    #entity_count_wiki()
    #entity_count_wiki_aux()

    # load_p_e_m()

    #entity_name_id_map_from_dump()
    #compare_name_id_maps()
    #test_wiki_name_id_map_txt_conflicts_when_lowering():


# boj 1405 미친로봇
# 배열 만들어주고 방문 확인하면서 하면 될듯
# 확률 찾는걸 모름...0.01
# https://summa-cum-laude.tistory.com/36

dx,dy = [0,0,1,-1],[1,-1,0,0] #동서남북 맞춰줌
def dfs(x,y,cnt,p):
    global ans

    if cnt==times:
        ans+=p
        return
    for i in range(4):
        nx,ny = x+dx[i], y+dy[i]
        if lst[nx][ny]:
            continue
        if not 0<=nx<(2*times)+1 or not 0<=ny<(2*times)+1:
            continue
        lst[nx][ny]=1
        dfs(nx,ny,cnt+1, p*poss[i]*0.01 )
        lst[nx][ny]=0

times, E, W, S, N = map(int, input().split())
poss = [E,W,S,N]
lst = [[0]*(2*times+1) for _ in range(2*times+1)] #한 방향으로 최대 n번 가니까 행렬 크기
lst[times][times]=1
ans = 0
dfs(times,times,0,1)
print(ans)


import logging

from hyo2.abc.lib.helper import Helper

logger = logging.getLogger(__name__)

qa_algos = {
    "BASE": 0,
    "GRID_QA_v5": 5,
    "GRID_QA_v6": 6,
}

class BaseGridQA:
    def __init__(self, grids):
        self.type = qa_algos["BASE"]
        # inputs
        self.grids = grids

    def __repr__(self):
        msg = "  <BaseGridQA>\n"

        msg += "    <type: %s>\n" % Helper.first_match(qa_algos, self.type)
        msg += "    <grids: %s>\n" % bool(self.grids)

        return msg


#!/usr/bin/env python

print("hello, gushi!")

import os.path
file = './spe/eu-152.spe'
if os.path.isfile(file):
    print("file %s found." % file)

    cnt = 0
    lt = 0.0
    rt = 0.0
    flag_mea = False
    mea = [0.0, 0.0]
    flag_len = False
    data_range = [0, 16383]
    flag_data = False
    idx = -1
    data = []
    for line in open(file):
        line = line.strip('\n')
        cnt = cnt + 1
#        if cnt > 40:
#            break
        if line.startswith('$MEAS_TIM:'):
            flag_mea = True
            continue
        if flag_mea:
            flag_mea = False
            mea = [float(val) for val in line.split()]
            print(mea)
            continue
        if line.startswith('$DATA:'):
            flag_len = True
            continue
        if flag_len:
            flag_len = False
            flag_data = True
            data_range = [int(val) for val in line.split()]
            idx = 0
            print(data_range)
            continue
        if flag_data and len(data_range) == 2:
            if idx > data_range[1]:
                print('Finished')
                flag_data = False
            else:
                #print('data(%d) %f' % (idx, float(line)))
                data.append(float(line))
                idx = idx + 1

    # data process
    print('data (%d) found!' % len(data))
    from matplotlib import pyplot as plt
    import math
    data1 = []
    for val in data:
        if val <= 0:
            data1.append(0)
        else:
            data1.append(math.log(val))
    # data = data1
    #plt.plot(data[0:1023])
    #plt.show()

    data = data[0:1023]

    import numpy as np
    from scipy.signal import find_peaks
    peaks, _ = find_peaks(data, distance=50)
    print(peaks)

    plt.plot(peaks, np.array(data)[peaks], 'xr')
    plt.plot(data)
    plt.show()

else:
    print("file %s NOT EXIST!")

print("bye, gushi.")


from collections import deque

N, K = map(int, input().split())
visit = [False] * 100001
Q = deque()
Q.append((N, 0))
visit[N] = True

ans = 0
while len(Q):
    x, t = Q.popleft()
    if x == K:
        ans = t
        break
    if x - 1 >= 0 and not visit[x - 1]:
        Q.append((x - 1, t + 1))
        visit[x - 1] = True
    if x + 1 <= 100000 and not visit[x + 1]:
        Q.append((x + 1, t + 1))
        visit[x + 1] = True
    if x << 1 <= 100000 and not visit[x << 1]:
        Q.append((x << 1, t + 1))
        visit[x << 1] = True

print(ans)


from controllers.tournament import TournamentController
from views.report import ReportView
from views.tournament import TournamentView
from models.tournament import TournamentModel
from models.player import PlayerModel
import sys
from constantes import MENU_REPORT_TOURNAMENT_PLAYERS, MENU_REPORT_TOURNAMENT_SCORES, MENU_REPORT_PLAYER_NAME,\
    MENU_REPORT_PLAYER_FNAME, MENU_RESULT_TOURNAMENT_LIST, MENU_RESULT_TOURNAMENT_DETAIL, MENU_REPORT_EXIT,\
    MENU_REPORT_EXPORT_HTML

class ReportController:
    """ reports class """
    def __init__(self):
        self.tournament_controller = TournamentController()
        self.report_view = ReportView()
        self.tournament_view = TournamentView()

    def menu_report(self):
        """ Reports menu """
        while True:
            choix = self.report_view.report_menu()
            if choix == MENU_REPORT_TOURNAMENT_PLAYERS:
                self.report_tournament("players")
            elif choix == MENU_REPORT_TOURNAMENT_SCORES:
                self.report_tournament("scores")
            elif choix == MENU_REPORT_PLAYER_NAME:
                self.report_players_name(by_name=True, by_fname=False)
            elif choix == MENU_REPORT_PLAYER_FNAME:
                self.report_players_name(by_name=False, by_fname=True)
            elif choix == MENU_RESULT_TOURNAMENT_LIST:
                self.report_tournament_list()
            elif choix == MENU_RESULT_TOURNAMENT_DETAIL:
                self.report_tournament_details()
            elif choix == MENU_REPORT_EXPORT_HTML:
                self.report_tournament("html_file")
            elif choix == MENU_REPORT_EXIT:
                break

    def report_tournament_details(self):
        """ method to display detail of a tournament """
        tournaments = TournamentModel.search_all_tournaments()
        while True:
            if tournaments == "no_result":
                self.report_view.choice("Aucun tournoi. Appuyez sur [ENTRER] pour revenir au menu et en créer.")
                break
            elif tournaments == "error":
                self.report_view.text_to_print("Problème de structure sur fichier tournaments.json.\nVérifiez"
                                               " le et recommencez.")
                sys.exit()
            else:
                index = 0
                for tournament in tournaments:
                    index += 1
                    self.report_view.text_to_print(str(index) + " - " + str(tournament))
                # select a tournament
                choix = self.tournament_view.select(tournaments)
                tournament = tournaments[int(choix) - 1]
                # tournament = tournament.extract_all_infos_tournaments()
                self.report_view.display_tournament_details(tournament)

                # display ordered player list of a tournament
                player_fname_name_list = []
                if tournament.tournament_list_players:
                    for player_uuid in tournament.tournament_list_players:
                        player = PlayerModel.create_player_object(player_uuid)
                        player_fname_name_list.append(player.extract_player_fname_and_name())
                    player_fname_name_list.sort()
                    self.report_view.text_to_print(
                        "La liste des joueurs (triée par ordre alphabétique) est la suivante :")
                    for player in player_fname_name_list:
                        self.report_view.text_to_print("- " + player)
                choix = self.report_view.choice("Faire une autre recherche (O/n)? ")
                if choix.upper() == "N":
                    break

    def report_tournament_list(self):
        """ method to display list of tournaments """
        self.tournament_controller.display_tournament()

    def report_players_name(self, by_name, by_fname):
        """ method to display all players in alphabetic order """
        while True:
            if PlayerModel.search_all_players() == "no_result":
                self.report_view.choice("Aucun joueurs. Appuyez sur [ENTRER] pour revenir au menu et en créer.")
                break
            elif PlayerModel.search_all_players() == "error":
                self.report_view.text_to_print("Problème de structure sur fichier tournaments.json.\nVérifiez"
                                               " le et recommencez.")
                sys.exit()
            else:
                players_list = PlayerModel.search_all_players(by_name, by_fname)
                for player in players_list:
                    self.report_view.text_to_print(" - " + str(player.extract_player_fname_and_name()))
                self.report_view.choice("Appuyez sur [ENTRER] pour revenir au menu.")
                break

    def report_tournament(self, display_type=None):
        """ method to display tournament report """
        while True:
            if TournamentModel.search_completed_tournaments() == "no_result":
                self.report_view.choice("Aucun tournoi. Appuyez sur [ENTRER] pour revenir au menu et en créer.")
                break
            elif TournamentModel.search_completed_tournaments() == "error":
                self.report_view.text_to_print("Problème de structure sur fichier tournaments.json.\nVérifiez"
                                               " le et recommencez.")
                sys.exit()
            else:
                # display ended tournaments
                ended_tournaments = TournamentModel.search_completed_tournaments()
                self.report_view.text_to_print("Liste des tournois terminés:")
                index = 0
                for tournament in ended_tournaments:
                    index += 1
                    self.report_view.text_to_print(str(index) + " - " + str(tournament))

                # select a tournament
                choix = self.tournament_view.select(ended_tournaments)
                tournament = ended_tournaments[int(choix) - 1]

                # extraction of all matchs associated to selected tournament
                # matchs_ids_list = tournament.extract_matchs_id_list()

                # extract all players and scores from matchs id list
                players_uuid_list, players_scores = tournament.extract_players_scores()

                # reinit scores in players.json
                PlayerModel.delete_score_player(players_uuid_list)

                # store scores in players.json for create ordered winners
                for player_uuid, player_score in zip(players_uuid_list, players_scores):
                    PlayerModel.store_score(player_uuid, player_score)

                # create tuple contains players fname & name + scores
                players_uuid_list = list(set(players_uuid_list))
                players_uuid = []
                players = []
                scores = []
                for player_uuid in players_uuid_list:
                    score = PlayerModel.search_player_score(player_uuid)
                    players_uuid.append(player_uuid)
                    scores.append(score)
                scores, players_uuid = zip(*sorted(zip(scores, players_uuid), reverse=True))
                for player_uuid in players_uuid:
                    player = PlayerModel.create_player_object(player_uuid)
                    player_fname_name = player.extract_player_fname_and_name()
                    players.append(player_fname_name)
                players_scores = [players, scores]

                # extraction of all rounds details
                rounds_list = tournament.tournament_list_rounds

                # extraction of start and end dates of a tournament
                tournament_start_date = tournament.tournament_start_date
                tournament_end_date = tournament.tournament_end_date

                # extraction of all scores of matchs list associated to the selected tournament
                tournaments_scores = tournament.extract_scores()
                if display_type == "players":
                    self.report_view.display_scores_players(tournaments_scores, rounds_list, tournament_start_date,
                                                            tournament_end_date, tournament.tournament_name,
                                                            players_scores)
                elif display_type == "scores":
                    self.report_view.display_scores_scores(tournaments_scores, rounds_list, tournament_start_date,
                                                           tournament_end_date, tournament.tournament_name,
                                                           players_scores)
                elif display_type == "html_file":
                    result = TournamentModel.export_tournament(tournaments_scores, rounds_list, tournament_start_date,
                                                               tournament_end_date, tournament.tournament_name,
                                                               players_scores)
                    self.report_view.text_to_print(result)
                    self.report_view.choice("Appuyez sur [ENTRER] pour continuer.")
                break


from django.shortcuts import render, redirect
from funcionarios.forms import FuncionarioForm
from funcionarios.models import Funcionario
from django.contrib import messages
from django.views.generic import ListView

def funcionario_cadastrar(request):

   if request.method == 'POST':
       form = FuncionarioForm(request.POST)
       if form.is_valid():
           form.save()
           messages.success(request, 'Cadastro de funcionario efetuado com sucesso.')
           return redirect("/funcionarios")

   form = FuncionarioForm()
   return render(request, 'cadastrar.html',{'form':form})
def funcionario_editar(request, id):
   instance = Funcionario.objects.get(id = id)
   form = FuncionarioForm(request.POST or None,instance=instance)
   if form.is_valid():
       form.save()
       messages.success(request, 'Cadastro de funcionario editado com sucesso.')
       return redirect("/funcionarios")
   return render(request, 'editar.html',{'form':form})

def funcionario_remover(request, id):
   if request.method == 'POST':
       instance = Funcionario.objects.get(id = id)
       instance.delete()
       messages.success(request, 'Cadastro de funcionario removido com sucesso.')
       return redirect("/funcionarios")

   # dictionary for initial data with
   # field names as keys
   context ={}
   # add the dictionary during initialization
   context["data"] = Funcionario.objects.get(id = id)

   return render(request, "funcionarios/remover.html", context)

def funcionario_detail(request, id):

   # dictionary for initial data with
   # field names as keys
   context ={}
   # add the dictionary during initialization
   context["data"] = Funcionario.objects.get(id = id)

   return render(request, "funcionario.html", context)

class FuncionarioListView(ListView):
   model = Funcionario
   template_name = 'listar.html'


from o2despy.sandbox import Sandbox
from o2despy.action import Action
from o2despy.entity import Entity

class Queue(Sandbox):
    def __init__(self):
        super().__init__()
        self.number_waiting = self.add_hour_counter()
        self.queue = list()
        self.on_enqueue = Action(Entity)

    def enqueue(self, load):
        self.number_waiting.observe_change(1)
        self.queue.append(load)
        self.on_enqueue.invoke(load)
        print("{0}\t{1}\tEnqueue. #Waiting: {2}, Load: {3}".format(self.clock_time,
                                                        type(self).__name__,
                                                        self.number_waiting.last_count,
                                                                   load.id))

    def dequeue(self, load):
        self.number_waiting.observe_change(-1)
        self.queue.remove(load)
        print("{0}\t{1}\tDequeue. #Waiting: {2}, Load: {3}".format(self.clock_time,
                                                        type(self).__name__,
                                                        self.number_waiting.last_count,
                                                                   load.id))


from socket import socket, AF_INET, SOCK_STREAM
from threading import Thread

client_socket_queue = []
members = 'accept_2862120466'

server_socket = socket(AF_INET, SOCK_STREAM)

server_socket.bind(('169.254.6.166',1234))

server_socket.listen(5)

user_dict = {
    '169.254.6.166':'TGW',
}

def send_msg(send_str):
    for client_socket in client_socket_queue:
        client_socket.send(send_str)

def tcplink(client_socket, addr):
    # client_socket.send('你成功加入聊天室！\n'.encode())
    # print("发送消息：'你成功加入聊天室！'给：%s:%s" % addr)

    while True:
        try:
            msg = client_socket.recv(10240)
            send_str = (user_dict.get(addr[0], ' ') + '：' + msg.decode()).encode()
            if msg.decode() == 'close':
                print("recv：%s" % msg.decode())

                members_new = members.replace( user_dict.get(addr[0]), '' )
                send_msg(members_new.encode())
                client_socket_queue.remove(client_socket)
                client_socket.close()

                print('关闭与%s:%s的连接' % addr)
                break

            elif msg.decode() and msg.decode() != 'close':
                print("recv：%s" % msg.decode())
                send_msg(send_str)
                print('send：%s' % msg.decode())

        except:
            break

while True: # 循环等待连接
    try:
        client_socket, addr = server_socket.accept()
        print('已与%s:%s创建连接' % addr)

        members += user_dict.get(addr[0]) + '\n'
        client_socket_queue.append(client_socket)
        send_msg(members.encode())

        t = Thread(target=tcplink, args=(client_socket, addr))
        t.start()
    except:
        break

代码练习/python实例练习/聊天室服务器.py


"""
Given a string s of '(' , ')' and lowercase English characters.

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

It is the empty string, contains only lowercase characters, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.

Example 1:

Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
Example 2:

Input: s = "a)b(c)d"
Output: "ab(c)d"
Example 3:

Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.
Example 4:

Input: s = "(a(b(c)d)"
Output: "a(b(c)d)"

Constraints:

1 <= s.length <= 10^5
s[i] is one of  '(' , ')' and lowercase English letters.
"""

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        stack = []
        for i,ch in enumerate(s):
            if ch == '(': stack.append(('(', i))
            elif ch == ')':
                if stack and stack[-1][0] == '(':
                    stack.pop()
                else:
                    stack.append((')', i))
        badIndex = set([item[1] for item in stack])
        ans = [s[i] for i in range(len(s)) if i not in badIndex]
        return ''.join(ans)
s = Solution()
print(s.minRemoveToMakeValid("))(("))

Leetcode/Leetcode - Minimum Remove to Make Valid Parentheses.py


#Soal no 3: Given two two digit numbers, merge their digits as shown in the tests below
x=int(input('Angka Pertama: '))
y=int(input('Angka Kedua: '))

print('Gabungan kedua angka: '+str(x)+str(y))
x=str(x)
y=str(y)

print('Hasil pengacakan posisi angka: '+x[0]+y[0]+x[1]+y[1])

#Cara Lain
# a=int(input('Masukkan 2 angka pertama: '))
# b=int(input('Masukkan 2 angka kedua: '))
# tens_a=a//10
# units_a=a%10
# tens_b=b//10
# units_b=b%10
# print(tens_a+tens_b+units_a+units_b)


import os
import tempfile

import pytest
from src import create_app
from src.database import init_db
from src.models import *
from src.serializer import *

@pytest.fixture
def client():
    db_fd,db_path = tempfile.mkstemp()
    app = create_app({'TESTING': True, 'DATABASE': db_path,
                    'SQLALCHEMY_TRACK_MODIFICATIONS':False})
    with app.test_client() as client:
        with app.app_context():
            init_db(app)
        yield client

    os.close(db_fd)
    os.unlink(db_path)

def test_empty_db(client):
    """Start with a blank database."""

    get = client.get('/')
    assert b'natural_wonders_api_docs' in get.data

def test_models(client):
    print(dir(client))
    data = dict(name = "Algonquin park",country="on,canada"\
                        ,about = "Its a beautiful water park")

    location = Locations(data)
    locations_schema = LocationsSchema()
    assert {} != locations_schema.dump(location)


from __future__ import annotations

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, Event
from homeassistant.const import CONF_MAC, EVENT_HOMEASSISTANT_STOP
from homeassistant.const import Platform

from .const import DOMAIN, CONF_RESET, CONF_DELAY
from .elkbledom import BLEDOMInstance
import logging

LOGGER = logging.getLogger(__name__)
PLATFORMS: list[Platform] = [
    Platform.LIGHT,
    Platform.NUMBER,
]

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up ElkBLEDOM from a config entry."""
    reset = entry.options.get(CONF_RESET, None) or entry.data.get(CONF_RESET, None)
    delay = entry.options.get(CONF_DELAY, None) or entry.data.get(CONF_DELAY, None)
    mac = entry.options.get(CONF_MAC, None) or entry.data.get(CONF_MAC, None)
    LOGGER.debug("Config: Reset: %s, Delay: %s, Mac: %s", reset, delay, mac)

    instance = BLEDOMInstance(entry.data[CONF_MAC], reset, delay, hass)
    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = instance

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
    entry.async_on_unload(entry.add_update_listener(_async_update_listener))

    async def _async_stop(event: Event) -> None:
        """Close the connection."""
        await instance.stop()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop)
    )
    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        instance = hass.data[DOMAIN][entry.entry_id]
        await instance.stop()
    return unload_ok

async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
    """Handle options update."""
    instance = hass.data[DOMAIN][entry.entry_id]
    if entry.title != instance.name:
        await hass.config_entries.async_reload(entry.entry_id)


n = int(input())
for i in range(n):
    result = 0
    quiz = list(str(input()))
    sum = 0
    for j in range(len(quiz)):
        if quiz[j] == 'X':
            sum = 0
        else:
            sum += 1
            result += sum
    print(result)


import re

def isPalindrome(s: str) -> bool:

    #함수의 대문자를 소문자로 바꾸기
    s = s.lower()
    #정규식으로 불필요한 문자 필터링
    s = re.sub('[^a-z0-9]','',s)
    #리스트 슬라이싱 - 배열 뒤집기
    return s == s[::-1]

mystring = "A man, a plan, a canal: Panama"
mystring2 = "race a car"
print(isPalindrome(mystring))
print(isPalindrome(mystring2))


# These don't work because ⅁ is the wrong width
#Ɔ⅁ꞱⱯ
#lower_to_upper = {"A":"Ɐ", "T":"Ʇ", "G":"⅁", "C":"Ɔ", " ":" ", "_":"_"}
#upper_to_lower = {"Ɐ":"A", "Ʇ":"T", "⅁":"G", "Ɔ":"C", " ":" ", "_":"_"}

complement = {"A":"T", "T":"A", "G":"C", "C":"G"}

class STRAND:

    def __init__(self,A="",B=""):

        # Check validity
        for string in [A,B]:
            for c in string:
                if c not in "ATGC ":
                    raise Exception(f"{c} is not a valid base")

        # If B isn't given then make A the lower string
        # If B is given then make A the upper string and B the lower string
        # This allows the common scenario where we just want the specify the lower
        # string and also lets us specify both an upper and lower string in a
        # readable way
        # The internal upper and lower are lists so that they are mutable
        if B == "":
            self.upper = [" "]*len(A)
            self.lower = [a for a in A]
        else:
            self.upper = [a for a in A]
            self.lower = [b for b in B]

    # No __repr__ method because the string has to be multiple lines
    def __str__(self):
        if all([u == " " for u in self.upper]):
            return f"{''.join(self.lower)}"
        return f"{''.join(self.upper)}\n{''.join(self.lower)}"

    # Quickly return length
    def __len__(self):
        return len(self.lower)

    # Rotates the STRAND by 180 degrees
    def switch(self):
        new_lower = self.upper[::-1]
        new_upper = self.lower[::-1]

        self.lower = new_lower
        self.upper = new_upper

    # Cut the strand at a position
    def cut(self,pos):
        L = STRAND(self.upper[:pos],self.lower[:pos])
        R = STRAND(self.upper[pos:],self.lower[pos:])
        return L,R

    # Insert a valid base or base pair at a position
    def insert(self,base,pos,copy_mode):
        if base not in "ATGC":
            raise Exception(f"{base} is not a valid base")

        new_lower = self.lower[:pos] + [base] + self.lower[pos:]
        if copy_mode:
            new_upper = self.upper[:pos] + [complement[base]] + self.upper[pos:]
        else:
            new_upper = self.upper[:pos] + [" "] + self.upper[pos:]
        self.lower = new_lower
        self.upper = new_upper

    # Place the complement of the lower base on the upper side
    def copy(self,pos):
        self.upper[pos] = complement[self.lower[pos]]

    # Quick access to string representation of the upper and lower parts of the
    # strand
    def _lower_string(self):
        return "".join(self.lower)

    def _upper_string(self):
        return "".join(self.upper)

    lower_string = property(_lower_string)
    upper_string = property(_upper_string)

def split_strand(strand):
    up = strand.upper_string[::-1]
    lo = strand.lower_string

    U = [STRAND(s) for s in up.split(" ") if s != ""]
    L = [STRAND(s) for s in lo.split(" ") if s != ""]

    return U+L

# Deal with duplets and amino acids
amino_acids = ["cut","del","swi","mvr","mvl","cop","off","ina","inc",
               "ing","int","rpy","rpu","lpy","lpu"]

duplet_to_amino = {"AA":"   ", "AC":"cut", "AG":"del", "AT":"swi",
                   "CA":"mvr", "CC":"mvl", "CG":"cop", "CT":"off",
                   "GA":"ina", "GC":"inc", "GG":"ing", "GT":"int",
                   "TA":"rpy", "TC":"rpu", "TG":"lpy", "TT":"lpu"}

#amino_to_duplet = {"   ":"AA", "cut":"AC", "del":"AG", "swi":"AT",
#                   "mvr":"CA", "mvl":"CC", "cop":"CG", "off":"CT",
#                   "ina":"GA", "inc":"GC", "ing":"GG", "int":"GT",
#                   "rpy":"TA", "rpu":"TC", "lpy":"TG", "lpu":"TT"}

amino_to_fold = {          "cut": 0, "del":0,  "swi":-1,
                 "mvr": 0, "mvl": 0, "cop":-1, "off": 1,
                 "ina": 0, "inc":-1, "ing":-1, "int": 1,
                 "rpy":-1, "rpu": 1, "lpy":1,  "lpu": 1}

direct_to_binding = {0:"A", 1:"C", 2:"T", 3:"G"}

def aminos_to_binding(aminos):
    direct = 0
    for a in aminos[1:-1]:
        direct = (direct+amino_to_fold[a])%4
    return direct_to_binding[direct]

class ENZYME:

    def __init__(self,aminos):

        for i in aminos:
            if i not in amino_acids:
                raise Exception(f"{i} is not a valid instruction")

        self.aminos = aminos
        self.copy_mode = False
        self.binding = aminos_to_binding(aminos)

    def __str__(self):
        S = f"({' 🡢 '.join(self.aminos)})"
        return S

    def __repr__(self):
        return str(self)

    def evaluate(self,strand,pos,show_steps=True):

        if type(strand) != STRAND:
            raise Exception("not a valid strand")

        if type(pos) != int:
            raise Exception("pos must be an integer")

        # We always start with copy mode off
        self.copy_mode = False
        # Collect anything that is snipped off by 'cut'
        snips = []

        if show_steps:
            print(str(strand) + f"  start\n" + " "*pos + "^\n")

        for a in self.aminos:

            # Set copy mode
            if a == "cop":
                self.copy_mode = True
                strand.copy(pos)
            if a == "off":
                self.copy_mode = False

            # Delete the base being worked on but NOT its complement if present
            if a == "del":
                self.strand.lower[pos] = " "

            # Cut to the right of the position
            if a == "cut":
                strand, R = strand.cut(pos+1)
                snips.append(R)

            # Insert rules
            if a == "ing":
                strand.insert("G",pos+1,self.copy_mode)
                pos += 1
            if a == "int":
                strand.insert("T",pos+1,self.copy_mode)
                pos += 1
            if a == "inc":
                strand.insert("C",pos+1,self.copy_mode)
                pos += 1
            if a == "ina":
                strand.insert("A",pos+1,self.copy_mode)
                pos += 1

            # Switch sides
            if a == "swi":
                strand.switch()
                pos = len(strand)-pos-1

            # Move one unit left or right
            if a == "mvr":
                pos += 1
                if pos == len(strand):
                    break
                if self.copy_mode:
                    strand.copy(pos)

            if a == "mvl":
                pos -= 1
                if pos == -1:
                    break
                if self.copy_mode:
                    strand.copy(pos)

            # Scan to find a purine or pyrimidine
            if a == "rpy":
                if strand.lower[pos] in "TC":
                    pos += 1
                    if pos == len(strand):
                        break
                    if self.copy_mode:
                        strand.copy(pos)
                while strand.lower[pos] not in "TC":
                    pos += 1
                    if pos == len(strand):
                        break
                    if self.copy_mode:
                        strand.copy(pos)

            if a == "rpu":
                if strand.lower[pos] in "AG":
                    pos += 1
                    if pos == len(strand):
                        break
                    if self.copy_mode:
                        strand.copy(pos)
                while strand.lower[pos] not in "AG":
                    pos += 1
                    if pos == len(strand):
                        break
                    if self.copy_mode:
                        strand.copy(pos)

            if a == "lpy":
                if strand.lower[pos] in "TC":
                    pos -= 1
                    if pos == -1:
                        break
                    if self.copy_mode:
                        strand.copy(pos)
                while strand.lower[pos] not in "TC":
                    pos -= 1
                    if pos == -1:
                        break
                    if self.copy_mode:
                        strand.copy(pos)
            if a == "lpu":
                if strand.lower[pos] in "AG":
                    pos -= 1
                    if pos == -1:
                        break
                    if self.copy_mode:
                        strand.copy(pos)
                while strand.lower[pos] not in "AG":
                    pos -= 1
                    if pos == -1:
                        break
                    if self.copy_mode:
                        strand.copy(pos)

            if show_steps:
                print(str(strand) + f"  {a}\n" + " "*pos + "^\n")

        # seperate out everything
        out = split_strand(strand)
        for s in snips:
            out += split_strand(s)
        return out

def chunk_by_size(L,n):
    return [L[i * n:(i + 1) * n] for i in range((len(L) + n - 1) // n )]

def strand_to_enzymes(strand):
    if not all([u == " " for u in strand.upper]):
        raise Exception("a strand with an upper attachment cannot be turned into an enzyme")

    string = strand.lower_string
    enzymes = []
    E = []
    for duplet in chunk_by_size(string,2):
        if len(duplet) < 2:
            break
        if duplet == "AA":
            enzymes.append(ENZYME(E))
            E = []
            continue
        E.append(duplet_to_amino[duplet])
    enzymes.append(ENZYME(E))

    return enzymes

def strands_to_enzymes(strands):
    enzymes = []
    for s in strands:
        enzymes += strand_to_enzymes(s)
    return enzymes

def strand_to_enzymes_cycle(strand,enzyme,pos,show_steps=False):

    print(f"Starting Strand:\n{strand}\n\nStarting Enzyme:\n{enzyme}\n")
    if show_steps:
        print("\nEnzyme Action:\n")
        strands = enzyme.evaluate(strand,pos,show_steps=True)
    else:
        strands = enzyme.evaluate(strand,pos,show_steps=False)
    print("\nResultant Strands:")
    for st in strands:
        print(st)
    print()
    print("Resultant Enzymes:")
    for enz in strands_to_enzymes(strands):
        print(enz)

if __name__ == '__main__':

    DNA1 = STRAND("CAAAGAGAATCCTCTTTGAT")
    E1 = ENZYME(["rpy","cop","rpu","cut"])
    strand_to_enzymes_cycle(DNA1,E1,2,show_steps=True)

    print("\n\n\n")

    DNA2 = STRAND("TAGATCCAGTCCATCGA")
    E2 = ENZYME(["rpu","inc","cop","mvr","mvl","swi","lpu","int"])
    strand_to_enzymes_cycle(DNA2,E2,8,show_steps=True)


import os
import sys
import reframe as rfm
import reframe.utility.sanity as sn
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
                '../common')))  # noqa: E402
import sphexa.hooks as hooks

# {{{ class SphExa_STAT_Check
@rfm.simple_test
class SphExa_STAT_Check(rfm.RegressionTest, hooks.setup_pe, hooks.setup_code):
    # {{{
    '''
    This class runs the test code with Cray stat
    '''
    # }}}
    steps = parameter([2])  # will hang rank0 at step0
    compute_node = parameter([1])
    np_per_c = parameter([1e3])
    debug_flags = variable(bool, value=True)

    def __init__(self):
        # {{{ pe
        self.descr = 'Tool validation'
        self.valid_prog_environs = [
            'PrgEnv-gnu', 'cpeGNU'
        ]
        self.valid_systems = [
            'dom:mc', 'dom:gpu', 'daint:mc', 'daint:gpu',
            'eiger:mc', 'pilatus:mc'
        ]
        self.tool = 'stat-cl'
        self.modules = ['cray-stat', 'cray-cti']
        self.maintainers = ['JG']
        self.tags = {'sph', 'hpctools', 'cpu', 'craype', 'debugging'}
        # }}}

        # {{{ compile
        self.testname = 'sedov'
        self.executable = 'mpi+omp'
        # re_ver_1 = 'STAT_VERSION1=$'
        # re_ver_2 = 'STAT_VERSION2=$'
        version_rpt = 'version.rpt'
        which_rpt = 'which.rpt'
        cs = self.current_system.name
        if cs not in {'pilatus', 'eiger'}:
            self.prebuild_cmds += [
                # --- chech tool version
                f'echo STAT_VERSION1=$STAT_VERSION > {version_rpt}',
                f'echo STAT_VERSION2=`STATbin --version` >> {version_rpt}',
            ]
        else:
            self.prebuild_cmds += [
                # --- chech tool version
                f'echo STAT_VERSION1=$STAT_LEVEL > {version_rpt}',
                f'echo STAT_VERSION2=`STATbin --version` >> {version_rpt}',
            ]

        self.prebuild_cmds += [
            f'STATbin -V >> {version_rpt}',
            f'which {self.tool} > {which_rpt}',
        ]

        # {{{ run
        self.time_limit = '10m'
        # }}}

        # {{{ sanity
        # TODO: regex = (
        #     r'function="(?P<fun>.*)", source="(?P<filename>.*)",'
        #     r' line=":(?P<ll>\d+)"'
        # )
        # + cuda
        # + largescale
        self.sanity_patterns = sn.all([
            # check the job output:
            sn.assert_found(r'Starting main loop', self.stdout),
            # check the tool output:
            sn.assert_not_found('not found', which_rpt),
            sn.assert_not_found('ERROR', self.stdout),
            # <LMON FE API> (ERROR): read_lmonp_msgheader failed while
            # attempting to receive continue launch message from back end
            sn.assert_found(r'STAT started', self.stdout),
            sn.assert_found(r'Attaching to job launcher', self.stdout),
            sn.assert_found(r'launching tool daemons', self.stdout),
            sn.assert_found(r'Results written to', self.stdout),
        ])
        # }}}

        # {{{ performance
        # see common/sphexa/hooks.py
        # }}}

    # {{{ hooks
    # {{{ set_hang
    @run_before('compile')
    def set_hang(self):
        source_file = 'include/sph/totalEnergy.hpp'
        die = '60'
        sed_header = (r'"s@USE_MPI@USE_MPI\n#include <thread>@"')
        sed_hang = (
            r'"/MPI_Allreduce(MPI_IN_PLACE, &einttmp, 1, MPI_DOUBLE, MPI_SUM, '
            r'MPI_COMM_WORLD);/a'
            r'int mpirank; MPI_Comm_rank(MPI_COMM_WORLD, &mpirank);'
            r'if (mpirank == 0 && d.iteration == 0) '
            r'{std::this_thread::sleep_for(std::chrono::seconds('f'{die}));'
            r'}"'
        )
        self.prebuild_cmds += [
            f'# --- make the code hang:',
            f'sed -i {sed_header} {source_file}',
            f'sed -i {sed_hang} {source_file}',
        ]
    # }}}

    # {{{ set_tool
    @run_before('run')
    def set_tool(self):
        self.executable_opts += ['& #']
        # FIXME: will default to: '& # -n 50 -s 2'
        ssh_cmd = 'ssh -o "StrictHostKeyChecking no"'
        self.postrun_cmds = [
            # slurm only
            'nid=`SQUEUE_FORMAT=%.9B squeue --noheader -j $SLURM_JOBID`',
            f'pidsrun=`{ssh_cmd} $nid "ps -hxo pid,cmd |grep -m1 srun" `',
            'pid=${pidsrun% srun*}',
            'echo "# nid=$nid pid=$pid"',
            'sleep 1',
            f'tool=`which {self.tool}`',
            'echo "tool=$tool"',
            f'{ssh_cmd} $nid "cd {self.stagedir} ;'
            f'$tool -i -j $SLURM_JOBID $pid"',
            'wait',
            'echo done'
        ]
    # }}}
    # }}}
# }}}


"""
Models for multivariate downscaling - predicting P(precip|Tmax)
"""

from .models.encoder import Encoder
from .models.mlp import MLP
from .models.final_layers import GaussianFinalLayer, GammaFinalLayer, GammaGPFinalLayer
from .models.cnn import CNN, ResConvBlock
from .models.utils import force_positive

class TmaxElevStacked(nn.Module):
    """
    Multivariate downscaling P(precip|Tmax)
    - Tmax
    Parameters:
    ----------
    decoder: convolutional architecture
    in_channels: Int
        Number of context variables
    ls: float
        Initial length scale for the RBF kernel
    """

    def __init__(self, decoder, in_channels=1, ls = 0.1):

        super().__init__()

        self.encoder = Encoder(in_channels)

        self.decoder= decoder

        self.mlp = MLP(decoder.out_channels, 2,
            hidden_channels = 64,
            hidden_layers = 4)

        self.elev_mlp = MLP(5, 2,
            hidden_channels = 64,
            hidden_layers = 4)

        self.activation_function = torch.relu
        self.final_layer = GaussianFinalLayer(0.1, 2)

    def forward(self, x, mask, dists, elev):

        # Encode with set convolution
        x = self.encoder(x, mask)
        x = self.activation_function(x)
        # Decode with CNN
        x = self.decoder(x)
        x = self.activation_function(x)
        # MLP
        x = self.mlp(x)

        mu, sigma = self.final_layer(x, dists)

        out = torch.cat([mu.view(*mu.shape, 1),
            sigma.view(*sigma.shape, 1)], dim = 2)

        # Do elevation
        elev = elev.repeat(out.shape[0], 1, 1)
        out = torch.cat([out, elev], dim = 2)
        out = self.elev_mlp(out)
        out[...,1] = force_positive(out[...,1])

        # Return target refinements and coarse scale predictions
        return out, x

class GammaElevStacked(nn.Module):
    """
    Multivariate downscaling P(precip|Tmax)
    - Gamma
    Parameters:
    ----------
    decoder: convolutional architecture
    tmax_model: trained convCNP predicting tmax
    in_channels: Int
        Number of context variables
    ls: float
        Initial length scale for the RBF kernel
    """

    def __init__(self,
                 decoder,
                 tmax_model,
                 in_channels = 1,
                 ls = 0.1):
        super().__init__()
        self.in_channels = in_channels
        self.activation = torch.relu
        self.sigmoid = nn.Sigmoid()

        self.encoder = Encoder(in_channels = in_channels+2)
        self.mlp = MLP(in_channels = 128,
            out_channels = 3,
            hidden_channels = 64,
            hidden_layers = 4)
        self.decoder = decoder
        self.out_layer = GammaFinalLayer(
            init_ls = ls,
            n_params = 3
        )

        self.elev_mlp = MLP(8,
            out_channels = 3,
            hidden_channels = 64,
            hidden_layers = 4)

        self.tmax_model = tmax_model

    def forward(self, h, mask, dists, elev):

        self.tmax_model.eval()

        # Predict tmax at the target points
        tmax_target, tmax_context  = tmax_model(h,
                                       mask,
                                       dists,
                                       elev)

        # Make new context and mask
        mask = torch.cat([mask, torch.ones(mask.shape[0], 2, 87, 50).cuda()], dim = 1)
        h = torch.cat([h, tmax_context.permute(0, 3, 1, 2)], axis = 1)

        # Encode with set convolution
        h = self.activation(self.encoder(h, mask))
        # Decode with CNN
        h = self.activation(self.decoder(h))
        # MLP
        h = self.mlp(h)
        # out layer
        rho, alpha, beta = self.out_layer(h, dists)
        out = torch.cat([rho.view(*rho.shape, 1),
            alpha.view(*alpha.shape, 1),
            beta.view(*beta.shape, 1)], dim = 2)

        # Do elevation
        elev = elev.repeat(out.shape[0], 1, 1)
        out = torch.cat([tmax_target, out[...,0], elev], dim = 2)
        out = self.elev_mlp(out)
        out[...,0] = self.sigmoid(out[...,0])
        out[...,1:] = force_positive(out[...,1:])

        return out


from nltk.tag import StanfordNERTagger
import re

class NERTagger():
    def __init__(self):
        stanford_ner_dir = '/Users/Rena/StandfordParserData/stanford-ner-2018-02-27/'
        eng_model_filename= stanford_ner_dir + 'classifiers/english.all.3class.distsim.crf.ser.gz'
        my_path_to_jar= stanford_ner_dir + 'stanford-ner.jar'

        self.tagger = StanfordNERTagger(model_filename=eng_model_filename, path_to_jar=my_path_to_jar)
        self.ner_cache = {}
        self.time_list = [
            'january',
            'february',
            'march',
            'april',
            'may',
            'june',
            'july',
            'august',
            'september',
            'october',
            'november',
            'december'
        ]
        self.ordinal_list = [
            'first',
            'largest',
            'highest',
            'second',
            'third',
            'fourth',
            'fifth',
            'one',
            'two',
            'three',
            'four',
            'five',
            'six',
            'seven',
            'eight',
            'nine',
            'ten'
        ]

    def cache_sents(self, sents):
        ###cache the documents###
        tokenised_sent = map(lambda x: x.split(), sents)
        tagged = self.tagger.tag_sents(tokenised_sent)
        for i in range(len(tokenised_sent)):
            self.ner_cache[sents[i]] = tagged[i]
        return True

    def tag(self, sents):

        pattern = '([^A-Z]\.\s[A-Z])'
        if re.search(pattern, sents):
            sentences = self.split_para(sents)
            entity_list = []
            for s in sentences:

                try:
                    tagged = self.ner_cache[s]
                except KeyError:
                    sent = map(self.strip_word, s.split())
                    tagged = self.tagger.tag(sent)
                    self.ner_cache[s] = tagged
                entity = self.entity_parse(tagged)
                entity_list.append(entity)
            result = sum(entity_list, [])
        else:

            try:
                tagged_sents = self.ner_cache[sents]
            except KeyError:
                sen = map(self.strip_word, sents.split())
                tagged_sents = self.tagger.tag(sen)
                self.ner_cache[sents] = tagged_sents

            result = self.entity_parse(tagged_sents)
        return result

    def strip_word(self, word):
        pattern = ('"",:.?!;''')
        return word.strip(pattern)

    def split_para(self, para):
        pattern = '([^A-Z]\.\s[A-Z])'
        splitted = re.split(pattern, para)
        matching_pattern = '^[^A-Z]\.\s[A-Z]$'

        for i in range(len(splitted)):
            if re.match(matching_pattern, splitted[i]):
                symbols = splitted[i].split()
                try:
                    splitted[i-1] += symbols[0]
                    splitted[i+1] = symbols[1] + splitted[i+1]
                except:
                    continue

        proper_splitted = []
        for i in range(len(splitted)):
            if re.match(matching_pattern, splitted[i]):
                continue
            else:
                proper_splitted.append(splitted[i])

        return proper_splitted

    def entity_parse_detail(self, tagged_sent):
        ###entity parsing method for detailed tagset###
        start = True
        retagged_entity = []
        for item in tagged_sent:
            token, tag = item
            if token.lower() in self.time_list:
                tag = 'MONTH'
            elif re.match('^[1|2][0-9]{3,3}$', token):
                tag = 'YEAR'
            elif token.lower() in self.ordinal_list:
                tag = 'NUMBER'
            elif tag == 'ORGANIZATION':
                tag = 'OTHER'
            elif tag == 'O':
                if not start and len(token) > 0 and token[0].isupper():
                    tag = 'OTHER'
                elif any(char == '%' for char in token):
                    tag = 'NUMBER'#'PERCENT'
                elif any(char == '$' for char in token):
                    tag = 'NUMBER'#'MONEY'
                elif any(char.isdigit() for char in token):
                    tag = 'NUMBER'

            if start:
                start = False
            retagged_entity.append((token, tag))

        retagged_entity = self.retag_date(retagged_entity)

        return self.gather_entity(retagged_entity)

    def retag_date(self, tagged_entity):
        ###gather NUMBER MONTH YEAR pattern into DATE###
        result_entity = []
        i = 0
        while i < len(tagged_entity) - 2:
            (token1, tag1) = tagged_entity[i]

            if tag1 == 'NUMBER':
                (token2, tag2) = tagged_entity[i+1]
                if tag2 == 'MONTH':
                    (token3, tag3) = tagged_entity[i+2]
                    if tag3 == 'YEAR':
                        result_entity.append((token1,'DATE'))
                        result_entity.append((token2, 'DATE'))
                        result_entity.append((token3, 'DATE'))
                        i = i + 3
                        continue
            elif tag1 == 'MONTH':
                (token2, tag2) = tagged_entity[i+1]
                if tag2 == 'NUMBER':
                    (token3, tag3) = tagged_entity[i+2]
                    if tag3 == 'YEAR':
                        result_entity.append((token1,'DATE'))
                        result_entity.append((token2, 'DATE'))
                        result_entity.append((token3, 'DATE'))
                        i = i + 3
                        continue
            result_entity.append((token1, tag1))
            i += 1
        for counter in range(len(tagged_entity) - i):
            result_entity.append(tagged_entity[i + counter])

        return result_entity

    def entity_parse(self, tagged_sent):
        ###entity parsing for general tagset###
        start = True
        retagged_entity = []
        for item in tagged_sent:
            token, tag = item
            if token.lower() in self.time_list:
                tag = 'NUMBER'
            if token.lower() in self.ordinal_list:
                tag = 'NUMBER'
            if tag == 'ORGANIZATION':
                tag = 'OTHER'
            if tag == 'O':
                if not start and len(token) > 0 and token[0].isupper():
                    tag = 'OTHER'
                elif any(char.isdigit() for char in token):
                    tag = 'NUMBER'

            if start:
                start = False
            retagged_entity.append((token, tag))

        return self.gather_entity(retagged_entity)

    def gather_entity(self, retagged_entity):
        ###gather continuous entities###
        gathered_entity = []
        tag = 'O'
        token = ''
        for (new_token, new_tag) in retagged_entity:
            if tag == new_tag:

                token = token + ' ' + new_token

            else:
                if tag != 'O':

                    gathered_entity.append((token, tag))
                tag = new_tag
                token = new_token
        if tag != 'O':

            gathered_entity.append((token, tag))

        return gathered_entity

'''
if __name__ == '__main__':
    ner = NERTagger()
    ner.tag('In 1925, the first meeting of the Hundred Percent Club, composed of IBM salesmen who meet their quotas, convened in Atlantic City, New Jersey.')
'''


import sys

# 230420

n = input()

stck = list()

for _ in range(int(n)):
    word = sys.stdin.readline().strip()
    if word.split()[0] == "push":
        stck.append(word.split()[1])
    elif word == "pop":
        if len(stck) == 0:
            print("-1")
        else:
            print(stck.pop())
    elif word == "size":
        print(len(stck))
    elif word == "empty":
        if len(stck) == 0:
            print(1)
        else:
            print(0)
    elif word == "top":
        if len(stck) == 0:
            print("-1")
        else:
            print(stck[-1])


import math

instructions = []

with open("data.txt", "r") as f:
	for l in f:
		instructions.append(l.split("\n")[0])

west = {90: "north", 180: "east", 270: "south", -90: "south", -180: "east", -270: "north"}
north = {90: "east", 180: "south", 270: "west", -90: "west", -180: "south", -270: "east"}
east = {90: "south", 180: "west", 270: "north", -90: "north", -180: "west", -270: "south"}
south = {90: "west", 180: "north", 270: "east", -90: "east", -180: "north", -270: "west"}

instr = []
tabPom = []
actual = "east"

for i in instructions:
	tabPom.append(i[0])
	tabPom.append(i[1:])
	instr.append(tabPom)
	tabPom = []

e=0
n=0
s=0
w=0

for ins in instr:
	if ins[0] == "E":
		e = e + int(ins[1])
	if ins[0] == "N":
		n = n + int(ins[1])
	if ins[0] == "S":
		s = s + int(ins[1])
	if ins[0] == "W":
		w = w + int(ins[1])
	if ins[0] == "R":
		if actual == "east":
			actual = east[int(ins[1])]
		elif actual == "north":
			actual = north[int(ins[1])]
		elif actual == "west":
			actual = west[int(ins[1])]
		elif actual == "south":
			actual = south[int(ins[1])]
	if ins[0] == "L":
		if actual == "east":
			actual = east[-int(ins[1])]
		elif actual == "north":
			actual = north[-int(ins[1])]
		elif actual == "west":
			actual = west[-int(ins[1])]
		elif actual == "south":
			actual = south[-int(ins[1])]
	if ins[0] == "F":
		if actual == "east":
			e = e + int(ins[1])
		elif actual == "north":
			n = n + int(ins[1])
		elif actual == "west":
			w = w + int(ins[1])
		elif actual == "south":
			s = s + int(ins[1])
	print(ins, e, n, s, w, actual)

pl = 0
gd = 0

gd = math.fabs(n - s)
pl = math.fabs(w - e)

print(e, n, s, w, actual )

print(gd + pl )


import tempfile
import gnupg
import pytest

from django.conf import settings
from snoop import emails, models, pgp

pytestmark = pytest.mark.skipif(not settings.SNOOP_GPG_BINARY,
    reason="SNOOP_GPG_BINARY not set")

PATH_HUSH_MAIL = 'eml-9-pgp/encrypted-hushmail-knockoff.eml'
HEIN_PRIVATE_KEY = 'eml-9-pgp/keys/hein-priv.gpg'
HEIN_PUBLIC_KEY = 'eml-9-pgp/keys/hein-pub.gpg'

@pytest.yield_fixture(autouse=True)
def patch_gpg_to_temp_dir(monkeypatch):
    with tempfile.TemporaryDirectory() as tmp:
        gpg = gnupg.GPG(gnupghome=tmp, gpgbinary='gpg')
        for path in [HEIN_PRIVATE_KEY, HEIN_PUBLIC_KEY]:
            with open(settings.SNOOP_ROOT + "/" + path, 'rb') as f:
                gpg.import_keys(f.read())
        monkeypatch.setattr(pgp, 'GPG', gpg)
        monkeypatch.setattr(settings, 'SNOOP_GPG_HOME', '/tmp')
        yield

def create_email_doc(path, collection):
    doc = models.Document(
        path=path,
        content_type='message/rfc822',
        collection=collection,
    )
    doc.save = lambda *a, **k: None
    return doc

def parse_email(path, document_collection):
    return emails.parse_email(create_email_doc(path, document_collection))

def open_email(path, document_collection):
    return emails.open_email(create_email_doc(path, document_collection))

def test_doc_flags(document_collection):
    doc = create_email_doc(PATH_HUSH_MAIL, document_collection)
    emails.parse_email(doc)
    assert doc.flags.get('pgp')

def test_header_data(document_collection):
    data = parse_email(PATH_HUSH_MAIL, document_collection)
    assert data['subject'] == "Fwd: test email"
    assert data['date'] == '2016-08-10T15:00:00'

def test_attachments(document_collection):
    data = parse_email(PATH_HUSH_MAIL, document_collection)
    attach = data['attachments']
    assert len(attach) == 6

    email = open_email(PATH_HUSH_MAIL, document_collection)
    assert email.pgp

    with email.open_part('3') as f:
        text = f.read().decode()
        assert "This is GPG v1 speaking!" in text
        assert "Sent from my Android piece of !@#%." in text


def count_substring(main,sub):
    count=0
    while True:
        #print(main)
        ind=main.find(sub)
        #print(ind)
        main=main[ind+len(sub):]

        if ind<0:
            return count
        count = count + 1

if __name__=="__main__":
    mainString=input()
    subString=input()
    print(count_substring(mainString,subString))


#% extends "py-script.mk" %#
#% block name %#phonify#% endblock %#
#% block script %#

##- '$(utils_py)' -##
##- '$(parsers_py)' -##

def check_item(item):
    if not "goal" in item:
        return False
    args = parseargs(item.get("msgargs", ""))
    return not args.not_phony

def main():
    items = " ".join(
        (
            i["goal"]
            for i in parse_help(gen_makefile(), require_msg=False)
            if check_item(i)
        )
    )
    sys.stdout.write(".PHONY: " + items)

if __name__ == "__main__":
    main()

#% endblock %#


import GPy
from hmm.continuous.LFMHMMcontinuous import LFMHMMcontinuous
from hmm.continuous.ICMHMMcontinuousMO import ICMHMMcontinuousMO
from matplotlib import pyplot as plt
import numpy as np

seed = np.random.random_integers(10000)
np.random.seed(seed)

print("Using GPy version: ", GPy.__version__)

data = GPy.util.datasets.cmu_mocap('05', ['20'], sample_every=1)
print(data['info'])
Y = data['Y']
nsamples, nfeatures = Y.shape
print("Y's shape ", Y.shape)

channel_ids = [9, 16]  # ltibia and rtibia

for idx in channel_ids:
    plt.plot(np.arange(nsamples), Y[:, idx])
plt.show()

number_hidden_states = 3
outputs = len(channel_ids)
start_t = 0.1
end_t = 5.1
locations_per_segment = 20
n_latent_forces = 1  # TODO: currently not passing this argument to the model.

lfm_hmm = ICMHMMcontinuousMO(outputs, number_hidden_states, locations_per_segment, start_t,
                           end_t, verbose=True)

number_training_sequences = 1
obs = []
for s in range(number_training_sequences):
    number_segments = 55  # fixed for now.
    c_obs = np.zeros((number_segments, locations_per_segment * outputs))
    for output_id in range(outputs):
        signal = Y[:, channel_ids[output_id]]
        idx = 0
        for i in range(number_segments):
            c_obs[i, output_id::outputs] = signal[idx:idx + locations_per_segment]
            idx = idx + locations_per_segment - 1
    obs.append(c_obs)

lfm_hmm.set_observations(obs)

print("before training")
print(lfm_hmm.pi)
print(lfm_hmm.A)
print(lfm_hmm.ICMparams)

train_flag = False
file = "second-ICM-MOCAP-MO"
if train_flag:
    lfm_hmm.train()
    lfm_hmm.save_params("/home/diego/tmp/Parameters/MOCAP", file)
else:
    lfm_hmm.read_params("/home/diego/tmp/Parameters/MOCAP", file)

print("after training")
print(lfm_hmm.pi)
print(lfm_hmm.A)
print(lfm_hmm.ICMparams)

obs_1 = obs[0]
hidden_states_1 = lfm_hmm._viterbi()[0]

considered_segments = len(obs_1)
number_testing_points = 100
# prediction
last_value = 0
plt.axvline(x=last_value, color='red', linestyle='--')
for i in range(considered_segments):
    c_hidden_state = hidden_states_1[i]
    c_obv = obs_1[i]
    # predicting more time steps
    t_test = np.linspace(start_t, end_t, number_testing_points)
    mean_pred, cov_pred = lfm_hmm.predict(t_test, c_hidden_state, c_obv)
    mean_pred = mean_pred.flatten()
    cov_pred = np.diag(cov_pred)

    current_outputs = np.zeros((number_testing_points, outputs))
    current_covariances = np.zeros((number_testing_points, outputs))
    # separating the outputs accordingly.
    for j in range(outputs):
        current_outputs[:, j] = mean_pred[j::outputs]
        current_covariances[:, j] = cov_pred[j::outputs]

    sl = lfm_hmm.sample_locations
    for j in range(outputs):
        plt.scatter(last_value + sl - sl[0], c_obv[j::outputs],
                    facecolors='none', label=[None, 'observations'][i == 0])

    plt.plot(last_value + t_test - t_test[0], current_outputs, color='green',
             label=[None, 'predicted mean'][i == 0])
    diag_cov = np.diag(cov_pred)
    plt.plot(last_value + t_test - t_test[0],
             current_outputs - 2 * np.sqrt(current_covariances), 'k--')
    plt.plot(last_value + t_test - t_test[0],
             current_outputs + 2 * np.sqrt(current_covariances), 'k--')
    last_value = last_value + end_t - start_t
    plt.axvline(x=last_value, color='red', linestyle='--')
plt.show()

print("Inferred hidden states ", hidden_states_1)
print("USED SEED", seed)


import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import openpyxl

ElectrolyserPower = 300        # in kW

xls = pd.read_excel('inverter_20221029_204628.xlsx', engine = 'openpyxl')

Power = xls["AC출력(kW)"]

class electrolyzer:
    def __init__(self,production_rate,max_power):
        self.production_rate = production_rate     #kg
        self.max_power = max_power                 #in kw

class ITM_PEM(electrolyzer):
    def __init__(self,production_rate, max_power):
        super().__init__(production_rate, max_power)
        self.min_power = max_power*10/100  # in kW

class battery:
    def __init__(self, capacity):                     # kwh
        self.power_rating = 0.25 * capacity           # kwh
        self.capacity = capacity *3600                # kj

electrolyser = ITM_PEM(4.86, ElectrolyserPower)

T = len(Power)                           # no. of hourly periods

state = np.ones((T,1))

grid_demand = np.zeros((T,1))            # power required from grid
H_produced = np.zeros((T,1))             # kg of hydrogen produced in the hour period
batt_power = np.zeros((T,1))             # Amt of power load into battery in kW
batt_soc = np.zeros((T,1))               # Amt of energy stored in battery in kJ
excess_solar = np.zeros((T,1))           # kW
electrolyzer_power = Power

#batt = battery(100)

batt_sol = []
baso = []
gridd = []
for i in range(400):
# Records hydrogen produced in each hour period
    print(i)
    #electrolyser = ITM_PEM(4.86, i)
    batt = battery(i)
    for j in range(T):
        #if electrolyser is on
        if state[j] == 1:
            if electrolyzer_power[j] >= electrolyser.max_power:                              #if theoretical power exceeds max power
                batt_power[j] = min((electrolyzer_power[j] - electrolyser.max_power), batt.power_rating)
                #print(batt_power)
                if batt_power[j] == batt.power_rating:
                    excess_solar[j] = electrolyzer_power[j] - batt.power_rating - electrolyser.max_power
                    #print(excess_solar)
                batt_soc[j] = min((batt_soc[j-1] + batt_power[j]*60*60), batt.capacity)

                if batt_soc[j-1] == batt.capacity:
                    excess_solar[j] = electrolyzer_power[j] - electrolyser.max_power
                    #print(excess_solar)
            else:                                                                           #if theoretical power is below min power
                grid_demand[j] = electrolyser.max_power - electrolyzer_power[j]

                if grid_demand[j] > batt.power_rating:                                 #if power demand exceeds battery power rating
                    if batt_soc[j-1] > batt.power_rating*60*60:
                        batt_soc[j] = batt_soc[j-1] - batt.power_rating*3600
                        grid_demand[j] = grid_demand[j] - batt.power_rating
                    else:
                        batt_soc[j] = batt_soc[j-1]
                elif grid_demand[j] < batt.power_rating:                               #if power demand is within battery power rating
                    #if there is sufficient energy in battery storage
                    if batt_soc[j-1] > grid_demand[j]*60*60:
                        batt_soc[j] = batt_soc[j-1] - grid_demand[j]*3600
                        grid_demand[j] = 0
                    else:
                        batt_soc[j] = batt_soc[j-1]

        #if electrolyser is off
        else:
            H_produced[j] = 0

            if batt_soc[j-1] == batt.capacity:
                excess_solar[j] = electrolyzer_power[j]
                batt_soc[j] = batt_soc[j-1]
            else:
                if electrolyzer_power[j] > batt.power_rating:
                    excess_solar[j] = electrolyzer_power[j] - batt.power_rating
                    batt_soc[j] = min((batt_soc[j-1] + batt.power_rating*60*60), batt.capacity)
                else:
                    batt_soc[j] = min((batt_soc[j-1] + electrolyzer_power[j]*60*60), batt.capacity)
    batt_sol.append(int(np.average(excess_solar)))
    baso.append(int(np.max(batt_soc)))
    gridd.append(int(np.max(grid_demand)))
    #print(batt_soc)

plt.figure(figsize = (10,10))

#ax = plt.subplot(1,1,1)
plt.plot(batt_sol)
plt.title("Hourly Battery State of Charge")
plt.xlabel('Batt cap')
plt.ylabel('soc')
plt.savefig("bcs.png")

plt.figure(figsize = (10,10))
plt.plot(batt_sol)
plt.title("Hourly Battery State of Charge")
plt.xlabel('Batt cap')
plt.ylabel('excess sol')
print(type(batt_sol))
print(batt_sol.index(min(batt_sol)))
plt.savefig("bces.png")
print(baso.index(min(gridd)))


from unittest import TestCase
from unittest.mock import patch, mock_open, MagicMock

from gobexport.exporter.dat import dat_exporter

class TestDatExporter(TestCase):

    def test_append_raises_notimplementederror(self):

        with self.assertRaises(NotImplementedError):
            dat_exporter([], '', append=True)

    @patch("builtins.open", mock_open())
    @patch("gobexport.exporter.dat.ProgressTicker")
    @patch("gobexport.exporter.dat.re", MagicMock())
    def test_dat_exporter_filter(self, mock_progress_ticker):

        api = [{'a': 'b'}]
        file = ""

        dat_exporter(api, file)
        mock_tick = mock_progress_ticker.return_value.__enter__.return_value
        mock_tick.tick.assert_called_once()
        mock_tick.tick.reset_mock()

        mock_filter = MagicMock()
        mock_filter.filter.return_value = False
        dat_exporter(api, file, filter=mock_filter)

        mock_filter.filter.assert_called_with({'a': 'b', 'row_count': 1})
        mock_tick.tick.assert_not_called()


# -*- coding: utf-8 -*-
"""
Created on Wed Nov  9 12:23:14 2022

@author: Marco-PC
"""

import networkx as nx
import matplotlib.pyplot as plt

def color(num,state):
    ret=None
    if(state=="S"):
        ret=["lightblue"]
    if(state=="E"):
        ret=["yellow"]
    if(state=="I"):
        ret=["red"]
    if(state=="R"):
        ret=["green"]
    if(state=="D"):
        ret=["gray"]
    return ret

def colors(states):
    ret=list()
    for s in states:
        ret+=color(*s)
    return ret

def onShow(G,state):
    colorList=colors(G.nodes(data="state"))
    nx.draw(G,with_labels=True,
            node_color=colorList)
    plt.show()

Master/Second Year/Second Semester/Information Retrieval/NS/utils.py


#! python3
from lark import Lark
from transformers import CleanNamespaceToken, CleanNamespaceTree, Base, Parse
from pathlib import Path
from pprint import pformat
from manipulators import correct_tddft_transition_number
import click
import sys

parser = Lark.open(
        Path(__file__).parents[0] / "grammar" / "parser.lark",
        import_paths=[Path(__file__).parents[0] / 'grammar'])

def parse(string, fix_occupied=True):
    tree = parser.parse(string)
    transformer = CleanNamespaceToken() * Base() * CleanNamespaceTree() * Parse()
    resulting_tree = transformer.transform(tree)
    result = resulting_tree.children
    if fix_occupied:
        correct_tddft_transition_number(result)
    return result

def pretty(string):
    tree = parser.parse(string)
    click.echo(tree.pretty())

def debug_f(string):
    tree = parser.parse(string)
    transformer = CleanNamespaceToken() * Base() * CleanNamespaceTree() * Parse()
    tree = transformer.transform(tree)
    # click.echo(tree.pretty())
    click.echo(pformat(tree.children["TDDFT"]))

@click.command()
@click.argument("inputfile", type=click.File('r'))
@click.option("-p", "--pretty-print", is_flag=True)
@click.option("-d", "--debug", is_flag=True)
@click.option("-n", "--no-fix_occupied", is_flag=True)
def main(inputfile, pretty_print, debug, no_fix_occupied):
    fstr = inputfile.read()
    inputfile.close()
    if pretty_print:
        pretty(fstr)
        sys.exit()
    if debug:
        debug_f(fstr)
        sys.exit()

    # Transformation returns the 'start' Tree instance, which contains the
    # dict in it's children property.
    parsed = parse(fstr, fix_occupied=not no_fix_occupied)
    # This should become json.dumps when the output is no longer a Tree instance.
    click.echo(pformat(parsed))

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding utf-8 -*-

import openai
import yaml

'''
模拟聊天客服，同样的问题，回答多次，会得到不同答案
'''

def get_api_key():
    with open("config.yaml", "r", encoding="utf-8") as yaml_file:
        yaml_data = yaml.safe_load(yaml_file)
        openai.api_key = yaml_data["openai"]["api_key"]

def get_response(prompt, temperature = 1.0):
    completions = openai.Completion.create (
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=temperature,
    )
    message = completions.choices[0].text
    return message

if __name__ == '__main__':
    get_api_key()
    prompt = '请你用朋友的语气回复给到客户，并称他为“亲”，他的订单已经发货在路上了，预计在3天之内会送达，订单号2021AEDG，我们很抱歉因为天气的原因物流时间比原来长，感谢他选购我们的商品。'
    print(get_response(prompt))
    print(get_response(prompt))
    print(get_response(prompt))

'''
亲,你的订单2021AEDG，我们已经发货，我们估计这份订单会在3天之内送达，但是由于天气的原因，物流时间比事先预期的可能会更长，我们深感抱歉。谢谢你的选购！
亲，您的订单（2021AEDG）已经发货，预计在三天内会到达，因天气原因导致物流时间可能比平时长，还请您耐心等待。非常感谢你选购我们的商品。如果你有其他问题欢迎随时联系我们，感谢支持！
亲，您好！感谢您对我们产品的信任，您的订单2021AEDG已发货，延误是因为天气原因，估计会在3天内送达，如果有什么疑问可以随时联系我们。再次感谢您的支持！
'''


import sys
sys.stdin = open('삼각 달팽이_input.txt')

'''
문제 설명
정수 n이 매개변수로 주어집니다.
 다음 그림과 같이 밑변의 길이와 높이가 n인 삼각형에서
 맨 위 꼭짓점부터 반시계 방향으로 달팽이 채우기를 진행한 후,
첫 행부터 마지막 행까지 모두 순서대로 합친 새로운 배열을 return 하도록 solution 함수를 완성해주세요.
n은 1 이상 1,000 이하입니다.
'''

t = int(input())
for case in range(t):
    n = int(input())
    answer = []
    g = [[0 for _ in range(n)] for _ in range(n)]
    print(n)
    x, y = 0, -1
    num = 1
    for i in range(n):
        for j in range(i, n):
            if i % 3 == 0:
                y += 1
            elif i % 3 == 1:
                x += 1
            elif i % 3 == 2:
                y -= 1
                x -= 1
            # print(num, y, x)
            g[y][x] = num
            num += 1
            # print(g)
    # for i in range(n):
    #     print(g[i])
    for i in range(n):
        for j in range(n):
            if g[i][j] != 0:
                answer.append(g[i][j])

    print(answer)

프로그래머스/삼각 달팽이.py


class Solution:
    def checkIfPangram(self, sentence: str) -> bool:
        if len(sentence) < 26:
            return False
        a=[0]*26
        for s in sentence:
            a[ord(s)-ord('a')]=1
            if sum(a)==26:
                return True
        return False


import csv
import uuid
from utils import connection_factory

def create_database():
    conn = connection_factory.create_initial_connection()
    conn.cursor().execute('CREATE DATABASE thesis')
    conn.commit()
    conn.close()
    print('Database created!')

def create_tables():
    conn = connection_factory.create_connection()
    cursor = conn.cursor()

    create_users_table = 'CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT, user_name VARCHAR(100) UNIQUE NOT NULL)'
    cursor.execute(create_users_table)
    conn.commit()

    create_measurement_table = 'CREATE TABLE measurements (id INT PRIMARY KEY AUTO_INCREMENT, external_id BINARY(16) ' \
                               'UNIQUE NOT NULL, user_id INT, FOREIGN KEY (user_id) REFERENCES users(id), is_training ' \
                               'BOOLEAN NOT NULL, H_period FLOAT, DD_period_t FLOAT, UD_period_t FLOAT, H_t FLOAT, ' \
                               'DD_t_i FLOAT, UD_t_i FLOAT, H_i FLOAT, DD_i_e FLOAT, UD_i_e FLOAT, H_e FLOAT, ' \
                               'DD_e_five FLOAT, UD_e_five FLOAT, H_five FLOAT, DD_five_Shift_r FLOAT, UD_five_Shift_r ' \
                               'FLOAT, H_Shift_r FLOAT, DD_Shift_r_o FLOAT, UD_Shift_r_o FLOAT, H_o FLOAT, DD_o_a FLOAT, ' \
                               'UD_o_a FLOAT, H_a FLOAT, DD_a_n FLOAT, UD_a_n FLOAT, H_n FLOAT, DD_n_l FLOAT, ' \
                               'UD_n_l FLOAT, H_l FLOAT) '

    cursor.execute(create_measurement_table)
    conn.commit()
    conn.close
    print('Tables created!')

def insert_user(cursor, conn, users_set):
    user_ids = {}
    for user_name in users_set:
        cursor.execute('INSERT INTO users (user_name) VALUES (%s)', (user_name,))
        user_ids[user_name] = cursor.lastrowid

    conn.commit()
    return user_ids

def populate_database():
    conn = connection_factory.create_connection()
    cursor = conn.cursor()

    with open('../resources/DSL-StrongPasswordData.csv', 'r') as file:
        reader = csv.DictReader(file)
        users = set()

        for i in reader:
            users.add(i['subject'])

        user_ids = insert_user(cursor, conn, users)

    with open('../resources/DSL-StrongPasswordData.csv', 'r') as file:
        reader = csv.DictReader(file)

        data = [(uuid.uuid4().hex, user_ids.get(i['subject']), True, i['H.period'], i['DD.period.t'], i['UD.period.t'],
                 i['H.t'], i['DD.t.i'], i['UD.t.i'], i['H.i'], i['DD.i.e'], i['UD.i.e'], i['H.e'], i['DD.e.five'],
                 i['UD.e.five'], i['H.five'], i['DD.five.Shift.r'], i['UD.five.Shift.r'], i['H.Shift.r'],
                 i['DD.Shift.r.o'],
                 i['UD.Shift.r.o'], i['H.o'], i['DD.o.a'], i['UD.o.a'], i['H.a'], i['DD.a.n'], i['UD.a.n'], i['H.n'],
                 i['DD.n.l'], i['UD.n.l'], i['H.l']) for i in reader]

        insert_data_query = 'INSERT INTO measurements (external_id, user_id, is_training, H_period, DD_period_t, ' \
                            'UD_period_t, H_t, DD_t_i, UD_t_i, H_i, DD_i_e, UD_i_e, H_e, DD_e_five, UD_e_five, H_five, ' \
                            'DD_five_Shift_r, UD_five_Shift_r, H_Shift_r, DD_Shift_r_o, UD_Shift_r_o, H_o, DD_o_a, ' \
                            'UD_o_a, H_a, DD_a_n, UD_a_n, H_n, DD_n_l, UD_n_l, H_l) VALUES (UUID_TO_BIN(%s), %s, %s, %s, ' \
                            '%s ,%s, %s, %s, %s ,%s, %s, %s, %s ,%s, %s, %s, %s ,%s, %s, %s, %s ,%s, %s, %s, %s ,%s, %s, ' \
                            '%s, %s, %s, %s) '

        cursor.executemany(insert_data_query, data)
        conn.commit()
        conn.close()

        print('Populated tables in thesis database: users, measurements!')

def init():
    create_database()
    create_tables()
    populate_database()


#### SCORER ###
from operator import index
from typing import List, Tuple, Dict

import pandas as pd
import numpy as np

from sklearn.metrics import roc_auc_score, r2_score

def scorer_(data: pd.DataFrame, model, splitter: float) -> tuple:
    """Fits a given model to a given dataset and
    returns the score on both training and testing as a tuple."""

    # Find the row to split dataset in training and testing set
    split = int(data.shape[0] * splitter)

    # Sclice the dataframe accordingly
    features_train = data.iloc[1:split,:-1]
    labels_train = data.iloc[1:split,-1]

    features_test = data.iloc[split:,:-1]
    labels_test = data.iloc[split:,-1]

    # Fit the model onto training data
    model.fit(features_train, labels_train)

    # Compute score for both training and testing
    training_score = model.score(features_train, labels_train)
    test_score = model.score(features_test, labels_test)

    return (training_score, test_score)

def evaluate_model(model, subtask, X_train, y_train, X_val, y_val) -> Dict[str, Tuple]:
    """Evaluates performance of a model wrt a specific label column"""

    model.fit(X_train, y_train)

    if subtask == 1 or subtask == 2:
        scorer = roc_auc_score

        # Get index corresponding to class 1
        index = list(model.classes_).index(1.0)
        y_pred = model.predict_proba(X_train)[:, index]
        y_val_pred = model.predict_proba(X_val)[:, index]

    elif subtask == 3:
        scorer = r2_score

        y_pred = model.predict(X_train)
        y_val_pred = model.predict(X_val)

    training_score = scorer(y_train, y_pred)
    val_score = scorer(y_val, y_val_pred)

    return model, (training_score, val_score)

def scoreboard(models: list, subtask: int, X_train, y_trains: List[pd.Series], X_val, y_vals: List[pd.Series]) -> dict:
    """Takes a list of several models and runs them on the same dataset.
    Trains each model wrt to each label column in the list of label columns.
    Training and Test scores are written to a dictionaru per model for each label column."""

    # Initializing output dict
    scores = dict()
    scores_model = dict()
    best_score = {y_train.name: 0 for y_train in y_trains}
    progress = dict()

    # Train each model on each label column
    for model_class, kwargs in models:
        model = model_class(**kwargs)

        model_name = type(model).__name__
        print(f"Evaluating {model_name}...")

        scores_model = dict()
        for y_train, y_val in zip(y_trains, y_vals):

            label = y_train.name
            prev_best_score = best_score[label]

            model_trained, score = evaluate_model(model, subtask, X_train, y_train, X_val, y_val)
            scores_model[label] = (model_trained, score)

            # Printing progress
            val_score = score[1]
            if val_score > prev_best_score:
                print(f"[Progress] Best validation score on column {label}:")
                print(f"    {model_name}: {val_score:.4f}")

                best_score[label] = val_score

                if "DummyClassifier" in list(scores.keys()):
                    val_score_dummy = scores["DummyClassifier"][label][1][1]
                    print(f"    DummyClassifier: {val_score_dummy:.4f}\n")
                    print(f"    Total progress: {val_score - val_score_dummy:.4f}\n")

                    progress[label] = val_score - val_score_dummy

        scores[model_name] = scores_model.copy()

    print(f"Total progress: {progress}")
    return scores


#!/usr/bin/env python3
from collections import deque

def main():
    M = int(input())

    G = [[] for _ in range(9)]
    for _ in range(M):
        U, V = map(int, input().split())
        U -= 1
        V -= 1
        G[U].append(V)
        G[V].append(U)

    P = list(map(lambda x: int(x) - 1, input().split()))
    aki = list(set(i for i in range(9)) - set(P))[0]
    P = tuple(P + [aki])

    memo = {P: 0}
    que = deque([P])
    while que:
        x = que.popleft()
        for koma in range(9):
            if x[koma] in G[x[8]]:
                x2 = list(x)
                x2[koma], x2[8] = x2[8], x2[koma]
                x2 = tuple(x2)

                if x2 not in memo:
                    memo[x2] = memo[x] + 1
                    que.append(x2)

    goal = tuple(i for i in range(9))
    print(memo[goal] if goal in memo else -1)

main()