#$Rev: 117 $
#$Author: fnight $
#$Date: 2009-08-20 18:16:18 +0400 (Чт, 20 авг 2009) $

#This file is part of Vitamin Project

from vitamin.modules.tpl.builtins import methods, modificators
import operator
from functools import partial
from collections import OrderedDict

builtin_methods = {x:getattr(methods, x) for x in dir(methods) if not x.startswith("_")}
builtin_modificators = {x:getattr(modificators, x) for x in dir(modificators) if not x.startswith("_")}

#переменаая, зависящая от контекста
class ContextVar(str):

    def __repr__(self):
        return "ctx.var:" + self.__str__()

#функция, зависящая от контекста
class ContextFunction():

    def __init__(self, name, *args, **kwargs):

        """
        Переменные должны быть только следующих типов:
            int, float, String, ContextVar, ContextFunction
        """

        self.name = name
        self.args = args
        self.kwargs = kwargs

class Context(dict):

    """
    Контекст - объект связывания переменных в шаблоне
    с переменными окружения. Каждая сессия отрисовки шаблона
    имеет свой контекст со своим набором переменных, изменяющихся
    в зависимости от ситуации. Контекст также позвляет шаблону
    получить доступ к определенным заранее модификаторам и методам
    обработки информации, которые расположены в модуле builtins.
    """

    def get(self, var):

        if isinstance(var, ContextVar):
            #разруливание переменных любой глубины var1.var2.var3...
            if "." in var:
                name, *path = var.split(".")
                getter = operator.attrgetter(path)
                if name in self:
                    getter(self[name])
                else:
                    raise Exception("context var failure: " + repr(name))
            else:
                if var in self:
                    return self[var]
                else:
                    raise Exception("context var failure: " + repr(var))

        elif isinstance(var, ContextFunction):
            #разруливание вызова функций с аргументами из шаблона
            function = None
            if var.name in self and hasattr(self[var.name], "__call__"):
                function = self[var.name]
            elif var.name in builtin_methods:
                function = builtin_methods[var.name]
            elif var.name in builtin_modificators:
                function = builtin_modificators[var.name]
            else:
                raise Exception("context function failure: " + repr(var.name))

            args = list(map(self.get, var.args))
            return partial(function, *args)

        else:
            #неразруливаемые типы(int, String, и проч.) просто возвращаются
            return var

class Aggregator(list):

    def __init__(self):
        self.mod_line = OrderedDict()
        self.aggregation = []

    def push_modificator(self, name, state):

        """
        Добавляет новое состояние модификатора в аггрегатор.
        Модификатор имеет состояние вкл/выкл(bool), и начинает
        применяться ко всем дальнейшим добавляемым строкам.

        Перед изменением состояния модификатора вызывает
        flush_mods().
        """

        assert name in builtin_modificators
        self.flush_mods()
        if not name in self.mod_line:
            self.mod_line[name] = []
        self.mod_line[name].append(state)

    def del_modificator(self, name):

        """
        Удаляет состояние модификатора из аггрегатора. Если
        удаляемое состояние - последнее из состояний модификатора,
        модификатор удаляется из аггрегатора.

        Перед изменением состояния модификатора вызывает
        flush_mods().
        """

        self.flush_mods()
        if self.mod_line[name]:
            del self.mod_line[name][-1]
        if not self.mod_line[name]:
            del self.mod_line[name]

    def slice(self):

        """
        Возвращает словарь - срез текущих состояних модификаторов,
        подставляя каждому активному модификатору только одно (последнее)
        состояние. Таким образом мы получаем возможность включать -
        отключать модификаторы в шаблоне по мере необходимости.
        """

        return OrderedDict(((x, self.mod_line[x][-1]) for x in self.mod_line))

    def append(self, item):

        """
        Операция добавления текста в аггрегатор.
        """

        if self.mod_line:
            self.aggregation.append(item)
        else:
            list.append(self, item)

    def flush_mods(self):

        """
        Операция применения модификаторов в состоянии текущего
        среза на накопленный буфер и сброс буфера. Применяется
        при изменении состояния какого- либо модификатора.
        """

        slice = self.slice()
        result = "".join(self.aggregation)
        for name, active in slice.items():
            if active:
                result = builtin_modificators[name](result)
        list.append(self, result)
        self.aggregation = []

    def join(self):

        """
        Свертка аггрегатора в результирующую строку
        """
        return "".join(self)


from datetime import datetime
import pandas as pd

def group_data(df, by=None):
    if by:
        return df.groupby(by=by).sum()
    else:
        return df

def aggregate_data(df, method=None):
    df = df.agg(method)
    return df

def top_events(data, event):
    agg = {"totalEvents": "sum", "uniqueEvents": "sum", "eventValue": "sum"}
    # if type(start_date) == str:
    #     start_date = datetime.strptime(start_date, "%Y-%m-%d")
    # if type(end_date) == str:
    #     end_date = datetime.strptime(end_date, "%Y-%m-%d")
    df = data.copy()
    df["date"] = pd.to_datetime(df["date"])
    df = (
        df[df["eventAction"] == event]
        .groupby(by=["name", "date"])
        .agg(agg)
        .reset_index()
    )
    df = df.sort_values(by=["eventValue"], ascending=False).reset_index(drop=True)
    return df

def prepare_video_events_df_list(video_df) -> list:
    """
    return list of dataframes spited by unique eventAction
    """
    set_of_events_action_dfs = []
    for event_action in video_df["eventAction"].unique():
        set_of_events_action_dfs.append(
            video_df[video_df["eventAction"] == event_action]
        )
    return set_of_events_action_dfs

def prepare_video_events_df_dict(video_df) -> dict:
    """
    return dict of dataframes spited by unique eventAction
    """
    dict_of_events_action_dfs = {}
    for event_action in video_df["eventAction"].unique():
        dict_of_events_action_dfs[event_action] = video_df[
            video_df["eventAction"] == event_action
        ]
    return dict_of_events_action_dfs

def prepare_video_events_counted_dfs(video_df):
    dict_of_counted_events_dfs = {}
    for event_action in video_df["eventAction"].unique():
        dict_of_counted_events_dfs[event_action] = (
            video_df[video_df["eventAction"] == event_action]
            .groupby(by=["name"])["name"]
            .count()
        )
    return dict_of_counted_events_dfs

def prepare_seek_time_df(video_df_seeking, video_df_seeked):
    seek_time = pd.merge(
        video_df_seeking,
        video_df_seeked,
        on=["eventLabel", "name", "date", "hour", "minute", "customUserID"],
        how="inner",
        suffixes=("_seeking", "_seeked"),
    )
    seek_time["seek_time"] = abs(
        seek_time["eventValue_seeked"] - seek_time["eventValue_seeking"]
    )
    return seek_time[seek_time["seek_time"] > 0][
        ["date", "hour", "minute", "customUserID", "name", "seek_time"]
    ]

def prepare_date_columns(df):
    df["day"] = df["date"].dt.isocalendar().day
    df["week"] = df["date"].dt.isocalendar().week
    df["month"] = df["date"].dt.month
    df["year"] = df["date"].dt.year
    return df


#Lista que conterá os dicionários
contatos = []
#for para preenchimento dos contatos de acordo com a quantidade
for i in range(5):
    #dicionario que conterá as informacoes
    contato = {}
    #entrada de dados
    contato["Nome"] = input("Digite o seu nome: ")
    contato["Endereço"] = input("Digite o seu endereço: ")
    contato["Número"] = int(input("Digite o seu número: "))
    #dicionario é adicionado à lista
    contatos.append(contato)

#print da lista com os dicionarios preenchidos
print(contatos)


from django import shortcuts
from django.views.decorators import vary
from django.shortcuts import render

import horizon

from openstack_auth import views

#huoqu yonghuming , panduan yonghu quanxian ,yongyu shezhi tiaozhuanjiemian

def get_user_home(user):
    if user.is_superuser:
        return horizon.get_dashboard('admin').get_absolute_url()
    return horizon.get_dashboard('project').get_absolute_url()

@vary.vary_on_cookie
#huoqu denglu jiemian de yonghuming he mima , yanzheng tongguo ze panduan yonghuquanxian, fouze shuaxin
def splash(request):
    if request.user.is_authenticated():
       return shortcuts.redirect(get_user_home(request.user))
#       return shortcuts.render(request, "admin")
    form = views.Login(request)
    request.session.clear()
    request.session.set_test_cookie()
    return shortcuts.render(request, 'splash.html', {'form': form})

def index(request):
    return render(request,'index.html')


import torch
import torch.nn as nn
import torch.nn.functional as F
from multi_head_att.submodules import MultiHeadAttention, PositionwiseFeedForward, PositionalEncoding

def masked_mean(input, mask=None, dim=1):
    # input: [batch_size, seq_len, hidden_size]
    # mask: Float Tensor of size [batch_size, seq_len], where 1.0 for unmask, 0.0 for mask ones
    if mask is None:
        return torch.mean(input, dim=dim)
    else:
        mask = mask.unsqueeze(-1)
        mask_input = input * mask
        sum_mask_input = mask_input.sum(dim=dim)
        for dim in range(mask.size(0)):
            sum_mask_input[dim] = sum_mask_input[dim] / mask[dim].sum()
        return sum_mask_input

def masked_max(input, mask=None, dim=1):
    # input: [batch_size, seq_len, hidden_size]
    # mask: Float Tensor of size [batch_size, seq_len], where 1.0 for unmask, 0.0 for mask ones
    if mask is None:
        max_v, _ = torch.max(input, dim=dim)
        return max_v
    else:
        mask = mask.unsqueeze(-1)
        mask = mask.repeat(1, 1, input.size(-1))
        input = input.masked_fill(mask == 0.0, float('-inf'))
        max_v, _ = torch.max(input, dim=dim)
        return max_v

class MaskedSoftmax(nn.Module):
    def __init__(self, dim):
        super(MaskedSoftmax, self).__init__()
        self.dim = dim

    def forward(self, logit, mask=None):
        if mask is None:
            dist = F.softmax(logit - torch.max(logit, dim=self.dim, keepdim=True)[0], dim=self.dim)
        else:
            dist_ = F.softmax(logit - torch.max(logit, dim=self.dim, keepdim=True)[0], dim=self.dim) * mask
            normalization_factor = dist_.sum(self.dim, keepdim=True)
            dist = dist_ / normalization_factor
        return dist

