# Test d'un cache en utilisant un weakref.WeakValueDictionary
# 2021-02-26    PV

import weakref
import collections
import random
import matplotlib.pyplot as plt     # type: ignore
import math

# Classe objet arbitraire
class sprocket:
    def __init__(self, key: int) -> None:
        self.key = key

def test_cache(global_size:int, cache_size: int, rounds: int) -> float:
    # Les objects ne sont présents dans ce cache que s'ils existent dans cache_que.  Le test est rapide puisque c'est un dictionnaire
    cache_dic: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
    # Simple queue de stockage des objets cachés, limitée à cache_size entrées
    cache_que: collections.deque = collections.deque(maxlen=cache_size)

    # Retourne le coût pour obtenir le sprocket de clé key, par convention la création de l'objet a un coût de 50 (ex: lecture BD) contre 1 s'il est dans le cache
    def build_item(key: int) -> int:
        if key in cache_dic:
            s = cache_dic[key]
            # On place l'objet en tête de cache, comme s'il venait d'être ajouté au cache pour la première fois
            cache_que.remove(s)
            cache_que.append(s)
            return 1
        s = sprocket(key)
        cache_que.append(s)
        cache_dic[key] = s
        return 50

    cost = 0
    for i in range(rounds):
        while True:
            # Deux modèle d'accès aléatoire aux clés, un modèle "loi normale" centrée en global_size/2, et un modèle uniforme
            k = math.floor(random.normalvariate(global_size/2,global_size/8))
            #k = random.randint(1, global_size)
            if 1<=k<=global_size: break
        cost += build_item(k)
    return cost/rounds

print(test_cache(10,10,100))

sizes = [5*i for i in range(0,20)]
costs = [test_cache(100,s,200) for s in sizes]

#print(sizes)
#print(costs)

"""
# Test d'une loi normale
b = 50
sizes = range(b+1)
costs = [0]*(b+1)
for i in range(100000):
    k = math.floor(random.normalvariate(b/2,b/8))
    if 0<=k<=b:
        costs[k]+=1
print(costs)
"""

plt.plot(sizes, costs)
plt.show()


from code import interact
from distutils.log import error
from ssl import VerifyFlags
import discord
import random
import asyncio
import os
import json
#-----------------

os.chdir("G:\\pyApps\\SimpleEcoBot") #Setar diretório

from dotenv import load_dotenv
from discord.ui import Button, View
from discord.ext import commands

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

load_dotenv()
TOKEN = os.getenv('TOKEN') #Pegar token do .env

client = discord.Client(intents=discord.Intents.all())
bot = commands.Bot(command_prefix='$',intents=discord.Intents.all())  ##Selecione prefix aqui

@bot.event #            Evento de contar servidores online
async def on_ready():
    guild_count = 0

    for guild in bot.guilds:
        guild_count =+ 1

    print(f"Conectado em {guild_count} guilds!")

#economia--------------------------------------------------------------

@bot.command(pass_context=True)
async def bal(ctx, user : discord.User = None): # Ver saldo
  if user != None:
    await open_account(user)
    users = await get_bank_data()
    id = user.id
    carteira_amt = users[str(id)]["carteira"]
    banco_amt = users[str(id)]["banco"]

    em = discord.Embed(title = f"Banco de {user.name}")
    em.add_field(name = "Saldo na Carteira: $", value = carteira_amt)
    em.add_field(name = "Saldo no Banco: $", value = banco_amt)

    await ctx.send(embed = em)
  else:
    await open_account(ctx.author)
    users = await get_bank_data()
    carteira_amt = users[str(ctx.author.id)]["carteira"]
    banco_amt = users[str(ctx.author.id)]["banco"]

    em = discord.Embed(title = f"Banco de {ctx.author.name}")
    em.add_field(name = "Saldo na Carteira: ", value = carteira_amt)
    em.add_field(name = "Saldo no Banco: ", value = banco_amt)

    await ctx.send(embed = em)

#@===============================

@bot.command()
@commands.cooldown(1, 3, commands.BucketType.user)

async def mendigar(ctx):         # Ganhar dinheiro
  await open_account(ctx.author)
  users = await get_bank_data()
  rng1 = random.randint(1,10)
  rng2 = random.randint(0,15)

  if rng1 == 10:
   loseamt = random.randrange(1,15)
   carteirab4 = users[str(ctx.author.id)]["carteira"]

   await ctx.send(f"**Você estava mendingando na área de outro mendigo, e ele te espancou e roubou ${int(carteirab4 / loseamt)} de você!**")

   carteira_amt = users[str(ctx.author.id)]["carteira"] = users[str(ctx.author.id)]["carteira"] - int(users[str(ctx.author.id)]["carteira"] / loseamt)

  else:
    await ctx.send(f"**Você mendigou o dia inteiro e acabou com mais ${rng2} no bolso.**")

    carteira_amt = users[str(ctx.author.id)]["carteira"] = users[str(ctx.author.id)]["carteira"] + rng2

  with open("utils\\bank.json","w") as f:
    json.dump(users,f)
  return True

#@===============================

@mendigar.error                          ## Detectar erro de cooldown e avisar o usuário
async def mendigar_error(ctx, error):
    if isinstance(error, discord.ext.commands.errors.CommandOnCooldown):
        msg1 =  await ctx.reply("*Comando em cooldown!*")
        await asyncio.sleep(1)
        await msg1.delete()
        await ctx.message.delete()

#@===============================

@bot.command()
async def dep(ctx, *, valor : int):     ## Comando de depositar (para realizar um withdraw é só inverter o comando)
  await open_account(ctx.author)
  users = await get_bank_data()
  carteira_amt = users[str(ctx.author.id)]["carteira"]
  banco_amt = users[str(ctx.author.id)]["banco"]
  if valor <= carteira_amt:
    banco_amt = users[str(ctx.author.id)]["banco"] = users[str(ctx.author.id)]["banco"] + valor
    carteira_amt = users[str(ctx.author.id)]["carteira"] = users[str(ctx.author.id)]["carteira"] - valor
    await ctx.send(f"**Você depositou ${valor}**")
  else:
    await ctx.send("**Você não tem dinheiro suficiente para depositar.**")

  with open("utils\\bank.json","w") as f:
    json.dump(users,f)
  return True

#@===============================

async def open_account(user):         ## Async de criar uma conta no bank.json se o usuário não tiver uma ainda
  users = await get_bank_data()

  if str(user.id) in users:
    return False
  else:
    users[str(user.id)] = {}
    users[str(user.id)]["carteira"] = 0
    users[str(user.id)]["banco"] = 0

  with open("utils\\bank.json","w") as f:
    json.dump(users,f)
  return True

async def get_bank_data():          ## Async de pegar dados de todos os usuários e retornar
  with open("utils\\bank.json","r") as f:
    users = json.load(f)
  return users

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

bot.run(TOKEN) #      Run


"""
From: https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html
"""

import time
import os

import torch
from torch import optim
from torch.utils.data import DataLoader
import torch.nn as nn
from torchtext.datasets import text_classification
from torch.utils.data.dataset import random_split

from src.ml_helper.training import (
    register_model_in_db, register_epoch_in_db,
    hash_parameters, delete_model
)

BATCH_SIZE = 16
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

class TextSentiment(nn.Module):
    def __init__(self, vocab_size, embed_dim, num_class):
        super().__init__()
        self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True)
        self.fc = nn.Linear(embed_dim, num_class)
        self.init_weights()

    def init_weights(self):
        initrange = 0.5
        self.embedding.weight.data.uniform_(-initrange, initrange)
        self.fc.weight.data.uniform_(-initrange, initrange)
        self.fc.bias.data.zero_()

    def forward(self, text, offsets):
        embedded = self.embedding(text, offsets)
        return self.fc(embedded)

def generate_batch(batch):
    label = torch.tensor([entry[0] for entry in batch])
    text = [entry[1] for entry in batch]
    offsets = [0] + [len(entry) for entry in text]
    # torch.Tensor.cumsum returns the cumulative sum
    # of elements in the dimension dim.
    # torch.Tensor([1.0, 2.0, 3.0]).cumsum(dim=0)

    offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)
    text = torch.cat(text)

    return text, offsets, label

def train_func(model, optimizer, criterion, scheduler, sub_train_):

    # Train the model
    train_loss = 0
    train_acc = 0
    data = DataLoader(
        sub_train_,
        batch_size=BATCH_SIZE,
        shuffle=True,
        collate_fn=generate_batch
    )

    for i, (text, offsets, cls) in enumerate(data):
        optimizer.zero_grad()
        text, offsets, cls = text.to(device), offsets.to(device), cls.to(device)
        output = model(text, offsets)
        loss = criterion(output, cls)
        train_loss += loss.item()
        loss.backward()
        optimizer.step()
        train_acc += (output.argmax(1) == cls).sum().item()

    # Adjust the learning rate
    scheduler.step()

    return train_loss / len(sub_train_), train_acc / len(sub_train_)

def test(model, criterion, data_):
    loss = 0
    acc = 0
    data = DataLoader(data_, batch_size=BATCH_SIZE, collate_fn=generate_batch)
    for text, offsets, cls in data:
        text, offsets, cls = text.to(device), offsets.to(device), cls.to(device)
        with torch.no_grad():
            output = model(text, offsets)
            loss = criterion(output, cls)
            loss += loss.item()
            acc += (output.argmax(1) == cls).sum().item()

    return loss / len(data_), acc / len(data_)

def main():
    if not os.path.isdir('./.data'):
        os.mkdir('./.data')

    train_dataset, test_dataset = text_classification.DATASETS['AG_NEWS'](
        root='./.data',
        ngrams=2,
        vocab=None
    )

    VOCAB_SIZE = len(train_dataset.get_vocab())
    NUN_CLASS = len(train_dataset.get_labels())

    params = dict(
        embed_dim=32,
        n_epochs=5,
        lr=0.04,
        model_name="TextSentiment",
        optimizer_name="SGD"
    )

    model_id = hash_parameters(params)
    delete_model(model_id)
    register_model_in_db(model_id, params)
    print("stored model id:", model_id)

    model = TextSentiment(
        VOCAB_SIZE,
        params["embed_dim"],
        NUN_CLASS
    ).to(device)

    criterion = torch.nn.CrossEntropyLoss().to(device)
    optimizer = getattr(optim, params["optimizer_name"])(model.parameters(), lr=params["lr"])
    scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, gamma=0.9)

    train_len = int(len(train_dataset) * 0.95)
    sub_train_, sub_valid_ = random_split(
        train_dataset,
        [train_len, len(train_dataset) - train_len]
    )

    for epoch in range(params["n_epochs"]):

        start_time = time.time()
        train_loss, train_acc = train_func(
            model, optimizer,
            criterion, scheduler, sub_train_
        )
        valid_loss, valid_acc = test(model, criterion, sub_valid_)

        secs = int(time.time() - start_time)
        mins = secs / 60
        secs = secs % 60

        register_epoch_in_db(
            model_id,
            epoch+1,
            training_loss=train_loss,
            eval_loss=valid_loss.item(),
            training_acc=train_acc,
            eval_acc=valid_acc
        )

        print('Epoch: %d' % (epoch + 1), " | time in %d minutes, %d seconds" % (mins, secs))
        print(f'\tLoss: {train_loss:.4f}(train)\t|\tAcc: {train_acc * 100:.1f} % (train)')
        print(f'\tLoss: {valid_loss:.4f}(valid)\t|\tAcc: {valid_acc * 100:.1f} % (valid)')

