from dataclasses import dataclass, fields
from typing import Any, ClassVar

from schema import Schema
from puft.core.db.db import orm
from puft.tools.log import log
from puft.core.cell.cell_error import CellError
from warepy import snakefy
from puft.core.ie.ie import Ie

@dataclass
class Cell(Ie):
    Model: ClassVar = None
    id: int
    type: str

    @classmethod
    def _get_formatted_name(cls, base_name: str = 'Cell') -> str:
        return super()._get_formatted_name(base_name)

    @classmethod
    def gen(cls, instance: orm.Model) -> 'Cell':
        return cls._gen_according(instance)

    @classmethod
    def _gen_according(cls, instance: orm.Model) -> Any:
        """Traverse all Models of all subclasses to find according to given
        type model cell.
        """
        cell_type_by_model_type: dict = {}
        subclasses: list[type] = cls.__subclasses__()
        model_type = type(instance)

        # Get models for cells from all inheritance tree
        cell_type_by_model_type.update(
            cls._get_ie_type_by_model_type(subclasses))

        try:
            cell_type = cell_type_by_model_type[model_type]
        except KeyError:
            raise CellError(
                f'Cannot find cell with requested model type: {model_type}\n'
                'Maybe you forgot to add `Model=...` to Ie\'s definition?')
        else:
            return cell_type.gen_instance(instance)

    @classmethod
    def gen_instance(cls) -> 'Ie':
        raise NotImplementedError('Should be re-implemented in child class')

    @classmethod
    def _get_ie_type_by_model_type(cls, subclasses: list) -> dict:
        cell_type_by_model_type: dict[type, type] = {}

        # Get own model
        if cls.Model is not None:
            cell_type_by_model_type[cls.Model] = cls

        # Traverse inheritance tree
        for subclass in subclasses:
            cell_type_by_model_type.update(
                subclass._get_ie_type_by_model_type(
                    subclass.__subclasses__()))

        return cell_type_by_model_type


def encrypt_caesar(plaintext: str, shift: int = 3):  # -> str:
    """
        Encrypts plaintext using a Caesar cipher.

        >>> encrypt_caesar("PYTHON")
        'SBWKRQ'
        >>> encrypt_caesar("python")
        'sbwkrq'
        >>> encrypt_caesar("Python3.6")
        'Sbwkrq3.6'
        >>> encrypt_caesar("")
        ''
    """
    tmp = [ord(c) for c in plaintext]
    A = []
    for i in tmp:
        if i in range(65, 91) or i in range(97, 123):
            if i > 90 - shift and i < 97:
                i = 64 - (90 - i)
            elif i > 122 - shift:
                i = 96 - (122 - i)
            i += shift
        A.append(i)
    result = [chr(c) for c in A]
    return ''.join(result)

def decrypt_caesar(ciphertext: str, shift: int = 3) -> str:
    """
        Decrypts a ciphertext using a Caesar cipher.

        >>> decrypt_caesar("SBWKRQ")
        'PYTHON'
        >>> decrypt_caesar("sbwkrq")
        'python'
        >>> decrypt_caesar("Sbwkrq3.6")
        'Python3.6'
        >>> decrypt_caesar("")
        ''
    """
    tmp = [ord(c) for c in ciphertext]
    A = []
    for i in tmp:
        if i in range(65, 91) or i in range(97, 123):
            if i < 65 + shift:
                i = 90 + (i - 64)
            elif i > 90 and i < 97 + shift:
                i = 122 + (i - 96)
            i -= shift
        A.append(i)
    result = [chr(c) for c in A]
    return ''.join(result)

def encrypt_vigenere_full(plaintext: str, keyword: str) -> str:
    base = 128 - 32
    l = len(plaintext)
    lk = len(keyword)
    repeatN = l // lk
    remainder = l % lk
    fullKey = keyword * repeatN + keyword[: remainder]
    result = []
    for idx, val in enumerate(plaintext):
        key = ord(plaintext[idx]) + ord(fullKey[idx])
        result.append(chr(key % base + 32))
    return ''.join(result)

def decrypt_vigenere_full(ciphertext: str, keyword: str) -> str:
    base = 128 - 32
    l = len(ciphertext)
    lk = len(keyword)
    repeatN = l // lk
    remainder = l % lk
    fullKey = keyword * repeatN + keyword[: remainder]
    result = []
    for idx, val in enumerate(ciphertext):
        key = ord(ciphertext[idx]) - 32 - ord(fullKey[idx]) + base
        result.append(chr(key % base))
    return ''.join(result)

dictA = [chr(i) for i in range(65, 91)]
dicta = [chr(i) for i in range(97, 123)]
dict = dictA + dicta

def findIdx(c):
    return dict.index(c)

def encrypt_vigenere(plaintext: str, keyword: str) -> str:
    """
    Encrypts plaintext using a Vigenere cipher.

    >>> encrypt_vigenere("PYTHON", "A")
    'PYTHON'
    >>> encrypt_vigenere("python", "a")
    'python'
    >>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
    'LXFOPVEFRNHR'
    """
    base = 52
    l = len(plaintext)
    lk = len(keyword)
    repeatN = l // lk
    remainder = l % lk
    fullKey = keyword * repeatN + keyword[: remainder]
    result = []
    for idx, val in enumerate(plaintext):
        key = findIdx(plaintext[idx]) + findIdx(fullKey[idx])
        result.append(dict[(key % base)])
    return ''.join(result)

def decrypt_vigenere(ciphertext: str, keyword: str) -> str:
    """
    Decrypts a ciphertext using a Vigenere cipher.

    >>> decrypt_vigenere("PYTHON", "A")
    'PYTHON'
    >>> decrypt_vigenere("python", "a")
    'python'
    >>> decrypt_vigenere("LXFOPVEFRNHR", "LEMON")
    'ATTACKATDAWN'
    """
    base = 52
    l = len(ciphertext)
    lk = len(keyword)
    repeatN = l // lk
    remainder = l % lk
    fullKey = keyword * repeatN + keyword[: remainder]
    result = []
    for idx, val in enumerate(ciphertext):
        key = findIdx(ciphertext[idx]) - findIdx(fullKey[idx]) + base
        result.append(dict[(key % base)])
    return ''.join(result)

if __name__ == '__main__':
    # x = encrypt_caesar('1@ABCDabcdUuWXYZwxyz')
    x = encrypt_caesar('pYThoN3.8')
    print(x)
    print(decrypt_caesar(x))

    y = encrypt_vigenere('ATTACKATDAWN', 'LEMON')
    print(y)
    print(decrypt_vigenere(y, 'LEMON'))


import jieba
import json
import numpy as np

class WordTable:
    def __init__(self):
        self.word2id_dict = {}
        self.id2word_dict = {}

    def build(self,corpus):
        '''
            从语料库中建立词表
            保存词表并保存用One-hot表示的语料库
        '''
        word2id_dict = {}
        id2word_dict = {}

        corpus_onehot = []

        word_id = 0
        jieba.load_userdict("user_dict.txt")
        for sentence in corpus:
            sentence_segL = jieba.cut(sentence)
            sentence_onehot = []
            for word in sentence_segL:
                word = word.strip()
                if word not in word2id_dict:
                    word2id_dict[word] = word_id
                    id2word_dict[word_id] = word
                    word_id += 1
                sentence_onehot.append(str(word2id_dict[word]))
            corpus_onehot.append(",".join(sentence_onehot)+"\n")
        self.word2id_dict, self.id2word_dict = word2id_dict, id2word_dict

        with open("out/corpus_onehot.txt","w",encoding="utf-8") as fp:
            fp.writelines(corpus_onehot)

        with open('out/word2id_dict.json','w',encoding="utf-8") as fp:
            json.dump(self.word2id_dict, fp,indent=4,ensure_ascii=False)
        with open('out/id2word_dict.json','w',encoding="utf-8") as fp:
            json.dump(self.id2word_dict, fp,indent=4,ensure_ascii=False)

    def load_dict(self):
        with open('out/word2id_dict.json','r',encoding="utf-8") as fp:
            self.word2id_dict = json.load(fp)
        with open('out/id2word_dict.json','r',encoding="utf-8") as fp:
            self.id2word_dict = json.load(fp)

    def word2id(self,word):
        return self.word2id_dict[word]

    def id2word(self,word_id):
        if type(word_id) is not str:
            word_id = str(word_id)
        return self.id2word_dict[word_id]

    def prepare_gensim(self):
        with open("out/corpus_onehot.txt","r",encoding="utf-8") as fp:
            textL = fp.readlines()

        fp = open("out/corpus_onehot_text.txt","w",encoding="utf-8")
        for text_onehot in textL:
            text = [self.id2word(i.strip()) for i in text_onehot.split(",")]
            text_str = " ".join(text)
            fp.write(text_str+"\n")
        fp.close()

    def __len__(self):
        return len(self.word2id_dict)

    def __getitem__(self,word_id):
        if type(word_id) is not str:
            word_id = str(word_id)
        return self.id2word_dict[word_id]

def cal_similarity(vec1,vec2):
    return np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))

def KNN(W,x,k=10):
    sim_np = np.matmul(W,x)/(1e-9+np.linalg.norm(W,axis=1)*np.linalg.norm(x))
    sim_indexL = sim_np.argsort().tolist()[:-(k+1):-1]
    return sim_indexL,[sim_np[i] for i in sim_indexL]

if __name__ == '__main__':
    word_table = WordTable()
    word_table.load_dict()
    word_table.prepare_gensim()

    # print(f"word_table length: {len(word_table)}")

    # print(cal_similarity([1,2],[1,1]))


import math
import time
from plotLive import liveGraph
import tkinter as tk

window = tk.Tk()
window.geometry("300x50")

window.rowconfigure([0, 1, 2, 3], minsize=25)
window.columnconfigure([0, 1, 2], minsize=100)

scaleVal = tk.DoubleVar()
scaleVal = scaleVal
scale = tk.Scale(from_ =0, to=100, orient=tk.HORIZONTAL, length=300, resolution=.1, variable=scaleVal)

scale.pack()

graph = liveGraph(Ylimits=[0,100],TkinterScale=False)

kp = .5
ki = .02
kd = .02
prevPoint =0
input = 0
setPoint = 50
output = 0
integral =0
lastError =0
dt =.01

val=0

scaleVal.set(50)

for val in range(1,4):
    setPoint = 50
    # if val == 1:
    #     setPoint = 50
    # elif val == 2:
    #     setPoint = 20
    # elif val == 3:
    #     setPoint = 80
    while True:
        window.update()

        time.sleep(.01)

        #print(f'KP: {(kp * (setPoint - input))} = {kp}* {setPoint} - {input}')
        print(f"{output} {setPoint} ")

        output += (kp * (setPoint - input))
        integral += (setPoint - input) * time.process_time()
        output += (ki * integral)
        output += kd * ((setPoint - input) - lastError / time.process_time())

        lastError = setPoint - input
        input += output
        graph.update(input)
        pass


import requests
import json
import sys
import base64
import datetime
import os

from cimetrics.env import get_env

# Always the same for metrics-devops
IMAGE_BRANCH_NAME = "cimetrics"
IMAGE_PATH = "_cimetrics/diff.png"
COMMENT_PATH = "_cimetrics/diff.txt"

