import numpy as np
import pytest

from modules.knn import (
    classify_with_mode,
    compute_accuracy,
    distance_matrix,
    evaluate_knn,
    knn_predict,
)

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.array([7, 8, 9])

a1 = np.array([a, a, a])
b1 = np.array([b, b])
c1 = np.array([c, c])

def test_distance_matrix():
    dists = distance_matrix(a1, b1)
    assert np.shape(dists) == (3, 2)
    assert np.array_equal(
        dists,
        [
            [np.sqrt(27), np.sqrt(27)],
        ]
        * 3,
    )

    dists1 = distance_matrix(a1, c1)
    assert np.shape(dists1) == (3, 2)
    assert np.array_equal(
        dists1,
        [
            [np.sqrt(108), np.sqrt(108)],
        ]
        * 3,
    )

    return

def test_distance_matrix_incompatible_arrays():
    d1 = np.array([[1, 2], [1, 2]])
    with pytest.raises(ValueError):
        distance_matrix(a1, d1)
    return

def test_knn_predict():
    predicts = np.array([0, 1, 2])

    dists = distance_matrix(a1, b1)
    results = knn_predict(dists, predicts, 2)
    assert np.shape(results) == (2, 2)
    assert np.array_equal(results, np.array([[0, 0], [1, 1]]))

    dists1 = distance_matrix(a1, c1)
    results1 = knn_predict(dists1, predicts)
    assert np.shape(results1) == (1, 2)
    assert np.array_equal(results1, np.array([[0, 0]]))

    assert len(knn_predict(dists, predicts, -1)) == 0
    assert len(knn_predict(dists, predicts, 4)) == 0

    return

def test_knn_predict_incompatible_arrays():
    predicts = np.array([0, 1])
    dists = distance_matrix(a1, b1)

    with pytest.raises(IndexError):
        knn_predict(dists, predicts, 3)
    return

def test_classify_with_mode():
    labels = np.array([[0, 0, 1, 2], [0, 0, 1, 2], [0, 0, 1, 2]])
    labels1 = np.array([[1, 5, 3, 6], [0, 9, 9, 9], [1, 9, 9, 9]])

    classification = classify_with_mode(labels)
    classification1 = classify_with_mode(labels1)

    assert np.array_equal(classification, [0, 0, 1, 2])
    assert np.array_equal(classification1, [1, 9, 9, 9])

    return

def test_compute_accuracy():
    predicts = np.array([0, 1, 2, 3])
    true_values = np.array([0, 0, 2, 3])
    assert compute_accuracy(true_values, predicts) == 0.75
    return

def test_compute_accuracy_incompatible_arrays():
    predicts = np.array([0, 1, 2])
    true_values = np.array([0, 0])
    with pytest.raises(ValueError):
        compute_accuracy(true_values, predicts)

def test_evaluate_knn():
    assert evaluate_knn([], [], [], [], -1) == None
    assert evaluate_knn([0, 1], [], [], [], 3) == None

    data_train = np.array([a, b, a, a])
    labels_train = np.array([0, 1, 0, 0])
    data_test = np.array([a, a, b, a])
    labels_test = np.array([0, 0, 0, 2])
    k = 1

    accuracy = evaluate_knn(data_train, labels_train, data_test, labels_test, k)
    assert accuracy == 0.5

    k = 4
    accuracy = evaluate_knn(data_train, labels_train, data_test, labels_test, k)
    assert accuracy == 0.75
    return


"""Base defines a common contract for connecting, closing, managing context for clients."""
import abc
from typing import Container, ContextManager, TypeVar, Union, cast

from tentaclio import protocols, urls

T = TypeVar("T")

class BaseClient(ContextManager[T], metaclass=abc.ABCMeta):
    """Abstract base class for clients, wrapping a connection.

    Offers context managing, connecting and closing functionalities.
    """

    url: urls.URL
    conn: protocols.Closable
    allowed_schemes: Container[str] = []
    closed: bool = True

    def __init__(self, url: Union[urls.URL, str]) -> None:
        """Create a new client based on a URL object or a string containing a url."""
        if isinstance(url, str):
            url = urls.URL(url)
        self.url = url
        if self.url.scheme not in self.allowed_schemes:
            raise ValueError(
                f"Allowed schemes for {type(self).__name__} are {self.allowed_schemes}; "
                f"found '{self.url.scheme}'"
            )

    # Context manager:

    def __enter__(self) -> T:
        """Connect to the resource when entering the context."""
        self.conn = self.connect()
        return cast(T, self)

    def __exit__(self, *args) -> None:
        """Close the connection when leaving the context."""
        self.close()

    # Connection methods:

    def connect(self) -> protocols.Closable:
        """Connect to the resource when entering the context."""
        self.closed = False
        return self._connect()

    @abc.abstractmethod
    def _connect(self) -> protocols.Closable:
        """Connect to the resource. This method needs to be overwritten by child classes."""
        ...

    def close(self) -> None:
        """Close the client connection."""
        if not self.closed:
            self.conn.close()
            self.closed = True


import unittest
import requests

class Backend(unittest.TestCase):
    def test_service(self):
        print ("/")
        r = requests.get('http://172.17.0.1:8080')
        self.assertEqual(r.status_code, 200)

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


import os
import setuptools

DOTA_DRAFT = 'dota-draft'

# Install a single environment by setting the ENVIRONMENT variable.
# See environments/README.md
environment = os.getenv('ENVIRONMENT') or DOTA_DRAFT

# WORKDIR is set by the Docker images, otherwise use current setup.
workdir = os.getenv('WORKDIR') or os.getcwd()

# Read from requirements.txt for consistency
dirs = ','.join(os.listdir('.'))
environments_dir = os.path.join(workdir, 'environments')
requirements_dir = os.path.join(environments_dir, environment)
requirements_path = os.path.join(requirements_dir, 'requirements.txt')
if not os.path.exists(environments_dir):
    raise RuntimeError(f'No environments folder within {workdir} with dirs ({dirs})')
if not os.path.exists(requirements_dir):
    raise RuntimeError(f'Could not find the environment {environment} within {workdir} with dirs ({dirs})')
if not os.path.exists(requirements_path):
    raise RuntimeError(f'Could not find the requirements file at {requirements_path} within {workdir} with dirs ({dirs})')

try:
    with open(requirements_path) as f:
        requirements = f.read().splitlines()
except FileNotFoundError:
    raise RuntimeError(f'Invalid environment {environment}, could not install dependencies.')

setuptools.setup(
    name=f'{DOTA_DRAFT}-{environment}' if environment != DOTA_DRAFT else DOTA_DRAFT,
    version='1.0',
    description='Dota draft package',
    author='Ariel Perez',
    author_email='arielperezch@gmail.com',
    url='https://github.com/asparagus/dota-draft',
    install_requires=requirements,
    packages=['draft'],
    package_data={'draft': ['configs/*.yaml']},
)


# -*- coding: utf-8 -*-

__author__ = 'Douglas Uba'
__email__  = 'douglas.uba@inpe.br'

import goes, goes.downloader
from PyQt5 import uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import s3fs

class Downloader(QWidget):
    def __init__(self):
        super(Downloader, self).__init__()
        # Load user-interface from ui file
        uic.loadUi('./ui/downloader.ui', self)

        # Setup buckets
        for bucket in goes.BUCKETS:
            self.satelliteComboBox.addItem(bucket)

        # Define default bucket
        self.bucket = goes.BUCKETS['GOES-16']

        # Populate hours
        for hour in goes.HOURS:
            item = QListWidgetItem(hour, self.hourListWidget, Qt.ItemIsUserCheckable);
            item.setCheckState(Qt.Checked)

        # Populate channels
        for channel in goes.CHANNELS:
            item = QListWidgetItem(channel, self.channelListWidget, Qt.ItemIsUserCheckable);
            item.setCheckState(Qt.Checked)

        # Flag that indicates if selected product is channel-separated
        self.hasChannels = True

        # Setup initial dates
        now = QDate.currentDate()
        self.startDateTimeEdit.setDate(now)
        self.endDateTimeEdit.setMaximumDate(now)
        self.endDateTimeEdit.setDate(now)

        # Setup output directory
        self.outputDirectoryLineEdit.setText(QDir.currentPath())

        # Signals & slots
        self.satelliteComboBox.currentTextChanged[str].connect(self.__onSatelliteComboBoxChanged)
        self.productsCheckBox.stateChanged.connect(self.__onProductsCheckBoxChanged)
        self.hoursCheckBox.stateChanged.connect(self.__onHoursCheckBoxChanged)
        self.channelsCheckBox.stateChanged.connect(self.__onChannelsCheckBoxChanged)
        self.outputDirectoryPushButton.released.connect(self.__onOutputDirectoryPushButtonReleased)
        self.downloadPushButton.released.connect(self.__onDownloadPushButtonReleased)

        # Connection with S3 GOES-16 AWS file system
        self.fs = s3fs.S3FileSystem(anon=True)

        # Fill product list
        self.__fillProducts()

    def __fillProducts(self):
        self.productListWidget.clear()
        for product in self.fs.ls(self.bucket):
            if 'index.html' not in product:
                item = QListWidgetItem(product, self.productListWidget, Qt.ItemIsUserCheckable);
                item.setCheckState(Qt.Unchecked)
        self.productListWidget.setCurrentRow(0)

    def __onSatelliteComboBoxChanged(self, satellite):
        self.bucket = goes.BUCKETS[satellite]
        self.__fillProducts()

    def __onProductsCheckBoxChanged(self, state):
        for i in range(self.hourListWidget.count()):
            self.productListWidget.item(i).setCheckState(state)

    def __onHoursCheckBoxChanged(self, state):
        for i in range(self.hourListWidget.count()):
            self.hourListWidget.item(i).setCheckState(state)

    def __onChannelsCheckBoxChanged(self, state):
        for i in range(self.channelListWidget.count()):
            self.channelListWidget.item(i).setCheckState(state)

    def __onOutputDirectoryPushButtonReleased(self):
        self.outputDirectoryLineEdit.setText(
            QFileDialog.getExistingDirectory(self, 'Output Directory', '.')
        )

    def __onDownloadPushButtonReleased(self):
        # Verify selected products
        products = self.__getSelectedItems(self.productListWidget)
        if not products:
            QMessageBox.information(self, 'Information',
                'Please, select at least one product.'
            )
            self.productListWidget.setFocus()
            return

        # Verify selected hours
        hours = self.__getSelectedItems(self.hourListWidget)
        if not hours:
            QMessageBox.information(self, 'Information',
                'Please, select at least one hour.'
            )
            self.hourListWidget.setFocus()
            return

        # Verify selected channels
        channels = self.__getSelectedItems(self.channelListWidget)
        if self.hasChannels and not channels:
            QMessageBox.information(self, 'Information',
                'Please, select at least one channel.'
            )
            self.channelListWidget.setFocus()
            return

        # Verify output directory
        output =  self.outputDirectoryLineEdit.text()
        if not output:
            QMessageBox.information(self, 'Information',
                'Please, select a directory to save files.'
            )
            self.outputDirectoryLineEdit.setFocus()
            return

        # Get selected dates
        start = self.startDateTimeEdit.date().toPyDate()
        end = self.endDateTimeEdit.date().toPyDate()

        progress = ProgressDialog(self)

        # Start search and download
        download = ProcessRunnable(target=goes.downloader.download,
                        args=(self.bucket, products, start, end, hours, channels, output, progress))

        download.start()

        progress.exec()

    def __getSelectedItems(self, listWidget):
        values = []
        for i in range(listWidget.count()):
            item = listWidget.item(i)
            if item.checkState():
                values.append(item.text())
        return values

