import random

from settings import *
import pygame
import numpy as np
from block import Block
from trap import Trap

# -----------------------------------对象定义---------------------------------
class myMap:
    def __init__(self, screen, all_sprites):
        super().__init__()
        # modify maz

        self.mazeMatrix = self.MazeGenerator()
        self.mazerow = np.shape(self.mazeMatrix)[0]
        self.mazecol = np.shape(self.mazeMatrix)[1]

        self.MoveArea = [[1 for i in range(0, GAME_SCREEN_WIDTH)] for j in range(0, GAME_SCREEN_HEIGHT)]

        self.Room_unit_Row = 5
        self.Room_unit_Col = 5

        self.RoomRow = self.mazerow // self.Room_unit_Row + 2
        self.RoomCol = self.mazecol // self.Room_unit_Col + 2
        # define para
        self.screen = screen

        self.xl = GAME_SCREEN_WIDTH // self.mazecol
        self.yl = GAME_SCREEN_HEIGHT // self.mazerow

        self.roomxl = GAME_SCREEN_WIDTH // self.RoomCol
        self.roomyl = GAME_SCREEN_HEIGHT // self.RoomRow

        self.cell_row = range(0, GAME_SCREEN_HEIGHT, self.yl)
        self.cell_col = range(0, GAME_SCREEN_WIDTH, self.xl)

        self.all_sprites = all_sprites
        self.block = Block(self.all_sprites)
        self.trap = Trap(self.all_sprites)

    # def drawWall(self):
    #     self.block.create_block_tile( self.mazeMatrix)
    #     self.block.block_sprites.draw(self.screen)
    #     for i in range(0, self.mazerow):
    #         for j in range(0, self.mazecol):
    #             if self.mazeMatrix[i][j] == 0:
    #                 for k in range(i * self.yl, (i + 1) * self.yl):
    #                     for p in range(j * self.xl, (j + 1) * self.xl):
    #                         self.MoveArea[k][p] = 0
    def drawRoom(self, x, y):
        room = self.toRoom(self.mazeMatrix, y, x)
        self.pr = room
        self.block.create_block_tile(room, self.roomyl, self.roomxl)
        self.block.block_sprites.draw(self.screen)
        self.trap.create_trap_tile(room, self.roomyl, self.roomxl)
        self.trap.trap_sprites.draw(self.screen)
        for i in range(0, self.RoomRow):
            for j in range(0, self.RoomCol):
                if room[i][j] == 0:
                    for k in range(max(i * self.roomyl - 32, 0),
                                   min((i + 1) * self.roomyl + 32, GAME_SCREEN_HEIGHT - 1)):
                        for p in range(max(j * self.roomxl - 32, 0), min((j + 1) * self.roomxl + 32,
                                                                         GAME_SCREEN_WIDTH - 1)):
                            self.MoveArea[k][p] = 0
    def getRoomBirthPos(self,RoomNO):
        room = self.toRoom(self.mazeMatrix, RoomNO[0], RoomNO[1])
        movepath = [[1 for i in range(0, GAME_SCREEN_WIDTH)] for j in range(0, GAME_SCREEN_HEIGHT)]
        for i in range(0, self.RoomRow):
            for j in range(0, self.RoomCol):
                if room[i][j] == 0:
                    for k in range(max(i * self.roomyl - 32, 0),
                                   min((i + 1) * self.roomyl + 32, GAME_SCREEN_HEIGHT - 1)):
                        for p in range(max(j * self.roomxl - 32, 0), min((j + 1) * self.roomxl + 32,
                                                                         GAME_SCREEN_WIDTH - 1)):
                            movepath[k][p] = 0
        birthPos = []
        err = 30
        for i in range(err, GAME_SCREEN_HEIGHT - err):
            for j in range(err, GAME_SCREEN_WIDTH - err):
                if movepath[i][j] == 1 and (movepath[i + k][j + p] == 1 for k, p in [-err, err]):
                    birthPos.append((j, i))

        # print(Player_birth)
        i=random.randint(0,len(birthPos)-1)
        Enemy_birth=birthPos[i]
        return Enemy_birth

    def toRoom(self, maze, i, j):
        room = np.zeros((self.RoomRow, self.RoomCol))
        for k in range(1, self.RoomRow - 1):
            for p in range(1, self.RoomCol - 1):
                room[k][p] = maze[k - 1 + i * (self.RoomRow - 2)][p - 1 + j * (self.RoomCol - 2)]
        for r in range(1, self.RoomRow - 1):
            if j < self.Room_unit_Col - 1:
                if maze[r - 1 + i * (self.RoomRow - 2)][(j + 1) * (self.RoomCol - 2) - 1] == 1 and \
                        maze[r - 1 + i * (self.RoomRow - 2)][(j + 1) * (self.RoomCol - 2)] == 1:
                    room[r][self.RoomCol - 1] = 1
            if j > 0:
                if maze[r - 1 + i * (self.RoomRow - 2)][j * (self.RoomCol - 2) - 1] == 1 and \
                        maze[r - 1 + i * (self.RoomRow - 2)][j * (self.RoomCol - 2)] == 1:
                    room[r][0] = 1

        for c in range(1, self.RoomCol - 1):
            if i < self.Room_unit_Row - 1:
                if maze[(i + 1) * (self.RoomRow - 2) - 1][c - 1 + j * (self.RoomCol - 2)] == 1 and \
                        maze[(i + 1) * (self.RoomRow - 2)][c - 1 + j * (self.RoomCol - 2)] == 1:
                    room[self.RoomRow - 1][c] = 1
            if i > 0:
                if maze[i * (self.RoomRow - 2) - 1][c - 1 + j * (self.RoomCol - 2)] == 1 and \
                        maze[i * (self.RoomRow - 2)][c - 1 + j * (self.RoomCol - 2)] == 1:
                    room[0][c] = 1

        return room

    def initMoveArea(self):

        self.MoveArea = [[1 for i in range(0, GAME_SCREEN_WIDTH)] for j in range(0, GAME_SCREEN_HEIGHT)]

    def printRoom(self):
        print(self.pr)

    def getRoomRC(self):

        return [self.Room_unit_Row, self.Room_unit_Col]

    def getBlock(self):

        return self.block.getBlockGroup()

    def getTrap(self):

        return self.trap.getTrapGroup()

    def getMoveArea(self):

        return self.MoveArea

    def getMovePos(self):
        movepos = []
        for i in range(0, GAME_SCREEN_HEIGHT):
            for j in range(0, GAME_SCREEN_WIDTH):
                if self.MoveArea[i][j] == 1:
                    movepos.append((i, j))
        return movepos

    def getmaze(self):
        return self.mazeMatrix

    def getmazerow(self):
        return self.mazerow

    def getmazecol(self):
        return self.mazecol

    def getcell_col(self):
        return self.cell_col

    def getcell_row(self):
        return self.cell_row

    def MazeGenerator(self):
        maze = [[1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1],
                [1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1],
                [1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1],
                [1, 8, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1],
                [0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1],
                [1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1],
                [1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1],
                [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1],
                [1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1],
                [1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1],
                [1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1],
                [1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1],
                [1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1],
                [1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1],
                [0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                [1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1],
                [1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1]]

        return maze


import json
import time

from player import Player
import random
from datetime import datetime

class Game:
    def __init__(self, json_file_name):
        with open(json_file_name) as json_file:
            self.data = json.load(json_file)["locations"]
        self.maxPlayers = 8
        self.location = None
        self.players = []
        self.startTime = None
        self.gameTime = 600
        self.spy = None
        self.gameIsLive = False

    def set_players(self, members):
        self.players = []
        for member in members:
            player = Player(member)
            self.players.append(player)

    def assign_roles(self):
        n = len(self.players)
        locations_len = len(self.data)
        self.location = self.data[random.randint(0, locations_len - 1)]
        roles = self.location["roles"]
        roles_numbers = random.sample(range(0, self.maxPlayers - 1), n-1)
        spy = 0
        if n != 1:
            spy = random.randint(0, n - 1)
            roles_numbers.insert(spy-1, -1)
        for i in range(0, n):
            if i != spy:
                role = roles[roles_numbers[i]]
            else:
                role = "Spy"
                self.spy = self.players[i]
            self.players[i].set_role(role)

    def get_spy(self):
        return self.spy

    def set_startTime(self, startTime):
        self.startTime = startTime

    def set_gameTime(self, gameTime):
        self.gameTime = gameTime

    def play(self, members):
        self.set_players(members)
        self.assign_roles()
        self.set_startTime(datetime.now())
        self.gameIsLive = True

    def show(self):
        for player in self.players:
            print(player.role, player.user.name)
        print(self.startTime)

    def add_location(self, location):
        self.data.append(location)

    def display(self):
        for e in self.data:
            print(e["title"], e["roles"])

    def countdown(self):
        countdown = self.gameTime
        while countdown != 0:
            time.sleep(1)
            countdown -= 1

    def gameEnd(self):
        self.gameIsLive = False


from requestServers import server_request
import sql_query
import json
from Globals import Global

class ServerRequestDatabase(server_request.ServerRequest):

    def __init__(self, db_name, db_table_name, col_names, col_options):
        """
        :param db_name:             (str)  name of database
        :param db_table_name:       (str)  name of table in database
        :param col_names:           (List) name of columns in table
        """

        table_col_options = []
        cols = list( zip( col_names, col_options ) )

        for col in cols:
            table_col_options.append( ' '.join( col ) )

        table_cols_str = ', '.join( table_col_options )

        self.sql_db = sql_query.sql_query(db_name)
        self.sql_db.add_table(db_table_name, col_names, [""]*len(col_names))

#                              self.table_col_names[0] + " INT, " +
#                              self.table_col_names[1] + " VARCHAR(255)"
#                              )

        self.table_name = db_table_name
        self.table_col_names = col_names  # ["spawn_time", "position"]

    def post_request(self, page_request, query, data):

        response = "Error: Not Found"
        status = 404

        if page_request.lower() == "/savedata":
            if query.lower() == "obj":
                response = self.add_data( data )
                status = 200

        return status, response

    def get_request(self, page_request, query):

        response = "Error: Not Found"
        status = 200

        if Global.DEBUG:
            print("Get Query:", query)

        if page_request.lower() == "/load":
            response = self.get_data(0)
        elif page_request.lower() == "/newGame".lower():
            response = self.get_data(0)
        elif page_request.lower() == "/delete" and query.split("=")[0] == "t":
            try:
                t = int(query.split("=")[1])
            except:
                t = 0
                print("Error: t was not an int :(")
            response = self.remove_data(t)
        elif page_request.lower() == "/clearTable".lower():
            response = self.clear_table()
        else:
            status = 404

        return status, response

    def get_data(self, time):
        """
        :param time: get all results after time. (0 if starting a new game)
        :return: string, of json, since 'time' or status if no data
        """

        if self.sql_db == None:         # create or get existing DB
            return "Error: No Database"

        # pull all data from the DB to be loaded into the game
        results = self.sql_db.select_from_table( self.table_name,
                                                 ', '.join(self.table_col_names),
                                                 "spwanTime > ?",
                                                 str(time) )
        row_data = []

        if results is None:
            return "Error: No Data"

        # stitch the col names and results together
        # appending it to row_data as a json str.
        for r in results:
            row = dict(zip(self.table_col_names, r))

            # check if the data starts with '{' if it does it need to be parshed into its own dict
            for key in row:
                # check that the row key does not start with { and ends in }
                if str(row[key])[0] == "{" and str(row[key])[-1] == "}":
                    row[key] = json.loads( row[key].replace("'", '"') )

            row_data.append( json.dumps( row ) )

            if Global.DEBUG:
                print("ADD: ", row_data[-1])

        if len(row_data) == 0:
            return "Error: No Data"
        else:
            return ';'.join( row_data )

    def add_data(self, json_data_str):
        """ Add data to table from json string

        :param json_data_str: json str of data to insert into table
        json keys must match table col names. (case-insensitive) (any others will be discarded)
        :return: status and message str( [status]:[message] )
        """
        if Global.DEBUG:
            print( "Add Data TO DB Json: ", json_data_str )  #.replace('\n', '').replace('\t', '').replace('\r', '') )

        json_data = json.loads( json_data_str )
        col_names = []
        data = []

        # find all data that matches table_col_names
        for j_col in json_data:
            for t_col in self.table_col_names:
                if j_col.lower() == t_col.lower():
                    col_names.append( j_col.lower() )
                    data.append( str(json_data[ t_col ] ) )
                    break

        if self.sql_db == None:
            return "Error: No Database"

        if len( col_names ) == 0:
            return "Error: No Data"
        if Global.DEBUG:
            print("col_names: ", col_names)

        self.sql_db.insert_row(self.table_name, col_names, data)

        return "Success: Row Added"

    def remove_data(self, time):
        """ Removes and object from the table.

        :param time: the time the object was spawned
        :return: status and message str( [status]:[message] )
        """

        if self.sql_db == None:
            return "Error: No Database"

        self.sql_db.remove_row(self.table_name, "spwanTime = ?", (str(time), ))

        return "Success: Row Removed"

    def clear_table(self):
        """ Causion: removes all values from table

                :return: status and message str( [status]:[message] )
        """

        if self.sql_db == None:
            return "Error: No Database"

        self.sql_db.remove_row(self.table_name, "spwanTime > ?", "0")

        return "Success: Row Removed"


import os

import pandas as pd

from algorecell_types import *
from colomoto.types import PartialState

class StableMotifsResult(object):
    """
    Class of objects returned by :py:func:`load` function giving access to
    StableMotifs results.

    .. py:attribute:: attractors

        List of attractors (dictionnaries mapping node names to ``0``, ``1``, or
        ``'X'``).
    """
    def __init__(self, wd, model_name, fixed):
        self.wd = wd
        self.model_name = model_name
        self.fixed = fixed
        self.attractors = self._parse_attractors()

    def _wfile(self, pattern):
        return os.path.join(self.wd, pattern%self.model_name)

    def _parse_attractors(self):
        inputf = self._wfile("%s-QuasiAttractors.txt")
        df = pd.read_csv(inputf, sep='\t', index_col=-1) #index_col=-1 we cheat by making the extra tabs at the end of the rows in the files as the index column, and then resetting it to just natural incrementing integers
        df.reset_index(inplace=True,drop=True)
        d = df.to_dict("index")
        return [d[i] for i in range(len(d))]

    def _parse_control_sets(self):
        inputf = self._wfile("%s-StableMotifControlSets.txt")
        control_sets = dict([(i, []) for i in range(len(self.attractors))])
        with open(inputf) as f:
            for c in f.readlines():
                if not c:
                    continue
                cc=c.split('\t')[0]
                cd=[(i.split('=')[0],int(i.split('=')[1])) for i in cc.split(' ')]
                attr=c.split('\t')[1]
                attr_id = int(attr[9:])
                control_sets[attr_id].append(dict(sorted(cd)))
        return control_sets

    def _parse_stable_motifs(self):
        inputf = self._wfile("%s-StableMotifs.txt")
        stable_motifs = []
        with open(inputf) as f:
            for sms in f.readlines():
                if not sms.strip():
                    continue
                smss=[(i.split('=')[0],int(i.split('=')[1])) for i in sms.strip().split('\t')]
                stable_motifs.append(dict(smss))
        return stable_motifs

    @property
    def stable_motifs(self):
        """
        List of stable motifs, mapping subset of nodes to Boolean values (`dict[str,int]`)
        """
        if not hasattr(self, "_StableMotifsResult__cache_stable_motifs"):
            self.__cache_stable_motifs = self._parse_stable_motifs()
        return self.__cache_stable_motifs

    @property
    def control_sets(self):
        """
        Dictionnary mapping attractor indices to their control sets (`dict[str,int] list`)
        """
        if not hasattr(self, "_StableMotifsResult__cache_control_sets"):
            self.__cache_control_sets = self._parse_control_sets()
        return self.__cache_control_sets

    def reprogramming_to_attractor(self, *spec, **kwspec):
        """
        Compute reprogramming strategies ensuring that only attractors matching
        with the given specification can be reached with the asynchronous mode.
        The perturbations are temporary, i.e., can be released once in the
        attractor.

        :rtype: `algorecell_types.ReprogrammingStrategies <https://algorecell-types.readthedocs.io/#algorecell_types.ReprogrammingStrategies>`_

        Examples:

        >>> sm.reprogramming_to_attractor(A=1, B=0)
        >>> sm.reprogramming_to_attractor({"A": 1, "B": 0})
        """
        strategies = ReprogrammingStrategies()
        spec = PartialState(*spec, **kwspec)
        for i, attractor in enumerate(self.attractors):
            if spec.match_state(attractor):
                for cs in self.control_sets[i]:
                    p = TemporaryPerturbation(cs)
                    s = FromCondition("input", p) if self.fixed else FromAny(p)
                    strategies.add(s)
        if self.fixed:
            strategies.register_alias("input", self.fixed)
        return strategies


"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('information/', include('information.urls')),
	path('works/', include('works.urls')),
    path('suppostInfo/', include('supportInfo.urls')),
    path('homePage/', include('homePage.urls')),
]


