from jogador import Jogador
from baralho import Baralho
from descarte import Descarte
from trinca import Trinca
from carta import Carta

class Mesa:
    def __init__(self):
        self.local_player = Jogador()
        self.remote_player = Jogador()

        # self.local_player.initialize(1, "local_player", "local_player")
        # self.remote_player.initialize(2, "remote_player", "remote_player")

        self.trincas = []

        self.match_status = 1
        self.baralho = None
        self.descarte = Descarte()

    def get_turn_player(self):
        if self.local_player.vez_jogada == True:
            return self.local_player
        else:
            return self.remote_player

    def get_card_amount(self):
        j_atual = self.get_turn_player()
        n = len(j_atual.cartas)
        return n

    def swap_turn(self):
        if self.getStatus() == 3:
            self.match_status = 2
        else:
            self.match_status = 3
        self.local_player.toggle_turn()
        self.remote_player.toggle_turn()

    def start_match(self, players, local_player_id):
        # self.baralho = Baralho()
        # self.descarte = Descarte()
        # self.local_player.reset()
        # self.remote_player.reset()
        self.local_player.initialize(1, players[0][1], players[0][0])
        self.remote_player.initialize(2, players[1][1], players[1][0])
        if players[0][2] == "1":
            self.local_player.toggle_turn()
            self.match_status = 2  #    waiting piece or origin selection (first action)
        else:
            self.remote_player.toggle_turn()
            self.match_status = 3  #    waiting remote action
        print("HERE!")

    def receive_start_match(self, players, local_player_id):
        # self.baralho = Baralho()
        # self.descarte = Descarte()
        # self.local_player.reset()
        # self.remote_player.reset()
        self.remote_player.initialize(1, players[0][1], players[0][0])
        self.local_player.initialize(2, players[1][1], players[1][0])
        if players[0][2] == "1":
            self.remote_player.toggle_turn()
            self.match_status = 2  #    waiting remote action
        else:
            self.local_player.toggle_turn()
            self.match_status = 3
        print("HERE RECEIVE!")

    def getStatus(self):
        return self.match_status

    def checa_fim_jogo(self):
        return len(self.remote_player.getTrincas()) == 3 or len(self.local_player.getTrincas()) == 3

    def receive_move(self,a_move):
        if self.baralho == None:
            print("receive baralho")
            self.baralho = Baralho()
            #print(a_move["baralho"])
            self.baralho.set_cards(self.getBaralhoFromDict(a_move["baralho"]))
            self.local_player.setCartas(self.getMaoFromCartas(a_move["j2_mao"]))
            self.remote_player.setCartas(self.getMaoFromCartas(a_move['j1_mao']))
            #print(self.local_player.cartas)
            #print(self.remote_player.cartas)
        else:
            print("receive else")
            if a_move["comprou_baralho"]:
                self.comprou_baralho(self.remote_player, True)
            else:
                self.comprou_baralho(self.remote_player, False)

            trinca = []
            #print(a_move["trincas_baixadas"])
            for trinca in a_move["trincas_baixadas"]:
                #print(trinca)
                self.baixar_trinca(self.remote_player, self.getTrincaFromDict(trinca))
                #print(self.remote_player.getTrincas())

            if a_move["carta_descarte"] != None:
                self.descartar_carta(self.remote_player, self.getCartaFromDict(a_move["carta_descarte"]))

            # if a_move['match_status'] == 'end':
            #     print("END GAME")

            self.swap_turn()
        #self.swap_turn()

    def baixar_trinca(self, player: Jogador, trinca:list()):
        if self.valido(trinca):
            nova_trinca = Trinca(player, trinca)
            for card in trinca:
                player.remove_card(card.num, card.naipe)
            player.add_trinca(nova_trinca)
            #self.trincas.append(nova_trinca)
            if self.checa_fim_jogo():
                self.match_status = 4
            return True
        return False

    def get_num_trincas(self, player: Jogador):
        return len(player.trincas)

    def checaVez(self):
        return self.local_player.vez_jogada

    def descartar_carta(self, player:Jogador, card):
        player.remove_card(card.num, card.naipe)
        self.descarte.push_top(card)
        self.toggle_turn()

    def comprou_baralho(self, player: Jogador, comprou_baralho: bool):
        if comprou_baralho:
            card = self.baralho.retirarCarta()
            if len(self.baralho.getCartas()) == 0:
                self.baralho.set_cards(self.descarte.cartas)
                self.descarte.cartas = []
                self.baralho.embaralhar()
            player.adicionaCarta(card)
            return True
        else:
            if len(self.descarte.cartas) > 0:
                card = self.descarte.retirarCarta()
                player.adicionaCarta(card)
                return True
            else: return False

    def toggle_turn(self):
        self.local_player.toggle_turn()
        self.remote_player.toggle_turn()

    def valido(self, trinca: list()):
        print("validando")
        naipe_igual = False
        if trinca[0].getNaipe() == trinca[1].getNaipe() and trinca[0].getNaipe() == trinca[2].getNaipe():
            naipe_igual = True

        if naipe_igual:
            print("naipe igual")
            trinca.sort(key=lambda x: x.getNum(), reverse=False)
            return int(trinca[0].getNum())+1 == int(trinca[1].getNum()) and int(trinca[0].getNum())+2 == int(trinca[2].getNum()) or (trinca[0].getNum()==1 and trinca[1].getNum()==12 and trinca[2].getNum()==13)
        else:
            print("naipe diferente")
            return int(trinca[0].getNum()) == int(trinca[1].getNum()) and int(trinca[0].getNum()) == int(trinca[2].getNum())and int(trinca[1].getNum()) == int(trinca[2].getNum())

    def getCartaFromDict(self, dic):
        num = dic['num']
        naipe = dic['naipe']
        return Carta(num, naipe)

    def getMaoFromCartas(self, cartas):
        mao = []
        for i in cartas:
            num = i['num']
            naipe = i['naipe']
            mao.append(Carta(num, naipe))
        return mao

    def getBaralhoFromDict(self, dic):
        print("bar from dic")
        #print(dic)
        bar = []
        for i in dic:
            #print(i)
            num = i['num']
            naipe = i['naipe']
            bar.append(Carta(num, naipe))
        return bar

    def getTrincaFromDict(self, dic):
        print("trinca from dict")
        #print(dic)
        trinca = []
        for i in dic:
            num = i['num']
            naipe = i['naipe']
            trinca.append(Carta(num, naipe))
        return trinca

    def receive_withdrawal_notification(self):
        self.match_status = 5   # Partida abandonada


from django.urls import path
from .views import home, formulario, login, listar_mascotas, eliminar_mascota, formulario_mascota, modificar_mascota, get_ciudades #Estamos importando la funcion "home" y la funcion "formulario " que hicimos en views

urlpatterns = [
    path('', home, name="home"), # Al principio no le pusimos ruta ya que se vera solo al poner la raiz que seria localhost
    path('formulario/', formulario, name="formulario"), # aqui le estamos diciendo que cuando le agregamos el /formulario nos va a llamar la funcion formulario que hicimos en views y el name sirve para llamarlo desde otro lado
    path('login/', login, name="login"),
    path('listar-mascotas/', listar_mascotas, name="listado_mascotas"),
    path('eliminar-mascota/<id>/', eliminar_mascota, name="eliminar_mascota"),
    path('formulario-mascota/', formulario_mascota, name="formulario_mascota"),
    path('modificar-mascota/<id>/', modificar_mascota, name="modificar_mascota"),
    path('get_ciudades/<id>/', get_ciudades, name="get_ciudades"),
]


import numpy as np
from particlesim.utils.conversion import prefactor
from .k_cython import calc_k_vectors

class EwaldSummation(object):
    r"""
    Parameters
    ----------
    system_conf : :obj:
        System configuration containing all parameters for the simulation.
    sigma : float
        Standard deviation of Gaussian charge distribution.
    k_cutoff : float
        Cutoff-radius in reciprocal space.

    """
    def __init__(self, system_conf, sigma, k_cutoff):
        self.system_conf = system_conf
        self.positions = system_conf.xyz # Original Positions
        self.charges = system_conf.charges
        self.volume = system_conf.volume
        self.sigma = sigma
        self.sigma_sq = sigma * sigma

        # Assig cutoff k and calculate vectors in k-space for longrange interaction energy
        self._k_cutoff = k_cutoff # multiple of 2*pi/L
        self.k_vectors = np.multiply(calc_k_vectors(self._k_cutoff), 2*np.pi/system_conf.box_size)

    @property
    def k_cutoff(self):
        return self._k_cutoff

    @k_cutoff.setter
    def k_cutoff(self, value):
        self._k_cutoff = value
        self.k_vectors = np.multiply(calc_k_vectors(self._k_cutoff), 2*np.pi/self.system_conf.box_size)

    def longrange_energy(self, positions):
        r"""
        Calculates the longrange potential and the self interaction potential
        of a given particle distribution using Ewald Summation.

        Atomic Units are used.

        Parameters
        ----------
        positions : array-like of floats
            Current position of all particles inside the box.

        Returns
        -------
        float
            long-range and self-interaction potential

        """
        self.positions  = positions

        # Calculate longrange potential vecotrized

        k_sq = np.einsum('ij,ij -> i', self.k_vectors, self.k_vectors)

        structure_factor = np.einsum('ik, k', np.exp(1j * np.einsum('ji, ki', self.k_vectors, self.positions)), self.charges )
        structure_factor_squared = structure_factor.real**2 + structure_factor.imag**2

        longrange_potential = np.dot(structure_factor_squared, np.exp(-self.sigma_sq * k_sq / 2) / k_sq) * \
                              prefactor / (2 * self.volume )

        # Calculate self-interaction potential

        self_interaction_potential = np.dot(self.charges.T, self.charges) * \
                                     1 / (np.sqrt(2*np.pi) * self.sigma) * 1/( 4 * np.pi) * prefactor

        # Calculate total potential
        longrange_and_self_potential = longrange_potential - self_interaction_potential

        return longrange_and_self_potential

    def get_iterations(self):
        r'''
        Function is used to calculate the time per iteration for the long-range Ewald summation.
        This time is used to calculate the optimal cutoff parameters.

        Returns
        -------
        it : int
            Number of steps for calculating the potential

        '''

        return len(self.k_vectors) * len(self.positions)


import requests
from bs4 import BeautifulSoup

response = requests.get('https://www.cmjornal.pt/cm-ao-minuto')

#print(response.content)
#print(type(response.content))

content = response.content

site = BeautifulSoup(content, 'html.parser')

#print(type(site))

#print(site.prettify())

#obter o html da noticia
noticia = site.find('div', attrs={'class': 'aominutoMain'})
#print(noticia)
#print(noticia.prettify())

#obter o titulo da noticia
titulo = noticia.find('span', attrs={'class': 'lead'})
#print(titulo)
print(titulo.text)
#print(titulo['href'])

dataN = noticia.find('a', attrs={'data-action': 'DestaquesPrincipais'})
print(dataN.text)
#noticiatitulo = noticia.find('h2', attrs={'class': 't-stamp-4'})
#print(noticiatitulo.text)
#Para obter somente o texto da noticia
#print(titulo.text)


#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
    k = 0
    m = 0
    col = len(matrix[0])
    row = len(matrix)
    new_matrix = [[0 for _ in range(col)] for _ in range(row)]
    for i in matrix:
        for j in i:
            new_matrix[k][m] = j * j
            m += 1
        k += 1
        m = 0
    return new_matrix


import socket
import threading
import signal
import sys

class PythonClient(object):

    def __init__(self, host='127.0.0.1', port=54321):
        self.__host__=host
        self.__port__=port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def is_connected(self):
        return False

    def connect(self):
        self.socket.connect((self.__host__,self.__port__))

    def disconnect(self):
        self.socket.close()

    def send(self,bytes):
        self.socket.send(bytes)
        self.response = self.socket.recv(1024)
        return self.response

if __name__ == '__main__':
    argc = len(sys.argv)

    if argc==1:
        p = PythonClient()
    elif argc==2:
        p = PythonClient(port=int(sys.argv[1]))
    elif argc>2:
        p = PythonClient(host=sys.argv[1],port=int(sys.argv[2]))

    p.connect()

    try:
        print("SEND>\t",end='',flush=True)
        for line in sys.stdin:
            response = p.send(line.encode())
            print("RECV>\t" + response.decode().strip())
            print("SEND>",end='\t',flush=True)

    except Exception as err:
        print(err)

    p.disconnect()

    # p.startServer()

    # try:
    #     s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #     s.connect(('127.0.0.1',54321))
    #     s.send('hello socket!'.encode())
    #     data = s.recv(1024)
    #     print(data.decode())


