import time
from datetime import datetime

import pytest

from telegram import (
    CallbackQuery,
    Chat,
    ChatJoinRequest,
    ChatMemberOwner,
    ChatMemberUpdated,
    ChosenInlineResult,
    InlineQuery,
    Message,
    Poll,
    PollAnswer,
    PollOption,
    PreCheckoutQuery,
    ShippingQuery,
    Update,
    User,
)
from telegram._utils.datetime import from_timestamp
from tests.auxil.slots import mro_slots

message = Message(1, datetime.utcnow(), Chat(1, ""), from_user=User(1, "", False), text="Text")
chat_member_updated = ChatMemberUpdated(
    Chat(1, "chat"),
    User(1, "", False),
    from_timestamp(int(time.time())),
    ChatMemberOwner(User(1, "", False), True),
    ChatMemberOwner(User(1, "", False), True),
)

chat_join_request = ChatJoinRequest(
    chat=Chat(1, Chat.SUPERGROUP),
    from_user=User(1, "first_name", False),
    date=from_timestamp(int(time.time())),
    user_chat_id=1,
    bio="bio",
)

params = [
    {"message": message},
    {"edited_message": message},
    {"callback_query": CallbackQuery(1, User(1, "", False), "chat", message=message)},
    {"channel_post": message},
    {"edited_channel_post": message},
    {"inline_query": InlineQuery(1, User(1, "", False), "", "")},
    {"chosen_inline_result": ChosenInlineResult("id", User(1, "", False), "")},
    {"shipping_query": ShippingQuery("id", User(1, "", False), "", None)},
    {"pre_checkout_query": PreCheckoutQuery("id", User(1, "", False), "", 0, "")},
    {"poll": Poll("id", "?", [PollOption(".", 1)], False, False, False, Poll.REGULAR, True)},
    {
        "poll_answer": PollAnswer(
            "id",
            [1],
            User(
                1,
                "",
                False,
            ),
            Chat(1, ""),
        )
    },
    {"my_chat_member": chat_member_updated},
    {"chat_member": chat_member_updated},
    {"chat_join_request": chat_join_request},
    # Must be last to conform with `ids` below!
    {"callback_query": CallbackQuery(1, User(1, "", False), "chat")},
]

all_types = (
    "message",
    "edited_message",
    "callback_query",
    "channel_post",
    "edited_channel_post",
    "inline_query",
    "chosen_inline_result",
    "shipping_query",
    "pre_checkout_query",
    "poll",
    "poll_answer",
    "my_chat_member",
    "chat_member",
    "chat_join_request",
)

ids = (*all_types, "callback_query_without_message")

@pytest.fixture(scope="module", params=params, ids=ids)
def update(request):
    return Update(update_id=TestUpdateBase.update_id, **request.param)

class TestUpdateBase:
    update_id = 868573637

class TestUpdateWithoutRequest(TestUpdateBase):
    def test_slot_behaviour(self):
        update = Update(self.update_id)
        for attr in update.__slots__:
            assert getattr(update, attr, "err") != "err", f"got extra slot '{attr}'"
        assert len(mro_slots(update)) == len(set(mro_slots(update))), "duplicate slot"

    @pytest.mark.parametrize("paramdict", argvalues=params, ids=ids)
    def test_de_json(self, bot, paramdict):
        json_dict = {"update_id": self.update_id}
        # Convert the single update 'item' to a dict of that item and apply it to the json_dict
        json_dict.update({k: v.to_dict() for k, v in paramdict.items()})
        update = Update.de_json(json_dict, bot)
        assert update.api_kwargs == {}

        assert update.update_id == self.update_id

        # Make sure only one thing in the update (other than update_id) is not None
        i = 0
        for _type in all_types:
            if getattr(update, _type) is not None:
                i += 1
                assert getattr(update, _type) == paramdict[_type]
        assert i == 1

    def test_update_de_json_empty(self, bot):
        update = Update.de_json(None, bot)

        assert update is None

    def test_to_dict(self, update):
        update_dict = update.to_dict()

        assert isinstance(update_dict, dict)
        assert update_dict["update_id"] == update.update_id
        for _type in all_types:
            if getattr(update, _type) is not None:
                assert update_dict[_type] == getattr(update, _type).to_dict()

    def test_equality(self):
        a = Update(self.update_id, message=message)
        b = Update(self.update_id, message=message)
        c = Update(self.update_id)
        d = Update(0, message=message)
        e = User(self.update_id, "", False)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)

    def test_effective_chat(self, update):
        # Test that it's sometimes None per docstring
        chat = update.effective_chat
        if not (
            update.inline_query is not None
            or update.chosen_inline_result is not None
            or (update.callback_query is not None and update.callback_query.message is None)
            or update.shipping_query is not None
            or update.pre_checkout_query is not None
            or update.poll is not None
            or update.poll_answer is not None
        ):
            assert chat.id == 1
        else:
            assert chat is None

    def test_effective_user(self, update):
        # Test that it's sometimes None per docstring
        user = update.effective_user
        if not (
            update.channel_post is not None
            or update.edited_channel_post is not None
            or update.poll is not None
        ):
            assert user.id == 1
        else:
            assert user is None

    def test_effective_message(self, update):
        # Test that it's sometimes None per docstring
        eff_message = update.effective_message
        if not (
            update.inline_query is not None
            or update.chosen_inline_result is not None
            or (update.callback_query is not None and update.callback_query.message is None)
            or update.shipping_query is not None
            or update.pre_checkout_query is not None
            or update.poll is not None
            or update.poll_answer is not None
            or update.my_chat_member is not None
            or update.chat_member is not None
            or update.chat_join_request is not None
        ):
            assert eff_message.message_id == message.message_id
        else:
            assert eff_message is None


import logging
import uuid
from copy import deepcopy
from datetime import datetime
from xml.etree import ElementTree

import pandas as pd
import pytz
import trodes_to_nwb.metadata_validation
import yaml
from hdmf.common.table import DynamicTable, VectorData
from ndx_franklab_novela import (
    AssociatedFiles,
    CameraDevice,
    DataAcqDevice,
    Probe,
    Shank,
    ShanksElectrode,
)
from pynwb import NWBFile
from pynwb.ecephys import ElectrodeGroup
from pynwb.file import ProcessingModule, Subject

from trodes_to_nwb import __version__

def load_metadata(
    metadata_path: str, probe_metadata_paths: list[str]
) -> tuple[dict, list[dict]]:
    """loads metadata files as dictionaries

    Parameters
    ----------
    metadata_path : str
        path to file made by yaml generator
    probe_metadata_paths : list[str]
        list of paths to yaml files with information on probe types

    Returns
    -------
    tuple[dict, list[dict]]
        the yaml generator metadata and list of probe metadatas
    """
    metadata = None
    with open(metadata_path, "r") as stream:
        metadata = yaml.safe_load(stream)
    (
        is_metadata_valid,
        metadata_errors,
    ) = trodes_to_nwb.metadata_validation.validate(metadata)
    if not is_metadata_valid:
        logger = logging.getLogger("convert")
        logger.exception("".join(metadata_errors))
    probe_metadata = []
    for path in probe_metadata_paths:
        with open(path, "r") as stream:
            probe_metadata.append(yaml.safe_load(stream))
    if not metadata["associated_files"] is None:
        for file in metadata["associated_files"]:
            file["task_epochs"] = [file["task_epochs"]]
    if not metadata["associated_video_files"] is None:
        for file in metadata["associated_video_files"]:
            file["task_epochs"] = [file["task_epochs"]]
    return metadata, probe_metadata

def initialize_nwb(metadata: dict, first_epoch_config: ElementTree) -> NWBFile:
    """constructs an NWBFile with basic session data

    Parameters
    ----------
    metadata : dict
        metadata from the yaml generator
    first_epoch_config : ElementTree
        xml tree of the first epoch's trodes rec file

    Returns
    -------
    NWBFile
        nwb file with basic session information
    """
    gconf = first_epoch_config.find("GlobalConfiguration")
    nwbfile = NWBFile(
        session_description=metadata["session_description"],
        experimenter=metadata["experimenter_name"],
        lab=metadata["lab"],
        institution=metadata["institution"],
        session_start_time=datetime.fromtimestamp(
            int(gconf.attrib["systemTimeAtCreation"].strip()) / 1000
        ),
        timestamps_reference_time=datetime.fromtimestamp(0, pytz.utc),
        identifier=str(uuid.uuid1()),
        session_id=metadata["session_id"],
        # notes=self.link_to_notes, TODO
        experiment_description=metadata["experiment_description"],
        source_script="trodes_to_nwb " + __version__,
        source_script_file_name="convert.py",
    )
    return nwbfile

def add_subject(nwbfile: NWBFile, metadata: dict) -> None:
    """Inserts Subject information into nwbfile

    Parameters
    ----------
    nwbfile : NWBFile
        nwb file being assembled
    metadata : dict
        metadata from the yaml generator
    """
    subject_metadata = deepcopy(metadata["subject"])
    # Convert weight to string and add units
    subject_metadata.update({"weight": f"{subject_metadata['weight']} g"})
    # Add the subject information to the file
    nwbfile.subject = Subject(**subject_metadata)

def add_cameras(nwbfile: NWBFile, metadata: dict) -> None:
    """Add information about each camera device to the nwb file

    Parameters
    ----------
    nwbfile : NWBFile
        nwb file being assembled
    metadata : dict
        metadata from the yaml generator
    """
    # add each camera device to the nwb
    for camera_metadata in metadata["cameras"]:
        nwbfile.add_device(
            CameraDevice(
                name="camera_device " + str(camera_metadata["id"]),
                meters_per_pixel=camera_metadata["meters_per_pixel"],
                manufacturer=camera_metadata["manufacturer"],
                model=camera_metadata["model"],
                lens=camera_metadata["lens"],
                camera_name=camera_metadata["camera_name"],
            )
        )

def add_acquisition_devices(nwbfile: NWBFile, metadata: dict) -> None:
    """Add information about each acquisition device to the nwb file

    Parameters
    ----------
    nwbfile : NWBFile
        nwb file being assembled
    metadata : dict
        metadata from the yaml generator
    """
    # add each acquisition device to the nwb
    for i, acq_metadata in enumerate(metadata["data_acq_device"]):
        # NOTE: naming convention taken from the old rec_to_nwb"
        nwbfile.add_device(
            DataAcqDevice(
                name=f"dataacq_device{i}",
                system=acq_metadata["system"],
                amplifier=acq_metadata["amplifier"],
                adc_circuit=acq_metadata["adc_circuit"],
            )
        )

