# -*- coding: utf-8 -*-
import util_estados
import numpy as npy

def r_file(file_map):
    data = []
    mapa = []
    k = 0
    for linha in file_map:
        if k == 0:
            ad_map = linha
        else:
            data.append(linha.split())
        k += 1
    i = ad_map.split()[0]
    j = ad_map.split()[1]
    k = i
    for lin in range(0, int(i)):
        mapa.append(list(data[lin][0]))

    file_map.close()
    return [i, j, mapa]

#Lê o arquivo contendo mapa à ser analisado
# return [linha, coluna, mapa, estado_inicial, estado_final]
def f_read(file_dir):
    #Lê as informações do arquivo .txt
    #e salva numa mapa
    file_map = open(file_dir, "r")
    dados = r_file(file_map)
    return dados #[linha, coluna, mapa]
#end read_file

def f_write(pi_mapa, pi_dir, q_mapa, q_dir):
    pi_file = open(pi_dir, "w")
    q_file = open(q_dir, "w")
    texto = []
    print(pi_mapa)
    i, j = npy.shape(pi_mapa)
    for col in range(0, int(j)):
        texto = " ".join(str(x) for x in pi_mapa[col]) + '\n'
        pi_file.write(texto)


import re

def uuid4(value):

    rxg = re.compile(
        r"^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$"
    )
    if not rxg.match(value):
        raise ValueError(f"{value} is not a valid UUID V4 string")
    return value

# # Swagger documentation
uuid4.__schema__ = {
    "type": "string",
    "pattern": r"^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
    "description": "UUID V4 string",
}

def task_data(value):
    return value

# task_data.__schema__ = {
#    "type": "object",
#    "additionalProperties": {"$ref": "#/definitions/cisco_nx-os_query"},
# }


import tensorflow as tf
import numpy as np
import argparse
import sys
import os

from tensorflow import keras
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2

def main():
    # parser initialization
    description_msg = "Export tensorflow 2.x models."
    parser = argparse.ArgumentParser(description = description_msg)

    # defining arguments
    parser.add_argument("-m", "--model", type=str, required=True,
                            help = "Tensorflow model.")

    parser.add_argument("-n", "--name", type=str, required=True,
                            help = "Exported model name.")

    # parsing arguments
    parser.parse_args()

    # read arguments from command line
    args = vars(parser.parse_args())

    # load model
    model = keras.models.load_model(args['model'])

    # convert model to concrete_function
    full_model = tf.function(lambda x: model(x))
    concrete_func = full_model.get_concrete_function(
        x = tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))

    # get frozen concrete_function
    frozen_func = convert_variables_to_constants_v2(concrete_func)
    frozen_func.graph.as_graph_def()

    # serialize the frozen graph
    model_export_name = args['name'] + "_frozen_graph"
    tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
        logdir=args['name'],
        name=model_export_name + ".pb",
        as_text=False)

    # frozen graph text representation
    tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
        logdir=args['name'],
        name=model_export_name + ".pbtxt",
        as_text=True)

if __name__ == "__main__":
    main()


# %%
"""
docstring module
"""
class Account:
    """
    classe Account
    """
    # attributs de classe

    # dans python, le premier argument de toute
    # méthodes est toujours l'instance, ici self
    # __init__: initialiseur: permet de renseigner
    # des attributs à l'instanciation
    def __init__(self, _id, balance=100.) -> None:
        # attributs d'instance
        # attribut privé, préfixé par "__"
        self.__id = _id
        # attribut public
        self.balance = balance

if __name__ == "__main__":
    acc = Account(1233434)
    print(acc.balance)
    # print(acc.__id)
    #pas de vrai encapsulation
    print(acc._Account__id)
# %%
class Account:

    def __init__(self, _id, balance=100.) -> None:
        self.__id = _id
        self.__balance = balance

    # méthodes publiques
    def get_balance(self):
        return self.__balance

    def withdraw(self, amount: float):
        if amount > 0:
            self.__update_balance(-amount)

    def deposit(self, amount: float):
        if amount > 0:
            self.__update_balance(amount)

    # méthode privée
    def __update_balance(self, amount: float):
        self.__balance += amount

if __name__ == "__main__":
    # en python on ne répète le premier argument à l'appel => self
    # puisque c'est l'instance acc qui appelle
    acc = Account(1233434)
    acc.deposit(300)
    acc.withdraw(100)
    print(acc.get_balance())
# %%
from typing import Any
# méthodes magiques
class Account:

    def __init__(self, _id, balance=100.) -> None:
        self.__id = _id
        self.__balance = balance

    def __str__(self) -> str:
        return f"id: {self.__id}, balance: {self.__balance}"

    def __add__(self, alt: Any):
        if isinstance(alt, Account):
        # if issubclass()...
            return self.__balance + alt._Account__balance
        elif isinstance(alt, float):
            return self.__balance + alt

acc = Account(1234)
acc2 =  Account(1234, 200.)
print(acc)
# polymorphisme
print(acc + acc2)
print(acc + 50.)
# %%
# itéranle

class IterExp:
    # fixer la condition limite
    def __init__(self, val=2, limit=10) -> None:
        self.__val = val
        self.__limit = limit

    # (re)initialiser le compteur
    # transofmrer un itérable en itérateur
    def __iter__(self):
        self.__cpt = 1
        return self

    # teste la condition limite
    # calcule la valeur de sortie
    # met à jour le compteur
    # ou interrompt l'itération
    def __next__(self):
        if self.__cpt < self.__limit:
            ret = self.__val ** self.__cpt
            self.__cpt += 1
            return ret
        else:
            raise StopIteration

# instanciation itérable
p2 = IterExp()
# transformation en itérateur
it = iter(p2)
# exécution pas à pas
for _ in range(1, 10):
    print(next(it))

for p in p2:
    print(p)
# %%

# générateur en python => itérable à partir d'une fonction
# fonction génératrice
def iter_exp(val=2, limit=10):
    for i in range(1, limit):
        # yield interrompt l'exécution de la fonction
        # jusqu'au prochain appel à next()
        yield val ** i

# objet générateur
# g = iter_exp()

for p in iter_exp():
    print(p)

list(iter_exp())
# %%
# les générateurs sont bcp plus légers
# car ils fournissent les valeurs à l'exécution
from sys import getsizeof
r = range(1000000)
l = list(range(1000000))
getsizeof(r), getsizeof(l)
# %%


from google import auth
from google.google_analytics.ga_model import Property, View

# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.readonly']

# Authenticate and construct service.
service = auth.get_service('analytics', 'v4')

def get_GA_results(config, pageToken=0):
    # Use the Analytics Service Object to query the Core Reporting API
    # for the number of sessions in the past seven days.
    if config.filters == '':

        data = service.reports().batchGet(
                 body={
                   'reportRequests':[
                   {
                       'viewId': config.ids,
                       'dateRanges': [{'startDate': config.start_date, 'endDate': config.end_date}],
                       'metrics': config.metrics,
                       'dimensions': config.dimensions,
                       'orderBys': config.orderBys,
                       'samplingLevel': 'LARGE',
                       'pageSize': 10000,
                       'pageToken': str(pageToken)
                   }]
                 }
               ).execute()
    else:
        data = service.reports().batchGet(
                 body={
                   'reportRequests':[
                   {
                       'viewId': config.ids,
                       'dateRanges': [{'startDate': config.start_date, 'endDate': config.end_date}],
                       'metrics': config.metrics,
                       'dimensions': config.dimensions,
                       'orderBys': config.orderBys,
                       'samplingLevel': 'LARGE',
                       'pageSize': 10000,
                       'pageToken': str(pageToken)
                   }]
                 }
               ).execute()
    return data

def dumpData(View):
    BulkDATA = list()
    nextPageToken = 0
    while nextPageToken != None:
        DATA = get_GA_results(View, nextPageToken)
        try:
            nextPageToken = DATA.get('reports').get('nextPageToken')
        except:
            nextPageToken = None
        BulkDATA.append(DATA)
    return BulkDATA


# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
import json
from pprint import pprint
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.pyplot import MultipleLocator

def obtain_spike_video(spikes, video_filename, **dataDict):
    spike_h = dataDict.get('spike_h')
    spike_w = dataDict.get('spike_w')
    timestamps = spikes.shape[0]

    mov = cv2.VideoWriter(video_filename, cv2.VideoWriter_fourcc(*'MJPG'), 30, (spike_w, spike_h))

    for iSpk in range(timestamps):
        tmpSpk = spikes[iSpk, :, :] * 255
        tmpSpk = cv2.cvtColor(tmpSpk.astype(np.uint8), cv2.COLOR_GRAY2BGR)
        mov.write(tmpSpk)

    mov.release()

def obtain_reconstruction_video(images, video_filename, **dataDict):
    spike_h = dataDict.get('spike_h')
    spike_w = dataDict.get('spike_w')

    img_num = images.shape[0]
    mov = cv2.VideoWriter(video_filename, cv2.VideoWriter_fourcc(*'MJPG'), 30, (spike_w, spike_h))
    for iImg in range(img_num):
        tmp_img = images[iImg, :, :]
        tmp_img = cv2.cvtColor(tmp_img, cv2.COLOR_GRAY2BGR)
        mov.write(tmp_img)

    mov.release()

def obtain_mot_video(spikes, video_filename, res_filepath, **dataDict):
    spike_h = dataDict.get('spike_h')
    spike_w = dataDict.get('spike_w')

    gt_file = dataDict.get('labeled_data_dir')
    gt_boxes = {}
    if gt_file is not None:
        gt_f = open(gt_file, 'r')
        gt_lines = gt_f.readlines()
        for line in gt_lines:
            gt_term = line.split(',')
            time_step = gt_term[0]
            box_id = gt_term[1]
            x = float(gt_term[2])
            y = float(gt_term[3])
            w = float(gt_term[4])
            h = float(gt_term[5])

            if str(time_step) not in gt_boxes:
                gt_boxes[str(time_step)] = []
            bbox = [box_id, x, y, w, h]
            gt_boxes[str(time_step)].append(bbox)

        gt_f.close()

    result_file = res_filepath
    test_boxes = {}
    result_f = open(result_file, 'r')
    result_lines = result_f.readlines()
    color_dict = {}

    for line in result_lines:
        res_box = line.split(',')
        time_step = res_box[0]
        track_id = res_box[1]
        if track_id not in color_dict.keys():
            colors = (np.random.rand(1, 3) * 255).astype(np.uint8)
            color_dict[track_id] = np.squeeze(colors)

        x = float(res_box[2])
        y = float(res_box[3])
        w = float(res_box[4])
        h = float(res_box[5])

        if str(time_step) not in test_boxes:
            test_boxes[str(time_step)] = []

        test_box = [track_id, x, y, w, h]
        test_boxes[str(time_step)].append(test_box)

    result_f.close()

    mov = cv2.VideoWriter(video_filename, cv2.VideoWriter_fourcc(*'MJPG'), 30, (spike_w, spike_h))

    timestamps = spikes.shape[0]
    for t in range(151, timestamps):
    # for t in range(160, 1000):
        tmp_ivs = spikes[t, :, :] * 255
        tmp_ivs = cv2.cvtColor(tmp_ivs.astype(np.uint8), cv2.COLOR_GRAY2BGR)

        if len(gt_boxes) > 0:
            if str(t) in gt_boxes:
                gts = gt_boxes[str(t)]
                gt_num = len(gts)
                for i in range(gt_num):
                    box = gts[i]
                    box_id = box[0]
                    cv2.rectangle(tmp_ivs, (int(box[2]), int(box[1])),
                                  (int(box[2] + box[4]), int(box[1] + box[3])),
                                  (int(255), int(255), int(255)), 2)

        if str(t) in test_boxes:
            test = test_boxes[str(t)]
            test_num = len(test)
            for i in range(test_num):
                box = test[i]
                box_id = box[0]
                colors = color_dict[box_id]
                cv2.rectangle(tmp_ivs, (int(box[2]), int(box[1])),
                              (int(box[2] + box[4]), int(box[1] + box[3])),
                              (int(colors[0]), int(colors[1]), int(colors[2])), 2)

        mov.write(tmp_ivs)

    mov.release()

