from pecan import expose, request
from pecan.hooks import HookController

from cloudrunner_server.api.hooks.braintree_hook import BrainTreeHook
from cloudrunner_server.api.hooks.db_hook import DbHook
from cloudrunner_server.api.hooks.error_hook import ErrorHook
from cloudrunner_server.api.hooks.perm_hook import PermHook
from cloudrunner_server.api.model import User
from cloudrunner_server.api.util import JsonOutput as O

class Billing(HookController):

    __hooks__ = [DbHook(), ErrorHook(), BrainTreeHook(),
                 PermHook(have=set(['is_admin']))]

    @expose('json', generic=True)
    def account(self, *args, **kwargs):
        """
        .. http:get:: /billing/account

            Returns basic account information

            >header:    Auth token
        """
        CS = request.braintree.CustomerSearch
        customers = [c for c in request.braintree.Customer.search(
            CS.company == request.user.org).items]
        if not customers:
            # Try to create customer
            user = User.visible(request).filter(
                User.username == request.user.username).one()
            result = request.braintree.Customer.create({
                "first_name": user.first_name,
                "last_name": user.last_name,
                "company": user.org.name,
                "email": user.email,
                "phone": user.phone,
            })

            if not result.is_success:
                return O.error("Cannot fetch data from billing system")

            customers = [result.customer]

        customer = customers[0]

        card, subs = {}, {}
        if customer.credit_cards:
            cc = customer.credit_cards[0]
            card['number'] = cc.masked_number
            card['expire'] = cc.expiration_date
            card['type'] = cc.card_type

            if cc.subscriptions:
                sub = cc.subscriptions[0]
                subs['next_date'] = sub.next_billing_date
                subs['next_amount'] = sub.next_billing_period_amount

        TS = request.braintree.TransactionSearch
        history = request.braintree.Transaction.search([
            TS.customer_company == request.user.org])
        return O.billing(transactions=[serialize_t(h) for h in history.items],
                         plan=subs, cards=card)

    @account.when(method='PUT', template='json')
    def update_data(self, *args, **kwargs):
        kwargs = kwargs or request.json
        if "cc" in kwargs:
            cc_data = kwargs['cc']
            CS = request.braintree.CustomerSearch
            customers = [c for c in request.braintree.Customer.search(
                CS.company == request.user.org).items]
            if not customers:
                return O.error("Customer not found")

            customer = customers[0]
            expire_m, expire_y = cc_data['expire_date'].split("/")

            token = ""
            if customer.credit_cards:
                # Update
                cc = customer.credit_cards[0]
                token = cc.token
                result = request.braintree.PaymentMethod.update(token, {
                    "number": cc_data['number'],
                    "cardholder_name": cc_data['cardholder_name'],
                    "expiration_month": expire_m,
                    "expiration_year": expire_y,
                    "cvv": cc_data['cvv'],
                })
            else:
                # Create
                result = request.braintree.CreditCard.create({
                    "customer_id": customer.id,
                    "number": cc_data["number"],
                    "expiration_month": expire_m,
                    "expiration_year": expire_y,
                    "cardholder_name": cc_data['cardholder_name'],
                    "cvv": cc_data['cvv']
                })

            if not result.is_success:
                errors = filter(None, result.errors.deep_errors)
                if errors:
                    return O.error(msg=errors[0].message)
            return O.success(msg="Account updated")

        return O.error(msg="No data provided for update")

    @expose('json')
    def change(self, *args, **kwargs):
        return O.error(msg="Not available yet")

def serialize_t(item):
    status_code = safe(lambda i: int(i or 0) / 10,
                       item.processor_response_code,
                       default=item.processor_response_code)
    return dict(amount=item.amount, created=item.created_at,
                currency=item.currency_iso_code, id=item.id,
                status=item.processor_response_text,
                status_code=status_code,
                plan=item.plan_id
                )

def safe(func, *args, **kwargs):
    try:
        return func(*args)
    except:
        return kwargs.get("default")


import devices.base.constants

from enum import Enum

NUMBER_PUMPS: int = 12
NODE_PREFIX: str = 'pump_'
STATUS_KEY = devices.base.constants.DEVICE_GLOBAL_PARAM_PREFIX + 'status'
MODE_SUFFIX = '_mode'
STEPS_DONE_SUFFIX = '_steps_done'
RPM_SUFFIX = '_rpm'
REV_PER_ML_SUFFIX = '_rev_per_ml'
TUBING_LENGTH_MM_SUFFIX = '_tubing_length_mm'
TUBING_ID_MM_SUFFIX = '_tubing_id_mm'
TUBING_MATERIAL_SUFFIX = '_tubing_material'
BLOCKING_SUFFIX = '_blocking'
BLOCKING_INTERVAL_KEY = 'blocking_interval_s'

ALL_STOPPED = 0x00
ALL_PAUSED = 0xFF

BASE = dict(
    type="PP12",
    number_ports=2*NUMBER_PUMPS,
    number_icons=NUMBER_PUMPS,
    _number_pump_inputs=NUMBER_PUMPS,
)

BASE_DTYPES = dict(
    _status=int.__name__,
    _number_pump_inputs=int.__name__,
)

def update_base_common(base: dict, base_dtypes: dict):
    base.update({
        STATUS_KEY: ALL_STOPPED,
        BLOCKING_INTERVAL_KEY: 0,
    })

    base_dtypes.update({
        STATUS_KEY: int.__name__,
        BLOCKING_INTERVAL_KEY: float.__name__
    })

def update_base(base: dict, base_dtypes: dict, number_pumps: int) -> None:

    for i in range(0, number_pumps):
        base.update({
            devices.base.constants.DEVICE_GLOBAL_PARAM_PREFIX + NODE_PREFIX + str(i) + MODE_SUFFIX: 0,
            devices.base.constants.DEVICE_GLOBAL_PARAM_PREFIX + NODE_PREFIX + str(i) + STEPS_DONE_SUFFIX: 0,
            devices.base.constants.DEVICE_GLOBAL_PARAM_PREFIX + NODE_PREFIX + str(i) + RPM_SUFFIX: 0,
            NODE_PREFIX + str(i) + REV_PER_ML_SUFFIX: 24,
            NODE_PREFIX + str(i) + TUBING_LENGTH_MM_SUFFIX: 121.5,
            NODE_PREFIX + str(i) + TUBING_ID_MM_SUFFIX: 1.,
            NODE_PREFIX + str(i) + TUBING_MATERIAL_SUFFIX: "pharmaline",
            NODE_PREFIX + str(i) + BLOCKING_SUFFIX: 0,
        })
        base_dtypes.update({
            devices.base.constants.DEVICE_GLOBAL_PARAM_PREFIX + NODE_PREFIX + str(i) + MODE_SUFFIX: int.__name__,
            devices.base.constants.DEVICE_GLOBAL_PARAM_PREFIX + NODE_PREFIX + str(i) + STEPS_DONE_SUFFIX: int.__name__,
            devices.base.constants.DEVICE_GLOBAL_PARAM_PREFIX + NODE_PREFIX + str(i) + RPM_SUFFIX: float.__name__,
            NODE_PREFIX + str(i) + REV_PER_ML_SUFFIX: float.__name__,
            NODE_PREFIX + str(i) + TUBING_LENGTH_MM_SUFFIX: float.__name__,
            NODE_PREFIX + str(i) + TUBING_ID_MM_SUFFIX: float.__name__,
            NODE_PREFIX + str(i) + TUBING_MATERIAL_SUFFIX: str.__name__,
            NODE_PREFIX + str(i) + BLOCKING_SUFFIX: int.__name__,
        })

update_base_common(BASE, BASE_DTYPES)
update_base(BASE, BASE_DTYPES, NUMBER_PUMPS)

BASE = {**devices.base.constants.BASE, **BASE}
BASE_DTYPES = {**devices.base.constants.BASE_DTYPES, **BASE_DTYPES}

DeviceBase = Enum('DeviceBase', {k: k for k in BASE.keys()})

DEVICE_TYPE = BASE.get('type')

DISPLAY_NAME = "12 x Peristaltic Pump (" + DEVICE_TYPE + ")"

CATEGORY = "Pumps"

STATUS_STOPPED = 0
STATUS_CLOCKWISE = 1
STATUS_COUNTERCLOCKWISE = 2
STATUS_PAUSED = 3

DIRECTION_MAPPING = dict(
    forward=STATUS_CLOCKWISE,
    f=STATUS_CLOCKWISE,
    cw=STATUS_CLOCKWISE,
    reverse=STATUS_COUNTERCLOCKWISE,
    r=STATUS_COUNTERCLOCKWISE,
    ccw=STATUS_COUNTERCLOCKWISE,
)

DIRECTION_MAPPING.update({
    str(STATUS_CLOCKWISE): STATUS_CLOCKWISE,
    str(STATUS_COUNTERCLOCKWISE): STATUS_COUNTERCLOCKWISE,
    STATUS_CLOCKWISE: STATUS_CLOCKWISE,
    STATUS_COUNTERCLOCKWISE: STATUS_COUNTERCLOCKWISE,
})

RPM = 0
UL_MIN = 1
UL_HR = 2
ML_MIN = 3
ML_HR = 4

RATE_UNIT_MAPPING = dict(
    rpm=RPM,
    ul_min=UL_MIN,
    ul_hr=UL_HR,
    ml_min=ML_MIN,
    ml_hr=ML_HR,
)

RATE_UNIT_MAPPING.update({
    "ul/min": UL_MIN,
    "ul/hr": UL_HR,
    "ml/min": ML_MIN,
    "ml/hr": ML_HR,
    str(RPM): RPM,
    str(UL_MIN): UL_MIN,
    str(UL_HR): UL_HR,
    str(ML_MIN): ML_MIN,
    str(ML_HR): ML_HR,
    RPM: RPM,
    UL_MIN: UL_MIN,
    UL_HR: UL_HR,
    ML_MIN: ML_MIN,
    ML_HR: ML_HR,
})

VALID_RATE_UNITS = set(RATE_UNIT_MAPPING.keys())

MODE_NOT_SET = -1
MODE_CONTINUOUS = 0
MODE_FINITE = 1

MODE_MAPPING = dict(
    continuous=MODE_CONTINUOUS,
    c=MODE_CONTINUOUS,
    finite=MODE_FINITE,
    f=MODE_FINITE,
)

MODE_MAPPING.update({
    str(MODE_CONTINUOUS): MODE_CONTINUOUS,
    str(MODE_FINITE): MODE_FINITE,
    MODE_FINITE: MODE_FINITE,
    MODE_CONTINUOUS: MODE_CONTINUOUS,
})

STEPS_PER_REV = 200
MAX_MICROSTEPS = 2147483648
MICROSTEPS_PER_STEP = 256

STEPS = 0
SECONDS = 1
MINUTES = 2
DEGREES = 3
ML = 4
UL = 5
REVOLUTIONS = 6

FINITE_UNIT_MAPPING = dict(
    steps=STEPS,
    seconds=SECONDS,
    minutes=MINUTES,
    degrees=DEGREES,
    ml=ML,
    ul=UL,
    s=SECONDS,
)

FINITE_UNIT_MAPPING.update({
    str(STEPS): STEPS,
    str(SECONDS): SECONDS,
    str(MINUTES): MINUTES,
    str(DEGREES): DEGREES,
    str(UL): UL,
    str(ML): ML,
    str(REVOLUTIONS): REVOLUTIONS,
    STEPS: STEPS,
    SECONDS: SECONDS,
    MINUTES: MINUTES,
    DEGREES: DEGREES,
    UL: UL,
    ML: ML,
    REVOLUTIONS: REVOLUTIONS,
})

VALID_FINITE_UNITS = set(FINITE_UNIT_MAPPING.keys())

AUTO_STOP_EXPR_STR = ""
for i in range(0, NUMBER_PUMPS):
    prepend = "" if i == 0 else " and "
    AUTO_STOP_EXPR_STR += "{}((int(S)>>(2*{}))&3) == {}".format(prepend, i, STATUS_STOPPED)

AUTO_STOP_EXPR_CONSTANT = "S"

del i


#!/usr/bin/env python
# coding: utf-8

# In[4]:

#Sort an array of 0s, 1s and 2s we have given an array and we have to sort it
# apporach 1:
def sort_0_1_2(arr):
    arr.sort()       ### this is a built-in function of python to sort an array

    return arr      #### here sorting takes O(nlogN) time , but we can optimize it .
