import os
from typing import Any, Dict, Union

import torch.cuda
import torch.nn as nn
import torch.nn.functional as F

from modelscope.metainfo import Models
from modelscope.models.base import Tensor
from modelscope.models.base.base_torch_model import TorchModel
from modelscope.models.builder import MODELS
from modelscope.models.cv.image_quality_assessment_degradation.degradation_model import \
    DegradationIQA
from modelscope.utils.config import Config
from modelscope.utils.constant import ModelFile, Tasks
from modelscope.utils.logger import get_logger

logger = get_logger()

__all__ = ['ImageQualityAssessmentDegradation']

@MODELS.register_module(
    Tasks.image_quality_assessment_degradation,
    module_name=Models.image_quality_assessment_degradation)
class ImageQualityAssessmentDegradation(TorchModel):
    """
    Its architecture is based on the modified resnet50, output with blur degree, noise degree, compression degree.
    Reference: Rich features for perceptual quality assessment of UGC videos.
    """

    def __init__(self, model_dir: str, *args, **kwargs):
        """initialize the image_quality_assessment_degradation model from the `model_dir` path.

        Args:
            model_dir (str): the model path.

        """
        super().__init__(model_dir, *args, **kwargs)
        self.model_dir = model_dir
        self.sigmoid_layer = nn.Sigmoid()
        self.config = Config.from_file(
            os.path.join(self.model_dir, ModelFile.CONFIGURATION))
        model_path = os.path.join(model_dir, ModelFile.TORCH_MODEL_FILE)

        self.model = DegradationIQA()
        self.model = self._load_pretrained(self.model, model_path)
        self.model.eval()

    def _train_forward(self, input: Tensor,
                       target: Tensor) -> Dict[str, Tensor]:
        losses = dict()
        return losses

    def _inference_forward(self, input: Tensor) -> Dict[str, Tensor]:
        # Todo
        # if img_tensor.shape[2]*img_tensor.shape[3] > 720*1280:
        #     img_tensor = torchvision.transforms.functional.resize(img_tensor, 720)
        preds = self.model(input, require_map=False)
        noise_degree, blur_degree, comp_degree = preds[1][:3]
        noise_degree, blur_degree, comp_degree = self.sigmoid_layer(
            noise_degree), self.sigmoid_layer(blur_degree), self.sigmoid_layer(
                comp_degree)
        if noise_degree > 0.3:
            noise_degree = noise_degree + 0.1
        if noise_degree >= 0.2 and noise_degree <= 0.3:
            noise_degree = (noise_degree - 0.2) * 2 + 0.2
        blur_degree = blur_degree + comp_degree / 2

        return {
            'noise_degree': noise_degree,
            'blur_degree': blur_degree,
            'comp_degree': comp_degree
        }

    def _evaluate_postprocess(self, input: Tensor, item_id: Tensor,
                              distortion_type: Tensor, target: Tensor,
                              **kwargs) -> Dict[str, list]:
        torch.cuda.empty_cache()
        with torch.no_grad():
            preds = self.model(input, require_map=False)
            noise_degree, blur_degree, comp_degree = preds[1][:3]
            noise_degree, blur_degree, comp_degree = self.sigmoid_layer(
                noise_degree), self.sigmoid_layer(
                    blur_degree), self.sigmoid_layer(comp_degree)
            noise_degree, blur_degree, comp_degree = noise_degree.cpu(
            ), blur_degree.cpu(), comp_degree.cpu()
            if noise_degree > 0.3:
                noise_degree = noise_degree + 0.1
            if noise_degree >= 0.2 and noise_degree <= 0.3:
                noise_degree = (noise_degree - 0.2) * 2 + 0.2
            blur_degree = blur_degree + comp_degree / 2
        del input
        target = target.cpu()
        torch.cuda.empty_cache()
        return {
            'item_id': item_id,
            'distortion_type': distortion_type,
            'noise_degree': noise_degree,
            'blur_degree': blur_degree,
            'comp_degree': comp_degree,
            'target': target
        }

    def forward(self, inputs: Dict[str,
                                   Tensor]) -> Dict[str, Union[list, Tensor]]:
        """return the result by the model

        Args:
            inputs (Tensor): the preprocessed data

        Returns:
            Dict[str, Tensor]: results
        """
        if self.training:
            return self._train_forward(**inputs)
        elif 'target' in inputs:
            return self._evaluate_postprocess(**inputs)
        else:
            return self._inference_forward(**inputs)


# dd7e3410-38c0-11e8-9b58-00505601122b
# 6e14ef6b-3281-11e8-9de3-00505601122b

#!/usr/bin/env python3
import numpy as np
import tensorflow as tf

from mnist import MNIST

# The neural network model
class Network(tf.keras.Model):
    def __init__(self, args):
        inputs = tf.keras.layers.Input(shape=[MNIST.H, MNIST.W, MNIST.C])

        # TODO: Add CNN layers specified by `args.cnn`, which contains
        # comma-separated list of the following layers:
        # - `C-filters-kernel_size-stride-padding`: Add a convolutional layer with ReLU
        #   activation and specified number of filters, kernel size, stride and padding.
        # - `CB-filters-kernel_size-stride-padding`: Same as `C`, but use batch normalization.
        #   In detail, start with a convolutional layer without bias and activation,
        #   then add batch normalization layer, and finally ReLU activation.
        # - `M-kernel_size-stride`: Add max pooling with specified size and stride.
        # - `R-[layers]`: Add a residual connection. The `layers` contain a specification
        #   of at least one convolutional layer (but not a recursive residual connection `R`).
        #   The input to the specified layers is then added to their output.
        # - `F`: Flatten inputs. Must appear exactly once in the architecture.
        # - `D-hidden_layer_size`: Add a dense layer with ReLU activation and specified size.
        # Produce the results in variable `hidden`.

        def feed_forward(layer, hidden):
            if layer[0] == 'CB':
                hidden = tf.keras.layers.Conv2D(layer[1], layer[2], strides = layer[3], padding = layer[4], use_bias = False)(hidden)
                hidden = tf.keras.layers.BatchNormalization()(hidden)
                return tf.keras.layers.ReLU()(hidden)
            elif layer[0] == 'C':
                return tf.keras.layers.Conv2D(layer[1], layer[2], strides = layer[3], padding = layer[4], activation = tf.nn.relu)(hidden)
            elif layer[0] == 'M':
                return tf.keras.layers.MaxPool2D(*layer[1:])(hidden)
            elif layer[0] == 'R':
                inpt = hidden
                for l in layer[1:]:
                    hidden = feed_forward(l, hidden)
                return hidden + inpt
            elif layer[0] == 'F':
                return tf.keras.layers.Flatten()(hidden)
            elif layer[0] == 'D':
                return tf.keras.layers.Dense(layer[1], activation = tf.nn.relu)(hidden)

        hidden = inputs
        if args.cnn != None:
            # preprocess args.cnn argument
            in_residual = False
            dsc = list(args.cnn)
            for i in range(len(dsc)):
                if dsc[i] == '[':
                    in_residual = True
                elif dsc[i] == ']':
                    in_residual = False
                elif dsc[i] == ',' and in_residual:
                    dsc[i] = ';'
            changed_argument = "".join(dsc)

            print(changed_argument)

            # parse args.cnn armument into parsed_layers
            parsed_layers = []
            for layer in changed_argument.split(','):
                if layer[0] == 'R':
                    layers = layer[3:][:-1]
                    l = ['R']
                    for layer in layers.split(';'):
                        l.append([int(p) if p.isdigit() else p for p in layer.split('-')])
                    parsed_layers.append(l)
                else:
                    parsed_layers.append([int(p) if p.isdigit() else p for p in layer.split('-')])

            print(parsed_layers)
            for layer in parsed_layers:
                hidden = feed_forward(layer, hidden)

        # Add the final output layer
        outputs = tf.keras.layers.Dense(MNIST.LABELS, activation=tf.nn.softmax)(hidden)

        super().__init__(inputs=inputs, outputs=outputs)

        self.compile(
            optimizer=tf.keras.optimizers.Adam(),
            loss=tf.keras.losses.SparseCategoricalCrossentropy(),
            metrics=[tf.keras.metrics.SparseCategoricalAccuracy(name="accuracy")],
        )

        self.tb_callback=tf.keras.callbacks.TensorBoard(args.logdir, update_freq=1000, profile_batch=1)
        self.tb_callback.on_train_end = lambda *_: None

    def train(self, mnist, args):
        self.fit(
            mnist.train.data["images"], mnist.train.data["labels"],
            batch_size=args.batch_size, epochs=args.epochs,
            validation_data=(mnist.dev.data["images"], mnist.dev.data["labels"]),
            callbacks=[self.tb_callback],
        )

    def test(self, mnist, args):
        test_logs = self.evaluate(mnist.test.data["images"], mnist.test.data["labels"], batch_size=args.batch_size)
        self.tb_callback.on_epoch_end(1, dict(("val_test_" + metric, value) for metric, value in zip(self.metrics_names, test_logs)))
        return test_logs[self.metrics_names.index("accuracy")]

if __name__ == "__main__":
    import argparse
    import datetime
    import os
    import re

    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch_size", default=50, type=int, help="Batch size.")
    parser.add_argument("--cnn", default="C-8-3-5-valid,R-[C-8-3-1-same,CB-8-3-1-same],F,D-50", type=str, help="CNN architecture.")
    parser.add_argument("--epochs", default=30, type=int, help="Number of epochs.")
    parser.add_argument("--recodex", default=False, action="store_true", help="Evaluation in ReCodEx.")
    parser.add_argument("--threads", default=1, type=int, help="Maximum number of threads to use.")
    args = parser.parse_args()

    # Fix random seeds and number of threads
    np.random.seed(42)
    tf.random.set_seed(42)
    if args.recodex:
        tf.keras.utils.get_custom_objects()["glorot_uniform"] = lambda: tf.keras.initializers.glorot_uniform(seed=42)
    tf.config.threading.set_inter_op_parallelism_threads(args.threads)
    tf.config.threading.set_intra_op_parallelism_threads(args.threads)

    # Create logdir name
    args.logdir = os.path.join("logs", "{}-{}-{}".format(
        os.path.basename(__file__),
        datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"),
        ",".join(("{}={}".format(re.sub("(.)[^_]*_?", r"\1", key), value) for key, value in sorted(vars(args).items())))
    ))

    # Load the data
    mnist = MNIST()

    # Create the network and train
    network = Network(args)
    network.train(mnist, args)

    # Compute test set accuracy and print it
    accuracy = network.test(mnist, args)
    with open("mnist_cnn.out", "w") as out_file:
        print("{:.2f}".format(100 * accuracy), file=out_file)


import re
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.utils.markdown import text
from loader import disp
from logger import bot_logger
from settings import URL
from handlers.utils import make_request
from keyboards.callbacks import visit_callback
from keyboards.inline_keyboards import search_schedule, search_user, month
from keyboards.reply_keyboards import statuses_keyboard, services_keyboard, discount_keyboard, continue_cancel_keyboard

class CreateVisit(StatesGroup):
    set_month = State()
    set_master = State()
    set_schedule_day = State()
    set_client = State()
    set_status = State()
    set_service = State()
    set_discount = State()
    request = State()

@disp.callback_query_handler(visit_callback.filter(action="create"))
async def process_create_visit(query: types.CallbackQuery, state: FSMContext):

    await query.message.delete_reply_markup()

    await CreateVisit.set_month.set()

    msg = text(f"Выберите месяц для поиска свободных окон в календаре: ")

    await query.message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=month)