# É uma função (pequena) sem nome
# Pode ter vários argumentos mas somente uma expressão
# Muito utilizado dentro de outras funções
# Código mais 'clean'
# lambda tem que colocar as variaveis quando imprimir, já na função não precisa

n1 = int(input('Digite um numero: '))
n2 = int(input('Digite outro numero: '))

soma = lambda n1,n2: n1 + n2

print(soma(n1,n2))


class SegmentTree:
    # 初期化処理
    # f : SegmentTreeにのせるモノイド
    # default : fに対する単位元
    def __init__(self, N, f=lambda x,y : x+y, default=0):
        self.N = N
        self.size = 2**(N-1).bit_length() # 簡単のため要素数Nを2冪にする
        self.default = default
        self.dat = [default]*(self.size*2) # 要素を単位元で初期化
        self.f = f

    def setTree(self,init_li):
        #配列の値をセット
        for i in range(self.N):
            self.dat[self.size+i] = init_li[i]
        #木の構築
        for i in range(self.size-1,0,-1):
            self.dat[i] = self.f(self.dat[2*i],self.dat[2*i+1])

    def update(self, i, x):
        i+=self.size
        self.dat[i] = x

        while i>1:
            self.dat[i>>1] = self.f(self.dat[i],self.dat[i^1])
            i>>=1

    def query(self, l, r):
        res = self.default

        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                res = self.f(res, self.dat[l])
                l += 1
            if r & 1:
                res = self.f(res, self.dat[r - 1])
            l >>= 1
            r >>= 1
        return res


# import textwrap
# textwrap.wrap(str, len)
str = input("please enter you string: ")
n = int(len(str) / 2)
if len(str) % 2 == 0:
    chunks = [str[i:i+n] for i in range(0, len(str), n)]
else:
    chunks = [str[i:i + n] for i in range(0, len(str), n)]
    chunks[0]= chunks[0]+chunks[2]
    chunks.pop()

print(chunks)


import os
import pygame
import importlib
from graphics.obstacles.obstacles import *
from graphics.floor_tiles.floor_tiles import *
DROIDPATH = os.path.join("graphics", "droids")
ITEMPATH = os.path.join("graphics", "items")
DIRECTIONS = {0: "SE", 1: "E", 2: "NE", 3: "N", 4: "NW", 5: "W", 6: "SW", 7: "S"}
BULLET_DIRECTIONS = {0: "NW", 2: "W", 4: "SW", 6: "S", 8: "SE", 10: "E", 12: "NE", 14: "N"}

def load_items():
    temp = importlib.import_module("graphics.item_specs")
    final = {}
    for item in temp.items:
        raw = item["rotation_series"].split("/")
        path = os.path.join(*raw)
        try:
            item["ingame"] = pygame.image.load(os.path.join(ITEMPATH, path, "ingame.png")).convert_alpha()
        except:
            item["ingame"] = None
        item["offset"] = [0, 0]
        try:
            with open(os.path.join(ITEMPATH, path, "ingame.offset")) as f:
                for line in f.readlines():
                    if line.startswith("OffsetX"):
                        item["offset"][0] = int(line.split("=")[1].strip())
                    elif line.startswith("OffsetY"):
                        item["offset"][1] = int(line.split("=")[1].strip())
        except:
            pass
        final[item["type"]] = item
    return final
def load_bullets():
    temp = importlib.import_module("graphics.bullet_specs")
    bullets = {}
    for bullet in temp.bullet_list:
        bullet["images"] = {"SE": [], "E": [], "NE": [], "N": [], "NW": [], "W": [], "SW": [], "S": []}
        for frame in range(bullet.get("phases", 1)):
            for rotation in BULLET_DIRECTIONS.keys():
                image = {}
                string = "iso_bullet" + "_" + bullet["name"] + "_" + str(rotation).zfill(2) + "_" + str(frame + 1).zfill(4)
                image["image"] = pygame.image.load(os.path.join("graphics", "bullets", string + ".png"))
                image["offset"] = [0, 0]
                with open(os.path.join("graphics", "bullets", string + ".offset")) as f:
                    for line in f.readlines():
                        if line.startswith("OffsetX"):
                            image["offset"][0] = int(line.split("=")[1].strip())
                        elif line.startswith("OffsetY"):
                            image["offset"][1] = int(line.split("=")[1].strip())
                bullet["images"][BULLET_DIRECTIONS[rotation]].append(image)
        bullets[bullet["name"]] = bullet
    return bullets
def load_blasts():
    pass
def load_images():
    images = {}
    with open(os.path.join("graphics", "floor_tiles", "atlas.txt")) as atlas:
        floor_atlas = atlas.readlines()
    with open(os.path.join("graphics", "obstacles", "atlas.txt")) as atlas:
        obstacle_atlas = atlas.readlines()
    for line in floor_atlas:
        line = line.split()
        if line[0].startswith("*"):
            image = line[1]
            image_surf = pygame.image.load(os.path.join("graphics", "floor_tiles", image)).convert_alpha()
        else:
            pos = [int(x) for x in line[1:3]]
            size = [int(x) for x in line[3:5]]
            offset = [int(x) for x in line[6:8]]
            images[line[0]] = {"offset": offset, "image": image_surf, "region": [pos, size]}
    for line in obstacle_atlas:
        line = line.split()
        if line[0].startswith("*"):
            image = line[1]
            image_surf = pygame.image.load(os.path.join("graphics", "obstacles", image)).convert_alpha()
        else:
            pos = [int(x) for x in line[1:3]]
            size = [int(x) for x in line[3:5]]
            offset = [int(x) for x in line[6:8]]
            images[line[0]] = {"offset": offset, "image": image_surf, "region": [pos, size]}
    return images
def add_to_list(lst, frame, content):
    length = len(lst)
    if frame >= length:
        lst += [None for x in range(frame - length)] + [content]
    else:
        lst[frame] = content
    return lst
def load_droid_atlas(path):
    images = {
        "N": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []},
        "S": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []},
        "E": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []},
        "W": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []},
        "NW": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []},
        "NE": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []},
        "SW": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []},
        "SE": {"stand": [], "walk": [], "gethit": [], "death": [], "attack": []}
        }
    folderpath = os.path.split(path)[0]
    with open(path) as f:
        image = None
        image_surf = None
        for line in f.readlines():
            if line.startswith("*"):
                image = line.split()[1]
                image_surf = pygame.image.load(os.path.join(folderpath, image)).convert_alpha()
            else:
                line = line.split()
                rot = DIRECTIONS[int(line[0][11])]
                state = line[0][13:-7]
                frame = int(line[0][-5])
                pos = [int(x) for x in line[1:3]]
                size = [int(x) for x in line[3:5]]
                offset = [int(x) for x in line[6:8]]
                images[rot][state] = add_to_list(images[rot][state], frame, {"offset": offset, "pos": pos, "size": size, "image": image_surf})
    return images
def load_character_graphics():
    graphics = {}
    for path in os.listdir(DROIDPATH):
        atlaspath = os.path.join(DROIDPATH, path, "atlas.txt")
        if os.path.exists(atlaspath):
            graphics[path] = load_droid_atlas(atlaspath)
    return graphics
def load_character_configs():
    configs = {}
    for path in os.listdir(DROIDPATH):
        configpath = os.path.join(DROIDPATH, path, "config.txt")
        if os.path.exists(configpath):
            fps = {}
            with open(configpath) as f:
                for line in f.readlines():
                    line_split = line.split("=")
                    if line_split[0].endswith("fps"):
                        fps[line_split[0][:-4]] = int(line_split[1].strip())
            configs[path] = fps
    return configs
def load_droid_archetypes():
    characters = {}
    character = {}
    current = ""
    with open(os.path.join(DROIDPATH, "droids.txt")) as f:
        for line in f.readlines():
            if line.startswith("** Start of new Robot: **"):
                if current != "":
                    characters[current] = character
                    character = {}
                    current = ""
            elif line.startswith("#") or line.strip() == "":
                pass
            else:
                line_split = line.split("=")
                value = line_split[1].strip()
                if line_split[0] == "droidname":
                    current = value
                elif line_split[0] in ["class", "drop_item_class", "health", "heal_rate", "experience_reward", "hit_probability"]:
                    value = int(float(value))
                elif line_split[0] in ["speed", "aggression_distance", "time_spent_eyeing_player", "gethit_recover_time"]:
                    value = float(value)
                character[line_split[0]] = value
        characters[current] = character
    return characters
def load_characters():
    characters = load_droid_archetypes()
    configs = load_character_configs()
    graphics = load_character_graphics()
    final_characters = {}
    for character in characters.keys():
        temp = characters[character].copy()
        temp["fps"] = configs[temp["graphics_path"]]
        try:
            temp["images"] = graphics[temp["graphics_path"]]
        except:
            pass
        final_characters[character] = temp
    return final_characters
def load_tiles():
    items = load_items()
    bullets = load_bullets()
    images = load_images()
    characters = load_characters()
    for obstacle in obstacles:
        if type(obstacle["images"]) == str:
            obstacle["images"] = images[obstacle["images"]]
        else:
            obstacle["images"] = [images[image] for image in obstacle["images"]]
    for index, tile in enumerate(floor_tiles):
        if type(tile) == str:
            floor_tiles[index] = images[tile]
        else:
            floor_tiles[index]["images"] = [images[image] for image in floor_tiles[index]["images"]]
    return floor_tiles, obstacles, characters, items, bullets


#!/usr/bin/env python3
import serial
import time
import json
## Need: Debugging to catch a changing serial path

if __name__ == '__main__':
    try:
        ser = serial.Serial('/dev/ttyACM1', 9600, timeout=1)
    except serial.SerialException:
        ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.reset_input_buffer()
    while True:
        ser.write(b"GO\n")
        line = ser.readline().decode('utf-8').rstrip()

        if line == "GO" :
            data = ser.readline().decode('utf-8').rstrip()
            datadict = json.loads(data)
            print(datadict,type(datadict))
        time.sleep(2)


import numpy as np
import sympy as sp
from sympy import exp
import itertools as it
from numpy import real, log
from scipy.linalg import eig
import mpmath as mp

def partition(n, blockSize):
	'''
	This function takes as input:
		n 			-	The size of the system of interest.
		blockSize	-	The size of the blocks of the transfer matrix.

	It returns a tuple containing the size of the left endcap, the number of
	blocks, and the size of the right endcap in that order. The right endcap
	is always chosen to have size 1.
	'''
	if n >= 2+blockSize:
		m = n - 1
		q = m % blockSize
		if q == 0:
			q += blockSize
		return q,(n-1-q)//blockSize,1
	else:
		return None

