import json
from enum import Enum

import pyperclip
from textual import on
from textual.app import ComposeResult
from textual.containers import Horizontal, Vertical
from textual.css.query import NoMatches
from textual.events import Click
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Input, LoadingIndicator, Static

from oterm.app.prompt import PromptWidget
from oterm.ollama import OllamaLLM

class Author(Enum):
    USER = "me"
    OLLAMA = "ollama"

class ChatContainer(Widget):
    ollama = OllamaLLM()
    messages: reactive[list[tuple[Author, str]]] = reactive([])
    chat_name: str

    def __init__(
        self,
        *children: Widget,
        db_id: int,
        chat_name: str,
        model: str = "nous-hermes:13b",
        context: list[int] = [],
        messages: list[tuple[Author, str]] = [],
        **kwargs,
    ) -> None:
        super().__init__(*children, **kwargs)

        self.ollama = OllamaLLM(
            model=model, context=context
        )  # We do this to reset the context
        self.chat_name = chat_name
        self.db_id = db_id
        self.messages = messages

    def on_mount(self) -> None:
        self.query_one("#prompt").focus()
        if self.messages:
            message_container = self.query_one("#messageContainer")
            for author, message in self.messages:
                chat_item = ChatItem()
                chat_item.text = message
                chat_item.author = author
                message_container.mount(chat_item)
            message_container.scroll_end()

    @on(Input.Submitted)
    async def on_submit(self, event: Input.Submitted) -> None:
        message = event.value
        input = event.input
        message_container = self.query_one("#messageContainer")

        input.clear()
        input.disabled = True
        self.messages.append((Author.USER, message))
        chat_item = ChatItem()
        chat_item.text = message
        chat_item.author = Author.USER
        message_container.mount(chat_item)

        chat_item = ChatItem()
        chat_item.author = Author.OLLAMA
        message_container.mount(chat_item)
        loading = LoadingIndicator()
        message_container.mount(loading)
        message_container.scroll_end()

        response = ""
        async for text in self.ollama.stream(message):
            response = text
            chat_item.text = text
            message_container.scroll_end()
        self.messages.append((Author.OLLAMA, response))
        loading.remove()
        input.disabled = False
        input.focus()

        # Save to db
        await self.app.store.save_context(  # type: ignore
            id=self.db_id,
            context=json.dumps(self.ollama.context),
        )
        await self.app.store.save_message(  # type: ignore
            chat_id=self.db_id,
            author=Author.USER.value,
            text=message,
        )
        await self.app.store.save_message(  # type: ignore
            chat_id=self.db_id,
            author=Author.OLLAMA.value,
            text=response,
        )

    def compose(self) -> ComposeResult:
        with Vertical():
            yield Static(f"model: {self.ollama.model}", id="info")
            yield Vertical(id="messageContainer")
            yield PromptWidget(id="prompt")

class ChatItem(Widget):
    text: reactive[str] = reactive("")
    author: Author

    @on(Click)
    async def on_click(self, event: Click) -> None:
        pyperclip.copy(self.text)
        widget = self.query_one(".text", Static)
        widget.styles.animate("opacity", 0.5, duration=0.1)
        widget.styles.animate("opacity", 1.0, duration=0.1, delay=0.1)

    def watch_text(self, text: str) -> None:
        try:
            widget = self.query_one(".text", Static)
            if widget:
                widget.update(text)
        except NoMatches:
            pass

    def compose(self) -> ComposeResult:
        """A chat item."""
        with Horizontal(classes=f"{self.author.name} chatItem"):
            yield Static(self.author.value, classes="author")
            yield Static(self.text, classes="text")


"""
Filename: arellano_vfi.py

Authors: Chase Coleman, John Stachurski

Solve the Arellano default risk model

References
----------

http://quant-econ.net/py/arellano.html

.. Arellano, Cristina. "Default risk and income fluctuations in emerging
   economies." The American Economic Review (2008): 690-712.

"""
from __future__ import division
import numpy as np
import random
import quantecon as qe
from numba import jit

class Arellano_Economy(object):
    """
    Arellano 2008 deals with a small open economy whose government
    invests in foreign assets in order to smooth the consumption of
    domestic households. Domestic households receive a stochastic
    path of income.

    Parameters
    ----------
    beta : float
        Time discounting parameter
    gamma : float
        Risk-aversion parameter
    r : float
        int lending rate
    rho : float
        Persistence in the income process
    eta : float
        Standard deviation of the income process
    theta : float
        Probability of re-entering financial markets in each period
    ny : int
        Number of points in y grid
    nB : int
        Number of points in B grid
    tol : float
        Error tolerance in iteration
    maxit : int
        Maximum number of iterations
    """

    def __init__(self,
            beta=.953,      # time discount rate
            gamma=2.,       # risk aversion
            r=0.017,        # international interest rate
            rho=.945,       # persistence in output
            eta=0.025,      # st dev of output shock
            theta=0.282,    # prob of regaining access
            ny=21,          # number of points in y grid
            nB=251,         # number of points in B grid
            tol=1e-8,       # error tolerance in iteration
            maxit=10000):

        # Save parameters
        self.beta, self.gamma, self.r = beta, gamma, r
        self.rho, self.eta, self.theta = rho, eta, theta
        self.ny, self.nB = ny, nB

        # Create grids and discretize Markov process
        self.Bgrid = np.linspace(-.45, .45, nB)
        self.mc = qe.markov.tauchen(rho, eta, 3, ny)
        self.ygrid = np.exp(self.mc.state_values)
        self.Py = self.mc.P

        # Output when in default
        ymean = np.mean(self.ygrid)
        self.def_y = np.minimum(0.969 * ymean, self.ygrid)

        # Allocate memory
        self.Vd = np.zeros(ny)
        self.Vc = np.zeros((ny, nB))
        self.V = np.zeros((ny, nB))
        self.Q = np.ones((ny, nB)) * .95  # Initial guess for prices
        self.default_prob = np.empty((ny, nB))

        # Compute the value functions, prices, and default prob
        self.solve(tol=tol, maxit=maxit)
        # Compute the optimal savings policy conditional on no default
        self.compute_savings_policy()

    def solve(self, tol=1e-8, maxit=10000):
        # Iteration Stuff
        it = 0
        dist = 10.

        # Alloc memory to store next iterate of value function
        V_upd = np.zeros((self.ny, self.nB))

        # == Main loop == #
        while dist > tol and maxit > it:

            # Compute expectations for this iteration
            Vs = self.V, self.Vd, self.Vc
            EV, EVd, EVc = (np.dot(self.Py, v) for v in Vs)

            # Run inner loop to update value functions Vc and Vd.
            # Note that Vc and Vd are updated in place.  Other objects
            # are not modified.
            _inner_loop(self.ygrid, self.def_y, self.Bgrid, self.Vd, self.Vc,
                    EVc, EVd, EV, self.Q,
                    self.beta, self.theta, self.gamma)

            # Update prices
            Vd_compat = np.repeat(self.Vd, self.nB).reshape(self.ny, self.nB)
            default_states = Vd_compat > self.Vc
            self.default_prob[:, :] = np.dot(self.Py, default_states)
            self.Q[:, :] = (1 - self.default_prob)/(1 + self.r)

            # Update main value function and distance
            V_upd[:, :] = np.maximum(self.Vc, Vd_compat)
            dist = np.max(np.abs(V_upd - self.V))
            self.V[:, :] = V_upd[:, :]

            it += 1
            if it % 25 == 0:
                print("Running iteration {} with dist of {}".format(it, dist))

        return None

    def compute_savings_policy(self):
        """
        Compute optimal savings B' conditional on not defaulting.
        The policy is recorded as an index value in Bgrid.
        """

        # Allocate memory
        self.next_B_index = np.empty((self.ny, self.nB))
        EV = np.dot(self.Py, self.V)

        _compute_savings_policy(self.ygrid, self.Bgrid, self.Q, EV,
                self.gamma, self.beta, self.next_B_index)

    def simulate(self, T, y_init=None, B_init=None):
        """
        Simulate time series for output, consumption, B'.
        """
        # Find index i such that Bgrid[i] is near 0
        zero_B_index = np.searchsorted(self.Bgrid, 0)

        if y_init is None:
            # Set to index near the mean of the ygrid
            y_init = np.searchsorted(self.ygrid, self.ygrid.mean())
        if B_init is None:
            B_init = zero_B_index
        # Start off not in default
        in_default = False

        y_sim_indices = self.mc.simulate_indices(T, init=y_init)
        B_sim_indices = np.empty(T, dtype=np.int64)
        B_sim_indices[0] = B_init
        q_sim = np.empty(T)
        in_default_series = np.zeros(T, dtype=np.int64)

        for t in range(T-1):
            yi, Bi = y_sim_indices[t], B_sim_indices[t]
            if not in_default:
                if self.Vc[yi, Bi] < self.Vd[yi]:
                    in_default = True
                    Bi_next = zero_B_index
                else:
                    new_index = self.next_B_index[yi, Bi]
                    Bi_next = new_index
            else:
                in_default_series[t] = 1
                Bi_next = zero_B_index
                if random.uniform(0, 1) < self.theta:
                    in_default = False
            B_sim_indices[t+1] = Bi_next
            q_sim[t] = self.Q[yi, Bi_next]

        q_sim[-1] = q_sim[-2] # Extrapolate for the last price
        return_vecs = (self.ygrid[y_sim_indices],
                      self.Bgrid[B_sim_indices],
                      q_sim,
                      in_default_series)

        return return_vecs

@jit(nopython=True)
def u(c, gamma):
    return c**(1-gamma)/(1-gamma)

@jit(nopython=True)
def _inner_loop(ygrid, def_y, Bgrid, Vd, Vc, EVc,
                         EVd, EV, qq, beta, theta, gamma):
    """
    This is a numba version of the inner loop of the solve in the
    Arellano class. It updates Vd and Vc in place.
    """
    ny, nB = len(ygrid), len(Bgrid)
    zero_ind = nB // 2  # Integer division
    for iy in range(ny):
        y = ygrid[iy]   # Pull out current y

        # Compute Vd
        Vd[iy] = u(def_y[iy], gamma) + \
                beta * (theta * EVc[iy, zero_ind] + (1 - theta) * EVd[iy])

        # Compute Vc
        for ib in range(nB):
            B = Bgrid[ib] # Pull out current B

            current_max = -1e14
            for ib_next in range(nB):
                c = max(y - qq[iy, ib_next] * Bgrid[ib_next] + B, 1e-14)
                m = u(c, gamma) + beta * EV[iy, ib_next]
                if m > current_max:
                    current_max = m
            Vc[iy, ib] = current_max

    return None

@jit(nopython=True)
def _compute_savings_policy(ygrid, Bgrid, Q, EV, gamma, beta, next_B_index):
    # Compute best index in Bgrid given iy, ib
    ny, nB = len(ygrid), len(Bgrid)
    for iy in range(ny):
        y = ygrid[iy]
        for ib in range(nB):
            B = Bgrid[ib]
            current_max = -1e10
            for ib_next in range(nB):
                c = max(y - Q[iy, ib_next] * Bgrid[ib_next] + B, 1e-14)
                m = u(c, gamma) + beta * EV[iy, ib_next]
                if m > current_max:
                    current_max = m
                    current_max_index = ib_next
            next_B_index[iy, ib] = current_max_index
    return None


import aiml
import logging
#import glob, os, psutil, sys, subprocess
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

#chat_id = CHAT_ID  # telegram chat_id (user or group)

# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text("I'm a bot, please talk to me!\n"
                              "/snap - Take a snapshot and send it: uses fswebcam to take a picture and immediately send it to the Telegram chat.\n"
                              "/startmotion - Start motion surveillance: start the Motion software with the personalised configuration file\n"
                              "/stopmotion - Stop motion surveillance: stop the Motion software with proc.kill()\n"
                              "/checkmotion - Check if motion surveillance is on: check from ps if the Motion software is running\n"
                              "/sendlast - Send last picture taken by motion surveillance: pictures are taken during the motion detection, the last one saved in the /pics folder is sent via Telegram\n"
                              "/cleanpics - Delete all pictures taken by motion surveillance: this delete all the .jpg files in the pics directory.")

def dialog(update, context):
    """Echo the user message."""
    bot = aiml.Kernel()
    #bot.bootstrap(learnFiles='/home/kamila/Documentos/chatbot_AIML/bot-start.xml', commands='INITIALIZING')
    bot.learn('./bot-start.aiml')
    bot.respond('INITIALIZING')
    #resposta = bot.respond(update.message.text)
    update.message.reply_text(bot.respond(update.message.text))

def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary

    updater = Updater("TOKEN_HERE", use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, dialog))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

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

# import aiml

# bot = aiml.Kernel()
# bot.learn('/home/kamila/Documentos/chatbot_AIML/conversa.xml')

# print(bot.respond("OLA ASSISTENTE"))
# while True:
#     r = input("Aluno ->")
#     r = bot.respond(r).split("/n")
#     print("Assistente ->")
#     for i in r:
#         print(i)


#
# Author: Jennifer Gomez
#
# This program will draw a regular polygon using turtle graphics. Each of the
# sides will have the same length and each angle will be the same size. The
# number of sides will be chosen by the user (must be greater than 2).

# Import the turtle module
from turtle import *

# Create a function to pick the colors for the fill and border.
def colorPicker(number):
    colors = ['coral', 'gold', 'brown', 'red', 'green', 'blue', 'yellow',
          'purple', 'orange', 'cyan', 'pink', 'magenta', 'goldenrod']
    return colors[number]

# The makePolygon function draws a polygon with the number of sides, side length
# border color, border width, and fill color as specified by the user.
def makePolygon(sides, length, borderColor, width, fillColor):
    s = sides
    begin_fill()
    while s > 0:
        forward(length)
        left(360 / sides)
        s = s - 1
    end_fill()

# Run the main program
print('This program will draw a polygon with 3 or more sides')
shape('turtle')
showturtle()

# Color of border
import random
number = random.randint(1, 12)
borderColor = pencolor(colorPicker(number))

# Fill color
import random
number = random.randint(1, 12)
fillColor = fillcolor(colorPicker(number))

# Number of Sides
sides = int(input('Enter the number of sides, less than 3 to exit: '))
width = width(sides%20 + 1)
length = 600 / sides
while sides >= 3:
    makePolygon(sides, length, borderColor, width, fillColor)
    sides = int(input('Enter the number of sides, less than 3 to exit: '))
    clear()
    towards(0,0)


import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist, Quaternion
from nav_msgs.msg import Odometry
import math

class DriveSquareNode(Node):
    def __init__(self):
        super().__init__('drive_square')
        self.twist_pub = self.create_publisher(Twist, "cmd_vel", 10)
        self.odom_sub = self.create_subscription(Odometry, 'odom', self.handle_odometry, 10)
        timer_period = 0.1
        self.timer = self.create_timer(timer_period, self.run_loop)
        self.x = 0.0
        self.y = 0.0
        self.angle = 0.0

    def handle_odometry(self, msg:Odometry):
        self.x = msg.pose.pose.position.x
        self.y = msg.pose.pose.position.y
        self.angle = quaternion_to_yaw(msg.pose.pose.orientation)

    def run_loop(self):
        msg = Twist()
        if self.y < 0 and 1 < self.angle < 2:
            msg.linear.x = 0.0
        elif self.x < 0 and 0 < self.angle < 1.57:
            msg.angular.z = 0.3
        elif self.y > 1 and 4.71 < self.angle < 6.28:
            msg.angular.z = 0.3
        elif self.x > 1 and 3.14 < self.angle < 4.71:
            msg.angular.z = 0.3
        else:
            msg.linear.x = 0.1
            print("working")
        self.twist_pub.publish(msg)

def quaternion_to_yaw(quat: Quaternion):
    x = quat.x
    y = quat.y
    z = quat.z
    w = quat.w

    t1 = 2.0 * (w * z + x * y)
    t2 = 1.0 - 2.0 * (y * y + z * z)
    yaw_z = math.atan2(t1, t2)

    return yaw_z + math.pi

def main():
    rclpy.init()
    node = DriveSquareNode()
    rclpy.spin(node)
    rclpy.shutdown()
    print('this works')

if __name__ == "__main__":
    main()


import glob
import setuptools
from os.path import basename, splitext

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

setuptools.setup(
    name="createflaskapp",
    version="1.2",
    license="MIT",
    author="Ivan Sakal",
    author_email="sakalivan4@gmail.com",
    description="Package for initializing a flask project structure",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/isakal/create-flask-app",
    classifiers=[
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.6",
    package_dir={"": "src"},
    packages=setuptools.find_packages("src"),
    py_modules=[splitext(basename(path))[0] for path in glob.glob('src/*.py')],
    include_package_data=True,
    # package_data={"": [".flake8"]},
    install_requires=[
        "Click>=7",
        "animation>=0.0.6",
        "termcolor>=1.1.0"
    ],
    entry_points={
        "console_scripts": ["create-flask-app=create_flask_app.cli:create_project"]
    }
)


import argparse
import glob
import json
import logging
import os
import sys
import time
import urllib.request

logging.basicConfig(stream = sys.stdout, level = logging.INFO, format="%(levelname)s:%(module)s:%(lineno)s: %(message)s")

class MobilecoindJsonClient:
    def __init__(self, base_url):
        if not base_url.endswith("/"):
            base_url += "/"
        self.base_url = base_url

    def request(self, url, data=None):
        req = urllib.request.Request(self.base_url + url)

        if data:
            data = json.dumps(data)
            data_bytes = data.encode("utf-8")

            req.add_header("Content-Type", "application/json; charset=utf-8")
            req.add_header("Content-Length", len(data_bytes))
            response = urllib.request.urlopen(req, data_bytes)
        else:
            response = urllib.request.urlopen(req)

        return json.loads(response.read())

    def get_balance(self, monitor_id, subaddress_index=0):
        response = self.request(f"monitors/{monitor_id}/subaddresses/{subaddress_index}/balance")
        if "balance" not in response:
            raise Exception(f"Invalid response: {response}")
        return int(response["balance"])

    def create_monitor(self, account_key, first_subaddress_index=0, num_subaddresses=1):
        return self.request(f"monitors", {
            "account_key": account_key,
            "first_subaddress": first_subaddress_index,
            "num_subaddresses": num_subaddresses,
        })

    def get_monitor(self, monitor_id):
        return self.request(f"monitors/{monitor_id}")

    def get_ledger_local(self):
        return self.request(f"ledger/local")

    # Takes the json loaded from a private key file, tests if it is mnemnonic or root entropy
    #
    # If it is mnemonic, we pass the mnemonic to `account-key-from-mnemonic` route
    # Otherwise, we hit the `entropy/{root_entropy}` route.
    # Both return Json account key response.
    def account_key_from_json(self, obj):
        if "mnemonic" in obj:
            return self.request("account-key-from-mnemonic", {"mnemonic": obj["mnemonic"]})
        elif "root_entropy" in obj:
            # Take the integer array in obj["root_entropy"], convert it to builtin bytes, then
            # get hex string of that.
            return self.request("entropy/{}".format(bytes(obj["root_entropy"]).hex()))
        else:
            raise Exception("unknown key format", obj)

    def get_public_address(self, monitor_id, subaddress_index=0):
        return self.request(f"monitors/{monitor_id}/subaddresses/{subaddress_index}/public-address")

    def pay_address_code(self, from_monitor_id, from_subaddress_index, to_b58_address, value):
        return self.request(f"monitors/{from_monitor_id}/subaddresses/{from_subaddress_index}/pay-address-code", {
            "receiver_b58_address_code": to_b58_address,
            "value": str(value),
        })

    def tx_status_as_sender(self, tx_info):
        return self.request(f"tx/status-as-sender", tx_info)

    def tx_status_as_receiver(self, monitor_id, receipt):
        return self.request(f"monitors/{monitor_id}/tx-status-as-receiver", receipt)

    def get_utxos(self, monitor_id, subaddress_index=0):
        return self.request(f"monitors/{monitor_id}/subaddresses/{subaddress_index}/utxos")["output_list"]

    def wait_for_monitor_to_sync(self, monitor_id, poll_interval=0.1):
        while True:
            local_ledger = self.get_ledger_local()
            monitor = self.get_monitor(monitor_id)
            if int(monitor["next_block"]) >= int(local_ledger["block_count"]):
                break
            time.sleep(poll_interval)

def load_keys(keys_dir):
    """Load all keys from the keys_dir directory"""

    # When Comparing filenames, make shorter file names compare less than longer filenames,
    # using this key function
    def filename_key(filename):
        return (len(filename), filename);

    return [
        json.load(open(f)) for f in
        sorted(glob.glob(os.path.join(keys_dir, "*.json")), key=filename_key)
    ]

def run_test(mobilecoind_json_url, keys_dir, max_seconds):
    logging.info(f"mobilecoind-json integration test starting with url={mobilecoind_json_url} keys_dir={keys_dir} max_seconds={max_seconds}")
    keys = load_keys(keys_dir)
    if not keys:
        raise Exception(f"No keys found in directory: {keys_dir}")
    logging.info(f"Loaded {len(keys)} keys")

    client = MobilecoindJsonClient(mobilecoind_json_url)

    # Add two monitors and wait for them to sync
    monitor_ids = []
    for i in range(2):
        account_key = client.account_key_from_json(keys[i])
        monitor = client.create_monitor(account_key)
        logging.info(f"{i}: Monitor created: {monitor}, waiting to sync...")
        monitor_id = monitor["monitor_id"]
        client.wait_for_monitor_to_sync(monitor_id)
        balance = client.get_balance(monitor_id)
        logging.info(f"{i}: Monitor synced: balance={balance}")
        monitor_ids.append(monitor_id)

    # Run tests
    test_pay_address_code(client, monitor_ids)
    test_utxos(client, monitor_ids[1])

def test_pay_address_code(client, monitor_ids):
    # Get the balance of both monitors and then transact from one to the other using the pay_address_code endpoint
    balance0 = client.get_balance(monitor_ids[0])
    balance1 = client.get_balance(monitor_ids[1])

    amount = 1
    addr1 = client.get_public_address(monitor_ids[1])["b58_address_code"]
    tx_info = client.pay_address_code(monitor_ids[0], 0, addr1, amount)
    logging.info(f"Tx submitted: {tx_info}")

    # Wait up to 30 seconds for tx to happen
    for _ in range(30):
        new_balance1 = client.get_balance(monitor_ids[1])
        if new_balance1 != balance1:
            break
        time.sleep(1)

    assert new_balance1 == balance1 + amount, f"Balance mismatch: {new_balance1} != {balance1} + {amount}"
    logging.info("Balance check passed")

    # Check the status as the sender
    response = client.tx_status_as_sender(tx_info)
    logging.info(f"tx_status_as_sender: {response}")
    if response["status"] != "verified":
        raise Exception(f"Failed tx_status_as_sender check: {response}")

    # Check the status as the receiver
    response = client.tx_status_as_receiver(monitor_ids[1], tx_info["receiver_tx_receipt_list"][0])
    logging.info(f"tx_status_as_receiver: {response}")
    if response["status"] != "verified":
        raise Exception(f"Failed tx_status_as_receiver check: {response}")

def test_utxos(client, monitor_id):
    # Confirm the balance matches the list of utos
    balance = client.get_balance(monitor_id)
    utxos = client.get_utxos(monitor_id)

    utxo_balance = sum(int(utxo["value"]) for utxo in utxos)
    logging.info(f"balance is {balance}, utxo_balance is {utxo_balance}")
    assert balance == utxo_balance

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--mobilecoind-json-url",
                        default="http://localhost:9090/",
                        type=str,
                        help="mobilecoind-json host")
    parser.add_argument("--key-dir",
                        type=str,
                        help="Path to directory of account_keys",
                        required=True)
    parser.add_argument("--max-seconds",
                        type=int,
                        default=40,
                        help="Number of seconds to wait for a tx to clean")
    args = parser.parse_args()
    run_test(
        args.mobilecoind_json_url,
        args.key_dir,
        args.max_seconds,
    )


