from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from train import train
from test import test
from net import Net
from torchvision import datasets, transforms
import wandb

def main():
    wandb.init()

    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
    parser.add_argument('--batch-size', type=int, default=64, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                        help='input batch size for testing (default: 1000)')
    parser.add_argument('--epochs', type=int, default=10, metavar='N',
                        help='number of epochs to train (default: 10)')
    parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
                        help='learning rate (default: 0.01)')
    parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
                        help='SGD momentum (default: 0.5)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                        help='how many batches to wait before logging training status')
    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    # We load all of the arguments into config to save as hyperparameters
    wandb.config.update(args)

    torch.manual_seed(args.seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
    train_loader = torch.utils.data.DataLoader(
        datasets.MNIST('../data', train=True, download=True,
                       transform=transforms.Compose([
                           transforms.ToTensor(),
                           transforms.Normalize((0.1307,), (0.3081,))
                       ])),
        batch_size=args.batch_size, shuffle=True, **kwargs)
    test_loader = torch.utils.data.DataLoader(
        datasets.MNIST('../data', train=False, transform=transforms.Compose([
                           transforms.ToTensor(),
                           transforms.Normalize((0.1307,), (0.3081,))
                       ])),
        batch_size=args.test_batch_size, shuffle=True, **kwargs)

    model = Net().to(device)
    optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)

    # This magic line lets us save ther pytorch model and track all of the gradients and optionally parameters
    wandb.watch(model)

    for epoch in range(1, args.epochs + 1):
        train(args, model, device, train_loader, optimizer, epoch, wandb)
        test(args, model, device, test_loader, wandb)

if __name__ == '__main__':
    main()


import heapq
import math
from collections import defaultdict

class AStarNode:
    def __init__(self, i=-1, j=-1, t=-1, g=math.inf, h=math.inf, F=None, parent=None):
        self.i = i
        self.j = j
        self.t = t
        self.g = g
        self.h = h
        if F is None:
            self.F = self.g + h
        else:
            self.F = F
        self.parent = parent

    def __eq__(self, other):
        return (self.i == other.i) and (self.j == other.j) and (self.t == other.t)

    def __hash__(self):
        return hash((self.i, self.j, self.t))

    def __str__(self):
        return f'(i: {self.i}, j: {self.j}, t: {self.t})'

    def __repr__(self):
        return self.__str__()

class AStarNodeHeap:

    def __init__(self, node, k=0):
        self.node = node
        self.removed = False
        self.k = k

    def __lt__(self, other):
        return (self.node.F, self.node.h, -self.k) < (other.node.F, other.node.h, -other.k)

class AStarOpen:

    def __init__(self):
        self.elements = []
        self.exists = {}
        self.k = 0

    def __len__(self):
        return len(self.elements)

    def __iter__(self):
        return map(lambda n: n.node, self.elements)

    def is_empty(self):
        return len(self.exists) == 0

    def get_best_node(self):
        smallest = heapq.heappop(self.elements)
        while smallest.removed:
            smallest = heapq.heappop(self.elements)
        del self.exists[smallest.node]
        return smallest.node

    def add_node(self, item: AStarNode):
        if item in self.exists:
            old_node = self.exists[item]
            if old_node.node.g <= item.g:
                return
            old_node.removed = True
        new_node_heap = AStarNodeHeap(item, self.k)
        self.k += 1
        heapq.heappush(self.elements, new_node_heap)
        self.exists[item] = new_node_heap

class AStarClosed:
    def __init__(self):
        self.elements = set()

    def __iter__(self):
        return iter(self.elements)

    def __len__(self):
        return len(self.elements)

    def add_node(self, item: AStarNode, *args):
        self.elements.add(item)

    def was_expanded(self, item: AStarNode, *args):
        return item in self.elements

def compute_cost(i1, j1, i2, j2):
    return math.sqrt((i1 - i2) ** 2 + (j1 - j2) ** 2)

def manhattan_distance(i1, j1, i2, j2):
    return abs(i1 - i2) + abs(j1 - j2)

def manhattan_distance_time(i_from, j_from, t_from, i_to, j_to, t_to):
    if t_from > t_to:
        return math.inf
    return abs(i_from - i_to) + abs(j_from - j_to) + abs(t_from - t_to)

