import discord
from discord.ext import commands
import discord.utils
import yaml
import asyncio
import math
import contextvars
import sys
import datetime
import re

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)

config = None

atc_timer_tasks = {}

def is_finite(x):
    return not math.isnan(x) and not math.isinf(x)

def load_config():
    global config

    with open("config.yml", "r") as f:
        config = yaml.safe_load(f)

class DiscordObjs:
    __slots_ = ("guild", "atc_role")

    def __init__(self):
        self.guild = None
        self.atc_role = None

discord_objs = DiscordObjs()

def load_discord_objs(bot_local):
    global config

    discord_objs.guild = bot_local.get_guild(config["guild_id"])
    discord_objs.atc_role = discord.utils.get(discord_objs.guild.roles, id=config["atc_role_id"])

def pretty_local_time():
    return datetime.datetime.now().strftime('%Y-%m-%d %I:%M %p')

GENERIC_HELP_MESSAGE = """Here are some examples of how to use the command:
- `!c`: Announces you are available for 1 hour.
- `!c 2h` OR `!c 2` OR `!c 2:00`: Announces you are available for 2 hours.
- `!c 1h45m` OR `!c 1.75` OR `!c 1:45`: Announces you are available for 1 hour and 45 minutes.
- `!c 15m` OR `!c 0.25` OR `!c 0:15`: Announces you are available for 15 minutes."""

duration_regex = re.compile(r"^(?:([0-9]+)h)?(?:([0-9]+)m)?$")
duration_2_regex = re.compile(r"^([0-9]+):([0-9]{2})?$")

def parse_hours_only(param):
    hours = None

    try:
        hours = float(param)
        if not is_finite(hours):
            hours = None
    except ValueError:
        pass

    return hours

def parse_complex_duration(param):
    duration = None
    #error_message = None

    match_obj = duration_regex.match(param)
    if not match_obj:
        match_obj = duration_2_regex.match(param)

    if match_obj:
        hours = match_obj.group(1)
        minutes = match_obj.group(2)
        if hours is not None or minutes is not None:
            if hours is None:
                hours = 0
            if minutes is None:
                minutes = 0

            try:
                duration = int(hours) * 3600 + int(minutes) * 60
            except ValueError:
                pass

    return duration

