class Solution1(object):
    def permute(self, l):
        return self._permute(l,len(l))

    def _permute(self, l, n):
        if n ==  0:
            return [[]]
        if n == 1:
            return [l[:n]]
        retL = []
        for subL in self._permute(l, n - 1):
            retL.append(subL + [l[n-1]])
            retL.append([l[n-1]] + subL)
            for i in xrange(1, n - 1):
                tmpL = subL[:i] + [l[n-1]] + subL[i:]
                retL.append(tmpL)
        return retL

class Solution(object):
    def permute(self, l):
        if len(l) == 0:
            return [[]]
        permuations = []
        curr = []
        isVisited = [False] * len(l)
        self.backTracking(permuations, curr, isVisited, l)
        return permuations

    def backTracking(self, permuations,  curr, isVisited, l):
        if len(curr) == len(l):
            permuations.append(curr[:])
            return

        for i in range(len(l)):
            if not isVisited[i]:
                isVisited[i] = True
                curr.append(l[i])
                self.backTracking(permuations, curr, isVisited, l)
                isVisited[i] = False
                curr.pop()


from __future__ import absolute_import
from Qshop.celery import app

@app.task #将普通的函数转换为celery任务
def taskExample():
    print("I am task Example")
    return "I am task Example"

@app.task #将普通的函数转换为celery任务
def add(x,y):
    return x+y

import json
import requests
from Qshop.settings import DING_URL
@app.task
def sendDing(content="hello world",to=None):
    headers = {
        "Content-Type": "application/json",
        "Charset": "utf-8"
    }
    requests_data = {
        "msgtype": "text",
        "text": {
            "content": content
        },
        "at": {
            "atMobiles": [
            ],
            "isAtAll": True
        }
    }
    if to:
        requests_data["at"]["atMobiles"].append(to)
        requests_data["at"]["isAtAll"] = False
    else:
        requests_data["at"]["atMobiles"].clear()
        requests_data["at"]["isAtAll"] = True
    sendData = json.dumps(requests_data)
    response = requests.post(url=DING_URL, headers=headers, data=sendData)
    content = response.json()
    return content


#!/usr/bin/env python3

"""Defines an easy function to set up a logger. """

import logging
import os

try:
    import colorlog
except ImportError:
    colorlog = None

CLUSTERKING_LOGLEVEL_ENV = "CLUSTERKING_LOG_LEVEL"

def get_logger(name="Logger", level=logging.WARNING, sh_level=logging.WARNING):
    """Sets up a logging.Logger.

    If the colorlog module is available, the logger will use colors,
    otherwise it will be in b/w. The colorlog module is available at
    https://github.com/borntyping/python-colorlog but can also easily be
    installed with e.g. 'sudo pip3 colorlog' or similar commands.

    Args:
        name: name of the logger
        level: General logging level
        sh_level: Logging level of stream handler

    Returns:
        Logger
    """
    if colorlog:
        _logger = colorlog.getLogger(name)
    else:
        _logger = logging.getLogger(name)

    if _logger.handlers:
        # the logger already has handlers attached to it, even though
        # we didn't add it ==> logging.get_logger got us an existing
        # logger ==> we don't need to do anything
        return _logger

    _logger.setLevel(level)
    if os.environ.get(CLUSTERKING_LOGLEVEL_ENV, False):
        _logger.setLevel(int(os.environ.get(CLUSTERKING_LOGLEVEL_ENV)))
    if colorlog is not None:
        sh = colorlog.StreamHandler()
        log_colors = {
            "DEBUG": "cyan",
            "INFO": "green",
            "WARNING": "yellow",
            "ERROR": "red",
            "CRITICAL": "red",
        }
        formatter = colorlog.ColoredFormatter(
            "%(log_color)s%(name)s:%(levelname)s:%(message)s",
            log_colors=log_colors,
        )
    else:
        # no colorlog available:
        sh = logging.StreamHandler()
        formatter = logging.Formatter("%(name)s:%(levelname)s:%(message)s")
    sh.setFormatter(formatter)
    sh.setLevel(sh_level)
    _logger.addHandler(sh)

    if colorlog is None:
        _logger.debug("Module colorlog not available. Log will be b/w.")

    return _logger

def set_global_log_level(level=logging.INFO):
    names = list(logging.root.manager.loggerDict.keys())
    names.append("DFMD")
    loggers = [logging.getLogger(name) for name in names]
    for logger in loggers:
        logger.setLevel(level)
    os.environ[CLUSTERKING_LOGLEVEL_ENV] = str(logging.WARNING)

if __name__ == "__main__":
    # Test the color scheme for the logger.
    lg = get_logger("test")
    lg.debug("Test debug message")
    lg.info("Test info message")
    lg.warning("Test warning message")
    lg.error("Test error message")
    lg.critical("Test critical message")


class Solution:
    def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
        N, M = len(robot), len(factory)
        INF = 10 ** 20
        robot.sort()
        factory.sort()

        @cache
        def go(i, j, k):
            if i == N: return 0

            res = INF

            if k > 0:
                res = min(res, go(i + 1, j, k - 1) + abs(factory[j][0] - robot[i]))

            if j + 1 < M:
                res = min(res, go(i, j + 1, factory[j + 1][1]))

            return res

        return go(0, 0, factory[0][1])


import os

#Convert seconds to minutes
def mins(length):
    minutes = int(length/60)
    seconds = str(length-minutes*60)
    if len(seconds)==1:
        seconds="0"+seconds
    return f"{minutes}:{seconds}"

def strip_path(song):
    song_name = os.path.basename(song)# path > filenames
    song_name_no_extension = ".".join(song_name.split(".")[:-1])
    return [song_name, song_name_no_extension]#delete the extension, better use regex or sth


"""
    To interact with web sites
    from Python and to get more
    experience with regular expressions

by: @eltonaloys
"""
import urllib.request  #importing URL and REGEX package libraries
from re import findall

def urlcount(r):
    httpurl = [] #Taking All the Values in a List

    try:
        req = urllib.request.urlopen(r).read() #Requesting for opening url
    except ValueError:
        raise ValueError("URL is Invalid")
    else:
        urls = findall(b'"(http[s]?://.*?)"', req) #Using regex to find "http/https"
    for items in urls:
        httpurl.append(items)
    allhttps = set(httpurl) #Taking Unique Values in a set
    counthttps = len(allhttps)
    return f"The count of distinct http/https is: {counthttps}" #Printing count of distinct values

def main():
    r = input("Enter URL(Eg: https://www.youtube.com) \n")
    print(urlcount(r))

main()


from Student.Student import Student
from Teacher.Teacher import Teacher
from util.ClearScreen import screen_clear
# Home Function
def Home():
     while True:
        screen_clear()
        print("---------------------------------------------")
        print("Welcome to our Tiny School Management System")
        print("---------------------------------------------")
        print("1) Teacher\n2) Student\n3) Exit\n")
        try:
            x = int(input("Please Enter a number: "))
            if x == 1:
                print("You are a Teacher")
                Teacher()
            elif x == 2:
                print("You are student")
                Student()
            elif x == 3:
                return
        except ValueError:
            print("Oops! That was no valid number. Try again...")


"""
August 5 2014

Short script to merge fragmented Tycho tables
meant for one time use (operated on pieces now stored in separate folder)
"""

import cPickle as pickle
import glob

fnames = glob.glob('Tycho_gen_2014-07-30_grid_6-100-20_vs-*.pkl')

f_orig = [f for f in fnames if 'part2' not in f]
f_pt2_1 = [f for f in fnames if 'mu-1.50' in f]
f_pt2_2 = [f for f in fnames if 'mu-2.00' in f]

f_orig.sort()
f_pt2_1.sort()
f_pt2_2.sort()

def pkldict(f):
    with open(f, 'r') as fpkl:
        d = pickle.load(fpkl)
    return d

# pt2_1 refers to mu=1.50, with subset of eta2 values
# pt2_2 refers to mu=2.00, with all eta2 values

for orig, pt2_1, pt2_2 in zip(f_orig, f_pt2_1, f_pt2_2):

    main_dict = pkldict(orig)
    main_dict[1.5].update( pkldict(pt2_1)[1.5] )
    main_dict.update( pkldict(pt2_2) )

    with open(orig + 'all', 'w') as fpkl:
        pickle.dump(main_dict, fpkl)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        level = [root]
        ret = []
        flag = True
        while len(level):
            level.reverse()
            ret.append([node.val for node in level])
            if flag:
                level= [child for node in level for child in (node.left, node.right) if child]
            else:
                level = [child for node in level for child in (node.right, node.left) if child]
            flag = not flag
        return ret


#!/usr/bin/env python3

def combine_phased_rotations(a_period, a_phase, b_period, b_phase):
    """Combine two phased rotations into a single phased rotation

    Returns: combined_period, combined_phase

    The combined rotation is at its reference point if and only if both a and b
    are at their reference points.
    """
    print("INPUTS", a_period, a_phase, b_period, b_phase)
    gcd, s, t = extended_gcd(a_period, b_period)
    print("GCD RESULT", gcd, s, t)
    phase_difference = a_phase - b_phase
    print("PD", phase_difference)
    pd_mult, pd_remainder = divmod(phase_difference, gcd)
    print("M, R", pd_mult, pd_remainder)
    if pd_remainder:
        raise ValueError("Rotation reference points never synchronize.")

    combined_period = a_period // gcd * b_period
    print("COMBINED_PERIOD", combined_period)
    combined_phase = (a_phase - s * pd_mult * a_period) % combined_period
    print("COMBINED_PHASE", combined_phase)
    return combined_period, combined_phase

def arrow_alignment(red_len, green_len, advantage):
    """Where the arrows first align, where green starts shifted by advantage"""
    period, phase = combine_phased_rotations(
        red_len, 0, green_len, -advantage % green_len
    )
    return -phase % period

def extended_gcd(a, b):
    """Extended Greatest Common Divisor Algorithm

    Returns:
        gcd: The greatest common divisor of a and b.
        s, t: Coefficients such that s*a + t*b = gcd

    Reference:
        https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode
    """
    old_r, r = a, b
    old_s, s = 1, 0
    old_t, t = 0, 1
    while r:
        quotient, remainder = divmod(old_r, r)
        old_r, r = r, remainder
        old_s, s = s, old_s - quotient * s
        old_t, t = t, old_t - quotient * t

    return old_r, old_s, old_t

#print(arrow_alignment(red_len=7, green_len=13, advantage=1))  # 18
#print(arrow_alignment(red_len=7, green_len=19, advantage=7))  # 18
#pd, ph = combine_phased_rotations(97, 77, 133, 126)
#print(pd, ph, -ph % pd)

pd1, ph1 = combine_phased_rotations(17, 0, 13, -2 % 13)
pd2, ph2 = combine_phased_rotations(17, 0, 19, -3 % 19)
pd, ph = combine_phased_rotations(pd1, ph1, pd2, ph2)
print(pd, ph)

pd1 = 1789
ph1 = 0
for o, p in enumerate((37, 47, 1889)):
    o = o + 1
    pd2 = p
    ph2 = -o % pd2
    pd1, ph1 = combine_phased_rotations(pd1, ph1, pd2, ph2)

import sys
sys.exit(0)
print(arrow_alignment(red_len=17, green_len=13, advantage=2))  # 18
print(arrow_alignment(red_len=17, green_len=19, advantage=3))  # 18
pd, ph = combine_phased_rotations(221, 102, 323, 187)
print(pd, ph, -ph % pd)


import os

import numpy as np
from PIL import Image, ImageDraw, ImageFilter
from scipy.spatial import Delaunay

from polinom import secant, bisect, bisect_numpy