@disp.callback_query_handler(lambda c: re.fullmatch(pattern=r'^month:[\d]{1,2}$', string=c.data), state=CreateVisit.set_month)
async def process_set_month(query: types.CallbackQuery, state: FSMContext) -> types.Message:

    await query.message.delete_reply_markup()

    await CreateVisit.next()

    month = query.data.split(":")[1]

    async with state.proxy() as state_data:
        state_data["month"] = month

    msg = text(f"Выберите мастера:")

    await query.message.answer(text=msg, parse_mode=types.ParseMode.HTML,
                               reply_markup=await search_user(user_type='master'))

@disp.callback_query_handler(lambda c: re.fullmatch(pattern=r'^([\d]{11}#([А-Я]{1}[а-яё]{2,15})\s([А-Я]{1}[а-яё]{2,15}))$',
                                                    string=c.data), state=CreateVisit.set_master)
async def process_set_data_master(query: types.CallbackQuery, state: FSMContext) -> types.Message:
    """Сохраняет данные о выбранном мастере в состояние"""

    await query.message.delete_reply_markup()

    await CreateVisit.next()

    master_phone, master_name = tuple(query.data.split("#"))

    async with state.proxy() as state_data:
        state_data["master_phone"] = master_phone
        state_data["master_name"] = master_name

        msg = text(f"Выберите свободное окно в календаре:")

        await query.message.answer(text=msg, parse_mode=types.ParseMode.HTML,
                                   reply_markup=await search_schedule(master=state_data["master_phone"], month=state_data["month"]))

@disp.callback_query_handler(lambda c: re.fullmatch(
    pattern=r'^((0[1-9]{1}|[1-2]{1}[0-9]{1}|3[0-1]{1})-(0[1-9]{1}|1[1-2]{1})-20[\d]{2} [\d]{2}:[\d]{2}#[\d]{1,})$',
    string=c.data), state=CreateVisit.set_schedule_day)
async def process_set_schedule_day(query: types.CallbackQuery, state: FSMContext):

    await query.message.delete_reply_markup()

    await CreateVisit.next()

    date_time, calendar_id = tuple(query.data.split("#"))

    async with state.proxy() as state_data:
        state_data['date_time'] = date_time
        state_data['calendar_id'] = calendar_id

    msg = "Далее необходимо выбрать клиента:"

    await query.message.answer(text=msg, parse_mode=types.ParseMode.HTML,
                               reply_markup=await search_user(user_type='client'))

@disp.callback_query_handler(lambda c: re.fullmatch(pattern=r'^([\d]{11}#([А-Я]{1}[а-яё]{2,15})\s([А-Я]{1}[а-яё]{2,15}))$',
                                                    string=c.data), state=CreateVisit.set_client)
async def process_set_data_client(query: types.CallbackQuery, state: FSMContext) -> types.Message:
    """Сохраняет данные о выбранном клиенте в состояние"""

    await query.message.delete_reply_markup()

    await CreateVisit.next()

    client_phone, client_name = tuple(query.data.split("#"))

    async with state.proxy() as state_data:
        state_data["client_phone"] = client_phone
        state_data["client_name"] = client_name

        msg = "Выберите тип записи:"

        await query.message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=statuses_keyboard)

@disp.message_handler(state=CreateVisit.set_status)
async def process_set_status(message: types.Message, state: FSMContext) -> types.Message:
    """Сохраняет выбранный статус в состояние"""

    async with state.proxy() as state_data:
        state_data['status'] = message.text

    await CreateVisit.set_service.set()

    msg = "Выберите тип услуги:"

    await message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=services_keyboard)

@disp.message_handler(state=CreateVisit.set_service)
async def process_set_service(message: types.Message, state: FSMContext) -> types.Message:
    """Сохраняет выбранную услугу в состояние"""

    await CreateVisit.next()

    async with state.proxy() as state_data:
        state_data['service'] = message.text

    msg = "Если необходимо, выберите тип скидки:"

    await message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=discount_keyboard)

@disp.message_handler(state=CreateVisit.set_discount)
async def process_set_discount(message: types.Message, state: FSMContext) -> types.Message:
    """Сохраняет выбранную скидку в состояние"""

    await CreateVisit.next()

    async with state.proxy() as state_data:
        if message.text == "Без скидки":
            state_data['discount'] = None
        else:
            state_data['discount'] = message.text

        msg = text("Подтвердите данные:",
                   f"Клиент: {state_data.get('client_name')}",
                   f"Мастер: {state_data.pop('master_name')}",
                   f"Дата и время: {state_data.get('date_time')}",
                   f"Статус: {state_data.get('status')}",
                   f"Услуга: {state_data.get('service')}",
                   f"Скидка: {state_data.get('discount')}",
                   sep='\n')

    await message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=continue_cancel_keyboard)

@disp.message_handler(state=CreateVisit.request)
async def process_request_visit(message: types.Message, state: FSMContext):
    """Добавление новой записи в БД на основе API."""

    bot_logger.info(f"[?] Обработка события от {message.chat.last_name} {message.chat.first_name}")

    async with state.proxy() as state_data:
        client = state_data.pop('client_name')
        date_time = state_data.pop('date_time')

        data = {"calendar": state_data["calendar_id"],
                "status": state_data["status"],
                "service": state_data["service"],
                "client": state_data["client_phone"],
                "discount": state_data['discount']}

        response, status = await make_request(method="POST", url=(URL + 'api/visits/'),
                                              data=data)

        if status == 201 and response:

            bot_logger.info(f"[+] Запись {date_time} {client} успешно создана.")

            msg = text("Запись успешно создана",
                       f"{date_time}",
                       f"{client}",
                       sep='\n')

            await message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=types.ReplyKeyboardRemove())

        elif status >= 400:

            for errors in response.values():
                for error in errors:
                    msg = f"{error}"
                    await message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=types.ReplyKeyboardRemove())

        else:

            bot_logger.info(f"[-] Попытка создать запись оказалась безуспешной [{status}]")
            msg = f"Попытка создать запись оказалась безуспешной [{status}]"
            await message.answer(text=msg, parse_mode=types.ParseMode.HTML, reply_markup=types.ReplyKeyboardRemove())

    await state.finish()


import re

from toolkit import re_search

from . import KafkaPipeline, FilePipeline
from .formatter import BaseAdapter
from .utils import format_price, SafeList

class FinishlinePipelineAdapter(BaseAdapter):

    @staticmethod
    def is_main(image_block):
        return bool(image_block.count("P1"))

    @staticmethod
    def get_type(image_block, regex=re.compile(r"_([A-Z0-9]+?)\?")):
        return re_search(regex, image_block)

    def process_custom(self, spu_id, total_albums, package, item):
        """
        主要用来获取bullet和skus
        :param spu_id:
        :param total_albums:
        :param package:
        :param item:
        :return:
        """
        skus = list()
        description = self.enrich_bullet(spu_id, item["productDescription"], "desc")
        title = self.enrich_bullet(spu_id, item["title"], "title")
        for color_id, color in item["colors"].items():
            color = self.enrich_dimension(spu_id, "color", color_id, color)
            for size in item["sizes"]["sizes_%s"%color_id]:
                id, value = size.popitem()

                size = self.enrich_dimension(spu_id, "size", id, value.replace("unavailable", "").strip())
                package["references"].append(size)
                steady_info = self.enrich_steady_info("", item["model_number"], item["mpn"], item["part_number"],
                              total_albums[color_id.replace("-", "_")], [description, title], size, color)
                prices = SafeList(item["prices"]["prices_%s"%color_id])
                availability = not bool(value.count("unavailable"))
                dyno_info = self.enrich_dyno_info(format_price(prices.pop()), format_price(prices.pop()), availability,
                                                  *("In stock", 5) if availability else ("Out of stock", 0), "USD")
                sku = self.enrich_sku(spu_id, id, item["status_code"], item["meta"]["tags"],
                    item["timestamp"], item["url"], dyno_info, steady_info)
                package["references"].append(sku)
                skus.append(sku)
            package["references"].append(color)
        package["references"].append(description)
        package["references"].append(title)
        return skus

class FinishlineKafkaPipeline(FinishlinePipelineAdapter, KafkaPipeline):
    pass

class FinishlineFilePipeline(FinishlinePipelineAdapter, FilePipeline):
    pass


#!/usr/bin/env python3
"""
Play Nerdle (https://nerdlegame.com)
"""
import json
import logging
from itertools import product
from os import mkdir
from os.path import dirname, join, realpath
from typing import Any, Iterator, List, Optional, Tuple

from .exceptions import CorrectAnswer, OutOfEquations, OutOfGuesses