def parse_duration(param):
    error_message = None
    duration = None

    if len(param) > 10:
        error_message = f"To prevent memory errors, the provided duration can be at most 10 characters long. {GENERIC_HELP_MESSAGE}"
    else:
        if param == "":
            duration = 3600
        else:
            hours = parse_hours_only(param)
            if hours is not None:
                duration = int((((hours * 3600) + 30) // 60) * 60)
            else:
                duration = parse_complex_duration(param)

        if duration is None:
            error_message = f"Please provide how long you are Available to Countdown for. {GENERIC_HELP_MESSAGE}"
        elif duration == 0:
            error_message = f"You cannot say that you are Available to Countdown for 0 hours. {GENERIC_HELP_MESSAGE}"
        elif duration < 0:
            error_message = f"You cannot say that you are Available to Countdown for less than 0 hours. {GENERIC_HELP_MESSAGE}"
        elif duration > 86400:
            error_message = f"You cannot say that you are Available to Countdown for more than 24 hours (so people don't forget to become unavailable). {GENERIC_HELP_MESSAGE}"

    return duration, error_message

def generate_duration_str(duration_as_minutes):
    #print(f"duration_as_minutes: {duration_as_minutes}")
    minutes = duration_as_minutes % 60
    hours = duration_as_minutes // 60

    duration_str_parts = []

    if hours != 0:
        if hours == 1:
            hours_str = f"{hours} hour"
        else:
            hours_str = f"{hours} hours"

        duration_str_parts.append(hours_str)

    if minutes != 0:
        if minutes == 1:
            minutes_str = f"{minutes} minute"
        else:
            minutes_str = f"{minutes} minutes"

        duration_str_parts.append(minutes_str)

    duration_str = f"{' and '.join(duration_str_parts)} ({hours}:{minutes:02d})"

    return duration_str

async def handle_available_timer(duration_as_minutes, user_id):
    #print(f"Duration as minutes: {duration_as_minutes}")
    duration = duration_as_minutes * 60
    await asyncio.sleep(duration)
    #print("After sleep")
    member = discord_objs.guild.get_member(user_id)
    print(f"Removing {member.name} from atc timer")
    await member.remove_roles(discord_objs.atc_role)

def add_atc_timer_task(user_id, duration_as_minutes):
    atc_timer_tasks[user_id] = asyncio.create_task(handle_available_timer(duration_as_minutes, user_id))

def cancel_atc_timer_task(user_id):
    atc_timer_task = atc_timer_tasks.get(user_id)
    # overwrite if existing
    if atc_timer_task is not None and not atc_timer_task.done():
        atc_timer_task.cancel()
        atc_timer_tasks[user_id] = None

async def add_atc_role_and_setup_timer_for_user(member, duration_as_minutes):
    cancel_atc_timer_task(member.id)
    await member.add_roles(discord_objs.atc_role)
    add_atc_timer_task(member.id, duration_as_minutes)

async def print_and_send(ctx, message):
    print(f"[{pretty_local_time()}] {message}")
    await ctx.send(message)

@bot.command()
async def c(ctx):
    response_contents = ""
    param = ctx.message.content.strip().split(maxsplit=1)
    if len(param) == 1:
        param = ""
    else:
        param = param[1]

    duration, error_message = parse_duration(param)
    if error_message is not None:
        await print_and_send(ctx, f"Error: {error_message}")
    else:
        duration_as_minutes = max(duration//60, 1)
        duration_str = generate_duration_str(duration_as_minutes)

        member = ctx.message.author

        await add_atc_role_and_setup_timer_for_user(member, duration_as_minutes)
        response_contents = f"You are now available to Countdown for {duration_str}, {ctx.message.author.name}"
        await print_and_send(ctx, response_contents)

@bot.command()
async def d(ctx):
    member = ctx.message.author
    cancel_atc_timer_task(member.id)
    await member.remove_roles(discord_objs.atc_role)
    response_contents = f"You are no longer available to Countdown, {member.name}"
    await print_and_send(ctx, response_contents)

@bot.event
async def on_ready():
    print("Running!")
    load_discord_objs(bot)

def main():
    load_config()

    token = config["token"]
    bot.run(token)

if __name__ == "__main__":
    main()


import torch.optim as optim
import matplotlib.pyplot as plt
from data.fer2013plus import *
from model.VGG import *
import datetime

epoch_print_gap = 1

def train_loop(config, checkpoint_dir=None, n_epochs=0, model=None, train_data=None, val_data=None):
    use_cuda = True
    device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")

    optimizer = optim.SGD(model.parameters(), lr=config["lr"], weight_decay=config['weight_decay'],
                          momentum=config['momentum'])

    criterion = nn.CrossEntropyLoss()

    train_loader = DataLoader(train_data, batch_size=config["batch_size"])
    val_loader = DataLoader(val_data)
    model = model.to(device)

    best_val_acc = 0
    best_val_epoch = 0

    train_losses = []
    train_accs = []
    val_losses = []
    val_accs = []

    path = '../model'

    for epoch in range(1, n_epochs + 1):
        loss_train = 0.0
        correct_train = 0
        train_steps = 0
        total_train = 0
        model.train()

        if epoch >= 50:
            for group in optimizer.param_groups:
                factor = 0.9 ** ((epoch - 80) // 5)
                group['lr'] = group['lr'] * factor

        for data in train_loader:

            imgs = data['Image']
            labels = data['Label']
            imgs, labels = imgs.to(device), labels.to(device)

            optimizer.zero_grad()

            outputs = model(imgs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            loss_train += loss.item()
            _, predicted = torch.max(outputs.data, 1)
            total_train += labels.size(0)
            correct_train += (predicted == labels).sum().item()
            #             correct_train += predicted.eq(labels.data).sum()

            train_steps += 1

        train_acc = 100 * correct_train / total_train
        train_losses.append(loss_train / train_steps)
        train_accs.append(train_acc)

        if epoch == 1 or epoch % epoch_print_gap == 0:
            print('{} Epoch {}, Training loss {}, Training Accuracy {}'.format(
                datetime.datetime.now(), epoch, train_losses[-1], train_acc))

        # Evaluation
        loss_val = 0
        val_steps = 0
        correct_val = 0
        total_val = 0
        model.eval()
        with torch.no_grad():
            for data in val_loader:
                inputs = data['Image']
                bs, ncrops, c, h, w = inputs.shape
                inputs = inputs.view(-1, c, h, w)

                targets = data['Label']

                inputs, targets = inputs.to(device), targets.to(device)
                #                 inputs, targets = inputs.to(device), targets.type(torch.FloatTensor).to(device)

                outputs = model(inputs)
                # combine results across the crops
                outputs = outputs.view(bs, ncrops, -1)
                outputs = torch.sum(outputs, dim=1) / ncrops

                loss = criterion(outputs, targets)
                loss_val += loss.cpu().numpy()

                _, predicted = torch.max(outputs.data, 1)
                total_val += targets.size(0)
                correct_val += (predicted == targets.data).sum().item()
                #                 correct_val += predicted.eq(targets.data).sum()

                #                 val_loss += loss.cpu().numpy()
                val_steps += 1

            val_acc = 100 * correct_val / total_val
            val_losses.append(loss_val / val_steps)
            val_accs.append(val_acc)

            validtaion_loss = loss_val / val_steps
            print('Validation loss {}, Validation accuracy {}'.format(val_losses[-1], val_acc))

            if val_acc > best_val_acc:
                print("saving..")
                print("best_PublicTest_acc: %0.3f" % val_acc)

                state = {
                    'model': model.state_dict() if use_cuda else model,
                    'acc': val_acc,
                    'epoch': epoch,
                }

                if not os.path.isdir(path):
                    os.mkdir(path)

                torch.save(state, os.path.join(path, 'PublicTest_model.t7'))
                best_val_acc = val_acc
                best_val_epoch = epoch

    # Plotting loss and accuracy curves
    plt.plot(train_losses, label='Training loss')
    plt.plot(val_losses, label='Validation loss')
    plt.legend()
    plt.show()

    plt.plot(train_accs, label='Training accuracy')
    plt.plot(val_accs, label='Validation accuracy')
    plt.legend()
    plt.show()

######################################################################
train_dataset = Fer2013(csv_file='./FER2013plus/FER2013Train/label.csv',
                        root_dir='./FER2013plus/FER2013Train',
                        transform=transforms.Compose([ToTensor()]),
                        mode="train")

validation_dataset = Fer2013(csv_file='./FER2013plus/FER2013Valid/label.csv',
                             root_dir='./FER2013plus/FER2013Valid',
                             transform=transforms.Compose([ToTensor()]),
                             mode = 'val')

model = VGG16(num_classes=8)

n_epochs = 40
config = {'lr': 0.01, 'batch_size': 128, 'weight_decay': 5e-4, 'momentum': 0.9}
train_loop(
    config = config,
    n_epochs = n_epochs,
    model = model,
    train_data = train_dataset,
    val_data = validation_dataset,
)


# -*- coding: utf-8 -*-
"""
    Author:1112
    Date:2023-09-04
    Update: ---
    Achieve:pywinauto知识点记录
"""

'''
    链接资料:
        具体例子：https://www.cnblogs.com/xp1315458571/p/13892205.html#_lab20_1
        pywinauto作者个人网页，可以提问：https://stackoverflow.com/users/3648361/vasily-ryabov
        github连接：https://github.com/yangtianyong/pywinauto
'''

'''
    使用UIspy进行元素的定位，定位属性一般使用：ClassName、Name、ProcessId、AutomationId
    pywinauto:
    支持控件访问技术：Win32 API MS UI Automation  uia
    Application:作用范围是一个进程，如一般桌面应用程序
    Desktop:作用范围可以跨进程，主要用于一个程序可以包含多个进程(实例)的程序
    辅助检查工具：Inspect.exe、spy++.exe、ViewWizard、UISpy.exe

    控件分类：
    状态栏：StatusBar          静态内容：Static
    按钮：Button               复选框：CheckBox
    单选框：RadioButton        组框：GroupBox
    组合框：ComboBox           对话框：Dialog
    编辑栏：Edit               头部内容：Header
    列表框：ListBox            选项卡控件：TabControl
    工具栏：Toolbar            工具提示：ToolTips
    树状视图：Tree View         菜单：Menu
    菜单项：MenuItem            窗格：Pane
'''

from pywinauto import Application
from pywinauto.keyboard import send_keys
import time
from pywinauto import mouse

# --------------------------  启动软件和连接已经打开的软件  ------------------------------------
# 使用地址来启动软件
# app = Application(backend="uia").start(r"D:\notepad\Notepad++\notepad++.exe")
# 连接已经打开的应用程序 -- 方式一：通过进程号  -- 方式二：通过窗口句柄 --- 可以通过ViewWizard查看到
# app = Application("uia").connect(process=4132)

# --------------------------  选择窗口  ----------------------------------------------------
#获取应用程序所有的窗口
# app.windows()
# 根据类名选择窗口
# dlg = app["Notepad++"]
# 根据标题选择窗口
# dlg = app["new 1 - Notepad++"]
# 打印窗口中所有的控件
# dlg.print_control_identifiers()

# --------------------------  窗口操作  ----------------------------------------------------
#窗口最大化
# dlg.maximize()
#窗口最小化
# dlg.minimize()
#窗口恢复正常大小
# dlg.restore()
#查看窗口显示状态,最大化：1；正常：0
# dlg.get_show_state()
#关闭窗口
# dlg.close()
#获取窗口坐标 -- 这个后续可能会用到
# rect = dlg.rectangle()
# print(rect)

# --------------------------  窗口控件选择  ------------------------------------------------
#选择控件
# menu = dlg["应用程序Menu"]
#  这种方式有时候会选择失效，则需要用下面一种方法选取
#file1 = menu["文件(F)"]
# file = menu.child_window(title="文件(F)")

# --------------------------  获取控件属性  ------------------------------------------------
#查看控件类型
# print(menu.wrapper_object())
# print(file.wrapper_object())
#获取控件文本内容
# print(file.texts())
#获取控件子元素
# print(menu.children())
#获取控件类名
# print(dlg.class_name())
#获取控件属性，返回值是字典
# print(menu.get_properties())
#窗口和控件截图处理  #若报错，运行 pip install image
# pic = dlg.capture_as_image()
# print(pic)
# pic.save("01.png")

# --------------------------  获取子菜单项  ------------------------------------------------
# 获取菜单的子菜单项
# print(menu.items())
#通过下标选择菜单项
# m = menu.item_by_index(0)
#通过路径选择菜单项
# T_save = menu.item_by_path("搜索->替换(R)...")
# T_save = menu.item_by_path("文件")

# --------------------------  菜单项点击  --------------------------------------------------
#点击菜单项
# file.click_input()
# T_save.click_input()

# --------------------------  等待机制 ----------------------------------------------------
'''
    等待机制： wait()方法：
    参数：wait_for:
        exists:表示该窗口是有效的句柄
        visible:表示该窗口未隐藏
        enabled:表示未禁用的窗口
        ready:表示该窗口可见并启用
        active：表示该窗口处于活动状态
    timeout:超时时间
    retry_interval:重试时间间隔
'''

#连接新的窗口
# new_dlg = app["另存为"]  # 这种情况有时候会报错，可以使用下面的方法
# new_dlg = dlg.child_window(title="替换")
# new_dlg.print_control_identifiers()
# new_dlg.wait(wait_for="ready",timeout=10,retry_interval=1)
# print("等待通过")

# --------------------------  键盘操作模块 -------------------------------------------
#按F1
# send_keys("{F1}")   #或者 send_keys("{VK_F1}")
#输入字母
# send_keys("A")

#example 通过按键操作进入cmd  打开python
# send_keys("{VK_LWIN}")
# send_keys("cmd")
# send_keys("{VK_RETURN}")
# send_keys("{VK_LWIN}cmd{VK_RETURN}")
# #延时等待
# time.sleep(2)
# send_keys("python")
# send_keys("{VK_RETURN}")

# --------------------------  键盘操修饰符 --------------------------------------------
'''
    "+"   -> 按Shift
    "^"   -> 按Ctrl
    "%"   -> 按Alt
    "^s"  -> 按Ctrl+S进行保存的操作
'''
# send_keys("^+n")

'''
    click            鼠标单击
    double_click     鼠标双击
    right_click      鼠标右击
    wheel_click      鼠标中间点击
'''
# mouse.click(coords=())       # 鼠标左键 通过像素坐标确认位置
# mouse.right_click(coords=)   # 鼠标右键 通过像素坐标确认位置
# mouse.double_click(coords=)  # 鼠标双击 通过像素坐标确认位置
#按下鼠标,运行后鼠标不会主动释放
# mouse.press(coords=)
#释放鼠标
# mouse.release(coords=)
#滑动鼠标滚轮 wheel_dist滚动的次数  +-表示往上滚动或者往下滚动
# mouse.scroll(coords=(),wheel_dist=1)
#移动鼠标位置
# mouse.move(coords=)

def exampleNotpad():
    #运行
    app = Application(backend="uia").start(r"D:\notepad\Notepad++\notepad++.exe")
    #连接主窗口
    dlg = app["Notepad++"]
    # 写入内容
    dlg["Pane0"].type_keys("hello, pywinauto")
    #菜单栏
    menu = dlg["应用程序Menu"]
    #选择
    T_repl = menu.item_by_path("搜索->替换(R)...")
    #点击
    T_repl.click_input()
    # 选择新窗口
    repl = dlg["替换"]
    # repl = dlg.child_window(title="替换")
    repl.wait(wait_for="ready",timeout=10,retry_interval=1)
    print("替换窗口ready检测成功")
    #查找新窗口下所有属性
    repl.print_control_identifiers()
    #选择查找目标编辑框
    repl.child_window(title="Edit")
    #工具类型的控件不能直接输入内容，需要点击选中 -- 从键盘输入

# exampleNotpad()

'''
    备注：
    1、有一些控件无法点击，需要通过鼠标的操作实现点击的功能;
    2、行为封装;
    3、一般会与其他工具结合起来：Unittest、Selenium;

'''


import csv, time, random
from sklearn.neighbors import LocalOutlierFactor
from sklearn.metrics import mean_squared_error

RESULTS = []

def load_dataset(file):
    instances = []
    targets = []
    training_dict = {}

    with open(file) as csvfile:
        csvreader = csv.reader(csvfile)
        for tokens in csvreader:
            row = []
            for x in range(0, len(tokens)):
                try:
                    if x == 2:
                        row.append(tokens[x])
                    else:
                        row.append(float(tokens[x]))
                except:
                    if x not in training_dict:
                        training_dict[x] = {}
                    if tokens[x] not in training_dict[x]:
                        training_dict[x][tokens[x]] = len(training_dict[x])
                    row.append(training_dict[x][tokens[x]])

            # only include 1% of actual injected processes
            if row[-1] == 0.0 or random.randint(0, 99) < 1:
                instances.append(row[:-1])
                targets.append(row[-1])
    return [instances, targets]

def check_accuracy(targets, scores, threshold, instances):
    fal_pos = 0
    fal_neg = 0
    tru_pos = 0
    tru_neg = 0

    guesses = []

    for x in range(0, len(targets)):
        lt_threshold = scores[x] < threshold

        if lt_threshold and targets[x] == 1:
            tru_pos += 1
            guesses.append(1)
        if lt_threshold and targets[x] == 0:
            fal_pos += 1
            guesses.append(1)
        if not lt_threshold and targets[x] == 1:
            fal_neg += 1
            guesses.append(0)
        if not lt_threshold and targets[x] == 0:
            tru_neg += 1
            guesses.append(0)

    # calculate the precision and accuracy
    # precision = TP / (TP + FP)
    if tru_pos + fal_pos > 0:
        precision = float(tru_pos) / (float(tru_pos) + float(fal_pos))
    else:
        precision = "0/0"
    if (float(fal_pos) + float(fal_neg) + float(tru_pos) + float(tru_neg)) > 0:
        accuracy = (float(tru_pos) + float(tru_neg)) / (float(fal_pos) + float(fal_neg) + float(tru_pos) + float(tru_neg))
    else:
        precision = "0/0"
    recall = float(tru_pos) / (float(tru_pos) + float(fal_neg))
    rmse = mean_squared_error(guesses, targets)

    print("False Positive: ", end="")
    print(fal_pos)
    print("False Negative: ", end="")
    print(fal_neg)
    print("True Positive: ", end="")
    print(tru_pos)
    print("True Negative: ", end="")
    print(tru_neg)
    print("Precision: ", end="")
    print(precision)
    print("Accuracy: ", end="")
    print(accuracy)
    print("Recall: ", end="")
    print(recall)
    print("RMSE:", end="")
    print(rmse)

    r = {}
    r["FP"] = fal_pos
    r["FN"] = fal_neg
    r["TP"] = tru_pos
    r["TN"] = tru_neg
    r["precision"] = precision
    r["accuracy"] = accuracy
    r["recall"] = recall
    r["rmse"] = rmse
    return r

def run_test():
    global RESULTS
    dataset = load_dataset("master_dataset_v6.csv")

    training = []
    # only select certain fields
    for p in dataset[0]:
        instance = []
        instance.append(p[1])
        instance.append(p[18])
        instance.append(p[-1])
        instance.append(p[-5])
        instance.append(p[-6])
        current = p[2].split(",")
        training.append(instance)

    lof = LocalOutlierFactor(n_neighbors=3)
    bools = lof.fit_predict(training)
    scores = lof.negative_outlier_factor_
    targets = []

    for x in range(0, len(scores)):
        targets.append(dataset[1][x])

    r = check_accuracy(targets, scores, -1, dataset[0])

    RESULTS.append(r)

    # get an average so far
    avg_precision = 0
    avg_accuracy = 0
    avg_recall = 0
    avg_rmse = 0

    for r in RESULTS:
        avg_precision += r["precision"]
        avg_accuracy += r["accuracy"]
        avg_recall += r["recall"]
        avg_rmse += r["rmse"]

    print("Average Precision: ", end="")
    print(avg_precision / len(RESULTS))
    print("Average Accuracy: ", end="")
    print(avg_accuracy / len(RESULTS))
    print("Average Recall: ", end="")
    print(avg_recall / len(RESULTS))
    print("Average RMSE: ", end="")
    print(avg_rmse / len(RESULTS))

# perform 1000 tests, average the results as we go
for x in range(0, 25):
    print("Iteration "+str(x))
    run_test()
    print("-----------------------------------")


import datetime, jwt, time
from app.dao.userDao import UserDao
from flask import jsonify
from .. import common
class Auth():
    @staticmethod
    def encode_auth_token(user_id, login_time):
        """
        生成认证Token
        :param user_id: int
        :param login_time: int(timestamp)
        :return: string
        """
        try:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=10),
                'iat': datetime.datetime.utcnow(),
                'iss': 'ken',
                'data': {
                    'id':user_id,
                    'login_time': login_time
                }
            }
            return jwt.encode(
                payload,
                'secret',
                algorithm='HS256'
            )
        except Exception  as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        """
        验证Token
        :param auth_token:
        :return: integer|string
        """
        try:
            payload = jwt.decode(auth_token, 'secret', options= {'verify_exp':False})
            if ('data' in payload and 'id' in payload['data']):
                return payload
            else:
                raise jwt.InvalidTokenError

        except jwt.ExpiredSignatureError:
            return "Token过期"
        except jwt.InvalidTokenError:
            return "无效的Token"

    def authenticate(self, username, password):
        """
        用户登录，登录成功返回token，写将登录时间写入数据库；登录失败返回失败原因
        :param password:
        :return: json
        """
        userDao = UserDao()
        user = userDao.search(username)
        if (user is None):
            return jsonify(common.falseReturn('', '找不到用户'))
        else:
            if (user.password == password):
                login_time = int(time.time())
                token = self.encode_auth_token(user.username, login_time)
                return jsonify(common.trueReturn(token.decode(), '登陆成功'))
            else:
                return jsonify(common.falseReturn('', '密码不正确'))

    def identify(self, request):
        """
        用户鉴权
        :return: list
        """
        auth_header = request.headers.get('Authorization')
        if (auth_header):
            auth_tokenArr = auth_header.split(" ")
            if (not auth_tokenArr or auth_tokenArr[0]!= 'JWT' or len(auth_tokenArr) != 2 ):
                result = common.falseReturn('','请传递正确的验证头信息')
            else:
                auth_token = auth_tokenArr[1]
                payload = self.decode_auth_token(auth_token)
                if not isinstance(payload, str):
                    userDao = UserDao()
                    user = userDao.search(payload['data']['id'])
                    if (user is None):
                        result = common.falseReturn('', '找不到该用户信息')
                    else:
                        result = common.trueReturn('', '请求成功')
                else:
                    result = common.falseReturn('', payload)
        else:
            result = common.falseReturn('','没有提供认证token')
        return result


import inspect
from typing import Union, Callable, AbstractSet, Mapping, Any, Dict, ClassVar
from pydantic.main import BaseModel
from pydantic.parse import load_str_bytes

IntStr = Union[int, str]
AbstractSetIntStr = AbstractSet[IntStr]
MappingIntStrAny = Mapping[IntStr, Any]
DictStrAny = Dict[str, Any]

__all__ = ['DecoderModelMetaclass', 'DecoderModel', 'encode', 'decode',  # 'field_property',
           'get_model_name', 'get_model', 'register_model', 'remove_model']

MODEL_TYPES = {}

def get_model_name(cls: Union[type, object] = None) -> str:
    """Return the model name for the given class."""
    if not inspect.isclass(cls):
        cls = cls.__class__
    return '{}.{}'.format(cls.__module__, cls.__name__)

def get_model(name: str) -> type:
    """Return the model type from the given model name."""
    return MODEL_TYPES[name]

def register_model(name: Union[str, type] = None, cls: type = None) -> Union[type, Callable]:
    """Register the given type for decoding."""
    # Check if class is given as first argument
    if name is not None and not isinstance(name, str):
        cls = name
        name = None

    # Check if decorator needs to be returned
    if cls is None:
        def decorator(cls: type = None):
            return register_model(name, cls)
        return decorator

    # Create a name if needed
    if name is None:
        name = get_model_name(cls)

    # Save the type and return the class (for decorator use)
    MODEL_TYPES[name] = cls
    return cls

def remove_model(cls: Union[str, type]):
    """Remove the type registered with the given name or class type."""
    try:
        # Try removing with string name
        MODEL_TYPES.pop(cls)
    except (KeyError, Exception):
        # Find the model and remove it
        try:
            for k, v in MODEL_TYPES.items():
                if v == cls:
                    MODEL_TYPES.pop(k)
                    break
        except (KeyError, Exception):
            pass

def encode(model: BaseModel) -> str:
    """Convert the given model to a string"""
    return model.json()

def decode(msg: Union[str, bytes]) -> 'BaseModel':
    """Convert the given text to the appropriate pydantic BaseModel."""
    return DecoderModel.decode(msg)

class DecoderModelMetaclass(type(BaseModel)):
    """Metaclass to automatically register every subclass."""
    def __new__(mcs, name, bases, namespace, **kwargs):
        new_cls = super().__new__(mcs, name, bases, namespace, **kwargs)
        register_model(new_cls)
        return new_cls

class DecoderModel(BaseModel, metaclass=DecoderModelMetaclass):
    """Pydantic model that registers every base class so it can be decoded later."""

    DECODER_KEY_NAME: ClassVar = 'DECODER_MODEL_TYPE'

    def dict(
        self,
        *,
        include: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
        exclude: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
        by_alias: bool = False,
        skip_defaults: bool = None,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
    ) -> 'DictStrAny':
        """
        Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
        """
        d = super().dict(include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults,
                         exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none)
        d[self.DECODER_KEY_NAME] = get_model_name(self)
        return d

    @classmethod
    def decode(cls, msg: Union[str, bytes]) -> 'BaseModel':
        """Convert the given message into a Pydantic BaseModel"""
        if isinstance(msg, bytes):
            msg = msg.decode('utf-8')

        d = load_str_bytes(msg)  # Dictionary should be returned
        typ = get_model(d.pop(cls.DECODER_KEY_NAME))
        model = typ(**d)
        return model


import os

import pandas as pd
import pytest

import cudf
from cudf import date_range
from cudf.testing._utils import assert_eq

def _get_all_zones():
    zones = []
    for root, dirs, files in os.walk("/usr/share/zoneinfo"):
        for f in files:
            zone_name = ("/".join([root, f])).lstrip("/usr/share/zoneinfo")
            try:
                _ = pd.DatetimeTZDtype("ns", zone_name)
            except Exception:
                continue
            zones.append(zone_name)
    return zones

# NOTE: ALL_TIME_ZONES is a very large list; we likely do NOT want to
# use it for more than a handful of tests
ALL_TIME_ZONES = _get_all_zones()

@pytest.fixture(params=["ns", "us", "ms", "s"])
def unit(request):
    return request.param

@pytest.fixture(
    params=["America/New_York", "Asia/Tokyo", "CET", "Etc/GMT+1", "UTC"]
)
def tz(request):
    return request.param

@pytest.mark.parametrize("zone_name", ALL_TIME_ZONES)
def test_tz_localize(unit, zone_name):
    s = cudf.Series(date_range("2001-01-01", "2001-01-02", freq="1s"))
    s = s.astype(f"<M8[{unit}]")
    s = s.dt.tz_localize(zone_name)
    assert isinstance(s.dtype, pd.DatetimeTZDtype)
    assert s.dtype.unit == unit
    assert str(s.dtype.tz) == zone_name

@pytest.mark.parametrize("zone_name", ALL_TIME_ZONES)
def test_localize_ambiguous(request, unit, zone_name):
    request.applymarker(
        pytest.mark.xfail(
            condition=(zone_name == "America/Metlakatla"),
            reason="https://www.timeanddate.com/news/time/metlakatla-quits-dst.html",  # noqa: E501
        )
    )
    s = cudf.Series(
        [
            "2018-11-04 00:30:00",
            "2018-11-04 01:00:00",
            "2018-11-04 01:30:00",
            "2018-11-04 02:00:00",
            None,
            "2018-11-04 02:30:00",
        ],
        dtype=f"datetime64[{unit}]",
    )
    expect = s.to_pandas().dt.tz_localize(
        zone_name, ambiguous="NaT", nonexistent="NaT"
    )
    got = s.dt.tz_localize(zone_name)
    assert_eq(expect, got)

@pytest.mark.parametrize("zone_name", ALL_TIME_ZONES)
def test_localize_nonexistent(request, unit, zone_name):
    request.applymarker(
        pytest.mark.xfail(
            condition=(zone_name == "America/Grand_Turk"),
            reason="https://www.worldtimezone.com/dst_news/dst_news_turkscaicos03.html",  # noqa: E501
        )
    )
    s = cudf.Series(
        [
            "2018-03-11 01:30:00",
            "2018-03-11 02:00:00",
            "2018-03-11 02:30:00",
            "2018-03-11 03:00:00",
            None,
            "2018-03-11 03:30:00",
        ],
        dtype=f"datetime64[{unit}]",
    )
    expect = s.to_pandas().dt.tz_localize(
        zone_name, ambiguous="NaT", nonexistent="NaT"
    )
    got = s.dt.tz_localize(zone_name)
    assert_eq(expect, got)

def test_delocalize(unit, tz):
    psr = pd.Series(
        pd.date_range("2001-01-01", "2001-01-02", freq="1s")
    ).astype(f"datetime64[{unit}]")
    sr = cudf.from_pandas(psr)

    expect = psr.dt.tz_localize(tz).dt.tz_localize(None)
    got = sr.dt.tz_localize(tz).dt.tz_localize(None)
    assert_eq(expect, got)

def test_delocalize_naive():
    # delocalizing naive datetimes should be a no-op
    psr = pd.Series(["2001-01-01"], dtype="datetime64[ns]")
    sr = cudf.from_pandas(psr)

    expect = psr.dt.tz_localize(None)
    got = sr.dt.tz_localize(None)
    assert_eq(expect, got)

@pytest.mark.parametrize(
    "from_tz", ["Europe/London", "America/Chicago", "UTC"]
)
@pytest.mark.parametrize(
    "to_tz", ["Europe/London", "America/Chicago", "UTC", None]
)
def test_convert(from_tz, to_tz):
    ps = pd.Series(pd.date_range("2023-01-01", periods=3, freq="H"))
    gs = cudf.from_pandas(ps)
    ps = ps.dt.tz_localize(from_tz)
    gs = gs.dt.tz_localize(from_tz)
    expect = ps.dt.tz_convert(to_tz)
    got = gs.dt.tz_convert(to_tz)
    assert_eq(expect, got)

def test_convert_from_naive():
    gs = cudf.Series(cudf.date_range("2023-01-01", periods=3, freq="H"))
    with pytest.raises(TypeError):
        gs.dt.tz_convert("America/New_York")

@pytest.mark.parametrize(
    "data,original_timezone,target_timezone",
    [
        # DST transition:
        (["2023-03-12 01:30:00"], "America/New_York", "America/Los_Angeles"),
        # crossing the international date line:
        (["2023-05-17 23:30:00"], "Pacific/Auckland", "America/Los_Angeles"),
        # timezone with non-integer offset:
        (["2023-05-17 12:00:00"], "Asia/Kolkata", "Australia/Eucla"),
        # timezone with negative offset:
        (["2023-05-17 09:00:00"], "America/Los_Angeles", "Pacific/Auckland"),
        # conversion across multiple days:
        (["2023-05-16 23:30:00"], "America/New_York", "Asia/Kolkata"),
        # timezone with half-hour offset:
        (["2023-05-17 12:00:00"], "Asia/Kolkata", "Australia/Adelaide"),
        # timezone conversion with a timestamp in the future:
        (["2025-01-01 00:00:00"], "America/New_York", "Europe/London"),
        # timezone conversion with a timestamp in the past:
        (["2000-01-01 12:00:00"], "Europe/Paris", "America/Los_Angeles"),
        # timezone conversion with a timestamp at midnight:
        (["2023-05-17 00:00:00"], "Asia/Tokyo", "Europe/Paris"),
    ],
)
def test_convert_edge_cases(data, original_timezone, target_timezone):
    ps = pd.Series(data, dtype="datetime64[s]").dt.tz_localize(
        original_timezone
    )
    gs = cudf.Series(data, dtype="datetime64[s]").dt.tz_localize(
        original_timezone
    )
    expect = ps.dt.tz_convert(target_timezone)
    got = gs.dt.tz_convert(target_timezone)
    assert_eq(expect, got)


from django.shortcuts import render
from block.models import Block
from .models import Article
from django.shortcuts import redirect
from .forms import ArticleForm

def article_list(request,block_id):
    block_id = int(block_id)
    block = Block.objects.get(id=block_id)
    articles_objs = Article.objects.filter(block=block,status=0).order_by("-id")
    return render(request,"article_list.html",{"articles":articles_objs,"b":block})

def article_create(request,block_id):
    block_id = int(block_id)
    block = Block.objects.get(id=block_id)
    if request.method == "GET":
        return render(request,"article_create.html",{"b":block})
    else:
        form = ArticleForm(request.POST)
        if form.is_valid():
           # article = Article(block=block,title=form.cleaned_data["title"],content=form.cleaned_data["content"],status=0)
            article = form.save(commit=False)
            article.block = block
            article.status = 0
            article.save()
            return redirect("/article/list/%s" % block_id)
        else:
            return render(request,"article_create.html",{"b":block,"form":form})
       # title = request.POST["title"].strip()
       # content = request.POST["content"].strip()
       # if not title or not content:
       #     return render(request,"article_create.html",{"b":block,"error":"内容和标题都不能为空","title":title,"content":content})
       # if len(title)>100 or len(content)>10000:
        #    return render(request,"article_create.html",{"b":block,"error":"标题或内容太长了","title":title,"content":content})
       # article = Article(block=block,title=title,content=content,status=0)
       # article.save()
       # return redirect("/article/list/%s" % block_id)

def article_detail(request,aid):
    article = Article.objects.get(id=aid)
    return render(request,"article_detail.html",{"a":article})


import dicom, dicom.UID
from dicom.dataset import Dataset, FileDataset
import numpy as np
import datetime, time

def write_dicom(pixel_array,filename):
    """
    INPUTS:
    pixel_array: 2D numpy ndarray.  If pixel_array is larger than 2D, errors.
    filename: string name for the output file.
    """

    ## This code block was taken from the output of a MATLAB secondary
    ## capture.  I do not know what the long dotted UIDs mean, but
    ## this code works.
    file_meta = Dataset()
    file_meta.MediaStorageSOPClassUID = 'Secondary Capture Image Storage'
    file_meta.MediaStorageSOPInstanceUID = '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
    file_meta.ImplementationClassUID = '1.3.6.1.4.1.9590.100.1.0.100.4.0'
    ds = FileDataset(filename, {},file_meta = file_meta,preamble="\0"*128)
    ds.Modality = 'WSD'
    ds.ContentDate = str(datetime.date.today()).replace('-','')
    ds.ContentTime = str(time.time()) #milliseconds since the epoch
    ds.StudyInstanceUID =  '1.3.6.1.4.1.9590.100.1.1.124313977412360175234271287472804872093'
    ds.SeriesInstanceUID = '1.3.6.1.4.1.9590.100.1.1.369231118011061003403421859172643143649'
    ds.SOPInstanceUID =    '1.3.6.1.4.1.9590.100.1.1.111165684411017669021768385720736873780'
    ds.SOPClassUID = 'Secondary Capture Image Storage'
    ds.SecondaryCaptureDeviceManufctur = 'Python 2.7.3'

    ## These are the necessary imaging components of the FileDataset object.
    ds.SamplesPerPixel = 1
    ds.PhotometricInterpretation = "MONOCHROME2"
    ds.PixelRepresentation = 0
    ds.HighBit = 15
    ds.BitsStored = 16
    ds.BitsAllocated = 16
    ds.SmallestImagePixelValue = '\\x00\\x00'
    ds.LargestImagePixelValue = '\\xff\\xff'
    ds.Columns = pixel_array.shape[0]
    ds.Rows = pixel_array.shape[1]
    if pixel_array.dtype != np.uint16:
        pixel_array = pixel_array.astype(np.uint16)
    ds.PixelData = pixel_array.tostring()

    ds.save_as(filename)
    return

if __name__ == "__main__":
#    pixel_array = np.arange(256*256).reshape(256,256)
#    pixel_array = np.tile(np.arange(256).reshape(16,16),(16,16))
    x = np.arange(16).reshape(16,1)
    pixel_array = (x + x.T) * 32
    pixel_array = np.tile(pixel_array,(16,16))
    write_dicom(pixel_array,'pretty.dcm')


import serial

PORT = '/dev/cu.usbmodem14101'
BAUDRATE = 9600

ON = '1'
OFF = '0'

if __name__ == "__main__":
	arduino = serial.Serial(PORT, BAUDRATE)
	if arduino.is_open:
		while True:
			state = int(input("Enter the state of the magnet (0 - off, 1 - on) or 9 to turn it off: "))
			if state == 9:
				arduino.close()
				break
			else:
				if state:
					arduino.write(str.encode(ON))
				else:
					arduino.write(str.encode(OFF))
	else:
		print("ERROR: Could not connect to port: " + PORT)


import os, sys
sys.path.append(os.path.abspath('.'))

from mdl import read_corpus, corpus_names
import json

# obtain an analysis from a given corpus
def get_unigrams(corpus_name):
	words = read_corpus(corpus_name)

	unigrams = {'#': len(words)} # account for the word boundary
	for char in ''.join(words):
		unigrams.setdefault(char, 0)
		unigrams[char] += 1

	with open(f'unigrams/unigrams_{corpus_name}.json', 'w', encoding='utf-8') as outfile:
		json.dump(unigrams, outfile, separators=(',', ':'), ensure_ascii=False)

	with open(f'unigrams/unigrams_{corpus_name}.txt', 'w', encoding='utf-8') as outfile:
		outfile.write(' '.join(f'{key}{val}' for key, val in unigrams.items()))

if __name__ == '__main__':
	for n in corpus_names:
		get_unigrams(n)


# Tim Pusateri
# Jon Richelsen
# CSE30332
# Final Project: PyGame + Twisted
# 3D_Pongbreaker
#
# FUTURE IMPROVEMENTS
# Make velocity a function of last 0.5? seconds

import pygame

from CONSTANTS import PADDLE_WIDTH
from CONSTANTS import PADDLE_HEIGHT
from CONSTANTS import PADDLE_COLOR
from CONSTANTS import PADDLE_ALPHA
from CONSTANTS import SCREEN_CENTER_X
from CONSTANTS import SCREEN_CENTER_Y

class Paddle(pygame.sprite.Sprite):
	def __init__(self, z_pos, owner, gs):
		# initialize
		pygame.sprite.Sprite.__init__(self)
		self.gs = gs
		self.image = pygame.Surface((PADDLE_WIDTH, PADDLE_HEIGHT))
		self.image.fill(PADDLE_COLOR)
		self.image.set_alpha(PADDLE_ALPHA)
		self.rect = self.image.get_rect()
		self.rect.center = (SCREEN_CENTER_X, SCREEN_CENTER_Y)
		self.z_pos = z_pos
		self.old_x_pos = int()
		self.old_y_pos = int()
		self.manual_x = 400
		self.manual_y = 400
		self.owner = owner # {host, client}
		self.launch = False
		self.score = 0

	def tick(self):
		self.old_x_pos = self.rect.centerx
		self.old_y_pos = self.rect.centery
		if self.owner == 'host':
			self.rect.center = pygame.mouse.get_pos()
		else:
			self.rect.center = (self.manual_x, self.manual_y)

	def get_vel(self):
		return ((self.rect.centerx - self.old_x_pos), (self.rect.centery - self.old_y_pos))


import os
import re
import sys
import glob
import pickle
import datetime
import numpy as np
import pandas as pd

from cypy2 import (file_utils, file_settings)

class StravaExportManager(object):
    '''
    Methods to organize and parse the FIT files in a Strava data export

    Currently (as of April 2019), Strava data exports include original FIT files for each activity;
    these appear in the activities/ subdirectory, with corresponding metadata in activities.csv.

    Note that this organization is hard-coded in the methods below;
    if the organization of the exports changes, these methods will need to be updated.

    Parameters
    ----------
    root_dirpath : path to the strava export directory
    from_cache : whether to load previously-parsed FIT-file data from a cache
                 (created by self.to_cache)

    '''

    def __init__(self, root_dirpath, from_cache=False):

        self.root_dirpath = root_dirpath
        self.root_dirname = root_dirpath.split(os.sep)[-1]

        # where to cache the parsed data
        self.cache_dirpath = os.path.join(
            os.getenv('HOME'),
            'parsed-strava-exports',
            self.root_dirname)
        os.makedirs(self.cache_dirpath, exist_ok=True)

        # load the CSV activity metadata
        self.metadata = pd.read_csv(os.path.join(self.root_dirpath, 'activities.csv'))

        if from_cache:
            self.activity_data = self._load_from_cache(self.cache_dirpath)
        else:
            # for now, we will leave it to the user to call self.parse_all manually
            pass

    @staticmethod
    def _load_from_cache(cache_dirpath):
        '''
        Unpickle cached parsed data
        '''
        filepaths = glob.glob(os.path.join(cache_dirpath, '*.p'))
        filepath = sorted(filepaths)[-1]

        if len(filepaths) > 1:
            print('Warning: multiple pickle files found; loading %s' % filepath.split(os.sep)[-1])

        with open(filepath, 'rb') as file:
            data = pickle.load(file)
        return data

    def parse_all(self):
        '''
        Parse all of the FIT files that appear in the Strava export's activity metadata

        **Note that this method ignores activities in other formats (e.g., GPX format)**

        Returns
        -------
        self.activity_data : list of dicts of dataframes, keyed by message name
        self.parsing_errors : list of metadata rows on which file_utils.parse_fit failed

        '''
        activity_data = []
        errors = []
        for ind, row in self.metadata.iterrows():
            sys.stdout.write('\r%s: %s' % (row.date, row.filename))

            if pd.isna(row.filename) or 'gpx' in row.filename.split('.'):
                continue

            try:
                data = file_utils.parse_fit(os.path.join(self.root_dirpath, row.filename))
            except Exception as error:
                errors.append([row, error])
                continue

            # use a dataframe here for consistency with message dataframes
            data['strava_metadata'] = pd.DataFrame([row])
            activity_data.append(data)

        if len(errors):
            print('Warning: some errors occured; inspect parsing_errors for details')

        self.activity_data = activity_data
        self.parsing_errors = errors

    def to_cache(self):
        '''
        Pickle and cache the parsed data
        '''
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d')
        filepath = os.path.join(self.cache_dirpath, '%s_all-parsed-fit-files.p' % timestamp)

        if os.path.isfile(filepath):
            print('Warning: cached data already exists')
            return

        with open(filepath, 'wb') as file:
            pickle.dump(self.activity_data, file)


from stl import mesh
import numpy as np
import sys
from environment import write

f = open(sys.argv[1] + "_stl.txt", "w")

write(f)

object = mesh.Mesh.from_file("./" + sys.argv[1] + ".stl")
obj_vectors = object.vectors

points = np.around(np.unique(obj_vectors.reshape([int(obj_vectors.size/3), 3]), axis=0),2)

for triangle in obj_vectors:
    coord0 = str([triangle[0][0], triangle[0][1], triangle[0][2]]).replace("]", "").replace("[", "")
    coord1 = str([triangle[1][0], triangle[1][1], triangle[1][2]]).replace("]", "").replace("[", "")
    coord2 = str([triangle[2][0], triangle[2][1], triangle[2][2]]).replace("]", "").replace("[", "")
    f.write("P(" + coord0 + "," + coord1 + "," + coord2 + ")\n")

f.close()


import cv2
import numpy as np

class SB:
    def __init__(self):
        #self.img = img
        self.sobelX = None
        self.sobelY = None
        self.sb = None

    # use kernel to filter the input image
    def kernel_filter (self, kernel):
        height, width = self.img.shape
        kernel_height, kernel_width = kernel.shape

        img_pad = np.zeros(((height+2), (width+2)), np.float32)
        img_pad[1:height+1, 1:width+1] = self.img

        window = np.zeros((kernel_height, kernel_width), np.float32)
        value = np.zeros((kernel_height, kernel_width), np.float32)
        img_filter = np.zeros((height, width))

        for row in range(1, height):
            for col in range(1, width):
                window = img_pad[(row - 1): (row + 2), (col - 1): (col + 2)]
                value = window*kernel
                img_filter[row-1, col-1] = int(value.sum())

        return img_filter

    def filter(self):
        filterX = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
        filterY = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
        filterG = np.array([(1, 2, 1), (2, 4, 2), (1, 2, 1)], np.float32)/16

        self.sobelX = self.kernel_filter(filterX)
        self.sobelY = self.kernel_filter(filterY)

        sb = cv2.magnitude(self.sobelX, self.sobelY)
        #(self.sobelX**2 + self.sobelY**2)**0.5
        self.sb = sb#cv2.GaussianBlur(sb, (5,5), 0)

    def threshold(self, th):
        img_thr = np.copy(self.sb)
        img_thr[img_thr >= th] = 255
        img_thr[img_thr != 255] = 0

        self.sb = img_thr

    def sobel(self, img, th=100):
        self.img = img
        self.filter()
        self.threshold(th)
        return self.sb

def apply_sobel(img, ksize, thres=None):
    """
    Apply Sobel operator [ksizexksize] to image.
    @param  img:    input image
    @param  ksize:  Sobel kernel size
                    @pre odd integer >= 3
    @param  thres:  binary threshold, if None do not threshold
                    @pre integer >= 0 & <= 255

    @return:    image of Sobel magnitude
    """
    Ix = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=ksize)
    Iy = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=ksize)
    Im = cv2.magnitude(Ix, Iy)
    if thres is not None:
        _, It = cv2.threshold(Im, thres, 1, cv2.THRESH_BINARY)
        return It
    else:
        return Im

# example
img = cv2.imread('eyes_search.png', 0)
#img = cv2.resize(img, (150,200))
sb = SB()
img = sb.sobel(img)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


from typing import Any, List, Mapping, MutableMapping, Tuple

import pendulum
import requests
from airbyte_cdk.sources import AbstractSource
from airbyte_cdk.sources.streams import Stream
from airbyte_cdk.sources.streams.http.requests_native_auth import Oauth2Authenticator

from .streams import ProcessedOrderDetails, ProcessedOrders, StockItems, StockLocationDetails, StockLocations

class LinnworksAuthenticator(Oauth2Authenticator):
    def __init__(
        self,
        token_refresh_endpoint: str,
        application_id: str,
        application_secret: str,
        token: str,
        token_expiry_date: pendulum.datetime = None,
        access_token_name: str = "Token",
        expires_in_name: str = "TTL",
        server_name: str = "Server",
    ):
        super().__init__(
            token_refresh_endpoint,
            application_id,
            application_secret,
            token,
            scopes=None,
            token_expiry_date=token_expiry_date,
            access_token_name=access_token_name,
            expires_in_name=expires_in_name,
        )

        self.application_id = application_id
        self.application_secret = application_secret
        self.token = token
        self.server_name = server_name

    def get_auth_header(self) -> Mapping[str, Any]:
        return {"Authorization": self.get_access_token()}

    def get_access_token(self):
        if self.token_has_expired():
            t0 = pendulum.now()
            token, expires_in, server = self.refresh_access_token()
            self._access_token = token
            self._token_expiry_date = t0.add(seconds=expires_in)
            self._server = server

        return self._access_token

    def get_server(self):
        if self.token_has_expired():
            self.get_access_token()

        return self._server

    def get_refresh_request_body(self) -> Mapping[str, Any]:
        payload: MutableMapping[str, Any] = {
            "applicationId": self.application_id,
            "applicationSecret": self.application_secret,
            "token": self.token,
        }

        return payload

    def refresh_access_token(self) -> Tuple[str, int]:
        try:
            response = requests.request(method="POST", url=self.token_refresh_endpoint, data=self.get_refresh_request_body())
            response.raise_for_status()
            response_json = response.json()
            return response_json[self.access_token_name], response_json[self.expires_in_name], response_json[self.server_name]
        except Exception as e:
            try:
                e = Exception(response.json()["Message"])
            except Exception:
                # Unable to get an error message from the response body.
                # Continue with the original error.
                pass
            raise Exception(f"Error while refreshing access token: {e}") from e

class SourceLinnworks(AbstractSource):
    def _auth(self, config):
        return LinnworksAuthenticator(
            token_refresh_endpoint="https://api.linnworks.net/api/Auth/AuthorizeByApplication",
            application_id=config["application_id"],
            application_secret=config["application_secret"],
            token=config["token"],
        )

    def check_connection(self, logger, config) -> Tuple[bool, any]:
        try:
            self._auth(config).get_auth_header()
        except Exception as error:
            return False, f"Unable to connect to Linnworks API with the provided credentials: {error}"
        return True, None

    def streams(self, config: Mapping[str, Any]) -> List[Stream]:
        auth = self._auth(config)
        return [
            StockLocations(authenticator=auth),
            StockLocationDetails(authenticator=auth),
            StockItems(authenticator=auth),
            ProcessedOrders(authenticator=auth, start_date=config["start_date"]),
            ProcessedOrderDetails(authenticator=auth, start_date=config["start_date"]),
        ]


from collections import deque

dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]

