# -*- coding: utf-8 -*-
"""
Sistema de Arquivos - Manipulação

"""
import os

#Descobrindo se um arqivo ou diretório exite
print(os.path.exists('arquivo.txt'))

#Somente criando arquivos - Forma 1
open('arquivo-teste.txt', 'w').close()

#Somente criando arquivos - Forma Correta
with open('arquivo-teste.txt', 'w') as arquivo:
    pass

#Somente criando arquivos - segunda maneira correta
os.mknod('arquivo.txt')

#Criar um diretório

os.mkdir('templates')

#Criando uma árvore de diretórios

os.makedirs('templates/geek/university')

#Renomear arquivos e diretórios

os.rename('templates2', 'geek2')
os.rename('geek2/novo2/outro2/teste.txt', 'geek2/novo2/outro2/geek.txt')

#Remover um arquivo
os.remove('geek.txt')

#Pegar o current directory
print(os.getcwd())

#Para mudar o diretório atual para outro
os.chdir('..')

#Identificar o meu sistema operacional
print(os.name())

#juntar meu diretório atual a outro
os.path.join(os.getcwd(), 'geek')

#listar os arquivos e diretórios
print(os.listdir())

#removendo diretórios vazios
os.rmdir('templates')

#removendo uma árvore de diretorios
for arquivo in os.scandir('geek2'):
    if arquivo.is_file():
        os.remove(arquivo.path)

#removendo uma árvore de diretórios vazios
os.removedirs('geek2/outro/mais')

#remover arquivos para lixeira, podendo restaura-los
from send2trash import send2trash

send2trash('cesta2.txt')

#Trabalhando com arquivos e diretórios temporários
#Cria um diretório na minha maquina temporariamente
#Utilizo o input pra segurar esse diretorio temporario
#Quando dou enter e saiu do input, o diretorio temporario se apaga
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    print(f'Criei o diretório temporário em {tmp}')
    with open(os.path.join(tmp, 'arquivo_temporario.txt'), 'w') as arq:
        arq.write('Geek University')
    input()

#Agora criando um arquivo temporário
with tempfile.TemporaryFile() as tmp:
    tmp.write(b'Geek University')
    #Esse 'b' converte essa string para binário, ou seja, bits (0 e 1)
    #Isso por que a gente só consegue escrever dados binários nesse
    #arquivo temporário.


# https://leetcode.com/problems/search-insert-position/
from typing import List

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        first = 0
        last = len(nums) - 1
        while first <= last:
            mid = (first + last) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                first = mid + 1
            else:
                last = mid - 1
        return first

if __name__ == "__main__":
    nums = [1, 3, 5, 6]
    target = 5
    print(Solution().searchInsert(nums, target))


from PIL import Image

import os

def resize_img(dir_path_og, dir_path_rs):

    img_list = os.listdir(dir_path_og)

    for img in img_list:
        im = Image.open(dir_path_og+img)

        width, height = im.size
        img_resized = im.resize((int(width*.68), height))
        img_resized.save(dir_path_rs+img)

if __name__=="__main__":
    resize_img("pictures/original/", "pictures/resized/")


from flipsyfat.cores.sd_emulator.linklayer import SDLinkLayer

from migen import *
from misoc.interconnect.csr import *
from misoc.interconnect.csr_eventmanager import *
from misoc.interconnect import wishbone

class SDEmulator(Module, AutoCSR):
    """Core for emulating SD card memory a block at a time,
       with reads and writes backed by software.
       """

    # Read and write buffers, each a single 512 byte block
    mem_size = 1024

    def _connect_event(self, ev, act, done):
        # Event triggered on 'act' positive edge, pulses 'done' on clear
        prev_act = Signal()
        self.sync += prev_act.eq(act)
        self.comb += ev.trigger.eq(act & ~prev_act)
        self.comb += done.eq(ev.clear)

    def __init__(self, platform, pads, **kwargs):
        self.submodules.ll = ClockDomainsRenamer("local")(SDLinkLayer(platform, pads, **kwargs))

        # Event interrupts and acknowledgment
        self.submodules.ev = EventManager()
        self.ev.read = EventSourcePulse()
        self.ev.write = EventSourcePulse()
        self.ev.finalize()
        self._connect_event(self.ev.read, self.ll.block_read_act, self.ll.block_read_go)
        self._connect_event(self.ev.write, self.ll.block_write_act, self.ll.block_write_done)

        # Wishbone access to SRAM buffers
        self.bus = wishbone.Interface()
        self.submodules.wb_rd_buffer = wishbone.SRAM(self.ll.rd_buffer, read_only=False)
        self.submodules.wb_wr_buffer = wishbone.SRAM(self.ll.wr_buffer, read_only=False)
        wb_slaves = [
            (lambda a: a[9] == 0, self.wb_rd_buffer.bus),
            (lambda a: a[9] == 1, self.wb_wr_buffer.bus)
        ]
        self.submodules.wb_decoder = wishbone.Decoder(self.bus, wb_slaves, register=True)

        # Local reset domain
        self._reset = CSRStorage()
        self.clock_domains.cd_local = ClockDomain()
        self.comb += self.cd_local.clk.eq(ClockSignal())
        self.comb += self.cd_local.rst.eq(ResetSignal() | self._reset.storage)

        # Current data operation
        self._read_act = CSRStatus()
        self._read_addr = CSRStatus(32)
        self._read_byteaddr = CSRStatus(32)
        self._read_num = CSRStatus(32)
        self._read_stop = CSRStatus()
        self._write_act = CSRStatus()
        self._write_addr = CSRStatus(32)
        self._write_byteaddr = CSRStatus(32)
        self._write_num = CSRStatus(32)
        self._preerase_num = CSRStatus(23)
        self._erase_start = CSRStatus(32)
        self._erase_end = CSRStatus(32)
        self.comb += [
            self._read_act.status.eq(self.ll.block_read_act),
            self._read_addr.status.eq(self.ll.block_read_addr),
            self._read_byteaddr.status.eq(self.ll.block_read_byteaddr),
            self._read_num.status.eq(self.ll.block_read_num),
            self._read_stop.status.eq(self.ll.block_read_stop),
            self._write_act.status.eq(self.ll.block_write_act),
            self._write_addr.status.eq(self.ll.block_write_addr),
            self._write_byteaddr.status.eq(self.ll.block_write_byteaddr),
            self._write_num.status.eq(self.ll.block_write_num),
            self._preerase_num.status.eq(self.ll.block_preerase_num),
            self._erase_start.status.eq(self.ll.block_erase_start),
            self._erase_end.status.eq(self.ll.block_erase_end),
        ]

        # Informational registers, not needed for data transfer
        self._info_bits = CSRStatus(16)
        self.comb += self._info_bits.status.eq(Cat(
            self.ll.mode_4bit,
            self.ll.mode_spi,
            self.ll.host_hc_support,
            Constant(False),             # Reserved bit 3
            Constant(False),             # Reserved bit 4
            Constant(False),             # Reserved bit 5
            Constant(False),             # Reserved bit 6
            Constant(False),             # Reserved bit 7
            self.ll.info_card_desel,
            self.ll.err_op_out_range,
            self.ll.err_unhandled_cmd,
            self.ll.err_cmd_crc,
        ))
        self._most_recent_cmd = CSRStatus(len(self.ll.cmd_in_cmd))
        self.comb += self._most_recent_cmd.status.eq(self.ll.cmd_in_cmd)
        self._card_status = CSRStatus(len(self.ll.card_status))
        self.comb += self._card_status.status.eq(self.ll.card_status)


import numpy as np
import pandas as pd