obj=sort_0_1_2([1,0,0,2,1,0,0,2])
print(obj)

# In[9]:

#apporach 2
           ### " DUTCH NATIONAL FLAG ALGORITHM "
## here we use iteration method ,in which something that is less to an specific value comes on left side and grater value comes on right and rest is eual to our assumption so it remain in middle
def sort_0_1_2(arr):
    low=0
    mid=0
    high=len(arr)-1
    while mid<=high:
        if arr[mid]==0:
            arr[mid],arr[low]=arr[low],arr[mid]   ### here we swapped both number and increment mid and low to its next value
            mid=mid+1
            low=low+1
        if arr[mid]==1:
            mid=mid+1                 # nothing to change we want to put 1 in between 0 and 2 so we are on that , so increment needed only
        if arr[mid]==2:
            arr[mid],arr[high]=arr[high],arr[mid]
            high=high-1         ### this part indicating that you swapped 2 on the right side so now check 1 less part of array
    return arr
print(sort_0_1_2([1,0,0,2,1,0,0,2,0,0,1,1,2,2,1,1,2,1,1,1,1,1,1,1,1,0,0,0,0,0,0,2,2,2,2,2,1,1,1,1,1]))

# In[ ]:

problem 3  Sort an array of 0s, 1s and 2s.py


def Fill100():
    l = []
    for i in range(101):
        l.append(i)
    return l

def SumOfSquare(l):
    s = 0
    for i in range(len(l)):
        l[i] = l[i]**2
    s = sum(l)
    return s
def SquareOfTheSum(l):
    s = 0
    for i in l:
        s += i
    s = s**2
    return s

prime = Fill100()
s1 = SquareOfTheSum(prime)

s2 = SumOfSquare(prime)
print(s1 - s2)


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

#####################################################
#                                                   #
#           INDEXACIÓN Y RECUPERACIÓN DE            #
#                    IMÁGENES                       #
#           Mª del Mar Alguacil Camarero            #
#                                                   #
#####################################################

import cv2
import unittest
import numpy as np
from matplotlib import pyplot as plt
from math import exp, ceil, floor, sqrt
from funciones import *
from auxFunc import *

############################
# EJERCICIO 1
############################

# EMPAREJAMIENTO DE DESCRIPTORES
# Leer parejas de imágenes que tengan partes de escena comunes.
# Haciendo uso de una máscara binaria o de las funciones extractRegion() y
# clickAndDraw(), seleccionar una región en la primera imagen que esté presente
# en la segunda imagen. Para ello solo hay que fijar los vértices de un polígono que contenga a la región.
# Extraiga los puntosSIFT contenidos en la región seleccionada de la primera
# imagen y calcule las correspondencias con todos los puntos SIFT de la segunda
# imagen. Pinte las correspondencias encontrados sobre las imágenes. Jugar con
# distintas parejas de imágenes y decir que conclusiones se extraen de los
# resultados obtenidos con respecto a la utilidad de esta aproximación
# en la recuperación de imágenes a través de descriptores.

def emparejamiento(filenames, leer=True):
    # Leemos y pasamos las imágenes a blanco y negro
    if leer:
        print(filenames[0])
        img1 = cv2.imread(filenames[0])
        img2 = cv2.imread(filenames[1])
    else:
        img1 = filenames[0]
        img2 = filenames[1]

    gray1 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)

    # Seleccionamos las regiones que queremos tener en cuenta
    region1 = extractRegion(gray1)
    region2 = extractRegion(gray2)

    # Calculamos las máscaras que deben ser del mismo tamaño que las respectivas
    # imágenes.
    img_nula1 = np.zeros(gray1.shape)
    mask1 = cv2.fillConvexPoly(img_nula1, np.asarray(region1), 255)

    img_nula2 = np.zeros(gray2.shape)
    mask2 = cv2.fillConvexPoly(img_nula2, np.array(region2), 255)

    # Calculamos los keypoints SIFT con dicha máscara y dibujamos las distintas
    # imágenes con las correspondencias obtenidas.
    emparejarSift([img1, img2], dibujar=True, leer=False, N=100, M=-1, f=0.65,
                    mask1=np.array(mask1, dtype=np.uint8),
                    mask2=np.array(mask2, dtype=np.uint8), ej1=False)

############################
# EJERCICIO 2
############################
#VISUALIZACIÓN DEL VOCABULARIO
# Usando las imágenes dadas se han extraido regiones de cada imagen y se ha
# construido un vocabulario de palabras usando k-means. Se han extraído de
# forma directa las regiones imágenes asociadas y se han re-escalado. Elegir al
# menos dos palabras visuales diferentes y visualizar las regiones imagen de los
# N parches más cercanos de cada palabra visual, de forma que se muestre el
# contenido visual que codifican.
def visVocabulario(vocabulario, regiones, p1, p2, N=15):
    # Leemos los ficheros
    descriptores, patches = loadAux(regiones, True)
    precision, etiquetas, palabras = loadDictionary(vocabulario)

    # Pasamos los parches a blanco y negro
    parches = []
    for patch in patches:
        parches.append(cv2.cvtColor(patch,cv2.COLOR_BGR2GRAY))

    # Matriz con las etiquetas(cluster al que pertenece) y la posición de los descriptores y los parches
    tam = len(parches)
    labels = np.squeeze(np.asarray((etiquetas)))[0:tam]
    labels = np.array([labels, list(range(tam))]).T

    labelsP1 = labels[np.where(labels[:,0] == p1)][:,1]
    labelsP2 = labels[np.where(labels[:,0] == p2)][:,1]

    # Normalizamos los descriptores para que tengan norma cuadrática igual a uno
    norma = np.sqrt((descriptores**2).sum(axis=1))
    norma = np.matrix([norma]*descriptores.shape[1]).T

    descriptores = np.array(np.divide(descriptores, norma))

    # Vector distancias
    distanciasP1 = np.matrix(palabras[p1]) * descriptores[labelsP1].T
    distanciasP1 = np.squeeze(np.asarray(distanciasP1))
    distanciasP2 = np.matrix(palabras[p2]) * descriptores[labelsP2].T
    distanciasP2 = np.squeeze(np.asarray(distanciasP2))

    # Matriz que contiene las distancias calculadas y la posición asociada
    distPosP1 = np.array([distanciasP1, labelsP1]).T
    distPosP2 = np.array([distanciasP2, labelsP2]).T

    # Ordenamos las distancias
    distPosP1 = distPosP1[distPosP1[:, 0].argsort()]
    distPosP1 = distPosP1[::-1]
    distPosP2 = distPosP2[distPosP2[:, 0].argsort()]
    distPosP2 = distPosP2[::-1]

    # Extraemos los índices de los N parches más cercanos
    S = min(N, distPosP1.shape[0])
    indices1 = np.array(distPosP1[0:S,1], dtype = np.int32)
    T = min(N, distPosP2.shape[0])
    indices2 = np.array(distPosP2[0:T,1], dtype = np.int32)

    # Convertimos la lista de parches en un array
    parches = np.array(parches)

    # Visualizar las regiones imagen de los N parches más cercanos de cada palabra visual
    visualization(parches[indices1], ['']*S, 3, S/3, color = False)
    visualization(parches[indices2], ['']*T, 3, T/3, color = False)

# Varianza de la palabra deseada
def varianza(descriptores, palabra):
    varianzas = np.squeeze(np.asarray(palabra*descriptores.T))

    return max(varianzas)

# Seleccionamos las num_palabras con menor dispersión
def varianzas(vocabulario, regiones, num_palabras=2):
    # Leemos los ficheros
    descriptores, parches = loadAux(regiones, True)
    precision, etiquetas, palabras = loadDictionary(vocabulario)

    # Normalizamos los descriptores para que tengan norma cuadrática igual a uno
    norma = np.sqrt((descriptores**2).sum(axis=1))
    norma = np.matrix([norma]*descriptores.shape[1]).T

    descriptores = np.array(np.divide(descriptores, norma))

    # Matriz con las etiquetas, los descriptores y los parches
    tam = len(parches)
    labels = np.squeeze(np.asarray((etiquetas)))[0:tam]
    labels = np.array([labels, list(range(tam))]).T

    # Varianzas de los distintos clusters
    N = palabras.shape[0]
    var = [None]*N
    for p in range(N):
        labelsP = labels[np.where(labels[:,0] == p)][:,1]
        var[p] = varianza(descriptores[labelsP], np.matrix(palabras[p]))
    var = np.array([var, list(range(N))]).T
    var = var[var[:, 0].argsort()]
    var = var[::-1]

    # Devolvemos los índices de las palabras
    return np.array(var[:num_palabras, 1], dtype=int)

############################
# EJERCICIO 3
############################

# RECUPERACIÓN DE IMÁGENES
# Implementar un modelo de índice invertido + bolsa de palabras para las imágenes
# dadas en imagenesIR.rar usando el vocabulario.
# Verificar que el modelo construido para cada imagen permite recuperar imágenes
# de la misma escena cuando la comparamos al resto de imágenes de la base de datos.
# Elegir dos imágenes-pregunta en las que se ponga de manifiesto que el modelo
# usado es realmente muy efetivo para extraer sus semejantes y elegir otra
# imagen-pregunta en la que se muestre que el modelo puede realmente fallar.
# Para ello muestre las cinco imágenes más semejantes de cada una de las
# imágenes-pregunta seleccionadas usando como medida de distancia el producto
# escalar normalizado de sus vectores de bolsa de palabras.

# Para todas las imagenes les saco los descriptores, bolsa de palabras para cada una
# fichero invertido:
def ficheroInvertido(filenames, vocabulario, umbral = 1.7):
    # Leemos todas la imagenes
    imagenes = []
    for file in filenames:
        imagenes.append(cv2.imread(file, 0))

    # Leemos el vocabulario
    precision, etiquetas, palabras = loadDictionary(vocabulario)

    # Inicializamos SIFT
    sift = cv2.xfeatures2d.SIFT_create()

    # Detectamos los keypoint y extraemos los descriptores de las distintas imágenes
    desc = []
    for img in imagenes:
        kpts, dcts = sift.detectAndCompute(img, None)
        desc.append(dcts)

    # Creamos una tabla de indice invertido de tamaño igual al número de palabras
#    fichero = np.empty(palabras.shape[0], dtype='O') # 'O' -> (Python) objects
    fichero = [np.copy([])]*palabras.shape[0]
    for j, descriptor in enumerate(desc):
        # Normalizamos los descriptores
        max_desc = np.max(descriptor)
        descriptor = np.matrix(descriptor/max_desc)

        # Matriz de distancias
        distancia = palabras*descriptor.T

        # Seleccionamos la distancia mayor
        # Máximo de cada fila (posición)
        maximos = np.argmax(distancia, axis=0)

        for i in range(maximos.shape[1]):
            maximo = maximos[0,i]
            if distancia[maximo,i] > umbral:
                fichero[maximo] = np.append(fichero[maximo], j)

    # BOLSA DE PALABRAS
    N = len(imagenes)
    # Incializamos los histogramas con 0's
    histogramas = np.zeros((N, len(fichero)))
    for j, palabra in enumerate(fichero):
        if len(palabra)!=0: # Si existe alguna imagen con esa palabra
            palabra = np.array(palabra)
            for i in range(N):
                histogramas[i,j] = len(np.where(palabra==i)[0])

    # Normalizamos el histograma
    for i in range(N):
        maxi = max(histogramas[i])
        histogramas[i] /= maxi

    return histogramas

def recuperacion(filenames, vocabulario, indice, N=5):
    histogramas = ficheroInvertido(filenames, vocabulario)
    # Comparamos histogramas y elegimos las N imagenes mas parecidas
    errores = []
    h = histogramas[indice]
    for i,g in enumerate(histogramas):
        if i!=indice:
            e = np.dot(g, h)/(sqrt(np.dot(g, g))*sqrt(np.dot(h, h)) )
            errores.append((e,i))

    errores.sort(key=lambda x: x[0], reverse=True)

    mejores = list(map(lambda x: x[1], errores[0:N]))

    hist = [histogramas[indice]]
    img = [cv2.imread(filenames[indice])]
    for i in range(N):
        ind = mejores[i]
        img.append( cv2.imread(filenames[ind]) )
        hist.append( histogramas[ind] )

    # Visualizamos las distintas imagenes y los histogramas asociados
    visualization(img, ['']*(N+1), 2, (N+1)/2, color = True)
    visualization(hist, ['']*(N+1), 2, (N+1)/2, plot=True)