def add_electrode_groups(
    nwbfile: NWBFile,
    metadata: dict,
    probe_metadata: list[dict],
    hw_channel_map: dict,
    ref_electrode_map: dict,
) -> None:
    """Adds electrode groups, probes, shanks, and electrodes to nwb file

    Parameters
    ----------
    nwbfile : NWBFile
        nwb file being assembled
    metadata : dict
        metadata from the yaml generator
    probe_metadata : list[dict]
        list of metadata about each probe type in the experiment
    hw_channel_map: dict
        A dictionary of dictionaries mapping {nwb_group_id->{nwb_electrode_id->hwChan}}
    """

    electrode_df_list = (
        []
    )  # dataframe to track non-default electrode data. add to electrodes table at end
    # loop through the electrode groups
    for probe_counter, egroup_metadata in enumerate(metadata["electrode_groups"]):
        # find correct channel map info
        channel_map = None
        for test_meta in metadata["ntrode_electrode_group_channel_map"]:
            if test_meta["electrode_group_id"] == egroup_metadata["id"]:
                channel_map = test_meta
                break
        # find the probe corresponding to the device type
        probe_meta = None
        for test_meta in probe_metadata:
            if test_meta["probe_type"] == egroup_metadata["device_type"]:
                probe_meta = test_meta
                break
        if probe_meta is None:
            raise FileNotFoundError(
                f"No probe metadata found for {egroup_metadata['device_type']}"
            )
        # Build the relevant Probe
        probe = Probe(
            id=egroup_metadata["id"],
            name=f"probe {egroup_metadata['id']}",
            probe_type=probe_meta["probe_type"],
            units=probe_meta["units"],
            probe_description=probe_meta["probe_description"],
            contact_side_numbering=probe_meta["contact_side_numbering"],
            contact_size=probe_meta["contact_size"],
        )
        # make the electrode group with the probe (Do it here so have electrodeGroup object to reference when making electrodes)
        e_group = ElectrodeGroup(
            name=str(egroup_metadata["id"]),
            description=egroup_metadata["description"],
            location=egroup_metadata["targeted_location"],
            device=probe,
        )
        nwbfile.add_electrode_group(e_group)
        # add Shanks to Probe
        electrode_counter_probe = 0
        for shank_counter, shank_meta in enumerate(probe_meta["shanks"]):
            # build the shank and add
            shank = Shank(
                name=str(shank_meta["shank_id"]),
            )
            # add the shank's electrodes based on metadata
            for electrode_meta in shank_meta["electrodes"]:
                shank.add_shanks_electrode(
                    ShanksElectrode(
                        name=str(electrode_meta["id"]),
                        rel_x=float(electrode_meta["rel_x"]),
                        rel_y=float(electrode_meta["rel_y"]),
                        rel_z=float(electrode_meta["rel_z"]),
                    )
                )
                # add the default electrode info to the nwb electrode table
                nwbfile.add_electrode(
                    location=egroup_metadata["targeted_location"],
                    group=e_group,
                    rel_x=float(electrode_meta["rel_x"]),
                    rel_y=float(electrode_meta["rel_y"]),
                    rel_z=float(electrode_meta["rel_z"]),
                    x=0.0,
                    y=0.0,
                    z=0.0,
                    imp=0.0,
                    filtering="None",
                )
                # track additional electrode data
                electrode_df_list.append(
                    pd.DataFrame.from_dict(
                        (
                            {
                                "hwChan": hw_channel_map[egroup_metadata["id"]][
                                    str(electrode_meta["id"])
                                ],
                                "ntrode_id": channel_map["ntrode_id"],
                                "channel_id": electrode_counter_probe,
                                "bad_channel": bool(
                                    electrode_counter_probe
                                    in channel_map["bad_channels"]
                                ),
                                "probe_shank": shank_counter,
                                "probe_electrode": electrode_counter_probe,
                            },
                        )
                    )
                )
                electrode_counter_probe += 1
            # add the shank to the probe
            probe.add_shank(shank)
        # add the completed probe to the nwb as a device
        nwbfile.add_device(probe)
    # add the electrode table information
    extend_electrode_table(nwbfile, pd.concat(electrode_df_list))
    # define the ref electrode for each row in the table
    # (done seperately because depends on indexing group id and channel)
    ref_electrode_id = []
    electrode_table = nwbfile.electrodes.to_dataframe()
    for nwb_group in list(electrode_table["group_name"]):
        # use the refference electrode map and defined electrode table to find index of the reference electrode
        ref_group, ref_electrode = ref_electrode_map[str(nwb_group)]
        ref_electrode_id.append(
            electrode_table.index[
                (electrode_table["group_name"] == ref_group)
                & (electrode_table["probe_electrode"] == ref_electrode)
            ][0]
        )
    # add the ref electrode id list to the electrodes table
    nwbfile.electrodes.add_column(
        name="ref_elect_id",
        description="Experimenter selected reference electrode id",
        data=ref_electrode_id,
    ),

def extend_electrode_table(nwbfile, electrode_df):
    nwbfile.electrodes.add_column(
        name="hwChan",
        description="SpikeGadgets Hardware channel",
        data=list(electrode_df["hwChan"]),
    )
    nwbfile.electrodes.add_column(
        name="ntrode_id",
        description="Experimenter defined ID for this probe",
        data=list(electrode_df["ntrode_id"]),
    )
    nwbfile.electrodes.add_column(
        name="channel_id",
        description="Channel number of electrode within the probe",
        data=list(electrode_df["channel_id"]),
    )
    nwbfile.electrodes.add_column(
        name="bad_channel",
        description="True if noisy or disconnected",
        data=list(electrode_df["bad_channel"]),
    )
    nwbfile.electrodes.add_column(
        name="probe_shank",
        description="The shank of the probe this channel is located on",
        data=list(electrode_df["probe_shank"]),
    )
    nwbfile.electrodes.add_column(
        name="probe_electrode",
        description="the number of this electrode with respect to the probe",
        data=list(electrode_df["probe_electrode"]),
    )

def add_tasks(nwbfile: NWBFile, metadata: dict) -> None:
    """Creates processing module for tasks and adds their metadata info

    Parameters
    ----------
    nwbfile : NWBFile
        nwb file being assembled
    metadata : dict
        metadata from the yaml generator
    """
    # make a processing module for task data
    nwbfile.add_processing_module(
        ProcessingModule("tasks", "Contains all tasks information")
    )
    # loop through tasks in the metadata and add them
    for i, task_metadata in enumerate(metadata["tasks"]):
        task_name = VectorData(
            name="task_name",
            description="the name of the task",
            data=[task_metadata["task_name"]],
        )
        task_description = VectorData(
            name="task_description",
            description="a description of the task",
            data=[task_metadata["task_description"]],
        )
        camera_id = VectorData(
            name="camera_id",
            description="the ID number of the camera used for video",
            data=[[int(camera_id) for camera_id in task_metadata["camera_id"]]],
        )
        task_epochs = VectorData(
            name="task_epochs",
            description="the temporal epochs where the animal was exposed to this task",
            data=[[int(epoch) for epoch in task_metadata["task_epochs"]]],
        )
        # NOTE: rec_to_nwb checked that this value existed and filed with none otherwise. Do we require this in yaml?
        task_environment = VectorData(
            name="task_environment",
            description="the environment in which the animal performed the task",
            data=[task_metadata["task_environment"]],
        )
        task = DynamicTable(
            name=f"task_{i}",  # NOTE: Do we want this name to match the descriptive name entered?
            description="",
            columns=[
                task_name,
                task_description,
                camera_id,
                task_epochs,
                task_environment,
            ],
        )
        nwbfile.processing["tasks"].add(task)

def add_associated_files(nwbfile: NWBFile, metadata: dict) -> None:
    """Adds associated files processing module. Reads in file referenced in metadata and stores in processing

    Parameters
    ----------
    nwbfile : NWBFile
        nwb file being assembled
    metadata : dict
        metadata from the yaml generator
    """
    if "associated_files" not in metadata:
        return

    logger = logging.getLogger("convert")
    associated_files = []
    for file in metadata["associated_files"]:
        # read file content
        content = ""
        try:
            with open(file["path"], "r") as open_file:
                content = open_file.read()
        except FileNotFoundError as err:
            logger.info(f"ERROR: associated file {file['path']} does not exist")
            logger.info(str(err))
        except IOError as err:
            logger.info(f"ERROR: Cannot read file at {file['path']}")
            logger.info(str(err))
        # convert task epoch values into strings
        task_epochs = "".join([str(element) + ", " for element in file["task_epochs"]])
        associated_files.append(
            AssociatedFiles(
                name=file["name"],
                description=file["description"],
                content=content,
                task_epochs=task_epochs,
            )
        )
    if "associated_files" not in nwbfile.processing:
        nwbfile.create_processing_module(
            name="associated_files", description="Contains all associated files data"
        )
    nwbfile.processing["associated_files"].add(associated_files)


import pandas as pd

# En este caso se leen los datos desde archivos csv, pero
#  aqui podríamos estar obteniendo datos en tiempo real.
# Probablemente se necesiten estar actualizando los datos de precios de la leche,
#  variables climatologicas y macroeconomicas

def obtain_data():
    # Obtener datos en tiempo real??
    precipitaciones = pd.read_csv('./data/precipitaciones.csv')
    banco_central = pd.read_csv('./data/banco_central.csv')
    precio_leche = pd.read_csv('./data/precio_leche.csv')

    # Guardarlos en archivos temporales
    precipitaciones.to_pickle('tmp/precipitaciones.pkl')
    banco_central.to_pickle('tmp/banco_central.pkl')
    precio_leche.to_pickle('tmp/precio_leche.pkl')


# Quebre o programa em pequenas partes.
import random

from arts import logo, vs
from game_data import data

# Mostrar a imagem.
print(logo)
score = 0
game_should_continue = True
account_b = random.choice(data)

# Formatar a lista para algo "User Friendly".
def format_data(account):
    """
    It takes a dictionary as an argument, and then prints out a formatted string based on the values of
    the dictionary
    :param account: The account object
    """
    account_name = account["name"]
    account_descr = account["description"]
    account_country = account["country"]
    return f"{account_name}, a {account_descr}, from {account_country}"

def check_answer(guess, a_followers, b_followers):
    """
    If a has more followers than b, then the guess should be "a", otherwise the guess should be "b"
    :param guess: a string, either "a" or "b" representing which account has more followers
    :param a_followers: The number of followers of the first account
    :param b_followers: the number of followers of the account that you think has more followers
    :return: True or False
    """
    if a_followers > b_followers:
        return guess == "a"
    else:
        return guess == "b"

# Faça o jogo repetir.
# noinspection SpellCheckingInspection
while game_should_continue:
    # Gerar uma lista aleatória do game_data.

    # Faça a lista B se tornar a lista A para próxima pergunta.
    account_a = account_b
    account_b = random.choice(data)
    while account_a == account_b:
        account_b = random.choice(data)

    print(f"Compare A: {format_data(account_a)}.")
    print(vs)
    print(f"Against B: {format_data(account_b)}.")

    # Faça uma pergunta para o úsuario.
    guess = input("Who has more followers? Type 'A' or 'B': ").lower()

    # Cheque se o usuario esta correto.
    ##Pegue o numero de seguidores de cada conta.
    a_followers_count = account_a["follower_count"]
    b_followers_count = account_b["follower_count"]

    is_correct = check_answer(guess, a_followers_count, b_followers_count)

    # Dar o feedback ao usuario.
    # Mantém a pontuação.
    if is_correct:
        # Mantém a pontuação.

        score += 1
        print(f"You're right! Current score: {score}.")
    else:
        game_should_continue = False
        print(f"Sorry, that's wrong. Final score: {score}.")

Days 10-19 (Beginner - Intermediate)/Day 14 - Higher Lower Game Project/day_14_project_correcao.py


import sqlite3

class SqlitePageRepository:
    _table = "content"
    _route = "route"
    _json = "json"

    _create = "CREATE TABLE IF NOT EXISTS " + _table + "(" + _route + " TEXT PRIMARY KEY NOT NULL UNIQUE, " + _json + " TEXT NOT NULL) WITHOUT ROWID;"
    _addOrUpdate = "INSERT OR REPLACE INTO " + _table + "(" + _route + ", " + _json + ") VALUES(?, ?);"
    _get = "SELECT " + _json + " FROM " + _table + " WHERE " + _route + " = ?;"
    _delete = "DELETE FROM " + _table + " WHERE " + _route + " = ?;"

    def __init__(self, dbPath):
        self.dbPath = dbPath
        con = self.__getConnection()
        with con:
            cursor = con.cursor()
            cursor.execute(self._create)

    def addOrUpdate(self, route, content):
        con = self.__getConnection()
        with con:
            cursor = con.cursor()
            cursor.execute(self._addOrUpdate,(route, content))

    def get(self, route):
        con = self.__getConnection()
        with con:
            cursor = con.cursor()
            cursor.execute(self._get,(route,))
            return cursor.fetchone()

    def delete(self, route):
        con = self.__getConnection()
        with con:
            cursor = con.cursor()
            cursor.execute(self._delete,(route,))

    def __getConnection(self):
        return sqlite3.connect(self.dbPath)