class ProgressDialog(QDialog):
    def __init__(self, parent=None):
        super(ProgressDialog, self).__init__(parent=parent)
        # Load user-interface from ui file
        uic.loadUi('./ui/progress.ui', self)
        # Flag that indicates if process was canceled
        self.canceled = False
        # Signal & slots
        self.cancelPushButton.released.connect(self.onCancelPushButtonReleased)

    @pyqtSlot(int)
    def onStartDownloadTask(self, numberOfFiles):
        self.progressBar.setMaximum(numberOfFiles)
        self.progressBar.setValue(0)

    @pyqtSlot(str)
    def onStartFileDownload(self, file):
        self.__appendText(('- Downloading {}'.format(file.split('/')[-1])))

    @pyqtSlot(str)
    def onEndFileDownload(self, file):
        self.__appendText(('* Finished -> {}'.format(file)))
        self.progressBar.setValue(self.progressBar.value() + 1)

    @pyqtSlot()
    def onEndDownloadTask(self):
        self.__appendText('Done!')
        self.progressBar.setValue(self.progressBar.maximum())
        QApplication.restoreOverrideCursor()

    def onCancelPushButtonReleased(self):
        self.canceled = True
        self.__appendText('\n*** Aborting. Please, wait... ***')
        self.cancelPushButton.setDisabled(True)
        QApplication.setOverrideCursor(Qt.WaitCursor)

    def wasCanceled(self):
        return self.canceled

    def __appendText(self, text):
        self.notificationPlainTextEdit.appendPlainText(text)
        scrool = self.notificationPlainTextEdit.verticalScrollBar()
        scrool.setValue(scrool.maximum())

class ProcessRunnable(QRunnable):
    def __init__(self, target, args):
        QRunnable.__init__(self)
        self.t = target
        self.args = args
        self.setAutoDelete(True)

    def __del__(self):
        QThreadPool.globalInstance().waitForDone()

    def run(self):
        self.t(*self.args)

    def start(self):
        QThreadPool.globalInstance().start(self)


import datetime as date
from dataclasses import dataclass

@dataclass
class dag_info:
    yesterday: date = date.date.today() - date.timedelta(1)
    airflow_home: str = None
    backend_url: str = ''
    dag_id: str = None
    owner: str = 'chequer'
    start_date: str = None
    catchup = 'False'
    schedule_interval: str = '@once'
    csv_files_directory: str = None

@dataclass
class db_info:
    db_type: int = None
    host: str = None
    port: str = None
    account: str = None
    id: str = None
    pwd: str = None
    warehouse: str = None
    option: str = None
    role: str = None

@dataclass
class user_data_carrier:
    columns: list = None
    pk: list = None
    updated: list = None
    schema: list = None
    dag_ids: list = None
    status: list = None
    upsert_rule: list = None
    tables: list = None
    status: list = None
    database: list = None
    schema: list = None

@dataclass
class user_all_data:
    def __init__(self, dag_id, id, pwd, columns, pk, updated, upsert_rule, tables, database,
                 csv_file_directory, warehouse='', option='', role='', schema=[], host='', port='',account=''):
        self.dag_id = dag_id
        self.host = host
        self.port = port
        self.id = id
        self.pwd = pwd
        self.columns = columns
        self.pk = pk
        self.updated = updated
        self.upsert_rule = upsert_rule
        self.tables = tables
        self.database = database
        self.csv_files_directory = csv_file_directory
        self.warehouse = warehouse
        self.option = option
        self.role = role
        self.schema = schema
        self.account = account

    dag_id: str = None
    host: str = None
    port: str = None
    account: str = None
    id: str = None
    pwd: str = None
    warehouse: str = None
    option: str = None
    role: str = None
    columns: list = None
    pk: list = None
    updated: list = None
    schema: list = None
    upsert_rule: list = None
    tables: list = None
    database: list = None
    csv_files_directory: str = None


from dobihtml import DobiHtml
from bs4 import BeautifulSoup

odziv = DobiHtml.dobi_html('http://www.cbz.si/zzzs/pao/bazazdr2.nsf/pregled13?openview&count=20000%27')
soup = BeautifulSoup(odziv, 'html.parser')
vrstice_zdravila = soup.find_all('tr', valign = 'top')

# pridobivamo podatke zdravil iz cbz.si
zdravila = []
def pridobi():
    for vrstica_zdravilo in vrstice_zdravila:
        td_ime = vrstica_zdravilo.find_all('td', class_ = 'textbarva0 gen-5')[0]
        td_sifra = vrstica_zdravilo.find_all('td', class_ = 'textbarva0 ts-s-4-6 ts-sez-c')[0]
        td_imetnik_dovoljenja = vrstica_zdravilo.find_all('td', class_ = "textbarva1")[1]
        td_cena = vrstica_zdravilo.find_all('td', class_ = 'textbarva4', width = '165')[0]

        a = td_ime.find_all('a')[1]
        ime = a.contents[0]
        sifra = td_sifra.contents[0]
        imetnik_dovoljenja = None if td_imetnik_dovoljenja.contents == [] else td_imetnik_dovoljenja.contents[0]
        cena = td_cena.find_all('center')[0].contents[0]
        zdravila.append((sifra, ime, cena, imetnik_dovoljenja))
    return zdravila

if __name__ == '__main__':
    pass


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr  8 09:37:55 2021

