"""
Tic Tac Toe Player
"""
import copy

X = "X"
O = "O"
EMPTY = None

def initial_state():
    """
    Returns starting state of the board.
    """
    return [[EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY]]

def isFull(board):
    """
    Returns true if board is full otherwise returns False
    """
    for i in range(3):
        for j in range(3):
            if board[i][j] == EMPTY:
                return False
    return True

def player(board):
    """
    Returns player who has the next turn on a board.
    """
    count =0
    for i in range(0,3):
        for j in range(0,3):
            if board[i][j]!=EMPTY:
                count=count+1
    if count%2==0:
        return X
    return O

def actions(board):
    """
    Returns set of all possible actions (i, j) available on the board.
    """
    moves =[]
    for i in range(0,3):
        for j in range(0,3):
            if board[i][j]==EMPTY:
                pair = (i,j)
                moves.append(pair)
    return moves

def result(board, action):
    """
    Returns the board that results from making move (i, j) on the board.
    """
    newboard = copy.deepcopy(board)
    turn = player(board)
    if turn==X:
        newboard[action[0]][action[1]] = X
    else:
        newboard[action[0]][action[1]] = O
    return newboard

def winner(board):
    """
    Returns the winner of the game, if there is one.
    """
    # check if player X or O wins
    for i in range(3):
        if board[i][0]==board[i][1] and board[i][1]==board[i][2]:
            if board[i][0]==X:
                return X
            elif board[i][0]==O:
                return O
        if board[0][i]==board[1][i] and board[1][i]==board[2][i]:
            if board[0][i]==X:
                return X
            elif board[0][i]==O:
                return O
    if board[0][0] == board[1][1] and board[1][1]==board[2][2]:
        if board[0][0]==X:
            return X
        elif board[0][0] == O:
            return O
    if board[2][0] == board[1][1] and board[1][1]==board[0][2]:
        if board[2][0]==X:
            return X
        elif board[2][0] == O:
            return O
    return None

def terminal(board):
    """
    Returns True if game is over, False otherwise.
    """
    if winner(board)==X or winner(board)==O or (winner(board) == None and isFull(board)):
        return True
    return False

def utility(board):
    """
    Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
    """
    if terminal(board):
        if winner(board)==X:
            return 1
        elif winner(board)==O:
            return -1
        else:
            return 0

def minimax(board):
    """
    Returns the optimal action for the current player on the board.
    """
    # X maximizes, O minimizes
    user = player(board)
    maxVal=-100
    minVal=100
    optAction = (0,0)
    if(terminal(board)):
        return None
    else:
        if user==X:
            for a in actions(board):
                val = minValue(result(board,a))
                if val >= maxVal:
                    maxVal=val
                    optAction=a
        else:
            for a in actions(board):
                val = maxValue(result(board,a))
                if val<=minVal:
                    minVal=val
                    optAction = a
    return optAction

def maxValue(board):
    v=-100 # technically -infinity
    if terminal(board):
        return utility(board)
    for a in actions(board):
        v= max(v,minValue(result(board,a)))
    return v

def minValue(board):
    v=100 # technically infinity
    if terminal(board):
        return utility(board)
    for a in actions(board):
        v= min(v,maxValue(result(board,a)))
    return v


import ndspy
import ndspy.rom, ndspy.bmg, ndspy.codeCompression
import ndspy.narc
import code
import io
import os
import json
import copy
import sys
import re

# code.interact(local=dict(globals(), **locals()))

######################### CONSTANTS #############################

def set_global_vars(rom_name):
	global ROM_NAME, NARC_FORMAT, BASE_ROM, MOVES, EFFECT_TABLE_OFFSET

	with open(f'{rom_name}/session_settings.json', "r") as outfile:
		settings = json.load(outfile)
		ROM_NAME = settings['rom_name']
		BASE_ROM = settings['base_rom']
		BASE_VERSION = settings["base_version"]

	MOVES = open(f'{ROM_NAME}/texts/moves.txt', mode="r").read().splitlines()

	NARC_FORMAT = []

	B2_EFFECT_TABLE_OFFSET = 0X000407F4
	W2_EFFECT_TABLE_OFFSET = 0X000407F4

	if BASE_VERSION == "B2":
		EFFECT_TABLE_OFFSET = B2_EFFECT_TABLE_OFFSET
	else:
		EFFECT_TABLE_OFFSET = W2_EFFECT_TABLE_OFFSET

	for n in range(258):
		NARC_FORMAT.append([4, f'move_id_{n}'])
		NARC_FORMAT.append([4, f'address_{n}'])

#################################################################

def output_move_effects_table(rom_name):
	set_global_vars(rom_name)
	json_file_path = f'{rom_name}/json/arm9/move_effects_table.json'

	move_effects_table_file_path = f'{rom_name}/move_effects_table.bin'
	stream = bytearray()

	with open(json_file_path, "r") as outfile:
		json_data = json.load(outfile)
		#USE THE FORMAT LIST TO PARSE BYTES
		for entry in NARC_FORMAT:
			if entry[1] in json_data["raw"]:
				data = json_data["raw"][entry[1]]
				write_bytes(stream, entry[0], data)

	stream
	open(move_effects_table_file_path, "wb").write(stream)

	overlay167_edited = bytearray(open(f'{rom_name}/overlay167.bin','rb').read())
	overlay167_edited[EFFECT_TABLE_OFFSET:EFFECT_TABLE_OFFSET + 2064] = stream

	open(f'{rom_name}/overlay167.bin', "wb").write(overlay167_edited)

	print("move_effects_table")

def write_bytes(stream, n, data):
	stream += (int(data).to_bytes(n, 'little'))
	return stream

def write_readable_to_raw(rom_name):
	data = {}
	json_file_path = f'{rom_name}/json/arm9/move_effects_table.json'

	with open(json_file_path, "r", encoding='ISO8859-1') as outfile:
		narc_data = json.load(outfile)

		if narc_data["readable"] is None:
			return
		new_raw_data = to_raw(narc_data["readable"])
		narc_data["raw"] = new_raw_data

	with open(json_file_path, "w", encoding='ISO8859-1') as outfile:
		json.dump(narc_data, outfile)

def to_raw(readable):
	raw = copy.deepcopy(readable)

	for n in range(258):
		raw[f'move_id_{n}'] = MOVES.index(readable[f'move_id_{n}'])

	return raw

def write_bytes(stream, n, data):
	stream += (int(data).to_bytes(n, 'little'))
	return stream

################ If run with arguments #############

if len(sys.argv) > 2 and sys.argv[1] == "update":
	set_global_vars(sys.argv[3])
	write_readable_to_raw(sys.argv[3])
	output_move_effects_table(sys.argv[3])


# 홀/짝을 입력하세요 홀
# 나 : 홀
# 컴 : 홀 / 짝
# 결과 : 승리 / 패배
from random import random
#
# a= input("홀/짝을 입력하세요")
# print("나 :" + a)
#
# com = random()
#
# if(com>0.5):
#     b = "홀"
#     print("컴 : " + b)
# else :
#     b = "짝"
#     print("컴 : " + b)
#
# if(a==b):
#     print("승리")
# else :
#     print("패배")

com = ""
mine = ""
result = ""

# 거러바 위엄 like a lion~ ♡
mine = input("홀/짝을 입력하세요")

rnd = random()
if rnd > 0.5 :
    com = "홀"
else :
    com = "짝"
if com == mine :
    result = "승리"
else :
    result = "패배"

print("나 : ", com)
print("컴 : ", mine)
print("결과 : ", result)


import bpy, os

from . preferences          import PreferencesPanel
from . utils                import parse_entry_list, split_entry, ASSET_TYPE_OBJECT

class CollectionImageParser:
    """
    Parser for PreviewHelper. Parses all supported objects and creates
    the collection using the preview images.
    data = [asset_type, category]
    """

    def parse(self, lst):
        """
        Parses the directory for supported files and create list from
        preview images.
        """
        asset_type, category = lst.data
        fp = os.path.join(PreferencesPanel.get().root, asset_type, category)
        print("Parse collection: ", fp)

        id = 0
        noIcon = os.path.join(os.path.dirname(__file__), "data", "No_Icon.png")
        for entry in parse_entry_list(asset_type, category):
            if not lst.collection: # lazy init
                lst.collection = bpy.utils.previews.new()

            imp, preview, label, mat = split_entry(entry)
            if os.path.exists(preview):
                thumb = lst.collection.load(entry, preview, 'IMAGE')
            else:
                thumb = lst.collection.load(entry, noIcon, 'IMAGE')
            lst.items.append((entry, label, label, thumb.icon_id, id))
            id += 1

class NodesParser:
    """
    Parses nodes from specific blend file, load previews from respective
    data folder.
    data = blend basename/folder name.
    """

    def parse(self, lst):
        """
        Parse node elements.
        """
        id = 0
        data = os.path.join(os.path.dirname(__file__), "data")
        noIcon = os.path.join(data, "No_Icon.png")
        blend = os.path.join(data, lst.data + ".blend")
        previews = os.path.join(data, lst.data)
        with bpy.data.libraries.load(blend, link=False) as (data_src, data_dst):
            for group in data_src.node_groups:
                if group.startswith("NW_"):
                    preview = os.path.join(previews, group + ".png")
                    if not lst.collection: # lazy init
                        lst.collection = bpy.utils.previews.new()
                    if os.path.exists(preview):
                        thumb = lst.collection.load(group, preview, 'IMAGE')
                    else:
                        thumb = lst.collection.load(group, noIcon, 'IMAGE')
                    lst.items.append(("%s::%s" % (blend, group), group, "", thumb.icon_id, id))
                    id += 1


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        org=ListNode(0) # must have a fake header.
        org.next=head
        keep=org
        for i in range(n):
            head=head.next

        while head is not None:
            head=head.next
            org=org.next
        org.next=org.next.next

        return keep.next


class Solution:
    def nextPermutation(self, nums):
        if len(nums) == 0 or len(nums) == 1:
            return
        i = len(nums) - 1
        while i > 0 and nums[i] <= nums[i - 1]:  # here must be <= to take care of the duplicates!
            i -= 1

        if i == 0:
            self.swap(nums, 0, len(nums) - 1)
            return
        left_index = i - 1

        i = len(nums) - 1
        while nums[i] <= nums[left_index]:
            i -= 1
        nums[i], nums[left_index] = nums[left_index], nums[i]
        self.swap(nums, left_index + 1, len(nums) - 1)

    def swap(self, nums, left, right):
        while left < right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1

aa = Solution()
aa.nextPermutation([1,1])


import time

from aiogram.types import ChatPermissions

async def ban_command(message, bot):
    if message.chat.type == "private":
        await message.reply(text="Команда для бана участников(доступно только админам паблика). Работает так:\n"
                                 "Чтобы забанить игрока ответи на его сообщение камандой /ban его сообщение. Там может быть 2 параметра:\n"
                                 "Продолжительности бана в секундах, не меньше 35 по умолчанию - 35\n"
                                 "Сообщение которое увидет получатель бана - по умолчанию 'Вы были забанены админом!\n'"
                                 "Параметры можно не прописывать и просто написать /ban но если они есть то должны прописываться строго через пробел!")
        with open(f'K:/shool_project/shool_project/ban.png', 'rb') as photo:
            await bot.send_photo(message.from_user.id, photo=photo)
        return

    chat_admins = await bot.get_chat_administrators(chat_id=message.chat.id)
    admins_userId = [admins.user.id for admins in chat_admins]
    if message.from_user.id not in admins_userId:
        await message.reply(text="Этой командой могут пользоваться только админы!")
        return
    if message.reply_to_message.from_user.id in admins_userId:
        await bot.send_message(message.chat.id,
                               text="Вы пытаетесь забанить админа!",
                               reply_to_message_id=message.reply_to_message.message_id)
        return
    # await message.reply
    duration = 35
    message_text = "Вы были забанены админом!"
    message_box = message.text.split(" ")
    if len(message_box) == 2:
        duration = int(message_box[1])
    elif len(message_box) > 2:
        message_text = " ".join(message_box[2:])

    await bot.restrict_chat_member(message.chat.id, message.reply_to_message.from_user.id,
                                   ChatPermissions(can_send_messages=False),
                                   until_date=time.time() + duration)
    await bot.send_message(message.chat.id,
                           text=message_text,
                           reply_to_message_id=message.reply_to_message.message_id)


