import time
import traceback
from typing import TYPE_CHECKING

import cherrypy
from marshmallow import ValidationError

from tortuga.node.manager import NodeStoreManager, NodeStatusStoreManager
from tortuga.web_service.auth.decorators import authentication_required
from .base import Controller, HttpError, HttpNotFoundError

if TYPE_CHECKING:
    from tortuga.node.types import Node

class NodeController(Controller):
    """
    Node web service controller class.

    """
    name = 'nodes'
    type_store = NodeStoreManager.get()
    methods = ['GET', 'PUT']

class NodeStatusController(Controller):
    name = 'node-status'
    type_store = NodeStatusStoreManager.get()
    methods = ['GET', 'PUT']

    def marshall(self, obj: 'Node') -> dict:
        schema_class = self.type_store.status_type_class.schema_class
        marshalled = schema_class().dump(obj)
        return marshalled.data

    def unmarshall(self, obj_dict: dict) -> 'Node':
        """
        Unmarshalls an obj dict into an obj class instance.
        We override the base class unmarshalling to add validation, which is
        not presently compatible with several schemas.
        """
        schema_class = self.type_store.type_class.get_schema_class()
        unmarshalled = schema_class().load(obj_dict)
        if unmarshalled.errors:
            raise ValidationError(unmarshalled.errors)
        return self.type_store.type_class(**unmarshalled.data)

    @authentication_required()
    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def update(self, obj_id: str) -> dict:
        try:
            # Get full Node object
            obj_current = self.type_store.get(obj_id)
            if not obj_current:
                raise HttpNotFoundError('Not found: {}'.format(obj_id))

            # Convert request to Node object (will be incomplete)
            obj = self.unmarshall(cherrypy.request.json)

            # NOTE: we don't check that the object IDs match since the
            # user may be doing the update by name and would not provide
            # the ID in the data.

            # Update the current object with the state from the request;
            # if state is not provided, keep the current state
            obj_current.state = obj.state or obj_current.state
            obj_current.last_update = time.strftime(
                '%Y-%m-%d %H:%M:%S',
                time.gmtime(time.time())
            )
            obj = self.type_store.save(obj_current)
            response = self.marshall(obj)
        except HttpError as ex:
            response = self.error_response(str(ex), http_status=ex.status_code)
        except Exception as ex:
            self._logger.error(traceback.format_exc())
            response = self.error_response(str(ex))
        return self.format_response(response)


from datetime import date
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

data = date.today()
meses = ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro',
         'novembro', 'dezembro']
ano, mes, dia = str(data).split("-")
mes = meses[int(mes) - 1]

for i in meses:
    exec(f"estoque{i}=open(f\"C:/Users/User/Desktop/estoque/estoque de {i}.txt\",\"a\")")
    exec(f"vendas{i}=open(f\"C:/Users/User/Desktop/estoque/vendas de {i}.txt\",\"a\")")

janela = Tk()

janela.title("mercado")

janela.geometry('350x200')

data2 = Label(janela, text=f"{dia} {mes} {ano}")
data2.grid(column=0, row=0)

lbl = Label(janela, text="-MERCADO-")
lbl.grid(column=0, row=1)

estoque = {}
fim = False
produtos = []

def salvarestoque(nome, qtde, preco):
    global estoque
    global janela
    estoque[nome.get()] = [qtde.get(), preco.get()]
    for i in meses:
        if i == mes:
            return exec(rf'estoque{i}.write(f"produto:{nome.get()}\npreço: R${preco.get()}\nestoque:{qtde.get()}\n\n")')

def defestoque():
    global produtos
    global estoque
    global janela
    estoque1 = Tk()

    estoque1.title(" ADD estoque")

    estoque1.geometry('350x200')

    data2 = Label(estoque1, text=f"{dia} {mes} {ano}", )
    data2.grid(column=0, row=1)

    addestoquejanela = Label(estoque1, text="ADD Estoque")
    addestoquejanela.grid(column=1, row=1)

    produto = Label(estoque1, text="PRODUTO")
    produto.grid(column=0, row=3, sticky=W, padx=5, pady=5)

    produtoentry = Entry(estoque1)
    produtoentry.grid(column=1, row=3, sticky=E, padx=5, pady=5)

    produtos.append(produtoentry.get())

    quantidade = Label(estoque1, text="QUANTIDADE")
    quantidade.grid(column=0, row=4, sticky=E, padx=5, pady=5)
    quantidadeentry = Entry(estoque1)
    quantidadeentry.grid(column=1, row=4, sticky=E, padx=5, pady=5)

    preco = Label(estoque1, text="PREÇO")
    preco.grid(column=0, row=5, sticky=E, padx=5, pady=5)
    precoentry = Entry(estoque1)
    precoentry.grid(column=1, row=5, sticky=E, padx=5, pady=5)

    blank1 = Label(estoque1, text="")
    blank1.grid(column=0, row=6)

    salvar = Button(estoque1, text="Salvar",
                    command=lambda: salvarestoque(produtoentry, precoentry, quantidadeentry))

    salvar.grid(column=0, row=7)

    estoque1.mainloop()

btn_estoque = Button(janela, text="ADD Estoque",command=defestoque)
btn_estoque.grid(column=0, row=2)