from time import sleep

def maior(* núm):
    cont = maior = 0
    print('-' * 30)
    print('Analisando os valores passados... ')
    print('-' * 30)
    for valor in núm:
        print(f'{valor} ', end='')
        sleep(0.3)
        if cont == 0:
            maior = valor
        else:
            if valor > maior:
                maior = valor
        cont += 1
    print(f'\nForam informados {cont} valores ao todo.')
    print(f'\nO maior valor encontrado foi {maior}.')

maior(2, 9, 4, 5, 7, 1)
maior(4, 7, 0)
maior(1, 2)
maior(6)
maior(0)


from django.core.management.base import BaseCommand, CommandError
from expert_system.utils import find_closest_request, timeit

class Command(BaseCommand):
    help = "Поиск самого похожего запроса в базе данных"

    def add_arguments(self, parser):
        parser.add_argument("user_request", type=str, help="Пользовательский запрос")

    @timeit
    def handle(self, *args, **options):
        closest_request = find_closest_request(options["user_request"])
        if closest_request is None:
            raise CommandError("Не удалось найти похожий запрос")
        self.stdout.write(
            self.style.SUCCESS(
                f'Наиболее похожий запрос на "{options["user_request"]}" - "{closest_request.request}" и '
                f'ответ: "{closest_request.text.text}".'
            )
        )


from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import *

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ("email",#"resident_type",
    "emailVerified",
    "is_staff", "is_active",
    )
    list_filter = ("email", "is_staff", "is_active",)
    fieldsets = (
        (None, {"fields": ("email", "password")}),
        ("Permissions", {"fields": ("is_staff", "is_active", "groups", "user_permissions")}),
    )
    # add_fieldsets = (
    #     (None, {
    #         "classes": ("wide",),
    #         "fields": (
    #             "email", "password1", "password2", "is_staff",
    #             "is_active", "groups", "user_permissions"
    #         )}
    #     ),
    # )
    search_fields = ("email",)
    ordering = ("email",)

admin.site.register(CustomUser)#, CustomUserAdmin)
admin.site.register(ResidenceType)
admin.site.register(StatusOfResidence)
admin.site.register(Profession)
admin.site.register(Profile)
admin.site.register(UserDocuments)
admin.site.register(TermsAndConditions)
admin.site.register(IntendedUseOfAccount)
admin.site.register(Ekyc)
# admin.site.register(AppVersion)
# admin.site.register(PostalCode)
admin.site.register(EkycType)
@admin.register(PostalCode)
class PostalCodeAdmin(admin.ModelAdmin):
    list_display=[k.name  for k in PostalCode._meta.fields]
# admin.site.register(CurrencyRate)
# @admin.register(CurrencyRate)
class CurrencyRateAdmin(admin.ModelAdmin):
    # list_display=["name","created_at","updated_at"]
    list_display=[k.name  for k in CurrencyRate._meta.fields]
    # list_display=[k for k in CurrencyRate._meta.get_fields()]
    # list_dispaly=('sell')#(k for k in CurrencyRate._meta.get_fields())
    list_filter = ('name','buy','sell', 'created_at','updated_at',)
    # list_display=['name','buy','sell', 'created_at','updated_at',]
    search_fields = ("name",'iso3')
admin.site.register(CurrencyRate,CurrencyRateAdmin)
# admin.site.register(ProfileDocuments)
@admin.register(ProfileDocuments)
class ProfileDocumentsAdmin(admin.ModelAdmin):
    # date_hierarchy = 'pub_date'
    list_display = ['id','user', 'created_at','updated_at','front_img_preview','back_img_preview','tilted_preview','blink_preview']

admin.site.register(ProvinceDistricts)

class BannersAdmin(admin.ModelAdmin): # new
    readonly_fields = ['img_preview']
    list_display = ['title', 'img_preview']
admin.site.register(Banners,BannersAdmin)
admin.site.site_header='Clone RPS Remit'

class CountryAdmin(admin.ModelAdmin):
    list_display=["img_preview","country","continent"]

admin.site.register(Country,CountryAdmin)
admin.site.register(TransactionType)
@admin.register(Transactions)

class Transactions(admin.ModelAdmin):
    list_display=[k.name  for k in Transactions._meta.fields]


print("Welcome to the bill calculator!")
bill = float(input("What was the total bill? $"))
tip = int(input("What percentage tip would you like to give? "))
people = int(input("How many people are splitting the bill? "))

bill_tip = bill * (1 + tip/100)

pay = round(bill_tip/people, 2)

pay = "{:.2f}".format(pay)

print(f"Everyone should pay ${pay}")


"""Utility functions for FarCry6 test script"""
import os
import cv2

# path relative to script
script_dir = os.path.dirname(os.path.realpath(__file__))
images_dir = os.path.join(script_dir, "images")
dir16x9 = os.path.join(images_dir, "16x9")
dir16x10 = os.path.join(images_dir, "16x10")

templates = {
    "options": {
        "16x10": cv2.imread(os.path.join(dir16x9, "options_menu_1080.png"), cv2.IMREAD_UNCHANGED),
        "16x9": cv2.imread(os.path.join(dir16x9, "options_menu_1080.png"), cv2.IMREAD_UNCHANGED)
    },
    "benchmark": {
        "16x10": cv2.imread(os.path.join(dir16x9, "benchmark_1080.png"), cv2.IMREAD_UNCHANGED),
        "16x9": cv2.imread(os.path.join(dir16x9, "benchmark_1080.png"), cv2.IMREAD_UNCHANGED)
    },
    "header": {
        "16x10": cv2.imread(os.path.join(dir16x9, "results_header_1080.png"), cv2.IMREAD_UNCHANGED),
        "16x9": cv2.imread(os.path.join(dir16x9, "results_header_1080.png"), cv2.IMREAD_UNCHANGED)
    },
}

def get_resolution():
    """Stub: Return resolution"""
    return 0,0


#!/usr/bin/python3
""" Module contains class Base """

class Base:
    """ Base class """

    __nb_objects = 0

    def __init__(self, id=None):
        """ Init method """

        if id is not None:
            id = int(id)
            self.id = id
        else:
            self.__class__.__nb_objects += 1
            self.id = self.__nb_objects

    @staticmethod
    def to_json_string(list_dictionaries):
        """ Imports a list of dictionaries to json """

        import json

        if list_dictionaries is None or len(list_dictionaries) is 0:
            return "[]"
        else:
            return json.dumps(list_dictionaries)

    @classmethod
    def save_to_file(cls, list_objs):
        """ Save json string of list of objects to file """

        filename = cls.__name__ + ".json"
        with open(filename, mode="w", encoding="utf-8") as myFile:
            list_dictionaries = []
            if list_objs is None:
                myFile.write("[]")
            else:
                list_dictionaries = [
                    iter.to_dictionary() for iter in list_objs]
            myFile.write(cls.to_json_string(list_dictionaries))

    @staticmethod
    def from_json_string(json_string):
        """ Return list of the JSON string from json_string """

        import json

        if json_string is None or len(json_string) is 0:
            return "[]"
        else:
            return json.loads(json_string)

    @classmethod
    def create(cls, **dictionary):
        """ Creates base instance with all attributes set from dictionary """

        dict_cls = cls(**dictionary)
        dict_cls.update(**dictionary)
        return dict_cls

    @classmethod
    def load_from_file(cls):
        """ Returns lists of instances dependent on class """

        filename = cls.__name__ + ".json"
        try:
            with open(filename) as myfile:
                list_json = cls.from_json_string(myfile.read())
        except FileNotFoundError:
            return []
        return [cls.create(**kwargs) for kwargs in list_json]

    @classmethod
    def save_to_file_csv(cls, list_objs):
        """ Saves to file in csv format """

        import csv

        filename = cls.__name__ + ".csv"
        dict_list = []
        for item in list_objs:
            itemdict = item.to_dictionary()
            dict_list.append(itemdict)
        if cls.__name__ is "Square":
            fields = ['x', 'y', 'id', 'size']
        else:
            fields = ['x', 'y', 'id', 'height', 'width']
        with open(filename, "w") as myfile:
            csv_writer = csv.DictWriter(myfile, fieldnames=fields)

            csv_writer.writeheader()
            csv_writer.writerows(dict_list)

    @classmethod
    def load_from_file_csv(cls):
        """ loads objects from csv file """
        import csv

        dict_list = []
        filename = cls.__name__ + ".csv"
        with open(filename, 'r') as myfile:
            csv_reader = csv.DictReader(myfile)

            for lines in csv_reader:
                dict_list.append(lines)

        return [cls.create(**kwargs) for kwargs in dict_list]

    @staticmethod
    def draw(list_rectangles, list_squares):
        """ draws objs """
        import turtle
        import random

        for rec in list_rectangles:
            turtle.penup()
            turtle.setpos(rec.x, rec.y)
            turtle.pencolor((random.random(), random.random(),
                            random.random()))
            turtle.pd()
            for i in range(0, 2):
                turtle.forward(rec.width)
                turtle.right(90)
                turtle.forward(rec.height)
                turtle.right(90)
        for rec in list_squares:
            turtle.penup()
            turtle.pensize(5)
            turtle.setpos(rec.x, rec.y)
            turtle.pencolor((random.random(), random.random(),
                            random.random()))
            turtle.pd()
            for i in range(0, 4):
                turtle.forward(rec.width)
                turtle.right(90)
        turtle.exitonclick()


import torch
import glob
import os

def load_wts(model, checkpoint_path):
    ckpt = torch.load(checkpoint_path)
    wts = ckpt['model']

    state = {}
    for k, v in wts.items():
        if k.startswith('module.'):
            k = k.replace('module.','')
        state[k] = v

    model.load_state_dict(state)
    return model


from selenium import webdriver

class WebDriverFactory:

    def __init__(self, browser):
        self.browser = browser

    def getWebDriverInstance(self):

        base_url = "https://www.amazon.com"
        if self.browser == "iexplorer":
            driver = webdriver.Ie()
        elif self.browser == "firefox":
            driver = webdriver.Firefox()
        elif self.browser == "chrome":
            driver = webdriver.Chrome()
        else:
            driver = webdriver.Chrome()

        driver.implicitly_wait(3)
        driver.maximize_window()
        driver.get(base_url)
        return driver