import cv2
import numpy as np

img = cv2.imread("Utils/ww3.jpg")
print(img.shape)

imgResize = cv2.resize(img, (480, 720)) # first is width then height

imgCrop = img[0:200, 200:500] # height is first then width
cv2.imshow("image", img)
cv2.imshow("ResizeImage", imgResize)
cv2.imshow("CropImage", imgCrop)

img1 = np.zeros((500, 500, 3), np.uint8)
#print(img1)
#img1[:] = 255, 0, 0 # : to apply to whole image, blue color

cv2.line(img1, (0, 0), (300, 300), (0, 255, 0), 3) # line whth dimensions
cv2.line(img1, (0, 0), (img1.shape[1], img1.shape[0]), (0, 255, 0), 3) # diagonal line
cv2.rectangle(img1, (0, 0), (200, 300), (0, 0, 255), 2)
cv2.circle(img1, (400, 50), 30, (255, 255, 0), 4)
cv2.putText(img1, "Dark Knight", (300, 200), cv2.FONT_ITALIC, 0.5, (0, 150, 100), 2)
cv2.imshow("blank", img1)

cv2.waitKey(0)


# Testing if the algorithm works based on Boost example:
# https://www.boost.org/doc/libs/1_68_0/libs/graph/example/r_c_shortest_paths_example.cpp

# Traditional Shortest Path Problem
if __name__ == '__main__':
    import rcsp_networkx
    import networkx

    g = networkx.DiGraph()

    #===========================================================================
    # g.add_node("A", earliestTime = 0, latestTime = 0)
    # g.add_node("B", earliestTime = 5, latestTime = 20)
    # g.add_node("C", earliestTime = 6, latestTime = 10)
    # g.add_node("D", earliestTime = 3, latestTime = 12)
    # g.add_node("E", earliestTime = 0, latestTime = 100)
    #===========================================================================

    g.add_node("A")
    g.add_node("B")
    g.add_node("C")
    g.add_node("D")
    g.add_node("E")

    g.add_edge("A", "C", cost=1, time=5)
    g.add_edge("B", "B", cost=2, time=5)
    g.add_edge("B", "D", cost=1, time=2)
    g.add_edge("B", "E", cost=2, time=7)
    g.add_edge("C", "B", cost=7, time=3)
    g.add_edge("C", "D", cost=3, time=8)
    g.add_edge("D", "E", cost=1, time=3)
    g.add_edge("E", "A", cost=1, time=5)
    g.add_edge("E", "B", cost=1, time=5)

    solutions = rcsp_networkx.rcsp(g, "A", "E")
    rcsp_networkx.printRCSP(solutions)


from sqlalchemy import select, insert, delete, update
from sqlalchemy.orm import sessionmaker
from .DB_models import *
from .DB_engines import engine

session_factory = sessionmaker(bind=engine)

class Populate:
    @classmethod
    def get_list_of_items(cls):
        """Returns DISTINCT 'names' from table 'Items'"""
        session = session_factory()
        list_of_items = session.execute(
            select(Items.name)
            .distinct()
        )
        for row in list_of_items:
            return row

    @classmethod
    def populate_active_items(cls, name):
        """Returns oldest items of requested name whose amount is not 0"""
        session = session_factory()
        item = session.scalars(
            select(
                Items.ID,
                Items.name,
                Items.amount,
                Items.pricePerUnit)
                .join(Invoices)
                .filter(Items.name.in_([name]), Items.amount != 0)
                .order_by(Invoices.date)
            ).first()
        return item

    @classmethod
    def populate_ingredients(cls):
        session = session_factory()
        ingredients = session.scalars(
            select(Ingredients)
            .order_by(Ingredients.name)
        ).all()
        return ingredients

    @classmethod
    def populate_recipes(cls):
        session = session_factory()
        recipes = session.scalars(
            select(Recipe)
            .order_by(Recipe.name)
        ).all()
        return recipes

    @classmethod
    def populate_promotions(cls):
        session = session_factory()
        promotions = session.scalars(
            select(Promotion)
            .order_by(Promotion.name)
        ).all()
        return promotions

    @classmethod
    def populate_groups(cls):
        session = session_factory()
        groups = session.scalars(
            select(Group)
            .order_by(Group.name)
        ).all()
        return groups

class POST:
    @classmethod
    def create_ingredient(cls, data):
        session = session_factory()
        name, item_name, used_amount, \
        production_cost, sale_price, menu = data

        new_ingredient = Ingredients(
            name            = name,
            item_name       = item_name,
            used_amount     = used_amount,
            production_cost = production_cost,
            sale_price      = sale_price,
            menu            = menu
        )
        session.add_all([new_ingredient])
        try:
            session.commit()
            return (200, "Ingredient created successfully")
        except:
            session.rollback()
            return (401, "Failed to create ingredient")
        finally:
            session.close()

    @classmethod
    def create_recipe(cls, data):
        session = session_factory()
        name, ingredient_list, production_cost, sale_price, \
        recipe_amount, portions, menu = data

        new_recipe = Ingredients(
            name            = name,
            ingredient_list = ingredient_list,
            production_cost = production_cost,
            sale_price      = sale_price,
            recipe_amount   = recipe_amount,
            portions        = portions,
            menu            = menu
        )
        session.add_all([new_recipe])
        try:
            session.commit()
            return (200, "Recipe created successfully")
        except:
            session.rollback()
            return (401, "Failed to create recipe")
        finally:
            session.close()

    @classmethod
    def create_promotion(cls, data):
        session = session_factory()
        name, production_cost, sale_price, items_list, menu = data

        new_promotion = Ingredients(
            name            = name,
            production_cost = production_cost,
            sale_price      = sale_price,
            items_list      = items_list,
            menu            = menu
        )
        session.add_all([new_promotion])
        try:
            session.commit()
            return (200, "Promotion created successfully")
        except:
            session.rollback()
            return (401, "Failed to create promotion")
        finally:
            session.close()

    @classmethod
    def create_group(cls, data):
        session = session_factory()
        name, members, menu = data

        new_group = Ingredients(
            name            = name,
            members         = members,
            menu            = menu
        )
        session.add_all([new_group])
        try:
            session.commit()
            return (200, "Promotion created successfully")
        except:
            session.rollback()
            return (401, "Failed to create promotion")
        finally:
            session.close()