class NerdleSolver:
    """
    Encapsulates the logic of Nerdle (https://nerdlegame.com)
    """

    # I like using short variable names in my methods.  And I really
    # don't care if I burn a few hundred microseconds interpolating a
    # string I'm not going to emit.

    # pylint: disable="invalid-name"
    # pylint: disable="logging-not-lazy"
    # pylint: disable="logging-fstring-interpolation"
    # pylint: disable="too-many-instance-attributes"

    def __init__(
        self,
        answer: str = "",
        debug: bool = False,
        expression_length: int = 8,
        guesses: int = 6,
        initial_guess: str = "",
        top: int = 5,
        expr_file: str = "",
    ):  # pylint: disable = "too-many-arguments"
        # pylint: disable = "too-many-statements"
        self.debug = debug
        self.log = logging.getLogger(__name__)
        level = logging.INFO
        if self.debug:
            level = logging.DEBUG
        logging.basicConfig(level=level)
        self.log.setLevel(level)
        self.valid_guess: str = ""
        self.guess: str = initial_guess
        self.answer: str = answer
        self.expr_value: int = -1
        self.expression_length: int = expression_length
        self.current_pattern: str = ""
        self.guesses: int = 1
        self.max_guesses: int = guesses
        self.top: int = top
        self.known_character_positions: str = "X" * self.expression_length
        self.position_could_be: List(set[str]) = []
        self.legal_chars: str = "0123456789+-*/="
        # pylint: disable="consider-using-set-comprehension"
        # pylint: disable="unnecessary-comprehension"
        for _ in range(self.expression_length):
            self.position_could_be.append(set([c for c in self.legal_chars]))
        self.not_in_expr: set[str] = set()
        self.in_expr: set[str] = set()
        self.guesses_tried: list[str] = []
        # in self._expr_by_str, a value of None means the expression does not
        # parse.  This lets us cache failed parses as well.
        self._expr_by_str: dict[str, Optional[int]] = {}
        self._expr_by_val: dict[int, List[str]] = {}
        # We only actually use them, though, if we have to build our own
        # list of valid equations
        self._valid_equations: dict[str, int] = {}
        expr_loaded = False
        if not expr_file:
            datadir = realpath(join(dirname(__file__), "static"))
            expr_file = f"{datadir}/equations-{self.expression_length}.json"
        try:
            with open(expr_file, "r", encoding="utf-8") as f:
                _exprs = json.load(f)
                self._valid_equations = _exprs
            expr_loaded = True
        except Exception as exc:  # pylint: disable="broad-except"
            self.log.debug(f"Failed to read expr file {expr_file}: {exc}")
            self.log.debug("Calculating legal expressions")
            self.generate_legal_expressions()
        if not expr_loaded:
            try:
                self.log.debug("Writing expression cache")
                try:
                    mkdir(datadir)
                except FileExistsError:
                    pass
                with open(expr_file, "w", encoding="utf-8") as f:
                    json.dump(self._valid_equations, f)
            except Exception as exc:  # pylint: disable="broad-except"
                self.log.debug(f"Failed to write expr file {expr_file}: {exc}")
        self.remaining_possibilities: list[str] = list(
            self._valid_equations.keys()
        )
        self.remaining_possibilities.sort()  # Initial lexicographic sort
        self._rp_hash = {}
        for rp in self.remaining_possibilities:
            # looking up a hash entry is constant-time.  Looking up in a
            # list is linear.  Validating our equations relies on that
            # lookup.  This actually makes an obvious difference when iterating
            # through all equations.
            self._rp_hash[rp] = True
        self.sort_remainder()
        if not self.guess:
            self.log.debug(
                "Best initial guesses:"
                + f"{self.remaining_possibilities[:self.top]}"
            )

    def play(self) -> None:
        """
        Main loop of the game.  If we get the right answer, it will raise
        CorrectAnswer; if we run out of guesses, OutOfGuesses.  We catch
        the first, report, and return.  We let the second propagate.
        """
        while True:
            self.log.info(f"{self.guesses}/{self.max_guesses}")
            try:
                self.loop_once()
            except CorrectAnswer as exc:
                self.log.info(
                    f"Correct answer: '{exc}' in {self.guesses} guesses"
                )
                return

    def loop_once(self) -> None:
        """
        Single pass through the loop
        """
        self.choose_or_show_next_guess()
        self.get_current_guess()
        self.update_pattern()
        self.guess = ""
        self.valid_guess = ""
        self.restrict_possibilities()
        self.sort_remainder()

    def get_current_guess(self) -> None:
        """
        Get and check a guess
        """
        while not self.valid_guess:
            self.solicit_current_guess()
            self.check_current_guess()

    def solicit_current_guess(self) -> None:
        """
        Interactively get a guess
        """
        if not self.guess:  # Initial guess will do, if we have one.
            self.guess = input("Guess expression > ")

    def check_current_guess(self) -> None:
        """
        Is the supplied guess valid?
        """
        try:
            self.validate_guess(self.guess)
            self.valid_guess = self.guess
        except ValueError as exc:
            self.log.warning(f"'{self.guess}' failed: {exc}")
            self.guess = ""
            self.expr_value = -1

    def parse_expr(self, expr: str) -> int:
        """
        This is the central feature.  Take a string consisting of digits and
        operators (excluding '='), and try to reduce it to an integer.

        If it succeeds, it stores the result in the self._expr_by_str cache,
        and if it fails, it stores None in that cache.
        """
        # Yes, it's a little complicated.
        #
        # pylint: disable = "too-many-statements"
        # pylint: disable = "too-many-branches"
        if expr in self._expr_by_str:
            if self._expr_by_str[expr] is None:
                raise ValueError(f"'{expr}' is known not to parse")
            return self._expr_by_str[expr]
        ttok = []
        curstr = ""
        for c in expr:
            if c.isdigit():
                curstr += c
            else:
                try:
                    # This will catch both leading zeroes and repeated
                    # operators
                    ttok.append(self.check_is_valid_number(curstr))
                except ValueError:
                    # Mark as invalid
                    self.store_expr(expr, None)
                    raise
                curstr = ""
                ttok.append(c)
        if curstr:
            # The last token was a number
            ttok.append(self.check_is_valid_number(curstr))
        # Now ttok contains alternating ints and strings representing
        # operations
        while True:
            if len(ttok) == 1:
                if ttok[0] < 0:
                    raise ValueError("Only non-negative results allowed")
                if ttok[0] != int(ttok[0]):
                    raise ValueError("Only integer expressions allowed")
                ttok = [int(ttok[0])]
                break
            for idx, tok in enumerate(ttok):
                if isinstance(tok, int) or isinstance(tok, float):
                    continue
                if tok in ("*", "/"):  # high-priority operator
                    if tok == "/":
                        # Division by zero can't happen without constant
                        # zero terms, because subtraction is lower-priority.
                        #
                        # However: we CAN have fractional terms, as long
                        # as they become integers by the time we have finished
                        # computing the expression.
                        result = ttok[idx - 1] / ttok[idx + 1]
                    else:
                        result = ttok[idx - 1] * ttok[idx + 1]
                else:
                    if "*" in ttok or "/" in ttok:
                        # We can't parse low-priority operators until
                        # we have exhausted the high-priority operators.
                        continue
                    if tok == "+":
                        result = ttok[idx - 1] + ttok[idx + 1]
                    else:
                        result = ttok[idx - 1] - ttok[idx + 1]
                # Replace the numbers on either side of the operator,
                #  and the operator itself, with the result.  Restart
                #  parsing ttok.
                first = []
                last = []
                if idx > 2:
                    first = ttok[: idx - 1]
                if len(ttok) > idx + 1:
                    last = ttok[idx + 2 :]
                ttok = first + [result] + last
                break  # From the inner for, not the 'while True'
        lhs = ttok[0]
        return lhs

    def validate_guess(self, guess) -> None:
        """
        Only returns if guess is plausible; raises ValueError otherwise
        """
        if guess not in self._rp_hash:
            raise ValueError(f"'{guess}' is not in remaining_possibilities.")
        chars_in_guess = set(guess)
        if chars_in_guess < self.in_expr:
            raise ValueError(
                f"{self.in_expr} are all in the expression, but "
                + f"{self.guess} only has {chars_in_guess}"
            )
        for idx, c in enumerate(guess):
            if c in self.not_in_expr:
                raise ValueError(f"'{c}' is known to not be in expression")
            if c not in self.position_could_be[idx]:
                raise ValueError(
                    f"'{c}' cannot be in position {idx}: "
                    + f"not one of {self.position_could_be[idx]}"
                )
        # Well, it *could* be right.

    def update_pattern(self) -> None:
        """
        If we know the answer, figure out the pattern; if not, request it
        from the user (who's presumably getting it from the game)
        """
        if self.answer:
            self.calculate_pattern()
        else:
            self.solicit_pattern()
        if self.current_pattern == "!" * self.expression_length:
            raise CorrectAnswer(self.guess)
        self.guesses += 1
        if self.guesses > self.max_guesses:
            raise OutOfGuesses()
        self.update_positions()

    def calculate_pattern(self) -> None:
        """
        If we know the answer, generate the response pattern
        """
        pattern = ""
        assert self.answer, "Cannot calculate pattern without the answer"
        for idx, c in enumerate(self.valid_guess):
            self.log.debug(f"considering '{c}' in position {idx}")
            p = self.answer[idx]
            if c == p:
                self.log.debug(f"'{c}' is in position {idx}")
                pattern += "!"
            elif c not in self.answer:
                self.log.debug(f"'{c}' does not appear in expression")
                pattern += "."
            else:
                self.log.debug(
                    f"'{c}' appears in expression, but not in position {idx}"
                )
                pattern += "D"
        # Just like update_positions, we do a second pass to catch multiples
        #  where we already have them all
        for idx, c in enumerate(self.valid_guess):
            if pattern[idx] != "D":
                continue
            actual_count = self.answer.count(c)
            # How many do we have that we know where they are?
            # There's gotta be a better way to do this, but let's get it
            # working first.
            pattern_count = 0
            for a_idx, a_c in enumerate(self.answer):
                if a_c == c:
                    if pattern[a_idx] == "!":
                        pattern_count += 1
            assert pattern_count <= actual_count, f"Overcount of '{c}'"
            # This might not be stable.
            pattern_char = "?"  # Default: we don't know where they all are
            if pattern_count == actual_count:
                self.log.debug(f"Already found all occurrences of '{c}'")
                pattern_char = "."
            else:
                self.log.debug(f"'{c}' appears but position unknown")
            # This should just replace this "D" with a resolved "?" or "."
            pattern = pattern[:idx] + pattern_char + pattern[idx + 1 :]
        self.current_pattern = pattern

    def solicit_pattern(self) -> None:
        """
        Since we don't know the answer, ask about the pattern
        """
        while True:
            response = input("Response pattern > ")
            if len(response) != self.expression_length:
                continue
            rchars = set(response)
            if not rchars <= set("!?."):
                self.log.debug(f"rchars {rchars}; {set('!?.')}")
                continue
            self.current_pattern = response
            break

    def update_positions(self) -> None:
        """
        For each position in the expression, update the set of possible
        characters
        """
        self.guesses_tried.append(self.valid_guess)
        for idx, c in enumerate(self.current_pattern):
            g = self.valid_guess[idx]
            setc = set(g)
            if c == "!":
                self.position_could_be[idx] = setc  # Fixed in place
                self.in_expr |= setc
                self.log.debug(f"position {idx}: '{g}'")
                continue
            if c == "?":
                self.position_could_be[idx] ^= setc
                self.in_expr |= setc
                self.log.debug(f"position {idx}: not '{g}'")
                self.log.debug(f"'{g}' in expression")
        # Now we start over.  This catches the case of "not in word" that
        #  really means "it's a multiple, and you have too many, and it's
        #  not here" because by the time we do this, if we have any
        #  occurrences, they will be in self.in_expr
        for idx, c in enumerate(self.current_pattern):
            if c == ".":
                g = self.valid_guess[idx]
                setc = set(g)
                self.position_could_be[idx] ^= setc
                self.log.debug(f"position {idx}: not '{g}'")
                if g not in self.in_expr:
                    self.log.debug(f"'{g}' not in expression")
                    self.not_in_expr |= setc

    def generate_legal_expressions(self):
        """
        If we did not have an expression file to load, generate legal
        equations.  This takes a while to run.
        """
        eqn: dict[str, bool] = {}
        e_l = self.expression_length
        equals_position = [e_l - 3, e_l - 2]  # Two-digit answers, then one.
        if e_l > 6:
            for i in range(e_l - 3, 3, -1):  # Then longer answers
                equals_position.append(i)
        # '=' cannot be farther to the left than the fourth character, because
        # the first three (at least) must be a OPR b .  Since the string length
        # is even, both sides cannot just be numbers, and the right hand side
        # has to be a non-negative integer without a leading zero (unless it
        # is just zero), so the equal sign can't be at the end.
        #
        # This is dumb, but what we are going to do is brute-force the solution
        # space, with the equals sign in the above place in each place in the
        # sequence based on my intuition that that the given sequence
        # represents the sequence of most likely places for it.
        #
        for eqp in equals_position:
            for exp_tuple in self.generate_expressions(eqp):
                q = "".join(exp_tuple)
                try:
                    _ = int(q)
                    continue
                    # It's an integer constant.  It evaluates to itself,
                    #  and it is not worth storing.
                except ValueError:
                    pass
                try:
                    lhs = self.parse_expr(q)
                    eqn = f"{q}={lhs}"
                    self.store_expr(q, lhs)
                except ValueError as exc:
                    self.log.debug(f"{q} does not parse: {exc}")
                    self.store_expr(q, None)
                    continue
                # Mark the equation as true
                self.store_expr(eqn, lhs)
                # Well, it's true, buuuuut...not valid by our rules.
                # So we don't store it as a valid equation.
                #
                # The LHS *is* permitted to be a lone zero.
                #
                if len(eqn) == self.expression_length:
                    self._valid_equations[eqn] = lhs
                # I thought about storing all the equations that evaluated
                # to invalid answers, but it takes a lot of memory for
                # not much gain.

    def store_expr(self, expr: str, val: Optional[int]):
        """
        Determining whether an expression has a legal evaluation is
        expensive, so we build a cache so we only evaluate each expression
        once.
        """
        if expr in self._expr_by_str:
            oldval = self._expr_by_str[expr]
            if oldval == val:
                return
            raise ValueError(f"Does '{expr}' evaluate to {oldval} or {val}?")
        try:
            # There's no point in storing integer constants: testing equality
            # is faster than looking up the map and then testing equality.
            _ = int(expr)
            return
        except ValueError:
            pass
        self._expr_by_str[expr] = val
        if val is None:
            return
        self.log.debug(f"Stored '{expr}' -> {val}")
        if val not in self._expr_by_val:
            self._expr_by_val[val] = []
        if expr not in self._expr_by_val[val]:
            self._expr_by_val[val].append(expr)

    def generate_expressions(self, e_l: int) -> Iterator[Tuple[Any, ...]]:
        """
        Generate all expressions of length e_l.  Returns an iterator so we
        can chew through, and cache, all the ones that parse to an integer
        value.
        """
        legal_rhs_chars = set("=") ^ set(self.legal_chars)
        digits = set("+-*/") ^ set(legal_rhs_chars)
        assert e_l > 2, "expression length must be at least 3"
        assert (
            e_l < self.expression_length - 1
        ), f"expression length must be at most {self.expression_length - 2}"
        # We know the first and last character are digits
        exp_args = [digits]
        for _ in range(e_l - 2):
            exp_args.append(legal_rhs_chars)
        exp_args.append(digits)
        expr = product(*exp_args)  # itertools is awesome
        return expr

    def check_is_valid_number(self, n: str) -> int:
        """
        Check whether a string is a valid-by-Nerdle-rules number: return
        the corresponding int if so.
        """
        # It's prettier this way.
        # pylint: disable="no-self-use"
        if not n:
            raise ValueError("The empty string is not a number")
        for c in n:
            if not c.isdigit():
                raise ValueError("numbers are made of digits")
        if len(n) > 1:
            if n[0] == "0":
                raise ValueError(
                    "Leading zeroes on multi-digit numbers are not allowed"
                )
        if n == "0":
            raise ValueError("Lone zeroes are not allowed")
        i_n = int(n)
        return i_n

    def restrict_possibilities(self) -> None:
        """
        Iterate through our remaining valid equations, eliminating the ones
        that don't fit the observed facts.
        """
        remainder = []
        rl = len(self.remaining_possibilities)
        for s in self.remaining_possibilities:
            try:
                self.validate_guess(s)
                remainder.append(s)
            except ValueError as exc:
                self.log.debug(f"'{s}' is eliminated: '{exc}'")
        rr = len(remainder)
        if rr == 0:
            raise OutOfEquations("No possible valid equations remain")
        self.log.debug(f"{rl - rr} equations eliminated: {rr} remain")
        remainder.sort()  # Having a stable order makes testing easier
        self.remaining_possibilities = remainder
        self._rp_hash = {}
        for rp in self.remaining_possibilities:
            self._rp_hash[rp] = True

    def sort_remainder(self) -> None:
        """
        Return the "best" remaining possibilities, for some metric of "best"
        """
        # No idea what the best strategy here is.  Let's pick the ones with
        # the most unconfirmed characters?  (Eliminated characters were
        # eliminated from remaining_possibilities already)
        #
        # So, in order: most unconfirmed characters, most characters,
        # mixing and matching from operator precedence, and finally we
        # inherit from the lexigraphic sort.
        self.remaining_possibilities.sort(
            key=lambda e: (
                len(set(e) - self.in_expr),
                len(set(e)),
            ),
            reverse=True,
        )

    def choose_or_show_next_guess(self) -> None:
        """
        We have a sorted list of remaining guesses.  If we know the answer,
        pick the top one.  If we don't, display some to the user to prompt
        the next guess.
        """
        if self.answer:
            if self.guesses == 1:
                if self.guess:
                    self.log.debug(f"Using initial guess '{self.guess}'")
                    if self.guess in self.remaining_possibilities:
                        self.valid_guess = self.guess
                        return
                    self.log.debug(f"Guess '{self.guess}' is invalid")
            self.log.debug("Choosing best guess")
            self.guess = self.remaining_possibilities[0]
            self.valid_guess = self.guess
            return
        if not self.guess:
            best = self.remaining_possibilities[: self.top]
            print(f"Best remaining possibilities: {', '.join(best)}")