from flask import Flask, request
from flask_cors import CORS
from keras.models import load_model
import tensorflow as tf
import numpy as np

app = Flask(__name__)
CORS(app)

@app.route('/', methods=['POST'])
def hello():
    model = load_model("model.h5")
    data = request.get_json()
    data = np.array(data, dtype=np.float32)
    data = tf.reshape(data, (data.shape[0], 1, data.shape[1]))
    res = np.round(model.predict(data, verbose=0))
    return res[0].tolist()

if __name__ == '__main__':
    app.run()


import requests
from selenium import webdriver
import smtplib
import csv
from email.message import EmailMessage

driver = webdriver.Chrome(executable_path=r"driver-path")

link = "https://summerofcode.withgoogle.com/archive/2020/organizations/"

driver.get(link)
orgs = driver.find_elements_by_class_name("organization-card__name")
orgs = [x.text for x in orgs]
links = driver.find_elements_by_class_name("organization-card__link")
links = [x.get_attribute('href') for x in links]
un = list(zip(orgs, links))
un = [list(x) for x in un]
for item in un:
    driver.get(item[1])
    techstack = driver.find_elements_by_class_name("organization__tag--technology")
    techstack = [x.text for x in techstack]
    item.append(techstack)
techstack = set()
for item in un:
    [techstack.add(x) for x in item[2]]

print(techstack)
msg = "placeholder"
know = list()
while msg!="exit":
    msg = input("Enter What you know from the above tech stack")
    know.append(msg)

with open('data.csv','w', newline='') as csvfile:
    csv_writer = csv.writer(csvfile)
    for item in know:
        for orgs in un:
            if item in orgs[2]:
                csv_writer.writerow(orgs)

msg = EmailMessage()
msg['Subject'] = 'Your GSOC matched orgs'
msg['From'] = 'sender-email'
msg['To'] = 'receiver-email'
msg.set_content('Here are your matched orgs based on the tech stack you entered')

with open('data.csv', 'rb') as f:
    file_data = f.read()
    file_name = f.name

msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login('sender-email', 'password')
    smtp.send_message(msg)
driver.quit()


from sklearn import datasets
from sklearn.svm import SVC
from sklearn.preprocessing import scale
from sklearn.model_selection import train_test_split
from itertools import combinations
import numpy as np

# Implement one-versus-the rest
def ovr(X,y,C):
    ovr_models = []
    for i in C:
        newy = []
        for j in range(len(y)):
            if y[j] == i:
                newy.append(i)
            else:
                newy.append(111)
        clf=SVC(kernel='linear')
        model = clf.fit(X,newy)
        ovr_models.append(model)
    return ovr_models
    # X: input data
    # y: target
    # C: unique set of classes with ascending order
    # return list of binary SVCs

def ovr_predict(models,X,C):
    pred_y = []
    for i in range(len(models)):
        y=models[i].predict(X)
        pred_y.append(y)

    new_pred_y = []
    for j in range(len(X)):
        cls_list = []
        for i in pred_y:
            cls_list.append(i[j])
        cls, counts = np.unique(cls_list,return_counts=True)
        count_cls = np.asarray((cls,counts))
        min_y = count_cls[0][list(count_cls[1]).index(min(count_cls[1]))]
        if min_y == 111:
            min_y = None
        new_pred_y.append(min_y)
    return new_pred_y
    # models: list of binary SVCs
    # X: input data
    # C: unique set of classes with ascending order
    # return predicted classes of samples in X (if ambiguous, set nan)

# Implement one-versus-one
def ovo(X,y,C):
    index=list(combinations(C,2))
    ovo_models=[]
    for i in range(len(index)):
        index_list=[]
        for j in range(len(y)):
            if y[j] == index[i][0] or y[j] == index[i][1]:
                index_list.append(j)
        newx = X[index_list]
        newy = y[index_list]
        clf=SVC(kernel='linear')
        model = clf.fit(newx,newy)
        ovo_models.append(model)
    return ovo_models
    # X: input data
    # y: target
    # C: unique set of classes with ascending order
    # return list of binary SVCs

def ovo_predict(models,X,C):
    pred_y = []
    for i in range(len(ovo_models)):
        y=ovo_models[i].predict(X)
        pred_y.append(y)

    new_pred_y = []
    for j in range(len(X)):
        num_cls = []
        for i in pred_y:
            num_cls.append(i[j])
        cls, counts = np.unique(num_cls,return_counts=True)
        count_cls = np.asarray((cls,counts))
        max_cls = count_cls[0][list(count_cls[1]).index(max(count_cls[1]))]
        new_pred_y.append(max_cls)
    return new_pred_y
    # X: input data
    # y: target
    # C: unique set of classes with ascending order
    # return predicted classes of samples in X (if ambiguous, set nan)

data=datasets.load_digits()
X,y=data.data, data.target
C=np.sort(np.unique(y))
X=scale(X)

Xtrain,Xval,ytrain,yval=train_test_split(X,y,test_size=0.2, random_state=100,stratify=y)

ovr_models=ovr(Xtrain,ytrain,C)
ovr_y_pred=ovr_predict(ovr_models,Xval,C)

ovo_models=ovo(Xtrain,ytrain,C)
ovo_y_pred=ovo_predict(ovo_models,Xval,C)

# compare accuracies for validation set
def acc_com(y_pred, y):
    return sum(y_pred == y)/len(y)

ovr_acc = acc_com(ovr_y_pred, yval)
ovo_acc = acc_com(ovo_y_pred, yval)

print('ovr_acc:{} \novo_acc:{}'.format(ovr_acc, ovo_acc))


import zmq
from abc import ABCMeta, abstractmethod
import struct

from logging import DEBUG, INFO, ERROR
import threading
from multiprocessing import Process

from zmq.eventloop.ioloop import IOLoop, PeriodicCallback
from zmq.eventloop.zmqstream import ZMQStream

from utils.logging_util import SetGlobalLoggingLevel, GetLogger
from server.ServerUtils.server_config import ServerConfig

# Global server config class
SERVER_CONFIG = ServerConfig.getInstance()

class AdapterBase(object):
    """
    General adapter class.
    @params protocol: Name of the protocol
    @params client_name: Name of the corosponding client.
    @params to_server_pub_port: What server port to publish packets to server.
    @params from_server_sub_port: What port to receive packets from server.
    @params to_client_pub_port: What port to publish packets to client.
    @params from_client_sub_port: What port to receive packets from client.
    """
    __metaclass__ = ABCMeta
    def __init__(self, protocol, client_name,  to_server_pub_port,\
                                               from_server_sub_port,\
                                               to_client_pub_port,\
                                               from_client_sub_port):

        self.__client_name = client_name
        self.__name = "{}_{}_adapter".format(client_name, protocol)

        # Setup Logger
        log_path = SERVER_CONFIG.get("filepaths", "server_log_filepath")
        self.__logger = GetLogger(self.__name,log_path, logLevel=DEBUG,\
                                               fileLevel=DEBUG)
        self.__logger.debug("Logger Active")
        self.__logger.debug("to_server_pub_port: {}".format(to_server_pub_port))
        self.__logger.debug("from_server_sub_port: {}".format(from_server_sub_port))
        self.__logger.debug("to_client_pub_port: {}".format(to_client_pub_port))
        self.__logger.debug("from_client_sub_port: {}".format(from_client_sub_port))

        # Adapter Information
        self.__protocol = protocol

        # Zmq Context
        self.__context = zmq.Context()

        # Book Keeping
        self.__client_connections = {} # Save connections by client ID

        # Create threads
        self.__from_client_decode_thread = threading.Thread(target=self.__FromClientDecodeThread,\
                                                            args=(self.__name,\
                                                                  self.__context,\
                                                                  from_client_sub_port,\
                                                                  to_server_pub_port))

        self.__to_client_encode_thread = threading.Thread(target=self.__ToClientEncodeThread,\
                                                          args=(self.__name,\
                                                                self.__context,\
                                                                to_client_pub_port,\
                                                                from_server_sub_port))

    def Start(self):
        """
        Startup the threads.
        """

        self.__logger.info("Starting adapter")
        self.__from_client_decode_thread.start()
        self.__to_client_encode_thread.start()

    def Quit(self):
        """
        Quit the threads by terminating the context.
        """
        self.__logger.info("Stopping adapter")

        self.__context.term()

    def __FromClientDecodeThread(self, adapter_name, context, from_client_sub_port, to_server_pub_port):
        """
        Receive encoded packets from the client and decode them.
        """
        name = "{}_decode_thread".format(adapter_name)
        # Setup Logger
        log_path = SERVER_CONFIG.get("filepaths", "server_log_filepath")
        logger = GetLogger(name,log_path, logLevel=DEBUG,\
                                               fileLevel=DEBUG)
        logger.debug("Logger Active")

        # Create the sockets
        from_client_sub_socket = context.socket(zmq.ROUTER) # Subscribe to packets from client
        from_client_sub_socket.bind("tcp://*:{}".format(from_client_sub_port))

        to_server_pub_socket   = context.socket(zmq.DEALER) # Publish packets to server
        to_server_pub_socket.setsockopt(zmq.IDENTITY, self.__client_name)
        to_server_pub_socket.connect("tcp://localhost:{}".format(to_server_pub_port))

        try:
            while(True):

                # Receive encoded packet
                msg_bundle = from_client_sub_socket.recv_multipart()
                logger.debug("Received: {}".format(msg_bundle))
                encoded_packet = msg_bundle[1]      # Ignore ID
                                                    # As our sub socket identity is
                                                    # The same as the client

                packet = self.Decode(encoded_packet) # Call the implemented decode method
                to_server_pub_socket.send(packet)

        except zmq.ZMQError as e:
            if e.errno == zmq.ETERM:
                from_client_sub_socket.close()
                to_server_pub_socket.close()
            else:
                raise

    def __ToClientEncodeThread(self, adapter_name, context, to_client_pub_port, from_server_sub_port):
        """
        Receive packets from the server and encode them.
        """
        name = "{}_encode_thread".format(adapter_name)
                        # Setup Logger
        log_path = SERVER_CONFIG.get("filepaths", "server_log_filepath")
        logger = GetLogger(name,log_path, logLevel=DEBUG,\
                                               fileLevel=DEBUG)
        logger.debug("Logger Active")

        # Create sockets
        from_server_sub_socket = context.socket(zmq.ROUTER) # Subscribe to packets from the server
        from_server_sub_socket.setsockopt(zmq.IDENTITY, self.__client_name)
        from_server_sub_socket.connect("tcp://localhost:{}".format(from_server_sub_port))

        to_client_pub_socket = context.socket(zmq.DEALER) # Publish packet to client
        to_client_pub_socket.bind("tcp://*:{}".format(to_client_pub_port))

        try:
            while(True):

                msg_bundle = from_server_sub_socket.recv_multipart()
                logger.debug("Received: {}".format(msg_bundle))
                packet      = msg_bundle[1] # The first frame contains the senders identifier. We don't need this.
                encoded_packet = self.Encode(packet) # Call the implemented encode function
                logger.debug("Sending: {}".format([encoded_packet]))
                to_client_pub_socket.send(encoded_packet)

        except zmq.ZMQError as e:
            if e.errno == zmq.ETERM:
                to_client_pub_socket.close()
                to_server_sub_socket.close()
            else:
                raise

    @abstractmethod
    def Decode(self, encoded_packet):
        """
        Abstact decode method.
        Returns a pure FPrime packet.
        """
        raise NotImplementedError

    @abstractmethod
    def Encode(self, packet):
        """
        Abstract encode method.
        Returns an encoded FPrime packet.
        """
        raise NotImplementedError