class TestPractica3(unittest.TestCase):
    def setUp(self):
        pass

     # EJERCICIO 1
    def test_emparejamiento(self):
        filename = ['./imagenes/36.png','./imagenes/50.png']
        emparejamiento(filename)

     # EJERCICIO 2
    def test_visVocabulario(self):
        vocabulario = 'kmeanscenters5000.pkl'
        regiones = 'descriptorsAndpatches.pkl'

        palabras = varianzas(vocabulario, regiones)
        #print(palabras)
        visVocabulario(vocabulario, regiones, palabras[0], palabras[1] )

        palabra1 = 1662
        palabra2 = 500
        visVocabulario(vocabulario, regiones, palabra1, palabra2 )

    # EJERCICIO 3
    def test_recuperacion(self):
        vocabulario = 'kmeanscenters5000.pkl'
        filenames = []
        for i in range(440):
            filenames.append('./imagenes/'+str(i)+'.png')

        recuperacion(filenames, vocabulario, 2)

if __name__ == '__main__':
    unittest.main()


import sys
import actionlib
import rospy
from rofunc_ros.msg import SpeechAction, SpeechGoal

if __name__ == '__main__':
    rospy.init_node('tts_action_client')
    client = actionlib.SimpleActionClient('tts', SpeechAction)
    client.wait_for_server()

    goal = SpeechGoal()

    print(sys.argv[1])
    goal.text = str(sys.argv[1]) if len(sys.argv) > 1 else 'I got no idea.'
    goal.metadata = str(sys.argv[2]) if len(sys.argv) > 2 else ''

    print(goal)

    client.send_goal(goal)
    client.wait_for_result()
    print('\n' + client.get_result().response)


import itertools
import random

from datetime import datetime
from dateutil.relativedelta import relativedelta

from odoo import fields
from odoo.addons.mail.tests import common as mail_test

class TestDigestCommon(mail_test.MailCommon):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        cls.company_1 = cls.env.company
        cls.company_2 = cls.env['res.company'].create({'name': 'Digest Company 2'})

        context = {
            'start_datetime': datetime.now() - relativedelta(days=1),
            'end_datetime': datetime.now() + relativedelta(days=1),
        }

        cls.all_digests = cls.env['digest.digest'].with_context(context).create([{
            'name': 'Digest 1',
            'company_id': cls.env.company.id,
            'kpi_mail_message_total': True,
            'kpi_res_users_connected': True,
            'periodicity': 'daily',
        }, {
            'name': 'Digest 2',
            'company_id': cls.company_2.id,
        }, {
            'name': 'Digest 3',
            'company_id': False,
        }])

        cls.digest_1, cls.digest_2, cls.digest_3 = cls.all_digests

    @classmethod
    def _setup_messages(cls):
        """ Remove all existing messages, then create a bunch of them on random
        partners with the correct types in correct time-bucket:

        - 3 in the previous 24h
        - 5 more in the 6 days before that for a total of 8 in the previous week
        - 7 more in the 20 days before *that* (because digest doc lies and is
          based around weeks and months not days), for a total of 15 in the
          previous month
        """
        # regular employee can't necessarily access "private" addresses
        partners = cls.env['res.partner'].search([])
        messages = cls.env['mail.message']
        counter = itertools.count()

        now = fields.Datetime.now()
        for count, (low, high) in [
            (3, (0 * 24, 1 * 24)),
            (5, (1 * 24, 7 * 24)),
            (7, (7 * 24, 27 * 24)),
        ]:
            for __ in range(count):
                create_date = now - relativedelta(hours=random.randint(low + 1, high - 1))
                messages += random.choice(partners).message_post(
                    author_id=cls.partner_admin.id,
                    body=f"Awesome Partner! ({next(counter)})",
                    email_from=cls.partner_admin.email_formatted,
                    message_type='comment',
                    subtype_xmlid='mail.mt_comment',
                    # adjust top and bottom by 1h to avoid overlapping with the
                    # range limit and dropping out of the digest's selection thing
                    create_date=create_date,
                )
        cls.env.flush_all()


#Kirjoita ohjelma, joka hakee ja tulostaa satunnaisen Chuck Norris -vitsin käyttäjälle. Käytä seuravalla sivulla
#esiteltävää rajapintaa: https://api.chucknorris.io/. Käyttäjälle on näytettävä pelkkä vitsin teksti.

import json
import requests

hakusana = input("Anna hakusana: ")

# Pyynnön malli: https://api.tvmaze.com/search/shows?q=girls
pyyntö = "https://api.tvmaze.com/search/shows?q=" + hakusana

try:
    vastaus = requests.get(pyyntö)
    if vastaus.status_code==200:
        json_vastaus = vastaus.json()
        print(f"Löytyi {len(json_vastaus)} kpl sarjoja")
        print(json.dumps(json_vastaus[0], indent=2))
        for a in json_vastaus:
            print(a["show"]["name"])
except requests.exceptions.RequestException as e:
    print ("Hakua ei voitu suorittaa.")

# print(json_vastaus[0]["show"]["name"])


#!/usr/bin/env python3

import numpy as np
import pydrake.all
from pydrake.all import (
    DiagramBuilder,
    RigidTransform,
    RollPitchYaw,
    RotationMatrix,
    Role,
    ConnectMeshcatVisualizer,
)
from panda_station import *

DIRECTIVE = "directives/video.yaml"
NAMES_AND_LINKS = [
    (name, "base_link") for name in parse_tables(find_resource(DIRECTIVE))
]

if __name__ == "__main__":
    builder = DiagramBuilder()
    station = PandaStation(name = "placement_station")
    station.setup_from_file(DIRECTIVE, names_and_links=NAMES_AND_LINKS)
    station.add_panda_with_hand(
        blocked=True, X_WB = RigidTransform(RotationMatrix(), [1000.00, 0, 0.0])
    )
    plant = station.get_multibody_plant()
    station.finalize()
    builder.AddSystem(station)
    scene_graph = station.get_scene_graph()
    zmq_url = "tcp://127.0.0.1:6001"
    v = ConnectMeshcatVisualizer(
        builder,
        scene_graph,
        output_port=station.GetOutputPort("query_object"),
        delete_prefix_on_load=True,
        zmq_url=zmq_url,
        #role = Role.kProximity
    )
    v.load()
    diagram = builder.Build()
    diagram_context = diagram.CreateDefaultContext()
    diagram.Publish(diagram_context)


from django.core.handlers.wsgi import WSGIRequest
from django.shortcuts import render
from random import randint

from play_cat.views.base import cat

def action_view(request):
    if request.POST.get('cat_name') is None:
        cat.cat_name = cat.cat_name
    else:
        cat.cat_name = request.POST.get('cat_name')
    cat.action = request.POST.get('action')
    cat.state = calculating_state_of_cat()
    cat.image = set_state_image()
    context = {
        'cat_name': cat.cat_name,
        'age': cat.age,
        'satiety': cat.satiety,
        'happiness': cat.happiness,
        'image': cat.image
    }
    return render(request, 'action_page.html', context)

def sleep_state():
    cat.state = 'sleep'
    return cat.state

def feed_state():
    if cat.state == 'sleep':
        return cat.state
    else:
        if cat.happiness == 100:
            cat.state = 'happy'
        if cat.satiety == 100:
            if cat.happiness - 30 < 0:
                cat.happiness = 0
                cat_state='angry'
            else:
                cat.happiness -= 30
            return cat.state
        if cat.satiety + 15 > 100:
            cat.happiness -= 30
            if cat.happiness < 0:
                cat.happiness = 0
            cat.satiety = 100
            cat.state = 'happy'
        else:
            cat.satiety += 15
            if cat.happiness + 5 > 100:
                cat.happiness = 100
            else:
                cat.happiness += 5
        cat.state == 'not_sleep'

def play_state():
    if cat.action == 'play with cat':
        if cat.state == 'sleep':
            cat.state = 'not_sleep'
            if cat.happiness - 5 > 0:
                cat.happiness -= 5
            else:
                cat.happiness = 0
        else:
            cat.state = 'play'
            angry_chance = randint(1, 3)
            if angry_chance == 3:
                cat.happiness = 0
                cat.state = 'angry'
            else:
                if cat.happiness + 15 > 100:
                    cat.happiness = 100
                    cat.state='happy'
                    if cat.satiety - 10 < 0:
                        cat.satiety = 0
                    else:
                        cat.satiety -= 10
                else:
                    cat.happiness += 15
                    cat.satiety -= 10
                    cat.state='happy'
    return cat.state

def calculating_state_of_cat():
    if cat.action == 'put cat to sleep':
        return sleep_state()
    elif cat.action == 'feed cat':
        return feed_state()
    else:
        return play_state()

def set_state_image():
    if cat.state=="happy":
        return 'img/happy.jpeg'
    elif cat.state == "angry":
        return 'img/angry.jpeg'
    elif cat.state =='sleep':
        return 'img/tired.jpeg'
    else:
        return 'img/day_mood.png'

    if 0<=cat.satiety<=30:
        return 'img/angry.jpeg'
    else:
        return 'img/day_mood.png'


# Purpose of this code is to create hangman game
# Project 1
# 6.21.2019
# Kevin Kim

import random

def findandreplace(word, letter):
    output = ""
    i = 0
    for char in word:
        if char == letter:
            output = output + letter
        else:
            output = output + hud[i]
        i += 1
    return output;

words = ["apple", "banana", "carrot", "cranberry"]
lives = 7
solution = random.choice(words)
hud = "";
i=0;
guess = ""
while i < len(solution):
    hud += "*"
    i = i + 1

while lives > 0:
    print("Guesses left: " + str(lives))
    print("Your current word: " + hud)
    guess = input("Enter a guess of a letter: ").lower()
    if solution.find(guess) != -1 and guess != "":
        print("correct!")
        hud = findandreplace(solution, guess)
    else:
        print("Ur WroNG XD!")
        lives-=1
    if hud.find("*") == -1:
        print("you win!")
        break

print("game over! Word was: " + solution)


from asyncio import AbstractEventLoop
from math import atan2, degrees
import time
from EB23_Enums.GEM_enums import ActionStatus, ActionTimings
from GP_Interface import GameAction
from .action_clients import ActionClientManager
from turag_interfaces.msg import Pose
import asyncio
from rclpy.node import Node
from action_msgs.msg import GoalStatus
import rclpy
from gem.field_state import FieldState

logger = rclpy.logging.get_logger("GPA_DriveToPlate")