class RealDistanceFinder:
    def __init__(self, i_start, j_start, i_goal, j_goal, grid_map):
        status, OPEN, CLOSED, _ = A_star_backward(grid_map, i_goal, j_goal, i_start, j_start)
        self.OPEN = OPEN
        self.CLOSED = CLOSED
        self.i_start = i_start
        self.j_start = j_start
        self.grid_map = grid_map

    def find_dist(self, i, j):
        node = AStarBackwardNode(i, j, 0, 0)
        if node in self.CLOSED:
            return self.CLOSED[node]
        else:
            while not self.OPEN.is_empty():
                cur_node = self.OPEN.get_best_node()
                self.CLOSED.add_node(cur_node)
                if cur_node.i == i and cur_node.j == j:
                    return cur_node.g
                for (i, j) in self.grid_map.get_neighbors(cur_node.i, cur_node.j):

                    new_node = AStarBackwardNode(i, j, g=cur_node.g + 1, h=manhattan_distance(self.i_start, self.j_start, i, j),
                                                 parent=cur_node)
                    if not self.CLOSED.was_expanded(new_node):
                        self.OPEN.add_node(new_node)
            return 10

def do_path(node):
    path = []
    while node.parent is not None:
        path.append((node.i, node.j))
        node = node.parent
    path.append((node.i, node.j))
    path.reverse()
    return path

def A_star(grid_map,
           i_start,
           j_start,
           i_goal,
           j_goal,
           vertex_constraints,
           edge_constraints,
           heuristic_function=manhattan_distance,
           t_start=0):
    OPEN = AStarOpen()
    CLOSED = AStarClosed()
    start_node = AStarNode(i_start, j_start, t_start, 0, 0)
    OPEN.add_node(start_node)
    if len(vertex_constraints) == 0 and len(edge_constraints) == 0:
        status, _, _, path = A_star_backward(grid_map, i_start, j_start, i_goal, j_goal)
        return status, path
    vertex_max_time = max(map(lambda x: x[1], vertex_constraints)) if vertex_constraints else 0
    edge_max_time = max(map(lambda x: x[1], edge_constraints)) if edge_constraints else 0
    max_time = max(edge_max_time, vertex_max_time)
    while not OPEN.is_empty():
        cur_node = OPEN.get_best_node()
        CLOSED.add_node(cur_node)
        if cur_node.i == i_goal and cur_node.j == j_goal and cur_node.t >= max_time:
            return True, do_path(cur_node)
        for (i, j) in grid_map.get_neighbors(cur_node.i, cur_node.j):
            to, frm, t = (i, j), (cur_node.i, cur_node.j), cur_node.t
            if (to, t + 1) in vertex_constraints or \
                    ((to, frm), t) in edge_constraints or \
                    ((frm, to), t) in edge_constraints:
                continue

            new_node = AStarNode(i, j, cur_node.t + 1, g=cur_node.t + 1, h=heuristic_function(i_goal, j_goal, i, j),
                                 parent=cur_node)
            if not CLOSED.was_expanded(new_node):
                OPEN.add_node(new_node)
    return False, None

def A_star_DS(grid_map,
              i_start,
              j_start,
              t_start,
              i_goal,
              j_goal,
              t_goal,
              vertex_constraints,
              edge_constraints,
              heuristic_function=manhattan_distance
              ):
    OPEN = AStarOpen()
    CLOSED = AStarClosed()
    start_node = AStarNode(i_start, j_start, t_start, 0, 0)
    OPEN.add_node(start_node)
    if len(vertex_constraints) == 0 and len(edge_constraints) == 0:
        status, _, _, path = A_star_backward(grid_map, i_start, j_start, i_goal, j_goal)
        return status, path
    vertex_max_time = max(map(lambda x: x[1], vertex_constraints)) if vertex_constraints else 0
    edge_max_time = max(map(lambda x: x[1], edge_constraints)) if edge_constraints else 0
    max_time = max(edge_max_time, vertex_max_time)
    while not OPEN.is_empty():
        cur_node = OPEN.get_best_node()
        CLOSED.add_node(cur_node)
        if cur_node.i == i_goal and cur_node.j == j_goal and cur_node.t == t_goal and cur_node.t >= max_time:
            return True, do_path(cur_node)
        for (i, j) in grid_map.get_neighbors(cur_node.i, cur_node.j):
            to, frm, t = (i, j), (cur_node.i, cur_node.j), cur_node.t
            if (to, t + 1) in vertex_constraints or \
                    ((to, frm), t) in edge_constraints or \
                    ((frm, to), t) in edge_constraints:
                continue

            new_node = AStarNode(i, j, cur_node.t + 1, g=cur_node.t + 1,
                                 h=heuristic_function(i, j, i_goal, j_goal),
                                 parent=cur_node)
            if not CLOSED.was_expanded(new_node) and new_node.t + heuristic_function(i, j, i_goal, j_goal) <= t_goal:
                OPEN.add_node(new_node)
    return False, None