@author: omartin
"""

import numpy as np
from astropy.table import Table
import matplotlib.pyplot as plt

def estimateLoopDelay(hdr):

    wssmprg  = int(hdr['WSSMPRG'])
    _,aoMode = getStagePositionWFS(hdr)

    if wssmprg == 0:
        t0 = 8000e-6
    if wssmprg == 1:
        t0 = 2600e-6
    if wssmprg == 2:
        t0 = 850e-6
    if wssmprg == 3:
        t0 = 700e-6
    if wssmprg == 4:
        t0 = 28000e-6
    if wssmprg == 5:
        t0 = 9500e-6
    if wssmprg == 6:
        t0 = 2000e-6
    if wssmprg == 7:
        t0 = 1350e-6

    # Total delays
    t8    = 40e-6
    delay = t0+t8

    if aoMode == 'NGS':
        t9        = 1e-6
        t10       = 2e-6
        textra_tt = 200e-6 # retrieved from rejection transfer function fit
        delay_tt  = t0 + t9 + t10 + textra_tt
    else:
        delay_tt  = 1e-3 #STRAP

    return delay, delay_tt

def getScale(hdr):
    """
    Returns the instrument pixel scale in mas
    """
    instName = getInstName(hdr)
    if instName == 'NIRC2':
        # Setup NIRC2 plate scales
        scales = {"NARROW": 9.942,
              "MEDIUM": 19.829,
              "WIDE": 39.686}
        return scales[hdr['CAMNAME'].upper()]

    elif instName == 'OSIRIS':
        return 9.95
    else:
        return None

def getPA(hdr):
    #theta = float(hdr['ROTPOSN']) - float(hdr['EL']) - getInstAngle(hdr)
    theta = float(hdr['ROTPOSN']) - getInstAngle(hdr)
    return theta

def getPupilMask(hdr):
    return hdr['PMSNAME']

def getTelescopeAirmass(hdr):
    el = float(hdr['EL'])
    zenithAngle = 90 - el
    airmass      = 1/np.cos(zenithAngle*np.pi/180)
    return zenithAngle,airmass

def getInstAngle(hdr):
    """
    Returns the instrument pupil position in degrees
    """
    instName = getInstName(hdr)
    if instName == 'NIRC2':
        return float(hdr['INSTANGL'])
    elif instName == 'OSIRIS':
        return float(hdr['INSTANGL']) - 42.5
    else:
        return 0

def getInstName(hdr):
    return hdr['CURRINST']

def getCentralWavelength(hdr):
    """
    Returns the central wavelength in meters
    """
    return float(hdr['CENWAVE'])*1e-6

def getGain(hdr):
    return hdr['DETGAIN']

def getFilterName(hdr):
    instName = getInstName(hdr)
    if instName == 'NIRC2':
        filter1 = hdr['fwiname']
        filter2 = hdr['fwoname']
        filt = filter1
        if (filter1.startswith('PK')):
            filt = filter2

        return filt
    elif instName == 'OSIRIS':
        f = hdr['ifilter']
        return f.split('-')[0]
    else:
        return None

def getFilterProfile(path_filter,spectral_filter):
    """
    Returns the wavelength (in microns) and the transmission for
    the specified NIRC2 filter.

    Example:
    (wave, trans) = nirc2.photometry.get_filter_profile('Kp')
    py.clf()
    py.plot(wave, trans)
    py.xlabel('Wavelength (microns)')
    py.ylabel('Transmission')
    """
    spectral_filter = spectral_filter.replace('_','')

    filters = ['J', 'H', 'K', 'Kcont', 'Kp', 'Ks', 'Lp', 'Ms',
               'Hcont', 'Brgamma', 'FeII']

    filters_upper = [x.upper() for x in filters]

    if spectral_filter.upper() not in filters_upper:
        print( 'Could not find profile for filter %s.' % spectral_filter)
        print( 'Choices are: ', filters)
        return

    spectral_filter = filters[filters_upper.index(spectral_filter.upper())]
    table = Table.read(path_filter + spectral_filter + '.dat', format='ascii')

    wavelength = table[table.colnames[0]]
    transmission = table[table.colnames[1]]

    # Lets fix wavelength array for duplicate values
    diff = np.diff(wavelength)
    idx = np.where(diff <= 0)[0]
    wavelength[idx+1] += 1.0e-7

    # Get rid of all entries with negative transmission
    idx = np.where(transmission > 1)[0]
    wavelength = wavelength[idx]
    transmission = transmission[idx] / 100.0 # convert from % to ratio

    return (wavelength*1e-6, transmission)

def getDate(hdr):
    return hdr['DATE-OBS']

def getNCPAstr(hdr):
    """
    """
    date = getDate(hdr)
    numMonth = date[5:7]
    strMonth = ''
    strYear = date[0:4]
    if numMonth == '01': pass
    elif numMonth == '02':
        strMonth = 'Feb'
    elif numMonth == '03':
        strMonth = 'March'
        strDay = date [8:10]
        NCPAstr = strDay+ strMonth + strYear + '_PD1'
    elif numMonth == '04': pass
    elif numMonth == '05': pass
    elif numMonth == '06': pass
    elif numMonth == '07': pass
    elif numMonth == '08':
        strMonth = 'Aug'
    elif numMonth == '09':
        strMonth = 'Sept'
    elif numMonth == '10': pass
    elif numMonth == '11': pass
    elif numMonth == '12': pass

    if numMonth != '03':
        NCPAstr = strMonth + '_' + strYear

    return 'NCPA_Keck_' + NCPAstr + '.fits'

def getExposureConfig(hdr):

    ittime   = hdr['ITIME']
    coadds   = hdr['COADDS']
    sampmode = hdr['SAMPMODE']
    numreads = hdr['MULTISAM']
    gain     = hdr['GAIN']
    if sampmode == 2:
        ron = 60
    else:
        ron = 15.0 * (16.0 / numreads)**0.5

    return ittime,coadds,sampmode,numreads,ron,gain

def samplingFilterProfile(path_filter,hdr,nWvl=3,thresold=0.9,bwMin = 100e-9,display=False):
    """
    """
    # reading the .dat file
    instName = getInstName(hdr)
    (wvl_all,tr_all)= getFilterProfile(path_filter,getFilterName(hdr))
    # fitting the transmission curve
    id_f    = tr_all > thresold*tr_all.max()
    tr_f    = tr_all[id_f]
    wvl_f   = wvl_all[id_f]
    # linear regression
    p       = np.polyfit(wvl_f,tr_f,1)
    tr_f    = np.polyval(p,wvl_f)
    # compressing the profile for PSF fitting; more bins means longer PSF model computation
    wvlMin = wvl_f.min()
    wvlMax = wvl_f.max()
    bw     = wvlMax - wvlMin
    # consider a monochromatic filter if the bandwith is smaller than the threshold
    if bw <= bwMin:
        nWvl = 1
    # perform the linear regression on the desired wavelengths
    if nWvl > 1:
        wvl_c  = np.linspace(wvlMin,wvlMax,nWvl)

    elif nWvl <=1:
         wvl_c  = np.array([getCentralWavelength(hdr)])
         bw     = 0.0
    tr_c   = np.polyval(p,wvl_c)

    # assumption : no chromatic dispersion
    disp = [list(np.zeros(nWvl)),list(np.zeros(nWvl))]

    if display:
        # plotting
        plt.figure(figsize=(7,7))
        plt.plot(wvl_all*1e6,tr_all,'b',label='True profile')
        plt.plot(wvl_f*1e6,tr_f,'r',label='Fitted profile')
        plt.plot(wvl_c*1e6,tr_c,'ks',label='Compressed profile')
        plt.xlabel('Wavelength [µm]')
        plt.ylabel('Transmission')
        plt.title(instName+' filter transmission')
        plt.legend()

    return wvl_c, bw, tr_c, disp

def getSaturationLevel(instName):
        """
        Set to the 95% saturation threshold in DN.
        """
        if instName == 'NIRC2':
            return 12000.0
        elif instName == 'OSIRIS':
            return 20000.0
        else:
            return np.inf

def getStagePositionWFS(hdr):
    """

    """
    OBWF   = float(hdr['OBWF'])
    LSPROP = hdr['LSPROP'].upper()
    if LSPROP == 'YES':
        aoMode = 'LGS'
        AOFCLGFO    = float(hdr['AOFCLGFO'])*1e3 #mm
        zstage_defocus = abs(OBWF - AOFCLGFO)
    else:
        aoMode = 'NGS'
        AOFCNGFO    = float(hdr['AOFCNGFO'])*1e3
        zstage_defocus = abs(OBWF - AOFCNGFO)

    return zstage_defocus, aoMode

def getWFSwavelength(hdr):
    return float(hdr['GUIDWAVE'])*1e-6


import numpy as np
import scipy.stats
from math import sqrt, log

from . import lib

def compute_perrakis_estimate(marginal_sample, lnlikefunc, lnpriorfunc,
                              lnlikeargs=(), lnpriorargs=(),
                              densityestimation='histogram', **kwargs):
    """
    Computes the Perrakis estimate of the bayesian evidence.

    The estimation is based on n marginal posterior samples
    (indexed by s, with s = 0, ..., n-1).

    :param array marginal_sample:
        A sample from the parameter marginal posterior distribution.
        Dimensions are (n x k), where k is the number of parameters.

    :param callable lnlikefunc:
        Function to compute ln(likelihood) on the marginal samples.

    :param callable lnpriorfunc:
        Function to compute ln(prior density) on the marginal samples.

    :param tuple lnlikeargs:
        Extra arguments passed to the likelihood function.

    :param tuple lnpriorargs:
        Extra arguments passed to the lnprior function.

    :param str densityestimation:
        The method used to estimate the marginal posterior density of each
        model parameter ("normal", "kde", or "histogram").

    Other parameters
    ----------------
    :param kwargs:
        Additional arguments passed to estimate_density function.

    :return:

    References
    ----------
    Perrakis et al. (2014; arXiv:1311.0674)
    """

    if not isinstance(marginal_sample, np.ndarray):
        marginal_sample = np.array(marginal_sample)

    number_parameters = marginal_sample.shape[1]

    ##
    # Estimate marginal posterior density for each parameter.
    log_marginal_posterior_density = np.zeros(marginal_sample.shape)

    for parameter_index in range(number_parameters):

        # Extract samples for this parameter.
        x = marginal_sample[:, parameter_index]

        # Estimate density with method "densityestimation".
        log_marginal_posterior_density[:, parameter_index] = \
            estimate_logdensity(x, method=densityestimation, **kwargs)

    # Compute produt of marginal posterior densities for all parameters
    log_marginal_densities = log_marginal_posterior_density.sum(axis=1)
    ##

    # Compute log likelihood in marginal sample.
    log_likelihood = lnlikefunc(marginal_sample, *lnlikeargs)

    # Compute weights (i.e. prior over marginal density)
    w = weight(marginal_sample, lnpriorfunc, lnpriorargs,
               log_marginal_densities)

    # Mask values with zero likelihood (a problem in lnlike)
    cond = log_likelihood != 0

    # Use identity for summation
    # http://en.wikipedia.org/wiki/List_of_logarithmic_identities#Summation.2Fsubtraction
    # ln(sum(x)) = ln(x[0]) + ln(1 + sum( exp( ln(x[1:]) - ln(x[0]) ) ) )
    # log_summands = log_likelihood[cond] + np.log(prior_probability[cond])
    #  - np.log(marginal_densities[cond])
    perr = lib.log_sum(w[cond] + log_likelihood[cond]) - log(len(w[cond]))

    return perr

def weight(marginal_sample, lnpriorfunc, lnpriorargs, log_marginal_densities):
    """
    Compute the weights for the Perrakis estimator.

    :param marginal_sample:
        A sample from the parameter marginal posterior distribution.
        Dimensions are (n x k), where k is the number of parameters.

    :param callable lnpriorfunc:
        Function to compute ln(prior density) on the marginal samples.

    :param tuple lnpriorargs:
        Extra arguments passed to the lnprior function.

    :param array log_marginal_densities:
        1-D array containing the value of the sum of the log marginal densities
        evaluated in the marginal_sample.

    :return: array with the wegiht values
    """
    log_prior = lnpriorfunc(marginal_sample, *lnpriorargs)
    return log_prior - log_marginal_densities

def estimate_logdensity(x, method='histogram', **kwargs):
    """
    Estimate log probability density based on a sample. Return value of density
    at sampled points.

    :param array_like x: sample.

    :param str method:
        Method used for the estimation. 'histogram' estimates the density based
        on a normalised histogram of nbins bins; 'kde' uses a 1D non-parametric
        gaussian kernel; 'normal approximates the distribution by a normal
        distribution.

    Additional parameters

    :param int nbins:
        Number of bins used in "histogram method".

    :return: density estimation at the sample points.
    """

    nbins = kwargs.pop('nbins', 100)

    if method == 'normal':
        # Approximate each parameter distribution by a normal.
        return scipy.stats.norm.logpdf(x, loc=x.mean(), scale=sqrt(x.var()))

    elif method == 'kde':
        # Approximate each parameter distribution using a gaussian
        # kernel estimation
        return scipy.stats.gaussian_kde(x).logpdf(x)

    elif method == 'histogram':
        # Approximate each parameter distribution based on the histogram
        # Uses nbins keyword parameter.
        density, bin_edges = np.histogram(x, nbins, density=True)

        # Find to which bin each element corresponds
        density_indexes = np.searchsorted(bin_edges, x, side='left')

        # Correct to avoid index zero from being assiged to last element
        density_indexes = np.where(density_indexes > 0, density_indexes,
                                   density_indexes + 1)

        return np.log(density[density_indexes - 1])

def make_marginal_samples(joint_sample, nsamples=None, seed=None):
    """
    Reshuffles samples from joint distribution of k parameters to obtain
    samples from the _marginal_ distribution of each parameter.

    :param np.array joint_sample:
        Sample from the parameter joint distribution. Dimensions are (n x k),
        where k is the number of parameters.

    :param nsamples:
        Number of samples to produce. If 0, use number of joint samples.
    :type nsamples:
        int or None

    :param seed:
        If not None, use as seed for random number generator.
    :type seed:
        int or None

    :return: shuffled version of joint distribution sample.
    """
    if seed is not None:
        np.random.seed(seed)

    if nsamples > len(joint_sample) or nsamples is None:
        nsamples = len(joint_sample)

    # Randomly select parameter vector elements from different joint dist.
    # samples
    number_parameters = joint_sample.shape[-1]

    ind = np.random.randint(joint_sample.shape[0],
                            size=(nsamples, number_parameters))

    return joint_sample[ind, range(number_parameters)]


import requests

def get_blaa_events_list(page):
    url = 'https://admin.banrepcultural.org/api/actividades?/api/taxonomias/etiquetas?tid_raw_4=1192&page={page}'
    response = requests.get(url.format(page=page), verify=False)
    data = response.json()
    nodes = data['nodes']
    view = data['view']
    pages_count = view['pages']
    events = []
    for node in nodes:
                events.append(node)
    return events, pages_count

def get_blaa_event(event_id):
    url = 'https://admin.banrepcultural.org/api/actividades/detalle?alias={event_id}'
    url = url.format(event_id=event_id.lstrip('/'))
    response = requests.get(url, verify=False)
    data = response.json()
    return data['nodes'][0]


import setuptools

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

setuptools.setup(
    name="discordpy_utils",
    version="0.0.1",
    author="EvieTheFlareon",
    author_email="hi.evietheflareon@outlook.com",
    description="A helpful package for discord.py",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/FlareonUwU/discordpy_utils",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.7',
)


import json
from fnmatch import translate
from difflib import get_close_matches

data = json.load(open("data.json"))

def translate(word):
    word = word.lower()
    if word in data:
        return data[word]
    elif word.title() in data:
        return data[word.title()]
    elif word.upper() in data:
        return data[word.upper()]
    else:
        print(" word is invalid")

word = input(" Enter the word to be Searched")
output = translate(word)

if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)


import pytest
from faker import Faker

from package.routes.user.inputs.BioInput import BioInput
from tests.fixtures.auth_client import AuthClient

@pytest.mark.anyio
async def test_bio(
    auth_client: AuthClient,
    faker: Faker
):
    before = await auth_client.acquire_user()

    assert before.bio is None

    body = BioInput(
        bio=faker.sentence()
    )

    response = await auth_client.patch('/user/bio', json=body.dict())
    after = await auth_client.acquire_user()

    assert response.json()['success']
    assert after.bio == body.bio


import imutils
from PIL import Image
def watermark_photo(waterpark_path,input_path,Output_path):

    img=Image.open(waterpark_path)

    Base=Image.open(input_path)
    position=((Base.width-img.width),0)
    img = img.convert("RGBA")
    datas = img.getdata()

    newData = []
    for item in datas:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)

    img.putdata(newData)
    Base.paste(img,position,img)
    Base.save(Output_path)
    # img.save()


from socket import socket
import json
import time

host = 'sawtooth-shell'
# host = '192.168.192.4'
host = '127.0.0.1'

commands = {"set_msgs" : [{"action" : "set", "name" : "station0", "value" : 1},
                    {"action" : "set", "name" : "station1", "value" : 0},
                    {"action" : "set", "name" : "station2", "value" : 1},
                    {"action" : "set", "name" : "station3", "value" : 0}
                    ],
            "inc_msgs" : [{"action" : "inc", "name" : "station0", "value" : 1},
                    {"action" : "inc", "name" : "station1", "value" : 1},
                    {"action" : "inc", "name" : "station2", "value" : 1},
                    {"action" : "inc", "name" : "station3", "value" : 1},
                    ],
            "show_msgs" : [{"action" : "show", "name" : "station0", "value" : 1},
                    {"action" : "show", "name" : "station1", "value" : 1},
                    {"action" : "show", "name" : "station2", "value" : 1},
                    {"action" : "show", "name" : "station3", "value" : 1},
                    ],
            "list_msgs" : {"action" : "list", "name" : "station0", "value" : 1}
}

class sawtoothClient():
  """docstring for client"""
  def __init__(self, host='127.0.0.1', port=9000):
    self.host = host
    self.port = port
    self.socket = socket()
    self._connect()

  def _connect(self):
    self.socket.connect((self.host, self.port))

  def _sendMessage(self,message):
    self.socket.send(message.encode())
    feedbackResp = self.socket.recv(1024).decode()
    return feedbackResp

  def deconnect(self):
    self.socket.close()

  def initialiseValues(self):
    messages_raw = commands['set_msgs']
    for message_raw in messages_raw:
      message = json.dumps(message_raw)
      feedbackResp = self._sendMessage(message)
      time.sleep(0.1)

  def sendInc(self, stationNum, value=1):
    message_raw = commands["inc_msgs"][stationNum]
    message = json.dumps(message_raw)
    message['value'] = value
    feedbackResp = self._sendMessage(message)
    time.sleep(0.1)
    return feedbackResp

  def sendShow(self, stationNum):
    message_raw = commands["show_msgs"][stationNum]
    message = json.dumps(message_raw)
    feedbackResp = self._sendMessage(message)
    time.sleep(0.1)
    return feedbackResp

  def sendList(self):
    message_raw = commands["list_msgs"]
    message = json.dumps(message_raw)
    feedbackResp = self._sendMessage(message)
    time.sleep(0.1)
    return feedbackResp


import telebot
from telebot import types
import psycopg2
import os
import json
import keyB
conn = psycopg2.connect(host='',
                        dbname='',
                        user='',
                        password='')
curs = conn.cursor()

bot = telebot.TeleBot("")

####################################находится ли id в определённом состоянии################################
def check(conditions, my_id):
	try:
		curs.execute("SELECT cond FROM users WHERE user_id = %s;",(my_id,))
		if (curs.fetchall()[0][0]) == conditions:
			return True
	except:
		pass

	return False
##################################есть ли данные###########################################################
def if_NULL(my_id):
	try:
		curs.execute("SELECT struc FROM users WHERE user_id = %s;",(my_id,))
		if curs.fetchone()[0] == '':
			return True
	except:
		return True
	return False

##########################################существует ли запись с таким id###################################
def exist(my_id):
	try:
		curs.execute("SELECT cond FROM users WHERE user_id = %s;",(my_id,))
		if curs.fetchone() == None:
			return False
		return True
	except:
		return False
#############################################приветствие####################################################
@bot.message_handler(commands=["start", "старт"])
def hello(message):
	bot.send_message(message.chat.id, """Привет, человек. Я помогу тебе составить программу тренировок.
		\nИспользуй клавиатуру\nЕё можно вызвать, воспользовавшись данной икнонкой.""",reply_markup=keyB.fkey())
	bot.send_photo(message.chat.id,'AgADAgADqqoxG70o6UktvVCAeVodcOjAtw4ABMgBwsHs5MEc6bIAAgI')

# @bot.message_handler(commands=['test'])
# def find_file_ids(message):
#     for file in os.listdir('img/'):
#         if file.split('.')[-1] == 'jpg':
#             f = open('img/'+file, 'rb')
#             msg = bot.send_photo(message.chat.id, f, None)
#             bot.send_message(message.chat.id, msg.photo, reply_to_message_id=msg.message_id)
#         time.sleep(3)

#####################################добавление данных в бд#################################################
@bot.message_handler(func=lambda message:  True and message.text == 'Добавить данные', content_types = ['text'])
def add_date1(message):
	if if_NULL(message.chat.id) == True:
		bot.send_message(message.chat.id,"""следующее твоё сообщение будет добавлено в базу данных\nВведи вес: """)
		curs.execute("INSERT INTO users VALUES (%s,%s,%s,%s,%s,%s,%s);",([message.chat.id,'NULL','NULL','NULL','NULL','NULL','weight']))
		conn.commit()
	else:
		bot.send_message(message.chat.id,"твои данные уже существуют, просто обнови их")

@bot.message_handler(func=lambda message: check('weight',message.chat.id), content_types = ['text'])
def add_date2(message):
	if message.text.isdecimal() == True:
		#тут нужно сделать проверку на нормальность данных
		curs.execute("UPDATE users SET weight = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('height', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Окей, теперь введи рост""")
	else:
		bot.send_message(message.chat.id,"""Просто введи цифру""")