btn_vendas = Button(janela, text="Vender", width=10, height=1)
btn_vendas.grid(column=0, row=3)

btn_verestoque = Button(janela, text="Ver estoque", width=10, height=1)
btn_verestoque.grid(column=0, row=4)

btn_vervendas = Button(janela, text="Ver vendas", width=10, height=1)
btn_vervendas.grid(column=0, row=5)

btn_fechar = Button(janela, text="fechar", width=10, height=1, command=lambda: janela.quit())
btn_fechar.grid(column=0, row=6)

janela.mainloop()


#!/usr/bin/env python3

import os, sys
import shutil
import signal
from datetime import datetime
#add other imports as needed by your script
# The purpose of this script is to give you simple functions for locating an executable program in common locations in the Linux path

# Simple shell
# COMMANDS          ERRORS CHECKED
# 1. info XX         - check file/dir exists
# 2. files
# ... omitted for simplicity
# 8. Default is to run the program

# Here the path is hardcoded, but you can easily optionally get your PATH environ variable
# by using: path = os.environ['PATH'] and then splitting based on ':' such as the_path = path.split(':')
THE_PATH = ["/bin/", "/usr/bin/", "/usr/local/bin/", "./"]

# ========================
#    Run command
#    Run an executable somewhere on the path
#    Any number of arguments
# ========================
def runCmd(fields):
    global PID, THE_PATH

    cmd = fields[0]
    count = 0
    args = []
    while count < len(fields):
        args.append(fields[count])
        count += 1

    execname = add_path(cmd, THE_PATH)

    # run the executable
    if not execname:
        print ("Executable file", cmd, "not found")
        return
    else:
      # execute the command
      print(execname)
#signal handler has to be in the parent
    PID = os.fork()
    # Wait if we're in parent, execute command if in child.
    if PID:
        os.waitpid(PID, 0)
    else:
    # execv executes a new program, replacing the current process; on success, it does not return.
    # On Linux systems, the new executable is loaded into the current process, and will have the same process id as the caller.
        os.execv(execname, args)

# ========================
#    Constructs the full path used to run the external command
#    Checks to see if the file is executable. Returns False on failure.
# ========================
def add_path(cmd, path):
    if cmd[0] not in ['#!/', '#!.']:
        for d in path:
            execname = d + cmd
            if os.path.isfile(execname) and os.access(execname, os.X_OK):
                return execname
        return False
    else:
        return cmd

# ========================
#    files command
#    List file and directory names
#    No arguments
# ========================
def filesCmd(fields):
    target = os.path.realpath(os.path.expanduser(fields[1]))
    print(target)
    if checkArgs(fields, 1):
        for filename in os.listdir(target):
            if os.path.isdir(os.path.abspath(filename)):
                print("dir:", filename)
            else:
                print("file:", filename)

# ========================
#  info command
#     List file information
#     1 argument: file name
# ========================
def infoCmd(fields):
    arg = 1
    if len(fields) > 1:
        while arg < len(fields):
            name = fields[arg]
            path = os.path.realpath(os.path.expanduser(name))

            print("\npath  | ", path)
            if os.path.islink(name):
                print("type  | link -> " + os.path.basename(os.readlink(name)))
            elif os.path.isfile(name):
                print("type  | file")
            elif os.path.isdir(name):
                print("type  | directory")
            else:
                print("type  | other")
            if not os.path.exists(path):
                print("The path above does not exist.")
                arg = arg + 1
                continue
            print("owner | ", Path(path).owner())
            if os.path.isfile(name):
                print("bytes | ", os.path.getsize(name))
            print("executable   |", os.access(path, os.X_OK))
            print("last_changed | ", datetime.fromtimestamp(os.path.getctime(path)).strftime('%b %d %Y %H:%M:%S'))

            arg = arg + 1
    else:
        print("Incorrect number of arguments for command:", fields[0])

# ========================
#  delete command
#     Delete file
#     1 argument: file name
# ========================
def del_cmd(fields):
    path = os.path.realpath(os.path.expanduser(fields[1]))
    if checkArgs(fields, 1):
        os.remove(path)
        if not os.path.exists(path):
            print("The file was deleted.")

# ========================
#  copy command
#     Copy and paste file
#     2 argument: file name, new file name
# ========================
def copy_cmd(fields):
    src = os.path.realpath(os.path.expanduser(fields[1]))
    dst = os.path.realpath(os.path.expanduser(fields[2]))

    if checkArgs(fields, 2):
        if os.path.exists((dst)) & os.path.isfile(dst):
            ans = input("This path already exists. Do you want to overwrite it with your copy? (Y/n)\n")
            while (not ans == "Y") and (not ans == "n"):
                ans = input("This path already exists. Do you want to overwrite it with your copy? (Y/n)\n")

            if ans == "Y":
                result = shutil.copy2(src, dst)
                print("Your file is at ", result + ".")
            else:
                print("Your file wasn't copied.")
        else:
            result = shutil.copy2(src, dst)
            print("Your file is at ", result + ".")

# ========================
#  where command
#     Show current directory
#     0 argument
#=========================
def where_cmd(fields):
    if checkArgs(fields, 0):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        print(dir_path)