def bfs(start):
    cnt = 1
    q = deque()
    q.append(start)

    while q:
        x, y = q.pop()
        visited[x][y] = 1
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < N and 0 <= ny < N:
                if MAP[nx][ny] == 1 and visited[nx][ny] == 0:
                    visited[nx][ny] = 1
                    cnt += 1
                    q.append([nx, ny])
    apt.append(cnt)

N = int(input())
MAP = [list(map(int, list(input()))) for i in range(N)]
visited = [[0]*N for i in range(N)]
apt = []
for i in range(N):
    for j in range(N):
        if MAP[i][j] == 1 and visited[i][j] == 0:
            bfs([i, j])
print(len(apt))
for i in sorted(apt):
    print(i)


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="pwrols_bknight_test_2",
    version="0.0.1",
    author="Benjamin S. Knight",
    author_email="knight.benjamin@gmail.com",
    description="Python package for sample size estimation in the context of OLS.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/b-knight/pwrols",
    install_requires=['scipy'],
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)


from unittest import TestCase
from unittest.mock import patch

import numpy as np
from pytest import raises

from aspire import __version__
from aspire.utils import get_full_version, powerset, utest_tolerance
from aspire.utils.misc import gaussian_1d, gaussian_2d, gaussian_3d

class UtilsTestCase(TestCase):
    def testGetFullVersion(self):
        """Test typical version string response is coherent with package."""

        self.assertTrue(get_full_version().startswith(__version__))

    @patch("os.path.isdir")
    def testGetFullVersionPath(self, d_mock):
        """Test not isdir case of get_full_version."""

        d_mock.return_value = False

        self.assertTrue(get_full_version() == __version__)

    @patch("subprocess.check_output")
    def testGetFullVersionSrc(self, p_mock):
        """Test subprocess exception case of get_full_version."""

        p_mock.side_effect = FileNotFoundError

        self.assertTrue(get_full_version() == __version__ + ".src")

    @patch("subprocess.check_output")
    def testGetFullVersionUnexpected(self, p_mock):
        """Test unexpected exception case of get_full_version."""

        p_mock.side_effect = RuntimeError

        self.assertTrue(get_full_version() == __version__ + ".x")

    def testPowerset(self):
        ref = sorted([(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)])
        s = range(1, 4)
        self.assertTrue(sorted(list(powerset(s))) == ref)

    def testGetTestTol(self):
        self.assertEqual(1e-8, utest_tolerance(np.float64))
        self.assertEqual(1e-5, utest_tolerance(np.float32))
        with raises(TypeError):
            utest_tolerance(int)

    def testGaussian2d(self):
        L = 100
        mu_x, mu_y = 7, -3
        s_x, s_y = 5, 6

        g = gaussian_2d(L, x0=mu_x, y0=mu_y, sigma_x=s_x, sigma_y=s_y)

        # The normalized sum across an axis should correspond to a 1d gaussian with appropriate mu, sigma, peak.
        g_x = np.sum(g, axis=1) / np.sum(g)
        g_y = np.sum(g, axis=0) / np.sum(g)

        # Corresponding 1d gaussians
        peak_x = 1 / np.sqrt(2 * np.pi * s_x**2)
        peak_y = 1 / np.sqrt(2 * np.pi * s_y**2)
        g_1d_x = gaussian_1d(L, mu=mu_x, sigma=s_x, peak=peak_x)
        g_1d_y = gaussian_1d(L, mu=mu_y, sigma=s_y, peak=peak_y)

        # Assert all-close
        self.assertTrue(np.allclose(g_x, g_1d_x))
        self.assertTrue(np.allclose(g_y, g_1d_y))

    def testGaussian3d(self):
        L = 100
        mu = (0, 5, 10)
        sigma = (5, 7, 9)

        G = gaussian_3d(L, mu, sigma)

        # The normalized sum across two axes should correspond to a 1d gaussian with appropriate mu, sigma, peak.
        G_x = np.sum(G, axis=(1, 2)) / np.sum(G)
        G_y = np.sum(G, axis=(0, 2)) / np.sum(G)
        G_z = np.sum(G, axis=(0, 1)) / np.sum(G)

        # Corresponding 1d gaussians
        peak_x = 1 / np.sqrt(2 * np.pi * sigma[0] ** 2)
        peak_y = 1 / np.sqrt(2 * np.pi * sigma[1] ** 2)
        peak_z = 1 / np.sqrt(2 * np.pi * sigma[2] ** 2)
        g_1d_x = gaussian_1d(L, mu=mu[0], sigma=sigma[0], peak=peak_x)
        g_1d_y = gaussian_1d(L, mu=mu[1], sigma=sigma[1], peak=peak_y)
        g_1d_z = gaussian_1d(L, mu=mu[2], sigma=sigma[2], peak=peak_z)

        # Assert all-close
        self.assertTrue(np.allclose(G_x, g_1d_x))
        self.assertTrue(np.allclose(G_y, g_1d_y))
        self.assertTrue(np.allclose(G_z, g_1d_z))