class AutoStringMapper:
    def __init__(self, from_column: any, to_column: any, ignore_case: bool = True) -> None:
        """
        Initiates an AutoStringMapper object with two string lists, series or
        np.arrays and creating a similarity matrix based on their string
        representations using the levenshtein distance. Use the get_mapping
        function of this object to then retrieve a mapping from it.

        Args:
            from_column (list, pandas.Series, np.ndarray): list of entries to
                map from
            to_column (list, pandas.Series, np.ndarray): list of entries to map
                to

        """
        from_column = self.clean_column(from_column, "from_column")
        to_column = self.clean_column(to_column, "to_column")

        unique_from_column = from_column.drop_duplicates().reset_index(drop=True)
        unique_to_column = to_column.drop_duplicates().reset_index(drop=True)

        len_from_column = unique_from_column.shape[0]
        len_to_column = unique_to_column.shape[0]

        maxlen_from_column = unique_from_column.str.len().max()
        maxlen_to_column = unique_to_column.str.len().max()

        (
            from_column_combinations,
            to_column_combinations,
        ) = self.create_combinations(unique_from_column, unique_to_column)

        if ignore_case:
            from_column_combinations = from_column_combinations.str.lower()
            to_column_combinations = to_column_combinations.str.lower()

        levenshtein_array = self.create_levenshtein_array(
            from_column_combinations,
            to_column_combinations,
            len_from_column,
            len_to_column,
            maxlen_from_column,
            maxlen_to_column,
        )

        self.distance_matrix = pd.DataFrame(
            levenshtein_array[:, maxlen_from_column - 1, maxlen_to_column - 1].reshape([len_to_column, len_from_column])
        )

        maxlen_matrix = self.create_maxlen_matrix(unique_from_column, unique_to_column)

        self.similarity_matrix = 1 - (self.distance_matrix / maxlen_matrix)

        self.similarity_matrix.index = unique_to_column.to_list()
        self.similarity_matrix.columns = unique_from_column.to_list()

    @staticmethod
    def determine_unused_row_name(index: pd.Index) -> str:
        """
        Searches and index for a suitable row name for the max column and
        creates one that is not in the index by appending.

        Args:
            index (pd.Index): index to be checked for the row name

        Returns:
            str: a row name that is not in the index

        """
        row_name = "max"
        while row_name in index:
            row_name += "max"
        return row_name

    @staticmethod
    def create_mapping(similarity_matrix: pd.DataFrame, max_row_name: str, similarity_threshold: float) -> tuple:
        """
        creats a mapping for a similarity matrix using a threshold and an unused row name

        Args:
            similarity_matrix (pd.DataFrame): similarity matrix to build the
                                              mapping on
            max_row_name (str): row name not used as a column
            similarity_threshold (float): minimum similarity in order to map

        Returns:
            tuple: tuple of the updated similarity_matrix (pd.DataFrame) and the
                   created mapping (pd.Series)

        """
        similarity_matrix.loc[max_row_name] = similarity_matrix.max(axis=0)

        similarity_matrix.sort_values(by=max_row_name, ascending=False, axis=1, inplace=True)

        similarity_matrix.drop([max_row_name], inplace=True)

        mapping = similarity_matrix.idxmax(axis=0)

        duplication_mask = mapping.duplicated(keep="first")

        similarity_threshold_mask = similarity_matrix.max(axis=0) < similarity_threshold

        net_mask = duplication_mask | similarity_threshold_mask

        mapping.mask(net_mask, np.nan, inplace=True)

        return mapping, similarity_matrix

    def clean_matrix(self, sub_similarity_matrix, sub_mapping, similarity_threshold=0):
        """
        Function clean the similarity matrix of columns and indices that are
        already in the mapping or that will never be in there as there best
        similarity is below the threshold

        Args:
            sub_similarity_matrix (pd.DataFrame): similarity matrix that needs
                to be cleaned
            sub_mapping (pd.Series): current version of the mapping with the
                values that are to be cleaned
            similarity_threshold (float): threshold which decides how
                similar two strings need to be in order to be included
                into the mapping and not as np.nan

        Returns:
            pd.DataFrame: updated similarity_matrix

        """
        for index, column in sub_mapping.iteritems():
            if not pd.isnull(column):

                sub_similarity_matrix.drop(columns=index, inplace=True)
                sub_similarity_matrix.drop(index=column, inplace=True)

        for column in sub_similarity_matrix.index[sub_similarity_matrix.max(axis=0) < similarity_threshold]:
            sub_similarity_matrix.drop(index=column, inplace=True)

        return sub_similarity_matrix

    def get_mapping(
        self,
        similarity_threshold: float = 0.0,
        relationship_type: str = "1:n",
        data_type: str = "dict",
    ) -> dict:
        """
        Function to retrieve a mapping using the similarity matrix

        Args:
            similarity_threshold (float): threshold which decides how
                similar two strings need to be in order to be included
                into the mapping and not as np.nan
            relationship_type (str): determines whether the mapping is a "1:n"
                / "one_to_many" or a "1:1" / "one_to_one" relationship
            data_type (str): determines whether the returned data type is a
                dict, a series or a data frame

        Returns:
            dict: dictionary with the mapping from the "from" to the "to" column

        Raises:
            ValueError: if similarity_threshold is not between 0 and 1 or if
                relationship_type is not "1:1" or "1:n" or if data_type is not
                "dict", "series" or "frame"

        """
        if similarity_threshold < 0.0 or similarity_threshold > 1.0:

            raise ValueError("Parameter similarity_threshold must be between 0 and 1")

        if relationship_type == "1:1" or relationship_type == "one_to_one":

            max_row_name = self.determine_unused_row_name(index=self.similarity_matrix.index)

            mapping, self.similarity_matrix = self.create_mapping(self.similarity_matrix, max_row_name, similarity_threshold)

            sub_similarity_matrix = self.similarity_matrix.copy()
            sub_mapping = mapping.copy()

            sub_similarity_matrix = self.clean_matrix(sub_similarity_matrix, sub_mapping, similarity_threshold)

            while sub_similarity_matrix.shape[0] != 0 and sub_similarity_matrix.shape[1] != 0:

                sub_mapping, sub_similarity_matrix = self.create_mapping(sub_similarity_matrix, max_row_name, similarity_threshold)

                mapping.fillna(sub_mapping, inplace=True)

                sub_similarity_matrix = self.clean_matrix(sub_similarity_matrix, sub_mapping)

        elif relationship_type == "1:n" or relationship_type == "one_to_many":

            mapping = self.similarity_matrix.idxmax(axis=0)

            similarity_threshold_mask = self.similarity_matrix.max(axis=0) < similarity_threshold

            mapping.mask(similarity_threshold_mask, np.nan, inplace=True)

        else:

            raise ValueError("Parameter relationship_type must be " "1:1" " or " "1:n" "")

        if data_type == "dict":

            return mapping.to_dict()

        elif data_type == "series":

            return mapping

        elif data_type == "frame":

            mapping = pd.DataFrame(mapping).reset_index()
            mapping.columns = ["from", "to"]
            return mapping

        else:
            raise ValueError("Parameter data_type must be " "dict" " or " "series" " or " "frame" "")

    @staticmethod
    def clean_column(column: any, column_name: str) -> pd.Series:
        """
        Cleans either of the from / to columns to be a pandas Series of type str.

        Args:
            column (list, pandas.Series, np.ndarray): column to be cleaned
            column_name (str): specifying whether this is the from or the to column

        Returns:
            pandas.Series: converted to type str

        Raises:
            ValueError: if not of any of the expected types

        """
        if type(column) == np.ndarray:
            column = pd.Series(column)
        elif type(column) == list:
            column = pd.Series(column)
        elif type(column) == pd.Series:
            pass
        else:
            raise ValueError(f"{column_name} not of type numpy.ndarray, pandas.Series or list")
        return column.astype(str)

    @staticmethod
    def create_combinations(from_column: pd.Series, to_column: pd.Series):
        """
        Creates all combinations of strings in the from column with all strings
        in the to column returning it as two pandas.Series to be interpreted
        together.

        Args:
            from_column (pandas.Series): column that is mapped from
            to_column (pandas.Series): column that is mapped to

        Returns:
            tuple: tuple including all the combinations with the from_column strings
                as the first entry and the to_column strings as the second
        """

        len_to_column = to_column.shape[0]
        len_from_column = from_column.shape[0]

        from_column_combinations = pd.Series(from_column.tolist() * len_to_column)

        to_column_combinations = []
        for element in to_column.tolist():
            list_element = [element] * len_from_column
            to_column_combinations = to_column_combinations + list_element

        to_column_combinations = pd.Series(to_column_combinations)

        return from_column_combinations, to_column_combinations

    @staticmethod
    def create_levenshtein_array(
        from_column: pd.Series,
        to_column: pd.Series,
        len_from_column: int,
        len_to_column: int,
        maxlen_from_column: int,
        maxlen_to_column: int,
    ) -> np.ndarray:
        """
        Creates a levenshtein matrix for alle from-to-string-combinations at the
        same time in a vectorized fashion.

        Args:
            from_column (pandas.Series): combinations of the from_column (needs
                to be read together with the to_column)
            to_column (pandas.Series): combinations of the to_column (needs to
                be read together with the from_column)
            len_from_column (int): number of elements in the from_column
            len_to_column (int): number of elements in the to_column
            maxlen_from_column (int): number of characters in the longest str
                of the from_column
            maxlen_to_column (int): number of characters in the longest str
                of the to_column

        Returns:
            np.ndarray: 3-dimensional array that includes the 2-dimensionl
            levenshtein array for alle from-to-string-combinations

        """

        levenshtein_array = np.zeros(
            [len_from_column * len_to_column, maxlen_from_column, maxlen_to_column],
            "int16",
        )

        for from_column_index in range(maxlen_from_column):
            for to_column_index in range(maxlen_to_column):

                if from_column_index == 0:

                    insertion = np.array([np.iinfo("int16").max] * len_from_column * len_to_column)

                else:

                    insertion = levenshtein_array[:, from_column_index - 1, to_column_index] + (
                        ~pd.isnull(from_column.str[from_column_index])
                    ).astype("int16")

                if to_column_index == 0:

                    deletion = np.array([np.iinfo("int16").max] * len_from_column * len_to_column)

                else:

                    deletion = levenshtein_array[:, from_column_index, to_column_index - 1] + (
                        ~pd.isnull(to_column.str[to_column_index])
                    ).astype("int16")

                if from_column_index == 0 or to_column_index == 0:

                    replacement = np.array([np.iinfo("int16").max] * len_from_column * len_to_column)

                    if from_column_index == 0 and to_column_index == 0:

                        comparison = from_column.str[from_column_index] != to_column.str[to_column_index]
                        replacement = comparison.astype("int16")

                else:

                    comparison = from_column.str[from_column_index] != to_column.str[to_column_index]
                    replacement = levenshtein_array[:, from_column_index - 1, to_column_index - 1] + comparison.astype("int16")

                levenshtein_array[:, from_column_index, to_column_index] = np.array([insertion, deletion, replacement]).min(axis=0)

        return levenshtein_array

    @staticmethod
    def create_maxlen_matrix(from_column: pd.Series, to_column: pd.Series) -> pd.DataFrame:
        """
        Creates a matrix which contains the maximum of the string lengths of all
        from-to-combination pairs.

        Args:
            from_column (pandas.Series): from_column strings
            to_column (pandas.Series): to_column strings

        Returns:
            pandas.DataFrame: matrix which contains the maximum length of the
                pairs

        """

        from_column_len = from_column.shape[0]
        to_column_len = to_column.shape[0]

        divisor_frame_from = pd.concat([from_column.str.len()] * to_column_len, axis=1).T

        # get rid of row and column index
        divisor_frame_from = divisor_frame_from.T.reset_index(drop=True).T
        divisor_frame_from.reset_index(drop=True, inplace=True)

        divisor_frame_to = pd.concat([to_column.str.len()] * from_column_len, axis=1)

        # get rid of row and column index
        divisor_frame_to = divisor_frame_to.T.reset_index(drop=True).T
        divisor_frame_to.reset_index(drop=True, inplace=True)

        maxlen_matrix = pd.concat([divisor_frame_from, divisor_frame_to]).groupby(level=0).max().astype("float64")

        return maxlen_matrix


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import roslib;
import rospy
import cv2

from geometry_msgs.msg import Twist, Vector3, Pose
from sensor_msgs.msg import LaserScan
from neato_node.msg import Bump
import numpy as np
import sys, select, termios, tty

msg = """

"""
maxSize = 250
res = (640,480)
obj_global = None
middleZone = 20;
Ylimit = 50;
delta= None
speed = 0.3;
turnSpeed = 2.5;
useLaser = True;
escanned = False
aborted = False
laserScan = [];
batidas = [];

def main(size, pos):
    print("main")
    wheel = [0,0]
    global delta
    if(aborted):
        print("bebe chutado")
        return;

    if(size > maxSize or pos[1] <= Ylimit):
        SendSpeed(wheel)
        return

    wheel = [speed,0]
    obgDist = pos[0] - (res[0] / 2)

    delta = -turnSpeed * (float(obgDist / (res[0] / 2)))

    wheel = [speed, delta]

    wheel = applyLaser(wheel)

    print(wheel)
    SendSpeed(wheel);
    print(delta)

def toggleLaser():
    global useLaser
    useLaser = not useLaser

def getMin(lista):
	minV = 10
	index = 0
	count = 0
	for i in lista:
		if (i < minV) and (i > 0.2):
			minV = i
			index = count
		count += 1
	return(minV,index)

def applyLaser(wheel):

    global laserScan

    if (escanned):
        laserScanlist = list(laserScan)
        temp = list(laserScan[330:])
        temp.extend(laserScan[:30])
        indexlist = []
        for i in range(len(temp)):
            if temp[i] < 0.25:
            	indexlist.append(i)

        for j in range(len(indexlist)):
            temp.pop(indexlist[-j -1])

        print(temp)

        print(indexlist, " IDEX LIST")
        meanRecon = np.mean(temp)

        pathRecon = list(laserScanlist[315:])
        pathRecon.extend(laserScanlist[:45])
        pathBack = list(laserScanlist[165:206])
        pathRight = list(laserScanlist[46:165])
        pathLeft = list(laserScanlist[206:315])

        lowerRecon = getMin(pathRecon)
        print(lowerRecon , " 00000000000000000000")
        lowerBack = getMin(pathBack)
        lowerRight = getMin(pathRight)
        lowerLeft = getMin(pathLeft)

        if(lowerRight[0] < 0.75 ):
            print("objeto a direita XXXXXXXXXXXXXXXX")
            print(lowerRight, " direita ");
            wheel[1] -= 1.5 * (0.75 - lowerRight[0])

        if(lowerLeft[0] < 0.75 ):
            wheel[1] += 1.5 * (0.75 - pathLeft[lowerLeft])
            print("objeto a esquerda XXXXXXXXXXXXXX")
            print(lowerLeft, " Left");

        if(lowerBack[0] < 0.5 ):
            print("correeee XXXXXXXXXXXXXXX")
            print(lowerBack, " Back ");
            wheel[0] += 1

        if(lowerRecon[0] < 1.5 and useLaser):
            print("EVADE PORRA")

            lower = lowerRecon[1]
            lower /= 45
            lower -= 1

            speed = 1
            speed *= (1.5 - lowerRecon[0])

            print(lowerRecon, " Recon")
            print(speed)
            wheel[1] -= speed
        print(meanRecon, 'media frontal')
        if(meanRecon < 0.6):
        	wheel = [0,0]
    return wheel

def SendSpeed(wheel):

    vel = Twist(Vector3(wheel[0],0,0),Vector3(0,0,wheel[1]))
    velocidadeFinal = rospy.Publisher("/cmd_vel", Twist, queue_size = 1)

    velocidadeFinal.publish(vel)

    #função que manda pro robo as velocidades de cada roda

def scaneou(laser):
    global laserScan
    global escanned
    laserScan = laser.ranges
    escanned = True

def bateu(bump_obj):
    global obj_global
    obj_global = bump_obj