from django.test import TestCase
from ..models import Subject, Category

class CategoryModelTest(TestCase):
    """Tests for Category model."""

    @classmethod
    def setUpTestData(cls):
        Category.objects.create(
            name='Разработка программ',
            slug='develop',
            description='Описание',
            content='Содержание',
            price=5000,
            status=True
        )

    def test_get_absolute_url(self):
        category = Category.objects.get(slug='develop')
        self.assertEqual(category.get_absolute_url(), '/subjects/develop/')

    def test_is_enabled(self):
        category = Category.objects.get(slug='develop')
        self.assertTrue(category.is_enabled())

class SubjectModelTest(TestCase):
    """Tests for Subject model."""

    @classmethod
    def setUpTestData(cls):
        category = Category.objects.create(
            name='Разработка программ',
            slug='develop',
            description='Описание',
            content='Содержание',
            price=5000,
            status=True
        )
        Subject.objects.create(
            name='Django site',
            description='Описание',
            content='Содердание',
            price=5000,
            status=Subject.STATUS_ENABLED,
            category=category
        )

    def test_get_absolute_url(self):
        subject = Subject.objects.get(pk=1)
        self.assertEqual(subject.get_absolute_url(), '/subjects/1/')

    def test_get_create_url(self):
        subject = Subject.objects.get(pk=1)
        self.assertEqual(subject.get_create_url(), '/orders/subject/1/')

    def test_get_status(self):
        subject = Subject.objects.get(pk=1)
        self.assertEqual(subject.status, Subject.STATUS_ENABLED)
        self.assertEqual(subject.get_status(), 'Доступно')

    def test_is_enabled(self):
        subject = Subject.objects.get(pk=1)
        self.assertTrue(subject.is_enabled())


#An adventure game where the player
#must prove the existence of a fabled creature

#1. Make dictonary for gameworld
#2. Make dictonary for player
#3. Make protoype that only uses movement
#4. Add take/drop items.
import csv
def load_text(file_name):
    file_data = []
    file_hndl = open(file_name, "r")
    for file_line in file_hndl.readlines():
        file_data.append(file_line)
        file_hndl.close()
    return file_data

def interact_npc(game_data, name):
    for npc in game_data["player"]["location"]["npc"]:
        npc_name = npc["name"].lower()

        if npc_name == name or npc_name.split()[0] == name or npc_name.split()[1] == name:
            #dialog_npc(game_data, npc)

            if npc["talk"]:
                dialog_npc(game_data, npc)
            else:
                print(npc_name, "is unavailable.")

            return
    print("NPC not found")
    return

def init_dialog(game_data, file_name):
    row_data = readCSV(file_name, False)
    return row_data

def dialog_npc(game_data, npc):
    dialog = npc["dialog"]
    talk = True
    name = npc["name"] +":"

    print("You are talking to", npc["name"])

    while talk:
        found_input = False

        dialog_input = input()

        for row in dialog:

            if row[0] == dialog_input:
                print(name, row[1])
                found_input = True

                if npc["name"]=="Father" and row[0] =="what did you see" and game_data["objectives"]["num"]==1:
                    add_objective(game_data)
                    game_data["npc"]["Crydus Averoth"]["dialog"] = readCSV("Assets/dialog/Crydus_Averoth_1.csv", False)
                    game_data["npc"]["Crydus Averoth"]["talk"] = True

                if npc["name"]=="Father" and row[0] =="where to go" and game_data["objectives"]["num"]==6:
                    add_objective(game_data)

                if npc["name"]=="Crydus Averoth" and row[0] =="how's life" and game_data["objectives"]["num"]==2:
                    add_objective(game_data)

                if npc["name"]=="Renaila Scoran" and (row[0] =="where's son" or row[0] == "what did you see") and game_data["objectives"]["num"]==4:
                    add_objective(game_data)
                    print("Crydus Averoth: Wait!", game_data["player"]["name"], "let me help you. Renaila, don't worry. We'll find him. Come on, I'll meet you at the lake.")
                break

        if not found_input:
            if dialog_input =="who are you" or dialog_input =="who are you?":
                print(name, npc["who are you"])

            elif dialog_input == "help":
                help(game_data, "dialog")

            elif dialog_input =='0':
                return

            else:
                print("Wrong dialog option. Try again.")

def add_objective(game_data):

    objective = game_data["objectives"]["list"][game_data["objectives"]["num"]]
    journal = game_data["journal"]["list"][game_data["objectives"]["num"]]

    if game_data["objectives"]["num"]>0:
        game_data["objectives"]["previous"].append(game_data["objectives"]["current"])
        game_data["journal"]["previous"].append(game_data["journal"]["current"])

    game_data["journal"]["current"] = journal
    game_data["objectives"]["current"] = objective
    print("NEW OBJECTIVE")
    game_data["score"]+=100
    game_data["objectives"]["num"] +=1

    if game_data["objectives"]["num"]==4:
        game_data["npc"]["Renaila Scoran"]["talk"] = True
        game_data["npc"]["Renaila Scoran"]["dialog"] = readCSV("Assets/dialog/Renaila_dialog1.csv", False)
        game_data["npc"]["Yorla Margrani"]["dialog"] = readCSV("Assets/dialog/Yorla_dialog1.csv", False)
        game_data["npc"]["Yorla Margrani"]["talk"] = True

        game_data["region"]["town"]["npc"].append(game_data["npc"]["Renaila Scoran"])
        game_data["region"]["town"]["npc"].remove(game_data["npc"]["Crydus Averoth"])
        update_player_region(game_data)

    elif game_data["objectives"]["num"]==5:
        game_data["region"]["lakeside"]["npc"].append(game_data["npc"]["Crydus Averoth"])
        game_data["npc"]["Crydus Averoth"]["dialog"] = readCSV("Assets/dialog/Crydus_Averoth_2.csv", False)
        game_data["npc"]["Crydus Averoth"]["talk"] = True

    elif game_data["objectives"]["num"]==6:
        game_data["npc"]["Father"]["talk"] = True
        game_data["npc"]["Father"]["dialog"] = readCSV("Assets/dialog/father_dialog2.csv", False)

    return game_data

def update_player_region(game_data):
    region_name = game_data["player"]["location"]["name"]
    game_data["player"]["location"] = game_data["region"][region_name]
    return game_data

def view_objectives(game_data):
    if game_data["objectives"]["num"] ==  0:
        print("No objectives found.")

    else:
        print("CURRENT OBJECTIVE: "+ game_data["objectives"]["current"])
        print(game_data["journal"]["current"])

        if(len(game_data["objectives"]["previous"])>0):
            print("PREVIOUS OBJECTIVES:")

            journal_reversed= game_data["journal"]["previous"][::-1]
            objective_reversed= game_data["objectives"]["previous"][::-1]

            for index in range(len(game_data["objectives"]["previous"])):
                print(str(index+1)+" - "+ objective_reversed[index])
                print(journal_reversed[index])

def readCSV(csv_file_name, is_map):

	with open(csv_file_name) as csvfile:
		readCSV = csv.reader(csvfile, delimiter=',')
		row_data = []
		i = 0
		for row in readCSV:

			if is_map:
				row_data.append(row)
			if i >0 and not is_map:
				row_data.append(row)
			i+=1
	return row_data

def view_inventory(game_data):

    while(True):

        print(game_data["coins"], "coins")
        print("You currently have "+str(len(game_data["inventory"])) +" items in your inventory")
        for item in game_data["inventory"]:
            print("\t"+item["name"])

        action = input()

        if action.split()[0] == 'drop':
            drop_item(game_data, action.split('drop ')[1])
        elif action.split()[0] == 'view':
            view_item(game_data, action.split('view ')[1])
        elif action =="help":
            help(game_data, "inventory")
        elif action == '0':
            break
        else:
            print("Error 02: Wrong input. Try again.")
        print("")

def view_item(game_data, item):

    if item == "coin" or item == "coins":
        print("Cannot examine this.")
        return

    for inventory_item in game_data["inventory"]:
        if item.lower()==inventory_item["name"].lower():
            print(inventory_item["type"]+": "+inventory_item["name"])
            print(inventory_item["info"])

            if(inventory_item["type"] == "Weapon"):
                print("damage: "+ str(inventory_item["damage"]) )

            elif(inventory_item["type"] == "Book"):
                for line in inventory_item["text"]:
                    print(line)
            return
    print("Item not found.")
    return

def drop_item(game_data, item):

    if(item == "coins" or item == "coin"):
        if game_data["coins"]==0:
            print("You cannot drop any more coins.")
            return
        amount = int(input("how many?: "))

        if amount>=game_data["coins"]:
            amount = game_data["coins"]

        game_data["coins"]-=amount
        game_data["region"][game_data["player"]["location"]["name"]]["coins"]+=amount
        game_data["player"]["location"] = game_data["region"][game_data["player"]["location"]["name"]]

        print(amount, "coins dropped.")
        return

    for location_item in game_data["inventory"]:

        if item.lower()==location_item["name"].lower():

            game_data["inventory"].remove(location_item)
            game_data["region"][game_data["player"]["location"]["name"]]["items"].append(location_item)
            game_data["player"]["location"] = game_data["region"][game_data["player"]["location"]["name"]]

            print("item removed")
            return game_data
    print("Item not found.")
    return game_data

def pickup_item(game_data, item):

    if(item == "coins" or item == "coin"):
        if game_data["region"][game_data["player"]["location"]["name"]]["coins"]==0:
            print("No coins to pickup.")
            return

        amount = int(input("how many?: "))

        if amount>=game_data["region"][game_data["player"]["location"]["name"]]["coins"]:
            amount = game_data["region"][game_data["player"]["location"]["name"]]["coins"]

        game_data["coins"]+= amount

        game_data["region"][game_data["player"]["location"]["name"]]["coins"]-= amount
        game_data["player"]["location"] = game_data["region"][game_data["player"]["location"]["name"]]

        print(amount, "coins picked up.")
        return

    for location_item in game_data["player"]["location"]["items"]:

        if item==location_item["name"].lower():

            if location_item["pickup"]:
                game_data["inventory"].append(location_item)
                game_data["region"][ game_data["player"]["location"]["name"] ]["items"].remove(location_item)
                game_data["player"]["location"] = game_data["region"][game_data["player"]["location"]["name"]]
                print("%s picked up" % location_item["name"])

                if item=="Father's letter".lower() and game_data["objectives"]["num"]==0:
                    add_objective(game_data)
                    game_data["npc"]["Father"]["talk"] = True
            else:
                print("Cannot pick this up.")

            return game_data
    print("Item not found.")
    return game_data

def update_region(game_data, region):
    return