from datadog import initialize, api
from settings import *
import chronos
from marathon import MarathonClient
import logging

def send_dd_event(title, text, tags, source_type, alert_type='info'):
    """Sends events to datadog"""

    options = {
        'api_key': DATADOG_API_KEY,
        'app_key': DATADOG_APP_KEY
    }

    initialize(**options)

    api.Event.create(title=title,
                     text=text,
                     tags=tags,
                     alert_type=alert_type,
                     source_type_name='chronos'),

def get_chronos_services_health(chronos_url):
    """Gets health of all services from chronos"""
    client = chronos.connect(chronos_url)
    for job in client.list():
        if job['errorsSinceLastSuccess'] is not 0:
            send_dd_event("Chronos task: {} failed".format(job['name']),
                          "Chronos Task Id: {}\nLast success: {}\nLast error: {}".format(job['name'], job['lastSuccess'], job['lastError']),
                          generate_tags('chronos', job['name']),
                          "chronos",
                          "error"
                         )
        else:
            send_dd_event("Chronos task: {} ran succesfully".format(job['name']),
                          "Chronos Task Id: {}\nLast success: {}\nLast error: {}".format(job['name'], job['lastSuccess'], job['lastError']),
                          generate_tags('chronos', job['name']),
                          "chronos",
                         )

