# codesignal level1 n2
def centuryFromYear(year):
    return (year - 1) // 100 + 1
# tests
print('century from hear 1905: ',centuryFromYear(1905)) # expected 20
print('century from hear 1700: ',centuryFromYear(1700)) # expected 17

#  codesignal level1 n3
def checkPalindrome(inputString):
    length = len(inputString)
    mid = length // 2
    return inputString[:mid-1:-1] == inputString[:mid] if length%2 == 0 else inputString[:mid] == inputString[:mid:-1]
# tests
print('checkPalindrome: "aabaa", expected True is: ',checkPalindrome("aabaa"))
print('checkPalindrome: "abac",  expected False is: ',checkPalindrome("abac"))
print('checkPalindrome: "a", expected True is: ',checkPalindrome("a"))
print('checkPalindrome: "abacaba", expected True is: ',checkPalindrome("abacaba"))

# codesignal level2 n1
def adjacentElementsProduct(inputArray):
    result = 0
    temp = 0
    for i in range(len(inputArray)):
        if i == 0:
            continue
        temp = inputArray[i-1] * inputArray[i]
        if result == 0:
            result = temp
        else :
            result = temp if temp > result else result
    return result
# tests
print('max of two multiplied members in list: [3, 6, -2, -5, 7, 3] is 21 = ',adjacentElementsProduct([3, 6, -2, -5, 7, 3]))
print('max of two multiplied members in list: [5, 1, 2, 3, 1, 4] is 6 = ',adjacentElementsProduct([5, 1, 2, 3, 1, 4]))

# codesignal level2 n2 - polygon shape area calculator
def shapeArea(n):
    return (n * n) + ((n - 1) * (n - 1))
# tests
print('polygon area of 2 squares is 5 = ',shapeArea(2))
print('polygon area of 7000 squares is 97986001 = ',shapeArea(7000))

# codesignal level2 n3 - find missing numbers count if list becomes sorted
def makeArrayConsecutive2(statues):
    full = list( range( min(statues), max(statues) ) )
    result = []
    for i in range( 0, len(full) ):
        if full[i] not in statues:
            result.append( full[i] )
    return len( result )
# tests
print('missing numbers count in list [6, 2, 3, 8] is 3 = ',makeArrayConsecutive2([6, 2, 3, 8]))
print('missing numbers count in list [6, 2, 10, 3, 15, 8] is 8 = ',makeArrayConsecutive2([6, 2, 10, 3, 15, 8]))

# codesignal level2 n4 - is it possible to get increasing sequence by removing only 1 member
def almostIncreasingSequence(sequence):
    j = first_bad_pair(sequence)
    if j == -1:
        return True  # List is increasing
    if first_bad_pair(sequence[j - 1:j] + sequence[j + 1:]) == -1:
        return True  # Deleting earlier element makes increasing
    if first_bad_pair(sequence[j:j + 1] + sequence[j + 2:]) == -1:
        return True  # Deleting later element makes increasing
    return False
# additional function for l2 n2 - almostIncreasingSequence
def first_bad_pair(sequence):
    for i in range(len(sequence) - 1):
        if sequence[i] >= sequence[i + 1]:
            return i
    return -1
# tests
print('almostIncreasingSequence of [1, 3, 2, 1] is false = ',almostIncreasingSequence([1, 3, 2, 1]))
print('almostIncreasingSequence of [123, -17, -5, 1, 2, 3, 12, 43, 45] is true = ',almostIncreasingSequence([123, -17, -5, 1, 2, 3, 12, 43, 45]))

# codesignal level2 n5 - matrix of ghosts
def matrixElementsSum(matrix):
    result = 0
    ignore = []
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] > 0 and j not in ignore:
                result += matrix[i][j]
            elif matrix[i][j] == 0 and j not in ignore:
                ignore.append(j)
    return result
# tests
print('matrix of ghosts [[0,1,1,2],[0,5,0,0],[2,0,3,3]] sum is 9 = ',matrixElementsSum([[0,1,1,2],[0,5,0,0],[2,0,3,3]]))
print('matrix of ghosts [[4,0,1],[10,7,0],[0,0,0],[9,1,2]] sum is 15 = ',matrixElementsSum([[4,0,1],[10,7,0],[0,0,0],[9,1,2]]))

# codesignal level3 n1 - find longest string in list and how many have same length
def allLongestStrings(inputArray):
    result = []
    longest = max(inputArray, key=len)
    length = len(longest)
    for i in inputArray:
        if len(i) == length:
            result.append(i)
    return result
# tests
print('all longest strings of ["aba","aa","ad","vcd","aba"] is ["aba","vcd","aba"] = ',allLongestStrings(["aba","aa","ad","vcd","aba"]))
print('all longest strings of ["abc","eeee","abcd","dcd"] is ["eeee","abcd"] = ',allLongestStrings(["abc","eeee","abcd","dcd"]))

# codesignal level3 n2
def commonCharacterCount(s1, s2):
    result = 0
    ignore = []
    for i in s1:
        for j in range(len(s2)):
            if i == s2[j] and j not in ignore:
                ignore.append(j)
                result += 1
                break
    return result
# tests
print('commonCharacterCount of "aabcc" and "adcaa" is 3 = ',commonCharacterCount("aabcc","adcaa"))
print('commonCharacterCount of "zzzz" and "zzzzzzz" is 4 = ',commonCharacterCount("zzzz","zzzzzzz"))
print('commonCharacterCount of "abca" and "xyzbac" is 3 = ',commonCharacterCount("abca","xyzbac"))

# codesignal level3 n3 - lottery win when one half of matrix sum is equal to other half
def isLucky(n):
    half = len(list(n)) // 2
    sum1 = 0
    sum2 = 0
    for i in n[:half]:
        sum1 += int(i)
    for j in n[half:]:
        sum2 += int(j)
    return sum1 == sum2
# tests
print('the ticket with "134008" is lucky: true = ',isLucky('134008'))
print('the ticket with "239017" is lucky: false = ',isLucky('239017'))

# codesignal level3 n4 - sort low to high humans ignoring trees
def sortByHeight(a):
    new = []
    tmp = []
    for v in a:
        if v != -1:
            tmp.append(v)
    tmp.sort()
    z = 0
    for j,x in enumerate(a):
        if x == -1:
            new.insert(j, x)
        else:
            new.insert(j, tmp[z])
            z += 1
    return new

# tests
print('sorted: ',sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]))
print('sorted: ',sortByHeight([23, 54, -1, 43, 1, -1, -1, 77, -1, -1, -1, 3]))

# codesignal level3 n5 - invert string in parentheses
def reverseInParentheses(inputString):
    stack = []
    for x in inputString:
        if x == ")":
            tmp = ""
            while stack[-1] != "(":
                tmp += stack.pop()
            stack.pop() # pop the (
            for item in tmp:
                stack.append(item)
        else:
            stack.append(x)

    return "".join(stack)

# tests "(bar)"
print('==========\n1) inverted: ',reverseInParentheses("(bar)")) # expected "rab"
print('==========\n2) inverted: ',reverseInParentheses("foo(bar)baz")) # expected "foorabbaz"
print('==========\n3) inverted: ',reverseInParentheses("foo(bar)baz(blim)")) # expected "foorabbazmilb"
print('==========\n4) inverted: ',reverseInParentheses("foo(bar(baz))blim"))  # expected "foobazrabblim"

# codesignal level4 n1 - alternating sums
def alternatingSums(a):
    return [sum(a[::2]), sum(a[1::2])]

# tests
print('==========\n1) inverted: ',alternatingSums([50, 60, 60, 45, 70])) # expected [180, 105]
print('==========\n2) inverted: ',alternatingSums([100, 50])) # expected [100, 50]
print('==========\n3) inverted: ',alternatingSums([100, 50, 10, 20, 30, 40])) # expected [140, 110]

# codesignal level4 n2 - alternating sums
def addBorder(picture):
    output = []
    border = ""
    for i in range(0,len(picture[0])+2):
        border += "*"
    output.append(border)
    for i in range(0,len(picture)):
        output.append("*"+picture[i]+"*")

    output.append(border)

    return output

# tests
print('==========\n1) bordered: ',addBorder(["abc","ded"])) # expected
print('==========\n2) bordered: ',addBorder(["a"])) # expected

# codesignal level4 n3 - similar when swapping at least 2 array members
def areSimilar(a, b):
    if a == b: return True
    not_same = []
    tmp = b
    for i,v in enumerate(a):
        # when more than 2 elements values do not match
        if len(not_same) > 2: return False #  result is false
        # when value of same index in both lists do not match
        if v != b[i]: not_same.append(i) # remember the value that did not matched
    if len(not_same) == 2:
        tmp[not_same[1]], tmp[not_same[0]] = b[not_same[0]], b[not_same[1]]
        print(f"a: {a}, b: {b}, tmp: {tmp}, not_same: {not_same}")
        return True if tmp == a else False
    return False
# tests
print('=========\n1) areSimilar is false =', areSimilar([1, 1, 4], [1, 2, 3]))
print('=========\n2) areSimilar is false =', areSimilar([1, 2, 2], [2, 1, 1]))
print('=========\n3) areSimilar false =', areSimilar([832, 998, 148, 570, 533, 561, 894, 147, 455, 279], [832, 570, 148, 998, 533, 561, 455, 147, 894, 279]))

# codesignal level4 n4 -
def arrayChange(inputArray):
    sum = 0
    q = inputArray[0]
    for i in inputArray[1:]:
        if i <= q:
            sum += q-i+1
            q = q+1
        else:
            q = i
    return sum

# tests
print('=========\n1) arrayChange is 3 =', arrayChange([1, 1, 1]))
print('=========\n2) arrayChange is 5 =', arrayChange([-1000, 0, -2, 0]))

# codesignal level4 n5 -
def palindromeRearranging(inputString):
    r = {}
    for v in inputString:
        if v not in r:
            r[v] = 1
        else:
            r[v] += 1
    count = [x for x in r if r[x] % 2]
    if len(count) > 1:
        return False
    else:
        return True
# tests
print('=========\n1) palindromeRearranging is true =', palindromeRearranging("aabb"))
print('=========\n2) palindromeRearranging is false =', palindromeRearranging("abca"))

# codesignal level5 n1 -
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
    return True if yourLeft == friendsLeft and yourRight == friendsRight or yourLeft == friendsRight and yourRight == friendsLeft else False
# tests
print('=========\n1) areEquallyStrong is true =', areEquallyStrong(10, 15, 15, 10))
print('=========\n2) areEquallyStrong is false =', areEquallyStrong(15, 10, 15, 9))

# codesignal level5 n2 -
def arrayMaximalAdjacentDifference(inputArray):
    diff = 0
    tmp = inputArray[0]
    for i in inputArray[1:]:
        if tmp > i and diff < tmp - i:
            diff = tmp - i
        if tmp < i and diff < i - tmp:
            diff = i - tmp
        tmp = i
    return diff
# tests
print('=========\n1) arrayMaximalAdjacentDifference is 2 =',
    arrayMaximalAdjacentDifference([10, 11, 13]))
print('=========\n2) arrayMaximalAdjacentDifference is 0 =',
    arrayMaximalAdjacentDifference([1, 1, 1, 1]))
print('=========\n3) arrayMaximalAdjacentDifference is 7 =',
    arrayMaximalAdjacentDifference([-1, 4, 10, 3, -2]))

# codesignal level5 n3 -
def isIPv4Address(inputString):
    splited = inputString.split('.')
    if len(splited) != 4:
        return False
    for x in splited:
        if x == '' or not x.isdigit() or int(x) < 0 or 255 < int(x):
            return False
    return True
# tests
print('=========\n1) isIPv4Address is true =', isIPv4Address("172.16.254.1"))
print('=========\n2) isIPv4Address is false =', isIPv4Address("172.316.254.1"))
print('=========\n3) isIPv4Address is false =', isIPv4Address(".254.255.0"))