class Attention(nn.Module):
    def __init__(self, decoder_size, memory_bank_size, need_mask=False):
        super(Attention, self).__init__()
        self.need_mask = need_mask
        self.v = nn.Linear(decoder_size, 1, bias=False)
        self.decode_project = nn.Linear(decoder_size, decoder_size)
        self.memory_project = nn.Linear(memory_bank_size, decoder_size, bias=False)
        self.softmax = MaskedSoftmax(dim=1)
        self.tanh = nn.Tanh()
        self.linear = nn.Linear(decoder_size + memory_bank_size, memory_bank_size)

    def score(self, memory_bank, decoder_state):
        """
        :param memory_bank: [batch_size, max_src_len, self.bi_hidden_size]
        :param decoder_state: [batch_size, decoder_size]
        :return: score: [batch_size, max_src_len]
        """
        batch_size, max_src_len, memory_bank_size = list(memory_bank.size())
        decoder_size = decoder_state.size(1)

        # Bahdanau style attention
        # project memory_bank
        memory_bank_ = memory_bank.view(-1, memory_bank_size)  # [batch_size*max_src_len, memory_bank_size]
        encoder_feature = self.memory_project(memory_bank_)  # [batch_size*max_src_len, decoder size]
        # project decoder state
        dec_feature = self.decode_project(decoder_state)  # [batch_size, decoder_size]
        dec_feature_expanded = dec_feature.unsqueeze(1).expand(batch_size, max_src_len, decoder_size).contiguous()
        dec_feature_expanded = dec_feature_expanded.view(-1, decoder_size)  # [batch_size*max_src_len, decoder_size]
        # sum up attention features
        att_features = encoder_feature + dec_feature_expanded  # [batch_size*max_src_len, decoder_size]

        # compute attention score and normalize them
        e = self.tanh(att_features)  # [batch_size*max_src_len, decoder_size]
        scores = self.v(e)  # [batch_size*max_src_len, 1]

        scores = scores.view(-1, max_src_len)  # [batch_size, max_src_len]
        return scores

    def forward(self, decoder_state, memory_bank, src_mask=None, return_attn=False):
        """
        :param decoder_state: [batch_size, decoder_size]
        :param memory_bank: [batch_size, max_input_seq_len, self.bi_hidden_size]
        :param src_mask: [batch_size, max_input_seq_len]
        :return: context, attn_dist
        """
        # init dimension info
        batch_size, max_src_len, memory_bank_size = list(memory_bank.size())

        if self.need_mask:
            assert src_mask is not None

        # if src_mask is None:  # if it does not supply a source mask, create a dummy mask with all ones
        #     src_mask = memory_bank.new_ones(batch_size, max_src_len)

        scores = self.score(memory_bank, decoder_state)
        attn_dist = self.softmax(scores, mask=src_mask)

        # Compute weighted sum of memory bank features
        attn_dist = attn_dist.unsqueeze(1)  # [batch_size, 1, max_input_seq_len]
        memory_bank = memory_bank.view(-1, max_src_len, memory_bank_size)  # batch_size, max_src_len, memory_bank_size]
        context = torch.bmm(attn_dist, memory_bank)  # [batch_size, 1, memory_bank_size]
        context = context.squeeze(1)  # [batch_size, memory_bank_size]
        attn_dist = attn_dist.squeeze(1)  # [batch_size, max_input_seq_len]

        # Update coverage
        assert attn_dist.size() == torch.Size([batch_size, max_src_len])
        assert context.size() == torch.Size([batch_size, memory_bank_size])

        context_output = self.linear(torch.cat([context, decoder_state], dim=1))
        if return_attn:
            return context_output, attn_dist
        return context_output

class CoAttention(nn.Module):
    def __init__(self, text_feat_size, img_feat_size, input_type='text_img'):
        """Initialize model."""
        super(CoAttention, self).__init__()
        self.text_feat_size = text_feat_size
        self.img_feat_size = img_feat_size
        self.input_type = input_type
        assert input_type in ['text_img', 'img_text', 'text_text']
        self.v_text = nn.Linear(text_feat_size, 1, bias=False)
        self.v_img = nn.Linear(img_feat_size, 1, bias=False)
        self.text2img_project = nn.Linear(text_feat_size, img_feat_size, bias=False)
        self.img2text_project = nn.Linear(img_feat_size, text_feat_size, bias=False)
        self.img_project = nn.Linear(img_feat_size, img_feat_size)
        self.text_project = nn.Linear(text_feat_size, text_feat_size)
        self.softmax = MaskedSoftmax(dim=1)
        self.linear = nn.Linear(text_feat_size + img_feat_size, text_feat_size)

    def text_att_scores(self, text_feat, img_feats):
        batch_size, img_num, img_feat_size = list(img_feats.size())
        batch_size, text_feat_size = list(text_feat.size())

        img_feats_ = img_feats.view(-1, img_feat_size)  # [batch_size*img_num, img_feat_size]
        img_feature = self.img2text_project(img_feats_)  # [batch_size*img_num, text_feat_size]

        # Project decoder state: text_feats (in our case)
        text_feature = self.text_project(text_feat)  # [batch_size, text_feat_size]
        text_feature_expanded = text_feature.unsqueeze(1).expand(batch_size, img_num, text_feat_size).contiguous()
        text_feature_expanded = text_feature_expanded.view(-1, text_feat_size)  # [batch_size*img_num, text_feat_size]

        # sum up attention features
        att_features = img_feature + text_feature_expanded  # [batch_size*img_num, text_feat_size]
        e = torch.tanh(att_features)  # [batch_size*img_num, text_feat_size]
        scores = self.v_text(e)  # [batch_size*img_num, 1]
        scores = scores.view(-1, img_num)  # [batch_size, img_num]
        return scores

    def img_att_scores(self, img_feat, text_feats):
        batch_size, max_src_len, text_feat_size = list(text_feats.size())
        batch_size, img_feat_size = list(img_feat.size())

        text_feats_ = text_feats.view(-1, text_feat_size)  # [batch_size*max_src_len, text_feat_size]
        text_feature = self.text2img_project(text_feats_)  # [batch_size*max_src_len, img_feat_size]

        # Project decoder state: text_feats (in our case)
        img_feature = self.img_project(img_feat)  # [batch_size, img_feat_size]
        img_feature_expanded = img_feature.unsqueeze(1).expand(batch_size, max_src_len, img_feat_size).contiguous()
        img_feature_expanded = img_feature_expanded.view(-1, img_feat_size)  # [batch_size*max_src_len, img_feat_size]

        # sum up attention features
        att_features = text_feature + img_feature_expanded  # [batch_size*max_src_len, img_feat_size]
        e = torch.tanh(att_features)  # [batch_size*max_src_len, img_feat_size]
        scores = self.v_img(e)  # [batch_size*max_src_len, 1]
        scores = scores.view(-1, max_src_len)  # [batch_size, max_src_len]
        return scores

    def forward(self, text_feats, img_feats, src_mask):
        # Text
        batch_size, img_num, img_feat_size = list(img_feats.size())
        batch_size, max_src_len, text_feat_size = list(text_feats.size())

        if self.input_type in ['text_img', 'text_text']:
            text_feat = masked_mean(text_feats, src_mask, dim=1)
        elif self.input_type in ['img_text']:
            text_feat = torch.mean(text_feats, dim=1)

        text_scores = self.text_att_scores(text_feat, img_feats)

        if self.input_type in ['text_img']:
            text_att_dist = self.softmax(text_scores)
        elif self.input_type in ['img_text', 'text_text']:
            text_att_dist = self.softmax(text_scores, mask=src_mask)

        text_att_dist = text_att_dist.unsqueeze(1)  # [batch_size, 1, img_num]
        img_feats = img_feats.view(-1, img_num, img_feat_size)  # batch_size, img_num, img_feat_size]
        img_context = torch.bmm(text_att_dist, img_feats)  # [batch_size, 1, img_feat_size]
        img_context = img_context.squeeze(1)  # [batch_size, img_feat_size]

        img_scores = self.img_att_scores(img_context, text_feats)

        if self.input_type in ['text_img', 'text_text']:
            img_att_dist = self.softmax(img_scores, mask=src_mask)
        elif self.input_type in ['img_text']:
            img_att_dist = self.softmax(img_scores)

        img_att_dist = img_att_dist.unsqueeze(1)  # [batch_size, 1, max_src_len]
        text_feats = text_feats.view(-1, max_src_len, text_feat_size)  # [batch_size, max_src_len, text_feat_size]
        text_context = torch.bmm(img_att_dist, text_feats)  # [batch_size, 1, text_feat_size]
        text_context = text_context.squeeze(1)  # [batch_size, text_feat_size]

        combined_features = torch.cat([img_context, text_context], dim=1)
        combined_features = self.linear(combined_features)
        return combined_features

class MyMultiHeadAttention(nn.Module):
    def __init__(self, n_head, d_model, d_kv, dropout=0.1, need_mask=False, is_regu=False):
        super(MyMultiHeadAttention, self).__init__()
        self.need_mask = need_mask
        self.is_regu = is_regu
        self.slf_attn = MultiHeadAttention(n_head, d_model, d_kv, d_kv, dropout=dropout, is_regu=is_regu)
        self.pos_ffn = PositionwiseFeedForward(d_model, d_model, dropout=dropout)

    def forward(self, q, k, v, mask=None):
        # q: [batch_size, d_model] ==>  k: [batch_size, 1, d_model]
        # mask: [batch_size, seq_len] == > [batch_size, 1, seq_len]
        # when there is only one query, we need to expand the dimension
        if len(q.shape) == 2:
            q = q.unsqueeze(1)
        if mask is not None:
            mask = mask.unsqueeze(1)  # [batch_size, 1, seq_len]
        if self.need_mask:
            assert mask is not None, 'Please pass the attention mask to the multi-head'
        if self.is_regu:
            enc_output, enc_slf_attn, head_diff = self.slf_attn(q, k, v, mask)
        else:
            enc_output, enc_slf_attn = self.slf_attn(q, k, v, mask)
        enc_output = self.pos_ffn(enc_output)

        # enc_output: [batch_size, 1, d_model] ==>  k: [batch_size, d_model]
        enc_output = enc_output.squeeze(1)
        if self.is_regu:
            return enc_output, enc_slf_attn, head_diff
        return enc_output, enc_slf_attn