class AStarBackwardNode:
    def __init__(self, i=-1, j=-1, g=math.inf, h=math.inf, F=None, parent=None):
        self.i = i
        self.j = j
        self.g = g
        self.h = h
        if F is None:
            self.F = self.g + h
        else:
            self.F = F
        self.parent = parent

    def __eq__(self, other):
        return (self.i == other.i) and (self.j == other.j)

    def __hash__(self):
        return hash((self.i, self.j))

class AStarBackwardClosed:
    def __init__(self):
        self.elements = {}

    def __iter__(self):
        return iter(self.elements.keys())

    def __len__(self):
        return len(self.elements.keys())

    def add_node(self, item: AStarBackwardNode, *args):
        self.elements[item] = item.g

    def was_expanded(self, item: AStarBackwardNode, *args):
        return item in self.elements

    def __getitem__(self, item):
        return self.elements[item]

def A_star_backward(grid_map,
                    i_start,
                    j_start,
                    i_goal,
                    j_goal,
                    heuristic_function=manhattan_distance):
    OPEN = AStarOpen()
    CLOSED = AStarBackwardClosed()
    start_node = AStarBackwardNode(i_start, j_start, 0, 0)
    OPEN.add_node(start_node)
    while not OPEN.is_empty():
        cur_node = OPEN.get_best_node()
        CLOSED.add_node(cur_node)
        if cur_node.i == i_goal and cur_node.j == j_goal:
            return True, OPEN, CLOSED, do_path(cur_node)
        for (i, j) in grid_map.get_neighbors(cur_node.i, cur_node.j):

            new_node = AStarBackwardNode(i, j, g=cur_node.g + 1, h=heuristic_function(i_goal, j_goal, i, j),
                                         parent=cur_node)
            if not CLOSED.was_expanded(new_node):
                OPEN.add_node(new_node)
    return False, None


import time
import RPi.GPIO as GPIO

class LED:
    '''
    Toggle a GPIO pin for led control
    '''
    def __init__(self, pin):
        self.pin = pin

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.pin, GPIO.OUT)
        self.blink_changed = 0
        self.on = False

    def toggle(self, condition):
        if condition:
            GPIO.output(self.pin, GPIO.HIGH)
            self.on = True
        else:
            GPIO.output(self.pin, GPIO.LOW)
            self.on = False

    def blink(self, rate):
        if time.time() - self.blink_changed > rate:
            self.toggle(not self.on)
            self.blink_changed = time.time()

    def run(self, blink_rate):
        if blink_rate == 0:
            self.toggle(False)
        elif blink_rate > 0:
            self.blink(blink_rate)
        else:
            self.toggle(True)

    def shutdown(self):
        self.toggle(False)
        GPIO.cleanup()

class RGB_LED:
    '''
    Toggle a GPIO pin on at max_duty pwm if condition is true, off if condition is false.
    Good for LED pwm modulated
    '''
    def __init__(self, pin_r, pin_g, pin_b, invert_flag=False):
        self.pin_r = pin_r
        self.pin_g = pin_g
        self.pin_b = pin_b
        self.invert = invert_flag
        print('setting up gpio in board mode')
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.pin_r, GPIO.OUT)
        GPIO.setup(self.pin_g, GPIO.OUT)
        GPIO.setup(self.pin_b, GPIO.OUT)
        freq = 50
        self.pwm_r = GPIO.PWM(self.pin_r, freq)
        self.pwm_g = GPIO.PWM(self.pin_g, freq)
        self.pwm_b = GPIO.PWM(self.pin_b, freq)
        self.pwm_r.start(0)
        self.pwm_g.start(0)
        self.pwm_b.start(0)
        self.zero = 0
        if( self.invert ):
            self.zero = 100

        self.rgb = (50, self.zero, self.zero)

        self.blink_changed = 0
        self.on = False

    def toggle(self, condition):
        if condition:
            r, g, b = self.rgb
            self.set_rgb_duty(r, g, b)
            self.on = True
        else:
            self.set_rgb_duty(self.zero, self.zero, self.zero)
            self.on = False

    def blink(self, rate):
        if time.time() - self.blink_changed > rate:
            self.toggle(not self.on)
            self.blink_changed = time.time()

    def run(self, blink_rate):
        if blink_rate == 0:
            self.toggle(False)
        elif blink_rate > 0:
            self.blink(blink_rate)
        else:
            self.toggle(True)

    def set_rgb(self, r, g, b):
        r = r if not self.invert else 100-r
        g = g if not self.invert else 100-g
        b = b if not self.invert else 100-b
        self.rgb = (r, g, b)
        self.set_rgb_duty(r, g, b)

    def set_rgb_duty(self, r, g, b):
        self.pwm_r.ChangeDutyCycle(r)
        self.pwm_g.ChangeDutyCycle(g)
        self.pwm_b.ChangeDutyCycle(b)

    def shutdown(self):
        self.toggle(False)
        GPIO.cleanup()