# codesignal 22
def avoidObstacles(inputArray):
    for i in range(1, max(inputArray)):
        divs = any([x for x in inputArray if not x%i])
        if not divs:
            return i
    return max(inputArray) + 1
# tests
print(avoidObstacles([5, 3, 6, 7, 9]))
print(avoidObstacles([2, 3]))
print(avoidObstacles([1, 4, 10, 6, 2]))

# codesignal 23
def pixel(matrix,i,j):
    total = 0
    for x in range(i - 1, i + 2):
        for y in range(j - 1, j + 2):
            total += matrix[x][y]
    return total//9

def boxBlur(image):
    sol = []
    row = len(image)
    col = len(image[0])
    for i in range(1, row - 1):
        temp = []
        for j in range(1, col - 1):
            temp.append(pixel(image, i, j))
        sol.append(temp)

    return sol
# tests
print(boxBlur([[1,1,1],
               [1,7,1],
               [1,1,1]]), 'result should be: [[1]]')
print(boxBlur([[36,0,18,9],
                [27,54,9,0],
                [81,63,72,45]]), 'result should be: [[40,30]]')


from sept.errors import OperatorNotFoundError, OperatorNameAlreadyExists

class OperatorManager(object):
    def __init__(self):
        super(OperatorManager, self).__init__()
        self._cache = {}

        from sept.builtin.operators import ALL_OPERATORS

        for operator_klass in ALL_OPERATORS:
            self._cache[operator_klass.name] = operator_klass

    @property
    def operators(self):
        # Don't include the NULL operator
        return sorted(
            filter(lambda op: op._private is False, self._cache.values()),
            key=lambda op: op.name,
        )

    def add_custom_operators(self, custom_operators, dont_overwrite=True):
        for custom_operator in custom_operators:
            if custom_operator.name in self._cache and dont_overwrite:
                raise OperatorNameAlreadyExists(
                    "An Operator with the name {name} already exists as "
                    "{value}. If you wish to overwrite that value, make sure "
                    "you pass `dont_overwrite=True` when adding custom "
                    "operators.".format(
                        name=custom_operator.name,
                        value=self._cache[custom_operator.name],
                    )
                )
            self._cache[custom_operator.name] = custom_operator()

    def getOperator(self, operator_name, args=None):
        if operator_name in self._cache:
            operator_klass = self._cache[operator_name]
            return operator_klass.create(args)
        raise OperatorNotFoundError(
            "Could not find an Operator with the name {}".format(operator_name)
        )


# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import os, requests, json

# python request examples
# https://www.pythonforbeginners.com/requests/using-requests-in-python

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.

def restexample01():
    github_url = "https://api.github.com/user/repos"
    data = json.dumps({'name': 'test', 'description': 'some test repo'})
    r = requests.post(github_url, data, auth=('user', '*****'))
    print(r.json)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    restexample01()
    print_hi("PyCharm. It's end of the code")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/


from typing import Tuple

from sqlalchemy import and_, desc

from quizard_backend import db
from quizard_backend.utils.exceptions import raise_not_found_exception
from quizard_backend.utils.transaction import in_transaction

def dict_to_filter_args(model, **kwargs):
    """
    Convert a dictionary to Gino/SQLAlchemy's conditions for filtering.

    Example:
        A correct Gino's query is:
            User.query.where(
                and_(
                    User.role_id == 10,
                    User.location == "Singapore"
                )
            ).gino.all()

        The given `kwargs` is:
            {
                "role_id": 10,
                "location": "Singapore",
            }
        This function unpacks the given dictionary `kwargs`
        into `and_(*clauses)`.
    """
    return (getattr(model, k) == v for k, v in kwargs.items())

async def get_one(model, **kwargs):
    return (
        await model.query.where(and_(*dict_to_filter_args(model, **kwargs)))
        .limit(1)
        .gino.first()
    )

async def get_many(
    model,
    columns=None,
    after_id=None,
    limit=15,
    in_column=None,
    in_values=None,
    order_by="internal_id",
    descrease=False,
    **kwargs,
):
    # Get the `internal_id` value from the starting row
    # And use it to query the next page of results
    last_internal_id = 0
    if after_id:
        row_of_after_id = await model.query.where(model.id == after_id).gino.first()
        if not row_of_after_id:
            raise_not_found_exception(model, **kwargs)

        last_internal_id = row_of_after_id.internal_id

    # Get certain columns only
    if columns:
        query = db.select([*(getattr(model, column) for column in columns)])
    else:
        query = model.query

    query = query.where(
        and_(
            *dict_to_filter_args(model, **kwargs),
            model.internal_id < last_internal_id
            if descrease and last_internal_id
            else model.internal_id > last_internal_id,
            getattr(model, in_column).in_(in_values)
            if in_column and in_values
            else True,
        )
    )

    return (
        await query.order_by(
            desc(getattr(model, order_by)) if descrease else getattr(model, order_by)
        )
        .limit(limit)
        .gino.all()
    )

async def get_latest_quiz_attempts(model, user_id, limit=15, after_id=None, **kwargs):
    # Get the `internal_id` value from the starting row
    # And use it to query the next page of results
    last_internal_id = 0
    if after_id:
        row_of_after_id = await model.query.where(model.id == after_id).gino.first()
        if not row_of_after_id:
            raise_not_found_exception(model, **kwargs)

        last_internal_id = row_of_after_id.internal_id

    return (
        await db.status(
            db.text(
                """SELECT * FROM (
                    SELECT DISTINCT ON (quiz_attempt.quiz_id, quiz_attempt.user_id)
                        quiz_attempt.quiz_id,
                        quiz_attempt.user_id,
                        quiz_attempt.is_finished,
                        quiz_attempt.internal_id
                    FROM quiz_attempt
                    WHERE quiz_attempt.user_id = :user_id {}
                    ORDER BY
                        quiz_attempt.quiz_id,
                        quiz_attempt.user_id,
                        quiz_attempt.internal_id DESC
                    ) t
                    ORDER By t.internal_id DESC limit :limit;""".format(
                    "and quiz_attempt.internal_id < :last_internal_id"
                    if after_id
                    else ""
                )
            ),
            {"user_id": user_id, "limit": limit, "last_internal_id": last_internal_id},
        )
    )[1]

async def get_one_latest(model, **kwargs):
    return (
        await model.query.where(and_(*dict_to_filter_args(model, **kwargs)))
        .order_by(desc(model.internal_id))
        .limit(1)
        .gino.first()
    )

async def get_many_with_count_and_group_by(
    model, *, columns, in_column=None, in_values=None
):
    return (
        await db.select(
            [*[getattr(model, column) for column in columns], db.func.count()]
        )
        .where(
            getattr(model, in_column).in_(in_values)
            if in_column and in_values
            else True
        )
        .group_by(*[getattr(model, column) for column in columns])
        .gino.all()
    )

@in_transaction
async def create_one(model, **kwargs):
    return await model(**kwargs).create()

@in_transaction
async def update_one(row, **kwargs):
    if not kwargs:
        return row

    await row.update(**kwargs).apply()
    return row

@in_transaction
async def update_many(model, get_kwargs, update_kwargs):
    status: Tuple[str, list] = await model.update.values(**update_kwargs).where(
        and_(*and_(*dict_to_filter_args(model, **get_kwargs)))
    ).gino.status()
    return status[0]

@in_transaction
async def delete_many(model, **kwargs):
    status: Tuple[str, list] = await model.delete.where(
        and_(*dict_to_filter_args(model, **kwargs))
    ).gino.status()
    return status[0]


from xadrez.tabuleiro.Cor import Cor
from xadrez.tabuleiro.Peca import Peca
from xadrez.tabuleiro.Posicao import Posicao
from xadrez.xadrez.Torre import Torre

class Rei(Peca):
    def __init__(self, tab, cor, partida):
        super().__init__(tab, cor)
        self.partida = partida

    def __str__(self):
        return "R"

    def podeMover(self, pos):
        p = self.tabuleiro.peca(pos)
        return p == None or p.cor != self.cor

    def __crie_matriz(self, n_linhas, n_colunas):
        matriz = []
        valor = False
        for _ in range(n_linhas):
            linha = []
            for _ in range(n_colunas):
                linha += [valor]
            matriz += [linha]

        return matriz

    def existeInimigo(self, pos):
        p = self.tabuleiro.peca(pos)
        return p != None and p.cor != self.cor

    def testeTorreParaRoque(self, pos):
        p = self.tabuleiro.peca(pos)
        return p != None and isinstance(p, Torre) and p.cor != self.cor and p.qteMovimentos == 0

    def movimentosPossiveis(self):
        mat = self.__crie_matriz(self.tabuleiro.linhas, self.tabuleiro.colunas)

        posicao = Posicao(0, 0)

        # ESQUERDA
        posicao.definirValores(self.posicao.linha, self.posicao.coluna - 1)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        # DIREITA
        posicao.definirValores(self.posicao.linha, self.posicao.coluna + 1)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        # ACIMA
        posicao.definirValores(self.posicao.linha - 1, self.posicao.coluna)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        # ABAIXO
        posicao.definirValores(self.posicao.linha + 1, self.posicao.coluna - 1)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        # NO
        posicao.definirValores(self.posicao.linha - 1, self.posicao.coluna - 1)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        # NE
        posicao.definirValores(self.posicao.linha - 1, self.posicao.coluna + 1)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        # SE
        posicao.definirValores(self.posicao.linha + 1, self.posicao.coluna + 1)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        # SO
        posicao.definirValores(self.posicao.linha + 1, self.posicao.coluna - 1)
        if (self.tabuleiro.posicaoValida(posicao) and self.podeMover(posicao)):
            mat[posicao.linha][posicao.coluna] = True

        if (self.qteMovimentos == 0 and not self.partida.xeque):
            posT1 = Posicao(self.posicao.linha, self.posicao.coluna + 3)
            if (self.testeTorreParaRoque(posT1)):
                p1 = Posicao(posicao.linha, posicao.coluna + 1)
                p2 = Posicao(posicao.linha, posicao.coluna + 2)
                if (self.tabuleiro.peca(p1) == None and self.tabuleiro.peca(p2) == None):
                    mat[posicao.linha][posicao.coluna + 2] = True

            posT2 = Posicao(self.posicao.linha, self.posicao.coluna - 4)
            if (self.testeTorreParaRoque(posT2)):
                p1 = Posicao(posicao.linha, posicao.coluna - 1)
                p2 = Posicao(posicao.linha, posicao.coluna - 2)
                p3 = Posicao(posicao.linha, posicao.coluna - 3)

                if (not any([self.tabuleiro.peca(p1), self.tabuleiro.peca(p2), self.tabuleiro.peca(p3)])):
                    mat[posicao.linha][posicao.coluna - 2] = True

        return mat


from db import Mysql_Object
import tkinter as tk
import random as rd
import tkinter.messagebox as msgbox