class PUT:
    @classmethod
    def update_ingredient(cls, data):
        session = session_factory()
        name, item_name, used_amount, production_cost, sale_price, menu = data

        update = session.execute(
                    select(Ingredients)
                    .filter(Ingredients.name == name)
                ).scalar_one()
        update.name = name
        update.item_name = item_name
        update.used_amount = used_amount
        update.production_cost = production_cost
        update.sale_price = sale_price
        update.menu = menu

        try:
            session.commit()
            return (200, "Ingredient updated successfully")
        except:
            session.rollback()
            return (401, "Failed to update ingredient")
        finally:
            session.close()

    @classmethod
    def update_recipe(cls, data):
        session = session_factory()
        name, ingredients_list, production_cost, sale_price, recipe_amount, portion, menu = data

        update = session.execute(
                    select(Recipe)
                    .filter(Recipe.name == name)
                ).scalar_one()
        update.name            = name
        ingredients_list       = ingredients_list
        update.production_cost = production_cost
        update.sale_price      = sale_price
        update.recipe_amount   = recipe_amount
        update.portions        = portion
        update.menu            = menu

        try:
            session.commit()
            return (200, "Recipe updated successfully")
        except:
            session.rollback()
            return (401, "Failed to update recipe")
        finally:
            session.close()

    @classmethod
    def update_promotion(cls, data):
        session = session_factory()
        name, production_cost, sale_price, items_list, menu = data

        update = session.execute(
            select(Promotion)
            .filter(Promotion.name == name)
        ).scalar_one()
        update.name = name
        update.production_cost = production_cost
        update.sale_price = sale_price
        update.items_list = items_list
        update.menu = menu

        try:
            session.commit()
            return (200, "Recipe updated successfully")
        except:
            session.rollback()
            return (401, "Failed to update recipe")
        finally:
            session.close()

    @classmethod
    def update_group(cls, data):
        session = session_factory()
        name , members, menu = data

        update = session.execute(
            select(Group)
            .filter(Group.name == name)
        ).scalar_one()
        update.name = name
        update.members = members
        update.menu = menu

        try:
            session.commit()
            return (200, "Recipe updated successfully")
        except:
            session.rollback()
            return (401, "Failed to update recipe")
        finally:
            session.close()

class DELETE:
    @classmethod
    def delete_ingredient(cls, name):
        session = session_factory()
        session.execute(
            delete(Ingredients)
            .where(Ingredients.name == name)
        )
        try:
            session.commit()
            return (200, "Ingredient deleted successfully")
        except:
            session.rollback()
            return (401, "Failed to delete ingredient")

    @classmethod
    def delete_recipe(cls, name):
        session = session_factory()
        session.execute(
            delete(Recipe)
            .where(Recipe.name == name)
        )
        try:
            session.commit()
            return (200, "Recipe deleted successfully")
        except:
            session.rollback()
            return (401, "Failed to delete recipe")

    @classmethod
    def delete_promotion(cls, name):
        session = session_factory()
        session.execute(
            delete(Promotion)
            .where(Promotion.name == name)
        )
        try:
            session.commit()
            return (200, "Promotion deleted successfully")
        except:
            session.rollback()
            return (401, "Failed to delete promotion")

    @classmethod
    def delete_group(cls, name):
        session = session_factory()
        session.execute(
            delete(Group)
            .where(Group.name == name)
        )
        try:
            session.commit()
            return (200, "Group deleted successfully")
        except:
            session.rollback()
            return (401, "Failed to delete group")

Populate.get_list_of_items()


nome = "Gustavo"
idade = 16
altura = 1.87
peso = 70.00
ano_atual = 2022

ano_nascimento = ano_atual - idade
imc = peso / altura ** 2

print(f"{nome} tem {idade} anos, {altura} de altura e pesa {peso}kg.")
print(f"O IMC de {nome} é {imc:.2f}")
print(f"{nome} nasceu em {ano_nascimento}.")


import threading
import time
import pickle
import socket
import os
import yaml
import ast

from robotino_core.Comm import Comm
from robotino_core.solvers.tsp_solver import *
from robotino_core.solvers.astar_solver import *

class AGV_TA_agent:

	"""
			A class containing the intelligence of the Task Allocation agent. This agent takes care of
			task collection from an external MES system, task allocation of new task among robots,
			and task switching of assinged tasks to improve the solution.
	"""

	def __init__(self, params_file):

		# Read params
		this_dir = os.path.dirname(os.path.dirname(__file__))
		data_path = os.path.join(this_dir, "params", params_file)
		with open(data_path, 'r') as file:
			self.params = yaml.load(file, Loader=yaml.FullLoader)

		# Init database communication for all threads
		self.comm_task_collector = Comm(self.params['ip'], self.params['port'], self.params['host'], self.params['user'], self.params['password'], self.params['database'])
		self.comm_task_allocator = Comm(self.params['ip'], self.params['port'], self.params['host'], self.params['user'], self.params['password'], self.params['database'])
		self.comm_task_switcher = Comm(self.params['ip'], self.params['port'], self.params['host'], self.params['user'], self.params['password'], self.params['database'])
		self.comm_task_scheduler = Comm(self.params['ip'], self.params['port'], self.params['host'], self.params['user'], self.params['password'], self.params['database'])

		# Exit event
		self.exit_event = threading.Event()

		# Processes
		self.threads = []
		self.threads.append(threading.Thread(target=self.task_collector))
		self.threads.append(threading.Thread(target=self.task_allocator))
		self.threads.append(threading.Thread(target=self.task_switcher))
		self.threads.append(threading.Thread(target=self.task_scheduler))

	def signal_handler(self, _, __):
		print("\n\nShutdown TA-agent")
		self.exit_event.set()

	def task_collector(self):

		"""
		This thread continuously listens to incoming tasks from an external system at its IP-address.
		If a task arrives, it puts it unassigned onto the global task list.

		"""

		# Open tcp server
		print("\nTA-agent:	Task collector thread started")
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock_server:
			sock_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			sock_server.bind((self.params['ip'], self.params['port']))
			sock_server.listen()
			sock_server.settimeout(None)
			time.sleep(1)

			# Loop
			while True:

				# Listening for incomming messages
				print("\nTA-agent:	Listening for incoming tasks...")
				conn, _ = sock_server.accept()

				# Receive the data and retransmit it
				with conn:
					data = conn.recv(1024)
					conn.sendall(data)

				# Convert data to dictionary
				try:
					data = pickle.loads(data)
				except EOFError:
					data = None
				print("\nTA-agent:	Received task " + str(data))

				# Get all tasks
				tasks = self.comm_task_collector.sql_select_everything_from_table('global_task_list')
				if tasks is None: continue

				# Put unnasigned task on global task list if not present yet
				print(str([task for task in tasks if task["order_number"] == data['order_number']]))
				if len([task for task in tasks if task["order_number"] == data['order_number']]) == 0:
					task_dict = {"order_number": data['order_number'], "node": data['node'], "priority": 0, "robot": -1, "estimated_start_time": "-", "estimated_end_time": "-", "estimated_duration": "-", "real_start_time": "-", "real_end_time": "-", "real_duration": "-", "progress": 0.0, "message": "-", "status": 'unassigned', "approach": data["approach"], "auctioneer": -1, "task_bids": '{}',"path": '[]', "slots": "[]", "dist": 0.0, "cost": 0.0}
					self.comm_task_collector.sql_add_to_table('global_task_list', task_dict)

	def task_allocator(self):

		"""
		This thread continuously reviews all tasks in the global_task_list that are unassigned and places a bid on this task.
		If it sees that after placing the bid, the number of placed bids equals the number of robots in the system, it selects
		the robot with the best bid and allocates the task to this robot. It does this at a certain 'task_allocator_rate'.

		"""

		# Loop
		print("TA-agent:	Task allocator thread started")
		while True:

			# Timeout and exit event
			if self.exit_event.wait(timeout=self.params['task_allocator_rate']):
				print("\nTA-agent:	Task allocator thread killed")
				break

			# Get unnasigned tasks
			unassigned_tasks = self.comm_task_allocator.sql_select_unassigned_tasks()
			if unassigned_tasks is None or len(unassigned_tasks) == 0: continue

			# Get all robots in the fleet
			robots = self.comm_task_allocator.sql_select_everything_from_table('global_robot_list')
			if robots is None or len(robots) == 0: continue

			# Get local task list
			local_task_list = self.comm_task_allocator.sql_select_local_task_list(self.params['id'])
			if local_task_list is None: continue

			# Get unassigned tasks not yet bid on
			unassigned_tasks = [task for task in unassigned_tasks if self.params['id'] not in ast.literal_eval(task['task_bids']).keys()]
			if len(unassigned_tasks) == 0: continue

			# Get first unassinged task and convert taks to dictionary
			task = unassigned_tasks[0]
			task_bids = ast.literal_eval(task['task_bids'])

			# Compute bid list and select bid regarding objective index
			bid_value_list = self.compute_bid(local_task_list, task, False, self.comm_task_allocator)
			bid = 1000 if not bid_value_list else bid_value_list[self.params['objective_index']]

			# Place bid at task
			task_bids[self.params['id']] = bid
			task_dict = {'task_bids': str(task_bids)}
			self.comm_task_allocator.sql_update_task(task['id'], task_dict)

			# Allocate task
			if len(task_bids.keys()) >= len(robots):
				winner_id = min(task_bids, key=task_bids.get)
				task_dict = {'robot': winner_id, 'status': 'assigned'}
				self.comm_task_allocator.sql_update_task(task['id'], task_dict)

	def task_switcher(self):

		"""
		This thread continuously reviews all tasks in the global_task_list that are assigned to robots and looks
		if a better solution could be found. It does this at a certain 'task_swither_rate'.

		"""

		# Loop
		print("TA-agent:	Task switcher thread started")
		while True:

			# Timeout and exit event
			if self.exit_event.wait(timeout=self.params['task_switcher_rate']):
				print("TA-agent:	Task switcher thread killed")
				break

			# Get asigned tasks
			assigned_tasks = self.comm_task_switcher.sql_select_assigned_tasks()
			if assigned_tasks is None or len(assigned_tasks) == 0: continue

			# Get local task list
			local_task_list = self.comm_task_switcher.sql_select_local_task_list(self.params['id'])
			if local_task_list is None: continue

			# Pick random task and convert task to dictionary
			task = assigned_tasks[random.randint(0, len(assigned_tasks)-1)]
			task_bids = ast.literal_eval(task['task_bids'])

			# Compute bid different if it is my own task compared to if it is another robot's task
			subtract = True if task['robot'] == self.params['id'] else False
			bid_multiplier = -1 if task['robot'] == self.params['id'] else 1

			# Compute bid list and select bid regarding objective index
			bid_value_list = self.compute_bid(local_task_list, task, subtract, self.comm_task_switcher)
			bid = 1000 if not bid_value_list else bid_value_list[self.params['objective_index']]

			# Place bid at task
			task_bids[self.params['id']] = bid * bid_multiplier
			task_dict = {'task_bids': str(task_bids)}
			self.comm_task_switcher.sql_update_task(task['id'], task_dict)

			# Allocate task
			winner_id = min(task_bids, key=task_bids.get)
			task_dict = {'robot': winner_id}
			self.comm_task_switcher.sql_update_task(task['id'], task_dict)

	def task_scheduler(self):

		"""
		This thread continuously updates the order of the local task list. It does this at a certain 'task_scheduler_rate'.

		"""

		# Loop
		print("TA-agent:	Task scheduler thread started")
		while True:

			# Timeout and exit event
			if self.exit_event.wait(timeout=self.params['task_scheduler_rate']):
				print("TA-agent:	Task scheduler thread killed")
				break

			# Get graph
			self.graph = self.comm_task_scheduler.sql_select_graph()
			if self.graph is None: return None

			# Get robot
			robot = self.comm_task_scheduler.sql_select_robot(self.params['id'])
			if robot is None or len(robot) == 0: return None

			# Get task executing
			task_executing = self.comm_task_scheduler.sql_select_executing_task(self.params['id'])
			if task_executing is None: return None

			# Get local task list
			local_task_list = self.comm_task_scheduler.sql_select_local_task_list(self.params['id'])
			if local_task_list is None: continue

			# Get start node and new local task list
			start_node = robot[0]['node'] if len(task_executing) == 0 else task_executing[0]['node']

			# Execute tsp using astar routing and only node names of the tasks
			nodes_to_visit = [task['node'] for task in local_task_list]
			solution = tsp(start_node, nodes_to_visit, self.dist_astar)

			# Convert task node names back to tasks including homing task
			sequence = [local_task_list[nodes_to_visit.index(name)] for name in solution['sequence']]

			# Update priorities
			for priority, task in enumerate(sequence):
				task_dict = {'priority': priority + 1}
				self.comm_task_scheduler.sql_update_task(task['id'], task_dict)

	def compute_bid(self, local_task_list, new_task, substract, comm):

		"""

		Computes the difference between the estimated current cost of the local task list and the
		estimated cost of the local task list including/excluding the new task. The estimated current
		cost is calculated by a performance monitor thread in the main vehicle agent.

		Input:
			- Local task list
			- New task
			- Substract the new task from the local task list or add it
			- Communication layer object
		Output:
			- Objective list

		"""

		# Assertions
		assert isinstance(local_task_list, list)
		assert isinstance(new_task, dict)
		assert isinstance(substract, bool)
		assert isinstance(comm, Comm)

		# Get graph
		self.graph = comm.sql_select_graph()
		if self.graph is None: return None

		# Get robot
		robot = comm.sql_select_robot(self.params['id'])
		if robot is None or len(robot) == 0 : return None

		# Get task executing
		task_executing = comm.sql_select_executing_task(self.params['id'])
		if task_executing is None: return None

		# Get start node and new local task list
		start_node = robot[0]['node'] if len(task_executing) == 0 else task_executing[0]['node']
		new_local_task_list = local_task_list + [new_task] if not substract else [t for t in local_task_list if t['id'] != new_task['id']]

		# Check if task occurs twice in list of all nodes
		all_nodes = [task['node'] for task in new_local_task_list] + [start_node]
		if not len(set(all_nodes)) == len(all_nodes): return None

		# Execute tsp using astar routing and only node names of the tasks
		nodes_to_visit = [task['node'] for task in new_local_task_list]
		solution = tsp(start_node, nodes_to_visit, self.dist_astar)

		# TODO: Insert optimal charging station (remove charging station, and add new if necessary)

		# TODO: Compute dmas routes between stations

		# Compute miniSum and miniMax objective values using the new and current costs of the local task list
		min_sum = sum(solution['dists']) - robot[0]['local_task_list_cost']
		min_max = sum(solution['dists'])

		print(f"Bid on task: {new_task['node']}")
		print(f"Current cost: {robot[0]['local_task_list_cost']}")
		print(f"New cost: {sum(solution['dists'])}")

		# Compute objective list
		objective = self.params['epsilon'] * min_sum + (1 - self.params['epsilon']) * min_max
		objective_list = [objective, min_sum, min_max]

		return objective_list

	def dist_astar(self, a, b):
		return get_shortest_path(self.graph, a, b)