def transferMatrix(eFunc, stateRange, params, blockSize, check=True):
	'''
	This function computes the transfer matrix associated with a Hamiltonian.
	The input parameters are:
		eFunc 		-	The Hamiltonian. This function must take as input a list of
						items drawn from stateRange and a list of parameters given
						by params.
		stateRange	-	This is a list specifying the allowed states on a site.
		params 		-	This is a list of the parameters in the Hamiltonian.
						These are sympy variables.
		blockSize	-	Transfer matrices generally require blocking together
						neighbouring sites. This is an integer specifying
						how many sites to block together. If this is set
						incorrectly the result will generically be wrong.
						This will never exceed the maximum range of the
						interactions in the system.
		check		-	An optional argument which defaults to True. If True
						the code will perform a basic check to see if the
						block size is correct. This is done just by examining the
						energy associated with a block which is 50% larger.

	This method implements a brute-force approach to finding the transfer matrix
	for a system. This works by constructing three neighbouring blocks of size blockSize.
	The states of these blocks are x, y, and y. For each (x,y) we compute eFunc(x,y,y).
	We also compute eFunc(y,y), the energy of two blocks of size blockSize in the
	same state. We subtract these and exponentiate, and take this to be the value of the
	transfer matrix for the state pair (x,y).

	The same method is then used to compute so-called endcap matrices. These matrices
	give the contribution of blocks smaller than blockSize which are attached to the
	ends of the system, so that we can deal with system sizes which are not integer
	multiples of the block size. The left endcap is computed with precisely the same
	logic, while the right endcap just returns exp(-eFunc(x + y)) with no subtraction.
	This has to be done at one endcap to anchor the energies, and we choose to do it
	at the right one.

	This method relies on the range of interactions being at most blockSize. This is so
	that eFunc(x, y, y) - eFunc(y, y) is precisely the contribution to the energy
	associated with adding on the block x to a block y, irrespective of the rest of the
	system. As a result if there are interactions which are longer-ranged than blockSize
	then this result will be invalid

	The mathematical operations are all performed in sympy so that this expensive operation
	need only be performed once.
	'''

	# Generate block states
	states = list(it.product(stateRange, repeat=blockSize))

	# Initialize matrix
	tMat = sp.zeros(len(states), len(states))

	# Compute transfer matrix
	for i, x in enumerate(states):
		print(i)
		for j, y in enumerate(states):
			tMat[i,j] = exp(eFunc(y + y, params) - eFunc(x + y + y, params))

			# Test block size (not guaranteed to catch errors in pathological cases)
			if check:
				for z in states:
					if exp(eFunc(y+z,params) - eFunc(x+y+z,params)) != tMat[i,j]:
						raise ValueError('Error: Block size too small.')

	# Initialize endcap states
	endStates = list([list(it.product(stateRange, repeat=l)) for l in range(1, blockSize + 1)])

	# Compute left end cap
	leftEnds = []
	for l in range(blockSize):
		print(l)
		end = sp.zeros(len(endStates[l]),len(states))
		for i,x in enumerate(endStates[l]):
			for j,y in enumerate(states):
				end[i,j] = exp(eFunc(y+y,params) - eFunc(x+y+y,params))
		leftEnds.append(end)

	# Compute right end cap
	rightEnds = []
	for l in range(blockSize):
		print(l)
		end = sp.zeros(len(states),len(endStates[l]))
		for i,x in enumerate(states):
			for j,y in enumerate(endStates[l]):
				# No subtraction here, as we want to set the energies in the case
				# of a single block with a right endcap (what we called anchoring the
				# energy in the docs above).
				end[i,j] = exp(-eFunc(x+y,params))
		rightEnds.append(end)

	return tMat,leftEnds,rightEnds

def transferMatrixVariableSize(eFunc, stateRange, params):
	'''
	This method takes as input:
		eFunc 		-	The Hamiltonian. This function must take as input a list of
						items drawn from stateRange and a list of parameters given
						by params.
		stateRange	-	This is a list specifying the allowed states on a site.
		params 		-	This is a list of the parameters in the Hamiltonian.
						These are sympy variables.

	This method attempts to find the correct block size for the transfer matrix.
	It does this by starting with a small block and increasing the size by one site
	until the check procedure does not fail. This is not guaranteed to work in pathological
	cases, but in cases with simple interacting Hamiltonians should be fine.

	'''

	blockSize = 1

	while True:

		try:
			tm = transferMatrix(eFunc, stateRange, params, blockSize, check=True)
			print('Final Size:',blockSize)
			return tm[0],tm[1],tm[2],blockSize
		except ValueError:
			print('Tried size',blockSize,'. Incrementing.')
			blockSize += 1

def wrapper(tm,leftEnds,rightEnds,params):
	'''
	This method takes as input a transfer matrix as well as the associated
	endcaps and parameters and wraps them so that they may be called as regular
	numeric functions rather than returning symbolic expressions.
	'''

	print('Wrapping transfer matrix...')
	T = sp.lambdify(params, tm, "mpmath")
	print('Wrapping transfer matrix derivative...')
	dP = sp.lambdify(params, tm.diff(params[0]), "mpmath")
	dQ = sp.lambdify(params, tm.diff(params[1]), "mpmath")
	dW = sp.lambdify(params, tm.diff(params[2]), "mpmath")
	print('Wrapping left end caps...')
	eL = list([sp.lambdify(params, l, "mpmath") for l in leftEnds])
	dQL = list([sp.lambdify(params, l.diff(params[1]), "mpmath") for l in leftEnds])
	dWL = list([sp.lambdify(params, l.diff(params[2]), "mpmath") for l in leftEnds])
	print('Wrapping right end caps...')
	eR = list([sp.lambdify(params, r, "mpmath") for r in rightEnds])
	dQR = list([sp.lambdify(params, r.diff(params[1]), "mpmath") for r in rightEnds])
	dWR = list([sp.lambdify(params, r.diff(params[2]), "mpmath") for r in rightEnds])
	print('Done!')
	return T,eL,eR,dP,dQ,dW,dQL,dWL,dQR,dWR

def fN(T,eL,eR,dP,dQ,dW,dQL,dWL,dQR,dWR,params,blockSize,n):
	'''
	This method takes as input:
		T 			-	The wrapped (numerical) transfer matrix.
		eL 			-	The wrapped (numerical) left endcap list.
		eR 			-	The wrapped (numerical) right endcap list.
		params 		-	The numerical values of the parameters.
		blockSize 	-	The block size used to construct T.
		n 			-	The size of the system of interest.

	This method computes the slope and intercept of the free energy form

	F(L) = a + b L

	b is computed using the maximal eigenvalue of T. The free energy is then computed
	for the system size n and this is used to determine a.

	'''

	# Partition the system size into left cap, blocks, right cap
	n1,n2,n3 = partition(n,blockSize)

	# Evaluate endcaps at partition sizes
	e1 = eL[n1-1](*params)
	e2 = eR[n3-1](*params)
	de1_dQ = dQL[n1-1](*params)
	de2_dQ = dQR[n3-1](*params)
	de1_dW = dWL[n1-1](*params)
	de2_dW = dWR[n3-1](*params)

	# Evaluate transfer matrix and derivative
	tm = T(*params)
	dp = dP(*params)
	dt_dQ = dQ(*params)
	dt_dW = dW(*params)

	# Normalize
	sh = np.array(tm.tolist(), dtype=float).shape
	y = -1e100
	for i in range(sh[0]):
		for j in range(sh[1]):
			if abs(tm[i,j]) > y:
				y = abs(tm[i,j])

	tm /= y
	dp /= y
	dt_dQ /= y
	dt_dW /= y

	# Cast to numpy
	e1 = np.array(e1.tolist(), dtype=float)
	e2 = np.array(e2.tolist(), dtype=float)
	tm = np.array(tm.tolist(), dtype=float)
	dp = np.array(dp.tolist(), dtype=float)
	dt_dQ = np.array(dt_dQ.tolist(), dtype=float)
	dt_dW = np.array(dt_dW.tolist(), dtype=float)
	de1_dQ = np.array(de1_dQ.tolist(), dtype=float)
	de2_dQ = np.array(de2_dQ.tolist(), dtype=float)
	de1_dW = np.array(de1_dW.tolist(), dtype=float)
	de2_dW = np.array(de2_dW.tolist(), dtype=float)

	# Compute slope and slope derivative
	vals, invvecs, vecs = eig(tm, left=True, right=True)

	ind = np.argmax(np.real(vals))
	val = np.real(vals[ind])
	logy = float(mp.log(y))
	logm = logy + log(val)
	slope = -logm / blockSize

	# ds = -d log m / blockSize
	# d log m = dm / m = d (m/y) / (m/y)
	# What we've written below as dm is actually d(m/y), so we divide it by val (which is just m/y).
	dm = np.dot(np.conj(invvecs[:,ind]), np.dot(dp, vecs[:,ind])) / np.dot(np.conj(invvecs[:,ind]), vecs[:,ind])
	ds = -np.real(dm) / (val * blockSize)

	d_lnZ_dQ_intensive = np.dot(np.conj(invvecs[:,ind]), np.dot(dt_dQ, vecs[:,ind])) / np.dot(np.conj(invvecs[:,ind]), vecs[:,ind])
	d_lnZ_dQ_intensive = -np.real(d_lnZ_dQ_intensive) / (val * blockSize)

	d_lnZ_dW_intensive = np.dot(np.conj(invvecs[:,ind]), np.dot(dt_dW, vecs[:,ind])) / np.dot(np.conj(invvecs[:,ind]), vecs[:,ind])
	d_lnZ_dW_intensive = -np.real(d_lnZ_dW_intensive) / (val * blockSize)

	# Compute free energy
	z = np.sum(np.dot(e1, np.dot(np.linalg.matrix_power(tm, n2 - 1), e2)))
	f = -real(log(z)) - (n2 - 1)*logy # logy provides the correction because we normalized tm

	# Compute dlnZ/dQ
	dlnZ = 0
	dlnZ += np.sum(np.dot(de1_dQ, np.dot(np.linalg.matrix_power(tm, n2 - 1), e2)))
	dlnZ += np.sum(np.dot(e1, np.dot(np.linalg.matrix_power(tm, n2 - 1), de2_dQ)))
	dlnZ += (n2 - 1) * np.sum(np.dot(e1, np.dot(dt_dQ, np.dot(np.linalg.matrix_power(tm, n2 - 2), e2))))
	dlnZ /= z
	num_Q = -dlnZ

	# Compute dlnZ/dW
	dlnZ = 0
	dlnZ += np.sum(np.dot(de1_dW, np.dot(np.linalg.matrix_power(tm, n2 - 1), e2)))
	dlnZ += np.sum(np.dot(e1, np.dot(np.linalg.matrix_power(tm, n2 - 1), de2_dW)))
	dlnZ += (n2 - 1) * np.sum(np.dot(e1, np.dot(dt_dW, np.dot(np.linalg.matrix_power(tm, n2 - 2), e2))))
	dlnZ /= z
	num_W = -dlnZ

	# Evaluate intercepts
	inter = f - slope*n
	interQ = num_Q - d_lnZ_dQ_intensive * n
	interW = num_W - d_lnZ_dW_intensive * n

	return slope,inter,f,ds, interQ, d_lnZ_dQ_intensive, interW, d_lnZ_dW_intensive


import cv2
import numpy as np

cap = cv2.VideoCapture(0)