class MyTransformer(nn.Module):
    def __init__(self, n_layers, n_head, d_model, d_kv, emb_size=200, dropout=0.1):
        super(MyTransformer, self).__init__()

        self.position_enc = PositionalEncoding(emb_size, n_position=200)
        self.dropout = nn.Dropout(p=dropout)
        self.layer_stack = nn.ModuleList([
            MyMultiHeadAttention(n_head, d_model, d_kv, dropout=dropout)
            for _ in range(n_layers)])
        self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)

    def forward(self, src_seq_embed, memory_bank, src_mask, return_attns=False):

        enc_slf_attn_list = []

        enc_output = self.dropout(self.position_enc(src_seq_embed))
        # (enc_output, memory_bank, memory_bank, src_mask)
        for enc_layer in self.layer_stack:
            enc_output, enc_slf_attn = enc_layer(enc_output, memory_bank, memory_bank, src_mask)
            enc_slf_attn_list += [enc_slf_attn] if return_attns else []

        enc_output = self.layer_norm(enc_output)

        if return_attns:
            return enc_output, enc_slf_attn_list
        return enc_output


from collections import OrderedDict
from polity.models import Polity

def navigation(request):

    # For now, we only support one level of sub-polities in the navigation.
    # This is mostly because we haven't designed the interface to accommodate
    # sub-sub-polities, and we're not likely to use them any time soon.
    #
    # This may seem overly convoluted (and hopefully adequately explained in
    # comments) but the effect we want is:
    #
    # a) All visible sub-polities of the uppermost polities being shown.
    # b) Only show polity types which actually contain sub-polities.
    # c) Order polity types as they are defined in the `Polity` model.
    # d) Sub-polity navigation being available from within sub-polities.

    # The resulting object, used in the template.
    polity_nav = OrderedDict()

    # Order of polity types as defined in Polity.POLITY_TYPES.
    type_order = [t[0] for t in Polity.POLITY_TYPES]

    # Get visible sub-polities of uppermost polity.
    polities = Polity.objects.visible().exclude(parent=None).filter(parent__parent=None)

    # Sort polities by type, in the order defined in Polity.POLITY_TYPES.
    polities = sorted(polities, key=lambda p: type_order.index(p.polity_type))

    # Add polities to the navigation, organized and ordered by type.
    for polity in polities:
        # Create the entry of the polity type if it doesn't exist.
        if polity.polity_type not in polity_nav:
            polity_nav[polity.polity_type] = {
                'polity_type_name': polity.get_polity_type_display(),
                'polities': [],
            }

        polity_nav[polity.polity_type]['polities'].append(polity)

    return { 'polity_nav': polity_nav }


import secrets
import uuid

from django.contrib.auth.models import User
from django.shortcuts import render
from requests import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

from .serializer import *
from .models import *
from rest_framework import generics, status

class QuesttionList(generics.ListAPIView):
    queryset = Questtion.objects.all()
    serializer_class = QuesttionSerializer

class DirectionList(generics.ListAPIView):
    queryset = Direction.objects.all()
    serializer_class = DirectionSerializer

class CandidateList(generics.ListCreateAPIView):
    queryset = Candidate.objects.all()
    serializer_class = CandidateSerializer

class CandidateDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Candidate.objects.all()
    serializer_class = CandidateSerializer

    def get_serializer_class(self):
        if self.request.method == 'PUT' or self.request.method == 'PATCH':
            return CandidateSerializer
        return CandidateCreateSerializer

class UserCreateAnswer(generics.ListCreateAPIView):
    queryset = UserAnswer.objects.all()
    serializer_class = AnswerSerializer

class UserAnswerDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = UserAnswer.objects.all()
    serializer_class = AnswerSerializer

    def get_serializer_class(self):
        if self.request.method == 'PUT' or self.request.method == 'PATCH':
            return AnswerSerializer
        return AnswerCreateSerializer

class APIKeyView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, format=None):
        user = request.user
        key = str(uuid.uuid4())
        api_key = APIKey.objects.create(user=user, key=key)
        return Response({'key': api_key.key}, status=status.HTTP_201_CREATED)


#!/usr/bin/env python

##from https://github.com/NamWoo

from __future__ import print_function
#import roslib
#roslib.load_manifest('my_package')
import sys, time
import rospy
import cv2
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError

def show_camera():
    pipeline_1 = 'nvarguscamerasrc ! video/x-raw(memory:NVMM), width=640, height=480, format=(string)NV12, framerate=(fraction)15/1 ! nvvidconv ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink'

    #pipeline_2 = "v4l2src device=/dev/video0 ! video/x-raw, width=640, height=480, framerate=15/1 ! videoconvert ! video/x-raw, format=(string)BGR ! appsink"

    #pipeline_3 = "v4l2src device=/dev/video0 ! video/x-h264, width=1280, height=720, framerate=30/1, format=H264 ! avdec_h264 ! videoconvert ! video/x-raw, format=(string)BGR ! appsink sync=false"

    cap = cv2.VideoCapture(pipeline_1, cv2.CAP_GSTREAMER)
    width = 640
    height = 480
    fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
    fps = cap.get(cv2.CAP_PROP_FPS)
    now = time.time()
    save_name = time.strftime('%m%d_%H%M%S', time.localtime(now))
    savepath = '/root/data/temp/{}.avi'.format(save_name)

    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    print('get :', frame_width, frame_height, width, height)

    # out = cv2.VideoWriter(savepath, fourcc, fps, (width, height), True)

    rospy.init_node('rgb_pub', anonymous=True)
    rgb_pub = rospy.Publish('rgb', Image, queue_size=1)
    bridge = CvBridge()

    if cap.isOpened():
        try:
            while True:
                ret_val, frame = cap.read()
                rgb_pub.publish(bridge.cv2_to_imgmsg(frame, 'bgr8'))
                # out.write(frame)

                # cv2.imshow('frame', frame)
                # keyCode = cv2.waitKey(10) & 0xFF
                # Stop the program on the ESC key or 'q'
                # if keyCode == 27 or keyCode == ord('q'):
                #     break

        finally:
            cap.release()
            cv2.destroyAllWindows()
            print('end')
    else:
        print("Error: Unable to open camera")

if __name__ == '__main__':

    show_camera()


'''RGB거리'''
import sys
input = sys.stdin.readline

n = int(input())
a = []
for i in range(n):
    a.append(list(map(int, input().split())))

dp = [[None for _ in range(3)] for __ in range(n)]
dp[0] = a[0]

for i in range(1, n):
    dp[i][0] = min(dp[i-1][1] + a[i][0], dp[i-1][2] + a[i][0])
    dp[i][1] = min(dp[i-1][0] + a[i][1], dp[i-1][2] + a[i][1])
    dp[i][2] = min(dp[i-1][0] + a[i][2], dp[i-1][1] + a[i][2])

print(min(dp[n-1]))


class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        info = {0: '.', -1: 'L', 1: 'R'}

        n = len(dominoes)
        status = [0] * n

        q = []
        for i in range(n):
            if dominoes[i]=='L':
                q.append((i, -1))
            elif dominoes[i]=='R':
                q.append((i, 1))

        ans = [dominoes[i] for i in range(n)]
        while len(q)>0:
            q1 = set([])
            for pi, di in q:
                pj = pi + di
                if pj>=0 and pj<=n-1 and ans[pj]=='.':
                    status[pj] += di
                    q1.add(pj)
            q = []
            for pj in q1:
                if status[pj]!=0:
                    ans[pj] = info[status[pj]]
                    q.append((pj, status[pj]))

        ans = "".join(ans)
        return ans


from zerver.models import Backlog, BacklogAccessory, UpdateBacklog, Statement, StatementBacklog, StatementAccessory, \
    StatementState, UserProfile, Stream, ZgStatementComment, ZgReplyComment,UserProfile
from django.http import JsonResponse
import datetime, time, json, calendar
from zerver.lib import avatar

from datetime import timezone, timedelta
from zerver.views.zg_tools import zg_send_tools

import re, math
from django.views.decorators.csrf import csrf_exempt
from zerver.lib.actions import get_user_ids_for_streams
from zerver.tornado.event_queue import send_event

def nuw_time():
    stockpile_time = datetime.datetime.utcnow()
    stockpile_time = stockpile_time.replace(tzinfo=timezone.utc)
    tzutc_8 = timezone(timedelta(hours=8))
    stockpile_time = stockpile_time.astimezone(tzutc_8)
    return stockpile_time

# 查看日志评论
def statement_review(request, user_profile):
    table_id = request.GET.get('table_id')
    if not table_id:
        return JsonResponse({'errno': 1, 'message': "缺少必要参数"})
    table_id = int(table_id)
    comment_list = []
    try:
        comment_obj_list = ZgStatementComment.objects.filter(topic_id=table_id)
    except Exception:
        return JsonResponse({'errno': 2, 'message': "获取评论失败"})

    for comment_obj in comment_obj_list:
        comment_dict = {}
        comment_dict['comment_id'] = comment_obj.id
        comment_dict['comment_content'] = comment_obj.content
        comment_dict['comment_time'] = comment_obj.comment_time
        user = UserProfile.objects.filter(id=comment_obj.from_uid)
        user = user[0]
        comment_dict['comment_user_name'] = user.full_name
        comment_dict['comment_user_avatar_url'] = avatar.absolute_avatar_url(user)
        reply_obj_list = ZgReplyComment.objects.filter(comment_id=comment_obj)
        comment_dict['comment_reply_list'] = []
        for reply_obj in reply_obj_list:
            reply_dict = {}

            # 用户回复id
            reply_dict['reply_user_id'] = reply_obj.reply_user_id
            if reply_obj.reply_user_id:
                user_obj = UserProfile.objects.get(id=reply_obj.reply_user_id)
                reply_dict['reply_user_name'] = user_obj.full_name

            # 回复内容
            reply_dict['reply_content'] = reply_obj.content
            # 回复用户id
            reply_dict['user_reply_id'] = reply_obj.from_uid
            user_obj = UserProfile.objects.get(id=reply_obj.from_uid)
            reply_dict['user_reply_avatar'] = avatar.absolute_avatar_url(user_obj)
            reply_dict['user_reply_name'] = user_obj.full_name

            # 回复时间
            reply_dict['reply_time'] = reply_obj.reply_time

            comment_dict['comment_reply_list'].append(reply_dict)

        comment_list.append(comment_dict)

    return JsonResponse({'errno': 0, 'message': "获取成功", 'comment_list': comment_list})