import os
from datetime import datetime

import tensorflow as tf

class ActionValueNetwork(object):
    def __init__(self, num_inputs, num_actions, learning_rate, name, log=False, load=True):
        self.num_inputs = num_inputs
        self.num_actions = num_actions
        self.learning_rate = learning_rate
        self.loss = tf.keras.metrics.Mean("loss")
        self.optimizer = tf.keras.optimizers.Adam(learning_rate=self.learning_rate)
        self.name = name
        self.checkpoint_path = "model_checkpoint"
        self.checkpoint_dir = os.path.dirname(self.checkpoint_path)

        self.model = self.load_model() if load else self.create(name)

        if log:
            current_time = datetime.now().strftime("%Y%m%d-%H%M%S")
            log_dir = 'logs/gradient_tape/' + current_time + '/'
            self.summary_writer = tf.summary.create_file_writer(log_dir)

    def create(self, name):
        model = tf.keras.Sequential(name=name)
        model.add(tf.keras.layers.Dense(32, activation="relu", input_shape=(self.num_inputs,)))
        model.add(tf.keras.layers.Dense(64, activation="relu"))
        model.add(tf.keras.layers.Dense(self.num_actions))
        model.compile(self.optimizer, loss="mse")
        return model

    def update_weights(self, target_weights):
        self.model.set_weights(target_weights)

    def predict(self, state):
        if self.model is None:
            raise Exception("Null Value, Model not created")
        return self.model(state)

    def checkpoint(self, episode):
        self.model.save(f'{self.checkpoint_path}/{self.name.lower()}/full_model')
        if episode % 20 == 0:
            self.model.save_weights(f'{self.checkpoint_path}/{self.name.lower()}/weights/weights_episode_{episode}')

    def load_model(self, episode=None):
        model = tf.keras.models.load_model(f'{self.checkpoint_path}/{self.name.lower()}/full_model')
        if episode is not None:
            model.load_weights(f'{self.checkpoint_path}/{self.name.lower()}/weights/weights_episode_{episode}')
        return model


"""
This code includes simple recurrent layer, which is developed by Elman.
Also known as (and should be) Elman Recurrent Layer.
"""

import numpy as np
import theano
import theano.tensor as T
from lemontree.layers.layer import BaseLayer
from lemontree.layers.recurrent import BaseRecurrentLayer
from lemontree.layers.activation import Tanh

class ElmanRecurrentLayer(BaseRecurrentLayer):
    """
    This class implements simple recurrent layer.
    """
    def __init__(self, input_shape, output_shape,
                 out_activation = Tanh(),
                 gradient_steps=-1,
                 output_return_index=[-1],
                 precompute=False, unroll=False, backward=False):
        """
        This function initializes the class.
        Input is 3D tensor, output is 3D tensor.
        Do not use activation layer after this layer, since activation is already applied to output.

        Parameters
        ----------
        input_shape: tuple
            a tuple of single value, i.e., (input dim,)
        output_shape: tuple
            a tuple of single value, i.e., (output dim,)
        out_activation: activation, default: Tanh()
            a base activation layer which will be used as output activation.
        gradient_steps: int, default: -1
            an integer which indicates unroll of rnn for backward path.
            if -1, pass gradient through whole sequence length.
            if a positive integer, pass gradient back only for that much.
        output_return_index: list, default: [-1]
            a list of integers which output step should be saved.
            if [-1], only final output is returned.
            if none, return all steps through sequence.
        precompute: bool, default: False
            a bool value determine input precomputation.
            for speedup, we can precompute input in return of increased memory usage.
        unroll: bool, default: False
            a bool value determine recurrent loop unrolling.
            for speedup, we can unroll and compile theano function,
            in return of increased memory usage and much increased compile time.
        backward: bool, default: False
            a bool value determine the direction of sequence.
            although using backward True, output will be original order.

        Returns
        -------
        None.
        """
        super(ElmanRecurrentLayer, self).__init__(gradient_steps, output_return_index, -1,
                                                  precompute, unroll, backward, name)
        # check asserts
        assert isinstance(input_shape, tuple) and len(input_shape) == 1, '"input_shape" should be a tuple with single value.'
        assert isinstance(output_shape, tuple) and len(output_shape) == 1, '"output_shape" should be a tuple with single value.'
        assert isinstance(out_activation, BaseLayer), '"out_activation" should be an activation layer itself.'

        # set members
        self.input_shape = input_shape
        self.output_shape = output_shape
        self.out_activation = out_activation

    def set_shared(self):
        """
        This function overrides the parents' one.
        Set shared variables.

        Shared Variables
        ----------------
        W: 2D matrix
            shape is (input dim, output dim).
        W: 2D matrix
            shape is (output dim, output dim).
        b: 1D vector
            shape is (output dim,).
        """
        W = np.zeros((self.input_shape[0], self.output_shape[0])).astype(theano.config.floatX)  # input[t] to output[t]
        self.W = theano.shared(W, self.name + '_weight_W')
        self.W.tags = ['weight', self.name]
        U = np.zeros((self.output_shape[0], self.output_shape[0])).astype(theano.config.floatX)  # output[t-1] to output[t]
        self.U = theano.shared(U, self.name + '_weight_U')
        self.U.tags = ['weight', self.name]
        b = np.zeros((self.output_shape,)).astype(theano.config.floatX)
        self.b = theano.shared(b, self.name + '_bias')
        self.b.tags = ['bias', self.name]

    def set_shared_by(self, params):
        self.W = params[0]
        self.U = params[1]
        self.b = params[2]

    def get_output(self, input_, mask_, hidden_init):
        """
        This function overrides the parents' one.
        Creates symbolic function to compute output from an input and output (hidden).

        Math Expression
        -------------------
        Y[t] = out_activation(dot(X[t], W) + dot(Y[t-1], U) + b)

        if precompute True, compute dot(X[t],W) for all steps first.
        if mask exist and 1, Y[t] = Y[t-1]

        Parameters
        ----------
        input_: TensorVariable
        mask_: TensorVariable
        hidden_init: TensorVariable

        Returns
        -------
        TensorVariable
        """
        # input_ are (n_batch, n_timesteps, n_features)
        # change to (n_timesteps, n_batch, n_features)
        input_ = input_.dimshuffle(1, 0, 2)
        # mask_ are (n_batch, n_timesteps)
        masks = masks.dimshuffle(1, 0, 'x')
        sequence_length = input_.shape[0]
        batch_num = input_.shape[1]

        # precompute input
        if self.precompute:
            additional_dims = tuple(input.shape[k] for k in range(2, input.ndim))  # (output_dim,)
            input = T.reshape(input, (sequence_length*batch_num,) + additional_dims)
            input = T.dot(input, self.W)
            additional_dims = tuple(input.shape[k] for k in range(1, input.ndim))  # (output_dim,)
            input = T.reshape(input, (sequence_length, batch_num,) + additional_dims)

        # step function
        def step(input_, hidden):
            if self.precompute:
                return self.out_activation.get_output(input_ + T.dot(hidden, self.U) + self.b)
            else:
                return self.out_activation.get_output(T.dot(input_, self.W) + T.dot(hidden, self.U) + self.b)

        # step function, with mask
        def step_masked(input_, mask_, hidden):
            hidden_computed = step(input_, hidden)
            return T.switch(mask_, hidden_computed, hidden)

        # main operation
        if self.unroll:
            counter = range(self.gradient_steps)
            if self.backward:
                counter = counter[::-1]  # reversed index
            iter_output = []
            outputs_info = [hidden_init]
            for index in counter:
                step_input = [input_[index], mask_[index]] + outputs_info
                step_output = step_masked(*step_input)
                iter_output.append(step_output)
                outputs_info = [iter_output[-1]]
            hidden_output = T.stack(iter_output, axis=0)

        else:
            hidden_output = theano.scan(fn=step_masked,
                                        sequences=[input_, mask_],
                                        outputs_info=[hidden_init],
                                        go_backwards=self.backward,
                                        n_steps = None,
                                        truncate_gradient=self.gradient_steps)[0]  # only need outputs, not updates

        # computed output are (n_timesteps, n_batch, n_features)
        # select only required
        if self.output_return_index is None:
            hidden_output_return = hidden_output
        else:
            hidden_output_return = hidden_output[self.output_return_index]
        # change to (n_batch, n_timesteps, n_features)
        hidden_output_return = hidden_output_return.dimshuffle(1, 0, *range(2, hidden_output_return.ndim))

        # backward order straight
        if self.backward:
            hidden_output_return = hidden_output_return[:, ::-1]

        return hidden_output_return

    def get_params(self):
        """
        This function overrides the parents' one.
        Returns interal layer parameters.

        Returns
        -------
        list
            a list of shared variables used.
        """
        return [self.W, self.U, self.b]