if __name__ == '__main__':
    main()


from telnetlib import SB
import numpy as np
from matplotlib import pyplot as plt
from scipy import interpolate
from scipy.ndimage.filters import uniform_filter1d
from . import loadMIT
from . import toolsMIT as TM
import pandas as pd

def nan_helper(y):
    """Helper to handle indices and logical indices of NaNs.

    Input:
        - y, 1d numpy array with possible NaNs
    Output:
        - nans, logical indices of NaNs
        - index, a function, with signature indices= index(logical_indices),
          to convert logical indices of NaNs to 'equivalent' indices
    Example:
        >>> # linear interpolation of NaNs
        >>> nans, x= nan_helper(y)
        >>> y[nans]= np.interp(x(nans), x(~nans), y[~nans])
    """

    return np.isnan(y), lambda z: z.nonzero()[0]

def ot_time(upr, Lx, dz, dy):
    if np.nansum(upr) == 0:
        mot = otp = otn = 0
        return mot, otp, otn

    negi = np.nonzero(upr < 0)[0]
    posi = np.nonzero(upr > 0)[0]
    maxi = np.nonzero(upr == np.nanmax(upr))[0]
    mini = np.nonzero(upr == np.nanmin(upr))[0]

    if maxi > np.max(negi):
        maxido = -1
    else:
        maxido = negi[np.min(np.nonzero(negi > maxi[0])[0])]

    if maxi < np.min(negi):
        maxiup = 0
    else:
        maxiup = negi[np.max(np.nonzero(negi < maxi[0])[0])] + 1

    if np.max(mini) > np.max(posi):
        minido = -1
    else:
        minido = posi[np.min(np.nonzero(posi > mini[0])[0])]

    if np.min(mini) < np.min(posi):
        miniup = 0
    else:
        miniup = posi[np.max(np.nonzero(posi < mini[0])[0])] + 1

    upos = np.nanmean(upr[maxiup:maxido])
    uneg = np.nanmean(upr[miniup:minido])

    otp = np.abs(Lx / np.abs(upos) / 86400)
    otn = np.abs(Lx / np.abs(uneg) / 86400)
    mot = otn + otp

    return mot, otn, otp

def ot_time_Q(coords, upr, Qout=False):
    dz = coords["dz"][0]
    dy = 10
    dx = coords["dx"][0]
    V = np.sum(coords["hfac"][:, 0:-200] * dx * dy * dz)
    Q = np.nancumsum(upr * dy * dz)
    mot = np.abs(V / np.max(np.abs(Q)) / 86400)
    if Qout:
        return mot, Q
    else:
        return mot

def gadeline(tice=-2, tam=0, sam=35, z=0):

    g = 9.81
    rhonil = 9.998e2
    a0 = -0.0575
    c0 = 0.0901
    b = -7.61e-8
    tfr1 = a0 * 0
    tfr2 = b * rhonil * g * z
    tfr = tfr1 + c0 + tfr2

    # %% Gade Line & T-Freeze
    L = 334e3
    cp = 3.994e3
    ci = 2e3
    gam = ci / cp

    T0 = tice  # ice
    T1 = tfr
    # Solve for T2
    T3 = tam

    TF = T3 - T1
    # S1 no exist
    S2 = sam - 2
    S3 = sam
    dTdS = S3 ** (-1) * (TF + L / cp + gam * (T1 - T0))

    T2 = T3 - dTdS * (S3 - S2)
    return [S2, S3], [T2, T3]

def calc_dist_along(a, b, c=None):
    if c is None:
        c = np.zeros(np.array(np.shape(a)))

    d = np.zeros(np.array(np.shape(a)))

    d[1:] = np.cumsum(np.sqrt((a[1:] - a[0:-1]) ** 2 + (b[1:] - b[0:-1]) ** 2))
    d[0] = 0

    return d

def nanave2d(a, w, axis=0):

    if axis == 0:
        niter = np.shape(a)[1]
        ave = np.zeros(niter)

        for i in np.arange(0, niter):
            if np.nansum(w[:, i]) == 0:
                ave[i] = np.nan
            else:
                ave[i] = np.nansum(a[:, i] * w[:, i]) / np.nansum(w[:, i])
    else:
        niter = np.shape(a)[0]
        ave = np.zeros(niter)

        for i in np.arange(0, niter):
            if np.nansum(w[i, :]) == 0:
                ave[i] = np.nan
            else:
                ave[i] = np.nansum(a[i, :] * w[i, :]) / np.nansum(w[i, :])

    return ave