#!/usr/bin/env python

import pytest

def testFundingCountries(dictionary):
    """Tests the countries listed in funding source"""

    countries = dictionary.getCategoryPdbxItemEnum("pdbx_audit_support.country")

    funding = dictionary.getEnumListAltWithDetail("pdbx_audit_support", "funding_organization")
    assert len(countries) != 0, print("Missing enumeration for pdbx_audit_support.country")

    assert len(funding) != 0, print("Missing enumeration for pdbx_audit_support.funding_organization")

    for (funder, country) in funding:
        if country == None:
            continue
        assert country in countries, print("Country unknown %s %s" % (funder, country))


import matplotlib.pyplot as plt
import matplotlib.axes as ax
import numpy as np
import os
import statistics
# from chebyshev_SEA import chebyshev_SEA as chebyshev
from chebyshev_adwin import chebyshev_adwin as chebyshev
from skmultiflow.drift_detection.adwin import ADWIN

fig, axs = plt.subplots(3)
fig = plt.gcf()
fig.set_size_inches(18, 9)

_len = 100
patterns = [("si",0,"SIN pattern"),("sq",1,"Square pattern"),("tr",2, "Triangle pattern")]
# patterns = [("si",0,"SIN pattern")]
_width = 1
min_len_cal = 0
max_len_cal = 1500000
cheb_windows_size = 500
k = 3
xlim_min = 0
xlim_max = 6000

# _path  = "D:\\git_project\\data stream\\dataset\\"
_path = "C:\\Users\\karnk\\git\\data_stream\\dataset\\"
raw = _path+"training\\poisson_train.txt"
for pattern,num_graph,pattern_name in patterns:
    test =  _path + "test\\poisson_test_"+pattern+"_w"+str(_width)+"_i"+str(_len)+".txt"
    answer = _path + "answer\\poisson_ans_"+pattern+"_w"+str(_width)+"_i"+str(_len)+".txt"

    # test =  _path + "test\\hinet_test_si_w1_i100.txt"
    # answer = _path + "answer\\hinet_ans_"+pattern+"_w"+str(w)+"_i"+str(size)+".txt"

    test_list = []
    answer_lists = []
    answer_st_ed_list = []

    cheb_ineq= chebyshev(max_window= cheb_windows_size, k=k)
    cheb_test_list = []

    with open(test) as txt_lines:
        for line in txt_lines:
            test_list.append(int(line.replace('\n', '')))

    with open(answer) as txt_lines:
        for line in txt_lines:
            answer_lists.append(int(line.replace('\n', ''))*_len)
    print(answer_lists)
    for i in answer_lists:
        start = i
        end = i + _len
        if start<= max_len_cal:
            if  end > max_len_cal:
                end = max_len_cal-1
            xa = range(start,end)
            answer_st_ed_list.append((start,end))
            ya = [160]*_len # Fix high of area
            axs[num_graph].fill_between(xa, ya,alpha=0.30,color='orange')

    data_lists = test_list[min_len_cal:max_len_cal]
    for i in range(len(data_lists)):
        cheb_ineq.add_element(data_lists[i])
        # adwin.add_element(data_lists[i])
        if cheb_ineq.detected_change():
        # if adwin.detected_change():
            cheb_test_list.append(i)

    for i in cheb_test_list:
        axs[num_graph].axvline(i, color='red', linestyle='-', linewidth=0.7)

    axs[num_graph].plot(test_list)
    axs[num_graph].set_ylim(55, 155)
    axs[num_graph].set_xlim(xlim_min, xlim_max)
    axs[num_graph].set_ylabel('value')
    axs[num_graph].set_xlabel('Time')
    # axs[1].ylabel('value')
    # axs[1].xlabel('Time')
    # fig.suptitle(pattern+" Width = "+ str(_width)+" Length ", fontsize=20)
    # fig.suptitle("Chev with max_size = "+str(max_size)+" min_size =  "+str(min_size), fontsize=20)
    # fig.suptitle("Chev with max_size = 3000", fontsize=20)

    # plt.plot(list_mean,color='green',linewidth=1)
    # plt.plot(list_up_variance,color='red')
    # plt.plot(list_low_variance,color='red')
    tittle = "{}: Width = {} Length = {}".format(pattern_name,_width,_len)
    # axs[num_graph].set_title(pattern_name+": Width = "+ str(_width)+" Length =" + str(_len), fontsize=20)
    axs[num_graph].set_title(tittle, fontsize=20)
#     acc cal
    transit_count = len(answer_st_ed_list)
    count = 0
    true_count = 0
    for start,end in answer_st_ed_list:
        found = False
        # i = 0
        for cheb_test in cheb_test_list:
            if (start <= cheb_test) & (cheb_test <= end):
                true_count = true_count + 1
                if not found:
                    count = count + 1
                    found = True
        # while (i < len(cheb_test_list))& (not found) :
        #     if (start <= cheb_test_list[i]) & (cheb_test_list[i]<=end):
        #         count = count + 1
        #         true_count = true_count+1
        #         found = True
        #     i = i + 1

    print("acc  {} trans_num = {} found = {} rate = {}".format(pattern_name,
                                                               transit_count,
                                                               count,
                                                               (float(count)/float(transit_count)*100)))
plt.show()


# A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of
# two 3-digit numbers.

def isPalindrome(string):
    char_list = []

    for character in string:
        char_list.append(character)

    rev_list = list(reversed(char_list))

    if char_list == rev_list:
        return True
    else:
        return False

def largest_palindrome_product(number_of_digits):
    ########################################################
    largest_product = 0
    # set the range of numbers that are going to be multiplied between
    # if the number has 2 digits, the range is 1 - 99
    start_digit_str = '1'  # the starting digit of a number will always be 1
    for i in range(1, number_of_digits):
        start_digit_str = start_digit_str + '0'

    # The range of n-digit numbers is start_value - end_value
    start_value = int(start_digit_str)
    end_value = int(start_digit_str + '0')

    print(f"The range of {number_of_digits}-digit numbers is: {start_value} - {end_value}")
    ########################################################

    # find the products of all the combination of numbers in this range
    for i in range(start_value, end_value):
        for j in range(start_value, end_value):
            product = i * j
            if isPalindrome(str(product)) and product > largest_product:
                largest_product = product
    # check if any of the results is palindrome

    return largest_product

print(largest_palindrome_product(4))


from utils import *
from global_data import *
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from sklearn.model_selection import cross_val_score

logging.info("Problem f")

gamma = [1000, 100, 10, 1, 0.1, 0.01, 0.001]

method_arr = [TruncatedSVD(n_components=50, n_iter=10, random_state=17),
              NMF(n_components=50, random_state=17)]
method_name = ["LSI", "NMF"]

train_reduced = []
test_reduced = []

for method in method_arr:
    pipeline_f = Pipeline([
        ('vect', CountVectorizer(min_df=MIN_DF, stop_words=ENGLISH_STOP_WORDS, tokenizer=stem_and_tokenize)),
        ('tfidf', TfidfTransformer()),
        ('reduce_dim', method),
    ])
    train_reduced.append(pipeline_f.fit_transform(train_data.data))
    test_reduced.append(pipeline_f.fit_transform(test_data.data))

best_g = []
for ai, method in enumerate(method_name):
    print("Using method "+method)
    Score = []
    for g in gamma:
        Score.append(np.average(cross_val_score(LinearSVC(C=g), train_reduced[ai], train_label, cv=5, n_jobs=-1)))
    plt.figure()
    plt.xlabel("Gamma")
    plt.ylabel('5-fold Cross Validation Score')
    plt.ylim([0.0, 1.05])
    plt.xscale('log')
    plt.plot(gamma, Score)
    plt.show()
    best_g.append(gamma[np.argmax(Score)])
    print("Best value for gamma: ", best_g[ai])

    pipeline_f = Pipeline([
        ('vect', CountVectorizer(min_df=mdf, stop_words=ENGLISH_STOP_WORDS, tokenizer=stem_and_tokenize)),
        ('tfidf', TfidfTransformer()),
        ('reduce_dim', TruncatedSVD(n_components=50, n_iter=10, random_state=17)),
        ('clf', LinearSVC(C=best_g[ai])),
    ])
    pipeline_f.fit(train_data.data, train_label)
    pred_test = pipeline_f.predict(test_data.data)
    pred_test_prob = pipeline_f.decision_function(test_data.data)
    print("-" * 70)
    print("Using method "+method+" and best gamma %f" % best_g[ai])
    analyze(test_label, pred_test_prob, pred_test, CAT, 2)
    print("-" * 70)

logging.info("finished Problem f")


import os
import sys

path = '/usr/local/mbaproject'
project = '/webMBArepo'
if path not in sys.path:
    sys.path.append(path)
    sys.path.append(path+project)

os.environ['DJANGO_SETTINGS_MODULE'] = 'webMBArepo.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()


from django.db import models, transaction, connection
from cryptography.fernet import Fernet
from django.conf import settings
from django.http import *

# To encrypt or decrypt data
from django.forms import model_to_dict

from office_app.models import *
import json

security = Fernet(settings.ENCRYPT_KEY)

class PAF(models.Model):
    pafID = models.BigAutoField(primary_key=True)

    # Employee Information
    emp_firstName = models.CharField(max_length=20, blank=True, null=True)
    emp_middleName = models.CharField(max_length=20, blank=True, null=True)
    emp_lastName = models.CharField(max_length=20, blank=True, null=True)
    emp_otherName = models.CharField(max_length=20, blank=True, null=True)
    emp_email = models.EmailField(unique=False, blank=True, null=True)
    emp_phone = models.CharField(unique=False, max_length=20, blank=True, null=True)
    emp_homeAddress = models.CharField(max_length=250, blank=True, null=True)

    # General Informationn
    dateOfHire = models.DateField(blank=True, null=True)
    position = models.CharField(max_length=50, blank=True, null=True)
    unit = models.CharField(max_length=50, blank=True, null=True)
    department = models.CharField(max_length=50, blank=True, null=True)
    actionType = models.CharField(max_length=50, blank=True, null=True)
    employmentType = models.CharField(max_length=50, blank=True, null=True)
    createdBy = models.CharField(max_length=50)

    def __str__(self):
        return str(self.pafID)

    """
        This function create new paf object and submit it to the data base
        Written by: Zaawar Ejaz
        :param: self: new paf object
    """

    def createPAF(self, emp_firstName, emp_middleName, emp_lastName, emp_otherName, emp_email, emp_phone,
                  emp_homeAddress, dateOfHire, position, unit, department, actionType, employmentType, createdBy):

        self.actionType = actionType
        self.employmentType = employmentType
        self.emp_firstName = emp_firstName
        self.emp_middleName = emp_middleName
        self.emp_lastName = emp_lastName
        self.emp_otherName = emp_otherName
        self.emp_email = emp_email
        self.emp_phone = emp_phone
        self.emp_homeAddress = emp_homeAddress
        self.dateOfHire = dateOfHire
        self.position = position
        self.unit = unit
        self.department = department
        self.createdBy = createdBy
        self.save()

    """
        This function returns all checklist in json format
        Written by: Zaawar Ejaz
        :param: pafID: the paf id of the paf
        :return: paf object

    """

    @staticmethod
    def get_paf_details(pafID):
        return PAF.objects.get(pafID=pafID)

    """
        This function returns all paf or paf created by manager (if id is provided) in json format
        Written by: Zaawar Ejaz
        :param manager_id: manager employee id
        :return: json formatted data

    """

    @staticmethod
    def get_all_paf(empID):
        cursor = connection.cursor()
        result = []

        cursor.execute(
            'SELECT "pafID","emp_firstName", "emp_middleName", "emp_lastName", "emp_email", "emp_phone", "position", "department", '
            '"unit", "employmentType", "actionType", "dateOfHire", "createdBy" '
            'FROM smart_hr_paf '
            'WHERE "createdBy" = %s', [empID]
        )

        try:
            for row in cursor.fetchall():
                result.append(dict(zip([col[0] for col in cursor.description], row)))
        except:
            return {"data": result}

        return {"data": result}