@bot.message_handler(func=lambda message: check('height',message.chat.id), content_types = ['text'])
def add_date3(message):
	if message.text.isdecimal() == True:
		#тут нужно сделать проверку на нормальность данных
		curs.execute("UPDATE users SET height = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('age', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Окей, теперь введи возраст""")
	else:
		bot.send_message(message.chat.id,"""Просто введи цифру""")
@bot.message_handler(func=lambda message: check('age',message.chat.id), content_types = ['text'])
def add_date4(message):
	if message.text.isdecimal() == True:
		#тут нужно сделать проверку на нормальность данных
		curs.execute("UPDATE users SET age = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('gender', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Окей, теперь введи свой пол - М или Ж""")
	else:
		bot.send_message(message.chat.id,"""Просто введи цифру""")

@bot.message_handler(func=lambda message: check('gender',message.chat.id), content_types = ['text'])
def add_date5(message):
	if message.text in ['М','Ж']:
		#тут нужно сделать проверку на нормальность данных
		curs.execute("UPDATE users SET gender = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('struc', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""окей теперь укажи телосложение - Эктоморф, Мезоморф или Эндоморф""")
		bot.send_photo(message.chat.id, 'AgADAgADIqkxG3uG6UlV_1oyJvtIUUhPqw4ABOPJmzjzR-ZIFzUDAAEC')
	else:
		bot.send_message(message.chat.id,"""Введи данные правильно \n- М или Ж  """)