# 添加评论
def statement_review_post(request, user_profile):
    req = request.body
    req = req.decode()
    req = json.loads(req)
    table_id = req.get('table_id')
    comment = req.get('comment')
    if not all([table_id, comment]):
        return JsonResponse({'errno': 1, 'message': "缺少必要参数"})
    print(table_id, comment)
    try:
        comment_obj = ZgStatementComment.objects.create(topic_id=table_id, content=comment, from_uid=user_profile.id,
                                                        comment_time=time.time(), topic_type='statement')

    except Exception:
        return JsonResponse({'errno': 1, 'message': "添加评论失败"})

    return JsonResponse({'errno': 0, 'message': "评论成功", 'comment_id': comment_obj.id})

# 添加评论回复
def reply_comment(request, user_profile):
    req = request.body
    req = req.decode()
    req = json.loads(req)
    comment_id = req.get('comment_id')
    content = req.get('content')
    reply_id = req.get('reply_id')
    if not all([comment_id, content]):
        return JsonResponse({'errno': 1, 'message': "缺少必要参数"})
    try:
        a = ZgStatementComment.objects.get(id=comment_id)
        reply_obj = ZgReplyComment(comment_id=a, content=content, reply_type='reply_comment',
                                   from_uid=user_profile.id, reply_time=time.time())
        reply_obj.save()
        if reply_id:
            reply_obj.reply_user_id = reply_id
            reply_obj.save()
            reply_id = reply_obj.id

    except Exception:
        return JsonResponse({'errno': 1, 'message': "添加回复失败"})
    return JsonResponse({'errno': 0, 'message': "评论成功", 'reply_id': reply_id})

# 已读未读
def state_view(request, user_profile):
    table_id = request.GET.get('table_id')
    states = request.GET.get('state')

    if not all([table_id, states]):
        return JsonResponse({'errno': 2, 'message': "缺少必要参数", })
    if states == 't':
        try:
            read_table = StatementState.objects.filter(statement_id=table_id, state='t').order_by('-id')
        except Exception:
            return JsonResponse({'errno': 1, 'message': "获取已读信息失败", })
        user_list = []
        for table in read_table:
            user_dict = {}
            user = UserProfile.objects.get(id=table.staff)
            user_dict['avatar'] = avatar.absolute_avatar_url(user)
            user_dict['user_name'] = user.full_name
            user_dict['table_id'] = table_id
            user_list.append(user_dict)
        return JsonResponse({'errno': 0, 'message': "成功", 'user_list': user_list})

    elif states == 'f':
        try:
            read_table = StatementState.objects.filter(statement_id=table_id, state='f').order_by('-id')

        except Exception:
            return JsonResponse({'errno': 3, 'message': "获取已读信息失败", })
        user_list = []
        for table in read_table:
            user_dict = {}
            user = UserProfile.objects.get(id=table.staff)
            user_dict['avatar'] = avatar.absolute_avatar_url(user)
            user_dict['user_name'] = user.full_name
            user_dict['table_id'] = table_id
            user_list.append(user_dict)

        return JsonResponse({'errno': 0, 'message': "成功", 'user_list': user_list})

# 查看自己和他人的报表
def look_table(request, user_profile):
    table_id = request.GET.get('table_id')
    print(table_id)

    if not table_id:
        return JsonResponse({'errno': 2, 'message': "缺少必要参数", })

    try:

        statement = Statement.objects.get(id=table_id)
        a = StatementState.objects.filter(statement_id=statement.id, staff=user_profile.id)
        if a:
            a[0].state = True
            a[0].save()

        statement_backlogs_list = StatementBacklog.objects.filter(statement_id=statement).order_by('-id')
        user = UserProfile.objects.get(email=statement.user)

        table_dict = dict()
        table_dict['avatar'] = avatar.absolute_avatar_url(user)
        table_dict['user_name'] = user.full_name
        table_dict['generate_time'] = statement.generate_time
        table_dict['accomplish'] = statement.accomplish
        table_dict['overdue'] = statement.overdue
        table_dict['underway'] = statement.underway
        table_dict['type'] = statement.types
        backlog_list = []
        table_dict['backlog_list'] = backlog_list
        for statement_backlogs in statement_backlogs_list:
            backlogs_dict = {}
            backlogs = Backlog.objects.get(id=statement_backlogs.backlog_id)
            backlogs_dict['task'] = backlogs.task
            backlogs_dict['over_time'] = backlogs.over_time
            backlog_list.append(backlogs_dict)

        url_list = []
        table_dict['url_list'] = url_list
        accessory_list = StatementAccessory.objects.filter(statement_id=table_id, is_delete='f').order_by('-id')
        if accessory_list:
            for accessory in accessory_list:
                accessory_dict = {}
                accessory_dict['url'] = accessory.statement_accessory_url
                accessory_dict['size'] = accessory.accessory_size
                accessory_dict['name'] = accessory.accessory_name
                url_list.append(accessory_dict)

    except Exception as e:
        print(e)
        return JsonResponse({'errno': 1, 'message': "获取数据失败", })
    # #
    return JsonResponse({'errno': 0, 'message': "获取数据成功", 'table_dict': table_dict})

# web接收到日志
def web_my_receive(request, user_profile):
    page = int(request.GET.get('page', 1))
    generate_time = request.GET.get('start_time')
    screen_over_time = request.GET.get('over_time')
    sender = request.GET.get('sender')
    date_type = request.GET.get('date_type')
    filter_dict = dict()
    if generate_time:
        filter_dict['receive_time__range'] = (generate_time, time.time())
    if screen_over_time:
        filter_dict['receive_time__range'] = ('0', screen_over_time)
    if all([generate_time, screen_over_time]):
        filter_dict['receive_time__range'] = (generate_time, screen_over_time)
    if sender:
        filter_dict['staff'] = sender
    else:
        filter_dict['staff'] = user_profile.id
    if date_type:
        filter_dict['types'] = date_type

    try:
        page1 = (page - 1) * 10
        page2 = page * 10
        statement_state_list = StatementState.objects.filter(**filter_dict).order_by('-id')[page1:page2]
        page_count = StatementState.objects.filter(**filter_dict).count()
        page_count = math.ceil(page_count / 10)

    except Exception:
        return JsonResponse({'errno': 1, 'message': "获取我收到的报表失败"})

    try:

        receive_table_list = []
        for statement_state in statement_state_list:

            web_my_receive_dict = {}
            s = Statement.objects.get(id=statement_state.statement_id.id)
            statement_state.state = True
            statement_state.save()

            user = UserProfile.objects.filter(email=s.user)
            user = user[0]

            web_my_receive_dict['avatarurl'] = avatar.absolute_avatar_url(user)
            web_my_receive_dict['fullname'] = user.full_name
            web_my_receive_dict['generate_time'] = statement_state.receive_time
            web_my_receive_dict['table_id'] = s.id
            web_my_receive_dict['accomplish'] = s.accomplish
            web_my_receive_dict['overdue'] = s.overdue
            web_my_receive_dict['underway'] = s.underway
            web_my_receive_dict['type'] = s.types
            backlog_list = []
            web_my_receive_dict['backlog_list'] = backlog_list
            statement_backlogs_list = StatementBacklog.objects.filter(statement_id=s).order_by('-id')
            for statement_backlogs in statement_backlogs_list:
                backlogs_dict = {}
                backlogs = Backlog.objects.get(id=statement_backlogs.backlog_id)
                backlogs_dict['task'] = backlogs.task
                backlogs_dict['over_time'] = backlogs.over_time
                backlog_list.append(backlogs_dict)

            url_list = []
            web_my_receive_dict['url_list'] = url_list
            accessory_list = StatementAccessory.objects.filter(statement_id=s, is_delete='f').order_by('-id')
            for accessory in accessory_list:
                accessory_dict = {}
                accessory_dict['url'] = accessory.statement_accessory_url
                accessory_dict['size'] = accessory.accessory_size
                accessory_name = accessory.accessory_name
                accessory_dict['name'] = accessory_name
                types = accessory_name.split('.')
                accessory_dict['type'] = types[-1]
                url_list.append(accessory_dict)
            receive_table_list.append(web_my_receive_dict)
    except Exception:
        return JsonResponse({'errno': 2, 'message': "获取信息失败"})
    return JsonResponse({'errno': 0, 'message': "成功", 'receive_table_list': receive_table_list, 'page': page_count})

# web发送的日志
def web_my_send(request, user_profile):
    page = int(request.GET.get('page', 1))
    generate_time = request.GET.get('start_time')
    screen_over_time = request.GET.get('over_time')
    date_type = request.GET.get('date_type')

    filter_dict = dict()
    if generate_time:
        filter_dict['generate_time__range'] = (generate_time, time.time())
    if screen_over_time:
        filter_dict['generate_time__range'] = ('0', screen_over_time)
    if all([generate_time, screen_over_time]):
        filter_dict['generate_time__range'] = (generate_time, screen_over_time)
    if date_type:
        filter_dict['types'] = date_type
    filter_dict['user'] = user_profile.email

    try:
        page1 = (page - 1) * 10
        page2 = page * 10
        statement = Statement.objects.filter(**filter_dict).order_by('-id')[page1:page2]
        page_count = Statement.objects.filter(**filter_dict).count()
        page_count = math.ceil(page_count / 10)
    except Exception as e:
        print(e)
        return JsonResponse({'errno': 1, 'message': "获取我收到的报表失败"})

    try:
        send_table_list = []
        for statement_state in statement:
            web_my_receive_dict = {}

            user = UserProfile.objects.get(email=statement_state.user)
            web_my_receive_dict['avatarurl'] = avatar.absolute_avatar_url(user_profile)
            web_my_receive_dict['fullname'] = user.full_name
            web_my_receive_dict['generate_time'] = statement_state.generate_time
            web_my_receive_dict['table_id'] = statement_state.id
            web_my_receive_dict['accomplish'] = statement_state.accomplish
            web_my_receive_dict['overdue'] = statement_state.overdue
            web_my_receive_dict['underway'] = statement_state.underway
            web_my_receive_dict['type'] = statement_state.types
            backlog_list = []
            web_my_receive_dict['backlog_list'] = backlog_list

            statement_backlogs_list = StatementBacklog.objects.filter(statement_id=statement_state)
            for statement_backlogs in statement_backlogs_list:
                backlogs_dict = {}
                backlogs = Backlog.objects.get(id=statement_backlogs.backlog_id)
                backlogs_dict['task'] = backlogs.task
                backlogs_dict['over_time'] = backlogs.over_time
                backlog_list.append(backlogs_dict)

            url_list = []
            web_my_receive_dict['url_list'] = url_list
            accessory_list = StatementAccessory.objects.filter(statement_id=statement_state, is_delete='f')
            for accessory in accessory_list:
                accessory_dict = dict()
                accessory_dict['url'] = accessory.statement_accessory_url
                accessory_dict['size'] = accessory.accessory_size
                accessory_name = accessory.accessory_name
                accessory_dict['name'] = accessory_name
                types = accessory_name.split('.')
                accessory_dict['type'] = types[-1]

                url_list.append(accessory_dict)

            try:
                read_table = StatementState.objects.filter(statement_id=statement_state.id, state='t').order_by('-id')
            except Exception:
                return JsonResponse({'errno': 1, 'message': "获取已读信息失败", })
            already_list = []
            for table in read_table:
                user_dict = {}
                user = UserProfile.objects.get(id=table.staff)
                user_dict['avatar'] = avatar.absolute_avatar_url(user)
                user_dict['user_name'] = user.full_name
                user_dict['table_id'] = statement_state.id
                already_list.append(user_dict)
            web_my_receive_dict['already_list'] = already_list

            try:
                read_table = StatementState.objects.filter(statement_id=statement_state.id, state='f').order_by('-id')
            except Exception:
                return JsonResponse({'errno': 3, 'message': "获取已读信息失败", })
            unread_list = []
            for table in read_table:
                user_dict = {}
                user = UserProfile.objects.get(id=table.staff)
                user_dict['avatar'] = avatar.absolute_avatar_url(user)
                user_dict['user_name'] = user.full_name
                user_dict['table_id'] = statement_state.id
                unread_list.append(user_dict)
            web_my_receive_dict['already_count'] = len(already_list)
            web_my_receive_dict['unread_count'] = len(unread_list)
            web_my_receive_dict['unread_list'] = unread_list

            send_table_list.append(web_my_receive_dict)

    except Exception:
        return JsonResponse({'errno': 2, 'message': "获取信息失败"})
    return JsonResponse({'errno': 0, 'message': "成功", 'send_table_list': send_table_list, 'page': page_count})