class DriveToPlate(GameAction):
    """
    Interface for Drive to Plate game action.

    !!! ACHTUNG: A team with multiple robots can only validate this action if both robots are in the same dropping area. !!!
    """

    def __str__(self) -> str:
        return "DriveToPlateAction"

    def requiredProperties(self):
        properties = {}
        properties["clients"] = [
            "CalculateGridPath",
            "CalculateSplinePath",
            "RecalculatePath",
            "DriveEmergencyStop",
            "DriveForce",
            "DrivePath",
            "DriveRelease",
            "DriveSoftStop",
            "DriveToPose",
            "ReconnectLMC",
            "DriveGridPath",
            "MoveArm",
        ]
        return properties

    def setup(self, config, requiredActions, loop: AbstractEventLoop, node: Node):
        self.clientManager = ActionClientManager(node)

        self.CalculateGridPathClient = requiredActions["CalculateGridPath"]
        self.CalculateSplinePathClient = requiredActions["CalculateSplinePath"]
        self.RecalculatePathClient = requiredActions["RecalculatePath"]
        self.DriveEmergencyStopClient = requiredActions["DriveEmergencyStop"]
        self.DriveForceClient = requiredActions["DriveForce"]
        self.DrivePathClient = requiredActions["DrivePath"]
        self.DriveReleaseClient = requiredActions["DriveRelease"]
        self.DriveSoftStopClient = requiredActions["DriveSoftStop"]
        self.DriveToPoseClient = requiredActions["DriveToPose"]
        self.DriveGridPathClient = requiredActions["DriveGridPath"]
        self.ReconnectLMCClient = requiredActions["ReconnectLMC"]
        self.MoveArmClient = requiredActions["MoveArm"]

        self.x = config["x"]
        self.y = config["y"]
        self.rot = config["rot"]

        self.node = node
        self.loop = loop
        return

    async def checkExecutability(self, robotstate, fieldstate: FieldState) -> bool:
        logger.info("Checking executability of DriveToPlate")
        if (
            time.time() > fieldstate.ending_time - fieldstate.ending_offset
            or time.time() < fieldstate.ending_time - 90
        ):
            logger.info(f"{fieldstate.ending_time - time.time()}")
            return False

        if robotstate.get_has_reached_ending_plate():
            self.node.get_logger("Already reached Ending Plate")
            return False

        self.robotstate = robotstate
        self.fieldstate = fieldstate

        if self.x != None:
            self.ending_plate_list = [[self.x, self.y, self.rot]]
        else:
            self.ending_plate_list = []

        calc_plates = self.fieldstate.calculate_nearest_ending_plate(
            self.robotstate.get_position()
        )

        if calc_plates == None and len(self.ending_plate_list) == 0:
            logger.info("No ending plate found")
            return True

        if len(self.ending_plate_list) == 0:
            self.ending_plate_list = calc_plates
        elif calc_plates != None:
            for calc_plate in calc_plates:
                self.ending_plate_list.append(calc_plate)

        for self.ending_plate in self.ending_plate_list:
            self.x = float(self.ending_plate[0])
            self.y = float(self.ending_plate[1])

            if len(self.ending_plate) == 2:
                self.calculate_new_rotation()

            goal_pose = Pose()
            goal_pose.x = float(self.x)
            goal_pose.y = float(self.y)
            goal_pose.angle = float(self.rot)

            ### path available check
            calc_result, status = await self.loop.create_task(
                self.clientManager.send_calculate_grid_path(
                    self.CalculateGridPathClient, goal_pose
                )
            )

            if status == GoalStatus.STATUS_SUCCEEDED and calc_result.success:
                return True

        # if status != GoalStatus.STATUS_SUCCEEDED or not calc_result.success:
        #    self.fieldstate.calculate_nearest_plate(self.robotstate.position)

        # if time.time() > (
        #    self.fieldstate.ending_time - fieldstate.needed_time_for_return_s
        # ):
        #    logger.info("Not enough time for DriveToPlate")
        #    return False

        return False

    async def preProcess(self, **kw_args):
        return ActionStatus.SUCCEEDED

    async def process(self, **kw_args):
        self.calculate_new_rotation()
        goal_pose = Pose()
        goal_pose.x = float(self.x)
        goal_pose.y = float(self.y)
        goal_pose.angle = float(self.rot)

        calc_result, status = await self.loop.create_task(
            self.clientManager.send_calculate_grid_path(
                self.CalculateGridPathClient, goal_pose
            )
        )

        if status == GoalStatus.STATUS_SUCCEEDED and calc_result.success:
            drive_result, drive_status = await self.loop.create_task(
                self.clientManager.send_drive_grid_path(
                    self.DriveGridPathClient, calc_result.path
                )
            )
        else:
            drive_status = GoalStatus.STATUS_ABORTED

        # logger.info(str(status))

        while drive_status == GoalStatus.STATUS_ABORTED and self.is_enough_time():
            # TODO maybe use recalculate here:

            if not self.is_enough_time():
                return ActionStatus.ABORTED

            calc_result, status = await self.loop.create_task(
                self.clientManager.send_calculate_grid_path(
                    self.CalculateGridPathClient, goal_pose
                )
            )
            if status == GoalStatus.STATUS_SUCCEEDED and calc_result.success:
                ### TODO remove:
                drive_task = self.loop.create_task(
                    self.clientManager.send_drive_grid_path(
                        self.DriveGridPathClient, calc_result.path
                    )
                )
                # drive_task = self.loop.create_task(
                # self.clientManager.send_drive_path(
                # self.DrivePathClient, calc_result.path
                #    )
                # )
                _, drive_status = await drive_task

        if drive_status == GoalStatus.STATUS_SUCCEEDED:
            if self.robotstate.name == "BotA":
                self.fieldstate.add_points(15)
                self.robotstate.set_has_reached_ending_plate(True)
            return ActionStatus.SUCCEEDED

        if drive_status == GoalStatus.STATUS_ABORTED:
            if self.fieldstate._is_current_bot_position_equal_to_one_of_our_plates(
                self.robotstate.get_position()[:2]
            )[0]:
                self.robotstate.set_has_reached_ending_plate(True)
                ## TODO Add check if cakes are in our plate
                if self.robotstate.name == "BotA":
                    self.fieldstate.add_points(15)
                return ActionStatus.SUCCEEDED
            else:
                return ActionStatus.FAILED

        return ActionStatus.FAILED

    async def postProcess(self, **kw_args):
        open_arm_task = self.loop.create_task(
            self.clientManager.send_move_arm(self.MoveArmClient, "open")
        )

        await open_arm_task
        return ActionStatus.SUCCEEDED

    def is_enough_time(self):
        if time.time() > self.fieldstate.ending_time - self.fieldstate.ending_offset:
            return False
        return True

    def calculate_new_rotation(self):
        if self.rot == None:
            position = self.robotstate.get_position()
            self.rot = degrees(
                atan2(
                    self.y - position[1],
                    self.x - position[0],
                )
            )
        else:
            self.rot = float(self.rot)


from flask import request, jsonify
from json import dumps
import webserver, json, os

def recover_format():
    format = {"peers" : [], "pending_peers" : [], "peer_amount" : 0}
    if(os.path.getsize("peers.json") == 0):
        with open("peers.json", "w") as peers_write:
            json.dump(format, peers_write)

class API:
    def __init__(self):
        self.peers_json = json.load(open("peers.json", "r"))

    def save_peerlist(self):
        open("peers.json", "w").write(dumps(self.peers_json)) # updating peer_json for other funcs

    def check_peer(self, peer, remove = False):
        it = 0
        for peer in self.peers_json["peers"]:
            if peer == request.remote_addr:
                if remove:
                    self.peers_json["peers"].pop(it)
                return False
            it += 1
        return True # Returning true if not in JSON file

    def check_pend_peer(self, peer, remove = False):
        it = 0
        for peer in self.peers_json["pending_peers"]:
            if peer == request.remote_addr:
                if remove:
                    self.peers_json["pending_peers"].pop(it)
                return False
            it += 1
        return True # Returning true if not in JSON file

    def check_pending(self, pend_miner):
        for pend in self.peers_json["pending_peers"]:
            if pend == request.remote_addr:
                return False

        return True # Returning true if not in JSON file

    def add_peer(self):
        if self.check_peer(request.remote_addr) == False:
            return jsonify({"status" : 203, "message" : "SIGNED"}) # IP addr is in json file, denied
        self.peers_json["peer_amount"] += 1
        self.peers_json["peers"].append(str(request.remote_addr))
        open("peers.json", "w").write(json.dumps(self.peers_json)) # dumping all changes to file
        self.save_peerlist()
        return jsonify({"status" : 200, "message" : "SUCCESS"})

    def add_pending_peer(self): # same code as add_peer() with minor changes
        if self.check_peer(request.remote_addr) == False:
            return jsonify({"status" : 203, "message" : "SIGNED"})
        self.peers_json["pending_peers"].append(str(request.remote_addr))
        open("peers.json", "w").write(json.dumps(self.peers_json))
        self.save_peerlist()
        return jsonify({"status" : 200, "message" : "SUCCESS"})

    def remove_pending_peer(self):
        if self.check_pend_peer(request.remote_addr, True) == True:
            return jsonify({"status" : "203", "message" : "UNKNOWN"})
        self.peers_json["peer_amount"] -= 1
        self.save_peerlist()
        return jsonify({"status" : 200, "message" : "SUCCESS"})

    def remove_peer(self):
        if self.check_pend_peer(request.remote_addr, True) == True:
            return jsonify({"status" : "203", "message" : "UNKNOWN"})
        self.peers_json["peer_amount"] -= 1
        self.save_peerlist()
        return jsonify({"status" : 200, "message" : "SUCCESS"})

    def get_peers(self):
        return str(json.dumps(self.peers_json["peers"]))

    def retrieve_peer_amount(self):
        return str(self.peers_json["peer_amount"])

    def retrieve_pending_peers(self):
        return str(json.dumps(self.peers_json["pending_peers"]))

if(__name__ == '__main__'):
    recover_format()
    webserver.server().start()


from api.models import TODOItem, TODOList
from rest_framework import viewsets, status
from rest_framework.decorators import list_route
from rest_framework.response import Response

from api.serializers import TODOItemSerializer, TODOListSerializer

class TODOItemViewSet(viewsets.ModelViewSet):
    queryset = TODOItem.objects.all().order_by('-created_at')
    serializer_class = TODOItemSerializer

    @list_route(methods=['delete'])
    def bulk_delete(self, request, *args, **kwargs):
        try:
            ids = request.query_params.get('ids').split(',')
            TODOItem.objects.filter(pk__in=ids).delete()
            return Response({'status': 'ok'})
        except AttributeError:
            return Response(status=status.HTTP_400_BAD_REQUEST)

class TODOListViewSet(viewsets.ModelViewSet):
    queryset = TODOList.objects.all().order_by('-created_at')
    serializer_class = TODOListSerializer


import numpy as np
import os
import minimal_pipe_mit5k
import tmp2tiff

_MIT_5K_ROOT = "/media/shared/data/MIT-Adobe-FiveK/fivek_dataset/raw_photos"
_DST_ROOT = "/media/shared/data/acr_hyperparams_mit5k_sweep/contrast_sweep"

# 0 rawprepare
# 1 temperature      *
# 2 highlights       *
# 3 demosaic
# 4 flip             *
# 5 exposure         *
# 6 colorin
# 7 sharpen          *
# 8 colorbalancergb  *
# [skip] 9 filmicrgb *
# 10 colorout
def convert_tmp2tiff(src_dir, dst_prefix):
    for stage in [
            'temperature_bayer',
            'highlights_bayer',
            'colorbalancergb',
            'exposure',
            'colorin',
            'sharpen',
            'colorbalancergb',
            'colorout'
    ]:
        for suffix in ["in", "out"]:
            in_file = os.path.join(src_dir, stage) + f'_{suffix}.tmp'
            out_file = f'{dst_prefix}_{stage}_{suffix}.tif'
            print(f"Converting {in_file} -> {out_file}")
            tmp2tiff.tmp2tiff(in_file, out_file)

def get_sorted_src_paths():
  src_paths = []
  for dir, subdir, files in os.walk(_MIT_5K_ROOT):
    for file in files:
      if file.endswith('.dng'):
        src_paths.append(os.path.join(dir, file))
  return sorted(src_paths)

def main():
  src_paths = get_sorted_src_paths()
  # print('basename: ', os.path.basename(src_paths[0]))

  start_idx = 0
  num_tasks = 1000

  for i in range(start_idx, start_idx + num_tasks):
    src_dng_path = src_paths[i]
    print(f"Reading: {src_dng_path}")
    base_name = os.path.basename(src_dng_path)

    raw_prepare_params, temperature_params = minimal_pipe_mit5k.read_dng_params(src_dng_path)
    print(raw_prepare_params, temperature_params)

    for contrast in np.linspace(-0.5, 0.9, 7):
      dst_prefix = f"{_DST_ROOT}/contrast_sweep/{base_name}_contrast=[{contrast:.3f}]"
      dst_png_path = dst_prefix + ".png"

      if os.path.exists(dst_png_path):
        print(f"Skipping: {dst_png_path} because it already exists")
      else:
        print(f"Processing: index {i:0>5}: {dst_png_path}")
        minimal_pipe_mit5k.contrast_only_pipe(src_dng_path, raw_prepare_params, temperature_params, float(contrast), dst_png_path)
        convert_tmp2tiff('/tmp', dst_prefix)

if __name__ == '__main__':
    main()


import rospy
from pid import PID
import math
from yaw_controller import YawController
#GAS_DENSITY = 2.858
#ONE_MPH = 0.44704
MAX_V_MPS = 44.7 # Maximum speed in meters_per_second
BRAKE_TORQUE_SCALE = 100000
YAW_SCALE = 8.2