class manage_page:
    def __init__(self, master):
        # 连接数据库
        self.sql = Mysql_Object('localhost', 'root', '123456', 'parkinglot_management')
        self.win = master
        self.win.resizable(0, 0)
        self.win.title('入场管理界面')

        # 窗口居中
        ww, wh = 800, 400
        sw, sh = self.win.winfo_screenwidth(), self.win.winfo_screenheight()
        x, y = (sw - ww) / 2, (sh - wh) / 2
        self.win.geometry("%dx%d+%d+%d" % (ww, wh, x, y))

        # 搭建存储文本框的frame
        self.f1 = tk.Frame(self.win, width=ww - 20, height=wh - 80, bg="lightgreen")
        self.f1.pack(padx=10, pady=10)

        # 创建多行文本框
        self.t1 = tk.Text(self.f1, width=ww - 40, height=21)
        self.t1.pack(side="top", padx=10, pady=10)

        lb = tk.Label(self.win, text="工号: ")
        lb.pack(side="left", padx=10, anchor="nw")

        show_free = tk.Label(self.win, text=self.get_id())
        show_free.pack(side='left', padx=10, anchor='nw')
        # var_num = tk.IntVar()
        # e1 = tk.Entry(window, textvariable=var_num)
        # e1.pack(side="left", padx=10, pady=10, anchor="sw")

        lb2 = tk.Label(self.win, text='输入车牌：')
        lb2.pack(side='left', padx=10, anchor='nw')

        self.var_spot = tk.StringVar()
        e_spot = tk.Entry(self.win, textvariable=self.var_spot, width=5)
        e_spot.pack(side='left', padx=15, anchor='nw')

        btn_cf = tk.Button(self.win, text="查看预约", command=self.search_reserve)
        btn_cf.pack(side="left", padx=10, anchor="nw")

        lb3 = tk.Label(self.win, text='选择车位：')
        lb3.pack(side='left', padx=10, anchor='nw')

        self.chosen_no = tk.IntVar()
        e_spot = tk.Entry(self.win, textvariable=self.chosen_no, width=5)
        e_spot.pack(side='left', padx=10, anchor='nw')

        btn_sel = tk.Button(self.win, text="查询空闲车位", command=self.select_spot)
        btn_sel.pack(side="left", padx=10, anchor="nw")

        btn_cfs = tk.Button(self.win, text='确认车位', command=self.cf_spot)
        btn_cfs.pack(side="left", padx=10, anchor="nw")

        btn_del = tk.Button(self.win, text="通行", command=self.let_goin)

        btn_exit = tk.Button(self.win, text="退出", command=self.win.destroy)
        # 放置
        btn_exit.pack(side="right", padx=10, pady=10, anchor="se")
        btn_del.pack(side="right", pady=10, anchor="se")

    #获取工号
    def get_id(self):
        msg = self.get_msg()[0].strip().strip("'")
        return msg

    # 查看空闲车位信息
    def select_spot(self):
        self.t1.delete(1.0, tk.END)
        self.t1.insert(1.0, "车位号\t\t车辆标签\t\t车位类型\t\t占用状态\n")
        msg = self.sql.select_sql("select * from parkingspot where Slabel='临时' and Sstate='未占用'")[1]
        # print(msg)
        for spot in msg:
            self.t1.insert('end', "{}\t\t{}\t\t{}\t\t{}\n".format(spot[0], spot[1], spot[2], spot[3]))

    #这里返回查询的预约记录
    def search_reserve(self):
        # print(self.var_spot)
        msg = "select * from parkingspot where Cno='{}'".format(self.var_spot.get())
        msg = self.sql.select_sql(msg)
        self.t1.delete(1.0, tk.END)
        self.t1.insert(1.0, "车位号\t\t车辆标签\t\t车位类型\t\t占用状态\t\t车牌号\t\t预约时间\t\t预约状态\n")
        for msg in msg[1]:
            self.t1.insert('end', "{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\n".format(msg[0], msg[1], msg[2], msg[3], msg[4], msg[5], msg[7]))

    # 确认车位
    def cf_spot(self):
        msg = "update parkingspot set Sstate='占用', Cno='{}', Suse_time='{}' where Sno='{}'".format(self.var_spot.get(), self.get_randusetiem(), self.chosen_no.get())
        self.sql.excute_sql(msg)
        msgbox.showinfo(message="确认成功")
        self.select_spot()

    # 获得随机使用时间
    def get_randusetiem(self):
        return rd.randint(10, 300)

    #这里实现通行
    def let_goin(self):
       #这里写入通行逻辑操作
       msgbox.showinfo(message="车辆已入场")

    def get_msg(self):
        with open('current_user.text', 'r') as f:
            msg = f.read().strip('(').strip(')').split(',')
            # print(msg)
        return msg

if __name__ == '__main__':
    window = tk.Tk()
    manage_page(window)
    window.mainloop()


import sys
import pefile
import re

# Pega os headers de um executável
def get_headers(executable):
    pe = pefile.PE(executable)
    sections = []
    for section in pe.sections:
        sections.append(section.Name.decode('utf-8'))
    return sections

# Pega os headers dos argumentos de entrada
sections1 = get_headers(sys.argv[1])
sections2 = get_headers(sys.argv[2])

# Imprime a intersecção entre as listas
commonSections = list(set(sections1).intersection(sections2))
print("Seções comuns: [", end="")
for i, section in enumerate(commonSections):
    print("'{}'".format(section), end="")
    if i < len(commonSections) - 1:
        print(', ', end="")
print("]\n")

# Imprime a diferença da lista 1 para a lista 2
difference12 = list(set(sections1).difference(sections2))
print(re.sub(".*/", "", sys.argv[1]) + ": [", end="")
for i, section in enumerate(difference12):
    print("'{}'".format(section), end="")
    if i < len(difference12) - 1:
        print(', ', end="")
print("]\n")

# Imprime a diferença da lista 2 para a lista 1
difference21 = list(set(sections2).difference(sections1))
print(re.sub(".*/", "", sys.argv[2]) + ": [", end="")
for i, section in enumerate(difference21):
    print("'{}'".format(section), end="")
    if i < len(difference21) - 1:
        print(', ', end="")
print("]\n")


"""
Common utilities for derp used by various classes.
"""
from collections import namedtuple
import cv2
from datetime import datetime
import heapq
import logging
import pathlib
import numpy as np
import os
import socket
import time
import yaml
import zmq
import capnp
import messages_capnp

Bbox = namedtuple("Bbox", ["x", "y", "w", "h"])

TOPICS = {
    "camera": messages_capnp.Camera,
    "controller": messages_capnp.Controller,
    "action": messages_capnp.Action,
    "imu": messages_capnp.Imu,
    "quality": messages_capnp.Quality,
}

DERP_ROOT = pathlib.Path(os.environ["DERP_ROOT"])
MODEL_ROOT = DERP_ROOT / "models"
RECORDING_ROOT = DERP_ROOT / "recordings"
CONFIG_ROOT = DERP_ROOT / "config"
MSG_STEM = "/tmp/derp_"

def is_already_running(path):
    """ For the given PID path check if the PID exists """
    if isinstance(path, str):
        path = pathlib.Path(path)
    if not path.exists():
        return False
    with open(str(path)) as pid_file:
        pid = int(pid_file.read())
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    return True

def write_pid(path):
    with open(str(path), 'w') as pid_file:
        pid_file.write(str(os.getpid()))
        pid_file.flush()

def init_logger(name, recording_path, level=logging.INFO):
    logger = logging.getLogger(name)
    formatter = logging.Formatter('%(asctime)s %(levelname)-5s %(message)s')
    fileHandler = logging.FileHandler(recording_path / ('%s.log' % name), mode='w')
    fileHandler.setFormatter(formatter)
    streamHandler = logging.StreamHandler()
    streamHandler.setFormatter(formatter)
    logger.setLevel(level)
    logger.addHandler(fileHandler)
    logger.addHandler(streamHandler)
    return logger

def make_recording_path():
    date = datetime.utcfromtimestamp(time.time()).strftime("%Y%m%d-%H%M%S")
    folder = RECORDING_ROOT / ("recording-%s-%s" % (date, socket.gethostname()))
    folder.mkdir(parents=True)
    return folder

def get_timestamp():
    return int(time.time() * 1e9)

def publisher(path):
    context = zmq.Context()
    sock = context.socket(zmq.PUB)
    sock.bind("ipc://" + path)
    # sock.bind("tcp://*:%s" % port)
    return context, sock

def subscriber(paths):
    context = zmq.Context()
    sock = context.socket(zmq.SUB)
    # sock.connect("tcp://localhost:%s" % port)
    for path in paths:
        sock.connect("ipc://" + path)
    sock.setsockopt(zmq.SUBSCRIBE, b"")
    return context, sock

def topic_file_reader(folder, topic):
    return open("%s/%s.bin" % (folder, topic), "rb")

def topic_exists(folder, topic):
    path = folder / ("%s.bin" % topic)
    return path.exists()

def topic_file_writer(folder, topic):
    return open("%s/%s.bin" % (folder, topic), "wb")

def print_image_config(name, config):
    """ Prints some useful variables about the camera for debugging purposes """
    top = config["pitch"] + config["vfov"] / 2
    bot = config["pitch"] - config["vfov"] / 2
    left = config["yaw"] - config["hfov"] / 2
    right = config["yaw"] + config["hfov"] / 2
    hppd = config["width"] / config["hfov"]
    vppd = config["height"] / config["vfov"]
    print(
        "%s top: %6.2f bot: %6.2f left: %6.2f right: %6.2f hppd: %5.1f vppd: %5.1f"
        % (name, top, bot, left, right, hppd, vppd)
    )

def get_patch_bbox(target_config, source_config):
    """
    Gets a different sub-persepective given a smaller desired hfov/vfov and different yaw/pitch
    """
    hfov_ratio = target_config["hfov"] / source_config["hfov"]
    vfov_ratio = target_config["vfov"] / source_config["vfov"]
    hfov_offset = source_config["yaw"] - target_config["yaw"]
    vfov_offset = source_config["pitch"] - target_config["pitch"]
    patch_width = int(source_config["width"] * hfov_ratio + 0.5)
    patch_height = int(source_config["height"] * vfov_ratio + 0.5)
    x_center = (source_config["width"] - patch_width) // 2
    y_center = (source_config["height"] - patch_height) // 2
    x_offset = int(hfov_offset / source_config["hfov"] * source_config["width"] + 0.5)
    y_offset = int(vfov_offset / source_config["vfov"] * source_config["height"] + 0.5)
    x = x_center + x_offset
    y = y_center + y_offset
    if (x >= 0 and x + patch_width <= source_config["width"] and
        y >= 0 and y + patch_height <= source_config["height"]):
        return Bbox(x, y, patch_width, patch_height)
    return None

def crop(image, bbox):
    """ Crops the Bbox(x,y,w,h) from the image. Copy indicates to copy of the ROI"s memory"""
    return image[bbox.y : bbox.y + bbox.h, bbox.x : bbox.x + bbox.w]

def resize(image, size):
    """ Resize the image to the target (w, h) """
    is_larger = size[0] > image.shape[1] or size[1] > image.shape[0]
    interpolation = cv2.INTER_LINEAR if is_larger else cv2.INTER_AREA
    return cv2.resize(image, size, interpolation=interpolation)

def perturb(frame, camera_config, shift=0, rotate=0):
    # Estimate how many pixels to rotate by, assuming fixed degrees per pixel
    pixels_per_degree = camera_config["width"] / camera_config["hfov"]

    # Figure out where the horizon is in the image
    horizon_frac = ((camera_config["vfov"] / 2) + camera_config["pitch"]) / camera_config["vfov"]

    # For each row in the frame shift/rotate it
    indexs = np.arange(len(frame))
    vertical_fracs = np.linspace(0, 1, len(frame))

    # For each vertical line, apply shift/rotation rolls
    for index, vertical_frac in zip(indexs, vertical_fracs):
        magnitude = rotate * pixels_per_degree
        if vertical_frac > horizon_frac:
            ground_angle = (vertical_frac - horizon_frac) * camera_config["vfov"]
            ground_distance = camera_config["z"] / np.tan(deg2rad(ground_angle))
            ground_width = 2 * ground_distance * np.tan(deg2rad(camera_config["hfov"]) / 2)
            magnitude += (shift / ground_width) * camera_config["width"]
        magnitude = int(magnitude + 0.5 * np.sign(magnitude))
        if magnitude > 0:
            frame[index, magnitude:, :] = frame[index, : frame.shape[1] - magnitude]
            frame[index, :magnitude, :] = 0
        elif magnitude < 0:
            frame[index, :magnitude, :] = frame[index, abs(magnitude) :]
            frame[index, frame.shape[1] + magnitude :] = 0
    return frame

def deg2rad(val):
    return val * np.pi / 180

def rad2deg(val):
    return val * 180 / np.pi

def load_image(path):
    return cv2.imread(str(path))