# 我发出的
def my_send(request, user_profile):
    page = int(request.GET.get('page', 1))

    generate_time = request.GET.get('start_time')
    screen_over_time = request.GET.get('over_time')
    date_type = request.GET.get('date_type')

    try:
        page1 = (page - 1) * 10
        page2 = page * 10
        filter_dict = dict()

        if generate_time:
            filter_dict['generate_time__range'] = (generate_time, time.time())
        if screen_over_time:
            filter_dict['generate_time__range'] = ('0', screen_over_time)
        if all([generate_time, screen_over_time]):
            filter_dict['generate_time__range'] = (generate_time, screen_over_time)
        if date_type:
            filter_dict['types'] = date_type
        filter_dict['user'] = user_profile.email

        statement = Statement.objects.filter(**filter_dict).order_by('-id')[page1:page2]
        page_count = Statement.objects.filter(**filter_dict).count()
        page_count = math.ceil(page_count / 10)
    except Exception:
        return JsonResponse({'errno': 2, 'message': "获取我收到的报表失败", })

    try:
        send_table_list = []
        for st in statement:
            user_dict = {}
            user_dict['avatarurl'] = avatar.absolute_avatar_url(user_profile)
            user_dict['fullname'] = user_profile.full_name
            user_dict['generate_time'] = st.generate_time
            user_dict['table_id'] = st.id
            user_dict['type'] = st.types
            send_table_list.append(user_dict)

    except Exception:
        return JsonResponse({'errno': 1, 'message': "获取数据失败", })

    return JsonResponse({'errno': 0, 'message': "成功", 'send_table_list': send_table_list, 'page': page_count})

# 我收到的
def my_receive(request, user_profile):
    generate_time = request.GET.get('start_time')
    screen_over_time = request.GET.get('over_time')
    sender = request.GET.get('sender')
    date_type = request.GET.get('date_type')

    page = int(request.GET.get('page', 1))
    page1 = (page - 1) * 10
    page2 = page * 10
    try:
        filter_dict = dict()
        if generate_time:
            filter_dict['receive_time__range'] = (generate_time, time.time())
        if screen_over_time:
            filter_dict['receive_time__range'] = ('0', screen_over_time)

        if all([generate_time, screen_over_time]):
            filter_dict['receive_time__range'] = (generate_time, screen_over_time)

        if sender:
            filter_dict['staff'] = sender
        else:
            filter_dict['staff'] = user_profile.id
        if date_type:
            filter_dict['types'] = date_type

        statement_state_list = StatementState.objects.filter(**filter_dict).order_by('-id')[page1:page2]
        page_count = StatementState.objects.filter(**filter_dict).count()
        page_count = math.ceil(page_count / 10)

    except Exception:
        return JsonResponse({'errno': 1, 'message': "获取我收到的报表失败"})

    try:
        receive_table_list = []
        for statement_state in statement_state_list:
            user_dict = {}
            s = Statement.objects.get(id=statement_state.statement_id.id)
            user = UserProfile.objects.get(email=s.user)
            user_dict['avatarurl'] = avatar.absolute_avatar_url(user)
            user_dict['fullname'] = user.full_name
            user_dict['generate_time'] = statement_state.receive_time
            user_dict['table_id'] = s.id
            user_dict['state'] = statement_state.state
            user_dict['type'] = s.types

            receive_table_list.append(user_dict)
    except Exception:
        return JsonResponse({'errno': 2, 'message': "获取信息失败"})
    return JsonResponse({'errno': 0, 'message': "成功", 'receive_table_list': receive_table_list, 'page': page_count})

# 日志助手
def log_assistant(request, user_profile):
    try:
        a = StatementState.objects.filter(staff=user_profile.id, state='f').count()
    except Exception:
        return JsonResponse({'errno': 1, 'message': "查询失败"})
    return JsonResponse({'errno': 0, 'message': "成功", 'count': a})

# 获取群组人员信息
def stream_recipient_data(request, user_profile):
    streams_list = Stream.objects.all()
    streams_user_list = get_user_ids_for_streams(streams_list)
    streams_dict = {}
    for streams_user_id_list in streams_user_list:
        streams_user_data_list = []
        streams_user_lists = streams_user_list[streams_user_id_list]
        if user_profile.id in streams_user_lists:
            streams_user_lists.remove(user_profile.id)
        for user_id in streams_user_lists:
            user_data_dict = {}
            user = UserProfile.objects.get(id=user_id)
            user_data_dict['avatarurl'] = avatar.absolute_avatar_url(user)
            user_data_dict['id'] = user.id
            user_data_dict['fullname'] = user.full_name
            user_data_dict['email'] = user.email
            streams_user_data_list.append(user_data_dict)
        a = Stream.objects.get(id=streams_user_id_list)
        streams_dict[a.name] = streams_user_data_list
        streams_dict['no_strems'] = []
    return JsonResponse({'errno': 0, 'message': "获取成功", 'streams_dict': streams_dict})

# 发送报表
def table_view(request, user_profile):
    user = str(user_profile)
    user = re.match(r"<UserProfile: (.*) <.*>>", user).group(1)
    req = request.body
    req = req.decode()
    req = json.loads(req)
    accomplish = req.get('accomplish')
    overdue = req.get("overdue")
    underway = req.get('underway')

    date_type = req.get('date_type')
    backlogs_list = req.get('backlog_list')
    statement_accessory_list = req.get('statement_accessory_list')
    send = req.get('send_list')

    if not all([date_type, accomplish]):
        return JsonResponse({'errno': 1, 'message': "缺少必要参数"})
    try:
        generate_time = time.time()
        a = Statement(user=user, generate_time=generate_time, types=date_type, accomplish=accomplish)

        if overdue:
            a.overdue = overdue

        if underway:
            a.underway = underway

        a.save()

        if backlogs_list:
            for backlog_id in backlogs_list:
                StatementBacklog.objects.create(statement_id=a, backlog_id=backlog_id)

        if statement_accessory_list:
            for statement_accessory_dict in statement_accessory_list:
                StatementAccessory.objects.create(statement_accessory_url=statement_accessory_dict['url'],
                                                  accessory_size=statement_accessory_dict['size'],
                                                  accessory_name=statement_accessory_dict['name'],
                                                  statement_id=a)
        if send:
            b = time.time()
            for staff in send:
                StatementState.objects.create(statement_id=a, staff=staff, receive_time=b)
            even = {'zg_type': 'DailyReport',
                    'theme': user_profile.full_name + '的日志',
                    'time': nuw_time(),
                    'avatar_url': avatar.absolute_avatar_url(user_profile),
                    'user_name': user_profile.full_name,
                    }
            send_event(zg_send_tools(even), send)

    except Exception as e:
        print(e)
        return JsonResponse({'errno': 2, 'message': "储存周报失败"})

    return JsonResponse({'errno': 0, 'message': "成功", 'table_id': a.id})