import math
import winsound
import os

name = input('请输入姓名：')
weight = int(input('请输入体重：'))
speed = int(input('请输入速度：'))
armor = float(input('请输入盔甲值：'))

power_level = math.log(0.5 * weight * speed ** 2 * (1 + armor))
print(name, '的战斗力指数是：', power_level)
# winsound.Beep(int(200 * power_level), 1000)
if power_level <= 5:
    os.system('2.mp3')
else:
    os.system('1.mp3')
print('GAME OVER!')


from flask import Flask,request,render_template,json
import time
import utils
import json
import string
from flask import jsonify
import decimal
from jieba.analyse import extract_tags

app = Flask(__name__)

class MyJSONEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, decimal.Decimal):
      # Convert decimal instances to strings.
      return str(obj)
    return super(MyJSONEncoder, self).default(obj)

@app.route('/')
def welcome():
  return  render_template("main.html")

@app.route('/login')
def form():
  id = request.values.get("id")
  return f"""
  <form>
    账号：<input value="{id}"><br />
    密码：<input>

  </form>
  """

@app.route('/time')
def get_time():
  return utils.get_time()

@app.route('/c2')
def get_c2_data():
  res = []
  # print(utils.get_c2_data())
  for tup in utils.get_c2_data():
    # print(tup)
    res.append({"name":tup[0],"value":int(tup[1])})
  return jsonify({"data":res})

@app.route('/c1')
def get_c1_data():
  data = utils.get_c1_data()
  return jsonify({"confirm":int(data[0]),"suspect":int(data[1]),"heal":int(data[2]),"dead":int(data[3])})

@app.route('/l1')
def get_l1_data():
  data = utils.get_l1_data()
  day,confirm,suspect,heal,dead = [],[],[],[],[]
  for a,b,c,d,e in data[7:]:
    day.append(a.strftime("%m-%d"))  #a是datatime类型
    confirm.append(b)
    suspect.append(c)
    heal.append(d)
    dead.append(e)
  return jsonify({"day":day,"confirm":confirm,"suspect":suspect,"heal":heal,"dead":dead})

@app.route("/l2")
def get_12_data():
  data = utils.get_l2_data()
  day,confirm_add,suspect_add = [],[],[]
  for a,b,c in data[7:]:
    day.append(a.strftime("%m-%d"))
    confirm_add.append(b)
    suspect_add.append(c)
  return jsonify({"day":day,"confirm_add":confirm_add,"suspect_add":suspect_add})

@app.route('/r1')
def get_r1_data():
  data = utils.get_r1_data()
  city = []
  confirm = []
  for k,v in data:
    city.append(k)
    confirm.append(int(v))
  return jsonify({"city":city,"confirm":confirm})

@app.route('/r2')
def get_r2_data():
  data = utils.get_r2_data()
  d = []
  for i in data:
    k = i[0].rstrip(string.digits) #去除热搜数字
    v = i[0][len(k) :] # 获取热搜数字
    ks = extract_tags(k) #使用jieba提取关键词
    for j in ks:
      if not j.isdigit():
        d.append({"name":j,"value":v})
  return jsonify({"kws": d})

# 修复TypeError: Object of type 'Decimal' is not JSON serializable
# decimal类型的对象不可JSON序列化
####以下代码未测试####################
# 重写flask.json.JSONEncoder里面默认方法
# class MyJSONEncoder(flask.json.JSONEncoder):
#
#     def default(self, obj):
#         if isinstance(obj, decimal.Decimal):
#             # Convert decimal instances to strings.
#             return str(obj)
#         return super(MyJSONEncoder, self).default(obj)
# app.json_encoder = MyJSONEncoder
# #################################
# class DecimalEncoder(json.JSONEncoder):
#   def default(self, o):
#     if isinstance(o, decimal.Decimal):
#       return float(o)
#     super(DecimalEncoder, self).default(o)

if __name__ == '__main__':

  app.json_encoder = MyJSONEncoder
  app.run(debug=True)


l = []

for i in range(9):
    l.append(int(input()))

max = l[0]
max_idx = 0

for j in range(1, 9):
    if max < l[j]:
        max = l[j]
        max_idx = j + 1
if max == l[0]:
    max_idx = 1

print(max)
print(max_idx)


import time
from binary import ArithmeticTM, convert_to_binary
from itertools import product
from machines import *
from turing import TuringMachine

SYMBOLS = ['0', '1']
DIRECTIONS = ['L', 'R']

# For testing
busy_beaver = TuringMachine(
    ['A01RB', 'A11LC', 'B01LA', 'B11RB', 'C01LB'],
    blank_symbol='0',
    example_state='A',
    example_tape='0',
    example_pos=0
)

class TagSystem():
    def __init__(
        self,

        # productions takes the form of a dict {symbol: series of symbols to append}
        # Need to specify None for the halting symbol
        productions,
        deletion_number=2,
        example_tape=''
    ):
        self.productions = {
            i: list(productions[i]) if isinstance(productions[i], str) else productions[i]
            for i in productions.keys()
        }
        self.deletion_number = deletion_number
        self.example_tape = example_tape
    def func(
        self,
        tape
    ):
        if isinstance(tape, str):
            tape = list(tape)
        if self.productions[tape[0]] is not None:
            new_tape = tape + self.productions[tape[0]]
            if len(new_tape) > self.deletion_number:
                return new_tape[self.deletion_number:]
        return
    def run(
        self,
        tape=None,
        pause=0,
        verbose=2
    ):
        if tape is None:
            tape = self.example_tape
        if isinstance(tape, str):
            tape = list(tape)
        state = None
        while True:
            time.sleep(pause)
            if verbose == 2:
                print(tape)
            if state != tape[0].split('[')[1].split('(')[0]:
                state = tape[0].split('[')[1].split('(')[0]
            if tape[0].startswith('A['):
                if verbose == 1:
                    print(state, len([s for s in tape if s.startswith('a')]), len([s for s in tape if s.startswith('b')]))
            if self.func(tape) is None:
                return
            tape = self.func(tape)

# Generate a tag system based on a binary Turing machine input
def convert_to_tag(tm):

    # (state, old symbol, new symbol, moves in direction, sees symbol) -> (new state, new symbol, new direction)
    tag_instructions = {
        (k[0], k[1], tm.instructions[k][0], tm.instructions[k][1], i): (
            tm.instructions[k][2],
            tm.instructions[tm.instructions[k][2], i][0],
            tm.instructions[tm.instructions[k][2], i][1]
        )
        for k, i in product(tm.instructions.keys(), SYMBOLS)
        if (tm.instructions[k][2], i) in tm.instructions.keys()
    }

    # Generate productions for tag system
    productions = {}
    for state, old_sym, new_sym, dir in product(tm.states, SYMBOLS, SYMBOLS, DIRECTIONS):

        # String versions of states to append to language characters
        curr_state = f'[{state}({old_sym}{new_sym}{dir})]'
        if (state, old_sym, new_sym, dir, '0') in tag_instructions.keys():
            next_state_0 = f'[{tag_instructions[state, old_sym, new_sym, dir, "0"][0]}(0{tag_instructions[state, old_sym, new_sym, dir, "0"][1]}{tag_instructions[state, old_sym, new_sym, dir, "0"][2]})]'
        else:
            next_state_0 = '[HALT]'
        if (state, old_sym, new_sym, dir, '1') in tag_instructions.keys():
            next_state_1 = f'[{tag_instructions[state, old_sym, new_sym, dir, "1"][0]}(1{tag_instructions[state, old_sym, new_sym, dir, "1"][1]}{tag_instructions[state, old_sym, new_sym, dir, "1"][2]})]'
        else:
            next_state_1 = '[HALT]'

        # General productions
        productions[f'C{curr_state}'] = [f'D1{curr_state}', f'D0{curr_state}']
        productions[f'c{curr_state}'] = [f'd1{curr_state}', f'd0{curr_state}']
        productions[f'S{curr_state}'] = [f'T1{curr_state}', f'T0{curr_state}']
        productions[f's{curr_state}'] = [f't1{curr_state}', f't0{curr_state}']

        # Conditional productions
        if dir == 'R':
            if new_sym == '0':
                productions[f'A{curr_state}'] = [f'C{curr_state}', f'c{curr_state}']
            if new_sym == '1':
                productions[f'A{curr_state}'] = [f'C{curr_state}', f'c{curr_state}', f'c{curr_state}', f'c{curr_state}']
            productions[f'a{curr_state}'] = [f'c{curr_state}', f'c{curr_state}', f'c{curr_state}', f'c{curr_state}']
            productions[f'B{curr_state}'] = [f'S{curr_state}']
            productions[f'b{curr_state}'] = [f's{curr_state}']
            productions[f'D1{curr_state}'] = [f'A{next_state_1}', f'a{next_state_1}']
            productions[f'd1{curr_state}'] = [f'a{next_state_1}', f'a{next_state_1}']
            productions[f'D0{curr_state}'] = [f'a{next_state_0}', f'A{next_state_0}', f'a{next_state_0}']
            productions[f'd0{curr_state}'] = [f'a{next_state_0}', f'a{next_state_0}']
            productions[f'T1{curr_state}'] = [f'B{next_state_1}', f'b{next_state_1}']
            productions[f't1{curr_state}'] = [f'b{next_state_1}', f'b{next_state_1}']
            productions[f'T0{curr_state}'] = [f'B{next_state_0}', f'b{next_state_0}']
            productions[f't0{curr_state}'] = [f'b{next_state_0}', f'b{next_state_0}']
        if dir == 'L':
            productions[f'A{curr_state}'] = [f'A*{curr_state}', f'a*{curr_state}']
            productions[f'a{curr_state}'] = [f'a*{curr_state}', f'a*{curr_state}']
            if new_sym == '0':
                productions[f'B{curr_state}'] = [f'C{curr_state}', f'c{curr_state}']
            if new_sym == '1':
                productions[f'B{curr_state}'] = [f'C{curr_state}', f'c{curr_state}', f'c{curr_state}', f'c{curr_state}']
            productions[f'b{curr_state}'] = [f'c{curr_state}', f'c{curr_state}', f'c{curr_state}', f'c{curr_state}']
            productions[f'D1{curr_state}'] = [f'B*1{curr_state}', f'b*1{curr_state}']
            productions[f'd1{curr_state}'] = [f'b*1{curr_state}', f'b*1{curr_state}']
            productions[f'D0{curr_state}'] = [f'b*0{curr_state}', f'B*0{curr_state}', f'b*0{curr_state}']
            productions[f'd0{curr_state}'] = [f'b*0{curr_state}', f'b*0{curr_state}']
            productions[f'T1{curr_state}'] = [f'A{next_state_1}', f'a{next_state_1}']
            productions[f't1{curr_state}'] = [f'a{next_state_1}', f'a{next_state_1}']
            productions[f'T0{curr_state}'] = [f'A{next_state_0}', f'a{next_state_0}']
            productions[f't0{curr_state}'] = [f'a{next_state_0}', f'a{next_state_0}']
            productions[f'A*{curr_state}'] = [f'S{curr_state}']
            productions[f'a*{curr_state}'] = [f's{curr_state}']
            productions[f'B*0{curr_state}'] = [f'B{next_state_0}', f'b{next_state_0}']
            productions[f'b*0{curr_state}'] = [f'b{next_state_0}', f'b{next_state_0}']
            productions[f'B*1{curr_state}'] = [f'B{next_state_1}', f'b{next_state_1}']
            productions[f'b*1{curr_state}'] = [f'b{next_state_1}', f'b{next_state_1}']

    # We have to define productions for A[HALT], etc, even though they will not be used
    # We arbitrarily assign values of themselves to symbols other than A[HALT]
    productions['A[HALT]'] = None
    productions['a[HALT]'] = ['a[HALT]']
    productions['B[HALT]'] = ['B[HALT]']
    productions['b[HALT]'] = ['b[HALT]']

    # Construct example tape
    atm = ArithmeticTM(tm)
    q, s, m, n = atm.get_qsmn()
    init_state = f'[{q}({tm.example_tape[tm.example_pos]}{tm.instructions[q, tm.example_tape[tm.example_pos]][0]}{tm.instructions[q, tm.example_tape[tm.example_pos]][1]})]'
    tape = [f'A{init_state}', f'a{init_state}'] + m * [f'a{init_state}', f'a{init_state}'] + [f'B{init_state}', f'b{init_state}'] + n * [f'b{init_state}', f'b{init_state}']

    # Generate tag system
    return TagSystem(
        productions,
        example_tape=tape
    )