def save_image(path, image):
    return cv2.imwrite(str(path), image)

def load_config(config_path):
    """ Load a configuration file, also reading any component configs """
    with open(str(config_path)) as config_fd:
        config = yaml.load(config_fd, Loader=yaml.FullLoader)
    for component in config:
        if isinstance(config[component], dict) and "path" in config[component]:
            component_path = CONFIG_ROOT / config[component]["path"]
            with open(str(component_path)) as component_fd:
                component_config = yaml.load(component_fd, Loader=yaml.FullLoader)
            component_config.update(config[component])
            config[component] = component_config
            if "name" not in config[component]:
                config[component]["name"] = component_path.stem
    if "name" not in config:
        config["name"] = config_path.stem
    return config

def dump_config(config, config_path):
    """ Write a configuration file """
    with open(str(config_path), 'w') as config_fd:
        yaml.dump(config, config_fd)

def extract_latest(desired_times, source_times, source_values):
    out = []
    pos = 0
    val = 0
    for desired_time in desired_times:
        while pos < len(source_times) and source_times[pos] < desired_time:
            val = source_values[pos]
            pos += 1
        out.append(val)
    return np.array(out)

def load_topics(folder):
    if isinstance(folder, str):
        folder = pathlib.Path(folder)
    out = {}
    for topic in TOPICS:
        if not topic_exists(folder, topic):
            continue
        topic_fd = topic_file_reader(folder, topic)
        out[topic] = [msg for msg in TOPICS[topic].read_multiple(topic_fd)]
        topic_fd.close()
    return out

def replay(topics):
    heap = []
    for topic in topics:
        for msg in topics[topic]:
            heapq.heappush(heap, [msg.publishNS, topic, msg])
    while heap:
        yield heapq.heappop(heap)

def decode_jpg(jpg):
    return cv2.imdecode(np.frombuffer(jpg, np.uint8), cv2.IMREAD_COLOR)