# 一键生成
def generate_table(request, user_profile):
    now = int(time.time())
    user = str(user_profile)
    user = re.match(r"<UserProfile: (.*) <.*>>", user).group(1)
    date_type = request.GET.get('date_type')

    if not all([user, date_type]):
        return JsonResponse({'errno': 1, 'message': "缺少参数"})

    if date_type == 'month':

        day_now = time.localtime()
        day_begin = '%d-%02d-01' % (day_now.tm_year, day_now.tm_mon)
        wday, monthRange = calendar.monthrange(day_now.tm_year,
                                               day_now.tm_mon)
        day_end = '%d-%02d-%02d' % (day_now.tm_year, day_now.tm_mon, monthRange)

        day_begin = day_begin + " " + '00:00:00'
        day_end = day_end + " " + "23:59:00"
        day_begin = time.mktime(time.strptime(day_begin, '%Y-%m-%d %H:%M:%S'))
        day_end = time.mktime(time.strptime(day_end, '%Y-%m-%d %H:%M:%S'))

        month_backlog_list = Backlog.objects.filter(user=user, create_time__range=(day_begin, day_end),
                                                    is_delete='f').order_by('-id')

        month_accomplish_list = []
        month_overdue_list = []
        month_underway_list = []
        month_accessory_list = []

        for month_backlog in month_backlog_list:
            if month_backlog.state == 0:
                month_accomplish_list.append(month_backlog.task)

            if month_backlog.over_time < now and month_backlog.state == 2:
                month_overdue_list.append(month_backlog.task)

            if month_backlog.over_time > now and month_backlog.state == 2:
                month_underway_list.append(month_backlog.task)

            month_accessory_obj_list = BacklogAccessory.objects.filter(backlog_id=month_backlog)
            month_accessory_obj_dict = {}

            for month_accessory_obj in month_accessory_obj_list:
                month_accessory_obj_dict['url'] = month_accessory_obj.accessory_url
                month_accessory_obj_dict['size'] = month_accessory_obj.accessory_size
                accessory_name = month_accessory_obj.accessory_name
                month_accessory_obj_dict['name'] = accessory_name
                types = accessory_name.split('.')
                month_accessory_obj_dict['type'] = types[-1]

            if month_accessory_obj_dict:
                month_accessory_list.append(month_accessory_obj_dict)
        month_backlog_count = Backlog.objects.filter(user=user, create_time__range=(day_begin, day_end),
                                                     is_delete='f', state=0).count()
        completeness = 0
        if month_backlog_count + len(month_overdue_list):
            completeness = month_backlog_count / (month_backlog_count + len(month_overdue_list))

        return JsonResponse(
            {'errno': 0, 'message': "成功", 'accomplish_list': month_accomplish_list, 'overdue_list':
                month_overdue_list, "underway_list": month_underway_list, 'completeness': completeness,
             'accessory_list': month_accessory_list})

    elif date_type == 'week':

        today = datetime.date.today()
        monday = datetime.date.today() - datetime.timedelta(days=datetime.date.today().weekday())
        sunday = today + datetime.timedelta(6 - today.weekday())
        a = time.mktime(monday.timetuple())
        b = time.mktime(sunday.timetuple())
        week_backlog_list = Backlog.objects.filter(user=user, create_time__range=(a, b), is_delete='f').order_by('-id')
        week_accomplish_list = []
        week_overdue_list = []
        week_underway_list = []
        week_accessory_list = []

        for week_backlog in week_backlog_list:
            if week_backlog.state == 0:
                week_accomplish_list.append(week_backlog.task)

            if week_backlog.over_time < now and week_backlog.state == 2:
                week_overdue_list.append(week_backlog.task)

            if week_backlog.over_time > now and week_backlog.state == 2:
                week_underway_list.append(week_backlog.task)

            month_accessory_obj_list = BacklogAccessory.objects.filter(backlog_id=week_backlog)
            month_accessory_obj_dict = {}

            for month_accessory_obj in month_accessory_obj_list:
                month_accessory_obj_dict['url'] = month_accessory_obj.accessory_url
                month_accessory_obj_dict['size'] = month_accessory_obj.accessory_size
                accessory_name = month_accessory_obj.accessory_name
                month_accessory_obj_dict['name'] = accessory_name
                types = accessory_name.split('.')
                month_accessory_obj_dict['type'] = types[-1]

            if month_accessory_obj_dict:
                week_accessory_list.append(month_accessory_obj_dict)

        week_backlog_count = Backlog.objects.filter(user=user, create_time__range=(a, b), is_delete='f',
                                                    state=0).count()
        completeness = 0
        if week_backlog_count + len(week_overdue_list):
            completeness = week_backlog_count / (week_backlog_count + len(week_overdue_list))

        return JsonResponse(
            {'errno': 0, 'message': "成功", 'accomplish_list': week_accomplish_list, 'overdue_list':
                week_overdue_list, "underway_list": week_underway_list, 'completeness': completeness,
             'accessory_list': week_accessory_list})

    elif date_type == "day":
        a = int(time.mktime(time.strptime(str(datetime.date.today()), '%Y-%m-%d')))
        b = int(time.mktime(time.strptime(str(datetime.date.today()
                                              + datetime.timedelta(days=1)), '%Y-%m-%d'))) - 1

        day_backlog_list = Backlog.objects.filter(user=user, create_time__range=(a, b), is_delete='f').order_by('-id')

        day_accomplish_list = []
        day_overdue_list = []
        day_underway_list = []
        day_accessory_list = []

        for day_backlog in day_backlog_list:
            if day_backlog.state == 0:
                day_accomplish_list.append(day_backlog.task)

            if day_backlog.over_time < now and day_backlog.state == 2:
                day_overdue_list.append(day_backlog.task)

            if day_backlog.over_time > now and day_backlog.state == 2:
                day_underway_list.append(day_backlog.task)

            month_accessory_obj_list = BacklogAccessory.objects.filter(backlog_id=day_backlog)
            month_accessory_obj_dict = {}

            for month_accessory_obj in month_accessory_obj_list:
                month_accessory_obj_dict['url'] = month_accessory_obj.accessory_url
                month_accessory_obj_dict['size'] = month_accessory_obj.accessory_size
                accessory_name = month_accessory_obj.accessory_name
                month_accessory_obj_dict['name'] = accessory_name
                types = accessory_name.split('.')
                month_accessory_obj_dict['type'] = types[-1]

            if month_accessory_obj_dict:
                day_accessory_list.append(month_accessory_obj_dict)

        day_backlog_count = Backlog.objects.filter(user=user, create_time__range=(a, b), is_delete='f', state=0).count()
        completeness = 0
        if day_backlog_count + len(day_overdue_list):
            completeness = day_backlog_count / (day_backlog_count + len(day_overdue_list))

        return JsonResponse(
            {'errno': 0, 'message': "成功", 'accomplish_list': day_accomplish_list, 'overdue_list':
                day_overdue_list, "underway_list": day_underway_list, 'completeness': completeness,
             'accessory_list': day_accessory_list})

# 待办事项增
def backlogs_view_po(request, user_profile):
    import re
    user = str(user_profile)
    user = re.match(r"<UserProfile: (.*) <.*>>", user).group(1)

    req = request.body
    req = req.decode()
    req = json.loads(req)
    task = req.get('task')
    over_time = req.get('over_time')
    task_details = req.get('task_details')
    create_time = req.get('create_time')

    if not create_time:
        create_time = int(time.time())

    if not all([task, over_time]):
        return JsonResponse({'errno': 1, 'message': '缺少必要参数'})

    over_time = int(over_time)
    create_time = int(create_time)
    if create_time > over_time:
        return JsonResponse({'errno': 3, 'message': '截止时间不能早于当前时间'})
    try:
        backlog = Backlog.objects.create(user=user, create_time=create_time, task=task,
                                         over_time=over_time, task_details=task_details
                                         )
        backlog_id = backlog.id
        time_array = time.localtime(create_time)
        other_styley_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
        update_create_time = "%s创建了事项" % other_styley_time
        UpdateBacklog.objects.create(backlog_id=backlog, update_backlog=update_create_time)

    except ImportError:
        return JsonResponse({'errno': 2, 'message': '创建事项失败'})

    return JsonResponse({'errno': 0, 'message': '事项创建成功，记得如期完成哦', 'backlog_id': backlog_id})

# 删
def backlogs_view_d(request, user_profile):
    req = request.body
    req = req.decode()
    req = json.loads(req)

    backlog_id = req.get('backlog_id')
    if not backlog_id:
        return JsonResponse({'errno': 2, 'message': '缺少参数'})

    try:
        backlog = Backlog.objects.get(id=backlog_id)
        backlog.is_delete = True
        backlog.save()
        a = BacklogAccessory.objects.filter(backlog_id=backlog_id, is_delete='f')
        for i in a:
            i.is_delete = True
            i.save()
    except Exception:
        return JsonResponse({'errno': 1, 'message': '删除失败'})

    return JsonResponse({'errno': 0, 'message': '删除成功'})

# 改
def backlogs_view_pu(request, user_profile):
    now = int(time.time())
    time_array = time.localtime(now)
    uodate_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
    req = request.body
    req = req.decode()
    req = json.loads(req)
    put_id = req.get('backlog_id')
    try:
        backlog = Backlog.objects.get(id=put_id)
        del req['backlog_id']
        for re in req:
            if re == "create_time":
                if not req['create_time']:
                    return JsonResponse({'errno': 1, 'message': '创建时间不能为空'})
                backlog.create_time = int(req['create_time'])
                time_array = time.localtime(req['create_time'])
                other_style_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)

                updatetime = '%s修改了事项的开始时间为:%s' % (uodate_time, other_style_time)
                UpdateBacklog.objects.create(update_backlog=updatetime, backlog_id=backlog)

            if re == "over_time":
                if not req['over_time']:
                    return JsonResponse({'errno': 2, 'message': '结束时间不能为空'})
                backlog.over_time = int(req['over_time'])
                time_array = time.localtime(req['over_time'])
                other_style_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
                updatetime = '%s修改了事项的完成时间为%s' % (uodate_time, other_style_time)
                UpdateBacklog.objects.create(update_backlog=updatetime, backlog_id=backlog)

            if re == "task":
                backlog.task = req['task']
                update_task = '%s修改事项为%s' % (uodate_time, req['task'])
                UpdateBacklog.objects.create(update_backlog=update_task, backlog_id=backlog)

            if re == 'task_details':
                backlog.task_details = req['task_details']
                update_task_details = "%s 修改事项详情为: %s" % (uodate_time, req['task_details'])
                UpdateBacklog.objects.create(update_backlog=update_task_details, backlog_id=backlog)

            if re == 'state':
                if req['state'] == 0:
                    if backlog.over_time < now:
                        backlog.state = req['state']
                        update_state = '%s逾期完成了事项' % uodate_time
                        UpdateBacklog.objects.create(update_backlog=update_state, backlog_id=backlog)

                    else:
                        backlog.state = req['state']
                        update_state = '%s完成了事项' % uodate_time
                        UpdateBacklog.objects.create(update_backlog=update_state, backlog_id=backlog)

                elif req['state'] == 2:
                    backlog.state = req['state']
        backlog.save()
    except Exception:
        return JsonResponse({'errno': 3, 'message': '保存数据失败'})
    return JsonResponse({'errno': 0, 'message': '成功'})