if __name__ == '__main__':
    binary_adder = convert_to_binary(adder)
    ts = convert_to_tag(binary_adder)
    ts.run(verbose=1)


#!/usr/bin/env python

import numpy as np
import cv2
import sys

cascade = cv2.CascadeClassifier("wenda_data/cascade.xml")

image = sys.argv[1]
scale = float(sys.argv[2])
img = cv2.imread("datasets/JPEGImages/" + image + ".jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

people = cascade.detectMultiScale(gray, 1.03)
img = cv2.resize(img,None, fx = scale, fy = scale)
for (x, y, w, h) in people:
    print("Wenda")
    print(str((x, y, w, h)))
    (x, y, w, h) = (int(x*scale), int(y*scale), int(w*scale), int(h*scale))
    print(str((x, y, w, h)))
    print(str((x, y)))
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)
cv2.imshow(image,img)
cv2.waitKey()

cv2.destroyAllWindows()


import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn as sns
sns.set_style("dark")

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import roc_auc_score, accuracy_score, f1_score
from sklearn.metrics import classification_report
from sklearn.preprocessing import StandardScaler

# Models
from sklearn import tree
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier
from sklearn import svm
from sklearn.neighbors import KNeighborsClassifier

from utils import learning_curve_plotter, model_param_curve, score, metrics

# base param
seed = 712

# Load Dataset
credit_card_path = "../data/UCI_Credit_Card.csv"
df_credit = pd.read_csv(credit_card_path)
# df_credit = df_credit[:100]

edu_converter = (df_credit.EDUCATION == 5) | (df_credit.EDUCATION == 6) | (df_credit.EDUCATION == 0)
df_credit.loc[edu_converter, 'EDUCATION'] = 4
df_credit["MARRIAGE"] = df_credit["MARRIAGE"].replace(0, 3)

target = 'default.payment.next.month'
features = [  'LIMIT_BAL', 'SEX', 'EDUCATION', 'MARRIAGE', 'AGE',
                'PAY_0', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6',
                'BILL_AMT1','BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6',
                'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6']

# features = [  'LIMIT_BAL', 'SEX', 'EDUCATION', 'MARRIAGE', 'AGE' ]

train_df, test_df = train_test_split(df_credit, test_size=0.2, random_state=712)
X_train, y_train = train_df[features], train_df[target]
X_test, y_test = test_df[features], test_df[target]

# # with scale
sc = StandardScaler()
sc.fit(X_train)

X_train = sc.transform(X_train)
X_test = sc.transform(X_test)

svm_params = {
    "kernel":["linear", "rbf"],
    "C": [0.001, 0.01, 0.1, 1, 10]
}

# svm_params = {
#     "kernel":["linear"],
#     "C": [0.1]
# }

def model_param_curve_multi(grid_search_result_df, x_label, params, param_name, save_fig_name):

    x_range=params[param_name]
    x_label=x_label
    y_label="f1_micro"
    title="Default of Credit Card"

    linear_df = grid_search_result_df[svm_grid_search_df['param_kernel'].str.contains('linear')]
    rbf_df = grid_search_result_df[svm_grid_search_df['param_kernel'].str.contains('rbf')]

    linear_mean_train = linear_df["mean_train_score"]
    linear_mean_test = linear_df["mean_test_score"]
    linear_std_train = linear_df["std_train_score"]
    linear_std_test = linear_df["std_test_score"]

    rbf_mean_train = rbf_df["mean_train_score"]
    rbf_mean_test = rbf_df["mean_test_score"]
    rbf_std_train = rbf_df["std_train_score"]
    rbf_std_test = rbf_df["std_test_score"]

    #Plotting
    plt.grid()
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.title(title)

    plt.plot(x_range, linear_mean_train, marker='o', label='linear train', color=f"C{1}")
    plt.fill_between(x_range, linear_mean_train+linear_std_train,
            linear_mean_train-linear_std_train, color=f'C{1}', alpha=0.1)
    plt.plot(x_range, linear_mean_test, marker='o', label='linear valid', color=f"C{2}")
    plt.fill_between(x_range, linear_mean_test+linear_std_test,
             linear_mean_test-linear_std_test, color=f"C{2}", alpha=0.1)
    plt.plot(x_range, rbf_mean_train, marker='v', label='rbf train', color=f"C{3}")
    plt.fill_between(x_range, rbf_mean_train+rbf_std_train,
             rbf_mean_train-rbf_std_train, color=f"C{3}", alpha=0.1)
    plt.plot(x_range, rbf_mean_test, marker='v', label='rbf valid', color=f"C{4}")
    plt.fill_between(x_range, rbf_mean_test+rbf_std_test,
             rbf_mean_test-rbf_std_test, color=f"C{4}", alpha=0.1)

    plt.legend()
    plt.savefig(save_fig_name)
    plt.show()

# svm_clf = svm.SVC(random_state=seed, verbose=False)
# svm_grid_search = GridSearchCV(estimator=svm_clf, param_grid=svm_params,
#                            scoring='f1_micro', return_train_score=True,
#                            verbose=3, n_jobs=-1)
# svm_grid_search.fit(X_train, y_train)

# svm_grid_search.cv_results_.keys()
# svm_grid_search_df = pd.DataFrame(svm_grid_search.cv_results_)
# svm_grid_search_df.sort_values(by="rank_test_score")

# linear_df = svm_grid_search_df[svm_grid_search_df['param_kernel'].str.contains('linear')]
# rbf_df = svm_grid_search_df[svm_grid_search_df['param_kernel'].str.contains('rbf')]

# best_params = svm_grid_search_df["params"][np.argmax(svm_grid_search_df['mean_test_score'])]
# best_score = np.max(svm_grid_search_df['mean_test_score'])
# print(best_params)
# model_param_curve_multi(svm_grid_search_df, "C value", svm_params, "C", "svm_c.png")

best_svm_clf = svm.SVC(
    random_state=seed,
    C=1,
    kernel='rbf',
    verbose=True
)
best_svm_clf.fit(X_train, y_train)
learning_curve_plotter(best_svm_clf, X_train, y_train, save_name="svm_lr.png")
metrics(X_train, y_train, X_test, y_test, best_svm_clf)

# kernels = ["linear", "rbf"]
# C = [0.1,1,100,1000]

# tr_scores = np.zeros((len(C), len(kernels)))
# test_scores = np.zeros((len(C), len(kernels)))

# for i in range(len(C)):
#     for j in range(len(kernels)):
#         svm_clf = svm.SVC(C=C[i], kernel=kernels[j], random_state=seed, verbose=True)
#         svm_clf.fit(X_train, y_train)
#         tr_roc, tr_f1, test_roc, test_f1 = metrics(X_train, y_train, X_test, y_test, svm_clf)
#         tr_scores[i,j] = tr_f1
#         test_scores[i,j] = test_f1
#         print(f"tr_f1: {tr_f1}, test_f1: {test_f1}, C: {C[i]}, kernel: {kernels[j]}")


#! /usr/bin/env python
# -*- coding: utf-8 -*-

# name: Zhornichenko Ilya Alekseevich
# group: TMSS
# course: Image analysis

# Importing libs

import numpy as np
from PIL import Image
from PIL import ImageChops
import scipy as sc
import matplotlib.pyplot as plt
from scipy.fftpack import fft, fftshift, ifft
import random

#correectly resampled image
def padImage(img):
    N0, N1 = img.size
    lenDiag = int(np.ceil(np.sqrt(N0**2+N1**2)))
    imgPad = Image.new('L',(lenDiag, lenDiag))
    c0, c1 = int(round((lenDiag-N0)/2)), int(round((lenDiag-N1)/2))
    imgPad.paste(img, (c0,c1))
    return imgPad, c0, c1
# getting sinogramm
def getProj(img, theta):
    numAngles = len(theta)
    sinogram = np.zeros((img.size[0],numAngles))
    for n in range(numAngles):
        rotImgObj = img.rotate(90-theta[n], resample=Image.BICUBIC)
        sinogram[:,n] = np.sum(rotImgObj, axis=0)
    return sinogram

#ramp filter for sinogram
def rmp_filter(sino):
    a = 0.1
    projLen, numAngles = sino.shape
    step = 2*np.pi/projLen
    w = np.arange(-np.pi, np.pi, step)
    if len(w) < projLen:
        w = np.concatenate([w, [w[-1]+step]])

    rn1 = abs(2/a*np.sin(a*w/2));
    rn2 = np.sin(a*w/2)/(a*w/2);
    r = rn1*(rn2)**2;

    filt = fftshift(r)
    filtered_sinogram = np.zeros((projLen, numAngles))
    for i in range(numAngles):
        projfft = fft(sino[:,i])
        filtProj = projfft*filt
        filtered_sinogram[:,i] = np.real(ifft(filtProj))

    return filtered_sinogram
#fbp reconstruction algoritm
def backproject(sinogram, theta):

    imageLen = sinogram.shape[0]
    reconMatrix = np.zeros((imageLen, imageLen))

    x = np.arange(imageLen)-imageLen/2
    y = x.copy()
    X, Y = np.meshgrid(x, y)

    plt.ion()
    fig2, ax = plt.subplots()
    im = plt.imshow(reconMatrix, cmap='gray')

    theta = theta*np.pi/180
    numAngles = len(theta)

    for n in range(numAngles):
        Xrot = X*np.sin(theta[n])-Y*np.cos(theta[n])
        XrotCor = np.round(Xrot+imageLen/2)
        XrotCor = XrotCor.astype('int')
        projMatrix = np.zeros((imageLen, imageLen))
        m0, m1 = np.where((XrotCor >= 0) & (XrotCor <= (imageLen-1)))
        s = sinogram[:,n]
        projMatrix[m0, m1] = s[XrotCor[m0, m1]]
        reconMatrix += projMatrix
    plt.close()
    plt.ioff()
    backprojArray = np.flipud(reconMatrix)
    return backprojArray

def delimeter(ramp_filtered_sino, delimeter):
    ramp_filtered_sino[:,::delimeter] = 255
    return ramp_filtered_sino