def Survival():
    if(not aborted):
        #print(laserScan)

        if obj_global != None:
            if  obj_global.rightFront==1:
                print("Bateu frente direita")
                SendSpeed([-1,-3])
                Abort(1.5)
            elif  obj_global.leftFront==1 :
                print("Bateu frente esquerda")
                SendSpeed([-1,3])
                Abort(1.5)

def Abort(time):
    global aborted
    global obj_global
    aborted = True
    print("estou abortando")
    cv2.waitKey(1000)
    aborted = False
    print("Desabortei")
    #dar ré por um tempo e virar um pouco
    #aborted = False

def Search(right):
    if(aborted):
        print("bebe chutado")
        return;

    if(right):
        SendSpeed([0,-0.3])
    else:
        SendSpeed([0,0.3])


import sys
import re
from Spell import Spell
from Drain import Drain
from preprocessor import Preprocessor
from os import listdir
from os.path import isfile, join

class ParserError(Exception):
    pass

class LogParser:
    def __init__(self, root_dir, output_dir, config, extractor = "Drain"):
        self.config = config
        self.root_dir = root_dir
        self.output_dir = output_dir
        self.extractor = extractor

    def newExtractor(self):
        if self.extractor == "Drain":
            st         = 0.5  # Similarity threshold
            depth      = 4  # Depth of all leaf nodes
            return Drain.LogParser(outdir = self.output_dir, depth=depth, st=st)
        elif self.extractor == "Spell":
            tau = 0.3
            return Spell.LogParser(outdir = self.output_dir, tau=tau)
        else:
            raise ParserError(f"Unknown extractor type {self.extractor}")

    def load_data(self):
        for path_config in self.config["logs"]:
            logical_name = path_config["name"]
            print(f"Parsing {logical_name}...")
            full_path = join(self.root_dir, path_config["input_dir"])
            logfile_pattern = path_config["logfile_pattern"]
            regex = re.compile(f'^{logfile_pattern}$')
            files = [f for f in listdir(full_path) if isfile(join(full_path, f))]
            preprocessor = Preprocessor(directory = full_path, logformat = path_config["logformat"], rex=[])
            for file in files:
                match = regex.search(file)
                if regex.search(file):
                    full_file_path = join(full_path, file)
                    print(f"Preprocessing {full_file_path}...")
                    preprocessor.load_data(full_file_path)
            df_log = preprocessor.get_log_dataframe()
            extractor = self.newExtractor()
            extractor.parse(df_log)
            extractor.outputResult(df_log, extractor.logCluL, path_config["name"])


import numpy as np

# input = np.array([3, 4, 3, 1, 2])
input = np.genfromtxt('adventOfCode\\2021\\06data.txt', dtype=int, delimiter=',')

def lanternfishCounter(array):
	return np.sum(array)

def timeStep(array):
	extendedArray = np.concatenate((array, [0]))
	extendedArray[7] += extendedArray[0]
	extendedArray[9] += extendedArray[0]
	return extendedArray[1:]

if __name__ == '__main__':
	timerCounter = np.zeros(9)

	# initial state
	for num in input:
		timerCounter[num] += 1

	numOfDays = 256
	for t in range(1, numOfDays + 1):
		timerCounter = timeStep(timerCounter)

	print('day', numOfDays, timerCounter)
	print('number of lanternfish: ', int(lanternfishCounter(timerCounter)))


import functools
import torch.nn as nn

from .build import HEAD_REGISTRY

class MLP(nn.Module):

    def __init__(
        self,
        in_features=2048,
        hidden_layers=[],
        activation="relu",
        bn=True,
        dropout=0.0,
    ):
        super().__init__()
        if isinstance(hidden_layers, int):
            hidden_layers = [hidden_layers]

        assert len(hidden_layers) > 0
        self.out_features = hidden_layers[-1]

        mlp = []

        if activation == "relu":
            act_fn = functools.partial(nn.ReLU, inplace=True)
        elif activation == "leaky_relu":
            act_fn = functools.partial(nn.LeakyReLU, inplace=True)
        else:
            raise NotImplementedError

        for hidden_dim in hidden_layers:
            mlp += [nn.Linear(in_features, hidden_dim)]
            if bn:
                mlp += [nn.BatchNorm1d(hidden_dim)]
            mlp += [act_fn()]
            if dropout > 0:
                mlp += [nn.Dropout(dropout)]
            in_features = hidden_dim

        self.mlp = nn.Sequential(*mlp)

    def forward(self, x):
        return self.mlp(x)

@HEAD_REGISTRY.register()
def mlp(**kwargs):
    return MLP(**kwargs)


import sys
import subprocess as sp
from datetime import datetime

globalCwd = "/home/ubuntu/audios"

if len(sys.argv)>1 and isinstance(sys.argv[1], str):
    globalCwd = sys.argv[1]

def run(x, cwd=globalCwd):
    command="cd {cwd} && ".format(cwd=cwd)+x
    return sp.getoutput(command)

x = run('find -iname "*wav" -mmin -2880 -print')

audioFiles = x.split("\n")
if audioFiles[0] is "":
    print("folder "+globalCwd+" does not contain files older than 48 hours.")
    exit()

print(audioFiles)

[dd, mm, yyyy] = datetime.now().strftime("%d/%m/%Y %H:%M:%S").split(' ')[0].split('/')

for i in audioFiles:
    deletedTime=datetime.now().astimezone().replace(microsecond=0).isoformat()
    deletedFileName="deleted-files-"+dd+"-"+mm+"-"+yyyy+".log"
    createdTime=run("date --iso-8601=seconds -r "+i)
    run("echo "+i+" "+deletedTime+" "+createdTime+" >> "+deletedFileName, ".")
    run("rm "+i)


""" This code predicts the gdp rate and upemployment rate, we can see their is
negative correlation between both the parameters."""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
data = np.array(pd.read_csv(r'data.csv'))
#print(data)
unemp_rate = data[:-2,1]
gdp_rate1 = data[:-2,2]
#print(gdp_rate1)
n = len(gdp_rate1)
gdp_rate = gdp_rate1.reshape(n,1)
#print(gdp_rate)
lr = LinearRegression()
plt.plot(gdp_rate1, unemp_rate)
plt.show()
trained = lr.fit(gdp_rate, unemp_rate)
x = [[6.54],[-23.9]]
res = trained.predict(x)
print(res)
#g = list(res)
#plt.plot(gdp_rate1,res,'^')
#plt.show()


import math

import numpy as np
import paddle
import paddleaudio

def create_dct(n_mfcc: int, n_mels: int, norm: str = 'ortho'):
    n = paddle.arange(float(n_mels))
    k = paddle.arange(float(n_mfcc)).unsqueeze(1)
    dct = paddle.cos(math.pi / float(n_mels) * (n + 0.5) * k)  # size (n_mfcc, n_mels)
    if norm is None:
        dct *= 2.0
    else:
        assert norm == "ortho"
        dct[0] *= 1.0 / math.sqrt(2.0)
        dct *= math.sqrt(2.0 / float(n_mels))
    return dct.t()

def compute_mfcc(
        x: paddle.Tensor,
        sr: int = 16000,
        n_mels: int = 40,
        n_fft: int = 480,
        win_length: int = 480,
        hop_length: int = 160,
        f_min: float = 0.0,
        f_max: float = None,
        center: bool = False,
        top_db: float = 80.0,
        norm: str = 'ortho',
):
    fbank = paddleaudio.features.spectrum.MelSpectrogram(
        sr=sr,
        n_mels=n_mels,
        n_fft=n_fft,
        win_length=win_length,
        hop_length=hop_length,
        f_min=0.0,
        f_max=f_max,
        center=center)(x)  # waveforms batch ~ (B, T)
    log_fbank = paddleaudio.features.spectrum.power_to_db(fbank, top_db=top_db)
    dct_matrix = create_dct(n_mfcc=n_mels, n_mels=n_mels, norm=norm)
    mfcc = paddle.matmul(log_fbank.transpose((0, 2, 1)), dct_matrix).transpose((0, 2, 1))  # (B, n_mels, L)
    return mfcc


'''
7.2. Напишите функцию, которая с помощью deque проверяет,
является ли некоторая строка палиндромом (читается одинаково слева направо и справа налево).
'''

from deque import Deque

def find_polindrom(string):
    deq = Deque()

    for s in string:
        deq.addFront(s)

    while deq.size() > 1:
        if deq.removeFront() != deq.removeTail():
            return False

    return True

string = input("Введите строку: ")
string = ''.join(string.split()) #убираем пробелы и склеиваем символы
string = "".join(c for c in string if c not in ('!','.',':','?',',')) #убираем знаки препинания
string = string.lower() #приводим к нижнему регистру

if find_polindrom(string) == True:
    print("Это палиндром")
else:
    print("Это не палиндром")


class Employee:
    no_of_leaves=8

    def __init__(self ,aname,asalary,arole):
        self.name = aname
        self.salary = asalary
        self.role = arole

    def print_details(self):
        return f"The Name is {self.name} salary is {self.salary} role is {self.role}"

harry = Employee("Harry",500,"Instructor")

# rony = Employee()
# harry = Employee()
# harry.name = "Harry"
# harry.salary = 500
# harry.role = "Instructor"
#
# print(harry.print_details())
print(harry.name)


# Import this module to automatically setup path to local win32py module
# This module first tries to see if win32py module is installed via pip
# If it does then we don't do anything else
# Else we look up grand-parent folder to see if it has win32py folder
#    and if it does then we add that in sys.path

import os,sys,logging

#this class simply tries to see if airsim
class SetupPath:
    @staticmethod
    def getDirLevels(path):
        path_norm = os.path.normpath(path)
        return len(path_norm.split(os.sep))

    @staticmethod
    def getCurrentPath():
        cur_filepath = __file__
        return os.path.dirname(cur_filepath)

    @staticmethod
    def getGrandParentDir():
        cur_path = SetupPath.getCurrentPath()
        if SetupPath.getDirLevels(cur_path) >= 2:
            return os.path.dirname(os.path.dirname(cur_path))
        return ''

    @staticmethod
    def getParentDir():
        cur_path = SetupPath.getCurrentPath()
        if SetupPath.getDirLevels(cur_path) >= 1:
            return os.path.dirname(cur_path)
        return ''

    @staticmethod
    def addPyWin32Module():
        # if pywin32 module is installed then don't do anything else
        #    return

        parent = SetupPath.getParentDir()
        if parent !=  '':
            pywin32_path = os.path.join(parent, 'pywin32')
            client_path = os.path.join(pywin32_path, 'pythoncom.py')
            if os.path.exists(client_path):
                sys.path.insert(0, parent)
        else:
            logging.warning("pywin32 module not found in parent folder. Using installed package (pip install pywin32).")

    @staticmethod
    def addtwillModule():
        # if twill module is installed then don't do anything else
        #    return

        parent = SetupPath.getParentDir()
        if parent !=  '':
            twill_path = os.path.join(parent, 'twill-3.0.1')
            client_path = os.path.join(twill_path, 'setup.py')
            if os.path.exists(client_path):
                sys.path.insert(0, parent)
        else:
            logging.warning("twill module not found in parent folder. Using installed package (pip install twill).")

    @staticmethod
    def addpandasModule():
        # if pandas module is installed then don't do anything else
        #    return

        parent = SetupPath.getParentDir()
        if parent !=  '':
            pandas_path = os.path.join(parent, 'pandas-1.3.5')
            client_path = os.path.join(pandas_path, 'setup.py')
            if os.path.exists(client_path):
                sys.path.insert(0, parent)
        else:
            logging.warning("pandas module not found in parent folder. Using installed package (pip install pandas).")

    @staticmethod
    def addRequestsModule():
        # if requests module is installed then don't do anything else
        #    return

        parent = SetupPath.getParentDir()
        if parent !=  '':
            r_path = os.path.join(parent, 'requests-2.26.0')
            client_path = os.path.join(r_path, 'setup.py')
            if os.path.exists(client_path):
                sys.path.insert(0, parent)
        else:
            logging.warning("requests module not found in parent folder. Using installed package (pip install requests).")

    @staticmethod
    def addZipModule():
        # if zip module is installed then don't do anything else
        #    return

        parent = SetupPath.getParentDir()
        if parent !=  '':
            z_path = os.path.join(parent, 'zip-0.0.2')
            client_path = os.path.join(z_path, 'setup.py')
            if os.path.exists(client_path):
                sys.path.insert(0, parent)
        else:
            logging.warning("zip module not found in parent folder. Using installed package (pip install zip).")

    @staticmethod
    def addNumpyModule():
        # if numpy module is installed then don't do anything else
        #    return

        parent = SetupPath.getParentDir()
        if parent !=  '':
            numpy_path = os.path.join(parent, 'numpy-1.21.4')
            client_path = os.path.join(numpy_path, 'setup.py')
            if os.path.exists(client_path):
                sys.path.insert(0, parent)
        else:
            logging.warning("numpy module not found in parent folder. Using installed package (pip install numpy).")

    @staticmethod
    def addMatplotlibModule():
        # if matplotlib module is installed then don't do anything else
        #    return

        parent = SetupPath.getParentDir()
        if parent !=  '':
            mat_path = os.path.join(parent, 'matplotlib-3.5.1')
            client_path = os.path.join(mat_path, 'setup.py')
            if os.path.exists(client_path):
                sys.path.insert(0, parent)
        else:
            logging.warning("matplotlib module not found in parent folder. Using installed package (pip install matplotlib).")