class ImgWorker:
    def __init__(self, img_name, angle=1500):
        self.img_name = img_name
        self.img = Image.open(img_name)
        self.img = self.img.filter(ImageFilter.GaussianBlur(radius=1))
        self.angle = angle
        self.cnt = 0
        if self.img.mode != 'RGB':
            self.img = self.img.convert('RGB')

        self.img = self.img.convert('L')
        self.P = np.array(self.img)

        self.K = np.array([
            [-1 / 16, 1 / 8, 1 / 4, -1 / 2],
            [9 / 16, -11 / 8, -1 / 4, 3 / 2],
            [9 / 16, 11 / 8, -1 / 4, -3 / 2],
            [-1 / 16, -1 / 8, 1 / 4, 1 / 2]
        ])
        self.K_t = self.K.transpose()

        self.B = {}
        self.C = {}
        self.h = {}
        self.l_max_f = {}

        self.zero = 0
        self.coord = []

    def save_grey_scale(self, name):
        self.img.save(name)

    def create_B_matrix(self):
        for i in range(len(self.P) - 3):
            for j in range(len(self.P[0]) - 3):
                p = self.P[i:i + 4, j:j + 4]
                self.B[i, j] = np.matmul(np.matmul(self.K_t, p), self.K)

    def work_with_b(self):

        def h_kink(l, h):
            ans = 0
            h_2 = [koef * my_h for koef, my_h in zip([2, 6, 12, 20, 30], h[2:])]
            for i, val in enumerate(h_2):
                ans += l ** i * val
            return ans

        for q, val in self.B.items():
            g_x = val[0][1]
            g_y = val[1][0]

            if g_x == 0 and g_y == 0:
                continue

            c = np.zeros(shape=(4, 4))

            pow_g_x = {i: g_x ** i for i in range(4)}
            pow_g_y = {i: g_y ** i for i in range(4)}

            for i in range(4):
                for j in range(4):
                    c[i][j] = pow_g_y[i] * pow_g_x[j] * val[i][j]

            self.C[q[0], q[1]] = c

            h = [c[0][0], c[1][0] + c[0][1], c[2][0] + c[1][1] + c[0][2], c[3][0] + c[2][1] + c[1][2] + c[0][3],
                 c[3][1] + c[2][2] + c[1][3], c[3][2] + c[2][3], c[3][3]]

            self.h[q[0], q[1]] = h

            if g_y == 0:
                l_max = 0.5 / g_x
            elif g_x == 0:
                l_max = 0.5 / g_y
            else:
                l_max = 0.5 / max(g_y, g_x)

            self.l_max_f[q[0], q[1]] = l_max

            def f(x_):
                return 2 * h[2] + x_ * (6 * h[3] + x_ * (12 * h[4] + x_ * (20 * h[5] + x_ * 30 * h[6])))

            def h_first_(x_):
                res = h[1] + 2 * h[2] * x_ + 3 * h[3] * (x_ ** 2) + 4 * h[4] * (x_ ** 3) + 5 * h[5] * (x_ ** 4) + 6 * h[
                    6] * (x_ ** 5)
                return res

            a, b = f(l_max), f(-l_max)

            # if a * b < 0:
            if (a > 0 and b < 0) or (a < 0 and b > 0):
                self.zero += 1
                # x = secant(f, -10000)
                # x = bisect(f, -l_max, l_max)

                # if abs(f(x)) <= 0.00000009 and l_max > x > -l_max:
                #     print(f(x))
                #     self.coord.append(q)
                roots = list(np.roots([30 * h[6], 20 * h[5], 12 * h[4], 6 * h[3], 2 * h[2]]))
                h_first_max, dot_ = -1, 0
                for root in roots:
                    if type(root) is type(np.complex128()):
                        continue
                    if -l_max < root < l_max:
                        h_first = h_first_(root)
                        if abs(h_first) > h_first_max:
                            h_first_max = abs(h_first)
                            dot_ = root

                # if h_first_max != -1 and h_first_max >= self.angle:
                #     self.coord.append(q)
                self.coord.append((h_first_max, q))

        # print(self.zero)
        # for i in self.coord:
        #     print(i)

    def test(self):
        img2 = self.img
        img2 = img2.convert('RGB')
        for angle, i in self.coord:
            if angle >= self.angle:
                rgb = (255, 0, 0)
                img2.putpixel((i[1] + 1, i[0] + 1), rgb)
                img2.putpixel((i[1] + 2, i[0] + 1), rgb)
                img2.putpixel((i[1] + 1, i[0] + 2), rgb)
                img2.putpixel((i[1] + 2, i[0] + 2), rgb)

        file_name = '{}_response.png'.format(self.img_name.split('/')[-1].split('.')[0])
        img2.save('static/img/{}'.format(file_name))

        return file_name

    def set_triangulation(self):
        points = np.array(self.coord)
        tri = Delaunay(points)
        img1 = ImageDraw.Draw(self.img)
        print(self.angle)
        for i in tri.simplices:
            x, y, z = points[i[0]], points[i[1]], points[i[2]]
            l = [(tuple(a[::-1]), tuple(b[::-1])) for a, b in [(x, y), (x, z), (y, z)]]
            for line in l:
                img1.line(line, fill="red", width=0)

        self.img.show()


'''
Author: Focsaneanu Andrei-Ciprian
June 2018

'''
import keras
from keras import backend as K
from keras.applications.inception_v3 import InceptionV3
from keras.applications.resnet50 import ResNet50
from keras.applications.densenet import DenseNet121
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping
from keras.layers import Dense, GlobalAveragePooling2D, Flatten, concatenate, Input
from keras.models import Model, model_from_json, load_model
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import SGD

import argparse
import numpy as np
import tensorflow as tf
import sys
from time import time
from sklearn.metrics import confusion_matrix

def train_model(context_model_file, data_directory, training_epochs, **args):

    print ('Training for ' + str(training_epochs))

    ## Prepare training data
    img_height = 224
    img_width = 224
    batch_size = 16

    if K.image_data_format() == 'channels_first':
      input_shape = (3, img_width, img_height)
    else:
      input_shape = (img_width, img_height, 3)

    # Directories used
    train_data_dir = data_directory + '\\train'
    validation_data_dir = data_directory + '\\validation'
    test_data_dir = data_directory + '\\test'

    # Prepare data generators
    train_datagen = ImageDataGenerator(rescale = 1./255,
            shear_range = 0.2,
            zoom_range = 0.2,
            horizontal_flip = True)
    train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size = (img_width, img_height),
        batch_size = batch_size,
        shuffle = True)
    validation_datagen = ImageDataGenerator(rescale = 1./255)
    validation_generator = validation_datagen.flow_from_directory(
        validation_data_dir,
        target_size = (img_width, img_height),
        batch_size = batch_size)
    classes = len(train_generator.class_indices)

    ## Give same input to both models
    model_input = Input(shape = input_shape)

    ## Load context recognition model pre-trained on 27 categories of Places205
    loaded_context_model = load_model(context_model_file)

    # Construct new context CNN model with pre-trained weights loaded but connected to input tensor
    context_cnn = DenseNet121(weights = None, include_top = False, input_tensor = model_input)
    x = GlobalAveragePooling2D()(context_cnn.output)
    x = Dense(1024, activation = 'relu')(x)
    context_predictions = Dense(27, activation = 'softmax')(x)
    context_model = Model(inputs = model_input, outputs = context_predictions)
    for new_layer, layer in zip(context_model.layers[1:], loaded_context_model.layers[1:]):
        new_layer.set_weights(layer.get_weights())

    ## Load object recognition model pre-trained on ImageNet
    object_model = ResNet50(include_top=True, weights='imagenet', input_tensor = model_input, pooling=None, classes=1000)
    # Hack to avoid https://github.com/keras-team/keras/issues/3974
    for i in range(1,len(object_model.layers)):
        object_model.layers[i].name = object_model.layers[i].name + '1'

    ## Merge/concatenate outputs of the two sub-models
    context_output = context_model.output
    object_output = object_model.output
    y = concatenate([context_output, object_output])

    ## Add extra layer(s) for classification of activities
    y = Dense(1024, activation = 'relu')(y)
    predictions = Dense(classes, activation = 'softmax')(y)

    ## Set C-CNN to be not trainable
    for layer in context_model.layers:
        layer.trainable = False

    ## Compile model
    model = Model(inputs = model_input, outputs = predictions)
    model.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])
    model.summary()

    prefix = 'oc-cnn'
    ## Define callbacks
    tensorboard = TensorBoard(log_dir='logs/' + prefix + "-{}".format(time()))
    es = EarlyStopping(monitor = 'val_loss', min_delta = 0, patience = 3, verbose = 0, mode = 'auto')

    ## Train model
    model.fit_generator(
        train_generator,
        epochs = training_epochs,
        validation_data = validation_generator,
        callbacks = [tensorboard, es])

    # Generate confusion matrix
    print ('Generating confusion matrix..')
    test_datagen = ImageDataGenerator(rescale = 1./255)
    test_generator = test_datagen.flow_from_directory(
        test_data_dir,
        target_size = (img_width, img_height),
        batch_size = 1,
        shuffle = False)
    test_elements = test_generator.__len__()
    probabilities = model.predict_generator(test_generator, test_elements)
    y_pred = np.argmax(probabilities, axis = 1)
    y_true = np.array([], dtype = int)
    y_true = test_generator.classes
    mat = np.matrix(confusion_matrix(y_true, y_pred))
    confusion_file = 'confusion-' + prefix + '-{}'.format(time()) + '.txt';
    with open(confusion_file,'wb') as f:
        for line in mat:
            np.savetxt(f, line, fmt='%d')
    print ('Wrote confusion matrix to ' + confusion_file)

    ## Save model # Save model weights
    model_filename = 'activity-recognition-model.h5'
    model.save(model_filename)
    print ('Saved model to :' + model_filename)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument(
      '--data_directory',
      help='Local path to training data',
      required=True)

    parser.add_argument(
      '--context_model_file',
      help='Filename of context recognition model',
      required=True)

    parser.add_argument(
      '--training_epochs',
      help='Number of epochs for training only the extra layers',
      type=int,
      default=20)

    args = parser.parse_args()
    arguments = args.__dict__

    train_model(**arguments)


T = int(input())
for tc in range(T):
    words = input()
    stack = [] # 스택 리스트
    # 문자열 회전
    for word in words:
        # 스택에 아무것도 없으면 추가
        if not stack:
            stack.append(word)
        # 스택에 마지막 부분이 현재 알파벳이랑 같으면 스택 마지막부분 제거
        elif word == stack[-1]:
            stack.pop()
        # 그게 아닐경우 스택에 단어를 추가해준다.
        else:
            stack.append(word)

    print("#{} {}".format(tc+1, len(stack)))


import ui
import check
import mod

def button_click():
    '''
    Функция запускает программу.
    '''
    ui.hello()
    deistvie = check.check_action()
    if deistvie == 1:
        mod.search_number(ui.input_search())
    elif deistvie == 2:
        data = ui.input_data()
        mod.write_number(data[0], data[1], data[2])


import math

def is_prime(n):
    if n < 0:
        raise ValueError("Input must be a positive integer")
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            return False
    return True


import os
from google.cloud import speech
import io
import streamlit as st
import pandas as pd
from word import Word
from janome.tokenizer import Tokenizer
from language import Language