class Controller(object):
    def __init__(self, **kwargs):
        # TODO: Implement
        max_lat_acc = kwargs['max_lat_acc']
        max_steer_angle = kwargs['max_steer_angle']
        steer_ratio = kwargs['steer_ratio']
        wheel_base = kwargs['wheel_base']

        self.accel_limit = kwargs['accel_limit']
        self.brake_deadband = kwargs['brake_deadband']
        self.decel_limit = kwargs['decel_limit']

        # Create Variable for the last update time
        self.last_update_time = None

        self.pid_c = PID(11.2, 0.05, 0.3, -self.accel_limit, self.accel_limit)
        self.steer_pid = PID(0.8, 0.05, 0.2, -max_steer_angle/2, max_steer_angle/2)

        # Create a steering controller
        self.steer_c = YawController(wheel_base=wheel_base, steer_ratio=steer_ratio, min_speed = 0.0, max_lat_accel = max_lat_acc, max_steer_angle = max_steer_angle)

        # scale of max acceleration to deceleration
        self.brake_scale = self.decel_limit/(-self.accel_limit)
        pass

    def control(self, **kwargs):
        # TODO: Change the arg, kwarg list to suit your needs
        # Return throttle, brake, steer

        # Get the variables from the arguments
        twist_linear = kwargs['twist_command'].twist.linear
        twist_angular = kwargs['twist_command'].twist.angular

        if math.fabs(twist_linear.x) < 0.1:
            twist_linear.x = 0.
        if math.fabs(twist_angular.z) < 0.001:
            twist_angular.z = 0.

        cv_linear = kwargs['current_velocity'].twist.linear
        cv_angular = kwargs['current_velocity'].twist.angular

        steer_feedback = kwargs['steer_feedback']

        # Set the Error
        vel_err = twist_linear.x - cv_linear.x

        # Convert to fraction of v_max so pid output is directly
        # usable as input to throttle_cmd
        vel_err = vel_err/MAX_V_MPS

        # Set the present and target values
        target_v = twist_linear.x
        present_v = cv_linear.x
        target_w = twist_angular.z

        if self.last_update_time is not None:
            # Get current time
            time = rospy.get_time()

            # Compute timestep between updates and save
            # for next iteration
            dt = time - self.last_update_time
            self.last_update_time = time

            # if vehicle is trying to stop we want to reset the integral component
            # of the PID controllers so as to not oscillate around zero
            if present_v < 1.0:
                self.pid_c.reset()
                self.steer_pid.reset()

            # PID class returns output for throttle and
            # brake axes as a joint forward_backward axis
            forward_axis = self.pid_c.step(vel_err, dt)
            reverse_axis = -forward_axis*(self.decel_limit/(-self.accel_limit))

            # if forward axis is positive only then give any throttle
            throttle = min(max(0.0, forward_axis), 0.33)
            # Only apply brakes if the reverse axis value is large enough to supersede the deadband
            #TODO: Figure out how this tuning will work for the real vehicle
            brake = max(0.0, reverse_axis - self.brake_deadband)

            # Convert brake to Torque value since that is what the publisher expects
            brake *= 100

            # get the steering value from the yaw controller
            steering = self.steer_c.get_steering(target_v, target_w, present_v)

            # update using steering pid loop
            steering = self.steer_pid.step(steering - steer_feedback, dt)
            # steering *= steer_ratios

            return throttle, brake, steering
        else:
            # Update the last_update time and send Zeroes tuple
            self.last_update_time = rospy.get_time()
            return 0., 0., 0.


import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.tsa.api as sm

# Load the data
df = pd.read_csv('D:/AIFriendsSchool/seoul2023forcastdata.csv', header=0, encoding='cp949')
df['day'] = pd.to_datetime(df['day'])
df.set_index('day', inplace=True)

# Fit an ARIMA model with order (2,1,2)
model = sm.tsa.arima.ARIMA(df['mm'], order=(2, 1, 2))
result = model.fit()

# Make predictions for the next 5 days
forecast_data = result.forecast(steps=5)

#print(forecast_data)
# 테스트데이터 불러오기
test_data = pd.read_csv('D:/AIFriendsSchool/seoul2023forcastTestdata.csv', header=0, encoding='cp949')
test_data = test_data.rename(columns={'mm':'y','day':'ds'})
#test_data['day'] = pd.to_datetime(test_data['day'])
#test_data.set_index('day', inplace=True)
#test_data.index = pd.DatetimeIndex(test_data.index).to_period('day')
# Extract the actual values for the last 5 days

# Extract the predicted values and prediction intervals
pred_y = forecast_data[0]
test_y = test_data['mm'].values
pred_y_lower = forecast_data[2][:, 0]
pred_y_upper = forecast_data[2][:, 1]

# Plot the predicted and actual values
plt.plot(pred_y, color='gold', label='predicted')
plt.plot(pred_y_lower, color='red', label='lower bound')
plt.plot(pred_y_upper, color='blue', label='upper bound')
plt.plot(test_y, color='green', label='actual')
plt.legend()
plt.show()


import django
import os
import argparse
from random import choice
from django.core.exceptions import ObjectDoesNotExist

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django.setup()

from datacenter.models import Commendation, Lesson, Schoolkid, Mark, Chastisement

def fix_marks(schoolkid):
    Mark.objects.filter(schoolkid=schoolkid, points__lte=3).update(points=choice([4, 5]))

def remove_chastisements(schoolkid):
    chastisement = Chastisement.objects.filter(schoolkid=schoolkid)
    chastisement.delete()

def create_commendation(schoolkid, subject):
    praises = [
        'Хвалю',
        'Молодец',
        'Так держать',
        'Хорошо',
        'Умничка'
    ]
    lesson = Lesson.objects.filter(
        year_of_study=schoolkid.year_of_study,
        group_letter=schoolkid.group_letter,
        subject__title=subject
    ).order_by('?').first()

    Commendation.objects.create(
        text=choice(praises),
        teacher=lesson.teacher,
        subject=lesson.subject,
        schoolkid=schoolkid,
        created=lesson.date
    )

def check_name(name):
    try:
        schoolkid = Schoolkid.objects.get(full_name__contains=name)
        print('Найденный ученик: {}, Год обучения: {}, Буква класса: {}'.format(
            schoolkid.full_name,
            schoolkid.year_of_study,
            schoolkid.group_letter
        ))

    except ObjectDoesNotExist:
        print('Имя не найдено.')
        quit()
    return schoolkid

def get_args():
    parser = argparse.ArgumentParser(description='Изменение оценок')
    parser.add_argument('name', help='ФИО ученика: "Фролов Иван Григорьевич" ')
    parser.add_argument('subject', help='Нужный предмет: "История", "Русский язык" и тд')
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = get_args()
    schoolkid = check_name(args.name)
    print('Желаете продолжить? y/n')

    if input() == 'y':
        fix_marks(schoolkid)
        remove_chastisements(schoolkid)
        create_commendation(schoolkid, args.subject)
        print('Скрипт сработал')


"""Instantiator for neural models"""
from learning.neural.models.bert import Bert
from learning.neural.models.huggingface_automodel_classifier import HF_Automodel
from learning.neural.models.bert_seq2seq import BertSeq2Seq
from learning.neural.models.mlp import MLPModel
from utils import error, warning
from learning.neural.dnn import SupervisedDNN, UnsupervisedDNN, LabelledDNN

from learning.neural.languagemodel.huggingface_seq2seq_transformer_lm import HuggingfaceSeq2Seq
from learning.neural.languagemodel.huggingface_transformer_lm import HuggingfaceTransformer
from learning.neural.languagemodel.labelled_huggingface_transformer_lm import LabelledHuggingfaceTransformer

available_models = [Bert, MLPModel, BertSeq2Seq, HF_Automodel]

available_wrappers = [SupervisedDNN, LabelledDNN, UnsupervisedDNN,
                      HuggingfaceTransformer,
                      LabelledHuggingfaceTransformer,
                      HuggingfaceSeq2Seq]

def get_neural_model_class(name):
    """Retrieve DNN architecture"""
    for candidate in available_models:
        if candidate.name == name:
            return candidate
    error(f"Undefined neural model: {name}")

def get_neural_wrapper_class(neural_model_name):
    """Retrieve the wrapper class of a neural model"""
    model_class = get_neural_model_class(neural_model_name)
    wrapper_name = model_class.wrapper_name
    try:
        wrapper_names = [w.name for w in available_wrappers]
        return available_wrappers[wrapper_names.index(wrapper_name)]
    except ValueError:
        warning(f"Available neural wrappers: {wrapper_names}")
        error(f"Undefined neural wrapper class: {wrapper_name} for neural model {neural_model_name}")

def get_neural_model_wrapper(neural_model):
    """Retrieve wrapper class of DNN architecture"""
    neural_model = get_neural_model_class(neural_model)
    return neural_model.wrapper_class


""" Methods for working with urllib scraping web pages """

import xml.etree.ElementTree as ET
import urllib.request

def rfindta(el, r, tag, attr):
    """ Recursively find tags with value tag and attribute attr and append to list r """
    if len(el) > 0:
        for c in el:
            rfindta(c, r, tag, attr)
    if el.tag.find(tag) >= 0:
        for child in el.attrib:
            if child.find(attr) >= 0:
                r.append(el.attrib[child])

def rfindt(el, r, tag):
    """ Recursively find tags with value tag append to list r """
    if len(el) > 0:
        for c in el:
            rfindt(c, r, tag)
    if el.tag.find(tag) >= 0:
        print(el.text)
        r.append(el.text)

def url_exists(url):
    req = urllib.request.Request(url)
    try:
        urllib.request.urlopen(req)
    except:
        return False
    else:
        return True

def read_url(url):
    try:
        r = urllib.request.urlopen(url).read().decode('UTF-8')
    except:
        return None
    return r

def load_et_root(url):
    return ET.fromstring(urllib.request.urlopen(url).read())


class A(object):
    d = "as"

    def method(self, arg, *args, kwarg):
        print("A", self, self.d)

class B(object):
    def method(self):
        print("B")

class C(A, B):
    def method(self, arg, *args, kwarg):
        print("C")

class D(C):
    d = "dla"

    def method(self, arg, *args, kwarg):
        print("D")

class Super:
    __slots__ = ['__self__', '__self_class__', '__this_class__']

    def __init__(self, subclass, instance):
        if not isinstance(subclass, type):
            raise TypeError("Super() argument 1 must be type, not {}"
                            .format(subclass.__class__.__name__))
        if not isinstance(instance, subclass):
            raise TypeError("Super(type, obj): obj must be an instance "
                            "or subtype of type")
        self.__this_class__ = subclass
        self.__self__ = instance
        self.__self_class__ = instance.__class__

    def __repr__(self):
        return "<Super: <class '{}'>, <{} object>>"\
            .format(self.__this_class__.__name__,
                    self.__self__.__class__.__name__)

    def __get__(self, instance, owner):
        return self

    """
    def decorator(self, func):
        #@functools.wraps(func)
        def bound_func(*args, **kwargs):
            func(self.__self__, *args, **kwargs)

        return bound_func

    def decorator(self, func):
        return lambda *args, **kwargs: func(self.__self__, *args, **kwargs)
    """
    def __getattribute__(self, item):
        if item in object.__getattribute__(self, '__slots__') \
                or item == "decorator":
            return object.__getattribute__(self, item)
        mro = self.__this_class__.mro()[1:]

        for subclass in mro:
            try:
                attr = object.__getattribute__(subclass, item)
                # better through types MethodType
                if callable(attr):
                    return attr.__get__(self.__self__, self.__this_class__)
                return attr
                # return self.decorator(object.__getattribute__(subclass, item))

            except AttributeError:
                continue
        raise AttributeError

if __name__ == "__main__":
    test_D = D()
    print(super(D))
    print(super(D, test_D))
    print()

    print(super(C, test_D).d)
    print(Super(C, test_D).d)
    print(Super(C, test_D).method)
    Super(C, test_D).method(1, kwarg=1)
    super(C, test_D).method(1, kwarg=1)
    print()

    # types
    """
        print(type(D.method))
        print(type(Super))
        print(type(super))
        print(type(Super(C, test_D)))
        print(type(super(A, test_D)))
    """
    # string representation
    print(Super(C, test_D))
    print(super(C, test_D))
    print()

    # super class members
    """
    print(dir(Super(C, test_D)))
    print(dir(super(C, test_D)))

    print(super(C, test_D).__get__(test_D, D).method())
    print(Super(C, test_D).__get__(test_D, D))

    print(super(C, test_D).__thisclass__)
    print(Super(C, test_D).__thisclass__)

    print(super(C, test_D).__self__)
    print(Super(C, test_D).__self__)
    print(super(C, test_D).__self_class__)
    print(Super(C, test_D).__self_class__)

    print(super.__self_class__)
    print(Super.__self_class__)
    print()

    # 1-st argument exception
    try:
        Super(test_D)
    except TypeError as err:
        print(err)
    try:
        super(test_D)
    except TypeError as err:
        print(err)
    print()

    # 2-nd argument exception
    try:
        Super(C, A())
    except TypeError as err:
        print(err)
    try:
        super(C, A())
    except TypeError as err:
        print(err)
    print()
    """