SetupPath.addpandasModule()
SetupPath.addNumpyModule()
SetupPath.addMatplotlibModule()
SetupPath.addRequestsModule()
SetupPath.addZipModule()
SetupPath.addtwillModule()
SetupPath.addPyWin32Module()


#res model

import torch, random, scipy, math
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
import numpy as np
from atom3d.datasets import LMDBDataset
#import atom3d.datasets.ppi.neighbors as nb
from torch.utils.data import IterableDataset
from . import GVP, GVPConvLayer, LayerNorm
import torch_cluster, torch_geometric, torch_scatter
from .data import _normalize, _rbf

_NUM_ATOM_TYPES = 9
_element_mapping = lambda x: {
    'H' : 0,
    'C' : 1,
    'N' : 2,
    'O' : 3,
    'F' : 4,
    'S' : 5,
    'Cl': 6, 'CL': 6,
    'P' : 7
}.get(x, 8)
_amino_acids = lambda x: {
    'ALA': 0,
    'ARG': 1,
    'ASN': 2,
    'ASP': 3,
    'CYS': 4,
    'GLU': 5,
    'GLN': 6,
    'GLY': 7,
    'HIS': 8,
    'ILE': 9,
    'LEU': 10,
    'LYS': 11,
    'MET': 12,
    'PHE': 13,
    'PRO': 14,
    'SER': 15,
    'THR': 16,
    'TRP': 17,
    'TYR': 18,
    'VAL': 19
}.get(x, 20)
_DEFAULT_V_DIM = (100, 16)
_DEFAULT_E_DIM = (32, 1)

def _edge_features(coords, edge_index, D_max=4.5, num_rbf=16, device='cpu'):

    E_vectors = coords[edge_index[0]] - coords[edge_index[1]]
    rbf = _rbf(E_vectors.norm(dim=-1),
               D_max=D_max, D_count=num_rbf, device=device)

    edge_s = rbf
    edge_v = _normalize(E_vectors).unsqueeze(-2)

    edge_s, edge_v = map(torch.nan_to_num,
            (edge_s, edge_v))

    return edge_s, edge_v

class BaseTransform:
    '''
    Implementation of an ATOM3D Transform which featurizes the atomic
    coordinates in an ATOM3D dataframes into `torch_geometric.data.Data`
    graphs. This class should not be used directly; instead, use the
    task-specific transforms, which all extend BaseTransform. Node
    and edge features are as described in the EGNN manuscript.

    Returned graphs have the following attributes:
    -x          atomic coordinates, shape [n_nodes, 3]
    -atoms      numeric encoding of atomic identity, shape [n_nodes]
    -edge_index edge indices, shape [2, n_edges]
    -edge_s     edge scalar features, shape [n_edges, 16]
    -edge_v     edge scalar features, shape [n_edges, 1, 3]

    Subclasses of BaseTransform will produce graphs with additional
    attributes for the tasks-specific training labels, in addition
    to the above.

    All subclasses of BaseTransform directly inherit the BaseTransform
    constructor.

    :param edge_cutoff: distance cutoff to use when drawing edges
    :param num_rbf: number of radial bases to encode the distance on each edge
    :device: if "cuda", will do preprocessing on the GPU
    '''
    def __init__(self, edge_cutoff=4.5, num_rbf=16, device='cpu'):
        self.edge_cutoff = edge_cutoff
        self.num_rbf = num_rbf
        self.device = device

    def __call__(self, df):
        '''
        :param df: `pandas.DataFrame` of atomic coordinates
                    in the ATOM3D format

        :return: `torch_geometric.data.Data` structure graph
        '''
        with torch.no_grad():
            coords = torch.as_tensor(df[['x', 'y', 'z']].to_numpy(),
                                     dtype=torch.float32, device=self.device)
            atoms = torch.as_tensor(list(map(_element_mapping, df.element)),
                                            dtype=torch.long, device=self.device)

            edge_index = torch_cluster.radius_graph(coords, r=self.edge_cutoff)

            edge_s, edge_v = _edge_features(coords, edge_index,
                                D_max=self.edge_cutoff, num_rbf=self.num_rbf, device=self.device)

            return torch_geometric.data.Data(x=coords, atoms=atoms,
                        edge_index=edge_index, edge_s=edge_s, edge_v=edge_v)

class BaseModel(nn.Module):
    '''
    A base 5-layer GVP-GNN for all ATOM3D tasks, using GVPs with
    vector gating as described in the manuscript. Takes in atomic-level
    structure graphs of type `torch_geometric.data.Batch`
    and returns a single scalar.

    This class should not be used directly. Instead, please use the
    task-specific models which extend BaseModel. (Some of these classes
    may be aliases of BaseModel.)

    :param num_rbf: number of radial bases to use in the edge embedding
    '''
    def __init__(self, num_rbf=16):

        super().__init__()
        activations = (F.relu, None)

        self.embed = nn.Embedding(_NUM_ATOM_TYPES, _NUM_ATOM_TYPES)

        self.W_e = nn.Sequential(
            LayerNorm((num_rbf, 1)),
            GVP((num_rbf, 1), _DEFAULT_E_DIM,
                activations=(None, None), vector_gate=True)
        )

        self.W_v = nn.Sequential(
            LayerNorm((_NUM_ATOM_TYPES, 0)),
            GVP((_NUM_ATOM_TYPES, 0), _DEFAULT_V_DIM,
                activations=(None, None), vector_gate=True)
        )

        # define 5 gvp convlayers.
        self.layers = nn.ModuleList(
                GVPConvLayer(_DEFAULT_V_DIM, _DEFAULT_E_DIM,
                             activations=activations, vector_gate=True)
            for _ in range(5))

        ns, _ = _DEFAULT_V_DIM
        self.W_out = nn.Sequential(
            LayerNorm(_DEFAULT_V_DIM),
            GVP(_DEFAULT_V_DIM, (ns, 0),
                activations=activations, vector_gate=True)
        )

        self.dense = nn.Sequential(
            nn.Linear(ns, 2*ns), nn.ReLU(inplace=True),
            nn.Dropout(p=0.1),
            nn.Linear(2*ns, 1)
        )

    def forward(self, batch, scatter_mean=True, dense=True):
        '''
        Forward pass which can be adjusted based on task formulation.

        :param batch: `torch_geometric.data.Batch` with data attributes
                      as returned from a BaseTransform
        :param scatter_mean: if `True`, returns mean of final node embeddings
                             (for each graph), else, returns embeddings seperately
        :param dense: if `True`, applies final dense layer to reduce embedding
                      to a single scalar; else, returns the embedding
        '''
        h_V = self.embed(batch.atoms)
        h_E = (batch.edge_s, batch.edge_v)
        h_V = self.W_v(h_V)
        h_E = self.W_e(h_E)

        batch_id = batch.batch

        for layer in self.layers: # self.layers is the the moduleList of 5 gvpConvLayers
            h_V = layer(h_V, batch.edge_index, h_E)

        out = self.W_out(h_V)
        if scatter_mean: out = torch_scatter.scatter_mean(out, batch_id, dim=0)
        if dense: out = self.dense(out).squeeze(-1) # squeeze() removes dimensions of size 1, what does -1 mean?
        return out

class RESModel(BaseModel):
    '''
    GVP-GNN for the RES task.

    Extends BaseModel to output a 20-dim vector instead of a single
    scalar for each graph, which can be used as logits in 20-way
    classification.

    As noted in the manuscript, RESModel uses the final alpha
    carbon embeddings instead of the graph mean embedding.
    '''
    def __init__(self, **kwargs):
        super().__init__(**kwargs) # makes the child class inherit all proporties of parent class
        ns, _ = _DEFAULT_V_DIM
        self.dense = nn.Sequential( # this overwrites the self.dense defined in the basemodel to output 20 dimensions instead.
            nn.Linear(ns, 2*ns), nn.ReLU(inplace=True),
            nn.Dropout(p=0.1),
            nn.Linear(2*ns, 20)
        )
    def forward(self, batch):
        out = super().forward(batch, scatter_mean=False) # call the base model transformations.
        return out[batch.ca_idx+batch.ptr[:-1]]


import pygame
from pygame.sprite import Sprite

class Monter(Sprite):
    # True=>右   False=>左
    fleet_direction = 1

    def __init__(self, screen):
        print("产生一个外星怪物")
        super().__init__()
        self.screen = screen
        self.image = pygame.image.load(r'D:\git\pygame\PlayAJoke\Alien\images\monter.bmp')
        self.rect = self.image.get_rect()

        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        self.x = float(self.rect.x)

        self.alien_speed_factor = 0.5

    def blitme(self):
        self.screen.blit(self.image, self.rect)

    # 怪物是否碰到了边框
    def check_edges(self):
        screen_rect = self.screen.get_rect()
        if self.rect.right >= screen_rect.right:
            return True
        elif self.rect.left <= 0:
            return True

    def update(self):
        # print("更新怪物位置")
        # 可以向右移动
        # if self.fleet_direction==1:
        self.x += (self.alien_speed_factor * self.fleet_direction)
        print(self.x)
        self.rect.x = self.x
        print("向右")
        print(self.alien_speed_factor * self.fleet_direction)
        if self.check_edges()==True:
            print("到达边界")
            self.fleet_direction = -1


from math import log

def viterbi(obs, states, start_p, trans_p, emit_p):
	V = [{}]
	for st in states:
		V[0][st] = {"prob": start_p[st] + emit_p[st][obs[0]], "prev": None}
	# Run Viterbi when t > 0
	for t in range(1, len(obs)):
		V.append({})
		for st in states:
			max_tr_prob = max(V[t-1][prev_st]["prob"]+trans_p[prev_st][st] for prev_st in states)
			for prev_st in states:
				if V[t-1][prev_st]["prob"] + trans_p[prev_st][st] == max_tr_prob:
					max_prob = max_tr_prob + emit_p[st][obs[t]]
					V[t][st] = {"prob": max_prob, "prev": prev_st}
					break
	opt = []
	# The highest probability
	max_prob = max(value["prob"] for value in V[-1].values())
	previous = None
	# Get most probable state and its backtrack
	for st, data in V[-1].items():
		if data["prob"] == max_prob:
			opt.append(st)
			previous = st
			break
	# Follow the backtrack till the first observation
	for t in range(len(V) - 2, -1, -1):
		opt.insert(0, V[t + 1][previous]["prev"])
		previous = V[t + 1][previous]["prev"]

	return max_prob,opt