# Create old frame
ret, frame = cap.read()
oldGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Lucas-Kanade Params
lkParams = dict(winSize=(20, 20),
                maxLevel=4,
                criteria=(cv2.TermCriteria_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

# Select Point Function
def select(event, x, y, flags, params):
    global point, objSelected, oldPoints
    if event == cv2.EVENT_LBUTTONDOWN:
        point = (x, y)
        objSelected = True
        oldPoints = np.array([[x, y]], dtype=np.float32)

# Detect Direction
def Direction(old, new):
    if new[0][0] + 1 < old[0][0]:
        dir = 'Left Direction'
    elif new[0][0] - 1 > old[0][0]:
        dir = 'Right Direction'
    else:
        dir = 'No motion'
    return dir

# Calling Select Object Function
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", select)

objSelected = False
point = ()
oldPoints = np.array([[]])

# While Loop
while True:

    ret, frame = cap.read()
    grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # If object selected, use Optical Flow Algorithm
    if objSelected is True:
        newPoints, status, error = cv2.calcOpticalFlowPyrLK(oldGray, grayFrame, oldPoints, None, **lkParams)
        oldGray = grayFrame.copy()
        dir = Direction(oldPoints, newPoints)
        oldPoints = newPoints
        x, y = newPoints.ravel()
        cv2.circle(frame, (x, y), 10, (0, 0, 0), -1)
        cv2.putText(frame, dir, (100, 450), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)

      #ask user to select point
    else:
        cv2.putText(frame, 'select point', (200, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)

    # Show Frame
    cv2.imshow("Frame", frame)

    #Wait Key
    key = cv2.waitKey(1)
    if key == 32:
        break

cap.release()
cv2.destroyAllWindows()


# from SetPin import SetPin
import time, string
import datalink_layer_receive as dl
import network_layer_recieve as nw
delimiters = ['**', '***', '****']

from MorseCode import MorseCode
Inverted = {MorseCode[letter]: letter for letter in MorseCode}
Numbers = {1: '.----', 2: '..---', 3: '...--', 4: '....-', 5: '.....', 6: '-....', 7: '--...', 8: '---..', 9: '----.', 10: '-----'}
InvertNumbers = {Numbers[n]: n for n in Numbers}

def splitAsterisks(incoming):
	out = []
	second = []
	first = incoming.split('**')
	for i in first:
		second += i.split('***')
	for j in second:
		out += j.split('****')
	return out

def process(input_message):
	input_message = input_message.split('*' * 15)[0].split('*' * 7)

	curMsg = nw.nwOperations(dl.dlOperations(input_message, address))

	incoming = curMsg[0]
	# Process message
	newwords = []
	words = incoming.split('*******')
	for w in words:
		letters = splitAsterisks(w)
		for i in range(len(letters)):
			letter = letters[i]
			letters[i] = Inverted[letter.replace('...', '-').replace('*','')]
		newwords.append(''.join(letters))
	return ' '.join(newwords)


import turtle as t
def square(turt,x,y,leng):
    c=1
    while c<19:
        turt.penup()
        turt.goto(x,y)
        turt.lt(20)

        turt.pendown()
        s=1
        while s<=4:
            turt.fd(leng)
            turt.lt(90)
            s+=1
        c+=1

bob=t.Turtle()

square(bob,0,0,100)


import matplotlib.pyplot as plt
#解决显示中文乱码问题
plt.rcParams["font.sans-serif"]=["SimHei"]
import seaborn as sns
import numpy as np
from PIL import Image
from sklearn.metrics import confusion_matrix,classification_report
from util_data import get_img_infos,split_dataset
sns.set_style("white")

def plot_label_distribution(img_labels):
    #绘制猫和狗的分布
    sns.countplot(img_labels)
    plt.title("cat and dog distribution")
    plt.show()

#用来绘制验证集和测试集的类标分布
def val_pred_and_real_distribution(pred_labels,real_labels):
    label_num_to_name = {0:"cat",1:"dog"}
    #将数字标签转为文字标签
    pred_labels = [label_num_to_name[label] for label in pred_labels]
    real_labels = [label_num_to_name[label] for label in real_labels]
    plt.figure(22)
    #绘制预测结果和真实结果标签的分布情况
    plt.subplot(221)
    sns.countplot(pred_labels)
    plt.title("prediction label distribution")
    plt.subplot(222)
    sns.countplot(real_labels)
    plt.title("real label distribution")
    #绘制预测正确结果和预测错误结果的分布情况
    #计算预测正确的下标位置
    correct_index = np.array(pred_labels)==np.array(real_labels)
    correct = np.array(real_labels)[correct_index]
    plt.subplot(223)
    sns.countplot(correct)
    plt.title("prediction correct label distribution")
    #计算预测错误的下标位置
    error_index = np.array(pred_labels) != np.array(real_labels)
    error = np.array(real_labels)[error_index]
    plt.subplot(224)
    sns.countplot(error)
    plt.title("prediction error label distribution")
    plt.show()

#展示预测正确和错误标签的部分图片
def show_part_image(pred_labels,real_labels,img_paths):
    label_num_to_name = {0:"cat",1:"dog"}
    #获取预测正确的下标
    correct_index = np.array(pred_labels) == np.array(real_labels)
    correct_pred_labels = np.array(pred_labels)[correct_index]
    correct_real_labels = np.array(real_labels)[correct_index]
    correct_img_paths = np.array(img_paths)[correct_index]
    #获取预测错误的下标
    error_index = np.array(pred_labels) != np.array(real_labels)
    error_pred_labels = np.array(pred_labels)[error_index]
    error_real_labels = np.array(real_labels)[error_index]
    error_img_paths = np.array(img_paths)[error_index]
    #展示十张图片上面5张预测正确的图片,下面5张预测错误的图片
    plt.figure(25)
    for i in range(5):
        plt.subplot(2,5,i+1)
        plt.imshow(Image.open(correct_img_paths[i]))
        plt.title("预测:%s\n真实:%s"%(label_num_to_name[correct_pred_labels[i]],
                                           label_num_to_name[correct_real_labels[i]]))
        plt.subplot(2,5,i+6)
        plt.imshow(Image.open(error_img_paths[i]))
        plt.title("预测:%s\n真实:%s"%(label_num_to_name[error_pred_labels[i]],
                                           label_num_to_name[error_real_labels[i]]))
    plt.show()

#绘制混淆矩阵,输出分类情况报告
def classifiction_report_info(pred_labels,real_labels):
    #输出分类结果报告
    classification_info = classification_report(real_labels,pred_labels,target_names=["cat","dog"])
    print(classification_info)
    #展示混淆矩阵
    con_matrix = confusion_matrix(real_labels,pred_labels)
    sns.heatmap(con_matrix,annot=True)
    plt.show()

if __name__ == "__main__":
    img_ids,img_labels,img_paths = get_img_infos("train","txt/train.txt")
    train_dataset,val_dataset = split_dataset(img_ids,img_paths,img_labels)
    print(img_paths)
    plot_label_distribution(train_dataset["img_label"])
    plot_label_distribution(val_dataset["img_label"])


import logging
import resource
import sys
sys.path.append('../../')

from collections import defaultdict

import numpy as np
import torch
from tqdm import tqdm

import data.mri_data_multicoil as data_batch
from common.args import TestArgs
from common.mytorch import root_sum_of_squares
from common.utils import save_reconstructions
from common.mytorch.tensor_ops import center_crop
from common.train_template import (
    postprocess,
)

logging.basicConfig(level=logging.INFO)
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))

def run_zero_filled_sense(args, data_loader):
    """ Run Adjoint (zero-filled SENSE) reconstruction """
    logging.info('Run zero-filled SENSE reconstruction')
    logging.info(f'Arguments: {args}')
    reconstructions = defaultdict(list)

    with torch.no_grad():
        for sample in tqdm(iter(data_loader)):
            sample = data_batch._read_data(sample)

            rec_x = sample['attrs']['metadata']['rec_x']
            rec_y = sample['attrs']['metadata']['rec_y']

            x = sample['input']

            recons = postprocess(x, (rec_x, rec_y))

            # mask background using background mean value
            if args.mask_bg:
                fg_mask = center_crop(
                    sample['fg_mask'],
                    (rec_x, rec_y),
                ).squeeze(1)
                if args.use_bg_noise_mean:
                    bg_mean = sample['input_rss_mean'].reshape(-1, 1, 1)
                    recons = recons * fg_mask + (1 - fg_mask) * bg_mean
                else:
                    recons = recons * fg_mask

            # renormalize
            norm = sample['attrs']['norm'].numpy()[:, np.newaxis, np.newaxis]
            recons = recons.numpy() * norm

            for bidx in range(recons.shape[0]):
                reconstructions[sample['fname']].append(
                    (sample['slidx'][bidx], recons[bidx])
                )

    reconstructions = {
        fname: np.stack([pred for _, pred in sorted(slice_preds)])
        for fname, slice_preds in reconstructions.items()}

    save_reconstructions(reconstructions, args.out_dir)

def main(args):
    if args.challenge == 'singlecoil':
        raise ValueError('This works only for multicoil challenge!')

    csv_eval = f'{args.csv_path}/multicoil_{args.data_split}.csv'

    data_loader = data_batch.create_eval_data_loaders(args, csv_eval=csv_eval)
    run_zero_filled_sense(args, data_loader)

def create_arg_parser():
    parser = TestArgs()
    parser.add_argument(
        '--use-bg-noise-mean',
        action='store_true',
        help='If set, replace the background by the estimated bg noise mean of the RSS. [Challenge only]',
    )
    return parser

if __name__ == '__main__':
    args = create_arg_parser().parse_args(sys.argv[1:])
    main(args)


from datetime import datetime
from ..utils.hasher import hashIt
from app.model.models import UserProfile, Location, Variable, Measurement, Date
from ..utils.constants import DATE_FORMAT, TIME_FORMAT
from app.utils.datetimeConverter import convertDatetime

def getOrCreateVariable(name, unit, value, category):
    if Variable.nodes.get_or_none(name=name, unit=unit, value=value, category=category) is None:
        return Variable(name=name, unit=unit, value=value, category=category).save()

    return Variable.nodes.get(name=name, unit=unit, value=value, category=category)

def getOrCreateDate(date):
    if Date.nodes.get_or_none(date=datetime.strptime(date, DATE_FORMAT)) is None:
        return Date(date=datetime.strptime(date, DATE_FORMAT)).save()

    return Date.nodes.get(date=datetime.strptime(date, DATE_FORMAT))

def getOrCreateLocation(longitude, latitude):
    if Location.nodes.get_or_none(latitude=latitude, longitude=longitude) is None:
        return Location(latitude=latitude, longitude=longitude).save()

    return Location.nodes.get(latitude=latitude, longitude=longitude)

def writeMeasurement(longitude, latitude, name, value, unit, date, time, category, uid):
    profile = UserProfile.nodes.get(uid=uid)
    date = convertDatetime(date, DATE_FORMAT)
    if time is not None:
        time = convertDatetime(time, TIME_FORMAT)

    if Measurement.nodes.get_or_none(hash=hashIt(date, time, uid, latitude, longitude)) is None:
        if time is not None:
            timeToInsert = datetime.strptime(time, TIME_FORMAT)
            digest = hashIt(date, time, uid, latitude, longitude)
            measurement = Measurement(hash=digest, time=timeToInsert)
        else:
            measurement = Measurement(hash=hashIt(date, time, uid, latitude, longitude))

        measurement.save()
        profile.measurements.connect(measurement)
        measurement.location.connect(getOrCreateLocation(longitude, latitude))
        measurement.date.connect(getOrCreateDate(date))
        measurement.variables.connect(getOrCreateVariable(name, unit, value, category))

    else:
        measurement = Measurement.nodes.get(hash=hashIt(date, time, uid, latitude, longitude))
        measurement.variables.connect(getOrCreateVariable(name, unit, value, category))
        measurement.save()


# Lab 4
#
# Name: Veronica Pollock
# Instructor: Sussan Einakian
# Section: 23

import driver

def letter(row, col):
	if row <= 9:
		return "R"
	else:
		return "Q"

if __name__ == '__main__':
	driver.comparePatterns(letter)


# coding: utf-8
# last modified:20220824
import time
import serial
import re
import datetime

import numpy as np
# import matplotlib.pyplot as plt
import subprocess

utctime = ''
lat = ''
ulat = ''
lon = ''
ulon = ''
numSv = ''
msl = ''
cogt = ''
cogm = ''
sog = ''
kph = ''
gps_t = 0

def Convert_to_degrees(in_data1, in_data2):
    len_data1 = len(in_data1)
    str_data2 = "%05d" % int(in_data2)
    temp_data = int(in_data1)
    symbol = 1
    if temp_data < 0:
        symbol = -1
    degree = int(temp_data / 100.0)
    str_decimal = str(in_data1[len_data1-2]) + str(in_data1[len_data1-1]) + str(str_data2)
    f_degree = int(str_decimal)/60.0/100000.0
    # print("f_degree:", f_degree)
    if symbol > 0:
        result = degree + f_degree
    else:
        result = degree - f_degree
    return result

gps_time_list = []
pc_time_list = []

def format_time(raw_time):
    dt = datetime.datetime.strptime(raw_time.decode(), ",%H%M%S.%f")
    # return dt.strftime("2023-%m-%d %H:%M:%S")
    return dt.strftime("2023-04-21 %H:%M:%S")

def GPS_read(ser):
    global utctime
    if ser.inWaiting():
        if ser.read(1) == b'G':
            if ser.inWaiting():
                if ser.read(1) == b'N':
                    if ser.inWaiting():
                        choice = ser.read(1)
                        if choice == b'G':
                            if ser.inWaiting():
                                if ser.read(1) == b'G':
                                    if ser.inWaiting():
                                        if ser.read(1) == b'A':
                                            utctime = ser.read(11) # 读取串口数据
                                            # print('utc:')
                                            # print(utctime)

                                            if(utctime[8] == 48):
                                                print('test:')
                                                print(utctime[8])

                                                gps_time_list.append(utctime) #记录gps报告时间
                                                pc_time_list.append(time.time()) #记录电脑时间
                                                print('utctime:', format_time(utctime))

                                                str1 = str(format_time(utctime))     #格式化GPS报告的时间
                                                # str2 = "2022-04-17 12:00:00"

                                                print('set clock:', str1)
                                                #print('2:', str2)
                                                output = subprocess.check_output(["date","-s", str1])  #设置时间
                                            # print(output.decode())
                                                return True

    return False

def main(Ser_name = "/dev/a-gps", period = 300):

    print("begin to set the clock!")
    Baudrate = 115200

    ser = serial.Serial(Ser_name, Baudrate)

    if ser.isOpen():

        print("GPS Serial Opened! Baudrate="+str(Baudrate))
    else:
        print("GPS Serial Open Failed!")

    while True:

        try:
            if(GPS_read(ser)):
                print('good')
                # time.sleep(period)
                time.sleep(0)

        except Exception as e:
            print(time.strftime("%H:%M:%S"), end=' ')
            print('GPS Exceptions!', e)
            time.sleep(10)
        except KeyboardInterrupt:
            ser.close()
            print("GPS serial Close!")

if __name__ == '__main__':
    main()

# print(gps_time_list)
# print(pc_time_list)
# print(len(gps_time_list))

# # 求误差
# errors = []
# for i in range(0, len(gps_time_list)):
#     s = gps_time_list[i].decode("utf-8")
#     gps_t = datetime.datetime.strptime(s, ",%H%M%S.%f") + datetime.timedelta(days=45012,hours = 8)
#     print(gps_t)
#     gps_timestamp = gps_t.timestamp()

#     pc_timestamp = pc_time_list[i]
#     errors.append(gps_timestamp - pc_timestamp)
#     # gps_t = float(str(gps_time_list[i])[3:-1])
#     # print(gps_t)

# print(errors)

# # 存储文件
# import pickle

# with open(Ser_name +'_data1.pickle', 'wb') as f:
#     pickle.dump(errors, f)

# with open('COM5_data.pickle', 'rb') as f:
#     errors_data1 = pickle.load(f)

# with open('COM7_data.pickle', 'rb') as f:
#     errors_data2 = pickle.load(f)

# data = [errors_data1, errors_data2]
# labels = ['module 1', 'module 2']

# # 绘制箱线图
# fig, ax = plt.subplots()
# ax.boxplot(data, labels=labels)
# ax.set_title('Error Boxplot')
# ax.set_xlabel('Error')
# ax.set_ylabel('Value')
# plt.show()


"""

给定一个字符串source和一个目标字符串target，在字符串source中找到包括所有目标字符串字母的子串。
注意事项

如果在source中没有这样的子串，返回""，如果有多个这样的子串，返回起始位置最小的子串。
您在真实的面试中是否遇到过这个题？
说明

在答案的子串中的字母在目标字符串中是否需要具有相同的顺序？

——不需要。
样例

给出source = "ADOBECODEBANC"，target = "ABC" 满足要求的解  "BANC"
"""
class Solution:
    """
    @param source: A string
    @param target: A string
    @return: A string denote the minimum window
             Return "" if there is no such a string
    """
    def minWindow(self, source, target):
        length = len(source)
        if length == 0:
            return ''
        find = 0
        window = [0, length+ 1]
        src = [0]*256
        tar = [0]*256
        for i in target:
            tar[ord(i)] += 1
        begin = 0
        for end in xrange(1, length+ 1):
            temp = source[end- 1]
            if tar[ord(temp)] != 0: src[ord(temp)] += 1
            if (tar[ord(temp)]> 0 and src[ord(temp)] <= tar[(ord(temp))]): find += 1

            if find == len(target):
            #将开头字母后续出现的删掉，字符出现次数超过了目标串中出现的次数，并把它们出现次数都减1
                while src[ord(source[begin])] > tar[ord(source[begin])] or tar[ord(source[begin])] == 0:
                    if tar[ord(source[begin])]> 0: src[ord(source[begin])] -= 1
                    begin += 1
                if (window[1]- window[0]) > (end- begin):
                    window[0], window[1] = begin, end

        if window[1] == length+ 1:
            return ''
        else:
            return source[window[0]: window[1]]


from collections import deque
import sys
sys.setrecursionlimit(10**7)

n, m, k = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(n + 1)]
visit_depth = [0] * (n + 1)
count = 1