class GithubPRPublisher(object):
    def __init__(self):
        self.env = get_env()
        if self.env is None:
            return

        self.request_header = {
            "content-type": "application/json",
            "Authorization": f"token {self.env.github_token}",
        }
        self.github_url = f"https://api.github.com/repos/{self.env.repo_id}"
        self.pull_request_id = self.env.pull_request_id

    def create_image_branch(self):
        # Does not do anything if the branch already exists
        params = {}
        params["ref"] = f"refs/heads/{IMAGE_BRANCH_NAME}"
        rep = requests.get(
            f"{self.github_url}/git/refs/heads/master",
            data="",
            headers=self.request_header,
        )
        json_rep = json.loads(rep.text)
        params["sha"] = json_rep["object"]["sha"]

        print(f"Creating branch {json.dumps(params)}")
        rep = requests.post(
            f"{self.github_url}/git/refs",
            data=json.dumps(params),
            headers=self.request_header,
        )

    def upload_image(self, encoded_image):
        params = {}
        params["message"] = "Uploading an image"
        params["branch"] = IMAGE_BRANCH_NAME
        params["content"] = encoded_image

        print(f"Uploading image to branch {IMAGE_BRANCH_NAME}")
        rep = requests.put(
            f"{self.github_url}/contents/{IMAGE_BRANCH_NAME}/image{datetime.datetime.now()}.png",
            data=json.dumps(params),
            headers=self.request_header,
        )
        json_rep = json.loads(rep.text)
        if "content" in json_rep:
            return json_rep["content"]["download_url"]
        else:
            raise Exception("Failed to upload image")

    def first_self_comment(self):
        rep = requests.get(
            f"{self.github_url}/issues/{self.pull_request_id}/comments",
            headers=self.request_header,
        )

        for comment in rep.json():
            login = comment.get("user", {}).get("login")
            if login == self.env.pr_user:
                return comment["id"]
        return None

    def publish_comment(self, image_report_url, comment):
        params = {}
        params["body"] = f"{comment}\n![images]({image_report_url})"

        comment_id = self.first_self_comment()
        if comment_id is None:
            print(f"Publishing comment to pull request {self.pull_request_id}")
            rep = requests.post(
                f"{self.github_url}/issues/{self.pull_request_id}/comments",
                data=json.dumps(params),
                headers=self.request_header,
            )
        else:
            print(
                f"Updating comment {comment_id} on pull request {self.pull_request_id}"
            )
            rep = requests.patch(
                f"{self.github_url}/issues/comments/{comment_id}",
                data=json.dumps(params),
                headers=self.request_header,
            )

if __name__ == "__main__":

    env = get_env()
    if env is None:
        print("Skipping publishing of PR comment (env)")
        sys.exit(0)

    publisher = GithubPRPublisher()

    publisher.create_image_branch()

    encoded_image = None
    with open(os.path.join(env.repo_root, IMAGE_PATH), "rb") as image_file:
        encoded_image = base64.b64encode(image_file.read())
    comment = ""
    with open(os.path.join(env.repo_root, COMMENT_PATH), "r") as comment_file:
        comment = comment_file.read()

    image_url = publisher.upload_image(str(encoded_image.decode()))
    publisher.publish_comment(image_url, comment)


# -----------------------------------------------------------------------------
#  (c) 2005 by Basler Vision Technologies
#  Section: Vision Components
#  Project: GenApiTest
#    Author:
#  $Header:
# -----------------------------------------------------------------------------

from genicam import *
import unittest
from genicamtestcase import GenicamTestCase
from testport import CTestPort, cast_buffer, cast_data, sizeof, CStructTestPort
from callbackhelper import CallbackObject