def splitwdtag(lin):
	wdl=[]
	tagl=[]
	for lu in lin:
		ind=lu.rfind("/")
		wdl.append(lu[:ind])
		tagl.append(lu[ind+1:])
	return wdl,tagl

def countfile(fname):
	states=set([])
	wds=set([])
	start_probability={}
	transition_probability={}
	emission_probability={}
	with open(fname) as frd:
		for line in frd:
			tmp=line.strip()
			if tmp:
				tmp=tmp.decode("utf-8")
				tmp=tmp.split("  ")
				wdl,tagl=splitwdtag(tmp)
				stag=tagl[0]
				if not stag in start_probability:
					start_probability[stag]=1
				else:
					start_probability[stag]+=1
				for i in xrange(len(wdl)-1):
					ctag=tagl[i]
					ntag=tagl[i+1]
					if not ctag in transition_probability:
						transition_probability[ctag]={}
					if not ntag in transition_probability[ctag]:
						transition_probability[ctag][ntag]=1
					else:
						transition_probability[ctag][ntag]+=1
					if not ctag in states:
						states.add(ctag)
					cword=wdl[i]
					if not cword in wds:
						wds.add(cword)
					if not ctag in emission_probability:
						emission_probability[ctag]={}
					if not cword in emission_probability[ctag]:
						emission_probability[ctag][cword]=1
					else:
						emission_probability[ctag][cword]+=1
				ctag=tagl[-1]
				cword=wdl[-1]
				if not cword in wds:
					wds.add(cword)
				if not ctag in states:
					states.add(ctag)
				if not ctag in emission_probability:
					emission_probability[ctag]={}
				if not cword in emission_probability[ctag]:
					emission_probability[ctag][cword]=1
				else:
					emission_probability[ctag][cword]+=1
	states=tuple(states)
	wds=tuple(wds)
	return states,norm(start_probability,states),transnorm(transition_probability,states),emisnorm(emission_probability,states,wds)

def norm(din,av):
	sum=0
	ndic={}
	for au in av:
		if au in din:
			tmp=din[au]+1
			sum+=tmp
			ndic[au]=tmp
		else:
			sum+=1
			ndic[au]=1
	sum=float(sum)
	rs={}
	for k,v in ndic.iteritems():
		rs[k]=log(v/sum)
	return rs

def emisnorm(d2in,sk,wk):
	rs={}
	awk=log(1/float(len(wk)))
	nvd={}
	for wu in wk:
		nvd[wu]=awk
	for au in sk:
		if au in d2in:
			rs[au]=norm(d2in[au],wk)
		else:
			rs[au]=nvd
	return rs

def transnorm(d2in,ak):
	rs={}
	aak=log(1/float(len(ak)))
	nvd={}
	for au in ak:
		nvd[au]=aak
	for au in ak:
		if au in d2in:
			rs[au]=norm(d2in[au],ak)
		else:
			rs[au]=nvd
	return rs

def runhmm(trainf,testfl,rsfl):
	states,start_probability,transition_probability,emission_probability=countfile(trainf)
	for i in xrange(len(testfl)):
		with open(rsfl[i],"w") as fwrt:
			with open(testfl[i]) as frd:
				for line in frd:
					tmp=line.strip()
					if tmp:
						tmp=tmp.decode("utf-8")
						wdl=tmp.split("  ")
						_,tagl=viterbi(tuple(wdl),states,start_probability,transition_probability,emission_probability)
						tmp=[]
						for ll in xrange(len(wdl)):
							tmp.append(wdl[ll]+"/"+tagl[ll])
						tmp="  ".join(tmp)+"\n"
						fwrt.write(tmp.encode("utf-8"))

if __name__=="__main__":
	tl=["dev","test"]
	runhmm("train.txt",[i+"wr.txt" for i in tl],[i+"rs.txt" for i in tl])


import enum
import math
import numpy as np

from shared.util.error_reporter import error_reporter as er
from shared.util.time_manager import time_manager as tm
from vehicle.skills.skills import Skill
from vehicle.skills.util import core
from vehicle.skills.util.motions import CableMotion
from vehicle.skills.util.motions import LookatMotion
from vehicle.skills.util.motions import OrbitMotion
from vehicle.skills.util.transform import Rot3
from vehicle.skills.util.transform import Transform
from vehicle.skills.util.ui import UiButton
from vehicle.skills.util.ui import UiSlider

class TourState(enum.Enum):
    # Wait for the user to start the tour
    SETUP = 0

    # Execute the tour
    GOTO = 1

    # Tapped STOP, quit the tour
    STOP = 5

class PropertyTour(Skill):
    """
    Create a simple tour based on the front door of a house
    and some basic size settings.
    """

    USER_SETTINGS = (
        UiSlider(
            identifier='speed',
            label='Speed',
            detail="Maximum R1 speed during motion.",
            units='m/s',
            min_value=0.1,
            max_value=8.0,
            value=6.0,
        ),
        UiSlider(
            identifier='width',
            label='Width',
            detail="The width of the house, assuming R1 is centered.",
            units='m',
            min_value=5,
            max_value=25,
            value=10,
        ),
        UiSlider(
            identifier='depth',
            label='Depth',
            detail="The depth of the house, assuming R1 is at one end.",
            units='m',
            min_value=0,
            max_value=50,
            value=15,
        ),
        UiSlider(
            identifier='height',
            label='Height',
            detail="Max altitude to fly.",
            units='m',
            min_value=5,
            max_value=30,
            value=15,
        ),
        UiSlider(
            identifier='radius',
            label='Radius',
            detail="Orbit radius",
            units='m',
            min_value=5,
            max_value=40,
            value=15,
        ),
    )

    def __init__(self):
        super(PropertyTour, self).__init__()
        self.state = TourState.SETUP
        self.has_subject = False
        self.publish_downsampler = tm.DownSampler(0.5)

        self.params = core.AttrDict()
        self.params.speed = 4.0
        self.params.min_turn_rate = 1  # [rad/update]
        self.params.max_turn_rate = 20  # [rad/update]
        self.params.distance_margin = 0.5  # [m]
        self.params.angle_margin = math.radians(0.75)  # [rad]
        self.params.giveup_utime = tm.seconds_to_utime(3)  # [s]
        self.params.giveup_speed = 0.1  # [m/s]

        self.motions = []
        self.motion_index = None

        # AR cache
        self.ar_frames = []  # list of Transforms for each cube in the frame(s)

    def allow_manual_control(self):
        return self.state in (TourState.STOP, TourState.SETUP)

    def button_pressed(self, api, button_id_pressed):
        if button_id_pressed == 'go':
            self.state = TourState.GOTO

            # Remember the current location.
            nav_T_cam = api.vehicle.get_camera_trans()

            yaw = nav_T_cam.get_euler_angles()[2]
            nav_T_cam_flat = Transform(
                rotation=Rot3.Ypr(yaw, 0, 0),
                translation=nav_T_cam.translation(),
            )

            width = self.get_value_for_user_setting('width')
            depth = self.get_value_for_user_setting('depth')
            height = self.get_value_for_user_setting('height')
            radius = self.get_value_for_user_setting('radius')

            # The first point is the home point.
            nav_T_start = nav_T_cam.copy()

            # Fly backward
            nav_T_back = Transform(
                rotation=nav_T_cam_flat.rotation(),
                translation=nav_T_cam_flat * np.array([-radius / 2, 0, 0]),
            )

            # Fly Up
            nav_T_top = Transform(
                rotation=Rot3.Ypr(yaw, math.radians(30), 0),
                translation=nav_T_cam_flat * np.array([-radius, 0, height])
            )

            # Fly over the house
            nav_T_over = Transform(
                rotation=nav_T_cam_flat.rotation(),
                translation=nav_T_cam_flat * np.array([depth, 0, height / 2]),
            )

            # Crane down
            nav_T_down = Transform(
                rotation=Rot3.Ypr(yaw, math.radians(88), 0),
                translation=nav_T_cam_flat * np.array([-radius / 4, 0, height]),
            )

            # Go left
            nav_T_left = Transform(
                rotation=nav_T_cam_flat.rotation(),
                translation=nav_T_cam_flat * np.array([-5, width / 2, 0]),
            )

            # Go Right
            nav_T_right = Transform(
                rotation=nav_T_cam_flat.rotation(),
                translation=nav_T_cam_flat * np.array([-5, -width / 2, 0]),
            )

            # The center of the house
            nav_T_lookat = Transform(
                rotation=nav_T_cam_flat.rotation(),
                translation=nav_T_cam_flat * np.array([depth / 2, 0, 0]),
            )

            self.motions = [
                # Cable backward as far as possible
                CableMotion(nav_T_start, nav_T_top, self.params),

                # Move while looking at the house
                LookatMotion(
                    start_point=nav_T_top * np.array([0, width, 0]),
                    end_point=nav_T_top * np.array([0, -width, 0]),
                    lookat_point=nav_T_lookat.translation(),
                    params=self.params,
                ),

                # Orbit around the property
                OrbitMotion(nav_T_lookat.translation(), radius, height, 1, self.params),

                # Fly down to the ground
                CableMotion(nav_T_top, nav_T_back, self.params),

                # Fly over the roof
                CableMotion(nav_T_back, nav_T_over, self.params),

                # Fly back and look down
                CableMotion(nav_T_over, nav_T_down, self.params),

                # Crane down to front door
                CableMotion(nav_T_down, nav_T_start, self.params),

                # Fly left
                CableMotion(nav_T_start, nav_T_left, self.params),

                # Fly right
                CableMotion(nav_T_left, nav_T_right, self.params),

                # Back to start
                CableMotion(nav_T_right, nav_T_start, self.params),

                # TODO:
                # Various panoramas in different spots
            ]
            self.motion_index = 0
            er.REPORT_STATUS("go pressed")

        elif button_id_pressed == 'skip':
            er.REPORT_STATUS("skip")
            self.motion_index += 1
            if self.motion_index >= len(self.motions):
                self.motion_index = 0

        if button_id_pressed == 'goto_cable':
            self.state = TourState.GOTO

        if button_id_pressed == 'stop':
            er.REPORT_STATUS('stopped')
            api.subject.cancel_subject_tracking(api.utime)
            self.state = TourState.STOP

    def get_motion(self):
        if self.motion_index is None or self.motion_index >= len(self.motions):
            return None
        return self.motions[self.motion_index]

    def update(self, api):
        # Stop tracking
        api.subject.cancel_subject_tracking(api.utime)

        # Update the speed dynamically, in case the user changes it
        self.params.speed = self.get_value_for_user_setting('speed')

        if self.allow_manual_control():
            api.phone.enable_movement_commands()
        else:
            api.phone.disable_movement_commands()

        if api.planner.is_landing():
            er.REPORT_STATUS("Exiting due to planner landing")
            api.skills.request_skill(api.utime, 'Basic')

        self.has_subject = api.subject.is_following_subject(api.utime)

        # Execute the current motion.
        if api.vehicle.get_pose():
            if self.state == TourState.GOTO:
                motion = self.get_motion()
                if motion:
                    motion.update(api)
                    if motion.done:
                        motion.reset(api)
                        er.REPORT_STATUS("motion done, index ++ {}", self.motion_index)
                        self.motion_index += 1
                    else:
                        er.REPORT_STATUS("motion in progress")
                else:
                    er.REPORT_STATUS("No more motions")
                    self.state = TourState.STOP
            else:
                er.REPORT_QUIET("Not active")
        else:
            er.REPORT_QUIET("Vehicle not ready")

        # Update the ui periodically
        if self.publish_downsampler.ready(api.utime):
            self.set_needs_layout()

    def get_onscreen_controls(self, api):
        title = ''
        detail_text = ''
        buttons = []
        show_stop = True
        controls_enabled = False
        targets_enabled = False
        show_slider = False
        promoted_control_id = ''
        battery_low_land = api.health_monitor.is_battery_critically_low()

        if battery_low_land:
            title = 'Low Battery'
            detail_text = 'Tour disabled'
            controls_enabled = True

        elif self.state == TourState.SETUP:
            title = 'Press Go to Begin Tour'
            detail_text = 'R1 will automatically film the area.'
            controls_enabled = True
            show_stop = False
            targets_enabled = False
            buttons.append(UiButton('go', 'Go', style='PRIMARY'))
            promoted_control_id = 'go'

        elif self.state == TourState.GOTO:
            title = 'Tour in Progress'
            detail_text = "Step {}".format(self.motion_index)
            show_slider = True
            targets_enabled = False
            buttons.append(UiButton('skip', label='Skip'))

        elif self.state == TourState.STOP:
            title = 'Press Go to Start New Tour'
            controls_enabled = True
            show_stop = False
            targets_enabled = False
            buttons.append(UiButton('go', 'Go', style='PRIMARY'))
            promoted_control_id = 'go'

        else:
            er.REPORT_WARNING('Unknown state "{}"'.format(self.state))

        return dict(
            title=title,
            detail=detail_text,
            arrows_enabled=controls_enabled,
            height_slider_enabled=controls_enabled,
            zoom_slider_enabled=controls_enabled and self.has_subject,
            steering_enabled=controls_enabled and not self.has_subject,
            tap_targets_enabled=targets_enabled,
            double_tap_enabled=controls_enabled,
            drag_enabled=controls_enabled,
            show_stop=show_stop,
            promoted_control='speed' if show_slider else promoted_control_id,
            buttons=buttons,
        )