def encode_jpg(image, quality):
    return cv2.imencode(".jpg", image, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tostring()

def extract_car_actions(topics):
    out = []
    autonomous = False
    speed_offset = 0
    steer_offset = 0
    for timestamp, topic, msg in replay(topics):
        if topic == "controller":
            autonomous = msg.isAutonomous
            speed_offset = msg.speedOffset
            steer_offset = msg.steerOffset
        elif topic == "action":
            if autonomous or msg.isManual:
                out.append([timestamp, msg.speed + speed_offset, msg.steer + steer_offset])
    if not out:
        out.append([0, 0, 0])
    return np.array(out)


from urllib import response
import requests
from pprint import pprint
from time import sleep
import os

from sqlalchemy import null

url = "http://10.0.1.10:8080"

# ------------------------ PRINT ------------------------
def menu():
    os.system('clear') or None
    print("-------------------:-------------------")
    print("| 1 |  Cadastrar Usuario              |")
    print("| 2 |  Exibir    Usuario              |")
    print("| 3 |  Alterar   Usuario              |")
    print("| 4 |  Excluir   Usuario              |")
    print("-------------------:-------------------")
    print("| 5 |  Cadastrar Projeto              |")
    print("| 6 |  Exibir    Projeto              |")
    print("| 7 |  Alterar   Projeto              |")
    print("| 8 |  Excluir   Projeto              |")
    print("-------------------:-------------------")
    print("| 9 |  SAIR                           |")
    print("-------------------:-------------------")

def menu1():
    os.system('clear') or None
    print("-------------------:-------------------")
    print("| 1 |  Pessoa Física                  |")
    print("| 2 |  Pessoa Jurídica        Sair[0] |")
    print("-------------------:-------------------")

def menu2():
    print("-------------------:-------------------")
    print("|            Deseja alterar?          |")
    print("|         [1] Sim      [2] Não        |")
    print("-------------------:-------------------")

def main():
    opc = None
    while opc != "9":
        menu()
        opc = input("Informe uma opcao: ")

        if opc == "1":        #Cadastrar Usuario
            cadastroUser()

        elif opc == "2":      #Exibir Usuario
            exibirUser()

        elif opc == "3":      #Alterar Usuario
            alterarUser()

        elif opc == "4":      #Excluir Usuario
            excluirUser()

        elif opc == "5":      #Cadastrar Projeto
            cadastroProj()

        elif opc == "6":      #Exibir Projeto
            exibirProj()

        elif opc == "7":      #Alterar Projeto
            alterarProj()

        elif opc == "8":      #Excluir Projeto
            excluirProj()

        elif opc == "9":
            exit()

        input("Pressione ENTER para continuar!\n")

def jsonPrint(resp):
    if resp.status_code == 200:
        pprint(resp.json())
    elif resp.status_code == 201:
        print("deletado!")
        print(resp)
    else:
        print(resp)

# ------------------------ USER ------------------------
def cadastroUser():
    opc = None
    while opc != 1 and opc != 2 and opc != 0:

        menu1()
        opc = input("Informe uma opcao: ")

        if opc == "1":        #Fisica
            nome =  input("Informe nome: ")
            idade = input("Informe idade: ")
            cpf = input("Informe cpf: ")
            instEnsino = input("Informe Instuicao de ensino: ")

            data = {"nome": nome, "idade": idade, "cpf": cpf, "instEnsino": instEnsino}
            requests.post(f"{url}/fisica", json=data)
            break

        elif opc == "2":      #Juridica
            nome =  input("Informe nome: ")
            segmento = input("Informe segmento: ")
            cnpj = input("Informe cnpj: ")

            data = {"nome": nome, "segmento": segmento, "cnpj": cnpj}
            requests.post(f"{url}/juridica", json=data)
            break

        elif opc == "0":
            break

        else:
            print("Opção invalida!")
            input("Pressione ENTER para continuar!\n")

def exibirUser():
    opc = None
    while opc != 1 and opc != 2 and opc != 0:

        menu1()
        opc = input("Informe uma opcao: ")

        if opc == "1":           #Fisica
            cpf = input("Informe o cpf: ")
            resp = requests.get(f"{url}/fisica/" + cpf)
            jsonPrint(resp)
            break

        elif opc == "2":         #Juridica
            cnpj = input("Informe o cnpj: ")
            resp = requests.get(f"{url}/juridica/" + cnpj)
            jsonPrint(resp)
            break

        elif opc == "0":
            break

        else:
            print("Opção invalida!")
            input("Pressione ENTER para continuar!\n")

def alterarUser():
    opc = None
    while opc != 1 and opc != 2 and opc != 0:

        menu1()
        opc = input("Informe uma opcao: ")

        if opc == "1":           #Fisica
            cpf = input("Informe o cpf: ")
            resp = requests.get(f"{url}/fisica/" + cpf)
            jsonPrint(resp)

            menu2()
            opc1 = input("Informe uma opcao: ")

            if opc1 == "1":
                nome =  input("Informe nome: ")
                idade = input("Informe idade: ")
                instEnsino = input("Informe Instuicao de ensino: ")

                data = {"nome": nome, "idade": idade, "cpf": cpf, "instEnsino": instEnsino}
                requests.put(f"{url}/fisica/" + cpf, json=data)
            else:
                break

            input("Pressione ENTER para continuar!\n")

        elif opc == "2":         #Juridica
            cnpj = input("Informe o cnpj: ")
            resp = requests.get(f"{url}/juridica/" + cnpj)
            jsonPrint(resp)

            menu2()
            opc1 = input("Informe uma opcao: ")
            if opc1 == "1":
                nome =  input("Informe nome: ")
                segmento = input("Informe segmento: ")

                data = {"nome": nome, "segmento": segmento, "cnpj": cnpj}
                requests.put(f"{url}/juridica/" + cnpj, json=data)

            else:
                break

        elif opc == "0":
            break

        else:
            print("Opção invalida!")
            input("Pressione ENTER para continuar!\n")

def excluirUser():
    opc = None
    while opc != 1 and opc != 2 and opc != 0:

        menu1()
        opc = input("Informe uma opcao: ")

        if opc == "1":
            cpf = input("Informe o cpf: ")
            resp = requests.delete(f"{url}/fisica/" + cpf)
            jsonPrint(resp)

        elif opc == "2":
            cnpj = input("Informe o cnpj: ")
            resp = requests.delete(f"{url}/juridica/" + cnpj)
            jsonPrint(resp)

        elif opc == "0":
            break

        else:
            print("Opção invalida!")
            input("Pressione ENTER para continuar!\n")

# ------------------------ PROJETO ------------------------
def cadastroProj():
    cpf = None
    cnpj = None
    nome =  input("Informe nome: ")
    segmento = input("Informe o segmento: ")
    descricao = input("Informe a descrição: ")
    opc = None
    while opc != 1 and opc != 2 and opc != 0:

        menu1()
        opc = input("Informe uma opcao: ")

        if opc == "1":        #Fisica
            cpf = input("Informe cpf: ")
            cnpj = "-"
            break

        elif opc == "2":      #Juridica
            cnpj = input("Informe cnpj: ")
            cpf = "-"
            break

        elif opc == "0":
            break

        else:
            print("Opção invalida!")
            input("Pressione ENTER para continuar!\n")

    data = {"nome": nome, "segmento": segmento, "descricao": descricao, "cpf": cpf, "cnpj": cnpj}
    requests.post(f"{url}/projeto", json=data)

def exibirProj():
    nome = input("Nome do Projeto: ")
    resp = requests.get(f"{url}/projeto/" + nome)
    jsonPrint(resp)

def alterarProj():
    opc = None
    while opc != 1 and opc != 2 and opc != 0:
        nome = input("Informe o nome: ")
        resp = requests.get(f"{url}/projeto/" + nome)
        jsonPrint(resp)

        menu2()
        opc = input("Informe uma opcao: ")

        if opc == "1":
            newname =  input("Informe nome: ")
            segmento = input("Informe o segmento: ")
            descricao = input("Informe a descrição: ")

            data = {"nome": newname, "segmento": segmento, "descricao": descricao}
            requests.put(f"{url}/projeto/" + nome, json=data)
            break
        else:
            break

def excluirProj():
    nome = input("Informe o nome: ")
    resp = requests.delete(f"{url}/projeto/" + nome)
    jsonPrint(resp)

if __name__ == "__main__":
    main()


# adapated from munch 2.5.0
from collections.abc import Mapping

class Munch(dict):
    """A dictionary that provides attribute-style access.

    >>> b = Munch()
    >>> b.hello = 'world'
    >>> b.hello
    'world'
    >>> b['hello'] += "!"
    >>> b.hello
    'world!'
    >>> b.foo = Munch(lol=True)
    >>> b.foo.lol
    True
    >>> b.foo is b['foo']
    True

    A Munch is a subclass of dict; it supports all the methods a dict does...

    >>> sorted(b.keys())
    ['foo', 'hello']

    Including update()...

    >>> b.update({ 'ponies': 'are pretty!' }, hello=42)
    >>> print (repr(b))
    Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})

    As well as iteration...

    >>> sorted([ (k,b[k]) for k in b ])
    [('foo', Munch({'lol': True})), ('hello', 42), ('ponies', 'are pretty!')]

    And "splats".

    >>> "The {knights} who say {ni}!".format(**Munch(knights='lolcats', ni='can haz'))
    'The lolcats who say can haz!'

    See unmunchify/Munch.toDict, munchify/Munch.fromDict for notes about conversion.
    """

    def __init__(self, *args, **kwargs):  # pylint: disable=super-init-not-called
        self.update(*args, **kwargs)

    # only called if k not found in normal places
    def __getattr__(self, k):
        """Gets key if it exists, otherwise throws AttributeError.

        nb. __getattr__ is only called if key is not found in normal places.

        >>> b = Munch(bar='baz', lol={})
        >>> b.foo
        Traceback (most recent call last):
            ...
        AttributeError: foo

        >>> b.bar
        'baz'
        >>> getattr(b, 'bar')
        'baz'
        >>> b['bar']
        'baz'

        >>> b.lol is b['lol']
        True
        >>> b.lol is getattr(b, 'lol')
        True
        """
        try:
            # Throws exception if not in prototype chain
            return object.__getattribute__(self, k)
        except AttributeError:
            try:
                return self[k]
            except KeyError as exc:
                raise AttributeError(k) from exc

    def __setattr__(self, k, v):
        """Sets attribute k if it exists, otherwise sets key k. A KeyError
        raised by set-item (only likely if you subclass Munch) will
        propagate as an AttributeError instead.

        >>> b = Munch(foo='bar', this_is='useful when subclassing')
        >>> hasattr(b.values, '__call__')
        True
        >>> b.values = 'uh oh'
        >>> b.values
        'uh oh'
        >>> b['values']
        Traceback (most recent call last):
            ...
        KeyError: 'values'
        """
        try:
            # Throws exception if not in prototype chain
            object.__getattribute__(self, k)
        except AttributeError:
            try:
                self[k] = v
            except KeyError as exc:
                raise AttributeError(k) from exc
        else:
            object.__setattr__(self, k, v)

    def __delattr__(self, k):
        """Deletes attribute k if it exists, otherwise deletes key k. A KeyError
        raised by deleting the key--such as when the key is missing--will
        propagate as an AttributeError instead.

        >>> b = Munch(lol=42)
        >>> del b.lol
        >>> b.lol
        Traceback (most recent call last):
            ...
        AttributeError: lol
        """
        try:
            # Throws exception if not in prototype chain
            object.__getattribute__(self, k)
        except AttributeError:
            try:
                del self[k]
            except KeyError as exc:
                raise AttributeError(k) from exc
        else:
            object.__delattr__(self, k)

    def toDict(self):
        """Recursively converts a munch back into a dictionary.

        >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
        >>> sorted(b.toDict().items())
        [('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')]

        See unmunchify for more info.
        """
        return unmunchify(self)

    @property
    def __dict__(self):
        return self.toDict()

    def __repr__(self):
        """Invertible* string-form of a Munch.

        >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
        >>> print (repr(b))
        Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})
        >>> eval(repr(b))
        Munch({'ponies': 'are pretty!', 'foo': Munch({'lol': True}), 'hello': 42})

        >>> with_spaces = Munch({1: 2, 'a b': 9, 'c': Munch({'simple': 5})})
        >>> print (repr(with_spaces))
        Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})
        >>> eval(repr(with_spaces))
        Munch({'a b': 9, 1: 2, 'c': Munch({'simple': 5})})

        (*) Invertible so long as collection contents are each repr-invertible.
        """
        return f"{self.__class__.__name__}({dict.__repr__(self)})"

    def __dir__(self):
        return list(self.keys())

    def __getstate__(self):
        """Implement a serializable interface used for pickling.

        See https://docs.python.org/3.6/library/pickle.html.
        """
        return {k: v for k, v in self.items()}

    def __setstate__(self, state):
        """Implement a serializable interface used for pickling.

        See https://docs.python.org/3.6/library/pickle.html.
        """
        self.clear()
        self.update(state)

    __members__ = __dir__  # for python2.x compatibility

    @classmethod
    def fromDict(cls, d):
        """Recursively transforms a dictionary into a Munch via copy.

        >>> b = Munch.fromDict({'urmom': {'sez': {'what': 'what'}}})
        >>> b.urmom.sez.what
        'what'

        See munchify for more info.
        """
        return munchify(d, cls)

    def copy(self):
        return type(self).fromDict(self)

    def update(self, *args, **kwargs):
        """
        Override built-in method to call custom __setitem__ method that may
        be defined in subclasses.
        """
        for k, v in dict(*args, **kwargs).items():
            self[k] = v

    def get(self, k, d=None):
        """
        D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
        """
        if k not in self:
            return d
        return self[k]

    def setdefault(self, k, d=None):
        """
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
        """
        if k not in self:
            self[k] = d
        return self[k]

def munchify(x):
    """Recursively transforms a dictionary into a Munch via copy.

    >>> b = munchify({'urmom': {'sez': {'what': 'what'}}})
    >>> b.urmom.sez.what
    'what'

    munchify can handle intermediary dicts, lists and tuples (as well as
    their subclasses), but ymmv on custom datatypes.

    >>> b = munchify({ 'lol': ('cats', {'hah':'i win again'}),
    ...         'hello': [{'french':'salut', 'german':'hallo'}] })
    >>> b.hello[0].french
    'salut'
    >>> b.lol[1].hah
    'i win again'

    nb. As dicts are not hashable, they cannot be nested in sets/frozensets.
    """
    # Munchify x, using `seen` to track object cycles
    seen = dict()

    def munchify_cycles(obj):
        # If we've already begun munchifying obj, just return the already-created munchified obj
        try:
            return seen[id(obj)]
        except KeyError:
            pass

        # Otherwise, first partly munchify obj (but without descending into any lists or dicts) and save that
        seen[id(obj)] = partial = pre_munchify(obj)
        # Then finish munchifying lists and dicts inside obj (reusing munchified obj if cycles are encountered)
        return post_munchify(partial, obj)

    def pre_munchify(obj):
        # Here we return a skeleton of munchified obj, which is enough to save for later (in case
        # we need to break cycles) but it needs to filled out in post_munchify
        if isinstance(obj, Mapping):
            return Munch({})
        elif isinstance(obj, list):
            return type(obj)()
        elif isinstance(obj, tuple):
            type_factory = getattr(obj, "_make", type(obj))
            return type_factory(munchify_cycles(item) for item in obj)
        else:
            return obj

    def post_munchify(partial, obj):
        # Here we finish munchifying the parts of obj that were deferred by pre_munchify because they
        # might be involved in a cycle
        if isinstance(obj, Mapping):
            partial.update((k, munchify_cycles(obj[k])) for k in obj.keys())
        elif isinstance(obj, list):
            partial.extend(munchify_cycles(item) for item in obj)
        elif isinstance(obj, tuple):
            for item_partial, item in zip(partial, obj):
                post_munchify(item_partial, item)

        return partial

    return munchify_cycles(x)

def unmunchify(x):
    """Recursively converts a Munch into a dictionary.

    >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!')
    >>> sorted(unmunchify(b).items())
    [('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')]

    unmunchify will handle intermediary dicts, lists and tuples (as well as
    their subclasses), but ymmv on custom datatypes.

    >>> b = Munch(foo=['bar', Munch(lol=True)], hello=42,
    ...         ponies=('are pretty!', Munch(lies='are trouble!')))
    >>> sorted(unmunchify(b).items()) #doctest: +NORMALIZE_WHITESPACE
    [('foo', ['bar', {'lol': True}]), ('hello', 42), ('ponies', ('are pretty!', {'lies': 'are trouble!'}))]

    nb. As dicts are not hashable, they cannot be nested in sets/frozensets.
    """

    # Munchify x, using `seen` to track object cycles
    seen = dict()

    def unmunchify_cycles(obj):
        # If we've already begun unmunchifying obj, just return the already-created unmunchified obj
        try:
            return seen[id(obj)]
        except KeyError:
            pass

        # Otherwise, first partly unmunchify obj (but without descending into any lists or dicts) and save that
        seen[id(obj)] = partial = pre_unmunchify(obj)
        # Then finish unmunchifying lists and dicts inside obj (reusing unmunchified obj if cycles are encountered)
        return post_unmunchify(partial, obj)

    def pre_unmunchify(obj):
        # Here we return a skeleton of unmunchified obj, which is enough to save for later (in case
        # we need to break cycles) but it needs to filled out in post_unmunchify
        if isinstance(obj, Mapping):
            return dict()
        elif isinstance(obj, list):
            return type(obj)()
        elif isinstance(obj, tuple):
            type_factory = getattr(obj, "_make", type(obj))
            return type_factory(unmunchify_cycles(item) for item in obj)
        else:
            return obj

    def post_unmunchify(partial, obj):
        # Here we finish unmunchifying the parts of obj that were deferred by pre_unmunchify because they
        # might be involved in a cycle
        if isinstance(obj, Mapping):
            partial.update((k, unmunchify_cycles(obj[k])) for k in obj.keys())
        elif isinstance(obj, list):
            partial.extend(unmunchify_cycles(v) for v in obj)
        elif isinstance(obj, tuple):
            for value_partial, value in zip(partial, obj):
                post_unmunchify(value_partial, value)

        return partial

    return unmunchify_cycles(x)


# import libraries
import sys
import nltk
nltk.download(['punkt', 'wordnet', 'stopwords'])

import re
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer

from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline
import pickle

def load_data(database_filepath):
    """
    Loads table from database as a Pandas Dataframe
    and returns the following:
    X -- feature dataset containing the messages to be
         categorized
    y -- label dataset containing the 36 categories that each
         message is assigned to.
    category_names -- list containing category names

    Keyword arguments:
    database_filepath -- filepath (including file name)
                         of the database containing the
                         messages and categories
    """
    engine = create_engine('sqlite:///' + database_filepath)
    df = pd.read_sql_table('messages_and_categories', engine)
    X = df['message']
    y = df.drop(columns=['id', 'message', 'original', 'genre'])
    category_names = list(y.columns)

    return X, y, category_names

def tokenize(text):
    """
    Cleans, tokenizes, lemmatizes messages in preparation for
    classification algorithm

    1) finds and replaces urls with a placeholder
    2) finds and replaces non alphanumeric characters with a space
    3) removes stop words from tokenized messages
    4) strips leading and trailing spaces and lowcases lemmatized
       tokens

    Keyword arguments:
    text -- raw message that will be cleaned, tokenized
    """
    url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    detected_urls = re.findall(url_regex, text)
    for url in detected_urls:
        text = text.replace(url, "urlplaceholder")

    text = re.sub(r'\W+', ' ', text)

    tokens = word_tokenize(text)
    tokens = [t for t in tokens if t not in stopwords.words("english")]
    lemmatizer = WordNetLemmatizer()

    clean_tokens = []
    for tok in tokens:
        clean_tok = lemmatizer.lemmatize(tok).lower().strip()
        clean_tokens.append(clean_tok)

    return clean_tokens

def build_model():
    """
    Creates a pipeline and grid search for hyperparameter tuning
    returns pipeline with the specified parameter search space
    """
    pipeline = Pipeline([
    ('vect', CountVectorizer(tokenizer=tokenize)),
    ('tfidf', TfidfTransformer()),
    ('clf', MultiOutputClassifier(estimator=AdaBoostClassifier()))
    ])

    # specify parameters for grid search
    parameters = {
        'vect__ngram_range': ((1, 1), (1, 2),(2,2)),
        'tfidf__use_idf': (True, False),
        'tfidf__norm': ('l1', 'l2'),
        'clf__estimator__learning_rate': [0.1, 0.5],
        'clf__estimator__n_estimators': [50, 60, 70]
        }
    # create grid search object
    cv = GridSearchCV(pipeline, param_grid=parameters, verbose=216)
    return cv

def evaluate_model(model, X_test, Y_test, category_names):
    """
    Generates predicted values for test data based on
    fit model. Outputs a classification report for each category.

    Keyword arguments:
    model -- fit model based on training data
    X_test, Y_test -- message and target category values for testing
    category_names -- list of possible categories for each message
    """
    Y_pred = model.predict(X_test)
    for i, label in enumerate(category_names):
        print(category_names[i])
        print(classification_report(Y_test[label], Y_pred[:,i]))

def save_model(model, model_filepath):
    """
    Export the classifier to a pickle file

    Keyword arguments:
    model -- final model
    model_filepath -- location and name of saved pickle file
    """
    with open(model_filepath, 'wb') as model_filepath:
        pickle.dump(model, model_filepath)

def main():
    if len(sys.argv) == 3:
        database_filepath, model_filepath = sys.argv[1:]
        print('Loading data...\n    DATABASE: {}'.format(database_filepath))
        X, Y, category_names = load_data(database_filepath)
        X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = 42)

        print('Building model...')
        model = build_model()

        print('Training model...')
        model.fit(X_train, Y_train)
        print(model.best_score_)
        print(model.best_params_)

        print('Evaluating model...')
        evaluate_model(model, X_test, Y_test, category_names)

        print('Saving model...\n    MODEL: {}'.format(model_filepath))
        save_model(model, model_filepath)

        print('Trained model saved!')

    else:
        print('Please provide the filepath of the disaster messages database '\
              'as the first argument and the filepath of the pickle file to '\
              'save the model to as the second argument. \n\nExample: python '\
              'train_classifier.py ../data/DisasterResponse.db classifier.pkl')