from django.shortcuts import render, HttpResponse
from django import forms
import json

# Create your views here.

from graphviz import Digraph

def json_to_image(data=None):
    u = Digraph('unix', format='png',
                node_attr={'color': 'lightblue2', 'style': 'filled'},
                engine='dot')
    colors = {"int": '#d25f76',
              "float": 'orange',
              "list": '#6c42c1',
              "dict": '#ae8f65',
              "str": '#96abff'}

    def get_type(var):
        return type(var).__name__

    def get_edges(treedict, parent=None, Clabel=None):
        for key in treedict.keys():
            # key_type = type(treedict[key])
            if parent:
                u.edge(parent, key, label=get_type(treedict[key]) ,fontcolor=colors[get_type(treedict[key])], color=colors[get_type(treedict[key])])
            if type(treedict[key]) not in [dict, list]:
                pass
                # u.edge(key,get_type(treedict[key]),label=get_type(treedict[key]))
            elif type(treedict[key]) is dict:
                # u.node(key)
                get_edges(treedict[key], parent=key,
                          Clabel=get_type(treedict[key]))
            elif type(treedict[key]) is list:
                # u.edge(parent,key,label="list")
                for i in treedict[key][:1]:
                    if type(i) not in [str, int, float]:
                        get_edges(i, parent=key, Clabel=get_type(i))
                    else:
                        u.edge(key, get_type(i), label=get_type(
                            i),fontcolor=colors[get_type(i)], color=colors[get_type(i)])

    if type(data) is list:
        for i, x in enumerate(data):
            if i < 1:
                get_edges(x,"List")
    elif type(data) is dict:
        main_ = "Response"
        u.node(main_)
        with u.subgraph() as s:
            s.attr(rank="same")
            for i in data.keys():
                s.node(i)
                s.edge(main_, i, label=get_type(data[i]), fontcolor=colors[get_type(data[i])],color=colors[get_type(data[i])])
        get_edges(data)
    return u.pipe()

class front_end(forms.Form):
    response = forms.JSONField()

def check(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.POST.get("response"))
            data = json_to_image(data)
        except Exception as e:
            return HttpResponse(f"Error loading the data,{e}")
        return HttpResponse(data, content_type="image/png")
    else:
        return render(request, 'index.html', {'form': front_end()})


# It's almost https://github.com/ros-drivers/usb_cam/blob/ros2/launch/demo_launch.py

import os
import sys

from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    ld = LaunchDescription()

    package_dir = get_package_share_directory('walker_usb_cameras')

    # color camera
    right_params_path = os.path.join(
        package_dir,
        'config',
        'est_right_params.yaml'
    )

    # infrarred camera
    left_params_path = os.path.join(
        package_dir,
        'config',
        'est_left_params.yaml'
    )

    ld.add_action(Node(
        package='usb_cam',
        executable='usb_cam_node_exe',
        output='screen',
        name='est_right_node',
        namespace='camera/right',
        parameters=[right_params_path]
        ))

    ld.add_action(Node(
        package='usb_cam',
        executable='usb_cam_node_exe',
        output='screen',
        name='est_left_node',
        namespace='camera/left',
        parameters=[left_params_path]
        ))

    return ld


import asyncio

import discord

from src.track.TrackAbstractBase import TrackAbstractBase
from src.GameObject.Player import Player, PlayerActivity
from src.GameObject.Map import Map, SquareType, GetSquareTypeStr
import src.Utilitary as utilis

class CollectTrack(TrackAbstractBase):
    def __init__(self, bot, ctx):
        super().__init__(bot, ctx)
        self.message = None
        self.player = Player(ctx.author.id)
        self.squareType = None
        self.task_id

    async def loop(self):
        try :
            reaction, _ = await self.bot.wait_for('reaction_add', check = lambda r,u: utilis.defaultCheck(r,u,player=self.player,message=self.message), timeout=60*3)
            if str(reaction.emoji) == "✔":
                await self.player.load(self.bot)
                self.squareType = await Map.GetOneSquareType(self.bot, self.player.position)
                if self.squareType in [SquareType.WOOD, SquareType.ROCK, SquareType.METAL]:
                    can_collect, activity = self.player.Can(PlayerActivity.COLLECT)
                    if can_collect:
                        self.player.SetInfo(activity=PlayerActivity.COLLECT, square_type=self.squareType)
                        await self.player.save(self.bot)
                        content = self.message.content
                        content += "\n Tu a commencer a collecter des resources."
                        await self.message.edit(content=content)

                    else:
                        content = self.message.content
                        content += "\nTu es déjà dans une activité, fini celle-ci puis réessaye après"
                        await self.message.edit(content=content)
                else:
                    content = self.message.content
                    content += "\nIl n'y a rien a collecter dans la zone où tu te trouve."
                    await self.message.edit(content=content)
                await asyncio.sleep(10)
        except asyncio.TimeoutError:
            pass
        try:
            await self.message.delete()
        except discord.NotFound:
            pass
        await self.player.DeleteUserTask(self.bot, self.task_id)

    async def load(self, **kwargs):
        await self.player.load(self.bot)
        self.squareType = await Map.GetOneSquareType(self.bot, self.player.position)
        if self.squareType in [SquareType.WOOD, SquareType.ROCK, SquareType.METAL]:
            can_collect, activity = self.player.Can(PlayerActivity.COLLECT)
            square_type_string = GetSquareTypeStr(self.squareType, pre=True)
            if can_collect:
                self.message = await self.ctx.send(f"{self.player.mention()}, veux tu commencer a collecter {square_type_string}?")
                await self.message.add_reaction("✔")
                await self.message.add_reaction("❌")
                self.task_id = self.message.id
                await Player.AddUserTask(self.bot, self.player.id, self.task_id)
                return True
            else:
                self.message = await self.ctx.send(f"{self.player.mention()}, tu es déjà dans une activité, fini celle-ci puis réessaye après")
                return False
        else:
            await self.ctx.send(f"{self.player.mention()}, il n'y a rien a collecter dans la zone où tu te trouve.")
            return False


from statistics import mode
import requests
import cv2
from keras.models import load_model
import numpy as np

from mooddetection.src.utils.datasets import get_labels
from mooddetection.src.utils.inference import detect_faces
from mooddetection.src.utils.inference import draw_text
from mooddetection.src.utils.inference import draw_bounding_box
from mooddetection.src.utils.inference import apply_offsets
from mooddetection.src.utils.inference import load_detection_model
from mooddetection.src.utils.preprocessor import preprocess_input

# parameters for loading data and images
# detection_model_path = '../trained_models/detection_models/haarcascade_frontalface_default.xml'
detection_model_path = './cascades/haarcascade_frontalface_default.xml'
# emotion_model_path = '../trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5'
emotion_model_path = './mooddetection/trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5'
emotion_labels = get_labels('fer2013')

# hyper-parameters for bounding boxes shape
frame_window = 10
emotion_offsets = (20, 40)

# loading models
face_detection = load_detection_model(detection_model_path)
emotion_classifier = load_model(emotion_model_path, compile=False)

# getting input model shapes for inference
emotion_target_size = emotion_classifier.input_shape[1:3]

# starting lists for calculating modes
emotion_window = []