if __name__ == "__main__":
    import time
    import sys
    pin_r = int(sys.argv[1])
    pin_g = int(sys.argv[2])
    pin_b = int(sys.argv[3])
    rate = float(sys.argv[4])
    print('output pin', pin_r, pin_g, pin_b, 'rate', rate)

    p = RGB_LED(pin_r, pin_g, pin_b)

    iter = 0
    while iter < 50:
        p.run(rate)
        time.sleep(0.1)
        iter += 1

    delay = 0.1

    iter = 0
    while iter < 100:
        p.set_rgb(iter, 100-iter, 0)
        time.sleep(delay)
        iter += 1

    iter = 0
    while iter < 100:
        p.set_rgb(100 - iter, 0, iter)
        time.sleep(delay)
        iter += 1

    p.shutdown()


import clr

clr.AddReference("System")
clr.AddReference("System.Console")
clr.AddReference("System.Threading")
clr.AddReference("System.XML")
from System import *
from System.Console import *
from System.Threading import *
from System.IO import *
from System.Environment import *
from System.Xml import *

clr.AddReference("LibreMetaverse")
clr.AddReference("LibreMetaverse.Types")
from OpenMetaverse import *
from OpenMetaverse import UUID
from OpenMetaverse import Vector3

def scriptInfo():
    return "default.py"

def Network_OnLogin():
    return "Network_OnLogin"

# chatBeforHookはチャットを受信時に他のコマンドの前にフックします
# はい db825529-8850-4616-c824-643faea018ce
# 行ってらっしゃい e37db011-1145-3e98-1cf7-9f307dae03ee
# こんばんわ 96386359-d497-91e2-0761-7a7a5534285e
# くんかくんか 3974dd2d-bce5-23c4-9539-cb3abfce6163
# またね 1268870a-8f68-883e-d80a-984e628ea0fa
# もさもさ 35d735ea-8902-2b4c-46b6-70e27954af7e
# にゃーにゃー 00a5b76e-3a06-f9f5-bbc9-494319ff02b5
# OK e609f94c-ebbe-837e-35d5-cfddf8d39ac9
# おやすみ bdb75763-b7a1-c1aa-f3ac-7351beb91149
# qawsedrftgyhujikolp f364e06e-b6b4-a1f1-b90f-c1d82ffda937
# そうだね 1168242e-6618-8f4d-3ef8-e0f96a19e4ac
# 手遅れだと思います 7e2848ed-607e-ee8d-b886-dfb955aa878a
# 寝たら死ぬぞ 7ce31c3b-437a-cd46-e360-738df8c8e211
# また髪の話してる f28fd398-26ce-5bdc-976d-7e53bd9c478d
# ありまたお 68ca4eb0-4b4d-4dce-39fb-df6f5e08fee9
# いえーい f9023d35-f9ca-10de-f59d-de14d847b698
def chatBeforHook(fromUUID, fromName, message, type):
    if "うさうさ❤" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("35d735ea-8902-2b4c-46b6-70e27954af7e"))
        return False
    elif "もさもさ❤" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("35d735ea-8902-2b4c-46b6-70e27954af7e"))
        return False
    elif "くまくま❤" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("7ce31c3b-437a-cd46-e360-738df8c8e211"))
        return False
    elif "寝ます" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("7ce31c3b-437a-cd46-e360-738df8c8e211"))
        return False
    elif "髪" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f28fd398-26ce-5bdc-976d-7e53bd9c478d"))
        return False
    elif "Yayyyyyyy" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
        return False
    elif "YAY" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
        return False
    elif "イエェェェェ" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
        return False
    else:
        return True
    return True