import os
import shutil
import torch
import splitfolders
from torch.utils.data import DataLoader
import segmentation_models_pytorch as smp
import segmentation_models_pytorch.utils

from utils.constants import Constants
from utils.logger import custom_logger
from utils.root_config import get_root_config
from utils.patching import patching, discard_useless_patches
from utils.preprocess import get_training_augmentation, get_preprocessing
from utils.dataset import SegmentationDataset

if __name__ == "__main__":

    ################################# Loading Variables and Paths from Config #################################

    ROOT, slice_config = get_root_config(__file__, Constants)

    # get the required variable values from config
    log_level = slice_config['vars']['log_level']
    file_type = slice_config['vars']['file_type']
    patch_size = slice_config['vars']['patch_size']
    discard_rate = slice_config['vars']['discard_rate']
    batch_size = slice_config['vars']['batch_size']
    model_arch = slice_config['vars']['model_arch']
    encoder = slice_config['vars']['encoder']
    encoder_weights = slice_config['vars']['encoder_weights']
    activation = slice_config['vars']['activation']
    optimizer_choice = slice_config['vars']['optimizer_choice']
    init_lr = slice_config['vars']['init_lr']
    epochs = slice_config['vars']['epochs']
    all_classes = slice_config['vars']['all_classes']
    classes = slice_config['vars']['train_classes']
    device = slice_config['vars']['device']

    preprocessing_fn = smp.encoders.get_preprocessing_fn(encoder, encoder_weights)

    # get the log file dir from config
    log_dir = ROOT / slice_config['dirs']['log_dir']
    # make the directory if it does not exist
    log_dir.mkdir(parents = True, exist_ok = True)
    # get the log file path
    log_path = log_dir / slice_config['vars']['train_log_name']
    # convert the path to string in a format compliant with the current OS
    log_path = log_path.as_posix()

    # initialize the logger
    logger = custom_logger("Land Cover Semantic Segmentation Train Logs", log_path, log_level)

    # get the train dir from config
    train_dir = ROOT / slice_config['dirs']['data_dir'] / slice_config['dirs']['train_dir']
    train_dir = train_dir.as_posix()

    # get the dir of input images for training from config
    img_dir = ROOT / slice_config['dirs']['data_dir'] / slice_config['dirs']['train_dir'] / slice_config['dirs']['image_dir']
    img_dir = img_dir.as_posix()

    # get the dir of input masks for training from config
    mask_dir = ROOT / slice_config['dirs']['data_dir'] / slice_config['dirs']['train_dir'] / slice_config['dirs']['mask_dir']
    mask_dir = mask_dir.as_posix()

    # get the model dir from config
    model_dir = ROOT / slice_config['dirs']['model_dir']
    model_dir = model_dir.as_posix()

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

    ####################################### Functional Part of Program ########################################

    # create the directory to save the patches of images and masks
    patches_dir = os.path.join(train_dir, f"patches_{patch_size}")
    patches_img_dir = os.path.join(patches_dir, "images")
    os.makedirs(patches_img_dir, exist_ok=True)
    patches_mask_dir = os.path.join(patches_dir, "masks")
    os.makedirs(patches_mask_dir, exist_ok=True)

    try:
        print("\nDividing images into patches...")
        patching(img_dir, patches_img_dir, file_type, patch_size)
        print("\nDivided images into patches successfully!")
        logger.info("Divided images into patches successfully!")
    except Exception as e:
        logger.error("Failed to divide images into patches!")
        raise e

    try:
        print("\nDividing masks into patches...")
        patching(mask_dir, patches_mask_dir, file_type, patch_size)
        print("\nDivided masks into patches successfully!")
        logger.info("Divided masks into patches successfully!")
    except Exception as e:
        logger.error("Failed to divide masks into patches!")
        raise e

    try:
        print("\nDiscarding useless patches where background covers more than 95% of the area...")
        discard_useless_patches(patches_img_dir, patches_mask_dir, discard_rate)
        print("\nDiscarded unused patches successfully!")
        logger.info("Discarded unused patches successfully!")
    except Exception as e:
        logger.error("Failed to discard unused patches!")
        raise e

    output_folder = os.path.join(patches_dir, "train_val_test")
    os.makedirs(output_folder, exist_ok=True)

    try:
        print("\nSplitting training and validation data...")
        # Split with a ratio.
        # To split into training, validation, and testing set, set a tuple to `ratio`, i.e, `(.8, .1, .1)`.
        splitfolders.ratio(patches_dir, output=output_folder, seed=42, ratio=(.8, .2), group_prefix=None, move=False) # splitting in training and validation only
        print("\nTraining and validation data split successfully!")
        logger.info("Training and validation data split successfully!")
    except Exception as e:
        logger.error("Failed to split training and validation data!")
        raise e

    train_dir = os.path.join(output_folder, "train")
    val_dir = os.path.join(output_folder, "val")
    # test_dir = os.path.join(output_folder, "test")
    x_train_dir = os.path.join(train_dir, "images")
    y_train_dir = os.path.join(train_dir, "masks")
    x_val_dir = os.path.join(val_dir, "images")
    y_val_dir = os.path.join(val_dir, "masks")

    try:
        # create segmentation model with pretrained encoder
        smp_model = getattr(smp, model_arch)
        model = smp_model(
            encoder_name=encoder,
            encoder_weights=encoder_weights,
            classes=len(classes),
            activation=activation,
        )
        print("\nBuilt the model successfully!")
        logger.info("Built the model successfully!")
    except Exception as e:
        logger.error("Failed to build the model!")
        raise e

    try:
        train_dataset = SegmentationDataset(
            x_train_dir,
            y_train_dir,
            all_classes=all_classes,
            classes=classes,
            augmentation=get_training_augmentation(),
            preprocessing=get_preprocessing(preprocessing_fn),
        )
        val_dataset = SegmentationDataset(
            x_val_dir,
            y_val_dir,
            all_classes=all_classes,
            classes=classes,
            preprocessing=get_preprocessing(preprocessing_fn),
        )
        train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
        valid_loader = DataLoader(val_dataset, batch_size=1, shuffle=False)
        print("\nInitialized training and validation datasets and dataloaders!")
        logger.info("Initialized training and validation datasets and dataloaders!")
    except Exception as e:
        logger.error("Failed to initialize training and validation datasets and dataloaders!")
        raise e

    try:
        loss = smp.utils.losses.DiceLoss()
        metrics = [
            smp.utils.metrics.IoU(threshold=0.5)
        ]
        print("\nInitialized the loss and evaluation metrics!")
        logger.info("Initialized the loss and evaluation metrics!")
    except Exception as e:
        logger.error("Failed to initialize loss and evaluation metrics")
        raise e

    try:
        torch_optimizer = getattr(torch.optim, optimizer_choice)
        optimizer = torch_optimizer([
            dict(params=model.parameters(), lr=init_lr),
        ])
        scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min')
        print("\nInitialized the optimizer!")
        logger.info("Initialized the optimizer!")
    except Exception as e:
        logger.error("Failed to initialize the optimizer!")
        raise e

    try:
        # create epoch runners
        # it is a simple loop of iterating over dataloader`s samples
        train_epoch = smp.utils.train.TrainEpoch(
            model,
            loss=loss,
            metrics=metrics,
            optimizer=optimizer,
            device=device,
            verbose=True,
        )
        valid_epoch = smp.utils.train.ValidEpoch(
            model,
            loss=loss,
            metrics=metrics,
            device=device,
            verbose=True,
        )
        print("\nInitialized epoch runners!")
        logger.info("Initialized epoch runners!")
    except Exception as e:
        logger.error("Failed to initialize epoch runners!")
        raise e

    try:
        print("\nStarting model training...")
        max_score = 0
        for i in range(0, epochs):

            print('\nEpoch: {}'.format(i))
            train_logs = train_epoch.run(train_loader)
            valid_logs = valid_epoch.run(valid_loader)

            # Do something (save model, change lr, etc.)
            if max_score < valid_logs['iou_score']:
                max_score = valid_logs['iou_score']
                torch.save(model, f'{model_dir}/landcover_{model_arch}_{encoder}_{optimizer_choice}_epochs{i}_patch{patch_size}_batch{batch_size}.pth')
                print('Current best model saved!')

            scheduler.step(valid_logs['dice_loss'])
        print("\nModel training finished!")
        logger.info("Model training finished!")
    except Exception as e:
        logger.error("Failed to train the model!")
        raise e

    shutil.rmtree(patches_dir)

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


class Opcode:
	opcode = 0
	modes = []

def getInput(filename):
	ret = []
	cool = []
	with open(filename) as f:
		ret = f.readline()
	ret = ret.split(',')
	for i in ret:
		cool.append(int(i))
	return (cool)

#for opcode 1

def applyAdd(intc, x, modes):
	n1 = intc[x + 1]
	n2 = intc[x + 2]
	pos = intc[x + 3]
	val = intc[n1] + intc[n2]
	intc[pos] = val
	return (intc)

#for opcode 2

def applyMul(intc, x, modes):
	n1 = intc[x + 1]
	n2 = intc[x + 2]
	pos = intc[x + 3]
	l = setModes(n1, n2, modes)
	val = intc[l[0]] * intc[l[1]]
	intc[pos] = val
	return (intc)

#for opcode 3

def applyStore(intc, x, input):
	pass

#for opcode 4

def outputVal(intc, x):
	pass

def setModes(intc, n1, n2, modes):
	l = []
	i = 0
	while i < len(modes) - 2:
		pass

def getModes(n):
	n = [int(x) for x in str(n)]
	while (len(n) < 5):
		n.insert(0, 0)
	if (n[-1] is 4 or n[-1] is 3):
		del n[0:2]
	del n[-1]
	del n[-1]
	return (n)

def intCode(intc, input):
	pos = 0
	op = Opcode()
	while opcode is not 99:
		op.opcode = intc[pos + 0] % 100
		op.modes = getModes(intc[pos + 0])
		if op.opcode is 1:
			intc = applyAdd(intc, pos, op.modes)
			pos += 4
		elif op.opcode is 2:
			intc = applyMul(intc, pos, op.modes)
			pos += 4
		elif op.opcode is 3:
			intc = applyStore(intc, pos, input, op.modes)
			pos += 2
		elif op.opcode is 4:
			outputVal(intc, pos, op.modes)
			pos += 2

print(getModes('103'))


import discord
import sys
import traceback
from cogs.listeners import filter
from cogs.music import Music
from cogs.moderation import moderationtools
from cogs.commands import fun
from cogs.Errorlistener import CommandErrorHandler
import asyncio
from async_timeout import timeout
from discord.ext import commands
from discord import message
from discord import Member
from discord import permissions
from discord.ext.commands import has_permissions, MissingPermissions, Cog, BucketType
from discord.ext.commands import (CommandNotFound, BadArgument, MissingRequiredArgument, CommandOnCooldown)
from asyncio import sleep
import json
import os
import random
from random import choice
import time
import DiscordUtils
from cogs.listeners import infodictdefine
import datetime
import asyncio
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils import manage_commands
from discord import CategoryChannel
class bcolors: #funny colors
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
#Change Bot Status
async def status_task():
    file = open("swagstatus.txt", "r+")
    statuschoiceorig = file.readlines()
    controller = True
    while controller == True:
      statuschoice = random.choice(statuschoiceorig)
      await bot.change_presence(status=discord.Status.online, activity=discord.Game(name=f"{statuschoice}"))
      statuschoiceorig = [x for x in statuschoiceorig if x != statuschoice] #list comprehension and removes the statuses as it needs too
      print(statuschoice)
      if len(statuschoiceorig) == 0: #Refils the list if its empty
        file = open("swagstatus.txt", "r+")
        statuschoiceorig = file.readlines()
      await asyncio.sleep(21600)