# ========================
#  down command
#     Move down to a directory
#     1 argument: directory name
#=========================
def down_cmd(fields):
    if checkArgs(fields, 1):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        dst = dir_path + "/" + fields[1]

        os.chdir(dst)
        print("Directory changed.")

# ========================
#  up command
#     Move up to a directory
#     0 argument
#=========================
def up_cmd(fields, current):
    if checkArgs(fields, 0):
        dst = os.path.dirname(os.path.realpath(current))

        os.chdir(dst)
        print("Directory changed.")

        return current

# ----------------------
# Other functions
# ----------------------
def checkArgs(fields, num):
    numArgs = len(fields) - 1
    if numArgs == num:
        return True
    if numArgs > num:
        unexpected = ""
        for arg in fields[num+1:]:
            unexpected = unexpected  + " " + arg
        print("Unexpected argument" + unexpected + " for command:", fields[0])
    else:
        print("Missing argument for command:", fields[0])

    return False

def sigint_handler(signum, frame):
    os.kill(PID, signal.SIGKILL)
    print(" Process:", str(PID) + " was killed.")

# ----------------------------------------------------------------------------------------------------------------------
signal.signal(signal.SIGINT, sigint_handler)

while True:
    try:

        line = input("PShell>")
        fields = line.split()

        if fields[0] == "files":
            filesCmd(fields)
        elif fields[0] == "info":
            infoCmd(fields)
        elif fields[0] == "delete":
            del_cmd(fields)
        elif fields[0] == "copy":
            copy_cmd(fields)
        elif fields[0] == "where":
            where_cmd(fields)
        elif fields[0] == "down":
            down_cmd(fields)
        elif fields[0] == "up":
            current = os.getcwd()
            if not current == "/":
                current = up_cmd(fields, current)
            else:
                print("No higher directory.")
        elif fields[0] == "finish" or fields[0] == "x":
            break
        else:
            runCmd(fields)
    except FileExistsError:
        print("File already exists.")
    except FileNotFoundError:
        print("The path above does not exist.")
    except IndexError:
        print("Incorrect number of arguments for command:", fields[0])
    except IsADirectoryError:
        print("This is a directory.")
    except NotADirectoryError:
        print("This isn't a directory.")


import requests
import hashlib
import datetime
import json
import logging
from django.conf import settings

logger = logging.getLogger(__name__)

public_key = settings.MARVEL_PUBLIC_KEY
private_key = settings.MARVEL_PRIVATE_KEY

def get_hash(timestamp):
    hash = hashlib.md5()
    hash.update(str(timestamp).encode('utf-8'))
    hash.update(private_key.encode('utf-8'))
    hash.update(public_key.encode('utf-8'))
    return hash.hexdigest()

def get_auth_credentials():
    timestamp = datetime.datetime.now().timestamp()

    return {
        "ts": timestamp,
        "hash": get_hash(timestamp),
        "apikey": public_key,
    }

def make_request(uri, params):

    auth_creds = get_auth_credentials()
    params.update(auth_creds)

    try:
        response = requests.get(uri, params=params)

    except requests.RequestException as ex:

        logger.error(f"Marvel API network error: {ex} uri {uri} params: {params}")
        return True, "Проблемы с соединением, повторите позже"

    if response.status_code == 200:
        try:
            data = response.json()

            logger.info(f"Marvel API: uri: {uri} params: {params} json: {data}")

            return False, data

        except json.JSONDecodeError as ex:
            logger.error(f"Marvel API json decode error: {ex} uri: {uri} params: {params} body: {response.body}")

            return True, "Ошибка сервера"

    elif response.status_code == 409:
        return True, "Ошибка входных параметров"

    elif response.status_code == 404:
        return True, "Данных не найдено"

    else:
        logger.error(f"Marvel API status_code error: {ex} uri: {uri} params: {params} body: {response.body}")
        return True, "Непредвиденная ошибка, обратитесь к администратору "


import numpy as np
import scipy.optimize
from scipy.special import erf
import matplotlib.pyplot as plt
from scipy.signal import find_peaks, peak_widths

# This file contains several fit routines and functions

def Linear(x, M, N):
    # Linear function
    # M: slope
    # N: intercept
    return M * x + N

def Gaussian(x, A, MU, SIGMA):
    # Gaussian function
    # A: amplitude
    # MU: mean
    # SIGMA: standard deviation
    return A * np.exp(-(x-MU)**2 / (2*SIGMA**2))

def SkewedGaussian(X,A,MU,SIGMA, GAMMA):
    return (A / (np.sqrt(2*np.pi) * SIGMA)) * np.exp(-(X-MU)**2 / (2*SIGMA**2)) * (1+erf((GAMMA*(X-MU)) / (SIGMA*np.sqrt(2))))