def get_marathon_services_health(marathon_url):
    """Gets health of all services from marathon"""
    client = MarathonClient(marathon_url)
    for app in client.list_apps(embed_tasks=True):
        if app.tasks_unhealthy > 0:
            unhealthy_tasks = []
            for task in app.tasks:
                if task.state == "TASK_RUNNING" or task.state == "TASK_STAGING":
                    continue
                else:
                    unhealthy_tasks.append(task.id)
            send_dd_event("Marathon service: {} has failed tasks".format(app.id),
                          "Id: {}\nRunning Tasks: {}\nUnhealthy Tasks: {}\nUnhealthy Task IDs: {}\n".format(app.id, app.tasks_running, app.tasks_unhealthy, unhealthy_tasks),
                          generate_tags('marathon', app.id),
                          "marathon",
                          "error"
                         )
        else:
            send_dd_event("Marathon service: {} healthy".format(app.id),
                          "Id: {}\nRunning Tasks: {}\nUnhealthy Tasks: {}".format(app.id, app.tasks_running, app.tasks_unhealthy),
                          generate_tags('marathon', app.id),
                          "marathon",
                         )

def generate_tags(framework, task_name):
    """Generates tags to send to datadog"""
    return [framework, task_name]


import numpy as np
import glob
import spams
import time
from skimage import io, color
# from sklearn.feature_extraction import image
import matplotlib.pyplot as plt
import dictlearn as dl
from pathlib import Path
import time