"""
    This function create new paf object and submit it to the data base
    Written by: Zaawar Ejaz
    :param: self: new paf object
"""

class PAFAuthorizer(models.Model):
    pafID = models.ForeignKey(PAF, on_delete=models.CASCADE)
    signature_number = models.IntegerField()
    fullName = models.CharField(max_length=50)
    dateSigned = models.DateField()

    def __str__(self):
        return str(self.pafID)

    def addPAFAuthorizer(self, pafID, fullName, dateSigned, signature_number):
        self.pafID = pafID
        self.signature_number = signature_number
        self.fullName = fullName
        self.dateSigned = dateSigned
        self.save()

    @staticmethod
    def getPAFAuthorizers(pafID):
        pafAuths = []
        for obj in PAFAuthorizer.objects.filter(pafID=pafID):
            pafAuths.append(obj)
        return pafAuths

    @staticmethod
    def get_Paf_Managers():
        managers = []
        for p in PAFAuthorizer.objects.filter(signature_number=1):
            managers.append(p)
        return managers

    """
         This function gets the string version of a field's value
         Author: Corrina Barr
         :param self: the Model's object(an instance of the model, a row in the model)
         :param field: the field in the object you want to be converted to a string
         :return: returns the object's field as a string datatype so it is easier for python to work with
    """

    def get_string_version(self, field):
        return str(field)

class ChecklistTask(models.Model):
    taskID = models.BigAutoField(primary_key=True)
    description = models.CharField(max_length=100, blank=True, null=True)
    department = models.ForeignKey(CostCenter, on_delete=models.CASCADE)
    status = models.BooleanField(default=True, blank=True)

    def __str__(self):
        return str(self.taskID)

class NewHireChecklist(models.Model):
    empID = models.ForeignKey(Employee, on_delete=models.CASCADE, to_field='associateID')
    taskID = models.ForeignKey(ChecklistTask, on_delete=models.CASCADE)
    taskAssignee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='employee', to_field='associateID')
    dueDate = models.DateField(blank=True, null=True)
    completed = models.BooleanField()
    dateCompleted = models.DateField(blank=True, null=True)

    def __str__(self):
        return str(self.empID)

    def updateChecklist(self, employeeID, taskID, dueDate):
        self.empID = employeeID
        self.taskID = taskID
        self.dueDate = dueDate

    def createChecklist(self, employeeID):
        self.empID = employeeID
        self.save()

    """
         This function gets the string version of a field's value
         Author: Corrina Barr
         :param self: the Model's object(an instance of the model, a row in the model)
         :param field: the field in the object you want to be converted to a string
         :return: returns the object's field as a string datatype so it is easier for python to work with
    """

    def get_string_version(self, field):
        return str(field)

    """
        This function returns all checklist in json format
        Written by: Zaawar Ejaz
        :return: json formatted data

    """

    @staticmethod
    def get_assigned_checklist(assigneeID):
        cursor = connection.cursor()
        result = []

        if UserPermissions.objects.filter(user=assigneeID, permission__key="view_all_checklist").count() > 0:
            cursor.execute(
                'SELECT DISTINCT '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID") as "totalTasks", '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID" and newhire."taskAssignee_id" = %s) as "assigneeTasks", '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID" and newhire."completed" = True) as "totalTasksCompleted", '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID" and newhire."taskAssignee_id" = %s and newhire."completed" = True) as "assigneeTasksCompleted", '
                'emp."associateID", emp."firstName", emp."middleName", emp."lastName", role."title" as position, costcenter."costCenterName" as department, emp."doh", manager."firstName" as mfname, manager."lastName" as mlname '
                'FROM smart_hr_newhirechecklist '
                'INNER JOIN office_app_employee AS emp '
                'ON smart_hr_newhirechecklist."empID_id" = emp."associateID"'
                'INNER JOIN office_app_employeedepartment AS empdept '
                'ON emp."associateID" = empdept."associateID_id"'
                'INNER JOIN office_app_costcenter AS costcenter '
                'ON costcenter."costCenterCode" = empdept."departmentID_id" '
                'INNER JOIN office_app_role AS role '
                'ON role."roleID" = empdept."roleID_id" '
                'INNER JOIN (SELECT * FROM office_app_employee) manager '
                'ON manager."associateID" = costcenter."managerBy_id" ', [assigneeID, assigneeID]
            )
        else:
            cursor.execute(
                'SELECT DISTINCT '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID") as "totalTasks", '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID" and newhire."taskAssignee_id" = %s) as "assigneeTasks", '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID" and newhire."completed" = True) as "totalTasksCompleted", '
                '(SELECT COUNT(*) FROM smart_hr_newhirechecklist newhire WHERE newhire."empID_id" = emp."associateID" and newhire."taskAssignee_id" = %s and newhire."completed" = True) as "assigneeTasksCompleted", '
                'emp."associateID", emp."firstName", emp."middleName", emp."lastName", role."title" as position, costcenter."costCenterName" as department, emp."doh", manager."firstName" as mfname, manager."lastName" as mlname '
                'FROM smart_hr_newhirechecklist '
                'INNER JOIN office_app_employee AS emp '
                'ON smart_hr_newhirechecklist."empID_id" = emp."associateID"'
                'INNER JOIN office_app_employeedepartment AS empdept '
                'ON emp."associateID" = empdept."associateID_id"'
                'INNER JOIN office_app_costcenter AS costcenter '
                'ON costcenter."costCenterCode" = empdept."departmentID_id" '
                'INNER JOIN office_app_role AS role '
                'ON role."roleID" = empdept."roleID_id" '
                'INNER JOIN (SELECT * FROM office_app_employee) manager '
                'ON manager."associateID" = costcenter."managedBy_id" '
                'WHERE smart_hr_newhirechecklist."taskAssignee_id" = %s ', [assigneeID, assigneeID, assigneeID]
            )
        try:
            for row in cursor.fetchall():
                result.append(dict(zip([col[0] for col in cursor.description], row)))
        except:
            return {"data": result}

        return {"data": result}


from matplotlib import pyplot as plt
import pickle
import numpy as np
from scipy.stats import ttest_rel, ttest_ind
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import spacy

nlp =  spacy.load("en_core_web_lg")

conds = ['intact','lesioned']

#for cond in conds:
if True:
    cond = 'Goodman'
    fname = "output_goodman_etal_intact_0p55nege1.pkl"

    f = open(fname, "rb")
    goodman = pickle.load(f)
    f.close()

    goodman_corr = np.array([goodman['correct']['vlens'][i][-1][0] for i in range(len(goodman['correct']['vlens']))])
    goodman_incr = np.array([goodman['incorrect']['vlens'][i][-1][0] for i in range(len(goodman['incorrect']['vlens']))])

    vlens_verbs = []
    vlens_nouns = []
    for i in range(len(goodman['correct']['probe'])):
        bg = goodman['correct']['probe'][i]
        [w1,w2] = bg.split()
        pos1 = nlp(w1)[0].pos_
        pos2 = nlp(w2)[0].pos_
        if pos2 == "NOUN":
            vlens_nouns.append( goodman['correct']['vlens'][i][-1][0] )
        elif pos2 == "VERB":
            vlens_verbs.append( goodman['correct']['vlens'][i][-1][0] )

    ttest = ttest_ind(vlens_nouns, vlens_verbs)
    t = np.round(ttest[0],2)
    p = np.round(ttest[1],3)
    M1 = np.round(np.mean(vlens_nouns),5)
    M2 = np.round(np.mean(vlens_verbs),5)
    df= min([len(vlens_nouns)-1, len(vlens_verbs)-1])
    print("Mean(Noun): {} --- Mean(Verb): {} --- t({}) = {}, p = {}".format(M1, M2, df, t, p ))

    vlens_verbs = []
    vlens_nouns = []
    for i in range(len(goodman['incorrect']['probe'])):
        bg = goodman['incorrect']['probe'][i]
        [w1,w2] = bg.split()
        pos1 = nlp(w1)[0].pos_
        pos2 = nlp(w2)[0].pos_
        if pos2 == "NOUN":
            vlens_nouns.append( goodman['incorrect']['vlens'][i][-1][0] )
        elif pos2 == "VERB":
            vlens_verbs.append( goodman['incorrect']['vlens'][i][-1][0] )

    ttest = ttest_ind(vlens_nouns, vlens_verbs)
    t = np.round(ttest[0],2)
    p = np.round(ttest[1],3)
    M1 = np.round(np.mean(vlens_nouns),5)
    M2 = np.round(np.mean(vlens_verbs),5)
    df= min([len(vlens_nouns)-1, len(vlens_verbs)-1])
    print("Mean(Noun): {} --- Mean(Verb): {} --- t({}) = {}, p = {}".format(M1, M2, df, t, p ))

    diff = goodman_corr - goodman_incr

    df = pd.DataFrame(np.array([goodman_corr, goodman_incr, diff]).T, columns=["Congruent", "Incongruent", "Difference"])

    d = np.mean(goodman_corr - goodman_incr)/np.std(goodman_corr - goodman_incr)

    sns.set_palette("Purples_r")
    N = 32
    print(N, ttest_rel(goodman_corr[:N], goodman_incr[:N]))

    fig = plt.figure()
    #sns.distplot(df['Congruent'], kde=False, label="Congruent")
    #sns.distplot(df['Incongruent'], kde=False, label="Incongruent")
    plot = sns.distplot(df["Difference"], kde=False)
#    plt.legend()
    plt.axvline(0, color="red")
    plot.set_xlabel("Familiarity difference", fontsize=15)
    plot.set_ylabel("Frequency", fontsize=15)
    fig.show()


"""REST client handling, including HubspotStream base class."""

from __future__ import annotations

import sys
from typing import Any, Callable

import requests
from singer_sdk.pagination import BaseAPIPaginator
from singer_sdk.streams import RESTStream
from singer_sdk import typing as th

if sys.version_info >= (3, 8):
    from functools import cached_property
else:
    from cached_property import cached_property

from singer_sdk.authenticators import BearerTokenAuthenticator
from tap_hubspot.auth import HubSpotOAuthAuthenticator

_Auth = Callable[[requests.PreparedRequest], requests.PreparedRequest]