def Linear_fit(x,y, plot=False):
    x = np.array(x)
    y = np.array(y)
    init = [(y[2]-y[1]) / (x[2]-x[1]), 0]                                 # initial guess of the parameters
    fit = scipy.optimize.curve_fit(Linear, x, y, init)                    # fit
    opt_param = fit[0]                                                    # optimal parameters that fit the data
    opt_param_cov = fit[1]                                                # matrix of covariance
    opt_param_error = np.sqrt(np.diag(opt_param_cov))                     # errors are in the diagonal of the matrix
    M = opt_param[0]                                                      # slope of the fit
    N = opt_param[1]                                                      # intercept of the fit
    delta_M = opt_param_error[0]                                          # error of the slope
    delta_N = opt_param_error[1]                                          # error of the intercept
    residuals = y - Linear(x, M, N)                                       # calculate residuals
    ss_res = np.sum(residuals ** 2)                                       # sum of the squared residuals
    ss_tot = np.sum((y - np.mean(y)) ** 2)                                # total sum of squares
    r_squared = 1 - (ss_res / ss_tot)                                     # r^2 (goodness of fit)
    values = {'slope': M, 'delta_slope': delta_M,                         # the fit is returned in a dictionary
              'intercept': N, 'delta_intercept': delta_N,
              'r_squared': r_squared
              }
    if plot:                                                              # plots the regression line and data
        new_x = np.linspace(x[0], x[-1])                                  # x for the regression line
        fig = plt.figure(1)
        plt.plot(x, y, "kx", zorder=1)
        plt.plot(new_x, Linear(new_x, values.get("slope"), values.get("intercept")), "r--", zorder=0)
        plt.xlabel("x")
        plt.ylabel("y")
        plt.title("Calibration")
        M = values.get("slope")
        M_err = values.get("delta_slope")
        N = values.get("intercept")
        N_err = values.get("delta_intercept")
        r_2 = values.get("r_squared")
        text = "m = " + "%.3f" % M + " $\pm$ " + "%.3f" % M_err + "\n" + "n = " + "%.3f" % N + " $\pm$ " + "%.3f" % N_err + "\n" + "$r^2$ = " + "%.4f" % r_2
        plt.text(0.15, 0.83, text, transform=fig.transFigure, bbox=dict(facecolor="white"))
        plt.tight_layout()
        plt.show()
    return values

def Gaussian_fit(x,y):
    init = [max(y), x[np.argmax(y)], (x[1] - x[0]) * 5]                     # initial guess of the parameters
    fit = scipy.optimize.curve_fit(Gaussian, x, y, init)                    # fit
    opt_param = fit[0]                                                      # optimal parameters that fit the data
    opt_param_cov = fit[1]                                                  # matrix of covariance
    opt_param_error = np.sqrt(np.diag(opt_param_cov))                       # errors are in the diagonal of the matrix
    A = opt_param[0]                                                        # amplitude of the fit
    MU = opt_param[1]                                                       # mean of the fit
    SIGMA = abs(opt_param[2])                                               # std dev of the fit (abs value)
    delta_A = opt_param_error[0]                                            # error of the amplitude
    delta_MU = opt_param_error[1]                                           # error of the mean
    delta_SIGMA = opt_param_error[2]                                        # error of the std dev
    FWHM = 2 * SIGMA * np.sqrt(2 * np.log(2))                               # Full Width at Half Maximum
    delta_FWHM = 2 * np.sqrt(2 * np.log(2)) * delta_SIGMA                   # error of FWHM
    R = 100 * FWHM / MU                                                     # Resolution
    delta_R = R * np.sqrt((delta_FWHM / FWHM) ** 2 + (delta_MU / MU) ** 2)  # error of R
    values = {'amplitude': A, 'delta_amplitude': delta_A,                   # the fit is returned in a dictionary
              'mean': MU, 'delta_mean': delta_MU,
              'sigma': SIGMA, 'delta_sigma': delta_SIGMA,
              'FWHM': FWHM, 'delta_FWHM': delta_SIGMA,
              'R[%]': R, 'delta_R[%]': delta_R
              }
    return values

def SkewedGaussian_fit(x,y):
    init = [max(y), x[np.argmax(y)], (x[np.argmax(y)] - x[0])/3, 1]         # initial guess of the parameters
    fit = scipy.optimize.curve_fit(SkewedGaussian, x, y, init)              # fit
    opt_param = fit[0]                                                      # optimal parameters that fit the data
    opt_param_cov = fit[1]                                                  # matrix of covariance
    opt_param_error = np.sqrt(np.diag(opt_param_cov))                       # errors are in the diagonal of the matrix
    A = opt_param[0]                                                        # amplitude of the fit
    MU = opt_param[1]                                                       # mean of the fit
    SIGMA = abs(opt_param[2])                                               # std dev of the fit (abs value)
    GAMMA = opt_param[3]                                                    # skewness
    delta_A = opt_param_error[0]                                            # error of the amplitude
    delta_MU = opt_param_error[1]                                           # error of the mean
    delta_SIGMA = opt_param_error[2]                                        # error of the std dev
    delta_GAMMA = opt_param_error[3]                                        # error of skewness
    values = {'amplitude': A, 'delta_amplitude': delta_A,                   # the fit is returned in a dictionary
              'mean': MU, 'delta_mean': delta_MU,
              'sigma': SIGMA, 'delta_sigma': delta_SIGMA,
              'gamma': GAMMA, 'delta_gamma': delta_GAMMA
              }
    return values


# coding: utf-8