# starting video streaming
cv2.namedWindow('window_frame')
video_capture = cv2.VideoCapture(0)
fps = 20
frame_delay = 1000 // fps
emotion_duration_ms = 1250
emotions = []
max_emotions_len = 2000 // frame_delay
while len(emotions) < max_emotions_len:
    cv2.waitKey(frame_delay)
    bgr_image = video_capture.read()[1]
    gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
    rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
    faces = detect_faces(face_detection, gray_image)

    for face_coordinates in faces:

        x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
        gray_face = gray_image[y1:y2, x1:x2]
        try:
            gray_face = cv2.resize(gray_face, (emotion_target_size))
        except:
            continue

        gray_face = preprocess_input(gray_face, True)
        gray_face = np.expand_dims(gray_face, 0)
        gray_face = np.expand_dims(gray_face, -1)
        emotion_prediction = emotion_classifier.predict(gray_face)
        emotion_probability = np.max(emotion_prediction)
        emotion_label_arg = np.argmax(emotion_prediction)
        emotion_text = emotion_labels[emotion_label_arg]
        emotion_window.append(emotion_text)
        emotions.append(emotion_text)

        if len(emotion_window) > frame_window:
            emotion_window.pop(0)
        try:
            emotion_mode = mode(emotion_window)
        except:
            continue

        if emotion_text == 'angry':
            color = emotion_probability * np.asarray((255, 0, 0))
        elif emotion_text == 'sad':
            color = emotion_probability * np.asarray((0, 0, 255))
        elif emotion_text == 'happy':
            color = emotion_probability * np.asarray((255, 255, 0))
        elif emotion_text == 'surprise':
            color = emotion_probability * np.asarray((0, 255, 255))
        else:
            color = emotion_probability * np.asarray((0, 255, 0))

        color = color.astype(int)
        color = color.tolist()

        draw_bounding_box(face_coordinates, rgb_image, color)
        draw_text(face_coordinates, rgb_image, emotion_mode,
                  color, 0, -45, 1, 1)

    bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
    cv2.imshow('window_frame', bgr_image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
final_emotion = mode(emotions)
print(f"Spotify API for emotion {final_emotion}")
video_capture.release()
cv2.destroyAllWindows()

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer BQCaR_vaYaQ687FxN-j5EfvKujeH-WYR9LEsotQsSliH-X8Tm3xgRnLRA9yTqxwhHRVzSx-IwS1mQAeMs6_qqJc_ORuMb9XExtAZs6bjEuJ7lfnYV1s8AfMPwynTSsIfgRFB35q6DlbyPB6voZUeVcX-54A_hDtGEaA11RFex9yDDMBPuFHddctY6kb0Tac-O2wW0V4tigAeqbn1IvveXhh-g1eSq1Klqx43kS9aWKvA62-TzKVNC8rsAruWBn4K9FeeeM0sjTBePcbd1AHZwGFaivVy1NK5aw'
}

data = '{"device_ids":["10640d809a60bd540378d37abc213d91f52357bc"]}'
response = requests.put('https://api.spotify.com/v1/me/player', headers=headers, data=data)
print(response.content)
params = (
    ('device_id', '10640d809a60bd540378d37abc213d91f52357bc'),
)

if final_emotion == 'happy':
    data = '{"context_uri":"spotify:playlist:1llkez7kiZtBeOw5UjFlJq","offset":{"position":1},"position_ms":0}'
elif final_emotion == 'sad':
    data = '{"context_uri":"spotify:playlist:3m0JCCYnh27D4J13rWBfgs","offset":{"position":1},"position_ms":0}'
elif final_emotion == 'surprise':
    data = '{"context_uri":"spotify:playlist:3ylCiverZxobHBTbMy1dO5","offset":{"position":1},"position_ms":0}'
elif final_emotion == 'angry':
    data = '{"context_uri":"spotify:playlist:0KPEhXA3O9jHFtpd1Ix5OB","offset":{"position":1},"position_ms":0}'
else:
    data = '{"context_uri":"spotify:playlist:0s609Gm5FgpZu6VfJA4I1H","offset":{"position":1},"position_ms":0}'

response = requests.put('https://api.spotify.com/v1/me/player/play', headers=headers, params=params, data=data)


import os
from pathlib import Path

# root package
PACKAGE_NAME = Path().resolve()

MODEL_NAME = 'clf_heart_disease.sav'
MODEL_PATH_INNER = os.path.join("app",'trained-model')
MODEL_PATH = PACKAGE_NAME / MODEL_PATH_INNER

test_dict = {"age":45,
            "sex":1,
            "cp":2,
            "trestbps":145,
            "chol":235,
            "fbs":0,
            "restecg":0,
            "thalach":180,
            "exang":0,
            "oldpeak":2.3,
            "slope":0,
            "ca":0,
            "thal":1}

class Config:
    DEBUG = False
    TESTING = False
    SECRET_KEY = 'things-to-keep-secret'

class DevelopmentConfig(Config):
    DEVELOPMENT = True
    DEBUG = True

class TestConfig(Config):
    TESTING = True


import pickle
import numpy as np
import pandas as pd

data= '10k'

with open('../data/cleaned_data_'+data+'.pickle','rb') as f:
    df = pickle.load(f)

Xs = {lag:np.empty((0,5+2*lag),dtype=np.float32) for lag in range(1,5)}
Ys = {lag:np.empty((0,2),dtype=np.float32) for lag in range(1,5)}

for lag in range(1,5):
    for index,row in df.iterrows():
        T = row['LENGTH']
        if T<=lag: continue
        block = np.tile(np.concatenate(([1],row['ENDPOINTS'])),(T-lag,1))
        for t in range(lag):
            block = np.concatenate((block,row['POLYLINE'][t:t+(T-lag),:]),axis=1)
        Xs[lag] = np.concatenate((X[lag],block),axis=0)
        Ys[lag] = np.concatenate((Y[lag],row['POLYLINE'][lag:T,:]),axis=0)

with open('../data/VAR_blocks'+data+'.pickle','wb') as f:
    pickle.dump((Xs,Ys),f,protocol=pickle.HIGHEST_PROTOCOL)


from django.urls import path
from .views import (
    all_products,
    a_product,
    rings,
    bracelets,
    necklaces,
    earrings
    )

urlpatterns = [
    path('all/', all_products, name='products'),
    path('<int:id>', a_product, name='product'),
    path('rings/', rings, name='ring'),
    path('necklaces/', necklaces, name='necklace'),
    path('bracelets/', bracelets, name='bracelet'),
    path('earrings/', earrings, name='earring'),
]


import math
import argparse

parser = argparse.ArgumentParser(description="Calculation of differentiated payments, Loan Principals, Monthly Payments and Periods \
To do this, the user can run the program specifying interest, number of monthly payments, and loan principal.")

parser.add_argument("--type", choices=["diff", "annuity"], help="You need to choose only one type from the list.")
parser.add_argument("--principal")
parser.add_argument("--payment")
parser.add_argument("--periods")
parser.add_argument("--interest")

args = parser.parse_args()

select = ""

while True:
    if args.type is None:
        print("Incorrect parameters")
        break

    elif args.type == "diff" and args.principal is not None and args.periods is not None and args.interest is not None:
        select = "d"
        break

    elif args.type == "annuity" and (
            args.principal is not None and args.periods is not None and args.interest is not None):
        select = "a"
        break

    elif args.type == "annuity" and (
            args.payment is not None and args.periods is not None and args.interest is not None):
        select = "p"
        break

    elif args.type == "annuity" and (
            args.payment is not None and args.principal is not None and args.interest is not None):
        select = "n"
        break

    else:
        print("Incorrect parameters")
        break

sum = 0

if select == "n":
    # print("Enter the loan principal:")
    loan_principal = int(args.principal)
    # print("Enter the monthly payment:")
    monthly_payment = float(args.payment)
    # print("Enter the loan interest:")
    loan_interest = float(args.interest)

    i = loan_interest / (12 * 100)

    temp_log = monthly_payment / (monthly_payment - i * loan_principal)

    n_months = math.ceil(math.log(temp_log, 1 + i))

    sum = monthly_payment * n_months

    over_payment = int(sum - loan_principal)

    if n_months % 12 == 0:
        years = n_months // 12
        print(f"It will take {years} years to repay this loan!")
    elif n_months % 12 != 0:
        years = n_months // 12
        month = n_months % 12
        if years == 0:
            print(f"It will take {month} months to repay this loan!")
        else:
            print(f"It will take {years} years and {month} months to repay this loan!")

    print(f"Overpayment = {over_payment}")

elif select == "a":
    # print("Enter the loan principal:")
    loan_principal = int(args.principal)
    # print("Enter the number of periods:")
    num_months = int(args.periods)
    # print("Enter the loan interest:")
    loan_interest = float(args.interest)

    i = loan_interest / (12 * 100)
    z = 1 + i
    cus_pow = math.pow(z, num_months)

    monthly_pay = math.ceil(loan_principal * abs((i * cus_pow) / (cus_pow - 1)))

    sum = num_months * monthly_pay

    over_payment = int(sum - loan_principal)

    print(f"Your annuity payment = {monthly_pay}!")

    print(f"Overpayment = {over_payment}")