class CommandTestSuite(GenicamTestCase):
    def test_Command01(self):
        """[ GenApiTest@CommandTestSuite_TestCommand01.xml|gxml

        <Category Name="Root">
           <pFeature>command</pFeature>
        </Category>

        <Command Name="command">
           <pValue>myIntReg</pValue>
           <CommandValue>0x4321</CommandValue>
        </Command>

        <IntReg Name="myIntReg">
            <Address>0x00ff</Address>
            <Length>4</Length>
            <AccessMode>RW</AccessMode>
            <pPort>MyPort</pPort>
            <Sign>Unsigned</Sign>
            <Endianess>BigEndian</Endianess>
        </IntReg>

        <Port Name="MyPort"/>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommand01")

        # create and initialize a test port
        Port = CTestPort()
        Port.CreateEntry(0x00ff, "uint32_t", 42, RW, BigEndian)

        # connect the node map to the port
        Camera._Connect(Port, "MyPort")

        #
        # Test the ICommand interface
        #

        # retrieve the node and convert it to ICommand
        Node = Camera.GetNode("command")
        Cmd = Node
        self.assertTrue(bool(Node))
        self.assertTrue(bool(Cmd))
        self.assertEqual(intfICommand, Cmd.GetNode().GetPrincipalInterfaceType())

        ##### getproperty of command pointer -
        try:
            ValueStr, AttributeStr = Cmd.GetNode().GetProperty("CommandValue")
        except:
            pass

        # execute function
        Cmd.Execute()
        # is executing?
        self.assertEqual(False, Cmd.IsDone())
        # manipulate the command register in order to simulate a self-resetting toggle
        # CLittleEndian<int32_t> tmp
        tmp_data = Port.Read(0x00ff, sizeof("int32_t"))
        self.assertEqual(0x21430000, cast_buffer("int32_t", LittleEndian, tmp_data))
        tmp = 0
        Port.Write(0x00ff, cast_data("int32_t", LittleEndian, tmp))
        self.assertEqual(True, Cmd.IsDone())

        # once again with verification
        Cmd.Execute()
        self.assertEqual(False, Cmd.IsDone(True))
        Port.Write(0x00ff, cast_data("int32_t", LittleEndian, tmp))
        self.assertEqual(True, Cmd.IsDone(True))

        # happy path (what to test on execution without verification?)
        Cmd.Execute(False)

        # execute function
        Cmd()
        # is executing?
        self.assertEqual(False, Cmd.IsDone())
        # manipulate the command register in order to simulate a self-resetting toggle
        tmp_data = Port.Read(0x00ff, sizeof("int32_t"))
        self.assertEqual(0x21430000, cast_buffer("int32_t", LittleEndian, tmp_data))
        tmp = 0
        Port.Write(0x00ff, cast_data("int32_t", LittleEndian, tmp))
        self.assertEqual(True, Cmd.IsDone())

        # TestAccessMode
        self.assertEqual(RW, Cmd.GetAccessMode())

        #
        # Test the IValue interface
        #
        Value = Cmd
        strExec = "0"
        # function is done => value is "0"
        self.assertEqual(strExec, Value.ToString())
        # execute using a string
        strExec = "1"
        Value.FromString(strExec)
        # function is executing => value is "1"
        self.assertEqual(strExec, Value.ToString())
        self.assertTrue(None != Value.GetNode())

        # try to use an illegal string
        with self.assertRaises(InvalidArgumentException):
            Value.FromString("foo")

        Value.FromString("true")

    def test_Command02(self):
        """[ GenApiTest@CommandTestSuite_TestCommand02.xml|gxml

        <Command Name="command">
            <Value>0</Value>
            <CommandValue>1</CommandValue>
        </Command>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommand02")

        #
        # Test the ICommand interface
        #

        # retrieve the node and convert it to ICommand
        Node = Camera.GetNode("command")
        Cmd = Node
        self.assertTrue(bool(Node))
        self.assertTrue(bool(Cmd))

        #
        # Test the IValue interface
        #
        # Execute function
        Value = Cmd
        strExec = "0"
        # Function not executing => CommandValue is 0
        self.assertEqual(strExec, Value.ToString())

        # Execute function
        # 1st Method
        strExec = "0"
        with self.assertRaises(InvalidArgumentException):
            Value.FromString(strExec)

        # 2nd Method
        strExec = "1"
        Value.FromString(strExec)  # equivalent to "ptrCmd.Execute()"

        # Function not executing (a floating command is immediatelx ready )
        strExec = "0"
        self.assertEqual(strExec, Value.ToString())

        # is executing?
        self.assertEqual(True, Cmd.IsDone())

    def test_Command03(self):
        """[ GenApiTest@CommandTestSuite_TestCommand03.xml|gxml

        <Command Name="Command">
            <pValue>Value</pValue>
            <pCommandValue>CommandValue</pCommandValue>
        </Command>

        <Integer Name="CommandValue">
            <Value>42</Value>
        </Integer>

        <Integer Name="Value">
            <Value>0</Value>
        </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommand03")

        Command = Camera.GetNode("Command")
        self.assertTrue(bool(Command))

        Value = Camera.GetNode("Value")
        self.assertTrue(bool(Value))

        CommandValue = Camera.GetNode("CommandValue")
        self.assertTrue(bool(CommandValue))

        CallbackTarget = CallbackObject()
        Register(Command.GetNode(), CallbackTarget.Callback)

        # nothing happened so no callback expected
        self.assertEqual(True, Command.IsDone())
        self.assertEqual(0, CallbackTarget.Count())

        # a first callback happens after execute
        Command.Execute()
        self.assertEqual(1, CallbackTarget.Count())

        for count in range(10, 0):
            # no callback on IsDone because the value has not changed yet
            self.assertEqual(False, Command.IsDone())
            # self.assertEqual( (int64_t)42, ptrValue.GetValue() )
            # self.assertEqual( 1, CallbackTarget.Count() )

        # now the value has changed so we expect a callback
        Value.SetValue(0)
        self.assertEqual(2, CallbackTarget.Count())

        # On IsDone the Command node notives that the vale has changed and fires another time
        self.assertEqual(True, Command.IsDone())
        self.assertEqual(3, CallbackTarget.Count())

    def test_Command04(self):
        """[ GenApiTest@CommandTestSuite_TestCommand04.xml|gxml

        <Command Name="Command">
            <ImposedAccessMode>WO</ImposedAccessMode>
            <pValue>Value</pValue>
            <pCommandValue>CommandValue</pCommandValue>
        </Command>

        <Integer Name="CommandValue">
            <Value>42</Value>
        </Integer>

        <Integer Name="Value">
            <Value>0</Value>
        </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommand04")

        Command = Camera.GetNode("Command")
        self.assertTrue(bool(Command))

        Value = Camera.GetNode("Value")
        self.assertTrue(bool(Value))

        CommandValue = Camera.GetNode("CommandValue")
        self.assertTrue(bool(CommandValue))

        CallbackTarget = CallbackObject()
        Register(Command.GetNode(), CallbackTarget.Callback)

        # due to the execute a callback is fired
        Command.Execute()
        self.assertEqual(1, CallbackTarget.Count())

        # since the command node is WO IsDone does not trigger a callback
        self.assertEqual(True, Command.IsDone())
        self.assertEqual(1, CallbackTarget.Count())

    def test_Command05(self):
        """[ GenApiTest@CommandTestSuite_TestCommand05.xml|gxml

        <Command Name="Command">
            <pValue>Value</pValue>
            <pCommandValue>CommandValue</pCommandValue>
            <PollingTime>1000</PollingTime>
        </Command>

        <Integer Name="CommandValue">
            <Value>42</Value>
        </Integer>

        <Integer Name="Value">
            <Value>0</Value>
        </Integer>

        <Command Name="CommandWO">
            <ImposedAccessMode>WO</ImposedAccessMode>
            <pValue>Value</pValue>
            <pCommandValue>CommandValue</pCommandValue>
            <PollingTime>1000</PollingTime>
        </Command>

        <Command Name="Command_ValueWO">
            <pValue>ValueWO</pValue>
            <pCommandValue>CommandValue</pCommandValue>
            <PollingTime>1000</PollingTime>
        </Command>

        <Integer Name="ValueWO">
            <ImposedAccessMode>WO</ImposedAccessMode>
            <Value>0</Value>
        </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommand05")

        Command = Camera.GetNode("Command")
        self.assertTrue(bool(Command))

        Value = Camera.GetNode("Value")
        self.assertTrue(bool(Value))

        CommandValue = Camera.GetNode("CommandValue")
        self.assertTrue(bool(CommandValue))

        CallbackTarget = CallbackObject()
        Register(Command.GetNode(), CallbackTarget.Callback)

        Command.Execute()
        self.assertEqual(1, CallbackTarget.Count())
        self.assertEqual(False, Command.IsDone())

        Camera._Poll(500)
        self.assertEqual(1, CallbackTarget.Count())
        self.assertEqual(False, Command.IsDone())

        Camera._Poll(500)
        self.assertEqual(2, CallbackTarget.Count())
        self.assertEqual(False, Command.IsDone())

        # now the self-clearing flag is clearing
        Value.SetValue(0)
        # this is due to the fact that Command is dependent on value
        self.assertEqual(3, CallbackTarget.Count())

        Camera._Poll(1000)
        self.assertEqual(4, CallbackTarget.Count())
        self.assertEqual(True, Command.IsDone())

        # similar tests with WO node (done immediatelly, no polling)
        CommandWO = Camera.GetNode("CommandWO")
        self.assertTrue(bool(CommandWO))

        CallbackTargetWO = CallbackObject()
        Register(CommandWO.GetNode(), CallbackTargetWO.Callback)

        CommandWO.Execute()
        self.assertEqual(1, CallbackTargetWO.Count())
        self.assertEqual(True, CommandWO.IsDone())

        Camera._Poll(1000)
        self.assertEqual(1, CallbackTargetWO.Count())
        self.assertEqual(True, CommandWO.IsDone())

        # and again with command having a WO value
        Command_ValueWO = Camera.GetNode("Command_ValueWO")
        self.assertTrue(bool(Command_ValueWO))

        CallbackTarget_ValueWO = CallbackObject()
        Register(Command_ValueWO.GetNode(), CallbackTarget_ValueWO.Callback)

        Command_ValueWO.Execute()
        self.assertEqual(1, CallbackTarget_ValueWO.Count())
        self.assertEqual(True, Command_ValueWO.IsDone())

        Camera._Poll(1000)
        self.assertEqual(1, CallbackTarget_ValueWO.Count())
        self.assertEqual(True, Command_ValueWO.IsDone())

    def test_Command06(self):
        """[ GenApiTest@CommandTestSuite_TestCommand06.xml|gxml

        <Command Name="Command">
            <pIsLocked>LockIt</pIsLocked>
            <ImposedAccessMode>WO</ImposedAccessMode>
            <pValue>Value</pValue>
            <pCommandValue>CommandValue</pCommandValue>
        </Command>

        <Integer Name="CommandValue">
            <pIsImplemented>CommandValueIsImpl</pIsImplemented>
            <pIsAvailable>CommandValueIsAvail</pIsAvailable>
            <Value>42</Value>
        </Integer>

        <Integer Name="Value">
            <Value>0</Value>
        </Integer>

        <Integer Name="LockIt">
            <Value>1</Value>
        </Integer>

        <Integer Name="CommandValueIsAvail">
            <Value>1</Value>
        </Integer>

        <Integer Name="CommandValueIsImpl">
            <Value>1</Value>
        </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommand06")

        Command = Camera.GetNode("Command")

        self.assertEqual(NA, Command.GetAccessMode())

        with self.assertRaises(AccessException):
            Command.FromString("42")
        with self.assertRaises(AccessException):
            Command.Execute()

        # disable the command value
        CmdValueAvailability = Camera.GetNode("CommandValueIsAvail")
        LockCommand = Camera.GetNode("LockIt")
        LockCommand.SetValue(0)
        CmdValueAvailability.SetValue(0)
        self.assertEqual(NA, Command.GetAccessMode())
        with self.assertRaises(AccessException):
            Command.FromString("42")
        with self.assertRaises(AccessException):
            Command.Execute()

        CmdValueImpl = Camera.GetNode("CommandValueIsImpl")
        CmdValueImpl.SetValue(0)
        self.assertEqual(NI, Command.GetAccessMode())

    def test_Command07(self):
        """[ GenApiTest@CommandTestSuite_TestCommand07.xml|gxml

            <Command Name="CommandRO">
                <ImposedAccessMode>RO</ImposedAccessMode>
                <pValue>Value</pValue>
                <CommandValue>1</CommandValue>
            </Command>

            <Command Name="Command_ValueWO">
                <pValue>Value</pValue>
                <pCommandValue>CommandValueWO</pCommandValue>
            </Command>

            <Integer Name="CommandValueWO">
                <ImposedAccessMode>WO</ImposedAccessMode>
                <Value>42</Value>
            </Integer>

            <Integer Name="Value">
                <Value>0</Value>
            </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommand07")

        CommandRO = Camera.GetNode("CommandRO")
        self.assertTrue(bool(CommandRO))
        Command_ValueWO = Camera.GetNode("Command_ValueWO")
        self.assertTrue(bool(Command_ValueWO))

        with self.assertRaises(AccessException):
            CommandRO.Execute()
        with self.assertRaises(AccessException):
            Command_ValueWO.Execute()

    def test_CommandMantis250(self):
        """[ GenApiTest@CommandTestSuite_TestCommandMantis250.xml|gxml

        <Integer Name="BinningVertical">
          <pValue>VerticalBinningReg</pValue>
          <Representation>Linear</Representation>
        </Integer>

        <IntReg Name="VerticalBinningReg">
          <Address>0x4</Address>
          <Length>4</Length>
          <AccessMode>RW</AccessMode>
          <pPort>MyPort</pPort>
          <pInvalidator>UserSetLoadReg</pInvalidator>
          <Sign>Unsigned</Sign>
          <Endianess>BigEndian</Endianess>
        </IntReg>

        <Command Name="Command">
          <pValue>UserSetLoadReg</pValue>
          <pCommandValue>CommandValue</pCommandValue>
        </Command>

        <Integer Name="CommandValue">
          <Value>42</Value>
        </Integer>

        <IntReg Name="UserSetLoadReg">
          <Address>0x8</Address>
          <Length>4</Length>
          <AccessMode>RW</AccessMode>
          <pPort>MyPort</pPort>
          <Cachable>NoCache</Cachable>
          <Sign>Unsigned</Sign>
          <Endianess>BigEndian</Endianess>
        </IntReg>

        <Port Name="MyPort"/>

        """
        Camera = CNodeMapRef()

        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommandMantis250")

        Port = CTestPort()
        Port.CreateEntry(0x0004, "uint32_t", 2, RW, BigEndian)  # VerticalBinningReg
        Port.CreateEntry(0x0008, "uint64_t", 0, RW, BigEndian)  # UserSetLoadReg

        # connect the node map to the port
        Camera._Connect(Port, "MyPort")

        Command = Camera.GetNode("Command")

        Binning = Camera.GetNode("BinningVertical")

        CallbackBinning = CallbackObjectMantis250()
        Register(Binning.GetNode(), CallbackBinning.Callback)

        CallbackCommand = CallbackObjectMantis250()
        Register(Command.GetNode(), CallbackCommand.Callback)

        # this writes 42 to the UserSetLoadReg
        # because VerticalBinningReg has a pInvalidates pointer to UserSetLoadReg it is invalidated
        Command.Execute()
        self.assertEqual(1, CallbackCommand.Count())
        self.assertEqual(1, CallbackBinning.Count())

        # since UserSetLoadReg has not change no callback fires on IsDone
        self.assertEqual(False, Command.IsDone())
        self.assertEqual(1, CallbackBinning.Count())
        self.assertEqual(1, CallbackCommand.Count())

        # now we reset UserSetLoadReg
        value = 0
        AccessMode = RO
        Port.UpdateEntry(0x0008, cast_data("uint64_t", LittleEndian, value), AccessMode)

        # on the next IsDone the callback fires
        self.assertEqual(True, Command.IsDone())
        self.assertEqual(2, CallbackCommand.Count())
        self.assertEqual(2, CallbackBinning.Count())

    def test_CommandMantis257(self):
        """[ GenApiTest@CommandTestSuite_TestCommandMantis257.xml|gxml

        <Command Name="Command">
            <pValue>Value</pValue>
            <pCommandValue>CommandValue</pCommandValue>
        </Command>

        <Integer Name="CommandValue">
            <Value>42</Value>
        </Integer>

        <Integer Name="Value">
            <Value>0</Value>
        </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommandMantis257")

        Command = Camera.GetNode("Command")

        Value = Camera.GetNode("Value")

        CommandValue = Camera.GetNode("CommandValue")

        CallbackTarget = CallbackObjectMantis257()
        Register(Command.GetNode(), CallbackTarget.Callback)

        # due to the execute a callback is fired
        Command.Execute()
        self.assertEqual(1, CallbackTarget.Count())
        self.assertEqual(False, CallbackTarget.NodeError())

        # due to changing the value another callback fires
        # BEWARE: inside the callback function (see CallbackObjectMantis257 class)
        # there is a call to IsDone. Since the cale has changed to
        # zero the command is now done and another callback fires
        Value.SetValue(0)
        self.assertEqual(3, CallbackTarget.Count())

        # since we have already called IsDone once no additional callback is fired.
        self.assertEqual(True, Command.IsDone())
        self.assertEqual(3, CallbackTarget.Count())

    # modification of TestCommandMantis250, where the pInvalidator points directly to the command node
    # the depending features should get updated twice per command as well
    def test_CommandMantis250_sch11(self):
        # <pInvalidator> pointing to a non-register node
        # if(GenApiSchemaVersion == v1_0)
        #    return

        """[ GenApiTest@CommandTestSuite_TestCommandMantis250_sch11.xml|gxml
        <Integer Name="BinningVertical">
          <pValue>pVerticalBinningReg</pValue>
          <Representation>Linear</Representation>
        </Integer>
        <IntReg Name="pVerticalBinningReg">
          <Address>0x4</Address>
          <Length>4</Length>
          <AccessMode>RW</AccessMode>
          <pPort>MyPort</pPort>
          <pInvalidator>Command</pInvalidator>
          <Sign>Unsigned</Sign>
          <Endianess>BigEndian</Endianess>
        </IntReg>

        <Command Name="Command">
            <pValue>pUserSetLoadReg</pValue>
            <pCommandValue>CommandValue</pCommandValue>
        </Command>

        <Integer Name="CommandValue">
            <Value>42</Value>
        </Integer>

        <IntReg Name="pUserSetLoadReg">
          <Address>0x8</Address>
          <Length>4</Length>
          <AccessMode>RW</AccessMode>
          <pPort>MyPort</pPort>
          <Cachable>NoCache</Cachable>
          <Sign>Unsigned</Sign>
          <Endianess>BigEndian</Endianess>
        </IntReg>

        <Port Name="MyPort"/>

        """
        Camera = CNodeMapRef()

        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommandMantis250_sch11")

        Port = CTestPort()
        Port.CreateEntry(0x0004, "uint32_t", 2, RW, BigEndian)
        Port.CreateEntry(0x0008, "uint64_t", 0, RW, BigEndian)

        # connect the node map to the port
        Camera._Connect(Port, "MyPort")

        Command = Camera.GetNode("Command")

        Binning = Camera.GetNode("BinningVertical")

        CallbackBinning = CallbackObjectMantis250()
        Register(Binning.GetNode(), CallbackBinning.Callback)

        CallbackCommand = CallbackObjectMantis250()
        Register(Command.GetNode(), CallbackCommand.Callback)

        Command.Execute()
        self.assertEqual(1, CallbackBinning.Count())

        self.assertEqual(False, Command.IsDone())
        self.assertEqual(False, Command.IsDone(False))
        self.assertEqual(1, CallbackBinning.Count())
        self.assertEqual(1, CallbackCommand.Count())

        value = 0
        AccessMode = RO
        Port.UpdateEntry(0x0008, cast_data("uint64_t", LittleEndian, value), AccessMode)

        self.assertEqual(True, Command.IsDone(False))
        self.assertEqual(True, Command.IsDone())
        self.assertEqual(2, CallbackCommand.Count())
        self.assertEqual(2, CallbackBinning.Count())

    def test_CornerCases(self):
        """[ GenApiTest@CommandTestSuite_TestCornerCases.xml|gxml

        <Command Name="CommandValWO">
            <pValue>Value</pValue>
            <pCommandValue>CommandValueWO</pCommandValue>
        </Command>

        <Integer Name="CommandValueWO">
            <ImposedAccessMode>WO</ImposedAccessMode>
            <Value>42</Value>
        </Integer>

        <Integer Name="Value">
            <Value>0</Value>
        </Integer>

        <Command Name="CommandValNI">
            <pValue>Value</pValue>
            <pCommandValue>CommandValueNI</pCommandValue>
        </Command>

        <Integer Name="CommandValueNI">
            <pIsImplemented>Zero</pIsImplemented>
            <Value>42</Value>
        </Integer>

        <Integer Name="Zero">
            <Value>0</Value>
        </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCornerCases")

        # test command which does not have readable command value
        CommandValWO = Camera.GetNode("CommandValWO")
        self.assertTrue(bool(CommandValWO))
        with self.assertRaises(AccessException):
            CommandValWO.Execute()
        # ??self.assertRaises (ptrCommandValWO.IsDone(), AccessException)
        self.assertEqual(NA, CommandValWO.GetAccessMode())

        # test command which has command value NI
        CommandValNI = Camera.GetNode("CommandValNI")
        self.assertTrue(bool(CommandValNI))
        with self.assertRaises(AccessException):
            CommandValNI.Execute()
        self.assertEqual(NI, CommandValNI.GetAccessMode())
        with self.assertRaises(AccessException):
            CommandValNI.IsDone()

    def test_CommandCaching(self):
        """[ GenApiTest@CommandTestSuite_TestCommandCaching.xml|gxml

        <Command Name="Command">
           <pValue>Value</pValue>
           <pCommandValue>CommandValue</pCommandValue>
        </Command>

        <Integer Name="Value">
           <Value>0</Value>
        </Integer>

        <IntReg Name="CommandValue">
            <Address>0x0000</Address>
            <Length>4</Length>
            <AccessMode>RW</AccessMode>
            <pPort>Device</pPort>
            <pInvalidator>Value</pInvalidator>
            <Sign>Unsigned</Sign>
            <Endianess>LittleEndian</Endianess>
        </IntReg>

        <Port Name="Device"/>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestCommandCaching")

        regs = [("ValueCommand", "uint32_t", 0, RW, LittleEndian),
                ]

        Port = CStructTestPort(regs)
        Camera._Connect(Port, "Device")

        Command = Camera.GetNode("Command")

        Value = Camera.GetNode("Value")

        Port.ValueCommand = 1
        Command.Execute()
        self.assertEqual(1, Value.GetValue())

        Port.ValueCommand = 2
        Command.Execute()
        self.assertEqual(2, Value.GetValue())

    def test_Ticket768(self):
        """[ GenApiTest@CommandTestSuite_TestTicket768.xml|gxml

        <Command Name="MyCommand1">
           <pValue>ValueReg1</pValue>
           <CommandValue>1</CommandValue>
        </Command>

        <IntReg Name="ValueReg1">
            <Address>0x0000</Address>
            <Length>4</Length>
            <AccessMode>RW</AccessMode>
            <pPort>Device</pPort>
            <Cachable>NoCache</Cachable>
            <Sign>Unsigned</Sign>
            <Endianess>LittleEndian</Endianess>
        </IntReg>

        <Command Name="MyCommand2">
           <pValue>ValueReg2</pValue>
           <CommandValue>1</CommandValue>
        </Command>

        <IntReg Name="ValueReg2">
            <Address>0x0004</Address>
            <Length>4</Length>
            <AccessMode>WO</AccessMode>
            <pPort>Device</pPort>
            <Cachable>NoCache</Cachable>
            <Sign>Unsigned</Sign>
            <Endianess>LittleEndian</Endianess>
        </IntReg>

        <Command Name="MyCommand3">
           <ImposedAccessMode>WO</ImposedAccessMode>
           <pValue>ValueReg3</pValue>
           <CommandValue>1</CommandValue>
        </Command>

        <IntReg Name="ValueReg3">
            <Address>0x0008</Address>
            <Length>4</Length>
            <AccessMode>RW</AccessMode>
            <pPort>Device</pPort>
            <Cachable>NoCache</Cachable>
            <Sign>Unsigned</Sign>
            <Endianess>LittleEndian</Endianess>
        </IntReg>

        <Port Name="Device"/>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "CommandTestSuite_TestTicket768")

        regs = [("ValueCommand1", "uint32_t", 0, RW, LittleEndian),
                ("ValueCommand2", "uint32_t", 0, RW, LittleEndian),
                ("ValueCommand3", "uint32_t", 0, RW, LittleEndian), ]

        Port = CStructTestPort(regs)
        Camera._Connect(Port, "Device")

        print("1) RW Value\n")

        MyCommand1 = Camera.GetNode("MyCommand1")
        Port.ValueCommand1 = 0
        Port.ResetStatistics()
        print("Reset   : NumReads= ", Port.GetNumReads(), "\n")

        print("Execute!\n")
        MyCommand1.Execute()
        print("NumReads= ", Port.GetNumReads(), "\n")
        self.assertEqual(0, Port.GetNumReads())

        print("IsDone?\n")
        self.assertEqual(False, MyCommand1.IsDone())
        print("NumReads= ", Port.GetNumReads(), "\n")
        self.assertEqual(1, Port.GetNumReads())

        print("Done!\n")
        Port.ValueCommand1 = 0

        print("IsDone?\n")
        self.assertEqual(True, MyCommand1.IsDone())
        print("NumReads= ", Port.GetNumReads(), "\n")
        self.assertEqual(2, Port.GetNumReads())

        print("2) WO Value\n")

        MyCommand2 = Camera.GetNode("MyCommand2")
        Port.ValueCommand2 = 0
        Port.ResetStatistics()
        print("Reset   : NumReads= ", Port.GetNumReads(), "\n")

        print("Execute!\n")
        MyCommand2.Execute()
        print("NumReads= ", Port.GetNumReads(), "\n")
        self.assertEqual(0, Port.GetNumReads())

        print("IsDone?\n")
        self.assertEqual(True, MyCommand2.IsDone())
        print("NumReads= ", Port.GetNumReads(), "\n")
        self.assertEqual(0, Port.GetNumReads())

        print("3) Imposed WO on the Command\n")

        MyCommand3 = Camera.GetNode("MyCommand3")
        Port.ValueCommand3 = 0
        Port.ResetStatistics()
        print("Reset   : NumReads= ", Port.GetNumReads(), "\n")

        print("Execute!\n")
        MyCommand3.Execute()
        print("NumReads= ", Port.GetNumReads(), "\n")
        self.assertEqual(0, Port.GetNumReads())

        print("IsDone?\n")
        self.assertEqual(True, MyCommand3.IsDone())
        print("NumReads= ", Port.GetNumReads(), "\n")
        self.assertEqual(0, Port.GetNumReads())

# Local CallbackObject for testing Mantis Bug #250
class CallbackObjectMantis250(object):
    m_Count = 0

    def Reset(self):
        self.m_Count = 0

    def Count(self):
        return self.m_Count

    def Callback(self, Node):
        self.m_Count += 1

# Local CallbackObject for testing Mantis Bug #257
class CallbackObjectMantis257(object):
    def __init__(self):
        self.m_Count = 0
        self.m_NodeError = False

    def Reset(self):
        self.m_Count = 0

    def Count(self):
        return self.m_Count

    def NodeError(self):
        return self.m_NodeError

    def Callback(self, Node):
        self.m_Count += 1
        if (self.m_Count > 3):
            return
        Command = Node
        if (Command):
            Command.IsDone()
        else:
            self.m_NodeError = True

if __name__ == "__main__":
    # import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


import locale
import logging
import os

from PySide2 import QtCore, QtGui, QtWidgets
from hyo2.abc.lib.helper import Helper
from hyo2.qc.common import lib_info
from hyo2.qc.qctools.gui_settings import GuiSettings

logger = logging.getLogger(__name__)

class ValsouChecksTab(QtWidgets.QMainWindow):

    here = os.path.abspath(os.path.dirname(__file__))

    def __init__(self, parent_win, prj):
        QtWidgets.QMainWindow.__init__(self)
        # store a project reference
        self.prj = prj
        self.parent_win = parent_win
        self.media = self.parent_win.media

        # ui
        self.panel = QtWidgets.QFrame()
        self.setCentralWidget(self.panel)
        self.vbox = QtWidgets.QVBoxLayout()
        self.panel.setLayout(self.vbox)

        # v8 parameters

        self.text_set_scale_v8 = None
        self.set_scale_fsv8 = None
        self.set_include_laser_fsv8 = None
        self.set_overlap_fsv8 = None
        self.toggle_overlap_v8 = None
        self.toggle_mode_v8 = None

        # v8 widgets
        self.valsouCheckv8 = QtWidgets.QGroupBox("VALSOU Checks v8")
        self.valsouCheckv8.setStyleSheet("QGroupBox::title { color: rgb(155, 155, 155); }")
        self.vbox.addWidget(self.valsouCheckv8)
        vcv8_hbox = QtWidgets.QHBoxLayout()
        self.valsouCheckv8.setLayout(vcv8_hbox)
        # -- parameters
        self.setParametersVCv8 = QtWidgets.QGroupBox("Parameters")
        self.setParametersVCv8.setStyleSheet("QGroupBox::title { color: rgb(155, 155, 155); }")
        vcv8_hbox.addWidget(self.setParametersVCv8)
        self._ui_parameters_vcv8()
        # -- execution
        self.executeVCv8 = QtWidgets.QGroupBox("Execution")
        self.executeVCv8.setStyleSheet("QGroupBox::title { color: rgb(155, 155, 155); }")
        vcv8_hbox.addWidget(self.executeVCv8)
        self._ui_execute_vcv8()

        self.vbox.addStretch()

    @classmethod
    def click_open_manual(cls):
        logger.debug("open manual")
        Helper.explore_folder("https://www.hydroffice.org/manuals/qctools/stable/user_manual_survey_valsou_checks.html")

    # ------- v8 --------

    def _ui_parameters_vcv8(self):
        hbox = QtWidgets.QHBoxLayout()
        self.setParametersVCv8.setLayout(hbox)
        hbox.addStretch()

        vbox = QtWidgets.QVBoxLayout()
        hbox.addLayout(vbox)
        vbox.addStretch()

        label_hbox = QtWidgets.QHBoxLayout()
        vbox.addLayout(label_hbox)
        # stretch
        label_hbox.addStretch()
        # specs
        empty = QtWidgets.QLabel("")
        empty.setAlignment(QtCore.Qt.AlignCenter)
        empty.setFixedWidth(160)
        label_hbox.addWidget(empty)
        # stretch
        label_hbox.addStretch()

        toggle_hbox = QtWidgets.QHBoxLayout()
        vbox.addLayout(toggle_hbox)
        # stretch
        toggle_hbox.addStretch()
        # mode
        self.toggle_mode_v8 = QtWidgets.QDial()
        self.toggle_mode_v8.setNotchesVisible(True)
        self.toggle_mode_v8.setWrapping(False)
        self.toggle_mode_v8.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.toggle_mode_v8.setRange(0, 1)
        self.toggle_mode_v8.setSliderPosition(0)
        self.toggle_mode_v8.setFixedSize(QtCore.QSize(40, 40))
        self.toggle_mode_v8.setInvertedAppearance(False)
        toggle_hbox.addWidget(self.toggle_mode_v8)
        # stretch
        toggle_hbox.addStretch()

        label2_hbox = QtWidgets.QHBoxLayout()
        vbox.addLayout(label2_hbox)
        # stretch
        label2_hbox.addStretch()
        # mode
        text_obj = QtWidgets.QLabel("Full coverage")
        text_obj.setAlignment(QtCore.Qt.AlignCenter)
        text_obj.setFixedWidth(85)
        label2_hbox.addWidget(text_obj)
        text_cov = QtWidgets.QLabel("Object detection")
        text_cov.setAlignment(QtCore.Qt.AlignCenter)
        text_cov.setFixedWidth(85)
        label2_hbox.addWidget(text_cov)
        # stretch
        label2_hbox.addStretch()

        vbox.addSpacing(10)

        options_hbox = QtWidgets.QHBoxLayout()
        vbox.addLayout(options_hbox)
        options_hbox.addStretch()

        text_set_overlap = QtWidgets.QLabel("Deconflict across grids")
        options_hbox.addWidget(text_set_overlap)
        text_set_overlap.setFixedHeight(GuiSettings.single_line_height())
        text_set_overlap.setMinimumWidth(80)
        # text_set_overlap.setStyleSheet("QLabel { color :  rgba(200, 0, 0, 200); }")
        self.set_overlap_fsv8 = QtWidgets.QCheckBox(self)
        self.set_overlap_fsv8.setToolTip("Test the flagged features across all the input grids")
        options_hbox.addWidget(self.set_overlap_fsv8)
        self.set_overlap_fsv8.setChecked(False)

        options_hbox.addSpacing(10)

        text_set_include_laser = QtWidgets.QLabel("Include TECSOU=laser")
        options_hbox.addWidget(text_set_include_laser)
        text_set_include_laser.setFixedHeight(GuiSettings.single_line_height())
        text_set_include_laser.setMinimumWidth(80)
        # text_set_neighborhood.setStyleSheet("QLabel { color :  rgba(200, 0, 0, 200); }")
        self.set_include_laser_fsv8 = QtWidgets.QCheckBox(self)
        self.set_include_laser_fsv8.setToolTip("Uncheck to skip features with TECSOU=laser")
        options_hbox.addWidget(self.set_include_laser_fsv8)
        self.set_include_laser_fsv8.setChecked(True)

        options_hbox.addStretch()

        vbox.addStretch()

        hbox.addStretch()

    def _ui_execute_vcv8(self):
        vbox = QtWidgets.QVBoxLayout()
        self.executeVCv8.setLayout(vbox)

        hbox = QtWidgets.QHBoxLayout()
        vbox.addLayout(hbox)

        hbox.addStretch()
        button = QtWidgets.QPushButton()
        hbox.addWidget(button)
        button.setFixedHeight(GuiSettings.single_line_height())
        button.setText("VALSOU Checks")
        button.setToolTip('Check VALSOU values against surface')
        # noinspection PyUnresolvedReferences
        button.clicked.connect(self.click_valsou_check_v8)

        button = QtWidgets.QPushButton()
        hbox.addWidget(button)
        button.setFixedHeight(GuiSettings.single_line_height())
        button.setFixedWidth(GuiSettings.single_line_height())
        icon_info = QtCore.QFileInfo(os.path.join(self.media, 'small_info.png'))
        button.setIcon(QtGui.QIcon(icon_info.absoluteFilePath()))
        button.setToolTip('Open the manual page')
        button.setStyleSheet("QPushButton { background-color: rgba(255, 255, 255, 0); }\n"
                             "QPushButton:hover { background-color: rgba(230, 230, 230, 100); }\n")
        # noinspection PyUnresolvedReferences
        button.clicked.connect(self.click_open_manual)

        hbox.addStretch()

    def click_valsou_check_v8(self):
        # - list of grids (although the buttons should be never been enabled without grids)
        if len(self.prj.s57_list) == 0:
            raise RuntimeError("the S57 list is empty")
        if len(self.prj.grid_list) == 0:
            raise RuntimeError("the grid list is empty")

        version = 8
        self.parent_win.change_info_url(Helper(lib_info=lib_info).web_url(suffix="survey_valsou_check_%d" % version))

        # for each file in the project grid list
        msg = "Flagged features per input pair:\n"
        s57_list = self.prj.s57_list
        grid_list = self.prj.grid_list
        opened_folders = list()

        for i, s57_file in enumerate(s57_list):

            # print("s57: %s" % s57_file)
            # we want to be sure that the label is based on the name of the new file input
            self.prj.clear_survey_label()

            try:
                self.prj.read_feature_file(feature_path=s57_file)

            except Exception as e:
                # noinspection PyCallByClass,PyArgumentList
                QtWidgets.QMessageBox.critical(self, "Error", "While reading s57 file, %s" % e,
                                               QtWidgets.QMessageBox.Ok)
                self.parent_win.progress.setValue(100)
                return

            for j, grid_file in enumerate(grid_list):

                idx = (j + 1)*(i*len(s57_list))
                total = len(s57_list)*len(grid_list)

                self._valsou_check_v8(grid_file=grid_file, version=version, idx=idx, total=total)

                logger.info("survey label: %s" % self.prj.survey_label)

                # de-confliction
                if self.set_overlap_fsv8.isChecked():
                    self.parent_win.progress.start(title="VALSOU Check v%d" % version,
                                                   text="Deconflicting [%d/%d]" % (idx, total),
                                                   init_value=90)
                    self.prj.valsou_check_deconflict()
                    self.parent_win.progress.end()

                # open the output folder (if not already open)
                if self._export_valsou_check():
                    if self.prj.valsou_output_folder not in opened_folders:
                        self.prj.open_valsou_output_folder()
                        opened_folders.append(self.prj.valsou_output_folder)

                if self.prj.valsou_out_of_bbox:
                    msg += "- %s VS. %s: %s\n" % (self.prj.cur_s57_basename, self.prj.cur_grid_basename,
                                                  "no overlap")
                else:
                    msg += "- %s VS. %s: %d\n" % (self.prj.cur_s57_basename, self.prj.cur_grid_basename,
                                                  self.prj.number_of_valsou_features())

                # close the grid file
                self.prj.close_cur_grid()

        # noinspection PyCallByClass
        QtWidgets.QMessageBox.information(self, "VALSOU Checks v%d" % version, msg, QtWidgets.QMessageBox.Ok)

    def _valsou_check_v8(self, grid_file, version, idx, total):
        """ VALSOU check for the loaded s57 features and grid"""

        # GUI takes care of progress bar

        logger.debug('VALSOU Checks v%d ...' % version)

        self.parent_win.progress.start(title="VALSOU Checks v%d" % version,
                                       text="Data loading [%d/%d]" % (idx, total),
                                       init_value=10)

        try:
            self.prj.open_grid(path=grid_file)

        except Exception as e:
            # noinspection PyCallByClass,PyArgumentList
            QtWidgets.QMessageBox.critical(self, "Error", "While reading grid file, %s" % e, QtWidgets.QMessageBox.Ok)
            self.parent_win.progress.end()
            return

        self.parent_win.progress.update(value=20, text="VALSOU Checks v%d [%d/%d]" % (version, idx, total))

        try:
            with_laser = self.set_include_laser_fsv8.isChecked()
            is_tgt_detect = self.toggle_mode_v8.value() == 1
            self.prj.valsou_check_v8(specs_version="2021", with_laser=with_laser, is_target_detection=is_tgt_detect)

        except Exception as e:
            # noinspection PyCallByClass, PyArgumentList
            QtWidgets.QMessageBox.critical(self, "Error", "While VALSOU checking, %s" % e, QtWidgets.QMessageBox.Ok)
            self.parent_win.progress.end()
            return

        self.parent_win.progress.end()

    def _export_valsou_check(self):
        """ export VALSOU features """
        logger.debug('exporting flagged VALSOU features ...')
        saved_s57 = self.prj.save_valsou_features()
        logger.debug('exporting flagged VALSOU features: done')
        return saved_s57


'''
Created on 14 Dec 2010

@author: pjl
'''

import sys
#import DBStuff

import matplotlib
matplotlib.use('GTK')
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
from matplotlib.backends.backend_gtk import FigureCanvasGTK, NavigationToolbar
from numpy import arange, sin, pi

class appGui:
    def __init__(self):
        gladefile = "project2.glade"
        self.windowname = "gtkbench"
        self.wTree = gtk.glade.XML(gladefile, self.windowname)
        dic = {"on_window1_destroy" : gtk.main_quit,
            "on_button1_clicked" : self.submitDB,
            "on_button3_clicked" : self.fillTree,
            "on_notebook1_switch_page" : self.selectNotebookPage,
            "on_treeview1_button_press_event" : self.clickTree,
            "on_button2_clicked" : self.createProjectGraph
            }
        self.wTree.signal_autoconnect(dic)

try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk
    import gtk.glade
except:
    sys.exit(1)


import numpy as np

from dezero import Variable
# noinspection PyProtectedMember
from dezero.utils import _dot_var, _dot_func

def test__dot_var():
    x = Variable(np.random.randn(2, 3))
    x.name = 'x'
    assert _dot_var(x) == f'{id(x)} [label="x", color=orange, style=filled]\n'
    assert _dot_var(x, verbose=True) == f'{id(x)} [label="x: (2, 3) float64", color=orange, style=filled]\n'

def test__dot_func():
    x0 = Variable(np.array(1))
    x1 = Variable(np.array(1))
    y = x0 + x1
    txt = _dot_func(y.creator)

    assert txt == f'{id(y.creator)} [label="Add", color=lightblue, style=filled, shape=box]\n' \
                  f'{id(x0)} -> {id(y.creator)}\n' \
                  f'{id(x1)} -> {id(y.creator)}\n' \
                  f'{id(y.creator)} -> {id(y)}\n'


from sys import stdin

class B:
	def __init__(self,N,L):
		self.N = int(N)
		self.L = int(L)
		self.taste = list()
		self.taste_abs = list() #絶対値

	def CollectTaste(self):
		for i in range(1,self.N+1):
			i = self.CulTasteFirst(i)
			self.taste.append(i)
			self.taste_abs.append(abs(i)) #絶対値リストの作成

		#絶対値の小さい要素を削除して計算する味リストの決定
		min_num = min(self.taste_abs)
		try:
			self.taste.remove(min_num)
		except ValueError:
			min_num *= -1
			self.taste.remove(min_num)

		ans = 0
		for i in self.taste:
			ans += i
		print(ans)
	def CulTasteFirst(self,i):
		i = int(i)
		return self.L+i-1

Inp = stdin.readline()
Inp = Inp.replace('\n','')
Inp = Inp.split()

do = B(Inp[0],Inp[1])
do.CollectTaste()


#import pandas as pd

'''df = pd.read_csv("farmbilldocuments.csv",encoding = "ISO-8859-1")

df = df[df.lang.str.contains("en")]
df['author_screen_name']=df['author_screen_name'].str.lower()
df['tweet_text']=df['tweet_text'].str.lower()
df = df[['author_screen_name','tweet_text']]
df.to_csv('farmbill_english_document_lower.csv',index = False)'''

import csv
import numpy
from sklearn.metrics import confusion_matrix
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from scipy.spatial import distance
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import euclidean_distances
import math
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.metrics.pairwise import manhattan_distances
from sklearn.metrics import jaccard_similarity_score
#covid_English_PartyAuthorTweet
#farmbill_english_document_party
reader = csv.reader(open("farmbill_english_document_party.csv", "rt",encoding = "ISO-8859-1"), delimiter=",")
x = list(reader)
x = numpy.array(x)
r,c = x.shape
bjp = []
inc = []
akali = []
rjd = []
cpimspeaks = []
jmmjharkhand = []
goaforwardparty = []
aamaadmiparty = []
aitcofficial = []
samajwadiparty = []
for i in range(1,r):
	if(x[i][0] == 'bjp4india'):
		bjp.append(x[i][2])
	if(x[i][0] == 'incindia'):
		inc.append(x[i][2])
	if(x[i][0] == 'akali_dal_'):
		akali.append(x[i][2])
	if(x[i][0] == 'rjdforindia'):
		rjd.append(x[i][2])
	if(x[i][0] == 'cpimspeaks'):
		cpimspeaks.append(x[i][2])
	if(x[i][0] == 'jmmjharkhand'):
		jmmjharkhand.append(x[i][2])
	if(x[i][0] == 'goaforwardparty'):
		goaforwardparty.append(x[i][2])
	if(x[i][0] == 'aamaadmiparty'):
		aamaadmiparty.append(x[i][2])
	if(x[i][0] == 'aitcofficial'):
		aitcofficial.append(x[i][2])
	if(x[i][0] == 'samajwadiparty'):
		samajwadiparty.append(x[i][2])
#print(len(inc), len(bjp))
# Python program to convert a list
# to string using list comprehension
#cpimspeaks , jmmjharkhand , goaforwardparty , aamaadmiparty , officeofrsp , jduonline , rlpindiaorg , arivalayam
#aitcofficial , samajwadiparty , ysrcparty , aimim_national , cpimspeak

def jaccard_similarity(list1, list2):
    intersection = len(list(set(list1).intersection(list2)))
    union = (len(list1) + len(list2)) - intersection
    return float(intersection) / union

# using list comprehension
bjp = ' '.join(map(str, bjp))
inc = ' '.join(map(str, inc))
aamaadmiparty = ' '.join(map(str, aamaadmiparty))
goaforwardparty = ' '.join(map(str, goaforwardparty))
rjd = ' '.join(map(str, rjd))

X_list = word_tokenize(inc)
Y_list = word_tokenize(rjd)

sw = stopwords.words('english')
l1 =[];l2 =[]

# remove stop words from the string
X_set = {w for w in X_list if not w in sw}
Y_set = {w for w in Y_list if not w in sw}

# form a set containing keywords of both strings
rvector = X_set.union(Y_set)
for w in rvector:
    if w in X_set: l1.append(1) # create a vector
    else: l1.append(0)
    if w in Y_set: l2.append(1)
    else: l2.append(0)
c = 0

# cosine formula
for i in range(len(rvector)):
        c+= l1[i]*l2[i]
cosine = c / float((sum(l1)*sum(l2))**0.5)
print("Cosine_similarity: ", cosine)
sim = jaccard_similarity(X_set,Y_set)
print("Jaccard_sim: ", sim)

#eucledian Distance
t = numpy.array(l1).reshape(1,-1)
n = numpy.array(l2).reshape(1,-1)
x=euclidean_distances(t, n)[0][0]
print("Eucledian Distance:",x)

y=manhattan_distances(t,n)[0][0]
print("Manhattan Distance:",y)


from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin
from pyvi import ViTokenizer
import tensorflow as tf
import gensim
import numpy as np
import pickle
import os

os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

app=Flask(__name__)

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

import gensim.models.keyedvectors as word2vec
model_embedding = word2vec.KeyedVectors.load('./wordgensim.model')

word_labels = []
max_seq = 100
embedding_size = 128

for word in model_embedding.vocab.keys():
    word_labels.append(word)

def comment_embedding(comment):
    matrix = np.zeros((max_seq, embedding_size))
    words = comment.split()
    lencmt = len(words)

    so_lan_du_1_cau = 0

    for i in range(max_seq):
        indexword = i % lencmt

        so_lan_du_1_cau = i//lencmt
        if (max_seq - so_lan_du_1_cau*lencmt < lencmt):
            break
        if(words[indexword] in word_labels):
            matrix[i] = model_embedding[words[indexword]]

    matrix = np.array(matrix)
    return matrix

def process_special_word(text):
    file = open('not.txt', 'r', encoding="utf8")
    not_lst = file.read().split('\n')
    file.close()
    for khong in not_lst:
      new_text = ''
      text_lst = text.split()
      i= 0
      if khong in text_lst:
          while i <= len(text_lst) - 1:
              word = text_lst[i]
              if  word == khong:
                  next_idx = i+1
                  if next_idx <= len(text_lst) -1:
                      word = word +'_'+ text_lst[next_idx]
                  i= next_idx + 1
              else:
                  i = i+1
              new_text = new_text + word + ' '
      else:
          new_text = text
      text=new_text
    return new_text.strip()

def ValuePredictor(comment):

    comment = process_special_word(comment)
    comment = ''.join( c for c in comment if  c not in '?:!/;#,1234567890.' )

    comment = gensim.utils.simple_preprocess(comment)
    comment = ' '.join(comment)
    comment = ViTokenizer.tokenize(comment)

    model_sentiment = tf.keras.models.load_model("sentiment_model.h5")
    maxtrix_embedding = np.expand_dims(comment_embedding(comment), axis=0)
    maxtrix_embedding = np.expand_dims(maxtrix_embedding, axis=3)
    result = model_sentiment.predict(maxtrix_embedding)
    return result

@app.route('/result',methods = ['POST'])
def result():
    if request.method == 'POST':
        input_ = request.form.to_dict()

        result = ValuePredictor(input_["cmt"])
        result = float(result)
        result = np.round(result,2)
        max_index = np.round(result)
        if max_index == 1:
            prediction = "Tích cực"

        if max_index == 0:
            prediction = "Tiêu cực"

        return render_template("result.html",prediction=prediction,c=input_["cmt"],p=result)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9999, debug=True)


import sys, struct, ctypes

def set_float(obj, value):
    assert isinstance(obj, float), 'Object must be a float!'
    assert isinstance(value, float), 'Value must be a float!'
    stop = sys.getsizeof(obj)
    start = stop - struct.calcsize('d')
    array = ctypes.cast(id(obj), ctypes.POINTER(ctypes.c_ubyte))
    for args in zip(range(start, stop), struct.pack('d', value)):
        array.__setitem__(*args)


import requests

def check_proxy(url, proxy, delay=3, debug=False):
    with requests.Session() as s:
        try:
            s.get(url, proxies={'http': 'http://'+proxy}, timeout=delay)
            print('\tSuccess connection!')
            s.close()
            return True
        except requests.RequestException as err:
            if debug:
                print('End with ', err)
        except ValueError:
            if debug:
                print('End with ValueError')

        print('\tFail connection!')
        s.close()
        return False

def check_proxy_from_file(url_list, file_path, delay=3, debug=False):
    result_list = []
    proxy_list = []

    file = open(file_path)
    for line in file:
        proxy_list.append(line[:len(line)-1])
    file.close()

    print('Check', len(proxy_list), 'proxy for', len(url_list), 'urls')
    for url in url_list:
        for proxy in proxy_list:
            print('Check', proxy, 'for', url)
            result = check_proxy(url, proxy, delay, debug)
            if result:
                result_list.append(proxy)

    return result_list


# -*- coding: utf-8 -*-
"""
Created on Sun Jul 29 18:00:08 2018

@author: wfok007
"""

from __future__ import print_function, division

import torch, math

import torch.nn as nn
import numpy as np

import matplotlib.pyplot as plt
from decompress import addAxis, fast_transfer
import os
from weightNorm import metaGen, Dice_Loss, non_differentiable_Dice_coef,  load_stat
from ensemblePrediction import create_Ensemble,  prepareInputsForGPU, ensemble_predict

if __name__ == '__main__':

    plt.close('all')

    prog_dir = r'Z:\mpi_heart\ensembleTestPredictions'
    training_dir = r'C:\Users\wfok007\femuring\imaging\AtriaSeg_2018_training'
    output_dir = r'Z:\mpi_heart\howBigEnsemble'
    debug_dir = r'C:\Users\wfok007\femuring\imaging\AtriaSeg_2018_training\debug'
    hpc = r'Z:\mpi_heart'
    weight_dir = 'Z:\mpi_heart\weight_checkpoints'

    mean, std = load_stat()

    num_ranks = 125
    od, oh, ow = 88 , 112, 112
    multiple = 0.25
    minibatch = 5
    threshold = 0.37
    aa_mean, aa_std = addAxis(mean, std)
    gaa_mean, gaa_std = fast_transfer(aa_mean), fast_transfer(aa_std)

    gen = metaGen('test', num_ranks, hpc)
    criterion = Dice_Loss()
    accuracy = non_differentiable_Dice_coef()

    chosen_num_members = 4
    weightNameList = [1480, 2440, 2880, 3320, 3920, 4440]
    weightNameList = ['weights'+str(i*minibatch) for i in weightNameList]

    # update the list
    groupMembers = weightNameList[0:chosen_num_members]
    ensemble = create_Ensemble(groupMembers)

    coefs2 = []
    MAX_EPOCH = 200 # the number of test cases

    for i, (full_image, full_mask, image, mask) in enumerate(gen):
        image1, target = prepareInputsForGPU(image, full_mask,gaa_mean, gaa_std, 88, 576, 576)

        with torch.no_grad():
            # ensemble
            output = ensemble_predict(ensemble, image1)

        coef2, true_pos_arr2, false_pos_arr2, false_neg_arr2 = accuracy(output, target, threshold=threshold, returnArr=True)
        print ('[%d] full resolution dice coef: %f' %(i, coef2))
        coefs2.append(coef2)

        sig = nn.functional.sigmoid(output)
        sig = sig.cpu().detach().numpy()
        pred_mask = sig[0,0,...]

        del output, sig, image1, target

        # save and draw the predictions and mistakes

#        pred_mask = pred_mask >= threshold
#        pred_mask = pred_mask *1
#
#
#
#        temp_img = fromFloat_to_uint8(full_image)
#
#
#        tag = str(i)+'_'+ str(round(coef2, 3)).replace('.', 'p')
#
#        save(temp_img, pred_mask, 'test_'+ tag, prog_dir)
#
#        # need to decompress the index to get mask
#        full_mask = decompress_mask(full_mask,88, 576, 576)
#
#        save(temp_img, full_mask, 'test_groundTruth_'+tag, prog_dir)
#
#        # don't put segment of codes far apart !!!
#        true_pos_arr2 = true_pos_arr2[0,0,...]
#        false_pos_arr2 = false_pos_arr2[0,0,...]
#        false_neg_arr2 = false_neg_arr2[0,0,...]
#        save(temp_img, true_pos_arr2, 'test_true_pos_'+tag, prog_dir)
#        save(temp_img, false_pos_arr2, 'test_false_pos_'+tag, prog_dir)
#        save(temp_img, false_neg_arr2, 'test_false_neg_'+tag, prog_dir)

        if i >= MAX_EPOCH-1:
            break
    print ('finish testing')
    print ('median full resolution dice coefficient %f' %(np.median(coefs2)))
    print ('std full resolution dice coefficient %f' %(np.std(coefs2)))
    print ('maximum allocated %f GB' %(torch.cuda.max_memory_allocated()/math.pow(10,9)))


from transformer import TransformerEncoder
from amc_dl.torch_plus.module import PytorchModel
import numpy as np
import torch.nn as nn
import torch

class MuseBERT(PytorchModel):

    tfm: TransformerEncoder

    def __init__(self, name, device, tfm, in_dims, out_dims, loss_inds):
        """
        :param name: name of the model, e.g., 'musebert'
        :param device: cpu or cuda
        :param tfm: transformer encoder
        :param in_dims: intput vocab sizes
        :param out_dims: output vocab sizes (distribution sizes)
        :param loss_inds: (which attributes to compute recon loss)
        """

        def compute_lr_inds(dims):
            dims = np.array(dims, dtype=np.int64)
            r_inds = np.cumsum(dims)
            l_inds = np.insert(r_inds[0: -1], 0, 0)
            return tuple(l_inds), tuple(r_inds)

        super(MuseBERT, self).__init__(name, device)

        self.in_dims = in_dims
        self.out_dims = out_dims
        self.n_col = len(in_dims)

        # the left, right endpoints for output distributions of attributes
        self.lout_inds, self.rout_inds = compute_lr_inds(out_dims)

        self.loss_inds = loss_inds

        self.embeddings = \
            nn.ModuleList([nn.Embedding(ind, tfm.d_model)
                           for ind in in_dims])
        self.tfm = tfm
        self.out = nn.Linear(tfm.d_model, self.rout_inds[-1])
        self.lossf = nn.CrossEntropyLoss(reduction='none')

    @property
    def d_model(self):
        return self.tfm.d_model

    @property
    def N(self):
        return self.tfm.N

    @staticmethod
    def _truncate_data(x, length=None, truncate_len=None, mode=0):
        """Apply data truncation in three different modes."""
        truncate_len = truncate_len if truncate_len is not None \
            else (length.max() if length is not None else None)
        if truncate_len is not None:
            if mode == 0:
                return x[:, 0: truncate_len]
            elif mode == 1:
                return x[:, 0: truncate_len, 0: truncate_len]
            elif mode == 2:
                return x[:, :, 0: truncate_len, 0: truncate_len]
            else:
                raise NotImplementedError
        return x

    def _truncate_lists(self, xs, length, modes):
        truncate_len = length.max()
        return tuple(self.__class__._truncate_data(
            x, None, truncate_len, m
        ) for x, m in zip(xs, modes))

    def truncate(self, data_in, mask, rel_mat, data, inds, length):
        """truncate the input data to max(length)."""
        return self._truncate_lists([data_in, mask, rel_mat, data, inds],
                                    length,
                                    modes=[0, 1, 2, 0, 0])

    def onset_pitch_dur_embedding(self, data_in):
        """ Sum up the onset, pitch, dur embeddings """
        return sum([self.embeddings[i](data_in[:, :, i])
                    for i in range(len(self.in_dims))])

    def run(self, data_in, rel_mat, mask):
        """
        batch -> output distribution
        :param data_in: (bs, L, 3) dtype long. Last dim: onset, pitch, dur.
        :param rel_mat: (bs, k, L, L)
        :param mask: (bs, L, L) dtype long
        :return: (bs, L, pitch + dur dims)
        """
        x = self.onset_pitch_dur_embedding(data_in)
        x = self.tfm(x, rel_mat, mask=mask)
        x = self.out(x)
        return x

    def loss_function(self, recon, tgt, inds, beta):
        """compute reconstuction loss on corrupted attributes (inds) only."""

        def atr_loss(recon, tgt, i):
            if i in self.loss_inds:
                l_ind = self.lout_inds[i]
                r_ind = self.rout_inds[i]
                return (self.lossf(recon[:, l_ind: r_ind],
                                   tgt[:, i]) * w).sum()
            else:
                return torch.zeros([]).float().to(self.device)

        # compute weight w: so that each data sample is treated equally.
        # E.g., when bs=2, 1st sample has 1 corrupted tokens and 2nd has 2,
        #  w = [0.5, 0.25, 0.25], not [0.333, 0.333, 0.333].
        counts = inds.long().sum(-1)
        bs = inds.size(0)
        w = torch.cat([torch.tensor([1 / c.float()] * c.long())
                       for c in counts], 0) / bs
        w = w.to(self.device)
        recon = recon[inds]  # (*, outs)
        tgt = tgt[inds]
        losses = [atr_loss(recon, tgt, i) for i in range(self.n_col)]

        # beta controls the weighting for different attributes
        total_loss = sum([ls * b for ls, b in zip(losses, beta)])

        return (total_loss, *losses)

    def loss(self, data, data_in, rel_mat, mask, inds, length, beta):
        data_in, mask, rel_mat, data, inds = \
            self.truncate(data_in, mask, rel_mat, data, inds, length)
        recon = self.run(data_in, rel_mat, mask)
        loss = self.loss_function(recon, data, inds, beta)
        return loss

    def inference(self, data, data_in, rel_mat, mask, inds,
                  length, truncate=True):
        self.eval()
        with torch.no_grad():
            if truncate:
                data_in, mask, rel_mat, data, inds = \
                    self.truncate(data_in, mask, rel_mat, data, inds, length)
            recon = self.run(data_in, rel_mat, mask)
        return recon

    @classmethod
    def init_model(cls, N=12, h=8, d_model=128, d_ff=512, non_linear=None,
                   relation_vocab_sizes=(5, 5, 5, 5),
                   in_dims=(15, 15, 15, 15, 15, 15, 15),
                   out_dims=(9, 7, 7, 3, 12, 5, 8),
                   loss_inds=(1, 3, 4, 5, 6),
                   dropout=0.1):
        """Easier way to initialize a MuseBERT"""
        name = 'musebert'
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        if non_linear == 'gelu':
            non_linear = nn.GELU()
        tfm = TransformerEncoder(N, h, d_model, d_ff, non_linear=non_linear,
                                 relation_vocab_sizes=relation_vocab_sizes,
                                 dropout=dropout, attn_dropout=None)
        model = cls(name, device, tfm, in_dims, out_dims, loss_inds)
        model.to(device)
        return model


print("--- Programa 47 ---")
sequencia = input("Digite um número binário: ")

tamMaior = 0
tamSubSeq = 0
for i in range(len(sequencia)):
    if sequencia[i] == '1':
        tamSubSeq += 1
        if tamSubSeq > tamMaior:
            tamMaior = tamSubSeq
    else: # OU se '0'
        tamSubSeq = 0

print("O tamanho da maior subsequência é", tamMaior, "dígitos 1´s.")


# Questão 3
# Considere o argumento abaixo:

# Você já deve ter ouvido algum especialista dizer que as pessoas precisam dedicar, no máximo, 30% da sua renda mensal à moradia, 20% à educação e 15% ao transporte. Esses valores não devem ser totalmente desprezados, mas não podem funcionar como um norte para o orçamento doméstico de todas as famílias.
# Fonte: BTG Pactual Digital

# Crie um programa contendo uma função que, dados um valor de renda mensal total, gastos totais com moradia, gastos totais com educação
#e gastos totais com transporte, faça um diagnóstico da saúde financeira do usuário,
#com base nos valores percentuais acima expostos,
#informando qual é o percentual da renda mensal total comprometido por cada custo.

# Se o gasto estiver dentro do percentual recomendado, informe ainda que
# Seus gastos estão dentro da margem recomendada.
# Caso contrário, informe:
#
# Portanto, idealmente, o máximo de sua renda comprometida com {tipo} deveria ser de R$ {valor_max}
#
# Onde tipo deve ser moradia, educação ou transportes e valor_max deve ser o valor equivalente ao percentual máximo de gasto
#com esse tipo de custo.

# Exemplo de saída do programa:

# Renda mensal total: R$ 5000
# Gastos totais com moradia: R$ 1760
# Gastos totais com educação: R$ 800
# Gastos totais com transporte: R$ 300

# Diagnóstico:

# Seus gastos totais com moradia comprometem 35.2% de sua renda total. O máximo recomendado é de 30%. Portanto, idealmente, o máximo de sua renda comprometida com moradia deveria ser de R$ 1500.
# Seus gastos totais com educação comprometem 16% de sua renda total. O máximo recomendado é de 20%. Seus gastos estão dentro da margem recomendada.
# Seus gastos totais com transporte comprometem 6% de sua renda total. O máximo recomendado é de 15%. Seus gastos estão dentro da margem recomendada.
gastoMoradiaIdeal = None
gastoTransporteIdeal = None
gastoEducacaoIdeal = None

def HealthCheck():

    #Verificação da porcentagem de gastos com moradia
    porcentagemMoradia = (gastoMoradia * 100) / rendaMensal
    gastoMoradiaIdeal = rendaMensal * 0.3
    porcentagemIdealMoradia = (gastoMoradiaIdeal * 100) / rendaMensal

    #Verificação da porcentagem de gastos com Educação
    porcentagemEducacao = (gastoEducacao * 100) / rendaMensal
    gastoEducacaoIdeal = rendaMensal * 0.2
    porcentagemIdealEducacao = (gastoEducacaoIdeal * 100) / rendaMensal

    #Verificação da porcentagem de gastos com Transporte
    porcentagemTransporte = (gastoTransporte * 100) / rendaMensal
    gastoTransporteIdeal = rendaMensal * 0.15
    porcentagemIdealTransporte = (gastoTransporteIdeal * 100) / rendaMensal

    print("\n Diagnóstico: ")

    #Validação se o custo com moradia é maior que o gasto ideal proposto
    if porcentagemMoradia > porcentagemIdealMoradia:
        diagnosticoMoradia = (f"Seus gastos totais com moradia comprometem {porcentagemMoradia}% de sua renda total. O máximo recomendado é de 30%. Portanto, idealmente, o máximo de sua renda comprometida com moradia deveria ser de R$ {gastoMoradiaIdeal:.2f}.")
    else:
        diagnosticoMoradia = (f"Seus gastos totais com moradia comprometem {porcentagemMoradia}% de sua renda total. O máximo recomendado é de 30%. Seus gastos estão dentro da margem recomendada.")

    #Validação se o custo com educação é maior que o gasto ideal proposto
    if porcentagemEducacao > porcentagemIdealEducacao:
        diagnosticoEducacao = (f"Seus gastos totais com educação comprometem {porcentagemEducacao}% de sua renda total. O máximo recomendado é de 20%. Portanto, idealmente, o máximo de sua renda comprometida com moradia deveria ser de R$ {gastoEducacaoIdeal:.2f}.")
    else:
        diagnosticoEducacao = (f"Seus gastos totais com educação comprometem {porcentagemEducacao}% de sua renda total. O máximo recomendado é de 20%. Seus gastos estão dentro da margem recomendada.")

    #Validação se o custo com transporte é maior que o gasto ideal proposto
    if porcentagemTransporte > porcentagemIdealTransporte:
        diagnosticoTransporte = (f"Seus gastos totais com transporte comprometem {porcentagemTransporte}% de sua renda total. O máximo recomendado é de 15%. Portanto, idealmente, o máximo de sua renda comprometida com moradia deveria ser de R$ {gastoTransporteIdeal:.2f}.")
    else:
        diagnosticoTransporte = (f"Seus gastos totais com transporte comprometem {porcentagemTransporte}% de sua renda total. O máximo recomendado é de 15%. Seus gastos estão dentro da margem recomendada.")

    #A função retorna um print com os valores de diagnóstico de moradia, educação e transporte
    return print(f" \n {diagnosticoMoradia} \n {diagnosticoEducacao} \n {diagnosticoTransporte}")

#Solicitar valores ao usuário
rendaMensal = float(input("Informe sua renda mensal: "))
gastoMoradia = float(input("Informe o gasto total com moradia: "))
gastoEducacao = float(input("Informe o gasto total com Educação: "))
gastoTransporte = float(input("Informe o gasto total com transporte: "))

#Chamando a função HealthCheck() para que seja impresso o resultado.
HealthCheck()


import random
from tqdm import tqdm
from collections import defaultdict
import matplotlib.pyplot as plt
import constraint

p = constraint.Problem()
p.addVariable('x', [1,2,3])
p.addVariable('y', range(10))

def our_constraint(x, y):
    if x + y >= 5:
        return True

p.addConstraint(our_constraint, ['x','y'])

solutions = p.getSolutions()
print(solutions)

def split_train_test_eval(data, percentage_test, percentage_eval):
    """
    Given a file that contains <id's>\t<sentence>. Returns a dict
    <id: "test"/"traning"> given a split precentage. The input text
    is shuffled and no overlap of sentences and speakers in the
    different sets.

    """
    spk_ids=[]
    for line in data:
        spk_ids.append(line[1])

    d = defaultdict(int)
    for w in spk_ids: d[w] += 1
    x=[]
    for line in data:

        x.append(line + [d[line[1]]])

    d = {k:v for k,v in sorted(d.items(), key=lambda items: items[1], reverse=True)}
    data = [v for v in sorted(x, key=lambda x: x[3], reverse=True)]
    #print(d)
    #for line in data:
    #    print(line)
    #    input()
    distribution = list(d.values())
    print(sum(distribution[0:20]))
    print(distribution[20])
    plt.plot(distribution)
    plt.savefig("distribution.png")

    status:dict = {}

    test_size = int(len(data)*(percentage_test/100))
    eval_size = int(len(data)*(percentage_eval/100))
    training_size = len(data) - test_size - eval_size

    print(f"\nThe total text is {len(data)} lines")
    print(f"The training_size set is {training_size} lines")
    print(f"The test set is {test_size} lines")
    print(f"The eval set is {eval_size} lines\n")

    test_senteces, eval_senteces, test_spk_id, eval_spk_id = set(), set(), set(), set()

    test_count, eval_count, n, max_rounds = 0,0,0, 5
    while (test_count != test_size and eval_count != eval_size) or n != max_rounds:
        for line in tqdm(data):
            key, spk_id, sentece, count = line
            if count >= 500:
                status[key] = 'training'

            elif sentece not in test_senteces \
                    and spk_id not in test_spk_id \
                    and test_count < test_size:
                test_senteces.add(sentece)
                test_spk_id.add(spk_id)

                status[key] = 'test'
                test_count +=1

            elif sentece not in test_senteces \
                        and sentece not in eval_senteces \
                        and spk_id not in test_spk_id \
                        and spk_id not in eval_spk_id \
                        and eval_count < eval_size:
                eval_senteces.add(sentece)
                eval_spk_id.add(spk_id)

                status[key] = 'eval'
                eval_count += 1

            else:
                status[key] = 'training'

        n += 1
    print(test_count)
    print(eval_count)

    assert test_count == test_size or eval_count == eval_size,\
        print(f"Eval or test size is not as expected\nTest: {test_count} {test_size}\nEval: {eval_count} {eval_size} ")

    return status


from mrjob.job import MRJob
from mrjob.step import MRStep
from mrjob.protocol import JSONValueProtocol
from io import StringIO
import csv
import re

class AttriCluster(MRJob):
    OUTPUT_PROTOCOL = JSONValueProtocol
    def steps(self):
        return [
            MRStep(mapper=self.mapper,
                   reducer=self.reducer),
            MRStep(reducer=self.reducer_final)
        ]

    def mapper(self, _, line):
        import os
        rd = csv.reader(StringIO(line),delimiter=";")
        row = next(rd)
        eid = row.pop(0)
        stop_words = r'the|and|:|,|&|\?|!'
        jointCol = ["joint"+str(i) for i in range(7)]
        if eid != "id":
            file_name = os.getenv('mapreduce_map_input_file')
            for index in range(len(row)):
                words = re.sub(stop_words," ",row[index].lower())
                fn = "s1" if "first" in file_name else "s2"
                for word in words.split():
                    if word != "none":
                        yield (jointCol[index]+"-"+word,(fn,int(eid)))

    def reducer(self, token, eids):
        es1 = []
        es2 = []
        for var in eids:
            if(var[0] == "s1"):
                es1.append(var[1])
            else:
                es2.append(var[1])

        if (len(es1) > 0) & (len(es2) > 0):
            yield (None,{token:{"s1":sorted(list(set(es1))),"s2":sorted(list(set(es2)))}})

    def reducer_final(self,key,value):
        yield None,list(value)

if __name__ == '__main__':
    AttriCluster.run()


from django import forms
from .models import PagamentosRecebidos

class FormPagamentosRecebidos(forms.ModelForm):
    class Meta:
        model = PagamentosRecebidos
        fields = (
            'data_pagamento',
            'data_vencimento',
            'valor_pagamento',
            'status_pagamento',
            'meio_pagamento',
            'observacoes_pagamento',
        )

class FormPagamentos(forms.ModelForm):
    class Meta:
        model = PagamentosRecebidos
        fields = ()


#Práctica 4: Views
from django.conf.urls import include, url
from . import views
#Páctica 11: Login
from django.contrib.auth.views import login, logout_then_login
#Páctica 12: SignUp
from .views import SignUp
from django.contrib.auth import views as auth_views

from django.conf.urls.static import static

from Practicas import settings

from django.views.static import serve

urlpatterns = [
    #Práctica 4: Views
    url(r'^$', views.index),
    url(r'^index/$', views.index, name="index"),
    url(r'^anime/$', views.anime, name="anime"),
    url(r'^naruto/$', views.naruto, name="naruto"),
    url(r'^snk/$', views.snk, name="snk"),
    url(r'^dbs/$', views.dbs, name="dbs"),
    url(r'^swknu/$', views.swknu, name="swknu"),
    #Práctica 8: Formularios
    url(r'^formPracticas/$', views.formPracticas, name="formPracticas"),
    url(r'^formAnimes/$', views.formAnimes, name="formAnimes"),
    url(r'^formNaruto/$', views.formNaruto, name="formNaruto"),
    url(r'^formSNK/$', views.formSNK, name="formSNK"),
    url(r'^formDBS/$', views.formDBS, name="formDBS"),
    url(r'^formSWKNU/$', views.formSWKNU, name="formSWKNU"),
    #Práctica 9: Vistas basadas en clases
    url(r'^animes_list/$', views.Animes_List.as_view(), name="animes_list"),
    url(r'^ninjas_list/$', views.Ninjas_List.as_view(), name="ninjas_list"),
    url(r'^soldados_list/$', views.Soldados_List.as_view(), name="soldados_list"),
    url(r'^guerreros_list/$', views.Guerreros_List.as_view(), name="guerreros_list"),
    url(r'^musicos_list/$', views.Musicos_List.as_view(), name="musicos_list"),
    #Práctica 10: Formularios mecanicos
    url(r'^formMecanicoAnimes/$', views.formMecanicoAnimes, name="formMecanicoAnimes"),
    url(r'^formMecanicoNinjas/$', views.formMecanicoNinjas, name="formMecanicoNinjas"),
    url(r'^formMecanicoSoldados/$', views.formMecanicoSNK, name="formMecanicoSoldados"),
    url(r'^formMecanicoDBS/$', views.formMecanicoDBS, name="formMecanicoDBS"),
    url(r'^formMecanicoSWKNU/$', views.formMecanicoSWKNU, name="formMecanicoSWKNU"),
    #Páctica 11: Login
    url(r'^login/$', login, {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', logout_then_login, name='logout'),
    #Páctica 12: SignUp
    url(r'^signup/$', views.SignUp.as_view(), name="signup"),

    url(r'^accounts/', include ('allauth.urls')),
]

if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import cv2
from aicity_reader import read_annotations, read_detections, group_by_frame
from noise_generator import add_noise
from voc_evaluation import voc_eval
from utils import draw_boxes

def task1_1(paths, show, noise_params):

    gt = read_annotations(paths['gt'], grouped=False, use_parked=True)
    det = read_detections(paths['det'], grouped=True)

    grouped_gt = group_by_frame(gt)

    # if we want to replicate results
    # np.random.seed(10)

    cap = cv2.VideoCapture(paths['video'])
    # cap.set(cv2.CAP_PROP_POS_FRAMES, frame_id)  # to start from frame #frame_id
    num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    if noise_params['add']:
        noisy_gt = add_noise(gt, noise_params, num_frames)
        grouped_noisy_gt = group_by_frame(noisy_gt)

    for frame_id in range(num_frames):
        _, frame = cap.read()

        if show['gt']:
            frame = draw_boxes(frame, grouped_gt[frame_id], color='g')

        if show['det']:
            frame = draw_boxes(frame, det[frame_id], color='b', det=True)

        if show['noisy']:
            frame = draw_boxes(frame, grouped_noisy_gt[frame_id], color='r')

        cv2.imshow('frame', frame)
        if cv2.waitKey() == 113:  # press q to quit
            break

        frame_id += 1

    cv2.destroyAllWindows()

    return

def task1_2(paths, ap=0.5):
    gt = read_annotations(paths['gt'], grouped=True, use_parked=True)
    det = read_detections(paths['det'])

    rec, prec, ap = voc_eval(det, gt, ap, use_confidence=True)
    print(ap)

    return

def run():
    paths = {
        'gt': '../data/AICity_data/train/S03/c010/ai_challenge_s03_c010-full_annotation.xml',
        'det': '../data/AICity_data/train/S03/c010/det/det_yolo3.txt',
        'video': '../data/vdo.avi'
    }

    show = {
        'gt': True,
        'det': False,
        'noisy': True
    }

    noise_params = {
        'add': True,
        'drop': 0.2,
        'generate_close': 0.2,
        'generate_random': 0.3,
        'type': 'specific',  # options: 'specific', 'gaussian', None
        'std': 40,  # pixels
        'position': False,
        'size': True,
        'keep_ratio': True
    }

    task1_1(paths, show, noise_params)
    task1_2(paths, ap=0.5)


import math

class CartesianTree:

    def __init__(self, key, parent=None, left=None, right=None):
        self.key = key
        self.parent = parent
        self.child = [left, right]

    def __str__(self, n=None, s="", d=0) -> str:
        if d == 0: n = self
        if n is None: return s
        s = self.__str__(n.child[1], s, d + 1)
        s += " "*4*d + str(n.key) + "\n"
        s = self.__str__(n.child[0], s, d + 1)
        return s

def cartesian_tree(l: list) -> CartesianTree:
    """ Constructs a Cartesian tree for a given list in O(n). """
    stk = []
    for i in range(len(l)):
        c = None
        while len(stk) > 0 and stk[-1].key > l[i]:
            c = stk.pop()
        stk.append(CartesianTree(l[i], stk[-1] if len(stk) > 0 else None, c))
        # add right child
        if len(stk) > 1:
            stk[-2].child[1] = stk[-1]
    return stk[0]

def cartesian_number(l: list) -> int:
    """ Returns the Cartesian number for a given list. """
    stk = []
    num = 0
    for i in range(len(l)):
        while len(stk) > 0 and stk[-1] > l[i]:
            stk.pop()
            num <<= 1
        stk.append(l[i])
        num <<= 1
        num |= 1
    return num << (2*len(l) - msb(num) - 1)

def msb(n: int) -> int:
    """ Returns the index of the most significant bit of n.
        Technically can be done in O(1) but too much work.
        http://web.stanford.edu/class/cs166/lectures/16/Slides16.pdf
    """
    return int(math.log2(n))

def sparse_table(l: list) -> list:
    """ Computes a sparse table (think 2^n jump pointers) """
    n, m = len(l), math.ceil(math.log2(len(l)))
    dp = [[] for i in range(n)]

    for i in range(n):
        dp[i].append(i)

    k = 1
    for j in range(m):
        for i in range(n):
            if i + k >= n or j >= len(dp[i + k]):
                break
            dp[i].append(min(dp[i][j], dp[i + k][j], key=lambda x: l[x]))
        k <<= 1

    return dp

def sparse_rmq(l: list, table: list, i: int, j: int) -> int:
    """ Returns the index of the minimum element between i and j. """
    k = msb(j - i + 1)
    return min(table[i][k], table[j - (1 << k) + 1][k], key=lambda x: l[x])

def full_table(l: list) -> list:
    """ Computes all possible ranges. """
    n = len(l)
    dp = [[] for i in range(n)]

    for i in range(n):
        dp[i].append(i)

    for j in range(n):
        for i in range(n - 1):
            if i + j >= n or j >= len(dp[i + 1]):
                break
            dp[i].append(min(dp[i][j], dp[i + 1][j], key=lambda x: l[x]))

    return dp

def full_rmq(table: list, i: int, j: int) -> int:
    """ O(1) RMQ. """
    return table[i][j - i]

def fischer_heun(l: list) -> tuple:
    """ Constructs the structure in O(n). """
    b = max(int(math.log2(len(l))) >> 2, 1)
    blocks = [l[i: i + b] for i in range(0, len(l), b)]
    a = [min(block) for block in blocks]
    indexes = [min(range(i, i + b), key=lambda x: l[x]) for i in range(0, len(l), b)]
    table = sparse_table(a)
    ids = [cartesian_number(block) for block in blocks]

    tables = {}
    for i, block in enumerate(blocks):
        if ids[i] not in tables:
            tables[ids[i]] = full_table(block)

    return b, a, indexes, ids, table, tables

def fh_rmq(o: list, b: int, a: list, indexes: list, ids: list, table: list, tables: list, i: int, j: int) -> int:
    """ O(1) RMQ. """
    l, r = i//b, j//b         # block indexes
    li, ri = i - l*b, j - r*b # index in the block
    # in same block
    if l == r:
        return b*l + full_rmq(tables[ids[l]], li, ri)
    return min(b*l + full_rmq(tables[ids[l]], li, b - 1), \
               indexes[sparse_rmq(a, table, l + 1, r - 1)] if r - 1 >= l + 1 else -1, \
               b*r + full_rmq(tables[ids[r]], 0, ri), key=lambda x: o[x] if x != -1 else float("inf"))

### PRESENTATION EXAMPLE

l = [5, 3, 4, 1, 2]

print("dp table")
dp = full_table(l)
for row in dp:
    print([l[i] for i in row])

print("sparse table")
sparse = sparse_table(l)
for row in sparse:
    print([l[i] for i in row])

# exit()

# http://web.stanford.edu/class/cs166/lectures/00/Slides00.pdf
# http://web.stanford.edu/class/cs166/lectures/01/Slides01.pdf

l = [32, 45, 16, 18, 9, 33]
l = [9, 3, 7, 1, 8, 12, 10, 20, 15, 18, 5]
l = [27, 18, 28, 18, 28, 45, 90, 45, 23, 53, 60, 28, 74, 71, 35]
# t = cartesian_tree(l)
# print(t)
# print(cartesian_number(l))

l = [16, 18, 33, 98]
# print(full_table(l))

l = [31, 41, 59, 26, 53, 58, 97, 93, 23, 84, 62, 64, 33, 83, 27]

# print(full_table(l))
stable = sparse_table(l)
# print(table)
# print(sparse_rmq(l, stable, 6, 9))
ftable = full_table(l)
# print(full_rmq(l, ftable, 6, 9))

# block size, "summary" array, summary mapping, cartesian numbers, sparse table, blockwise tables
b, a, indexes, ids, table, tables = fischer_heun(l)
# v = fh_rmq(l, b, a, indexes, ids, table, tables, 6, 10)
# print(v, l[v])

for i in range(len(l)):
    for j in range(i, len(l)):
        k = sparse_rmq(l, stable, i, j)
        assert k == full_rmq(ftable, i, j) and min(range(i, j + 1), key=lambda x: l[x]) == k
        assert k == fh_rmq(l, b, a, indexes, ids, table, tables, i, j)


from bs4 import BeautifulSoup
import requests

with open('index.html') as html_file:
    soup = BeautifulSoup(html_file, 'lxml')     # passing file and parser

# print(soup.prettify())      # using prettify to properly represent with html indent

# title = soup.title.text            # for printing the 1st title tag in from our html file
# print(title)

# div = soup.find('div', class_="collapse navbar-collapse")    # we have used css class_ instead of css class coz python has class keyword
# print(div)

links = soup.find_all('a')          # returns a list
for link in links:
    print(link)


from .frame import Frame
from .widget import Widget

class Container (Widget):
    def __init__ (self):
        Widget.__init__ (self)
        self._frames = {}
        self.focus_child = None

    def focus (self, child):
        if self.focus_child is child:
            return
        if self.focus_child is not None:
            self.focus_child.set_focus (False)
        self.focus_child = child
        if child is not None:
            child.set_focus (True)

    def render_child (self, child, width, height, theme):
        frame = self._frames.get (child)
        if frame is None or (frame.width, frame.height) != (width, height):
            frame = Frame (width, height)
            self._frames[child] = frame
        child.render_aligned (frame, theme)
        return frame

    def handle_event (self, event):
        if self.focus_child is not None and self.focus_child.handle_event (event):
            return True
        else:
            return False