def get_prefix(client, message):  ##first we define get_prefix
  with open('prefixes.json', 'r') as f:  ##we open and read the prefixes.json, assuming it's in the same file
    prefixes = json.load(f)  #load the json as prefixes
    try:
      return prefixes[str(message.author.id)]  #recieve the prefix for the guild id given
    except:
      if message.guild.id == 664264869717213225:
        return "swag!"
      else:
        return "."

async def reset_keys():
  while True:
      now = time.localtime()
      current_time = time.strftime("%H:%M:%S", now)
      infodictdefine.inforeset()
      print(f"[{bcolors.WARNING}LISTENER INFO{bcolors.ENDC}] [{bcolors.HEADER}{current_time}{bcolors.ENDC}] Info Dictionary has been reset!")
      await asyncio.sleep(21600)

#initial startup
bot = commands.Bot(command_prefix=get_prefix,status=discord.Status.dnd,activity=discord.Game(name="Getting Ready..."), intents=discord.Intents.all())
bot.remove_command("help")
slash = slash = SlashCommand(bot, sync_commands=True)
guild_ids=[807777602633728011, 577904583213449237, 664264869717213225]
#ready
@bot.event
async def on_ready():
  now = time.localtime()
  current_time = time.strftime("%H:%M:%S", now)
  print(f"[{bcolors.OKBLUE}SYSTEM INFO{bcolors.ENDC}] [{bcolors.HEADER}{current_time}{bcolors.ENDC}] Bot Ready! Logged in as De Fan")
  print(f"[{bcolors.WARNING}LISTENER INFO{bcolors.ENDC}] [{bcolors.HEADER}{current_time}{bcolors.ENDC}] Info Dictionary has been reset!")
  bot.loop.create_task(status_task())
  bot.loop.create_task(reset_keys())

#new help command
@bot.command(aliases=["h", "i", "info"])
async def help(ctx):
    with open('prefixes.json', 'r') as f:  ##we open and read the prefixes.json, assuming it's in the same file
      prefixes = json.load(f)  #load the json as prefixes
    try:
      user_prefix = prefixes[str(ctx.message.author.id)]  #recieve the prefix for the guild id given
    except:
      user_prefix = "."
    ping_ = bot.latency
    ping = round(ping_ * 1000) #convert to ms
    embed=discord.Embed(title="Help", description=f"Commands and Usage for {ctx.guild.me.display_name}", color=0x00ff75)
    embed.add_field(name="Prefixes", value="Default is `.`\nUse the `mp` command to set your own custom prefix!", inline=False)
    embed.add_field(name="Your Prefix:", value=f"`{user_prefix}`", inline=True)
    embed.add_field(name="Current Bot Latency:", value=f"**{ping}** ms", inline=True)
    embed2=discord.Embed(title="General Commands", description="Commands everyone can use!", color=0x00ff75)
    embed2.add_field(name="__***Commands***__", value="`help/h` - Displays this help message\n`ping` - Fetches the Latency of this bot\n`mp {new prefix}` - Changes *your* custom prefix. Can be anything\n`hjail @user` - sends a user to horny jail\n`kill @user` - kills a user\n`8ball {question}` - magic 8 ball\n`copypasta` - prints a random copypasta to chat\n`hug @user` - hugs a user\n`kiss @user` - kisses a user\n`uwu` - idek man\n`coin` - Flips a coin. Pretty simple\n`credits` - Credit to Team!\n`swagscale @user percent(optional)` - Rates a user on the swag meter:tm:\n`boobah` - gives you the link to the boobah game", inline=True)
    embed2.add_field(name="** **", value="`poll {time} \"{question, must be in quotation marks}\" \"{options, must be in quotation marks. Up to 27 options allowed}\"` - Creates a poll based on time. Quotation marks **MUST** be around all options besides the time.\n```diff\n+Yes: .poll 1 \"Test Poll\" \"option 1\"... (Up to 27 options)\n\n-No: .poll 1 question 1 option1 option 2 etc.\n```")
    embed3=discord.Embed(title="Administrator Commands", description="Modz only!! :sunglasses:", color=0x00ff75)
    embed3.add_field(name="__***Commands***__", value="\n`lockdown/lock {time}` - locks a channel for a specified amount of time\n`clear/purge {number}` - Clears specified number of messages from the channel. Only works for messages younger than two weeks.", inline=True)
    musicembed=discord.Embed(title="Music Commands", description=f"{ctx.guild.me.display_name} supports a music player! This is how to use it.", color=0x00ff75)
    musicembed.add_field(name="__***Commands***__", value="`p/play {song name/link}` - Plays the specified song\n`queue/q` - Show upcoming songs\n`skip/s` - Skips the current song\n`v/setvol/volume {number}` - Sets volume client side\n`loop` - Toggles the loop on the current song\n`eq/equalize {mode}` - Its an equalizer. Supported presets are:\n```diff\nflat - resets the equalizer\nboost - bass booster\nmetal - For rock songs\npiano - For piano songs\n```", inline=False)
    musicembed.set_thumbnail(url="https://cdn.discordapp.com/emojis/710232673976582215.gif?v=1")
    paginator = DiscordUtils.Pagination.CustomEmbedPaginator(ctx, timeout=30, auto_footer=True, remove_reactions=True)
    paginator.add_reaction('⏮', 'first')
    paginator.add_reaction('⬅', 'back')
    paginator.add_reaction('➡', 'next')
    paginator.add_reaction('⏭', 'last')
    embeds = [embed, embed2, embed3, musicembed]
    await paginator.run(embeds)

@slash.slash(
  name="Help",
  description="Need help? Use this command to see the Help Menu",
  options=None,
  guild_ids=guild_ids
)
async def help(ctx: SlashContext):
    with open('prefixes.json', 'r') as f:  ##we open and read the prefixes.json, assuming it's in the same file
      prefixes = json.load(f)  #load the json as prefixes
    try:
      user_prefix = prefixes[str(ctx.author.id)]  #recieve the prefix for the guild id given
    except:
      user_prefix = "."
    ping_ = bot.latency
    ping = round(ping_ * 1000) #convert to ms
    embed=discord.Embed(title="Help", description="Commands and Usage for De Fan", color=0x00ff75)
    embed.add_field(name="Prefixes", value="Default is `.`\nUse the `mp` command to set your own custom prefix!", inline=False)
    embed.add_field(name="Your Prefix:", value=f"`{user_prefix}`", inline=True)
    embed.add_field(name="Current Bot Latency:", value=f"**{ping}** ms", inline=True)
    embed2=discord.Embed(title="General Commands", description="Commands everyone can use!", color=0x00ff75)
    embed2.add_field(name="__***Commands***__", value="`help/h` - Displays this help message\n`ping` - Fetches the Latency of this bot\n`mp {new prefix}` - Changes *your* custom prefix. Can be anything\n`hjail @user` - sends a user to horny jail\n`kill @user` - kills a user\n`8ball {question}` - magic 8 ball\n`copypasta` - prints a random copypasta to chat\n`hug @user` - hugs a user\n`kiss @user` - kisses a user\n`uwu` - idek man\n`coin` - Flips a coin. Pretty simple\n`credits` - Credit to Team!\n`swagscale @user percent(optional)` - Rates a user on the swag meter:tm:\n`boobah` - gives you the link to the boobah game", inline=True)
    embed2.add_field(name="** **", value="`poll {time} \"{question, must be in quotation marks}\" \"{options, must be in quotation marks. Up to 27 options allowed}\"` - Creates a poll based on time. Quotation marks **MUST** be around all options besides the time.\n```diff\n+Yes: .poll 1 \"Test Poll\" \"option 1\"... (Up to 27 options)\n\n-No: .poll 1 question 1 option1 option 2 etc.\n```")
    embed3=discord.Embed(title="Administrator Commands", description="Modz only!! :sunglasses:", color=0x00ff75)
    embed3.add_field(name="__***Commands***__", value="\n`lockdown/lock {time}` - locks a channel for a specified amount of time\n`clear/purge {number}` - Clears specified number of messages from the channel. Only works for messages younger than two weeks.", inline=True)
    musicembed=discord.Embed(title="Music Commands", description="Defan now supports a music player! This is how to use it.", color=0x00ff75)
    musicembed.add_field(name="__***Commands***__", value="`p/play {song name/link}` - Plays the specified song\n`queue/q` - Show upcoming songs\n`skip/s` - Skips the current song\n`v/setvol/volume {number}` - Sets volume client side\n`loop` - Toggles the loop on the current song\n`eq/equalize {mode}` - Its an equalizer. Supported presets are:\n```diff\nflat - resets the equalizer\nboost - bass booster\nmetal - For rock songs\npiano - For piano songs\n```", inline=False)
    musicembed.set_thumbnail(url="https://cdn.discordapp.com/emojis/710232673976582215.gif?v=1")
    paginator = DiscordUtils.Pagination.CustomEmbedPaginator(ctx, timeout=30, auto_footer=True, remove_reactions=True)
    paginator.add_reaction('⏮', 'first')
    paginator.add_reaction('⬅', 'back')
    paginator.add_reaction('➡', 'next')
    paginator.add_reaction('⏭', 'last')
    embeds = [embed, embed2, embed3, musicembed]
    await paginator.run(embeds)

@bot.command(aliases=["prefix", "mp"])
async def myprefix(ctx, prefix):
  with open('prefixes.json', 'r') as f:
    prefixes = json.load(f)

  prefixes[str(ctx.message.author.id)] = prefix

  with open('prefixes.json','w') as f:  #writes the new prefix into the .json
    json.dump(prefixes, f, indent=4)

  now = time.localtime()
  current_time = time.strftime("%H:%M:%S", now)
  print(f"[{bcolors.WARNING}NON-CRITICAL ALERT{bcolors.ENDC}] [{bcolors.HEADER}{current_time}{bcolors.ENDC}] User {ctx.message.author.display_name} changed their prefix to [{bcolors.FAIL}{prefix}{bcolors.ENDC}]")
  await ctx.send(f'{ctx.message.author.mention} Your prefix was changed to: {prefix}') #confirms the prefix it's been changed to

@slash.slash(
  name="NewPrefix",
  description="Set your own custom prefix!",
  options=[manage_commands.create_option(
    name = "Prefix",
    description = "Prefix you want",
    option_type = 3,
    required = True
  )],
  guild_ids=guild_ids
)
async def myprefix(ctx: SlashContext, prefix): #ignore already defined warning, ide is a bitch
  author_id = ctx.author
  with open('prefixes.json', 'r') as f:
    prefixes = json.load(f)

  prefixes[str(author_id)] = prefix

  with open('prefixes.json','w') as f:  #writes the new prefix into the .json
    json.dump(prefixes, f, indent=4)

  now = time.localtime()
  current_time = time.strftime("%H:%M:%S", now)
  print(f"[{bcolors.WARNING}NON-CRITICAL ALERT{bcolors.ENDC}] [{bcolors.HEADER}{current_time}{bcolors.ENDC}] User {ctx.message.author.display_name} changed their prefix to [{bcolors.FAIL}{prefix}{bcolors.ENDC}]")
  await ctx.send(f'{ctx.message.author.mention} Your prefix was changed to: {prefix}') #confirms the prefix it's been changed to

#fetch latency
@bot.command(aliases=["pong"])
@commands.cooldown(1, 2, commands.BucketType.user)
async def ping(ctx):
    ping_ = bot.latency
    ping = round(ping_ * 1000) #convert to ms
    now = time.localtime()
    current_time = time.strftime("%H:%M:%S", now)
    await ctx.channel.send(f"***✓*** Pong! The current ping of De Fan is {ping} ms")
    print(f"[{bcolors.OKBLUE}SYSTEM INFO{bcolors.ENDC}] [{bcolors.HEADER}{current_time}{bcolors.ENDC}] Ping requested.\nThe current latency is {ping} ms.")