import torch
from PIL import Image

class dataset(torch.utils.data.Dataset):
    def __init__(self,file_list,transform=None):
        self.file_list = file_list
        self.transform = transform
    def __len__(self):
        self.filelength = len(self.file_list)
        return self.filelength
    def __getitem__(self,idx):
        img_path = self.file_list[idx]
        img = Image.open(img_path)
        img_transformed = self.transform(img)
        label = img_path.split('/')[-1].split('.')[0]
        if label == 'train\\dog':
            label=1
        elif label == 'train\\cat':
            label=0
        return img_transformed,label


from django.urls import path

from . import views

urlpatterns = [
    path("", views.IndexView.as_view(), name="index"),
    path("entries/", views.EntryListView.as_view(), name="entries"),
    path("entry/<pk>", views.EntryDetailView.as_view(), name="entry"),
    path("create/", views.EntryCreateView.as_view(), name="entry-create"),
]


#!/usr/bin/python

import socket

host = '127.0.0.1'
port = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((host, port))
    s.listen()
    conn, addr = s.accept()

    with conn:
        print("Connected by ", addr)
        while True:

            print("Waiting for message!\n")
            data = conn.recv(1024)
            conn.sendall(data)

            str_data = data.decode('utf-8')

            if str_data == 'bye':
                print("Exiting")
                s.shutdown(socket.SHUT_RDWR)
                s.close()
                exit()


# -*- coding: utf-8 -*-
# @Time    : 2016-12-07 16:00
# @Author  : wzb<wangzhibin_x@foxmail.com>
import sched
import sys
import configparser
import binascii
import re
import sys
import time

from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QTextCursor, QRegExpValidator
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
from PyQt5 import QtCore,QtGui,QtWidgets
from gevent.corecext import SIGNAL
from threading import Timer
import logging