def main():
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'config/secret.json'

    # ファイルを読み込んでテキスト化する
    def transcribe_file(content, lang = Language.ENG.value[1]) -> str:
        client = speech.SpeechClient()
        audio = speech.RecognitionAudio(content = content)
        config = speech.RecognitionConfig(
            encoding = speech.RecognitionConfig.AudioEncoding.ENCODING_UNSPECIFIED,
            language_code = lang,
        )
        response = client.recognize(config = config, audio = audio)

        for result in response.results:
            return result.alternatives[0].transcript

    # 音声認識したテキストから単語リストを生成
    def generate_word_list(lang) -> list[str]:
        text = st.session_state.result

        if lang == Language.JP.value[0]:
            text = morphological_analyze(text)
        elif lang == Language.ENG.value[0]:
            text = text.split(' ')
        else:
            pass

        words = []
        for index, word in enumerate(text):
            words.append(Word(index = index, name = word))
        return words

    # 入力値をもとに単語を検索をする
    def search(input_words: list[str]) -> list[Word]:
        words = generate_word_list(st.session_state.lang)

        result = []
        for target in input_words:
            for w in words:
                if(w.name == target):
                    result.append(w)
        return result

    # 入力された検索文字列毎に前後5単語を抽出して二次元配列を作成
    def extract_words(matched_words) -> list[list[Word]]:
        lumps = []
        word_list = generate_word_list(st.session_state.lang)

        for word in matched_words:
            if len(word_list) < 11:
                lumps.append(word_list)
            elif word.index < 5:
                lumps.append(word_list[:word.index+6])
            else: lumps.append(word_list[word.index-5:word.index+6])
        return lumps

    # 入力された文字列の前後5文字を抽出
    def extract_chars(input_words, text, lang) -> list[tuple]:
        input_words = [st for st in input_words if st != '']
        if lang == Language.ENG.value[0]:
            text = ''.join(text.split(' '))

        for word in input_words:
            list = []
            target = word
            n = 0
            for i in range(0, len(text)):
                index = text.find(target, n)
                n = index + len(target)
                if index == -1:
                    break
                if index < 5:
                    list.append((index, target, text[:index+len(target)+5]))
                else:
                    list.append((index, target, text[index-5:index+len(target)+5]))
        return list

    # 画面表示用のテーブルを作成する
    def create_table(lumps):
        df = pd.DataFrame(data = map(lambda l: map(lambda w: w.name, l), lumps))
        df.index = df.index + 1
        df.columns = df.columns + 1
        st.table(df)

    # 検索文字列をハイライト
    def highlight_col(df):
        copied_df = df.copy()
        copied_df.loc[:,:] = None
        copied_df[[5]] = 'background-color: #F7A8D4'
        return copied_df

    # 形態素解析で日本語を分割
    def morphological_analyze(text) -> list[str]:
        t = Tokenizer()
        return t.tokenize(text, wakati=True)

    # Streamlitへの書き出し
    st.title('Transcription App')
    st.header('Overview')
    st.write('This is a transcription application that uses Google Cloud Speech-to-Text. The link is below.')
    st.markdown('Cloud Speech-to-Text', unsafe_allow_html = True)

    # APIコール結果をセッションで保持する
    if 'result' not in st.session_state:
        st.session_state['result'] = None

    # 選択言語をセッションで保持する
    if 'lang' not in st.session_state:
        st.session_state['lang'] = None

    # ファイルアップロード
    upload_file = st.file_uploader('Upload File', type = ['mp3', 'wav'])

    # ファイル切り替える際にセッションを破棄する
    if upload_file is None:
        st.session_state.result = None
        st.session_state.word_1 = ''
        st.session_state.word_2 = ''
        st.session_state.word_3 = ''
        st.session_state.lang = None

    if upload_file is not None:
        content = upload_file.read()
        st.subheader('File Details')
        file_details = {
            'FileName': upload_file.name,
            'FileType': upload_file.type,
            'FileSize': upload_file.size
        }
        st.write(file_details)
        st.subheader('Audio Playback')
        st.audio(content)

        st.subheader('Chose Language')
        option = st.selectbox('Select a language for translation', (Language.ENG.value[0], Language.JP.value[0]))
        st.session_state.lang = option

        st.subheader('Transcription')
        if st.button('Start'):
            comment = st.empty()
            comment.write('Analyzing..')
            st.session_state.result = transcribe_file(content, lang = Language.get_code(option))
            # 文字起こし後のダミーデータ
            # st.session_state.result = "Erin how can I help you today I see you signed up for a course online and I just cannot access that I've been trying the last 4 hours download display doesn't do anything"
            # st.session_state.result = 'ご住所の変更でございますねご連絡ありがとうございます恐れ入りますがご契約内容を確認いたしますのでお電話を頂いてる方は契約者ご本人様でいらっしゃいますかはいそうです本人ですそれではお電話をいただいておりますお客様のお名前をお願い致します山田太郎です'
            comment.write('')
        if st.session_state.result is not None:
            st.write(st.session_state.result)

        if st.session_state.result:
            st.title('Search Words')
            input_words = []
            with st.form(key = 'search'):
                st.caption('Type words for searching')
                col1, col2, col3 = st.columns([2,2,2])

                with col1:
                    word1 = st.text_input(label = '1', key = 'word_1')
                    input_words.append(word1)
                with col2:
                    word2 = st.text_input(label = '2', key = 'word_2')
                    input_words.append(word2)
                with col3:
                    word3 = st.text_input(label = '3', key = 'word_3')
                    input_words.append(word3)
                    st.form_submit_button(label = "Search")

            matched_words = search(input_words)
            lumps = extract_words(matched_words)

            text = st.session_state.result
            lang = st.session_state.lang

            if input_words[0] is not '' or input_words[1] is not '' or input_words[2] is not '':
                st.subheader('Results')
                st.subheader('Char Classification')
                chars = extract_chars(input_words, text, lang)
                for char in chars:
                    st.write(f'Position={char[0]+1}, Word={char[1]}, Chars={char[2]}')

            if len(lumps) is not 0:
                st.subheader('Word Classification')
                for w in matched_words:
                    st.write(f'Position={w.index + 1}, Word={w.name}')
                st.subheader('5 Words before/after the search word')
                create_table(lumps)

if __name__ == "__main__":
    main()


from math import cos, sin, pi
import pygame
import pygame.gfxdraw

def poly_gen(v_count, **kwargs):
    offset = kwargs.get('offset', 0)
    offset_x = kwargs.get('offset_x', offset)
    offset_y = kwargs.get('offset_y', offset)
    radius = kwargs.get('radius', 100)
    rotation = kwargs.get('rotation', 100)
    return [((radius * cos((2 * pi * i / v_count) + rotation)) + offset_x,
             (radius * sin((2 * pi * i / v_count) + rotation)) + offset_y)
            for i in range(v_count)]

def axial_to_linear(q, r):
    if r == -2:
        return q
    if r == -1:
        return 4 + q
    if r == 0:
        return 9 + q
    if r == 1:
        return 14 + q
    if r == 2:
        return 18 + q

class Render:
    def __init__(self):
        pygame.init()
        self.roll_font = pygame.font.Font('freesansbold.ttf', 36)
        self.bank_font = pygame.font.Font('freesansbold.ttf', 18)

        # Set up the drawing window
        self.screen = pygame.display.set_mode([1400, 900])

    def render(self, gamestate):
        buttons = {}

        def draw_rounded_rect(surface, rect, color, corner_radius):
            """ Draw a rectangle with rounded corners.
            Would prefer this:
                pygame.draw.rect(surface, color, rect, border_radius=corner_radius)
            but this option is not yet supported in my version of pygame so do it ourselves.

            We use anti-aliased circles to make the corners smoother

            yoinked of of stack overflow
            """
            if rect.width < 2 * corner_radius or rect.height < 2 * corner_radius:
                raise ValueError(
                    f"Both height (rect.height) and width (rect.width) must be > 2 * corner radius ({corner_radius})")

            # need to use anti aliasing circle drawing routines to smooth the corners
            pygame.gfxdraw.aacircle(surface, rect.left + corner_radius, rect.top + corner_radius, corner_radius, color)
            pygame.gfxdraw.aacircle(surface, rect.right - corner_radius - 1, rect.top + corner_radius, corner_radius,
                                    color)
            pygame.gfxdraw.aacircle(surface, rect.left + corner_radius, rect.bottom - corner_radius - 1, corner_radius,
                                    color)
            pygame.gfxdraw.aacircle(surface, rect.right - corner_radius - 1, rect.bottom - corner_radius - 1,
                                    corner_radius, color)

            pygame.gfxdraw.filled_circle(surface, rect.left + corner_radius, rect.top + corner_radius, corner_radius,
                                         color)
            pygame.gfxdraw.filled_circle(surface, rect.right - corner_radius - 1, rect.top + corner_radius,
                                         corner_radius, color)
            pygame.gfxdraw.filled_circle(surface, rect.left + corner_radius, rect.bottom - corner_radius - 1,
                                         corner_radius, color)
            pygame.gfxdraw.filled_circle(surface, rect.right - corner_radius - 1, rect.bottom - corner_radius - 1,
                                         corner_radius, color)

            rect_tmp = pygame.Rect(rect)

            rect_tmp.width -= 2 * corner_radius
            rect_tmp.center = rect.center
            pygame.draw.rect(surface, color, rect_tmp)

            rect_tmp.width = rect.width
            rect_tmp.height -= 2 * corner_radius
            rect_tmp.center = rect.center
            pygame.draw.rect(surface, color, rect_tmp)

        def click_handler(pos, player):
            # pixel to point
            # Check Points
            f = open("Points.txt", "r")
            points = [[int(i[0]), int(i[1])] for i in [x.split(",") for x in f.readlines()]]
            for index, l in enumerate(points):
                # Do x or y first?
                if pos[0] - 15 < l[0] < pos[0] + 15:
                    if pos[1] - 15 < l[1] < pos[1] + 15:
                        gamestate.board.build_settlement(gamestate, player, index)
            f.close()

            # Check Roads
            f = open("Roads.txt", "r")
            points = [[int(i[0]), int(i[1])] for i in [x.split(";")[0].split(",") for x in f.readlines()]]
            for index, l in enumerate(points):
                # Do x or y first?
                if pos[0] - 15 < l[0] < pos[0] + 15:
                    if pos[1] - 15 < l[1] < pos[1] + 15:
                        print("point:", index)
                        gamestate.board.build_road(gamestate, player, index)
            f.close()

            # check if a button within the dict was pressed
            for k in buttons.keys():
                if buttons[k].contains(pos[0] - 5, pos[1] - 5, 10, 10):
                    # Check which button
                    if k == "Next":
                        gamestate.next_turn()

        # Fill the background with white
        self.screen.fill((255, 255, 255))

        for index, cell in enumerate(gamestate.board.lands):
            # draw the land the land colour
            pygame.draw.polygon(self.screen, gamestate.board.lands[axial_to_linear(cell.q, cell.r)].colour_gen(),
                                poly_gen(6, rotation=(pi / 2), offset_x=cell.x(), offset_y=cell.y(), radius=cell.size))
            # draw the border to the land
            pygame.draw.polygon(self.screen, (100, 100, 100),
                                poly_gen(6, rotation=(pi / 2), offset_x=cell.x(), offset_y=cell.y(), radius=cell.size), width=5)

            # draw on the roll number
            text = self.roll_font.render(str(gamestate.board.lands[axial_to_linear(cell.q, cell.r)].roll), True, (0, 0, 0))
            textRect = text.get_rect()
            textRect.center = (cell.x(), cell.y())
            self.screen.blit(text, textRect)

        # draw on points
        for point in gamestate.board.points:
            radius = 15
            pygame.draw.circle(self.screen, gamestate.get_player_colour(point.settlement), (point.x, point.y), radius)

        for road in gamestate.board.roads:
            radius = 5
            pygame.draw.circle(self.screen, gamestate.get_player_colour(road.owner), (road.x, road.y), radius)

        # draw player banks
        for index, player in enumerate(gamestate.players):
            x = (index * 100) + 900
            y = 40

            text = "Player " + str(player.id) + ":"

            render_text = self.bank_font.render(text, True, (20, 20, 20))
            textRect = render_text.get_rect()
            textRect.center = (x, 20)
            self.screen.blit(render_text, textRect)

            for resource_type in player.resources.keys():
                text = resource_type + ": " + str(player.resources[resource_type])

                render_text = self.bank_font.render(text, True, (200, 150, 100))
                textRect = render_text.get_rect()
                textRect.center = (x, y)
                self.screen.blit(render_text, textRect)
                y += 15

        # draw a red box around the current player
        rect = ((gamestate.current_player * 100) + 850, 5, 100, 110)
        pygame.draw.rect(self.screen, (255, 0, 0), rect, 5, True)

        # draw next player button
        text = "Next Turn"

        render_text = self.roll_font.render(text, True, (20, 20, 20))
        textRect = render_text.get_rect()
        textRect.center = (900, 700)
        draw_rounded_rect(self.screen, textRect, (200, 200, 200), 5)
        buttons["Next"] = textRect

        self.screen.blit(render_text, textRect)

        # Did the user click the window close button?
        for e in pygame.event.get():
            if e.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                click_handler(pos, gamestate.current_player)

            if e.type == pygame.QUIT:
                return False

        pygame.display.update()
        return True


import streamlit as st
import pandas as pd

#
# ページのセッティング
#
st.set_page_config(
    page_title="Streamlit Examples",
    page_icon="🧊",
    layout="centered",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://www.extremelycoolapp.com/help',
        'Report a bug': "https://www.extremelycoolapp.com/bug",
        'About': "# This is a header. This is an *extremely* cool app!"
    }
)

def sidebar():
    pass