if __name__ == '__main__':
    main()


import os
import json

import flask
from vrprot.alphafold_db_parser import AlphafoldDBParser

import vrprot

from . import map_uniprot
from . import settings as st
from . import util
from .classes import NodeTags as NT

def get_scales(uniprot_ids=[], mode=st.DEFAULT_MODE):
    return vrprot.overview_util.get_scale(uniprot_ids, mode)

def run_pipeline(proteins: list, parser: AlphafoldDBParser = st.parser, **kwargs):
    # create the output directory for the corresponding coloring mode if they do not exist
    # output_dir = os.path.join(st._MAPS_PATH, parser.processing)
    output_dir = os.path.join(st._MAPS_PATH)
    parser.update_output_dir(output_dir)

    # initialize the structures dictionary of the parser and check wether some processing files do already exist
    parser.init_structures_dict(proteins)
    for protein in proteins:
        parser.update_existence(protein)
    # run the batched process
    try:
        parser.fetch_pipeline(proteins, **kwargs)
        # batch([parser.fetch_pdb, parser.pdb_pipeline], proteins, parser.batch_size)
    except vrprot.exceptions.ChimeraXException as e:
        return {"error": "ChimeraX could not be found. Is it installed?"}
    result = get_scales(proteins, parser.processing)

    # update the existence of the processed files
    for protein in proteins:
        parser.update_existence(protein)

    return result

def fetch_from_request(request: flask.Request, parser: AlphafoldDBParser = st.parser):
    # get information from request
    pdb_id = request.args.get("id")
    if pdb_id is None:
        return {
            "error": "No PDB ID provided.",
            "example": f"{request.host}/vrprot/fetch?id=P69905",
        }

    # extract processing mode and alphafold version from request
    parser = util.parse_request(parser, request)
    # if mode is not part of the list of available modes, return an error
    if isinstance(parser, dict):
        return parser

    # create a list of proteins to be processed
    proteins = [pdb_id]
    return fetch(proteins, parser)

def fetch(proteins: list[str], parser: AlphafoldDBParser = st.parser):
    # run the batched process
    parser.not_fetched = set()
    parser.already_exists = set()
    result = run_pipeline(proteins, parser)
    # Try whether you can find an updated UniProt id
    second_try = {}
    if len(parser.not_fetched) > 0:
        try:
            mapped_ac = map_uniprot.main(
                parser.not_fetched,
                source_db=map_uniprot.Databases.uniprot_ac,
                target_db=map_uniprot.Databases.uniprot,
            )
            for re in mapped_ac["results"]:
                a, b = True, True
                while a and b:
                    a = re.get("from")
                    b = re.get("to")
                    b = b.get("uniProtKBCrossReferences")
                    for entry in b:
                        if entry.get("database") == "AlphaFoldDB":
                            b = entry.get("id")
                            second_try[b] = a
                            if a in parser.not_fetched:
                                parser.not_fetched.remove(a)
                            break
                    break
            result.update(run_pipeline(second_try, parser))
            tmp = parser.not_fetched.copy()
            for ac in tmp:
                if ac in second_try:
                    parser.not_fetched.remove(ac)
                    parser.not_fetched.add(second_try[ac])
        except Exception as e:
            print(e)
    return {
        "not_fetched": list(parser.not_fetched),
        "already_exists": list(parser.already_processed),
        "results": result,
        "alternative_ids": {v: k for k, v in second_try.items()},
    }

def for_project(
    project: str, request: flask.request, parser: AlphafoldDBParser = st.parser
):
    # get information from request

    if project is None:
        return {"error": "No project provided."}

    # extract processing mode and alphafold version from request
    parser = util.parse_request(parser, request)

    # if mode is not part of the list of available modes, return an error
    if isinstance(parser, dict):
        return parser

    # extract node data from the projects nodes.json file
    nodes_files = os.path.join(st._PROJECTS_PATH, project, "nodes.json")
    if not os.path.isfile(nodes_files):
        return {"error": "Project does not exist."}

    with open(nodes_files, "r") as f:
        nodes = json.load(f)["nodes"]

    # extract the uniprot ids from the nodes
    proteins = [",".join(node[NT.uniprot]) for node in nodes if node.get(NT.uniprot)]

    # run the batched process
    result = run_pipeline(proteins, parser, on_demand=False)
    return {"not_fetched": list(parser.not_fetched), "results": result}

def fetch_list_from_request(
    request: flask.Request, parser: AlphafoldDBParser = st.parser
):
    # get information from request
    pdb_ids = request.args.get("ids")
    if pdb_ids is None:
        return {
            "error": "No PDB IDs provided.",
            "example": f"http://{request.host}/vrprot/list?ids=P02655,At1g58602",
        }

    # extract processing mode and alphafold version from request
    parser = util.parse_request(parser, request)
    # if mode is not part of the list of available modes, return an error
    if isinstance(parser, dict):
        return parser

    # create a list of proteins to be processed
    proteins = [id for id in pdb_ids.split(",")]

    return fetch_list(proteins, parser)

def fetch_list(proteins: list[str], parser: AlphafoldDBParser = st.parser):
    # run the batched process
    result = run_pipeline(proteins, parser, on_demand=False)

    return {"not_fetched": list(parser.not_fetched), "results": result}


from __future__ import annotations

from typing import TYPE_CHECKING

from avilla.core.context import Context
from avilla.core.event import RelationshipCreated, RelationshipDestroyed
from avilla.core.selector import Selector
from avilla.core.trait.context import EventParserRecorder
from cai.client.events.group import (
    GroupLuckyCharacterChangedEvent,
    GroupLuckyCharacterClosedEvent,
    GroupLuckyCharacterInitEvent,
    GroupLuckyCharacterNewEvent,
    GroupLuckyCharacterOpenedEvent,
    GroupMemberJoinedEvent,
    GroupMemberLeaveEvent,
    GroupMemberMutedEvent,
    GroupMemberPermissionChangeEvent,
    GroupMemberSpecialTitleChangedEvent,
    GroupMemberUnMutedEvent,
    GroupNameChangedEvent,
    TransferGroupEvent,
)

if TYPE_CHECKING:
    from ..account import CAIAccount
    from ..protocol import CAIProtocol

event = EventParserRecorder["CAIProtocol", "CAIAccount"]

@event("GroupMemberJoinedEvent")
async def group_member_joined_event(
    protocol: CAIProtocol, account: CAIAccount, raw: GroupMemberJoinedEvent
):
    group = Selector().land(protocol.land.name).group(str(raw.group_id))
    member = group.member(str(raw.uin))
    context = Context(
        account=account,
        client=member,
        endpoint=group,
        scene=group,
        selft=group.member(account.id),
    )
    return RelationshipCreated(context, member, group, context.self), context

@event("GroupMemberLeaveEvent")
async def group_member_leave_event(
    protocol: CAIProtocol, account: CAIAccount, raw: GroupMemberLeaveEvent
):
    group = Selector().land(protocol.land.name).group(str(raw.group_id))
    member = group.member(str(raw.uin))
    context = Context(
        account=account,
        client=member,
        endpoint=group,
        scene=group,
        selft=group.member(account.id),
    )
    res = RelationshipDestroyed(context, member, group, context.self)
    if raw.operator and raw.operator != raw.uin:
        res.mediums.append(group.member(str(raw.operator)))
    return res, context


"""
    최적화 비중을 계산해주는 모듈

    @author: Younghyun Kim
    Created on 2021.10.05
"""
import numpy as np
import pandas as pd
import cvxpy as cp
import torch
from cvxpylayers.torch import CvxpyLayer