def plume_diag(coords, var, ret=[], mask="w"):
    """
    calculate Plume diagnostics
    """

    hfac = 1 * coords["hfac"]
    ice = coords["ice"]

    x = coords["x"]
    dx = coords["dx"]
    if len(ice) > len(x):
        ice = ice[: len(x)]

    d = calc_dist_along(x, ice) + x[0]

    z = coords["z"]
    dz = -coords["dz"][0]

    pthresh = 35 * dz
    z_plu = np.arange(0, -pthresh - dz, -dz)

    t = np.nanmean(var["t_all"], axis=0)
    taw = var["tref"][-1]
    tref = var["tref"]
    tamb = t[:, 2000]
    dt = np.zeros(np.shape(t))
    # dt = t - taw
    s = np.nanmean(var["s_all"], axis=0)
    saw = var["sref"][-1]
    sref = var["sref"]
    samb = s[:, 2000]
    ds = np.zeros(np.shape(s))
    for i in np.arange(0, len(x)):
        ds[:, i] = s[:, i] - sref
        dt[:, i] = t[:, i] - tref
    # ds = s - saw
    u = np.nanmean(var["u_all"], axis=0)
    u_all = var["u_all"]
    w_all = var["w_all"]
    w = np.nanmean(var["w_all"], axis=0)

    # fig, ax = plt.subplots(1, 1)
    # cf = ax.contourf(ds)
    # fig.colorbar(cf, ax=ax)
    # fig.show()

    pmask = np.ones(np.shape(t)) * hfac
    for i in np.arange(0, np.shape(t)[1]):
        if ice[i] < 0:
            indi = np.where(z < (ice[i] - pthresh))
            pmask[indi, i] = 0
        else:
            pmask[:, i] = 0

    u, w = loadMIT.uw_ontracer(u, w, coords)

    wthresh = 0.0000
    tthresh = -0.01
    sthresh = -0.01

    if mask == "w":
        pmask[w <= wthresh] = 0
    elif mask == "u":
        pmask[u <= wthresh] = 0
    elif mask == "t":
        pmask[dt >= tthresh] = 0
    elif mask == "s":
        pmask[ds >= sthresh] = 0

    t_plu = np.zeros([int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    dt_plu = np.zeros([int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    s_plu = np.zeros([int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    u_plu = np.zeros([int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    w_plu = np.zeros([int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    h_plu = np.zeros([int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    u_plu_all = (
        np.zeros([np.shape(u_all)[0], int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    )
    w_plu_all = (
        np.zeros([np.shape(w_all)[0], int(pthresh / dz) + 1, np.shape(d)[0]]) * np.nan
    )

    for i in np.arange(np.shape(d)[0]):
        plu = np.where(pmask[:, i] != 0)
        t_plu[: np.shape(plu)[1], i] = t[plu, i]
        dt_plu[: np.shape(plu)[1], i] = dt[plu, i]
        s_plu[: np.shape(plu)[1], i] = s[plu, i]
        u_plu[: np.shape(plu)[1], i] = u[plu, i]
        w_plu[: np.shape(plu)[1], i] = w[plu, i]
        h_plu[: np.shape(plu)[1], i] = u[plu, i]
        for n in range(np.shape(u_all)[0]):
            u_plu_all[n, : np.shape(plu)[1], i] = u_all[n, plu, i]
            w_plu_all[n, : np.shape(plu)[1], i] = w_all[n, plu, i]

    thick = np.nansum(dz * pmask, axis=0)

    if "flx" in ret:
        uflx = u_plu * h_plu * dz * dx
        wflx = w_plu * dx * dx

        flx = np.sqrt(uflx**2 + wflx**2)

        uflx = np.nansum(uflx, axis=0)
        wflx = np.nansum(wflx, axis=0)
        flx = np.nansum(flx, axis=0)

    ret_dic = {
        "d": d,
        "thick": thick,
        "t_plu": t_plu,
        "dt_plu": dt_plu,
        "s_plu": s_plu,
        "u_plu": u_plu,
        "w_plu": w_plu,
        "u_plu_all": u_plu_all,
        "w_plu_all": w_plu_all,
        "z_plu": z_plu,
        "dt": dt,
        "ds": ds,
    }
    if "flx" in ret:
        ret_dic.update(
            {
                "flx": flx,
                "uflx": uflx,
                "wflx": wflx,
            }
        )

    return ret_dic

def entraiment_coeff(w, rho, rho_amb, dx, dz, kappa_z=[], kappa_x=[]):
    drhod = np.zeros(np.shape(rho))
    if kappa_z:
        print("use vertical derivative and horizontal velocity")
        kappa = kappa_z
        for j in range(np.shape(rho)[1]):
            drhod[1:-1, j] = (rho[0:-2, j] - rho[2:, j]) / 2 * -dz
            drhod[0, j] = (rho[1, j] - rho[0, j]) / -dz
            drhod[-1, j] = (rho[-1, j] - rho[-2, j]) / -dz
    if kappa_x:
        kappa = kappa_x
        print("use horizontal derivative/diffusivity and vertical velocity")
        for j in range(np.shape(rho)[0]):
            drhod[j, 1:-1] = (rho[j, 0:-2] - rho[j, 2:]) / 2 * dx
            drhod[j, 0] = (rho[j, 1] - rho[j, 0]) / dx
            drhod[j, -1] = (rho[j, -1] - rho[j, -2]) / dx

    if len([rho_amb]) == 1:
        drho = np.abs(rho_amb - rho)
    elif len(rho_amb) == np.shape(rho)[0]:
        drho = np.zeros(np.shape(rho))
        for i in range(np.shape(rho)[1]):
            drho[:, i] = rho_amb - rho[:, i]
    elif len(rho_amb) == np.shape(rho)[1]:
        drho = np.zeros(np.shape(rho))
        for i in range(np.shape(rho)[0]):
            drho[i, :] = rho_amb - rho[i, :]

    # plt.plot(np.nansum(drhod, axis=0), label="drhodz")
    # plt.plot(np.nansum(w, axis=0), label="u")
    # plt.plot(np.nansum(drho, axis=0), label="delta rho")
    # plt.legend()
    # plt.show()

    drho[np.isnan(drhod)] = np.nan
    Fe = np.nansum(w * drho * dx * dz)
    Fe_x = np.nansum(w * drho * dx * dz, axis=0)
    Fe_x[Fe_x == 0] = np.nan

    Fd = np.nansum(drhod * dx * dz)
    Fd_x = np.nansum(drhod * dx * dz, axis=0)

    # plt.plot(Fd_x, label="Fd")
    # plt.plot(Fe_x, label="Fe")
    # plt.plot(Fd_x[100:] / Fe_x[100:], label="")
    # plt.legend()
    # plt.show()

    alpha = Fd / Fe * kappa
    alpha_x = (Fd_x / Fe_x) * kappa

    entrain = {
        "alpha": alpha,
        "alpha_x": alpha_x,
        "Fe": Fe,
        "Fe_x": Fe_x,
        "Fd": Fd,
        "Fd_x": Fd_x,
    }
    return entrain

def rho_cont(T, S):
    t = np.linspace(min(T), max(T), 99)
    s = np.linspace(min(S), max(S), 100)

    tm, sm = np.meshgrid(t, s)

    t0 = 1
    s0 = 35
    tAlpha = -0.4e-4
    sBeta = 8.0e-4
    rnil = 999.8

    rm = rnil * (1 + tAlpha * (tm - t0) + sBeta * (sm - s0))
    return tm, sm, rm

def extract_mdata(path, filename=[], to_file=False):

    global mdata
    coords = TM.coords
    dx = coords[0]["dx"][-1]
    ice = coords[0]["ice"]
    data = TM.data
    SHIflx = TM.SHIflx

    lam1 = -5.75e-2
    lam2 = 9.01e-2
    lam3 = -7.61e-4
    tAlpha = -0.4e-4
    sBeta = 8.0e-4
    rnil = 999.8

    mdata = {
        "exp": [],
        "T_AW": [],
        "sgd": [],
        "MeltFlux": [],
        "PlumeFlux": [],
        "TF": [],
        "AveMelt": [],
        "Entrainment_u": [],
        "Fe/Fd": [],
    }
    for vi in np.arange(0, np.shape(data)[0]):
        print(path[vi])
        plume = plume_diag(coords[vi], data[vi], ["flx"], mask="u")
        dz = plume["z_plu"][1] - plume["z_plu"][0]
        flx = plume["flx"]
        flxi = np.min([np.nanargmax(flx), 1500])

        taw = data[vi]["tref"][-1]
        saw = data[vi]["sref"][-1]
        raw = (1 + saw * sBeta + taw * tAlpha) * rnil

        t_ice = plume["t_plu"][0, :]
        s_ice = plume["s_plu"][0, :]

        nans, i = nan_helper(s_ice)
        s_ice[nans] = np.interp(i(nans), i(~nans), s_ice[~nans])
        si_fil = uniform_filter1d(s_ice, size=20)

        t_f = lam1 * si_fil + lam2 + ice * lam3
        TF = t_ice - t_f

        melt = np.abs(SHIflx[vi]["fwfx"]) / 1000 * dx

        # entrainment
        rho_plu = (1 + (plume["s_plu"]) * sBeta + (plume["t_plu"]) * tAlpha) * rnil
        kappa_z = 2e-5
        kappa_x = 2.5e-1
        entrain = entraiment_coeff(
            plume["u_plu"], rho_plu, raw, kappa_z=kappa_z, dx=dx, dz=dz
        )

        if "gd0" in path[vi]:
            sgd = int(path[vi][3:6])
            print("sgd = {} percent of control melt".format(sgd))
        else:
            sgd = 0
            print("no sgd")

        cmelt = np.nancumsum(melt)
        amelt = np.nanmean(melt)
        # safe data for fitting
        mdata["exp"].append(path[vi])
        mdata["T_AW"].append(taw)
        mdata["MeltFlux"].append(cmelt[flxi])
        mdata["AveMelt"].append(amelt)
        mdata["PlumeFlux"].append(np.nanmax(flx))
        mdata["TF"].append(np.nanmean(TF[0:flxi]))
        mdata["sgd"].append(sgd)
        mdata["Entrainment_u"].append(entrain["alpha"])
        mdata["Fe/Fd"].append(entrain["Fe"] / entrain["Fd"])

    mdata = pd.DataFrame(mdata)
    mdata.head()

    if to_file:
        mdata.to_csv("{}.csv".format(filename), index=False)

def extract_prdata(path, prx=21e3, to_file=False):

    global prdata
    coords = TM.coords
    z = coords[0]["z"]
    data = TM.data

    prdata = {"z": z}
    prdf = pd.DataFrame(prdata)
    print(prdf.head())
    for vi in range(np.shape(data)[0]):
        pri = np.min(np.where(coords[vi]["x"] >= prx)[0])
        tpr = TM.data[vi]["t_all"][vi, :, pri]
        spr = TM.data[vi]["s_all"][vi, :, pri]

        prdf["t_{}".format(path[vi])] = tpr
        prdf["s_{}".format(path[vi])] = spr

        print(prdf.head())

    if to_file:
        prdf.to_csv("profile_ts_{:.0f}km.csv".format(prx / 1e3), index=False)


import json
import nextcord
from cmds.ban import ban
from nextcord.ext import commands
from core.classes import Cog_Extension

class Ban_list(Cog_Extension):
    @commands.command()
    @commands.has_any_role(978680963099942912, 979385876209610752, 978956326359138314, 1070679396165373984, 1080095809175035984)    # 社長、工程師、管理員
    async def ban_list(self, ctx):
        with open('data/list.json', 'r', encoding = 'utf-8') as ban_l:
            banlast = json.load(ban_l)
        list_embed = nextcord.Embed(title = "ban人名單", color = 0xffe380)
        for i in banlast['ban']:
            u_name = self.bot.get_user(i)
            list_embed.add_field(name = u_name, value = i, inline = False)
        await ctx.send(embed = list_embed)
        print(f'-> List ban_list for {ctx.author}')

def setup(bot):
    bot.add_cog(Ban_list(bot))


#coding=utf-8
__author__ = 'wanglu'

import hashlib
import logging

from flask import Blueprint,request

from ..weixin import receive
from ..weixin import reply
import main.config.app_settings as conf

weixin_blueprint = Blueprint("weixin_blueprint",__name__)

logger = logging.getLogger(__name__)

@weixin_blueprint.route("/",methods=["GET","POST"])
def index():

    try:
        if request.method == "GET":
            signature = request.args["signature"]
            echostr = request.args["echostr"]
            timestamp = request.args["timestamp"]
            nonce = request.args["nonce"]

            token = conf.APP_TOKEN

            list = [token,timestamp,nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            print ("handle/GET func: hashcode, signature: ", hashcode, signature)

            if hashcode == signature:
                return echostr
            else:
                return ""

        if request.method == "POST":
            webData = request.data
            logger.info("Handle Post webdata is: %s" % webData)   #后台打日志
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg, receive.Msg):
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                if  recMsg.MsgType == 'text':
                    if recMsg.Content == "test":
                        content = "test"
                    elif recMsg.Content == "baidu":
                        content = "test http://www.baidu.com"
                    else:
                        content = "test"
                    replyMsg = reply.TextMsg(toUser, fromUser, content)
                    return replyMsg.send()
                if recMsg.MsgType == 'image':
                    mediaId = recMsg.MediaId
                    replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                    return replyMsg.send()
                else:
                    return reply.Msg().send()
            elif isinstance(recMsg,receive.Event):
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                if recMsg.Event == "VIEW":
                    content = "Menu Event View"
                    replyMsg = reply.TextMsg(toUser,fromUser,content)
                    return replyMsg.send()
            else:
                logger.info("暂且不处理")
                return "success"
    except Exception as err:
        return "error"


from rapid_api import city_founding, create_hotel_message
from keyboards.inline.buttons import city_markup, quantity_hotels_markup, \
    photo_y_n_markup, quantity_photo_markup
from loader import bot
from states.state_for_lowprice import UserInfoState
from loguru import logger
from datetime import date
from telegram_bot_calendar import DetailedTelegramCalendar, LSTEP

@bot.message_handler(commands=['low_price', 'high_price', 'bestdeal'])
@logger.catch
def start(message):
    bot.set_state(message.from_user.id, UserInfoState.command, message.chat.id)

    with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
        data['command'] = message.text[1:]

    bot.send_message(message.chat.id, '🗺В какой город направляетесь?')
    bot.set_state(message.from_user.id, UserInfoState.city, message.chat.id)

@bot.message_handler(state=UserInfoState.city)
@logger.catch
def city(message):
    # список районов города

    cities_list = city_founding(message.text)

    if cities_list is None:
        bot.send_message(message.chat.id, 'Извините, не могу найти такой город(( '
                                          'Пожалуйста, проверьте правильность написания города')
    else:
        bot.send_message(message.chat.id, '🏙Уточните, пожалуйста, район города:',
                         reply_markup=city_markup(cities_list))
        # bot.set_state(message.from_user.id, UserInfoState.quantity_hotels, message.chat.id)

        with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
            data['city'] = message.text
            logger.info('city={text}'.format(text=message.text))

@bot.callback_query_handler(func=lambda call: call.data.endswith('_1'))
@logger.catch
def city_area(call):
    # сохраняет id района города
    # календарь

    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        data['city_area_id'] = call.data[:-2]

    bot.delete_message(call.message.chat.id, call.message.message_id)
    calendar, step = DetailedTelegramCalendar(calendar_id='in',
                                              min_date=date.today(),
                                              max_date=date(2024, 10, 21)).build()

    ru_steps = {'y': 'год', 'm': 'месяц', 'd': 'день'}
    bot.send_message(call.message.chat.id, f'🗓Выберите дату заезда:\n{ru_steps[step]}',
                     reply_markup=calendar)

@bot.callback_query_handler(func=DetailedTelegramCalendar.func(calendar_id='in'))
@logger.catch
def call_back_check_in(call):
    result, key, step = DetailedTelegramCalendar(
        calendar_id='in',
        locale='ru',
        min_date=date.today(),
        max_date=date(2024, 3, 31)
    ).process(call.data)

    ru_steps = {'y': 'год', 'm': 'месяц', 'd': 'день'}

    if not result and key:
        bot.edit_message_text(f"Выберите: {ru_steps[step]}",
                              chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              reply_markup=key)
    elif result:
        bot.edit_message_text(f"🗓Дата заезда: {result}",
                              call.message.chat.id,
                              call.message.message_id)
        with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
            data['check_in'] = result

        calendar, step = DetailedTelegramCalendar(
            calendar_id='out',
            min_date=date.today(),
            max_date=date(2024, 3, 31)
        ).build()

        bot.send_message(call.message.chat.id, f'🗓Выберите дату выезда:\n{ru_steps[step]}',
                         reply_markup=calendar)

@bot.callback_query_handler(func=DetailedTelegramCalendar.func(calendar_id='out'))
@logger.catch
def call_back_check_out(call):
    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        result, key, step = DetailedTelegramCalendar(
            calendar_id='out',
            locale='ru',
            min_date=data['check_in'],
            max_date=date(2024, 3, 31)).process(call_data=call.data)

    if not result and key:
        ru_steps = {'y': 'год', 'm': 'месяц', 'd': 'день'}
        bot.edit_message_text(f"Выберите {ru_steps[step]}",
                              chat_id=call.message.chat.id,
                              message_id=call.message.message_id,
                              reply_markup=key)
    elif result:
        bot.edit_message_text(f"🗓Дата выезда: {result}",
                              call.message.chat.id,
                              call.message.message_id)

        with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
            data['check_out'] = result

            if data['command'] == 'bestdeal':
                bot.send_message(call.message.chat.id, '💲Введите минимальную стоимость отеля за ночь:')
                bot.set_state(call.from_user.id, UserInfoState.min_price, call.message.chat.id)
            else:
                bot.send_message(call.message.chat.id, 'Сколько отелей показать?',
                                 reply_markup=quantity_hotels_markup())
                # bot.set_state(call.message.from_user.id, UserInfoState.photo_y_n, call.message.chat.id)

@bot.callback_query_handler(func=lambda call: call.data.endswith('_2'))
@logger.catch
def photo_y_n(call):
    # сохраняет количество отелей
    # фото отелей

    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        data['quantity_hotels'] = int(call.data[:-2])

    bot.delete_message(call.message.chat.id, call.message.message_id)
    bot.send_message(call.message.chat.id, 'Показать фото отелей?',
                     reply_markup=photo_y_n_markup())
    # bot.set_state(call.message.from_user.id, UserInfoState.quantity_photo, call.message.chat.id)

@bot.callback_query_handler(func=lambda call: call.data.endswith('_3'))
@logger.catch
def quantity_photo(call):
    # если да - запрашивает количество фото
    # если нет - список отелей

    bot.delete_message(call.message.chat.id, call.message.message_id)
    if call.data[:-2] == 'Да':
        bot.send_message(call.message.chat.id, 'Сколько фото показать?',
                         reply_markup=quantity_photo_markup())
        # bot.set_state(call.message.from_user.id, UserInfoState.hotels, call.message.chat.id)
    else:
        with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
            days = (data['check_out'] - data['check_in']).days
            create_hotel_message(bot_data=data,
                                 days_count=days,
                                 user_id=call.from_user.id)

@bot.callback_query_handler(func=lambda call: call.data.endswith('_4'))
@logger.catch
def hotels(call):
    # сохраняет количество фото
    # список отелей

    with bot.retrieve_data(call.from_user.id, call.message.chat.id) as data:
        data['quantity_photo'] = int(call.data[:-2])

        bot.delete_message(call.message.chat.id, call.message.message_id)
        days = (data['check_out'] - data['check_in']).days
        create_hotel_message(bot_data=data,
                             days_count=days,
                             user_id=call.from_user.id,
                             photo_quantity=data['quantity_photo'])


import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font
from typing import Dict, List
import logging
from controllers.battle_summary_controller import BattleSummaryController, MoveRenderInfo

from gui import custom_components
from gui.popups.battle_config_popup import BattleConfigWindow
from pkmn import damage_calc, universal_data_objects
from routing import full_route_state
from routing import route_events
from utils.config_manager import config
from utils.constants import const
from pkmn.gen_factory import current_gen_info

logger = logging.getLogger(__name__)

class BattleSummary(ttk.Frame):
    def __init__(self, controller:BattleSummaryController, *args, **kwargs):
        self._controller = controller
        super().__init__(*args, **kwargs)

        self.columnconfigure(0, weight=1)

        # these are matched lists, with the solo mon being updated for each enemy pkmn, in case of level-ups
        self._enemy_pkmn:List[universal_data_objects.EnemyPkmn] = None
        self._solo_pkmn:List[universal_data_objects.EnemyPkmn] = None
        self._source_state:full_route_state.RouteState = None
        self._source_event_group:route_events.EventGroup = None
        self._player_stage_modifiers:universal_data_objects.StageModifiers = universal_data_objects.StageModifiers()
        self._enemy_stage_modifiers:universal_data_objects.StageModifiers = universal_data_objects.StageModifiers()
        self._mimic_selection = ""
        self._custom_move_data = None

        self._top_bar = ttk.Frame(self)
        self._top_bar.grid(row=0, column=0, sticky=tk.EW)

        self._setup_half = ttk.Frame(self._top_bar)
        self._setup_half.grid(row=0, column=0, sticky=tk.EW)
        self._weather_half = ttk.Frame(self._top_bar)
        self._weather_half.grid(row=0, column=1, sticky=tk.EW)

        self._top_bar.columnconfigure(0, weight=1)

        self.setup_moves = SetupMovesSummary(self._setup_half, callback=self._player_setup_move_callback)
        self.setup_moves.grid(row=0, column=0, sticky=tk.EW, pady=(0, 2))

        self.enemy_setup_moves = SetupMovesSummary(self._setup_half, callback=self._enemy_setup_move_callback, is_player=False)
        self.enemy_setup_moves.grid(row=1, column=0, sticky=tk.EW)

        self.config_button = custom_components.SimpleButton(self._weather_half, text="Configure/Help", command=self._launch_config_popup)
        self.config_button.grid(row=0, column=0, sticky=tk.EW, padx=10, pady=(0, 2))

        self.weather_status = WeatherSummary(self._weather_half, callback=self._weather_callback)
        self.weather_status.grid(row=0, column=1, sticky=tk.EW, padx=2, pady=(0, 2))

        self.candy_summary = PrefightCandySummary(self._weather_half, callback=self._candy_callback)
        self.candy_summary.grid(row=1, column=1, sticky=tk.EW, padx=2, pady=(0, 2))

        self._mon_pairs:List[MonPairSummary] = []

        for idx in range(6):
            self._mon_pairs.append(MonPairSummary(self._controller, idx, self))

        self.error_message = tk.Label(self, text="Select a battle to see damage calculations")
        self.should_render = False
        self.bind(self._controller.register_refresh(self), self._on_full_refresh)
        self.set_team(None)

    def configure_weather(self, possible_weather_vals):
        self.weather_status.configure_weather(possible_weather_vals)

    def configure_setup_moves(self, possible_setup_moves):
        self.setup_moves.configure_moves(possible_setup_moves)
        self.enemy_setup_moves.configure_moves(possible_setup_moves)

    def hide_contents(self):
        self.should_render = False
        for cur_mon_pair in self._mon_pairs:
            cur_mon_pair.grid_forget()

    def show_contents(self):
        self.should_render = True
        self._on_full_refresh()

    def _launch_config_popup(self, *args, **kwargs):
        BattleConfigWindow(self.winfo_toplevel(), battle_controller=self._controller)

    def _weather_callback(self, *args, **kwargs):
        self._controller.update_weather(self.weather_status.get_weather())

    def _candy_callback(self, *args, **kwargs):
        self._controller.update_prefight_candies(self.candy_summary.get_prefight_candy_count())

    def _player_setup_move_callback(self, *args, **kwargs):
        self._controller.update_player_setup_moves(self.setup_moves._move_list.copy())

    def _enemy_setup_move_callback(self, *args, **kwargs):
        self._controller.update_enemy_setup_moves(self.enemy_setup_moves._move_list.copy())

    def set_team(
        self,
        enemy_pkmn:List[universal_data_objects.EnemyPkmn],
        cur_state:full_route_state.RouteState=None,
        event_group:route_events.EventGroup=None,
    ):
        if event_group is not None:
            self._controller.load_from_event(event_group)
        elif cur_state is not None and enemy_pkmn is not None:
            self._controller.load_from_state(cur_state, enemy_pkmn)
        else:
            self._controller.load_empty()

    def _on_full_refresh(self, *args, **kwargs):
        if not self.should_render:
            return

        self.candy_summary.set_candy_count(self._controller.get_prefight_candy_count())
        if not self._controller.can_support_prefight_candies():
            self.candy_summary.disable()
        else:
            self.candy_summary.enable()
        self.weather_status.set_weather(self._controller.get_weather())
        self.setup_moves.set_move_list(self._controller.get_player_setup_moves())
        self.enemy_setup_moves.set_move_list(self._controller.get_enemy_setup_moves())
        for idx in range(6):
            player_info = self._controller.get_pkmn_info(idx, True)
            enemy_info = self._controller.get_pkmn_info(idx, False)

            if player_info is None and enemy_info is None:
                self._mon_pairs[idx].grid_forget()
                if idx == 0:
                    pass

            else:
                self._mon_pairs[idx].grid(row=idx + 2, column=0, sticky=tk.EW)
                self._mon_pairs[idx].update_rendering()

class SetupMovesSummary(ttk.Frame):
    def __init__(self, *args, callback=None, is_player=True, **kwargs):
        super().__init__(*args, **kwargs)

        self._callback = callback
        self._move_list = []

        self.reset_button = custom_components.SimpleButton(self, text="Reset Setup", command=self._reset)
        self.reset_button.grid(row=0, column=0, padx=2)

        self.setup_label = ttk.Label(self, text="Move:")
        self.setup_label.grid(row=0, column=1, padx=2)

        self.setup_moves = custom_components.SimpleOptionMenu(self, ["N/A"])
        self.setup_moves.grid(row=0, column=2, padx=2)

        self.add_button = custom_components.SimpleButton(self, text="Apply Move", command=self._add_setup_move)
        self.add_button.grid(row=0, column=3, padx=2)

        if is_player:
            label_text = "Player Setup:"
        else:
            label_text = "Enemy Setup:"
        self.extra_label = ttk.Label(self, text=label_text)
        self.extra_label.grid(row=0, column=4, padx=2)

        self.move_list_label = ttk.Label(self)
        self.move_list_label.grid(row=0, column=5, padx=2)

    def _reset(self, *args, **kwargs):
        self._move_list = []
        self._move_list_updated()

    def _add_setup_move(self, *args, **kwargs):
        self._move_list.append(self.setup_moves.get())
        self._move_list_updated()

    def configure_moves(self, new_moves):
        self.setup_moves.new_values(new_moves)

    def set_move_list(self, new_moves, trigger_update=False):
        self._move_list = new_moves
        self._move_list_updated(trigger_update=trigger_update)

    def get_stage_modifiers(self):
        result = universal_data_objects.StageModifiers()

        for cur_move in self._move_list:
            result = result.apply_stat_mod(current_gen_info().move_db().get_stat_mod(cur_move))

        return result

    def _move_list_updated(self, trigger_update=True):
        to_display = ", ".join(self._move_list)
        if not to_display:
            to_display = "None"

        self.move_list_label.configure(text=to_display)
        if self._callback is not None and trigger_update:
            self._callback()

class WeatherSummary(ttk.Frame):
    def __init__(self, *args, callback=None, **kwargs):
        super().__init__(*args, **kwargs)
        self._outer_callback = callback
        self._loading = False

        self.label = ttk.Label(self, text="Weather:")
        self.label.grid(row=0, column=0, padx=2)

        self.weather_dropdown = custom_components.SimpleOptionMenu(self, [const.WEATHER_NONE], callback=self._callback)
        self.weather_dropdown.grid(row=0, column=1, padx=2)

    def _callback(self, *args, **kwargs):
        if self._loading:
            return

        if self._outer_callback is not None:
            self._outer_callback()

    def set_weather(self, new_weather):
        self._loading = True
        self.weather_dropdown.set(new_weather)
        self._loading = False

    def configure_weather(self, weather_vals):
        self.weather_dropdown.new_values(weather_vals)

    def get_weather(self):
        return self.weather_dropdown.get()

class PrefightCandySummary(ttk.Frame):
    def __init__(self, *args, callback=None, **kwargs):
        super().__init__(*args, **kwargs)
        self._outer_callback = callback
        self._loading = False

        self.label = ttk.Label(self, text="Prefight Candies:")
        self.label.grid(row=0, column=0, padx=2)

        self.candy_count = custom_components.AmountEntry(self, min_val=0, init_val=0, callback=self._callback, width=5)
        self.candy_count.grid(row=0, column=1, padx=2)

    def _callback(self, *args, **kwargs):
        if self._loading:
            return

        if self._outer_callback is not None:
            self._outer_callback()

    def set_candy_count(self, new_amount):
        self._loading = True
        self.candy_count.set(new_amount)
        self._loading = False

    def get_prefight_candy_count(self):
        try:
            return int(self.candy_count.get())
        except Exception:
            return 0

    def disable(self):
        self.candy_count.disable()

    def enable(self):
        self.candy_count.enable()

class MonPairSummary(ttk.Frame):
    def __init__(self, controller:BattleSummaryController, mon_idx, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._controller = controller
        self._mon_idx = mon_idx

        bold_font = tkinter.font.nametofont("TkDefaultFont").copy()
        bold_font.configure(weight="bold")

        self.left_mon_label_frame = ttk.Frame(self, style="Header.TFrame")
        self.left_mon_label_frame.grid(row=0, column=0, columnspan=4, sticky=tk.EW, padx=2, pady=2)

        self.left_label = ttk.Label(self.left_mon_label_frame, text="", style="Header.TLabel")
        self.left_label.grid(row=0, column=1)

        self.left_mon_label_frame.columnconfigure(0, weight=1, uniform="left_col_group")
        self.left_mon_label_frame.columnconfigure(2, weight=1, uniform="left_col_group")

        self.divider = ttk.Frame(self, width=4, style="Divider.TFrame")
        self.divider.grid(row=0, column=4, rowspan=2, sticky=tk.NS)
        self.divider.grid_propagate(0)

        self.right_mon_label_frame = ttk.Frame(self, style="Header.TFrame")
        self.right_mon_label_frame.grid(row=0, column=5, columnspan=4, sticky=tk.EW, padx=2, pady=2)

        self.right_label = ttk.Label(self.right_mon_label_frame, text="", style="Header.TLabel")
        self.right_label.grid(row=0, column=1)

        self.right_mon_label_frame.columnconfigure(0, weight=1, uniform="right_col_group")
        self.right_mon_label_frame.columnconfigure(2, weight=1, uniform="right_col_group")

        self.columnconfigure(0, weight=1, uniform="label_group")
        self.columnconfigure(1, weight=1, uniform="label_group")

        self.columnconfigure(0, weight=1, uniform="move_group")
        self.columnconfigure(1, weight=1, uniform="move_group")
        self.columnconfigure(2, weight=1, uniform="move_group")
        self.columnconfigure(3, weight=1, uniform="move_group")

        self.columnconfigure(5, weight=1, uniform="move_group")
        self.columnconfigure(6, weight=1, uniform="move_group")
        self.columnconfigure(7, weight=1, uniform="move_group")
        self.columnconfigure(8, weight=1, uniform="move_group")

        self.move_list:List[DamageSummary] = []
        for cur_idx in range(8):
            self.move_list.append(DamageSummary(self._controller, self._mon_idx, cur_idx % 4, cur_idx < 4, self))

    def update_rendering(self):
        player_rendering_info = self._controller.get_pkmn_info(self._mon_idx, True)
        enemy_rendering_info = self._controller.get_pkmn_info(self._mon_idx, False)

        self.left_label.configure(text=f"{player_rendering_info}")
        self.right_label.configure(text=f"{enemy_rendering_info}")

        for cur_idx, cur_move in enumerate(self.move_list):
            column_idx = cur_idx
            if column_idx >= 4:
                column_idx += 1

            if self._controller.get_move_info(cur_move._mon_idx, cur_move._move_idx, cur_move._is_player_mon) is not None:
                cur_move.grid(row=1, column=column_idx, sticky=tk.NSEW)
            else:
                cur_move.grid_forget()

            cur_move.update_rendering()

class DamageSummary(ttk.Frame):
    def __init__(self, controller:BattleSummaryController, mon_idx, move_idx, is_player_mon, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._controller = controller
        self._mon_idx = mon_idx
        self._move_idx = move_idx
        self._is_player_mon = is_player_mon
        self._move_name = None
        self._is_loading = False

        self.columnconfigure(0, weight=1)

        self.padx = 2
        self.pady = 0
        self.row_idx = 0

        self.header = ttk.Frame(self, style="Primary.TFrame")
        self.header.grid(row=self.row_idx, column=0, sticky=tk.NSEW, padx=self.padx, pady=self.pady)
        self.header.columnconfigure(0, weight=1)
        self.row_idx += 1

        self.move_name_label = ttk.Label(self.header, style="BattleMovePrimary.TLabel")
        self.custom_data_dropdown = custom_components.SimpleOptionMenu(self.header, [""], callback=self._custom_data_callback, width=14)

        self.range_frame = ttk.Frame(self, style="Contrast.TFrame")
        self.range_frame.grid(row=self.row_idx, column=0, sticky=tk.NSEW, padx=self.padx, pady=self.pady)
        self.range_frame.columnconfigure(0, weight=1)
        self.row_idx += 1

        self.damage_range = ttk.Label(self.range_frame, style="Contrast.TLabel")
        self.damage_range.grid(row=0, column=0, sticky=tk.W)
        self.pct_damage_range = ttk.Label(self.range_frame, style="Contrast.TLabel")
        self.pct_damage_range.grid(row=0, column=1, sticky=tk.E)
        self.crit_damage_range = ttk.Label(self.range_frame, style="Contrast.TLabel")
        self.crit_damage_range.grid(row=1, column=0, sticky=tk.W)
        self.crit_pct_damage_range = ttk.Label(self.range_frame, style="Contrast.TLabel")
        self.crit_pct_damage_range.grid(row=1, column=1, sticky=tk.E)

        self.kill_frame = ttk.Frame(self, style="Secondary.TFrame")
        self.kill_frame.grid(row=self.row_idx, column=0, sticky=tk.NSEW, padx=self.padx, pady=self.pady)
        self.rowconfigure(self.row_idx, weight=1)
        self.row_idx += 1

        self.num_to_kill = ttk.Label(self.kill_frame, justify=tk.LEFT, style="Secondary.TLabel")
        self.num_to_kill.grid(row=0, column=0, sticky=tk.NSEW)

    def flag_as_best_move(self):
        if self._is_player_mon:
            style = "Success"
        else:
            style = "Failure"

        self.kill_frame.configure(style=f"{style}.TFrame")
        self.num_to_kill.configure(style=f"{style}.TLabel")

    def unflag_as_best_move(self):
        self.kill_frame.configure(style="Secondary.TFrame")
        self.num_to_kill.configure(style="Secondary.TLabel")

    def _custom_data_callback(self, *args, **kwargs):
        if self._is_loading:
            return
        if self._move_name == const.MIMIC_MOVE_NAME:
            self._controller.update_mimic_selection(self.custom_data_dropdown.get())
        else:
            self._controller.update_custom_move_data(self._mon_idx, self._move_idx, self._is_player_mon, self.custom_data_dropdown.get())

    @staticmethod
    def format_message(kill_info):
        kill_pct = kill_info[1]
        if kill_pct == -1:
            if config.do_ignore_accuracy():
                return f"{kill_info[0]}-hit kill: 100 %"
            else:
                return f"{kill_info[0]}-hit kill, IGNORING ACC"
        if config.do_ignore_accuracy():
            return f"{kill_info[0]}-hit kill: {kill_pct:.2f} %"
        return f"{kill_info[0]}-turn kill: {kill_pct:.2f} %"

    def update_rendering(self):
        move = self._controller.get_move_info(self._mon_idx, self._move_idx, self._is_player_mon)
        self._move_name = None if move is None else move.name

        self._is_loading = True
        if move is None or not move.is_best_move:
            self.unflag_as_best_move()
        else:
            self.flag_as_best_move()

        custom_data_options = None
        custom_data_selection = None
        if move is not None:
            custom_data_options = move.custom_data_options
            custom_data_selection = move.custom_data_selection
        if self._move_name == const.MIMIC_MOVE_NAME:
            custom_data_options = move.mimic_options
            custom_data_selection = move.mimic_data

        if custom_data_options:
            self.move_name_label.grid_forget()
            self.move_name_label.grid(row=0, column=0)
            self.custom_data_dropdown.grid(row=0, column=1)
            self.custom_data_dropdown.new_values(custom_data_options, default_val=custom_data_selection)
        else:
            self.move_name_label.grid_forget()
            self.move_name_label.grid(row=0, column=0, columnspan=2)
            self.custom_data_dropdown.grid_forget()

        if move is None:
            self.move_name_label.configure(text="")
            self.damage_range.configure(text="")
            self.pct_damage_range.configure(text="")
            self.crit_damage_range.configure(text="")
            self.crit_pct_damage_range.configure(text="")
        else:
            self.move_name_label.configure(text=f"{move.name}")
            if move.damage_ranges is None:
                self.damage_range.configure(text="")
                self.pct_damage_range.configure(text="")
                self.crit_damage_range.configure(text="")
                self.crit_pct_damage_range.configure(text="")

            else:
                self.damage_range.configure(text=f"{move.damage_ranges.min_damage} - {move.damage_ranges.max_damage}")
                pct_min_damage = f"{move.damage_ranges.min_damage / move.defending_mon_hp * 100:.2f}%"
                pct_max_damage = f"{move.damage_ranges.max_damage / move.defending_mon_hp * 100:.2f}%"
                self.pct_damage_range.configure(text=f"{pct_min_damage} - {pct_max_damage}")

                self.crit_damage_range.configure(text=f"{move.crit_damage_ranges.min_damage} - {move.crit_damage_ranges.max_damage}")
                crit_pct_min_damage = f"{move.crit_damage_ranges.min_damage / move.defending_mon_hp * 100:.2f}%"
                crit_pct_max_damage = f"{move.crit_damage_ranges.max_damage / move.defending_mon_hp * 100:.2f}%"
                self.crit_pct_damage_range.configure(text=f"{crit_pct_min_damage} - {crit_pct_max_damage}")

            max_num_messages = 3
            kill_ranges = move.kill_ranges
            if len(kill_ranges) > max_num_messages:
                kill_ranges = kill_ranges[:max_num_messages - 1] + [kill_ranges[-1]]

            kill_ranges = [self.format_message(x) for x in kill_ranges]
            self.num_to_kill.configure(text="\n".join(kill_ranges))

        self._is_loading = False


import argparse
import os
import os.path as osp
import time
import json

import numpy as np
import torch
import torch.nn as nn
import torch.optim

import models
import ebms
from ebms import ActRateTracker
from datasets import load_dataset, get_num_classes
from tools.penalize_transformation import validate, train, plot_curve, save_stats, eval_acc_loss
from tools.utils import sample_input
from metrics.calc_info import calc_information_for_epoch_KDE
from tools.lib import update_lr, save_obj, set_seed

def parse_args():
    parser = argparse.ArgumentParser(description='Penalize the transformation complexity')
    parser.add_argument("--data-root", type=str, default="./data",
                        help="the root folder of datasets")
    parser.add_argument("--dataset", type=str, default="cifar10",
                        help="the name of the dataset")
    parser.add_argument('--arch', type=str, default='resmlp10',
                        help='model architecture')

    parser.add_argument('--model-lr', default=1e-2, type=float,
                        metavar='LR', help='initial learning rate')
    parser.add_argument('--model-lr-decay', default=2, type=float)
    parser.add_argument('--epochs', default=201, type=int, metavar='EPOCHS',
                        help='number of total epochs to run')
    parser.add_argument('--batch-size', default=128, type=int,
                        metavar='BS', help='mini-batch size (default: 128)')
    parser.add_argument('--default_train', action="store_true",
                        help='train without complexity loss')

    parser.add_argument("--penalize-layers", type=str, default="layers.5.act,layers.6.act,layers.7.act,layers.8.act",
                        help="which layers to penalize the transformation complexity")
    parser.add_argument("--energy-functions", type=str, default="E_3072d,E_3072d,E_3072d,E_3072d",
                        help="configuration of the energy function of each layer")
    parser.add_argument("--n-channels", type=str, default="3072,3072,3072,3072",
                        help="# of channels in gating layers")

    parser.add_argument('--ebm-lr', default=1e-4, type=float)
    parser.add_argument('--ebm-lr-decay', default=2, type=float)
    parser.add_argument('--l_step', default=5, type=int, metavar='L_STEP',
                        help='langevin step number')
    parser.add_argument('--tau', default=0.001, type=float, metavar='TAU',
                        help='tau is the step length in langevin step')
    parser.add_argument('--loss_lambda', default=-4.0, type=float, metavar='LAMBDA',
                        help='control the ratio between criterion loss and f function loss')
    parser.add_argument("--train-interval", type=int, default=10)

    parser.add_argument('--plot', action="store_true",
                        help='whether we should plot the loss function and train/test accuracy')
    parser.add_argument('--print-freq', '-p', default=50, type=int,
                        metavar='N', help='print every x batches (default: 50)')
    parser.add_argument("--save-folder", default="./saved-models")

    parser.add_argument("--gpu-id", type=int, default=0)
    parser.add_argument("--seed", type=int, default=1234)

    parser.add_argument("--evaluate", action="store_true")
    parser.add_argument("--num-per-class", type=int, default=200)

    args = parser.parse_args()
    print()
    print(args)
    print()
    return args

def load_model(args):
    model = models.__dict__[args.arch](activation_type="swish").to(args.gpu_id)
    optimizer = torch.optim.SGD(model.parameters(), args.model_lr, momentum=0.9, weight_decay=5e-4)
    if args.default_train:
        return model, [], [], optimizer, []

    model.set_store_soft_gating_states(save_layers=args.penalize_layers)
    f_list = [ebms.__dict__[e_func]().to(args.gpu_id) for e_func in args.energy_functions.split(",")]
    q_list = [ActRateTracker(n_channels=int(n_c)).to(args.gpu_id) for n_c in args.n_channels.split(",")]
    f_optimizer_list = [
        torch.optim.SGD(f_list[i].parameters(), args.ebm_lr, momentum=0.9, weight_decay=5e-4)
        for i in range(len(f_list))
    ]
    return model, f_list, q_list, optimizer, f_optimizer_list

def setup(args):
    seed = args.seed
    set_seed(seed)

    if not args.default_train:
        args.save_folder = osp.join(args.save_folder, f"dataset={args.dataset}_model={args.arch}",
                                    f"M__bs={args.batch_size}_model-lr={args.model_lr}_epochs={args.epochs}_"
                                    f"E__l={args.l_step}_tau={args.tau}_lambda={args.loss_lambda}"
                                    f"_interval={args.train_interval}_seed={args.seed}")
    else:
        args.save_folder = osp.join(args.save_folder, f"dataset={args.dataset}_model={args.arch}",
                                    f"M__bs={args.batch_size}_model-lr={args.model_lr}"
                                    f"_epochs={args.epochs}_seed={args.seed}")

    if not args.evaluate:
        os.makedirs(args.save_folder, exist_ok=True)
        os.makedirs(osp.join(args.save_folder, "model"), exist_ok=True)
        os.makedirs(osp.join(args.save_folder, "curve"), exist_ok=True)

        with open(osp.join(args.save_folder, "hparams.json"), "w") as f:
            json.dump(vars(args), f, indent=4)
    else:
        args.model_path = osp.join(args.save_folder, "model", "model.pth")
        os.makedirs(osp.join(args.save_folder, "evaluate"), exist_ok=True)

        with open(osp.join(args.save_folder, "hparams_eval.json"), "w") as f:
            json.dump(vars(args), f, indent=4)

def main(args):

    setup(args)

    plot_dic = {
        "loss_label": [],
        "loss_compl": [],
        "loss_total": [],
        **{f"loss_compl_{i}": [] for i in range(len(args.penalize_layers.split(",")))},
        **{f"loss_f_{i}": [] for i in range(len(args.penalize_layers.split(",")))},
        **{f"p_{i}": [] for i in range(len(args.penalize_layers.split(",")))},
        "train_acc": [],
        "test_acc": []
    }

    model_lr_list = np.logspace(np.log10(args.model_lr), np.log10(args.model_lr) - args.model_lr_decay, args.epochs)
    f_lr_list = np.logspace(np.log10(args.ebm_lr), np.log10(args.ebm_lr) - args.ebm_lr_decay, args.epochs)

    train_loader, val_loader = load_dataset(dataset=args.dataset, data_root=args.data_root, batch_size=args.batch_size)
    model, f_list, q_list, optimizer, f_optimizer_list = load_model(args=args)
    assert len(f_list) == len(q_list)
    criterion = nn.CrossEntropyLoss()

    for epoch in range(args.epochs):
        # update learning rates
        update_lr(optimizer, model_lr_list[epoch])
        for ebm_id in range(len(f_list)):
            update_lr(f_optimizer_list[ebm_id], f_lr_list[epoch])
        print('current lr {:.5e}'.format(optimizer.param_groups[0]['lr']))

        # train and evaluate the model
        train(args, train_loader, model, f_list, q_list, criterion, optimizer, f_optimizer_list, epoch, plot_dic)
        prec1 = validate(val_loader, model, criterion, print_freq=args.print_freq, device=args.gpu_id)

        plot_dic["test_acc"].append(prec1)

        if args.plot or True:
            plot_curve(plot_dict=plot_dic, save_path=osp.join(args.save_folder, "curve", "curve.png"))

        save_obj(plot_dic, osp.join(args.save_folder, "curve", "data.bin"))

    torch.save(model.cpu().state_dict(), os.path.join(args.save_folder, "model", "model.pth"))
    for ebm_id in range(len(f_list)):
        torch.save(f_list[ebm_id].cpu().state_dict(), os.path.join(args.save_folder, "model", f"f{ebm_id}.pth"))
        torch.save(q_list[ebm_id].cpu().state_dict(), os.path.join(args.save_folder, "model", f"q{ebm_id}.pth"))

    save_stats(plot_dict=plot_dic, save_path=osp.join(args.save_folder, "model", "stats.txt"))

def main_evaluate(args):

    setup(args)

    # load dataset and model
    train_loader, val_loader = load_dataset(dataset=args.dataset, data_root=args.data_root,
                                            batch_size=args.batch_size, shuffle_train=False, data_aug_train=False)
    train_loader_sample, _ = load_dataset(dataset=args.dataset, data_root=args.data_root,
                                          batch_size=1, shuffle_train=False, data_aug_train=False)
    model, _, _, _, _ = load_model(args=args)
    model.load_state_dict(torch.load(args.model_path, map_location=torch.device(f"cuda:{args.gpu_id}")))
    model.eval()
    print(f"Model loaded from {args.model_path}")

    # sample some input images for calculating transformation complexity (See Appendix G.1)
    num_classes = get_num_classes(args.dataset)
    input, label = sample_input(num_classes=num_classes, num_per_class=args.num_per_class,
                                data_loader=train_loader_sample, device=args.gpu_id)

    # generating the gating states
    with torch.no_grad():
        model(input)
    num_samples = input.shape[0]
    sigma = [model.sigma_list[layer_id].reshape(num_samples, -1) for layer_id in model.sigma_list.keys()]
    sigma = torch.cat(sigma, dim=1)
    for t in model.sigma_list.values():
        if len(t.shape) == 4:
            sigma = sigma.unsqueeze(2).unsqueeze(3)
            break
    sigma_label = [sigma, label]

    # calculate transformation complexity
    ret_dict = {}
    network_info = calc_information_for_epoch_KDE(sigma_label, device=args.gpu_id)
    HS = network_info[0]['local_IXT']  # H(\Sigma)
    ISY = network_info[0]['local_ITY']  # I(X;\Sigma;Y)
    ret_dict["HS"] = HS.item()
    ret_dict["ISY"] = ISY.item()

    # calculate loss and accuracy
    _, train_loss = eval_acc_loss(model, train_loader, device=args.gpu_id)
    test_acc, test_loss = eval_acc_loss(model, val_loader, device=args.gpu_id)
    ret_dict["train_loss"] = train_loss
    ret_dict["test_loss"] = test_loss
    ret_dict["test_acc"] = test_acc

    save_obj(ret_dict, osp.join(args.save_folder, "evaluate", "info.bin"))
    with open(osp.join(args.save_folder, "evaluate", "info.json"), "w") as f:
        json.dump(ret_dict, f, indent=4)

    return ret_dict

if __name__ == '__main__':
    args = parse_args()
    if not args.evaluate:
        main(args)
    else:
        main_evaluate(args)


from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
from absl import app, flags

from modules.models import PPG2ECG

flags.DEFINE_string("weights", "", "model weights for inferencing")
flags.DEFINE_string("input", "example/PPG.npy", "input data (numpy array)")
FLAGS = flags.FLAGS

def main(argv):
    # prepare the parameters
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # prepare the model
    model = PPG2ECG(
        input_size=200,
        use_stn=True,
        use_attention=True).to(device)

    # load the model state
    model.load_state_dict(torch.load(Path(FLAGS.weights))["net"])
    model.eval()

    # prepare the inference data (PPG data)
    ppg = np.load(Path(FLAGS.input))
    print("ppg shape: {}".format(ppg.shape))

    # run through the data
    idx = 0
    step = 100
    ecg = []
    while True:
        # out of range for ppg data
        if (idx+200) > len(ppg):
            break
        # preprocess the single data to match the input size
        input_data = ppg[idx:idx+200]

        # reshape the data to [1, 200]
        input_data = input_data.reshape((1, -1))

        # move ppg data to torch tensor and device
        input_data = torch.from_numpy(input_data).to(device).float()

        # inference
        # in torch, you need (batch, data) for forward
        # so you should unsqueeze the input data by unsqueeze(0)
        # now the input size should be [1, 1, 200]
        with torch.no_grad():
            output_data = model(input_data.unsqueeze(0))
            output_data = output_data["output"].cpu()
            ecg.append(output_data[0, 0])  # [1, 1, 200] -> [200,]
        idx += step

    # model performs better in middle [50:150] for whole output [0:200]
    # also we drop first 50 and last 50 for ppg to align the ppg and ecg
    ecg = [e[50:150] for e in ecg]
    ppg = ppg[50:-50]

    # show the plot
    ecg = torch.cat(ecg)
    plt.plot(ppg, label="ppg")
    plt.plot(ecg, label="ecg")
    plt.legend()
    plt.show()

if __name__ == "__main__":
    app.run(main)


"""
util.async_helpers - various utilities for asyncio functions and tasks.
"""

from functools import wraps
from typing import TypeVar, Callable, Awaitable, cast, Any

import asyncio

async def asyncio_yield() -> None:
    """
    Ensure that the current task yields to the event loop.

    The python async framework only switches between concurrently-running tasks when
    the currently-running task hits a leaf call that requires waiting for an event on
    the loop. That means that you can have a very long call of nice coroutines with
    async def and await call() that still effectively "block" other concurrent tasks
    from actually executing.

    There's also not really a nice way to yield to the event loop explicitly. The best
    way to do it is to drop in await asyncio.sleep(0), which will yield to the loop and
    let something else run.

    If you have an async call chain that is used in a tight loop and at no point contains
    an await() call that will yield the loop - this will be anything that
    - Involves touching a file descriptor that is registered with an asyncio protocol
    - Involves waiting for a Future
    - Involves waiting for another task
    - Involves specifically invoking an asyncio scheduling operation like gather()
    - Uses asyncio.sleep()

    You should drop an await asyncio_yield() at the most frequent leaf call to make sure
    that other tasks on the loop get a chance to run.
    """
    await asyncio.sleep(0)

Wrapped = TypeVar("Wrapped", bound=Callable[..., Awaitable[Any]])

def ensure_yield(async_def_func: Wrapped) -> Wrapped:
    """
    A decorator that makes sure that asyncio_yield() is called after the decorated async
    function finishes executing.
    """

    # _wrapper can be typed using ParamSpec https://docs.python.org/3/library/typing.html#typing.ParamSpec
    # when we
    # - bump to a mypy version that supports it (>0.930)
    # - either go to python 3.10 or bump typing_extensions to 4.2.0
    # Until then, this is a mess of opaque type vars and disabling internal checking because of their
    # opacity. The cast on line 58 should keep the external interface of the annotated function correct.
    @wraps(async_def_func)
    async def _wrapper(*args: Any, **kwargs: Any) -> Any:
        ret = await async_def_func(*args, **kwargs)
        await asyncio_yield()
        return ret

    return cast(Wrapped, _wrapper)


from datetime import datetime
from django.db.models import Q

def create_date_filter(query_params):
    start_date = query_params.get('start_date', None)
    end_date = query_params.get('end_date', None)

    _q = Q()

    if start_date:
        start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        _q &= Q(created_at__date__gte=start_date)
    if end_date:
        end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
        _q &= Q(created_at__date__lte=end_date)

    return _q


import random
import json
import torch
from Classes.Model import NeuralNet
from nltk_utils import bag_of_words, tokenize, stem

def main():

    # Set-up
    FILE = r'data\processed\model.pth'
    data = torch.load(FILE)

    input_size = data['input_size']
    hidden_size = data['hidden_size']
    output_size = data['output_size']
    all_words = data['all_words']
    tags = data['tags']
    model_state = data['model_state']

    with open(r'data\training_data\train.json') as f:
        intents = json.load(f)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    model = NeuralNet(input_size, hidden_size, output_size).to(device)
    model.load_state_dict(model_state)
    model.eval()

    botName = "Albert"
    print(f"{botName}> Hello, I am {botName}, let's talk fitness!")

    while True:
        sentence = input("You: ")
        if sentence == "quit":
            break

        sentence = tokenize(sentence)
        X = bag_of_words(sentence, all_words)
        X = X.reshape(1, X.shape[0])
        X = torch.from_numpy(X).to(device)

        output = model(X)
        _, predicted = torch.max(output, 1)
        print(predicted)
        tag = tags[predicted.item()]

        probs = torch.softmax(output, dim=1)
        prob = probs[0][predicted.item()] # type: ignore
        print(f"{botName}> {tag} ({prob:.2f})")

        # Confidence routing
        if prob.item() > 0.75:
            for intent in intents['intents']:
                if tag == intent['tag']:
                    print(f"{botName}> {random.choice(intent['responses'])}")
                    break
        else:
            print(f"{botName}> I'm sorry, I don't understand.")

    pass

if __name__ == "__main__":
    main()


"""Add settings table

Revision ID: c7dd6d36b41e
Revises: 68968c14ecde
Create Date: 2022-11-02 08:46:15.446878

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c7dd6d36b41e'
down_revision = '68968c14ecde'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('settings',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('lcd_brightness', sa.Integer(), nullable=True),
    sa.Column('wifi_enabled', sa.Boolean(), nullable=True),
    sa.Column('bluetooth_enabled', sa.Boolean(), nullable=True),
    sa.Column('lights_enabled', sa.Boolean(), nullable=True),
    sa.Column('upload_enabled', sa.Boolean(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('settings')
    # ### end Alembic commands ###


from P4 import P4,P4Exception
import config

p4 = P4()
p4.port = config.P4PORT
p4.user = config.P4USER

try:
  p4.connect()
  # p4 servers
  servers = p4.run( "servers" )
  for server in servers:
    for key in server:
      print(key, "=", server[key])
    print()
  p4.disconnect()
except P4Exception:
  for e in p4.errors:
      print(e)


#!/usr/bin/python3
# -*- coding: utf-8 -*-

import hmac
import sys
from base64 import b64decode
import random
from datetime import datetime
from binascii import unhexlify
import json

import requests
from Crypto.Cipher import AES
from Crypto.Hash import SHA256, SHA384, HMAC

from rngatherd.RandPi.pbkdf2 import PBKDF2

class RandPiClient(object):
    def __init__(self, url, secret, salt="pepper"):
        self.url = url
        self.SHARED_SECRET = secret
        self.SHARED_SALT = salt
        base_key = PBKDF2(self.SHARED_SECRET.encode('utf-8'), self.SHARED_SALT.encode('utf-8'),
                          iterations=32000, digestmodule=SHA384, macmodule=HMAC).read(64)
        self.ENCRYPTION_KEY = base_key[:32]
        self.HMAC_KEY = base_key[32:64]
        random.seed(datetime.now())

    @staticmethod
    def remove_pkcs7_padding(data):
        return data[:-data[-1]]

    def get_random(self, length=64):
        try:
            nonce = "".join([random.choice(list('0123456789abcdef')) for _ in range(2 * int((length + 1) / 2))])
            response = requests.post(self.url, data={
                'length': length,
                'nonce': nonce
            })
            response_data = response.json()
        except OSError:
            return b''
        if 'iv' not in response_data or 'encrypted_data' not in response_data or 'hmac' not in response_data:
            print("Response in a wrong format:\n" + json.dumps(response_data))
            return b''
        if hmac.new(self.HMAC_KEY,
                    b64decode(response_data['encrypted_data']) + unhexlify(nonce),
                    SHA256).digest() != b64decode(response_data['hmac']):
            print("Wrong signature!")
            return b''
        cipher = AES.new(self.ENCRYPTION_KEY, AES.MODE_CBC, b64decode(response_data['iv']))
        data = self.remove_pkcs7_padding(cipher.decrypt(b64decode(response_data['encrypted_data'])))
        return data

if __name__ == "__main__":
    DEMO_SHARED_SECRET = "Mein tolles langes Passwort, das total sicher ist. " + \
                         "Das sieht man an den Sonderzeichen wie / (Slash) oder $ (Dollar). " + \
                         "Außerdem enthält diese Passphrase einfach eine Menge Zeichen, " + \
                         "die ein Angreifer erst mal erraten muss."
    client = RandPiClient("http://127.0.0.1:8000/entropy/random", DEMO_SHARED_SECRET)
    sys.stdout.buffer.write(client.get_random())


import time
from typing import Dict

import jwt
from decouple import config

JWT_SECRET = config("secret")
JWT_ALGORITHM = config("algorithm")

def token_response(token: str):
    return {
        "access_token": token
    }

def signJWT(user: Dict) -> Dict[str, str]:
    payload = {
        "id": user["id"],
        "firstname": user["firstName"],
        "lastname": user["lastName"],
        "roles": user["roles"],
        "expires": time.time()+60000
    }
    token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM)
    print({**user, "access_token": token})
    return {**user, "access_token": token}

def decodeJWT(token: str) -> dict:
    try:
        decoded_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
        return decoded_token if decoded_token["expires"] >= time.time() else None
    except:
        return {}


import io
import os
import urllib

import requests
from PIL import Image
from telethon import events

HAREM = os.environ.get("HAREM", False)

opener = urllib.request.build_opener()
useragent = "Mozilla/5.0 (Linux; Android 9; SM-G960F Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36"
opener.addheaders = [("User-agent", useragent)]

if HAREM:

    @catub.on(events.NewMessage, outgoing=False, from_users=792028928)
    async def waifus_are_eternal(event):
        if event.is_private:
            return
        if event.media:
            borg = event.client
            if "Add" in event.raw_text:
                logger.info("OwO! A Waifu.")
                waifu_moment = io.BytesIO()
                await borg.download_media(event.media, waifu_moment)
                try:
                    image = Image.open(waifu_moment)
                except OSError:
                    return
                name = "waifu.png"
                image.save(name, "PNG")
                image.close()
                searchUrl = "https://www.google.com/searchbyimage/upload"
                file_img = {
                    "encoded_image": (name, open(name, "rb")),
                    "image_content": "",
                }
                response = requests.post(
                    searchUrl, files=file_img, allow_redirects=False
                )
                os.remove(name)
                if response.status_code == 400:
                    return
                fetchUrl = response.headers["Location"]
                match = await ParseSauce(fetchUrl + "&preferences?hl=en&fg=1#languages")
                guessp = match["best_guess"]
                if not guessp:
                    return
                guess = guessp.replace("Results for", "").replace(" ", "")
                await borg.send_message(event.chat_id, f"/protecc {guess}")


from __future__ import annotations

import os

from fastapi import FastAPI, status
from fastapi.requests import Request
from fastapi.responses import StreamingResponse

app = FastAPI()

def video_to_chunks(source: str, chunk_size: int, start: int, size: int) -> bytes:
    bytes_read = 0

    with open(source, mode="rb") as stream:
        stream.seek(start)

        while bytes_read < size:
            bytes_to_read = min(chunk_size, size - bytes_read)
            yield stream.read(bytes_to_read)
            bytes_read += bytes_to_read

@app.get("/video")
def stream_video(request: Request):
    chunk_size = 1024 * 1024
    range = request.headers.get("Range")
    start, end = range.replace("bytes=", "").split("-")
    start = int(start)
    end = int(end) if end else start + chunk_size
    source = "red-leaves-in-autumn.mp4"
    total_size = os.path.getsize(source)

    return StreamingResponse(
        content=video_to_chunks(
            source=source, chunk_size=chunk_size, start=start, size=total_size
        ),
        status_code=status.HTTP_206_PARTIAL_CONTENT,
        headers={
            "Accept-Ranges": "bytes",
            "Content-Length": total_size,
            "Content-Range": f"bytes {start}-{start + chunk_size}/{total_size}",
            "Content-Type": "video/mp4",
        },
    )


from django.conf.urls import patterns, include, url
from dogapp.views import search, listall, addNew

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Roverexample.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
	#url(r'^time/$', current_datetime),

    url(r'^admin/', include(admin.site.urls)),
	url(r'^search/$', search),
	url(r'^listall/$', listall),
	url(r'^addNew/$', addNew),
)


import cv2
import numpy as np
from config import *

def yolo_prediction(img):
    # Load Yolo
    net = cv2.dnn.readNet(YOLO_MODEL, YOLO_CONFIG)

    # Name custom object
    classes = ["ecg"]

    layer_names = net.getLayerNames()
    output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
    colors = np.random.uniform(0, 255, size=(len(classes), 3))

    coords = list()

    # img = cv2.resize(img, None, fx=0.4, fy=0.4)
    # img = cv2.resize(img, dsize=(1280,720))

    height, width, channels = img.shape

    # Detecting objects
    blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)

    net.setInput(blob)
    outs = net.forward(output_layers)

    # Showing informations on the screen
    class_ids = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.3:
                # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                # Rectangle coordinates
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                class_ids.append(class_id)

    # ? show predictions image
    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
    font = cv2.FONT_HERSHEY_PLAIN
    detection_image = img.copy()
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]

            coords.append([[x,abs(y)],[x + w, y + h]])

            label = str(classes[class_ids[i]])
            color = colors[class_ids[i]]
            cv2.rectangle(detection_image, (x, y), (x + w, y + h), color, 2)
            cv2.putText(detection_image, label, (x, y + 30), font, 3, color, 2)

    cv2.imshow("detection_image", detection_image)
    key = cv2.waitKey(0)

    cv2.destroyAllWindows()

    return coords, img

img_path = 'src/full/anormal-S.jpg'
img = cv2.imread(img_path)

coords, img = yolo_prediction(img)

for pts in coords:
    try:
        pt1, pt2 = pts
        print(pt1,pt2)
        cutted_image = img[pt1[1]:pt2[1], pt1[0]:pt2[0]]
        cv2.imshow('img',cutted_image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    except Exception as e:
        print(e)


from google.cloud import language

from google.cloud.language import enums
from google.cloud.language import types
import csv
# Instantiates a client
client = language.LanguageServiceClient()
# export GOOGLE_APPLICATION_CREDENTIALS="/Users/rustamquliyev/Documents/Optify/Optify_App/Django-backend/optify/optify-a768f9fd8bc9.json"

with open('schedule_data.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        text = row[0]
        document = types.Document(
        content=text,
        language="en",
        type=enums.Document.Type.PLAIN_TEXT)
        response = client.analyze_syntax(
            document=document
        )
        print(response)

    # Get the language of the text, which will be the same as
    # the language specified in the request or, if not specified,
    # the automatically-detected language.

#Entity Analyss

# Detects the sentiment of the text
# sentiment = client.analyze_sentiment(document=document).document_sentiment

# print('Text: {}'.format(text))
# print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))


from typing import ChainMap
from django.http.response import HttpResponseNotModified
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
from django.urls import reverse
from django.template.loader import render_to_string #allows use of HTML docs by converting them to str
from django.http import Http404
# Create your views here.

# def jan(request):
#     return HttpResponse("Request Accepted  for Jan.")
# # This function is created to handle url requests

# def feb(request):
#     return HttpResponse("February works baby!")

# dictionary URL
m_challenges = {
    "january": "Jan is the goat",
    "february": "Feb is the cat",
    "march": "Ye-yeah!",
    "april": "Yoyo!",
    "may": "Forgot about MAY!",
    "june": None,
    "july": None,
    "august": None,
    "september": None,
    "october": None,
    "november": None,
    "december": None
}

# def index(request): #standard name for homepage func
#     # Inefficient way of creating index func
#     list_items = ""
#     months = list(m_challenges.keys())

#     for month in months:
#         capital_month = month.capitalize()
#         month_path = reverse("month-challenge", args =[month])
#         list_items += f"
{capital_month}
" # dont fucking forget {} for paths!!

#     response_data = f"
{list_items}
"
#     return HttpResponse(response_data)

def index(request):
    # Standard index func
    months = list(m_challenges.keys())
    return render(request, "challenges/index.html", {
        "month_list": months
    })

def monthpages_by_number(request, month):
# redirects numerical URLs to corresponding month
    months = list(m_challenges.keys())

    if month > len(months):
        return HttpResponseNotFound("number invalid, b*tch")

    redirect_months = months[month-1] # the -1 aligns the index
    redirect_path = reverse("month-challenge", args =[redirect_months])

    return HttpResponseRedirect(redirect_path)

def monthpages(request, month): # second arg is the <placeholder> mentioned in urls
    # http response func receives request, lookup dictionary value then returns response
    try:
        challenge_text = m_challenges[month] # square brackets cite item inside dictionary
        #response_data = render_to_string("challenges/challenge.html")
        #return HttpResponse(response_data)
        return render(request, "challenges/challenge.html", {
            "text": challenge_text,
            "month_name": month
        }) #shorthanded version of above 2 comments
    except:
        # response_data = render_to_string("404.html")
        #return HttpResponseNotFound(response_data) # Obsolete command. Instead we raise the class 404 by importing http404
        raise Http404() # automatically looks for 404.html in root template folder.
                        # This is useful when deving since you get the bultin errors when urls dont work helping you troubleshoot

# The objective of your views.py is to keep the functions as lean as possible and avoid any hardcoded html.
#  Leave all html for the actual html documents


# Define your model
import matplotlib.pyplot as plt
import pandas as pd
import torch

from cam_tools import *
from d2l import *
from dp.model import *

#加载模型
model_path = r"D:\all_code\cam_code\model\3.pt"
model = ResNet(in_channels=6, classes=3)
model.load_state_dict(torch.load(model_path))
model.eval()

#加载数据
IMU_data=get_test_data(r"D:\all_code\cam_code\data\test1","1x_0")
print(IMU_data.shape)
start=3
IMU_data=IMU_data[:,int(start*500):int(start*500+1024)]
input_tensor=torch.Tensor(IMU_data)

#获取最后一个全连接层的参数

    # 获取模型的所有参数
params = model.parameters()
    # 将参数列表转换为一个可迭代的列表
param_list = list(params)
    # 获取倒数第二层的参数
last_layer_params = param_list[-2]
print(last_layer_params.shape)

#获取网路最后一个卷积层的输出
    # 定义一个列表来保存最后一层卷积层的输出结果
last_conv_output = []
    # 定义一个钩子函数来获取最后一层卷积层的输出结果
def get_last_conv_output(module, input, output):
    last_conv_output.append(output)
    # 获取最后一层卷积层
last_conv_layer=model.features[-2].layer[6]
    # 将钩子函数附加到最后一层卷积层上
hook = last_conv_layer.register_forward_hook(get_last_conv_output)

#获取cam
out = model(input_tensor.unsqueeze(0))
print(out)
print(last_conv_output[-1].shape)
result=get_cam_1D(last_layer_params,last_conv_output[-1],out)
print(result.shape)
print(result)
print(type(result))
plt.plot(IMU_data[0])
plt.show()

import seaborn as sns
result0=pd.DataFrame(result[0].reshape(1,-1))
print(result0.shape)
sns.heatmap(result0, cmap='coolwarm',cbar=False)
plt.show()
# 绘制第二个子图
result1=pd.DataFrame(result[1].reshape(1,-1))
sns.heatmap(result1, cmap='coolwarm',cbar=False)
plt.show()
# 绘制第二个子图
result2=pd.DataFrame(result[2].reshape(1,-1))
sns.heatmap(result2, cmap='coolwarm',cbar=False)
plt.show()
result=pd.DataFrame(result)
sns.heatmap(result, cmap='coolwarm',cbar=False)
plt.show()

print(result0,result1,result0+result1)


import os
import nltk
import numpy as np
import math
import pickle as pkl
from tqdm import tqdm

root = "./pa1-data/"
documents = {}
tokens = {}
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
stop_words = nltk.corpus.stopwords.words('english')
lematizer = nltk.stem.WordNetLemmatizer()
steamer = nltk.stem.PorterStemmer()

break_point = 0
for folder in os.listdir(root):

    path = root + folder
    for name in tqdm(os.listdir(path)):
        break_point = break_point + 1

        file_name = path + "/" + name
        file = open(file_name, 'r')

        for line in file:

            documents[name] = line
            tokens[name] = tokenizer.tokenize(line)

            text_no_stop_words = []
            for word in tokens[name]:
                if word not in stop_words:
                    text_no_stop_words.append(word)

            text_no_stop_words = [lematizer.lemmatize(word) for word in text_no_stop_words]
            text_no_stop_words = [steamer.stem(word) for word in text_no_stop_words]
            tokens[name] = text_no_stop_words

def get_vocabulary(collection):
    """
        Get the vocabulary from the collection
    """
    vocabulary = []

    for key in tqdm(collection):
        for word in collection[key]:
            if word not in vocabulary:
                vocabulary.append(word)

    return vocabulary

"""
    Here we extract the vocabulary from the collection!
"""
Vocabulary = get_vocabulary(tokens)

print(len(documents))
print(len(Vocabulary))

pkl.dump(Vocabulary, open("Vocabulary.pkl", "wb"))


#!/usr/bin/env python3
"""
A file housing all functions for preprocessing Twitter data.
"""

from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize

def preprocess_text(text):
    """
    Preprocess the given text into tokens. This function
        - Removes stop words
        - Lemmatizes tokens
    Preconditions:
        text : String. The text to preprocess.
    Returns:
        The cleaned tokens, in dictionary format with all tokens mapped to True (i.e. the correct format for NLTK classifiers).
    """
    tokens = word_tokenize(text)

    stop_words = stopwords.words('english')
    lemmatizer = WordNetLemmatizer()
    cleaned_tokens = {
        lemmatizer.lemmatize(token) : True for token in tokens if not token in stop_words
    }

    return cleaned_tokens