def dfs(x):
    global count
    count += 1
    for i in graph[x]:
        if visit_depth[i] == 0:
            visit_depth[i] = count
            dfs(i)

for i in range(m):
    a, b = map(int, sys.stdin.readline().split())
    graph[a].append(b)
    graph[b].append(a)

for i in range(1, n + 1):
    graph[i].sort()

visit_depth[k] = 1
dfs(k)

for i in range(1, n + 1):
    print(visit_depth[i])


# https://leetcode.com/problems/merge-sorted-array

from typing import List
import unittest
from dataclasses import dataclass
from typing import List, Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    def __repr__(self):
        return f'{self.__class__.__name__}(val={self.val}, next={self.next})'

def list_to_listnode(int_list: Optional[List[int]]) -> Optional[ListNode]:
    if not int_list:
        return None

    node = None

    for i in reversed(int_list):
        node = ListNode(i, node)

    return node

def listnode_to_list(list_node: Optional[ListNode]) -> Optional[List[int]]:
    if not list_node:
        return []

    if not list_node.next:
        return [list_node.val]

    node = list_node
    result = []

    while node:
        result.append(node.val)
        node = node.next

    return result

class Solution:
    @staticmethod
    def merge_two_lists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = current = ListNode()

        if not list1 and not list2:
            return list1

        while list1 and list2:
            if list1.val > list2.val:
                current.next = list2
                list2 = list2.next
            else:
                current.next = list1
                list1 = list1.next
            current = current.next

        if list1:
            current.next = list1
        if list2:
            current.next = list2
        return dummy.next

@dataclass
class TestCase:
    list1: Optional[ListNode]
    list2: Optional[ListNode]
    expectation: Optional[ListNode]

class TestSolution(unittest.TestCase):
    def test_solution(self):
        solution = Solution()

        tests = [
            TestCase(list1=[], list2=[], expectation=[]),
            TestCase(list1=[], list2=[0], expectation=[0]),
            TestCase(list1=[1, 2, 4], list2=[1, 3, 4], expectation=[1, 1, 2, 3, 4, 4]),
        ]

        for t in tests:
            with self.subTest(t):
                self.assertEqual(
                    listnode_to_list(solution.merge_two_lists(list_to_listnode(t.list1), list_to_listnode(t.list2))),
                    t.expectation)


import tkinter as tk
from tkinter import messagebox
import tkinter.ttk as ttk
from datetime import date

root = tk.Tk()
root.title("EDAD")
labdia = ttk.Label(root,text="Dia").grid(row=0,column=0,padx=10,pady=10)
dia =ttk.Entry(root)
dia.grid(row=0,column=1)

labmes = ttk.Label(root,text="Mes").grid(row=1,column=0,padx=10,pady=10)
mes = ttk.Combobox(root, values=("Enero", "Febrero", "Marzo", "Abril", "Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"))
mes.set("Enero")
mes.grid(row=1,column=1)

labyear = ttk.Label(root,text="Anio").grid(row=2,column=0,padx=10,pady=10)
year =ttk.Entry(root)
year.grid(row=2,column=1)

def escribir():
    dicdias={"Enero":(1,31), "Febrero":(2,28), "Marzo":(3,31), "Abril":(4,30),"Mayo":(5,31),"Junio":(6,30),"Julio":(7,31),"Agosto":(8,31),"Septiembre":(9,30),"Octubre":(10,31),"Noviembre":(11,30),"Diciembre":(12,31)}
    try:
        d = int(dia.get())
        m = str(mes.get())
        y = int(year.get())
        today = date.today()
        cumplea=date(y,dicdias[m][0],d)
        if d > dicdias[m][1] or len(str(y)) != 4  or y > today.year:
            raise ("len error")
        edad = today.year - cumplea.year - ((today.month, today.day) < (cumplea.month, cumplea.day))
    except:
        tk.messagebox.showwarning(title="Datos No validos", message="Corrobore dia (DD) y anio (YYYY)")
    ttk.Label(root,text = "Edad: " ).grid(row=3,column=0)
    ttk.Label(root,text = edad ).grid(row=3,column=1,padx=10,pady=10)

tk.Button(root, text="Submit", fg = "black", bg = "gold", font = "Helvetica 20 bold italic",command = escribir).grid(row=3,column=0)

root.mainloop()

#Ejemplo by Lean


def main(a, b):
    ans = ''
    if a > b:
        for _ in range(a):
            ans += str(b)
    elif a <= b:
        for _ in range(b):
            ans += str(a)

    print(ans)

if __name__ == '__main__':
    params = input()
    params = params.split()
    a = int(params[0])
    b = int(params[1])
    main(a, b)


from django.contrib.auth.decorators import permission_required, login_required
from django.core.urlresolvers import reverse
from django.db import transaction
from django.http import Http404
from django.shortcuts import redirect, render
from core.forms.tags import AddUserForm, NewUserForm, NewTagForm
from core.models import UserTag, Tag
from core.views.auth import _createNewUser

def _lazyAddUserForm(request, usertags):
    """
    If the user is admin, it should be able to see all tags, including ones where it isn't subscribed
    Create a lazy list of UserTags based on all tags available for the organization, and all marked as "owned"
    """
    for usertag in usertags:
        def lazyCrateUserForm(usertag):
            def curry():
                add_user_form = AddUserForm(tag_id=usertag.tag.id)
                add_user_form.fields['user'].queryset = add_user_form.fields['user'].queryset. \
                    filter(organization = request.loggedin().organization).exclude(usertags__tag = usertag.tag)
                return add_user_form
            return curry
        setattr(usertag, "add_user_form", lazyCrateUserForm(usertag))
        yield usertag

def _getLazyTagCreatorUserTags(request):
    usertags = (UserTag(tag=tag, user=request.loggedin(), owns_tag = True)
                for tag in request.loggedin().organization.tags.all())
    return _lazyAddUserForm(request, usertags)

def _processNewUserForm(request):
    """
    Return a NewUserForm if the user is owner, and create a new user if POST
    Returns form=None if not owner and user=False if no user created
    Returns (form, user)
    """
    if request.loggedin().owner:
        if request.method == "POST":
            new_user_form = NewUserForm(request.POST)
            if new_user_form.is_active():
                if new_user_form.is_valid():
                    user, auth_user = _createNewUser(new_user_form.cleaned_data["email"], request.loggedin().organization)
                    return NewUserForm(), user
                else:
                    return new_user_form, False
            else:
                return NewUserForm(), False
        else:
            return NewUserForm(), False
    return None, False

def _processNewTagForm(request):
    """
    Return a NewTagForm if the user is admin, and create a Tag if POST
    Returns None if not admin
    """
    if request.loggedin().owner or request.loggedin().tag_creator:
        if request.method == "POST":
            new_tag_form = NewTagForm(request.POST, request = request)
            if new_tag_form.is_active():
                if new_tag_form.is_valid():
                    with transaction.atomic():
                        new_tag = Tag.objects.create(organization = request.loggedin().organization,
                                                     name = new_tag_form.cleaned_data["name"])
                        UserTag.objects.create(user = request.loggedin(), tag = new_tag, owns_tag = True)
                else:
                    return new_tag_form
        return NewTagForm(request=request)
    return None

@login_required
def delete_tag(request, org_slug, tag_id):
    """
    Delete the tag pointed to by tag_id redirecting to tags:organization when done
    """
    org = request.loggedin().organization
    if org_slug != org.slug:
        raise Http404()
    if request.loggedin().owner or request.loggedin().tag_creator:
        try:
            tag = Tag.objects.get(pk=tag_id)
            if tag.organization.id == request.loggedin().organization.id:
                tag.delete()
        except Tag.DoesNotExist:
            pass
    return redirect(reverse("tags:organization", args=(org.slug,)))

@login_required
def delete_usertag(request, org_slug, tag_id, user_id):
    """
    Delete the usertag pointed to by tag_id + user_id, redirecting to tags:organization when done
    """
    org = request.loggedin().organization
    if org_slug != org.slug:
        raise Http404()
    if request.loggedin().owner or request.loggedin().tag_creator:
        try:
            usertag = UserTag.objects.get(tag__id = tag_id, user__id = user_id)
            if usertag.tag.organization == request.loggedin().organization:
                allowed = True
                if not request.loggedin().owner and not request.loggedin().tag_creator:
                    loggedin_usertag = usertag.tag.usertags.get(user = request.loggedin())
                    if not loggedin_usertag.owns_tag:
                        allowed = False
                if allowed:
                    usertag.delete()
        except UserTag.DoesNotExist:
            pass
    return redirect(reverse("tags:organization", args=(org.slug,)))