class HubspotStream(RESTStream):
    """tap-hubspot stream class."""

    @property
    def url_base(self) -> str:
        """
        Returns base url
        """
        return "https://api.hubapi.com/"

    records_jsonpath = "$[*]"  # Or override `parse_response`.

    # Set this value or override `get_new_paginator`.
    next_page_token_jsonpath = "$.next_page"

    @cached_property
    def authenticator(self) -> _Auth:
        """Return a new authenticator object.

        Returns:
            An authenticator instance.
        """

        if "refresh_token" in self.config:
            return HubSpotOAuthAuthenticator(
                self,
                auth_endpoint="https://api.hubapi.com/oauth/v1/token",
            )
        else:
            return BearerTokenAuthenticator(
                self,
                token=self.config.get("access_token"),
            )

    @property
    def http_headers(self) -> dict:
        """Return the http headers needed.

        Returns:
            A dictionary of HTTP headers.
        """
        headers = {}
        if "user_agent" in self.config:
            headers["User-Agent"] = self.config.get("user_agent")
        return headers

    def get_new_paginator(self) -> BaseAPIPaginator:
        """Create a new pagination helper instance.

        If the source API can make use of the `next_page_token_jsonpath`
        attribute, or it contains a `X-Next-Page` header in the response
        then you can remove this method.

        If you need custom pagination that uses page numbers, "next" links, or
        other approaches, please read the guide: https://sdk.meltano.com/en/v0.25.0/guides/pagination-classes.html.

        Returns:
            A pagination helper instance.
        """
        return super().get_new_paginator()

    def get_next_page_token(
        self,
        response: requests.Response,
        previous_token: t.Any | None,
    ) -> t.Any | None:
        """Return a token for identifying next page or None if no more pages."""
        # If pagination is required, return a token which can be used to get the
        #       next page. If this is the final page, return "None" to end the
        #       pagination loop.
        resp_json = response.json()
        paging = resp_json.get("paging")

        if paging is not None:
            next_page_token = resp_json.get("paging", {}).get("next", {}).get("after")
        else:
            next_page_token = None
        return next_page_token

    def get_url_params(
        self,
        context: dict | None,
        next_page_token: Any | None,
    ) -> dict[str, Any]:
        """Return a dictionary of values to be used in URL parameterization.

        Args:
            context: The stream context.
            next_page_token: The next page index or value.

        Returns:
            A dictionary of URL query parameters.
        """
        params: dict = {}
        if next_page_token:
            params["after"] = next_page_token
        if self.replication_key:
            params["sort"] = "asc"
            params["order_by"] = self.replication_key

        return params