import os
import sys

import numpy as np
import pandas as pd
from PySide6.QtCore import Slot, Qt
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtGui import QIcon

from designs.mainWindow import Ui_MainWindow
import info.transform as tnsf

try:
    from ctypes import windll
    myappid = 'mycompany.myproduct.subproduct.version'
    windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
    pass

basedir = os.path.dirname(__file__)

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("EPH")

        self.table = pd.read_csv(
            os.path.join(basedir, "info", "table_month.csv"), index_col=0
        )
        self.input_Button.clicked.connect(self.push_button)

        self.output_Label1.setStyleSheet("color: red")
        self.output_Label1.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.output_Label1.setText("")

    @Slot()
    def push_button(self):
        temp_max = self.input_Line1.text()
        temp_mean = self.input_Line2.text()
        temp_min = self.input_Line3.text()

        if not (temp_min and temp_mean and temp_max):
            self.output_Label1.setText("Faltan introducir una o más temperaturas")
            return

        try:
            temp_min = float(temp_min)
            temp_mean = float(temp_mean)
            temp_max = float(temp_max)
        except:
            self.output_Label1.setText("Una o más temperaturas son inválidas")
            return

        row = tnsf.LAT[self.input_Combo3.currentText()]
        column = (
            tnsf.MONTH[self.input_Combo2.currentText()]
            + "."
            + tnsf.HEM[self.input_Combo1.currentText()]
        )

        r0 = self.table[column][row]
        kt = tnsf.KT[self.input_Combo4.currentText()]

        rs = round(r0 * kt * ((temp_max - temp_min) ** 0.5), 3)
        et0 = round(0.0135 * (temp_mean + 17.78) * rs, 3)

        if type(rs) == np.complex128:
            self.output_Label1.setText(
                "Las temperaturas son incorrectas (Posiblemente Tmax mayor a Tmin)"
            )
            return
        self.output_Label1.setText("")
        self.output_Line1.setText(str(rs))
        self.output_Line2.setText(str(et0))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(os.path.join(basedir,"resources", 'icon.ico')))
    window = MainWindow()
    window.show()

    sys.exit(app.exec())


from heapq import merge
from csvreader import csv_reader
import firebase_admin

from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate('pythonScripts /team-7-site-59ff2-firebase-adminsdkServiceKey.json')
firebase_admin.initialize_app(cred,{'projectID': "team-7-site-59ff2",})

db = firestore.client()

employee_ref = db.collection('employees')
emp = employee_ref.stream()

emp_ref = employee_ref.document('id')

for doc in emp:
  print(f'{doc.id} => {doc.to_dict()}')

reader = csv_reader()
all_rows = reader.read_file("pythonScripts /employeeDatabase.csv")

for row in all_rows:
  print(row)
  '''
  new_emp_ref = employee_ref.document()
  new_emp_ref.set({
    'firstName' : row['\ufeffFirst Name '],
    'lastName'  : row['Last Name '],
    'employeeStatus': row['Employee Status'],
    'title' : row['Title(ROLE)'],
    'payRate' : row['Pay-Rate'],
    'gender' :  row['Gender'],
    'hireDate' :  row['Hire-Date'],
    'email' : row['Email'],
    'phoneNumber' : row['PhoneNumber'],
  })
'''


from collections import namedtuple

Result = namedtuple("Result","maxSum leftBound rightBound upBound lowBound")

KadanesResult = namedtuple("KadanesResult","maxSum start end")

def kadanes(temp):
  _max = 0
  max_start = -1
  max_end = -1
  current_start = 0
  max_so_far = 0
  for i in range(len(temp)):
    max_so_far += temp[i]
    if max_so_far < 0:
      max_so_far = 0
      current_start = i + 1
    if max_so_far > _max:
      max_start = current_start
      max_end = i
      _max = max_so_far
  return KadanesResult(_max, max_start, max_end)

def max_sum_rectangle(rectangle):
  rows = len(rectangle)
  cols = len(rectangle[0])
  result = Result(float("-inf"), -1, -1, -1, -1)
  for left in range(cols):
    temp = [0 for _ in range(rows)]
    for right in range(left, cols):
      for i in range(rows):
        temp[i] += rectangle[i][right]

      kadanes_result = kadanes(temp)
      if kadanes_result.maxSum >  result.maxSum:
        result = Result(kadanes_result.maxSum, left, right, kadanes_result.start, kadanes_result.end)
  return result

M = [
  [2, 1, -3, -4, 5],
  [0, 6, 3, 4, 1],
  [2, -2, -1, 4, -5],
  [-3, 3, 1, 0, 3]
]

result = max_sum_rectangle(M)
print(result)


import pygame
import random

import constants
from img_sound_loader import load_image
from img_sound_loader import load_sound

def create_item(classname,x,y,player):
    enemy_dict = {HP_Potion.__name__:HP_Potion(x,y,player),
                  }
    try:
        return enemy_dict[classname]
    except KeyError:
        print("item doesn't match the key.")
        raise

class Item(pygame.sprite.Sprite):
    def __init__(self,x,y,player):
        super().__init__()

        # Set hit player sound.
        self.hit_player_sound = None

        # Moving frames sprite.
        self.moving_frames = []

        # Current image of item
        self.image = None
        self.rect = None

        # Get sound when hit
        self.hit_sound = None

        # Frame count
        self.frame_count = 0
    def update(self):
        pass
    def draw(self,screen):
        screen.blit(self.image,(self.rect.x,self.rect.y))
    def use_item(self):
        pass

