import re
from collections import namedtuple
from detect_wizard_src.WizardLogger import WizardLogger

def test_sensitivity(op_val_pair: tuple, sensitivity):
    cmp_op, val = op_val_pair
    if cmp_op == '>':
        return sensitivity > val
    elif cmp_op == '<':
        return sensitivity < val
    elif cmp_op == '>=':
        return sensitivity >= val
    elif cmp_op == '<=':
        return sensitivity <= val
    elif cmp_op == "=" or cmp_op == "==":
        return sensitivity == val
    elif cmp_op == "!=":
        return sensitivity != val
    else:
        raise ValueError("{} is not a valid value for sensitivity comparison".format(op_val_pair))

def invert_op(op_val_pair: tuple):
    op, val = op_val_pair
    if op == "!=":
        return "==", val
    elif op == "==" or op == "=":
        return "!=", val
    elif op == "<=":
        return ">", val
    elif op == ">=":
        return "<", val
    elif op == ">":
        return "<=", val
    elif op == "<":
        return ">=", val

def format_op_val_pair(op_val_pair: tuple):
    return "sensitivity {} {}".format(*op_val_pair)

def format_value(val: str):

    if val.lower() == "true":
        return True
    elif val.lower() == "false":
        return False
    elif (val.startswith('"') and val.endswith('"')) or (val.startswith("'") and val.endswith("'")):
        return str(val[1:len(val)-1])
    elif val.isdecimal():
        return int(val)
    else:
        try:
            return round(float(val), 4)
        except ValueError:
            return val

def parse_cause_actions(cause_action_dict: dict, vars_dict: dict):
    output = {}
    for k, v in cause_action_dict.items():
        split_str = re.split("(?:\\s+(and|or)\\s+)", k)
        intermediate_results = []
        causes_for = []
        causes_against = []
        did_fail = False
        for component in split_str:
            findallret = re.findall("(^[a-z\\_]+) ([!<>=]+) ([0-9a-zA-Z\"\'.]+)$", component)
            if len(findallret) > 0:
                # this is an operator
                var, op, val = findallret[0]
                if var not in vars_dict.keys():
                    raise ValueError("Variable {} not found in vars_dict ({})".format(var, vars_dict.keys()))
                else:
                    test_result = test_sensitivity((op, format_value(val)), vars_dict[var])
                    the_result = test_result
                    if the_result:
                        causes_for.append("{} {} {}".format(var, op, val))
                    else:
                        did_fail = True
                        inv = invert_op((op, val))
                        causes_against.append("{} {} {}".format(var, inv[0], inv[1]))

                    if len(intermediate_results) > 0:
                        intermediate_results.append(intermediate_results.pop()(test_result))
                    else:
                        intermediate_results.append(test_result)
                    if did_fail:
                        break
            else:
                if component == "and":
                    intermediate_results.append(lambda x: intermediate_results.pop() and x)
                elif component == "or":
                    intermediate_results.append(lambda x: intermediate_results.pop() or x)
        if did_fail:
            output[v] = (intermediate_results[0], causes_against)
        else:
            output[v] = (intermediate_results[0], causes_for)

    return output

def parse_and_replace_action_vars(action, vars_dict: dict):
    if type(action) == str:
        action_vars = re.findall("\\${([a-zA-Z-0-9_]+)}", action)
        if action_vars is not None:
            for var_name in action_vars:
                if var_name == "OUT":
                    continue
                result = vars_dict[var_name]
                if callable(result):
                    return result
                action = action.replace("${" + "{}".format(var_name) + "}", str(format_value(str(result))))
    return action

class Actionable(object):
    wl = WizardLogger()
    Output = namedtuple("Output", ["outcome", "causes", "description"])

    def __init__(self, title: str, cause_action_dict, default_description=None):
        self.title = title
        self.cause_action_dict = cause_action_dict
        self.default = default_description

    def test(self, **vars_dict):
        output = parse_cause_actions(self.cause_action_dict, vars_dict)
        true_count = 0
        value_action = None
        failed_test_causes = set()
        for k, v in output.items():
            if v[0]:
                outcome = parse_and_replace_action_vars(k[0], vars_dict)
                desc = parse_and_replace_action_vars(k[1], vars_dict)
                if callable(outcome):
                    result = outcome()
                    if type(result) == list:
                        result = "\n".join(result)
                    desc = desc.replace("${OUT}", str(result))
                    outcome = result
                value_action = Actionable.Output(outcome=outcome, causes=v[1], description=desc)
                true_count += 1
            else:
                failed_test_causes = failed_test_causes.union(set(v[1]))
        if true_count == 0:
            value_action = Actionable.Output("NO-OP", failed_test_causes, parse_and_replace_action_vars(self.default, vars_dict))
        Actionable.wl.log(topic=self.title, causes=value_action.causes, outcome=value_action.outcome, description=value_action.description)
        return value_action

    def get_table(self, sensitivity_value):
        return Actionable.wl.make_table(sensitivity_value)

    def __str__(self):
        return "[{}]: ({} OR {})".format(self.title, self.cause_action_dict, self.default)

if __name__ == "__main__":
    a = Actionable("sig_scan", {"sensitivity < 2 or json_splitter = true": ("--detect.tools.excluded=SIGNATURE_SCAN", "thing"),
                                  "sensitivity > 5": ("--detect.tools.excluded=WOW", "do iother thing")}, "Default")
    print(a.test(sensitivity=5, json_splitter=False))


# -*- coding: utf-8 -*-
"""
Created on Sat Aug 19 07:55:33 2017

@author: AtotheM
"""

import pandas as pd
import os
dir_path = os.path.dirname(os.path.realpath(__file__))

##########################################################################################################
"""Import conductor resistance and reactance spreadsheet and create DataFrames of data"""
##########################################################################################################

conductorData = pd.read_excel(dir_path+"\Conductor Impedance.xlsx", skiprows=range(5)+[23,24],parse_cols=9)
conductorData = conductorData.drop(conductorData.columns[1], axis=1)

def dropKM(values):
    try:
        split = values.splitlines()
        km = float(split[0])
        feet = float(split[1])
    except Exception:
        return values
    return feet

conductorData = conductorData.applymap(dropKM)
conductorDataCopper = conductorData.drop(conductorData.columns[6:], axis=1)
conductorDataAlum = conductorData.drop(conductorData.columns[3:6], axis=1)

"""
AWG = AWG (up to 4/0) or kcmil (250 - 400) of wire
xL NF = Wire reactance in PVC and aluminum conduit per 1000 ft in ohms
xL F = Wire reactance in steel conduit per 1000 ft  in ohms
xR PVC = Wire resistance in PVC conduit per 1000 ft in ohms
xR Alum = Wire resistance in aluminum conduit per 1000 ft in ohms
xR Steel = Wire resistance in steel conduit per 1000 ft in ohms
"""
columnNames = ["AWG", "xL NF", "xL F", "xR PVC", "xR Alum", "xR Steel"]

conductorDataCopper.columns = columnNames
conductorDataAlum.columns = columnNames

conductorDataCopper = conductorDataCopper.set_index(["AWG"])
conductorDataCopper.index = conductorDataCopper.index.map(str)
conductorDataAlum = conductorDataAlum.set_index(["AWG"])
conductorDataAlum.index = conductorDataAlum.index.map(str)

##########################################################################################################
"""Other"""
##########################################################################################################

systemConfigDict = {
"12470/7200, 3PH": {"vLL":12470, "vLG":7200, "Phase":3},
"7200, 1PH": {"vLL":7200, "vLG":7200, "Phase":1},
"300/600, 1PH": {"vLL":600, "vLG":300, "Phase":1},
"600, 1PH": {"vLL":600, "vLG":600, "Phase":1},
"240/480, 1PH": {"vLL":480, "vLG":240, "Phase":1},
"480, 1PH": {"vLL":480, "vLG":480, "Phase":1},
"277, 1PH": {"vLL":277, "vLG":277, "Phase":1},
"208/120, 3PH": {"vLL":208, "vLG":120, "Phase":3},
"208, 1PH": {"vLL": 208, "vLG": 208, "Phase":1},
"120/240, 1PH": {"vLL":240, "vLG":120, "Phase":1},
"240, 1PH": {"vLL":240, "vLG":240, "Phase":1},
"120, 1PH": {"vLL":120, "vLG":120, "Phase":1},
"30/60, 1PH": {"vLL":60, "vLG":30, "Phase":1},
"60, 1PH": {"vLL":60, "vLG":60, "Phase":1},
"50, 1PH": {"vLL":50, "vLG":50, "Phase":1},
"15/30, 1PH": {"vLL":30, "vLG":15, "Phase":1},
"30, 1PH": {"vLL":30, "vLG":30, "Phase":1},
"12/24, 1PH":  {"vLL":24, "vLG":12, "Phase":1},
"24, 1PH": {"vLL":24, "vLG":24, "Phase":1}
}

voltageCompatDict = {
"12470": [12470, 7200],
"7200": [7200],
"600": [600, 300],
"480": [480, 277, 240],
"277": [277],
"240": [240, 120],
"208": [208, 120],
"120": [120, 60],
"60": [60, 30],
"50": [50],
"30": [30, 15],
"24": [24, 12]
}

compatWireSizes = ['14', '12', '10', '8', '6', '4', '3', '2', '1', '1/0', '2/0', '3/0', '4/0', '250', '300', '350', '400']
compatWireMaterial = ['copper', 'aluminum']
compatConduitMaterial = ['HDPE', 'PVC', "aluminum", "steel"]

WBASE = 1.0
VARBASE = 1.0

"""Example of how to access conductor data from DataFrame created above"""
# wireSize = 4
# print conductorDataCopper["xR PVC"].get(wireSize)


#!/usr/bin/python3
import random
import time
import sys
import curses
import argparse

__VERSION__ = "v0.1"

# matrix.py
# A cool matrix effect for your terminal!
# Fully customizable, of course.
# by illinoisjackson: https://github.com/illinoisjackson

if sys.version_info <= (3, 0):
    _PY2 = 1
else:
    _PY2 = 0

class ScreenSpace:
    def __init__(self, win):
        self.chars = []
        self.win = win
        self.size = self.win.getmaxyx()
        curses.start_color()
        curses.use_default_colors()
        self.win.nodelay(1)
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, -1)

    def addchar(self, x, y, char, mods):
        self.chars.append((x, y, char, mods))

    def render(self, debug=None):
        self.win.erase()
        self.size = self.win.getmaxyx()
        for ch in self.chars:
            if ch[0] >= 0:
                if ch[0] < self.size[1] - 1:
                    if ch[1] >= 0:
                        if ch[1] < self.size[0]:
                            try:
                                self.win.addstr(int(ch[1]), int(ch[0]), chr(
                                    ch[2]), curses.color_pair(ch[3]))
                            except:
                                pass
        if debug != None:
            for dstr in range(len(debug)):
                self.win.addstr(dstr, 0, debug[dstr], curses.color_pair(0))
        self.win.refresh()
        self.chars = []

    def destroy(self):
        curses.nocbreak()
        self.win.keypad(0)
        curses.echo()
        curses.endwin()

class Fade:
    def __init__(self, starttick, x, y, headcolor, colors, unics, length, lifetime, speed):
        self.st = starttick
        self.colors = colors
        self.lcolors = len(self.colors)
        self.headcolor = headcolor
        self.unics = unics
        self.length = length
        self.lt = lifetime
        self.speed = speed
        self.pos = [x, y]
        self.time = 0
        self.dstd = 0

    def render(self, tick, screenspace):
        self.time += 1
        for i in range(self.length):
            if i == 0:
                self.pendingcolor = self.headcolor
            else:
                self.pendingcolor = self.colors[int(
                    (i / self.length) * self.lcolors)]
            self.pendingchar = random.choice(self.unics)
            screenspace.addchar(self.pos[0], round(self.pos[1]) - i, self.pendingchar,
                                self.pendingcolor)
        self.pos[1] += self.speed
        if self.time == round(self.lt):
            self.dstd = 1

    def destroy(self):
        self = None

def print_error(s):
    print("\x1b[31m%s" % s)