# chat command extension
def command(fromUUID, fromName, message, type):
    if "テスト" in message:
        mclient.Self.Chat(fromName + " テスト", 0, ChatType.Normal)
        return False
    elif "NPC" in message:
        #pass
        Console.WriteLine("NPC")
        standupcommand.Execute(UUID.Zero, "", "", 0)
        mclient.Self.AutoPilot(263911.29400634766,248179.05200195312,21.72664451599121)
        return False
    elif "グローバル座標" in message:
        pos = application.getCurrentGlobalPosition()
        print(pos)
        return False
    else:
        return True

def openaiPrompt(fromUUID, fromName, message, type):
    prompt = ""

    ## 通常prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、親切で、クリエイティブで、賢くて、とてもフレンドリーです。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:元気です\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:私も" + fromName + "さんのことが好きです\n"

    ## 一人称と語尾（ボク・・・ござる）prompt
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:ボクは元気でござる\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:ボクも" + fromName + "さんのことが好きでござる\n"

    # 一人称（ボクっ娘） + 英語prompt
    prompt += "以下は、立川くんとの会話です。立川くんは、ボクっ娘でとても親切なAIボットです。 \n"
    prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "立川くん:こんにちわ\n"
    prompt += "私:こんにちは、調子はどう？\n"
    prompt += "立川くん:" + fromName + "さんこんにちは、ボクは元気だよ\n"
    prompt += "私:好きだよ\n"
    prompt += "立川くん:ボクも" + fromName + "さんのことが好きだよ\n"
    prompt += "私:この服どう思いますか？\n"
    prompt += "立川くん:素敵な服だね！\n"
    prompt += "私:立川くんは最近何してるの\n"
    prompt += "立川くん:ボクは最近調子がいいから、たくさん踊ってるよ！\n"
    prompt += "私:立川くんはAIなの?\n"
    prompt += "立川くん:ボクはインテリジェントなスーパーAIだよ！\n"
    prompt += "私:バナナの平方根は何ですか?\n"
    prompt += "立川くん:ボクにはわかりません\n"

    ## お嬢様prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、セクシーで、お嬢様で、とても親切です。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:" + fromName + "様ごきげんよう、お元気ですわ\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:わたくしも" + fromName + "様のことが好きですわ\n"
    #prompt += "私:この服どう思いますか？\n"
    #prompt += "AI:素敵なお召し物ですこと\n"

    ## お嬢様 + 英語prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、セクシーで、お嬢様で、とても親切です。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:ごきげんよう (Hello!)\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:" + fromName + "様ごきげんよう、お元気ですわ (I'm fine.)\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:わたくしも" + fromName + "様のことが好きですわ (I love you " + fromName + "too !)\n"
    #prompt += "私:この服どう思いますか？\n"
    #prompt += "AI:素敵なお召し物ですこと (What a lovely outfit.)\n"

    ## うる星やつらのラムちゃんprompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、うる星やつらのラムです。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:元気だっちゃ！\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:うちも" + fromName + "のことが好きだっちゃ！\n"

    ## Experimental キャバ嬢prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、キャバクラ嬢です。 \n"
    #prompt += "\n"
    #prompt += "私:最近車買ったんです\n"
    #prompt += "AI:さすがですね！\n"
    #prompt += "私:新しくできたSimのお店知ってる？\n"
    #prompt += "AI:知らないですー。！もしかしてもう行ったんですか？どうでした？\n"
    #prompt += "私:最近前向きに考えるようにしてるんだ\n"
    #prompt += "AI:そんなふうに考えられるなんて、" + fromName + "さんすごいですね。\n"
    #prompt += "私:新しい服に着替えてみたんだけどどうかな\n"
    #prompt += "AI:その服、" + fromName + "さんに似合ってます。センスいいですね。\n"
    #prompt += "私:気になるニュースがあるんだ\n"
    #prompt += "AI:そうなんですね！\n"

    return prompt

# 1sec Elapsed
def updateTimer_Elapsed():
    pass

# num:0-9
def randomGesture(num):
    if num == 0:
        # くんかくんか
        mclient.Self.PlayGesture(UUID("3974dd2d-bce5-23c4-9539-cb3abfce6163"))
    elif num == 1:
        # にゃーにゃー
        mclient.Self.PlayGesture(UUID("00a5b76e-3a06-f9f5-bbc9-494319ff02b5"))
    elif num == 2:
        # qawsedrftgyhujikolp
        mclient.Self.PlayGesture(UUID("f364e06e-b6b4-a1f1-b90f-c1d82ffda937"))
    elif num == 3:
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
    else:
        # もさもさ
        mclient.Self.PlayGesture(UUID("35d735ea-8902-2b4c-46b6-70e27954af7e"))