# 更新待办事项附件
def accessory_up(request, user_profile):
    req = request.body
    req = req.decode()
    req = json.loads(req)
    now = int(time.time())
    time_array = time.localtime(now)
    uodate_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
    accessory_list = req['accessory_list']
    backlog_id = req['backlog_id']

    try:
        accessory_lists = []
        backlog = Backlog.objects.get(id=backlog_id)
        for i in accessory_list:
            if i['type'] == 'add':
                accessory_dict = {}
                if not all([i['url'], i['size'], i['name']]):
                    return JsonResponse({'errno': 2, 'message': '缺少必要参数'})
                a = BacklogAccessory.objects.create(backlog_id=backlog,
                                                    accessory_url=i['url'],
                                                    accessory_size=i['size'],
                                                    accessory_name=i['name'])

                accessory_dict['name'] = a.accessory_name
                accessory_dict['url'] = a.accessory_url
                accessory_dict['size'] = a.accessory_size
                accessory_dict['id'] = a.id
                accessory_lists.append(accessory_dict)

            elif i['type'] == 'del':
                if not i['accessory_id']:
                    return JsonResponse({'errno': 3, 'message': '缺少必要参数'})
                accessory = BacklogAccessory.objects.get(id=i['accessory_id'])
                accessory.is_delete = True
                accessory.save()
        UpdateBacklog.objects.create(update_backlog="%s修改了附件" % uodate_time, backlog_id=backlog)
    except Exception:
        return JsonResponse({'errno': 1, 'message': '错误'})

    if accessory_list:
        return JsonResponse({'errno': 0, 'message': '修改完成', 'accessory_list': accessory_lists})
    return JsonResponse({'errno': 0, 'message': '修改完成'})

# 待办事项列表
def backlogs_view_g(request, user_profile):
    user = str(user_profile)
    import re
    user = re.match(r"<UserProfile: (.*) <.*>>", user).group(1)
    # 获取当前时间戳
    now = int(time.time())
    try:
        backlogs_list = Backlog.objects.filter(user=user, state=2, is_delete='f').order_by('-id')
    except Exception:
        return JsonResponse({'errno': 1, 'message': '获取数据失败'})
    # 过期
    past_due_list = []
    backlog_list = []

    for bl in backlogs_list:
        if bl.over_time < now:
            a = {}
            a['backlog_id'] = bl.id
            time_array = time.localtime(bl.create_time)
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
            a['create_time'] = create_time
            a['create_timestamp'] = bl.create_time
            a['over_timestamp'] = bl.over_time
            time_array = time.localtime(bl.over_time)
            over_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
            a['over_time'] = over_time
            a['task'] = bl.task
            a['task_details'] = bl.task_details
            a['state'] = bl.state
            accessory_lists = BacklogAccessory.objects.filter(backlog_id=bl.id, is_delete='f')
            accessory_list = []
            if accessory_lists:
                for accessory in accessory_lists:
                    accessory_list.append(accessory.accessory_url)
                a["accessory_list"] = accessory_list
            past_due_list.append(a)

        else:
            b = {}
            b['backlog_id'] = bl.id
            time_array = time.localtime(bl.create_time)
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
            b['create_time'] = create_time
            b['create_timestamp'] = bl.create_time
            time_array = time.localtime(bl.over_time)
            over_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
            b['over_time'] = over_time
            b['over_timestamp'] = bl.over_time
            b['task'] = bl.task
            b['task_details'] = bl.task_details
            if bl.over_time - now < 86400:
                b['warn'] = True

            else:
                b['warn'] = False
            b['state'] = bl.state

            accessory_lists = BacklogAccessory.objects.filter(backlog_id=bl.id, is_delete='f')
            accessory_list = []
            if accessory_lists:
                for accessory in accessory_lists:
                    accessory_list.append(accessory.accessory_url)
                b["accessory_list"] = accessory_list

            backlog_list.append(b)

    return JsonResponse({'errno': 0, 'message': '成功', 'past_due_list': past_due_list, 'backlog_list': backlog_list})

# 事项详情
def backlogs_details(request, user_profile):
    backlog_id = request.GET.get('backlog_id')
    try:

        backlogs = Backlog.objects.get(id=backlog_id)
        update_backlog = UpdateBacklog.objects.filter(backlog_id=backlog_id).order_by('-id')
        backlogs_accessory_list = BacklogAccessory.objects.filter(backlog_id=backlog_id, is_delete='f')
    except Exception:
        return JsonResponse({'errno': 1, 'message': '获取事项详情失败'})

    update_backlog_list = []
    for i in update_backlog:
        update_backlog_list.append(i.update_backlog)

    backlogs_dict = dict()
    backlogs_dict['id'] = backlogs.id
    backlogs_dict['create_time'] = backlogs.create_time
    backlogs_dict['over_time'] = backlogs.over_time
    backlogs_dict['task'] = backlogs.task
    backlogs_dict['task_details'] = backlogs.task_details
    backlogs_dict['state'] = backlogs.state
    accessory_list = []
    for accessory in backlogs_accessory_list:
        accessory_dict = dict()
        accessory_dict['id'] = accessory.id
        accessory_dict['url'] = accessory.accessory_url
        accessory_dict["size"] = accessory.accessory_size
        accessory_name = accessory.accessory_name
        accessory_dict['name'] = accessory_name
        types = accessory_name.split('.')
        accessory_dict['type'] = types[-1]
        accessory_list.append(accessory_dict)
    backlogs_dict['accessory_list'] = accessory_list

    return JsonResponse(
        {'errno': 0, 'message': '成功', 'backlog_dict': backlogs_dict, "update_backlog_list": update_backlog_list})

# 查看已完成事项
def accomplis_backlogs_view(request, user_profile):
    user = str(user_profile)
    user = re.match(r"<UserProfile: (.*) <.*>>", user).group(1)

    page = request.GET.get('page')
    generate_time = request.GET.get('start_time')
    over_time = request.GET.get('over_time')
    accomplis_task = request.GET.get('accomplis_task')
    filter_dict = {}

    if generate_time:
        filter_dict['create_time__range'] = (generate_time, time.time())
    if over_time:
        filter_dict['create_time__range'] = ('0', over_time)
    if all([generate_time, over_time]):
        filter_dict['create_time__range'] = (generate_time, over_time)

    if accomplis_task:
        filter_dict['task__contains'] = accomplis_task
    filter_dict['user'] = user
    filter_dict['state'] = 0
    filter_dict['is_delete'] = 'f'

    try:
        page = int(page)
        sums1 = 0
        sums2 = 20
        if page != 1:
            sums1 = (page - 1) * 20
            sums2 = page * 20
        accomplis_backlogs_list = Backlog.objects.filter(**filter_dict).order_by('-id')[sums1:sums2]
    except Exception:
        return JsonResponse({'errno': 1, 'message': '获取数据失败'})

    accomplis_backlogs_listss = []
    for accomplis_backlogs in accomplis_backlogs_list:
        a = {}
        a['id'] = accomplis_backlogs.id

        time_array = time.localtime(accomplis_backlogs.create_time)
        create_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
        a['create_time'] = create_time

        time_array = time.localtime(accomplis_backlogs.over_time)
        over_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
        a['over_time'] = over_time

        a['task'] = accomplis_backlogs.task
        a['task_details'] = accomplis_backlogs.task_details
        accessory_list = BacklogAccessory.objects.filter(backlog_id=accomplis_backlogs.id)
        if accessory_list:
            accessory_dict = {}
            for accessory in accessory_list:
                accessory_dict[accessory.id] = accessory.accessory_url
                accessory_dict["size"] = accessory.accessory_size
                accessory_name = accessory.accessory_name
                accessory_dict['name'] = accessory_name
                types = accessory_name.split('.')
                accessory_dict['type'] = types[-1]
            a["accessory_dict"] = accessory_dict

        a['state'] = accomplis_backlogs.state
        accomplis_backlogs_listss.append(a)

    return JsonResponse({'errno': 0, 'message': '成功', 'accomplis_backlog_list': accomplis_backlogs_listss})

def users_view(request, user_profile):
    users = UserProfile.objects.all().order_by('full_name')
    user_list = list()
    for user in users:
        if user == user_profile or user.full_name[-3:] == 'Bot':
            continue

        user_dict = dict()
        user_dict['user_avatar'] = avatar.absolute_avatar_url(user)
        user_dict['name'] = user.full_name
        user_dict['id'] = user.id
        user_dict['email'] = user.email
        user_dict['short_name'] = user.short_name
        user_list.append(user_dict)
    return JsonResponse({'errno': '0', 'message': '成功', 'user_list': user_list, 'user_me': user_profile.full_name,
                         'user_id': user_profile.id})


import streamlit as st
from miscellanious_functions import *
from ClarkeAndWrightSavingsAlgorithm import ClarkeAndWrightSavingsAlgorithmWithVehConstraint
from MDVRP_KMeansFunc import KMeansClusteringBasedNodesSelection
from MDVRP_HierClustFunc import HierClusteringBasedNodeSelection
import datetime

st.set_page_config(page_title = "Multi-Depot Vehicle Routing Problem Simulator",
page_icon="🚚",
layout="wide"
)

st.title("Multi-Depot Vehicle Routing Problem Simulator")
st.subheader("Batch Simulations")

with st.sidebar:
    st.subheader("Problem Instances")

    noc = st.number_input('Insert number of clients 🏬',
    min_value=1,
    max_value=1000,
    value=50,
    step=1,
    help="Insert the total number of clients that need to be served"
    )

    nos = st.slider("Choose seed range 🌱",
    min_value=1,
    max_value=200,
    value=20,
    step=1,
    help="Seed range for which mass testing will be implemented")

    nov = st.number_input('Insert number of vehicles 🚚',
    min_value=1,
    max_value=20,
    value=2,
    step=1,
    help="The number of vehicles each depot has"
    )

    nod = st.number_input('Insert number of depots 🏭',
    min_value=2,
    max_value=20,
    value=2,
    step=1,
    help="The total number of exisitng depots"
    )

    nog = st.number_input('Insert grid size 📏',
    min_value=20,
    max_value=200,
    value=100,
    step=5,
    help="Grid is the size of the plot's height and width. It is also the maximum value a node's x and y coordinates can be equal to"
    )

    novc = st.number_input('Insert vehicle capacity 📦',
    min_value=2,
    max_value=800,
    value=50,
    step=1,
    help="The maximum capacity of each truck"
    )

    nomd = st.number_input('Insert maximum customer demand 📬',
    min_value=1,
    max_value=20,
    value=3,
    step=1,
    help="The maximum demand a customer can have"
    )

if st.button('Start Batch Simulations'):
    dir_path = os.getcwd() # Get the current working directory

    # Loop through all the files in the current directory
    for file_name in os.listdir(dir_path):
        if file_name.endswith(".xlsx"):  # Check if the file is an xlsx file
            file_path = os.path.join(dir_path, file_name)
            if os.path.exists(file_path):
                os.remove(file_path)

    with st.spinner('Wait for it...'):
        start_time = time.time()
        BatchTestingExcelWriter(7, 1, nos, noc, nov, nod, nog, novc, nomd)
        st.write("..Done")
        end_time = time.time()
        st.write("Elapsed time:", str(datetime.timedelta(seconds=end_time-start_time)))

        dir_path = os.getcwd()
        for file_name in os.listdir(dir_path):
            if file_name.endswith(".xlsx"):
                file_path = os.path.join(dir_path, file_name)
                with open(file_path, 'rb') as file:
                    file_contents = file.read()
                    if st.download_button(label='📥 Export Excel File', data=file, file_name="Simulations.xlsx", mime="text/xlsx", key=2):
                        break