def parse_chars(chrl, argp):
    charlist = []
    try:
        chrl = chrl.split(",")
        for chrr in chrl:
            if "-" in chrr:
                dashs = chrr.split("-")
                if len(dashs) == 2:
                    charlist.extend(range(int(dashs[0]), int(dashs[1])))
            elif chrr != "":
                charlist.append(int(chrr))
            assert len(charlist) > 0
        return charlist
    except:
        argp.print_help()
        print_error("Could not parse characters list!")
        sys.exit(1)

def parse_colors(cll, argp):
    headcolor = None
    colorlist = []
    try:
        mtchs = re.finditer(r"(\d*\!?)", cll)
        for mt in mtchs:
            mtchg = mt.group()
            if "!" in mtchg:
                headcolor = int(mtchg.strip("!"))
            elif mtchg != "":
                colorlist.append(int(mtchg))
        return headcolor, colorlist
    except:
        argp.print_help()
        print_error("Could not parse colors list!")
        sys.exit(1)

def main(stdscr, params, chars):
    STARTTIME = time.time()
    PARAMS = params
    FADES = [None for fd in range(PARAMS.fades)]
    TICK = 0
    SCSP = ScreenSpace(stdscr)
    for fade in range(PARAMS.fades):
        FADES[fade] = Fade(
            TICK,
            random.randint(0, SCSP.size[1]),
            random.randint(0, SCSP.size[0]),
            PARAMS.headcolor,
            [int(j) for j in PARAMS.colors.rstrip(",").split(",")],
            chars,
            random.randint(PARAMS.minlength, PARAMS.maxlength),
            random.uniform(PARAMS.minlifetime, PARAMS.maxlifetime),
            random.uniform(PARAMS.minspeed, PARAMS.maxspeed))
    try:
        while True:
            time.sleep(PARAMS.delay)
            for fade in range(PARAMS.fades):
                if FADES[fade].dstd == 1:
                    FADES[fade] = Fade(
                        TICK,
                        random.randint(0, SCSP.size[1]),
                        random.randint(0, SCSP.size[0]),
                        PARAMS.headcolor,
                        [int(j) for j in PARAMS.colors.rstrip(",").split(",")],
                        chars,
                        random.randint(PARAMS.minlength, PARAMS.maxlength),
                        random.uniform(PARAMS.minlifetime, PARAMS.maxlifetime),
                        random.uniform(PARAMS.minspeed, PARAMS.maxspeed))
            for fade in FADES:
                fade.render(TICK, SCSP)
            if SCSP.win.getch() == ord('q'):
                SCSP.destroy()
                sys.exit()
            deb = []
            if (time.time() - STARTTIME) < 2:
                deb.append("Press Q or CTRL-C to quit.")
                if _PY2:
                    deb.append("NOTE: Colors do not work properly in python2.")
                    deb.append("Try running in python3 to get colors working.")
            if PARAMS.debug == True:
                deb.append("matrix.py %s" % __VERSION__)
                deb.append("%s\tframes, delay %s, colors %s, fades %s" % (
                    str(TICK), str(PARAMS.delay), PARAMS.colors, str(PARAMS.fades)))
            SCSP.render(deb)
            TICK += 1
    except KeyboardInterrupt:
        SCSP.destroy()
        sys.exit()

def colortest(stdscr):
    # http://stackoverflow.com/questions/18551558/how-to-use-terminal-color-palette-with-curses
    curses.start_color()
    curses.use_default_colors()
    stdscr.addstr(0, 0, "%s colors on %s.\n" %
                  (str(curses.COLORS), str(curses.termname())))
    for i in range(0, curses.COLORS):
        curses.init_pair(i + 1, i, -1)
    for i in range(curses.COLORS):
        try:
            stdscr.addstr(str(i) + "\t", curses.color_pair(i))
        except:
            pass
    stdscr.getch()

if __name__ == '__main__':
    agp = argparse.ArgumentParser(
        description="A cool matrix effect for your terminal!")
    agp.add_argument("-d", "--delay", type=float, default=0.1,
                     help="set delay between frames in seconds (default 0.1)")
    agp.add_argument("-n", "--fades", type=int, default=40,
                     help="set number of \"fades\" on screen (default 25)")
    agp.add_argument("-miln", "--minlength", type=int, default=4,
                     help="set minimum length of fades (default 4)")
    agp.add_argument("-mxln", "--maxlength", type=int, default=20,
                     help="set maximum length of fades (default 20)")
    agp.add_argument("-mis", "--minspeed", type=float, default=0.5,
                     help="set minimum speed of fades (default 0.5)")
    agp.add_argument("-mxs", "--maxspeed", type=float, default=2,
                     help="set maximum speed of fades (default 2)")
    agp.add_argument("-milt", "--minlifetime", type=int, default=10,
                     help="set minimum lifetime of fades (default 10)")
    agp.add_argument("-mxlt", "--maxlifetime", type=int, default=30,
                     help="set maximum lifetime of fades (default 30)")
    agp.add_argument("-c", "--colors", type=str, default="83,84,119,120",
                     help="set fade colors.\n" +
                     "Must be a comma separated list of values on the terminal's color palette.\n" +
                     "(default 83,84,119,120)")
    agp.add_argument("-cc", "--headcolor", type=int, default=16,
                     help="set fade head color. (default 16)")
    agp.add_argument("-C", "--chars", type=str, default="32-128",
                     help="set fade characters. Is a comma separated list of unicode ranges.\n" +
                     "Can be one character or a range. [Example: -C 32-55,66,2605,2606,6785-8941]\n" +
                     "(default 32-128)")
    agp.add_argument("-g", "--debug", action="store_true",
                     help="show debug statistics in upper left corner")
    agp.add_argument("-t", "--colortest", action="store_true",
                     help="output a color test screen")
    args = agp.parse_args()
    if args.colortest == True:
        curses.wrapper(colortest)
    else:
        chars = parse_chars(args.chars, agp)
        curses.wrapper(main, args, chars)


from ndicapy import (
    ndiDeviceName, ndiProbe, NDI_OKAY,
    ndiOpen, ndiClose, ndiCommand, ndiGetError,
    ndiErrorString, NDI_115200,
    NDI_8N1, NDI_NOHANDSHAKE,
)

MAX_SERIAL_PORTS = 20
if __name__ == '__main__':
    name = ''
    for port_no in range(MAX_SERIAL_PORTS):
        name = ndiDeviceName(port_no)
        if not name:
            continue
        result = ndiProbe(name)
        if result == NDI_OKAY:
            break
    if result != NDI_OKAY:
        raise IOError(
            'Could not find any NDI device in '
            '{} serial port candidates checked. '
            'Please check the following:\n'
            '\t1) Is an NDI device connected to your computer?\n'
            '\t2) Is the NDI device switched on?\n'
            '\t3) Do you have sufficient privilege to connect to '
            'the device? (e.g. on Linux are you part of the "dialout" '
            'group?)'.format(MAX_SERIAL_PORTS)
        )

    device = ndiOpen(name)
    if not device:
        raise IOError(
            'Could not connect to NDI device found on '
            '{}'.format(name)
        )

    reply = ndiCommand(device, 'INIT:')
    error = ndiGetError(device)
    if reply.startswith('ERROR') or error != NDI_OKAY:
        raise IOError(
            'Error when sending command: '
            '{}'.format(ndiErrorString(error))
        )

    reply = ndiCommand(
        device,
        'COMM:{:d}{:03d}{:d}'.format(NDI_115200, NDI_8N1, NDI_NOHANDSHAKE)
    )

    # Add your own commands here!!!

    ndiClose(device)


import sys
import numpy as np
data=np.loadtxt(sys.argv[1])
#print len(data[:len(data)//2+1 ,0])
#print len(data[len(data)//2:,0 ])
#print data