import pandas as pd
import io
from collections import Counter

df = pd.read_csv('')

token = list(df['token'])

for i,v in enumerate(token):
  if len(v) < 2:
    token.pop(i)

countToken = Counter(token)
comList = countToken.most_common(30)
for v in comList:
  print(v)


from typing import List

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:

        if len(intervals) < 1:
            return intervals
        intervals.sort(key=lambda interval: interval[0])

        prev = intervals[0]
        result = []
        for i in range(1, len(intervals)):
            curr = intervals[i]
            if prev[1] >= curr[0]:
                prev = [min(prev[0], curr[0]), max(prev[1], curr[1])]
            else:
                result.append(prev)
                prev = curr

        result.append(prev)
        return result

intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]

s = Solution()
res = s.merge(intervals)
print(res)

intervals = [[1, 4], [0, 0]]

s = Solution()
res = s.merge(intervals)
print(res)


import numpy
import cPickle
import argparse
from config import *
import random
import re
import json
import logging
import os

logging.basicConfig(level = logging.DEBUG,
	                format = '[%(asctime)s %(levelname)s] %(message)s',
	                datefmt = '%d %b %H:%M:%S')

parser = argparse.ArgumentParser("generate vocabulary file and pickled corpus")
parser.add_argument('-c', '--config', help = 'path to config file')
parser.add_argument('-wd', '--withdict', action = "store_true", help = 'preprocess with existing vocabulary file')
parser.add_argument('-gr', '--fromgr', action = "store_true", help = 'transfer from Groundhog vocabulary file, must use with --wd')
parser.add_argument('-np', '--nopreprocess', action = "store_true", help = 'skip preprocessing')
parser.add_argument('-ns', '--noshuffle', action = "store_true", help = 'skip shuffling')

def preprocess(num, \
		       vocab_f, \
			   ivocab_f, \
			   input_f, \
			   output_f, \
			   data_vocab = 'cPickle', \
			   data_corpus = 'json', \
			   withdict = False, \
			   fromgr = False):
	'''
		Count the most frequent words in the training corpus.
		Then, generate the vocabulary file and index the corpus.

		:type vocab_f: string
		:param vocab_f: the path to vocabulary file

		:type ivocab_f: string
		:param ivocab_f: the path to vocabulary to index file

		:type input_f: string
		:param input_f: the path to corpus (text) file

		:type output_f: string
		:param output_f: the path to indexed corpus file

		:type withdict: bool
		:param withdict: if set to True, vocabulary will be loaded from existing file instead.
	'''
	if not withdict:
		logging.info('Building dictionary')
		input = open(input_f, 'r')
		line = input.readline()
		count = {}

		# building a dictionary
		while line != '':
			line = line.strip()
			words = re.split(' ', line)
			for word in words:
				if not count.has_key(word):
					count[word] = 1
				else:
					count[word] += 1

			line = input.readline()

		count_sort = sorted(count.items(), key=lambda x: x[1], reverse = True)
		vocab = ['<s>', 'UNK']
		ivocab = {'UNK': 1, '<s>': 0}
		vnum = 2
		while vnum < num:
			if vnum-2 >= len(count_sort):
				break
			vocab.append(count_sort[vnum - 2][0])
			ivocab[count_sort[vnum - 2][0]] = vnum
			vnum += 1

		with open(vocab_f, 'wb') as f:
			cPickle.dump(vocab, f)
		with open(ivocab_f, 'wb') as f:
			cPickle.dump(ivocab, f)

		input.close()
	else:
		logging.info('Loading dictionary')
		vocab_old = cPickle.load(open(vocab_f, 'rb'))
		ivocab_old = cPickle.load(open(ivocab_f, 'rb'))

		if fromgr:
			vocab = [0]*num
			for key in ivocab_old:
				vocab[key] = ivocab_old[key]
			vocab[0] = '<s>'

			ivocab = vocab_old
			if ivocab.has_key('</s>'):
				ivocab['<s>'] = ivocab['</s>']
				del ivocab['</s>']

			with open(vocab_f, 'wb') as f:
				cPickle.dump(vocab, f)
			with open(ivocab_f, 'wb') as f:
				cPickle.dump(ivocab, f)
		else:
			vocab = vocab_old
			ivocab = ivocab_old

	# indexing the corpus
	logging.info('Indexing the corpus')
	input = open(input_f, 'r')
	line = input.readline()
	corpora = []
	num_words = 0
	UNKs = 0
	num_sentences = 0
	while line != '':
		corpora.append([])
		line = line.strip()
		words = line.split(' ')
		for word in words:
			if not ivocab.has_key(word):
				corpora[num_sentences].append(1)
				UNKs += 1
			else:
				corpora[num_sentences].append(ivocab[word])
			num_words += 1
		num_sentences += 1
		line = input.readline()

	if not withdict:
		logging.info('%d unique words in %d sentences' % (len(count_sort), num_sentences))
		logging.info('Perserving %d words (including the UNK and empty symbols) and covering %2f of the words.' % (len(vocab), 100. * (num_words - UNKs) / num_words))
	if data_corpus == 'cPickle':
		with open(output_f, 'wb') as f:
			cPickle.dump(corpora, f)
	elif data_corpus == 'json':
		with open(output_f, 'wb') as f:
			json.dump(corpora, f)

def shuffle(src, trg, src_shuf, trg_shuf, data_corpus = 'json'):
	'''
		Randomly shuffling the parallel corpus

		:type src: string
		:param src: the path to indexed source corpus file

		:type trg: string
		:param trg: the path to indexed target corpus file

		:type src_shuf: string
		:param src_shuf: the path to shuffled indexed source corpus file

		:type trg_shuf: string
		:param trg_shuf: the path to shuffled indexed target corpus file
	'''

	# source
	logging.info('Loading source corpus')
	if data_corpus == 'cPickle':
		before_source = cPickle.load(open(src, 'rb'))
	elif data_corpus == 'json':
		before_source = json.load(open(src, 'rb'))
	length = len(before_source)
	logging.info('Total number of source sentences: %d' % length)

	idx = range(length)
	random.shuffle(idx)
	logging.info('Shuffling source corpus')
	after_source = []
	for i in range(len(idx)):
		if (i + 1) % 100000 == 0:
			logging.debug(str(i + 1))
		index = idx[i]
		after_source.append(before_source[index])

	logging.info('Dumping shuffled source corpus')

	if data_corpus == 'cPickle':
		with open(src_shuf, 'wb') as f:
			cPickle.dump(after_source, f)
			f.close()
	elif data_corpus == 'json':
		with open(src_shuf, 'wb') as f:
			json.dump(after_source, f)
			f.close()

	del before_source
	del after_source

	# target
	logging.info('Loading target corpus')
	if data_corpus == 'cPickle':
		before_target = cPickle.load(open(trg, 'rb'))
	elif data_corpus == 'json':
		before_target = json.load(open(trg, 'rb'))
	assert length == len(before_target)

	logging.info('Shuffling target corpus')
	after_target = []
	for i in range(len(idx)):
		if (i+1) % 100000 == 0:
			logging.debug(str(i+1))
		index = idx[i]
		after_target.append(before_target[index])

	logging.info('Dumping shuffled target corpus')

	if data_corpus == 'cPickle':
		with open(trg_shuf, 'wb') as f:
			cPickle.dump(after_target, f)
	elif data_corpus == 'json':
		with open(trg_shuf, 'wb') as f:
			json.dump(after_target, f)

def shuffle_mono(src, src_shuf, data_corpus = 'json'):
	'''
		Randomly shuffling the monolingual corpus.

		:type src: string
		:param src: the path to indexed corpus file

		:type src_shuf: string
		:param src_shuf: the path to indexed corpus file
	'''

	if data_corpus == 'cPickle':
		before_source = cPickle.load(open(src, 'rb'))
	elif data_corpus == 'json':
		before_source = json.load(open(src, 'rb'))
	length = len(before_source)

	idx = range(length)
	random.shuffle(idx)
	after_source = []
	for i in range(len(idx)):
		if (i + 1) % 100000 == 0:
			logging.debug(str(i + 1))
		index = idx[i]
		after_source.append(before_source[index])

	if data_corpus == 'cPickle':
		with open(src_shuf, 'wb') as f:
			cPickle.dump(after_source, f)
			f.close()
	elif data_corpus == 'json':
		with open(src_shuf, 'wb') as f:
			json.dump(after_source, f)
			f.close()

if __name__ == "__main__":
	args = parser.parse_args()

	#init config
	cfg = config()
	if args.config:
		cfg = update_config(cfg, load_config(open(args.config, 'r').read()))

	logging.info('STEP 1: Processing\n')
	if os.path.exists(cfg['src_shuf']) and os.path.exists(cfg['trg_shuf']):
		logging.info('File exists! Skipped.\n')
	else:
		if not args.nopreprocess:
			logging.info('STEP 1.1: Processing source corpus')
			preprocess(cfg['index_eos_src'],
					   cfg['vocab_src'],
					   cfg['ivocab_src'],
					   cfg['src_text'],
					   cfg['src'],
					   cfg['data_vocab'],
					   cfg['data_corpus'],
					   args.withdict,
					   args.fromgr)
			logging.info('Done!\n')
			logging.info('STEP 1.2: Processing target corpus')
			preprocess(cfg['index_eos_trg'],
				   	   cfg['vocab_trg'],
					   cfg['ivocab_trg'],
					   cfg['trg_text'],
					   cfg['trg'],
					   cfg['data_vocab'],
					   cfg['data_corpus'],
					   args.withdict,
					   args.fromgr)
			logging.info('Done!\n')

		if not args.noshuffle:
			logging.info('STEP 1.3: Shuffling')
			shuffle(cfg['src'],
				    cfg['trg'],
				    cfg['src_shuf'],
				    cfg['trg_shuf'],
				    cfg['data_corpus'])
			logging.info('Done!\n')

	if cfg['src_mono_shuf'] != '':
		if os.path.exists(cfg['src_mono_shuf']):
			logging.info('Monolingual source file exists! Skipped.\n')
		else:
			logging.info('STEP 1.4: Processing monolingual source corpus')
			preprocess(cfg['index_eos_src'],
					   cfg['vocab_src'],
					   cfg['ivocab_src'],
					   cfg['src_mono_text'],
					   cfg['src_mono'],
					   cfg['data_vocab'],
					   cfg['data_corpus'],
					   True,
					   args.fromgr)
			logging.info('Shuffling\n')
			shuffle_mono(cfg['src_mono'],
					     cfg['src_mono_shuf'],
					     cfg['data_corpus'])
			logging.info('Done!\n')
	if cfg['trg_mono_shuf'] != '':
		if os.path.exists(cfg['trg_mono_shuf']):
			logging.info('Monolingual target file exists! Skipped.\n')
		else:
			logging.info('STEP 1.5: Processing monolingual target corpus.')
			preprocess(cfg['index_eos_trg'],
				 	   cfg['vocab_trg'],
					   cfg['ivocab_trg'],
					   cfg['trg_mono_text'],
					   cfg['trg_mono'],
					   cfg['data_vocab'],
					   cfg['data_corpus'],
					   True,
					   args.fromgr)
			logging.info('Shuffling\n')
			shuffle_mono(cfg['trg_mono'],
					     cfg['trg_mono_shuf'],
					     cfg['data_corpus'])
			logging.info('Done!\n')


# Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
'''
>>> from class_ext import *

Ensure sanity:

    >>> x = X(42)
    >>> x_function(x)
    42

Demonstrate extraction in the presence of metaclass changes:

    >>> class MetaX(X.__class__):
    ...     def __new__(cls, *args):
    ...         return super(MetaX, cls).__new__(cls, *args)
    >>> class XPlusMetatype(X):
    ...     __metaclass__ = MetaX
    >>> x = XPlusMetatype(42)
    >>> x_function(x)
    42

'''