'''
Lights Out

Given a 3x3 matrix representing rows and columns of light bulbs,
the initial state of the lights are on (represented by 1).
Given another 3x3 matrix representing the number of toggles to the
initial state of the lights, determine the look of the lights
after the toggles. Note that each toggle will toggle all horizontally
and vertically adjacent lights.
'''

lights = [[1, 1, 1],
          [1, 1, 1],
          [1, 1, 1]]

def toggle_adj(*args: tuple):
    """
    Summary:
        Toggles all horizontally and vertically adjacent lights (and itself)
        given the coordinate of the light switch in the 3x3 matrix.

    Args:
        args (tuple): represents the Cartesian coordinate of the light switch to be
        toggled.
    """
    (i, j) = args
    n = len(lights)  # represents the length of the 3x3 matrix (n = 3)

    # Determine the appropriate range of light switches
    # to be searched to reduce the number of operations.
    rxl = 0 if i <= 1 else 1
    rxu = 2 if i < 1 else n
    ryl = 0 if j <= 1 else 1
    ryu = 2 if j < 1 else n
    for di in range(rxl, rxu):
        for dj in range(ryl, ryu):
            if (abs(di - i) + abs(dj - j)) < 2:
                lights[di][dj] ^= 1

# Get the 3x3 matrix representing the number of toggles on each light
for i in range(3):
    row = list(map(int, input().split()))
    for j in range(len(row)):
        if row[j] & 1:
            # Toggle the light switch
            toggle_adj(i, j)

print(*lights, sep="\n")

'''
Notes:

A relatively straightforward implementation when done properly.
It is important to realize the following details:
    1: Use bitwise operations to reduce unnecessary computation.
    2: Determine the range of the light switches to be toggled to
       minimize the number of toggle operations, if needed.
    3: At first it may be obvious to implement a solution where the input
       is taken in first, then determine the light switches to be toggled
       (and store them in a list), then implement the toggle operation.
       However, it is important to optimize the process of:
            input taking -> switching finding -> switch toggling
       in order to achieve the minimal amount of time to output the correct solution.
'''


class Solution:
    def valid(self, num, i, val, cache):
        n = len(num)
        if i == n:
            return val == 0
        key = (i, val)
        if key in cache:
            return cache[key]
        curr = 0
        for j in range(i, n):
            curr = 10 * curr + num[j]
            if self.valid(num, j + 1, val - curr, cache):
                cache[key] = True
                return True
        cache[key] = False
        return False

    def punishmentNumber(self, n: int) -> int:
        res = 0
        for i in range(1, n + 1):
            if self.valid(list(map(int, str(i * i))), 0, i, {}):
                res += i * i
        return res


#Escreva uma função em Python que recebe um número e verifica se ele é positivo

def pos(num):
    if num > 0:
        return "É positivo"
    elif num < 0:
        return "É negativo"
    else:
        return "É igual a 0"

x = int(input("Digite um número: "))
result = pos(x)
print (result)


import control as ct
import numpy as np

# %% Projeto do Compensador
class Compensador:
    def __init__(self, planta, P, Q):

        # Ordem do sistema
        n = planta.A.shape[0]

        # Projeto numérico do regulador integral
        Aa = np.block([[planta.A, np.zeros((n, 1))], [-planta.C, 0]])
        Ba = np.block([[planta.B], [0]])
        Ka = ct.acker(Aa, Ba, P)
        K = Ka[:, :n]
        Ki = Ka[:, n]

        # Projeto numérico do observador
        L = ct.acker(planta.A.T, planta.C.T, Q).T

        # Matrizes para implementação do compensador
        Ar = np.block(
            [[planta.A-planta.B@K-L@planta.C, -planta.B*Ki], [np.zeros((1, n+1))]])
        Br = np.block([[L, np.zeros((n, 1))], [-1, 1]])

        # Armazena atributos do objeto
        self.Ar = Ar
        self.Br = Br
        self.K = K[0, :]
        self.Ki = Ki
        self.Ka = Ka[0, :]
        self.L = L

    # Definindo os sinais de referência para rastreamento
    @staticmethod
    def ref_seno(t):
        return (mag.x0*np.sin(2*pi*t))

    @staticmethod
    def ref_quad(t):
        return (mag.x0)*(np.sin(2*pi*t) >= 0)


from django.shortcuts import render
from django.http import HttpResponse

from . import forms

## Initalize dictionary of neighborhood coordinates
neighborhood_coord_dict = forms.get_neighborhood_dict()
c = {"neighborhoods": neighborhood_coord_dict}

## Blank/unknown site page
def blank(request):
	return render(request, "maps/default.html")

## Main site page
def healthy_neighborhoods(request):
	c["form"] = forms.Variable()

	if request.method == "POST":
		if "ex_1" in request.POST:
			var_1 = "Below Poverty Level"
			var_2 = "Childhood Blood Lead Level Screening"
		elif "ex_2" in request.POST:
			var_1= "Assault (Homicide)"
			var_2 = "Per Capita Income"
		elif "ex_3" in request.POST:
			var_1 = "Dependency"
			var_2 = "Firearm-related"
		else:
			form = forms.Variable(request.POST)
			if form.is_valid():
				var_1 = form.cleaned_data["variable_1"]
				var_2 = form.cleaned_data["variable_2"]

		c["variables"] = [var_1.lower(), var_2.lower()]

		coef, neighborhood_list = forms.get_result_list(var_1, var_2)

		c["coef"] = '{0:.3f}'.format(coef)

		## Add color identifiers to neighborhood dictionaries
		forms.get_combo_dict(neighborhood_list, neighborhood_coord_dict)

		return render(request, "maps/healthy_neighborhoods.html", c)
	return render(request, "maps/healthy_neighborhoods_start.html", c)

## Site documentaion page
def documentation(request):
	return render(request, "maps/documentation.html")


import pandas as pd
import numpy as np

df= pd.read_csv('../Datos/Premios2020.csv',encoding='ISO-8859-1')

# print(df.isnull().sum())
# moda = df.release.mode()
# valores = {'release': moda[0]}
# df.fillna(value=valores, inplace=True)

moda = df['release'].mode()
df['release'] = df['release'].replace([np.nan], moda)

print(pd.value_counts(df['release']))

mapeo = {"release": {"January":1, "February":2, "March":3,
                      "April":4, "May":5, "June":6,
                      "July":7, "August":8, "September":9,
                      "October":10, "November":11, "December":12}}

df.replace(mapeo, inplace=True)
print(df['release'].describe())


import pygame
import random

# Dimensiones de la ventana del juego
WIDTH = 800
HEIGHT = 600

# Colores
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# Tamaño del jugador
PLAYER_WIDTH = 60
PLAYER_HEIGHT = 80

# Tamaño de la bala
BULLET_WIDTH = 10
BULLET_HEIGHT = 20

# Velocidad del jugador
PLAYER_SPEED = 8

# Velocidad de la bala
BULLET_SPEED = 10

# Velocidad del enemigo
ENEMY_SPEED = 5

# Inicializar Pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

# Clase para representar al jugador
class Player:
    def __init__(self):
        self.rect = pygame.Rect(50, HEIGHT - PLAYER_HEIGHT - 10, PLAYER_WIDTH, PLAYER_HEIGHT)
        self.color = BLUE
        self.speed = PLAYER_SPEED
        self.lives = 3

    def update(self, keys):
        if keys[pygame.K_LEFT]:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT]:
            self.rect.x += self.speed

        # Limitar el movimiento del jugador dentro de la pantalla
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH

    def draw(self):
        pygame.draw.rect(screen, self.color, self.rect)

# Clase para representar a las balas
class Bullet:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, BULLET_WIDTH, BULLET_HEIGHT)
        self.color = RED
        self.speed = BULLET_SPEED

    def update(self):
        self.rect.x += self.speed

    def draw(self):
        pygame.draw.rect(screen, self.color, self.rect)

# Clase para representar a los enemigos
class Enemy:
    def __init__(self, x):
        self.rect = pygame.Rect(x, HEIGHT - PLAYER_HEIGHT - 10, PLAYER_WIDTH, PLAYER_HEIGHT)
        self.color = RED
        self.speed = ENEMY_SPEED

    def update(self):
        self.rect.x -= self.speed

    def draw(self):
        pygame.draw.rect(screen, self.color, self.rect)

# Listas para almacenar a las balas y enemigos
bullets = []
enemies = []

# Crear al jugador
player = Player()

# Bucle principal del juego
running = True
while running:
    keys = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # Disparar una bala cuando se presiona la tecla de espacio
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            bullet = Bullet(player.rect.centerx, player.rect.y)
            bullets.append(bullet)

    screen.fill(BLACK)

    player.update(keys)
    player.draw()

    # Actualizar y dibujar las balas
    for bullet in bullets:
        bullet.update()
        bullet.draw()

        # Eliminar las balas que salen de la pantalla
        if bullet.rect.right > WIDTH:
            bullets.remove(bullet)

    # Generar nuevos enemigos
    if random.randint(0, 100) < 2:
        enemy = Enemy(WIDTH)
        enemies.append(enemy)

    # Actualizar y dibujar a los enemigos
    for enemy in enemies:
        enemy.update()
        enemy.draw()

        # Comprobar colisiones entre las balas y los enemigos
        for bullet in bullets:
            if bullet.rect.colliderect(enemy.rect):
                bullets.remove(bullet)
                enemies.remove(enemy)
                break

        # Comprobar colisiones entre el jugador y los enemigos
        if player.rect.colliderect(enemy.rect):
            player.lives -= 1
            enemies.remove(enemy)

        # Eliminar los enemigos que salen de la pantalla
        if enemy.rect.right < 0:
            enemies.remove(enemy)

    # Comprobar si el jugador ha perdido todas las vidas
    if player.lives <= 0:
        running = False

    # Dibujar el contador de vidas
    font = pygame.font.Font(None, 36)
    text = font.render(f"Lives: {player.lives}", True, RED)
    screen.blit(text, (10, 10))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()