@login_required
def organization(request, org_slug):
    """
    Serve a page listing all tags the user is subscribed to (or all if admin), along with other users subscribed
    to those tags. Show create/delete-functions for Tags, Users and UserTags if the loggedin is admin
    """
    # "Return" 404 if the url doesn't match the logged in users organization
    org = request.loggedin().organization
    if org_slug != org.slug:
        raise Http404()

    # If the user was redirected from the registration page, set "token" to the first installation uuid for downloading
    # TODO: This is temporary since we don't have a client yet
    token = False
    if request.GET.get("token", None) is not None:
        installations = list(request.loggedin().installations.all())
        if len(installations) == 1:
            token = installations[0].uuid

    # Create form for creating new user if the loggedin is the owner of the organization
    # Handles POST to the form and returns the user if created
    new_user_form, new_user_created = _processNewUserForm(request)

    # Create form for creating new tags if the loggedin is owner or tag_creator
    # Handles POST to the form and creates new tags
    new_tag_form = _processNewTagForm(request)

    if request.loggedin().owner or request.loggedin().tag_creator:
        # Since this user is admin, it should be able to see all tags, including ones where it isn't subscribed
        # Create a lazy list of UserTags based on all tags available for the organization, and all marked as "owned"
        usertags = _getLazyTagCreatorUserTags(request)

        # If the user has the ability to add users to tags, we check if a valid AddUserForm has been submitted
        # Then validate it against the list of users not already added to that tag and then add the user
        if request.method == "POST" and request.POST.get("add_user_tag_id") is not None:
            try:
                tag_id = int(request.POST["add_user_tag_id"])
                tag = Tag.objects.get(pk=tag_id)
                add_user_form = AddUserForm(request.POST, tag_id=tag.id)
                add_user_form.fields['user'].queryset = add_user_form.fields['user'].queryset. \
                    filter(organization = request.loggedin().organization).exclude(usertags__tag = tag)
                if add_user_form.is_valid():
                    UserTag.objects.create(user = add_user_form.cleaned_data["user"], tag = tag, owns_tag = False)
            except Tag.DoesNotExist:
                pass
    else:
        # Fetch all usertags that this user subscribes to
        usertags = request.loggedin().usertags.all()

    return render(request, "tags/organization.html", {"TITLE": org.name,
                                                        "org":org,
                                                        "usertags":usertags,
                                                        "token": token,
                                                        "new_tag_form":new_tag_form,
                                                        "new_user_form":new_user_form,
                                                        "new_user_created":new_user_created})


# -*- coding: utf-8 -*-
from __future__ import print_function

import oss2, sys, glob, os

endpoint = 'http://cn-shanghai.oss.aliyun-inc.com'
destBaseUrl = 'http://skycloud-oss.cn-shanghai.oss.aliyun-inc.com/'

auth = oss2.Auth(os.environ['THERA_OSS_ACCESS_ID'], os.environ['THERA_OSS_ACCESS_KEY'])
bucket = oss2.Bucket(auth, endpoint, 'skycloud-oss')

# progress callback
def percentage(consumed_bytes, total_bytes):
    if total_bytes:
        rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
        print('\r{0}% '.format(rate), end='')
        sys.stdout.flush()

# upload
for file in glob.glob('out/*.zip'):
    if file != 'out/thera-mac-symbols.zip':
        destPath = os.path.join('thera', 'ide', 'auto', os.path.basename(file))
        print('Uploading ' + file + ' to ' + destBaseUrl + destPath)
        bucket.put_object_from_file(destPath, file, progress_callback=percentage)
        print('Uploaded')


import tensorflow as tf
import numpy as np
import wave
from ProcessData import open_file, write_to_file

from AudioReader import *

class WaveNet:
    def __init__(self):
        self.graph = tf.Graph()
        self.data = tf.placeholder(tf.float32, shape=(1, 98473, 1, 256))
        self.skip_sum = None

    def dilated_causle_convolution(self, x, dilation_value, filter_out, filter_width=2, name=None):
        channels = x.shape[3]
        padding = (filter_width - 1) * dilation_value
        x = tf.pad(x, tf.constant([(0, 0,), (0, 0,), (1, 0), (0, 0)]) * padding)
        filters = tf.get_variable("%s_weights" %name, [1, filter_width, channels, filter_out])
        dilations = [1, 1, dilation_value, 1]
        x = tf.nn.conv2d(x, filters, [1, 1, 1, 1], "VALID", dilations=dilations, name="%s_conv" %name)
        return x

    def skip_connection(self, x, name="skip"):
        skip = self.dilated_causle_convolution(x, 1, 256, 1, name="%s_1x1_conv1" %name)
        skip = tf.reduce_sum(skip, 2, keepdims=True)
        skip = tf.nn.relu(skip)
        skip = self.dilated_causle_convolution(skip, 1, 256, 1, name="%s_1x1_conv2" %name)
        skip = tf.nn.relu(skip)
        skip = self.dilated_causle_convolution(skip, 1, 256, 1, name="%s_1x1_conv3" %name)
        return tf.nn.softmax(skip)

    def residual_block(self, x, dilation_value, out_channels=32, name=None):
        input_tensor = x
        tanh = self.dilated_causle_convolution(x, dilation_value, out_channels, name="%s_tanh_conv" %name)
        sigmoid = self.dilated_causle_convolution(x, dilation_value, out_channels, name="%s_sigmoid_conv" %name)

        tanh = tf.math.tanh(tanh)
        sigmoid = tf.math.sigmoid(sigmoid)

        x = tf.math.multiply(tanh, sigmoid)
        skip_conv = self.dilated_causle_convolution(x, 1, out_channels, 1, name="%s_skip_conv" %name)
        skip_conv = tf.slice(skip_conv, [0, 360, 0, 0], [-1, skip_conv.shape[1] - 360, -1, -1])
        if self.skip_sum is None:
            self.skip_sum = skip_conv
        else:
            self.skip_sum += skip_conv
        self.skip_sum = tf.add(self.skip_sum, skip_conv)
        x = self.dilated_causle_convolution(x, 1, out_channels, 1, name="%s_1x1_conv" %name)
        return input_tensor + x

    def model(self):
        x = self.dilated_causle_convolution(self.data, 1, 32, name="input_conv")
        x = self.residual_block(x, 1, name="res_1")
        x = self.residual_block(x, 2, name="res_2")
        x = self.residual_block(x, 4, name="res_3")
        x = self.residual_block(x, 8, name="res_4")
        x = self.residual_block(x, 16, name="res_5")
        x = self.skip_connection(self.skip_sum)
        shape = self.data.shape
        usable_data = tf.slice(self.data, [0, 360, 0, 0], [-1, shape[1] - 360, -1, -1])
        print(x.shape)
        print(usable_data.shape)
        print(self.data.shape)
        loss = tf.losses.softmax_cross_entropy(usable_data, x)
        return x, loss

loaded_wav, sr = open_file("p225_001.wav")

waveNet = WaveNet()

with tf.Session() as session:

    x, loss = waveNet.model()

    optimizer = tf.train.AdamOptimizer().minimize(loss)

    tf.global_variables_initializer().run()
    print("initialized")

    counter = 100
    while counter > 0:
        output = session.run([optimizer, loss, x], feed_dict={waveNet.data: loaded_wav})
        counter -= 1
        print(counter)

waveform = [max(i[0]) for i in output[2][0]]
print(waveform)
write_to_file(waveform, sr)


from base64 import decode
from django.urls import resolve, reverse
from recipes.views import category
from .test_recipe_base import RecipeTestBase

class RecipeViewsTest(RecipeTestBase):
    def test_recipe_category_views_function_is_correct(self):
        category_view = resolve(
            reverse('recipes:category', kwargs={'category_id': 1}))
        self.assertIs(category_view.func, category)

    def test_recipe_category_view_return_404_if_no_recipes_found(self):
        response = self.client.get(
            reverse('recipes:category', kwargs={'category_id': 1000}))
        self.assertEqual(response.status_code, 404)

    def test_recipe_category_template_loads_recipes(self):
        needed_title = 'test recipe'
        recipe = self.make_recipe(title=needed_title)
        response = self.client.get(reverse('recipes:category', kwargs={
                                   'category_id': recipe.category_id}))
        self.assertIn(needed_title, response.content.decode('utf-8'))

    def test_recipe_category_template_dont_show_not_published_recipes(self):
        needed_title = 'Test not published recipes'
        recipe = self.make_recipe(title=needed_title, is_published=False)
        response = self.client.get(
            reverse('recipes:category', kwargs={'category_id': recipe.category_id}))
        self.assertNotIn(needed_title, response.content.decode('utf-8'))


def divide_n_conquer(nums, left, right):
    # base case
    if left == right:
        return nums[left]
    p = (left + right) // 2

    left_sum = divide_n_conquer(nums, left, p)
    right_sum = divide_n_conquer(nums, p + 1, right)
    cross_sum = cross_sum_fn(nums, left, right, p)

    return max(left_sum, right_sum, cross_sum)

# start at p, go left to beginning finding max_left_sum
# then go right from p to the end finding max_right_sum
# then return max_left_sum + max_right_sum
def cross_sum_fn(nums, left, right, p):

    max_left_sum = float('-inf')
    max_right_sum = float('-inf')
    cur = 0

    for i in range(p, left - 1, -1):
        cur += nums[i]
        max_left_sum = max(cur, max_left_sum)

    cur = 0
    for i in range(p + 1, right + 1):
        cur += nums[i]
        max_right_sum = max(cur, max_right_sum)
    return max_left_sum + max_right_sum

# Kadane's algorithm based on the following formula:
# dp[i] = max(dp[i-1], 0) + arr[i]
def kadane(arr):
    dp = [arr[0]]

    for i in range(1, len(arr)):
        dp.append(max(dp[i - 1], 0) + arr[i])
    print(dp)
    return max(dp)

arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print (divide_n_conquer(arr, 0, len(arr) - 1))
print (kadane(arr))
arr = [0, 1, 2, 3, -1]
print (kadane(arr))
arr = [-1, 0, 1, 2, 3]
print (kadane(arr))


import csv

from sys import exit

try:
    # csv 파일을 연다.
    f = open('crimedata.csv', 'r', encoding='cp949')
    # 만약 예외가 발생한다면,
except Exception as ex:
    # 예외 메세지를 출력하고 종료한다.
    print(str(ex))
    exit(0)

# csv를 읽어올 수 있도록 준비한다.
data = csv.reader(f)

crimedict = {}
crimenums_type = {}
citynames = []
crimenames = []
hardcrimenames = []
linenum = 1

# csv 파일로 부터 한 줄씩 읽어온다.
for row in data:
    # indexcut: 줄에서 도시별 범죄가 나와있는 부분만 잘라낸 것.
    indexcut = row[3:]
    # 만약 첫번째 줄이라면
    if linenum == 1:
        # 줄에서 도시 이름을 하나씩 가져와서,
        for cities in indexcut:
            # citynames에 추가한다.
            citynames.append(cities)
            # crimedict에 도시 이름을 키로 하여 새로운 dict를 만든다.
            crimedict[cities] = {}
    else:
        # 범죄의 이름을 crimenames에 추가한다.
        crimenames.append(row[1])
        # 만약 범죄 유형이 강력범죄라면,
        if row[0] == '강력범죄':
            # 범죄의 이름을 hardcrimenames에 추가한다.
            hardcrimenames.append(row[1])
            # citynames에서 각각의 도시 이름을 가져온다.
        for i in range(len(citynames)):
            # 횟수를 가져오되, csv 파일 내에서 천단위를 구분하기 위해 넣은 콤마를 없앤다.
            num = indexcut[i].replace(',', '')
            # crimedict에 각 도시별로 범죄유형과 해당 유형 범죄의 횟수를 추가한다. -로 표시된 것은 0회에 해당하는 것이다.
            crimedict[citynames[i]][row[1]] = int(
                num if num.isdecimal() else 0)
    # 줄 번호를 1 늘린다.
    linenum += 1

totalcrime = 0
totalcrimemax = -1
totalcrimemin = 500000
maxname = None
minname = None

# crimenums_type: 범죄 유형별 횟수를 세기 위한 dict.
for name in crimenames:
    crimenums_type[name] = 0

# 각각의 도시에 대해,
for c in citynames:
    # crimedict에서 범죄 유형 데이터를 가져온다.
    dat = crimedict[c]
    # 그 중 값(범죄 횟수)만 가져온다.
    crimenums_city = list(dat.values())
    crime_city = 0

    for i in range(len(crimenums_city)):
        # crime_city: 각 도시별 일어난 범죄 횟수의 합
        crime_city += crimenums_city[i]
        # 각 도시에서 일어난 범죄 횟수를 다시 범죄 유형별로 정리하고 합산한다.
        crimenums_type[crimenames[i]] += crimenums_city[i]
        # 만약 그 도시에서 일어난 범죄 횟수가 최대/최소 값이라면, 도시 이름과 최대/최소 횟수를 갱신한다.
    if crime_city > totalcrimemax:
        totalcrimemax = crime_city
        maxname = c
    if crime_city < totalcrimemin:
        totalcrimemin = crime_city
        minname = c
    # totalcrime: 일어난 총 범죄 횟수
    totalcrime += crime_city