def obtain_detection_video(spikes, video_filename, res_filepath, **dataDict):
    spike_h = dataDict.get('spike_h')
    spike_w = dataDict.get('spike_w')

    result_file = res_filepath
    test_boxes = {}
    result_f = open(result_file, 'r')
    result_lines = result_f.readlines()
    color_dict = {}

    for line in result_lines:
        res_box = line.split(',')
        time_step = res_box[0]
        track_id = res_box[1]
        if track_id not in color_dict.keys():
            colors = (np.random.rand(1, 3) * 255).astype(np.uint8)
            color_dict[track_id] = np.squeeze(colors)

        x = float(res_box[2])
        y = float(res_box[3])
        w = float(res_box[4])
        h = float(res_box[5])

        if str(time_step) not in test_boxes:
            test_boxes[str(time_step)] = []

        test_box = [track_id, x, y, w, h]
        test_boxes[str(time_step)].append(test_box)

    result_f.close()

    mov = cv2.VideoWriter(video_filename, cv2.VideoWriter_fourcc(*'MJPG'), 30, (spike_w, spike_h))

    block_len = spikes.shape[0]
    for t in range(150, block_len):
        tmp_ivs = spikes[t, :, :] * 255
        tmp_ivs = cv2.cvtColor(tmp_ivs.astype(np.uint8), cv2.COLOR_GRAY2BGR)

        if str(t) in test_boxes:
            test = test_boxes[str(t)]
            test_num = len(test)
            for i in range(test_num):
                box = test[i]
                box_id = box[0]
                colors = color_dict[box_id]
                cv2.rectangle(tmp_ivs, (int(box[2]), int(box[1])),
                              (int(box[2] + box[4]), int(box[1] + box[3])),
                              (int(colors[0]), int(colors[1]), int(colors[2])), 2)

        mov.write(tmp_ivs)

    mov.release()

def vis_trajectory(box_file, json_file, filename, **dataDict):

    spike_h = dataDict.get('spike_h')
    spike_w = dataDict.get('spike_w')
    traj_dict = []
    with open(json_file, 'r') as f:
        for line in f.readlines():
            traj_dict.append(json.loads(line))

    box_file = open(box_file, 'r')
    result_lines = box_file.readlines()
    num_traj = len(traj_dict)

    fig = plt.figure(figsize=[10, 6])
    ax = fig.add_subplot(111, projection='3d')
    min_t = 1000
    max_t = 0

    for tmp_traj in traj_dict:
        tmp_t = np.array(tmp_traj['t'])
        if np.min(tmp_t) < min_t:
            min_t = np.min(tmp_t)
        if np.max(tmp_t) > max_t:
           max_t = np.max(tmp_t)

        tmp_x = spike_w - np.array(tmp_traj['x'])
        tmp_y = np.array(tmp_traj['y'])
        tmp_color = np.array(tmp_traj['color']) / 255.
        ax.plot(tmp_t, tmp_x, tmp_y, color=tmp_color, linewidth=2, label='traj ' + str(tmp_traj['id']))

    ax.legend(loc='best', bbox_to_anchor=(0.7, 0., 0.4, 0.8))
    zoom = [2.2, 0.8, 0.5, 1]
    ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([zoom[0], zoom[1], zoom[2], zoom[3]]))
    ax.set_xlim(min_t, max_t)
    ax.set_ylim(0, spike_w)
    ax.set_zlim(0, spike_h)

    ax.set_xlabel('time', fontsize=15)
    ax.set_ylabel('width', fontsize=15)
    ax.set_zlabel('height', fontsize=15)

    ax.view_init(elev=16, azim=135)
    ax.yaxis.set_major_locator(MultipleLocator(100))
    fig.subplots_adjust(top=1., bottom=0., left=0.2, right=1.)
    # fig.tight_layout()
    plt.savefig(filename, dpi=500, transparent=True)
    # plt.show()


# -------------------------------------------------------------Experiment 1-------------------------------------------------------------
import random
import timeit
import matplotlib.pyplot as plt

for i in range(s):
    total1 = 0
    for _ in range(n):
        L = create_random_list(i, m)

        start = timeit.default_timer()
        insertion_sort(L)
        end = timeit.default_timer()
        total1 += (end - start)

    result.append(total1 / n)

plt.plot(result)
plt.xlabel("List Size")
plt.ylabel("Average Performance Time (seconds)")
plt.show()

# -------------------------------------------------------------Experiment 2-------------------------------------------------------------
# ******************* Bubble sort code *******************

# Traditional Bubble sort
def bubble_sort(L):
    for i in range(len(L)):
        for j in range(len(L) - 1):
            if L[j] > L[j + 1]:
                swap(L, j, j + 1)

def bubble_sort2(L):
    for i in range(len(L)):
        value = L[0]
        for j in range(len(L) - 1):
            if value > L[j + 1]:
                L[j] = L[j + 1]
            else:
                L[j] = value
                value = L[j + 1]
        L[-1] = value

# ******************* Selection sort code *******************

# Traditional Selection sort
def selection_sort(L):
    for i in range(len(L)):
        min_index = find_min_index(L, i)
        swap(L, i, min_index)

def selection_sort2(L):
    for i in range(int(len(L) / 2)):
        min_index = find_min_index(L, i)
        swap(L, i, min_index)

        max_index = find_max_index(L, i)
        swap(L, (-i - 1), max_index)

# Find min before finding max. Hence, n index will be smallest at that iteration. Skip to the next index for max and
#  start at n + 2. Remember to not include sorted max section in list.
def find_max_index(L, n):
    max_index = n + 1
    for i in range(n + 2, len(L) - n):
        if L[i] > L[max_index]:
            max_index = i
    return max_index

def find_min_index(L, n):
    min_index = n
    for i in range(n + 1, len(L)):
        if L[i] < L[min_index]:
            min_index = i
    return min_index

for i in range(s):
    total1 = 0
    total2 = 0
    for _ in range(n):
        L = create_random_list(i, m)
        L2 = L.copy()

        start = timeit.default_timer()
        bubble_sort(L)
        end = timeit.default_timer()
        total1 += end - start

        start = timeit.default_timer()
        bubble_sort2(L2)
        end = timeit.default_timer()
        total2 += end - start

    result.append((1 - (total2 / n) / (total1 / n)) * 100)

plt.plot(result)
plt.xlabel("List Size")
plt.ylabel("Average Percentage Improvement")
plt.show()

# -------------------------------------------------------------Experiment 3-------------------------------------------------------------

n = 20  # runs
s = 10  # Swaps
m = 5000  # max list number

result1 = []
result2 = []
result3 = []
for i in range(s):
    total1 = 0
    total2 = 0
    total3 = 0
    for _ in range(n):  # Total runs
        L = create_near_sorted_list(5000, m, s)
        L2 = L.copy()
        L3 = L.copy()

        start = timeit.default_timer()
        bubble_sort(L)
        end = timeit.default_timer()
        total1 += (end - start)

        start = timeit.default_timer()
        insertion_sort(L2)
        end = timeit.default_timer()
        total2 += (end - start)

        start = timeit.default_timer()
        selection_sort(L3)
        end = timeit.default_timer()
        total3 += (end - start)

    result1.append(total1 / n)
    result2.append(total2 / n)
    result3.append(total3 / n)

x = range(s)
plt.plot(x, result1, label="BubbleSort")
plt.plot(x, result2, label="InsertionSort")
plt.plot(x, result3, label="SelectionSort")
plt.xlabel("Number of Swaps")
plt.ylabel("Average Time")
plt.show()

# -------------------------------------------------------------Experiment 4-------------------------------------------------------------

import matplotlib.pyplot as plt
import autograd.numpy as np
from datetime import datetime

sortingAlgorithms = [quicksort, mergesort, heapsort]
algString = ['quicksort', 'mergesort', 'heapsort']

for s in sortingAlgorithms:
    arrayLength = list(range(10, 10000, 100))  # where we have total of 10000/100 = 100 data points on our x-axis
    time_history = []  # reseting out time_history for each sortng algorithm

    for i in arrayLength:
        # Numbers in our list can be in range of 0 to max(arrayLength)
        mini = 0
        maxi = max(arrayLength)
        # samples to try and take an average
        numberSamples = 20
        # Samples is a vector of size (number of samples); where each row is a array of size 'i' (our current arrayLength)
        samples = np.random.randint(mini, maxi, (numberSamples, i))

        # Doing an avarage on 20 samples and appending the average time took to our time_history
        now = datetime.now()
        out = [s(sample) for sample in samples]
        later = datetime.now()
        time_history.append(((later - now).total_seconds()) / numberSamples)

    # Plotting the data considering x-axis is our n (number of iputs) and y the time for each n to be sorted
    x = arrayLength
    y = time_history
    plt.scatter(x, y)
    plt.plot(x, y)
    plt.title('Graph of %s' % algString[sortingAlgorithms.index(s)])
    plt.xlabel('Length of our array', color='#1C2833')
    plt.ylabel('Time spent to sort (Seconds)', color='#1C2833')
    plt.grid()
    plt.show()

# -------------------------------------------------------------Experiment 5-------------------------------------------------------------

import random

# Create a random list length "length" containing whole numbers between 0 and max_value inclusive
def create_random_list(length, max_value):
    return [random.randint(0, max_value) for _ in range(length)]

# Creates a near sorted list by creating a random list, sorting it, then doing a random number of swaps
def create_near_sorted_list(length, max_value, swaps):
    L = create_random_list(length, max_value)
    L.sort()
    for _ in range(swaps):
        r1 = random.randint(0, length - 1)
        r2 = random.randint(0, length - 1)
        swap(L, r1, r2)
    return L

# I have created this function to make the sorting algorithm code read easier
def swap(L, i, j):
    L[i], L[j] = L[j], L[i]

sortingAlgorithms = [quicksort, mergesort, heapsort]
algString = ['quicksort', 'mergesort', 'heapsort']

for s in sortingAlgorithms:

    time_history = []
    length = 1000
    numberOfTests = 20
    swaps = list(range(1, 500, 10))
    for l in swaps:
        now = datetime.now()
        average_samples = 10
        for i in range(0, average_samples):
            sample = create_near_sorted_list(length, length, l)
            out = s(sample)
        later = datetime.now()
        time_history.append(((later - now).total_seconds()) / average_samples)

    x = swaps
    y = time_history
    plt.scatter(x, y)
    plt.plot(x, y)
    plt.title('Graph of %s' % algString[sortingAlgorithms.index(s)])
    plt.xlabel('Number of swaps', color='#1C2833')
    plt.ylabel('Time spent to sort (Seconds)', color='#1C2833')
    plt.grid()
    plt.show()

# -------------------------------------------------------------Experiment 6-------------------------------------------------------------