def mainview():
    st.markdown("# data display")

    #
    # json
    # https://docs.streamlit.io/library/api-reference/data/st.json
    #
    st.json({
        'foo': 'bar',
        'baz': 'boz',
        'stuff': [
            'stuff 1',
            'stuff 2',
            'stuff 3',
            'stuff 5',
        ],
    })

    #
    # dataframe
    # https://docs.streamlit.io/library/api-reference/data/st.dataframe
    #
    dataframe = pd.DataFrame({
        'first column': [1, 2, 3, 4],
        'second column': [10, 20, 30, 40],
    })
    st.experimental_show(dataframe)

    with st.form("my_form"):
        st.write("Inside the form")
        slider_val = st.slider("Form slider")
        checkbox_val = st.checkbox("Form checkbox")

        # Every form must have a submit button.
        submitted = st.form_submit_button("Submit")
        if submitted:
            st.write("slider", slider_val, "checkbox", checkbox_val)

if __name__ == "__main__":
    mainview()


import time

from acts import asserts
from acts import utils
from acts.test_decorators import test_tracker_info
from acts_contrib.test_utils.wifi import wifi_test_utils as wutils
from acts_contrib.test_utils.wifi.aware import aware_const as aconsts
from acts_contrib.test_utils.wifi.aware import aware_test_utils as autils
from acts_contrib.test_utils.wifi.aware.AwareBaseTest import AwareBaseTest

class AttachTest(AwareBaseTest):
    @test_tracker_info(uuid="cdafd1e0-bcf5-4fe8-ae32-f55483db9925")
    def test_attach(self):
        """Functional test case / Attach test cases / attach

    Validates that attaching to the Wi-Fi Aware service works (receive
    the expected callback).
    """
        dut = self.android_devices[0]
        dut.droid.wifiAwareAttach(False)
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACHED)
        autils.fail_on_event(dut, aconsts.EVENT_CB_ON_IDENTITY_CHANGED)

    @test_tracker_info(uuid="82f2a8bc-a62b-49c2-ac8a-fe8460010ba2")
    def test_attach_with_identity(self):
        """Functional test case / Attach test cases / attach with identity callback

    Validates that attaching to the Wi-Fi Aware service works (receive
    the expected callbacks).
    """
        dut = self.android_devices[0]
        dut.droid.wifiAwareAttach(True)
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACHED)
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_IDENTITY_CHANGED)

    @test_tracker_info(uuid="d2714d14-f330-47d4-b8e9-ee4d5e5b7ea0")
    def test_attach_multiple_sessions(self):
        """Functional test case / Attach test cases / multiple attach sessions

    Validates that when creating multiple attach sessions each can be
    configured independently as to whether or not to receive an identity
    callback.
    """
        dut = self.android_devices[0]

        # Create 3 attach sessions: 2 without identity callback, 1 with
        id1 = dut.droid.wifiAwareAttach(False, None, True)
        time.sleep(10)  # to make sure all calls and callbacks are done
        id2 = dut.droid.wifiAwareAttach(True, None, True)
        time.sleep(10)  # to make sure all calls and callbacks are done
        id3 = dut.droid.wifiAwareAttach(False, None, True)
        dut.log.info('id1=%d, id2=%d, id3=%d', id1, id2, id3)

        # Attach session 1: wait for attach, should not get identity
        autils.wait_for_event(
            dut, autils.decorate_event(aconsts.EVENT_CB_ON_ATTACHED, id1))
        autils.fail_on_event(
            dut,
            autils.decorate_event(aconsts.EVENT_CB_ON_IDENTITY_CHANGED, id1))

        # Attach session 2: wait for attach and for identity callback
        autils.wait_for_event(
            dut, autils.decorate_event(aconsts.EVENT_CB_ON_ATTACHED, id2))
        autils.wait_for_event(
            dut,
            autils.decorate_event(aconsts.EVENT_CB_ON_IDENTITY_CHANGED, id2))

        # Attach session 3: wait for attach, should not get identity
        autils.wait_for_event(
            dut, autils.decorate_event(aconsts.EVENT_CB_ON_ATTACHED, id3))
        autils.fail_on_event(
            dut,
            autils.decorate_event(aconsts.EVENT_CB_ON_IDENTITY_CHANGED, id3))

    @test_tracker_info(uuid="b8ea4d02-ae23-42a7-a85e-def52932c858")
    def test_attach_with_no_wifi(self):
        """Function test case / Attach test cases / attempt to attach with wifi off

    Validates that if trying to attach with Wi-Fi disabled will receive the
    expected failure callback. As a side-effect also validates that the
    broadcast for Aware unavailable is received.
    """
        dut = self.android_devices[0]
        wutils.wifi_toggle_state(dut, False)
        autils.wait_for_event(dut, aconsts.BROADCAST_WIFI_AWARE_NOT_AVAILABLE)
        dut.droid.wifiAwareAttach()
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACH_FAILED)

    @test_tracker_info(uuid="7dcc4530-c936-4447-9d22-a7c5b315e2ce")
    def test_attach_with_doze(self):
        """Function test case / Attach test cases / attempt to attach with doze on

    Validates that if trying to attach with device in doze mode will receive the
    expected failure callback. As a side-effect also validates that the
    broadcast for Aware unavailable is received.
    """
        dut = self.android_devices[0]
        asserts.assert_true(utils.enable_doze(dut), "Can't enable doze")
        autils.wait_for_event(dut, aconsts.BROADCAST_WIFI_AWARE_NOT_AVAILABLE)
        dut.droid.wifiAwareAttach()
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACH_FAILED)
        asserts.assert_true(utils.disable_doze(dut), "Can't disable doze")
        autils.wait_for_event(dut, aconsts.BROADCAST_WIFI_AWARE_AVAILABLE)

    @test_tracker_info(uuid="2574fd01-8974-4dd0-aeb8-a7194461140e")
    def test_attach_with_location_off(self):
        """Function test case / Attach test cases / attempt to attach with location
    mode off.

    Validates that if trying to attach with device location mode off will
    receive the expected failure callback. As a side-effect also validates that
    the broadcast for Aware unavailable is received.
    """
        dut = self.android_devices[0]
        utils.set_location_service(dut, False)
        autils.wait_for_event(dut, aconsts.BROADCAST_WIFI_AWARE_NOT_AVAILABLE)
        dut.droid.wifiAwareAttach()
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACH_FAILED)
        utils.set_location_service(dut, True)
        autils.wait_for_event(dut, aconsts.BROADCAST_WIFI_AWARE_AVAILABLE)

    @test_tracker_info(uuid="7ffde8e7-a010-4b77-97f5-959f263b5249")
    def test_attach_apm_toggle_attach_again(self):
        """Validates that enabling Airplane mode while Aware is on resets it
    correctly, and allows it to be re-enabled when Airplane mode is then
    disabled."""
        dut = self.android_devices[0]

        # enable Aware (attach)
        dut.droid.wifiAwareAttach()
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACHED)

        # enable airplane mode
        utils.force_airplane_mode(dut, True)
        autils.wait_for_event(dut, aconsts.BROADCAST_WIFI_AWARE_NOT_AVAILABLE)

        # wait a few seconds and disable airplane mode
        time.sleep(10)
        utils.force_airplane_mode(dut, False)
        autils.wait_for_event(dut, aconsts.BROADCAST_WIFI_AWARE_AVAILABLE)

        # try enabling Aware again (attach)
        dut.droid.wifiAwareAttach()
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACHED)


"""Calculate pi to N digits using Gauss-Legendre algorithm"""
from decimal import Decimal
from decimal import getcontext

N = 10000     # max decimal points displayed
getcontext().prec = N

# starting values for algorithm
A = Decimal(1)
B = Decimal(2 ** (-.5))
T = Decimal(.25)
P = Decimal(1)

def gen_abtp(a, b, t, p):
    """Generates the next a, b, t, and p values in the algorithm"""
    a_next = (a + b)/2
    b_next = (a*b).sqrt()
    t_next = t - p*(a-a_next)**2
    p_next = 2*p
    yield a_next, b_next, t_next, p_next

def gen_pi(a, b, t, p, n):
    """Generates the next estimate of pi from the algorithm"""
    for _ in range(n):
        yield ((a+b)**2)/(4*t)
        (a, b, t, p) = next(gen_abtp(a, b, t, p))

def calc_n_digits_pi(n):
    """Calculates pi to an accuracy of at least n digits and then returns the result"""
    max_error = Decimal(10) ** (-n)
    pi_approx = Decimal(1)
    for pi_gen in gen_pi(A, B, T, P, 100):
        if abs(pi_approx - pi_gen) < max_error:
            return pi_gen.quantize(max_error)
        pi_approx = pi_gen

def main():
    """Prompts user to calculate pi to this many digits then displays the result."""
    print("\n"*100)
    print("Welcome to the pi calculator!")

    run = True
    while run:
        print("\nHow many digits of pi would you like to calculate?")
        # check if input is an integer
        try:
            digits = int(input("Input any integer between 1 and 10000: "))
        except ValueError:
            print("You must input an integer. Try again.")
            continue

        # check if number is within range
        if 0 < digits < 10001:
            input(f"\nOK calculating {digits} digits of pi!\n\n *** Press Enter to continue ***\n")
        else:
            print("That number is out of range. Try again.")
            continue

        # calculate pi
        pi_est = calc_n_digits_pi(digits-1)
        print(f"Pi is approximately: {pi_est}\n")

        user_input = None
        while user_input not in ('y', 'n'):
            user_input = input("Would you like to calculate again? y/n ").lower()
            if user_input == 'y':
                print("\nYay pi!")
            elif user_input == 'n':
                print("\nGoodbye!")
                run = False
            else:
                print("Please input 'y' or 'n'. Try again.\n")

if __name__ == "__main__":
    main()


import aubio
import numpy as np
import pyaudio

import time
import argparse

import queue

import music21  # yes! new favorite library

parser = argparse.ArgumentParser()
parser.add_argument("-input", required=False, type=int, help="Audio Input Device")
args = parser.parse_args()
args.input = 0
if args.input== None:
    print("No input device specified. Printing list of input devices now: ")
    p = pyaudio.PyAudio()
    for i in range(p.get_device_count()):
        print("Device number (%i): %s" % (i, p.get_device_info_by_index(i).get('name')))
    print("Run this program with -input 1, or the number of the input you'd like to use.")
    exit()

# PyAudio object.
p = pyaudio.PyAudio()

# Open stream.
stream = p.open(format=pyaudio.paFloat32,
                channels=1, rate=44100, input=True,
                input_device_index=args.input, frames_per_buffer=4096)
#time.sleep(1)