class HP_Potion(Item):
    def __init__(self,x,y,player):
        super().__init__(x,y,player)

        self.player = player

        self.hit_sound = load_sound("HP_potion_hit.ogg","resources/sounds")

        # Add the picture of each frames for this item.
        image,rect = load_image("HP_potion1.png","resources/items",-1)
        self.moving_frames.append(image)
        image,rect = load_image("HP_potion2.png","resources/items",-1)
        self.moving_frames.append(image)

        self.image = self.moving_frames[0]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
    def update(self):
        # Change image every 60 frames.(1 second)
        self.frame_count = (self.frame_count + 1) % 120
        frame = (self.frame_count // 60) % len(self.moving_frames)
        self.image = self.moving_frames[frame]
    def use_item(self):
        self.player.HP += 2


import requests
from bs4 import BeautifulSoup
import pandas as pd
import markdownify
import re
from tqdm import tqdm
from datasets import Dataset
import concurrent.futures
import os

import itertools

class LinksParser:
    def __init__(
        self,
    ) -> None:
        self.domain = "https://www.povarenok.ru/recipes"
        self.dataset = []

    def parse_func(self, page_num):
        url = f"{self.domain}/~{page_num}/?sort=rating&order=desc"
        response = requests.get(url=url)
        soup = BeautifulSoup(response.text)
        items = soup.find_all("article", class_="item-bl")
        dataset = []

        for card in items:
            title = card.find("h2").text.strip()
            ingridients = [
                item.text for item in card.find("span", class_="list").find_all("a")
            ]
            views = int(card.find("span", class_="i-views").text)
            likes = int(card.find("span", class_="i-likes").text)
            ups = int(card.find("span", class_="i-up").text)
            link = card.find("h2").find("a")["href"]

            dataset.append(
                {
                    "title": title,
                    "ingridients": ingridients,
                    "views": views,
                    "likes": likes,
                    "ups": ups,
                    "link": link,
                }
            )
        return dataset

    def parse_parallel(self):
        with concurrent.futures.ProcessPoolExecutor(
            max_workers=os.cpu_count()
        ) as executor:
            texts = tqdm(
                executor.map(
                    self.parse_func,
                    list(range(1, 3101)),
                    chunksize=1,
                )
            )
            texts = list(texts)
        self.dataset = list(itertools.chain(*texts))

if __name__ == "__main__":
    parser = LinksParser()
    parser.parse_parallel()
    # print(parser.dataset)
    dataset = Dataset.from_list(parser.dataset)
    dataset.push_to_hub("dim/povarenok_links")


import sys

import libs.utils as utils

from libs.Experiment import Experiment

class Controller:
    ''' Handles meta information to run an experiment, such
        as setting pathing and loading config files.
    '''

    def __init__(self, logger) -> None:
        self.logger = logger
        self.main_dir = utils.get_main_dir_from_config_file()
        self.exps = self.get_experiment_dict()
        self.add_sys_paths()
        self.main_config = utils.load_data_from_yaml(self.main_dir/'resources'/'config.yaml')

    def add_sys_paths(self):
        '''
        Add ./libs and ./exp_module/experiments/ to sys path

        Args
        ----------

        Returns
        ----------
        '''

        for path in [self.main_dir/'libs',
                     self.main_dir/'exp_module'/'experiments']:
            sys.path.insert(0, path)

    def get_experiment_dict(self):
        '''
        Creates a dictionary with paths to all
        experiment folders

        Args
        ----------

        Returns
        ----------
        exp_dict: dict{exp_folder_name: Path()}
        '''

        path = self.main_dir/'exp_module'/'experiments'

        return {exp.name: path/exp for exp in path.iterdir()
                                   if '__' not in exp.name}

    def load(self, name, ppt_id):
        '''
        Creates an Experiment instance and runs it.
        Raises Exception if anything fails

        Args
        ----------
        name: str
            name of experiment
        ppt_id: str
            id of participant, as set in Admin panel

        Returns
        ----------
        e: Experiment() or Exception
            experiment instance or, if failed, an Exception
        '''

        try:
            e = Experiment(name, ppt_id, debug=self.main_config['debug'],
                                         logger=self.logger)
            e.go()
            return e

        except Exception as e:
            self.logger.error(f"Failed running {name}.")
            self.logger.error(f"ERROR {e}.")
            return e

if __name__=='__main__':
    import logging
    c = Controller(logging)
    c.load('grasping', 'test_id_01')


counter = 1     # global counter

# test function takes an output and checks it against a single or list of expected outputs. default expected is None
def test(actual, expected=None, subtest=False):
    global counter  # global test number
    boolean = False  # whether test passed
    try:
        if type(expected) is not list and expected is not None:
            expected = [expected]
        if not subtest:
            print(f"test {counter} -> ", end="")
        try:
            if (actual is None and expected is None) or (actual in expected):
                if not subtest:
                    print("passed")
                boolean = True
            else:
                if not subtest:
                    print("failed\t[ actual { " + str(actual) + " }  expected { " + str(*expected) + " } ] ")
        except TypeError:
            if not subtest:
                print("failed\t[ actual { " + str(actual) + " }  expected { " + str(expected) + " } ] ")
    except Exception:
        boolean = False
        if not subtest:
            print("failed\t[ encountered error ] ")
    counter += 1
    return counter - 1, boolean

if __name__ == "__main__":
    # testing the tests ;)
    test(test("output", "output", True), (counter-1, True))
    test(test("output", "error", True), (counter-1, False))
    test(test(None, subtest=True), (counter-1, True))
    test(test(24, 24, True), (counter-1, True))
    test(test(3.45, 3.45, True), (counter-1, True))
    test(test(True, True, True), (counter-1, True))
    test(test(True, False, True), (counter-1, False))


# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None:
            return l2
        elif l2 is None:
            return l1

        result_list = None
        result_cur = result_list

        while l1 is not None and l2 is not None:
            if l1.val < l2.val:
                if result_cur is None:
                    result_list = l1
                else:
                    result_cur.next = l1
                result_cur = l1
                l1 = l1.next
            else:
                if result_cur is None:
                    result_list = l2
                else:
                    result_cur.next = l2
                result_cur = l2
                l2 = l2.next

        while l1 is not None:
            result_cur.next = l1
            result_cur = l1
            l1 = l1.next

        while l2 is not None:
            result_cur.next = l2
            result_cur = l2
            l2 = l2.next

        return result_list

test_input_1 = [3,6,9]
test_input_2 = [1,1,5,8]

###############
test_l1 = ListNode(test_input_1[0])
test_l1_cur = test_l1

for data in test_input_1[1:]:
    new_node = ListNode(data)
    test_l1_cur.next = new_node
    test_l1_cur = test_l1_cur.next

test_l1_cur = test_l1

while test_l1_cur is not None:
    print(test_l1_cur.val,'** ',end='')
    test_l1_cur = test_l1_cur.next

print('')
###############

test_l2 = ListNode(test_input_2[0])
test_l2_cur = test_l2

for data in test_input_2[1:]:
    new_node = ListNode(data)
    test_l2_cur.next = new_node
    test_l2_cur = test_l2_cur.next

test_l2_cur = test_l2
while test_l2_cur is not None:
    print(test_l2_cur.val,'** ',end='')
    test_l2_cur = test_l2_cur.next

print('')
#################

sol = Solution()
result_list = sol.mergeTwoLists(test_l1, test_l2)

result_cur = result_list
while result_cur is not None:
    print(result_cur.val,'** ',end='')
    result_cur = result_cur.next


# -*-coding:utf-8 -*-
import numpy as np
import pandas as pd
from NPClab_Package.traitement_deeplabcut.DeepLabCut_traitment import PreFormDLC
from NPClab_Package.utilitaire_load import LabviewFilesReward, LabviewFilesTrajectory, LoadData, DeepLabCutFileImport
from utilitaire_traitement.TrajectoryTraitement import BasicTraitmentTrajectory
from traitement_labview.Labview_traitment import AnalyseFromLabview

# _______________________________a utiliser pour les data deeplabcut
dir_DLC = r'/data/trajectoire_tarek_deeplapcut/DLC_data'
DLC_brute = LoadData.init_data(DeepLabCutFileImport, dir_DLC,
                               'Chichi_3_cplx_04bis_500mV_03042020-1627DLC_resnet50_testgpuMay2shuffle1_50000.csv')

data_DLC = PreFormDLC()
data_tracking_DLC = data_DLC.load_data_from_DLC(data_brute=DLC_brute.data)

traitment_DLC = BasicTraitmentTrajectory()
data_tracking_brute_DLC = traitment_DLC.data_brute(data_DLC, data_tracking_DLC)
# data_tracking_correc_DLC = traitment_DLC.correction(data_DLC, data_tracking_DLC)
#
# norme_vecteur_entre_point = traitment_DLC.norme_vecteur_entre_points(data_tracking_DLC, name_pointsA='hang',
#                                                                      name_pointsB='hand')

# name = f'\\testsave.csv'
# csv_save = SavingMethodes()
# csv_save.save_csv(path=dir_DLC + name, data=data_tracking_DLC)

# ------------------------------------- parti plot ----------------------------------------
from utilitaire_plot.TrajectoireBasicPlot import SpecifiquePlot
plotcomportement = SpecifiquePlot()
# plotcomportement.plot_norme_vecteur(traitment_DLC.norme_vecteur, data_DLC)
plotcomportement.plot_traj(data_tracking_brute_DLC, data_DLC.items, 'DLC')

#------------------------------------- parti import data labview ---------------------------------------------------

dir_txt_traj = r'D:\Dropbox\python\import_neuralynxv2\data\cplx07 + bsl\fichier traj\*.txt'

# chargement de la trajectoire contient "x, y, point"
trajectoire = LoadData.init_data(LabviewFilesTrajectory, dir_txt_traj)
# chargement des temps en ms "temps" contenu dans le fichier rewards
reward = LoadData.init_data(LabviewFilesReward, dir_txt_traj)

# traitement
data_AFL = AnalyseFromLabview()
# création d'un dataframe contenant "trajectoire_x, trajectoire_y, reward, rewards, omissions"
data_tracking_AFL = data_AFL.load_data_from_labview(trajectoire, reward)

# ------------------------------------- parti traitement de la trajectoire labview -----------------
traitment_AFL = BasicTraitmentTrajectory()
data_traiter_AFL = traitment_AFL.correction(data_AFL, data_AFL.format_correction)

# ------------------------------------- parti preparation des données pour le plot ---------
from utilitaire_traitement.PreFormatData import PreFormatData

data_formater = PreFormatData()

omission_time = pd.Series(data_AFL.omission, name='omission')
# ---------------------------------------------
data_formater.make_event_around(data=traitment_AFL.norme_vecteur, reward=omission_time)

# ------------------------------------- parti plot ----------------------------------------
# from utilitaire_plot.TrajectoireBasicPlot import SpecifiquePlot
# plotcomportement = SpecifiquePlot()
# plotcomportement.plot_event_around(['trajectoire'], data_formater.around_event)
# plotcomportement.plot_norme_vecteur(traitment_AFL.norme_vecteur, data_AFL)
# plotcomportement.plot_traj(data_tracking_AFL, data_AFL.couple_de_points[0])

# -------------------------------------------- partie event ---------------------------------------------------
from NPClab_Package.utilitaire_load import ImportNeuralynx, LoadData
from NPClab_Package.traitement_event import EventFileNeuralynx, EventRewardNeuralynx

dir_data: str = r'/data/cplx07 + bsl'

event_brute = LoadData.init_data(ImportNeuralynx, dir_data, 'event')

Event = EventFileNeuralynx(dir_data=dir_data, event=event_brute)
info_event, all_event = Event.set_event()

reward = EventRewardNeuralynx()

start_stim, start_stim_index = reward.set_reward(reward_time=all_event['num segment : 1']['time'],
                                                 reward_index=all_event['num segment : 1']['index'])
start_stim_index = start_stim_index.astype(dtype=int)

# ------------------------------------ parti spike -----------------------------------------
from traitement_spike import Segment, Spike, PreFormatSpike
from NPClab_Package.utilitaire_load import NeuralynxFilesSpike

dir_spikefile: str = r'D:\Dropbox\python\import_neuralynxv2\data\cplx07 + bsl\clustering\*.txt'

spikefiles = LoadData.init_data(NeuralynxFilesSpike, dir_spikefile)

segment_infos = Segment(dir_data=dir_data)
segment_data = segment_infos.set_segment(event_brute=event_brute.Event, event_final=all_event)

e = PreFormatSpike(dir_data=dir_data, spike_files=spikefiles, segment_infos=segment_data, all_event=all_event)
e.set_spike()

spike = Spike(dir_data=dir_data, name_neurone='neurone0_brute', segment_infos=segment_data, num_segment=0)
spike.set_neurone()
spike = Spike(dir_data=dir_data, name_neurone='neurone0_brute', segment_infos=segment_data, num_segment=1)
spike.set_neurone()
spike = Spike(dir_data=dir_data, name_neurone='neurone1_brute', segment_infos=segment_data, num_segment=0)
spike.set_neurone()
spike = Spike(dir_data=dir_data, name_neurone='neurone1_brute', segment_infos=segment_data, num_segment=1)
spike.set_neurone()

del spike, segment_infos, segment_data, e

# -------------------------------------------- partie reload specifique neurone ---------------------------------
from NPClab_Package.utilitaire_load import NeuroneFilesSerialiser

dir_save = r'/data/cplx07 + bsl/save'
name = 'segment1_neurone0'
neurone = LoadData.init_data(NeuroneFilesSerialiser, dir_save, name)

# ------------------------------------- parti reload specification segment ----------------------------------
from NPClab_Package.utilitaire_load import SegmentFilesSerialiser

dir_save = r'/data/cplx07 + bsl/save'
name = 'segment_infos'
num_segment = 1
base_time_segment = LoadData.init_data(SegmentFilesSerialiser, dir_save, name, num_segment)

# -------------------------------------- parti recallage omission sur temps spike --------------------------
from NPClab_Package.traitement_event import EventFromOther

omission_recallage = EventFromOther()
omission_recallage.start(np.array(omission_time), base_time_segment.data, base_time_segment.data[0])
omission_spike_time = pd.Series(base_time_segment.data[omission_recallage.event_time_in_raw])
# ------------------------------------- parti preparation des données pour le plot avec spike---------
from utilitaire_plot.BasicPlotSpike import GenericPlotV2

plot = GenericPlotV2()

omission_plot_data = plot.plot_raster_event_spike(spike_time=np.array(neurone.data['time']),
                                                  time_event=omission_spike_time, name='omission')
plot.plot_kernel_density(omission_plot_data, 'omission')

reward_spike_time = pd.Series(base_time_segment.data[start_stim_index])
reward_plot_data = plot.plot_raster_event_spike(spike_time=np.array(neurone.data['time']), time_event=reward_spike_time,
                                                name='reward')
plot.plot_kernel_density(reward_plot_data, 'reward')
# -------------------------------------------- partie plot spike ----------------------------------------------

print('fin')


from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.registerPage, name="register"),
	path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),

    path('profile', views.profile, name='profile'),
    path('update', views.update, name='update'),

    path('', views.index, name='index'),
    path('languages', views.languages, name='languages'),
    path('test/<str:pk>/', views.test, name='test'),
    path('save/<str:pk>/', views.saveSelected, name='save'),
    path('result', views.result, name='result'),
    path('contactus', views.contactus, name='contact'),
]


from tkinter import *
from pyspark import SparkContext, SparkConf, SparkFiles
from pyspark.sql import SparkSession
from pyspark.sql.types import StringType
from pyspark import SparkFiles
from DataTree import Tree
from tkinter import messagebox as mb
import tkinter.font as font
from node_utils.Node import Node
from node_utils.nodes.ReduceByKey import ReduceByKey
from node_utils.nodes.Map import Map
from node_utils.nodes.Input import InputFile
from node_utils.nodes.Output import OutputNode
from node_utils.nodes.Filter import Filter
from node_utils.nodes.Combiner import Combiner
from node_utils.nodes.Model import Model
from node_utils.nodes.Evaluate import Evaluator
from line_utils.Line import Connection
from graph_utils.Graph import Graph
import os