@bot.message_handler(func=lambda message: check('struc',message.chat.id), content_types = ['text'])
def add_date6(message):
	if message.text in ['Эктоморф','Мезоморф','Эндоморф']:
	#тут нужно сделать проверку на нормальность данных
		curs.execute("UPDATE users SET struc = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('zero', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Готово, все твои данные созданы, ты можешь посмотреть их в основном меню""")
	else:
		bot.send_message(message.chat.id,"""Введи данные правильно \n- Эктоморф, Мезоморф или Эндоморф""")

# #################################обновление даннных в бд###################################################
@bot.message_handler(func=lambda message:  True and message.text == 'Обновить мои данные', content_types = ['text'])
def update1(message):
	if exist(message.chat.id) == True:

		keyboard = types.InlineKeyboardMarkup()
		row = []
		row.append(types.InlineKeyboardButton(text="вес", callback_data="weight"))
		row.append(types.InlineKeyboardButton(text="рост", callback_data="height"))
		row.append(types.InlineKeyboardButton(text="возраст", callback_data="age"))
		row.append(types.InlineKeyboardButton(text="пол", callback_data="gender"))
		row.append(types.InlineKeyboardButton(text="ничего", callback_data="zero"))
		row.append(types.InlineKeyboardButton(text="телосложение", callback_data="struc"))

		keyboard.add(*row)
		bot.send_message(message.chat.id, "что будем обновлять?", reply_markup=keyboard)

	else:
		bot.send_message(message.chat.id,"""тебе нечего обновлять, добавь данные""")

@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
	if call.message:
		if call.data == "weight":
			bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="""введи новый вес""")
			curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('update_w', call.message.chat.id))
			conn.commit()
		elif call.data == "height":
			bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="""введи новый рост""")
			curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('update_h', call.message.chat.id))
			conn.commit()
		elif call.data == "age":
			bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="""введи новый возраст""")
			curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('update_a', call.message.chat.id))
			conn.commit()
		elif call.data == "struc":
			bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="""введи новое телосложение""")
			bot.send_photo(call.message.chat.id, 'AgADAgADIqkxG3uG6UlV_1oyJvtIUUhPqw4ABOPJmzjzR-ZIFzUDAAEC', None)
			curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('update_s', call.message.chat.id))
			conn.commit()
		elif call.data == "gender":
			bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="""введи новый пол (ты просто ошибся, когда заполнял данные, да?)""")
			curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('update_g', call.message.chat.id))
			conn.commit()
		elif call.data == "zero":
			bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="""Окей, что-то ещё?""")
			curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('zero', call.message.chat.id))
			conn.commit()

@bot.message_handler(func=lambda message: check('update_w',message.chat.id), content_types = ['text'])
def update_2(message):
	if message.text.isdecimal() == True:
		curs.execute("UPDATE users SET weight = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('zero', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Отлично, мы обновили твой вес""")
	else:
		bot.send_message(message.chat.id,"""Просто введи цифру""")
@bot.message_handler(func=lambda message: check('update_h',message.chat.id), content_types = ['text'])
def update_3(message):
	if message.text.isdecimal() == True:
		curs.execute("UPDATE users SET height = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('zero', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Отлично, мы обновили твой рост""")
	else:
		bot.send_message(message.chat.id,"""Просто введи цифру""")

@bot.message_handler(func=lambda message: check('update_a',message.chat.id), content_types = ['text'])
def update_4(message):
	if message.text.isdecimal() == True:
		curs.execute("UPDATE users SET age = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('zero', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Отлично, мы обновили твой возраст""")
	else:
		bot.send_message(message.chat.id,"""Просто введи цифру""")

@bot.message_handler(func=lambda message: check('update_s',message.chat.id), content_types = ['text'])
def update_5(message):
	if message.text in ['Эктоморф','Мезоморф','Эндоморф']:
		curs.execute("UPDATE users SET struc = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('zero', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Отлично, мы обновили твоё телосложение""")
	else:
		bot.send_message(message.chat.id,"""Введи данные правильно \n- Эктоморф, Мезоморф или Эндоморф""")

@bot.message_handler(func=lambda message: check('update_g',message.chat.id), content_types = ['text'])
def update_6(message):
	if message.text in ['М','Ж']:
		curs.execute("UPDATE users SET gender = %s WHERE user_id = %s;",(message.text, message.chat.id))
		conn.commit()
		curs.execute("UPDATE users SET cond = %s WHERE user_id = %s;",('zero', message.chat.id))
		conn.commit()
		bot.send_message(message.chat.id,"""Мы обновили твой пол...""")
	else:
		bot.send_message(message.chat.id,"""Введи данные правильно \n- М или Ж  """)

@bot.message_handler(func = lambda message: True and message.text == 'Показать мои данные', content_types = ['text'])
def show1(message):
	if if_NULL(message.chat.id) == False:
		curs.execute("SELECT weight, height, age, gender, struc from users WHERE user_id = %s;",(message.chat.id,))
		date = curs.fetchone()
		bot.send_message(message.chat.id,"Твои данные:\n\n"+"вес: "+str(date[0])+"\n"+"рост: "+str(date[1])+"\n"+"возраст: "+str(date[2])+"\n"+"пол: "+str(date[3])+"\n"+
										 "телосложение: "+str(date[4])+"\n")
	else:
		bot.send_message(message.chat.id,"твои данных ещё не существует, используй /add или /update")

@bot.message_handler(func=lambda message:  check('zero',message.chat.id) and message.text == 'Найти программу', content_types = ['text'])
def find_program(message):
	curs.execute("SELECT gender, struc from users WHERE user_id = %s;",(message.chat.id,))
	date = curs.fetchone()
	json_date  = []

	path_to_json = 'prog/'+date[0]+"/"+date[1]+"/"
	if  os.listdir(path_to_json) !=[]:
		json_files = [ x for x in os.listdir(path_to_json) if x.endswith("json") ]
		json_data = list()
		for json_file in json_files:
			json_file_path = os.path.join(path_to_json, json_file)
			with open (json_file_path, "r", encoding='utf-8') as f:
				bot.send_message(message.chat.id,  json.load(f)['text'])
	else:
		bot.send_message(message.chat.id,"Пока для таких параметров нет программы, попробуй использовать что-то ещё")

@bot.message_handler(func=lambda message:  check('zero',message.chat.id) and message.text == 'Как пользоваться ботом?', content_types = ['text'])
def hepl(message):
	keyboard = types.InlineKeyboardMarkup()
	row = []
	row.append(types.InlineKeyboardButton(text="поодержать в QIWI", url = 'https://qiwi.me/3282c84e-7c67-4f14-8037-9d770ff3d56b'))
	keyboard.add(*row)
	bot.send_message(message.chat.id, """Добавь в бота данные о себе и найди программу тренировок!\nДля связи с ботом ты можешь использовать клавиатуру, которая вызывается соответсвующей икнокой (рядом со скрепочкой над клавиатурой) некоторые разделы бота до сих пор находится в разработке. \n\nЕсли у тебя есть идеи или пожелания - пиши: @Nickolas_510\n\n
		Если ты хочешь поодержать проект деньгами""",reply_markup=keyboard)

#############################################################################################################
#Добавить статистику прогресса из json-бэкапов

if __name__ == "__main__":
    bot.polling(none_stop=True)


import pygame.sprite
from Util.asset_dictionary import AssetDictionary

class FrogNest(pygame.sprite.Sprite):
    """
    Pygame sprite class for frog nests used for checking the win condition.
    """

    # Constructor should be passed an int to indicate which nest position the sprite should go in
    def __init__(self, pos):
        """
        - :param pos:
            An int representing the "index" of the nest. Should be 1-5, with 1 representing the left-most nest and 5 representing the right-most nest.
        """
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([70, 50])
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect()
        self.rect.y = 40
        self.set_pos(pos)

    def set_pos(self, pos):
        """
        Helper method called by the constructor. Takes the position argument passed to the constructor and places the nest in the proper slot.

        - :param pos:
            An int representing the "index" of the nest. Should be 1-5, with 1 representing the left-most nest and 5 representing the right-most nest.
        - :return:
            None
        """
        if pos == 1:
            self.rect.x = 67

        elif pos == 2:
            self.rect.x = 230

        elif pos == 3:
            self.rect.x = 390

        elif pos == 4:
            self.rect.x = 550

        else:
            self.rect.x = 710

    def disable(self, render_group, disabled_nests, player):
        """
        Called when the player reaches a nest. Disables the nest for the given player.

        - :param render_group:
            A pygame LayerdUpdates object holding the sprites to be rendered in the game. The nest will be added to this group.
        - :param disabled_nests:
            A list of nests that have already been disabled. This list is independent of the player.disabled_nests attribute.
        - :param player:
            A Player object. This player will have their disabled_nests attribute updated with the nest.
        - :return:
            None
        """
        render_group
        # self.remove(win_group)
        self.image = AssetDictionary.asset_dict["win-frog"]
        self.add(render_group)
        self.add(disabled_nests)
        player.disabled_nests.add(self)