"""
    ExtremeCloud IQ API

    ExtremeCloud IQ RESTful API for external and internal applications.  # noqa: E501

    The version of the OpenAPI document: 23.6.0.46
    Contact: support@extremenetworks.com
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from extremecloudiq.configuration import Configuration

class XiqAuthLog(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'id': 'str',
        'auth_type': 'str',
        'sn': 'str',
        'vhm_id': 'str',
        'username': 'str',
        'reply': 'str',
        'called_station_id': 'str',
        'calling_station_id': 'str',
        'auth_date': 'int',
        'ssid': 'str',
        'identity': 'str',
        'nas_port_type': 'str',
        'reject_reason': 'str',
        'nas_identifier': 'str',
        'mgmt_mac_address': 'str',
        'org_id': 'int',
        'timestamp': 'int'
    }

    attribute_map = {
        'id': 'id',
        'auth_type': 'auth_type',
        'sn': 'sn',
        'vhm_id': 'vhm_id',
        'username': 'username',
        'reply': 'reply',
        'called_station_id': 'called_station_id',
        'calling_station_id': 'calling_station_id',
        'auth_date': 'auth_date',
        'ssid': 'ssid',
        'identity': 'identity',
        'nas_port_type': 'nas_port_type',
        'reject_reason': 'reject_reason',
        'nas_identifier': 'nas_identifier',
        'mgmt_mac_address': 'mgmt_mac_address',
        'org_id': 'org_id',
        'timestamp': 'timestamp'
    }

    def __init__(self, id=None, auth_type=None, sn=None, vhm_id=None, username=None, reply=None, called_station_id=None, calling_station_id=None, auth_date=None, ssid=None, identity=None, nas_port_type=None, reject_reason=None, nas_identifier=None, mgmt_mac_address=None, org_id=None, timestamp=None, local_vars_configuration=None):  # noqa: E501
        """XiqAuthLog - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._id = None
        self._auth_type = None
        self._sn = None
        self._vhm_id = None
        self._username = None
        self._reply = None
        self._called_station_id = None
        self._calling_station_id = None
        self._auth_date = None
        self._ssid = None
        self._identity = None
        self._nas_port_type = None
        self._reject_reason = None
        self._nas_identifier = None
        self._mgmt_mac_address = None
        self._org_id = None
        self._timestamp = None
        self.discriminator = None

        self.id = id
        if auth_type is not None:
            self.auth_type = auth_type
        if sn is not None:
            self.sn = sn
        if vhm_id is not None:
            self.vhm_id = vhm_id
        if username is not None:
            self.username = username
        if reply is not None:
            self.reply = reply
        if called_station_id is not None:
            self.called_station_id = called_station_id
        if calling_station_id is not None:
            self.calling_station_id = calling_station_id
        if auth_date is not None:
            self.auth_date = auth_date
        if ssid is not None:
            self.ssid = ssid
        if identity is not None:
            self.identity = identity
        if nas_port_type is not None:
            self.nas_port_type = nas_port_type
        if reject_reason is not None:
            self.reject_reason = reject_reason
        if nas_identifier is not None:
            self.nas_identifier = nas_identifier
        if mgmt_mac_address is not None:
            self.mgmt_mac_address = mgmt_mac_address
        if org_id is not None:
            self.org_id = org_id
        if timestamp is not None:
            self.timestamp = timestamp

    @property
    def id(self):
        """Gets the id of this XiqAuthLog.  # noqa: E501

        The auth log id  # noqa: E501

        :return: The id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._id

    @id.setter
    def id(self, id):
        """Sets the id of this XiqAuthLog.

        The auth log id  # noqa: E501

        :param id: The id of this XiqAuthLog.  # noqa: E501
        :type: str
        """
        if self.local_vars_configuration.client_side_validation and id is None:  # noqa: E501
            raise ValueError("Invalid value for `id`, must not be `None`")  # noqa: E501

        self._id = id

    @property
    def auth_type(self):
        """Gets the auth_type of this XiqAuthLog.  # noqa: E501

        The auth type  # noqa: E501

        :return: The auth_type of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._auth_type

    @auth_type.setter
    def auth_type(self, auth_type):
        """Sets the auth_type of this XiqAuthLog.

        The auth type  # noqa: E501

        :param auth_type: The auth_type of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._auth_type = auth_type

    @property
    def sn(self):
        """Gets the sn of this XiqAuthLog.  # noqa: E501

        The serial number  # noqa: E501

        :return: The sn of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._sn

    @sn.setter
    def sn(self, sn):
        """Sets the sn of this XiqAuthLog.

        The serial number  # noqa: E501

        :param sn: The sn of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._sn = sn

    @property
    def vhm_id(self):
        """Gets the vhm_id of this XiqAuthLog.  # noqa: E501

        The vhm id  # noqa: E501

        :return: The vhm_id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._vhm_id

    @vhm_id.setter
    def vhm_id(self, vhm_id):
        """Sets the vhm_id of this XiqAuthLog.

        The vhm id  # noqa: E501

        :param vhm_id: The vhm_id of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._vhm_id = vhm_id

    @property
    def username(self):
        """Gets the username of this XiqAuthLog.  # noqa: E501

        The username  # noqa: E501

        :return: The username of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._username

    @username.setter
    def username(self, username):
        """Sets the username of this XiqAuthLog.

        The username  # noqa: E501

        :param username: The username of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._username = username

    @property
    def reply(self):
        """Gets the reply of this XiqAuthLog.  # noqa: E501

        The reply  # noqa: E501

        :return: The reply of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._reply

    @reply.setter
    def reply(self, reply):
        """Sets the reply of this XiqAuthLog.

        The reply  # noqa: E501

        :param reply: The reply of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._reply = reply

    @property
    def called_station_id(self):
        """Gets the called_station_id of this XiqAuthLog.  # noqa: E501

        The called station id  # noqa: E501

        :return: The called_station_id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._called_station_id

    @called_station_id.setter
    def called_station_id(self, called_station_id):
        """Sets the called_station_id of this XiqAuthLog.

        The called station id  # noqa: E501

        :param called_station_id: The called_station_id of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._called_station_id = called_station_id

    @property
    def calling_station_id(self):
        """Gets the calling_station_id of this XiqAuthLog.  # noqa: E501

        The calling station id  # noqa: E501

        :return: The calling_station_id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._calling_station_id

    @calling_station_id.setter
    def calling_station_id(self, calling_station_id):
        """Sets the calling_station_id of this XiqAuthLog.

        The calling station id  # noqa: E501

        :param calling_station_id: The calling_station_id of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._calling_station_id = calling_station_id

    @property
    def auth_date(self):
        """Gets the auth_date of this XiqAuthLog.  # noqa: E501

        The authentication date  # noqa: E501

        :return: The auth_date of this XiqAuthLog.  # noqa: E501
        :rtype: int
        """
        return self._auth_date

    @auth_date.setter
    def auth_date(self, auth_date):
        """Sets the auth_date of this XiqAuthLog.

        The authentication date  # noqa: E501

        :param auth_date: The auth_date of this XiqAuthLog.  # noqa: E501
        :type: int
        """

        self._auth_date = auth_date

    @property
    def ssid(self):
        """Gets the ssid of this XiqAuthLog.  # noqa: E501

        The ssid  # noqa: E501

        :return: The ssid of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._ssid

    @ssid.setter
    def ssid(self, ssid):
        """Sets the ssid of this XiqAuthLog.

        The ssid  # noqa: E501

        :param ssid: The ssid of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._ssid = ssid

    @property
    def identity(self):
        """Gets the identity of this XiqAuthLog.  # noqa: E501

        The identity  # noqa: E501

        :return: The identity of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._identity

    @identity.setter
    def identity(self, identity):
        """Sets the identity of this XiqAuthLog.

        The identity  # noqa: E501

        :param identity: The identity of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._identity = identity

    @property
    def nas_port_type(self):
        """Gets the nas_port_type of this XiqAuthLog.  # noqa: E501

        The nas port type  # noqa: E501

        :return: The nas_port_type of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._nas_port_type

    @nas_port_type.setter
    def nas_port_type(self, nas_port_type):
        """Sets the nas_port_type of this XiqAuthLog.

        The nas port type  # noqa: E501

        :param nas_port_type: The nas_port_type of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._nas_port_type = nas_port_type

    @property
    def reject_reason(self):
        """Gets the reject_reason of this XiqAuthLog.  # noqa: E501

        The reject reason  # noqa: E501

        :return: The reject_reason of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._reject_reason

    @reject_reason.setter
    def reject_reason(self, reject_reason):
        """Sets the reject_reason of this XiqAuthLog.

        The reject reason  # noqa: E501

        :param reject_reason: The reject_reason of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._reject_reason = reject_reason

    @property
    def nas_identifier(self):
        """Gets the nas_identifier of this XiqAuthLog.  # noqa: E501

        The nas identifier  # noqa: E501

        :return: The nas_identifier of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._nas_identifier

    @nas_identifier.setter
    def nas_identifier(self, nas_identifier):
        """Sets the nas_identifier of this XiqAuthLog.

        The nas identifier  # noqa: E501

        :param nas_identifier: The nas_identifier of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._nas_identifier = nas_identifier

    @property
    def mgmt_mac_address(self):
        """Gets the mgmt_mac_address of this XiqAuthLog.  # noqa: E501

        The management mac address  # noqa: E501

        :return: The mgmt_mac_address of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._mgmt_mac_address

    @mgmt_mac_address.setter
    def mgmt_mac_address(self, mgmt_mac_address):
        """Sets the mgmt_mac_address of this XiqAuthLog.

        The management mac address  # noqa: E501

        :param mgmt_mac_address: The mgmt_mac_address of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._mgmt_mac_address = mgmt_mac_address

    @property
    def org_id(self):
        """Gets the org_id of this XiqAuthLog.  # noqa: E501

        The org id  # noqa: E501

        :return: The org_id of this XiqAuthLog.  # noqa: E501
        :rtype: int
        """
        return self._org_id

    @org_id.setter
    def org_id(self, org_id):
        """Sets the org_id of this XiqAuthLog.

        The org id  # noqa: E501

        :param org_id: The org_id of this XiqAuthLog.  # noqa: E501
        :type: int
        """

        self._org_id = org_id

    @property
    def timestamp(self):
        """Gets the timestamp of this XiqAuthLog.  # noqa: E501

        The audit log timestamp  # noqa: E501

        :return: The timestamp of this XiqAuthLog.  # noqa: E501
        :rtype: int
        """
        return self._timestamp

    @timestamp.setter
    def timestamp(self, timestamp):
        """Sets the timestamp of this XiqAuthLog.

        The audit log timestamp  # noqa: E501

        :param timestamp: The timestamp of this XiqAuthLog.  # noqa: E501
        :type: int
        """

        self._timestamp = timestamp

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, XiqAuthLog):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, XiqAuthLog):
            return True

        return self.to_dict() != other.to_dict()


import redis
import threading
class quote_cache:
    def __init__(self):
        self.load_env()
        self.r = redis.Redis(host=self.redis_host, port=self.redis_port)
        self.mutex = threading.Lock()

    def load_env(self):
        import os
        from dotenv import load_dotenv
        load_dotenv()
        self.redis_host = os.environ.get("redis_host")
        self.redis_port = int(os.environ.get("redis_port"))

    def sanitize_byte_keys_and_vals(self, response):
        sanitized_dict = {}
        keys = response.keys()
        for key in keys:
            sanitized_dict[str(key, encoding="utf-8")] = str(response[key], encoding="utf-8")
        return sanitized_dict

    def cache_quote(self, data):
        stock_symbol = data["stock_symbol"]
        dollars = data["dollars"]
        cents = data["cents"]
        quote_time = data["quote_time"]
        cryptokey = data["cryptokey"]
        response = {}

        self.mutex.acquire()

        try:
            bool_result = self.r.hmset(stock_symbol, {"dollars": dollars, "cents": cents, "quote_time": quote_time, "cryptokey": cryptokey})
            if (bool_result):
                response["status"] = "SUCCESS"
            else:
                response["status"] = "ERROR"

        finally:
            self.mutex.release()

        return response

    def get_quote(self, stock_symbol):
        response = {"status": "ERROR"}
        response["data"] = self.sanitize_byte_keys_and_vals(self.r.hgetall(stock_symbol))
        if (response["data"] != None and len(response["data"]) != 0):
            response["status"] = "SUCCESS"
        return response


import logging

# if cp_test_nn is imported, make sure the importer doesn't see
#  any logs by default, but can choose to enable them by calling
#  cp_test_nn.logging_setup()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
log.addHandler(logging.NullHandler())

def logging_setup(level=logging.INFO):
    handler = logging.StreamHandler()
    handler.setLevel(level)
    log.addHandler(handler)


from collections import Counter

def solution(progresses, speeds):

    day = [0]*len(progresses)
    for i in range(len(progresses)):
        div, mod = divmod((100-progresses[i]), speeds[i])
        if mod == 0 : day[i] = div
        else : day[i] = div+1

    for i in range(len(day)-1):
        if day[i+1] < day[i]:
            day[i+1] = day[i]

    return list(Counter(day).values())


import sys
from collections import deque
input = sys.stdin.readline

n = int(input().rstrip())
maps = [list(map(int, input().rstrip().split())) for _ in range(n)]

visited = [[0 for _ in range(n)] for _ in range(n)]

visited[0][0] = 1
queue = deque()
queue.append((0, 0))

done = 0
while queue:
    y, x = queue.popleft()

    if y == n - 1 and x == n - 1:
        done = 1
        break
    if maps[y][x] == 0:
        continue

    if y + maps[y][x] < n:
        queue.append((y+maps[y][x], x))
        visited[y+maps[y][x]][x] = 1
    if x + maps[y][x] < n:
        queue.append((y, x+maps[y][x]))
        visited[y][x+maps[y][x]] = 1

if done == 1: print("HaruHaru")
else: print("Hing")

백준/Silver/16173. 점프왕 쩰리 （Small）/점프왕 쩰리 （Small）.py

점프왕 쩰리 （Small）.py


from django.urls import include, path

from backend.core import views as v

app_name = 'core'

url_coreui = [
    path('colors', v.colors, name='colors'),
    path('typography', v.typography, name='typography'),
    path('accordion', v.accordion, name='accordion'),
    path('breadcrumb', v.breadcrumb, name='breadcrumb'),
    path('cards', v.cards, name='cards'),
    path('carousel', v.carousel, name='carousel'),
    path('collapse', v.collapse, name='collapse'),
    path('list-group', v.list_group, name='list_group'),
    path('navs-tabs', v.navs_tabs, name='navs_tabs'),
    path('pagination', v.pagination, name='pagination'),
    path('placeholders', v.placeholders, name='placeholders'),
    path('popovers', v.popovers, name='popovers'),
    path('progress', v.progress, name='progress'),
    path('spinners', v.spinners, name='spinners'),
    path('tables', v.tables, name='tables'),
    path('tooltips', v.tooltips, name='tooltips'),
    path('buttons', v.buttons, name='buttons'),
    path('button-group', v.button_group, name='button_group'),
    path('dropdowns', v.dropdowns, name='dropdowns'),
    path('charts', v.charts, name='charts'),
    path('form-control', v.form_control, name='form_control'),
    path('select', v.select, name='select'),
    path('checks-radios', v.checks_radios, name='checks_radios'),
    path('range', v.range, name='range'),
    path('input-group', v.input_group, name='input_group'),
    path('floating-labels', v.floating_labels, name='floating_labels'),
    path('layout', v.layout, name='layout'),
    path('validation', v.validation, name='validation'),
    path('coreui-icons-free', v.coreui_icons_free, name='coreui_icons_free'),
    path('coreui-icons-brand', v.coreui_icons_brand, name='coreui_icons_brand'),
    path('coreui-icons-flag', v.coreui_icons_flag, name='coreui_icons_flag'),
    path('alerts', v.alerts, name='alerts'),
    path('badge', v.badge, name='badge'),
    path('modals', v.modals, name='modals'),
    path('toasts', v.toasts, name='toasts'),
    path('widgets', v.widgets, name='widgets'),
    path('login', v.login, name='login'),
    path('register', v.register, name='register'),
    path('page404', v.page404, name='page404'),
    path('page500', v.page500, name='page500'),
]

urlpatterns = [
    path('', v.index, name='index'),
    path('list/', v._list, name='list'),
    path('detail/', v._detail, name='detail'),
    path('add/', v._create, name='create'),
    path('blank/', v.blank, name='blank'),
    path('coreui/', include(url_coreui)),
]


import os
import config
import tkinter as tk
from tkinter import ttk
from tkinter.ttk import Notebook
import docker.db as db
import docker

class Timer(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title(config.title)
        self.geometry(config.geometry)

        self.notebook = Notebook(self)
        running_tab = RunTag(self.notebook)
        images_tab = ImagesTab(self.notebook)

        self.notebook.add(running_tab, text="运行中的容器")
        self.notebook.add(images_tab, text="镜像管理")
        self.notebook.pack(fill=tk.BOTH, expand=1)

class RunTag(tk.Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__()

        rigth_frame = tk.LabelFrame(self)
        rigth_frame.pack(side=tk.RIGHT, expand=1, fill=tk.X, anchor=tk.N)

        content = tk.LabelFrame(self, background="cyan")
        content.pack(side=tk.RIGHT, expand=0, fill=tk.X)

        docker_ps = docker.container.running()

        tree = ttk.Treeview(content, columns=("NAMES", "IMAGE", "PORTS"), height=18, show="headings")
        tree.heading("NAMES", text=docker.container.titleKeyToName("NAMES"), anchor=tk.W)
        tree.column("NAMES", anchor=tk.W, width=100)
        tree.heading("IMAGE", text=docker.container.titleKeyToName("IMAGE"), anchor=tk.W)
        tree.column("IMAGE", anchor=tk.W, width=180)
        tree.heading("PORTS", text=docker.container.titleKeyToName("PORTS"), anchor=tk.W)
        tree.column("PORTS", anchor=tk.W, width=250)

        for values in docker_ps:
            value = (values["NAMES"], values["IMAGE"], values["PORTS"])
            tree.insert("", tk.END, values=value)
        tree.pack()

        translate_button = tk.Button(rigth_frame, text="开始")
        translate_button.pack(side=tk.TOP, fill=tk.BOTH)
        translate_button = tk.Button(rigth_frame, text="停止")
        translate_button.pack(side=tk.TOP, fill=tk.X)
        translate_button = tk.Button(rigth_frame, text="重启")
        translate_button.pack(side=tk.TOP, fill=tk.X)
        translate_button = tk.Button(rigth_frame, text="删除")
        translate_button.pack(side=tk.BOTTOM, fill=tk.X)

class ImagesTab(tk.Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__()
        self.italian_copy_button = tk.Button(self, text="Copy to Clipboard", command=self.test())
        self.italian_copy_button.pack(side=tk.BOTTOM, fill=tk.X)

        self.italian_translation = tk.StringVar(self)
        self.italian_translation.set("")

        self.italian_label = tk.Label(self, textvar=self.italian_translation, bg="lightgrey", fg="black")
        self.italian_label.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def test(self):
        pass

if __name__ == "__main__":
    timer = Timer()

    if not os.path.isfile("docker.db"):
        db.create()

    timer.mainloop()


import torch.nn as nn
model_name = 'bert-base-uncased'
max_seq_len = 25

class BERTda(nn.Module):

    def __init__(self, bert):
        super(BERTda, self).__init__()
        self.bert_large = model_name == 'bert-large-uncased'
        self.bert = bert

        # dropout layer
        self.dropout = nn.Dropout(0.1)

        # relu activation function
        self.relu = nn.ReLU()

        # dense layer 0 if bert_large is true, else skip it
        if self.bert_large:
            self.fc0 = nn.Linear(1024, 768)

        self.fc1 = nn.Linear(768, 512)

        # dense layer 2 (Output layer)
        self.fc2 = nn.Linear(512, 2)

        # softmax activation function
        self.softmax = nn.LogSoftmax(dim=1)

    # define the forward pass
    def forward(self, sent_id, mask):
        # pass the inputs to the model
        _, cls_hs = self.bert(sent_id, attention_mask=mask, return_dict=False)

        if self.bert_large:
            x = self.fc0(cls_hs)

            x = self.relu(x)

            x = self.dropout(x)
        else:
            x = cls_hs

        x = self.fc1(x)

        x = self.relu(x)

        x = self.dropout(x)

        # output layer
        x = self.fc2(x)

        # apply softmax activation
        x = self.softmax(x)

        return x