class GUI:
    sc = SparkContext(master="local[*]", appName="gui")
    # sc = SparkContext(master="spark://spark-master:7077", appName="gui")
    spark = SparkSession.builder.appName("gui").getOrCreate()

    def __init__(self, root):
        self.root = root
        self.canvas = Canvas(root, width=1600, height=800)
        self.canvas.pack()
        self.frame = Frame(root, width=1600, height=100).pack()
        self.buttons = {}
        self.nodes = []  # array keeping track of all nodes
        self.lines = []
        self.selectedShape = 0
        self.bind_keys()
        self.create()

    def create(self):
        buttonFont = font.Font(weight="bold", size=14)
        labelFont = font.Font(weight="bold", size = 18)
        label = Label(self.frame, text="Node creation boxes", font=labelFont)
        label.place(y=620, x=550)
        label2 = Label(self.frame, text="Configuration boxes", font=labelFont)
        label2.place(y=620, x=970)
        self.canvas.create_rectangle(10, 10, 1430, 600)
        self.buttons["input"] = Button(self.frame, text="Input", background="light goldenrod",
                                       command=self.createInputNode, font=buttonFont)
        self.buttons["input"].place(height=40, width=120, y=660, x=350)
        # self.buttons["combine"] = Button(self.frame, text="Combine files", highlightbackground="cyan",
        #                                command=self.create_combiner_node)
        # self.buttons["combine"].place(height=40, width=120, y=740, x=350)
        self.buttons["foreach"] = Button(self.frame, text="For-each", background="cornflower blue",
                                         command=lambda: self.create_new_node(Map), font=buttonFont)
        self.buttons["foreach"].place(height=40, width=120, y=660, x=500)
        self.buttons["reduce"] = Button(self.frame, text="Aggregate", background="sienna2",
                                        command=lambda: self.create_new_node(ReduceByKey), font=buttonFont)
        self.buttons["reduce"].place(height=40, width=120, y=660, x=650)
        self.buttons["filter"] = Button(self.frame, text="Filter", background="firebrick2",
                                        command=lambda: self.create_new_node(Filter), font=buttonFont)
        self.buttons["filter"].place(height=40, width=120, y=660, x=800)
        self.buttons["output"] = Button(self.frame, text="Output", background="SeaGreen3",
                                        command=lambda: self.create_new_node(OutputNode), font=buttonFont)
        self.buttons["output"].place(height=40, width=120, y=740, x=725)
        self.buttons["model"] = Button(self.frame, text="Model", background="MediumPurple1",
                                           command=lambda: self.create_new_node(Model), font=buttonFont)
        self.buttons["model"].place(height=40, width=120, y=740, x=425)
        self.buttons["evaluate"] = Button(self.frame, text="Evaluate", background="medium orchid",
                                          command=lambda: self.create_new_node(Evaluator), font=buttonFont)
        self.buttons["evaluate"].place(height=40, width=120, y=740, x=575)
        self.buttons["calculate"] = Button(self.frame, text="Calculate path", background="PaleGreen1",
                                           command=self.createDAG, font=buttonFont)
        self.buttons["calculate"].place(height=40, width=160, y=660, x=1000)
        self.buttons["options"] = Button(self.frame, text="Options", background="snow3",
                                         command=self.show_options_dialog, font=buttonFont)
        self.buttons["options"].place(height=40, width=120, y=710, x=1000)
        self.buttons["code"] = Button(self.frame, text="Show code", background="snow3",
                                         command=self.show_code_dialog, font=buttonFont)
        self.buttons["code"].place(height=40, width=140, y=760, x=1000)
        # self.buttons["delete"] = Button(self.frame, text="Delete", highlightbackground="green",
        #                                 command=self.delete_node)
        # self.buttons["delete"].place(height=40, width=120, y=740, x=1150)

    def bind_keys(self):
        self.canvas.bind("<Button-1>", self.select_shape)
        self.canvas.bind("<B1-Motion>", self.dragShape)

    def delete_node(self):
        deleted_edges = self.selectedShape.delete()
        self.nodes.remove(self.selectedShape)
        for edge in deleted_edges:
            self.lines.remove(edge)
        del self.selectedShape
        self.selectedShape = 0

    def show_options_dialog(self):
        if self.selectedShape != 0:
            self.selectedShape.show_options()

    def show_code_dialog(self):
        if self.selectedShape != 0:
            self.selectedShape.show_code()

    def create_new_node(self, type):
        if type == Evaluator:
            new_node = type(self.canvas, self)
        else:
            new_node = type(self.canvas)
            self.lines.append(Connection(self.selectedShape, new_node, self.canvas))
        self.nodes.append(new_node)
        self.selectedShape = new_node

    def select_shape(self, event):
        widget = event.widget
        xc = widget.canvasx(event.x)
        yc = widget.canvasx(event.y)
        try:
            select = self.canvas.find_closest(xc, yc)[0]
            for node in self.nodes:
                if node.is_selected(select):
                    self.selectedShape = node
        except IndexError:
            pass
        if isinstance(self.selectedShape, InputFile):
            self.previous_selected = self.selectedShape
            self.disableButtons(["output", "calculate", "input"])
            self.enableButtons(["foreach", "reduce", "filter", "options"])
        elif isinstance(self.selectedShape, OutputNode):
            self.disableButtons(["input", "filter", "output", "options", "foreach", "reduce"])
            self.enableButtons(["calculate"])
        elif isinstance(self.selectedShape, ReduceByKey):
            self.disableButtons(["calculate"])
            self.enableButtons(["input", "filter", "output", "options", "foreach", "reduce", "model", "code"])
        elif isinstance(self.selectedShape, int):
            self.enableButtons(self.buttons.keys())
        else:
            self.disableButtons(["calculate", "code"])
            self.enableButtons(["input", "filter", "output", "options", "foreach", "reduce", "model"])

    def dragShape(self, event):
        if isinstance(self.selectedShape, Node):
            self.selectedShape.drag(event)
        pass

    def createInputNode(self):
        self.inputNode = InputFile(self.canvas)
        self.sc.addFile(self.inputNode.directory)

        print("File has been added")
        if self.inputNode.header_sep == None:
            self.rdd = self.sc.textFile("file://" + SparkFiles.get(self.inputNode.fileName))
            df = self.spark.createDataFrame(self.rdd, StringType())
        else:
            df = self.spark.read.csv(SparkFiles.get(self.inputNode.fileName), header=True,
                                        sep=self.inputNode.header_sep)
            while self.inputNode.data_tree is None:
                try:
                    self.inputNode.data_tree = Tree(["row", df.columns])
                    print(self.inputNode.data_tree.contents)
                except:
                    mb.showinfo("Tree construction failed",
                                "Unable to derive the structure specified, please try again.")
            self.rdd = df.rdd
        self.inputNode.df = df

        self.nodes.append(self.inputNode)
        self.inputNode.rdd = self.rdd
        self.selectedShape = self.inputNode
        print("RDD created: ", self.rdd.take(10))
        self.inputFile = self.inputNode.fileName
        self.levels = self.inputNode.data_tree.contents
        self.disableButtons(["input", "filter", "output", "calculate"])

    def disableButtons(self, button_list):
        for button_key in button_list:
            self.buttons[button_key]["state"] = DISABLED

    def enableButtons(self, button_list):
        for button_key in button_list:
            self.buttons[button_key]["state"] = ACTIVE

    def createDAG(self):
        self.selectedShape.get_rdd()

if __name__ == "__main__":
    root = Tk()
    gui = GUI(root)
    root.mainloop()


import cv2
import numpy as np
import matplotlib.pyplot as plt

# plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # 用来正常显示中文标签 MAC下
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

img = cv2.imread('./img/lenna.png', 0)
print(img.shape)

# 获取图像高度、宽度
rows, cols = img.shape[:]
print(rows, cols)

# 图像二维像素转换为一维
data = img.reshape((rows * cols, 1))
data = np.float32(data)
print(data)

# 停止条件 TERM_CRITERIA_EPS满足精度条件停止、TERM_CRITERIA_MAX_ITER 迭代次数超过最大阈值停止
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

flags = cv2.KMEANS_RANDOM_CENTERS

comt, labels, centers = cv2.kmeans(data, 4, None, criteria, 10, flags)
print(comt, labels, centers)

dst = labels.reshape((img.shape[0], img.shape[1]))

# 显示图像
titles = [u'原始图像', u'聚类图像']
images = [img, dst]
for i in range(2):
    plt.subplot(1, 2, i + 1), plt.imshow(images[i], 'gray'),
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()


import numpy as np
import matplotlib.pyplot as plt
T = 1
dt = 0.02
x0 = np.array([2.,3.,5.])
x1 = np.array([5.,5.,7.])
dim = x0.size
N = int(T/dt)+1 #number of ticks
coeff = np.empty((4,dim))*np.nan
A = np.array([[1, 0, 0, 0],
              [1, T, T**2, T**3],
              [0, 1, 0, 0],
              [0, 1, 2*T, 3*T**2]])
for s in range(dim):
    b = np.array([x0[s], x1[s], 0, 0]).transpose()
    # solving poly_coeff = A^-1*b
    coeff[:,s] = np.dot(np.linalg.inv(A), b)

x = np.empty((dim,N))*np.nan
dx = np.empty((dim,N))*np.nan
ddx = np.empty((dim,N))*np.nan
for i in range(dim):
    for j in range(N):
        x[i,j]=coeff[0,i]+dt*j*coeff[1,i]+(dt*j)**2*coeff[2,i]+(dt*j)**3*coeff[3,i]
        dx[i,j]=coeff[1,i]+2*dt*j*coeff[2,i]+3*(dt*j)**2*coeff[3,i]
        ddx[i,j]=2*coeff[2,i]+6*dt*j*coeff[3,i]

print(x)
plt.plot(range(N),x[0,:])
""" plt.plot(range(N),dx[0,:])
plt.plot(range(N),ddx[0,:]) """
plt.show()

""" b = np.load('talos_walking_traj_lipm.npz')
print(b['foot_steps']) """


import cv2

'''
RGB to Gray
'''
im = cv2.imread(r"me.jpg")
cv2.imshow("BGR", im)
# 使用cvtColor进行颜色空间变化 cv2.COLOR_BGR2GRAY 代表BGR to gray
img_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", img_gray)
cv2.waitKey()
cv2.destroyAllWindows()

'''
BGR to RGB
'''
# 使用cvtColor进行颜色空间变化 cv2.COLOR_BGR2RGB 代表BGR to RGB
im_rgb = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
# 当图像数据为3通道时，imshow函数认为数据是BGR的
# 使用imshow显示RGB数据，会发现图片显示颜色畸变
cv2.imshow("RGB", im_rgb)
cv2.waitKey()
cv2.destroyAllWindows()

'''
BGR to HSV
'''
# 使用cvtColor进行颜色空间变化 cv2.COLOR_BGR2HSV 代表BGR to HSV
im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
# 当图像数据为3通道时，imshow函数认为数据是BGR的
# 使用imshow显示HSV数据，会将HSV分量强行当做BGR进行显示
cv2.imshow("HSV", im_hsv)
cv2.waitKey()
cv2.destroyAllWindows()


from kivymd.uix.screen import MDScreen
from kivy.storage.jsonstore import JsonStore
from kivymd.uix.menu.menu import MDDropdownMenu
from kivy.network.urlrequest import UrlRequest

estados_opcoes = []
pais_opcoes = []
banco_estados = JsonStore('banco/estados.json')
banco_pais = JsonStore('banco/pais.json')
banco_cidades = JsonStore('banco/cidades.json')