class ClassicOptimizer:
    """
        Classic Optimizer
    """
    def __init__(self, m=100,
                buying_fee=0.01, selling_fee=0.01,
                min_cash_rate=0.01):
        """
            Initialization

            Args:
                m: big number
        """
        self.m = m
        self.buying_fee = buying_fee
        self.selling_fee = selling_fee
        self.min_cash_rate = min_cash_rate

    def max_sr(self, returns, nonneg=True, adjust=True):
        """
            Maximize Sharpe Ratio

            Args:
                returns: pd.DataFrame or np.array
            Return:
                weights: np.array(N)
        """
        if isinstance(returns, pd.DataFrame):
            returns = returns.values

        creturns = returns * self.m
        cov = np.cov(creturns.transpose())
        cov = np.nan_to_num(cov)

        mu = creturns.mean(0).reshape(-1)
        mu_min = abs(mu.min())
        if mu[mu > 0].shape[0] == 0:
            mu += mu_min
        mu = np.nan_to_num(mu)

        weights = cp.Variable(returns.shape[1])
        cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]), symmetric=True)

        objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))

        constraints = [mu.T @ weights >= 1]
        if nonneg:
            constraints.append(0 <= weights)

        prob = cp.Problem(objective, constraints)
        assert prob.is_dpp()

        cov = torch.FloatTensor(cov.astype(float))

        cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
                                variables=[weights])

        weights, = cvxpylayer(cov)

        if adjust:
            weights = self.adjust_weights(weights)

        return weights.numpy()

    def min_var(self, returns):
        """
            Minimum Variance Portfolio
            Args:
                returns: pd.DataFrame or np.array
            Return:
                weights: np.array(N)
        """
        if isinstance(returns, pd.DataFrame):
            returns = returns.values

        creturns = returns * self.m
        cov = np.cov(creturns.transpose())
        cov = np.nan_to_num(cov)

        weights = cp.Variable(returns.shape[1])
        cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]),
                            symmetric=True)

        objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))

        constraints = [cp.sum(weights) == 1, 0 <= weights]

        prob = cp.Problem(objective, constraints)
        assert prob.is_dpp()

        cov = torch.FloatTensor(cov.astype(float))

        cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
                                variables=[weights])

        weights, = cvxpylayer(cov)

        return weights.numpy()

    def max_div(self, returns, nonneg=True, adjust=True):
        """
            Maximum Diversification Portfolio

            Args:
                returns: pd.DataFrame or np.array
            Return:
                weights: np.array(N)
        """
        if isinstance(returns, pd.DataFrame):
            returns = returns.values

        creturns = returns * self.m
        cov = np.cov(creturns.transpose())
        cov = np.nan_to_num(cov)

        sig = creturns.std(0).reshape(-1)
        sig = np.nan_to_num(sig)

        weights = cp.Variable(returns.shape[1])
        cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]),
                                symmetric=True)

        objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))

        constraints = [sig.T @ weights >= 1]
        if nonneg:
            constraints.append(0 <= weights)

        prob = cp.Problem(objective, constraints)
        assert prob.is_dpp()

        cov = torch.FloatTensor(cov.astype(float))

        cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
                                variables=[weights])

        weights, = cvxpylayer(cov)

        if adjust:
            weights = self.adjust_weights(weights)

        return weights.numpy()

    def mv_mean(self, returns):
        """
            Mean-Variance Portfolio with min ret based on mean ret
            Args:
                returns: pd.DataFrame or np.array
            Return:
                weights: np.array(N)
        """
        if isinstance(returns, pd.DataFrame):
            returns = returns.values

        creturns = returns * self.m
        cov = np.cov(creturns.transpose())
        cov = np.nan_to_num(cov)

        weights = cp.Variable(returns.shape[1])
        cov_cp = cp.Parameter((cov.shape[1], cov.shape[0]),
                            symmetric=True)

        mu = creturns.mean(0).reshape(-1)
        mu_min = abs(mu.min())
        if mu[mu > 0].shape[0] == 0:
            mu += mu_min
        mu = np.nan_to_num(mu)
        mret = mu.mean().item()

        objective = cp.Minimize(cp.sum_squares(cov_cp @ weights))

        constraints = [cp.sum(weights) == 1,
                        mu.T @ weights >= mret,
                        0 <= weights]

        prob = cp.Problem(objective, constraints)
        assert prob.is_dpp()

        cov = torch.FloatTensor(cov.astype(float))

        cvxpylayer = CvxpyLayer(prob, parameters=[cov_cp],
                                variables=[weights])

        weights, = cvxpylayer(cov)

        return weights.numpy()

    def pm_port(self, returns, topk=5, return_type='pct'):
        """
            Price Momentum Equal Weight Portfolio with TopK
            Args:
                returns: pd.DataFrame or np.array
                topk: top K
                return_type: return type(log or pct)
            Return:
                weights: np.array(N)
        """
        if isinstance(returns, pd.DataFrame):
            returns = returns.values

        if return_type == 'pct':
            returns = np.log(returns + 1.)

        crets = returns.sum(0)
        crets = np.nan_to_num(crets)

        crank = crets.argsort()
        weights = np.zeros(returns.shape[1])
        weights[crank[-topk:]] = 1. / topk

        return weights

    def lowvol_port(self, returns, topk=5):
        """
            Lowvol Equal Weight Portfolio with TopK
            Args:
                returns: pd.DataFrame or np.array
                topk: top K
            Return:
                weights: np.array(N)
        """
        if isinstance(returns, pd.DataFrame):
            returns = returns.values

        sig = returns.std(0)
        sig = np.nan_to_num(sig)

        srank = sig.argsort()
        weights = np.zeros(returns.shape[1])
        weights[srank[:topk]] = 1. / topk

        return weights

    def ew_port(self, n):
        """
            Equal Weight Portfolio with n assets
            Args:
                n: asset num
            Return:
                weights: np.array(n)
        """
        weights = torch.ones(n) / n

        return weights

    def solve_amount(self, asset_prices, asset_embs, optimal_emb, wealth):
        """
            Solving method for trading amounts

            Args:
                asset_prices: np.array 수량 계산에 필요한 자산 별 가격(1 X N)
                asset_embs = np.array 자산 별 임베딩(N X M)
                optimal_emb: 최적 포트폴리오 임베딩(1 X M)
                wealth: 총 투자금

            Return:
                buying_amount: 종목 별 수량
                prob_value: 최적과 최종 포트폴리오 거리(L2)
        """
        wealth =\
            wealth * (1. - max(self.buying_fee, self.selling_fee))  # 비용 고려
        wealth = wealth * (1. - self.min_cash_rate)  # 최소 보유 현금 고려
        asset_embs_v = asset_embs.transpose() * asset_prices / wealth
        asset_prices = asset_prices.reshape(-1)

        buying_amount = cp.Variable(asset_prices.shape[0])
        optimal_emb = optimal_emb.reshape(-1)

        objective = cp.Minimize(self.m *
                                cp.sum_squares((asset_embs_v @ buying_amount)
                                                - optimal_emb))
        constraints = [buying_amount >= 0,
                    asset_prices.T @ buying_amount == wealth]

        prob = cp.Problem(objective, constraints)
        prob.solve()

        buying_amount = np.round(buying_amount.value, 0)

        return buying_amount, prob.value

    def get_replicated_buying_amounts(self, closes, asset_embs, weights,
                                    insts=['A069500', 'A229200',
                                            'A114800', 'A251340'],
                                    topk=10, wealth=50000000):
        """
            closes: pd.Series 종목 별 종가(stock_num)
            asset_embs: torch.tensor 종목 별 임베딩(1, stock_num, emb_dim)
            weights: torch.tensor 종목 별 투자비중(1, stock_num)
            insts: list 복제에 활용될 시장 ETF(default: K200, KQ150)
            topk: 복제하기 위한 상위 종목 수

            * closes, asset_embs, weights는 종목 별 순서가 일치해야함

            Return:
                amounts: pd.DataFrame 매수수량
                aweights: pd.DataFrame 매수수량을 바탕으로 한 투자비중
                value_est: closes를 바탕으로 계산한 총금액
                prob_value: 임베딩 거리
        """
        ins = []
        for inst in insts:
            ind = np.argwhere(closes.index == inst).item()
            ins.append(ind)

        ranks = weights.argsort(descending=True)
        ranks = ranks.cpu().numpy().reshape(-1)
        sel = np.unique(np.concatenate((ranks[:topk], ins), axis=-1))

        optimal_emb = self.calc_optimal_emb(asset_embs, weights)

        embs = asset_embs[0, sel].cpu().numpy()
        optimal_emb = optimal_emb.view(-1, 1).cpu().numpy()

        amounts, prob_value = self.solve_amount(closes.iloc[sel].values,
                                        embs, optimal_emb, wealth)

        amounts = pd.DataFrame(amounts.reshape(-1, 1),
                            index=closes.index[sel],
                            columns=['amounts'])
        amounts = amounts[amounts['amounts'] > 0]

        closes = pd.DataFrame(closes.values, index=closes.index, columns=amounts.columns)

        value_est = (amounts.values.ravel() * closes.loc[amounts.index].values.ravel()).sum()

        aweights = (amounts * closes.loc[amounts.index]) / value_est

        return amounts, aweights, value_est, prob_value

    def calc_optimal_emb(self, asset_embs, weights):
        """
            calculate optimal embedding
            Args:
                asset_embs: torch.tensor
                    (batch_size, stock_num, emb_dim)
                weights: torch.tensor
                    (batch_size, stock_num)
        """
        optimal_emb = torch.matmul(weights, asset_embs)

        return optimal_emb

    def adjust_weights(self, weights):
        """
            비중 조정
                * nonneg일때,
                    weights /= weights.sum()
                * weights[weights > 0].sum() > 0 일때,
                    weights /= weights[weights > 0].sum()
                * weights[weights > 0].sum() < 0이고,
                weights[weights < 0] != 0일때,
                    weights /= -weights[weights < 0].sum()
        """
        if (weights != 0).sum() > 0:
            weights = weights / abs(weights).max()

        wpos_sum = weights[weights > 0].sum()
        wneg_sum = -weights[weights < 0].sum()

        if weights.sum() != 0:
            weights /= max(wpos_sum, wneg_sum)

        return weights


from tkinter import Button, Checkbutton, Entry, IntVar, Label, Tk
from tkinter import messagebox
from solve import Solver
q = Solver()
def show_plot():
    if accur_entry.get().isdigit():
        n = int(accur_entry.get())
    else:
        messagebox.showerror(message="put integer")
        return
    potential = pot.get()
    if wave.get().isdigit():
        number = int(wave.get())
    else:
        messagebox.showerror(message="put integer")
        return
    if spread.get().isdigit():
        s = int(spread.get())
    else:
        messagebox.showerror(message="put integer")
        return
    if n != q.n or potential != q.pot or s != q.range:
        print(accur_entry.get(), q.n)
        print(potential, q.pot)
        print(s, q.range)
        q._init(n, potential, s)
    if pp.get() == 1:
        q.plopoten()
        q.show()
    if pi.get() == 1:
        if ow.get() == 1:
            for i in range(number):
                q.plot(False, i)
        else:
            q.plot(False, number)
    else:
        if ow.get() == 1:
            for i in range(number):
                q.plot(True, i)
        else:
            q.plot(True, number)
    q.show()

window = Tk()
window.title("stationary state grapher")
ow = IntVar()
pi = IntVar()
pp = IntVar()
window.config(padx=20, pady=20)
accur = Label(text="give number of grid points")
accur_entry = Entry()
accur_entry.insert(0, "2000")
pot_lab = Label(text="give potential")
wave_lab = Label(text="wave number ")
wave = Entry()
spread_lab = Label(text="give the bounded range ")
spread = Entry()
spread.insert(0, "100")
prob = Checkbutton(text="see probability ", variable=pi, onvalue=1, offvalue=0)
only_wave = Checkbutton(text="see all the waves upto that number", variable=ow, onvalue=1, offvalue=0)
plot = Button(text="show the plot", width=32, command=show_plot)
pot = Entry()
pot.focus()
potplot = Checkbutton(text="plot potential function ", variable=pp, onvalue=1, offvalue=0)
# grid
accur.grid(row=0, column=0)
accur_entry.grid(row=0, column=1)
pot_lab.grid(row=1, column=0)
pot.grid(row=1, column=1)
wave_lab.grid(row=3, column=0)
wave.grid(row=3, column=1)
spread_lab.grid(row=2, column=0)
spread.grid(row=2, column=1)
prob.grid(row=4, column=0, columnspan=2)
only_wave.grid(row=5, column=0, columnspan=2)
potplot.grid(row=6, column=0, columnspan=2)
plot.grid(row=7, column=0, columnspan=2)
window.mainloop()


#!/usr/bin/env python3

import rclpy
from rclpy.node import Node
import speech_recognition as sr
from custom_if.srv import SendSentence
from functools import partial
import time

### Node class
class SpeechToText(Node):
	def __init__(self):
		super().__init__("stt_node")
		self.get_logger().info("STT node is up.")
		self.stt = sr.Recognizer()

		# Methods
		self.listen_to_user()

	## Listen and write
	def listen_to_user(self):

		self.call_nlu("Welcome")

		# Inner loop
		while True:
			with sr.Microphone() as source:
				self.stt.adjust_for_ambient_noise(source, duration=0.2)
				audio = self.stt.listen(source)

			try:
				sentence = "{0}".format(self.stt.recognize_google(audio, language="it-IT"))
				if 'Marvin' in sentence.split(" "):
					self.call_nlu(sentence)

			except sr.UnknownValueError:
				self.get_logger().warn("Waiting for a command.")

			except sr.RequestError as e:
				self.get_logger().error("STT Error; {0}".format(e))

	# Definition of the client request to the TTS
	def call_nlu(self, sentence):
		client = self.create_client(SendSentence, "send_command")
		while not client.wait_for_service(1.0):
			self.get_logger().warn("Waiting for Server...")

		request = SendSentence.Request()
		request.sentence = sentence
		future = client.call_async(request)
		future.add_done_callback(partial(self.callback_call_nlu, sentence=sentence))

	def callback_call_nlu(self, future, sentence):
		try:
			response = future.result()
			self.get_logger().info(f"Request solved: {response}")

		except Exception as e:
			self.get_logger().error("Request failed.")

def main(args=None):
	rclpy.init(args=args)
	node = SpeechToText()
	rclpy.spin(node)
	rclpy.shutdown()

if __name__ == "__main__":
	main()


from lib2to3.pgen2 import token
from brownie import Test, accounts, interface
from eth_utils import to_wei
from web3 import Web3

def main():
    deploy()

def deploy():
    amount_in = Web3.toWei(1000000, "ether")

    # DAI address
    DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F"

    # DAI whale
    DAI_WHALE = "0xcffad3200574698b78f32232aa9d63eabd290703"

    # WETH
    WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"

    # WETH whale
    WETH_WHALE = "0xeD1840223484483C0cb050E6fC344d1eBF0778a9"

    print("===Transferring gas cost covers===")
    # covering the transaction cost
    # accounts[0].transfer(DAI_WHALE, "1 ether")
    # accounts[0].transfer(WETH_WHALE, "1 ether")

    tokenA = interface.IERC20(DAI)
    tokenB = interface.IERC20(WETH)
    print("===Transferring the tokenA and tokenB amounts from whales to account[0]===")
    tokenA.transfer(accounts[0], Web3.toWei(2400, "ether"), {"from": DAI_WHALE})
    tokenB.transfer(accounts[0], Web3.toWei(1, "ether"), {"from": WETH_WHALE})

    contract = Test.deploy({"from": accounts[0]})

    tokenA.approve(contract.address, Web3.toWei(2400, "ether"), {"from": accounts[0]})
    tokenB.approve(contract.address, Web3.toWei(1, "ether"), {"from": accounts[0]})

    print("Adding liquidity...")
    tx = contract.addLiquidity(
        DAI,
        WETH,
        Web3.toWei(2400, "ether"),
        Web3.toWei(1, "ether"),
        {"from": accounts[0]},
    )
    tx.wait(1)

    print("Added Liquidity...")

    for i in tx.events["Log"]:
        print(i)

    print("=== Removing Liquidity ===")

    tx = contract.removeLiquidity(DAI, WETH, {"from": accounts[0]})

    tx.wait(1)

    for i in tx.events["Log"]:
        print(i)