from discord.ext import commands

from Models.Context import Context

class SetupCog(commands.Cog):
    """
    初回起動時に行う処理。

    ロールからクラメンを取得し、内部データに保持する
    """
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        # 起動時にContextを生成しておく
        await Context.get_instance(self.bot)

        print("finish set up.")


import sys
read = sys.stdin.readline
ra = range
enu = enumerate

def a_int(): return int(read())

from itertools import product

# 画像でおいた自分の解説見て
N = a_int()
B = []
for _ in ra(N):
    A = read()[:-1]  # floatで扱うと誤差で死ぬ
    if '.' not in A:
        A += '.'
    for _ in range(9 - A[::-1].index('.')):
        A += '0'
    B.append(int(A[:-10] + A[-9:]))

N = []
M = []
for b in B:
    n = 0
    while ~b & 1:  # 偶数である限り
        b >>= 1
        n += 1
    N.append(n)

    m = 0
    while b % 5 == 0:  # 5で割れる限り
        b //= 5
        m += 1
    M.append(m)

cnt = [[0] * 19 for _ in ra(19)]
ans = 0
for n, m in zip(N, M):
    x = max(18 - n, 0)
    y = max(18 - m, 0)
    for i, j in product(range(x, 19), range(y, 19)):
        ans += cnt[i][j]
    # このデータをcntに追加
    cnt[min(n, 18)][min(m, 18)] += 1

print(ans)


from copy import deepcopy
from math import degrees
from naoqi import ALProxy
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from torch import nn

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch

from Human import HumanInterface
from io_routines import readCSV
from network import Net
from setting import *

class NAOInterface:

    def __init__(self, IP, PORT, JOINT_NANE='Joints', TIME_INTERVAL=0.5):
        self.jointSetName = JOINT_NANE
        self.motion = ALProxy("ALMotion", IP, PORT)
        self.joint_names = self.motion.getBodyNames(self.jointSetName) # list
        limits = np.array(self.motion.getLimits(self.jointSetName)) # numpy.ndarray
        # limits = torch.tensor(self.motion.getLimits(self.jointSetName)) # torch.tensor
        self.limits = {
            'minAngle':     limits[:, 0],
            'maxAngle':     limits[:, 1],
            'maxChange':    limits[:, 2],
            'maxTorque':    limits[:, 3]
        }
        self.jointAngles = []
        self.jointAnglesBackup = []

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

    def __str__(self):
        return ' '.join(self.joint_names)

    def __iter__(self):
        for joint in self.jointAngles:
            yield joint

    def __getitem__(self, i):
        return self.jointAngles[i]

    def readJointAnglesFromCSV(self, filenameList):
        self.jointAngles = []
        if type(filenameList) is str:
            filenameList = [filenameList]
        for filename in filenameList:
            df = pd.read_csv(filename)
            self.jointAngles += df.values.tolist()
        self.jointAnglesBackup = deepcopy(self.jointAngles)

    def writeJointAnglesToCSV(self, filename, mode='a'):
        file = open(filename, mode=mode)
        if mode == 'w':
            file.write(', '.join(self.joint_names)+'\n')
            for angle in self.jointAngles:
                file.write(', '.join(list(map(str, angle)))+'\n')
        elif mode == 'a':
            for angle in self.jointAngles:
                file.write(', '.join(list(map(str, angle)))+'\n')
        file.close()

    def getJointAngleDegrees(self):
        for joint in self.jointAngles:
            print(np.degrees(joint))

    def getJointNames(self):
        print('=====> Joint names:')
        print(self.joint_names)

    def getAngleLimits(self):
        print('=====> Lower bound:')
        print(self.limits['minAngle'])
        print('=====> Upper bound:')
        print(self.limits['maxAngle'])
        print('=====> Max angle velocity:')
        print(self.limits['maxChange'])

    def animateAngleLimit(self, jointName, inter=25, time=0.1, repeat=2):
        index = self.getJointIndex(jointName)
        print("Animate the limits on joint "+self.joint_names[index])
        minAngle = self.limits['minAngle'][index]
        maxAngle = self.limits['maxAngle'][index]
        sequence = np.linspace(minAngle, maxAngle, inter)
        sequence = np.hstack([sequence, sequence[::-1]])
        sequence = np.tile(sequence, repeat)
        TIME = [time * (i+1) for i in range(len(sequence))]
        self.motion.angleInterpolation(jointName, sequence[0], 1, True)
        raw_input('Press ENTER to start animate the joint limits.')
        self.motion.angleInterpolation(jointName, sequence.tolist(), TIME, True)

    def getJointIndex(self, jointName):
        return self.joint_names.index(jointName)

    def getCurrentJointAngle(self):
        return self.motion.getAngles(self.jointSetName, True)

    def addCurrentJointAngleToList(self):
        self.jointAngles.append(self.getCurrentJointAngle())

    def startRecordJointAngles(self):
        self.jointAngles = []
        CONTINUE = True
        while CONTINUE:
            nao.addCurrentJointAngleToList()
            if_continue = raw_input("If continue to record current joint angle (y/n): ")
            if if_continue in ['y', 'Y', 'yes']:
                CONTINUE = True
            elif if_continue in ['n', 'N', 'no']:
                CONTINUE = False
            else:
                if_continue = raw_input("Input 'y' or 'n': ")

    def transformJointAnglesListToHuman(self, human):
        for jointAngle in self.jointAngles:
            humanJointAngle = self.transformJointAnglesToHuman(human, jointAngle)
            human.jointAngles.append(humanJointAngle)

    def transformJointAnglesToHuman(self, human, jointAngle):
        humanJointAngle = [0] * len(human)
        humanJointAngle[human.getStartAngleIndex('RightShoulder')] = 90
        humanJointAngle[human.getStartAngleIndex('LeftShoulder')] = -90
        naoJointList = [
            'RShoulderRoll', 'LShoulderRoll', 'RShoulderPitch', 'LShoulderPitch',
            'RElbowRoll', 'LElbowRoll', 'RElbowYaw', 'LElbowYaw',
            'RWristYaw', 'LWristYaw'
        ]
        humanJointList = [
            ['RightArm', 0], ['LeftArm', 0], ['RightArm', 1], ['LeftArm', 1],
            ['RightForeArm', 1], ['LeftForeArm', 1], ['RightArm', 2], ['LeftArm', 2],
            ['RightForeArm', 2], ['LeftForeArm', 2]
        ]
        for naoJoint, humanJoint in zip(naoJointList, humanJointList):
            naoIndex = self.getJointIndex(naoJoint)
            humanIndex = human.getStartAngleIndex(humanJoint[0]) + humanJoint[1]
            if naoJoint in ['RShoulderRoll', 'LElbowYaw']:
                humanJointAngle[humanIndex] = degrees(jointAngle[naoIndex]) + 90
            elif naoJoint in ['LShoulderRoll', 'RElbowYaw']:
                humanJointAngle[humanIndex] = degrees(jointAngle[naoIndex]) - 90
            elif naoJoint in ['RShoulderPitch', 'LShoulderPitch']:
                humanJointAngle[humanIndex] = - degrees(jointAngle[naoIndex]) + 90
            elif naoJoint in ['RWristYaw', 'LWristYaw', 'RElbowRoll']:
                humanJointAngle[humanIndex] = degrees(jointAngle[naoIndex])
            elif naoJoint in ['LElbowRoll']:
                humanJointAngle[humanIndex] = - degrees(jointAngle[naoIndex])
            # print(naoJoint, naoIndex, degrees(jointAngle[naoIndex]), humanJoint, humanIndex, humanJointAngle[humanIndex])
        return humanJointAngle

    def loadNetwork(self, PATH):
        # self.net = xxx.load_state_dict(torch.load(PATH))
        pass

    def loadTalk(self, TALKFILE):
        self.talk = readCSV(TALKFILE)
        # self.joint_angles = self.net(self.talk)
        # self.cutAngles()

    def loadPoses(self, joint_angles):
        # joint_angles: torch.tensor / numpy.ndarray

        self.joint_angles = joint_angles.tolist()
        self.cutAngles()

        self.joint_name_angles = dict(zip(self.joint_names, self.joint_angles))

    def cutAngles(self):
        for joint in self.joint_angles:
            lower_index = joint < self.limits['minAngle']
            upper_index = joint > self.limits['maxAngle']
            joint[lower_index] = self.limits['minAngle'][lower_index]
            joint[upper_index] = self.limits['maxAngle'][upper_index]

    def cutOneAngle(self, joint):
        joint = np.array(joint)
        lower_index = joint < self.limits['minAngle']
        upper_index = joint > self.limits['maxAngle']
        joint[lower_index] = self.limits['minAngle'][lower_index]
        joint[upper_index] = self.limits['maxAngle'][upper_index]
        return joint.tolist()

    def executePose(self, jointAngle):
        T = [0.5] * len(jointAngle)
        self.motion.angleInterpolation("Joints", jointAngle, T, True)

    def executePosesOneByOne(self, index=None):
        T = [0.5] * len(self.joint_names)
        if index:
            print("=====> Pose index: %d." % (index+1))
            self.motion.angleInterpolation(self.jointSetName, self.jointAngles[index], T, True)
        else:
            for index, angle in enumerate(self.jointAngles):
                print("=====> Pose index: %d." % (index+1))
                self.motion.angleInterpolation(self.jointSetName, angle, T, True)
                raw_input("Press ENTER to continue ...")

    def generatePoses(self):
        pass

    def plotJoint(self, joint_name, *plt_args):
        try: plt.plot(self.joint_name_angles[joint_name], *plt_args)
        except ValueError: print('Warning: the joint name is not valid.')

    def stand(self):
        J = [0.0, 0.0, 1.5476394891738892, 0.1388729065656662, -1.5734877586364746, -0.044828496873378754, 2.802596928649634e-45, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.5476394891738892, -0.1388729065656662, 1.5734877586364746, 0.044828496873378754, -2.802596928649634e-45]
        T = [0.5] * len(J)
        self.motion.angleInterpolation("Joints", J, T, True)