from ui_mainwindow import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow,QtWidgets.QDialog):
    config = configparser.ConfigParser()
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle('蓝牙测试工具V2.2')
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                            datefmt='%a, %d %b %Y %H:%M:%S',
                            filename='test.log',
                            filemode='w')
        self.init_config()

        self.btn_com.clicked.connect(self.btn_com_click)
        self.cb_rssi.stateChanged.connect(self.cb_rssi_state)
        self.cb_devname.stateChanged.connect(self.cb_devname_state)
        self.btn_conn_state.setStyleSheet('background-color:green')
        self.tv_last_snamac.setStyleSheet('color:green')
        self.btn_disconnect.clicked.connect(self.btn_disconnect_click)
        self.btn_next.clicked.connect(self.btn_next_click)
        self.tv_log.setFont(QtGui.QFont("Roman times",14))
        self.conn_info.setFont(QtGui.QFont("Roman times", 14))
        self.et_snmac.setFocus()
        self.et_snmac.setFont(QtGui.QFont("Roman times", 20))
        self.et_snmac.setFont(QtGui.QFont("Roman times", 20))
        self.tv_systime.setFont(QtGui.QFont("Roman times", 16))
        self.btn_next.setFont(QtGui.QFont("宋体", 20))
        self.et_snmac.textChanged.connect(self.snmac_change)
        regx = QRegExp("^Q{1}D{1}[0-9A-Z]{13}/{1}[0-9A-F]{12}$")
        validator = QRegExpValidator(regx, self.et_snmac)
        self.et_snmac.setValidator(validator)
        self.tv_last_snamac.setFont(QtGui.QFont("Roman times",20))
        self.init_com()
        self.reset_all_result()
        self.con_state_timer=QtCore.QTimer()
        self.con_state_timer.timeout.connect(self.update_con_state)
        self.con_state_counter=0
        self.con_state=False
        self.con_state_timer.start(200)
        self.init_ui()
        self.init_res()

    def init_res(self):
        pass

    def refresh_systime(self):
        systime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        self.tv_systime.setText(systime)

    def refresh_total_num(self):
        print('refresh_total_num')
        self.ln_total_num.display(self.write_ok_total_num)
        self.config.set('info', 'totalnum', str(self.write_ok_total_num))
        self.config.write(open('v.cfg', 'w'))

    def init_ui(self):
        self.btn_reset_total_num.clicked.connect(self.btn_reset_total_num_click)

    def init_com(self):
        self.com=QSerialPort()
        self.com.readyRead.connect(self.on_receiveData)

    def btn_reset_total_num_click(self):
        self.write_ok_total_num=0
        self.config.set('info', 'totalnum', str(self.write_ok_total_num))
        self.config.write(open('v.cfg', 'w'))
        self.ln_total_num.display(self.write_ok_total_num)

    def update_con_state(self):
        self.refresh_systime()
        if  self.con_state_counter <=2:
            self.con_state_counter+=1
            if self.con_state == False:
                self.btn_conn_state.setStyleSheet('background-color:red')
            else:
                self.btn_conn_state.setStyleSheet('background-color:green')
        else:
            self.con_state_counter = 0
            self.btn_conn_state.setStyleSheet('background-color:white ')

    def set_result(self,result):
        print('set_result:',result)
        if result == True:
            self.btn_result.setText('PASS')
            self.btn_result.setStyleSheet('background-color:green')
            self.write_ok_total_num+=1
            self.refresh_total_num()
        else:
            self.btn_result.setText('FAIL')
            self.btn_result.setStyleSheet('background-color:red')

    def reset_all_result(self):
        self.set_result(False)
        self.set_acc_result(False)
        self.set_gyr_result(False)
        self.set_cps_result(False)
        self.set_sn_result(False)
        self.set_mac_result(False)
        self.conn_info.setText('未连接')
        self.con_state=False
        self.sensor_re=False
        self.read_sensor_num=0
        self.write_snmac_flag = False
        self.sn_v=''
        self.mac_v=''
        self.acc_result=False
        self.gyr_result=False
        self.cps_result=False
        self.sn_result=False
        self.mac_result=False
        self.write_sn_state=False
        self.write_mac_state=False
        self.et_snmac.setEnabled(False)

    def set_acc_result(self,r):
        if r == True:
            self.btn_acc.setText('PASS')
            self.btn_acc.setStyleSheet('background-color:green')
        else:
            self.btn_acc.setText('FAIL')
            self.btn_acc.setStyleSheet('background-color:red')

    def set_gyr_result(self,r):
        if r == True:
            self.btn_gyr.setText('PASS')
            self.btn_gyr.setStyleSheet('background-color:green')
        else:
            self.btn_gyr.setText('FAIL')
            self.btn_gyr.setStyleSheet('background-color:red')

    def set_cps_result(self,r):
        if r == True:
            self.btn_cps.setText('PASS')
            self.btn_cps.setStyleSheet('background-color:green')
        else:
            self.btn_cps.setText('FAIL')
            self.btn_cps.setStyleSheet('background-color:red')

    def set_sn_result(self,r):
        if r == True:
            self.btn_sn.setText('PASS')
            self.btn_sn.setStyleSheet('background-color:green')
        else:
            self.btn_sn.setText('FAIL')
            self.btn_sn.setStyleSheet('background-color:red')

    def set_mac_result(self,r):
        if r == True:
            self.btn_mac.setText('PASS')
            self.btn_mac.setStyleSheet('background-color:green')
        else:
            self.btn_mac.setText('FAIL')
            self.btn_mac.setStyleSheet('background-color:red')

    def snmac_change(self):
        print('sn mac change')
        if self.write_snmac_flag == False:
            return
        snmac=self.et_snmac.text()
        if len(snmac) == 28:
            self.tv_last_snamac.clear()
            self.tv_last_snamac.setText(snmac)
            self.et_snmac.clear()
            self.et_snmac.setFocus(True)
            self.write_snmac()

    def write_snmac(self):
        print('write sn mac')
        snmac=self.tv_last_snamac.toPlainText()
        if len(snmac) != 28:
            QtWidgets.QMessageBox.critical(self, '严重错误', 'sn/mac 格式不正确')
            self.set_result(False)
            return

        sn=snmac[:15]
        print('sn='+sn)
        self.sn_v=sn
        self.write_sn(sn)
        mac=snmac[26:28]+snmac[24:26]+snmac[22:24]+snmac[20:22]+snmac[18:20]+snmac[16:18]
        print('mac='+mac)
        self.mac_v=mac

    def write_sn(self,sn):
        self.write_sn_state=True
        print('write sn:'+sn)
        self.tv_log.insertPlainText('write sn:' + sn + '\n')
        self.tv_log.moveCursor(QTextCursor.End)
        value='0bffffffff'+bytes.decode((binascii.b2a_hex(sn.encode())))
        self.send_data(value)

    def write_mac(self,mac):
        self.write_mac_state=True
        print('write mac:'+mac)
        self.tv_log.insertPlainText('write mac:' + mac + '\n')
        self.tv_log.moveCursor(QTextCursor.End)
        value='0affffffff'+mac
        self.send_data(value)

    def read_sensor(self):
        _data='aa1700c1'
        self.send_data(_data)
        self.read_sensor_num+=1

    def stop_sensor(self):
        _data='ff07'
        self.send_data(_data)

    def on_receiveData(self):
        try:
            '''将串口接收到的QByteArray格式数据转为bytes,并用gkb或utf8解码'''
            receivedData = bytes(self.com.readAll())
            print(receivedData)
        except:
            QtWidgets.QMessageBox.critical(self, '严重错误', '串口接收数据错误')

        if len(receivedData) > 0:
            str_receivedData = receivedData.decode('utf-8','ignore')
            if 'OK+LOST' in str_receivedData:
                print('ble disconnected')
                self.con_state = False
                self.conn_info.setText('未连接')
                #self.reset_all_result()

            print('re_mode:'+self.rw_flag)

            if self.rw_flag == 'HEXMODE':
                data = binascii.b2a_hex(receivedData).decode('ascii')
                self.tv_log.insertPlainText('receive:' + data+'\n')
                self.tv_log.moveCursor(QTextCursor.End)
                try:
                    self.parse_cmd(data)
                except Exception as e:
                    logging.exception(e)

            else:
                try:
                    self.parse_cmd(str_receivedData)
                except Exception as e:
                    logging.exception(e)
                self.tv_log.insertPlainText('receive:'+str_receivedData+'\n')
                self.tv_log.moveCursor(QTextCursor.End)

    def parse_cmd(self,cmd):

        print('parse_cmd: mode='+self.rw_flag)
        if self.rw_flag == 'SCAN':
            #if ',' in cmd:
            if cmd.count(',')>=2:
                device_id=cmd[:1]
                device_rssi='-60'
                device_name=''
                s=cmd.split(',')
                #print(s)
                if len(s)>=3:
                    device_rssi=s[1]
                    device_name=s[2]
                #for test
                #self.ble_reconnect()
                #return
                ###
                if self.cb_rssi.isChecked():
                    if int(device_rssi)<int(self.et_rssi.toPlainText()):
                        #print('rssi:'+device_rssi+'/'+self.et_rssi.toPlainText())
                        return
                if self.cb_devname.isChecked():
                    name=self.et_devname.toPlainText()
                    if  name in device_name== False:

                        #print('name:'+device_name+'/'+self.et_devname.toPlainText())
                        return
                self.ble_connect(device_id)
                return
            if 'Devices Found' in cmd:
                self.ble_scan()

        elif self.rw_flag == 'CONN':
            if 'OK+CONN' in cmd:
                self.conn_info.setText('已连接蓝牙设备')
                self.con_state=True

            elif 'Chars Found' in cmd:
                self.rw_flag='HEXMODE'
                self.read_sensor()

        elif self.rw_flag == 'HEXMODE':
            print('cmd:' + cmd)
            if cmd.startswith('aa9706') and len(cmd) == 6:
                #print('1111111111')
                self.tmp_sensor=cmd
                self.sensor_re=True
                return
            if self.sensor_re == True:
                if len(cmd)==40:
                    #print('3333333333')
                    self.sensor_re=False
                    result_sensor=self.tmp_sensor+cmd;
                    self.cal_sensor(result_sensor)
                    return
            if cmd.startswith('aa9706') and len(cmd)==46:
                #print('22222222')
                self.cal_sensor(cmd)
                return
            if cmd.startswith('ff07ff') and len(cmd)==6:
                self.tv_log.insertPlainText('stop sensor\n')
                self.tv_log.moveCursor(QTextCursor.End)
                self.write_snmac_flag=True
                self.et_snmac.setEnabled(True)
                self.et_snmac.clear()
                self.et_snmac.setFocus(True)
                return
            if cmd.startswith('0bff') and len(cmd)==36:
                re_sn=cmd[6:36]
                if re_sn == bytes.decode((binascii.b2a_hex(self.sn_v.encode()))):
                    self.set_sn_result(True)
                    self.sn_result=True
                else:
                    self.set_sn_result(False)
                    self.sn_result = False
                self.write_mac(self.mac_v)
                return
            if cmd.startswith('0aff') and len(cmd)==18:
                re_mac=cmd[6:18]
                if re_mac.lower()== self.mac_v.lower():
                    self.set_mac_result(True)
                    self.mac_result=True
                else:
                    self.set_mac_result(False)
                    self.mac_result=False

                if self.acc_result and self.gyr_result and self.cps_result and self.sn_result and self.mac_result:
                    self.set_result(True)
                else:
                    self.set_result(False)
                return

    def cal_sensor(self,cmd):
        for i in range(6, 30):
            #print('i=' + str(i) + 'v=' + cmd[i])
            if cmd[i] != '0':
                self.set_acc_result(True)
                self.acc_result = True
                break
        for i in range(30, 38):
            #print('i=' + str(i) + 'v=' + cmd[i])
            if cmd[i] != '0':
                self.set_gyr_result(True)
                self.gyr_result = True
                break
        for i in range(38, 46):
            #print('i=' + str(i) + 'v=' + cmd[i])
            if cmd[i] != '0':
                self.set_cps_result(True)
                self.cps_result = True
                break
        if self.read_sensor_num==1:
            self.tv_log.insertPlainText('第1次读取sensor:' + cmd+'\n')
            self.tv_log.insertPlainText('sleep 3s \n')
            self.tv_log.moveCursor(QTextCursor.End)
            time.sleep(3)
            self.read_sensor()
        elif self.read_sensor_num==2:
            self.tv_log.insertPlainText('第2次读取sensor:' + cmd+'\n')
            self.tv_log.moveCursor(QTextCursor.End)
            self.stop_sensor()

    def openSerial(self,com_id):

        self.com.setPortName('COM'+com_id)
        try:
            if self.com.open(QSerialPort.ReadWrite) == False:
                QtWidgets.QMessageBox.critical(self, '严重错误', '串口打开失败')
                return -1
        except:
            QtWidgets.QMessageBox.critical(self, '严重错误', '串口打开失败')
            return -1
        self.com.setBaudRate(115200)
        self.et_snmac.setFocus()
        return 0

    def send_data(self,data):
        if len(data) ==0:
            return

        if self.rw_flag == 'HEXMODE':
            print('send hex mode')
            print(data)
            s=data.replace(' ', '')
            try:
                hexData = binascii.a2b_hex(s)
            except:
                QtWidgets.QMessageBox.critical(self, '错误', '转换编码错误')
                return
            try:
                n = self.com.write(hexData)
                self.tv_log.insertPlainText('send:' + data + '\n')
                self.tv_log.moveCursor(QTextCursor.End)
            except:
                QtWidgets.QMessageBox.critical(self, '异常', '十六进制发送错误')
                return
        else:
            n = self.com.write(data.encode('utf-8', "ignore"))
            self.tv_log.insertPlainText('send:'+data+'\n')
            self.tv_log.moveCursor(QTextCursor.End)

    def init_config(self):
        self.config.read('v.cfg')

        com = self.config.get('info', 'com')
        self.et_com.setText(com)
        self.et_com.setFont(QtGui.QFont("Roman times", 20))
        rssi = self.config.get('info', 'rssi')
        self.et_rssi.setText(rssi)
        self.et_rssi.setFont(QtGui.QFont("Roman times", 20))
        devname = self.config.get('info', 'devname')
        self.et_devname.setText(devname)
        self.et_devname.setFont(QtGui.QFont("Roman times", 12))

        self.write_ok_total_num=self.config.getint('info','totalnum')
        self.ln_total_num.setDecMode()
        self.ln_total_num.setDigitCount(10)
        self.ln_total_num.display(self.write_ok_total_num)

    def btn_disconnect_click(self):

        self.ble_disconnect()

    def btn_next_click(self):
        self.et_snmac.setFocus()
        self.reset_all_result()
        self.ble_disconnect()
        self.com.flush()
        time.sleep(1)
        self.ble_scan()

    def cb_rssi_state(self,state):
        self.et_snmac.setFocus()
        if state == QtCore.Qt.Checked:
            self.et_rssi.setEnabled(False)
            rssi=self.et_rssi.toPlainText()
            self.config.set('info', 'rssi', rssi)
            self.config.write(open('v.cfg', 'w'))
        else:
            self.et_rssi.setEnabled(True)

    def cb_devname_state(self,state):
        self.et_snmac.setFocus()
        if state == QtCore.Qt.Checked:
            self.et_devname.setEnabled(False)
            devname=self.et_devname.toPlainText()
            self.config.set('info', 'devname', devname)
            self.config.write(open('v.cfg', 'w'))
        else:
            self.et_devname.setEnabled(True)

    def btn_com_click(self):
        com=self.et_com.toPlainText()
        if self.openSerial(com)!= -1:
            self.et_com.setEnabled(False)
            self.btn_com.setEnabled(False)
            print(com)
            self.config.set('info','com',com)
            self.config.write(open('v.cfg','w'))

    def ble_scan(self):
        self.rw_flag='SCAN'
        _cmd='AT+SCAN?'
        self.send_data(_cmd)
        self.conn_info.setText('BLE Scaning...')

    def ble_connect(self,id):
        self.rw_flag = 'CONN'
        _cmd='AT+CONN'+id
        self.send_data(_cmd)

    def ble_reconnect(self):
        self.rw_flag = 'CONN'
        _cmd='AT+CONNL'
        self.send_data(_cmd)

    def ble_disconnect(self):
        self.rw_flag= 'DISCON'
        _cmd='AT+DISCON'
        self.send_data(_cmd)

    def ble_send_end(self):
        self.rw_flag='SENDEND'
        _cmd="\r\n"
        self.send_data(_cmd)

    def ble_set_tx_uuid(self):
        _cmd='AT+CHTX10'
        self.send_data(_cmd)

    def ble_set_rx_uuid(self):
        _cmd='AT+CHRX11'
        self.send_data(_cmd)

    def ble_set_scan_time(self,time=5):
        _cmd='AT+SDUR'+time
        self.send_data(_cmd)

    def ble_set_baud(self,baud=115200):
        if baud==115200:
            id=4
        elif baud==9600:
            id=0
        elif baud==19200:
            id=1
        elif baud==38400:
            id=2
        elif baud==57600:
            id=3
        else:
            id=4
        _cmd='AT+BAUD'+id
        self.send_data(_cmd)

    def ble_reset(self):
        _cmd='AT+RESET'
        self.send_data(_cmd)

    def closeSerial(self):
        self.com.close()

    def __del__(self):
        print('del')
        self.closeSerial()
        if self.con_state_timer.isActive():
            self.con_state_timer.stop()

if __name__ == '__main__':
    app=QtWidgets.QApplication(sys.argv)
    mainWindow=MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())


"""Provides methods related to the Fast Fourier Transform.

.. _src-methods-fourier:
    https://github.com/hivebattery/gui/blob/master/driver/src/methods/fourier.py

"""
from __future__ import division
from __future__ import absolute_import

import numpy as np