class CidadaoCriarScreen(MDScreen):
    """
    Example Screen
    """

    def data_pais(req, result):
        for pais in result:
            banco_pais.put(pais['nome'])

    def data_estado(req, result):
        for estado in result:
            banco_estados.put(estado['nome'], id=estado['id'])

    #url = UrlRequest('https://servicodados.ibge.gov.br/api/v1/localidades/estados', on_success=data_estado)

    nomes = banco_estados.keys()
    paises = banco_pais.keys()
    estados = banco_estados.keys()

    def abrir_bairro(self):

        menu_item = [
            {
                'text': cidades[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{cidades[index]}' : self.cidade_filtro(x)
            } for index in range(len(cidades))
        ]
        menu = MDDropdownMenu(
            caller=self.ids.cidade,
            items= menu_item,
            width_mult=4
        )
        menu.open()

    def cidade_filtro(self, cidade):
        self.cidade = cidade
        self.ids.cidade.text = cidade

    def abrir_menu_cidade(self):
        cidades = banco_cidades.keys()
        menu_item = [
            {
                'text': cidades[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{cidades[index]}' : self.cidade_filtro(x)
            } for index in range(len(cidades))
        ]
        menu = MDDropdownMenu(
            caller=self.ids.cidade,
            items= menu_item,
            width_mult=4
        )
        menu.open()

    def estado_filtro(self, estado):
        def data_cidade(req, result):
            for cidade in result:
                banco_cidades.put(cidade['nome'], id=cidade['id'])
        self.estado = estado
        self.ids.estado.text = str(self.estado)
        estado_data = banco_estados.get(str(self.estado))
        estado_selecionado = estado_data['id']
        url = UrlRequest(f'https://servicodados.ibge.gov.br/api/v1/localidades/estados/${estado_selecionado}/municipios', on_success=data_cidade)

    def abrir_menu_estado(self):
        menu_item = [
            {
                'text': self.nomes[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{self.nomes[index]}' : self.estado_filtro(x)
            } for index in range(len(self.nomes))
        ]
        menu = MDDropdownMenu(
            caller=self.ids.estado,
            items= menu_item,
            width_mult=4
        )
        menu.open()
    def pais_filtro(self, pais):
        self.pais = pais
        self.ids.nacionalidade.text = str(self.pais)
    def abrir_paises(self):
        menu_item = [
            {
                'text': self.paises[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{self.paises[index]}' : self.pais_filtro(x)
            } for index in range(len(self.paises))
        ]
        menu = MDDropdownMenu(
            caller=self.ids.nacionalidade,
            items=menu_item,
            width_mult=4
        )
        menu.open()

    dados = JsonStore('hello.json')
    sexo = None
    estado_civil = None
    cor = None
    escolaridade = None

    def sexo_filtro(self, sexo):
        self.sexo = sexo
        self.ids.sexo.text = str(sexo)
    def sexo(self):
        opcoes = ['heterossexual', 'homossexual', 'bissexual','assexual', 'masculino', 'feminino']
        menu_items = [{
                'text': opcoes[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{opcoes[index]}' : self.sexo_filtro(x)
            } for index in range(len(opcoes))]
        self.menu = MDDropdownMenu(
            caller=self.ids.sexo,
            items= menu_items,
            width_mult=4
        )
        self.menu.open()

    def estado_civil_filtro(self, estado_civil):
        self.estado_civil = estado_civil
        self.ids.estado_civil.text = str(estado_civil)
    def estado_civil(self):
        opcoes = ['Amasiada(o)', 'Casada(o)', 'Divorciada(o)', 'Desconhecido',
        'Separada(o)','Solteira(o)','Viuva(o)']
        menu_items = [
            {
                'text': opcoes[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{opcoes[index]}' : self.estado_civil_filtro(x)
            } for index in range(len(opcoes))
            ]
        self.menu = MDDropdownMenu(
            caller=self.ids.estado_civil,
            items= menu_items,
            width_mult=4
        )
        self.menu.open()

    def cor_filtro(self, cor):
        self.cor = cor
        self.ids.cor.text = str(cor)
    def cor(self):
        opcoes = ['Amarela', 'Branca', 'Indígena','Parda', 'Preta']
        menu_items = [{
                'text': opcoes[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{opcoes[index]}' : self.cor_filtro(x)
            } for index in range(len(opcoes))]
        self.menu = MDDropdownMenu(
            caller=self.ids.cor,
            items= menu_items,
            width_mult=4
        )
        self.menu.open()

    def escolaridade_filtro(self, escolaridade):
        self.escolaridade = escolaridade
        self.ids.escolaridade.text = str(escolaridade)
    def escolaridade(self):
        opcoes = ['1º Ensino fundamental', '1º Ensino médio', '2º Ensino fundamental', '2º Ensino médio',
        '3º Ensino fundamental','3º Ensino médio','4º Ensino fundamental', '5º Ensino fundamental',
        '6º Ensino fundamental', '7º Ensino fundamental','8º Ensino fundamental','9º Ensino fundamental',
        'APAE','Creche','Desconhecido','EJA','Ensino médio completo','Não estuda','Não se aplica',
        'Pós-graduado','Pré-escola','Superior','Superior incompleto','Supletivo','']
        menu_items = [
            {
                'text': opcoes[index],
                "viewclass": "OneLineListItem",
                'on_release': lambda x = f'{opcoes[index]}' : self.escolaridade_filtro(x)
            } for index in range(len(opcoes))
            ]
        self.menu = MDDropdownMenu(
            caller=self.ids.escolaridade,
            items= menu_items,
            width_mult=4
        )
        self.menu.open()

    def inserir_dados(self):
        try:
            nome = self.ids.nome.text
            apelido = self.ids.apelido.text
            cpf = self.ids.cpf.text
            rg = self.ids.rg.text
            certidao_nascimento = self.ids.certidao_nascimento.text
            rne = self.ids.rne.text
            fone_i = self.ids.fone_i.text
            fone_ii = self.ids.fone_ii.text
            sexo = self.sexo
            estado_civil = self.ids.estado_civil.text
            nacionalidade = self.ids.nacionalidade.text
            escolaridade = self.ids.escolaridade.text
            estado = self.ids.estado.text
            cidade = self.ids.cidade.text
            bairro = self.ids.bairro.text
            logradouro = self.ids.logradouro.text
            cep = self.ids.cep.text
            cor  = self.ids.cor.text
            complemento = self.ids.complemento.text

            if nome == None and apelido == None and cpf == None and rg == None and certidao_nascimento == None and rne == None and escolaridade == None and fone_i == None and fone_ii == None and sexo == None and estado_civil == None and nacionalidade == None and escolaridade == None and estado == None and cidade == None and bairro == None and logradouro == None and cep == None and cor == None:
                return False

            self.dados.put(nome, nome=nome,apelido=apelido,cpf=cpf,rg=rg,
            certidao_nascimento=certidao_nascimento,rne=rne,estado_civil=estado_civil,
            fone_i=fone_i,fone_ii=fone_ii,sexo=sexo, estado=estado,cidade=cidade,
            bairro=bairro,logradouro=logradouro, cep=cep,cor=cor,complemento=complemento,
            nacionalidade=nacionalidade,escolaridade=escolaridade)

            if self.dados.exists(cpf):
                return True
        except:
            self.ids.criar.text = 'Existe algum campo errado'
            return True


from selenium import webdriver
import math
import os

url = 'http://suninjuly.github.io/file_input.html'

browser = webdriver.Chrome()
browser.get(url)

element = browser.find_element_by_tag_name('[placeholder="Enter first name"]')
element.send_keys('FirstName')

element = browser.find_element_by_tag_name('[placeholder="Enter last name"]')
element.send_keys('LastName')

element = browser.find_element_by_tag_name('[placeholder="Enter email"]')
element.send_keys('Email')

current_dir = os.path.abspath(os.path.dirname(__file__))    # получаем путь к директории текущего исполняемого файла
file_path = os.path.join(current_dir, 'file.txt')           # добавляем к этому пути имя файла
element = browser.find_element_by_tag_name('[type="file"]')
element.send_keys(file_path)

button = browser.find_element_by_css_selector('button.btn')
button.click()

browser.quit()


"""
[TERMINAL WIDGET ESP32 EXAMPLE] =====================================================================================

Environment prepare:
In your Blynk App project:
  - add "Terminal" widget,
  - bind it to Virtual Pin V2,
  - add input line option in widget settings
  - Run the App (green triangle in the upper right corner).
  - define your auth token for current example
  - define SSID and WiFi password that will be used by ESP32 board
  - run current example

This started program will call and execute event handler "write_virtual_pin_handler" if new
event comes from terminal app widget.
In App Terminal widget you can type commands.
'help' - info about available commnds
'logo' - prints blynk library ascii logo
'version' - prints blynk library version
'sysinfo' - prints board system info
'ls' - list target board dir. Example: 'ls /lib'.
       root dir will be listed if no arguments provided

For any other terminal inputs will be printed error info that provided command is not supported.
=====================================================================================================================
Additional info about blynk you can find by examining such resources:

    Downloads, docs, tutorials:     https://blynk.io
    Sketch generator:               http://examples.blynk.cc
    Blynk community:                http://community.blynk.cc
    Social networks:                http://www.fb.com/blynkapp
                                    http://twitter.com/blynk_app
=====================================================================================================================
"""
import blynklib_mp as blynklib
import network
import uos
import utime as time

WIFI_SSID = 'YourWifiSSID'
WIFI_PASS = 'YourWifiPassword'
BLYNK_AUTH = 'YourAuthToken'

print("Connecting to WiFi network '{}'".format(WIFI_SSID))
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASS)
while not wifi.isconnected():
    time.sleep(1)
    print('WiFi connect retry ...')
print('WiFi IP:', wifi.ifconfig()[0])

print("Connecting to Blynk server...")
blynk = blynklib.Blynk(BLYNK_AUTH)

CMD_LIST = ['logo', 'version', 'sysinfo', 'ls']

@blynk.handle_event('write V2')
def write_handler(pin, values):
    if values:
        in_args = values[0].split(' ')
        cmd = in_args[0]
        cmd_args = in_args[1:]

        if cmd == 'help':
            output = ' '.join(CMD_LIST)
        elif cmd == CMD_LIST[0]:
            output = blynklib.LOGO
        elif cmd == CMD_LIST[1]:
            output = blynklib.__version__
        elif cmd == CMD_LIST[2]:
            output = uos.uname()
        elif cmd == CMD_LIST[3]:
            arg = cmd_args[0] if cmd_args else ''
            output = uos.listdir(arg)
        else:
            output = "[ERR]: Not supported command '{}'".format(values[0])

        blynk.virtual_write(pin, output)
        blynk.virtual_write(pin, '\n')

while True:
    blynk.run()


import cv2

src = cv2.imread('data/images/threshold.png', 0)

# 구분하기 위한 값 설정
thresh = 0
#배경이 검은색일때 검은색에 가까운것들을 잘 안보이게 되므로

# 위에서 설정한 값보다 큰 것들은, 모두 255로 색으로 변경하겠다는 것
maxValue = 255

cv2.imshow('Original', src)

# 2번째 파라미터는 구분하기 위한 색(배경색)을 설정
# 두번째 리턴값이 dst변수에 들어가는 것이 적용된 이미지(numpy)
th, dst = cv2.threshold(src, thresh, maxValue, cv2.THRESH_BINARY )

cv2.imshow('Thresholded Image', dst)

cv2.waitKey()
cv2.destroyAllWindows()


import numpy as np
import pandas as pd
from scipy.io import loadmat
from scipy.stats import skew, kurtosis, kendalltau
from itertools import combinations, groupby
from scipy.ndimage.filters import gaussian_filter as gf

def autocorrelation_tau(detrended_data, param_dict):
    '''
    param_dict requires
        repeats (or number of places)
        T (total time period)
        BT (set to zero)
        windowSize (for the calculating )
        lag_tau '''
    AC_results = np.zeros((param_dict['repeats'], param_dict['T']+param_dict['BT']))
#     wd = param_dict['windowSize']//2
    wd = round(param_dict['windowSize']/2)
    for i in (range(wd,param_dict['T']+param_dict['BT']-(wd))):
        if param_dict['windowSize']%2==0:
            subtract = 1
        else:
            subtract = 2
        data_window = detrended_data[:,( i-(wd)):(i+(wd))]
        x = data_window[:, :-1] -np.transpose((np.nanmean(data_window[:,:-param_dict['lag_tau']],
                                                 axis = 1),)*(param_dict['windowSize']-subtract
                                                                ))
        x_tau = data_window[:,1:] -  np.transpose((np.nanmean(data_window[:,param_dict['lag_tau']:],
                                                        axis = 1),)*(param_dict['windowSize']-subtract
                                                                ))
        numerator = np.mean(x*x_tau, axis = 1)
        denominator = np.std(x,axis =1)*np.std(x_tau, axis = 1)
        xtest_autocorr=numerator/denominator
        # below is a different method (using inbuilt Pandas series function) but takes longer
    #     xtest_autocorr = pd.DataFrame(xtest.T).apply(lambda x:  pd.Series(x).autocorr(lag = 1)).values
        AC_results[:,i] = xtest_autocorr
    return AC_results

def populationEstimation(pop_2015, years, rate):
    sign = lambda x: (1, -1)[x<0]
    a_de_ppreciation = years - 2015
    growth = [pop_2015*(1+sign(value)*rate)**abs(value) for value in a_de_ppreciation ]
    return growth

def no_detrending(df):
    return df

def realisation_detrending(df):
    remove_mean_space = df.sub(df.mean(axis = 1), axis = 'rows')
    return remove_mean_space

def decay_time(AC):
    denom = np.log(np.minimum(np.maximum(AC, 0), 1))
    return -1/denom

def pandas_zscore(dataframe):
    rolling_mean = dataframe.expanding().mean()
    rolling_std = dataframe.expanding().std(ddof=0)
    normalise_stats = (dataframe - rolling_mean)/rolling_std
    return normalise_stats

def twosigma(standardised):
    n = len(standardised)
    running_average = np.zeros(n)
    running_std= np.zeros(n)
    for j in range(n):
        running_average[j] = np.nanmean(standardised[1:j+1])
        running_std[j] = np.nanstd(standardised[1:j+1])

    return running_std, running_average

def statistics_on_window(dataframe, window_size, detrend_function, window_detrend = None, std = None, filtering_size = 4, center = True):
#     print(detrend_function)
    if detrend_function == linear_window_detrending:

        detrended_data = detrend_function(df = dataframe,
                                          BW = filtering_size ,
                             wind = str(window_detrend),
                                          std_val=std)
    elif detrend_function == gf:
        smooth_data = np.zeros((dataframe.shape[0], dataframe.shape[1]))
        for index_col, col in enumerate(dataframe.columns):
            data = dataframe[col].values
            smooth = gf(data, sigma=std, mode='reflect')
            smooth_data[:, index_col] = smooth
        detrended_data = dataframe - pd.DataFrame(data = smooth_data)
    else:
        detrended_data = detrend_function(dataframe)
    statistics_window ={}
    statistics_window['Variance'] = detrended_data.rolling(center = center,
                             window = window_size,
                             win_type=None,
                             min_periods=1
                            ).var()
    statistics_window['Mean'] = detrended_data.rolling(center = center,
                                 window = window_size,
                                 win_type=None,
                                 min_periods=1
                                ).mean()
    statistics_window['First difference'] =(detrended_data.rolling(center = center,
                                 window = window_size,
                                 win_type=None,
                                 min_periods=1
                                ).var()).diff(axis = 0)
    statistics_window['Index of dispersion'] = detrended_data.rolling(center = center,
                             window = window_size,
                             win_type=None,
                             min_periods=1
                            ).var()/dataframe

    statistics_window['CV'] = detrended_data.rolling(center = center,
                             window = window_size,
                             win_type=None,
                             min_periods=1
                            ).std()/dataframe

    statistics_window['Kurtosis'] = detrended_data.rolling(center = center,
                                 window = window_size,
                                 win_type=None,
                                 min_periods=1
                                ).kurt()
    statistics_window['Skewness'] = detrended_data.rolling(center = center,
                                 window = window_size,
                                 win_type=None,
                                 min_periods=1
                                ).skew()

    ### autocorrelation
    matrix_time_place = detrended_data.to_numpy()
    matrix_place_time = matrix_time_place.T
    ac_tau_1 = autocorrelation_tau(matrix_place_time, param_dict={'repeats': len(dataframe.columns),
                                                             'T': len(dataframe.index),
                                                             'BT': 0,
                                                             'windowSize': window_size,
                                                             'lag_tau': 1})

    statistics_window['AC(1)'] =pd.DataFrame(ac_tau_1.T, index=dataframe.index, columns= dataframe.columns)
    statistics_window['Decay Time'] = pd.DataFrame(decay_time(ac_tau_1).T,
                                                   index=dataframe.index,
                                                   columns= dataframe.columns)
    statistics_window['CV'][statistics_window['CV']==np.inf] = np.nan

    normalised_stats = {}
    for stat_df in list(statistics_window.keys()):
        stat_dict_df = statistics_window[stat_df]
        zscore_df = pandas_zscore(stat_dict_df)
        normalised_stats[stat_df] = zscore_df
    return statistics_window, normalised_stats

def linear_window_detrending(df, BW ,center = True,
                             wind = None, std_val=None, axis = 0):
    linear_mean = df.rolling(center = center,
                                 window = BW,
                                 win_type=wind,
                             axis = axis,
                                 min_periods=1
                                ).mean(std = std_val)
    remove_mean_window = df - linear_mean
    return remove_mean_window


#!/usr/bin/python3
# -*- coding: utf8 -*-

import tkinter as tk

# Instance
import tk_gui_tools.manage_widget as manage_widget

# Heritage
from tk_gui_tools.command_gui.mouse import Mouse
from tk_gui_tools.command_gui.keyboard import Keyboard
from tk_gui_tools.command_gui.command import CommandGUI
from tk_gui_tools.tool.scroolbar import ScrollBar

class Base(Mouse, Keyboard, CommandGUI, ScrollBar):
    """
    Base is a pre-filled template to inherit and use command functionality
    """

    def __init__(self, window):

        # width screen
        self.width = window.winfo_screenwidth()
        # height screen
        self.height = window.winfo_screenheight()

        # Create the Canvas
        self.canvas = tk.Canvas(
            window,
            height=self.height,
            width=self.width,
            bg="grey",
            scrollregion=(0, 0, self.width, self.height),
        )

        # Instance
        self.window = window
        self.manage = manage_widget.ManageWidget(self.canvas)

        # Init ScrollBar Héritage
        ScrollBar.__init__(self)

        # Init Keyboard and Mouse Héritage
        Keyboard.__init__(self)
        Mouse.__init__(self)

        self.canvas.pack(fill=tk.BOTH, side=tk.LEFT, expand=tk.TRUE)

    def update(self):
        """
        Update the template
        """

        self.canvas.update_idletasks()


import os, sys
import math
import time

from . import robot

def maze():
    """Track the left hand side and *reduce* power (so we can run at full)

    * Track the differential of the left-hand side, not the left-right difference
    * To turn right, reduce the right power so we can usually run at full
    """
    FRONT_MM_OFFSET = 10 # the front sensor is off by this number of mm
    dleft_threshold_mm = dright_threshold_mm = 3 ## if we've moved by this much, go the other way
    base_power = .5
    power_increment = base_power * 0.2
    left_power = right_power = base_power
    left_increment = right_increment = 0
    time_increment = 0.1

    t1 = time.time() + 10
    with robot.Robot() as robbie:
        previous_left_mm = left_mm = robbie.get_left_mm()
        previous_right_mm = right_mm = robbie.get_right_mm()
        while (robbie.get_front_mm() - FRONT_MM_OFFSET) > 15:
            robbie.forwards(left_power + left_increment, right_power + right_increment)
            front_mm = robbie.get_front_mm()
            print("Left: %4.2f; Right: %4.2f; Front: %4.2f" % (left_mm, right_mm, front_mm))
            if front_mm < 400:
                return
            left_mm = robbie.get_left_mm()
            right_mm = robbie.get_right_mm()
            dleft_mm = previous_left_mm - left_mm
            dright_mm = previous_right_mm - right_mm
            if dleft_mm > dleft_threshold_mm:
                print("Moved left by %smm; About to move right" % dleft_mm)
                left_increment = +power_increment
                right_increment = -power_increment
            #
            # Better to let it be guided from the left; otherwise
            # there's a lot of jinking
            #
            #~ elif dright_mm > dright_threshold_mm:
                #~ print("About to move left")
                #~ right_increment = +power_increment
                #~ left_increment = -power_increment
            else:
                left_increment = right_increment = 0
            previous_left_mm = left_mm
            previous_right_mm = right_mm
            time.sleep(time_increment)

def start_stop():
    with robot.Robot() as robbie:
        robbie.forwards(.5, .5)
        print()
        time.sleep(0.5)
        robbie.stop()
        print()
        print("Front:", robbie.get_front_mm())
        print("Front Raw:", robbie.get_front_mm(use_raw=True))
        time.sleep(1)
        print()
        print("Front:", robbie.get_front_mm())
        print("Front Raw:", robbie.get_front_mm(use_raw=True))
        time.sleep(5)
        print()
        print("Front:", robbie.get_front_mm())
        print("Front Raw:", robbie.get_front_mm(use_raw=True))

if __name__ == '__main__':
    maze(*sys.argv[1:])


#MaBe
#Aula de listas parte 2

#Cria as listas
maria = ['Maria', 18]
joao = ['João', 18]
luan = ['Luan', 17]
pedro = ['Pedro', 16]
pessoas = []

#Cria uma ligação entre duas listas
#Dessa forma, toda alteração que eu fizer em maria, também será feita em pessoas e vice versa
#pessoas = maria

#Faz uma cópia de uma lista
#Dessa forma, as listas são independentes. Uma não interfere na outra.
#pessoas = maria[:]

#Coloca todas essas listas dentro de outra
pessoas = [maria[:], joao[:], luan[:], pedro[:]]
print(pessoas)

#Coloca as listas dentro de outra - modo 2
pessoas2 = []
pessoas2.append(maria[:])
pessoas2.append(joao[:])
pessoas2.append(luan[:])
pessoas2.append(pedro[:])
print(pessoas2, '\n')

#acessando os elementos das listas dentro de uma outra lista
#Elemento 1 da lista 0. Vai exibir 18.
#print(pessoas[0][1])

#acessando as sublistas
print(pessoas[0])
print(pessoas[1])
print(pessoas[2])
print(pessoas[3], '\n')

#exemplo de uso com estrutura de repetição
for p in pessoas:
    print(f'{p[0]} tem {p[1]} anos de idade!')

print()
#outro exemplo de uso com repetição
#interação com usuário
galera = []
dados = []
for d in range(0, 5):
    dados.append(input('Nome: '))
    dados.append(int(input('Idade: ')))
    galera.append(dados[:])
    dados = []
print('Dados coletados.')
print(galera)

tmai = 0
tmen = 0
tido = 0

for g in galera:
    if g[1] < 18:
        print(f'{g[0]} é menor de idade')
        tmen += 1
    elif g[1] >= 18 and g[1] < 60:
        print(f'{g[0]} é maior de idade')
        tmai += 1
    elif g[1] >= 60:
        print(f'{g[0]} é idoso')
        tido += 1

print(f'Total de {tmen} menores de idade.')
print(f'Total de {tmai} maiores de idade.')
print(f'Total de {tido} idosos.')


#11.2.1 使用pack()方法的布局
# 例11-5 使用pack()方法的anchor参数设置组件的布局.py
from tkinter import *
win=Tk()
label1 = Label(win,text="标签标题",fg="white",bg="blue")
label1.grid( )
label1.pack(anchor=NW,padx=5)
#组件在窗口中位置,锚点为西北NW，组件外部预留空白宽为5
label2 = Label(win)
label2.config(text="标签内容",fg="white",bg="grey") #配置文本属性
label2.pack(expand=YES,fill=BOTH,padx=5)
#组件可拉伸，X和Y方向填充，组件外部预留空白宽为5
btn= Button()
btn['text']="click" #配置文本属性的另一种方法
btn.pack()
win.title("Example11-5")    #title()方法
win.geometry("300x200")    #geometry()方法
win.mainloop()

11.2.1 使用pack()方法的布局（例11-5 使用pack()方法的anchor参数设置组件的布局）.py


import argparse
from snake_engine.pygame_screen import run_display
from AI.q_learning import run_q_learn

def run(args):
    should_learn = True if args.learn is not None else False
    if args.nodisplay:
        run_q_learn(args.learn, should_learn)
    else:
        run_display(args.learn, should_learn)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Python Q-Learning Agent that learns to play the game Snake")
    parser.add_argument('--learn', dest="learn", type=int, help="The number of episodes (games) for the Snake to learn from (default 100000). If not specified will use prelearnt Q-table instead.", default=None)
    parser.add_argument('--no-display', dest="nodisplay", action="store_true", help="Do not use Pygame to display the final Snake gameplay.", default=False)
    args = parser.parse_args()
    print(args)
    run(args)


# quiz_data.py

глаголы = {
    "Accept": "Принимать",
    "Achieve": "Достигать",
    "Act": "Действовать",
    "Add": "Добавлять",
    "Admire": "Восхищаться",
    "Agree": "Соглашаться",
    "Aim": "Целиться",
    "Allow": "Позволять",
    "Announce": "Объявлять",
    "Answer": "Отвечать",
    "Appear": "Появляться",
    "Apply": "Применять",
    "Approve": "Одобрять",
    "Argue": "Спорить",
    "Arrange": "Устраивать",
    "Ask": "Спрашивать",
    "Attack": "Атаковать",
    "Avoid": "Избегать",
    "Bake": "Выпекать",
    "Base": "Основывать",
    "Become": "Становиться",
    "Begin": "Начинать",
    "Believe": "Верить",
    "Bend": "Гнуть",
    "Bet": "Делать ставку",
    "Blame": "Винить",
    "Boil": "Кипятить",
    "Break": "Ломать",
    "Build": "Строить",
    "Burn": "Сжигать",
    "Buy": "Покупать",
    "Call": "Звонить",
    "Carry": "Носить",
    "Catch": "Ловить",
    "Change": "Изменять",
    "Choose": "Выбирать",
    "Clean": "Чистить",
    "Close": "Закрывать",
    "Collect": "Собирать",
    "Come": "Приходить",
    "Compare": "Сравнивать",
    "Complicate": "Усложнять",
    "Consider": "Считать",
    "Cook": "Готовить",
    "Copy": "Копировать",
    "Count": "Считать",
    "Create": "Создавать",
    "Cry": "Плакать",
    "Dance": "Танцевать",
    "Decide": "Решать",
    "Declare": "Объявлять",
    "Decorate": "Украшать",
    "Defend": "Защищать",
    "Delay": "Задерживать",
    "Demand": "Требовать",
    "Depend": "Зависеть",
    "Deserve": "Заслуживать",
    "Destroy": "Уничтожать",
    "Develop": "Развивать",
    "Disappear": "Исчезать",
    "Discuss": "Обсуждать",
    "Divide": "Делить",
    "Do": "Делать(процесс)",
    "Draw": "Рисовать",
    "Dream": "Мечтать",
    "Drink": "Пить",
    "Drive": "Водить машину",
    "Drop": "Падать",
    "Earn": "Зарабатывать",
    "Eat": "Есть",
    "Employ": "Нанимать",
    "Enjoy": "Наслаждаться",
    "Explain": "Объяснять",
    "Fail": "Проваливаться",
    "Fall": "Падать",
    "Feel": "Чувствовать",
    "Fight": "Бороться",
    "Find": "Находить",
    "Finish": "Заканчивать",
    "Fly": "Летать",
    "Follow": "Следовать",
    "Forget": "Забывать",
    "Forgive": "Прощать",
    "Freeze": "Замерзать",
    "Get": "Получать",
    "Give": "Давать",
    "Go": "Идти",
    "Grow": "Расти",
    "Happen": "Происходить",
    "Hate": "Ненавидеть",
    "Have": "Иметь",
    "Help": "Помогать",
    "Hide": "Прятать",
    "Hit": "Бить",
    "Hold": "Держать",
    "Hope": "Надеяться",
    "Hurt": "Причинять боль",
    "Include": "Включать",
    "Invent": "Изобретать",
    "Invite": "Приглашать",
    "Jump": "Прыгать",
    "Keep": "Сохранять",
    "Kill": "Убивать",
    "Know": "Знать",
    "Laugh": "Смеяться",
    "Learn": "Учиться",
    "Leave": "Уходить",
    "Listen": "Слушать",
    "Live": "Жить",
    "Look": "Смотреть",
    "Lose": "Терять",
    "Love": "Любить",
    "Make": "Делать(объект)",
    "Manage": "Управлять",
    "Marry": "Жениться/выйти замуж",
    "Meet": "Встречать",
    "Miss": "Пропускать",
    "Move": "Двигаться",
    "Need": "Нуждаться",
    "Open": "Открывать",
    "Order": "Заказывать",
    "Paint": "Рисовать",
    "Pay": "Платить",
    "Play": "Играть",
    "Please": "Угождать",
    "Prepare": "Подготавливать",
    "Produce": "Производить",
    "Promise": "Обещать",
    "Protect": "Защищать",
    "Pull": "Тянуть",
    "Push": "Толкать",
    "Put": "Класть",
    "Read": "Читать",
    "Realize": "Понимать",
    "Receive": "Получать",
    "Refuse": "Отказываться",
    "Remember": "Помнить",
    "Rent": "Арендовать",
    "Repeat": "Повторять",
    "Reply": "Отвечать",
    "Respect": "Уважать",
    "Return": "Возвращаться",
    "Ride": "Кататься",
    "Ring": "Звонить",
    "Rise": "Подниматься",
    "Run": "Бежать",
    "Say": "Говорить",
    "See": "Видеть",
    "Sell": "Продавать",
    "Send": "Отправлять",
    "Serve": "Обслуживать",
    "Set": "Устанавливать",
    "Shake": "Трясти",
    "Shout": "Кричать",
    "Sing": "Петь",
    "Sit": "Сидеть",
    "Sleep": "Спать",
    "Smile": "Улыбаться",
    "Smoke": "Курить",
    "Speak": "Говорить",
    "Spend": "Тратить",
    "Stand": "Стоять",
    "Start": "Начинать",
    "Stay": "Оставаться",
    "Stop": "Останавливаться",
    "Study": "Учиться",
    "Succeed": "Достигать успеха",
    "Suffer": "Страдать",
    "Suggest": "Предлагать",
    "Talk": "Говорить",
    "Teach": "Учить",
    "Tell": "Рассказывать",
    "Think": "Думать",
    "Touch": "Касаться",
    "Travel": "Путешествовать",
    "Try": "Пытаться",
    "Understand": "Понимать",
    "Use": "Использовать",
    "Wait": "Ждать",
    "Walk": "Гулять",
    "Want": "Хотеть",
    "Watch": "Смотреть",
    "Win": "Выигрывать",
    "Work": "Работать",
    "Worry": "Беспокоиться",
    "Write": "Писать",
}

глаголы_для_теста = list(глаголы.keys())


"""Escribe un programa que te pida nombres de personas y sus números de teléfono. Para terminar debe pulsar “S” cuando te pida el nombre. El programa termina escribiendo nombres y números de teléfono. Nota: La lista en la que se guardan los nombres y números de teléfono tiene esta estructura[[nombre1, telef1], [nombre2, telef2], [nom3, telef3], etc], es decir, lista de listas.
Dame un nombre: Pepe González
Dame el teléfono: 971971971
Dame un nombre: Macarena Gómez
Dame el teléfono: 971999999
Dame un nombre: Pascual Ribot
Dame el teléfono: 666555444
Dame un nombre: S
Los nombres y teléfonos de la agenda son:
Pepe González: 971971971
Macarena Gómez: 971999999
Pasqual Ribot: 666555444
Sergio Torres Cano
"""

lista=[]
nombre=input("Dame un nombre: ")
telefono=int(input("Dame el teléfono: "))
while nombre != "S":
    dato=[nombre,telefono]
    nombre=input("Dame un nombre (Si desea terminar pulse (S)): ")
    if nombre!="S":
        telefono=int(input("Dame el teléfono: "))
    lista+=[dato]
print ("Los nombres y teléfonos de la agenda son:")
for i in range (len(lista)):
    for j in range(2):
        if j==0:
            print (lista[i][j],end=': ')
        else:
            print (lista[i][j])


import time
import logging

from bottle import request, abort

from ..core.serializer import from_stream_str

def process_heartbeat(data):
    try:
        data = from_stream_str(data)
    except (AttributeError, ValueError):
        import traceback
        traceback.print_exc()
        # Request body is either not available at all, or the JSON is malformed
        abort(400, 'Invalid data')

    logging.info('Received %s data points', len(data))

    for d in data:
        process_data(d)

    logging.info('Finished storing all data points')

    return 'OK'

def service_ok(data):
    signal_lock = data['signal_lock']
    service_lock = data['service_lock']
    bitrate = data['bitrate']
    carousels_count = data['carousel_count']
    carousels_status = data['carousel_status']

    if not signal_lock:
        # This is always OK because if there's no lock, we don't know if the
        # service is alright.
        return True
    if not bitrate:
        return False
    if not service_lock:
        # This is disputable, because transfers could be empty for reasons
        # other than broadcast problem (e.g., broken cache directory, full
        # disk). We'll go with this for now, and change later if necessary.
        return False
    if carousels_count == 0 or not any(carousels_status):
        # This means than either no carousels were detected or none of them
        # were transmitting
        return False
    return True

def process_data(data):
    db = request.db.monitoring

    status = service_ok(data)

    payload = {
        'client_id': data['client_id'],
        'signal_lock': data['signal_lock'],
        'service_lock': data['service_lock'],
        'signal_strength': data['signal_strength'],
        'bitrate': data['bitrate'],
        'snr': data['snr'],
        'service_ok': status,
        'tuner_vendor': data['tuner_vendor'],
        'tuner_model': data['tuner_model'],
        'tuner_preset': data['tuner_preset'],
        'carousels_count': data['carousel_count'],
        'carousels_status': data['carousel_status'],
        'timestamp': data['timestamp'],
        'reported': time.time(),
    }

    qry = db.Insert('stats', cols=payload.keys())
    db.execute(qry, payload)
    return status


from bs4 import BeautifulSoup as beauty
import cloudscraper

# scraper = cloudscraper.create_scraper(delay=10, browser='chrome',debug=True)
scraper = cloudscraper.create_scraper(delay=10, browser='chrome')
url = "https://www.fiverr.com/categories/online-marketing"

info = scraper.get(url).text
# print("0 ===============")
# print(info)
soup = beauty(info, "html.parser")
# print("1 ===============")
# print(soup)
soup = soup.find_all('a', 'item-name')
print("2 ===============")
print(soup)

for data in soup:
    sub_url = 'https://www.fiverr.com'+data['href']
    print("===============")
    print(data.get_text())
    # print(sub_url)

    # info2 = scraper.get(sub_url).text
    # soup2 = beauty(info2, "html.parser")
    # if soup2.find('p', 'sc-subtitle'):
    #     print(f"title: {soup2.find('h1').text}")
    #     print(f"description: {soup2.find('p', 'sc-subtitle').text}")
    # else :
    #     print("error")
    #     print(f"title: {soup2.find('h1')}")
    #     print(f"description: {soup2.find('p', 'sc-subtitle')}")