def init_game_data():

    game_data ={}

    game_data["score"] = 0
    game_data["game_over"] = False

    game_data["info"] ="You are in a ...."

    game_data["coins"] = 100
    game_data["player"] ={}
    game_data["inventory"] = []

    game_data["objectives"] = {}

    game_data["objectives"]["list"] = []
    game_data["journal"] = {}
    game_data["journal"]["current"] =None
    game_data["journal"]["previous"] = []
    game_data["journal"]["list"] = []

    row_data = readCSV("Assets/objectives.csv", False)
    for objective in row_data:
        game_data["objectives"]["list"].append(objective[0])

    row_data = readCSV("Assets/journal.csv", False)
    for objective in row_data:
        game_data["journal"]["list"].append(objective[0])

    game_data["objectives"]["current"] = None
    game_data["objectives"]["num"] = 0
    game_data["objectives"]["previous"] = []

    game_data["region"] ={}
    row_data = readCSV("Assets/regions.csv", False)

    for region_data in row_data:
        game_data["region"][region_data[0]] = {}
        game_data["region"][region_data[0]]["name"] = region_data[0]
        game_data["region"][region_data[0]]["info"] = region_data[1]
        game_data["region"][region_data[0]]["look"] = region_data[2]
        game_data["region"][region_data[0]]["access"] = []
        game_data["region"][region_data[0]]["items"] = []
        game_data["region"][region_data[0]]["npc"] = []
        game_data["region"][region_data[0]]["coins"] = 0

        access = region_data[3].split(", ")
        for access_area in access:
            game_data["region"][region_data[0]]["access"].append(access_area)

    game_data["region"]["bedroom"]["coins"] = 40

    game_data["items"] = {}
    row_data = readCSV("Assets/Items.csv", False)

    for item in row_data:
        game_data["items"][item[0]] = {}
        game_data["items"][item[0]]["name"] = item[0]
        game_data["items"][item[0]]["info"] = item[1]
        game_data["items"][item[0]]["type"] = item[2]

        if item[5] =="TRUE":
            game_data["items"][item[0]]["pickup"] = True
        else:
            game_data["items"][item[0]]["pickup"] = False

        if item[2]=="Book" or item[2] == "Text":
            game_data["items"][item[0]]["text"] = load_text(item[3])
        elif item[2] == "Weapon":
            game_data["items"][item[0]]["damage"] = item[3]

        if not item[4]=="None":
            game_data["region"][item[4]]["items"].append(game_data["items"][item[0]])

    game_data["enemies"] ={}

    game_data["npc"] ={}
    row_data = readCSV("Assets/npc.csv", False)

    for npc_data in row_data:
        game_data["npc"][npc_data[0]] = {}
        game_data["npc"][npc_data[0]]["name"] = npc_data[0]
        game_data["npc"][npc_data[0]]["region"] = npc_data[1]
        game_data["npc"][npc_data[0]]["who are you"] = npc_data[2]
        game_data["npc"][npc_data[0]]["access"] = npc_data[3]
        game_data["npc"][npc_data[0]]["encounter"] = 1
        game_data["npc"][npc_data[0]]["talk"] = False
        if not npc_data[1] =="None":
            game_data["region"][npc_data[1]]["npc"].append(game_data["npc"][npc_data[0]])

    game_data["npc"]["Father"]["dialog"] = init_dialog(game_data,"Assets/dialog/father_dialog1.csv")

    #print(game_data["npc"]["Father"]["dialog"])

    game_data["player"]["location"] = game_data["region"]["bedroom"]

    return game_data

def help(game_data, mode):
    if mode =="default":
        print("Type '0' to quit.")
        print("Type 'inventory' to access inventory")
        print("Type 'pickup' followed by the item name to pickup the item")
        print("Type 'drop' followed by the item name to drop the item")
        print("Type 'examine' followed by the item name to examine an item in the room.")
        print("Type 'look' to get a detailed look around your enviroment")
        print("Type 'move' followed by a location to move")
        print("Type 'objective' to view current objective.")
        print("Type 'talk' followed by the NPC's name to talk to them.")
        print("Type 'help' when in inventory, dialog mode to get help.")

    elif mode == "inventory":
        print("Type '0' to exit inventory.")
        print("Type 'drop' followed by the item name to drop an item.")
        print("Type 'view' followed by the item name to view an item.")
        print("Type 'equip' followed by the item name to equip a weapon.")

    elif mode == "dialog":
        print("Type 'ask about' followed by a noun to ask about a certain event, thing, or person.")
        print("Type 'who killed' followed by a person's name to find out who the killer was.")
        print("Type 'what did you see'/'what do you see' to ask about what the person saw.")
        print("Type 'what happened' to know more about an event that occured.")
        print("Type 'How's life' to get some current insight into the person's day to day life.")
        print("Type 'where's' followed by a person's name to find out where they are")
        print("Type 'Found something' to ask about what the person has found.")
        print("Type 'Where to go' to get advice about where you should go.")

def look(game_data):

    if game_data["objectives"]["num"]==3:
        print("It's night now. The sky is turning pitch black. You better hurry and get home.")

    if game_data["objectives"]["num"] ==4 and game_data["player"]["location"]["name"]=="traven":
        print("This is odd. You look around the building and see dozens of men all scampering around. You gaze at their faces and all you see is shock. Even some of the town guards are here. Something is wrong. You decide to ask Yorla about it. ")

    print(game_data["player"]["location"]["look"])

    if(len(game_data["player"]["location"]["items"])>0):
        print("List of items found:")
        for item in game_data["player"]["location"]["items"]:
            if  item["pickup"]:
                print(item["name"]+"    ", end='')

    if game_data["player"]["location"]["coins"]>0:
        print(str(game_data["player"]["location"]["coins"]), "coins")

    if len(game_data["player"]["location"]["items"])<=0 and game_data["player"]["location"]["coins"]==0:
        print("No items found")

    for npc in game_data["player"]["location"]["npc"]:
        print(npc["access"])

def examine(game_data, item):
    if(item =="coin" or item =="coins"):
        print("Cannot examine this.")
        return

    for location_item in game_data["player"]["location"]["items"]:
        if item.lower() == location_item["name"].lower():

            if location_item["name"]=="footprint" and game_data["objectives"]["num"]==5:
                print(location_item["info"])
                print("Crydus Averoth: This... This is a horse footprint. But it doesn't make sense... What's a horse doing out here, and why is it walking out of a lake?")
                print("You know what this is. You rise up from the wet ground, your back soaked, and you tell Crydus that the horse is actually going towards the water instead. His face lights up in shock and disbelief. You suddenly realize: Your father was telling the truth.")
                add_objective(game_data)

            elif location_item["type"]=="text":
                print(location_item["name"])
                print(location_item["text"])
            else:
                print(location_item["info"])
            return

    print("Item not found.")
    return

def move_region(game_data, region_name):

    for region in game_data["player"]["location"]["access"]:

        if region.split('_')[0]==region_name:
            game_data["player"]["location"] = game_data["region"][region.split('_')[1]]

            if region_name=="bedroom" and game_data["objectives"]["num"]:
                add_objective(game_data)
                print("You wake up, fresh as ever.")
            return game_data
    print("Invalid move location.")
    return game_data

def main():

    game_quit = False
    while(not game_quit):
        game_data = init_game_data()

        print("The Creature beneath the lake")
        player_input = input("Press any key to start, or '0' to quit: ")

        if player_input =='0':
            game_quit = True

        else:
            game_data["player"]["name"] = "Servius"
            #game_data["player"]["name"] = input("Type your character's name: ")
            print("Type 'help' for help.")

            print("You lie still on your wool bed. Suddenly, you wake up. You look outside to see the sun shining a warm, bright light into your eyes.")
            while(not game_data["game_over"]):
                print("SCORE: " + str(game_data["score"]))
                print(game_data["player"]["location"]["info"]+"\n")

                player_input = input().lower()

                if player_input =='0':
                    game_data["game_over"] = True

                elif player_input== "help":
                    help(game_data, "default")
                elif player_input.split()[0] == 'move':
                    move_region(game_data, player_input.split('move ')[1])

                elif player_input.split()[0] == 'examine':
                    examine(game_data, player_input.split('examine ')[1])
                elif player_input=="look":
                    look(game_data)

                elif player_input =='inventory':
                    view_inventory(game_data)

                elif player_input.split()[0] == 'drop':
                    drop_item(game_data, player_input.split('drop ')[1])

                elif player_input.split()[0] =='pickup':
                    pickup_item(game_data, player_input.split('pickup ')[1])

                elif player_input== "objective":
                    view_objectives(game_data)

                elif player_input.split()[0] =="talk":
                    interact_npc(game_data, player_input.split('talk ')[1])

                else:
                    print("Error 01: Wrong input. Try again")

                print("")

if __name__ == "__main__":
    main()


def absDistinct(A):
    count = len(A)
    start = 0
    end = count - 1

    # iterate using two pointers (start & end)
    while start < end:
        # skip equal adjacent values
        while start < end and A[start] == A[start+1]:
            start += 1
            count -= 1
        while start < end and A[end] == A[end-1]:
            end -= 1
            count -= 1

        # if start = end, break out of loop
        if start == end:
            break

        # if sum of two pointers is 0, not distinct
        if A[start] + A[end] == 0:
            count -= 1
            start += 1
            end -= 1
        # if negative sum, move right to check for any additional 0-sums
        elif A[start] + A[end] < 0:
            start += 1
        # if positive sum, move left to check for any additional 0-sum
        elif A[start] + A[end] > 0:
            end -= 1

    # return count
    return count

print(absDistinct([-5,-3,-1,0,3,6])) # 5
print(absDistinct([1,1]))


from rhapsody.io.log import get_default_logger

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import ProgrammingError, InternalError, IntegrityError, OperationalError

class Database:

    connection_string_templates = {
        'psql': 'postgresql+psycopg2://{user}:{pswd}@{host}/{db_name}',
        'mssql': 'mssql+pyodbc://{user}:{pswd}@{host}/{db_name}?driver=SQL+Server'
    }

    def __init__(self, name, type_, host, user, pswd, logger=None):
        if not logger:
            logger = get_default_logger('{}({})'.format(self.__class__.__name__, name))
        self.log = logger
        self.name = name
        self.type = type_
        self.host = host
        self.user = user
        self.pswd = pswd
        connection_string = self.connection_string_templates[self.type].format(user=self.user, pswd=self.pswd,
                                                                               host=self.host, db_name=self.name)
        self.engine = create_engine(connection_string)
        self.Session = sessionmaker(bind=self.engine)  # Not thread safe!
        # Use below for the thread safe Session. class!
        # self.session_factory = sessionmaker(bind=self.engine)
        # self.Session = scoped_session(self.session_factory)

    def get_session(self):
        """Don't forget to close the session!!!"""
        return self.Session()

    def create_self(self, super_user_database, overwrite=False):
        super_session = super_user_database.get_session()
        super_session.execute('COMMIT')

        if overwrite:
            # destroy database
            try:
                super_session.execute('DROP DATABASE IF EXISTS {};'.format(self.name))
            except OperationalError as err:
                self.log.warn('{}'.format(err))
                return -3
            super_session.execute('COMMIT')

        try:
            # create databases
            super_session.execute('CREATE DATABASE {0} OWNER {1};'.format(self.name, self.user))
            super_session.execute('COMMIT')
        except ProgrammingError as err:
            self.log.warn('{}'.format(err))
            return -2
        else:
            self.log.info('DATABASE {} created.'.format(self.name))
        finally:
            super_session.close()

    def create_tables_from_orm_dict(self, orm_dict):
        for setup in orm_dict:
            cls = setup['class']
            self.log.debug('Creating table for ORM class {c} with name: {t}'.format(c=cls.__name__,
                                                                                t=cls.__tablename__))
            cls.metadata.create_all(self.engine)

    def fill_from_orm_dict(self, orm_dict):
        """
        See rhapsody.database.example_orm_dict for more info.
        :param orm_dict: dict
        :return: -
        """
        self.log.debug('Filling database with data from orm dictionary')
        session = self.get_session()

        for setup in orm_dict:
            setup_class = setup['class']  # pointer to the class
            self.log.debug(setup_class.__tablename__ + ': ')
            setup_data = setup['data']
            for record in setup_data:
                self.log.debug(record)
                instance = setup_class(**record)  # create object from the class
                try:
                    # 1-N, N-1, N-N relations
                    children = instance.get_children()
                except AttributeError as err:
                    pass
                else:
                    for child in children:
                        session.add(child)
                session.add(instance)
                try:
                    session.commit()
                except IntegrityError as err:
                    self.log.warn('{}'.format(err))
                    # new session must be created because of old one rolled back!
                    session = self.get_session()

        session.close()