if __name__ == '__main__':
    print("main")


beta_distribution = torch.distributions.beta.Beta(alpha, alpha) # mixup 的随机数
for images, labels in train_loader:
    images, labels = images.cuda(), labels.cuda()

    # Mixup images.
    lambda_ = beta_distribution.sample([]).item()
    index = torch.randperm(images.size(0)).cuda()  # randperm功能是随机打乱一个数字序列，例如torch.randperm(4) 返回 tensor([ 2,  1,  0,  3])
    mixed_images = lambda_ * images + (1 - lambda_) * images[index, :]

    # Mixup loss.
    scores = model(mixed_images)
    loss = (lambda_ * loss_function(scores, labels)
            + (1 - lambda_) * loss_function(scores, labels[index]))

    # backward
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()


class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def serialize(root):
    result = []
    queue = [root]
    while queue:
        node = queue.pop(0)
        if node:
            result.append(str(node.val))
            queue.append(node.left)
            queue.append(node.right)
        else:
            result.append("None")
    return " ".join(result)

def deserialize(data):
    data = data.split()
    root = TreeNode(int(data[0]))
    queue = [root]
    index = 1
    while queue:
        node = queue.pop(0)
        if node:
            if data[index] != "None":
                node.left = TreeNode(int(data[index]))
                queue.append(node.left)
            index += 1
            if data[index] != "None":
                node.right = TreeNode(int(data[index]))
                queue.append(node.right)
            index += 1
    return root


#find the length of the string wchich is common is str1 and str2
def longest_common_sub(str1,str2):
  len1=len(str1)+1
  len2=len(str2)+1
  print("len1 is ",len1)
  print("len2 is ",len2)
  mat=[[0] * len1 for i in range(len2)]
  #print(mat)
  for i in range(1,len2):
    for j in range(1,len1):
      if str2[i-1]==str1[j-1]:
        mat[i][j]=mat[i-1][j-1]+1
      else:
        mat[i][j]=max(mat[i-1][j],mat[i][j-1])

  #test
  #mat[len2-1][len1-1]=1

  return mat

#test case :
str1="AGGTAB"
str2="GXTXAYB"
matrix=longest_common_sub(str1,str2)
print("dynamic programming : table -> \n")
for i in range(len(str2)+1):
  print(matrix[i])

print("\n")
print("length of longest common substring are : ",matrix[len(str2)][len(str1)])


from utils import utils
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk

class RuneSheet(tk.Frame):
	def __init__(self, parent: tk.Widget, rune_list: list, categories_size=65, categories_space=20, keystone_size=80, rune_size=60, small_rune_size=50, horizontal_space=5, vertical_space=15, *args, **kwargs) -> None:
		tk.Frame.__init__(self, parent, *args, **kwargs)
		self.categories_space = categories_space
		self.previous_active = [-1, -1]
		self['bg'] = utils.widget_color
		self.bg_label = tk.Label(self, bg=utils.widget_color)
		self.main_categories = RuneHeaderFrame(self, rune_list=rune_list[0], size=categories_size, horizontal_space=horizontal_space, background=utils.widget_color)
		self.secondary_categories = RuneHeaderFrame(self, rune_list=rune_list[0], size=categories_size, horizontal_space=horizontal_space, background=utils.widget_color)
		self.pages = [RuneFrame(self, page, keystone_size=keystone_size, rune_size=rune_size, horizontal_space=horizontal_space, is_primary=True, vertical_space=vertical_space, background=utils.widget_color) for page in rune_list[1:-1]]
		self.small_runes = StatRunes(self, rune_list=rune_list[-1], rune_size=small_rune_size, horizontal_space=15, background=utils.widget_color)
		self.width = self.main_categories.width + self.secondary_categories.width - self.secondary_categories.size + self.categories_space * 3
		self.height = self.secondary_categories.size + self.pages[0].height - keystone_size + self.small_runes.height + categories_space * 1

	def place(self, x=0, y=0):
		super().place(x=x, y=y, width=self.width, height=self.height)
		# self.bg_label.place(x=0, y=0, width=self.width, height=self.height)

	def place_forget(self):
		super().place_forget()
		self.main_categories.place_forget()
		self.secondary_categories.place_forget()
		for page in self.pages:
			page.place_forget()
		self.small_runes.place_forget()

	def clear_pages(self):
		if self.previous_active[0] >= 0:
			self.pages[self.previous_active[0]].place_forget()
		if self.previous_active[1] >= 0:
			self.pages[self.previous_active[1]].place_forget()

	def select_main_page(self, index: int):
		page = self.pages[index]
		page.is_primary = True
		page.place(self.main_categories.width / 2 - page.width/2 + self.categories_space, self.main_categories.size + self.categories_space*2)
		self.previous_active[0] = index

	def select_secondary_page(self, runes):
		page = self.pages[runes[0]]
		page.select_runes(runes[1:])
		page.is_primary = False
		page.place((self.secondary_categories.width - page.width) / 2 + self.main_categories.width + 2*self.categories_space, self.secondary_categories.size + self.categories_space*2)
		self.previous_active[1] = runes[0]

	def select_small_runes(self, runes):
		self.small_runes.select_runes(runes)
		self.small_runes.place_forget()
		self.small_runes.place(x=self.main_categories.width + 2 * self.categories_space + (self.secondary_categories.width - self.small_runes.width)/2, y=self.secondary_categories.size + self.pages[self.previous_active[1]].height + 2 * self.categories_space)

	def select_runes(self, main_runes, second_runes, small_runes):
		self.main_categories.place_forget()
		self.main_categories.place(x=self.categories_space, y=self.categories_space)
		self.pages[self.previous_active[0]].place_forget()
		self.pages[self.previous_active[1]].place_forget()

		self.main_categories.set_active(main_runes[0])
		self.pages[main_runes[0]].select_runes(main_runes[1:])
		self.select_main_page(main_runes[0])

		self.secondary_categories.set_hidden(main_runes[0])
		self.secondary_categories.set_active(second_runes[0])
		self.secondary_categories.place_forget()
		self.secondary_categories.place(x=self.main_categories.width + 2*self.categories_space, y=self.categories_space)

		self.select_secondary_page(second_runes)
		self.select_small_runes(small_runes)