hardcrime = 0

for crimenames in hardcrimenames:
    # 범죄 유형 중 강력범죄가 일어난 횟수만 합산한다(hardcrimes).
    hardcrime += crimenums_type[crimenames]

try:
    # 최대/최소 값과 도시 이름 출력
    print('범죄가 가장 많은 지역은 {} 이고, 횟수는 {}회 입니다.'.format(maxname, totalcrimemax))
    print('범죄가 가장 적은 지역은 {} 이고, 횟수는 {}회 입니다.'.format(minname, totalcrimemin))
    # 도시 별 평균 범죄 횟수는 전체 범죄 횟수를 도시 수로 나눈 것이다.
    print('지역 당 평균 범죄 횟수는 %.02f회 입니다.' % (float(totalcrime) / len(citynames)))
    # 강력 범죄의 비율은 강력 범죄 횟수를 전체 범죄 횟수로 나눈 것이다.
    print('전체 범죄 중 강력범죄의 비율은 %.02f%% 입니다.' %
          (float(hardcrime) / totalcrime * 100))
# 만약 0으로 나누는 에러가 발생하는 경우
except ZeroDivisionError as err:
    # 에러메세지를 출력하고 종료한다.
    print('0으로 나눌 수 없습니다!')
    exit(0)


def get_number_from_position(list_of_number, asked_position):
    # check if the asked position is inside the list
    if len(list_of_number) >= asked_position:
        value_at_position = list_of_number[asked_position - 1]
        print(f"The number {value_at_position} is at the position {asked_position}")
    else:
        print("invalid position")

if __name__ == '__main__':

    number_list = [23, 45, 234, 67, 98, 45, 234, 79, 23]

    # ask the user for a position
    try:
        user_input = int(input("whats the position of the object? "))

        # pass the position to a new function (to create) called get_number_from_position
        get_number_from_position(number_list, user_input)
    except:
        print(f'Invalid number')


from pbprocesstools.pbpt_q_process import PBPTQProcessTool
import logging
import os
import shutil
import rsgislib
import rsgislib.vectorutils
import rsgislib.imagecalc

logger = logging.getLogger(__name__)

class RasteriseQAExtras(PBPTQProcessTool):

    def __init__(self):
        super().__init__(cmd_name='rasterise_qa_xtrs.py', descript=None)

    def do_processing(self, **kwargs):

        gapfill_qa_img = os.path.join(self.params['tmp_dir'], 'gapfill_qa.kea')
        rsgislib.vectorutils.rasteriseVecLyr(self.params['gapfill_qa_vec'], self.params['gapfill_qa_lyr'],
                                             self.params['tile_img'], gapfill_qa_img, gdalformat="KEA",
                                             burnVal=1, datatype=rsgislib.TYPE_8UINT, vecAtt=None, vecExt=False,
                                             thematic=True, nodata=0)

        french_img = os.path.join(self.params['tmp_dir'], 'french_mangroves.kea')
        rsgislib.vectorutils.rasteriseVecLyr(self.params['french_qa_vec'], self.params['french_qa_lyr'],
                                             self.params['tile_img'], french_img, gdalformat="KEA",
                                             burnVal=1, datatype=rsgislib.TYPE_8UINT, vecAtt=None, vecExt=False,
                                             thematic=True, nodata=0)

        bandDefns = []
        bandDefns.append(rsgislib.imagecalc.BandDefn('qa', gapfill_qa_img, 1))
        bandDefns.append(rsgislib.imagecalc.BandDefn('french', french_img, 1))
        rsgislib.imagecalc.bandMath(self.params['out_file'], '(qa==1)||(french==1)?1:0', 'KEA', rsgislib.TYPE_8UINT, bandDefns)

        if os.path.exists(self.params['tmp_dir']):
            shutil.rmtree(self.params['tmp_dir'])

    def required_fields(self, **kwargs):
        return ["tile_img", "gapfill_qa_vec", "gapfill_qa_lyr", "french_qa_vec", "french_qa_lyr", "out_file", "tmp_dir"]

    def outputs_present(self, **kwargs):
        files_dict = dict()
        files_dict[self.params['out_file']] = 'gdal_image'
        return self.check_files(files_dict)

    def remove_outputs(self, **kwargs):
        # Remove the output file.
        if os.path.exists(self.params['out_file']):
            os.remove(self.params['out_file'])

        # Reset the tmp dir
        if os.path.exists(self.params['tmp_dir']):
            shutil.rmtree(self.params['tmp_dir'])
        os.mkdir(self.params['tmp_dir'])

if __name__ == "__main__":
    RasteriseQAExtras().std_run()


#!/home/fengxiang/anaconda3/envs/wrfout/bin/python
# -*- encoding: utf-8 -*-
'''
Description:
读micpas的探空资料, 第5类
02时的探空没有温度和露点温度, 故不读它
且该脚本只读取了郑州站的数据
height是海拔高度(m)

那曲站数据为例
站号   经度  纬度  海拔高度 单站内容长度
55299 92.07 31.48 4508.2 1098
   588.3   450.8   13.8   4.1   248   5.1
   588.3   450.8   13.8   4.1   248   5
   588.3   450.8   13.8   4.1   248   5.1
   588.3   450.8   13.8   4.1   248   5
气压  位势高度(10gpm) 温度  露点  风向  风速

-----------------------------------------
Time             :2021/07/26 09:48:05
Author           :Forxd
Version          :1.0
'''

# %%
from typing import Pattern
import pandas as pd
import numpy as np
import xarray as xr
import re
import sys
import os
from io import StringIO

# from xarray.core import variable
from global_variable import station_dic
from multiprocessing import Pool

# from data_process_main import GetData

# %%
### 可以使用nmc改写这个程序
# from nmc_met_io.read_micaps import read_micaps_1, read_micaps_2, read_micaps_5
# flnm = '/mnt/zfm_18T/fengxiang/DATA/UPAR/202107_upar/20210706020000.000'
# ds  = read_micaps_5(flnm)
# ds[ds['ID']=='57083']

# %%
class GetMicaps():

    def __init__(self, station):
        pass
        self.station = station
        self.station_number = station['number']
        self.path_micaps = '/mnt/zfm_18T/fengxiang/DATA/UPAR/202107_upar/'

    def read_data_once(self, flnm):
        """根据初始的txt文件
        筛选出需要的站点数据
        """
        with open(flnm, 'r', encoding='gbk') as f:
            whole_text = f.read()
        # pattern = '[0-9]+\s+\S+\.\d+\s+\S+\.\d+\s+\d+\s+\d+'
        # pattern = '[0-9]{4,5}\s{1}\S+\s+\S+\s+\d+\s+\d+'
        # pattern = '[0-9]{4,5}\s{1}\S+\s+\S+\s+\d+.{0,1}\d+\s\d+'
        # pattern = '[0-9]{4,5}\s{1}\S+\s+\S+\s+\d+.{0,1}\d+\s+'
        pattern = '[0-9]{4,5} \S+ \S+ \S+ \d+'
        # pattern = '[0-9]{4,5} \S+ \S+ \d\d+\S+ \d+'
        data = re.split(pattern, whole_text)

        dd = data.pop(0)  # 去掉首行的信息
        # print(data[0])
        seg_data = re.findall(pattern, whole_text)
        # print(seg_data[1])
        length = len(seg_data)
        station = seg_data[0].split()[0]
        # print(seg_data[1])
        # print(station)

        for i in range(length):
            # if
            station = seg_data[i]
            # print(station)
            station_number = station.split()[0]
            # print(station_number)
            if str(station_number) == str(self.station_number):
                pass
                # print(station_number)
                df_data = data[i]
                # print(df_data)
                data_file = StringIO(df_data)  # 将这一个站点的数据，模拟到文件中去
                return data_file

    def transpose_data_once(self, data_file):
        """将站点数据文件转换为df格式,
        再转为DataArray
        data_file, 字符串生成的虚假文件
        """
        # data_file = self.read_data_once()
        col_names = ['pressure', 'height', 'temp', 'td', 'wind_d', 'wind_s']
        df = pd.read_table(
            data_file,  # 由字符串虚拟的文件
            sep='\\s+',
            skiprows=1,
            usecols=[0,1,2,3,4,5],
            names=col_names,
        )
        # print(df)
        df = df.where(df < 9999, np.nan)  # 将缺省值赋值为NaN
        df = df.drop_duplicates('pressure', 'first')  # 返回副本
        df = df.set_index(['pressure'])  # 将pressure这一列设为index
        df.columns.name = 'variable'  # 还必须是这个名称

        # print(df['height'].min())
        ## 换算位势高度单位， 位势10m--> 位势m
        df['height'] = df['height']*10
        df['height_agl'] = df['height']-self.station['height']
        print(df['height_agl'])
        da = xr.DataArray(df)
        # print('读成功')
        return da

    def interp_data(self, da):
        """对这个读入的原始站点数据进行插值处理

        Args:
            da (DataArray): df直接转换成的DataArray

        Returns:
            [Dataset]: 各变量组成的Dataset
        """
        var_list = list(da.coords['variable'].values)
        # print(var_list)
        # pressure_level = np.arange(800,100,-1)
        pressure_level = np.arange(990,190,-10)
        var_list_process = []
        vards = xr.Dataset()
        for var in var_list:
            dda = da.sel(variable=var)
            dc = dda.dropna(dim='pressure')
            # print(var)
            # ddc = dc.interp(pressure=pressure_level, kwargs={'fill_value':'extrapolate'})
            ddc = dc.interp(pressure=pressure_level)
            vards[var] = ddc
        # print("返回")
        # print(dc)
        # return da
        # #### 在这里计算U,V

        # vards['U'] = xr.ufuncs.sin(vards['wind_d']/180*np.pi)*vards['wind_s']*(-1)
        # vards['V'] = xr.ufuncs.cos(vards['wind_d']/180*np.pi)*vards['wind_s']*(-1)
        vards['u'] = -1*np.sin(vards['wind_d']/180*np.pi)*vards['wind_s']
        vards['v'] = -1*np.cos(vards['wind_d']/180*np.pi)*vards['wind_s']
        # v = -1*np.cos(ddf['wind_angle']/180*np.pi)*ddf['wind_speed']
        vards = vards.drop_vars(['wind_d', 'wind_s'])
        return vards

    def data_micaps(self, ):

        fl_list = os.popen('ls {}2021*.000'.format(self.path_micaps))  # 打开一个管道
        fl_list = fl_list.read().split()
        # dds_list = []
        aa = fl_list
        # print(aa)

        aa.sort()  # 排一下顺序，这个是对列表本身进行操作
        da_time = []  # 每个时次变量的列表
        ttt = []  # 时间序列列表

        for flnm in aa:
            pass
            fl_time = flnm[-18:-8]
            tt = pd.to_datetime(fl_time, format='%Y%m%d%H')
            ## 转为世界时
            tt = tt - pd.Timedelta(hours=8)
            # print(tt)
            ## 这时间是不规则的
            file_name = os.path.join(self.path_micaps, flnm)
            print(file_name)
            data_file = self.read_data_once(file_name)
            # print(data_file)
            if not data_file:
                # return None
                continue
            ttt.append(tt)
            # print(ttt)
            da = self.transpose_data_once(data_file)
            ds_interp = self.interp_data(da)

            da_time.append(ds_interp)
        ds_return = xr.concat(da_time, pd.Index(ttt, name='time'))
        return ds_return

############ 测试开始 ############
def get_one_station():
    ds_nc = xr.Dataset()
    station = station_dic['ZhenZhou']
    gd = GetMicaps(station=station)
    ds = gd.data_micaps()
    ## 位势高度更名为geopt
    ds = ds.rename({'height':'geopt'})
    ds.to_netcdf('/mnt/zfm_18T/fengxiang/HeNan/Data/upar_zhenzhou.nc')
    return ds

# %%
# aa.time
# aa.to_netcdf('/mnt/zfm_18T/fengxiang/HeNan/Data/upar_zhenzhou.nc')