fname = str(Path.home()) + '/Imagens/720pMoria.png'

m11, m22 = (8,8)

if __name__ == "__main__":
    from skimage.measure import compare_psnr

    D = np.loadtxt('dltrainfiles/dl8_ycbcr_ds96_720pmoria.txt').T
    # D = np.zeros((192,64))
    # D[::3] = dl.dct_dict(64, 8)
    # D[1::3] = dl.dct_dict(64, 8)
    # D[2::3] = dl.dct_dict(64, 8)
    # np.savetxt('dct8_ds64.txt', D)
    # D = dl.dct_dict(64,12)
    # print(D.shape)
    # exit()

    image = io.imread(fname)
    if image.shape[-1] == 4:
        image = color.rgba2rgb(image)
    img_train = color.rgb2ycbcr(image) / 255.
    # img_train = image/255.
    # Duse = color.ycbcr2rgb(D)

    nl, nc, _= img_train.shape
    img4 = img_train
    t0 = time.monotonic()
    Ps = []
    for i in range(0, nl, m11):
        for j in range(0, nc, m22):
            if i + m11 <= nl and j + m22 <= nc:
                p = img4[i:(i+m11), j:(j+m22)]
                Ps.append(p)

    Ps = np.array(Ps).reshape(len(Ps), -1).T

    psnrs = []

    for i in range(1, int(Ps.shape[0])):
        mask = np.zeros(Ps.shape[0])
        choose = np.random.choice(Ps.shape[0], i, replace=False)
        # print(mask.shape)
        mask[choose] = 1
        # Dnew = np.asfortranarray((D * np.outer(mask, np.ones((1, D.shape[1])))),np.float)
        Dnew = np.asfortranarray(Duse[choose, :])
        Psnew = np.asfortranarray(Ps[choose, :])
        # res = np.array(dl.omp_mask(Ps, mask, D, 10, n_threads=4))
        res = spams.lasso(Psnew, Dnew, lambda1=0.000001, L=14).toarray()
        res = D.dot(res).T
        img1 = np.vstack((spl.reshape(-1,m11,m22,3).transpose(1,0,2,3).reshape(m11,-1,3) for spl in np.vsplit(res, int(nl / m11))))
        imgrgb = color.ycbcr2rgb(img1*255).clip(0,1)
        # imgrgb = (img1+1)/2
        psnrs.append(compare_psnr(image, imgrgb))
        print("%d: %.3f" % (i, psnrs[-1]))
    # dl.ps
    plt.subplot(2,1,1)
    plt.plot(psnrs, 'o-')

    print(imgrgb.min(), imgrgb.max())
    plt.subplot(2,1,2)
    plt.imshow(imgrgb)
    plt.show()


import numpy as np
import torch
import timm
from CustomVIT import VisionTransformer

def get_params(module):
    return sum(p.numel() for p in module.parameters() if p.requires_grad)

def assert_tensors_equal(t1, t2):
    a1, a2 = t1.detach().numpy(), t2.detach().numpy()

    np.testing.assert_allclose(a1, a2)

model_name = "vit_base_patch16_384"
model_official = timm.create_model(model_name, pretrained=True)
model_official.eval()

custom_config = {
    "img_size" : 384,
    "in_chans": 3,
    "patch_size": 16,
    "embed_dim": 768,
    "depth": 12,
    "n_heads": 12,
    "qkv_bias": True,
    "mlp_ratio": 4
}

model_custom = VisionTransformer(**custom_config)
model_custom.eval()

for (n_0, p_0), (n_c, p_c) in zip(
    model_official.named_parameters(), model_custom.named_parameters()
):
    assert p_0.numel() == p_c.numel()
    print(f"{n_0} | {n_c}")

    p_c.data[:] = p_0.data

    assert_tensors_equal(p_c.data, p_0.data)

inp = torch.rand(1, 3, 384, 384)
res_c = model_custom(inp)
rec_o = model_official(inp)

assert get_params(model_custom) == get_params(model_official)
assert_tensors_equal(res_c, rec_o)
torch.save(model_custom,
           r"C:\Users\Vadim\Desktop\folders\For myself\Python\CV\Реализации\VisionTransformers\model_custom.pth")


# - *- coding: utf- 8 - *-
import sqlite3
from time import time
from data.config import PATH_DATABASE

########################################
#  _    _ _______ _____ _       _____  #
# | |  | |__   __|_   _| |     / ____| #
# | |  | |  | |    | | | |    | (___   #
# | |  | |  | |    | | | |     \___ \  #
# | |__| |  | |   _| |_| |____ ____) | #
#  \____/   |_|  |_____|______|_____/  #
########################################
# Спасибо Djimbo (https://zelenka.guru/djimbo/)
# Форматирование запроса без аргументов

def update_format(sql, parameters: dict):
    if "XXX" not in sql:
        sql += " XXX "

    values = ", ".join([
        f"{item} = ?" for item in parameters
    ])
    sql = sql.replace("XXX", values)

    return sql, list(parameters.values())

# Форматирование запроса с аргументами
def update_format_args(sql, parameters: dict):
    sql = f"{sql} WHERE "

    sql += " AND ".join([
        f"{item} = ?" for item in parameters
    ])

    return sql, list(parameters.values())