import sys
from aspartix_parser import Apx_parser
import itertools

def conflict_free(arguments, attacks):
    confl_free_sets = []
    combs = []

    for i in range(1, len(arguments) + 1):
        els = [list(x) for x in itertools.combinations(arguments, i)]
        combs.extend(els)
    combs_sorted = [list(combs_sorted) for combs_sorted in combs][::-1]
    # print("Combs: ", combs_sorted)
    for i in combs_sorted:
        att_count = 0
        # print(i)
        for att in attacks:
            # print(att)
            if set([str(att)[2], str(att)[4]]).issubset(set(i)) or any([i in item for item in
                                                                        confl_free_sets]):  # any(x in item for item in confl_free_sets for x in i):#(True if list(filter(lambda x:i in x,confl_free_sets)) else False):#(any([set(i).issubset(set(item)) in item for item in confl_free_sets])):
                break
            else:
                att_count += 1
            #    print(att_count)
            # if ((str(att)[2] and str(att)[4]) not in i) and (not any([i in item for item in confl_free_sets])):
            #     att_count += 1
            #     print(att_count)
            if att_count == len(attacks):
                confl_free_sets.append(i)
    return confl_free_sets

def admissible(confl_free, attacks):
    admissible_sets = []

    for ext in confl_free:
        count = 0
        # print(ext)
        for att in attacks:
            if str(att)[4] not in ext:
                count += 1
                # print(att, count)
            else:
                # print(att, count)
                for atr in attacks:
                    # print(att, atr, count, str(atr)[4], str(att)[2])
                    if (str(att)[2] == str(atr)[4]) and (str(atr)[2] in ext):
                        count += 1
                        # print(count)
        if count == len(attacks):
            admissible_sets.append(ext)

    return admissible_sets

# def complete(admissible_sets, attacks):
#     complete_ext = []
#     for adm in admissible_sets:
#         for att in attacks:
#             if (str(att)[2] in adm) and
#
#     return complete_ext

def preferred(admissible_sets):
    preferred_exts = []

    for adm in admissible_sets:
        count = 0
        # print(adm, count)
        for adm_t in admissible_sets:
            if set(adm).issubset(set(adm_t)) and adm_t != adm:
                pass
            else:
                count += 1
                # print(adm, adm_t, count)
            if count == len(admissible_sets):
                preferred_exts.append(adm)

    return preferred_exts

def stable_extensions(stable_exts):
    pass

if __name__ == '__main__':
    filepath = 'example.apx'
    if sys.argv[1:]:
        filepath = sys.argv[1]

    arguments = []
    attacks = []
    parser = Apx_parser(filepath)
    arguments, attacks = parser.read_file()
    parser.close()
    print(arguments, attacks)
    print("There are ", len(arguments), " arguments and ", len(attacks), " attacks.")
    # print(str(attacks[0])[4])
    confl_free = conflict_free(arguments, attacks)
    print("Conflict free extensions: ", "[]", sorted(confl_free))
    admissible_sets = admissible(confl_free, attacks)
    print("Admissible extensions: ", "[]", sorted(admissible_sets))
    # complete_ext = complete(admissible_sets, attacks)
    preferred_exts = preferred(admissible_sets)
    print("Preferred extensions: ", sorted(preferred_exts))
    stable_exts = stable_extensions(preferred_exts)
    print("Stable extensions: ", stable_exts)


from typing import Dict, Tuple
from copy import deepcopy
import torch
from config import tqc_config
from modules import Actor, TruncatedQuantileEnsembledCritic

class TQC:
    def __init__(self,
                 cfg: tqc_config,
                 actor: Actor,
                 critic: TruncatedQuantileEnsembledCritic) -> None:
        self.cfg = cfg
        self.device = cfg.device
        self.tau = cfg.tau
        self.discount = cfg.discount
        self.batch_size = cfg.batch_size

        self.target_entropy = -float(actor.action_dim)

        self.log_alpha = torch.tensor([0.0], dtype=torch.float32, device=self.device, requires_grad=True)

        self.alpha_optimizer = torch.optim.AdamW([self.log_alpha], lr=cfg.alpha_lr)
        self.alpha = self.log_alpha.exp().detach()

        self.actor = actor.to(self.device)
        self.actor_optim = torch.optim.AdamW(self.actor.parameters(), lr=cfg.actor_lr)

        self.critic = critic.to(self.device)
        self.critic_target = deepcopy(critic).to(self.device)
        self.critic_optim = torch.optim.AdamW(self.critic.parameters(), lr=cfg.critic_lr)

        self.quantiles_total = critic.num_critics * critic.num_quantiles
        self.quantiles2drop = cfg.quantiles_to_drop_per_critic * cfg.num_critics
        self.top = self.quantiles_total - self.quantiles2drop

        huber_tau = torch.arange(self.cfg.num_quantiles, device=self.device).float() / self.top + 1 / (2 * self.top)
        self.huber_tau = huber_tau[None, None, :, None]

        self.total_iterations = 0

    def train(self,
              states: torch.Tensor,
              actions: torch.Tensor,
              rewards: torch.Tensor,
              next_states: torch.Tensor,
              dones: torch.Tensor) -> Dict[str, float]:
        self.total_iterations += 1

        # critic step
        critic_loss = self.critic_loss(states, actions, rewards, next_states, dones)

        self.critic_optim.zero_grad()
        critic_loss.backward()
        self.critic_optim.step()

        # actor step
        actor_loss, batch_entropy, qz_values = self.actor_loss(states)

        self.actor_optim.zero_grad()
        actor_loss.backward()
        self.actor_optim.step()

        # alpha step
        alpha_loss = self.alpha_loss(states)

        self.alpha_optimizer.zero_grad()
        alpha_loss.backward()
        self.alpha_optimizer.step()

        self.alpha = self.log_alpha.exp().detach()

        self.soft_critic_update()

        return {
            "critic_loss": critic_loss.item(),
            "actor_loss": actor_loss.item(),
            "actor_batch_entropy": batch_entropy,
            "qz_values": qz_values,
            "alpha": self.alpha.item(),
            "alpha_loss": alpha_loss.item()
        }

    def actor_loss(self, states: torch.Tensor) -> Tuple[torch.Tensor, float, float]:
        actions, log_prob = self.actor(states, need_log_prob=True)

        qz_values = self.critic(states, actions).mean(dim=2).mean(dim=1, keepdim=True)

        loss = self.alpha * log_prob - qz_values
        batch_entropy = -log_prob.mean().item()

        return loss.mean(), batch_entropy, qz_values.mean().item()

    def critic_loss(self,
                    states: torch.Tensor,
                    actions: torch.Tensor,
                    rewards: torch.Tensor,
                    next_states: torch.Tensor,
                    dones: torch.Tensor) -> torch.Tensor:
        with torch.no_grad():
            next_actions, next_log_prob = self.actor(next_states, need_log_prob=True)

            next_z = self.critic_target(next_states, next_actions)

            sorted_next_z = torch.sort(next_z.reshape(self.batch_size, -1)).values
            sorted_next_z_top = sorted_next_z[:, :self.top]
            sorted_next_z_top = sorted_next_z_top - self.alpha * next_log_prob.unsqueeze(-1)

            quantiles_target = rewards + self.discount * (1.0 - dones) * sorted_next_z_top

        current_z = self.critic(states, actions)
        loss = self.quantile_huber_loss(current_z, quantiles_target)

        return loss

    def quantile_huber_loss(self, quantiles: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        pairwise_diff = target[:, None, None, :] - quantiles[:, :, :, None]
        abs_val = pairwise_diff.abs()

        huber_loss = torch.where(abs_val > 1.0,
                                 abs_val - 0.5,
                                 pairwise_diff.pow(2) / 2)

        loss = torch.abs(self.huber_tau - (pairwise_diff < 0).float()) * huber_loss
        return loss.mean()

    def alpha_loss(self, state: torch.Tensor) -> torch.Tensor:
        with torch.no_grad():
            action, log_prob = self.actor(state, need_log_prob=True)

        loss = -self.log_alpha * (log_prob + self.target_entropy)
        return loss.mean()

    def soft_critic_update(self):
        for param, tgt_param in zip(self.critic.parameters(), self.critic_target.parameters()):
            tgt_param.data.copy_(self.tau * param.data + (1 - self.tau) * tgt_param.data)


from tkinter import *

class JogoDaForca:
    def __init__(self, master):
        self.master = master
        master.title("Jogo da Forca")
        master.geometry("300x300")

        # palavra secreta
        self.palavra_secreta = "banana"

        # letras adivinhadas
        self.letras_adivinhadas = []

        # número de tentativas
        self.tentativas_restantes = 6

        # widgets
        self.lbl_palavra = Label(master, text=self.esconder_palavra())
        self.lbl_palavra.pack()

        self.lbl_letras_adivinhadas = Label(master, text=self.formatar_letras_adivinhadas())
        self.lbl_letras_adivinhadas.pack()

        self.lbl_tentativas = Label(master, text="Tentativas restantes: {}".format(self.tentativas_restantes))
        self.lbl_tentativas.pack()

        self.lbl_mensagem = Label(master, text="")
        self.lbl_mensagem.pack()

        self.ent_palpite = Entry(master)
        self.ent_palpite.pack()

        self.btn_adivinhar = Button(master, text="Adivinhar", command=self.adivinhar_letra)
        self.btn_adivinhar.pack()

    def esconder_palavra(self):
        palavra_escondida = ""

        for letra in self.palavra_secreta:
            if letra in self.letras_adivinhadas:
                palavra_escondida += letra
            else:
                palavra_escondida += "_"

        return palavra_escondida

    def formatar_letras_adivinhadas(self):
        return "Letras adivinhadas: {}".format(", ".join(self.letras_adivinhadas))

    def adivinhar_letra(self):
        palpite = self.ent_palpite.get()

        if len(palpite) != 1:
            self.lbl_mensagem.configure(text="Por favor, digite uma letra de cada vez.")
            return

        if palpite in self.letras_adivinhadas:
            self.lbl_mensagem.configure(text="Você já adivinhou essa letra.")
            return

        self.letras_adivinhadas.append(palpite)

        if palpite not in self.palavra_secreta:
            self.tentativas_restantes -= 1
            self.lbl_tentativas.configure(text="Tentativas restantes: {}".format(self.tentativas_restantes))

            if self.tentativas_restantes == 0:
                self.lbl_mensagem.configure(text="Você perdeu!")
                self.btn_adivinhar.configure(state=DISABLED)
                return

        if self.esconder_palavra() == self.palavra_secreta:
            self.lbl_mensagem.configure(text="Você ganhou!")
            self.btn_adivinhar.configure(state=DISABLED)
            return

        self.lbl_palavra.configure(text=self.esconder_palavra())
        self.lbl_letras_adivinhadas.configure(text=self.formatar_letras_adivinhadas())
        self.ent_palpite.delete(0, END)

    def iniciar_jogo(self):
        self.master.mainloop()

root = Tk()
jogo_da_forca = JogoDaForca(root)
jogo_da_forca.iniciar_jogo()