class DatabaseUser(Database):

    def __init__(self, name, pswd, type_, host, logger=None):
        super().__init__(name, type_, host, name, pswd, logger)

    def create_self(self, super_user_database, overwrite=False):
        super_session = super_user_database.get_session()
        super_session.execute('COMMIT')

        if overwrite:
            # drop user
            try:
                super_session.execute('DROP USER IF EXISTS {0};'.format(self.name))
                super_session.execute('COMMIT')
            except InternalError as err:
                self.log.warn('(Err: {}).'.format(err))
                return -3
            else:
                self.log.info('USER {} dropped.'.format(self.name))

        # create user
        try:
            super_session.execute('CREATE USER {0} WITH PASSWORD \'{1}\';'.format(self.name, self.pswd))
            super_session.execute('COMMIT')
        except ProgrammingError as err:
            self.log.warn('{}'.format(err))
            return -1
        else:
            self.log.info('USER {} created.'.format(self.name))
            # create user's main database - same db name as user name
            try:
                super_session.execute('CREATE DATABASE {0} OWNER {0};'.format(self.name))
                super_session.execute('COMMIT')
            except ProgrammingError as err:
                self.log.warn('{}'.format(err))
                return -2
            else:
                self.log.info('DATABASE {} created.'.format(self.name))


import htmlgenerator as hg
from django.utils.translation import gettext_lazy as _

from basxbread.utils import get_all_subclasses

from .button import Button

_CACHE = {}

def field_help(model, max_depth=3):
    if model not in _CACHE:
        _CACHE[model] = hg.mark_safe(
            hg.render(
                hg.BaseElement(
                    hg.DIV(
                        hg.format(_("Base model: ")),
                        model._meta.verbose_name,
                        style="margin-top: 2rem",
                    ),
                    hg.DIV(
                        _("Click "),
                        hg.SPAN(
                            " ... ",
                            style="width: 1rem; height: 1rem; background-color: lightgray;",
                        ),
                        " ",
                        _(" to copy the accessor"),
                        style="margin-top: 2rem",
                    ),
                    hg.DIV(_("Fields"), style="margin-top: 2rem"),
                    hg.DIV(
                        get_field_list(
                            model,
                            max_depth,
                            list(
                                set(
                                    [
                                        model,
                                        model.__mro__[-3],
                                        *get_all_subclasses(model.__mro__[-3]),
                                    ]
                                )
                            ),
                            display="block",
                        ),
                        style="line-height: 2rem",
                    ),
                ),
                {},
            )
        )
    return _CACHE[model]

def get_field_list(model, depth, excludemodels, display="none", parent_accessor=[]):
    fields = {}
    for f in model._meta.get_fields():
        # if not f.concrete and (f.one_to_many or f.many_to_many):
        # continue
        fields[f] = hg.DIV(
            hg.SPAN(
                ".".join(parent_accessor + [_field_attname(f)]),
                style="display:none;"
                "position: absolute;"
                "top: -2rem;"
                "background-color: white;"
                "padding: 0.25rem",
            ),
            hg.SPAN(
                " ... ",
                style="width: 1rem; height: 1rem; background-color: lightgray; cursor: pointer;",
                onmouseover="this.previousElementSibling.style.display = 'block'",
                onmouseout="this.previousElementSibling.style.display = 'none'",
                onclick="navigator.clipboard.writeText(this.previousElementSibling.innerText);",
            ),
            " ",
            hg.SPAN(
                hg.SPAN(_field_attname(f), style="font-weight: 700"),
                " ",
                _field_type_repr(f),
            ),
            style="position: relative",
        )
        if (
            f.related_model
            and not f.many_to_many
            and f.related_model not in excludemodels
            and depth > 0
        ):
            fields[f].append(
                Button(
                    buttontype="ghost",
                    icon="chevron--down",
                    onclick=_js_toggle_display("this.nextElementSibling"),
                )
            )
            fields[f].append(
                get_field_list(
                    f.related_model,
                    depth - 1,
                    excludemodels + [model],
                    parent_accessor=parent_accessor + [_field_attname(f)],
                )
            )
    return hg.UL(
        hg.Iterator(
            sorted(
                fields.items(),
                key=lambda k: ("1" if k[0].related_model else "0")
                + _field_attname(k[0]),
            ),
            "field",
            hg.LI(hg.C("field.1")),
        ),
        style=f"margin-left: 2rem; display: {display}",
    )

def _field_type_repr(field):
    from django.contrib.contenttypes.fields import GenericForeignKey

    if field.related_model:
        if field.one_to_one or field.many_to_one:
            return _(' reference to "%s"') % field.related_model._meta.verbose_name
        if field.one_to_many or field.many_to_many:
            return (
                _(' reference to multiple "%s"')
                % field.related_model._meta.verbose_name_plural
            )
    if isinstance(field, GenericForeignKey):
        return f"{type(field).__name__}"

    return f"{type(field).__name__}({field.verbose_name})"

def _field_attname(field):
    attname = field.name
    if hasattr(field, "attname"):
        attname = field.attname
    elif hasattr(field, "get_accessor_name"):
        attname = field.get_accessor_name()
    if attname.endswith("_id"):
        attname = attname[:-3]
    return attname

def _js_toggle_display(element_accessor):
    return (
        f"{element_accessor}.style.display = "
        f"{element_accessor}.style.display == 'none' ? 'block': 'none'"
    )


import numpy as np
from pyspark import SparkContext, HiveContext
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.externals import joblib
from data_process import sample, extract_feature_label

# gbdt training

def gbdt_train(train_data, train_label):
    print("starting training gbdt model...")
    gbdt = GradientBoostingClassifier(n_estimators=100, max_leaf_nodes=31)
    print("saving gbdt model...")
    joblib.dump(gbdt, '../model/gbdt_model/gbdt.model')
    print("starting prediction leaf...")
    gbdt_model = gbdt.fit(train_data, train_label)
    leaf = gbdt_model.apply(train_data)[:,:,0].astype(int)
    return leaf

#transform feature
def transfromed_feature(leaf, num_leaf):
    transfrom_feature_matrix=np.zeros([len(leaf), len(leaf[0]) * num_leaf], dtype=np.int64)
    for i in range(len(leaf)):
        temp=np.arange(len(leaf[0])) * num_leaf - 1 + np.array(leaf[i])
        transfrom_feature_matrix[i][temp] += 1
    return transfrom_feature_matrix

# lr model
def lr_train(train_data, train_label):
    print('starting training lr model')
    lr = LogisticRegression(penalty='l2')
    lr_model = lr.fit(train_data, train_label)

    print("saving lr model...")
    joblib.dump(lr, '../model/gbdt_model/lr.model')
    # prediction
    print("starting lr model predict...")
    y_pred = lr_model.predict(train_data)
    y_prob = lr_model.predict_proba(train_data)[:,1]

    print("evaluation model")
    pr = float(np.sum([1 if y_pred[i] == train_label[i] else 0 for i in range(len(train_label))]))/float(len(train_label))
    print("prediction precision: " + str(pr))

def train(rating_file_path, user_file_path, item_file_path, k):
    data_sample = sample(sc, rating_file_path, user_file_path, item_file_path, k)
    train_data, train_label = extract_feature_label(data_sample)
    leaf = gbdt_train(train_data, train_label)
    leaf_transform = transfromed_feature(leaf, leaf.max())
    lr_train(leaf_transform, train_label)

if __name__=="__main__":
    sc = SparkContext('local', 'traing')
    sqlcontext = HiveContext(sc)
    sc.setLogLevel("ERROR")
    rating_file_path = "E:/data/ml-100k/u.data"
    user_file_path = "E:/data/ml-100k/u.user"
    item_file_path = "E:/data/ml-100k/u.item"
    k= 5
    train(rating_file_path, user_file_path, item_file_path, k)


"""
You're playing a game in which you're given a sequence of various jewels. If adjacent jewels are of the same type, you can gain 1 point by collecting them (thus removing them from the sequence).

Given a string of lowercase English letters, where each letters represents a different type of jewel, find the maximum score you can obtain by playing the game optimally.

For example, if  = "abccbda", you can play as follows:

Collect "cc". These jewels are removed, the string becomes "abbda", and your score becomes 1.
Collect "bb". The string becomes "ada", and your score becomes 2.
After this, it is impossible to collect any more jewels. Therefore, the answer is 2.

Input Format

The first line contains an integer, , denoting the number of test cases.

Each test contains a single string, .

Constraints

 length of
Output Format

Print  lines. Each line should contain a single integer denoting the maximum score for the corresponding test case.

Sample Input 0

2
abcddcbd
abcd
Sample Output 0

3
0
Explanation 0

In the first case, we first collect "dd". The jewels now become "abccbd". Then collect "cc" followed by "bb". The jewels now become "ad", and no more jewels can be collected. The final score is , which is the maximum score possible.

In the second case, it is not possible to collect any jewels.
"""
# SOLUTION
#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'getMaxScore' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING jewels as parameter.
#
def getMaxScore(jewels):
    st = []
    i = 0
    count = 0
    while i < len(jewels):
        if len(st)!=0 and st[-1]==jewels[i]:
            i+=1
            st.pop(-1)
            count += 1
        else:
            st.append(jewels[i])
            i+=1
    return count

if _name_ == '_main_':
    t = int(input().strip())
    for t_itr in range(t):
        jewels = input()
        print(getMaxScore(jewels))


from collections import Counter
from functools import reduce

def filter_anagrams(word, iterable):

    def check_anagram(string):

        counter_1 = Counter(word)
        counter_2 = Counter(string)
        if counter_1 == counter_2:
            return string

    return filter(check_anagram, iterable)