# Aubio's pitch detection.
pDetection = aubio.pitch("default", 2048, 2048//2, 44100)
# Set unit.
pDetection.set_unit("Hz")
pDetection.set_silence(-40)

q = queue.Queue()

def get_current_note(volume_thresh=0.01, printOut=False):
    """Returns the Note Currently Played on the q object when audio is present

    Keyword arguments:

    volume_thresh -- the volume threshold for input. defaults to 0.01
    printOut -- whether or not to print to the terminal. defaults to False
    """
    current_pitch = music21.pitch.Pitch()

    while True:

        data = stream.read(1024, exception_on_overflow=False)
        samples = np.fromstring(data,
                                dtype=aubio.float_type)
        pitch = pDetection(samples)[0]

        # Compute the energy (volume) of the
        # current frame.
        volume = np.sum(samples**2)/len(samples) * 100

        if pitch and volume > volume_thresh:  # adjust with your mic!
            current_pitch.frequency = pitch   # pitch es la frecuencia dada por aubio, y se transforma en una instancia de current_pitch de Music21
        else:
            continue

        if printOut:
            print(current_pitch, pitch)

        else:
            current = current_pitch.nameWithOctave
            current_midi = current_pitch.midi
            q.put({'Note': current, 'Cents': current_pitch.microtone.cents, 'NotePitch': pitch, 'NoteMidi': current_midi}) #añadido NotePitch

if __name__ == '__main__':
    get_current_note(volume_thresh=0.001, printOut=True)

'''from threading import Thread
import pygame

#from shortvoiceController import q, get_current_note

pygame.init()

screenWidth, screenHeight = 288, 512
screen = pygame.display.set_mode((screenWidth, screenHeight))
clock = pygame.time.Clock()

running = True

titleFont = pygame.font.Font(None, 34)
titleText = titleFont.render("Sing a", True, (0, 128, 0))
titleCurr = titleFont.render("Low Note", True, (0, 128, 0))

noteFont = pygame.font.Font(None, 55)

t = Thread(target=get_current_note)
t.daemon = True
t.start()

low_note = ""
high_note = ""
have_low = False
have_high = True

noteHoldLength = 20  # how many samples in a row user needs to hold a note
noteHeldCurrently = 0  # keep track of how long current note is held
noteHeld = ""  # string of the current note

centTolerance = 20  # how much deviance from proper note to tolerate

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_q:
            running = False

    screen.fill((0, 0, 0))

    # draw line to show visually how far away from note voice is
    pygame.draw.line(screen, (255, 255, 255), (10, 290), (10, 310))
    pygame.draw.line(screen, (255, 255, 255), (screenWidth - 10, 290),
                     (screenWidth - 10, 310))
    pygame.draw.line(screen, (255, 255, 255), (10, 300),
                     (screenWidth - 10, 300))

    # our user should be singing if there's a note on the queue
    if not q.empty():
        b = q.get()
        if b['Cents'] < 15:
            pygame.draw.circle(screen, (0, 128, 0),
                               (screenWidth // 2 + (int(b['Cents']) * 2),300),
                               5)
        else:
            pygame.draw.circle(screen, (128, 0, 0),
                               (screenWidth // 2 + (int(b['Cents']) * 2), 300),
                               5)

        noteText = noteFont.render(b['Note'], True, (0, 128, 0))
        if b['Note'] == noteHeldCurrently:
            noteHeld += 1
            if noteHeld == noteHoldLength:
                if not have_low:
                    low_note = noteHeldCurrently
                    have_low = True
                    titleCurr = titleFont.render("High Note", True,
                                                 (128, 128, 0))
                else:
                    if int(noteHeldCurrently[-1]) <= int(low_note[-1]):
                        noteHeld = 0  # we're holding a lower octave note
                    elif int(noteHeldCurrently[-1]) and not high_note:
                        high_note = noteHeldCurrently
                        have_high = True
                        titleText = titleFont.render("Perfect!", True,
                                                     (0, 128, 0))
                        titleCurr = titleFont.render("%s to %s" %
                                                     (low_note, high_note),
                                                     True, (0, 128, 0))
        else:
            noteHeldCurrently = b['Note']
            noteHeld = 1
        screen.blit(noteText, (50, 400))

    screen.blit(titleText, (10,  80))
    screen.blit(titleCurr, (10, 120))
    pygame.display.flip()
    clock.tick(30)'''


import requests
from bs4 import BeautifulSoup
import csv
from datetime import datetime
from multiprocessing import Pool

def get_html(url: str) -> str:
    """Возвращает html страницы."""
    response = requests.get(url)  # объект Response
    return response.text

def get_all_links(html: str) -> list:
    """Возвращает ссылки на страницы криптовалют."""
    soup = BeautifulSoup(html, "html.parser")  # объект BeautifulSoup
    links = []

    try:
        trs = soup.find("tbody").find_all("tr", class_="cmc-table-row")  # объект ResultSet
    except AttributeError:
        pass
    else:
        for tr in trs:
            a = tr.find("a", class_="cmc-link").get("href", None)
            if a is not None:
                links.append("https://coinmarketcap.com" + a)
    return links

def get_page_data(html: str) -> dict:
    """Возвращает название и цену криптовалюты."""
    soup = BeautifulSoup(html, "html.parser")
    coin_info = soup.find("div", id="section-coin-overview")
    coin_name, coin_price = None, None

    if coin_info is not None:
        coin_name = coin_info.find("span", class_="coin-name-pc")
        coin_price = coin_info.find("span", class_="sc-16891c57-0 dxubiK base-text")

        if coin_name is not None:
            coin_name = coin_name.text.strip()
        if coin_price is not None:
            coin_price = coin_price.text.strip()

    return {"name": coin_name, "price": coin_price}

def write_csv(data: dict, file_name: str):
    """Запись данных о криптовалюте в csv файл."""
    with open(file_name, "a") as file:
        writer = csv.writer(file)
        writer.writerow((data["name"], data["price"]))

def main_one_process(links):
    """Парсинг сайта одним процессом."""
    start_time = datetime.now()

    for ind, link in enumerate(links):
        html = get_html(link)
        data = get_page_data(html)
        write_csv(data, "coinmarketcap/coins_one_process.csv")
        print(f"{ind}: {data['name']}\nTime: {datetime.now() - start_time}\n")

    print(f"Total time: {datetime.now() - start_time}\n")

def parse_and_write_coin(link):
    """Парсинг и запись информации о криптовалюте в файл."""
    html = get_html(link)
    data = get_page_data(html)
    write_csv(data, "coinmarketcap/coins_multiprocessing.csv")
    print(f"{data['name']}")

def main_multiprocessing(links):
    """Парсинг сайта несколькими процессами."""
    start_time = datetime.now()

    with Pool(20) as pool:
        pool.map(parse_and_write_coin, links)

    print(f"Total time: {datetime.now() - start_time}\n")

if __name__ == "__main__":
    base_url = "https://coinmarketcap.com/all/views/all/"

    all_links = get_all_links(get_html(base_url))

    main_one_process(all_links)  # 52 секунды
    main_multiprocessing(all_links)  # 27 секунд


"""
Задача №39
============================================================
Даны два массива чисел. Требуется вывести те элементы
первого массива (в том порядке, в каком они идут в первом
массиве), которых нет во втором массиве. Пользователь вводит
число N - количество элементов в первом массиве, затем N
чисел - элементы массива. Затем число M - количество
элементов во втором массиве. Затем элементы второго массива
============================================================
Ввод: (каждое число вводится с новой строки)
7
3 1 3 4 2 4 12
6
4 15 43 1 15 1
Вывод: 3 3 2 12
"""

def get_unique_elements_from_1(num_list_1: list[int], num_list_2: list[int]):
    unique_elems: list[int] = list()
    for num_1 in num_list_1:
        if num_list_2.count(num_1) == 0:
            unique_elems.append(num_1)
    return unique_elems

def prompt_number(message: str = "") -> int:
    line: str = ""
    number: int = 0
    while line.strip() == "":
        if not message.strip() == "":
            print(message)
        try:
            line = input(">>> ").strip()
        except KeyboardInterrupt:
            print("Эх, меня закрыли...")
            exit(1)
        if line == "":
            print("Вы ничего не ввели!")
            line = ""
            continue
        try:
            number = int(line)
        except ValueError:
            print("Ваше введенное значение не является числом!")
            line = ""
            continue
        except OverflowError:
            print("Ваше введенное число слишком большое!")
            line = ""
            continue
        if number > 32767 or number < -32768:
            print("Ваше введенное число слишком большое!")
            line = ""
            continue
    return number

def prompt_num_list(message: str = "", size: int = -1) -> list[int]:
    result = []
    while size == -1 or len(result) < size:
        try:
            num = int(input(f"{message} ({len(result)+1}/{size}): "))
            result.append(num)
        except ValueError:
            print("Некорректный ввод. Пожалуйста, введите целое число.")
        except KeyboardInterrupt:
            break
    return result

number_n = prompt_number("Введите кол-во чисел в 1 массиве")
number_list_n: list[int] = prompt_num_list("число", number_n)
number_m = prompt_number("Введите кол-во чисел в 2 массиве")
number_list_m: list[int] = prompt_num_list("число", number_m)
unique_numbers: list[int] = get_unique_elements_from_1(number_list_n, number_list_m)
print(unique_numbers)


'''
Created on Mar 3, 2015

@author: andreweckford
'''

import numpy as np

def genP(bigDelta, t_on, t_off):

    Px = np.array([[1-bigDelta/t_off,bigDelta/t_off],[bigDelta/t_on,1-bigDelta/t_on]])

    # State numbering:
    # Let (C,N) represent the number of bound sites at the C and N ends, respectively.
    # Then
    # 0 = (0,0)
    # 1 = (0,1)
    # 2 = (0,2)
    # 3 = (1,0)
    # 4 = (1,1)
    # 5 = (1,2)
    # 6 = (2,0)
    # 7 = (2,1)
    # 8 = (2,2)

    maps = [[[0],[1],[2],[3],[4],[5],[6],[7],[8]],[[0,1,3,4],[2,5],[6,7],[8]]]

    x_array = np.array([1e-7,1e-6])

    # units are per second -- multiply by 1e-3 later to make them per ms
    kPlus1N = 7.7e8 # per mol
    kPlus2N = 3.2e10 # per mol
    kMinus1N = 1.6e5
    kMinus2N = 2.2e4
    kPlus1C = 8.4e7 # per mol
    kPlus2C = 3.3e7 # per mol
    kMinus1C = 8.7e3
    kMinus2C = 9.8

    P = []

    for x in x_array:
        RN = np.array([[0,kPlus1N*x,0],[kMinus1N,0,kPlus2N*x],[0,kMinus2N,0]])
        dPlus1 = np.identity(3)*kPlus1C*x
        dPlus2 = np.identity(3)*kPlus2C*x
        dMinus1 = np.identity(3)*kMinus1C
        dMinus2 = np.identity(3)*kMinus2C
        z = np.zeros((3,3))

        R = np.hstack((RN,dPlus1,z)) # first row
        R = np.vstack((R,np.hstack((dMinus1,RN,dPlus2))))
        R = np.vstack((R,np.hstack((z,dMinus2,RN))))

        # make row sum equal to zero
        R = R - np.diag(np.sum(R,axis=1))

        # scale per ms rather than per s
        R = R * (1e-3)

        # watch out: some

        # append to P
        P.append(np.identity(9)+bigDelta*R)
        if any([np.any(t < 0) for t in P]) or any([np.any(t > 1) for t in P]):
            raise ValueError("Your parameters lead to an invalid transition probability matrix. Try decreasing time step.")

    return [P,Px,maps]


import numpy as np
import gym
from gym.spaces import Box, Dict

from utils.helpers import extract_observable_state  # get_raw_state_size
from utils.load_confs import load_parameters, load_paths
params = load_parameters()

def goal_distance(goal_a, goal_b, dim_scale=True, time_feat=False):
    # if dim_scale is True, scale distance by a factor of sqrt(d) so that the distance is invariant to dimensionality
    # of the goals. By using a dimension invariant distance, we can use a constant distance threshold to determine whether
    # a state is equal to the goal, across all environments.
    # if time_feat is True (assumed to be last feature), ignore it
    assert goal_a.shape == goal_b.shape, f"goal a shape: {goal_a.shape}, goal b shape: {goal_b.shape}"
    if time_feat:
        goal_a = goal_a[:-1]
        goal_b = goal_b[:-1]

    if dim_scale:
        dist = np.linalg.norm(goal_a - goal_b, axis=-1,
                              ord=2) / np.sqrt(goal_a.shape[0])
        return dist

    else:
        return np.linalg.norm(goal_a - goal_b, axis=-1, ord=2)

class GoalDemoWrapper(gym.Wrapper):
    def __init__(self, env, env_id, expert_demo, raw=False, displace_t=0,
                 reward_type='sparse', distance_threshold=1e-4, time_feat=False, sin_cos_repr=False,
                 potential_coef=1):
        '''
        This wrapper makes MuJoCo continuous control environments into GoalEnvs, where the expert
        demonstrations provide the goals. Satisfies requirements of a Gym goalenv without actually inheriting
        from it.

        displace_t: if agent's state is s_t, append expert state s^e_{t+displace_t}
        '''
        super(GoalDemoWrapper, self).__init__(env)
        self.env = env
        self.env_id = env_id

        self.expert_demo = expert_demo
        assert len(self.expert_demo.shape) == 2
        self.n_demo_timesteps = self.expert_demo.shape[0]
        self.displace_t = displace_t

        self.raw = raw
        if raw:
            obs_type = "raw"
        else:
            obs_type = "full"

        self.discount = params['sac'][env_id.strip("-v2").lower()]["gamma"]

        # load reward params
        self.reward_type = reward_type
        self.reward_params = params['rew_shaping'][env_id.strip(
            "-v2").lower()][obs_type]
        self.dist_std = self.reward_params["dist_std"]
        self.imit_rew_coef = self.reward_params["imit_rew_coef"]
        self.gamma = self.reward_params["gamma"]
        self.alpha = self.reward_params["alpha"]
        self.terminal_phi0 = params['pbrs']['terminal_phi0']

        self.distance_threshold = distance_threshold

        # correct observation space size
        self.expert_state_size = self.expert_demo.shape[1]
        self.obs_size = self.env.observation_space.shape[0]
        self.act_size = self.env.action_space.shape[0]
        self.time_feat = time_feat
        self.sin_cos_repr = sin_cos_repr
        self.potential_coef = potential_coef
        # self.obs_size += 1 # taken care of obs size returned by time feat wrapper
        # self.observation_space = Box(low=-np.inf, high=np.inf,
        #                                         shape=(self.obs_size + self.expert_state_size, ),
        #                                         dtype=np.float32)

        self.observation_space = Dict(dict(
                                      desired_goal=Box(low=-np.inf, high=np.inf,
                                                       shape=(
                                                           self.expert_state_size, ),
                                                       dtype=np.float32),
                                      achieved_goal=Box(low=-np.inf, high=np.inf,
                                                        shape=(
                                                            self.expert_state_size, ),
                                                        dtype=np.float32),
                                      observation=Box(low=-np.inf, high=np.inf,
                                                      shape=(self.obs_size, ),
                                                      dtype=np.float32)
                                      ))
        self.replay_buffer_obs_space = Dict(dict(
            desired_goal=Box(low=-np.inf, high=np.inf,
                             shape=(
                                 self.expert_state_size, ),
                             dtype=np.float32),
            observation=Box(low=-np.inf, high=np.inf,
                            shape=(self.obs_size, ),
                            dtype=np.float32)
        ))

        self.current_t = 0

    def get_expert_demo(self, ob):
        '''At time t, append expert's state at time t+displace_t'''
        if (self.current_t + self.displace_t) > self.n_demo_timesteps - 1:
            # append expert state
            self.expert_t = self.n_demo_timesteps - 1
        else:
            self.expert_t = self.current_t + self.displace_t
        self.demo_ob = self.expert_demo[self.expert_t]

        self.current_t += 1

    def compute_reward(self, achieved_goal_tp1, desired_goal_t, info, eval_mode=False):
        """
        TODO: REFACTOR desired_goal_t to desired_goal_tp1
        NOTE: If eval_mode, mutate the info dict to contain the goal reaching information

        Compute the step reward. This externalizes the reward function and makes
        it dependent on an a desired goal and the one that was achieved. If you wish to include
        additional rewards that are independent of the goal, you can include the necessary values
        to derive it in info and compute it accordingly.
        Args:
            achieved_goal (object): the goal that was achieved during execution
            desired_goal (object): the desired goal that we asked the agent to attempt to achieve
            info (dict): an info dictionary with additional information
        Returns:
            float: The reward that corresponds to the provided achieved goal w.r.t. to the desired
            goal. Note that the following should always hold true:
                ob, reward, done, info = env.step()
                assert reward == env.compute_reward(ob['achieved_goal'], ob['goal'], info)
        """        # here the achieved goal is the achieved state at time t+1
        if self.reward_type == 'sparse':
            d = goal_distance(achieved_goal_tp1, desired_goal_t,
                              dim_scale=True, time_feat=self.time_feat)
            total_rew = -(d > self.distance_threshold).astype(np.float32)
        elif self.reward_type == 'dense':
            d = goal_distance(achieved_goal_tp1, desired_goal_t,
                              dim_scale=True, time_feat=self.time_feat)
            total_rew = -d
        elif self.reward_type == 'huber+env':
            # tuning occured with no dimension scaling
            d = goal_distance(achieved_goal_tp1, desired_goal_t,
                              dim_scale=False, time_feat=self.time_feat)
            sq_dist = np.square(d) / self.dist_std
            imit_rew = - (self.alpha * sq_dist) - \
                ((1 - self.alpha) * np.sqrt(self.gamma + sq_dist))
            total_rew = ((1 - self.imit_rew_coef) *
                         info["env_rew"]) + (self.imit_rew_coef * imit_rew)
        elif self.reward_type == 'potential_dense':
            if info["done"] and self.terminal_phi0:
                d_tp1 = 0
            else:
                d_tp1 = goal_distance(
                    achieved_goal_tp1, desired_goal_t, dim_scale=True, time_feat=self.time_feat)
            d_t = goal_distance(info["prev_ob"]["achieved_goal"], info["prev_ob"]
                                ["desired_goal"], dim_scale=True, time_feat=self.time_feat)
            # (s_t | g_t, a_t, r_t, s_t+1 | g_t+1) <- example of a transition with goals
            # note that we need a negative distance here
            potential = - self.discount * d_tp1 + d_t
            total_rew = info["env_rew"] + self.potential_coef * potential
        elif self.reward_type == 'env':
            total_rew = info["env_rew"]
        else:
            print(f"Reward type {self.reward_type} not supported. ")

        if eval_mode:  # Mutate info dict
            # compute potential_corrected here
            if info["done"] and self.terminal_phi0:
                d_tp1 = 0
            else:
                d_tp1 = goal_distance(
                    achieved_goal_tp1, desired_goal_t, dim_scale=True, time_feat=self.time_feat)
            d_t = goal_distance(info["prev_ob"]["achieved_goal"], info["prev_ob"]
                                ["desired_goal"], dim_scale=True, time_feat=self.time_feat)
            # compute potential_dense
            potential = - self.discount * d_tp1 + d_t
            shaped_rew = info["env_rew"] + self.potential_coef * potential
            info["goal_dist"] = d_tp1
            info["shaped_rew"] = shaped_rew

        return total_rew

    def _get_obs(self, agent_ob):
        # HER env wrapper will concatenate all of these
        return {
            'observation': agent_ob.copy(),
            'achieved_goal': extract_observable_state(agent_ob, self.env_id, self.time_feat,
                                                      sin_cos_repr=self.sin_cos_repr) if self.raw else agent_ob.copy(),
            'desired_goal': self.demo_ob.copy()
        }

    def reset(self):
        ob = self.env.reset()
        self.current_t = 0
        self.get_expert_demo(ob)  # sets current_t = 1
        obs_dict = self._get_obs(ob)
        self.prev_obs_dict = obs_dict
        return obs_dict

    def step(self, action, eval_mode=False):
        ob, env_rew, done, env_rew_info = self.env.step(
            action)  # discard env reward for now
        self.get_expert_demo(ob)

        obs_dict = self._get_obs(ob)
        info = {**env_rew_info,
                "env_rew": env_rew,
                "prev_ob": self.prev_obs_dict,
                "done": done
                }
        # TODO: refactor desired_goal_t to desired_goal_tp1
        reward = self.compute_reward(achieved_goal_tp1=obs_dict['achieved_goal'],
                                     desired_goal_t=obs_dict['desired_goal'],
                                     info=info,
                                     eval_mode=eval_mode)  # info will be mutated if eval_mode is True
        self.prev_obs_dict = obs_dict
        return obs_dict, reward, done, info


import datetime as dt

import numpy as np
from numpy.testing import (
    assert_,
    assert_allclose,
    assert_almost_equal,
    assert_array_almost_equal,
    assert_equal,
    assert_raises,
)
import pandas as pd
import pytest

from statsmodels.sandbox.tsa.fftarma import ArmaFft
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.arima_process import (
    ArmaProcess,
    arma_acf,
    arma_acovf,
    arma_generate_sample,
    arma_impulse_response,
    index2lpol,
    lpol2index,
    lpol_fiar,
    lpol_fima,
)
from statsmodels.tsa.tests.results import results_arma_acf
from statsmodels.tsa.tests.results.results_process import (
    armarep,  # benchmarkdata
)

arlist = [
    [1.0],
    [1, -0.9],  # ma representation will need many terms to get high precision
    [1, 0.9],
    [1, -0.9, 0.3],
]

malist = [[1.0], [1, 0.9], [1, -0.9], [1, 0.9, -0.3]]

DECIMAL_4 = 4

def test_arma_acovf():
    # Check for specific AR(1)
    N = 20
    phi = 0.9
    sigma = 1
    # rep 1: from module function
    rep1 = arma_acovf([1, -phi], [1], N)
    # rep 2: manually
    rep2 = [1.0 * sigma * phi ** i / (1 - phi ** 2) for i in range(N)]
    assert_allclose(rep1, rep2)

def test_arma_acovf_persistent():
    # Test arma_acovf in case where there is a near-unit root.
    # .999 is high enough to trigger the "while ir[-1] > 5*1e-5:" clause,
    # but not high enough to trigger the "nobs_ir > 50000" clause.
    ar = np.array([1, -0.9995])
    ma = np.array([1])
    process = ArmaProcess(ar, ma)
    res = process.acovf(10)

    # Theoretical variance sig2 given by:
    # sig2 = .9995**2 * sig2 + 1
    sig2 = 1 / (1 - 0.9995 ** 2)

    corrs = 0.9995 ** np.arange(10)
    expected = sig2 * corrs
    assert_equal(res.ndim, 1)
    assert_allclose(res, expected)

def test_arma_acf():
    # Check for specific AR(1)
    N = 20
    phi = 0.9
    sigma = 1
    # rep 1: from module function
    rep1 = arma_acf([1, -phi], [1], N)
    # rep 2: manually
    acovf = np.array(
        [1.0 * sigma * phi ** i / (1 - phi ** 2) for i in range(N)]
    )
    rep2 = acovf / (1.0 / (1 - phi ** 2))
    assert_allclose(rep1, rep2)

def test_arma_acf_compare_R_ARMAacf():
    # Test specific cases against output from R's ARMAacf
    bd_example_3_3_2 = arma_acf([1, -1, 0.25], [1, 1])
    assert_allclose(bd_example_3_3_2, results_arma_acf.bd_example_3_3_2)
    example_1 = arma_acf([1, -1, 0.25], [1, 1, 0.2])
    assert_allclose(example_1, results_arma_acf.custom_example_1)
    example_2 = arma_acf([1, -1, 0.25], [1, 1, 0.2, 0.3])
    assert_allclose(example_2, results_arma_acf.custom_example_2)
    example_3 = arma_acf([1, -1, 0.25], [1, 1, 0.2, 0.3, -0.35])
    assert_allclose(example_3, results_arma_acf.custom_example_3)
    example_4 = arma_acf([1, -1, 0.25], [1, 1, 0.2, 0.3, -0.35, -0.1])
    assert_allclose(example_4, results_arma_acf.custom_example_4)
    example_5 = arma_acf([1, -1, 0.25, -0.1], [1, 1, 0.2])
    assert_allclose(example_5, results_arma_acf.custom_example_5)
    example_6 = arma_acf([1, -1, 0.25, -0.1, 0.05], [1, 1, 0.2])
    assert_allclose(example_6, results_arma_acf.custom_example_6)
    example_7 = arma_acf([1, -1, 0.25, -0.1, 0.05, -0.02], [1, 1, 0.2])
    assert_allclose(example_7, results_arma_acf.custom_example_7)

def test_arma_acov_compare_theoretical_arma_acov():
    # Test against the older version of this function, which used a different
    # approach that nicely shows the theoretical relationship
    # See GH:5324 when this was removed for full version of the function
    # including documentation and inline comments

    def arma_acovf_historical(ar, ma, nobs=10):
        if np.abs(np.sum(ar) - 1) > 0.9:
            nobs_ir = max(1000, 2 * nobs)
        else:
            nobs_ir = max(100, 2 * nobs)
        ir = arma_impulse_response(ar, ma, leads=nobs_ir)
        while ir[-1] > 5 * 1e-5:
            nobs_ir *= 10
            ir = arma_impulse_response(ar, ma, leads=nobs_ir)
        if nobs_ir > 50000 and nobs < 1001:
            end = len(ir)
            acovf = np.array(
                [
                    np.dot(ir[: end - nobs - t], ir[t : end - nobs])
                    for t in range(nobs)
                ]
            )
        else:
            acovf = np.correlate(ir, ir, "full")[len(ir) - 1 :]
        return acovf[:nobs]

    assert_allclose(
        arma_acovf([1, -0.5], [1, 0.2]),
        arma_acovf_historical([1, -0.5], [1, 0.2]),
    )
    assert_allclose(
        arma_acovf([1, -0.99], [1, 0.2]),
        arma_acovf_historical([1, -0.99], [1, 0.2]),
    )

def _manual_arma_generate_sample(ar, ma, eta):
    T = len(eta)
    ar = ar[::-1]
    ma = ma[::-1]
    p, q = len(ar), len(ma)
    rep2 = [0] * max(p, q)  # initialize with zeroes
    for t in range(T):
        yt = eta[t]
        if p:
            yt += np.dot(rep2[-p:], ar)
        if q:
            # left pad shocks with zeros
            yt += np.dot([0] * (q - t) + list(eta[max(0, t - q) : t]), ma)
        rep2.append(yt)
    return np.array(rep2[max(p, q) :])

@pytest.mark.parametrize("ar", arlist)
@pytest.mark.parametrize("ma", malist)
@pytest.mark.parametrize("dist", [np.random.standard_normal])
def test_arma_generate_sample(dist, ar, ma):
    # Test that this generates a true ARMA process
    # (amounts to just a test that scipy.signal.lfilter does what we want)
    T = 100
    np.random.seed(1234)
    eta = dist(T)

    # rep1: from module function
    np.random.seed(1234)
    rep1 = arma_generate_sample(ar, ma, T, distrvs=dist)
    # rep2: "manually" create the ARMA process
    ar_params = -1 * np.array(ar[1:])
    ma_params = np.array(ma[1:])
    rep2 = _manual_arma_generate_sample(ar_params, ma_params, eta)
    assert_array_almost_equal(rep1, rep2, 13)

def test_fi():
    # test identity of ma and ar representation of fi lag polynomial
    n = 100
    mafromar = arma_impulse_response(lpol_fiar(0.4, n=n), [1], n)
    assert_array_almost_equal(mafromar, lpol_fima(0.4, n=n), 13)

def test_arma_impulse_response():
    arrep = arma_impulse_response(armarep.ma, armarep.ar, leads=21)[1:]
    marep = arma_impulse_response(armarep.ar, armarep.ma, leads=21)[1:]
    assert_array_almost_equal(armarep.marep.ravel(), marep, 14)
    # difference in sign convention to matlab for AR term
    assert_array_almost_equal(-armarep.arrep.ravel(), arrep, 14)

@pytest.mark.parametrize("ar", arlist)
@pytest.mark.parametrize("ma", malist)
def test_spectrum(ar, ma):
    nfreq = 20
    w = np.linspace(0, np.pi, nfreq, endpoint=False)

    arma = ArmaFft(ar, ma, 20)
    spdr, wr = arma.spdroots(w)
    spdp, wp = arma.spdpoly(w, 200)
    spdd, wd = arma.spddirect(nfreq * 2)
    assert_equal(w, wr)
    assert_equal(w, wp)
    assert_almost_equal(w, wd[:nfreq], decimal=14)
    assert_almost_equal(
        spdr,
        spdd[:nfreq],
        decimal=7,
        err_msg="spdr spdd not equal for %s, %s" % (ar, ma),
    )
    assert_almost_equal(
        spdr,
        spdp,
        decimal=7,
        err_msg="spdr spdp not equal for %s, %s" % (ar, ma),
    )

@pytest.mark.parametrize("ar", arlist)
@pytest.mark.parametrize("ma", malist)
def test_armafft(ar, ma):
    # test other methods
    nfreq = 20
    w = np.linspace(0, np.pi, nfreq, endpoint=False)

    arma = ArmaFft(ar, ma, 20)
    ac1 = arma.invpowerspd(1024)[:10]
    ac2 = arma.acovf(10)[:10]
    assert_allclose(
        ac1, ac2, atol=1e-15, err_msg="acovf not equal for %s, %s" % (ar, ma)
    )

def test_lpol2index_index2lpol():
    process = ArmaProcess([1, 0, 0, -0.8])
    coefs, locs = lpol2index(process.arcoefs)
    assert_almost_equal(coefs, [0.8])
    assert_equal(locs, [2])

    process = ArmaProcess([1, 0.1, 0.1, -0.8])
    coefs, locs = lpol2index(process.arcoefs)
    assert_almost_equal(coefs, [-0.1, -0.1, 0.8])
    assert_equal(locs, [0, 1, 2])
    ar = index2lpol(coefs, locs)
    assert_equal(process.arcoefs, ar)

class TestArmaProcess:
    def test_empty_coeff(self):
        process = ArmaProcess()
        assert_equal(process.arcoefs, np.array([]))
        assert_equal(process.macoefs, np.array([]))

        process = ArmaProcess([1, -0.8])
        assert_equal(process.arcoefs, np.array([0.8]))
        assert_equal(process.macoefs, np.array([]))

        process = ArmaProcess(ma=[1, -0.8])
        assert_equal(process.arcoefs, np.array([]))
        assert_equal(process.macoefs, np.array([-0.8]))

    def test_from_roots(self):
        ar = [1.8, -0.9]
        ma = [0.3]

        ar.insert(0, -1)
        ma.insert(0, 1)
        ar_p = -1 * np.array(ar)
        ma_p = ma
        process_direct = ArmaProcess(ar_p, ma_p)

        process = ArmaProcess.from_roots(np.array(process_direct.maroots), np.array(process_direct.arroots))

        assert_almost_equal(process.arcoefs, process_direct.arcoefs)
        assert_almost_equal(process.macoefs, process_direct.macoefs)
        assert_almost_equal(process.nobs, process_direct.nobs)
        assert_almost_equal(process.maroots, process_direct.maroots)
        assert_almost_equal(process.arroots, process_direct.arroots)
        assert_almost_equal(process.isinvertible, process_direct.isinvertible)
        assert_almost_equal(process.isstationary, process_direct.isstationary)

        process_direct = ArmaProcess(ar=ar_p)
        process = ArmaProcess.from_roots(arroots=np.array(process_direct.arroots))

        assert_almost_equal(process.arcoefs, process_direct.arcoefs)
        assert_almost_equal(process.macoefs, process_direct.macoefs)
        assert_almost_equal(process.nobs, process_direct.nobs)
        assert_almost_equal(process.maroots, process_direct.maroots)
        assert_almost_equal(process.arroots, process_direct.arroots)
        assert_almost_equal(process.isinvertible, process_direct.isinvertible)
        assert_almost_equal(process.isstationary, process_direct.isstationary)

        process_direct = ArmaProcess(ma=ma_p)
        process = ArmaProcess.from_roots(maroots=np.array(process_direct.maroots))

        assert_almost_equal(process.arcoefs, process_direct.arcoefs)
        assert_almost_equal(process.macoefs, process_direct.macoefs)
        assert_almost_equal(process.nobs, process_direct.nobs)
        assert_almost_equal(process.maroots, process_direct.maroots)
        assert_almost_equal(process.arroots, process_direct.arroots)
        assert_almost_equal(process.isinvertible, process_direct.isinvertible)
        assert_almost_equal(process.isstationary, process_direct.isstationary)

        process_direct = ArmaProcess()
        process = ArmaProcess.from_roots()

        assert_almost_equal(process.arcoefs, process_direct.arcoefs)
        assert_almost_equal(process.macoefs, process_direct.macoefs)
        assert_almost_equal(process.nobs, process_direct.nobs)
        assert_almost_equal(process.maroots, process_direct.maroots)
        assert_almost_equal(process.arroots, process_direct.arroots)
        assert_almost_equal(process.isinvertible, process_direct.isinvertible)
        assert_almost_equal(process.isstationary, process_direct.isstationary)

    def test_from_coeff(self):
        ar = [1.8, -0.9]
        ma = [0.3]
        process = ArmaProcess.from_coeffs(np.array(ar), np.array(ma))

        ar.insert(0, -1)
        ma.insert(0, 1)
        ar_p = -1 * np.array(ar)
        ma_p = ma
        process_direct = ArmaProcess(ar_p, ma_p)

        assert_equal(process.arcoefs, process_direct.arcoefs)
        assert_equal(process.macoefs, process_direct.macoefs)
        assert_equal(process.nobs, process_direct.nobs)
        assert_equal(process.maroots, process_direct.maroots)
        assert_equal(process.arroots, process_direct.arroots)
        assert_equal(process.isinvertible, process_direct.isinvertible)
        assert_equal(process.isstationary, process_direct.isstationary)

    def test_process_multiplication(self):
        process1 = ArmaProcess.from_coeffs([0.9])
        process2 = ArmaProcess.from_coeffs([0.7])
        process3 = process1 * process2
        assert_equal(process3.arcoefs, np.array([1.6, -0.7 * 0.9]))
        assert_equal(process3.macoefs, np.array([]))

        process1 = ArmaProcess.from_coeffs([0.9], [0.2])
        process2 = ArmaProcess.from_coeffs([0.7])
        process3 = process1 * process2

        assert_equal(process3.arcoefs, np.array([1.6, -0.7 * 0.9]))
        assert_equal(process3.macoefs, np.array([0.2]))

        process1 = ArmaProcess.from_coeffs([0.9], [0.2])
        process2 = process1 * (np.array([1.0, -0.7]), np.array([1.0]))
        assert_equal(process2.arcoefs, np.array([1.6, -0.7 * 0.9]))

        assert_raises(TypeError, process1.__mul__, [3])

    def test_str_repr(self):
        process1 = ArmaProcess.from_coeffs([0.9], [0.2])
        out = process1.__str__()
        print(out)
        assert_(out.find("AR: [1.0, -0.9]") != -1)
        assert_(out.find("MA: [1.0, 0.2]") != -1)

        out = process1.__repr__()
        assert_(out.find("nobs=100") != -1)
        assert_(out.find("at " + str(hex(id(process1)))) != -1)

    def test_acf(self):
        process1 = ArmaProcess.from_coeffs([0.9])
        acf = process1.acf(10)
        expected = np.array(0.9) ** np.arange(10.0)
        assert_array_almost_equal(acf, expected)

        acf = process1.acf()
        assert_(acf.shape[0] == process1.nobs)

    def test_pacf(self):
        process1 = ArmaProcess.from_coeffs([0.9])
        pacf = process1.pacf(10)
        expected = np.array([1, 0.9] + [0] * 8)
        assert_array_almost_equal(pacf, expected)

        pacf = process1.pacf()
        assert_(pacf.shape[0] == process1.nobs)

    def test_isstationary(self):
        process1 = ArmaProcess.from_coeffs([1.1])
        assert_equal(process1.isstationary, False)

        process1 = ArmaProcess.from_coeffs([1.8, -0.9])
        assert_equal(process1.isstationary, True)

        process1 = ArmaProcess.from_coeffs([1.5, -0.5])
        print(np.abs(process1.arroots))
        assert_equal(process1.isstationary, False)

    def test_arma2ar(self):
        process1 = ArmaProcess.from_coeffs([], [0.8])
        vals = process1.arma2ar(100)
        assert_almost_equal(vals, (-0.8) ** np.arange(100.0))

    def test_invertroots(self):
        process1 = ArmaProcess.from_coeffs([], [2.5])
        process2 = process1.invertroots(True)
        assert_almost_equal(process2.ma, np.array([1.0, 0.4]))

        process1 = ArmaProcess.from_coeffs([], [0.4])
        process2 = process1.invertroots(True)
        assert_almost_equal(process2.ma, np.array([1.0, 0.4]))

        process1 = ArmaProcess.from_coeffs([], [2.5])
        roots, invertable = process1.invertroots(False)
        assert_equal(invertable, False)
        assert_almost_equal(roots, np.array([1, 0.4]))

    def test_generate_sample(self):
        process = ArmaProcess.from_coeffs([0.9])
        np.random.seed(12345)
        sample = process.generate_sample()
        np.random.seed(12345)
        expected = np.random.randn(100)
        for i in range(1, 100):
            expected[i] = 0.9 * expected[i - 1] + expected[i]
        assert_almost_equal(sample, expected)

        process = ArmaProcess.from_coeffs([1.6, -0.9])
        np.random.seed(12345)
        sample = process.generate_sample()
        np.random.seed(12345)
        expected = np.random.randn(100)
        expected[1] = 1.6 * expected[0] + expected[1]
        for i in range(2, 100):
            expected[i] = (
                1.6 * expected[i - 1] - 0.9 * expected[i - 2] + expected[i]
            )
        assert_almost_equal(sample, expected)

        process = ArmaProcess.from_coeffs([1.6, -0.9])
        np.random.seed(12345)
        sample = process.generate_sample(burnin=100)
        np.random.seed(12345)
        expected = np.random.randn(200)
        expected[1] = 1.6 * expected[0] + expected[1]
        for i in range(2, 200):
            expected[i] = (
                1.6 * expected[i - 1] - 0.9 * expected[i - 2] + expected[i]
            )
        assert_almost_equal(sample, expected[100:])

        np.random.seed(12345)
        sample = process.generate_sample(nsample=(100, 5))
        assert_equal(sample.shape, (100, 5))

    def test_impulse_response(self):
        process = ArmaProcess.from_coeffs([0.9])
        ir = process.impulse_response(10)
        assert_almost_equal(ir, 0.9 ** np.arange(10))

    def test_periodogram(self):
        process = ArmaProcess()
        pg = process.periodogram()
        assert_almost_equal(pg[0], np.linspace(0, np.pi, 100, False))
        assert_almost_equal(pg[1], np.sqrt(2 / np.pi) / 2 * np.ones(100))

@pytest.mark.parametrize("d", [0, 1])
@pytest.mark.parametrize("seasonal", [True])
def test_from_estimation(d, seasonal):
    ar = [0.8] if not seasonal else [0.8, 0, 0, 0.2, -0.16]
    ma = [0.4] if not seasonal else [0.4, 0, 0, 0.2, -0.08]
    ap = ArmaProcess.from_coeffs(ar, ma, 500)
    idx = pd.date_range(dt.datetime(1900, 1, 1), periods=500, freq="Q")
    data = ap.generate_sample(500)
    if d == 1:
        data = np.cumsum(data)
    data = pd.Series(data, index=idx)
    seasonal_order = (1, 0, 1, 4) if seasonal else None
    mod = ARIMA(data, order=(1, d, 1), seasonal_order=seasonal_order)
    res = mod.fit()
    ap_from = ArmaProcess.from_estimation(res)
    shape = (5,) if seasonal else (1,)
    assert ap_from.arcoefs.shape == shape
    assert ap_from.macoefs.shape == shape


from decimal import *
getcontext().prec = 1000000
def pow(x, n):
    if n == 1:
        return x
    if n % 2 == 0:
        return pow(x, n//2)**2
    else:
        return pow(x, (n-1)//2)**2 * x

a, b = input().split()
c = Decimal(pow(Decimal(a),Decimal(b)))
print("{:f}".format(c))


import networkx as nx
import os
import matplotlib.pyplot as plt
import random
import numpy as np
import math
import operator
import torch
import scipy.sparse as sp
from torch.utils.data import Dataset
import xlwt

# 计算最大连通子图函数，返回的是连通子图（按大小依次排列）
def connected_component_subgraphs(G):
    for c in nx.connected_components(G):
        yield G.subgraph(c)

# 对拓扑进行随即攻击
def network_attack(G, mode):
    test_G = nx.Graph(G)
    N = nx.number_of_nodes(test_G)
    node_list = list(test_G.nodes())
    point = [x*10 for x in list(range(11))]
    print(point)
    res = []
    # 进行N次攻击，分为随机攻击和恶意攻击两种
    if mode == 0:
        while len(node_list) > 0:
            # graphs代表了所有连通子图
            graphs = list(connected_component_subgraphs(test_G))
            if len(node_list) in point:
                res.append(len(graphs[0]))
            selected_node = random.choice(node_list)
            node_list.remove(selected_node)
            test_G.remove_node(selected_node)
        res.append(0)
    else:
        for i in range(N):
            # graphs代表了所有连通子图
            graphs = list(connected_component_subgraphs(test_G))
            # 删除当前度最高的节点
            degree_list = list(test_G.degree())
            del_node = sorted(degree_list, key=lambda x: (x[1], x[0]), reverse=True)[0][0]
            if i in point:
                res.append(len(graphs[0]))
            test_G.remove_node(del_node)
        res.append(0)
    return res

# 计算鲁棒衡量系数R
def CalRobust(G):
    test_G = nx.Graph(G)
    numerator = 0
    N = nx.number_of_nodes(test_G)
    # test_G用于计算R
    # 进行N次恶意攻击（N为节点总数）
    for i in range(N):
        # graphs代表了所有连通子图
        graphs = list(connected_component_subgraphs(test_G))
        numerator += len(graphs[0])
        # 删除当前度最高的节点
        degreeList = list(test_G.degree())
        delNode = sorted(degreeList, key=lambda x: (x[1], x[0]), reverse=True)[0][0]
        test_G.remove_node(delNode)
    # 进行计算
    return numerator / (N * (N + 1))

# 判断重组边是否已经存在
def has_path(G, a, b):
    edges = list(G.edges())
    if (a, b) in edges or (b, a) in edges:
        return 0
    else:
        return 1

# 返回随即交换完的拓扑结构
def switch_edges(G):
    new_G = nx.Graph(G)
    # print(new_G.edges())
    edges = list(new_G.edges())
    # 随机选择两条边
    rand = np.random.randint(0, len(edges), 2)
    # 选择交换方式
    rand_mode = random.choice([0, 1])
    edge1 = edges[rand[0]]
    edge2 = edges[rand[1]]
    # 待交换的四个点
    a, b, c, d = edge1[0], edge1[1], edge2[0], edge2[1]
    # print('Before------edge:', edge1, edge2, 'degree:', new_G.degree([a, b, c, d]))
    new_edge1, new_edge2 = [], []
    # 如果两边有四点的flag
    repeat_flag = a not in edge2 and b not in edge2
    # 判断重组边是否已经存在的标志
    path_flag = has_path(new_G, a, c) and has_path(new_G, a, d) and has_path(new_G, b, c) and has_path(new_G, b, d)
    if repeat_flag and path_flag:

        new_G.remove_edge(a, b)
        new_G.remove_edge(c, d)
        if rand_mode:
            # new_edge1+=[edge1[0], edge2[0]]
            # new_edge2+=[edge1[1], edge2[1]]
            new_G.add_edge(a, c)
            new_G.add_edge(b, d)
        else:
            # new_edge1+=[edge1[0], edge2[1]]
            # new_edge2+=[edge1[1], edge2[0]]
            new_G.add_edge(a, d)
            new_G.add_edge(b, c)

    # print('After------edge:', new_edge1, new_edge2, 'newG.degree:', new_G.degree([a, b, c, d]))

    return new_G

# 鲁棒性优化函数（模拟退火法）
def OptiTopo_sa(graph_init):
    G = nx.Graph(graph_init)
    print("初始R值", CalRobust(G))
    # 设置初始化温度与最终温度,每个温度下的迭代次数
    T = 1
    Tmin = 1e-3
    k = 10
    while T > Tmin:
        print(T)
        for i in range(k):
            new_G = switch_edges(G)
            R_old = CalRobust(G)
            R_new = CalRobust(new_G)
            if R_new > R_old:
                G = nx.Graph(new_G)
            else:
                p = math.exp(-abs(R_old - R_new) / T)
                r = np.random.uniform(low=0, high=1)
                if r < p:
                    G = nx.Graph(new_G)
        # 降温
        T *= 0.9

    print("结束后的R值", CalRobust(G))
    return G

# 鲁棒性优化函数（爬山算法）
def OptiTopo_hill(graph_init):

    G = nx.Graph(graph_init)
    k = 100
    print("初始R值", CalRobust(G))
    # 设置初始化温度与最终温度,每个温度下的迭代次数
    for i in range(k):
        new_G = switch_edges(G)
        R_old = CalRobust(G)
        R_new = CalRobust(new_G)
        if R_new > R_old:
            G = nx.Graph(new_G)
    print("结束后的R值", CalRobust(G))
    return G

# 加载数据集，返回原始邻接矩阵和特征矩阵  -----------需要填写完整
def load_data(G):
    adj = nx.adjacency_matrix(G)
    features = torch.eye(adj.shape[0])
    return adj, features

# 将一个稀疏矩阵转为稀疏张量矩阵
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
    """Convert a scipy sparse matrix to a torch sparse tensor."""
    sparse_mx = sparse_mx.tocoo().astype(np.float32)
    indices = torch.from_numpy(
        np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
    values = torch.from_numpy(sparse_mx.data)
    shape = torch.Size(sparse_mx.shape)
    return torch.sparse.FloatTensor(indices, values, shape)

# 对邻接矩阵进行预处理，由A变为A~
def preprocess(adj):
    adj = sp.coo_matrix(adj)
    adj_ = adj + sp.eye(adj.shape[0])
    rowsum = np.array(adj_.sum(1))
    degree_mat_inv_sqrt = sp.diags(np.power(rowsum, -0.5).flatten())
    adj_normalized = adj_.dot(degree_mat_inv_sqrt).transpose().dot(degree_mat_inv_sqrt).tocoo()
    return adj_normalized

# 初始拓扑数据集
class InitTopoDataset(Dataset):
    def __init__(self, data_dir):
        self.init_data_dir = data_dir
        self.size = len(os.listdir(data_dir))

    def __len__(self):
        return self.size

    def __getitem__(self, idx):
        data_path = self.init_data_dir
        init_graph = nx.read_gpickle(path=os.path.join(data_path, 'init_{}.gpickle'.format(idx)))
        # 取拓扑的邻接矩阵与特征矩阵
        adj, features = load_data(init_graph)
        # 正则化之后的A~
        adj_norm = preprocess(adj)
        adj_norm = torch.FloatTensor(adj_norm.toarray())
        # 标签A(对角线为1)
        adj_label = adj + sp.eye(adj.shape[0])
        adj_label = torch.FloatTensor(adj_label.toarray())
        adj = torch.FloatTensor(adj.toarray())
        sample = {'adj': adj, 'adj_norm': adj_norm, 'features': features, 'adj_label': adj_label}
        # 返回的样本
        return adj, adj_norm, features, adj_label

# 优化拓扑数据集
class OptiTopoDataset(Dataset):
    def __init__(self, data_dir):
        self.init_data_dir = data_dir
        self.size = len(os.listdir(data_dir))

    def __len__(self):
        return self.size

    def __getitem__(self, idx):
        data_path = self.init_data_dir
        opti_graph = nx.read_gpickle(path=os.path.join(data_path, 'opti_{}.gpickle'.format(idx)))
        # 取拓扑的邻接矩阵与特征矩阵
        adj, features = load_data(opti_graph)
        # 正则化之后的A~
        adj_norm = preprocess(adj)
        adj_norm = torch.FloatTensor(adj_norm.toarray())
        # 标签A(对角线为1)
        adj_label = adj + sp.eye(adj.shape[0])
        adj_label = torch.FloatTensor(adj_label.toarray())
        adj = torch.FloatTensor(adj.toarray())
        sample = {'adj': adj, 'adj_norm': adj_norm, 'features': features, 'adj_label': adj_label}
        # 返回的样本
        return adj, adj_norm, features, adj_label

# 成对拓扑数据集
class PairTopoDataset(Dataset):
    def __init__(self, init_dir, opti_dir):
        self.init_data_dir = init_dir
        self.opti_data_dir = opti_dir
        self.size = len(os.listdir(init_dir))

    def __len__(self):
        return self.size

    def __getitem__(self, idx):
        init_data_path = self.init_data_dir
        opti_data_path = self.opti_data_dir
        init_graph = nx.read_gpickle(path=os.path.join(init_data_path, 'init_{}.gpickle'.format(idx)))
        opti_graph = nx.read_gpickle(path=os.path.join(opti_data_path, 'opti_{}.gpickle'.format(idx)))
        # 取拓扑的邻接矩阵与特征矩阵
        adj_init, features = load_data(init_graph)
        adj_opti, features = load_data(opti_graph)
        # 正则化之后的A~
        adj_norm = preprocess(adj_init)
        adj_norm = torch.FloatTensor(adj_norm.toarray())
        # 标签A(对角线为1)
        adj_label = adj_opti + sp.eye(adj_opti.shape[0])
        adj_label = torch.FloatTensor(adj_label.toarray())
        adj = torch.FloatTensor(adj_opti.toarray())
        sample = {'adj': adj, 'adj_norm': adj_norm, 'features': features, 'adj_label': adj_label}
        # 返回的样本
        return adj, adj_norm, features, adj_label
        return init_graph

# 将数据写入新文件
def data_write(datas):
    f = open('loss_data.txt', 'w')
    for loss in datas:
        f.write(str(loss))
        f.write('\n')
    f.close()

# 文件读取
def read_data(file_name):
    loss = []
    with open(file_name, "r") as f:
        for line in f.readlines():
            line = line.strip('\n')  # 去掉列表中每一个元素的换行符
            loss.append(line)
    return loss

# 矩阵转换
def transfer_mat(adj):
    adj = torch.sigmoid(adj)
    adj = adj.numpy()
    if adj.shape[0] == 100:
        threshold = 0.78
    if adj.shape[0] == 200:
        threshold = 0.80
    if adj.shape[0] == 300:
        threshold = 0.82
    adj[adj < threshold] = 0
    adj[adj >= threshold] = 1
    np.fill_diagonal(adj, 0)
    return adj