if __name__ == "__main__":
    human = HumanInterface.createFromBVH('dataset/BVH/human_skeletion.bvh')
    human.readJointAnglesFromBVH('dataset/BVH/human_test.bvh')
    # human.readJointAnglesFromCSV('dataset/human_right_hand.csv')
    try: nao = NAOInterface(IP=P_NAO_IP, PORT=P_NAO_PORT)
    except: nao = NAOInterface(IP=NAO_IP, PORT=NAO_PORT)
    print(nao)
    nao.getAngleLimits(); exit()
    # nao.animateAngleLimit('LShoulderRoll')
    # HeadYaw HeadPitch
    # LShoulderPitch LShoulderRoll LElbowYaw LElbowRoll LWristYaw
    # LHipYawPitch LHipRoll LHipPitch LKneePitch LAnklePitch LAnkleRoll
    # RHipYawPitch RHipRoll RHipPitch RKneePitch RAnklePitch RAnkleRoll
    # RShoulderPitch RShoulderRoll RElbowYaw RElbowRoll RWristYaw

    nao.readJointAnglesFromCSV('dataset/NAO_overlap.csv')
    nao.executePosesOneByOne()
    exit()

    try:
        file = open('dataset/NAO_test.csv')
        lines = file.readlines()
        file.close()
        COUNT = len(lines)
    except: COUNT = 1

    if COUNT == 1:
        mode = 'w'
    else:
        mode = 'a'

    print("=====> Start to record key poses {}".format(COUNT))
    while COUNT <= len(human.jointAngles):
        naoJoint = human.transformJointAnglesToNAO(nao, human[COUNT-1])
        print(naoJoint)
        naoJoint = nao.cutOneAngle(naoJoint)
        print(naoJoint)
        nao.executePose(naoJoint)

        if_record = raw_input("If record current joint angle (y/n/s):")
        if if_record in ['y', 'Y', 'yes']:
            nao.addCurrentJointAngleToList()
            print("=====> Count: {} key poses collected".format(COUNT))
            COUNT += 1
            print("=====> Start to record key poses {}".format(COUNT))

        elif if_record in ['n', 'N', 'no']:
            continue
        elif if_record in ['s', 'S', 'stop']:
            break
        else:
            if_record = raw_input("Input 'y' or 'n': ", end='')

    nao.writeJointAnglesToCSV('dataset/NAO_test.csv', mode=mode)


from flask import Flask, render_template, url_for, request, redirect, Response
from datetime import datetime
import os
import main
import re
import sys

IMAGES_FOLDER = os.path.join('static', 'temporary_files')
TWEET_LEN = 140

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = IMAGES_FOLDER
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

# No caching at all for API endpoints.
@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '-1'
    return response

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        hashtag_name = request.form['hashtag']
        splitted_hashtags = [ht.strip() for ht in re.split(", ", hashtag_name)]
        if check_if_hashtags_are_valid(splitted_hashtags):
            main.run(splitted_hashtags)
            full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'fig100.png')
            return render_template("search.html", image = full_filename)
        else:
            return render_template("index.html")
    else:
        return render_template("index.html")

def check_if_hashtags_are_valid(hashtags):
    if len(hashtags) == 0:
        return False
    else:
        for ht in hashtags:
            if not (0 < len(ht) <= TWEET_LEN) or ht[0] != '#':
                return False
        return True

if __name__ == "__main__":
    app.run(debug=True)


from flask import Flask, render_template, Blueprint, request, session, g, redirect, url_for
import pyrebase
import time
import requests

from config import config, user_types
from auth import check_token
from incentives import i_portions

firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
db = firebase.database()
storage = firebase.storage()

INCENTIVE_AMOUNT = 10

bp = Blueprint("disposal", __name__, url_prefix="/disposal")

@bp.route("/home", methods=["GET"])
def get_disposal_home():
  return render_template("disposal/disposal_home.html")

@bp.route("/user/incentivize", methods=["POST"])
def item_incentivize():
  u_token = session['user_id']
  user_data = check_token(u_token)
  if user_data == "invalid token":
    g.user = None
    session.clear()
    return redirect(url_for('auth.login_user'))
  disposal_id = user_data['localId']

  params = request.get_json()
  item_id = params["item_id"]
  multiplier = float(params["multiplier"])

  #customer_id can be both registered & temp id
  customer_id = params["customer_id"]

  #get information about the item
  item_info = db.child("items").child(item_id).get().val()
  factory_id = item_info["factory_id"]

  if (int(item_info["incentive_status"]) == 1):
    return {"status": "item already claimed & incentivized"}, 403

  #update item status
  db.child("items").child(item_id).update({
    "item_location": disposal_id,
    "incentive_status": 1
  })

  c_incen = INCENTIVE_AMOUNT * multiplier * i_portions["customer"]
  f_incen = INCENTIVE_AMOUNT * i_portions["factory"]
  d_incen = INCENTIVE_AMOUNT * i_portions["disposal"]
  lo_incen = INCENTIVE_AMOUNT * i_portions["lottery"]
  le_incen = INCENTIVE_AMOUNT * i_portions["leaderboard"]

  #multiplier is 0.7 ~ 1.05 (70% to 105%)
  #depending on the multiplie, our total gain is 0.75 ~ 2.5 out of 10
  fc_delta = INCENTIVE_AMOUNT * (1 - multiplier) * i_portions["customer"]
  fc_incen = INCENTIVE_AMOUNT * i_portions["FullCycle"] + fc_delta

  #give incentives to customer, factory, disposal, and FullCycle
  ##0.5 to customer
  db.child("incentives").push({
    "product_id": item_info["product_id"],
    "item_id": item_info["item_id"],
    "customer_id": customer_id,
    "disposal_id": disposal_id,
    "factory_id": factory_id,
    "incentive_amount": [c_incen, f_incen, d_incen, fc_incen, lo_incen, le_incen],
    "c_incen_left": c_incen,
    "f_incen_left": f_incen,
    "d_incen_left": d_incen,
    "fc_incen_left": fc_incen,
    "lo_incen_left": lo_incen,
    "le_incen_left": le_incen,
    "timestamp": int(time.time()),
  })

  return {"status": "post success"}, 200

@bp.route("/temp/create", methods=["GET"])
def create_temp_qr():
  #assign temp id
  temp_id = "t-" + db.generate_key()
  db.child("users").child(temp_id).set({
    "temp_id": temp_id,
    "u_type": "temp_user"
  })

  return render_template("disposal/create_temp_qr.html", temp_id=temp_id)

@bp.route("dispose/step1", methods=["GET"])
def disposal_step_1():
  return render_template("disposal/disposal_step_1.html")

@bp.route("dispose/step2/<c_id>", methods=["GET"])
def disposal_step_2(c_id):
  return render_template("disposal/disposal_step_2.html", c_id=c_id)

@bp.route("dispose/step3/<c_id>/<i_id>", methods=["GET"])
def disposal_step_3(c_id, i_id):
  p_id = db.child("items").child(i_id).get().val()["product_id"]
  p_name = db.child("products").child(p_id).get().val()["product_name"]
  p_trash = db.child("products").child(p_id).get().val()["product_trash"]
  return render_template("disposal/disposal_step_3.html", c_id=c_id, i_id=i_id, p_name=p_name, p_trash=p_trash)


import inspect
from collections import deque
from functools import wraps
from typing import (
    Callable,
    NamedTuple,
    Sequence,
    Type,
    TypeVar,
    Union,
    cast,
    get_args,
    get_origin,
    get_type_hints,
)

from omegaconf import ListConfig
from typing_extensions import TypeGuard

_T = TypeVar("_T", bound=Callable)

__all__ = ["coerce_sequences"]

def _is_namedtuple_type(x) -> TypeGuard[Type[NamedTuple]]:  # pragma: no cover
    try:
        bases = x.__bases__
        fields = x._fields
    except AttributeError:
        return False

    if bases is None:
        return False

    if len(bases) != 1 or bases[0] is not tuple:
        return False

    if not isinstance(fields, tuple):
        return False

    return all(isinstance(fieldname, str) for fieldname in fields)

_NoneType = type(None)

_POSITIONAL_ONLY = inspect.Parameter.POSITIONAL_ONLY
_VAR_POSITIONAL = inspect.Parameter.VAR_POSITIONAL
_KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY
_VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD

def coerce_sequences(obj: _T) -> _T:
    """
    Hydra is only able to read non-string sequences as lists (or ListConfig).
    This wrapper will cast these lists to their desired type, based
    on the annotated-type associated with that sequence.

    This is a no-op for objects that don't have any annotated non-string
    sequence types.

    This is strictly an experimental utility. Use at your own risk.

    Parameters
    ----------
    obj : Callable

    Returns
    -------
    wrapped_obj

    Notes
    -----
    The supported non-string sequence types are:
    - tuples
    - dequeues
    - lists
    - named-tuples

    The only Union-based types that are supported are of the form
    ``Optional[<sequence-type>]``.

    Examples
    --------
    >>> from hydra_zen import builds, instantiate
    >>> def f(x: tuple): return x

    Without wrapping:

    >>> conf_no_wrap = builds(f, x=(1, 2))
    >>> instantiate(conf_no_wrap)
    [1, 2]

    With wrapping:

    >>> conf_wrapped = builds(f, x=(1, 2), zen_wrappers=convert_sequences)
    >>> instantiate(conf_wrapped)
    (1, 2)
    """
    if inspect.isclass(obj) and hasattr(type, "__init__"):
        hints = get_type_hints(obj.__init__)
    else:
        hints = get_type_hints(obj)

    if not hints:
        return cast(_T, obj)

    # We need to keep track of parameters that are annotated with
    # sequence-like annotations
    list_caster_by_pos = {}  # by pos-index in the signature
    list_caster_by_name = {}  # by param-name in the signature

    sig = inspect.signature(obj)
    for n, (name, param) in enumerate(sig.parameters.items()):  # pragma: no branch
        if name not in hints or param.kind in {_VAR_KEYWORD, _VAR_POSITIONAL}:
            continue

        annotation = hints[name]

        _origin = get_origin(annotation)

        if _origin is not None and _origin is Union:
            # Check for Optional[A]
            _args = get_args(annotation)
            if len(_args) == 2:
                if _args[0] is _NoneType:
                    annotation = _args[1]
                elif _args[1] is _NoneType:
                    annotation = _args[0]
                else:  # pragma: no cover
                    # E.g. Union[A, B]
                    # we cover this  in tests coverage-tooling struggles here
                    continue
            else:  # pragma: no cover
                # E.g. Union[A, B, C]
                # we cover this in tests but coverage-tooling struggles here
                continue
        del _origin

        if not isinstance(annotation, type):
            # E.g. annotation = Tuple[int, int]
            # Tuple[int, int].__origin__ -> tuple
            caster = get_origin(annotation)
            if caster is None:  # pragma: no cover
                continue
        else:
            # E.g. annotation = tuple
            caster = annotation

        if (
            inspect.isclass(caster)
            and issubclass(caster, Sequence)
            and not issubclass(caster, str)  # strings don't need to be cast
            and caster is not list  # annotation is list to begin with
        ):
            if caster in {tuple, deque}:
                pass
            elif _is_namedtuple_type(annotation):

                def _unpack(x):
                    return annotation(*x)

                caster = _unpack
            else:  # pragma: no cover
                # covered in tests but coverage-tooling struggles here
                continue

            if param.kind is not _KEYWORD_ONLY:
                list_caster_by_pos[n] = caster
            if param.kind is not _POSITIONAL_ONLY:  # pragma: no branch
                list_caster_by_name[name] = caster

    min_pos: int = min(list_caster_by_pos) if list_caster_by_pos else 0

    if not list_caster_by_name and not list_caster_by_pos:
        # no annotations associated with sequences
        return cast(_T, obj)

    @wraps(obj)
    def wrapper(*args, **kwargs):
        if list_caster_by_pos and min_pos < len(args):
            # at least one positional argument needs to be cast
            args = list(args)
            for pos in list_caster_by_pos:
                if pos < len(args):
                    if isinstance(args[pos], (list, ListConfig)):
                        args[pos] = list_caster_by_pos[pos](args[pos])
                else:
                    # pos is inserted in dict in ascending order
                    break
        if list_caster_by_name and kwargs:
            named = set(list_caster_by_name).intersection(kwargs)
            for name in named:
                # at least one named-arg needs to be cast
                if isinstance(kwargs[name], (list, ListConfig)):
                    kwargs[name] = list_caster_by_name[name](kwargs[name])

        return obj(*args, **kwargs)

    return cast(_T, wrapper)


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

# In[1]:

import sys #tuve que usar esto para poder importar sklearn, pandas y numpy
get_ipython().system('{sys.executable} -m pip install sklearn')
get_ipython().system('{sys.executable} -m pip install pandas')
get_ipython().system('{sys.executable} -m pip install numpy')

# In[2]:

import pandas as pd
import numpy as np
import sklearn as sk
from IPython.core.display import display
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv("data.csv")
display(df.head())
pd.isna(df).value_counts()
#elimino las entradas con más de un NaN
df = df.dropna(thresh=6)
pd.isna(df).value_counts()

vars = ['Year','Month','Day']
label_encoder = LabelEncoder()
for i in vars:
    df[i] = label_encoder.fit_transform(df[i])
df.dtypes

training_set, test_set = train_test_split(vars.copy(), test_size = 0.3)
training_set, validation_set = train_test_split(training_set.copy(), test_size = 0.1)

print(f'Tamaño set entrenamiento: {len(training_set)}')
print(f'Tamaño set validación: {len(validation_set)}')
print(f'Tamaño set test: {len(test_set)}')

#data = pd.read_csv(f'data.csv').rename(columns={'Unnamed: 0': 'Index'}).set_index('Index')
#data.head()

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
features = ['O3','PM2.5','Environmental_risk']

#training_set[features] = scaler.fit_transform(training_set[features])
#validation_set[features] = scaler.transform(validation_set[features])
#test_set[features] = scaler.transform(test_set[features])

#training_set.head()

# In[ ]:


from __future__ import absolute_import

from gevent import monkey

monkey.patch_all()  # NOQA

import json
import logging
import os
import signal

import yaml
from k8s import config as k8s_config

from fiaas_skipper.deploy import StatusTracker
from fiaas_skipper.update import AutoUpdater
from .config import Configuration
from .deploy import CrdDeployer, ReleaseChannelFactory, CrdBootstrapper, \
    FiaasApplication
from .deploy.channel import FakeReleaseChannelFactory
from .deploy.cluster import Cluster
from .logsetup import init_logging
from .web import create_webapp

from gevent.pywsgi import WSGIServer, LoggingLogAdapter

LOG = logging.getLogger(__name__)

class ExitOnSignal(Exception):
    pass

def signal_handler(signum, frame):
    signame = signal.Signals(signum).name
    LOG.critical(f"Received signal {signame}({signum}), exiting")
    raise ExitOnSignal()

def init_k8s_client(config, log):
    if config.client_cert:
        k8s_config.cert = (config.client_cert, config.client_key)

    if config.api_token:
        k8s_config.api_token = config.api_token
    else:
        # use default in-cluster config if api_token is not explicitly set
        try:
            # sets api_token_source and verify_ssl
            k8s_config.use_in_cluster_config()
        except IOError as e:
            if not config.client_cert:
                log.warn("No apiserver auth config was specified, and in-cluster config could not be set up: " + str(e))

    # if api_cert or debug is explicitly set, override in-cluster config setting (if used)
    if config.api_cert:
        k8s_config.verify_ssl = config.api_cert
    elif config.debug:
        k8s_config.verify_ssl = not config.debug

    k8s_config.api_server = config.api_server
    k8s_config.debug = config.debug
    k8s_config.timeout = 60

def _load_spec_config(spec_file):
    with open(spec_file, 'r') as stream:
        return yaml.safe_load(stream)

def _read_file(spec_file):
    with open(spec_file) as f:
        return f.read()

def main():
    cfg = Configuration()
    init_logging(cfg)
    log = logging.getLogger(__name__)
    init_k8s_client(cfg, log)
    for sig in (signal.SIGTERM, signal.SIGINT):
        signal.signal(sig, signal_handler)
    try:
        log.info("fiaas-skipper starting with configuration {!r}".format(cfg))
        cluster = Cluster()
        if cfg.release_channel_metadata:
            log.warning("!!Using hardcoded release channel metadata {!r}".format(cfg.release_channel_metadata))
            log.warning("!!Reading hardcoded release channel metadata spec file from {!r}".format(
                cfg.release_channel_metadata_spec))
            spec = _read_file(cfg.release_channel_metadata_spec)
            release_channel_factory = FakeReleaseChannelFactory(json.loads(cfg.release_channel_metadata), spec)
        else:
            release_channel_factory = ReleaseChannelFactory(cfg.baseurl)
        spec_config_extension = None
        if os.path.isfile(cfg.spec_file_override):
            try:
                spec_config_extension = _load_spec_config(cfg.spec_file_override)
                log.debug("Loaded spec config extension from file {!r}".format(cfg.spec_file_override))
            except yaml.YAMLError:
                log.exception("Unable to load spec config extension file {!r} using defaults"
                              .format(cfg.spec_file_override))
        deployer = CrdDeployer(cluster=cluster, release_channel_factory=release_channel_factory,
                               bootstrap=CrdBootstrapper(cfg.use_apiextensionsv1_crd),
                               spec_config_extension=spec_config_extension, rbac=cfg.manage_rbac)
        # Do period checking of deployment status across all namespaces
        status_tracker = StatusTracker(cluster=cluster, application=FiaasApplication,
                                       interval=cfg.status_update_interval)
        status_tracker.start()
        if not cfg.disable_autoupdate:
            updater = AutoUpdater(release_channel_factory=release_channel_factory, deployer=deployer,
                                  status=status_tracker)
            updater.start()
        else:
            log.debug("Auto updates disabled")
        webapp = create_webapp(deployer, cluster, release_channel_factory, status_tracker)
        log = LoggingLogAdapter(LOG, logging.DEBUG)
        error_log = LoggingLogAdapter(LOG, logging.ERROR)
        # Run web-app in main thread
        http_server = WSGIServer(("", cfg.port), webapp, log=log, error_log=error_log)
        http_server.serve_forever()
    except ExitOnSignal:
        pass
    except BaseException:
        log.exception("General failure! Inspect traceback and make the code better!")

if __name__ == "__main__":
    main()