@bot.listen('on_member_join')
async def newmember(member):#SW
    if member.guild.id == 664264869717213225:
        XXI = discord.utils.get(member.guild.categories, id=664264870656475156)
        channel = bot.get_channel(XXI.channels.pop(0).id)
        introduce = bot.get_channel(667178772381827072)
        roles = bot.get_channel(721462151184646254)
        await channel.send(f"Hey {member.mention}!" + f" Welcome to da swag house :fire: :sunglasses: Go to the pinned messages in {roles.mention} to give yourself pronoun, color, and other roles, and don't forget to introduce yourself in {introduce.mention}")
        await member.send(f"Hey {member.mention}!" + f" Welcome to da swag house :fire: :sunglasses: Go to the pinned messages in {roles.mention} to give yourself pronoun, color, and other roles, and don't forget to introduce yourself in {introduce.mention}")
    elif member.guild.id == 577904583213449237:#CC
      channel = bot.get_channel(577906129133109259)
      await channel.send(f"Welcome To {member.guild.name} {member.mention}. Feel free to say hi and poke around. Check the reaction roles channel to get some cool roles!")
    else:
      await member.send(f"Welcome To {member.guild.name} {member.mention}. Feel free to say hi and poke around.")

emojiLetters = [
            "\N{REGIONAL INDICATOR SYMBOL LETTER A}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER B}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER C}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER D}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER E}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER F}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER G}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER H}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER I}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER J}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER K}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER L}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER M}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER N}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER O}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER P}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER Q}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER R}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER S}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER T}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER U}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER V}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER W}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER X}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER Y}",
            "\N{REGIONAL INDICATOR SYMBOL LETTER Z}"]

@bot.command() #Simple polling command
async def poll(ctx, timeout_opt: int, question, *args):
  #poll init
  voters = []
  vote_counts = {}
  votecountpub = 0
  options = []
  react_to_option = {}
  description = ""
  for i, arg in enumerate(args): #this works because if you have
    description += f"React with {emojiLetters[i]} + to cast your vote for ** {arg} **\n" #Enumerate through the options passed through the *arg argument.
    options.append(arg)
    react_to_option[emojiLetters[i]] = arg
  print(react_to_option)
  #Vote counter
  for option in options:
    vote_counts[option] = 0
  my_poll = discord.Embed(
    title = question,
    description = f"Hosted by {ctx.author.display_name}\n\n{description}",
    color=ctx.author.color,
    timestamp=datetime.datetime.utcnow()
    ) #embed creation. The timestamp will update on every vote effectively telling you when the last vote was cast.
  message = await ctx.send(embed = my_poll)
  start_time = datetime.datetime.now()

  for i, option in enumerate(options):
    await message.add_reaction(emojiLetters[i])
  # Get votes
  reaction = None
  # Ensure reaction is to the poll message and the reactor is not the bot
  def check(reaction, user):
    return reaction.message.id == message.id and user.id != 763576957618618428 #THIS IS THE BOT ID, switch this out for

  while True: # Exit after a certain time
    try:
      reaction, user = await bot.wait_for('reaction_add', timeout = 0.5, check = check)
      await message.remove_reaction(reaction, user)
      #Checks if the user has already voted
      if user not in voters:
        voters.append(user)
        votecountpub += 1
        vote_counts[react_to_option[reaction.emoji]] += 1
        my_poll.set_footer(text=f"Total votes: {votecountpub}")
        await message.edit(embed=my_poll)
      elif user in voters:
        await user.send("I appreciate the enthusiasm but you have already voted for that poll!")
    except asyncio.TimeoutError:
      if datetime.datetime.now() >= start_time + datetime.timedelta(seconds = timeout_opt): #checks for if the poll time has been reached
        break

  # Send messages of results
  print("done")
  results = ""
  for option in vote_counts:
    results += option + " - " + "**" + str(vote_counts[option]) +"**" + " Votes" + "\n"
  results_message = discord.Embed(
    title = f"Poll Ended!\n{question}",
    description = f"Hosted by {ctx.author.display_name}\n\n__**Results**__\n{results}",
    color=ctx.author.color,
    timestamp=datetime.datetime.utcnow()
    )
  await message.clear_reactions()
  await message.delete()
  await ctx.send(embed = results_message)

#More commands in COG FOLDER
#ATTACH COGS
bot.add_cog(CommandErrorHandler(bot)) #errorlistener.py
bot.add_cog(fun(bot)) #Commands.py
bot.add_cog(moderationtools(bot)) #moderation.py
bot.add_cog(filter(bot)) #This is not really a filter in all honesty
bot.add_cog(Music(bot))
###IMPORTANT####
bot.run("Token") #Keep this token private, discord will freak if you dont
###IMPORTANT###


from random import choice
from .Division import Division

class Fraction(Division):
    _fractions = {
        2: "demi",
        3: "tiers",
        4: "quart",
        5: "cinquième",
        6: "sixième",
    }

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

    def formatString(self):
        return f"le {self._fractions[self._b]} de {self._a}"

    def generateValues(self, generator):
        division = Division()
        self._b = choice([x for x in self._fractions])
        division.generateValues(generator, self._b)
        self._a = division.a

    def formatCorrectedString(self):
        return (
            f"le {self._fractions[self._b]} de {self._a} = "
            f"{int(self._a / self._b)}"
        )


from spack import *

class Rocblas(CMakePackage):
    """Radeon Open Compute BLAS library"""

    homepage = "https://github.com/ROCmSoftwarePlatform/rocBLAS/"
    url      = "https://github.com/ROCmSoftwarePlatform/rocBLAS/archive/rocm-4.0.0.tar.gz"

    maintainers = ['srekolam', 'arjun-raj-kuppala']

    version('4.0.0', sha256='78e37a7597b581d90a29e4b956fa65d0f8d1c8fb51667906b5fe2a223338d401')
    version('3.10.0', sha256='9bfd0cf99662192b1ac105ab387531cfa9338ae615db80ed690c6a14d987e0e8')
    version('3.9.0', sha256='3ecd2d9fd2be0e1697a191d143a2d447b53a91ae01afb50231d591136ad5e2fe')
    version('3.8.0', sha256='568a9da0360349b1b134d74cc67cbb69b43c06eeca7c33b50072cd26cd3d8900')
    version('3.7.0', sha256='9425db5f8e8b6f7fb172d09e2a360025b63a4e54414607709efc5acb28819642')
    version('3.5.0', sha256='8560fabef7f13e8d67da997de2295399f6ec595edfd77e452978c140d5f936f0')

    tensile_architecture = ('all', 'gfx803', 'gfx900', 'gfx906', 'gfx908')

    variant('tensile_architecture', default='all', values=tensile_architecture, multi=False)

    depends_on('cmake@3:', type='build')

    for ver in ['3.5.0', '3.7.0', '3.8.0', '3.9.0', '3.10.0', '4.0.0']:
        depends_on('rocm-cmake@' + ver, type='build', when='@' + ver)
        depends_on('rocm-device-libs@' + ver, type='build', when='@' + ver)
        depends_on('hip@' + ver, when='@' + ver)
        depends_on('comgr@' + ver, type='build', when='@' + ver)
        # used in Tensile
        depends_on('rocm-smi@' + ver, type='build', when='@' + ver)
        depends_on('llvm-amdgpu@' + ver, type='build', when='@' + ver)

    # This is the default library format since 3.7.0
    depends_on('msgpack-c@3:', when='@3.7:')

    depends_on('python', type='build')
    depends_on('py-virtualenv', type='build')
    depends_on('perl-file-which', type='build')
    depends_on('py-pyyaml', type='build')
    depends_on('py-wheel', type='build')
    depends_on('py-msgpack', type='build')

    resource(name='Tensile',
             git='https://github.com/ROCmSoftwarePlatform/Tensile.git',
             commit='f842a1a4427624eff6cbddb2405c36dec9a210cd',
             when='@3.5.0')

    resource(name='Tensile',
             git='https://github.com/ROCmSoftwarePlatform/Tensile.git',
             commit='af71ea890a893e647bf2cf4571a90297d65689ca',
             when='@3.7.0')

    resource(name='Tensile',
             git='https://github.com/ROCmSoftwarePlatform/Tensile.git',
             commit='9123205f9b5f95c96ff955695e942d2c3b321cbf',
             when='@3.8.0')

    resource(name='Tensile',
             git='https://github.com/ROCmSoftwarePlatform/Tensile.git',
             commit='b68edc65aaeed08c71b2b8622f69f83498b57d7a',
             when='@3.9.0')

    resource(name='Tensile',
             git='https://github.com/ROCmSoftwarePlatform/Tensile.git',
             commit='ab44bf46b609b5a40053f310bef2ab7511f726ae',
             when='@3.10.0')

    resource(name='Tensile',
             git='https://github.com/ROCmSoftwarePlatform/Tensile.git',
             commit='ab44bf46b609b5a40053f310bef2ab7511f726ae',
             when='@4.0.0')

    # Status: https://github.com/ROCmSoftwarePlatform/Tensile/commit/a488f7dadba34f84b9658ba92ce9ec5a0615a087
    # Not yet landed in 3.7.0, nor 3.8.0.
    patch('0001-Fix-compilation-error-with-StringRef-to-basic-string.patch', when='@:3.8')

    def setup_build_environment(self, env):
        env.set('CXX', self.spec['hip'].hipcc)

    def cmake_args(self):
        arch = self.spec.variants['tensile_architecture'].value

        tensile = join_path(self.stage.source_path, 'Tensile')

        args = [
            '-Damd_comgr_DIR={0}'.format(self.spec['comgr'].prefix),
            '-DBUILD_CLIENTS_TESTS=OFF',
            '-DBUILD_CLIENTS_BENCHMARKS=OFF',
            '-DBUILD_CLIENTS_SAMPLES=OFF',
            '-DRUN_HEADER_TESTING=OFF',
            '-DBUILD_WITH_TENSILE=ON',
            '-DTensile_TEST_LOCAL_PATH={0}'.format(tensile),
            '-DTensile_COMPILER=hipcc',
            '-DTensile_ARCHITECTURE={0}'.format(arch),
            '-DTensile_LOGIC=asm_full',
            '-DTensile_CODE_OBJECT_VERSION=V3',
            '-DBUILD_WITH_TENSILE_HOST={0}'.format(
                'ON' if '@3.7.0:' in self.spec else 'OFF'
            )
        ]

        if '@3.7.0:' in self.spec:
            args.append('-DTensile_LIBRARY_FORMAT=msgpack')

        return args


from django.urls import path
from studserviceapp.views.backend import rasporedi, predmeti, grupe, izborne_grupe, studenti, obavestenja, auth, email, nalozi

urlpatterns = [
    # RASPORED
    path('raspored-predavanja/', rasporedi.get_raspored_predavanja),

    path('raspored-ispita/', rasporedi.get_raspored_ispita),

    path('raspored-kolokvijuma/', rasporedi.get_raspored_kolokvijuma),

    # IZBORNE GRUPE
    path('unos-grupe/', izborne_grupe.unos_izborne_grupe),

    path('obrisi-grupu/', izborne_grupe.obrisi_izbornu_grupu),

    path('izmeni-grupu/', izborne_grupe.izmeni_izbornu_grupu),

    path('izborne-grupe/<str:godina>/', izborne_grupe.get_izborne_grupe_godina),

    path('izborne-grupe/', izborne_grupe.get_all_izborne_grupe),

    # GRUPE
    path('grupe/', grupe.get_all_grupe),

    path('grupe/<str:godina>/', grupe.get_grupe_po_godini),

    # STUDENTI
    path('studenti/', studenti.get_all_studenti),

    path('studenti/grupa/<str:grupa>/', studenti.get_studenti_grupa),

    path('studenti/godina/<str:godina>/', studenti.get_studenti_godina),

    # PREDMETI
    path('predmeti/', predmeti.get_all_predmeti),

    # OBAVESTENJA
    path('unos-obavestenja/', obavestenja.unos_obavestenja),

    # AUTORIZACIJA
    path('authorize/', auth.authorize),

    #EMAIL
    path('send-email/', email.send_email),

    #NALOZI
    path('get-nalozi/', nalozi.get_all_nalozi)
]


for _ in range(int(input())):
    n=int(input())
    s=input().lower()
    x=len(list(set(list(s))))
    if 'm' in s and 'e' in s and 'o' in s and 'w' in s and x==4:
        m=s.index('m')
        mm=s.rindex('m')
        e=s.index('e')
        ee=s.rindex('e')
        o=s.index('o')
        oo=s.rindex('o')
        w=s.index('w')
        ww=s.rindex('w')
        if(m<=mm<e<=ee<o<=oo<w<=ww):
            print("YES")
        else:
            print("NO")
    else:
        print("NO")