def run(args = None):
    import sys
    import doctest

    if args is not None:
        sys.argv = args
    return doctest.testmod(sys.modules.get(__name__))

if __name__ == '__main__':
    print("running...")
    import sys
    status = run()[0]
    if (status == 0): print("Done.")
    sys.exit(status)


from __future__ import unicode_literals

from django.db import models
from django.utils import timezone

# Create your models here.

class Movie(models.Model):
    uploader = models.ForeignKey("auth.User")
    title = models.CharField(max_length=200)
    desc = models.TextField()
    pic_url = models.TextField()
    m_type = models.IntegerField()
    quality = models.IntegerField()
    status = models.IntegerField()
    create_date = models.DateField(
        blank=True, null=True)
    publish_date = models.DateField(
        blank=True, null=True)

    def publish(self):
        self.publish_date = timezone.now()
        self.save()

    def __unicode__(self):
        return self.title


from .Extensions import PBinaryWriter
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.exceptions import InvalidSignature
from typing import List

class Ed25519Signature:
    def __init__(self, bytes=None):
        self.bytes = bytes
        self.kind = "Ed25519"  # assuming SignatureKind is an enum or similar in Python

    def verify(self, message: bytes, address) -> bool:
        return self.verify_multiple(message, [address])

    def verify_multiple(self, message: bytes, addresses: List) -> bool:
        for address in addresses:
            if not address.is_user:
                continue
            public_key_bytes = address.to_byte_array()[2:]
            public_key = ed25519.Ed25519PublicKey.from_public_bytes(public_key_bytes)
            try:
                public_key.verify(self.bytes, message)
                return True
            except InvalidSignature:
                continue
        return False

    def serialize_data(self, writer) -> None:
        writer.write_byte_array(self.bytes)

    def unserialize_data(self, reader) -> None:
        self.bytes = reader.read_byte_array()

    def to_byte_array(self) -> bytes:
        # Assuming PBinaryWriter is implemented in Python
        writer = PBinaryWriter()
        self.serialize_data(writer)
        return writer.to_bytes()

    @staticmethod
    def generate(keypair, message: bytes):
        private_key = ed25519.Ed25519PrivateKey.from_private_bytes(keypair.private_key)
        signature = private_key.sign(message)
        return Ed25519Signature(signature)


from python.build_schemas_resolvers.utils import parse_type
from python.classes import Attribute, Component, Schema

STRING_COMPONENT_OBJECT = Component('String', [Attribute('value', 'string', True)])
STRING_SCHEMA = Schema('_OBJECT_STRING', STRING_COMPONENT_OBJECT)

NUMBER_COMPONENT_OBJECT = Component('Number', [Attribute('value', 'number', True)])
NUMBER_SCHEMA = Schema('_OBJECT_NUMBER', NUMBER_COMPONENT_OBJECT)

BOOLEAN_COMPONENT_OBJECT = Component('Boolean', [Attribute('value', 'boolean', True)])
BOOLEAN_SCHEMA = Schema('_OBJECT_BOOLEAN', BOOLEAN_COMPONENT_OBJECT)

INTEGER_COMPONENT_OBJECT = Component('Integer', [Attribute('value', 'integer', True)])
INTEGER_SCHEMA = Schema('_OBJECT_INTEGER', INTEGER_COMPONENT_OBJECT)

def read_schemas(file_path: str) -> list[Schema]:

    """
    Read the schemas config file and return a list of schemas.

    :param file_path:
        The path of the config file.
    :return:
        A list of schemas.
    """

    schemas = []
    with open(file_path, 'r') as file:
        lines = file.read()
        posicion_inicio = lines.find('types:')
        posicion_fin = lines.find('\t{\n\n\n')
        contenido_deseado = lines[posicion_inicio + len('schemas:'):posicion_fin]
        first_schema = contenido_deseado.split('\t}\n\n')[:-1][0]

        list_schemas = contenido_deseado.split('\t}\n\n')[:-1]

        list_schemas[0] = '\t' + list_schemas[0]

        for schema in list_schemas:
            first_line = schema.splitlines()[0]
            if schema.startswith('\ttype'):
                name_component = first_line.split('type')[1].strip().replace('{', '').strip()
                type_schema = parse_type(name_component)
                atributes = []
                for line in schema.splitlines():
                    if  line.startswith('\t\t'):
                        name = line.split(':')[0].strip()
                        type = line.split(':')[1].strip()
                        items_type = None
                        required = False

                        if type.__contains__('!'):
                            required = True
                            type = type.replace('!', '').strip()

                        if type.__contains__('['):
                                items_type = parse_type(type.split('[')[1].split(']')[0])
                                type = 'array'
                        else:
                            type = parse_type(type)

                        atributes.append(Attribute(name = name, type = type, items_type = items_type, required = required))

                component = Component(name = name_component, attributes = atributes)
                schema = Schema(type = type_schema, component = component)
                schemas.append(schema)
            elif schema.startswith('\tinput'):
                name_component = first_line.split('input')[1].strip().replace('{', '').strip()
                name_component = name_component.replace('Input', '')
                type_schema = parse_type(name_component)
                atributes = []
                for line in schema.splitlines():
                    if line.startswith('\t\t'):
                        name = line.split(':')[0].strip()

                        type = line.split(':')[1].strip()
                        items_type = None
                        required = False

                        if type.__contains__('!'):
                            required = True
                            type = type.replace('!', '').strip()

                        if type.__contains__('['):
                            items_type = parse_type(type.split('[')[1].split(']')[0])
                            type = 'array'
                        else:
                            type = parse_type(type)

                        atributes.append(Attribute(name=name, type=type, items_type=items_type, required=required))

                component = Component(name=name_component, attributes=atributes)
                schema = Schema(type=type_schema, component=component)
                schemas.append(schema)

    return schemas

def search_schema(file_path: str, component_name:str) -> Schema:
    if component_name == 'String':
        return STRING_SCHEMA
    elif component_name == 'Number':
        return NUMBER_SCHEMA
    elif component_name == 'Boolean':
        return BOOLEAN_SCHEMA
    elif component_name == 'Integer':
        return INTEGER_SCHEMA
    schemas = read_schemas(file_path)
    type_array = False
    if component_name.__contains__('['):
        component_name = component_name.replace('[', '').replace(']', '')
        type_array = True

    for schema in schemas:
        if schema.component.name == component_name.strip():
            if type_array:
                schema.type = 'array'
            return schema


from selenium import webdriver
import time
from selenium.webdriver.common.by import By

class zapzapBot:
    def __init__(self):
        self.mensagem = "Salve Salve Familia"
        self. grupos = ["aaaa"]
        options = webdriver.ChromeOptions()
        options.add_argument('lang=pt-br')
        self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')

    def enviarMensagens(self):
        #aaaa
        #

        #
        self.driver.get('https://web.whatsapp.com/')
        time.sleep(30)

        for grupo in self.grupos:
            #grupo = self.driver.find_element_by_xpath(f"//span[@title='{grupo}']")
            grupo = self.driver.find_element(by=By.XPATH, valeu = f"//span[@title='{grupo}']")
            time.sleep(3)
            grupo.click()
            chat_box = self.driver.find_element_by_class_name('p3_M1')
            chat_box = self.driver.find_element(by=By.CLASS_NAME, valeu = 'p3_M1')
            time.sleep(3)
            chat_box.click()
            chat_box.send_keys(self.mensagem)
            #botao_enviar = self.driver.find_element_by_xpath("//span[@data-icon='send']")
            botao_enviar = self.driver.find_element(by=By.XPATH, valeu = "//span[@data-icon='send']")
            time.sleep(3)
            botao_enviar.click()
            time.sleep(5)

bot = zapzapBot()
bot.enviarMensagens()


from re import compile

from odoo import models, fields, _
from odoo.exceptions import ValidationError

class L10nLatamDocumentType(models.Model):
    _inherit = "l10n_latam.document.type"

    def _get_l10n_do_ncf_types(self):
        """Return a list of fiscal types and their respective sequence type to be used
        on sequences, journals and document types."""
        return [
            ("fiscal", "01"),
            ("consumer", "02"),
            ("debit_note", "03"),
            ("credit_note", "04"),
            ("informal", "11"),
            ("unique", "12"),
            ("minor", "13"),
            ("special", "14"),
            ("governmental", "15"),
            ("export", "16"),
            ("exterior", "17"),
            ("e-fiscal", "31"),
            ("e-consumer", "32"),
            ("e-debit_note", "33"),
            ("e-credit_note", "34"),
            ("e-informal", "41"),
            ("e-minor", "43"),
            ("e-special", "44"),
            ("e-governmental", "45"),
            ("e-export", "46"),
            ("e-exterior", "47"),
            ("in_fiscal", "01"),
        ]

    l10n_do_ncf_type = fields.Selection(
        selection="_get_l10n_do_ncf_types",
        string="NCF types",
        help="NCF types defined by the DGII that can be used to identify the"
        " documents presented to the government and that depends on the"
        " operation type, the responsibility of both the issuer and the"
        " receptor of the document",
    )
    internal_type = fields.Selection(
        selection_add=[
            ("in_invoice", "Supplier Invoices"),
            ("in_credit_note", "Supplier Credit Note"),
            ("in_debit_note", "Supplier Debit Note"),
        ]
    )
    is_vat_required = fields.Boolean(
        default=False,
    )

    def _get_document_sequence_vals(self, journal):
        """ Values to create the sequences """
        self.ensure_one()
        values = {'name': '%s - %s' % (journal.name, self.name), 'padding': 8, 'prefix': self.code, 'code': self.doc_code_prefix + '-' + journal.name}

        # values = super()._get_document_sequence_vals(journal)
        if self.country_id != self.env.ref("base.do"):
            return values

        values.update(
            {
                "padding": 10 if str(self.l10n_do_ncf_type).startswith("e-") else 8,
                "implementation": "no_gap",
                "prefix": self.doc_code_prefix,
                "l10n_latam_document_type_id": self.id,
                "l10n_latam_journal_id": journal.id,
            }
        )
        return values

    def _format_document_number(self, document_number):
        """Make validation of Import Dispatch Number
        * making validations on the document_number.
        * format the document_number against a pattern and return it
        """
        self.ensure_one()
        if self.country_id != self.env.ref("base.do"):
            return super()._format_document_number(document_number)

        if not document_number:
            return False

        # NCF/ECF validation regex
        # regex = (
        #     r"^((P?(?=.{11})B)|(?=.{13})E)%s(\d{8}|\d{10})$"
        #     % dict(self._get_l10n_do_ncf_types())[self.l10n_do_ncf_type]
        # )
        # pattern = compile(regex)

        # if not bool(pattern.match(document_number)):
        if document_number[0] not in ('B','E') or len(document_number) not in (11,13):
            raise ValidationError(
                _("NCF %s doesn't have the correct structure") % document_number
            )
        return document_number


#!/usr/bin/python3
import socket

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(("",9999))
data,addr=s.recvfrom(1024)
string_received=data.decode("utf-8")
print(string_received)
result=eval(string_received)
print(result)
result_bytes=str(result).encode("utf-8")
s.sendto(result_bytes,addr)


dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
apiurl = "https://example.com/pywebfinance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
certfile = None
threads = 4

banks = [ "bankofamerica",
          "citicards",
          "wellsfargo",
          "chase",
          "paypal",
          "gap",
          "fecu",
          "csvurl",
          "imap",
          "uesp",
          "janus",
          "fidelity",
          "vanguard"
        ]