result = list(filter_anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']))
print(result)
print(tuple(filter_anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer'])))
print(list(filter_anagrams([1, 2], [[2, 1], [2, 2], [1, 2]])))
print(list(filter_anagrams((1, 2), ((2, 1), (2, 2), (1, 2)))))
empty = ''
print(list(filter_anagrams(empty, [empty, 'foo', empty])))
print('/////')

def same_parity_filter(start_list):

    if len(start_list) == 0:
        return []
    n = start_list[0] % 2
    return list(filter(lambda x: x % 2 == n, start_list))

result = same_parity_filter([2, 0, 1, -3, 10, -2])
print(result)
print(same_parity_filter([1, 2, 0, 1, -3, 10, -2]))
print('***')

def find_index_of_nearest(desired_number, list_):

    if len(list_) == 0:
        return None

    enumerate_list = list(enumerate(list_))

    def compare(tuple_1, tuple_2):
        if abs(tuple_1[1] - desired_number) <= abs(tuple_2[1] - desired_number):
            return tuple_1
        return tuple_2

    return reduce(compare, enumerate_list, enumerate_list[0])[0]

print(find_index_of_nearest(7, [15, 10, 3, 7, 7, 4]))
print('++++++++')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import roslib
import rospy
import sys
import cv2
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
import os
import math
import numpy as np
import pandas as pd
import seaborn as sb
import os
import statistics
import scipy as sp
from scipy.signal.signaltools import correlate2d as c2d

def deteccion_dinamico(matriz1, cont_sec, carpeta, zona_ant, thres):
  data_m = pd.DataFrame(matriz1, columns=['r', 'dr', 'alfa'])
  data_seg, zona, umb, thres_bool = segmenta_max(data_m, zona_ant, thres)
  if thres_bool:
    data_zona = segmenta_zonas(data_m, umb)
    data_m = pd.DataFrame(data_zona, columns=['r', 'dr', 'alfa','n','seg','color'])
    data = []
    bolsa_front = []
    band = True
    capa = min(data_m['seg'].values)
    top_c = max(data_m['seg'].values)+1
    while band:# determinamos las diferentes zonas que tiene con negativo alta variabilidad positivo zonas baja variabilidad
         datos_s = data_m[(data_m['seg'] == capa) & (data_m['dr'] > 0)]
         if len(datos_s) != 0:
            n_dat = datos_s['n'].values
            max_dat = max(n_dat)
            min_dat = min(n_dat)
            clas = 0
            if capa<0:
               clas = -1
            if capa !=0:
               bolsa_front.append([max_dat, min_dat, max_dat-min_dat, clas])
            data.append(datos_s)
         capa += 1
         if capa == 0:
           capa += 1
         if capa >= top_c:
            band = False
    if len(zona) != 0:
       dr_p = umbral_move(bolsa_front)#se establece cuanto fue lo maximo que se pudo mover una zona
       bolsa_front, band_end,zona = detectar_dinamico(bolsa_front, zona, dr_p)
       if band_end:
          max_ant = zona_ant[0]+zona_ant[3]
          min_ant = zona_ant[1]-zona_ant[3]
          if max_ant > 90:
            max_ant = 90
          if min_ant < 0:
             min_ant = 0
          zona = [max_ant, min_ant, max_ant-min_ant,zona_ant[3]]
       if carpeta != None:
          data = []
          data.append(data_m[(data_m['seg'] == 0)])
       return(zona)
    else:
       return([0, 90, 0,0])
  else:
       return(zona)

def umbral_move(bolsa_in):
    max_long = 0
    for i in range(len(bolsa_in)):
      if bolsa_in[i][3] <0 and bolsa_in[i][2] > max_long:
         max_long =  bolsa_in[i][2]
    return(max_long)

def detectar_dinamico(bolsa_in, zona, dr_p):
    ''' debo mejorar el criterio para seleccionar la zona dinámica puede ser la correlación'''
    max_vect = []
    for elem in bolsa_in:#ordena la bolsa de menor a mayor de este modo se ordenan los espacios
       max_vect.append(elem[0])
    max_vect = list(max_vect)
    max_vect.sort()
    vect_ord = []
    for n_ord in max_vect:
       for bol in bolsa_in:
         if bol[0] == n_ord:
            vect_ord.append(bol)
    cont_alt = 0
    band_enc = False
    for i in range(len(vect_ord)):
       if vect_ord[i][3] <0 and cont_alt == 0:
          cont_alt = 1
          try:
             max_det, min_det, long_det = vect_ord[i+1][0],vect_ord[i][1],vect_ord[i+1][2]
          except:
             try:
                max_det, min_det, long_det, zn = zona
             except:
                max_det, min_det, long_det = zona
       elif vect_ord[i][3] <0 and cont_alt == 1 and vect_ord[i-1][3] == 0:
          vect_ord[i-1][3] = 1
          cont_alt = 1
          max_det = vect_ord[i][0]
          band_enc = True
    zona =  [max_det, min_det, long_det, dr_p]

    return(vect_ord, not(band_enc),zona)

def segmenta_max(matriz, zona, thres):
   dr_eva = []
   cont = 1
   n = 1
   band = True
   dr_v = matriz['dr'].values
   if thres<max(dr_v):
    umb=max(dr_v)/2
    for i in range(len(matriz)):
       r = matriz['r'][i]
       dr = matriz['dr'][i]
       alf  = matriz['alfa'][i]
       if dr > umb:
          dr_eva.append((r,dr,alf,i))
    dr_eva = np.array(dr_eva)
    dr_f_seg = []
    if len(dr_eva) >1  :
       not_e = 0
       for l in range(len(dr_eva)-1):
             n  = dr_eva[l][3]
             n_1  = dr_eva[l+1][3]
             if abs(n_1-n) == 1:
                if dr_eva[l][1] < dr_eva[l+1][1]:
                   dr_f_seg.append(dr_eva[l+1])
                else:
                   dr_f_seg.append(dr_eva[l])
                   dr_eva[l+1] = dr_eva[l]
             else:
                dr_f_seg.append(dr_eva[l])
       n  = dr_eva[len(dr_eva)-1][3]
       n_1  = dr_eva[len(dr_eva)-2][3]
       if abs(n_1-n) == 1:
          if dr_eva[len(dr_eva)-1][1] > dr_eva[len(dr_eva)-2][1]:
             dr_f_seg[len(dr_f_seg)-1] = dr_eva[len(dr_eva)-1]
       else:
          dr_f_seg.append(dr_eva[len(dr_eva)-1])
       dr_eva = dr_f_seg
       dr_f_seg = []
       dr_f_seg.append(dr_eva[0])
       for o in range(len(dr_eva)-1):
          if dr_eva[o][3] != dr_eva[o+1][3]:
             dr_f_seg.append(dr_eva[o+1])
       dr_eva = dr_f_seg
    dr_eva = np.array(dr_eva)

    for j in range(len(dr_eva)-2):
       dr_v = dr_eva[:,1]
       dr_v_min = min(dr_v)
       for k in range(len(dr_eva)):
          if dr_eva[k][1] == dr_v_min:
             dr_eva = np.delete(dr_eva,k, axis=0)
             break
    dr_v = dr_eva[:,1]
    if len(dr_v) == 2:
       max_dr = max(dr_v)
       min_dr = min(dr_v)
    else:
       max_dr = dr_v
       min_dr = dr_v
    matriz_seg = []
    min_n, max_n = 0,0

    for i in range(len(matriz)):
       r = matriz['r'][i]
       dr = matriz['dr'][i]
       alf  = matriz['alfa'][i]
       if dr == max_dr:
          col = [0,255,0]
          matriz_seg.append([r,dr,alf,i,col])
          max_n = i
       elif dr == min_dr:
          col = [0,255,0]
          matriz_seg.append([r,dr,alf,i,col])
          min_n = i
       else:
          col = [0,0,255]
          matriz_seg.append([r,dr,alf,i,col])
    if  min_dr == max_dr and len(zona)>0:
        if abs(max_n-zona[0]) < abs(max_n-zona[1]):
          if max_n-zona[2] < 0:
             min_n = max_n-zona[2]
          else:
             min_n = 0
          if min_n<0:
             min_n = 0
          matriz_seg[min_n][4] = [0,255,0]
        else:
          min_n = max_n
          max_n = min_n+zona[2]
          if max_n > 89:
             matriz_seg[89][4] = [0,255,0]
          else:
             matriz_seg[max_n][4] = [0,255,0]
    vect = [max_n, min_n]
    max_n = max(vect)
    min_n = min(vect)
    if len(zona) == 4:
       max_a,min_a,long_a,dp = zona
       if abs(max_a-max_n) > abs(min_a-max_n):
           min_n_p = min_n
           min_n = max_n
           max_n = min_n_p
       if abs(max_n-max_a)>abs(min_a-min_n):
          if abs(min_n-max_n) > abs(long_a+dp):
             max_n = min_n+long_a+dp
       else:
          if abs(min_n-max_n) > abs(long_a+dp):
             min_n = max_n+long_a+dp

       if max_n-min_n < 0:
          if abs(max_a-max_n) < abs(min_a-min_n):
             min_n = max_a-long_a
          else:
             max_n = min_n+long_a
    zona = [max_n, min_n, max_n-min_n]
    return(matriz_seg, zona,umb, True)
   else:
     zona = [0, 90, 0,0]
     return( matriz, zona, 0, False)
def segmenta_zonas(matriz, umb):# se divide en zonas a partir de la superación del umbral dinámico
    segmen = []
    cont = 1
    cont_0 = -1
    n = 1
    band = True
    band_0 = True
    np_matriz = np.array(matriz)
    for ele in np_matriz:
       r,dr,alf = ele
       if dr > umb:
          band_0 = True
          if band:
             cont += 1
             band = False
          col = [0,150,155]
          segmen.append([r,dr,alf,n ,cont_0,col])
       else:
          segmen.append([r,dr,alf,n ,cont,color(cont)])
          band = True
          if band_0:
             cont_0 -= 1
             band_0 = False
       n += 1
    return(segmen)

def color(num):
    c = (num) * 130
    if c<255:
       col = [c,0,0]
    elif c<510 and c>=255:
       c = c-255
       col = [255,c,0]
    elif c>=510 and c<765:
       c = c-510
       col = [255,255,c]
    else:
       col = [255,255,255]
    return(col)


import json
from unittest import TestCase
from models import CompanyModel

class CompanyTest(TestCase):
    def testCreateCompany(self):
        company = CompanyModel(
            "Test Company",
            "40028922",
            "Rua Aririzal, 12",
            "2023-07-08",
            "10000",
            [])

        self.assertEqual(company.companyName, "Test Company",
                         "The name of the company after creation is not equal to the constructor argument.")
        self.assertEqual(company.phone, "40028922",
                         "The phone of the company after creation is not equal to the constructor argument.")
        self.assertEqual(company.address, "Rua Aririzal, 12",
                         "The address of the company after creation is not equal to the constructor argument.")
        self.assertEqual(company.registrationDate, "2023-07-08",
                         "The registration date of the company after creation is not equal to the constructor argument.")
        self.assertEqual(company.billing, 10000,
                         "The billing of the company after creation is not equal to the constructor argument.")


import matplotlib.animation as animation
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import time

from colect_sim.controller.operational_space_controller import ImpedanceController, ComplianceController, OperationalSpaceController, TargetType
from colect_sim.controller.joint_effort_controller import JointEffortController
from colect_sim.controller.joint_velocity_controller import JointVelocityController
from colect_sim.controller.joint_position_controller import JointPositionController
from colect_sim.controller.force_torque_sensor_controller import ForceTorqueSensorController
from colect_sim.env.mujoco_env import MujocoEnv
from colect_sim.utils.mujoco_utils import MujocoModelNames
from mujoco import viewer
from os import path

from threading import Thread, Lock

np.set_printoptions(formatter={'float': lambda x: "{0:0.5f}".format(x)})

DEFAULT_CAMERA_CONFIG = {
    "distance": 2.2,
    "azimuth": 0.0,
    "elevation": -20.0,
    "lookat": np.array([0, 0, 1]),
}

class BaseRobot(MujocoEnv):

    metadata = {
        "render_modes": [
            "human",
            "rgb_array",
            "depth_array",
        ],
        "render_fps": 62,
    }

    def __init__(
        self,
        model_path="../../scene/scene.xml",
        frame_skip=16,
        default_camera_config: dict = DEFAULT_CAMERA_CONFIG,
        plot=False,
        **kwargs,
    ):
        xml_file_path = path.join(
            path.dirname(path.realpath(__file__)),
            model_path,
        )

        super().__init__(
            xml_file_path,
            frame_skip,
            default_camera_config=default_camera_config,
            **kwargs,
        )

        self.init_qvel = self.data.qvel.copy()
        self.init_ctrl = self.data.ctrl.copy()

        self.model_names = MujocoModelNames(self.model)

        # self.controller = ImpedanceController(
        #     model=self.model,
        #     data=self.data,
        #     model_names=self.model_names,
        #     eef_name='robot0:eef_site',
        #     joint_names=[
        #         'robot0:ur5e:shoulder_pan_joint',
        #         'robot0:ur5e:shoulder_lift_joint',
        #         'robot0:ur5e:elbow_joint',
        #         'robot0:ur5e:wrist_1_joint',
        #         'robot0:ur5e:wrist_2_joint',
        #         'robot0:ur5e:wrist_3_joint',
        #     ],
        #     actuator_names=[
        #         'robot0:ur5e:shoulder_pan',
        #         'robot0:ur5e:shoulder_lift',
        #         'robot0:ur5e:elbow',
        #         'robot0:ur5e:wrist_1',
        #         'robot0:ur5e:wrist_2',
        #         'robot0:ur5e:wrist_3',
        #     ],
        #     min_effort=[-150, -150, -150, -150, -150, -150],
        #     max_effort=[150, 150, 150, 150, 150, 150],
        #     null_damp_kv=10,
        # )

        self.controller = OperationalSpaceController(
            model=self.model,
            data=self.data,
            model_names=self.model_names,
            eef_name='eef_site',
            joint_names=[
                'shoulder_pan_joint',
                'shoulder_lift_joint',
                'elbow_joint',
                'wrist_1_joint',
                'wrist_2_joint',
                'wrist_3_joint',
            ],
            actuator_names=[
                'shoulder_pan',
                'shoulder_lift',
                'elbow',
                'wrist_1',
                'wrist_2',
                'wrist_3',
            ],
            min_effort=[-150, -150, -150, -150, -150, -150],
            max_effort=[150, 150, 150, 150, 150, 150],
            target_type=TargetType.POSE,
            kp=200.0,
            ko=200.0,
            kv=50.0,
            vmax_xyz=0.2,
            vmax_abg=1,
            null_damp_kv=10,
        )

        # self.controller = JointEffortController(
        #     model=self.model,
        #     data=self.data,
        #     model_names=self.model_names,
        #     eef_name='robot0:eef_site',
        #     joint_names=[
        #         'robot0:ur5e:shoulder_pan_joint',
        #         'robot0:ur5e:shoulder_lift_joint',
        #         'robot0:ur5e:elbow_joint',
        #         'robot0:ur5e:wrist_1_joint',
        #         'robot0:ur5e:wrist_2_joint',
        #         'robot0:ur5e:wrist_3_joint',
        #     ],
        #     actuator_names=[
        #         'robot0:ur5e:shoulder_pan',
        #         'robot0:ur5e:shoulder_lift',
        #         'robot0:ur5e:elbow',
        #         'robot0:ur5e:wrist_1',
        #         'robot0:ur5e:wrist_2',
        #         'robot0:ur5e:wrist_3',
        #     ],
        #     min_effort=[-150, -150, -150, -150, -150, -150],
        #     max_effort=[150, 150, 150, 150, 150, 150],
        # )

        # self.controller = JointVelocityController(
        #     model=self.model,
        #     data=self.data,
        #     model_names=self.model_names,
        #     eef_name='robot0:eef_site',
        #     joint_names=[
        #         'robot0:ur5e:shoulder_pan_joint',
        #         'robot0:ur5e:shoulder_lift_joint',
        #         'robot0:ur5e:elbow_joint',
        #         'robot0:ur5e:wrist_1_joint',
        #         'robot0:ur5e:wrist_2_joint',
        #         'robot0:ur5e:wrist_3_joint',
        #     ],
        #     actuator_names=[
        #         'robot0:ur5e:shoulder_pan',
        #         'robot0:ur5e:shoulder_lift',
        #         'robot0:ur5e:elbow',
        #         'robot0:ur5e:wrist_1',
        #         'robot0:ur5e:wrist_2',
        #         'robot0:ur5e:wrist_3',
        #     ],
        #     min_effort=[-150, -150, -150, -150, -150, -150],
        #     max_effort=[150, 150, 150, 150, 150, 150],
        #     min_velocity=[-1, -1, -1, -1, -1, -1],
        #     max_velocity=[1, 1, 1, 1, 1, 1],
        #     kp=[100, 100, 100, 100, 100, 100],
        #     ki=0,
        #     kd=0,
        # )

        # self.controller = JointPositionController(
        #     model=self.model,
        #     data=self.data,
        #     model_names=self.model_names,
        #     eef_name='robot0:eef_site',
        #     joint_names=[
        #         'robot0:ur5e:shoulder_pan_joint',
        #         'robot0:ur5e:shoulder_lift_joint',
        #         'robot0:ur5e:elbow_joint',
        #         'robot0:ur5e:wrist_1_joint',
        #         'robot0:ur5e:wrist_2_joint',
        #         'robot0:ur5e:wrist_3_joint',
        #     ],
        #     actuator_names=[
        #         'robot0:ur5e:shoulder_pan',
        #         'robot0:ur5e:shoulder_lift',
        #         'robot0:ur5e:elbow',
        #         'robot0:ur5e:wrist_1',
        #         'robot0:ur5e:wrist_2',
        #         'robot0:ur5e:wrist_3',
        #     ],
        #     min_effort=[-150, -150, -150, -150, -150, -150],
        #     max_effort=[150, 150, 150, 150, 150, 150],
        #     min_position=[-1, -1, -1, -1, -1, -1],
        #     max_position=[1, 1, 1, 1, 1, 1],
        #     kp=[100, 100, 100, 100, 100, 100],
        #     kd=[20, 20, 20, 20, 20, 20],
        # )

        self.init_qpos_config = {
            "shoulder_pan_joint": 0,
            "shoulder_lift_joint": -np.pi / 2.0,
            "elbow_joint": -np.pi / 2.0,
            "wrist_1_joint": -np.pi / 2.0,
            "wrist_2_joint": np.pi / 2.0,
            "wrist_3_joint": 0,
        }
        for joint_name, joint_pos in self.init_qpos_config.items():
            joint_id = self.model_names.joint_name2id[joint_name]
            qpos_id = self.model.jnt_qposadr[joint_id]
            self.init_qpos[qpos_id] = joint_pos

        # self.controller = ComplianceController(
        #     model=self.model,
        #     data=self.data,
        #     model_names=self.model_names,
        #     eef_name='robot0:eef_site',
        #     joint_names=[
        #         'robot0:ur5e:shoulder_pan_joint',
        #         'robot0:ur5e:shoulder_lift_joint',
        #         'robot0:ur5e:elbow_joint',
        #         'robot0:ur5e:wrist_1_joint',
        #         'robot0:ur5e:wrist_2_joint',
        #         'robot0:ur5e:wrist_3_joint',
        #     ],
        #     actuator_names=[
        #         'robot0:ur5e:shoulder_pan',
        #         'robot0:ur5e:shoulder_lift',
        #         'robot0:ur5e:elbow',
        #         'robot0:ur5e:wrist_1',
        #         'robot0:ur5e:wrist_2',
        #         'robot0:ur5e:wrist_3',
        #     ],
        #     min_effort=[-150, -150, -150, -150, -150, -150],
        #     max_effort=[150, 150, 150, 150, 150, 150],
        #     min_velocity=[-1, -1, -1, -1, -1, -1],
        #     max_velocity=[1, 1, 1, 1, 1, 1],
        #     kp_jnt_vel=[100, 100, 100, 100, 100, 100],
        #     ki_jnt_vel=0,
        #     kd_jnt_vel=0,
        #     kp=[10, 10, 10, 10, 10, 10],
        #     ki=[0, 0, 0, 0, 0, 0],
        #     kd=[3, 3, 3, 8, 8, 8],
        #     control_period=self.model.opt.timestep,
        #     ft_sensor_site='robot0:eef_site',
        #     force_sensor_name='robot0:eef_force',
        #     torque_sensor_name='robot0:eef_torque',
        #     subtree_body_name='robot0:ur5e:wrist_3_link',
        #     ft_smoothing_factor=0,
        # )

        self.op_target = None
        self.op_target_reached = False

        home_data = [-0.33357, 0.81420, 0.06377, 0.00005, 0.70715, -0.00005, 0.70707, 0, 0, 0, 0, 0, 0]

        self.history_lock = Lock()
        self.history = [home_data]*2000

        self.plot = plot
        if self.plot:
            self.p = Thread(target=self.runGraph, daemon=True)
            self.p.start()

        self.viewer = viewer.launch_passive(self.model, self.data)
        self.wait_for_viewer()

    def runGraph(self):
        # Create figure for plotting
        fig = plt.figure(figsize=(10,6))
        gs = gridspec.GridSpec(2,14,wspace=3)

        dt = 0.001
        time = dt*np.arange(0, 2000)
        data = []
        lines = []
        labels = ['Position x [m]',
                  'Position y [m]',
                  'Position z [m]',
                  'Quaternion x [m]',
                  'Quaternion y [m]',
                  'Quaternion z [m]',
                  'Quaternion w [m]',
                  'Force x [N]',
                  'Force y [N]',
                  'Force z [N]',
                  'Torque x [Nmm]',
                  'Torque y [Nmm]',
                  'Torque z [Nmm]']

        axes = []
        for i in range(0, 13):
            if i < 7:
                ax = plt.subplot(gs[0, 2 * i:2 * i + 2])
            else:
                ax = plt.subplot(gs[1, 2 * i - 13:2 * i + 2 - 13])
            ax.set_xlabel('Time [s]')
            ax.set_ylabel(labels[i])
            ax.grid()
            axes.append(ax)

        for i in range(7):
            data = [pose[i] for pose in self.history]
            line, = axes[i].plot(time, data)
            lines.append(line)
        for i in range(6):
            data = [wrench[7 + i] for wrench in self.history]
            line, = axes[7+i].plot(time, data)
            lines.append(line)

        def animate(i, plot_data):
            # Update line with new Y values
            with self.history_lock:
                for i in range(7):
                    data = [pose[i] for pose in plot_data]
                    lines[i].set_ydata(data[-2000:])
                    buffer = 0.1*(max(data) - min(data))
                    axes[i].set_ylim(min(data) - buffer, max(data) + buffer)
                for i in range(6):
                    data = [wrench[7 + i] for wrench in plot_data]
                    lines[7 + i].set_ydata(data[-2000:])
                    buffer = 0.1*(max(data) - min(data))
                    axes[7+i].set_ylim(min(data) - buffer, max(data) + buffer)

            return [line for line in lines]

        # Set up plot to call animate() function periodically

        ani = animation.FuncAnimation(fig,
            animate,
            fargs=(self.history, ),
            interval=50,
            blit=True,
            cache_frame_data=False)
        plt.show()

    def wait_for_viewer(self):
        timeout = 5.0
        start_time = time.time()
        while not self.viewer.is_running():
            elapsed = time.time() - start_time
            if elapsed > timeout:
                print("Timeout while waiting for viewer to start.")

    def step(self, action):

        for i in range(self.frame_skip):
            ctrl = self.data.ctrl.copy()

            self.controller.run(
                action,
                ctrl
            )

            self.do_simulation(ctrl, n_frames=1)
        # Update the visualization
        self.viewer.sync()

        with self.history_lock:
            if self.controller.plot_data is not None:
                self.history.append(self.controller.plot_data)
                self.history.pop(0)

        return self.controller.target_reached(), not self.viewer.is_running()

    def reset_model(self):
        qpos = self.init_qpos
        qvel = self.init_qvel
        self.set_state(qpos, qvel)

    def close(self):
        if self.viewer.is_running():
            self.viewer.close()
        if self.plot:
            self.p.join(timeout=5.0)