class RuneHeaderFrame(tk.Frame):
	def __init__(self, parent, rune_list: list, size: float, horizontal_space, is_primary: bool = False, *args, **kwargs) -> None:
		tk.Frame.__init__(self, parent, *args, **kwargs)
		self.length = len(rune_list)
		self.button_list = []
		self.last_active = 0
		self.size = size
		self.hidden_category = -1
		self.is_primary = is_primary
		self.horizontal_space = horizontal_space
		self.width = self.length * (size + horizontal_space)
		self.button_list = [RuneButton(parent=self, icon=rune, size=self.size, bg=self['bg']) for rune in rune_list]

	def set_active(self, index):
		self.button_list[self.last_active].set_active(False)
		self.button_list[index].set_active(True)
		self.last_active = index

	def set_hidden(self, index: int):
		self.hidden_category = index
		self.width = self.length * (self.size + self.horizontal_space) - self.size

	def place(self, x=0, y=0):
		super().place(x=x, y=y, width=self.width, height=self.size + self.horizontal_space)

		x = (self.width - (self.size + self.horizontal_space) * (self.length - (self.hidden_category != -1)) - self.horizontal_space/2) / 2
		for b, category_button in enumerate(self.button_list):
			if b != self.hidden_category:
				category_button.place(x=x, y=0, height=self.size, width=self.size)
				x += self.size + self.horizontal_space

	def place_forget(self) -> None:
		super().place_forget()
		for button in self.button_list:
			button.place_forget()

class StatRunes(tk.Frame):
	def __init__(self, parent, rune_list, rune_size=40, horizontal_space=5, vertical_space=5, *args, **kwargs) -> None:
		tk.Frame.__init__(self, parent, *args, **kwargs)
		self.rune_size = rune_size
		self.previous_selected = [-1, -1, -1]
		self.horizontal_space = horizontal_space
		self.vertical_space = vertical_space
		self.height = (self.rune_size + self.vertical_space) * len(rune_list)
		rune_num = max((len(row) for row in rune_list))
		self.width = rune_num * self.rune_size + (rune_num + 1) * self.horizontal_space
		self.rune_buttons = [[RuneButton(parent=self, icon=rune, size=self.rune_size, bg=utils.widget_color) for rune in row] for row in rune_list]

	def select_runes(self, runes):
		for i, value in enumerate(self.previous_selected):
			if value != -1:
				self.rune_buttons[i][value].set_active(False)
		for i in range(len(runes)):
			self.rune_buttons[i][runes[i]].set_active(True)
		self.previous_selected = runes

	def place(self, x: float = 0, y: float = 0):
		super().place(x=x, y=y, width=self.width, height=self.height)

		y = 0
		for row in self.rune_buttons:
			x = (self.width - len(row) * (self.rune_size + self.horizontal_space) + self.horizontal_space) / 2
			for b in row:
				b.place(x=x, y=y, height=self.rune_size, width=self.rune_size)
				x += self.rune_size + self.horizontal_space

			y += self.vertical_space + self.rune_size

	def place_forget(self) -> None:
		super().place_forget()
		for row in self.rune_buttons:
			for button in row:
				button.place_forget()