def get_impedance(data_set, n_samples):
    """Calculate Impedance.

    Calculates the real and imaginary impedance given arrays of current and voltage data.

    Args:
        data_set (list of float): A list made up of voltage and current data produced by the EIS.
        n_samples (int): The number of samples.

    Returns:
        list of complex: The real and imaginary impedance.

    """
    k = len(data_set) // 2
    periods = k // n_samples

    voltage = data_set[:k]
    current = data_set[k:]

    n = len(voltage) - n_samples

    fft_data_voltage = (np.fft.fft(voltage[n_samples:]) / n)[:(n // 2)]
    fft_data_current = (np.fft.fft(current[n_samples:]) / n)[:(n // 2)]

    fft_voltage = [fft_data_voltage[0]]
    fft_curr = [fft_data_current[0]]

    for i in range(1, len(fft_data_voltage)):
        fft_voltage.append(fft_data_voltage[i] * 2)
        fft_curr.append(fft_data_current[i] * 2)

    target_voltage = fft_voltage[periods - 1]
    target_current = fft_curr[periods - 1]

    mag = np.abs(target_voltage) / np.abs(target_current)
    angle = np.angle(target_voltage) - np.angle(target_current)

    return mag * np.cos(angle) + 1j * mag * np.sin(angle)


import urllib

from oslo.config import cfg
import psutil

from stackalytics.openstack.common import log as logging
from stackalytics.processor import config
from stackalytics.processor import default_data_processor
from stackalytics.processor import lp
from stackalytics.processor import mls
from stackalytics.processor import rcs
from stackalytics.processor import record_processor
from stackalytics.processor import runtime_storage
from stackalytics.processor import utils
from stackalytics.processor import vcs

LOG = logging.getLogger(__name__)

def get_pids():
    uwsgi_dict = {}
    for pid in psutil.get_pid_list():
        try:
            p = psutil.Process(pid)
            if p.cmdline and p.cmdline[0].find('/uwsgi'):
                if p.parent:
                    uwsgi_dict[p.pid] = p.parent.pid
        except Exception as e:
            LOG.debug('Exception while iterating process list: %s', e)
            pass

    result = set()
    for pid in uwsgi_dict:
        if uwsgi_dict[pid] in uwsgi_dict:
            result.add(pid)

    return result

def update_pids(runtime_storage):
    pids = get_pids()
    if not pids:
        return
    runtime_storage.active_pids(pids)

def _merge_commits(original, new):
    if new['branches'] < original['branches']:
        return False
    else:
        original['branches'] |= new['branches']
        return True

def _record_typer(record_iterator, record_type):
    for record in record_iterator:
        record['record_type'] = record_type
        yield record

def process_repo(repo, runtime_storage_inst, record_processor_inst):
    uri = repo['uri']
    LOG.debug('Processing repo uri %s' % uri)

    bp_iterator = lp.log(repo)
    bp_iterator_typed = _record_typer(bp_iterator, 'bp')
    processed_bp_iterator = record_processor_inst.process(
        bp_iterator_typed)
    runtime_storage_inst.set_records(processed_bp_iterator,
                                     utils.merge_records)

    vcs_inst = vcs.get_vcs(repo, cfg.CONF.sources_root)
    vcs_inst.fetch()

    rcs_inst = rcs.get_rcs(repo, cfg.CONF.review_uri)
    rcs_inst.setup(key_filename=cfg.CONF.ssh_key_filename,
                   username=cfg.CONF.ssh_username)

    branches = set(['master'])
    for release in repo.get('releases'):
        if 'branch' in release:
            branches.add(release['branch'])

    for branch in branches:
        LOG.debug('Processing repo %s, branch %s', uri, branch)

        vcs_key = 'vcs:' + str(urllib.quote_plus(uri) + ':' + branch)
        last_id = runtime_storage_inst.get_by_key(vcs_key)

        commit_iterator = vcs_inst.log(branch, last_id)
        commit_iterator_typed = _record_typer(commit_iterator, 'commit')
        processed_commit_iterator = record_processor_inst.process(
            commit_iterator_typed)
        runtime_storage_inst.set_records(
            processed_commit_iterator, _merge_commits)

        last_id = vcs_inst.get_last_id(branch)
        runtime_storage_inst.set_by_key(vcs_key, last_id)

        LOG.debug('Processing reviews for repo %s, branch %s', uri, branch)

        rcs_key = 'rcs:' + str(urllib.quote_plus(uri) + ':' + branch)
        last_id = runtime_storage_inst.get_by_key(rcs_key)

        review_iterator = rcs_inst.log(branch, last_id)
        review_iterator_typed = _record_typer(review_iterator, 'review')
        processed_review_iterator = record_processor_inst.process(
            review_iterator_typed)
        runtime_storage_inst.set_records(processed_review_iterator,
                                         utils.merge_records)

        last_id = rcs_inst.get_last_id(branch)
        runtime_storage_inst.set_by_key(rcs_key, last_id)

def process_mail_list(uri, runtime_storage_inst, record_processor_inst):
    mail_iterator = mls.log(uri, runtime_storage_inst)
    mail_iterator_typed = _record_typer(mail_iterator, 'email')
    processed_mail_iterator = record_processor_inst.process(
        mail_iterator_typed)
    runtime_storage_inst.set_records(processed_mail_iterator)

def update_records(runtime_storage_inst):
    repos = utils.load_repos(runtime_storage_inst)
    record_processor_inst = record_processor.RecordProcessor(
        runtime_storage_inst)

    for repo in repos:
        process_repo(repo, runtime_storage_inst, record_processor_inst)

    mail_lists = runtime_storage_inst.get_by_key('mail_lists') or []
    for mail_list in mail_lists:
        process_mail_list(mail_list, runtime_storage_inst,
                          record_processor_inst)

    record_processor_inst.finalize()

def apply_corrections(uri, runtime_storage_inst):
    LOG.info('Applying corrections from uri %s', uri)
    corrections = utils.read_json_from_uri(uri)
    if not corrections:
        LOG.error('Unable to read corrections from uri: %s', uri)
        return

    valid_corrections = []
    for c in corrections['corrections']:
        if 'primary_key' in c:
            valid_corrections.append(c)
        else:
            LOG.warn('Correction misses primary key: %s', c)
    runtime_storage_inst.apply_corrections(valid_corrections)

def main():
    # init conf and logging
    conf = cfg.CONF
    conf.register_cli_opts(config.OPTS)
    conf.register_opts(config.OPTS)
    conf()

    logging.setup('stackalytics')
    LOG.info('Logging enabled')

    runtime_storage_inst = runtime_storage.get_runtime_storage(
        cfg.CONF.runtime_storage_uri)

    default_data = utils.read_json_from_uri(cfg.CONF.default_data_uri)
    if not default_data:
        LOG.critical('Unable to load default data')
        return not 0
    default_data_processor.process(runtime_storage_inst,
                                   default_data,
                                   cfg.CONF.sources_root,
                                   cfg.CONF.force_update)

    update_pids(runtime_storage_inst)

    update_records(runtime_storage_inst)

    apply_corrections(cfg.CONF.corrections_uri, runtime_storage_inst)

if __name__ == '__main__':
    main()


maior = homens = mulheres = 0
c = 1
opcao = 'S'
while True:
    if opcao == 'S':
        idade = int(input(f'Digite a idade da {c} pessoa: '))
        sexo = str(input(f'Digite o sexo da {c} pessoa: [M/F] ' )).strip().upper()[0]
        c += 1
        if idade >= 18:
            maior += 1
        if sexo == 'M':
            homens += 1
        if sexo == 'F':
            if idade <= 20:
                mulheres += 1
        while True:
            opcao = str(input('Você deseja continuar? S/N ')).strip().upper()[0]
            if opcao in 'SN':
                break
    else:
        break
print(f'O número de pessoas com mais de 18 anos é {maior}')
print(f'O número de homens ccadastrados é {homens}')
print(f'O número de mulheres com menos de 20 anos é {mulheres}')


"""add sended cullumn for telegram bot

Revision ID: 285dc64949f2
Revises: 891b92b56514
Create Date: 2021-08-03 23:47:08.957433

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '285dc64949f2'
down_revision = '891b92b56514'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('news', sa.Column('sended', sa.String(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('news', 'sended')
    # ### end Alembic commands ###


# coding: utf-8
import importlib
import json

import logging
import six

def import_module(val, raise_exception=True):
    """
    Attempt to import a class from a string representation.
    copied from: djang_rest_framework
            (https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/settings.py#L169)

    modified to raise exception by default

    Args:
        raise_exception: boolean to declare if method should return None or raise exception
        val: string representation of a class to import
    """
    try:
        parts = val.split('.')
        module_path, class_name = '.'.join(parts[:-1]), parts[-1]
        module = importlib.import_module(module_path)
        return getattr(module, class_name)
    except (ImportError, AttributeError) as e:
        msg = "Could not import '%s'. %s: %s." % (val, e.__class__.__name__, e)
        logging.warning(ImportError(msg))
        if raise_exception:
            raise ImportError(msg)
    return None

def clean_params(params, drop_nones=True, recursive=True):
    """Clean up a dict of API parameters to be sent to the Coinbase API.
    Some endpoints require boolean options to be represented as integers. By
    default, will remove all keys whose value is None, so that they will not be
    sent to the API endpoint at all.
    """
    cleaned = {}
    for key, value in six.iteritems(params):
        if drop_nones and value is None:
            continue
        if recursive and isinstance(value, dict):
            value = clean_params(value, drop_nones, recursive)
        cleaned[key] = value
    return cleaned

def encode_params(params, **kwargs):
    """Clean and JSON-encode a dict of parameters."""
    cleaned = clean_params(params, **kwargs)
    return json.dumps(cleaned)

def new_api_object(client, obj, cls=None, **kwargs):
    if isinstance(obj, dict):
        if not cls:
            resource = obj.get('resource', None)
            cls = _resource_to_model.get(resource, None)
        if not cls:
            obj_keys = set(six.iterkeys(obj))
            for keys, model in six.iteritems(_obj_keys_to_model):
                if keys <= obj_keys:
                    cls = model
                    break
        cls = cls or APIObject
        result = cls(client, **kwargs)
        for k, v in six.iteritems(obj):
            result[k] = new_api_object(client, v)
        return result
    if isinstance(obj, list):
        return [new_api_object(client, v, cls) for v in obj]
    return obj

class APIObject(dict):
    """Generic class used to represent a JSON response from the Coinbase API.
    If you're a consumer of the API, you shouldn't be using this class directly.
    This exists to make it easier to consume our API by allowing dot-notation
    access to the responses, as well as automatically parsing the responses into
    the appropriate Python models.
    """
    __api_client = None
    __response = None
    __pagination = None
    __warnings = None

    def __init__(self, api_client, response=None, pagination=None, warnings=None):
        self.__api_client = api_client
        self.__response = response
        self.__pagination = pagination
        self.__warnings = warnings

    @property
    def api_client(self):
        return self.__api_client

    @property
    def response(self):
        return self.__response

    @property
    def warnings(self):
        return self.__warnings

    @property
    def pagination(self):
        return self.__pagination

    def refresh(self, **params):
        url = getattr(self, 'resource_path', None)
        if not url:
            raise ValueError("Unable to refresh: missing 'resource_path' attribute.")
        response = self.api_client._get(url, data=params)
        data = self.api_client._make_api_object(response, type(self))
        self.update(data)
        return data

    # The following three method definitions allow dot-notation access to member
    # objects for convenience.
    def __getattr__(self, *args, **kwargs):
        try:
            return dict.__getitem__(self, *args, **kwargs)
        except KeyError as key_error:
            attribute_error = AttributeError(*key_error.args)
            attribute_error.message = key_error.message
            raise attribute_error

    def __delattr__(self, *args, **kwargs):
        try:
            return dict.__delitem__(self, *args, **kwargs)
        except KeyError as key_error:
            attribute_error = AttributeError(*key_error.args)
            attribute_error.message = key_error.message
            raise attribute_error

    def __setattr__(self, key, value):
        # All attributes that start with '_' will not be accessible via item-getter
        # syntax, which means that they won't be included in conversion to a
        # vanilla dict, which means that APIObjects can be treated as equivalent to
        # dicts. This is nice because it allows direct JSON-serialization of any
        # APIObject.
        if key.startswith('_') or key in self.__dict__:
            return dict.__setattr__(self, key, value)
        return dict.__setitem__(self, key, value)

    # When an API response includes multiple items, allow direct accessing that
    # data instead of forcing additional attribute access. This works for
    # slicing and index reference only.
    def __getitem__(self, key):
        data = getattr(self, 'data', None)
        if isinstance(data, list) and isinstance(key, (int, slice)):
            return data[key]
        return dict.__getitem__(self, key)

    def __dir__(self):  # pragma: no cover
        # This makes tab completion work in interactive shells like IPython for all
        # attributes, items, and methods.
        return list(self.keys())

    def __str__(self):
        try:
            return json.dumps(self, sort_keys=True, indent=2)
        except TypeError:
            return '(invalid JSON)'

    def __name__(self):
        return '<{0} @ {1}>'.format(type(self).__name__, hex(id(self)))  # pragma: no cover

    def __repr__(self):
        return '{0} {1}'.format(self.__name__(), str(self))  # pragma: no cover

class Money(APIObject):
    def __str__(self):
        currency_str = '%s %s' % (self.currency, self.amount)
        # Some API responses return mappings that look like Money objects (with
        # 'amount' and 'currency' keys) but with additional information. In those
        # cases, the string representation also includes a full dump of the keys of
        # the object.
        if set(dir(self)) > set(('amount', 'currency')):
            return '{0} {1}'.format(
                currency_str, json.dumps(self, sort_keys=True, indent=2))
        return currency_str

_resource_to_model = {

}

_obj_keys_to_model = {
    frozenset(('amount', 'currency')): Money,
}