class DynamicHubspotStream(HubspotStream):
    """DynamicHubspotStream"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def _get_datatype(self, data_type: str) -> th.JSONTypeHelper:
        # TODO: consider typing more precisely
        return th.StringType()

    @cached_property
    def schema(self) -> dict:
        """Return a draft JSON schema for this stream."""
        hs_props = []
        self.hs_properties = self._get_available_properties()
        for name, type in self.hs_properties.items():
            hs_props.append(
                th.Property(name, self._get_datatype(type))
            )
        return th.PropertiesList(
            th.Property("id", th.StringType),
            th.Property(
                "properties", th.ObjectType(*hs_props),
            ),
            th.Property("createdAt", th.StringType),
            th.Property("updatedAt", th.StringType),
            th.Property("archived", th.BooleanType),
        ).to_dict()

    def _get_available_properties(self) -> dict[str, str]:
        session = requests.Session()
        session.auth = self.authenticator

        resp = session.get(
            f"https://api.hubapi.com/crm/v3/properties/{self.name}",
        )
        resp.raise_for_status()
        results = resp.json().get("results", [])
        return {prop["name"]: prop["type"] for prop in results}

    def get_url_params(
        self,
        context: dict | None,
        next_page_token: Any | None,
    ) -> dict[str, Any]:
        """Return a dictionary of values to be used in URL parameterization.

        Args:
            context: The stream context.
            next_page_token: The next page index or value.

        Returns:
            A dictionary of URL query parameters.
        """
        params = super().get_url_params(context, next_page_token)
        if self.hs_properties:
            params["properties"] = ",".join(self.hs_properties)
        return params


from django.shortcuts import render, redirect
from .jsonbase import JsonBase
from .models import Document
from .vision import vision
from django.contrib import messages
import os
import json
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
from .vision2 import vision2, vision3

# 관리자 메인 페이지
def admin_form_view(request):
    context = {

    }

    return render(request, 'admin_form_view.html', context)

# 관리자 양식추가 페이지
def admin_form_make(request):
    context = {

    }

    context["boxData"] = [
        {"label": "label", "x":100, "y":100, "w":100, "h":100, "type": "type"}
    ]

    return render(request, 'admin_form_make.html', context)

# 확인용 test함수
def test(request):
    context = {}

    data_title = request.POST["data_title"]
    data_file = json.loads(request.POST["data_file"])

    print(data_title)
    print(data_file)
    print(type(data_file))
    print(data_file[0])
    print(type(data_file[0]))

    return render(request, 'test.html')

def home(request):
    context = {}

    j = JsonBase('jsonbase.json')
    json_data = j.all_data()
    context['jsonData'] = json_data

    if request.method == "POST":

        title = request.POST["input_title"]
        image = request.FILES['input_file']

        # doc = Document.objects.filter(images=image)

        # 똑같은 양식명에 파일이 한개라도 있다면 overwriting
        # if doc.count():
        #     doc[0].images = request.FILES['input_file']
        #     doc[0].save()

        # 양식명이 똑같은 것이 없다면 new save
        # else:
        document = Document()
        document.title = title
        document.images = image
        document.save()

        last_img = 'media/' + str(Document.objects.last().images)

        # input_title이 없을때 자동인식 실시
        if not title:
            # 모든 데이터 첫번째 label 제목만 불러와 적용후 일치시 title 도출
            titles = []
            for i in json_data:
                titles.append(i['form_title'])

            for data in json_data:
                w = data['lot'][0]['w']
                h = data['lot'][0]['h']
                cx = data['lot'][0]['cx']
                cy = data['lot'][0]['cy']

                img = cv2.imread(last_img)
                img = cv2.resize(img, (2480, 3508))

                img_r = cv2.getRectSubPix(
                            img,
                            patchSize=(w, h),
                            center=(cx, cy),
                    )
                img_gray = cv2.cvtColor(img_r, cv2.COLOR_BGR2GRAY)
                img_blur = cv2.GaussianBlur(img_gray, (5, 5), 0)

                ret, img_th = cv2.threshold(img_blur, 120, 230, cv2.THRESH_BINARY_INV)

                options = "--oem 1 --psm 7"

                title = pytesseract.image_to_string(cv2.cvtColor(img_th, cv2.COLOR_BGR2RGB), config=options, lang='Hangul')
                title = title.replace(' ', '').replace('\n', '')

                # 파일에 일치하는 제목을 찾는다면 아까 빈파일에 저장한 값에 overwriting 한다
                if title in titles:
                    doc = Document.objects.last()
                    doc.title = title
                    doc.save()
                    break

                # 만약 아무것도 일치하는 것이 없다면
                title = None

        context['title'] = title

        # title이 없다면 여기서 그냥 return 시킨다
        if title == None:
            return render(request, 'home.html', context)

        # if not os.path.exists(os.path.join(base, str(request.FILES['input_file'])))
        img = cv2.imread(last_img)
        img1 = cv2.resize(img, (2480, 3508))

        data = j.search_data(title)

        for i in data[0]['lot']:
                (x, y, w, h) = (int(i['cx'] - i['w'] / 2), int(i['cy'] - i['h'] / 2), int(i['w']), int(i['h']))
                cv2.rectangle(img1, (x , y), (x + w, y + h), (255, 0, 0), 2)

        ret, _ = cv2.imencode('.jpg', img1)
        cv2.imwrite('./media/temp1.jpg', img1)

        form_number = j.search_number_from_title(title)

        # form number, image
        csv_table = vision(form_number, last_img)

        context['ret'] = ret
        context['files'] = 'media/temp1.jpg'
        context['csv_files'] = csv_table

    return render(request, 'home.html', context)

# 양식 jsonbase.json에 저장
def save(request):
    data_title = request.POST["data_title"]
    data_ret = request.POST["data_ret"]
    data_lot = json.loads(request.POST["data_lot"])

    data = {
        "form_title": data_title,
        "form_ret": data_ret,
        "lot": [],
    }

    for d in data_lot:
        d["x"] = int(d["x"]) * 4
        d["y"] = int(d["y"]) * 4
        d["w"] = int(d["w"]) * 4
        d["h"] = int(d["h"]) * 4
        d["cx"] = int(d["x"] + (d["w"] / 2))
        d["cy"] = int(d["y"] + (d["h"] / 2))
        del d["x"]
        del d["y"]
        data["lot"].append(d)

    print(data)

    j = JsonBase('jsonbase.json')
    if j.update_data(data):
        print('\nsave\n')
    else:
        print('\nfail\n')

    return redirect('admin_form_make')

# id OCR 페이지
def idcard(request):
    context = {}

    if request.method == "POST":
        image = request.FILES["ifile"]
        kind = request.POST['idcard']

        document = Document()
        document.title = kind
        document.images = request.FILES['ifile']
        document.save()

        last_img = 'media/' + str(Document.objects.last().images)
        last_num = Document.objects.last().title

        # if kind.count():
        #     # if not os.path.exists(os.path.join(base, str(request.FILES['input_file'])))
        img = cv2.imread(last_img)
        ret, _ = cv2.imencode('.jpg', img)

        if ret:
            cv2.imwrite('./media/temp2.jpg', img)
            csv_table = vision2(int(last_num), './media/temp2.jpg')

            csv_image = vision3('./media/temp2.jpg')
            context['files'] = '/media/temp2.jpg'
            context['csv_files'] = csv_table
            context['image'] = csv_image

    return render(request, 'idcard.html', context)

def pass_s(request):
    ppw = "1234"
    if request.POST.get('password') == ppw:
        return render(request, 'admin_form_make.html')
    else:
        # messages.warning(request, "입장할 수 없습니다.")
        return render(request, 'pass_s.html')


# -*- coding: utf-8 -*-
# 7. Дана матрица символов. Заменить в ней все гласные английские буквы на
# точки.
from check import *

def matrix_input(arr):
    n = checker(input("Введите кол-во строк  : "))
    m = checker(input("Введите кол-во столбцов : "))
    n = int(n)
    m = int(m)
    if n == 0 or m == 0:  # Если кол-во строк или столбцов = 0 выводим ошибку и возвращаем в начало
        print('Вы ввели нулевые значения')
        return arr
    arr.clear()
    for i in range(n):  # Вводим строку
        arr_new = list(map(str, input(f'Введите строку №{i + 1} через пробел: ').split()))
        while len(arr_new) != m:  # Пока длина строки не равна кол-ву столбцов
            print('Длина строки не соответсвует порядку матрицы')
            arr_new = list(map(str, input(f'Введите строку  №{i + 1} через пробел: ').split()))
        arr.append(arr_new)
    return arr

D = []
D = matrix_input(D)
matrix_print_f(D)
for i in range(len(D)):
    l = 0
    p = 0
    for j in range(len(D[i])):
        s = ''
        for k in D[i][j]:
            if k in "aeuioAEYUIO":
                s += '.'
            else:
                s += k
        D[i][j] = s
matrix_print_f(D)


from threading import Thread
from queue import Queue
from logging import basicConfig, info, INFO
from time import sleep
from random import randint

LOG_FORMAT = '%(asctime)s %(threadName)-17s %(levelname)-8s %(message)s'
basicConfig(level=INFO, format=LOG_FORMAT)

class Producer(Thread):
	def __init__(self, queue, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.queue = queue

	def run(self):
		for i in range(5):
			item = randint(0, 256)
			self.queue.put(item)
			info(f"Producer notify: item #{item} appended to queue by {self.name}")
			sleep(1)

class Consumer(Thread):
	def __init__(self, queue, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.queue = queue

	def run(self):
		while True:
			item = self.queue.get()
			info(f"Consumer notify: {item} popped from queue by {self.name}")
			self.queue.task_done()

if __name__=="__main__":
	queue = Queue()

	t1 = Producer(queue, name="Producer-1")
	t2 = Consumer(queue, name="Consumer-1")
	t3 = Consumer(queue, name="Consumer-2")
	t4 = Consumer(queue, name="Consumer-3")

	t1.start()
	t2.start()
	t3.start()
	t4.start()

	t1.join()
	t2.join()
	t3.join()
	t4.join()


import sys
import os
import json

sys.path.append(os.getcwd() + "/..")
from testslide import TestCase

from map.map import GLOBAL_MAP, Coordinate, Map
from communication.packet import Packet

class TestMap(TestCase):
    def setUp(self):
        super().setUp()
        self.map = Map()
        self.packet1 = Packet(1,3,7,1,0,0,0,0)
        self.packet2 = Packet(1,3,7,2,0,5,0,0)

    def test_add_obstacle(self):
        self.map.add_obstacle(self.packet1)
        coord = Coordinate(4, 7)
        self.assertTrue(coord in self.map.map)
        self.map.add_obstacle(self.packet2)
        print(self.map.distance)
        self.assertTrue(False)

    def test_global_map(self):
        self.map.add_obstacle(self.packet1)
        coord1 = Coordinate(4, 7)

        new_map = Map()
        new_map.add_obstacle(self.packet2)
        coord2 = Coordinate(5, 7)

        x = 7
        y = 8
        coord3 = Coordinate(x, y)
        self.assertTrue(coord1 in GLOBAL_MAP)
        self.assertTrue(coord2 in GLOBAL_MAP)
        self.assertTrue(coord3 not in GLOBAL_MAP)

    # def test_get_map(self):
    #     x1 = 3
    #     y1 = 7
    #     self.map.add_obstacle(self.packet1)

    #     x2 = 8
    #     y2 = 7
    #     self.map.add_obstacle(self.packet2)

    #     idx = 1
    #     map = self.map.get_map(idx)
    #     returned_map = json.loads(map)
    #     self.assertTrue(returned_map["id"] == 1)
    #     self.assertTrue(returned_map["x"] == [x2,x1])
    #     self.assertTrue(returned_map["y"] == [y2,y1])


"""Helper functions for geocoding and coordinate conversions."""

from builtins import enumerate
import requests
import json

def get_RDXY(postcode, huisnummer):
    """
    Fetches X, Y Rijksdriehoek coordinates from BAG.

    postcode:   Dutch zipcode in format '1234AB'
    huisnmmmer: house number, without any additions

    https://basisregistraties.arcgisonline.nl/arcgis/rest/services/BAG/
    """

    URL = f"https://basisregistraties.arcgisonline.nl/arcgis/rest/services/BAG/BAGv2/MapServer/0/query?where=huisnummer%3D%27{huisnummer}%27+AND+postcode+%3D+%27{postcode}%27&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=28992&having=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentOnly=false&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&featureEncoding=esriDefault&f=pjson"
    get_ = requests.get(URL.format(postcode=postcode, huisnummer=str(huisnummer)))
    try:
        return get_.json()["features"][0]["geometry"]
    except (KeyError, IndexError):
        return None

# Can't access API reference, so don't know how to code proper POST request
#
# def test(postcode, huisnummer):
#     URL = "https://basisregistraties.arcgisonline.nl/arcgis/rest/services/BAG/BAGv2/MapServer/0/query"
#     query = {'postcode': postcode,
#     'huisnummer': huisnummer,
#     'GeometryType': 'esriGeometryEnvelope',
#     'outSR': '28992',
#     'featureEncoding': 'esriDefault',
#     'f': 'pjson'
#     }
#     print(json.dumps(query))
#     response = requests.request('POST', URL, data=json.dumps(query))
# print(response.json())

class RDWGS84Converter(object):
    """
    The formulas in this class were based on a white paper by ing. F.H. Schreutelkamp from "Stichting De Koepel" and
    ir. G.L. Strang van Hees, former scholar at TU Delft.
    Unfortunately, as of January 1st 2014, the foundation "De Koepel" has halted all their activities and suspended their
    website. As the original article can no longer be found on the website, I've made sure to host
    `a backup of it <http://media.thomasv.nl/2015/07/Transformatieformules.pdf>`_ (in Dutch). Please consult this white
    paper for the origin of the coefficients used below.
    I take no credit for the formulas used, all I have done was convert the formulas into an easy to work with Python
    class for usage in other projects. All credit for the formulas go to F.H. Schreutelkamp and G.L. Strang van Hees.
    """

    x0 = 155000
    y0 = 463000
    phi0 = 52.15517440
    lam0 = 5.38720621

    # Coefficients or the conversion from RD to WGS84
    Kp = [0, 2, 0, 2, 0, 2, 1, 4, 2, 4, 1]
    Kq = [1, 0, 2, 1, 3, 2, 0, 0, 3, 1, 1]
    Kpq = [
        3235.65389,
        -32.58297,
        -0.24750,
        -0.84978,
        -0.06550,
        -0.01709,
        -0.00738,
        0.00530,
        -0.00039,
        0.00033,
        -0.00012,
    ]

    Lp = [1, 1, 1, 3, 1, 3, 0, 3, 1, 0, 2, 5]
    Lq = [0, 1, 2, 0, 3, 1, 1, 2, 4, 2, 0, 0]
    Lpq = [
        5260.52916,
        105.94684,
        2.45656,
        -0.81885,
        0.05594,
        -0.05607,
        0.01199,
        -0.00256,
        0.00128,
        0.00022,
        -0.00022,
        0.00026,
    ]
    # Coefficients for the conversion from WGS84 to RD
    Rp = [0, 1, 2, 0, 1, 3, 1, 0, 2]
    Rq = [1, 1, 1, 3, 0, 1, 3, 2, 3]
    Rpq = [
        190094.945,
        -11832.228,
        -114.221,
        -32.391,
        -0.705,
        -2.340,
        -0.608,
        -0.008,
        0.148,
    ]

    Sp = [1, 0, 2, 1, 3, 0, 2, 1, 0, 1]
    Sq = [0, 2, 0, 2, 0, 1, 2, 1, 4, 4]
    Spq = [
        309056.544,
        3638.893,
        73.077,
        -157.984,
        59.788,
        0.433,
        -6.439,
        -0.032,
        0.092,
        -0.054,
    ]

    def from_rd(self, x: int, y: int) -> tuple:
        """
        Converts RD coordinates into WGS84 coordinates
        """
        dx = 1e-5 * (x - self.x0)
        dy = 1e-5 * (y - self.y0)
        latitude = (
            self.phi0
            + sum(
                [
                    v * dx ** self.Kp[i] * dy ** self.Kq[i]
                    for i, v in enumerate(self.Kpq)
                ]
            )
            / 3600
        )
        longitude = (
            self.lam0
            + sum(
                [
                    v * dx ** self.Lp[i] * dy ** self.Lq[i]
                    for i, v in enumerate(self.Lpq)
                ]
            )
            / 3600
        )

        return latitude, longitude

    # https://github.com/thomasvnl/rd-to-wgs84
    def from_wgs84(self, latitude: float, longitude: float) -> tuple:
        """
        Converts WGS84 coordinates into RD coordinates
        """
        dlat = 0.36 * (latitude - self.phi0)
        dlon = 0.36 * (longitude - self.lam0)
        x = self.x0 + sum(
            [
                v * dlat ** self.Rp[i] * dlon ** self.Rq[i]
                for i, v in enumerate(self.Rpq)
            ]
        )
        y = self.y0 + sum(
            [
                v * dlat ** self.Sp[i] * dlon ** self.Sq[i]
                for i, v in enumerate(self.Spq)
            ]
        )

        return x, y


import random
import pyasge
from game.pathfinding import resolve
from game.catdata import CatType
from enum import IntEnum

class NodeType(IntEnum):
    SELECTOR = 1
    SEQUENCE = 2
    DECORATOR = 3
    LEAF = 4
    ROOT = 5

class BehaviourTreeRodent:
    def __init__(self, data, rodent, cats):
        # Last branch with the path to door
        self.branch4 = SequenceNode(
            [DecoratorNode(OnDoorTile(data, rodent), data), GoToDoor(data, rodent)], data)
        # Branch if cat is in agro range
        self.branch3 = SequenceNode(
            [InRangeRodent(cats, rodent, rodent.rodent_data.sight_range),
             GoToCat(data, rodent, cats)], data)
        # Branch if cat is in attack range
        self.branch2 = SequenceNode(
            [InRangeRodent(cats, rodent, rodent.rodent_data.attack_range),
             GoToCat(data, rodent, cats), AttackCat(cats, rodent, rodent.rodent_data)], data)
        # Branch if rodent is low and needs to go to spawn
        self.branch1 = SequenceNode(
            [LowHP(rodent.rodent_data, rodent.rodent_data.low_hp_range), DecoratorNode(OnSpawnTile(data, rodent), data),
             GoToSpawn(data, rodent)], data)

        self.base_selector = SelectorNode(
            [self.branch1, self.branch2, self.branch3,
             self.branch4, GoToCat(data, rodent, cats)], data)

        self.root = RootNode(self.base_selector)

    def update(self, game_time: pyasge.GameTime):
        self.root.update(game_time)

class BehaviourTreeCat:
    def __init__(self, data, cat, rodents, cat_data):
        # If RODENTS are in CAT range
        self.range_node = InRangeCat(rodents, cat, cat_data)
        # Shoot projectile at closest RODENT
        self.shoot_node = ShootProjectile(rodents, cat, cat_data)

        self.branch1 = SequenceNode([self.range_node, self.shoot_node], data)
        self.base_selector = SelectorNode([self.branch1], data)
        self.root = RootNode(self.base_selector)

    def update(self, game_time: pyasge.GameTime):
        self.root.update(game_time)

class BehaviourTreeResourceCat:
    def __init__(self, data, cat):
        # Generate yarn on a timer
        self.generate_node = GenerateYarn(data, cat)

        self.branch1 = SequenceNode([self.generate_node], data)
        self.base_selector = SelectorNode([self.branch1], data)
        self.root = RootNode(self.base_selector)

    def update(self, game_time: pyasge.GameTime):
        self.root.update(game_time)

class BehaviourTreeSlowCat:
    def __init__(self, data, cat, rodents, cat_data):
        # Slow RODENTS in range
        self.slow_node = SlowRodent(rodents, cat, cat_data)

        self.branch1 = SequenceNode([self.slow_node], data)
        self.base_selector = SelectorNode([self.branch1], data)
        self.root = RootNode(self.base_selector)

    def update(self, game_time: pyasge.GameTime):
        self.root.update(game_time)

class BehaviourTreeBoostCat:
    def __init__(self, data, cat, cats, cat_data):
        # Boost CATS in range
        self.boost_node = BoostCat(cats, cat, cat_data)

        self.branch1 = SequenceNode([self.boost_node], data)
        self.base_selector = SelectorNode([self.branch1], data)
        self.root = RootNode(self.base_selector)

    def update(self, game_time: pyasge.GameTime):
        self.root.update(game_time)

class RootNode:
    def __init__(self, child):
        # Root node, returns what is child returns
        self.type = NodeType.ROOT
        self.child = child

    def update(self, game_time: pyasge.GameTime):
        return self.child.update(game_time)

class SequenceNode:
    def __init__(self, nodes, data):
        # Sequence node, goes through children until one fails or all are gone through
        # Returns true if all children succeeded, returns false if one child fails
        self.data = data
        self.type = NodeType.SEQUENCE
        self.children = nodes

    def update(self, game_time: pyasge.GameTime):
        for child in self.children:
            update = child.update(game_time)
            if not update:
                return update
        return True

class SelectorNode:
    def __init__(self, nodes, data):
        # Selector node, goes through children until one succeeds or all are gone through
        # Returns false if all children fail, returns true if one child succeeds
        self.data = data
        self.type = NodeType.SELECTOR
        self.children = nodes

    def update(self, game_time: pyasge.GameTime):
        for child in self.children:
            update = child.update(game_time)
            if update:
                return update
        return False

class DecoratorNode:
    def __init__(self, child, data):
        # Decorator node, returns opposite of child
        self.data = data
        self.type = NodeType.DECORATOR
        self.child = child

    def update(self, game_time: pyasge.GameTime):
        return not self.child.update(game_time)

class InRangeCat:
    def __init__(self, targets, actor, data):
        # If there is a target is in range, return true [CHANGING RANGE, USED FOR CATS]
        self.targets = targets
        self.actor = actor
        self.data = data

    def update(self, game_time: pyasge.GameTime):
        att_range = self.data.attack_range * pow(self.data.stat_inc_per_level, self.data.upgrade_level-1)
        if self.data.boost_buff:
            att_range = att_range * self.data.boost_percent
        for target in self.targets:
            distance = pyasge.Point2D.distance(target.sprite.midpoint, self.actor.sprite.midpoint)
            if distance <= att_range and not target.rodent_data.invisible:
                return True
        return False

class InRangeRodent:
    def __init__(self, targets, actor, range_fixed):
        # If there is a target in range, return true [FIXED RANGE, USED FOR RODENTS]
        self.targets = targets
        self.actor = actor
        self.range = range_fixed

    def update(self, game_time: pyasge.GameTime):
        for target in self.targets:
            distance = pyasge.Point2D.distance(target.sprite.midpoint, self.actor.sprite.midpoint)
            if distance <= self.range and target.cat_data.cat_type == CatType.BLOCKER:
                self.actor.rodent_data.cat_in_range = True
                return True
        self.actor.rodent_data.cat_in_range = False
        return False

class ShootProjectile:
    def __init__(self, targets, actor, cat_data):
        # Shoot projectile at closest target
        self.targets = targets
        self.actor = actor
        self.timer = 0
        self.cat_data = cat_data

    def update(self, game_time: pyasge.GameTime):
        max_reload_timer = self.cat_data.reload_time / pow(self.cat_data.stat_inc_per_level, self.cat_data.upgrade_level-1)
        if self.cat_data.boost_buff:
            max_reload_timer = max_reload_timer / self.cat_data.boost_percent
        # If entity has had enough time between shots
        if self.timer >= max_reload_timer:
            # Find the closest target
            closest_target = None
            closest_dist = 1000
            for target in self.targets:
                distance = pyasge.Point2D.distance(target.sprite.midpoint, self.actor.sprite.midpoint)
                if distance < closest_dist and not target.rodent_data.invisible:
                    closest_dist = distance
                    closest_target = target
            # Shoot at closest target
            self.actor.cat_data.shooting = True
            self.actor.cat_data.targeted_rodent = closest_target
            self.timer = 0
        else:
            self.timer += game_time.frame_time
        return True

class LowHP:
    def __init__(self, data, low_hp):
        # Returns true if target is low hp
        self.data = data
        self.low_hp = low_hp

    def update(self, game_time: pyasge.GameTime):
        if self.data.fleeing:
            return True
        if self.data.hp <= self.low_hp:
            self.data.fleeing = True
            return True
        return False

class OnSpawnTile:
    def __init__(self, game_data, rodent):
        self.game_data = game_data
        self.rodent = rodent

    def update(self, game_time: pyasge.GameTime):
        # If rodent pos in range of game_data.spawn_tiles, de spawn the rodent and return true
        rodent_tile = self.game_data.game_map.tile(self.rodent.sprite.midpoint)
        for spawn in self.game_data.game_map.spawn_points:
            sp_point = pyasge.Point2D(spawn[0], spawn[1])
            spawn_tile = self.game_data.game_map.tile(sp_point)
            if spawn_tile == rodent_tile:
                self.rodent.rodent_data.on_spawn_tile = True
                return True
        return False

class OnDoorTile:
    def __init__(self, game_data, rodent):
        self.game_data = game_data
        self.rodent = rodent

    def update(self, game_time: pyasge.GameTime):
        # If rodent pos in range of game_data.home_points, de spawn the rodent and return true
        rodent_tile = self.game_data.game_map.tile(self.rodent.sprite.midpoint)
        for point in self.game_data.game_map.home_points:
            sp_point = pyasge.Point2D(point[0], point[1])
            spawn_tile = self.game_data.game_map.tile(sp_point)
            if spawn_tile == rodent_tile:
                self.rodent.rodent_data.on_home_tile = True
                return True
        return False

class GoToSpawn:
    def __init__(self, game_data, rodent):
        self.game_data = game_data
        self.rodent = rodent

    def update(self, game_time: pyasge.GameTime):
        # Path find to spawn
        if not self.rodent.rodent_data.update_path:
            return True
        self.rodent.rodent_data.update_path = False
        quickest_path = []
        quickest_cost = 0
        for spawn in self.game_data.game_map.spawn_points:
            path = resolve(pyasge.Point2D(spawn[0], spawn[1]), self.game_data,
                           self.rodent.sprite.midpoint, self.rodent.rodent_data.can_hidden_path)
            cost = path.pop(-1)
            if len(quickest_path) == 0 or cost < quickest_cost:
                quickest_path = path
                quickest_cost = cost
        self.rodent.destination = quickest_path
        return True

class GoToDoor:
    def __init__(self, game_data, rodent):
        self.game_data = game_data
        self.rodent = rodent

    def update(self, game_time: pyasge.GameTime):
        # Path find to door
        if not self.rodent.rodent_data.update_path:
            return True
        self.rodent.rodent_data.update_path = False
        quickest_path = []
        quickest_cost = 0
        for home_point in self.game_data.game_map.home_points:
            path = resolve(pyasge.Point2D(home_point[0], home_point[1]), self.game_data,
                           self.rodent.sprite.midpoint, self.rodent.rodent_data.can_hidden_path)
            cost = path.pop(-1)
            if len(quickest_path) == 0 or cost < quickest_cost:
                quickest_path = path
                quickest_cost = cost
        self.rodent.destination = quickest_path
        return True

class AttackCat:
    def __init__(self, targets, actor, rodent_data):
        # Attacks closest target [USED FOR RODENTS]
        self.targets = targets
        self.actor = actor
        self.timer = 0
        self.rodent_data = rodent_data

    def update(self, game_time: pyasge.GameTime):
        max_reload_timer = self.rodent_data.time_between_hits
        # If entity has had enough time between hits
        if self.timer >= max_reload_timer:
            # Find closest target
            closest_target = None
            closest_dist = 1000
            for target in self.targets:
                distance = pyasge.Point2D.distance(target.sprite.midpoint, self.actor.sprite.midpoint)
                if distance < closest_dist and target.cat_data.cat_type == CatType.BLOCKER:
                    closest_dist = distance
                    closest_target = target
            # Attack closest target
            self.actor.rodent_data.attacking = True
            self.actor.rodent_data.targeted_cat = closest_target
            self.timer = 0
        else:
            self.timer += game_time.frame_time
        #print("Attacking cat")
        return True

class GoToCat:
    def __init__(self, game_data, actor, targets):
        self.game_data = game_data
        self.actor = actor
        self.targets = targets

    def update(self, game_time: pyasge.GameTime):
        # Find closest target
        if not self.actor.rodent_data.update_path:
            return True
        self.actor.rodent_data.update_path = False
        closest_target = None
        closest_dist = 1000
        for target in self.targets:
            distance = pyasge.Point2D.distance(target.sprite.midpoint, self.actor.sprite.midpoint)
            if distance < closest_dist and target.cat_data.cat_type == CatType.BLOCKER:
                closest_dist = distance
                closest_target = target
        self.actor.rodent_data.targeted_cat = closest_target
        # Path find to target cat
        path = resolve(pyasge.Point2D(closest_target.sprite.midpoint.x, closest_target.sprite.midpoint.y),
                       self.game_data, self.actor.sprite.midpoint, self.actor.rodent_data.can_hidden_path)
        path.pop(-1)
        self.actor.destination = path
        return True

class GenerateYarn:
    def __init__(self, game_data, cat):
        self.game_data = game_data
        self.cat = cat
        self.timer = 0

    def update(self, game_time: pyasge.GameTime):
        # Inc Yarn
        if self.timer >= self.cat.cat_data.reload_time:
            self.game_data.yarn += self.cat.cat_data.yarn_per_resource
            self.timer = 0
        else:
            self.timer += game_time.frame_time

        return True

class SlowRodent:
    def __init__(self, targets, actor, data):
        # Slow all targets in range
        self.targets = targets
        self.actor = actor
        self.data = data

    def update(self, game_time: pyasge.GameTime):
        # Determines if target is in range
        att_range = self.data.attack_range * pow(self.data.stat_inc_per_level, self.data.upgrade_level-1)
        for target in self.targets:
            distance = pyasge.Point2D.distance(target.sprite.midpoint, self.actor.sprite.midpoint)
            # De buffs them if in range
            if distance <= att_range:
                target.rodent_data.slow_de_buff = True
            else:
                target.rodent_data.slow_de_buff = target.rodent_data.slow_de_buff
        return True

class BoostCat:
    def __init__(self, targets, actor, data):
        # Boost all targets in range
        self.targets = targets
        self.actor = actor
        self.data = data

    def update(self, game_time: pyasge.GameTime):
        # Determines if in range
        att_range = self.data.attack_range * pow(self.data.stat_inc_per_level, self.data.upgrade_level-1)
        for target in self.targets:
            distance = pyasge.Point2D.distance(target.sprite.midpoint, self.actor.sprite.midpoint)
            # Buffs them if in range
            if distance <= att_range:
                target.cat_data.boost_buff = True
            else:
                target.cat_data.boost_buff = False
        return True


import tensorflow as tf
from tensorflow.python.platform import gfile
from tensorflow.python.framework import tensor_util
import sys
import pickle

def read_weights(frozen_model):
    weights = {}
    with tf.Session() as sess:
        with gfile.FastGFile(frozen_model, 'rb') as f:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(f.read())
            tf.import_graph_def(graph_def)
        for n in graph_def.node:
            if n.op == 'Const':
                weights[n.name] = tensor_util.MakeNdarray(n.attr['value'].tensor)
                print("Name:", n.name, "Shape:", weights[n.name].shape)
    return weights

if len(sys.argv)  < 3:
    print("Usage: python extract_tf_weights.py <frozen_model.pb> <weights_file.pickle>")

frozen_model = sys.argv[1]
weights_file = sys.argv[2]

weights = read_weights(frozen_model)
with open(weights_file, "wb") as f:
    pickle.dump(weights, f)
    print(f"Saved weights to {weights_file}.")


import gym
from collections import deque
import numpy as np

class NstepWrapper(gym.Wrapper):
	def __init__(self, env, nstep, gamma):
		super(NstepWrapper, self).__init__(env)
		self.env = env
		self.nstep = nstep
		self.gamma = gamma

		# nstep
		self.reset_buffer()

		# multiplier
		self.discount_multiplier = np.array([gamma**i for i in range(nstep)])

	def reset_buffer(self):
		self.obs = deque(maxlen=self.nstep)
		self.obs2 = deque(maxlen=self.nstep)
		self.acts = deque(maxlen=self.nstep)
		self.rews = deque(maxlen=self.nstep)
		self.dones = deque(maxlen=self.nstep)

	def reset(self):
		self.reset_buffer()
		o = self.env.reset()
		self.obs.append(o)
		return o

	def nstep_reward(self, rlist):
		return np.sum(self.discount_multiplier * np.array(rlist))

	def step(self, action):
		o, r, done, info = self.env.step(action)
		# record
		self.obs2.append(o)
		self.rews.append(r)
		self.acts.append(action)
		self.dones.append(done)
		# add to info if necessary
		if len(self.obs2) == self.nstep:
			nstep_r = self.nstep_reward(self.rews)
			nstep_data = [self.obs[0], self.acts[0], nstep_r, self.obs2[-1], self.dones[-1]]
			info.update({'nstep_data_{}'.format(self.nstep): nstep_data})
		# record obs1
		self.obs.append(o)
		return o, r, done, info


def Func(s):
    s+='0000'
    s=s[:s.find('.')+4]
    s=s.replace('.','')
    return int(s)

def main():
    import sys
    X,Y,R=list(map(Func,sys.stdin.readline().split()))

    print(X,Y,R)

if __name__ == "__main__":
    main()


import numpy as np

def evaluate(annotation, chorus):
    # print annotation
    offset = 5
    anno_num = (len(annotation) - offset) / 2
    overlap_len = 0
    anno_len = 0
    chorus_len = 0
    chorus_num = len(chorus)
    for i in range(chorus_num):
        chorus_len += chorus[i, 1] - chorus[i, 0]

    for i in range(anno_num):
        anno = (float(annotation[i * 2 + offset]), float(annotation[i * 2 + 1 + offset]))
        for j in range(chorus_num):
            overlap_len += calculate_overlap(anno, chorus[j])
        anno_len += anno[1] - anno[0]

    recall = overlap_len / anno_len
    precision = overlap_len / chorus_len

    return recall, precision

def calculate_overlap(field_1, field_2):
    start_1 = field_1[0]
    end_1 = field_1[1]
    start_2 = field_2[0]
    end_2 = field_2[1]

    overlap_len = np.min([end_1, end_2]) - np.max([start_1, start_2])
    if overlap_len < 0:
        overlap_len = 0

    return overlap_len


import asyncio

from async_firmata.const import *

class Protocol(asyncio.Protocol):
    """asyncio Protocol responsible for data transport"""
    _connected: asyncio.Event
    _buffer: bytearray
    transport: asyncio.Transport

    def __init__(self, board) -> None:
        self.board = board
        self.loop = board.loop
        self._connected = asyncio.Event()

    def connection_made(self, transport: asyncio.Transport) -> None:
        """
        Handles a new connection
        Saves the transport and sets the connected event
        """
        self.transport = transport
        self._buffer = bytearray()
        self._connected.set()

    def data_received(self, data: bytearray) -> None:
        """
        Handles new packets
        """
        self._buffer.extend(data)

        if data[0] < SYSEX_START:
            while data:
                message_type = data[0] & 0xF0
                if message_type == ANALOG_MESSAGE:
                    asyncio.ensure_future(
                        self.board.handle_analog_message(data[0] & 0x0F, data[1], data[2]))
                    data = data[3:]
                elif message_type == DIGITAL_MESSAGE:
                    print(data)
                    asyncio.ensure_future(
                        self.board.handle_digital_message(data[0] & 0x0F, data[1], data[2]))
                    data = data[3:]
                else:
                    break

        while SYSEX_END in self._buffer and SYSEX_START in self._buffer:
            del self._buffer[:self._buffer.index(SYSEX_START)+1]
            sysex_message = self._buffer[:self._buffer.index(SYSEX_END)]
            del self._buffer[:self._buffer.index(SYSEX_END)+1]

            asyncio.ensure_future(self.board.handle_sysex_command(sysex_message[0], sysex_message[1:]))

    def connection_lost(self, exc: Exception) -> None:
        self._connected.clear()

    async def write(self, packet: bytearray) -> None:
        await self._connected.wait()
        return self.transport.write(packet)

    @property
    def connected(self) -> bool:
        return self._connected.is_set()

    def close(self) -> None:
        if self.connected:
            self.transport.close()


import numpy as np

class perceptron(object):
    def __init__(self,no_of_inputs,threshold=10,learning_rate=0.1):
        self.threshold = threshold
        self.learning_rate = learning_rate
        self.weights = np.zeros(no_of_inputs+1)

    def predict(self,inputs):
         summation = np.dot(inputs,self.weights[1:]) + self.weights[0]
         if summation > 0:
             return 1
         else:
              return 0

    def fit(self,training_inputs,label):
          for _ in range(self.threshold):
              for inputs,label in zip(training_inputs,label):
                  p=self.predict(inputs)
                  self.weights[1:]+= self.learning_rate*(label-p)*inputs
                  self.weights[0]+=  self.learning_rate*(label-p)

model = perceptron(3)
training_inputs = ([[0,0,0],[0,1,0],[1,0,0],[1,1,0],[1,0,1],[0,1,1],[0,0,1],[1,1,1]])
label = ([[0],[1],[1],[0],[],[],[],[]])
model.fit(training_inputs,label)

#test :
test = np.array([1,0,1])
print(model.predict(test))


from base.views import supplier_views as views
from django.urls import path

urlpatterns = [
    path('', views.getSuppliers, name='suppliers'),
    path('upload/', views.uploadImage, name='image-upload'),
    path('<str:pk>/', views.getSupplier, name='supplier'),
    path('<str:pk>/reviews/', views.createSupplierReview, name='create-review'),
    path('<str:pk>/products/', views.getSupplierProducts, name='supplier-products'),
    path('<str:pk>/products/<str:pk2>/', views.getSupplierProduct, name='supplier-product'),
    path('user/<str:pk>/', views.getSupplierByUserId, name='user-supplier'),
]


import nltk
from tqdm import tqdm_notebook as tqdm
import pickle
import  os
import spacy
import nltk
import pandas as pd
from tqdm import tqdm
from sarvam.colorful_logger import *
# Find how often each Category used each word
# import en_core_web_lg
# nlp = spacy.load('en_core_web_sm')

def tokenize(df: pd.DataFrame, text_col, nlp):
    '''
    In place tokenization on text column
    :param df: Pandas Dataframe
    :par am text_col: Text Column
    :return:
    '''

    if not nlp:
        print_error("Do a global initilization nlp = spacy.load('en_core_web_sm')")
        raise Warning("Initialize nlp = spacy.load('en_core_web_sm')")

    def cleaning(sentence):
        sentence = nlp(str(sentence))
        tokens = [token.text for token in sentence]
        tokens = ' '.join(tokens)
        return tokens

    # df = df.assign(spacy_processed = lambda rows : rows[text_col].map(lambda row: cleaning(row)))
    data = [cleaning(line) for line in tqdm(df[text_col].tolist())]
    df[text_col] = data
    return df

def extract_lemmas(df: pd.DataFrame, text_col, nlp):

    stopwords = nltk.corpus.stopwords.words('english')

    def cleaning(sentence):
        sentence = nlp(sentence)
        tokens = [token.lemma_+"_"+token.pos_ for token in sentence
                  if not token.is_punct | token.is_space | token.is_bracket | (token.text in stopwords)]
        tokens = ' '.join(tokens)
        return tokens

    df = df.assign(nlp_processed = lambda rows : rows[text_col].map(lambda row: cleaning(row)))

    return df

def doc_to_integers(df: pd.DataFrame, text_col, nlp=spacy.load('en')):
    stopwords = nltk.corpus.stopwords.words('english')

    def cleaning(sentence):
        sentence = nlp(sentence)
        tokens = [token.orth + token.lemma + token.pos for token in sentence if not token.is_punct | token.is_space | token.is_bracket | (token.text in stopwords)]
        return tokens

    df = df.assign(nlp_processed = lambda rows : rows[text_col].map(lambda row: cleaning(row)))

    return df

#Refence: https://www.kaggle.com/mageswaran/beginner-s-tutorial-python/editnb
class ConditionalWordFreq:

    def __init__(self):
        # word frequency by category
        self.wordFreqByCategory = None

    def fit(self, df, tex_col, category_col):

        self.wordFreqByCategory = nltk.probability.ConditionalFreqDist()

        by_category = df.groupby(category_col)
        for category, group in tqdm(by_category):
            sentences = group[tex_col].str.cat(sep = ' ')

            sentences = sentences.lower()

            tokens = nltk.tokenize.word_tokenize(sentences)

            frequency = nltk.FreqDist(tokens)

            self.wordFreqByCategory[category] = (frequency)

        wordFreqByCategoryFile = open('wordFreqByCategory.pickle', 'wb')
        pickle.dump(self.wordFreqByCategory, wordFreqByCategoryFile)

    def load(self):
        if os.path.exists('wordFreqByCategory.pickle') and self.wordFreqByCategory is None:
            self.wordFreqByCategory = pickle.load(open('wordFreqByCategory.pickle', 'rb'))

    def category_probabilities(self, word):
        for category in self.wordFreqByCategory.keys():
            print('Probability of' + word + '  in ' + category + ' is ' + str(self.wordFreqByCategory[category].freq(word)))


'''
PYTHON CODE TO TEST THE TRAINED KERAS MODEL
'''
# import the necessary packages
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import numpy as np
import imutils
import cv2

# load the image
image = cv2.imread('M:\\Tericsoft\\Teric_Research\\keras-data-augmentation\\dogs_vs_cats_small\\cats\\cats_00001.jpg')
orig = image.copy()

# pre-process the image for classification
image = cv2.resize(image, (28, 28))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)

# load the trained convolutional neural network
print("[INFO] loading network...")
model = load_model('M:\\Tericsoft\\Teric_Research\\image-classification-keras\\cats_and_dogs.model')

# classify the input image
(dog, cat) = model.predict(image)[0]

# build the label
label = "cat" if cat > dog else "dog"
proba = cat if cat > dog else dog
label = "{}: {:.2f}%".format(label, proba * 100)

# draw the label on the image
output = imutils.resize(orig, width=400)
cv2.putText(output, label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX,
	0.7, (0, 255, 0), 2)

# show the output image
cv2.imshow("Output", output)
cv2.waitKey(0)


import requests
import bs4
from bs4 import BeautifulSoup as bs

url = 'https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53'}

data = requests.get(url, headers=headers)

soup = bs(data.text, 'html.parser')
td = soup.select("#old_content > table > tbody > tr")

for i in td:
    movie = []
    td_num = i.select_one('.ac > img')
    td_title = i.select_one('div > a')
    td_point = i.select_one('.point')
    if td_title is not None:
        movie.append(td_num['alt'] + " " +td_title.text + " " + td_point.text)
        movie = movie[0]
        print(movie)


# coding=utf-8
from __future__ import unicode_literals, absolute_import

from dynamic_scraper.spiders.django_spider import DjangoSpider

from swgoh.units import models

class UnitsSpider(DjangoSpider):
    name = 'units_spider'
    custom_settings = {
        'ITEM_PIPELINES': {
            'dynamic_scraper.pipelines.DjangoImagesPipeline': 200,
            'dynamic_scraper.pipelines.ValidationPipeline': 400,
            'swgoh.units.scraper.pipelines.DjangoWriterPipeline': 800,
        }
    }

    def __init__(self, *args, **kwargs):
        self._set_ref_object(models.UnitPage, **kwargs)
        self.scraper = self.ref_object.scraper
        self.scrape_url = self.ref_object.url
        self.scheduler_runtime = self.ref_object.scraper_runtime
        if self.ref_object.unit_type == 0:
            self.scraped_obj_class = models.Character
            self.scraped_obj_item_class = models.CharacterItem
        else:
            self.scraped_obj_class = models.Ship
            self.scraped_obj_item_class = models.ShipItem
        super(UnitsSpider, self).__init__(self, *args, **kwargs)


# B. Trouble Sort
t = int(input())
for i in range(t):
  n = int(input())
  a = [int(val) for val in input().split()]
  b = [int(val) for val in input().split()]
  # if a is sorted, then "Yes"
  # otherwise, check if b is same type
  # how to check if it's sorted or not
  isSorted = True
  # how to check if same type
  isSameType = True
  for j in range(1, n):
    if a[j] < a[j-1]:
      isSorted = False
    if b[j] != b[j-1]:
      isSameType = False

  if isSorted or not isSameType:
    print("Yes")
  else:
    print("No")


from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process_data', methods=['POST'])
def process_data():
    data = request.json

    result = {'message': 'Dados recebidos com sucesso!', 'data': data}
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)