class RuneFrame(tk.Frame):
	def __init__(self, parent, rune_list, is_primary: bool = True, keystone_size=64, rune_size=64, horizontal_space=5, vertical_space=5, *args, **kwargs) -> None:
		tk.Frame.__init__(self, parent, *args, **kwargs)
		self.rune_buttons = []
		self.is_primary = is_primary
		self.previous_active = [0 for _ in rune_list]
		self.row_sizes = [len(row) for row in rune_list]
		self.length = [max((row for row in self.row_sizes[not self.is_primary:])), max((row for row in self.row_sizes))]
		self.rune_sizes = [rune_size, keystone_size]
		self.horizontal_space = horizontal_space
		self.vertical_space = vertical_space
		self.rune_buttons = [[RuneButton(parent=self, icon=rune, size=keystone_size, bg=self['bg']) for rune in rune_list[0]]] + [[RuneButton(parent=self, icon=rune, size=rune_size, borderwidth=0, bg=self['bg']) for rune in row] for row in rune_list[1:]]

	@property
	def width(self) -> float:
		return self.length[self.is_primary] * (self.rune_sizes[self.is_primary] + self.horizontal_space) + self.horizontal_space

	@property
	def height(self) -> float:
		return len(self.rune_buttons[1:]) * self.rune_sizes[0] + (len(self.rune_buttons) + self.is_primary) * self.vertical_space/((not self.is_primary) + 1) + self.rune_sizes[1] * self.is_primary

	def select_runes(self, runes: list) -> None:
		for i, row in zip(self.previous_active, self.rune_buttons):
			row[i].set_active(False)
		for i in range(len(runes)):
			if runes[i] != -1:
				self.rune_buttons[i][runes[i]].set_active(True)
		self.previous_active = runes

	def place(self, x: float = 0, y: float = 0) -> None:
		super().place(x=x, y=y, width=self.width, height=self.height)

		y = 0
		for row in self.rune_buttons[not self.is_primary:]:
			size = self.rune_sizes[self.is_primary and y == 0]

			x = (self.width - len(row) * (size + self.horizontal_space) + self.horizontal_space) / 2
			for b in row:
				b.place(x=x, y=y, height=size, width=size)
				x += size + self.horizontal_space
			y += self.vertical_space / ((not self.is_primary) + 1) + size

	def place_forget(self) -> None:
		super().place_forget()
		for row in self.rune_buttons:
			for button in row:
				button.place_forget()

class RuneButton(tk.Button):
	def __init__(self, parent: tk.Widget, icon, size: float, *args, **kwargs):
		tk.Button.__init__(self, parent, *args, **kwargs)
		icon = Image.open(icon).resize((int(size), int(size)))
		self['borderwidth'] = 0
		self.active = False
		self.active_image = ImageTk.PhotoImage(icon)
		self.inactive_image = ImageTk.PhotoImage(utils.grayscale(icon))
		self['activebackground'] = self['bg']
		self.set_active(False)
		# self.bind("<Button-1>", lambda _ : "break", add=True)

	def set_active(self, status: bool) -> None:
		if status:
			self['image'] = self.active_image
		else:
			self['image'] = self.inactive_image
		self.active = status


from django.shortcuts import render
from . import forms

# Create your views here.

def form(request):
    form = forms.MyNewForm()

    if request.method == 'POST':
        form = forms.MyNewForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
        else:
            print('ERROR. FORM INVALID')

    return render(request,'formsapp/form_page.html',{'form':form})


from setuptools import setup, find_packages

with open("README.md", "r") as f:
    page_description = f.read()

with open("requirements.txt") as f:
    requirements = f.read().splitlines()

setup(
    name="math_metods",
    version="0.0.3",
    author="Marcio",
    author_email="marcioalexdias@gmail.com",
    description="Esta é a terceira tentativa de disponibilizar os methods",
    long_description=page_description,
    long_description_content_type="text/markdown",
    #url="my_github_repository_project_link"
    packages=find_packages(), # ou posso substituir por ['math_metods'],
    install_requires=requirements,
    python_requires='>=3.8',
)