# -------------------------------------------------------------Experiment 7-------------------------------------------------------------

# -------------------------------------------------------------Experiment 8-------------------------------------------------------------

# ******************* Insertion sort code *******************
# This is the optimization/improvement we saw in lecture
def insertion_sort2(L):
    for i in range(1, len(L)):
        insert2(L, i)

def insert2(L, i):
    value = L[i]
    while i > 0:
        if L[i - 1] > value:
            L[i] = L[i - 1]
            i -= 1
        else:
            L[i] = value
            return
    L[0] = value

sortingAlgorithms = [insertion_sort2, quicksort, mergesort]
algString = ['insertion sort', 'quicksort', 'mergesort']
arrayLength = list(range(3, 50, 1))  # where we have total of 47 data points on our x-axis
samples = []

# generating the list where each item of the list is a  vector of size (number of samples) for taking the average
for arrLength in arrayLength:
    # Numbers in our list can be in range of 0 to max(arrayLength)
    mini = 0
    maxi = max(arrayLength)
    # samples to try and take an average
    numberSamples = 100
    # Samples is a vector of size (number of samples); where each row is a array of size 'arrLength' (our current arrayLength)
    runs = np.random.randint(mini, maxi, (numberSamples, arrLength))
    samples.append(runs)

for s in sortingAlgorithms:
    time_history = []  # reseting out time_history for each sortng algorithm

    for sample in samples:
        # Doing an avarage on 100 samples and appending the average time took to our time_history
        now = datetime.now()
        out = [s(run) for run in sample]
        later = datetime.now()
        time_history.append(((later - now).total_seconds()) / numberSamples)

    # Plotting the data considering x-axis is our n (number of iputs) and y the time for each n to be sorted
    x = arrayLength
    y = time_history
    plt.scatter(x, y)
    plt.plot(x, y)
    plt.title('Graph of %s' % algString[sortingAlgorithms.index(s)])
    plt.xlabel('Length of our array', color='#1C2833')
    plt.ylabel('Time spent to sort (Seconds)', color='#1C2833')
    plt.grid()
    plt.show()


import lib
from tabulate import tabulate

def func(x):
    f = (4/(1+x**2))
    return f

# append pi vs N in tabular format
data = [(lib.montecarlo(0, 1, N, func)[0],  N)
        for N in range(10, 1001, 10)]
print(tabulate(data, headers=['Pi', 'N']))


import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from scipy import integrate
import os
from mpl_toolkits.mplot3d import Axes3D
# K(s) = Ko * Kr
# Kukl = K/(1+K)
# Ko = 1/(s+1)^3
# Kr = kp + ki/s
# K = (kp + ki/s )* (s+1)^3 = kp*s^3 + (ki + kp + 3)s^2 + 3*s + 1
# K/(1+K) = (s^3 + 3s^2 + (3+kp)*s + (ki + 1))/((kp + 1)*s + ki)

def pi_regulator(kp: float, ki: float, linspaceFinish: float, linspaceSize: int, plot_dest: str, show=True) -> float:
    Tls = np.linspace(0., linspaceFinish, num=linspaceSize)
    num = [0, 0, 0, kp, ki]
    den = [1, 3, 3, (1 + kp), ki]
    K = signal.TransferFunction(num, den)
    p = signal.tf2zpk(num, den)
    print(p)
    if np.ndarray.max((np.real(p[1]))) > 0.0:
        return -1.
    tp, yp = signal.step(K, T=Tls, N=1000)
    eps = yp[-1] - yp
    Q = integrate.simpson(np.power(eps, 2), tp)
    if show:
        plt.figure()
        plt.plot(tp, yp)
        plt.xlabel('Time [s]')
        plt.ylabel('Amplitude')
        plt.title(r"Charakterystyka wyjściowa regulatora PI: $k_p = %f $, $k_i = %f $ " "\n" " $Q = %f $, $\epsilon_{ust} = %f$" % (
            kp, ki, Q, yp[-1]))
        plt.grid()
        plt.savefig(plot_dest)
        plt.draw()
    return yp[-1]

def find_min_by_ki(kp: float, ki: np.ndarray, linspaceFinish: float, linspaceSize: int, plot_dest1: str, plot_dest2: str):
    Tls = np.linspace(0., linspaceFinish, num=linspaceSize)
    Q = []
    epsMin = 10000.0
    i = 0
    # for kps in kp:
    for kis in ki:
        K = signal.TransferFunction(
            [0, 0, 0, kp, kis], [1, 3, 3, (1 + kp), kis])

        tp, yp = signal.step(K, T=Tls, N=1000)

        eps = yp[-1] - yp
        os.system('clear')
        i += 1
        print(i)

        Q.append(integrate.simpson(np.power(eps, 2), tp))
        if Q[-1] < epsMin:
            tpMin = tp
            ypMin = yp
            kiMin = kis
            kpMin = kp
            epsMin = Q[-1]

    print(Q)
    epsIntArr = np.array(Q)
    print(epsIntArr.min())
    plt.figure()
    plt.plot(tpMin, ypMin, label=r"Charakterystyka wyjściowa $k_p=%f$ $k_i = %f$" % (
        kpMin, kiMin))
    plt.xlabel('Time [s]')
    plt.ylabel('Amplitude')
    plt.title(r"Charakterystyka wyjściowa dla minimalnego $Q$")
    plt.grid()
    plt.legend()
    plt.savefig(plot_dest1)
    plt.draw()

    plt.figure()
    plt.plot(ki, epsIntArr)
    plt.xlabel(r'$k_i$')
    plt.ylabel(r'$Q$')
    plt.title(r"Zależność $Q$ od $k_i$ ")
    plt.grid()
    plt.savefig(plot_dest2)
    plt.draw()

l_f = 1500.
l_s = 2500

## ! REGULATOR P : p_i == 0 ! ###

k_ps1 = [0.4, 1.2, 3.0, 4.6, 6.0]
epsis1 = []

k_ps2 = np.arange(0.1, 20., 0.1)
epsis2 = []
k_ps_end = []
for idx, kpp in enumerate(k_ps1):
    epsis1.append(pi_regulator(kpp, 0, l_f, l_s,
                  'lab3_docs/p_regulator_%d.png' % idx))
    if epsis1[-1] == -1.:
        print("Unstable")

for idx, kpp in enumerate(k_ps2):
    p = pi_regulator(kpp, 0, l_f, l_s, "", show=False)
    if p == -1.:
        print("Unstable")
        np.delete(k_ps2, idx)
    else:
        epsis2.append(p)
        k_ps_end.append(kpp)

plt.figure()
plt.plot(k_ps_end, epsis2)
plt.xlabel(r'$k_p$')
plt.ylabel(r'$\epsilon$')
plt.title(r"Zależność $\epsilon$ od $k_p$ dla regulatora P")
plt.grid()
plt.savefig("lab3_docs/p_regulator_esp.png")
plt.draw()

## ! REGULATOR PI ! ###

kp = 0.5

ki_five = [0.1, 0.2, 0.3, 0.4, 0.5]

for idx, kip in enumerate(ki_five):
    pi_regulator(kp, kip, l_f, l_s, 'lab3_docs/pi_regulator_%d.png' % idx)
    print(kip, idx)

ki1 = np.arange(0.01, 5.00, 0.01)
ki2 = np.arange(0.401, 0.500, 0.001)

find_min_by_ki(kp, ki1, l_f, l_s, "lab3_docs/pi_min_1.png", "lab3_docs/pi_Q_1.png")
find_min_by_ki(kp, ki2, l_f, l_s, "lab3_docs/pi_min_2.png", "lab3_docs/pi_Q_2.png")

plt.show()


import pytest

from eth2._utils.bitfield import get_empty_bitfield, set_voted
from eth2.beacon.committee_helpers import (
    get_beacon_proposer_index,
    iterate_committees_at_epoch,
)
from eth2.beacon.constants import (
    FAR_FUTURE_EPOCH,
    GWEI_PER_ETH,
    JUSTIFICATION_BITS_LENGTH,
)
from eth2.beacon.helpers import (
    compute_start_slot_at_epoch,
    get_block_root,
    get_block_root_at_slot,
)
from eth2.beacon.state_machines.forks.serenity.epoch_processing import (
    _bft_threshold_met,
    _determine_new_finalized_epoch,
    _determine_slashing_penalty,
    compute_activation_exit_epoch,
    get_attestation_deltas,
    process_justification_and_finalization,
    process_registry_updates,
    process_slashings,
)
from eth2.beacon.tools.builder.validator import (
    mk_all_pending_attestations_with_full_participation_in_epoch,
)
from eth2.beacon.types.attestation_data import AttestationData
from eth2.beacon.types.checkpoints import Checkpoint
from eth2.beacon.types.pending_attestations import PendingAttestation
from eth2.beacon.types.validators import Validator
from eth2.beacon.typing import Gwei

@pytest.mark.parametrize(
    "total_balance," "attesting_balance," "expected,",
    (
        (1500 * GWEI_PER_ETH, 1000 * GWEI_PER_ETH, True),
        (1500 * GWEI_PER_ETH, 999 * GWEI_PER_ETH, False),
    ),
)
def test_bft_threshold_met(attesting_balance, total_balance, expected):
    assert _bft_threshold_met(attesting_balance, total_balance) == expected

@pytest.mark.parametrize(
    "justification_bits,"
    "previous_justified_epoch,"
    "current_justified_epoch,"
    "expected,",
    (
        # Rule 1
        ((False, True, True, True), 3, 3, 3),
        # Rule 2
        ((False, True, True, False), 4, 4, 4),
        # Rule 3
        ((True, True, True, False), 3, 4, 4),
        # Rule 4
        ((True, True, False, False), 2, 5, 5),
        # No finalize
        ((False, False, False, False), 2, 2, 1),
        ((True, True, True, True), 2, 2, 1),
    ),
)
def test_get_finalized_epoch(
    justification_bits, previous_justified_epoch, current_justified_epoch, expected
):
    current_epoch = 6
    finalized_epoch = 1
    assert (
        _determine_new_finalized_epoch(
            finalized_epoch,
            previous_justified_epoch,
            current_justified_epoch,
            current_epoch,
            justification_bits,
        )
        == expected
    )

def test_justification_without_mock(genesis_state, slots_per_historical_root, config):

    state = genesis_state
    state = process_justification_and_finalization(state, config)
    assert state.justification_bits == (False,) * JUSTIFICATION_BITS_LENGTH