# Преобразования sql списка в словарь
def dict_factory(cursor, row):
    save_dict = {}

    for idx, col in enumerate(cursor.description):
        save_dict[col[0]] = row[idx]

    return save_dict

##########################
#   _____  ____  _       #
#  / ____|/ __ \| |      #
# | (___ | |  | | |      #
#  \___ \| |  | | |      #
#  ____) | |__| | |____  #
# |_____/ \___\_\______| #
##########################
# Добавление пользователя
def add_user(user_id, username, fullname):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        con.execute("INSERT INTO users "
                    "(user_id, username, fullname, balance, created) "
                    "VALUES (?, ?, ?, ?, ?)",
                    [user_id, username, fullname, 0, int(time())])
        con.commit()

# Получение пользователя
def get_user(**kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM users"
        sql, parameters = update_format_args(sql, kwargs)
        return con.execute(sql, parameters).fetchone()

# Получение пользователей
def get_users(**kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM users"
        sql, parameters = update_format_args(sql, kwargs)
        return con.execute(sql, parameters).fetchall()

# Получение всех пользователей
def get_all_users():
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM users"
        return con.execute(sql).fetchall()

# Редактирование пользователя
def update_user(user_id, **kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = f"UPDATE users SET"
        sql, parameters = update_format(sql, kwargs)
        parameters.append(user_id)
        con.execute(sql + "WHERE user_id = ?", parameters)
        con.commit()

# Удаление пользователя
def delete_user(**kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "DELETE FROM users"
        sql, parameters = update_format_args(sql, kwargs)
        con.execute(sql, parameters)
        con.commit()

# Получение настроек
def get_settings():
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM settings"
        return con.execute(sql).fetchone()


# Description
## Assume we have a capacitor with 6 Coulombs of charge in it and having 3 volts on it's terminals.
## According to the definition of Capacitance this capacitor should have C = 2 Farads.

from collections import namedtuple
from pytest import approx, fixture, raises
from symplyphysics import (
    errors,
    units,
    convert_to,
    Quantity,
    SI,
)
from symplyphysics.definitions import capacitance_from_charge_and_voltage as capacitance_def

@fixture(name="test_args")
def test_args_fixture():
    C = Quantity(2 * units.farad)
    Q = Quantity(6 * units.coulomb)
    U = Quantity(3 * units.volts)
    Args = namedtuple("Args", ["C", "Q", "U"])
    return Args(C=C, Q=Q, U=U)

def test_basic_capacitance(test_args):
    result = capacitance_def.calculate_capacitance(test_args.Q, test_args.U)
    assert SI.get_dimension_system().equivalent_dims(result.dimension, units.capacitance)
    result_cap = convert_to(result, capacitance_def.definition_units_SI).evalf(4)
    assert result_cap == approx(2, 0.01)

def test_bad_charge(test_args):
    Qb = Quantity(1 * units.meter)
    with raises(errors.UnitsError):
        capacitance_def.calculate_capacitance(Qb, test_args.U)
    with raises(TypeError):
        capacitance_def.calculate_capacitance(100, test_args.U)

def test_bad_voltage(test_args):
    Vb = Quantity(1 * units.meter)
    with raises(errors.UnitsError):
        capacitance_def.calculate_capacitance(test_args.Q, Vb)
    with raises(TypeError):
        capacitance_def.calculate_capacitance(test_args.Q, 100)


# -*- coding: utf-8 -*-
"""
XYZtoTIN
==============

Script:   XYZtoTIN.py

Author:   loyler@usgs.gov

Modified: 2021-07-12

Purpose:  Converting an XYZ_uncert_source text file into points joined with LiDAR that can then be

Useage:

References:

:---------------------------------------------------------------------:
"""
# ---------------------------------------------------------------------------
# XYZtoTINModelBuilderArcPyTemplate.py
# Created on: 2021-07-09 14:46:13.00000
#   (generated by ArcGIS/ModelBuilder)
# Usage: XYZtoTINModelBuilderArcPyTemplate <Output_Folder> <Spatial_Reference> <XYZ_Shapefile_Name> <LAS_Shapefile_Name> <Input_XYZ_Table> <Input_LAS_Table> <Original_Lake_Polygon> <Output_Buffer_Name_with_File_Path_and_Extension> <Buffer_Distance> <Minimum_Allowed_Distance_XYZ> <Minimum_Allowed_Distance_LAS>
# Description:
# This model is a multi-step process for thinning CUBEd XYZ bathymetry and LiDAR data after it has been combined, filtered, and exported in R. The model reads in the raw X,Y,Z columns from a .csv or .txt table, makes a layer, creates a buffer that will contain the thinned LiDAR points, erases points within specified boundaries, removes points that are within a specified distance of each other, and outputs new shapefiles and tables.

# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy
#Checking to make sure the appropriate extensions are activated
class LicenseError(Exception):
    pass

try:
    if arcpy.CheckExtension("3D") == "Available":
        arcpy.CheckOutExtension("3D")
    else:
        # raise a custom exception
        raise LicenseError
except LicenseError:
    print("3D Analyst license is unavailable")
except arcpy.ExecuteError:
    print(arcpy.GetMessages(2))

#Timing how long it takes to run each function
from datetime import datetime
start_time = datetime.now()

#Function definition:
def XYZTextFileToTIN(LakeName,Home_Dir, Input_XYZ_Table, Input_LAS_Table,
                     LidarBoundsPolygon, Map_Resolution):

    # Setting the environments outputs can be overwritten if the code is run multiple times and setting the output workspace
    Output_GDB = Home_Dir + "\\" + LakeName + ".gdb"
    arcpy.env.overwriteOutput = True
    arcpy.env.workspace = Output_GDB

    #Setting local variables
    X_Field = "X"
    Y_Field = "Y"
    Z_Field = "Z"
    xyz_uncert_source_Layer = "xyz_uncert_source_Layer"
    temp_las = "temp_las"
    Inner_buffer_path = Output_GDB + "\\InnerBuffer"
    Outer_buffer_path = Output_GDB + "\\OuterBuffer"
    Big_outside_buffer_path = Output_GDB + "\\BigOutsideBuffer"
    Spatial_Reference = "PROJCS['NAD_1983_2011_UTM_Zone_15N',GEOGCS['GCS_NAD_1983_2011',DATUM['D_NAD_1983_2011',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-93.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision" # provide a default value if unspecified
    Minimum_Allowed_Distance_XYZ = Map_Resolution - 0.01
    XYZ_Shapefile_Name = LakeName + "_xyz"
    LAS_Shapefile_Name = LakeName + "_las"

    if Output_GDB == '#' or not Output_GDB:
        Output_GDB = "C:\\Users\\loyler\\Documents\\ArcGIS\\Default.gdb"  # provide a default value if unspecified

    if Minimum_Allowed_Distance_XYZ == '#' or not Minimum_Allowed_Distance_XYZ:
        Minimum_Allowed_Distance_XYZ = "0.5 Meters"  # provide a default value if unspecified

    ##Making buffers that will be used to create a 3 meter gap between the MB and the LiDAR to make sure they don't overlap

    # Process: Inner Buffer
    Inner_buffer = arcpy.Buffer_analysis(LidarBoundsPolygon, Inner_buffer_path, "-1.5 Meters", "FULL", "ROUND", "NONE", "", "PLANAR")
    # Process: Outer Buffer
    Outer_buffer = arcpy.Buffer_analysis(LidarBoundsPolygon, Outer_buffer_path, "1.5 Meters", "FULL", "ROUND", "NONE", "", "PLANAR")
    #Process: Big outside buffer that selects only relevant LiDAR points
    Big_outside_buffer = arcpy.Buffer_analysis(LidarBoundsPolygon, Big_outside_buffer_path, "500 Meters", "FULL", "ROUND","NONE", "", "PLANAR")
    ##XYZ Points Processing : Output Feature class, thinning, and erasing points outside the buffer

    # Process: Make XY Event Layer
    arcpy.MakeXYEventLayer_management(Input_XYZ_Table, X_Field, Y_Field, xyz_uncert_source_Layer, Spatial_Reference, Z_Field)
    # Process: XYZ Feature Class to Feature Class
    MBextent = arcpy.FeatureClassToFeatureClass_conversion(xyz_uncert_source_Layer, Output_GDB, XYZ_Shapefile_Name,"","","")

    # Process: Making a basic minimum bounding geometry polygon from the thinned MB points
    MBpoly_name = Output_GDB + "\\" + LakeName + "_MBpoly"
    arcpy.MinimumBoundingGeometry_management(
        in_features=MBextent,
        out_feature_class=MBpoly_name,
        geometry_type="CONVEX_HULL", group_option="ALL", group_field="", mbg_fields_option="NO_MBG_FIELDS")

    # Process: XYZ_Uncert_Source Create Random Points
    xyz_uncert_source_crp = arcpy.CreateRandomPoints_management(Output_GDB,
                                        XYZ_Shapefile_Name + "_crp",
                                        XYZ_Shapefile_Name,
                                        "",
                                        4000000,
                                        Minimum_Allowed_Distance_XYZ,
                                        "POINT",
                                        "0")

    # Process: XYZ_Uncert_Source Erase Point
    arcpy.ErasePoint_edit(xyz_uncert_source_crp, Inner_buffer, "OUTSIDE")

    xyz_uncert_source_joined = arcpy.SpatialJoin_analysis(xyz_uncert_source_crp,
                               XYZ_Shapefile_Name,
                               XYZ_Shapefile_Name + "_thinned")

    ###Lidar Processing
    # Process: Make XY Event Layer
    arcpy.MakeXYEventLayer_management(Input_LAS_Table, X_Field, Y_Field, temp_las, Spatial_Reference, Z_Field)
    # Process: LAS Feature Class to Feature Class
    arcpy.FeatureClassToFeatureClass_conversion(temp_las, Output_GDB, LAS_Shapefile_Name, "", "", "")

    # Process: LAS Erase Point (removes all of the irrelevant points outside the general lake region of interest
    arcpy.ErasePoint_edit(LAS_Shapefile_Name, Big_outside_buffer, "OUTSIDE")

    # Process: LAS Create Random Points
    las_crp = arcpy.CreateRandomPoints_management(Output_GDB,
                                                  LAS_Shapefile_Name + "_crp",
                                                  LAS_Shapefile_Name,
                                                  "",
                                                  4000000,
                                                  Minimum_Allowed_Distance_XYZ,
                                                  "POINT",
                                                  "0")

    # Process: LAS Erase Point (removes all points within 1.5 meters of the lake polygon)
    arcpy.ErasePoint_edit(las_crp, Outer_buffer, "INSIDE")

    # Process: Spatial join attribute table from original LAS file
    las_joined = arcpy.SpatialJoin_analysis(las_crp,
                               LAS_Shapefile_Name,
                               LAS_Shapefile_Name + "_thinned")

    ###Creating the Preliminary TIN from the thinned points, LiDAR, and lake polygon:
    #tin_params = xyz_uncert_source_joined + ' Z Mass_points <None>;' + las_joined + ' Z Mass_points <None>'
    #arcpy.env.workspace = Home_Dir + "\\"
    #arcpy.CreateTin_3d(LakeName + '_prelimTIN', Spatial_Reference,
     #                  [xyz_uncert_source_joined,'Z','Mass_points',None],[las_joined,'Z','Mass_points',None])

    #xyz_TIN_portion = Output_GDB + "\\" + LakeName + "_xyz_thinned"
    #las_TIN_portion = Output_GDB + "\\" + LakeName + "_las_thinned"

    #arcpy.CreateTin_3d(out_tin=LakeName + "_prelimTIN",
    #                   spatial_reference="PROJCS['NAD_1983_2011_UTM_Zone_15N',GEOGCS['GCS_NAD_1983_2011',DATUM['D_NAD_1983_2011',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-93.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]",
     #                  in_features=[las_TIN_portion + ' Z Mass_Points <None>',xyz_TIN_portion + ' Z Mass_Points <None>'],
      #                 constrained_delaunay="DELAUNAY")

#Running the function itself:
XYZTextFileToTIN(LakeName="GardenCityOld",
                 Home_Dir="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\GIS",
                 Input_XYZ_Table="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\RTextFiles\\GardenCityOld_xyz_uncert_source.csv",
                 Input_LAS_Table="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\RTextFiles\\GardenCityOld_las.txt",
                 LidarBoundsPolygon="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\GIS\\GardenCityOld.gdb\\GardenCityOld_lidarbounds",
                 Map_Resolution=0.5)

end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))


import numpy as np
import os
from tqdm import tqdm
import glob
import tgt
from scipy.io.wavfile import read
import pyworld as pw
import torch
import audio as Audio
import utils
from text import _clean_text
import hparams as hp

def prepare_align(in_dir):
    for dirpath, dirnames, filenames in tqdm(os.walk(in_dir)):
        for file in filenames:
            if file.endswith(".txt"):
                path_in  = os.path.join(dirpath, file)
                with open(path_in, 'r', encoding='utf-8') as f:
                    lines = f.readlines()
                    assert(len(lines) == 1)
                    text = lines[0]
                    text = _clean_text(text, hp.text_cleaners)

                path_out = os.path.join(dirpath, file)
                with open(path_out, 'w', encoding='utf-8') as f:
                    f.write(text)

def build_from_path(in_dir, out_dir):
    ref_dir_name = in_dir.split("/")[-1]
    basenames = []
    audio_paths = list(glob.glob(os.path.join(in_dir, '*.wav')))
    index = 1
    f0_max = energy_max = 0
    f0_min = energy_min = 1000000
    n_frames = 0
    filelist_list = list()
    for ref_path in glob.glob(os.path.join(in_dir, '*.wav')):
        basename = ref_path.split("/")[-1].replace(".wav","")
        text = utils.get_transcript(ref_path.replace(".wav", ".txt"))
        filelist_list.append("|".join([basename, text]))

        try:
            ret = process_utterance(in_dir, out_dir, basename)
            if ret is None:
                continue
            else:
                info, f_max, f_min, e_max, e_min, n = ret

            print("Done {}: {}".format(index, basename))
            basenames.append(basename)

            index = index + 1

            f0_max = max(f0_max, f_max)
            f0_min = min(f0_min, f_min)
            energy_max = max(energy_max, e_max)
            energy_min = min(energy_min, e_min)
            n_frames += n
        except:
            print("Can't process:", basename)

    strs = ['Total time: {} hours'.format(n_frames*hp.hop_length/hp.sampling_rate/3600),
            'Total frames: {}'.format(n_frames),
            'Min F0: {}'.format(f0_min),
            'Max F0: {}'.format(f0_max),
            'Min energy: {}'.format(energy_min),
            'Max energy: {}'.format(energy_max)]
    for s in strs:
        print(s)

    ### Write Filelist ###
    with open(os.path.join(out_dir, '{}.txt'.format(ref_dir_name)), 'w', encoding='utf-8') as f:
        print("Total saved filelist elements:", len(filelist_list))
        for row in filelist_list:
            f.write(str(row)+'\n')

    return basenames, audio_paths

def process_utterance(in_dir, out_dir, basename):
    wav_path = os.path.join(in_dir, '{}.wav'.format(basename))
    tg_path = os.path.join(out_dir, 'TextGrid', '{}.TextGrid'.format(basename))

    # Get alignments
    textgrid = tgt.io.read_textgrid(tg_path)
    phone, duration, start, end = utils.get_alignment(
        textgrid.get_tier_by_name('phones'))
    # '{A}{B}{$}{C}', $ represents silent phones
    text = '{' + '}{'.join(phone) + '}'
    text = text.replace('{$}', ' ')    # '{A}{B} {C}'
    text = text.replace('}{', ' ')     # '{A B} {C}'

    if start >= end:
        return None

    # Read and trim wav files
    _, wav = read(wav_path)
    wav = wav[int(hp.sampling_rate*start):int(hp.sampling_rate*end)].astype(np.float32)

    # Compute fundamental frequency
    f0, _ = pw.dio(wav.astype(np.float64), hp.sampling_rate,
                   frame_period=hp.hop_length/hp.sampling_rate*1000)
    f0 = f0[:sum(duration)]

    # Compute mel-scale spectrogram and energy
    mel_spectrogram, energy, _ = Audio.tools.get_mel_from_wav(
        torch.FloatTensor(wav))
    mel_spectrogram = mel_spectrogram.numpy().astype(np.float32)[
        :, :sum(duration)]
    energy = energy.numpy().astype(np.float32)[:sum(duration)]
    if mel_spectrogram.shape[1] >= hp.max_seq_len:
        return None

    # Save alignment
    ali_filename = '{}-ali-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'alignment', ali_filename),
            duration, allow_pickle=False)

    # Save fundamental prequency
    f0_filename = '{}-f0-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'f0', f0_filename), f0, allow_pickle=False)

    # Save normalized fundamental prequency
    f0_norm = utils.f0_normalization(f0)
    np.save(os.path.join(out_dir, 'f0_norm', f0_filename), f0_norm, allow_pickle=False)

    # Save energy
    energy_filename = '{}-energy-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'energy', energy_filename),
            energy, allow_pickle=False)

    # Save rescaled energy
    energy_0to1 = utils.energy_rescaling(energy)
    np.save(os.path.join(out_dir, 'energy_0to1', energy_filename), energy_0to1, allow_pickle=False)

    # Save spectrogram
    mel_filename = '{}-mel-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'mel', mel_filename),
            mel_spectrogram.T, allow_pickle=False)

    return '|'.join([basename, text]), max(f0), min([f for f in f0 if f != 0]), max(energy), min(energy), mel_spectrogram.shape[1]