elif select == "p":
    # print("Enter the annuity payment:")
    montly_payment = float(args.payment)
    # print("Enter the number of periods:")
    num_months = int(args.periods)
    # print("Enter the loan interest:")
    loan_interest = float(args.interest)

    i = loan_interest / (12 * 100)

    z = 1 + i

    cus_pow = math.pow(z, num_months)

    loan_principal = int(montly_payment // (abs((i * cus_pow) / (cus_pow - 1))))

    sum = num_months * montly_payment

    over_payment = int(sum - loan_principal)

    print(f"Your loan principal = {loan_principal}!")

    print(f"Overpayment = {over_payment}")

elif select == "d":
    # print("Enter the loan principal:")
    loan_principal = int(args.principal)
    # print("Enter the number of periods:")
    num_months = int(args.periods)
    # print("Enter the loan interest:")
    loan_interest = float(args.interest)

    p = loan_principal

    n = num_months

    m = n

    i = loan_interest / (12 * 100)

    for m in range(1, num_months + 1):
        d = int(math.ceil((p / n + i * (p - ((p * (m - 1)) / n)))))
        sum = sum + d
        print(f"Month {m}: payment is {d}")

    over_payment = int(sum - p)

    print(f"Overpayment = {over_payment}")


# _*_ encoding: utf-8 _*_
from sklearn.externals import joblib
from sklearn.metrics import mean_squared_error

# from V5.V5_test_One_hot import Preprocessing_One_hot
from v1_v7.V6.V6_new_feature_engineering_One_hot import Preprocessing_One_hot
__author__ = 'wjk'
__date__ = '2019/10/7 9:16'
import pandas as pd
import numpy as np

atom = 'H'
data = pd.read_csv('../test_V6_DDEC_atom_type.csv')
test_num = data.iloc[:,0].value_counts()[atom].tolist()

atom_type_num, bond_type_num, atom_type, bond_type, X_Distance, y = Preprocessing_One_hot(
    'V6_DDEC_atom_type.csv', 'V6_DDEC_bond_type.csv', 'V6_DDEC_charge.csv', 'V6_DDEC_distance.csv', atom, 1000000)

X_test = np.hstack((atom_type[-test_num:-1,:], bond_type[-test_num:-1,:], X_Distance[-test_num:-1,:]))
y_test = y[-test_num:-1,:]

rf= joblib.load(atom+'.model')
print('load finish')

# rf.fit(X, y.ravel())

rf_predict = rf.predict(X_test)
MSE = mean_squared_error(y_test, rf_predict)
RMSE = np.sqrt(mean_squared_error(y_test, rf_predict))

print(atom+'rf_predict回归精度：', RMSE, '/n', MSE)
# prediction_list.extend(rf_predict)
# test_list.extend(y_test)
#
# Y = pd.DataFrame(prediction_list)
# X = pd.DataFrame(test_list)
# pre_result = pd.concat([X, Y], axis=1)
# pre_result.columns = ['test', 'predict']
# pre_result.to_csv(i + '_results.csv', mode='a', header=0, index=False, sep=',')
print('end!')


import torch.nn as nn
import backbones
import detector
from loss_function.dice_Loss import DiceLoss

class SegNet(nn.Module):

    def __init__(self, device, **kwargs):
        super(SegNet, self).__init__()
        self.backbone = backbones.resnet18(**kwargs)
        self.SEGdetector = detector.SEGDetecor()
        self.device = device
        self.criterion = DiceLoss()
        self.to(self.device)

    def forward(self, batch):
        features = self.backbone(batch['image'].cuda())
        pred = self.SEGdetector(features)

        if 'gt' in batch:
            gt = batch['gt'].cuda()
            loss = self.criterion(pred, gt)
            return loss, pred

        return pred

# if __name__=='__main__':
#     model = SegNet()
#     print(model)


#Zachary Blackwell 1941472
import math
# (1) Wall area calculations
wall_height = int(input('Enter wall height (feet):\n'))
wall_width = int(input('Enter wall width (feet):\n'))
wall_area = int(wall_width * wall_height)
print('Wall area:', wall_area, 'square feet')
#(2) Paint gallons calculations
paint_needed = wall_area / 350
print('Paint needed:', '{:.2f}'.format(paint_needed), 'gallons')
#(3) Number of gallon cans needed
cans_needed = math.ceil(paint_needed)
print('Cans needed:', cans_needed, 'can(s)')
#(4) Color of paint
print()
color_paint = input('Choose a color to paint the wall:\n')
color_price = {'red': 35, 'blue': 25, 'green': 23}
total_cost = str(color_price[color_paint] * cans_needed)
print('Cost of purchasing', color_paint, 'paint:','$' + total_cost)


import re
import sys
with open('parse_text.txt') as file:
    inc_zero = sys.argv[1] == '1'
    output = open('output.txt', 'w+')
    output_string = ''

    for line in file.readlines():
        var_name = ''
        write_line = '['
        for indx, word in enumerate(line.split()):
            if re.search('[a-zA-Z]', word):
                var_name = word + ' = '
            elif indx == len(line.split()) - 1 and (not word == '0' or inc_zero):
                write_line += word
            elif not word == '0' or inc_zero:
                write_line += word + ', '

        write_line = var_name + write_line + ']' + '\n'
        output_string += write_line
    output.write(output_string)
    output.close()


templates = {
    "standard": "
item0
\n
item1
",
    "links": "
item0
\n
item1
\nitem3",
    "invite": "
item0
\n
item1
\n
What: item2
\n
When: item3
\n
Where: item4
"
}
def load_template(template):
    if template in templates:
      file = templates[template]
      return file
    else:
      raise TypeError("Invalid template.")


from copy import deepcopy
from itertools import combinations, permutations
# import numpy as np
import re

from collections import defaultdict, Counter

with open('input_file.txt') as inputfile:
    rows = [line.strip().split(',') for line in inputfile]

wire_1 = rows[0]
wire_2 = rows[1]

def man_dist(x,y):
    return sum(abs(a-b) for a,b in zip(x,y))
def intersection(list_a, list_b):
    return [ e for e in list_a if e in list_b ]

def get_locations(path):
    locs = []
    cur = (0, 0)

    for p in path:
        d = p[0]
        amount = int(p[1:])

        if d == 'R':
            for _ in range(amount):
                locs.append((cur[0] + _, cur[1]))
            cur = (cur[0]+amount, cur[1])
        elif d == 'L':
            for _ in range(amount):
                locs.append((cur[0] - _, cur[1]))
            cur = (cur[0]-amount, cur[1])
        elif d == 'U':
            for _ in range(amount):
                locs.append((cur[0], cur[1] + _))
            cur = (cur[0], cur[1]+amount)
        elif d == 'D':
            for _ in range(amount):
                locs.append((cur[0], cur[1] - _))
            cur = (cur[0], cur[1]-amount)

        # print(locs)

    return locs

loc_1 = get_locations(wire_1)
print("got loc1")
loc_2 = get_locations(wire_2)
print("got loc2")
insect = list(set(loc_1) & set(loc_2))
if (0, 0) in insect:
    insect.remove((0, 0))

min_dist = 99999999999999
for item in insect:
    dist = man_dist((0, 0), item)
    if dist < min_dist:
        min_dist = dist

print(min_dist)

def get_locations_2(path):
    locs = []
    cur = (0, 0)
    count = 0
    counts = {}

    for p in path:
        d = p[0]
        amount = int(p[1:])

        if d == 'R':
            for _ in range(1, amount+1):
                locs.append((cur[0] + _, cur[1]))
                count += 1
                counts[(cur[0] + _, cur[1])] = count
            cur = (cur[0]+amount, cur[1])
        elif d == 'L':
            for _ in range(1, amount+1):
                locs.append((cur[0] - _, cur[1]))
                count += 1
                counts[(cur[0] - _, cur[1])] = count
            cur = (cur[0]-amount, cur[1])
        elif d == 'U':
            for _ in range(1, amount+1):
                locs.append((cur[0], cur[1] + _))
                count += 1
                counts[(cur[0], cur[1] + _)] = count
            cur = (cur[0], cur[1]+amount)
        elif d == 'D':
            for _ in range(1, amount+1):
                locs.append((cur[0], cur[1] - _))
                count += 1
                counts[(cur[0], cur[1] - _)] = count
            cur = (cur[0], cur[1]-amount)

    return counts

min_dist_2 = 999999999999999999
counts_1 = get_locations_2(wire_1)
counts_2 = get_locations_2(wire_2)
for item in insect:
    if counts_1[item] + counts_2[item] < min_dist_2:
        min_dist_2 = counts_1[item] + counts_2[item]

print(min_dist_2)
import pdb; pdb.set_trace()  # noqa


import tkinter as tk
from tkinter import  ttk
import os
from tkinter import messagebox
from functools import partial
import csv
def run():

  from logic.solon_insert import insert_data
  from logic.solon_load import load_csv, read_data
  from logic.solon_edit import edit_data
  from logic.solon_delete import delete_data
  from ui.solon_show_data import show_data
  from ui.start_search import start_search
  from logic.timestamp import get_timestamp, saved_time

  # File Paths that are needed
  # Get the current directory of your script
  current_dir = os.path.dirname(__file__)

  # Navigate up one level to the parent directory, which is 'solon search'
  parent_dir = os.path.dirname(current_dir)

  # Define the path to the 'info.csv' file in the 'data' folder
  INPATH = os.path.join(parent_dir, 'data', 'input_data.csv')
  INFOPATH = os.path.join(parent_dir, 'data', 'info_data.csv')
  OUTPATH = os.path.join(parent_dir, 'data', 'output_data.csv')
  KATPATH = os.path.join(parent_dir, 'data', 'dikastiria.csv')

  # List of court options
  kat_options = []
  with open(KATPATH, 'r', encoding='utf-8') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
      kat_options.append(row[0])

  # Function to show the entry fields for data insertion
  def show_fields(type, tree):

    if type =="edit" and not(tree.selection()):
      messagebox.showerror("ΣΦΑΛΜΑ", "ΠΑΡΑΚΑΛΩ ΕΠΙΛΕΞΤΕ ΓΡΑΜΜΗ ΓΙΑ ΕΠΕΞΕΡΓΑΣΙΑ")
      return
    # Entry Window
    entry_window = tk.Toplevel(root)
    if type == "insert":
      entry_window.title("ΕΙΣΑΓΩΓΗ ΔΕΔΟΜΕΝΩΝ")
    elif type == "edit":
      entry_window.title("ΕΠΕΞΕΡΓΑΣΙΑ ΔΕΔΟΜΕΝΩΝ")
    root_width = root.winfo_screenwidth()
    root_height = root.winfo_height()

    # entry_window.iconphoto(True, icon)

    entry_window_width = 500
    entry_window_height = 250

    # Center the progress window on top of the root window
    x = (root_width - entry_window_width) // 2
    y = (root_height - entry_window_height) // 2
    entry_window.geometry(f"{entry_window_width}x{entry_window_height}+{x}+{y}")

    entry_frame = ttk.Frame(entry_window)
    entry_frame.pack()

    # Focus on the window
    entry_frame.focus_set()

    # Entry Fields for Data Insertion
    kat_label = ttk.Label(entry_frame, text="ΔΙΚΑΣΤΗΡΙΟ:", font = FONT_OPTIONS)
    kat_label.grid(row = 0, column = 0, padx = 10, pady = 5, sticky = 'w')
    kat_combobox = ttk.Combobox(entry_frame, values = kat_options, state="readonly", font = FONT_OPTIONS)
    kat_combobox.grid(row = 0, column = 1, columnspan = 2, padx = 10, pady = 5)

    gak_label = ttk.Label(entry_frame, text="ΓΑΚ:", font = FONT_OPTIONS)
    gak_label.grid(row = 1, column = 0, padx = 10, pady = 5, sticky = 'w')
    gak_entry = ttk.Entry(entry_frame, font = FONT_OPTIONS)
    gak_entry.grid(row = 1, column = 1, columnspan = 2, padx = 10, pady = 5)

    year_label = ttk.Label(entry_frame, text="ΕΤΟΣ:", font = FONT_OPTIONS)
    year_label.grid(row = 2, column = 0, padx = 10, pady = 5, sticky = 'w')
    year_entry = ttk.Entry(entry_frame, font = FONT_OPTIONS)
    year_entry.grid(row = 2, column = 1, columnspan = 2, padx = 10, pady = 5)

    customer_label = ttk.Label(entry_frame, text="ΠΕΛΑΤΗΣ: ", font = FONT_OPTIONS)
    customer_label.grid(row = 3, column = 0, padx = 10, pady = 5, sticky = 'w')
    customer_entry = ttk.Entry(entry_frame, font = FONT_OPTIONS)
    customer_entry.grid(row = 3, column = 1, padx = 10, pady = 5)

    antidikos_label = ttk.Label(entry_frame, text="ΑΝΤΙΔΙΚΟΣ: ", font = FONT_OPTIONS)
    antidikos_label.grid(row = 4, column = 0, padx = 10, pady = 5, sticky = 'w')
    antidikos_entry = ttk.Entry(entry_frame, font = FONT_OPTIONS)
    antidikos_entry.grid(row = 4, column = 1, padx = 10, pady = 5)

    comment_label = ttk.Label(entry_frame, text="ΣΧΟΛΙΑ: ", font = FONT_OPTIONS)
    comment_label.grid(row = 5, column = 0, padx = 10, pady = 5, sticky = 'w')
    comment_entry = ttk.Entry(entry_frame, font = FONT_OPTIONS)
    comment_entry.grid(row = 5, column = 1, padx = 10, pady = 5)

    if type == "insert":

      insert_button = ttk.Button(entry_frame, text="ΕΙΣΑΓΩΓΗ", style = "Insert.TButton", command= partial(insert_data, kat_combobox, gak_entry, year_entry, customer_entry, antidikos_entry, comment_entry, tree))
      insert_button.grid(row = 6, column = 0, columnspan = 2, padx = 10, pady = 5)

    elif type == "edit":
      try:
        # get the selected row
        row_to_edit = tree.selection()
        index = tree.index(row_to_edit)

        # read the data that is needed
        input_data = read_data(INPATH)
        info_data = read_data(INFOPATH)

        kat = input_data[index][0]
        gak = input_data[index][1]
        year = input_data[index][2]
        customer = info_data[index][0]
        antidikos = info_data[index][1]
        comment = info_data[index][2]

        # fill out the fields with the values
        kat_combobox.set(kat)
        gak_entry.insert(0, gak)
        year_entry.insert(0, year)
        customer_entry.insert(0, customer)
        antidikos_entry.insert(0, antidikos)
        comment_entry.insert(0, comment)

        save_edit_button = ttk.Button(entry_frame, text="ΑΠΟΘΗΚΕΥΣΗ", style = "Edit.TButton", command = partial(edit_data, entry_window, index, kat, gak, year, kat_combobox, gak_entry, year_entry, customer_entry, antidikos_entry, comment_entry, tree))
        save_edit_button.grid(row = 6, column = 0, columnspan = 2, padx = 10, pady = 5)

      except Exception as E:
        print(E)

  # Layout-----------------------------

  # Define custom colors using hexadecimal color codes - these are not actively used except
  # for the background color for the root window which is light gray by default
  BACKGROUND_COLOR = "#F0F0F0"  # Light Gray
  # PRIMARY_COLOR = "#007ACC"  # Blue
  # SECONDARY_COLOR = "#FFA500"  # Orange

  # Define Font options for the Text
  FONT_OPTIONS = ("Arial", 13)

  root = tk.Tk()
  root.title("Solon Search")
  # Configure the root window's background color
  root.configure(background=BACKGROUND_COLOR)

  # Load the icon file
  # icon = tk.PhotoImage(file = "./test.png")
  # root.iconphoto(True, icon)

  # Get the screen width and height
  screen_width = root.winfo_screenwidth()
  screen_height = root.winfo_screenheight()

  window_width = 1100
  window_height = 650

  # Calculate the x and y coordinates for the center of the screen
  x = (screen_width - window_width) // 2
  y = (screen_height - window_height) // 2

  # Set the geometry of the root window to open it in the center of the screen
  root.geometry(f"{window_width}x{window_height}+{x}+{y}")

  global timestamp_label, search_time_label, total_searches_label

  # Treeview to display CSV data

  # Also includes Button Frame and deselect function so
  # user can deselect rows
  # def tree(root, timestamp_label, search_time_label, total_searches_label):
  def tree(root):
    tree_style = ttk.Style()
    tree_style.configure("Custom.Treeview", rowheight = 30, font = FONT_OPTIONS)
    tree = ttk.Treeview(root, columns=("Kat", "Gak", "Year", "Customer", "Antidikos", "Comment", "Result"), show="headings", style = "Custom.Treeview")

    # Set column widths (adjust these values as needed)
    tree.column("#1", width=220)  # First column
    tree.column("#2", width=60)  # Second column
    tree.column("#3", width=60)   # Third column
    tree.column("#4", width=170)   # Third column
    tree.column("#5", width=170)   # Third column
    tree.column("#6", width=150)   # Third column
    tree.column("#7", width=250)  # Seventh column

    # Function to change the font of Treeview headings
    def change_heading_font(font):
        style = ttk.Style()
        style.configure("Treeview.Heading", font=font)

    # Apply the custom font to the headings
    change_heading_font(("open sans", 14))

    tree.heading("Kat", text="ΔΙΚΑΣΤΗΡΙΟ", anchor = "w")
    tree.heading("Gak", text="ΓΑΚ", anchor = "w")
    tree.heading("Year", text="ΕΤΟΣ", anchor = "w")
    tree.heading("Customer", text="ΠΕΛΑΤΗΣ", anchor = 'w')
    tree.heading("Antidikos", text="ΑΝΤΙΔΙΚΟΣ", anchor = 'w')
    tree.heading("Comment", text="ΣΧΟΛΙΑ", anchor = 'w')
    tree.heading("Result", text="ΑΠΟΦΑΣΗ", anchor = "w")

    # Create a vertical scrollbar
    vscrollbar = ttk.Scrollbar(root, orient="vertical", command=tree.yview)
    vscrollbar.pack(side="right", fill="y")

    # Configure the Treeview to use the vertical scrollbar
    tree.configure(yscrollcommand=vscrollbar.set)

    data = load_csv()
    show_data(data, tree)

    tree.pack()
    # Button Frame
    def button_frame(root):
      button_frame = ttk.Frame(root)
      button_frame.pack(side='top', pady = 20)

      # Button to Insert Data
      insbutton_style = ttk.Style()
      insbutton_style.configure("Insert.TButton", font = (FONT_OPTIONS), background = 'green', foreground='black')
      insbutton = ttk.Button(button_frame, text="ΕΙΣΑΓΩΓΗ ΔΕΔΟΜΕΝΩΝ", style = "Insert.TButton", command= partial(show_fields, "insert", tree))
      insbutton.grid(row = 0, column = 0, padx = 10, pady = 5)

      # Edit Button
      editbutton_style = ttk.Style()
      editbutton_style.configure("Edit.TButton", font = (FONT_OPTIONS), background = 'orange', foreground = 'black')
      edit_button = ttk.Button(button_frame, text = 'ΕΠΕΞΕΡΓΑΣΙΑ', style = "Edit.TButton", command = partial(show_fields, "edit", tree))
      edit_button.grid(row = 0, column = 1, padx = 10, pady = 5)

      # Delete Button
      delbutton_style = ttk.Style()
      delbutton_style.configure("Delete.TButton", font = (FONT_OPTIONS), background = 'red', foreground = 'black')
      delete_button = ttk.Button(button_frame, text="ΔΙΑΓΡΑΦΗ ΔΕΔΟΜΕΝΩΝ", style = "Delete.TButton", command = partial(delete_data, tree, root))
      # delete_button = ttk.Button(button_frame, text="ΔΙΑΓΡΑΦΗ ΔΕΔΟΜΕΝΩΝ", style = "Delete.TButton", command = partial(show_fields,"delete", tree))
      delete_button.grid(row = 0, column = 2, padx = 10, pady = 5)

      # Search Button
      searchbutton_style = ttk.Style()
      searchbutton_style.configure("Search.TButton", font = (FONT_OPTIONS), background = 'blue', foreground = 'black')
      global timestamp_label, search_time_label, total_searches_label
      search_button = ttk.Button(button_frame, text="ΑΝΑΖΗΤΗΣΗ", style = "Search.TButton", command = partial(start_search, root, tree, timestamp_label, search_time_label, total_searches_label))
      search_button.grid(row = 0, column = 3, padx = 10, pady = 5)
      return edit_button, delete_button

    edit_button, delete_button = button_frame(root)
    # Function to unselect the currently selected row in the Treeview
    def unselect_tree_row(event):
      # not clicked on delete button
      if event.widget == delete_button:
          return
      # not clicked on edit button
      elif event.widget == edit_button:
          return
      # not clicked on other point in tree
      elif event.widget != tree:
        tree.selection_remove(tree.selection())
    # Bind the click event on the root window to unselect the Treeview row
    root.bind("<Button-1>", unselect_tree_row)

  # Set up the time Frame
  def time_frame(root):

    time_frame = ttk.Frame(root)
    # time_frame.pack(side = 'top', pady = 10)

    timestamp, total_searches = get_timestamp()
    hours, minutes = saved_time(total_searches[0])
    global timestamp_label, search_time_label, total_searches_label
    timestamp_label = tk.Label(time_frame, text="ΤΕΛΕΥΤΑΙΑ ΑΝΑΖΗΤΗΣΗ: " + timestamp[0], font = FONT_OPTIONS)
    timestamp_label.grid(row = 0, pady = 0)
    search_time_label = tk.Label(time_frame, text = "ΕΧΕΤΕ ΓΛΥΤΩΣΕΙ ΣΥΝΟΛΙΚΑ " + hours + " ΩΡΕΣ ΚΑΙ " + minutes + " ΛΕΠΤΑ ΑΝΑΖΗΤΗΣΗΣ!", font = ("open sans", 9))
    search_time_label.grid(row = 1, pady = 0)
    total_searches_label = tk.Label(time_frame, text = "ΕΧΕΤΕ ΠΡΑΓΜΑΤΟΠΟΙΗΣΕΙ ΣΥΝΟΛΙΚΑ " + total_searches[0] + " ΑΝΑΖΗΤΗΣΕΙΣ", font = ("open sans", 9))
    total_searches_label.grid(row = 2, pady = 0)
    return time_frame

  # Set up the adbox
  def adbox_frame(root):
    adbox_frame = ttk.Frame(root)
    adbox_frame.pack(side = 'bottom', pady = 20)

    adbox_label = tk.Label(adbox_frame, text = "Νικόλαος Ραζέλος - Πληροφορική για δικηγόρους", font = FONT_OPTIONS)
    adbox_label2 = tk.Label(adbox_frame, text = "example@email.com", font = FONT_OPTIONS)
    adbox_label3 = tk.Label(adbox_frame, text = "694 3755 032", font = FONT_OPTIONS)
    adbox_label.grid(row = 0, column = 0, padx = 10, pady = 5)
    adbox_label2.grid(row = 1, column = 0, padx = 10, pady = 5)
    adbox_label3.grid(row = 2, column = 0, padx = 10, pady = 5)

  timeframe = time_frame(root)
  tree(root)
  timeframe.pack(side = 'top', pady = 10)
  adbox_frame(root)

  root.mainloop()

# run()


class Solution:
    def findLength(self, nums1, nums2):
        x, y = len(nums1), len(nums2)
        dp = [[0]*(y+1) for _ in range(x+1)]
        ans = 0
        for i in range(1, x+1):
            for j in range(1, y+1):
                if nums1[i-1]==nums2[j-1]:
                    dp[i][j] = dp[i-1][j-1]+1
                    ans = max(ans, dp[i][j])
                else:
                    dp[i][j] = 0
        return ans


from django.db import models

# фотография для слайдера

class Slider(models.Model):

    name = models.CharField(max_length=50, blank=True, null=True, verbose_name="Ady")
    image = models.ImageField(upload_to='slider', blank=True, null=True, verbose_name='Slider')
    is_active = models.BooleanField(default=False)

    class Meta:
        verbose_name = 'Slider'
        verbose_name_plural = 'Sliderler'

    def __str__(self):
        return self.name

# категория

class Category(models.Model):

    name = models.CharField(max_length=100, blank=True, null=True, verbose_name="Ady")
    desc = models.CharField(max_length=255, blank=True, null=True, verbose_name="Beýany")
    image = models.ImageField(upload_to='category', blank=True, null=True, verbose_name='Kategoriyalar')

    class Meta:
        verbose_name = 'Kategoryia'
        verbose_name_plural = 'Kategoriyalar'

    def __str__(self):
        return self.name

# Продукт

class Product(models.Model):

    category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name='Haysy kategoriya degishliligi')
    sale = models.BooleanField(default=False)
    new =  models.BooleanField(default=False)

    name = models.CharField(max_length=255, blank=True, null=True)
    title = models.TextField(blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    main_image = models.ImageField(upload_to='product', blank=True, null=True, verbose_name='Esasy Haryt')
    second_image = models.ImageField(upload_to='product', blank=True, null=True, verbose_name='ikinji Haryt')
    three_image = models.ImageField(upload_to='product', blank=True, null=True, verbose_name='uchunji Haryt')

# первая таблица о продукте

    packing = models.CharField(max_length=255, blank=True, null=True, verbose_name='Gaplamak')
    box_weight = models.CharField(max_length=255, blank=True, null=True, verbose_name='Gutynyň agramy')
    quantity_in_the_box = models.CharField(max_length=255, blank=True, null=True, verbose_name='Bir gutydaky mukdar')
    shelf_life = models.CharField(max_length=255, blank=True, null=True, verbose_name='Ýaramlylyk möhleti')

# вторая  таблица о продукте

    protein = models.CharField(max_length=255, blank=True, null=True, verbose_name='Belok')
    fat = models.CharField(max_length=255, blank=True, null=True, verbose_name='Yag')
    carbohydrate = models.CharField(max_length=255, blank=True, null=True, verbose_name='Uglerod')
    the_energy_value = models.CharField(max_length=255, blank=True, null=True, verbose_name='Kuwwatlylyk gymmaty')
    weight = models.CharField(max_length=255, blank=True, null=True, verbose_name='Agramy')

    class Meta:
        verbose_name = 'Haryt'
        verbose_name_plural = 'Harytlar'

    def __str__(self):
        return self.name

# форма для отправки

class ContactUs(models.Model):

    email = models.EmailField(max_length=50, verbose_name="Email poçtasy")
    name = models.CharField(max_length=100, verbose_name="Ady")
    phone = models.CharField(max_length=50, verbose_name="El telefony")
    message = models.TextField(verbose_name="SMS")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

    class Meta:
        ordering = ("-created_at",)

    class Meta:
        verbose_name = 'SMS'
        verbose_name_plural = 'SMSLER'

# фотографии о компании

class Galleria(models.Model):

    name = models.CharField(max_length=255, blank=True, null=True, verbose_name="Ady")
    image = models.ImageField(upload_to='galleria', blank=True, null=True, verbose_name='Gallereýa üçin surat')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Galleria'
        verbose_name_plural = 'Galleria üçin suratlar'

# о компании

class About_us(models.Model):

    title = models.CharField(max_length=255, verbose_name="Beýan")
    desc = models.TextField(verbose_name="Kompaniýa barada")
    main_image = models.ImageField(upload_to='about_us', blank=True, null=True, verbose_name='Kompaniýa barada banner')
    second_image = models.ImageField(upload_to='about_us', blank=True, null=True, verbose_name='Kompaniýa barada surat')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Kompaniýa barada'
        verbose_name_plural = 'Kompaniýa barada maglumatlar'

# контакты

class Contacts(models.Model):

    map = models.TextField( blank=True, null=True, verbose_name="Kartada ýerleşýän ýeriňiz")
    phone = models.CharField( blank=True, null=True, max_length=50, verbose_name='Telefon belgi')
    email = models.EmailField( blank=True, null=True, verbose_name='Elektron poçtaňyz')
    address = models.CharField( blank=True, null=True, max_length=255, verbose_name='Adress')
    header_logo = models.ImageField( blank=True, null=True, upload_to='header_logo', verbose_name='Ýokardaky logo')
    footer_logo = models.ImageField( blank=True, null=True, upload_to='footer_logo', verbose_name='Aşakdaky logo')
    mini_desc = models.CharField( blank=True, null=True, max_length=255, verbose_name='Gysgaça beýan')
    gmail = models.CharField( blank=True, null=True, max_length=255, verbose_name='Gmail')
    instagram = models.CharField( blank=True, null=True, max_length=255, verbose_name='Instagram')
    mail = models.CharField(  blank=True, null=True, max_length=255, verbose_name='Mail')
    tiktok = models.CharField( blank=True, null=True, max_length=255, verbose_name='TikTok')

    def __str__(self):
        return self.address

    class Meta:
        verbose_name = 'Kontakt'
        verbose_name_plural = 'Kontaktlar'


number = int(input())

left_sum = 0
right_sum = 0
diff = 0
for num in range(number):
   current_sum = int(input())
   left_sum += current_sum
for num in range(number):
    current_sum = int(input())
    right_sum += current_sum

if left_sum == right_sum:
    print(f"Yes, sum = {left_sum}")
elif left_sum != right_sum:
    diff = abs(right_sum - left_sum)
    print(f"No, diff = {diff}")


# Find All Anagrams in a String
# Given two strings s and p, return an array of all the start indices of p's anagrams in s.
# You may return the answer in any order.

from collections import defaultdict

def find_anagrams(a, b):
    char_map = defaultdict(int)

    # add all characters in b to the char_map, which we will use for comparison
    for c in b:
        char_map[c] += 1

    results = []
    for i in range(len(a)):
        c = a[i] # get char in a

        # remove characters from the char_map as we are sliding it along (sliding window)
        # c_old is the char that is beyond the length of b, so we remove that from char_map by increasing the count by 1
        if i >= len(b):
            c_old = a[i - len(b)]
            char_map[c_old] += 1
            if char_map[c_old] == 0:
                del char_map[c_old]

        # we add characters to char_map by decreasing the count by 1,
        # so a negative 1 for character 'd' means we seen 'd' in a but it is not in original char_map
        # if char_map of that character is equal to zero then we delete from char_map
        char_map[c] -= 1
        if char_map[c] == 0:
            del char_map[c]

        # if length of char_map is equal to zero, we append the starting index of the anagram to results
        if i + 1 >= len(b) and len(char_map) == 0:
            results.append(i - len(b) + 1)

    return results

# my solution
def find_permutation(str1, pattern):
  start = 0
  char_map = {}
  result = []

  # add all characters in pattern to the hash map
  for s in pattern:
    char_map[s] = char_map.get(s, 0) + 1

  for end in range(len(str1)):
    right_char = str1[end]
    # for every character seen in str1 we decrement the count in the hash map
    char_map[right_char] = char_map.get(right_char, 0) - 1
    if char_map[right_char] == 0:
      del char_map[right_char]

    # slide the window when the number of characters in our sliding window has hit the length limit
    if end >= len(pattern) - 1:
      # if length of character map is zero then we have matched all the characters in the pattern
      if len(char_map) == 0:
        result.append(start)
      # begin to slide the window by taking note of the character exiting the window
      start_char = str1[start]
      char_map[start_char] = char_map.get(start_char, 0) + 1 # add back the count to the char map when sliding out
      if char_map[start_char] == 0:
        del char_map[start_char]
      start += 1 # slide the window ahead

  return result

print(find_anagrams('acdbacdacb', 'abc'))
# [3, 7]

print(find_permutation('acdbacdacb', 'abc'))
# [3, 7]


#!/usr/bin/python3

import numpy as np

import tf
import rospy
import std_msgs

from tf.transformations import quaternion_multiply
from geometry_msgs.msg import PoseStamped, PoseArray, Vector3, Pose
from visualization_msgs.msg import Marker, MarkerArray
from pose_selector.srv import GetPoses

'''
Query poses from pose selector and publish them as markers in rviz for visualisation purposes
'''

class PoseSelectorVisualizer:
    def __init__(self, wait_for_pose_selector_srv=True):
        self.color = rospy.get_param('~object_color_rgba', [0,0,0,0])
        self.mesh_urls = rospy.get_param('~meshes')
        self.objects_mesh_publisher = rospy.Publisher('pose_selector_objects', MarkerArray, queue_size=1, latch=True)

        #Wait for pose_selector_get_all_poses service to be up and available
        rospy.loginfo(f'Waiting for pose selector services')
        if wait_for_pose_selector_srv:
            rospy.wait_for_service('/pose_selector_get_all_service', 10.0)
        self.pose_selector_get_all_poses_srv = rospy.ServiceProxy('/pose_selector_get_all_service', GetPoses)

        rospy.loginfo('Found pose selector services')
        rospy.sleep(0.5)
        rospy.loginfo('Pose selector visualizer node started')

    def make_mesh_marker_msg(self, mesh_path, mesh_pose, mesh_scale=[1,1,1], id=1, color=[0,0,0,0]):
        assert isinstance(mesh_pose, PoseStamped)
        mesh_marker_msg = Marker()
        mesh_marker_msg.id = id
        # mesh_marker_msg.lifetime = rospy.Duration(3.0)
        mesh_marker_msg.ns = 'object'
        mesh_marker_msg.header.frame_id = mesh_pose.header.frame_id
        mesh_marker_msg.pose = mesh_pose.pose
        mesh_marker_msg.type = Marker.MESH_RESOURCE
        mesh_marker_msg.mesh_use_embedded_materials = True
        mesh_marker_msg.scale = Vector3(mesh_scale[0], mesh_scale[1], mesh_scale[2])
        # set rgba to 0 to allow mesh_use_embedded_materials to work
        mesh_marker_msg.color = std_msgs.msg.ColorRGBA(*color)
        mesh_marker_msg.mesh_resource = mesh_path
        return mesh_marker_msg

    def make_obj_marker_msg(self, object_name, mesh_pose, id=1):
        assert isinstance(object_name, str)
        assert isinstance(mesh_pose, PoseStamped)
        mesh_path = self.mesh_urls[object_name]
        marker_msg = self.make_mesh_marker_msg(mesh_path, mesh_pose, id=id, color=self.color)
        return marker_msg

    def update_object_poses(self):
        marker_array_msg = MarkerArray()
        id = 0
        # query pose selector
        resp = self.pose_selector_get_all_poses_srv()
        if len(resp.poses.objects) > 0:
            for obj_pose in resp.poses.objects:
                if obj_pose.class_id in self.mesh_urls:
                    rospy.logdebug(f'obj found: {obj_pose}')
                    pose_stamped_msg = PoseStamped()
                    pose_stamped_msg.header.frame_id = 'map'
                    pose_stamped_msg.pose.position = obj_pose.pose.position
                    pose_stamped_msg.pose.orientation = obj_pose.pose.orientation
                    marker_array_msg.markers.append(self.make_obj_marker_msg(obj_pose.class_id, pose_stamped_msg, id=id))
                    id += 1
                else:
                    #Mesh URL for object not provided in configuration
                    rospy.logwarn(f'URL for {obj_pose.class_id} mesh not provided in configuration file')

        if len(marker_array_msg.markers) > 0:
            self.objects_mesh_publisher.publish(marker_array_msg)

    def start_pose_selector_visualizer(self):
        while not rospy.is_shutdown():
            self.update_object_poses()
            rospy.sleep(1.0)

if __name__ == '__main__':
    rospy.init_node('grasp_visualizer', anonymous=False)
    grasp_visualizer = PoseSelectorVisualizer(wait_for_pose_selector_srv=True)
    grasp_visualizer.start_pose_selector_visualizer()


from django.shortcuts import render, get_object_or_404
from category.models import Category
from store.models import Product
from django.db.models import Q
from django.core.paginator import EmptyPage, PageNotAnInteger,Paginator

def store(request, category_slug=None):
    categories = None
    products = None

    if category_slug != None:
        categories = get_object_or_404(Category, slug=category_slug)
        products = Product.objects.filter(category=categories, is_available=True)
        paginator=Paginator(products,2)
        page =request.GET.get('page')#capture the page number that comes with the url
        paged_products=paginator.get_page(page)
        product_count = products.count()
    else:
        products = Product.objects.all().filter(is_available=True).order_by('id')
        paginator=Paginator(products,6)
        page =request.GET.get('page')#capture the page number that comes with the url
        paged_products=paginator.get_page(page)#paged_products have 6 prducts
        product_count = products.count()

    context = {
        'products': paged_products,
        'product_count': product_count,
    }
    return render(request, 'store/allproducts.html', context)

def sort_by_price(request):
    products = Product.objects.filter(is_available=True)
    product_count = products.count()

    # get the sorting parameter from the request
    sort_param = request.GET.get('sort')

    if sort_param == 'low_to_high':
        sortby = products.order_by('price')

    elif sort_param == 'high_to_low':
        sortby = products.order_by('-price')
    else:
        sortby = products

    context = {
        'products': sortby,
        'sort_param': sort_param,
        'product_count':product_count,

    }
    return render(request, 'store/allproducts.html', context)

def product_detail(request, category_slug, product_slug):
    try:
        single_product = Product.objects.get(category__slug=category_slug, slug=product_slug)
    except Exception as e:
        raise e
    context = {
        'single_product': single_product,
    }
    return render(request, 'store/product_detail.html',context)

def search(request):
  if request.method == 'GET':
    keyword= request.GET['keyword']
    if keyword:
      products = Product.objects.order_by('-created_date').filter(Q(description__icontains=keyword) | Q(product_name__icontains=keyword))
      product_count = products.count()

  paginator = Paginator(products, 9)
  page_number = request.GET.get('page')
  page_obj = paginator.get_page(page_number)

  context = {
    'products':page_obj,
    'product_count':product_count,
  }
  return render(request, 'store/allproducts.html', context)