def _convert_to_bitfield(bits):
    data = bits.to_bytes(1, "little")
    length = bits.bit_length()
    bitfield = get_empty_bitfield(length)
    for index in range(length):
        value = (data[index // 8] >> index % 8) % 2
        if value:
            bitfield = set_voted(bitfield, index)
    return (bitfield + (False,) * (4 - length))[0:4]

@pytest.mark.parametrize(
    (
        "current_epoch",
        "current_epoch_justifiable",
        "previous_epoch_justifiable",
        "previous_justified_epoch",
        "current_justified_epoch",
        "justification_bits",
        "finalized_epoch",
        "justified_epoch_after",
        "justification_bits_after",
        "finalized_epoch_after",
    ),
    (
        # No processing on first and second epochs
        (0, True, False, 0, 0, 0b0, 0, 0, 0b0, 0),
        (1, True, True, 0, 0, 0b1, 0, 0, 0b1, 0),
        # Trigger R4 to finalize epoch 1
        (2, True, True, 0, 1, 0b11, 0, 2, 0b111, 1),  # R4 finalize 1
        # Trigger R2 to finalize epoch 1
        # Trigger R3 to finalize epoch 2
        (2, False, True, 0, 1, 0b11, 0, 1, 0b110, 0),  # R2 finalize 0
        (3, False, True, 1, 1, 0b110, 0, 2, 0b1110, 1),  # R2 finalize 1
        (4, True, True, 1, 2, 0b1110, 1, 4, 0b11111, 2),  # R3 finalize 2
        # Trigger R1 to finalize epoch 2
        (2, False, True, 0, 1, 0b11, 0, 1, 0b110, 0),  # R2 finalize 0
        (3, False, True, 1, 1, 0b110, 0, 2, 0b1110, 1),  # R2 finalize 1
        (4, False, True, 1, 2, 0b1110, 1, 3, 0b11110, 1),  # R1 finalize 1
        (5, False, True, 2, 3, 0b11110, 1, 4, 0b111110, 2),  # R1 finalize 2
    ),
)
def test_process_justification_and_finalization(
    genesis_state,
    current_epoch,
    current_epoch_justifiable,
    previous_epoch_justifiable,
    previous_justified_epoch,
    current_justified_epoch,
    justification_bits,
    finalized_epoch,
    justified_epoch_after,
    justification_bits_after,
    finalized_epoch_after,
    config,
):
    justification_bits = _convert_to_bitfield(justification_bits)
    justification_bits_after = _convert_to_bitfield(justification_bits_after)
    previous_epoch = max(current_epoch - 1, 0)
    slot = (current_epoch + 1) * config.SLOTS_PER_EPOCH - 1

    state = genesis_state.mset(
        "slot",
        slot,
        "previous_justified_checkpoint",
        Checkpoint.create(epoch=previous_justified_epoch),
        "current_justified_checkpoint",
        Checkpoint.create(epoch=current_justified_epoch),
        "justification_bits",
        justification_bits,
        "finalized_checkpoint",
        Checkpoint.create(epoch=finalized_epoch),
        "block_roots",
        tuple(
            i.to_bytes(32, "little") for i in range(config.SLOTS_PER_HISTORICAL_ROOT)
        ),
    )

    if previous_epoch_justifiable:
        attestations = mk_all_pending_attestations_with_full_participation_in_epoch(
            state, previous_epoch, config
        )
        state = state.set("previous_epoch_attestations", attestations)

    if current_epoch_justifiable:
        attestations = mk_all_pending_attestations_with_full_participation_in_epoch(
            state, current_epoch, config
        )
        state = state.set("current_epoch_attestations", attestations)

    post_state = process_justification_and_finalization(state, config)

    assert (
        post_state.previous_justified_checkpoint.epoch
        == state.current_justified_checkpoint.epoch
    )
    assert post_state.current_justified_checkpoint.epoch == justified_epoch_after
    assert post_state.justification_bits == justification_bits_after
    assert post_state.finalized_checkpoint.epoch == finalized_epoch_after

# TODO better testing on attestation deltas
@pytest.mark.parametrize(
    (
        "validator_count",
        "slots_per_epoch",
        "min_epochs_to_inactivity_penalty",
        "target_committee_size",
    ),
    [(100, 8, 4, 10)],
)
@pytest.mark.parametrize(
    ("finalized_epoch", "current_slot"),
    [
        (
            4,
            (4 + 1 + 4) * 8,
        ),  # epochs_since_finality <= min_epochs_to_inactivity_penalty
        (
            4,
            (4 + 1 + 5) * 8,
        ),  # epochs_since_finality > min_epochs_to_inactivity_penalty
    ],
)
def test_get_attestation_deltas(
    genesis_state,
    config,
    slots_per_epoch,
    target_committee_size,
    max_committees_per_slot,
    min_attestation_inclusion_delay,
    inactivity_penalty_quotient,
    finalized_epoch,
    current_slot,
    sample_pending_attestation_record_params,
    sample_attestation_data_params,
):

    state = genesis_state.mset(
        "slot",
        current_slot,
        "finalized_checkpoint",
        Checkpoint.create(epoch=finalized_epoch),
    )
    previous_epoch = state.previous_epoch(config.SLOTS_PER_EPOCH)
    has_inactivity_penalty = (
        previous_epoch - finalized_epoch > config.MIN_EPOCHS_TO_INACTIVITY_PENALTY
    )

    indices_to_check = set()

    prev_epoch_attestations = tuple()

    for committee, committee_index, slot in iterate_committees_at_epoch(
        state, previous_epoch, config
    ):
        participants_bitfield = get_empty_bitfield(len(committee))
        for i, index in enumerate(committee):
            indices_to_check.add(index)
            participants_bitfield = set_voted(participants_bitfield, i)
        prev_epoch_attestations += (
            PendingAttestation.create(**sample_pending_attestation_record_params).mset(
                "aggregation_bits",
                participants_bitfield,
                "inclusion_delay",
                min_attestation_inclusion_delay,
                "proposer_index",
                get_beacon_proposer_index(state.set("slot", slot), config),
                "data",
                AttestationData.create(**sample_attestation_data_params).mset(
                    "slot",
                    slot,
                    "index",
                    committee_index,
                    "beacon_block_root",
                    get_block_root_at_slot(
                        state, slot, config.SLOTS_PER_HISTORICAL_ROOT
                    ),
                    "target",
                    Checkpoint.create(
                        epoch=previous_epoch,
                        root=get_block_root(
                            state,
                            previous_epoch,
                            config.SLOTS_PER_EPOCH,
                            config.SLOTS_PER_HISTORICAL_ROOT,
                        ),
                    ),
                ),
            ),
        )
    state = state.set("previous_epoch_attestations", prev_epoch_attestations)

    rewards_received, penalties_received = get_attestation_deltas(state, config)
    if has_inactivity_penalty:
        assert sum(penalties_received) > 0
    else:
        assert sum(penalties_received) == 0
    assert all(reward > 0 for reward in rewards_received)

@pytest.mark.parametrize(
    (
        "validator_count",
        "slots_per_epoch",
        "target_committee_size",
        "max_committees_per_slot",
    ),
    [(10, 10, 9, 10)],
)
def test_process_registry_updates(
    validator_count, genesis_state, config, slots_per_epoch
):
    eligible_index = len(genesis_state.validators)
    activation_index = len(genesis_state.validators) + 1
    exiting_index = len(genesis_state.validators) - 1

    eligible_validator = Validator.create_pending_validator(
        pubkey=b"\x10" * 48,
        withdrawal_credentials=b"\x11" * 32,
        amount=Gwei(32 * GWEI_PER_ETH),
        config=config,
    )
    activating_validator = eligible_validator.set(
        "activation_eligibility_epoch", genesis_state.finalized_checkpoint.epoch
    )

    state = genesis_state.mset(
        "validators",
        genesis_state.validators[:exiting_index]
        + (
            genesis_state.validators[exiting_index].set(
                "effective_balance", config.EJECTION_BALANCE - 1
            ),
        )
        + (eligible_validator, activating_validator),
        "balances",
        genesis_state.balances
        + (config.MAX_EFFECTIVE_BALANCE, config.MAX_EFFECTIVE_BALANCE),
    )

    # handles activations
    post_state = process_registry_updates(state, config)

    # Check if the eligible_validator is eligible
    pre_eligible_validator = state.validators[eligible_index]
    post_eligible_validator = post_state.validators[eligible_index]
    assert pre_eligible_validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH
    assert pre_eligible_validator.activation_epoch == FAR_FUTURE_EPOCH
    assert (
        post_eligible_validator.activation_eligibility_epoch
        == state.current_epoch(slots_per_epoch) + 1
    )

    # Check if the activating_validator is activated
    pre_activation_validator = state.validators[activation_index]
    post_activation_validator = post_state.validators[activation_index]
    assert pre_activation_validator.activation_epoch == FAR_FUTURE_EPOCH
    assert post_activation_validator.activation_eligibility_epoch != FAR_FUTURE_EPOCH
    activation_epoch = compute_activation_exit_epoch(
        state.current_epoch(config.SLOTS_PER_EPOCH), config.MAX_SEED_LOOKAHEAD
    )
    assert post_activation_validator.is_active(activation_epoch)

    # Check if the exiting_validator is exited
    pre_exiting_validator = state.validators[exiting_index]
    post_exiting_validator = post_state.validators[exiting_index]
    assert pre_exiting_validator.exit_epoch == FAR_FUTURE_EPOCH
    assert pre_exiting_validator.withdrawable_epoch == FAR_FUTURE_EPOCH
    assert state.validators[exiting_index].effective_balance <= config.EJECTION_BALANCE
    assert post_exiting_validator.exit_epoch != FAR_FUTURE_EPOCH
    assert post_exiting_validator.withdrawable_epoch != FAR_FUTURE_EPOCH
    assert post_exiting_validator.withdrawable_epoch > post_exiting_validator.exit_epoch

@pytest.mark.parametrize(
    (
        "validator_count",
        "slots_per_epoch",
        "current_epoch",
        "epochs_per_slashings_vector",
    ),
    [(10, 4, 8, 8)],
)
@pytest.mark.parametrize(
    ("total_penalties", "total_balance", "expected_penalty"),
    [
        # total_penalties * 3 is less than total_balance
        (
            32 * 10 ** 9,  # 1 ETH
            (32 * 10 ** 9 * 10),
            # effective_balance * total_penalties * 3 // total_balance
            ((32 * 10 ** 9) // 10 ** 9)
            * (3 * 32 * 10 ** 9)
            // (32 * 10 ** 9 * 10)
            * 10 ** 9,
        ),
        # total_balance is less than total_penalties * 3
        (
            32 * 4 * 10 ** 9,
            (32 * 10 ** 9 * 10),
            # effective_balance * total_balance // total_balance,
            (32 * 10 ** 9)
            // 10 ** 9
            * (32 * 10 ** 9 * 10)
            // (32 * 10 ** 9 * 10)
            * 10 ** 9,
        ),
    ],
)
def test_determine_slashing_penalty(
    genesis_state,
    config,
    slots_per_epoch,
    current_epoch,
    epochs_per_slashings_vector,
    total_penalties,
    total_balance,
    expected_penalty,
):
    state = genesis_state.set(
        "slot", compute_start_slot_at_epoch(current_epoch, slots_per_epoch)
    )
    # if the size of the v-set changes then update the parameters above
    assert len(state.validators) == 10
    validator_index = 0
    penalty = _determine_slashing_penalty(
        total_penalties,
        total_balance,
        state.validators[validator_index].effective_balance,
        config.EFFECTIVE_BALANCE_INCREMENT,
    )
    assert penalty == expected_penalty

@pytest.mark.parametrize(
    (
        "validator_count",
        "slots_per_epoch",
        "current_epoch",
        "epochs_per_slashings_vector",
        "slashings",
        "expected_penalty",
    ),
    [
        (
            10,
            4,
            8,
            8,
            (19 * 10 ** 9, 10 ** 9) + (0,) * 6,
            (32 * 10 ** 9 // 10 ** 9 * 60 * 10 ** 9) // (320 * 10 ** 9) * 10 ** 9,
        )
    ],
)
def test_process_slashings(
    genesis_state,
    config,
    current_epoch,
    slashings,
    slots_per_epoch,
    epochs_per_slashings_vector,
    expected_penalty,
):
    state = genesis_state.mset(
        "slot",
        compute_start_slot_at_epoch(current_epoch, slots_per_epoch),
        "slashings",
        slashings,
    )
    slashing_validator_index = 0
    validator = state.validators[slashing_validator_index].mset(
        "slashed",
        True,
        "withdrawable_epoch",
        current_epoch + epochs_per_slashings_vector // 2,
    )
    state = state.transform(["validators", slashing_validator_index], validator)

    result_state = process_slashings(state, config)
    penalty = (
        state.balances[slashing_validator_index]
        - result_state.balances[slashing_validator_index]
    )
    assert penalty == expected_penalty


import os
import json
import requests
import re

from idt.utils.download_images import download
from idt.utils.remove_corrupt import erase_duplicates
from rich.progress import Progress

__name__ = "flickr_api"

class FlickrApiSearchEngine:
	def __init__(self,data,n_images,folder,resize_method,root_folder,size,api_key):
		self.data = data
		self.n_images = n_images
		self.folder = folder
		self.resize_method = resize_method
		self.root_folder = root_folder
		self.size = size
		self.downloaded_images = 0
		self.dataset_info = []
		self.page = 1
		self.api_key = api_key
		self.search()

	def search(self):
		FLICKR_LINK = 'https://www.flickr.com/services/rest/'

		#headers = {"Ocp-Apim-Subscription-Key" : self.api_key}
		data = self.data.replace(" ", "+")

		if data[0] == "+":
			data  = data[1:]

		params = {
		"method": "flickr.photos.search",
		"api_key": self.api_key,
		"tags": data,
		"format": "json",
		"page": self.page,
		"nojsoncallback": 1
		}
		with Progress() as progress:
			task1 = progress.add_task(f"Downloading [blue]{self.data}[/blue] class...",total=self.n_images)
			while self.downloaded_images < self.n_images:
				response = requests.get(FLICKR_LINK, params=params)
				response.raise_for_status()
				results = response.json()
				results = results['photos']
				if results['total'] == 0:
					progress.update(task1, advance=self.n_images)
					return 0

				self.page += 1

				if not os.path.exists(self.root_folder):
					os.mkdir(self.root_folder)

				target_folder = os.path.join(self.root_folder, self.folder)
				if not os.path.exists(target_folder):
					os.mkdir(target_folder)

				for result in results['photo']:
					try:
						if self.downloaded_images < self.n_images:
							link = f"https://farm{result['farm']}.staticflickr.com/{result['server']}/{result['id']}_{result['secret']}.jpg"
							download(link, self.size,self.root_folder,self.folder, self.resize_method)
							self.downloaded_images += 1
							progress.update(task1, advance=1)
						else:
							break;
					except:
						continue
			self.downloaded_images -= erase_duplicates(target_folder)


# clien_market_parser.py
import requests
from bs4 import BeautifulSoup
import os
import time
import telegram

# 파일의 위치
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

url = f"https://api.telegram.org/bot6502198106:AAGGfbeQ3Uvm0yZkr_xua4__9g_MNBAlrnk/sendMessage"

# req = requests.get('https://arca.live/b/hotdeal')
# req.encoding = 'utf-8'
# html = req.text
# soup = BeautifulSoup(html, 'html.parser')

# posts = soup.select('body > div.root-container > div.content-wrapper.clearfix > article > div > div.article-list > div.list-table.hybrid > div:nth-child(4) > div > div > span.vcol.col-id > span')
# latest = posts[0].text
# print(latest)

# new_Post = soup.select('body > div.root-container > div.content-wrapper.clearfix > article > div > div.article-list > div.list-table.hybrid > div:nth-child(4) > div > a')
# print(new_Post[0].attrs['href'])

#새로운 글이 있느지 확인후 있으면 톡 보내기
while True:
    req = requests.get('https://arca.live/b/hotdeal')
    req.encoding = 'utf-8'

    html = req.text
    soup = BeautifulSoup(html, 'html.parser')
    posts = soup.select('body > div.root-container > div.content-wrapper.clearfix > article > div > div.article-list > div.list-table.hybrid > div:nth-child(4) > div > div > span.vcol.col-id > span')
    latest = posts[0].text
    new_Post = soup.select('body > div.root-container > div.content-wrapper.clearfix > article > div > div.article-list > div.list-table.hybrid > div:nth-child(4) > div > a')

    params = {
    'chat_id': -4079462539,
    'text': 'https://arca.live/'+new_Post[0].attrs['href'],
    }
    with open(os.path.join(BASE_DIR, 'latest.txt'), 'r+') as f_read:
        before = f_read.readline()
        if before != latest:
            r = requests.get(url, params=params)
        f_read.close()

    with open(os.path.join(BASE_DIR, 'latest.txt'), 'w+') as f_write:
        f_write.write(latest)
        f_write.close()

    time.sleep(600)


import sys
sys.stdin=open("input.txt")

for test in range(int(input())):
    n,m=map(int,input().split())
    lst=list(map(int,input().split()))
    new=[] # 화덕
    number=[]
    num=[]

    for i in range(1,m+1):
        num.append(i) # 번호표 빼주는곳
    for j in range(n):
        b=num.pop(0)
        number.append(b)

    for i in range(n):
        a=lst.pop(0)
        new.append(a)

    while len(new)>1:
        new[0]=new[0]//2
        if new[0]==0:
            new.pop(new[0])
            number.pop(0)
            if lst:
                new.append(lst[0])
                lst.pop(0)
                number.append(num[0])
                num.pop(0)
        else:
            first=new.pop(0)
            new.append(first)
            second=number.pop(0)
            number.append(second)

    print("#{} {}".format(test+1,number[0]))

Python/SW Expert Academy/Programming Intermediate/Queue/5099. 피자 굽기.py


import random

def create_board(size):
    '''int->list (of str)
       Precondition: size is even positive integer between 2 and 52
    '''
    board = [None]*size

    letter='A'
    for i in range(len(board)//2):
          board[i]=letter
          board[i+len(board)//2 ]=board[i]
          letter=chr(ord(letter)+1)
    random.shuffle(board)
    return board

def print_board(a):
    '''(list of str)->None
       Prints the current board in a nicely formated way
    '''
    for i in range(len(a)):
        print('{0:4}'.format(a[i]), end=' ')
    print()
    for i in range(len(a)):
        print('{0:4}'.format(str(i+1)), end=' ')

def wait_for_player():
    '''(None)->None
    Pauses the program until the user presses enter
    '''
    try:
        input("Press enter to continue ")
    except SyntaxError:
        pass

def play_game(board):
    '''(list of str)->None'''

    # The following line of code creates a list indicating what locations are paired, i.e., discovered
    # At the begining none are, so default initializaiton to False is ok
    # You may find this useful
    discovered=[False]*len(board)

   # YOUR CODE GOES HERE
   # this is the funciton that plays the game

# MAIN

size=14
# YOUR CODE GOES HERE TOO
# HERE YOU OBTAIN THE SIZE OF THE BOARD THE PLAYER WANTS TO PLAY WITH
# once you are done remove size=14 above. I just did that so that this partial program should run

# this creates the board for you of the given size
board=create_board(size)

# this calls your play_game function that plays the game
play_game(board)


#importing requests and working on the script to
import requests

url_of_poke = 'https://pokeapi.co/api/v2/pokemon/'

def searching_for_poke_ability(Search=''):

    Search = str(Search).strip().lower()

    print ('\n',f'Searching for the Pokemon Ability with the id as inputed {Search}...........', '\n', end='')

    header = {'accept' : 'application/json'}

    #Searching the url of the poke in order to collect it's name and ability through the id as inputed by the user.
    searching_the_url = url_of_poke + Search

    msg_response = requests.get(searching_the_url, headers=header)

    if msg_response.status_code == requests.codes.ok:
        print('\n','Congratulations, the data has been fetched successfully', '\n')
        return msg_response.json()
    else:
        print('\n','Failure, No such data is available','\n')
        print('\n',f'Error Code : {msg_response.status_code}, Reason For Error : {msg_response.reason}', '\n')


print('Hello World')
a = 8
b = 8
print (a+b)
print (a)
if a > b:
    print("Чокопай")
elif a == b:
    print("Печенье")
else:
    print("Конфета")
d = 18
c = 7
if d > c + 10:
    print("Шоколад")
name = "Дильназ"
height = 1.63
weight = 36
bmi = weight / (height * height )
print ("Индекс массы тела: " + str(bmi))
if bmi < 25:
    print("y " + name + " нет лишнего веса")
else:
    print("y " + name + "есть лишний вес")
name = 'Серикова Асем Куанышевна'
age = 18
city = 'Атырау'
group = 'АиУ-19 р/о'
print("ФИО: " +name+ ". Возраст: " +str(age)+ " лет. " "Город: "+city+ ". Группа: " +group+".")

name = 'Серикова Асем Куанышевна'
age = 18
city = 'Атырау'
group = 'АиУ-19 р/о'
print("\nФИО: " +name+ ". \nВозраст: " +str(age)+ " лет. \nГород: "+city+ ". \nГруппа: " +group+".")


from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler
from mycroft.util.log import LOG
from mycroft.util.parse import match_one
import requests

class ButtonValidator:
    def __init__(self, values, threshold):
        self.values = values
        self.threshold = threshold

    def validate(self, utterance):
        best = match_one(utterance, self.values)
        return best[1] > self.threshold

class RasaSkill(MycroftSkill):
    button_match_threshold = 0.6
    button_attempts_max = 3

    # The constructor of the skill, which calls MycroftSkill's constructor
    def __init__(self):
        super(RasaSkill, self).__init__(name="RasaSkill")
        self.conversation_active = False
        self.rasa_host = "http://localhost:5005/"
        self.append_endpoint = (
            self.rasa_host + "conversations/mycroft_user/messages?include_events=NONE"
        )
        self.predict_endpoint = self.rasa_host + "conversations/mycroft_user/predict"
        self.action_endpoint = (
            self.rasa_host + "conversations/mycroft_user/execute?include_events=APPLIED"
        )

    @intent_handler(IntentBuilder("").require("Chatwithrasa"))
    def handle_talk_to_rasa_intent(self, message):
        response = self.get_response("connecting.to.rasa")
        self.conversation_active = True
        while response is not None and self.conversation_active:
            messages = self.get_rasa_response(response)
            if len(messages) > 1:
                for rasa_message in messages[:-1]:
                    self.speak(rasa_message)
            if len(messages) == 0:
                messages = ["no response from rasa"]
            response = self.handle_final_output(messages[-1])

        self.speak("disconnecting from rasa")

    def handle_final_output(self, message, attempts=0):
        if attempts > self.button_attempts_max:
            return None
        if attempts > 0:
            self.speak("You can also say Option 1, Option 2, etc")
        # if we have buttons, handle them
        if "buttons" in message:
            # speak the text on the message
            self.speak(message["text"])

            buttons = message["buttons"]
            button_titles = [b["title"] for b in buttons]

            if len(buttons) == 1:
                # if we have a single button, assume it's a confirmation
                self.speak("To confirm, say")
            elif len(buttons) > 1:
                # if we have many buttons, list the options
                self.speak("You can say")
            # read out our button title options, separated by "Or"
            for button in buttons[:-1]:
                self.speak(button["title"])
                self.speak("Or")
            # read the final button option, and await a response
            # that is in the list of what we just returned OR
            # is "option 1", "option 2", ..., "option N"  N
            option_list = [f"option {i+1}" for i in range(len(buttons))]
            validation_options = button_titles + option_list
            button_validator = ButtonValidator(
                validation_options, self.button_match_threshold
            )
            print(f"trying attempt {attempts}")
            response = self.get_response(
                button_titles[-1],
                validator=button_validator.validate,
                num_retries=0,
                on_fail=self.on_failed_button,
            )
            print(f"response {response}")
            # if response is not None, we passed the validator
            if response is not None:
                best_match = match_one(response, validation_options)
                response = best_match[0]
                best_ind = validation_options.index(response)
                if best_ind >= len(buttons):
                    best_ind = best_ind % len(buttons)
                response = buttons[best_ind]["payload"]
                return response
            return self.handle_final_output(message, attempts=attempts + 1)
        # if we don't have buttons, just get_response
        return self.get_response(message["text"], num_retries=0)

    def on_failed_button(self, utt):
        return "Sorry I didn't catch that."

    def get_rasa_response(self, utterance):
        if "stop" in utterance.lower():
            self.conversation_active = False
            return [{"text": "goodbye from rasa"}]
        messages = self.hit_rasa(utterance)
        print(messages)
        return messages

    def stop(self):
        self.conversation_active = False

    def hit_rasa(self, utterance):
        # send our utterance to rasa
        print(f"sending {utterance} to {self.append_endpoint}")
        append_response = requests.post(
            self.append_endpoint, json={"text": utterance, "sender": "user"}
        )
        # run actions until we get an action_listen response
        action = None
        outputs = []
        while action != "action_listen":
            response = requests.post(self.predict_endpoint).json()
            # send the most likely action to the execute endpoint
            action = response["scores"][0]["action"]
            self.log.debug(action)
            print(f"sending {action} to {self.action_endpoint}")
            run_action = requests.post(
                self.action_endpoint, json={"name": action}
            ).json()
            outputs += [m for m in run_action["messages"]]
        self.log.debug(outputs)
        return outputs

def create_skill():
    return RasaSkill()


import cv2 as cv
import numpy as np

class ImageManipulation:

    def edge_detection(self, img): # Method to get the edges
        image = img.copy()
        # sourced from https://docs.opencv.org/3.1.0/d4/d13/tutorial_py_filtering.html
        kernel = np.ones((3, 5), np.float32) / 25
        image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
        image = cv.filter2D(image, -1, kernel)  # Blurs the image
        image = cv.Canny(image, 50, 200, True) # Creates edges
        return image

    def fill_image(self, image):
# Code sourced for this method from https://stackoverflow.com/questions/45135950/how-to-fill-an-image-from-bottom-side-until-an-edge-is-detected-using-opencv
        height, width = image.shape[:2]
        max_row_index = height - np.argmax(image[::-1], axis=0) # Inverts the edges from top to bottom
        row_index = np.indices((height,width))[0]
        after_edge = row_index >= max_row_index # Sets edges to fill to
        filled_image = np.zeros((height, width))
        filled_image[after_edge] = 255  # fills the image
# erode code sourced from https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html
        kernel = np.ones((5,5), np.uint8)
        filled_image = cv.erode(filled_image, kernel, iterations=1) # Erodes the image to remove small unusable lines for the robot
        return filled_image
cap = cv.VideoCapture(0)

while True:
    status, img = cap.read()
    #img = cv.imread('image.png')
    manipulation = ImageManipulation()
    image = manipulation.edge_detection(img.copy())
    image = manipulation.fill_image(image)
    cv.imshow("Video", image)
    k = cv.waitKey(1)
    if k == 27:
        break
cv.destroyAllWindows()


from glob import glob
from PyPDF2 import PdfReader

data_path = 'data/*'
data_files = glob(data_path)

def parsePDF(file):
    raw_text = ''
    reader = PdfReader(file)
    for i, page in enumerate(reader.pages):
        text = page.extract_text()
        if text:
            raw_text += text
    return raw_text


import unittest

import tweepy

from settings import consumer_key, consumer_secret, key, secret
from fetch_mentions import GetMentions

class AuthenticationTestCase(unittest.TestCase):
    """
    Test Cases for twitter authentication
    """

    def authenticate(self, *args):
        """
        Authenticate twitter credentials
        """
        auth = tweepy.OAuthHandler(args[0], args[1])
        auth.set_access_token(args[2], args[3])
        api = tweepy.API(auth)
        return api

    def test_twitter_successful_authentication(self):
        """
        Test Case for successful twitter authentication
        """
        obj = GetMentions()
        obj.authenticate()
        self.assertIsNot(False, obj.verify_credentials())

    def test_twitter_consumer_key_failure(self):
        """
        Test Case for failed twitter authentication when provided with wrong consumer key
        """
        wrong_consumer_key = "wrong key"
        api = self.authenticate(wrong_consumer_key, consumer_secret, key, secret)
        obj = GetMentions()
        obj.api = api
        self.assertFalse(obj.verify_credentials())

    def test_twitter_consumer__secret_key_failure(self):
        """
        Test Case for failed twitter authentication when provided with wrong consumer secret key
        """
        wrong_consumer_secret = "wrong key"
        api = self.authenticate(consumer_key, wrong_consumer_secret, key, secret)
        obj = GetMentions()
        obj.api = api
        self.assertFalse(obj.verify_credentials())

    def test_twitter_access_token_failure(self):
        """
        Test Case for failed twitter authentication when provided with wrong token
        """
        wrong_key = "wrong key"
        api = self.authenticate(consumer_key, consumer_secret, wrong_key, secret)
        obj = GetMentions()
        obj.api = api
        self.assertFalse(obj.verify_credentials())

    def test_twitter_access_token_secret_key_failure(self):
        """
        Test Case for failed twitter authentication when provided with wrong token secret key
        """
        wrong_secret_key = "wrong key"
        api = self.authenticate(consumer_key, consumer_secret, key, wrong_secret_key)
        obj = GetMentions()
        obj.api = api
        self.assertFalse(obj.verify_credentials())

if __name__ == '__main__':
    unittest.main()


"""
Module to set up run time parameters for Clawpack.

The values set in the function setrun are then written out to data files
that will be read in by the Fortran code.

"""

from __future__ import absolute_import
from __future__ import print_function
import os
import numpy as np
#CC=os.environ['CC']

try:
    CLAW = os.environ['CLAW']
except:
    raise Exception("*** Must first set CLAW enviornment variable")

# Scratch directory for storing topo and dtopo files:
#scratch_dir = os.path.join(CLAW, 'geoclaw', 'scratch')

#-----------------------------------------------
# Set these parameters for adjoint flagging....

# location of output from computing adjoint:
adjoint_output = os.path.abspath('../adjoint_CrescentCity_26hrs/_output')
print('Will flag using adjoint solution from  %s' % adjoint_output)

# Time period of interest: doing a little test
t1 = 14.0*3600.
t2 = 26.0*3600.

# tolerance for adjoint flagging:
adjoint_flag_tolerance = 7e-6
#-----------------------------------------------

#------------------------------
def setrun(claw_pkg='geoclaw'):
#------------------------------

    """
    Define the parameters used for running Clawpack.

    INPUT:
        claw_pkg expected to be "geoclaw" for this setrun.

    OUTPUT:
        rundata - object of class ClawRunData

    """

    from clawpack.clawutil import data

    assert claw_pkg.lower() == 'geoclaw',  "Expected claw_pkg = 'geoclaw'"

    num_dim = 2
    rundata = data.ClawRunData(claw_pkg, num_dim)

    #------------------------------------------------------------------
    # Problem-specific parameters to be written to setprob.data:
    #------------------------------------------------------------------

    #probdata = rundata.new_UserData(name='probdata',fname='setprob.data')

    #------------------------------------------------------------------
    # GeoClaw specific parameters:
    #------------------------------------------------------------------
    rundata = setgeo(rundata)

    #------------------------------------------------------------------
    # Standard Clawpack parameters to be written to claw.data:
    #   (or to amr2ez.data for AMR)
    #------------------------------------------------------------------
    clawdata = rundata.clawdata  # initialized when rundata instantiated

    # Set single grid parameters first.
    # See below for AMR parameters.

    # ---------------
    # Spatial domain:
    # ---------------

    # Number of space dimensions:
    clawdata.num_dim = num_dim

    # Lower and upper edge of computational domain:
    #clawdata.lower[0] = -240.0      # west longitude
    #clawdata.upper[0] = -100.0       # east longitude
    #clawdata.lower[1] = -41.0       # south latitude
    #clawdata.upper[1] = 65.0         # north latitude

    ### for chile, consider -48 as southern bdry and -66 as eastern
    ###          ,         -240, -66; -47, 65.
    ###          , delta long = 87; delta lat = 56
    clawdata.lower[0] = -240.0      # west longitude
    clawdata.upper[0] = -66.0       # east longitude
    clawdata.lower[1] = -47.0       # south latitude
    clawdata.upper[1] = 65.0         # north latitude

    # Number of grid cells: Coarsest grid 2 degrees
    clawdata.num_cells[0] = 87
    clawdata.num_cells[1] = 56

    # ---------------
    # Size of system:
    # ---------------

    # Number of equations in the system:
    clawdata.num_eqn = 3

    # Number of auxiliary variables in the aux array (initialized in setaux)
    clawdata.num_aux = 3

    # Index of aux array corresponding to capacity function, if there is one:
    clawdata.capa_index = 2

    # -------------
    # Initial time:
    # -------------

    clawdata.t0 = 0.0

    # Restart from checkpoint file of a previous run?
    # If restarting, t0 above should be from original run, and the
    # restart_file 'fort.chkNNNNN' specified below should be in
    # the OUTDIR indicated in Makefile.

    clawdata.restart = False              # True to restart from prior results
    clawdata.restart_file = 'fort.chk00096'  # File to use for restart data

    # -------------
    # Output times:
    #--------------

    # Specify at what times the results should be written to fort.q files.
    # Note that the time integration stops after the final output time.
    # The solution at initial time t0 is always written in addition.

    clawdata.output_style = 2
    #clawdata.output_style = 1

    if clawdata.output_style==1:
        # Output nout frames at equally spaced times up to tfinal:
        clawdata.num_output_times = 84
        clawdata.tfinal = 16*3600.
        clawdata.output_t0 = True  # output at initial (or restart) time?

    elif clawdata.output_style == 2:
        # Specify a list of output times.
        clawdata.output_times = np.linspace(1,26,51) * 3600.
        #clawdata.output_times = np.linspace(0,3,7) * 3600.

    elif clawdata.output_style == 3:
        # Output every iout timesteps with a total of ntot time steps:
        clawdata.output_step_interval = 1
        clawdata.total_steps = 3
        clawdata.output_t0 = True

    #clawdata.output_format = 'ascii'      # 'ascii' or 'netcdf'
    clawdata.output_format = 'binary'      # 'ascii' or 'netcdf'

    clawdata.output_q_components = 'all'   # need all
    clawdata.output_aux_components = 'none'  # eta=h+B is in q
    clawdata.output_aux_onlyonce = False    # output aux arrays each frame

    # ---------------------------------------------------
    # Verbosity of messages to screen during integration:
    # ---------------------------------------------------

    # The current t, dt, and cfl will be printed every time step
    # at AMR levels <= verbosity.  Set verbosity = 0 for no printing.
    #   (E.g. verbosity == 2 means print only on levels 1 and 2.)
    clawdata.verbosity = 1

    # --------------
    # Time stepping:
    # --------------

    # if dt_variable==1: variable time steps used based on cfl_desired,
    # if dt_variable==0: fixed time steps dt = dt_initial will always be used.
    clawdata.dt_variable = True

    # Initial time step for variable dt.
    # If dt_variable==0 then dt=dt_initial for all steps:
    clawdata.dt_initial = 0.2

    # Max time step to be allowed if variable dt used:
    clawdata.dt_max = 1e+99

    # Desired Courant number if variable dt used, and max to allow without
    # retaking step with a smaller dt:
    clawdata.cfl_desired = 0.75
    clawdata.cfl_max = 1.0

    # Maximum number of time steps to allow between output times:
    clawdata.steps_max = 5000

    # ------------------
    # Method to be used:
    # ------------------

    # Order of accuracy:  1 => Godunov,  2 => Lax-Wendroff plus limiters
    clawdata.order = 2

    # Use dimensional splitting? (not yet available for AMR)
    clawdata.dimensional_split = 'unsplit'

    # For unsplit method, transverse_waves can be
    #  0 or 'none'      ==> donor cell (only normal solver used)
    #  1 or 'increment' ==> corner transport of waves
    #  2 or 'all'       ==> corner transport of 2nd order corrections too
    clawdata.transverse_waves = 2

    # Number of waves in the Riemann solution:
    clawdata.num_waves = 3

    # List of limiters to use for each wave family:
    # Required:  len(limiter) == num_waves
    # Some options:
    #   0 or 'none'     ==> no limiter (Lax-Wendroff)
    #   1 or 'minmod'   ==> minmod
    #   2 or 'superbee' ==> superbee
    #   3 or 'mc'       ==> MC limiter
    #   4 or 'vanleer'  ==> van Leer
    clawdata.limiter = ['mc', 'mc', 'mc']

    clawdata.use_fwaves = True    # True ==> use f-wave version of algorithms

    # Source terms splitting:
    #   src_split == 0 or 'none'    ==> no source term (src routine never called)
    #   src_split == 1 or 'godunov' ==> Godunov (1st order) splitting used,
    #   src_split == 2 or 'strang'  ==> Strang (2nd order) splitting used,  not recommended.
    clawdata.source_split = 'godunov'

    # --------------------
    # Boundary conditions:
    # --------------------

    # Number of ghost cells (usually 2)
    clawdata.num_ghost = 2

    # Choice of BCs at xlower and xupper:
    #   0 => user specified (must modify bcN.f to use this option)
    #   1 => extrapolation (non-reflecting outflow)
    #   2 => periodic (must specify this at both boundaries)
    #   3 => solid wall for systems where q(2) is normal velocity

    clawdata.bc_lower[0] = 'extrap'
    clawdata.bc_upper[0] = 'extrap'

    clawdata.bc_lower[1] = 'extrap'
    clawdata.bc_upper[1] = 'extrap'

    # --------------
    # Checkpointing:
    # --------------

    # Specify when checkpoint files should be created that can be
    # used to restart a computation.

    clawdata.checkpt_style = 0

    if clawdata.checkpt_style == 0:
        # Do not checkpoint at all
        pass

    elif clawdata.checkpt_style == 1:
        # Checkpoint only at tfinal.
        pass

    elif clawdata.checkpt_style == 2:
        # Specify a list of checkpoint times.
        clawdata.checkpt_times = [0.1,0.15]

    elif clawdata.checkpt_style == 3:
        # Checkpoint every checkpt_interval timesteps (on Level 1)
        # and at the final time.
        clawdata.checkpt_interval = 5

    # ---------------
    # AMR parameters:
    # ---------------
    amrdata = rundata.amrdata

    # max number of refinement levels:
    amrdata.amr_levels_max = 8

    # List of refinement ratios at each level (length at least mxnest-1)

    #1sec
    # 2 degree, 24', 4', 1', 12", 6", 1"  for 7 levels.
    #amrdata.refinement_ratios_x = [5, 6, 4, 5, 2, 6]
    #amrdata.refinement_ratios_y = [5, 6, 4, 5, 2, 6]
    #amrdata.refinement_ratios_t = [5, 6, 4, 5, 2, 6]

    #2sec
    # 2 degree, 24', 4', 1', 12", 6", 2"  for 7 levels.
    #amrdata.refinement_ratios_x = [5, 6, 4, 5, 2, 3]
    #amrdata.refinement_ratios_y = [5, 6, 4, 5, 2, 3]
    #amrdata.refinement_ratios_t = [5, 6, 4, 5, 2, 3]

    #1/3sec, trying one with 8 levels, including 6sec region
    # 2 degree, 24', 4', 1', 12", 6", 1", 1/3" for 8 levels.
    # level 5 is still 12". level 6 is 6", level 7 is 1 sec, and level 8 is 1/3
    amrdata.refinement_ratios_x = [5, 6, 4, 5, 2, 6, 3]
    amrdata.refinement_ratios_y = [5, 6, 4, 5, 2, 6, 3]
    amrdata.refinement_ratios_t = [5, 6, 4, 5, 2, 6, 3]

    # Specify type of each aux variable in amrdata.auxtype.
    # This must be a list of length maux, each element of which is one of:
    #   'center',  'capacity', 'xleft', or 'yleft'  (see documentation).

    amrdata.aux_type = ['center','capacity','yleft']

    # Flag using refinement routine flag2refine rather than richardson error
    amrdata.flag_richardson = False    # use Richardson?
    amrdata.flag2refine = True

    # steps to take on each level L between regriddings of level L+1:
    amrdata.regrid_interval = 3

    # width of buffer zone around flagged points:
    # (typically the same as regrid_interval so waves don't escape):
    amrdata.regrid_buffer_width  = 2

    # clustering alg. cutoff for (# flagged pts) / (total # of cells refined)
    # (closer to 1.0 => more small grids may be needed to cover flagged cells)
    amrdata.clustering_cutoff = 0.700000

    # print info about each regridding up to this level:
    amrdata.verbosity_regrid = 0

    #  ----- For developers -----
    # Toggle debugging print statements:
    amrdata.dprint = False      # print domain flags
    amrdata.eprint = False      # print err est flags
    amrdata.edebug = False      # even more err est flags
    amrdata.gprint = False      # grid bisection/clustering
    amrdata.nprint = False      # proper nesting output
    amrdata.pprint = False      # proj. of tagged points
    amrdata.rprint = False      # print regridding summary
    amrdata.sprint = False      # space/memory output
    amrdata.tprint = False      # time step reporting each level
    amrdata.uprint = False      # update/upbnd reporting

    # More AMR parameters can be set -- see the defaults in pyclaw/data.py

    # ---------------------------------------------------------------
    #1sec
    # 2 degree, 24', 4', 1', 12", 1" 6 levels.
    # --------------------------------------------------------------
    rundata.regiondata.regions = []
    # to specify regions of refinement append lines of the form
    #  [minlevel,maxlevel,t1,t2,x1,x2,y1,y2]

    # Ocean refinement from Chile, using adjoint, below is whole domain
    rundata.regiondata.regions.append([1, 5, 0., 1e9, -240,-66,-47,65])
    #rundata.regiondata.regions.append([1, 4, 13.0*3600., 1e9, -160,-120,34,62])
    #rundata.regiondata.regions.append([1, 4, 10.5*3600., 1e9, -160,-110,18,34])

    # Chile source:
    # Note, we are using 1 minute around the source. It may not be necessary.
    ### domain,         -240, -66; -47, 65.
    ### pink deformation has region:  -94.65, -67.9833; -46.294, -24.8641
    #rundata.regiondata.regions.append([4, 4, 0., 4.0*3600, -96.0,-68.0,-47.0,-24.0])
    # above region is from Loyce. Trying a smaller source region:
    rundata.regiondata.regions.append([4, 4, 0., 4.0*3600, -80.0,-68.0,-40.0,-20.0])

    #Port Orford   (lat: 42degrees, 44.3min, long: 124degrees, 29.9min)
    #Crescent City (lat: 41degrees, 44.7min, long: 124degrees, 11.1min)
    #Arena Cove    (lat: 38degrees, 54.9min, long: 123degrees, 42.7min)
    #San Luis      (lat: 35degrees, 10.1min, long: 120degrees, 45.2min)

    #Make a new bigger A grid:
    #rundata.regiondata.regions.append([1, 4, 13.0*3600., 1e9, -129,-123,38,46])

    #Diego's A grid becomes the B (12sec) grid:
    #rundata.regiondata.regions.append([4, 4, 14.0*3600., 1e9, -126.995,-123.535,40.515,44.495])
    #rundata.regiondata.regions.append([1, 5, 14.0*3600., 1e9, -126.995,-123.535,40.515,44.495])

    #Diego's B grid becomes a 6sec grid:
    rundata.regiondata.regions.append([1, 6, 14.5*3600., 1e9, -124.6,-124.05,41.5017,41.9983])

    #For the 1sec and 2sec runs, match Diego C grid as below for 7,7
    #For the UW topo, use this one for the 1sec as well when doing 1/3
    #Too much land
    #rundata.regiondata.regions.append([7, 7, 14.5*3600., 1e9, -124.2345, -124.1434,41.7168,41.7829])

    #For the 1/3 run, make region 6 match the 1/3 data with 1sec computation
    #Use this even for UW 1/3 run
    rundata.regiondata.regions.append([1, 7, 14.5*3600., 1e9, -124.2345, -124.1595,41.7168,41.76948])

    #Trying a 1/3 grid close in  (our D grid)
    rundata.regiondata.regions.append([1, 8, 14.5*3600., 1e9, -124.202, -124.180,41.733,41.752])

    # ---------------
    # Gauges:
    # ---------------
    rundata.gaugedata.gauges = []
    # for gauges append lines of the form  [gaugeno, x, y, t1, t2]

    #from Diego file

    rundata.gaugedata.gauges.append([2, -124.18397, 41.74512, 14.5*3600., 1.e10])

    #------------------------------------------------------------------
    # Adjoint specific data:
    #------------------------------------------------------------------
    # Do this last since it resets some parameters such as num_aux
    # as needed for adjoint flagging.
    rundata = setadjoint(rundata)

    return rundata
    # end of function setrun
    # ----------------------

#-------------------
def setgeo(rundata):
#-------------------
    """
    Set GeoClaw specific runtime parameters.
    For documentation see ....
    """

    try:
        geo_data = rundata.geo_data
    except:
        print("*** Error, this rundata has no geo_data attribute")
        raise AttributeError("Missing geo_data attribute")

    # == Physics ==
    geo_data.gravity = 9.81
    geo_data.coordinate_system = 2
    geo_data.earth_radius = 6367.5e3

    # == Forcing Options
    geo_data.coriolis_forcing = False

    # == Algorithm and Initial Conditions ==
    geo_data.sea_level = 0 # -1.5
    geo_data.dry_tolerance = 1.e-3
    geo_data.friction_forcing = True
    geo_data.manning_coefficient =.025
    geo_data.friction_depth = 1e6

    # Refinement settings
    refinement_data = rundata.refinement_data
    refinement_data.variable_dt_refinement_ratios = True
    refinement_data.wave_tolerance = 0.002
    refinement_data.deep_depth = 1e2
    #refinement_data.max_level_deep = 3 (changing to 4)
    refinement_data.max_level_deep = 4

    # == settopo.data values ==
    topo_data = rundata.topo_data
    # for topography, append lines of the form
    #    [topotype, minlevel, maxlevel, t1, t2, fname]

    #topo_dir = '../../topo_for_runs/'  ## for new set of topo files
    #topo_dir = '../../topo/PacificDEMs/'
    #topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
    #    topo_dir+'etopo1_-180_-60_-65_65_4min.tt3'])
    #topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
    #    topo_dir+'etopo1_-240_-180_-65_65_4min.tt3'])

    # The 1 minute file files.
    #topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
    #    topo_dir+'etopo1_-240_-180_-41_65_1min.tt3'])
    #topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
    #    topo_dir+'etopo1_-180_-100_-41_65_1min.tt3'])
    ### domain,         -240, -66; -47, 65.
    #
    #Need the new 1 minute files below.
    #topo_dir = '../../topo/etopo/'  ## for new set of topo files
    topo_dir = '../../topo_for_runs/'  ## for new set of topo files
    topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
        topo_dir+'etopo1_-240_-180_-47_65_1min.tt3'])
    topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
        topo_dir+'etopo1_-180_-66_-47_65_1min.tt3'])

    ## Around Crescent City
    ### Diegos 1sec topo, was pierless
    ### This is used for the 1sec and 2 sec runs for Japan2011
    ### and Samoa2009 1 and 2 sec run. Use here for Chile 1sec run
    #topo_dir = '../../topo/PMEL/'
    #topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
    #    topo_dir+'cresc1sec.asc'])

    #These are the UW topo files for Crescent City
    #topo_dir = CC + '/topo/'
    topo_data.topofiles.append([3, 1, 1, 0., 1.e10, \
       topo_dir+'cc-1_3sec-c_pierless.asc'])
    topo_data.topofiles.append([-3, 1, 1, 0., 1.e10, \
       topo_dir+'cc-1sec-c.asc'])

    # == setdtopo.data values ==
    dtopo_data = rundata.dtopo_data
    # for moving topography, append lines of the form :   (<= 1 allowed for now!)
    #   [topotype, minlevel,maxlevel,fname]
    ### pink deformation has region:  -94.65, -67.9833; -46.294, -24.8641
    ### This is about 27 degees by 25 degrees deltas. at one min 27*60 by 25*60
    dtopo_path = '../../dtopo/2010Chile_deformation_most.asc'
    dtopo_data.dtopofiles.append([3,1,1,dtopo_path])
    dtopo_data.dt_max_dtopo = 0.2

    # == setqinit.data values ==
    rundata.qinit_data.qinit_type = 0
    rundata.qinit_data.qinitfiles = []
    # for qinit perturbations, append lines of the form: (<= 1 allowed for now!)
    #   [minlev, maxlev, fname]

    # == setfixedgrids.data values ==
    fixed_grids = rundata.fixed_grid_data
    # for fixed grids append lines of the form
    # [t1,t2,noutput,x1,x2,y1,y2,xpoints,ypoints,\
    #  ioutarrivaltimes,ioutsurfacemax]

    return rundata
    # end of function setgeo
    # ----------------------

#-------------------
def setadjoint(rundata):
#-------------------

    """
    Set parameters used for adjoint flagging.
    Also reads in all of the checkpointed Adjoint files.
    """

    import glob

    # Set these parameters at top of this file:
    # adjoint_flag_tolerance, t1, t2, adjoint_output
    # Then you don't need to modify this function...

    rundata.amrdata.flag2refine = True  # for adjoint flagging
    rundata.amrdata.flag2refine_tol = adjoint_flag_tolerance

    rundata.clawdata.num_aux = 4   # 4 required for adjoint flagging
    rundata.amrdata.aux_type = ['center','capacity','yleft','center']

    adjointdata = rundata.new_UserData(name='adjointdata',fname='adjoint.data')
    adjointdata.add_param('adjoint_output',adjoint_output,'adjoint_output')
    adjointdata.add_param('t1',t1,'t1, start time of interest')
    adjointdata.add_param('t2',t2,'t2, final time of interest')

    files = glob.glob(os.path.join(adjoint_output,"fort.b*"))

    files.sort()

    if (len(files) == 0):
        print("No binary files found for adjoint output!")

    adjointdata.add_param('numadjoints', len(files),
                       'Number of adjoint output files.')
    adjointdata.add_param('innerprod_index', 4,
                       'Index for innerproduct data in aux array.')

    counter = 1
    for fname in files:
        f = open(fname)
        adjointdata.add_param('file' + str(counter), fname, \
            'Binary file' + str(counter))
        counter = counter + 1

    return rundata
    # end of function setadjoint
    # ----------------------

if __name__ == '__main__':
    # Set up run-time parameters and write all data files.
    import sys
    rundata = setrun(*sys.argv[1:])
    rundata.write()

    from clawpack.geoclaw import kmltools
    kmltools.make_input_data_kmls(rundata)


#!/usr/bin/env python
#coding=utf8

from __future__ import print_function

import sys
import math
import vtkmodules.test.Testing

try:
    import numpy
except ImportError:
    print("This test requires numpy!")
    vtkmodules.test.Testing.skip()

from vtkmodules.vtkCommonCore import (
    vtkFloatArray,
    vtkPoints,
)
from vtkmodules.vtkCommonDataModel import (
    vtkCellArray,
    vtkHexahedron,
    vtkUnstructuredGrid,
)
from vtkmodules.vtkFiltersGeneral import vtkCellDerivatives

# Create a simple hexahedron
points = vtkPoints()
points.SetNumberOfPoints(8)
points.InsertPoint(0, 0, 0, 0)
points.InsertPoint(1, 1, 0, 0)
points.InsertPoint(2, 1, 1, 0)
points.InsertPoint(3, 0, 1, 0)
points.InsertPoint(4, 0, 0, 1)
points.InsertPoint(5, 1, 0, 1)
points.InsertPoint(6, 1, 1, 1)
points.InsertPoint(7, 0, 1, 1)
#for k_point in range(8): print points.GetPoint(k_point)

hexahedron = vtkHexahedron()
for k_point in range(8):
    hexahedron.GetPointIds().SetId(k_point, k_point)

cell_array = vtkCellArray()
cell_array.InsertNextCell(hexahedron)

farray_disp = vtkFloatArray()
farray_disp.SetName("displacement")
farray_disp.SetNumberOfComponents(3)
farray_disp.SetNumberOfTuples(8)

ugrid_hex = vtkUnstructuredGrid()
ugrid_hex.SetPoints(points)
ugrid_hex.SetCells(hexahedron.GetCellType(), cell_array)
ugrid_hex.GetPointData().AddArray(farray_disp)
ugrid_hex.GetPointData().SetActiveVectors("displacement")

# Test a few deformation gradients
F_lst  = []

# Simple extensions
F_lst += [numpy.array([[2,0,0],
                       [0,1,0],
                       [0,0,1]])]
F_lst += [numpy.array([[1,0,0],
                       [0,2,0],
                       [0,0,1]])]
F_lst += [numpy.array([[1,0,0],
                       [0,1,0],
                       [0,0,2]])]

# Simple shears
F_lst += [numpy.array([[1,1,0],
                       [0,1,0],
                       [0,0,1]])]
F_lst += [numpy.array([[1,0,1],
                       [0,1,0],
                       [0,0,1]])]
F_lst += [numpy.array([[1,0,0],
                       [0,1,1],
                       [0,0,1]])]
F_lst += [numpy.array([[1,0,0],
                       [1,1,0],
                       [0,0,1]])]
F_lst += [numpy.array([[1,0,0],
                       [0,1,0],
                       [1,0,1]])]
F_lst += [numpy.array([[1,0,0],
                       [0,1,0],
                       [0,1,1]])]

# Rotation
alpha = math.pi/2
F_lst += [numpy.array([[+math.cos(alpha),-math.sin(alpha),0],
                       [+math.sin(alpha),+math.cos(alpha),0],
                       [               0,               0,1]])]

for F in F_lst:
    print("F = " + str(F))

    # Assuming an homogeneous deformation gradient, compute the displacement and displacement gradient: u = x(X)-X = F.X-X = (F-1).X = GU.X with GU = F-1
    GU = F - numpy.eye(3)
    print("GU = " + str(GU))

    for k_point in range(8):
        farray_disp.SetTuple(k_point, numpy.dot(GU, points.GetPoint(k_point)))
        #print farray_disp.GetTuple(k_point)

    # Compute the small (linearized) strain tensor: e = (GU)_sym = (GU+GU^T)/2
    e = (GU + numpy.transpose(GU))/2
    print("e = " + str(e))

    # Compute the Green-Lagrange strain tensor: E = (F.F^T-1)/2 = (GU+GU^T+GU^T.GU)/2 = e + GU^T.GU/2
    E = e + numpy.dot(numpy.transpose(GU), GU)/2
    print("E = " + str(E))

    # Compute displacement gradient using vtkCellDerivatives
    cell_derivatives = vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    cell_derivatives.SetInputData(ugrid_hex)
    cell_derivatives.Update()
    vector_gradient = numpy.reshape(cell_derivatives.GetOutput().GetCellData().GetArray("VectorGradient").GetTuple(0), (3,3))
    print("VectorGradient = " + str(vector_gradient))
    assert numpy.allclose(vector_gradient, GU)

    # Compute small strain tensor using vtkCellDerivatives
    cell_derivatives = vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeStrain()
    cell_derivatives.SetInputData(ugrid_hex)
    cell_derivatives.Update()
    strain = numpy.reshape(cell_derivatives.GetOutput().GetCellData().GetArray("Strain").GetTuple(0), (3,3))
    print("Strain = " + str(strain))
    assert numpy.allclose(strain, e)

    # Compute Green-Lagrange strain tensor using vtkCellDerivatives
    cell_derivatives = vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGreenLagrangeStrain()
    cell_derivatives.SetInputData(ugrid_hex)
    cell_derivatives.Update()
    green_lagrange_strain = numpy.reshape(cell_derivatives.GetOutput().GetCellData().GetArray("GreenLagrangeStrain").GetTuple(0), (3,3))
    print("GreenLagrangeStrain = " + str(green_lagrange_strain))
    assert numpy.allclose(green_lagrange_strain, E)


# https://paulgray.net/the-state-monad/

# Imperative programming
import math
from random import randint

def random_number_generator(seed: int) -> int:
    nextSeed = (1839567234 * seed + 972348567) % 8239451023
    return nextSeed

seed = 1
randomNumber1 = random_number_generator(seed)
randomNumber2 = random_number_generator(randomNumber1)

print(randomNumber1)
print(randomNumber2)

# Generate random with interval

def random_in_range_equal(seed: int, minium: int, maximum: int) -> int:
    nextSeed = random_number_generator(seed)
    random = minium + math.floor((nextSeed / maximum) * (maximum - minium))
    return random

seed = 1
random1 = random_in_range_equal(seed, 0, 10)
random2 = random_in_range_equal(seed, 0, 10)

print(random1)
print(random2)

def random_in_range(seed: int, minium: int, maximum: int) -> list[int]:
    nextSeed = random_number_generator(seed)
    random = minium + math.floor((nextSeed / maximum) * (maximum - minium))
    return [nextSeed, random]

seed1 = 1
[seed2, random1] = random_in_range(seed1, 0, 10)
[seed3, random2] = random_in_range(seed2, 0, 10)

print([seed2, random1])
print([seed3, random2])

FirstNames = ['João', 'Maria', 'José', 'Carla']

def random_first_name(seed: int):
    [seed2, ranged] = random_in_range(seed, 0, len(FirstNames))
    return [seed2, FirstNames[ranged]]