import cv2
import numpy as np

"""
this script deals with finding the sudoku square (and removing the background)
"""

def extract_grid(img_path):
    """
        reads img from the path specified and returns only the sudoku puzzle
    """
    print("extracting the sudoku grid.....")

    # read the image from path
    img = cv2.imread(img_path)

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
    thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)

    contours, _  = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

    # find the ten contours having the largest area
    contours = sorted(contours,key=cv2.contourArea,reverse=True)[:10]

    sudoku_square = None
    for c in contours[1:]:
        # approximate the contour to a polygon (closed figure)
        # for more info refer: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.015 * peri, True)

        # if the polygon has four sides break (largest 4 sided polygon)
        if len(approx) == 4:
            sudoku_square = approx
            break

    # return the image after performing perspective transform
    # refer more here: https://docs.opencv.org/master/da/d6e/tutorial_py_geometric_transformations.html
    return(grab_warp(img,sudoku_square))

"""
    For perspective transformation, you need a 3x3 transformation matrix. Straight lines will remain straight even after the transformation. To find this transformation matrix, you need 4 points on the input image and corresponding points on the output image. Among these 4 points, 3 of them should not be collinear. Then the transformation matrix can be found by the function cv.getPerspectiveTransform. Then apply cv.warpPerspective with this 3x3 transformation matrix.
"""

def grab_warp(img,sudoku_square):
    """ performs perspective transform """

    # converting the cordinates of the sudoku square into required format (4 corners of the sudoku square)
    pts = sudoku_square.reshape((4,2))
    rect = get_rect(pts)

    (maxHeight,maxWidth) = getMax_HW(rect)

    # 4 corners of the final sudoku square
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype = "float32")

    M = cv2.getPerspectiveTransform(rect, dst)
    warp = cv2.warpPerspective(img, M, (maxWidth, maxHeight))
    return warp

def get_rect(pts):
    """
        helper function to find the four corners of the
        sudoku square in original image
    """
    rect = np.zeros((4,2),dtype=np.float32)
    s = pts.sum(axis = 1)
    rect[0] = pts[np.argmin(s)]
    rect[2] = pts[np.argmax(s)]

    diff = np.diff(pts, axis = 1)
    rect[1] = pts[np.argmin(diff)]
    rect[3] = pts[np.argmax(diff)]
    return rect

def getMax_HW(rect):
    """
        helper function to find the maximum width and
        height of the sudoku square in original image
    """
    (tl, tr, br, bl) = rect

    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))

    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))

    maxWidth = max(int(widthA), int(widthB))
    maxHeight = max(int(heightA), int(heightB))
    return (maxHeight,maxWidth)


from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox

from vistas.editParametros import Ui_Dialog
from PyQt5.QtGui import QIntValidator

from modelos.modeloParametros import Modelo_conexion

#En esta clase se inserta codigo que permita a la vista realizar distintos comportamientos sin modificar el archivo principal de la vista

class Controlador_parametros(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        self.ui= Ui_Dialog()
        self.modelo = Modelo_conexion()
        self.ui.setupUi(self)
        self.InicializarGui()
        self.cargarParametris()

    def InicializarGui(self):
        self.ui.pushButton_4.clicked.connect(self.editarParametros)

    def cargarParametris(self):

        datos = self.modelo.cargarDatos()

        ListaDatos = datos[0]

        print("Los datos son los siguientes: ")
        print(str(datos))

        self.ui.lineEdit.setPlaceholderText(str(ListaDatos[0]).strip())
        self.ui.lineEdit_2.setPlaceholderText(str(ListaDatos[1]).strip())

    def editarParametros(self):

        if len(self.ui.lineEdit.text()) != 40:
            Alerta = QMessageBox.information(self, 'Alerta', "El Client Id debe tener 40 caracteres sin espacios", QMessageBox.Ok)

        elif len(self.ui.lineEdit_2.text()) != 128:

            Alerta = QMessageBox.information(self, 'Alerta', "El Secret Id debe tener 128 caracteres sin espacios", QMessageBox.Ok)
        else:
            clinteId = self.ui.lineEdit.text()
            SecretId = self.ui.lineEdit_2.text()

            self.modelo.editar(clinteId,SecretId)