# %%
if __name__ == '__main__':
    pass
    aa = get_one_station()
    # %%
    ##### 单进程
    # ds_nc = xr.Dataset()
    # for key in station_dic:

    #     print("读取 %s 站的数据"%key)
    #     station = station_dic[key]
    #     print(station['name'], station['number'])
    #     # print(station_number)
    #     gd = GetMicaps(station=station)
    #     ds = gd.data_micaps()
    # #     ds_diagnostic = gd.caculate_diagnostic(ds)
    # #     ## 将原来的变量和计算的诊断变量合并为一个DataArray
    # #     ds_return = xr.merge([ds, ds_diagnostic])
    # #     ds_return = ds_return.where(ds_return['height']>0, drop=True)
    # #     dda = ds_return.to_array()
    # #     ## 不同站点的数据组合为一个Dataset
    # #     ds_nc[key] = dda
    # # ds_nc.to_netcdf('/mnt/zfm_18T/fengxiang/DATA/UPAR/upar_2021_station.nc')

#### 多进程
    # ds_nc = xr.Dataset()

    # %%
    # def get_one(station):
    #     """读一个站点的数据
    #     """
    #     gd = GetMicaps(station=station)
    #     ds = gd.data_micaps()
    #     ds_diagnostic = gd.caculate_diagnostic(ds)
    #     ## 将原来的变量和计算的诊断变量合并为一个DataArray
    #     ds_return = xr.merge([ds, ds_diagnostic])
    #     # ds_return = ds_return.where(ds_return['height']>0, drop=True)
    #     dda = ds_return.to_array()
    #     return dda

    # pool = Pool(6)
    # result = []
    # for key in station_dic:
    #     print("读取 %s 站的数据"%key)
    #     station = station_dic[key]
    #     tr = pool.apply_async(get_one, args=(station,))
    #     result.append(tr)
    # pool.close()
    # pool.join()

    # ds_nc = xr.Dataset()
    # num = len(station_dic)

    # for i,j in zip(result,station_dic):
    #     ds_nc[j] = i.get()
    # print(ds_nc)

    # # %%
    # # ds_nc['LinZhi'].sel(variable='height').isel(time=0)
    # # ds_return = ds_return.where(ds_return['height']>0, drop=True)
    # dds = ds_nc.where(ds_nc.sel(variable='height')>0, drop=True)

    # # ds_all = get_station_average(dds)

    # # ds_all.to_netcdf('/mnt/zfm_18T/fengxiang/DATA/UPAR/upar_2016_all_station2.nc')

# %%


import os
import os.path
import sys
import shutil
import subprocess

#we have to have the root dir of the repository in sys.path.
repository_root = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
sys.path = [repository_root] + sys.path
import docgen
import bindings.get_info

if __name__ == '__main__':
    print("Building documentation...")
    info=bindings.get_info.get_all_info()
    docgen.prepare_docs(info)
    dest_dir = os.path.join(repository_root, 'build', 'documentation')

    node_reference = docgen.make_node_reference(info)
    c_api_docs=docgen.make_c_api(info)
    enum_docs=docgen.make_enumerations(info)
    if os.path.exists(dest_dir):
        shutil.rmtree(dest_dir)

    shutil.copytree(os.path.join(repository_root, 'documentation'), dest_dir)

    with open(os.path.join(dest_dir, 'node_reference.asciidoc'), 'w') as f:
        f.write(node_reference)
    with open(os.path.join(dest_dir, 'c_api.asciidoc'), 'w') as f:
        f.write(c_api_docs)
    with open(os.path.join(dest_dir, 'enumerations.asciidoc'), 'w') as f:
        f.write(enum_docs)

    subprocess.call(["asciidoctor", os.path.join(dest_dir, 'libaudioverse_manual.asciidoc')], stderr= subprocess.STDOUT, shell = True)

    if not os.path.exists(os.path.join(repository_root, "build", "artifacts")):
        os.makedirs(os.path.join(repository_root, "build", "artifacts"))
    shutil.copy(os.path.join(repository_root, "build", "documentation", "libaudioverse_manual.html"),
    os.path.join(repository_root, "build", "artifacts"))


# Skeleton Program for the AQA AS Summer 2018 examinationTea
# this code should be used in conjunction with the Preliminary Material
# written by the AQA AS Programmer Team
# developed in a Python 3 environment

# Version Number : 1.6

SPACE = ' '
EOL = '#'
EMPTYSTRING = ''

def ReportError(s):
    print('{0:<5}'.format('*'),s,'{0:>5}'.format('*'))

def StripLeadingSpaces(Transmission):
    TransmissionLength = len(Transmission)
    if TransmissionLength > 0:
        FirstSignal = Transmission[0]
        while FirstSignal == SPACE and TransmissionLength > 0:
            TransmissionLength -= 1
            Transmission = Transmission[1:]
            if TransmissionLength > 0:
                FirstSignal = Transmission[0]
    if TransmissionLength == 0:
        ReportError("No signal received")
    return Transmission

def StripTrailingSpaces(Transmission):
    LastChar = len(Transmission) - 1
    while Transmission[LastChar] == SPACE:
        LastChar -= 1
        Transmission = Transmission[:-1]
    return Transmission

def GetTransmission():
  no_file="EMPTY"
  while no_file.lower()[0]!='y' and no_file.lower()[0]!='n':
    no_file=input("Do you already have a file with morse code in (y/n): ")
  if no_file.lower()[0]!='y':
    create_morse_file()
    FileName='tempfile.txt'
  else:
    FileName = input("Enter file name: ")
  try:
    FileHandle = open(FileName, 'r+')
    Transmission = FileHandle.readline()
    FileHandle.close()
    Transmission = StripLeadingSpaces(Transmission)
    if len(Transmission) > 0:
      Transmission = StripTrailingSpaces(Transmission)
      Transmission = Transmission + EOL
  except:
    ReportError("No transmission found")
    Transmission = EMPTYSTRING
  return Transmission

def create_morse_file():
  morse_code=input("What is the morse code you want to be translated (slashed between words): ")

  morse_code=list(morse_code)
  for i,e in enumerate(morse_code):
    if e=='/' and morse_code[i-1]==" ":
      del morse_code[i-1]
  for i,e in enumerate(morse_code):
    if e=='-':
      morse_code[i]="=== "
    elif e=='.':
      morse_code[i]="= "
    elif e==" ":
      morse_code[i]="  "
    elif e=="/":
      morse_code[i]="      "
    else:
      return None
  with open("tempfile.txt",'w') as f:
    f.write("".join(letter for letter in morse_code))

def GetNextSymbol(i, Transmission):
    if Transmission[i] == EOL:
        print()
        print("End of transmission")
        Symbol = EMPTYSTRING
    else:
        SymbolLength = 0
        Signal = Transmission[i]
        while Signal != SPACE and Signal != EOL:
            i += 1
            Signal = Transmission[i]
            SymbolLength += 1
        if SymbolLength == 1:
            Symbol = '.'
        elif SymbolLength == 3:
            Symbol = '-'
        elif SymbolLength == 0:
            Symbol = SPACE
        else:
            ReportError("Non-standard symbol received")
            Symbol = EMPTYSTRING
    return i, Symbol

def GetNextLetter(i, Transmission):
    SymbolString = EMPTYSTRING
    LetterEnd = False
    while not LetterEnd:
        i, Symbol = GetNextSymbol(i, Transmission)
        if Symbol == SPACE:
            LetterEnd = True
            i += 4
        elif Transmission[i] == EOL:
            LetterEnd = True
        elif Transmission[i + 1] == SPACE and Transmission[i + 2] == SPACE:
            LetterEnd = True
            i += 3
        else:
            i += 1
        SymbolString = SymbolString + Symbol
    return i, SymbolString

def Decode(CodedLetter, Dash, Letter, Dot):
    CodedLetterLength = len(CodedLetter)
    Pointer = 0
    for i in range(CodedLetterLength):
        Symbol = CodedLetter[i]
        if Symbol == SPACE:
            return SPACE
        elif Symbol == '-':
            Pointer = Dash[Pointer]
        else:

            Pointer = Dot[Pointer]
    return Letter[Pointer]

def ReceiveMorseCode(Dash, Letter, Dot):
    PlainText = EMPTYSTRING
    MorseCodeString = EMPTYSTRING
    Transmission = GetTransmission()
    LastChar = len(Transmission) - 1
    i = 0
    while i < LastChar:
        i, CodedLetter = GetNextLetter(i, Transmission)
        MorseCodeString = MorseCodeString + SPACE + CodedLetter
        PlainTextLetter = Decode(CodedLetter, Dash, Letter, Dot)
        PlainText = PlainText + PlainTextLetter
    print(PlainText)

def SendMorseCode(MorseCode):
    PlainText = input("Enter your message (uppercase letters and spaces only): ")
    PlainTextLength = len(PlainText)
    MorseCodeString = EMPTYSTRING
    for i in range(PlainTextLength):
        PlainTextLetter = PlainText[i]
        if PlainTextLetter == SPACE:
            Index = 0
        else:
            Index = ord(PlainTextLetter) - ord('A') + 1
        CodedLetter = MorseCode[Index]
        MorseCodeString = MorseCodeString + CodedLetter + SPACE
    print(MorseCodeString)

def DisplayMenu():
    print()
    print("Main Menu")
    print("=========")
    print("R - Receive Morse code")
    print("S - Send Morse code")
    print("X - Exit program")
    print()

def GetMenuOption():
    MenuOption = EMPTYSTRING
    while len(MenuOption) != 1 and MenuOption.upper() !="R" and MenuOption.upper()!="S" and MenuOption.upper()!= "X" :
        MenuOption = input("Enter the option, either R,S,X: ")
    return MenuOption.upper()

def SendReceiveMessages():
    Dash = [20,23,0,0,24,1,0,17,0,21,0,25,0,15,11,0,0,0,0,22,13,0,0,10,0,0,0]
    Dot = [5,18,0,0,2,9,0,26,0,19,0,3,0,7,4,0,0,0,12,8,14,6,0,16,0,0,0]
    Letter = [' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

    MorseCode = [' ','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']

    ProgramEnd = False
    while not ProgramEnd:
        DisplayMenu()
        MenuOption = GetMenuOption()
        if MenuOption == 'R':
            ReceiveMorseCode(Dash, Letter, Dot)
        elif MenuOption == 'S':
            SendMorseCode(MorseCode)
        elif MenuOption == 'X':
            ProgramEnd = True

if __name__ == "__main__":
    SendReceiveMessages()


import os
import tempfile

from django.conf import settings
from django.test import TestCase

from cities import models, utils

STATES_FILE = """code,abbr,name
12,AC,Acre
35,SP,São Paulo
"""

CITIES_FILE = """code,name,state
120001,Acrelândia,AC
350330,Araras,SP
"""

def save_content_to_tmp_file(content):
    filename = os.path.join(tempfile.mkdtemp(), "testing.txt")
    with open(filename, "w", encoding="utf-8") as f:
        f.write(content)
    return filename

class UtilsTest(TestCase):
    def test_get_states_filename(self):
        """Should get the full path to the states data file"""
        directory = utils.get_states_filename("Brazil")
        expected = os.path.join(settings.CITIES_DATA_LOCATION, "brazil", "states.csv")
        self.assertEqual(directory, expected)

    def test_get_cities_filename(self):
        """Should get the full path to the cities data file"""
        directory = utils.get_cities_filename("Brazil")
        expected = os.path.join(settings.CITIES_DATA_LOCATION, "brazil", "cities.csv")
        self.assertEqual(directory, expected)

    def test_load_states(self):
        """Should load the correct states from the file"""
        filename = save_content_to_tmp_file(STATES_FILE)
        utils.load_states_from_file(filename)

        acre = models.State.objects.get(code=12)
        sao_paulo = models.State.objects.get(code=35)

        self.assertEqual("AC", acre.abbr)
        self.assertEqual("Acre", acre.name)

        self.assertEqual("SP", sao_paulo.abbr)
        self.assertEqual("São Paulo", sao_paulo.name)

    def test_load_cities(self):
        """Should load the correct cities from the file"""
        states_file = save_content_to_tmp_file(STATES_FILE)
        cities_file = save_content_to_tmp_file(CITIES_FILE)
        utils.load_states_from_file(states_file)
        utils.load_cities_from_file(cities_file)

        acrelandia = models.City.objects.get(code=120001)
        araras = models.City.objects.get(code=350330)

        self.assertEqual("AC", acrelandia.state.abbr)
        self.assertEqual("Acrelândia", acrelandia.name)
        self.assertEqual("acrelandia", acrelandia.search_name)

        self.assertEqual("SP", araras.state.abbr)
        self.assertEqual("Araras", araras.name)
        self.assertEqual("araras", araras.search_name)