if(len(data)%2 == 0):
   mid1=int(len(data)//2)
   mid2=int(len(data)//2)
else:
   mid1=int(len(data)//2)+1
   mid2=int(len(data)//2)
left=data[:mid1]
left=left[::-1]
right=data[mid2:]
x=data[:,0]
# x=right[:,0]-left[0,0]
# data2=np.zeros((len(x),len(data[:])))
# #pressure
sym=0.5*(left[:,1:] + right[:,1:])
data2=data*0
data2[:,0]=x
data2[:mid1,1:]=sym[::-1]
data2[mid2:,1:]=sym
#data2=0.5*(left[:,1:] + right[:,1:])
np.savetxt('%s_sym.dat'%(sys.argv[1].split('.')[0]),data2)


from abc import abstractmethod
import numpy as np
from keras import Model
from keras.callbacks import ModelCheckpoint
from pandas import DataFrame
from ml4iiot.algorithm.abstractalgorithm import AbstractAlgorithm
from ml4iiot.utility import str2bool, get_current_out_path
from keras.models import load_model

class AbstractAutoencoder(AbstractAlgorithm):

    def __init__(self, config: dict):
        super().__init__(config)

        self.verbose = str2bool(self.get_config('verbose', default=False))
        self.batch_size = self.get_config('batch_size', default=1)
        self.epochs = self.get_config('epochs', default=1)
        self.save_best_model = self.get_config('save_best_model', default=False)
        self.load_model = self.get_config('load_model', default=None)
        self.shuffle = self.get_config('shuffle', default=True)

        self.next_batch = []
        self.callbacks = []
        self.autoencoder = None

        if self.save_best_model:
            self.callbacks.append(ModelCheckpoint(get_current_out_path('best_model.hdf5'), save_best_only=True, monitor='loss'))

    def init(self) -> None:
        if self.load_model is None:
            self.autoencoder = self.create_autoencoder_model()

            self.compile_autoencoder()
        else:
            self.autoencoder = load_model(self.load_model)

        if self.verbose:
            self.autoencoder.summary()

    @abstractmethod
    def create_autoencoder_model(self) -> Model:
        pass

    def compile_autoencoder(self):
        self.autoencoder.compile(
             optimizer=self.get_config('optimizer', default='adam'),
             loss=self.get_config('loss', default='binary_crossentropy')
        )

    def data_frame_to_input_data(self, data_frame: DataFrame):
        return np.array([data_frame[self.get_config('input')]])

    def fit(self):
        next_batch = np.array(self.next_batch)

        return self.autoencoder.fit(
            next_batch,
            next_batch,
            batch_size=self.batch_size,
            epochs=self.epochs,
            verbose=self.verbose,
            callbacks=self.callbacks,
            shuffle=self.shuffle
        )

    def process(self, data_frame: DataFrame) -> None:
        data_frame['do_fit'] = float('nan')
        data_frame['do_predict'] = float('nan')
        data_frame['loss'] = float('nan')
        input_data = self.data_frame_to_input_data(data_frame)

        if self.do_predict(data_frame):
            data_frame['do_predict'].iloc[-1] = 1

            reconstruction = self.autoencoder.predict(input_data)
            reconstruction_difference = reconstruction - input_data
            reconstruction_error = sum(abs(reconstruction_difference[0]))

            data_frame['reconstruction'] = reconstruction[0]
            data_frame['absolute_reconstruction_error'] = float('nan')
            data_frame['relative_reconstruction_error'] = float('nan')

            data_frame['absolute_reconstruction_error'].iloc[-1] = reconstruction_error
            data_frame['relative_reconstruction_error'].iloc[-1] = reconstruction_error / len(data_frame.index)
        else:
            data_frame['do_predict'].iloc[-1] = 0

        if self.do_fit(data_frame):
            data_frame['do_fit'].iloc[-1] = 1
            self.next_batch.append(input_data[0])

            if len(self.next_batch) >= self.batch_size:
                history = self.fit()
                data_frame['loss'] = np.average(history.history['loss'])
                self.next_batch = []
        else:
            data_frame['do_fit'].iloc[-1] = 0


# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 15:11:43 2017

@author: Jesse
"""
from Cy_Ks_Gillespie import Cy_Ks_Gillespie
import numpy as np
import matplotlib.pyplot as plt

kinParams = {"a_s_A": 0.3,	"a_s_B": -12.5,	"a_s_C": 23.6,
        "b_s_A":(1.7**3*0.000739),"b_s_B":-80.1,"b_s_C": 21.8}

E_rest = -168
V_m = E_rest
doInit = 1
N_slowK = 150
it = 0.001
si = 0
chan_states = []
s0 = []
s1 = []
chan_states = Cy_Ks_Gillespie(N_slowK,chan_states,V_m+E_rest,si,it,kinParams)
stim = np.linspace(E_rest,40,150)
for V_m in stim:
    s = Cy_Ks_Gillespie(N_slowK,chan_states,V_m+E_rest,si,it,kinParams)
    s0 = np.append(s0,chan_states[0]/N_slowK)
    s1 = np.append(s1,chan_states[1]/N_slowK)

plt.plot(stim,s0,'bo',stim,s1,'r^')


class Settings():

    def __init__(self):
        #Inicializa las configuracionesd el juego

        self.screen_width = 1200
        self.screen_high= 800
        self.bg_color = (230,230,230)

        #Bullet Settings
        self.bullet_speed_factor = 3
        self.bullet_width = 3
        self.bullet_high = 15
        self.bullet_color = 60,60,60
        self.bullets_allowed = 3

        #Ship Settings
        self.ship_speed_factor = 1.5
        self.ship_limit = 3

        #Aliens settigns
        self.alien_speed_factor = 1
        self.fleet_drop_speed = 10
        #Fleet_director of 1 represents righ; -1 represents left
        self.fleet_direction = 1


import pandas as pnd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
def dim_2():
    frutas = pnd.read_csv("/Users/rauln/Documents/Desarrolo orientado a objetos/Albaricoques-cerezas-clustering/codigo-cap09/datas/frutas.csv", names=['DIAMETRO','PESO'], header=None)

    # Extraer x e y
    x = frutas.DIAMETRO
    y = frutas.PESO
    # Define los límites
    deltaX = (max(x) - min(x))/10
    deltaY = (max(y) - min(y))/10
    xmin = min(x) - deltaX
    xmax = max(x) + deltaX
    ymin = min(y) - deltaY
    ymax = max(y) + deltaY
    print(xmin, xmax, ymin, ymax)
    # Crear meshgrid
    xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]

    posiciones = np.vstack([xx.ravel(), yy.ravel()])
    values = np.vstack([x, y])
    kernel = st.gaussian_kde(values)
    f = np.reshape(kernel(posiciones).T, xx.shape)

    fig = plt.figure(figsize=(8,8))
    ax = fig.gca()
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    cfset = ax.contourf(xx, yy, f, cmap='coolwarm')
    ax.imshow(np.rot90(f), cmap='coolwarm', extent=[xmin, xmax, ymin, ymax])
    cset = ax.contour(xx, yy, f, colors='k')
    ax.clabel(cset, inline=1, fontsize=10)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    plt.show()


import sys
n = int(input())
max_num = -sys.maxsize
sum_num = 0

for i in range(0, n):
    current_num = int(input())
    if current_num > max_num:
        max_num = current_num
    sum_num += current_num

current_sum = sum_num - max_num

if max_num == current_sum:
    print('Yes')
    print(f'Sum = {max_num}')
else:
    print('No')
    print(f'Diff = {abs(max_num - current_sum)}')


# -*- coding: utf-8 -*-
"""
Created on Tue May 19 11:35:48 2015

@author: geography

Plots Degradation/Active Layer D50 against migration rate for various floodplain scenarios
"""
import os
import matplotlib.pyplot as plt
from size_spec_load_plot import extractGSDdata
from ActiveLayerGSDnormaliser import normaliseGSD

miglist = [0.0, 1.0, 1.5, 2.0]
#pblist = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
pblist = [0.0, 0.6, 1.0]
#labellist = ['0.0 (3.85 mm)', '0.2 (5.06 mm)','0.4 (7.01 mm)','0.6 (12.04 mm)','0.8 (24.45 mm)','1.0 (45.25 mm)']
labellist = ['0.0 (3.85 mm)','0.6 (12.04 mm)','1.0 (45.25 mm)']
colorlist = ['k','b','r','g','c','m']

bigdeglist = []
bigDlist = []

# Load data
mainpath = os.path.join(os.pardir, "migration_vs_alphabar")
outputfolders = os.listdir(mainpath)

for p in pblist:
    deglist = []
    Dlist = []
    for m in miglist:
        name = str(m)+"_"+str(p)
        for folder in outputfolders:
            if name in folder:
                path = str(os.path.join(mainpath, folder))
                degfile = open(path + '//' + 'Out_CumulativeBedChange', 'r')
                degfile = degfile.readlines()
                str(degfile)
                Dfile = open(path + '//' + 'Out_ActiveLayer.GSD.D50', 'r')
                Dfile = Dfile.readlines()
                str(Dfile)
                #normaliseGSD(path)
                #data = extractGSDdata(path)
                #cobmob = data[3]
                degnode = degfile[3].split()
                Dnode = Dfile[3].split()
                degvalue = float(degnode[-1])
                #Dvalue = float(cobmob[-1])
                Dvalue = float(Dnode[-1])
                deglist.append(degvalue)
                Dlist.append(Dvalue)
    bigdeglist.append(deglist)
    bigDlist.append(Dlist)

# Plot data

fig = plt.figure()
degsub = fig.add_subplot(2,1,1)
Dsub = fig.add_subplot(2,1,2)

i = 0
handlelist = []
for p in pblist:
    deg, = degsub.plot(miglist,bigdeglist[i], label=labellist[i], color = colorlist[i])
    degsub.set_ylabel('Bed elevation change (m)')
    Dsub.plot(miglist,bigDlist[i],color = colorlist[i])
    Dsub.set_ylabel('Active Layer D50 (mm)')
    plt.xlabel('Migration rate (m/yr)')
    plt.hold(True)
    handlelist.append(deg)
    i = i + 1
fig.tight_layout()
plt.legend(handles=handlelist, loc="center", bbox_to_anchor=(1.4,1), title="AlphaBar (Initial Floodplain D50)")

plt.show()


import sys
import pandas as pd

date_borders = "01-08-2021_22-01-2022"
path_to_output = "../../data/trades/processed"

print("Parsing done.")
print("Concatenating started...")
filenames = [
    f"{path_to_output}/parts_{date_borders}/{i}.csv"
    for i in range(int(sys.argv[1]))
]
concatenated_csv: pd.DataFrame = pd.concat(
    [pd.read_csv(filename) for filename in filenames]
)
concatenated_csv.to_csv(
    f"{path_to_output}/indicators_{date_borders}.csv", index=False
)
print("Done")


# Leo colorizer control file for velocity mode.
# This file is in the public domain.

# Properties for velocity mode.
properties = {
    "commentEnd": "*#",
    "commentStart": "#*",
    "lineComment": "##",
}

# Attributes dict for velocity_main ruleset.
velocity_main_attributes_dict = {
    "default": "null",
    "digit_re": "",
    "escape": "",
    "highlight_digits": "true",
    "ignore_case": "true",
    "no_word_sep": "",
}

# Attributes dict for velocity_velocity ruleset.
velocity_velocity_attributes_dict = {
    "default": "null",
    "digit_re": "",
    "escape": "",
    "highlight_digits": "true",
    "ignore_case": "true",
    "no_word_sep": "",
}

# Attributes dict for velocity_javascript ruleset.
velocity_javascript_attributes_dict = {
    "default": "MARKUP",
    "digit_re": "",
    "escape": "",
    "highlight_digits": "true",
    "ignore_case": "true",
    "no_word_sep": "",
}

# Attributes dict for velocity_javascript2 ruleset.
velocity_javascript2_attributes_dict = {
    "default": "MARKUP",
    "digit_re": "(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)",
    "escape": "\\",
    "highlight_digits": "true",
    "ignore_case": "false",
    "no_word_sep": "",
}

# Attributes dict for velocity_back_to_html ruleset.
velocity_back_to_html_attributes_dict = {
    "default": "MARKUP",
    "digit_re": "(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)",
    "escape": "\\",
    "highlight_digits": "true",
    "ignore_case": "false",
    "no_word_sep": "",
}

# Attributes dict for velocity_css ruleset.
velocity_css_attributes_dict = {
    "default": "MARKUP",
    "digit_re": "(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)",
    "escape": "\\",
    "highlight_digits": "true",
    "ignore_case": "false",
    "no_word_sep": "",
}

# Attributes dict for velocity_css2 ruleset.
velocity_css2_attributes_dict = {
    "default": "MARKUP",
    "digit_re": "[[:digit:]]+(pt|pc|in|mm|cm|em|ex|px|ms|s|%)",
    "escape": "\\",
    "highlight_digits": "true",
    "ignore_case": "true",
    "no_word_sep": "-_",
}

# Dictionary of attributes dictionaries for velocity mode.
attributesDictDict = {
    "velocity_back_to_html": velocity_back_to_html_attributes_dict,
    "velocity_css": velocity_css_attributes_dict,
    "velocity_css2": velocity_css2_attributes_dict,
    "velocity_javascript": velocity_javascript_attributes_dict,
    "velocity_javascript2": velocity_javascript2_attributes_dict,
    "velocity_main": velocity_main_attributes_dict,
    "velocity_velocity": velocity_velocity_attributes_dict,
}

# Keywords dict for velocity_main ruleset.
velocity_main_keywords_dict = {}

# Keywords dict for velocity_velocity ruleset.
velocity_velocity_keywords_dict = {
    "#else": "keyword1",
    "#elseif": "keyword1",
    "#end": "keyword1",
    "#foreach": "keyword1",
    "#if": "keyword1",
    "#include": "keyword1",
    "#macro": "keyword1",
    "#parse": "keyword1",
    "#set": "keyword1",
    "#stop": "keyword1",
}

# Keywords dict for velocity_javascript ruleset.
velocity_javascript_keywords_dict = {}

# Keywords dict for velocity_javascript2 ruleset.
velocity_javascript2_keywords_dict = {}

# Keywords dict for velocity_back_to_html ruleset.
velocity_back_to_html_keywords_dict = {}

# Keywords dict for velocity_css ruleset.
velocity_css_keywords_dict = {}

# Keywords dict for velocity_css2 ruleset.
velocity_css2_keywords_dict = {}

# Dictionary of keywords dictionaries for velocity mode.
keywordsDictDict = {
    "velocity_back_to_html": velocity_back_to_html_keywords_dict,
    "velocity_css": velocity_css_keywords_dict,
    "velocity_css2": velocity_css2_keywords_dict,
    "velocity_javascript": velocity_javascript_keywords_dict,
    "velocity_javascript2": velocity_javascript2_keywords_dict,
    "velocity_main": velocity_main_keywords_dict,
    "velocity_velocity": velocity_velocity_keywords_dict,
}

# Rules for velocity_main ruleset.

def velocity_rule0(colorer, s, i):
    return colorer.match_span(s, i, kind="comment1", begin="<!--", end="-->")

def velocity_rule1(colorer, s, i):
    return colorer.match_span(s, i, kind="markup", begin="<SCRIPT", end="</SCRIPT>",
          delegate="velocity::javascript")

def velocity_rule2(colorer, s, i):
    return colorer.match_span(s, i, kind="markup", begin="<STYLE", end="</STYLE>",
          delegate="velocity::css")

def velocity_rule3(colorer, s, i):
    return colorer.match_span(s, i, kind="keyword2", begin="<!", end=">",
          delegate="xml::dtd-tags")

def velocity_rule4(colorer, s, i):
    return colorer.match_span(s, i, kind="markup", begin="<", end=">",
          delegate="html::tags")

def velocity_rule5(colorer, s, i):
    return colorer.match_span(s, i, kind="literal2", begin="&", end=";",
          no_word_break=True)

# Rules dict for velocity_main ruleset.
rulesDict1 = {
    "&": [velocity_rule5,],
    "<": [velocity_rule0, velocity_rule1, velocity_rule2, velocity_rule3, velocity_rule4,],
}

# Rules for velocity_velocity ruleset.

def velocity_rule6(colorer, s, i):
    return colorer.match_span(s, i, kind="comment2", begin="#*", end="*#")

def velocity_rule7(colorer, s, i):
    return colorer.match_eol_span(s, i, kind="comment3", seq="##")

def velocity_rule8(colorer, s, i):
    return colorer.match_span(s, i, kind="keyword3", begin="${", end="}",
          no_line_break=True)

def velocity_rule9(colorer, s, i):
    return colorer.match_mark_following(s, i, kind="keyword3", pattern="$!")

def velocity_rule10(colorer, s, i):
    return colorer.match_mark_following(s, i, kind="keyword3", pattern="$")

def velocity_rule11(colorer, s, i):
    return colorer.match_keywords(s, i)

# Rules dict for velocity_velocity ruleset.
rulesDict2 = {
    "#": [velocity_rule6, velocity_rule7, velocity_rule11,],
    "$": [velocity_rule8, velocity_rule9, velocity_rule10,],
    "0": [velocity_rule11,],
    "1": [velocity_rule11,],
    "2": [velocity_rule11,],
    "3": [velocity_rule11,],
    "4": [velocity_rule11,],
    "5": [velocity_rule11,],
    "6": [velocity_rule11,],
    "7": [velocity_rule11,],
    "8": [velocity_rule11,],
    "9": [velocity_rule11,],
    "@": [velocity_rule11,],
    "A": [velocity_rule11,],
    "B": [velocity_rule11,],
    "C": [velocity_rule11,],
    "D": [velocity_rule11,],
    "E": [velocity_rule11,],
    "F": [velocity_rule11,],
    "G": [velocity_rule11,],
    "H": [velocity_rule11,],
    "I": [velocity_rule11,],
    "J": [velocity_rule11,],
    "K": [velocity_rule11,],
    "L": [velocity_rule11,],
    "M": [velocity_rule11,],
    "N": [velocity_rule11,],
    "O": [velocity_rule11,],
    "P": [velocity_rule11,],
    "Q": [velocity_rule11,],
    "R": [velocity_rule11,],
    "S": [velocity_rule11,],
    "T": [velocity_rule11,],
    "U": [velocity_rule11,],
    "V": [velocity_rule11,],
    "W": [velocity_rule11,],
    "X": [velocity_rule11,],
    "Y": [velocity_rule11,],
    "Z": [velocity_rule11,],
    "a": [velocity_rule11,],
    "b": [velocity_rule11,],
    "c": [velocity_rule11,],
    "d": [velocity_rule11,],
    "e": [velocity_rule11,],
    "f": [velocity_rule11,],
    "g": [velocity_rule11,],
    "h": [velocity_rule11,],
    "i": [velocity_rule11,],
    "j": [velocity_rule11,],
    "k": [velocity_rule11,],
    "l": [velocity_rule11,],
    "m": [velocity_rule11,],
    "n": [velocity_rule11,],
    "o": [velocity_rule11,],
    "p": [velocity_rule11,],
    "q": [velocity_rule11,],
    "r": [velocity_rule11,],
    "s": [velocity_rule11,],
    "t": [velocity_rule11,],
    "u": [velocity_rule11,],
    "v": [velocity_rule11,],
    "w": [velocity_rule11,],
    "x": [velocity_rule11,],
    "y": [velocity_rule11,],
    "z": [velocity_rule11,],
}

# Rules for velocity_javascript ruleset.

def velocity_rule12(colorer, s, i):
    return colorer.match_seq(s, i, kind="markup", seq=">",
          delegate="velocity::javascript2")

def velocity_rule13(colorer, s, i):
    return colorer.match_seq(s, i, kind="markup", seq="SRC=",
          delegate="velocity::back_to_html")

# Rules dict for velocity_javascript ruleset.
rulesDict3 = {
    ">": [velocity_rule12,],
    "S": [velocity_rule13,],
}

# Rules for velocity_javascript2 ruleset.

# Rules dict for velocity_javascript2 ruleset.
rulesDict4 = {}

# Rules for velocity_back_to_html ruleset.

def velocity_rule14(colorer, s, i):
    return colorer.match_seq(s, i, kind="markup", seq=">",
          delegate="velocity::main")

# Rules dict for velocity_back_to_html ruleset.
rulesDict5 = {
    ">": [velocity_rule14,],
}

# Rules for velocity_css ruleset.

def velocity_rule15(colorer, s, i):
    return colorer.match_seq(s, i, kind="markup", seq=">",
          delegate="velocity::css2")

# Rules dict for velocity_css ruleset.
rulesDict6 = {
    ">": [velocity_rule15,],
}

# Rules for velocity_css2 ruleset.

# Rules dict for velocity_css2 ruleset.
rulesDict7 = {}

# x.rulesDictDict for velocity mode.
rulesDictDict = {
    "velocity_back_to_html": rulesDict5,
    "velocity_css": rulesDict6,
    "velocity_css2": rulesDict7,
    "velocity_javascript": rulesDict3,
    "velocity_javascript2": rulesDict4,
    "velocity_main": rulesDict1,
    "velocity_velocity": rulesDict2,
}

# Import dict for velocity mode.
importDict = {
    "velocity_css2": ["velocity_css2::velocity", "css::main",],
    "velocity_javascript2": ["velocity_javascript2::velocity", "javascript::main",],
    "velocity_main": ["velocity_main::velocity",],
}


print('Введи 2 числа')

x = int(input('x = '))
y = int(input('y = '))

if x == y:
    print('Нет Min и Max >>>', x,'=',y)
else:
    if x > y:
        Max = x
        Min = y
    else:
        Max = y
        Min = x

    print('Max -->', Max)
    print('Min -->', Min)


import sys
import copy

import numpy as np
import scipy.stats
import colorama

import state
from smc.particle_filter.particle_filter import ParticleFilter
import sensor as sensor_module

import smc_tools.util

class TargetTrackingParticleFilter(ParticleFilter):

	def __init__(
			self, n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors,
			aggregated_weight=1.0):

		super().__init__(n_particles, resampling_algorithm, resampling_criterion)

		# a vector with the weights is created...but not initialized (that must be done by the "initialize" method)
		self._log_weights = np.empty(n_particles)

		# the state equation is encoded in the transition kernel
		self._state_transition_kernel = state_transition_kernel

		# the prior is needed to initialize the state
		self._prior = prior

		# the sensors are kept
		self._sensors = copy.deepcopy(sensors)

		# EVERY time this PF is initialized, the aggregated weight is set to this value
		self._initial_aggregated_weight = aggregated_weight

		self._log_initial_aggregated_weight = np.log(aggregated_weight)

		# these will get set as soon as the "initialize" method gets called
		self._state = None
		self._log_aggregated_weight = None
		self._loglikelihoods_product = None

		# TODO: this class and its children should receive a *sensorsArray* object
		if isinstance(sensors[0], sensor_module.RSSsensor):
			self._sensors_array = sensor_module.RSSsensorsArray(self._sensors)
		elif isinstance(sensors[0], sensor_module.BinarySensor):
			self._sensors_array = sensor_module.BinarySensorsArray(self._sensors)
		else:
			raise Exception('an array of this type of sensor is not supported')

	# this should be called whenever any of the sensors within the PF are modified
	def reset_sensors_array(self):

		self._sensors_array = sensor_module.RSSsensorsArray(self._sensors)

	def initialize(self):

		# initial samples...
		self._state = self._prior.sample(self._n_particles)

		# the weights are assigned equal probabilities
		self._log_weights.fill(self._log_initial_aggregated_weight - np.log(self._n_particles))

		self._log_aggregated_weight = self._log_initial_aggregated_weight

	def step(self, observations):

		assert len(observations) == len(self._sensors)

		# every particle is updated (previous state is not stored...)
		self._state = self._state_transition_kernel.next_state(self._state)

		# FIXME: this code is needed if the sensor is not RSS
		# # for each sensor, we compute the likelihood of EVERY particle (position)
		# likelihoods = np.array(
		# 	[sensor.likelihood(obs, state.to_position(self._state)) for sensor, obs in
		# 	 zip(self._sensors, observations)])

		# for EVERY sensor, we compute the likelihood of EVERY particle (position)
		likelihoods = self._sensors_array.likelihood(observations, state.to_position(self._state))

		# in order to avoid floating point arithmetic issues
		likelihoods += 1e-200

		loglikelihoods = np.log(likelihoods)

		# for each particle, we compute the product of the likelihoods for all the sensors
		self._loglikelihoods_product = loglikelihoods.sum(axis=0)

		# the weights are updated
		self._log_weights += self._loglikelihoods_product

		# the aggregated weight is kept up to date at all times
		self.update_aggregated_weight()

		# whatever is required (it depends on the algorithm) to avoid weights degeneracy...
		self.avoid_weight_degeneracy()

	def resample(self, normalized_log_weights):

		# the weights need to be converted to "natural" units
		normalized_weights = np.exp(normalized_log_weights)

		# we check whether a resampling step is actually needed or not
		if self._resampling_criterion.is_resampling_needed(normalized_weights):

			try:
				# the resampling algorithm is used to decide which particles to keep
				i_particles_to_be_kept = self._resampling_algorithm.get_indexes(normalized_weights)

			except ValueError:

				# this should mean the normalized weights don't add up EXACTLY to one...we renormalize them...
				normalized_weights /= normalized_weights.sum()

				# ...and try again
				i_particles_to_be_kept = self._resampling_algorithm.get_indexes(normalized_weights)

			# the above indexes are used to update the state
			self._state = self._state[:, i_particles_to_be_kept]

			# note that if the weights have been normalized ("standard" centralized particle filter),
			# then "self.aggregated_weight" is equal to 1
			self._log_weights.fill(self._log_aggregated_weight - np.log(self._n_particles))

	def get_particle(self, index):

		return self._state[:, index:index+1].copy(), self._log_weights[index]

	def get_samples_at(self, indexes):

		"""Obtain (just) the samples at certain given indexes.

		This yields a "view" of the data, rather than a copy.

		Parameters
		----------
		indexes: 1-D ndarray
			The indexes of the requested particles

		Returns
		-------
		samples: 2-D ndarray
			The selected samples
		"""

		return self._state[:, indexes]

	@property
	def last_unnormalized_loglikelihoods(self):

		return self._loglikelihoods_product

	@property
	def samples(self):

		return self._state

	@samples.setter
	def samples(self, value):

		if value.shape == self._state.shape:

			self._state = value

		else:

			raise Exception('the number and/or dimensions of the samples are not equal to the current ones')

	@property
	def sensors(self):

		return self._sensors

	def set_particle(self, index, particle):

		self._state[:, index:index+1] = particle[0]
		self._log_weights[index] = particle[1]

		# the sum of the weights might have changed...
		self.update_aggregated_weight()

	def update_aggregated_weight(self):

		# the aggregated weight is simply the sum of the non-normalized weights
		self._log_aggregated_weight = smc_tools.util.log_sum_from_individual_logs(self._log_weights)

	def compute_mean(self):

		normalized_log_weights = self._log_weights - self._log_aggregated_weight

		# element-wise multiplication of the state vectors and their correspondent weights,
		# followed by addition => weighted mean
		return (self._state*np.exp(normalized_log_weights)[np.newaxis, :]).sum(axis=1)[:, np.newaxis]

	def normalize_weights(self):

		self._log_weights -= self._log_aggregated_weight

		# we forced this above
		self._log_aggregated_weight = 0.

		# TODO: make sure the (natural units) weights add up to 1 exactly to avoid numerical issues?

	def normalize_weights_and_update_aggregated(self):

		self._log_weights -= smc_tools.util.log_sum_from_individual_logs(self._log_weights)

		# this is enforced above
		self._log_aggregated_weight = 0.

	# this methods encapsulates the parts within the code of "step" which are different in this class and its children
	def avoid_weight_degeneracy(self):

		self.normalize_weights()

		# the normalized weights are used to resample
		self.resample(self._log_weights)

	@property
	def log_weights(self):

		return self._log_weights

	@log_weights.setter
	def log_weights(self, value):

		if self._log_weights.shape == value.shape:

			self._log_weights = value

		else:

			raise Exception('the number of weights does not match the number of particles')

	@property
	def weights(self):

		return np.exp(self._log_weights)

	@weights.setter
	def weights(self, value):

		if self._log_weights.shape == value.shape:

			self._log_weights = np.log(value)

		else:

			raise Exception('the number of weights does not match the number of particles')

# =========================================================================================================

class EmbeddedTargetTrackingParticleFilter(TargetTrackingParticleFilter):

	@property
	def aggregated_weight(self):

		return np.exp(self._log_aggregated_weight)

	@aggregated_weight.setter
	def aggregated_weight(self, value):

		self._log_aggregated_weight =  np.log(value)

	def divide_weights(self, factor):

		log_factor = np.log(factor)

		self._log_weights -= log_factor
		self._log_aggregated_weight -= log_factor

	# NOTE: using np.close may yield quite different results
	def avoid_weight_degeneracy(self):

		# the normalized weights are used to resample
		self.resample(self._log_weights - self._log_aggregated_weight)

# =========================================================================================================

class TargetTrackingParticleFilterWithConsensusCapabilities(TargetTrackingParticleFilter):

	def __init__(
			self, n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors,
			M, R_p, r_a_tuples, r_a, r_d_tuples, r_d, rs_gamma):

		super().__init__(n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors)

		# the noise covariance matrix is built from the individual variances of each sensor
		self._noiseCovariance = np.diag([s.noise_var for s in sensors])

		# the position of every sensor
		self._sensorsPositions = np.hstack([s.position for s in sensors])

		# M, R_p, r_a_tuples, r_a, r_d_tuples, r_d, rs_gamma

		self._M = M
		self._R_p = R_p
		self._r_a_tuples = r_a_tuples
		self._r_a = r_a
		self._r_d_tuples = r_d_tuples
		self._r_d = r_d
		self._rs_gamma = rs_gamma

	def likelihood_mean(self, positions):

		# each row gives the distances from a sensor to ALL the positions
		distances = np.linalg.norm(positions[:, :, np.newaxis] - self._sensorsPositions[:, np.newaxis, :], axis=0).T

		return np.vstack([s.likelihood_mean(d) for d, s in zip(distances, self._sensors)])

	def step(self, observations):

		# the exponents of the monomials and their associated coefficients are extracted from the "consensed" beta's
		exponents = np.array(list(self.betaConsensus.keys()))
		betas = np.array(list(self.betaConsensus.values()))

		# for the sake of convenience
		x = state.to_position(self._state)

		# a matrix containing the monomials evaluated for the all the x's
		phi = (x[:, :, np.newaxis]**exponents.T[:, np.newaxis, :]).prod(axis=0)

		# the exponent of the Joint Likelihood Function (JLF) for every particle (x), as computed in this PE
		S = (phi * betas[np.newaxis, :]).sum(axis=1)

		# S contains exponents...and hence subtracting a constant is tantamount to scaling the power (the JLF)
		shifted_S = S - max(S)

		# the weights should be multiplied by e^shifted_S and divided by the sum thereof, and when taking
		# the logarithm this yields
		self._log_weights += shifted_S - np.log(np.exp(shifted_S).sum())

		# the aggregated weight is kept up to date at all times
		self.update_aggregated_weight()

		# whatever is required (it depends on the algorithm) to avoid weights degeneracy...
		self.avoid_weight_degeneracy()

	def pre_consensus_step(self, observations):

		assert len(observations) == len(self._sensors)

		# every particle is updated (previous state is not stored...)
		self._state = self._state_transition_kernel.next_state(self._state)

		self.polynomial_approximation(observations)

	def polynomial_approximation(self, observations):

		x = state.to_position(self._state)

		# in the first matrix, we just replicate the samples matrix (<component within sample>,<number of sample>)
		# along the third dimension; in the second matrix, the third dimension gives the number of monomial
		phi = (x[:, :, np.newaxis]**self._r_a.T[:, np.newaxis, :]).prod(axis=0)

		# the true values for the function to be approximated
		A = self.likelihood_mean(x).T

		# the coefficients of the approximation (each row corresponds to one coefficient)
		Y = np.linalg.pinv(phi).dot(A)

		# the solution is stored in a dictionary for easy access
		alpha = dict(zip(self._r_a_tuples, Y))

		# a dictionary (indexed by the elements in r_d_tuples) with the computed coefficients gamma
		gamma = {}

		for r, possible_combinations in zip(self._r_d, self._rs_gamma):

			accum = 0

			# we sum over all the possible combinations (each one gives rise to one term)
			for t in possible_combinations:

				# alpha * covariance * alpha^T (alpha has been stored as a row vector)
				accum += alpha[t[:self._M]].dot(self._noiseCovariance).dot(alpha[t[self._M:]][:, np.newaxis])

			accum /= 2

			# the computed value is added to the dictionary
			gamma[tuple(r)] = accum.item(0)

		# this term is independent of the indices
		b = self._noiseCovariance.dot(observations)

		# a dictionary to store the beta component associated to every vector of indices
		self.beta = {}

		for r in self._r_d_tuples:

			deg = sum(r)

			if deg <= self._R_p:

				self.beta[r] = alpha[r].dot(b) - gamma[r]

			elif deg <= (2*self._R_p):

				self.beta[r] = - gamma[r]

			else:

				raise Exception('coefficient for this combination of exponents not found!!')

# =========================================================================================================

class TargetTrackingParticleFilterWithFusionCenter(TargetTrackingParticleFilter):

	def __init__(
			self, n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors,
			i_fusion_center_neighbour, aggregated_weight=1.0):

		super().__init__(
			n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors, aggregated_weight)

		self._i_fusion_center_neighbour = i_fusion_center_neighbour

	def messages(self, processing_elements_topology, each_processing_element_connected_sensors):

		distances = processing_elements_topology.distances_between_processing_elements[self._i_fusion_center_neighbour] + 1

		return sum([d*len(each_processing_element_connected_sensors) for d, c in zip(
			distances, each_processing_element_connected_sensors)])

# =========================================================================================================

class TargetTrackingGaussianParticleFilter(TargetTrackingParticleFilter):

	def __init__(
			self, n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors,
			initial_size_estimate, room, PRNG):

		super().__init__(n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors)

		self.estimated_n_PEs = initial_size_estimate
		self._room = room
		self._PRNG = PRNG

		# they will be set later
		self._Q = None
		self._nu = None
		self._mean = None
		self._covariance = None

		# value of the elements in the diagonal of a covariance matrix that became 0
		self._default_variance = 20

		self._fake_random_state = self.FakeRandomState()

	class FakeRandomState:

		def __init__(self):

			pass

		def normal(self, mean, variance, size):

			return np.zeros(size)

	def step(self, observations):

		assert len(observations) == len(self._sensors)

		# the particles are propagated with a *fake* RandomState that always returns 0's
		predictions = self._state_transition_kernel.next_state(self._state, self._fake_random_state)

		# for each sensor, we compute the likelihood of EVERY predicted particle (position)
		predictions_likelihoods = np.array(
			[sensor.likelihood(obs, state.to_position(predictions)) for sensor, obs in
			 zip(self._sensors, observations)])

		# + 1e-200 in order to avoid division by zero
		predictions_likelihoods_product = predictions_likelihoods.prod(axis=0) + 1e-200

		# first-stage weights in Auxiliary Particle Filter
		sampling_weights = predictions_likelihoods_product / predictions_likelihoods_product.sum()

		i_particles_resampled = self._resampling_algorithm.get_indexes(sampling_weights)

		# every particle is updated (previous state is not stored...)
		self._state = self._state_transition_kernel.next_state(self._state[:, i_particles_resampled])

		# for each sensor, we compute the likelihood of EVERY particle (position)
		likelihoods = np.array([
				sensor.likelihood(obs, state.to_position(self._state))
				for sensor, obs in zip(self._sensors, observations)
				])

		# careful with floating point arithmetic issues
		likelihoods += 1e-200

		loglikelihoods = np.log(likelihoods)

		# for each particle, we compute the product of the likelihoods for all the sensors
		loglikelihoods_product = loglikelihoods.sum(axis=0)

		# every likelihood is exponentiated by the estimate of the number of PEs
		# REMARK: exponentiating the argument of the logaritm is tantamount to multiplying the logarithm
		self._log_weights = loglikelihoods_product*self.estimated_n_PEs - np.log(
			predictions_likelihoods_product[i_particles_resampled])

		# normalization
		self.normalize_weights_and_update_aggregated()

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

		# we compute the mean...
		self._mean = (self.weights[np.newaxis, :] * self.samples).sum(axis=1)

		# ...and (weighted) covariance
		self._covariance = np.cov(self.samples, ddof=0, aweights=self.weights)

		# if the matrix is singular (this happens when a single particle accumulates most of the weight)
		if np.isnan(np.linalg.cond(self._covariance)) or np.linalg.cond(self._covariance) > (1 / sys.float_info.epsilon):

			# the (weighted) self._covariance matrix being zero does NOT self._mean there is no uncertainty about the random vector.
			# On the contrary, it *most likely* means that ALL of the likelihoods are really small, which results in a
			# single (arbitrary, due to numeric precision) weight concentrating all the mass (corresponding to the
			# biggest likelihood that may be 10^-12...)
			self._covariance += np.identity(state.n_elements)*self._default_variance

		# we try...
		try:

			# ...to invert the self._covariance matrix
			inv_covariance = np.linalg.inv(self._covariance)

		# it it's not possible (singular)...
		except np.linalg.linalg.LinAlgError:

			# an epsilon is added to the diagonal of the self._covariance matrix
			inv_covariance = np.linalg.inv(self._covariance + np.identity(self._covariance.shape[0])*1e-9)

		# Q and nu are updated
		self._Q, self._nu = inv_covariance, inv_covariance @ self._mean

	def actual_sampling(self, observations):

		# an estimate of (n times) the *global* covariance...
		covariance = np.linalg.inv(self._Q)

		# ...and another for the *global* mean
		mean = covariance @ self._nu

		# we start assuming mean and covariance resulting from consensus are fine; if inverse covariance and transformed
		# mean resulting from consensus are not trustworthy, then neither are the covariance and mean *computed from them*
		invalid_mean_or_covariance = False

		# try:
		#
		# 	# probability of the *global* mean conditional on the local mean
		# 	local_likelihood = scipy.stats.multivariate_normal.pdf(x=mean, mean=self._mean, cov=self._covariance)
		#
		# except np.linalg.linalg.LinAlgError:
		#
		# 	# the covariance matrix is not even a covariance matrix
		# 	invalid_mean_or_covariance = True
		#
		# else:
		#
		# 	# a sample (or mean) that cannot happen according to the local data should never have happened either
		# 	# according to the global data, and hence if it has, there must be something wrong with the consensus
		# 	if local_likelihood == 0:
		#
		# 		invalid_mean_or_covariance = True

		try:

			# FIXME: this is to force an exception whenever the matrix is not positive definite...
			np.linalg.cholesky(covariance)

		except np.linalg.linalg.LinAlgError:

			# ...in which case, the covariance is not valid
			invalid_mean_or_covariance = True

		# if we cannot trust the resulting mean and/or covariance...
		if invalid_mean_or_covariance:

			print(type(self).__name__ + ': ' + colorama.Fore.RED + 'using local mean and covariance...' + colorama.Style.RESET_ALL)

			# ...we just use the local ones
			mean = self._mean
			covariance = self._covariance

		self._state = self._PRNG.multivariate_normal(mean, covariance, size=self.n_particles).T

		# the position of samples that fall outside the region are truncated
		self._room.bind(self._state)

		# weights must be reinitialized
		self.weights = np.full(self.n_particles, 1 / self.n_particles)

# =========================================================================================================

class TargetTrackingSetMembershipConstrainedParticleFilter(TargetTrackingParticleFilter):

	def __init__(
			self, n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors, L,
			alpha, beta, n_repeats_rejection_sampling, RS_PRNG):

		super().__init__(
			n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors)

		self._L = L
		self._alpha = alpha
		self._beta = beta
		self._n_repeats_rejection_sampling = n_repeats_rejection_sampling
		self._RS_PRNG = RS_PRNG

		self.bounding_box_min = None
		self.bounding_box_max = None
		self.loglikelihoods = None
		self.norm_constants = None

		self._alpha_beta_ratio = self._beta/self._alpha

	def belongs(self, samples):

		return np.logical_and(
			(samples.T > self.bounding_box_min).all(axis=1),
			(samples.T < self.bounding_box_max).all(axis=1)
		)

	def step(self, observations):

		# oversampling (of the previous probability measure)
		i_oversampled_particles = self._resampling_algorithm.get_indexes(self.weights, self.n_particles*self._L)

		# oversampled particles are updated
		oversampled_particles = self._state_transition_kernel.next_state(self._state[:, i_oversampled_particles])

		# for each sensor, we compute the likelihood of EVERY particle (position)
		likelihoods = np.prod([sensor.likelihood(obs, state.to_position(oversampled_particles))
		                       for sensor, obs in zip(self._sensors, observations)], axis=0)

		# in order to avoid dividing by zero
		likelihoods += 1e-200

		# normalization
		weights = likelihoods/likelihoods.sum()

		# indexes of the particles...
		i_sampled_particles = self._resampling_algorithm.get_indexes(weights, self.n_particles)

		# ...that determine the bounding box
		particles_bounding_box = oversampled_particles[:, i_sampled_particles]

		self.bounding_box_min = particles_bounding_box.min(axis=1)
		self.bounding_box_max = particles_bounding_box.max(axis=1)

	def rejection_sampling(self, samples):

		# in order to avoid loops, each particle is replicated as many times as
		n_replicas = self._n_repeats_rejection_sampling

		# all the replicas of all the particles are propagated
		n_fold_propagated_samples = self._state_transition_kernel.next_state(np.repeat(samples, n_replicas, axis=1))

		# are particles within bounds?
		within_bounds = self.belongs(n_fold_propagated_samples).reshape(-1, n_replicas)

		# there is a small chance they will be accepted anyway
		accept_anyway = scipy.stats.bernoulli.rvs(
			self._alpha_beta_ratio, size=(self.n_particles, n_replicas), random_state=self._RS_PRNG).astype(np.bool)

		# the index for the first valid replica of each particle
		i_first_valid = [np.where(sample_fold)[0][0] for sample_fold in (within_bounds | accept_anyway)]

		# we need to choose the right particle from the manifold of replicas
		i_valid = np.array(i_first_valid) + n_replicas*np.arange(self.n_particles)

		propagated_particles = n_fold_propagated_samples[:, i_valid]

		# a rough way of computing the normalization constant for every particle
		# ===========================

		# for every particle, (an approximation of) the probability of drawing a sample within the region
		prob_within = within_bounds.sum(axis=1)/n_replicas

		# for every particle, (an approximation of) the probability of drawing a sample outside the region, and accepting
		# it anyway
		# prob_outside_but_accepted = (~within_bounds & accept_anyway).sum(axis=1)/n_replicas

		# another (not exactly equivalent) way; this should be better because the above probability will usually be high,
		# and hence easier to estimate
		prob_outside_but_accepted = (1-prob_within)*self._beta

		# the (approximation of the) normalization constant is the sum of the two of them
		norm_constants = self._alpha*prob_within + prob_outside_but_accepted

		return propagated_particles, norm_constants

	def actual_sampling_step(self, observations):

		# resampling of the particles from the previous time instant (with a RandomState object that should be
		# synchronized across different PEs
		i_sampled_particles = self._resampling_algorithm.get_indexes(self.weights)

		# ...the resulting particles
		self._state, self.norm_constants = self.rejection_sampling(self._state[:, i_sampled_particles])

		likelihoods = np.prod([sensor.likelihood(obs, state.to_position(self._state))
		                       for sensor, obs in zip(self._sensors, observations)], axis=0)

		# in order to avoid numerical precision problems
		likelihoods += 1e-200

		self.loglikelihoods = np.log(likelihoods)

	def weight_update_step(self):

		# particles are in the right region?
		belongs =self.belongs(self._state)

		# the last term in the weights update equation
		tentative_term = np.log(self._alpha * belongs.astype(float) + self._beta * (~belongs).astype(float))

		# the new log-weights
		self.log_weights = self.loglikelihoods + np.log(self.norm_constants) - tentative_term

		# normalization
		self.normalize_weights_and_update_aggregated()

# =========================================================================================================

class TargetTrackingSelectiveGossipParticleFilter(TargetTrackingParticleFilter):

	def __init__(
			self, n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors,
			n_PEs):

		super().__init__(n_particles, resampling_algorithm, resampling_criterion, prior, state_transition_kernel, sensors)

		self._n_PEs = n_PEs

		# for later use
		self.gamma = None
		self.ro = None

	def step(self, observations):

		# every particle is propagated for computing the first-stage weights
		auxiliar_state = self._state_transition_kernel.next_state(self._state)

		# for each sensor, we compute the likelihood of EVERY particle (position)
		likelihoods = np.array(
			[sensor.likelihood(obs, state.to_position(auxiliar_state)) for sensor, obs in zip(self._sensors, observations)])

		# careful with floating point arithmetic issues
		likelihoods += 1e-200

		loglikelihoods = np.log(likelihoods)

		# for each particle we store the product of the likelihoods for all the sensors multiplied by the number of PEs
		self.gamma = self._n_PEs*loglikelihoods.sum(axis=0)

	def actual_sampling_step(self, observations):

		ro = np.exp(self.gamma_postgossip)

		# the significant samples according to the consensus algorithm...
		significant_samples = self._state[:, self.i_significant]

		# ...and their corresponding weights, which are at the same time updated using the first-stage weights
		updated_significant_weights = self.weights[self.i_significant]*ro

		# in order to avoid numerical problems...
		updated_significant_weights += 1e-200

		# ...when normalizing
		updated_significant_weights /= updated_significant_weights.sum()

		# resampling of the particles from the previous step according to the first-stage weights
		i_resampled = self._resampling_algorithm.get_indexes(updated_significant_weights, self.n_particles)
		resampled = significant_samples[:, i_resampled]
		self.ro = ro[i_resampled]

		self._state = self._state_transition_kernel.next_state(resampled)

		# for each sensor, we compute the likelihood of EVERY particle (position)
		likelihoods = np.array(
			[sensor.likelihood(obs, state.to_position(self._state)) for sensor, obs in zip(self._sensors, observations)])

		# careful with floating point arithmetic issues
		likelihoods += 1e-200

		loglikelihoods = np.log(likelihoods)

		# for each particle we store the product of the likelihoods for all the sensors multiplied by the number of PEs
		self.gamma = self._n_PEs*loglikelihoods.sum(axis=0)

	def weights_update_step(self):

		significant_state = self._state[:, self.i_significant]

		# an epsilon is added in the denominator to avoid numerical issues
		weights = np.exp(self.gamma_postgossip)/(self.ro[self.i_significant] + 1e-200)

		# to avoid numerical issues
		weights += 1e-200

		weights /= weights.sum()

		# we resample from the set of *significant* particles
		i_resampling = self._resampling_algorithm.get_indexes(weights, self.n_particles)

		self._state = significant_state[:, i_resampling]
		self.weights = np.full(self.n_particles, 1/self.n_particles)

class EstimateStoringParticleFilterDecorator:

	def __init__(self, decorated):

		self._decorated = decorated

		self.estimates_history = None

	def __getattr__(self, item):

		return getattr(self._decorated, item)

	def initialize(self):

		self._decorated.initialize()

		self.estimates_history = [self._decorated.compute_mean()]

	def step(self, observations):

		self._decorated.step(observations)

		self.estimates_history.append(self._decorated.compute_mean())


import numpy as np
import os
import pandas as pd
import subprocess
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.linear_model import LinearRegression
from utils import emotion_to_id, aro_val_to_emo
from sklearn.model_selection import train_test_split

def parallel(X, i):
    y = X[:, i]
    X_i = np.concatenate((X[:, :i], X[:, i+1:]), axis=1)
    clf = LinearRegression()
    X_train, X_test, y_train, y_test = train_test_split(X_i, y, test_size = 0.3)
    clf.fit(X_train, y_train)
    return clf.score(X_test, y_test)

class Featurizer():
    def __init__(self):
        self.n_features = 6374

    def run_enterface(self, metadata):
        # open smile, compare feature set
        df = pd.DataFrame()
        labels = []
        banned = ['subject 6', 'subject 23']
        for subject, emotion, sentence, path in metadata.values:
            if(not subject in banned):
                path = '../' + path.replace('.avi', '.wav')
                data_fname = 'data/csvs/' + subject[subject.rindex(' ')+1:] + '_' + emotion + '_' + sentence[-1] + '.csv'

                if(not os.path.isfile(data_fname)):
                    subprocess.run(['SMILExtract', '-C', 'data/config/IS13_ComParE.conf', '-I', path, '-csvoutput', data_fname])

                df_tmp = pd.read_csv(data_fname, sep=';', header=0)
                df_tmp = df_tmp.drop(list(df_tmp.columns)[0], axis=1)
                df = df.append(df_tmp, ignore_index=True)
                labels.append(emotion)
        return df.values, labels

    def run_iemocap(self, metadata):
        data_folder = '../data/IEMOCAP_full_release/'
        df = pd.DataFrame()
        labels = []

        for sess,fname,utt,_,_,arousal,valence,emotion in metadata.values:
            data_fname = 'data/csvs/' + fname + '_' + utt + '.csv'

            if(not os.path.isfile(data_fname)):
                path = data_folder + sess + '/sentences/wav/' + fname +'/' + fname + '_' + utt + '.wav'
                subprocess.run(['SMILExtract', '-C', 'data/config/IS13_ComParE.conf', '-I', path, '-csvoutput', data_fname])

            df_tmp = pd.read_csv(data_fname, sep=';', header=0)
            df_tmp = df_tmp.drop(list(df_tmp.columns)[0], axis=1)
            df = df.append(df_tmp, ignore_index=True)
            labels.append([emotion, arousal, valence])

        return df.values, np.array(labels)

    def run_mosei(self, metadata):
        data_folder = '../data/mosei/Raw/'
        df = pd.DataFrame()
        labels = []

        for path,vid,clip,emotion,arousal,valence in metadata.values:
            path = '../' + path.replace('[modal]', 'Audio').replace('[ext]', '.wav')
            if(os.path.isfile(path)):
                data_fname = 'data/csvs/mosei' + str(vid) + '_' + str(clip) + '.csv'

                if(not os.path.isfile(data_fname)):
                    subprocess.run(['SMILExtract', '-C', 'data/config/IS13_ComParE.conf', '-I', path, '-csvoutput', data_fname])

                df_tmp = pd.read_csv(data_fname, sep=';', header=0)
                df_tmp = df_tmp.drop(list(df_tmp.columns)[0], axis=1)
            else:
                df_tmp = pd.DataFrame([np.nan for _ in range(self.n_features)])
            df = df.append(df_tmp, ignore_index=True)
            labels.append([emotion, arousal, valence])

        return df.values, np.array(labels)

    def run_hci(self, metadata):
        data_folder = '../data/hci_tagging/Sessions/'
        df = pd.DataFrame()
        labels = []

        for sess, aro, val in metadata.values:
            emotion = aro_val_to_emo(aro, val)
            wavs = [x for x in os.listdir(data_folder+'/'+str(sess)) if '.wav' in x]
            if(len(wavs) == 1):
                data_fname = data_folder+'/'+str(sess)+'/'+wavs[0]
                csv_fname = 'data/csvs/hci_'+str(sess)+'.csv'
                if(not os.path.isfile(csv_fname)):
                    subprocess.run(['SMILExtract', '-C', 'data/config/IS13_ComParE.conf', '-I', data_fname, '-csvoutput', csv_fname])

                df_tmp = pd.read_csv(csv_fname, sep=';', header=0)
                df_tmp = df_tmp.drop(list(df_tmp.columns)[0], axis=1)
            elif(len(wavs)>1):
                raise Exception('more than 1 wav file for session: ' + str(sess))
            else:
                df_tmp = pd.DataFrame([np.nan for _ in range(self.n_features)])
            df = df.append(df_tmp, ignore_index=True)
            labels.append([emotion, aro, val])

        return df.values, np.array(labels)

    def select_features_continuous(self, X, y, dataset):
        X = X.astype(np.float32)
        df_f = pd.DataFrame(X)
        df_f.columns = np.arange(df_f.shape[1])

        print("features: ", len(df_f.columns))

        epsilon = 1e-4 # 1e-5
        df_f_tmp = df_f.loc[:,df_f.var()>epsilon]
        tmp = list(df_f_tmp.columns)
        df_f_tmp.columns = np.arange(df_f_tmp.shape[1])

        print("selected after variance filter:", len(tmp))

        X = df_f_tmp.values.astype(np.float32)

        y_tmp = emotion_to_id(y[:,0], dataset)
        # remove nans
        idxs = []
        for i in range(len(X)):
            if(not np.isnan(X[i,:]).any()):
                idxs.append(i)

        X = X[idxs]
        y = np.array(y)[idxs]

        X, tmp = self.select_vif(X, tmp)
        df_f = df_f.loc[:, tmp]
        print("selected after VIF filter:", len(tmp))

        y_emo = y[:,0]
        y_emo = emotion_to_id(y_emo, dataset)
        y_aro = y[:, 1].astype(np.float32)
        y_val = y[:, 2].astype(np.float32)

        self.idxs = []

        for mode in ['emo', 'aro', 'val']:
            idxs = []
            if(mode == 'emo'):
                model = RandomForestClassifier(n_estimators=100)
                model.fit(X, y_emo)
                threshold = 1e-3
            elif(mode == 'aro'):
                model = RandomForestRegressor(n_estimators=100)
                model.fit(X, y_aro)
                threshold = 1e-3
            elif(mode == 'val'):
                model = RandomForestRegressor(n_estimators=100)
                model.fit(X, y_val)
                threshold = 1e-3

            importances = model.feature_importances_
            for i in range(len(importances)):
                if(importances[i]>threshold):
                    idxs.append(tmp[i])
            self.idxs.append(np.array(idxs))

            if(mode == 'emo'):
                df_f_emo = df_f.loc[:, importances>threshold]
                print("selected for emotion:", len(df_f_emo.columns))
                X_emo = df_f_emo.values
            elif(mode == 'aro'):
                df_f_aro = df_f.loc[:, importances>threshold]
                print("selected for arousal:", len(df_f_aro.columns))
                X_aro = df_f_aro.values
            elif(mode == 'val'):
                df_f_val = df_f.loc[:, importances>threshold]
                print("selected for valence:", len(df_f_val.columns))
                X_val = df_f_val.values
        X = [X_emo, X_aro, X_val]

        return X

    def select_features_categorical(self, X, y, dataset):
        df_f = pd.DataFrame(X)
        df_f.columns = np.arange(df_f.shape[1])

        print("features: ", len(df_f.columns))

        epsilon = 1e-4 # 1e-5
        df_f_tmp = df_f.loc[:,df_f.var()>epsilon]
        tmp = list(df_f_tmp.columns)
        df_f_tmp.columns = np.arange(df_f_tmp.shape[1])

        X = df_f_tmp.values.astype(np.float32)

        # remove nans
        idxs = []
        for i in range(len(X)):
            if(not np.isnan(X[i,:]).any()):
                idxs.append(i)

        X = X[idxs]
        y = np.array(y)[idxs]
        y = emotion_to_id(y, dataset)

        X, tmp = self.select_vif(X, tmp)
        df_f = df_f.loc[:, tmp]
        print("selected after VIF filter:", len(tmp))

        clf = RandomForestClassifier()
        clf.fit(X,y)

        self.idxs = []
        # threshold = 1e-3
        threshold = 5e-4
        importances = clf.feature_importances_
        for i in range(len(importances)):
            if(importances[i]>threshold):
                self.idxs.append(tmp[i])
        self.idxs = np.array(self.idxs)

        df_f = df_f.loc[:, importances>threshold]
        print("selected:", len(df_f.columns))

        # df = pd.concat((df_m, df_f), axis=1, ignore_index=True)
        # df.columns = np.arange(df.shape[1])
        X = df_f.values

        return X

    def select_vif(self, X, tmp):
        vifs = [np.inf]
        tmp = np.array(tmp)
        while(np.max(vifs) > 10):
            print(len(tmp), np.max(vifs))
            vifs = []

            results = []
            for i in range(len(X.T)):
                results.append(parallel(X, i))

            for r in results:
                vifs.append(1/(1-r))

            if(len(tmp) > 150):
                if(len(tmp) > 1000):
                    limit = 1000
                elif(len(tmp) > 500):
                    limit = 300
                elif(len(tmp) > 250):
                    limit = 25
                elif(len(tmp) > 150):
                    limit = 5

                data = [[i, vif] for i,vif in enumerate(vifs)]
                data = sorted(data, key=lambda x: x[1], reverse=True)
                idxs = [x[0] for x in data[:limit]]

                X = np.delete(X, idxs, axis=1)
                tmp = np.delete(tmp, idxs)

            else:
                if(np.max(vifs) > 10):
                    idx = np.argmax(vifs)
                    tmp = np.delete(tmp, idx)
                    X = np.concatenate((X[:, :idx], X[:, idx+1:]), axis=1)

        return X, tmp


#!/usr/bin/python3
"""Rectangle module"""

class Rectangle:
    """Rectangle class"""

    def __init__(self, width=0, height=0):
        """Initializes instance"""
        self.height = height
        self.width = width
        if type(width) is not int:
            raise TypeError("width must be an integer")
        if type(height) is not int:
            raise TypeError("width must be an integer")
        if height < 0:
            raise ValueError("height must be >= 0")
        if width < 0:
            raise ValueError("width must be >= 0")

    def area(self):
        """returns area"""
        return self.__height * self.__width

    def perimeter(self):
        """Returns perimeter"""
        if self.__width == 0 or self.__height == 0:
            return 0
        return self.__width*2 + self.__height*2

    @property
    def width(self):
        """Width getter"""
        return self.__width

    @property
    def height(self):
        """Height setter"""
        return self.__height

    @width.setter
    def width(self, value):
        """Width getter"""
        if type(value) is not int:
            raise TypeError("width must be an integer")
        if value < 0:
            raise ValueError("width must be >= 0")
        self.__width = value

    @height.setter
    def height(self, value):
        """Height getter"""
        if type(value) is not int:
            raise TypeError("height must be an integer")
        if value < 0:
            raise ValueError("height must be >= 0")
        self.__height = value


with open('2022/puzzle_inputs/3.txt') as file:
    strInput = file.read()

prior_str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
priority = {}
for i, letter in enumerate(prior_str):
    priority[letter] = i + 1

rucksacks = strInput.split('\n')[:-1]

priority_values = []
for sack in rucksacks:
    size = int(len(sack)/2)
    compartment1 = set(sack[:size])
    compartment2 = set(sack[size:])
    priority_values.append(priority[compartment1.intersection(compartment2).pop()])

# 1 - 7446
print(sum(priority_values))

priority_values = []
for i, sack1 in enumerate(rucksacks[::3]):
    sack1 = set(sack1)
    sack2 = set(rucksacks[(3*i)+1])
    sack3 = set(rucksacks[(3*i)+2])
    # intersect 1/2 and 2/3
    sack12 = sack1.intersection(sack2)
    sack23 = sack2.intersection(sack3)
    # intersection of the intersections
    priority_values.append(priority[sack12.intersection(sack23).pop()])

# 2- 2646
print(sum(priority_values))


#コードテストが動かないため途中で放り出した。

S = input()
len_bit = len(S)-1
T = []
temp = 0
ans = 0

for i in range(2 ** len(S)):
  list = []
  print("pattern {}: ".format(i), end="")
  for j in range(len_bit):
    if((i >> j) & 1):
      temp = int(T)
    else:
      T.append(S[j+1])
  Temp = int(T)
print(T)

C - たくさんの数式.py


import RPi.GPIO as GPIO
import time
import metroGPIO as io
import os

class _Getch:
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()
#This function must be called if using Metropolia IO board
io.initMetroPins()
def QuitIt():
	sys.exit()
# Turn all out put pins off
clearPins()
def action(key):
    global delay
    if key == 'w':
        print ("Forward")
        GPIO.output(io.OUT2, True)
        GPIO.output(io.OUT3, True)
        time.sleep(delay)
        GPIO.output(io.OUT2, False)
        GPIO.output(io.OUT3, False)

    if key == 's':
        print ("Reverse")
        GPIO.output(io.OUT4, True)
        GPIO.output(io.OUT1, True)
        time.sleep(delay)
        GPIO.output(io.OUT4, False)
        GPIO.output(io.OUT1, False)

    if key == 'a':
        print ("Left Pivot")
        GPIO.output(io.OUT2, True)
        GPIO.output(io.OUT4, True)
        time.sleep(delay)
        GPIO.output(io.OUT2, False)
        GPIO.output(io.OUT4, False)

    if key == 'd':
        print ("Right Pivot")
        GPIO.output(io.OUT3, True)
        GPIO.output(io.OUT1, True)
        time.sleep(delay)
        GPIO.output(io.OUT3, False)
        GPIO.output(io.OUT1, False)

    if key == 'l':
        delay = delay + 0.1
        print ("Delay Up: " + str(delay))

    if key == 'k':
        delay = delay - 0.1
        print ("Delay Dw: " + str(delay))

    if key == 'q':
        print ("Quit")
        QuitIt()

delay = 0.2

getch = _Getch()

try:
## Test the output: Change the while condition if you want to run this
    while True:
       action(getch())

#The GPIO.cleanup() function should be called at the end of your code always when using GPIO pins
except KeyboardInterrupt:
	pass

GPIO.cleanup()
print("Program has exited successfully!")

#end file


f = open("data.txt", "r")

def draw(X):
    global crt
    if len(crt) % 40 in {X-1, X, X+1}:
        crt.append('#')
    else:
        crt.append('.')

rows = 6
cols = 40
crt = []

X = 1

for line in f:
    line = line.strip()
    line = line.split(" ")

    if line[0] == "noop":
        draw(X)

    elif line[0] == "addx":
        draw(X)
        draw(X)
        X += int(line[1])

for i in range(rows):
    for j in range(cols):
        print(crt[i*cols + j], end='')
    print()


""" Some people tried to use TextLineReader for the assignment 1
but seem to have problems getting it work, so here is a short
script demonstrating the use of CSV reader on the heart dataset.
Note that the heart dataset is originally in txt so I first
converted it to csv to take advantage of the already laid out columns.

You can download heart.csv in the data folder.
Author: Chip Huyen
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
cs20si.stanford.edu
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import sys
sys.path.append('..')

import tensorflow as tf

DATA_PATH = 'data/heart.csv'
BATCH_SIZE = 2
N_FEATURES = 9

def batch_generator(filenames):
    """ filenames is the list of files you want to read from.
    In this case, it contains only heart.csv
    """
    filename_queue = tf.train.string_input_producer(filenames)
    reader = tf.TextLineReader(skip_header_lines=1) # skip the first line in the file
    _, value = reader.read(filename_queue)

    # record_defaults are the default values in case some of our columns are empty
    # This is also to tell tensorflow the format of our data (the type of the decode result)
    # for this dataset, out of 9 feature columns,
    # 8 of them are floats (some are integers, but to make our features homogenous,
    # we consider them floats), and 1 is string (at position 5)
    # the last column corresponds to the lable is an integer

    record_defaults = [[1.0] for _ in range(N_FEATURES)]
    record_defaults[4] = ['']
    record_defaults.append([1])

    # read in the 10 rows of data
    content = tf.decode_csv(value, record_defaults=record_defaults)

    # convert the 5th column (present/absent) to the binary value 0 and 1
    content[4] = tf.cond(tf.equal(content[4], tf.constant('Present')), lambda: tf.constant(1.0), lambda: tf.constant(0.0))

    # pack all 9 features into a tensor
    features = tf.stack(content[:N_FEATURES])

    # assign the last column to label
    label = content[-1]

    # minimum number elements in the queue after a dequeue, used to ensure
    # that the samples are sufficiently mixed
    # I think 10 times the BATCH_SIZE is sufficient
    min_after_dequeue = 10 * BATCH_SIZE

    # the maximum number of elements in the queue
    capacity = 20 * BATCH_SIZE

    # shuffle the data to generate BATCH_SIZE sample pairs
    data_batch, label_batch = tf.train.shuffle_batch([features, label], batch_size=BATCH_SIZE,
                                        capacity=capacity, min_after_dequeue=min_after_dequeue)

    return data_batch, label_batch

def generate_batches(data_batch, label_batch):
    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        for _ in range(10): # generate 10 batches
            features, labels = sess.run([data_batch, label_batch])
            print(features)
        coord.request_stop()
        coord.join(threads)

def main():
    data_batch, label_batch = batch_generator([DATA_PATH])
    generate_batches(data_batch, label_batch)

if __name__ == '__main__':
    main()


#importing flask, jsonify, render template and  request
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template("./index.html")

@app.route('/compute')
def compute():
    a = 4
    b = 3
    return str(a * b)

@app.route('/result')
def name_result():
    name = {
        "first": "Paul",
        "last": "Omikunle",
        "course": "Data Science"
    }
    {
        "first": "Lola",
        "last": "Omikunle",
        "course": "Machine learning"
    }
    return jsonify(name)

@app.route('/score', methods= ["POST"])
def score_val():
    DataDict = request.get_json()

    return jsonify(DataDict)

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


import os
import itertools
import argparse
from torch.utils.data import DataLoader
import torch

from tactile_gym.assets import add_assets_path
from tactile_gym.utils.general_utils import str2bool

from tactile_gym_sim2real.pix2pix.image_generator import DataGenerator
from tactile_gym_sim2real.image_transforms import *

parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int, default=1, help="size of the batches")
parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation")
parser.add_argument("--channels", type=int, default=1, help="number of image channels")
parser.add_argument("--shuffle", type=str2bool, default=True, help="shuffle the generated image data")
opt = parser.parse_args()

# Parameters
augmentation_params = {
          'dims':        (256, 256),
          'rshift':      None,  # (0.025, 0.025),
          'rzoom':       None,  # (0.98, 1),
          'thresh':      True,
          'brightlims':  None,  # [0.3,1.0,-50,50], # alpha limits for contrast, beta limits for brightness
          'noise_var':   None,  # 0.001,
          'stdiz':       False,
          'normlz':      True,
          'joint_aug':   False
          }

add_border = True
image_size_str = str(augmentation_params['dims'][0]) + 'x' + str(augmentation_params['dims'][1])

if add_border:

    border_images_path = add_assets_path(
        os.path.join('robot_assets', 'tactip', 'tactip_reference_images')
    )

    saved_file_dir = os.path.join(
        border_images_path,
        'standard',  # TODO: automate flat/standard/right_angle choice
        image_size_str,
    )

    border_gray = torch.FloatTensor(np.load(os.path.join(saved_file_dir, "nodef_gray.npy")))
    border_mask = torch.FloatTensor(np.load(os.path.join(saved_file_dir, "border_mask.npy")))

# data collected for task
# task_dirs = ['edge_2d']
task_dirs = ['surface_3d']
# task_dirs = ['spherical_probe']
# task_dirs = ['edge_2d', 'surface_3d']

# for GAN data
# data_dirs = ['tap']
data_dirs = ['shear']
# data_dirs = ['tap', 'shear']

# combine the data directories
combined_dirs = list(itertools.product(task_dirs, data_dirs))
combined_paths = [os.path.join(*i) for i in combined_dirs]

# data dir real -> sim
training_real_data_dirs = [os.path.join('../data_collection/real/data/', data_path, 'csv_train') for data_path in combined_paths]
validation_real_data_dirs = [os.path.join('../data_collection/real/data/', data_path, 'csv_val') for data_path in combined_paths]
training_sim_data_dirs = [os.path.join('../data_collection/sim/data/', data_path, image_size_str, 'csv_train') for data_path in combined_paths]
validation_sim_data_dirs = [os.path.join('../data_collection/sim/data/', data_path, image_size_str, 'csv_val') for data_path in combined_paths]

# Configure dataloaders
training_generator = DataGenerator(real_data_dirs=training_real_data_dirs,
                                   sim_data_dirs=training_sim_data_dirs,
                                   dim=augmentation_params['dims'],
                                   stdiz=augmentation_params['stdiz'],
                                   normlz=augmentation_params['normlz'],
                                   thresh=augmentation_params['thresh'],
                                   rshift=augmentation_params['rshift'],
                                   rzoom=augmentation_params['rzoom'],
                                   brightlims=augmentation_params['brightlims'],
                                   noise_var=augmentation_params['noise_var'],
                                   joint_aug=augmentation_params['joint_aug'])

val_generator = DataGenerator(real_data_dirs=validation_real_data_dirs,
                              sim_data_dirs=validation_sim_data_dirs,
                              dim=augmentation_params['dims'],
                              stdiz=augmentation_params['stdiz'],
                              normlz=augmentation_params['normlz'],
                              thresh=augmentation_params['thresh'],
                              rshift=None,
                              rzoom=None,
                              brightlims=None,
                              noise_var=None,
                              joint_aug=False)

training_loader = torch.utils.data.DataLoader(training_generator,
                                              batch_size=opt.batch_size,
                                              shuffle=opt.shuffle,
                                              num_workers=opt.n_cpu)

val_loader = torch.utils.data.DataLoader(val_generator,
                                         batch_size=opt.batch_size,
                                         shuffle=opt.shuffle,
                                         num_workers=opt.n_cpu)

for (i_batch, sample_batched) in enumerate(training_loader,0):

    real_images = sample_batched['real']
    sim_images = sample_batched['sim']

    if add_border:
        sim_images[:, :, border_mask == 1] = border_gray[border_mask == 1] / 255.0

    cv2.namedWindow("training_images")

    for i in range(opt.batch_size):

        # convert image to opencv format, not pytorch
        real_image = np.swapaxes(np.swapaxes(real_images[i].numpy(), 0, 2), 0, 1)
        sim_image  = np.swapaxes(np.swapaxes(sim_images[i].numpy(), 0, 2), 0, 1)
        overlay_image = cv2.addWeighted(real_image, 0.25, sim_image, 0.9, 0)[...,np.newaxis]

        disp_image = np.concatenate([real_image, sim_image, overlay_image], axis=1)

    # show image
    cv2.imshow("training_images", disp_image)
    k = cv2.waitKey(500)
    if k == 27:    # Esc key to stop
        break


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        stack1 = []
        stack2 = []
        carry = 0
        head = None
        # 先把两个链表数据分别入栈
        while l1:
            stack1.append(l1.val)
            l1 = l1.next
        while l2:
            stack2.append(l2.val)
            l2 = l2.next
        # 进行加法运算
        while stack1 or stack2:
            x = stack1.pop() if stack1 else 0
            y = stack2.pop() if stack2 else 0
            ans = x + y + carry
            res = ans % 10
            carry = ans // 10
            # 创建新链表方法
            cur = ListNode(res)
            cur.next = head
            head = cur
        # 如果两个栈长度相等 判断是否有进位
        if carry != 0:
            # 创建新链表 并指向cur
            last = ListNode(carry)
            last.next = cur
            return last
        return cur


from pathlib import Path
import pandas as pd
from prefect import flow, task
from prefect_gcp.cloud_storage import GcsBucket
from prefect_gcp import GcpCredentials

def extract_from_gcs(color: str, year: int, month: int) -> Path:
    """ Download trip data from GCS """
    gcs_path = f"data/{color}/{color}_tripdata_{year}-{month:02}.parquet"
    gcs_block = GcsBucket.load("dez-gcs")
    gcs_block.get_directory(from_path=gcs_path, local_path=f"./")
    return Path(f"./{gcs_path}")

@task()
def write_bq(df: pd.DataFrame) -> None:
    """Write DataFrame to BiqQuery"""
    gcp_credentials_block = GcpCredentials.load("dez-gcp-creds")

    df.to_gbq(
        destination_table="trips_data_all.rides",
        project_id="sage-nucleus-376020",
        credentials=gcp_credentials_block.get_credentials_from_service_account(),
        chunksize=500_000,
        if_exists="append"
    )

@flow(log_prints=False)
def etl_gcs_to_bq(months: list[int] = [1, 2], year: int = 2021, color: str = "yellow"):
    """Main ETL flow to lad data into Big Query"""
    total_rows = 0
    for month in months:
        path = extract_from_gcs(color=color, year=year, month=month)
        df = pd.read_parquet(path)
        total_rows += len(df)
        write_bq(df)
    print(f"Total number of rows processed: {total_rows}.")

if __name__ == "__main__":
    color = "yellow"
    months = [2,3]
    year = 2019
    etl_gcs_to_bq(months, year, color)


import datetime
import logging

import requests

from commands.feriados.constants import month_names, FERIADOS_URL, ESP_DAY

logger = logging.getLogger(__name__)

def get_feriados(year, **request_args):
    try:
        url = FERIADOS_URL.format(year=year)
        r = requests.get(url, **request_args)
        logger.info(f'Retrieved feriados from {r.url}')
    except Exception:
        logger.error("Error requestion feriados", exc_info=True)
        return None
    if r.status_code != 200:
        logger.info(f"Response not 200. {r.status_code} {r.reason}")
        return None

    feriados = r.json()
    logger.info("Feriados: %s", feriados)

    return feriados

def filter_past_feriados(today, feriados):
    """Returns the future feriados. Filtering past feriados."""
    return (
        f for f in feriados
        if (f['mes'], f['dia']) > (today.month, today.day)
    )

def next_feriado_message(today, nextest_feriado):
    """Get message corresponding to how many days are left until next feriado"""
    # Get days until next feriado
    next_feriado_date = datetime.datetime(
        day=nextest_feriado['dia'], month=nextest_feriado['mes'], year=today.year,
        hour=today.hour, minute=today.minute, second=min(today.second + 1, 59),
        tzinfo=datetime.timezone(datetime.timedelta(hours=-3))
    )

    # In python, timedeltas can have negative days if we do a-b and b > a). See timedelta docs for details
    faltan = (next_feriado_date - today)
    days_to_feriado = max(faltan.days, 0)

    if days_to_feriado == 0:
        feriado_msg = f"Hoy es feriado por *{nextest_feriado['motivo']}*! ðŸŽ‰\n"
    else:
        feriado_msg = (
            f"Faltan *{days_to_feriado} dÃas* para el prÃ³ximo feriado\n"
            f"- *{ESP_DAY[next_feriado_date.weekday()]} {nextest_feriado['dia']}"
            f" de {month_names[nextest_feriado['mes']]}* | _{nextest_feriado['motivo']}_\n"
        )

    return feriado_msg

def prettify_feriados(feriados, limit=None):
    """Receives a feriado generator of dict of following feriados and pretty prints them.
    ({
        "motivo": "AÃ±o Nuevo",
        "tipo": "inamovible",
        "dia": 1,
        "mes": 1,
        "id": "aÃ±o-nuevo"
    }, {
        "motivo": "Carnaval",
        "tipo": "inamovible",
        "dia": 4,
        "mes": 3,
        "id": "carnaval"
    },
        ...
    )
    Output:
        ðŸ‘‰ 25 de diciembre  -  Navidad | inamovible
        ðŸ‘‰ 31 de diciembre  -  Feriado Puente TurÃstico | puente
    """
    res = ''
    for feriado in list(feriados)[:limit]:
        fecha = f"{feriado['dia']} de {month_names[feriado['mes']]}"
        res += f"ðŸ‘‰ *{fecha}* -  {feriado['motivo']} | _{feriado['tipo']}_\n"

    return res

def read_limit_from_args(args):
    """Limit the amount of feriados to show."""
    DEFAULT = 10

    if not args:
        return DEFAULT
    elif args[0].upper() == 'ALL':
        # my_list[:None] == my_list
        return None
    else:
        try:
            return int(args[0])
        except (TypeError, ValueError):
            return DEFAULT


def temphum():
    import pigpio
    from time import sleep
    import RPi.GPIO as GPIO
    pi=pigpio.pi()
    import DHT22
    datapin=4
    s=DHT22.sensor(pi,datapin)
    s.trigger()
    sleep(2)
    t=s.humidity()
    h=s.temperature()
        #read soil moisture sensor
    GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering
    GPIO.setup(18, GPIO.IN)
               # this will carry on until you hit CTRL+C
    if GPIO.input(18):
        m="Soil is DRY"
        print("no water detected")
    else:
        print("water detected")
        m="Soil is WET"

    #print(t,s)
    print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t,h))
    s.cancel
    pi.stop()

    return(t,h,m)