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

# In[1]:

import pandas as pd
import numpy as np
import requests
import sys
import pymysql
import schedule
from datetime import timedelta
from datetime import datetime

# In[2]:

def connection():
    """Conecta com o banco de dados.

    c, conn = connection()

    Return
    ----------------------
    c    : cursor - objeto.
    conn : connection - objeto.

    """
    conn = pymysql.connect(user='root',
                           password='',
                           db='tpf',
                           charset='utf8mb4',
                           cursorclass=pymysql.cursors.DictCursor)
    c = conn.cursor()
    return c, conn

# In[3]:

def get_rotulos(x):
    """Acessa a API que fornece os rótulos, também chamados de serviços, de determinada empresa.

    df = get_rotulos(x)

    Parameters
    ----------
    x    : id da empresa - int.

    Return
    ----------------------
    df    : dataframe com os rótulos de determinada empresa - dataframe.

    """
    df = pd.DataFrame((requests.get('http://backend.rassystem.com.br/app/v1/api/filiais/' + str(x) + '/rotulos',
                                    auth=('', ''))).json())
    df['cad_empresa_id'] = df_filiais[df_filiais['idFilial'] == x]['idFilial'].values[0]
    return df

# In[4]:

def get_veiculo(id):
    """Acessa a API que fornece os veículos de determinado rótulo.

    df = get_veiculo(id)

    Parameters
    ----------
    id  : id do rótulo - int.

    Return
    ----------------------
    df    : dataframe com os veículos de determinado rótulo - dataframe.

    """
    df_veiculos = pd.DataFrame(
        requests.get('http://backend.rassystem.com.br/app/v1/api/rotulos/' + str(id) + '/veiculos',
                     auth=('', '')).json())
    df_veiculos['cad_servico_id'] = id
    df_veiculos['lote'] = \
        df_filiais[df_filiais['idFilial'] == df_rotulos[df_rotulos['id'] == id]['cad_empresa_id'].values[0]][
            'nome'].values[
            0]
    df_veiculos['servico'] = df_rotulos[df_rotulos['id'] == id]['nome'].values[0]
    return (df_veiculos)

# In[5]:

f = lambda x: dict(x['properties'], **{'longitude': x['geometry']['coordinates'][0]},
                   **{'latitude': x['geometry']['coordinates'][1]})

# In[6]:

def get_rastreio(id, servico, data_start, data_end):
    """Acessa a API que fornece os rastreios de determinado veículo.

    df = get_rastreio(id, data_start, data_end)

    Parameters
    ----------
    id  : id do veículo - int.
    data_start: data de ínicio da consulta - string no formato "%Y-%m-%dT07:30:00-03:00"
    data_end: data de fim da consulta - string no formato "%Y-%m-%dT07:30:00-03:00"

    Return
    ----------------------
    df    : dataframe com os dados de  rastreios do veículo -  dataframe.

    """
    req = requests.get("http://backend.rassystem.com.br/app/v1/api/veiculos/" + str(
        int(id)) + "/rastreio?dataInicio=" + data_start + "&dataFim=" + data_end, auth=('', ''))
    if req.status_code == 200:
        df = pd.DataFrame((map(f, req.json()['features'])))
        df['servico'] = servico
        return df

# In[8]:

def get_parada(id, servico, data_start, data_end):
    """Acessa a API que fornece os dados de parada de determinado veículo.

    df = get_parada(id, data_start, data_end)

    Parameters
    ----------
    id  : id do veículo - int.
    data_start: data de ínicio da consulta - string no formato "%Y-%m-%dT07:30:00-03:00"
    data_end: data de fim da consulta - string no formato "%Y-%m-%dT07:30:00-03:00"

    Return
    ----------------------
    df    : dataframe com os dados de parada do veículo -  dataframe.

    """
    req = requests.get("http://backend.rassystem.com.br/app/v1/api/veiculos/" + str(
        int(id)) + "/paradas?dataInicio=" + data_start + "&dataFim=" + data_end, auth=('', ''))
    if req.status_code == 200:
        df = pd.DataFrame((map(f, req.json()['features'])))
        df['servico'] = servico
        return df

# In[11]:

def proc(df):
    """Processa o dataframe com dados de rastreio ou dados de parada para conter as informações de
    data, hora, serviço, lote, chamada e placa.

    df = proc(df)

    Parameters
    ----------
    df : dataframe com os dados de parada ou rastreio do veículo -  dataframe.

    Return
    ----------------------
    df : dataframe processado com os dados de parada ou rastreio do veículo -  dataframe.

    """
    placa = lambda x: df_veiculos[df_veiculos['id'] == x]['nome'].iloc[0]
    # df['servico'] = df['idVeiculo'].apply(lambda x: df_veiculos[df_veiculos['id'] == x]['servico'].iloc[0])
    df['lote'] = df['idVeiculo'].apply(lambda x: df_veiculos[df_veiculos['id'] == x]['lote'].iloc[0])
    df['chamada'] = 'parada' if ('segundos' in df.columns) else 'rastreio'
    df['hora'] = df['data'].apply(lambda x: x.split('T')[1].split('.')[0])
    df['data'] = df['data'].apply(lambda x: x.split('T')[0])
    df['idVeiculo'] = df['idVeiculo'].apply(placa)
    return df

# In[12]:

def get_dataframes(data_start, data_end):
    """Chama as funções para consultar as API's nos limites entre data_start e data_end
    e obter os dados de parada e rastreio para todos os veículos cadastrados em todos os
    serviços de todas as empresas.

    df_filiais, df_rotulos, df_veiculos, df = get_dataframes(data_start, data_end)

    Parameters
    ----------
    data_start: data de ínicio da consulta - string no formato "%Y-%m-%dT07:30:00-03:00"
    data_end: data de fim da consulta - string no formato "%Y-%m-%dT07:30:00-03:00"

    Return
    ----------------------
    df_filiais = dataframe com os dados das empresas - dataframe.
    df_rotulos = dataframe com os dados dos serviço  - dataframe.
    df_veiculos = dataframe com os dados dos veículos - dataframe.
    df : dataframe com os dados de parada ou rastreio do veículo -  dataframe.

    """
    req = requests.get('http://backend.rassystem.com.br/app/v1/api/filiais', auth=('', ''))
    global df_filiais
    global df_rotulos
    global df_veiculos
    df_filiais = pd.DataFrame(req.json())
    df_rotulos = pd.concat(map(get_rotulos, df_filiais['idFilial']))
    df_veiculos = pd.concat(map(get_veiculo, df_rotulos['id']))

    df_veiculos.rename(columns={'placa': 'nome'}, inplace=True)

    ids = df_veiculos['id']

    servico = df_veiculos['servico']

    len_ids = len(ids)

    df_parada = pd.concat(map(get_parada, ids, servico, [data_start] * len_ids, [data_end] * len_ids))

    df_rastreio = pd.concat(map(get_rastreio, ids, servico, [data_start] * len_ids, [data_end] * len_ids))

    return df_filiais, df_rotulos, df_veiculos, pd.concat(map(proc, [df_rastreio, df_parada])).rename(
        columns={'idVeiculo': 'placa'})

# In[67]:

def rotina():
    """Gerencia as extrações e insere os dados no banco de dados

    rotina()

    """
    c, conn = connection()
    c.execute("select * from tb_log_extracao")
    conn.close()
    df_log_extracao = pd.DataFrame(c)
    # display(df_log_extracao)
    date_fail = df_log_extracao[df_log_extracao['status'] == 'fail'][['id', 'date_start', 'date_end']].values

    for i in date_fail:

        try:

            df_filiais, df_rotulos, df_veiculos, df = get_dataframes(i[1], i[2])
            df = df.where((pd.notnull(df)), None)
            c, conn = connection()
            c.executemany(
                "insert into tb_rastreio_parada (" + ', '.join(df.columns) + ") values (" + ("%s, " * len(df.columns))[
                                                                                :-2] + ")",
                [tuple(row) for row in df.values])
            c.execute(r'update tb_log_extracao set status = %s where ID = %s', ('sucess', i[0]))
            conn.commit()
        except:
            pass

    try:

        data_start = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%dT07:30:00-03:00")
        data_end = (datetime.now()).strftime("%Y-%m-%dT07:30:00-03:00")
        if data_end not in df_log_extracao[df_log_extracao['status'] == 'sucess']['date_end'].values:
            print(data_start, data_end)
            df_filiais, df_rotulos, df_veiculos, df = get_dataframes(data_start, data_end)

            df = df.where((pd.notnull(df)), None)
            c, conn = connection()
            c.execute("delete from cad_veiculo")
            c.executemany("insert into cad_veiculo (" + ', '.join(df_veiculos.columns) + ") values (" + ("%s, " * len(
                df_veiculos.columns))[:-2] + ")",
                          [tuple(row) for row in df_veiculos.values])
            c.executemany(
                "insert into tb_rastreio_parada (" + ', '.join(df.columns) + ") values (" + ("%s, " * len(df.columns))[
                                                                                :-2] + ")",
                [tuple(row) for row in df.values])
            conn.commit()
            conn.close()
            print('pronto')
            c, conn = connection()
            c.execute("insert into tb_log_extracao (date_start, date_end, status) values (%s, %s, %s)",
                      [data_start, data_end, 'sucess'])
            conn.commit()

    except Exception as e:

        exc_type, exc_obj, exc_tb = sys.exc_info()
        print(str(e))
        c, conn = connection()
        c.execute("insert into tb_log_extracao (date_start, date_end, status, log) values (%s, %s, %s,%s)",
                  [data_start, data_end, 'fail', str(e)])
        conn.commit()

def main():
    schedule.every().day.at("09:30").do(rotina)

    while True:
        schedule.run_pending()

if __name__ == "__main__":
    main()


from keras.models import load_model

# Config 모듈을 적용하기 위해서는 다른 Kivy 모듈을 불러오기 전에 설정을 해야 한다.
# 어플리케이션 창을 높이와 너비가 800px로 고정된 사이즈 재조정 불가능한 테두리 없는 창으로 설정한다.
from kivy.config import Config
Config.set('graphics', 'resizable', '0'); Config.set('graphics', 'borderless', '1')
Config.set('graphics', 'height', '600'); Config.set('graphics', 'width', '600')

from kivy.clock import Clock
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line, Ellipse
from kivy.properties import StringProperty, NumericProperty

import numpy as np
import cv2
import os
import time
import sys

# 학습된 모델 활용을 위해 해당 스크립트에 로드합니다.
model = load_model('.\\model_dir\\QD_model.h5')

# 클래스를 자동으로 추출하도록 시행되는 코드입니다. 우선 클래스의 이름을 어디에서 참고할 것인지 경로를 지정합니다.
path = os.listdir(".\\numpy_dataset")
class_name = {}
class_count = 0
# For 문을 통해 해당 경로에 있는 모든 파일의 이름에 대하여 전부 확인합니다.
for file in path:
    # 우선 데이터세트 파일 이름을 통해 경로를 포함한 파일 이름 전체를 획득합니다.
    file = ".\\numpy_dataset\\" + file
    # splitext 매소드를 통해 확장자 텍스트를 제거합니다.
    file_name, _ = os.path.splitext(file)
    # 공통적으로 들어있는 앞 부분을 전부 제거하여 클래스의 이름만 추출하여 사전에 추가합니다.
    class_name[class_count] = file_name[38:]
    # 사전에 추가를 완료하였으면 다음 클래스 이름을 받기 위한 키를 할당합니다.
    class_count += 1

# 클래스 인덱스 순서를 무작위로 섞으되 반복되지 않도록 range를 설정하고 리스트에 재할당한 것입니다.
rand_int = np.arange(class_count-1)
np.random.shuffle(rand_int)

Builder.load_string("""
<Screen>:
    canvas:
        Color:
            rgb: 255, 255, 255
        Rectangle:
            size:self.size

<SettingsScreen>:
    id : div_screen
    ProjectCanvas:
        id: div_canvas
        canvas.before:
            Color:
                rgb: 255, 255, 255
            Rectangle:
                size: self.size
                pos: self.pos
    FloatLayout:
        Button:
            text: 'REDO'
            color: 0, 0, 0, 0.5
            size_hint: (.1, .1)
            pos_hint: {'right':0.3}
            background_color: (0, 0, 0, 0.1)
            on_release: div_canvas.redo()
        Button:
            text: 'UNDO'
            color: 0, 0, 0, 0.5
            size_hint: (.1, .1)
            pos_hint: {'right':0.2}
            background_color: (0, 0, 0, 0.1)
            on_release: div_canvas.undo()
        Button:
            text: 'CLEAR'
            bold: 1
            color: 1, 0, 0, 1
            size_hint: (.1, .1)
            pos_hint: {'right':0.1}
            background_color: (0, 0, 0, 0.1)
            on_release: div_canvas.new_canvas()
        Label:
            text: div_canvas.pred_realtime
            bold: 1
            font_size: 26
            color: 1, 0, 0, 1
            size_hint: (.1, .1)
            pos_hint: {'right':.95,'top':1}
            background_color: (0, 0, 0, 0)
        Label:
            text: str(app.time)
            color: 1, 0, 0, 1
            size_hint: (.1, .1)
            pos_hint: {'right':1}
            background_color: (0, 0, 0, 0)

<ProjectReady>:
    Button:
        text: root.show_keyword
        # 버튼에 마우스 클릭을 떼면 App 클래스, 즉 ProjectMain 내의 load_canvas() 클래스 매소드를 시행합니다.
        on_release: app.load_canvas()

<ProjectEnd>:
    BoxLayout:
        canvas.before:
            Color:
                rgba: 0, 0, 0, 0.62
            Rectangle:
                pos: self.pos
                size: self.size
        orientation: 'vertical'
        Label:
            text: 'CORRECT: ' + str(app.correct)
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y:0.5
            Button:
                text: 'FINISH'
                on_release: app.end()
            Button:
                text: 'AGAIN'
                on_release: app.again()

<ProjectCorrect>:
    Button:
        text:'CORRECT'
        on_release: app.load_ready()

<ProjectWrong>:
    Button:
        text:'WRONG'
        on_release: app.load_ready()
""")

class SettingsScreen(Screen):
    pass

# ProjectCanvas() 클래스는 Screen()를 슈퍼클래스로 두는 서브클래스입니다.
# 프로그램에서 실제로 그림을 그릴 수 있는 틀인 "캔버스"를 제공합니다.
# 본 클래스는 ProjectMain()이라는 클래스의 self.canvas 속성에 할당되었습니다.
class ProjectCanvas(Widget):

    # drawing 변수는 그림의 한 점 또는 한 획에 대한 (x,y) 좌표 정보의 1차원 행렬을 담는 2차원 NumPy 행렬이다.
    drawing = []

    # undolist 변수는 undo 버튼을 클릭하였을 때, 되돌리기 기능의 redo 버튼을 대비한 임시 정보 저장을 위한 2차원 NumPy 행렬입니다.
    # undolist 변수가 담는 정보는 한 획의 (x,y) 좌표 정보가 있는 1차원 행렬입니다.
    undolist = []

    # 실시간으로 추론 결과를 화면에 보여지도록 하는 String 전용 변수입니다.
    pred_realtime = StringProperty()

    # ProjectCanvas()의 __init__은 속성 초기값을 설정하며, 직접 self.attribute_name 등을 통해 속성을 만들 수도 있습니다.
    # 어떠한 값이 입력될 것인지 알지만 아직 정의되지 않은 파라미터는 "**kwargs" (i.e. known arguments)라고 합니다.
    # 그리고 여러 입력을 받을 수 있도록 하는 파라미터는 "*args"라고 합니다.
    def __init__(self, **kwargs):
        # ProjectCanvas()가 속해있는 Screen() 슈퍼클래스의 __init__ 속성을 모두 ProjectCanvas().__init__에 불러옵니다.
        # PYTHON 2에서는 아래의 코드를 사용하나, PYTHON 3에서는 코드를 super().__init__(**kwargs)로 간략화시킬 수 있습니다.
        super(ProjectCanvas, self).__init__(**kwargs)
        self.pred_realtime = ''

    # 마우스로 캔버스를 클릭할 때 캔버스에 점을 찍을 수 있도록 지정하며, 직선의 시작점을 제공하기도 합니다.
    def on_touch_down(self, touch):
        with self.canvas:
            # 캔버스에 그릴 색과 획의 두께를 결정합니다.
            Color(0, 0, 0); d = 16
            # 마우스 클릭 한 번으로 점을 찍으며 <Ellipse object>. 이를 drawing 변수에 추가합니다.
            self.drawing.append(Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d)))
            # 마우스 클릭을 하고 움직일 때 <Line object> 좌표 정보를 drawing 변수에 추가합니다.
            # 즉, 한 번의 마우스 클릭은 <Ellipse object>와 <Line object>의 좌표 정보를 동시에 저장합니다.
            self.ud = Line(points=(touch.x, touch.y), width=8)
            self.drawing.append(self.ud)

    # 마우스가 클릭된 상태에서 캔버스 위에 움직였을 때, 직선을 그릴 수 있도록 합니다.
    def on_touch_move(self, touch):
        """전체적인 이동경로 좌표를 보고 싶으면 해당 함수의 끝부분에 print(touch.ud['line'])를 추가하도록 합니다.
        만일 시좌표(instantaneous coordinate)을 보고 싶으면 대신 print(np.array(Window.mouse_pos))을 추가합니다."""
        # 아래의 코드가 활성화되지 않으면 선을 그릴 수가 없습니다.
        # 여기에 저장된 데이터로 시작점과 불연속점, 그리고 끝점을 모두 입력받아 실시간으로 선을 캔버스에 나타내는 방식입니다.
        self.ud.points += [touch.x, touch.y]

        # 실시간 데이터 처리가 가장 이상적이지만, 현재 추출하고자 하는 데이터는 막대한 픽셀양의 PNG 이미지이다.
        # 실시간 이미지 처리에 최적화되지 않은 KIVY에서는 실시간 데이터 처리는 오히려 심각한 문제를 야기한다.
        # 어차피 그림의 시작과 끝에 PNG 추출이 이루어지므로, 획이 특정 데이터양이 모일 때만 PNG를 추출한다.
        if len(self.ud.points) % 100 is 0:
            self.capture_canvas()

    # 마우스 클릭을 뗀 상태에서 직선 정보보다 PNG 이미지 추출이 중점으로 여긴다.
    def on_touch_up(self, touch):
        # 좌표 평면을 행렬화하여 계산하는 것보다 직접 캔버스에 그려진 이미지를 추출하여 활용한다.
        # 수학적으로 좌표평면 위치들을 행렬화시켜 활요하는 것은 픽셀레이션 및 각 픽셀에 대한 회색조 값에 대하여
        # 표현하는데 더 복잡해지는 문제가 생긴다.
        self.capture_canvas()

    # Undo 버튼을 클릭할 시 실행되는 함수입니다.
    def undo(self):
        # 만일 그림을 그린게 없으면 undo 함수는 아무런 기능을 하지 않습니다.
        if len(self.drawing) == 0:
            return
        # <Ellipse object> 및 <Line object> 좌표 정보를 임시 변수에 추출합니다.
        tmp_ellipse = self.drawing.pop(-2)
        tmp_line = self.drawing.pop(-1)
        # Undo 및 Redo 기능을 위해 좌표 정보를 undolist 리스트 변수에 저장합니다.
        self.undolist.append(tmp_ellipse)
        self.undolist.append(tmp_line)
        # 캔버스에 저장된 해당 좌표 정보들을 삭제합니다.
        self.canvas.remove(tmp_ellipse)
        self.canvas.remove(tmp_line)
        # 삭제하여 변경된 그림을 추론을 위해 저장합니다.
        self.capture_canvas()

    # Redo 버튼을 클릭할 시 실행되는 함수입니다.
    def redo(self):
        # 만일 그림을 그린게 없으면 redo 함수 또한 아무런 기능을 하지 않습니다.
        if len(self.undolist) == 0:
            return
        # undolist 리스트 변수에 임시로 저장된 <Ellipse object> 및 <Line object> 좌표 정보를 임시 변수에 추출합니다.
        tmp_ellipse = self.undolist.pop(-2)
        tmp_line = self.undolist.pop(-1)
        # Undo 및 Redo 기능을 위해 좌표 정보를 drawing 리스트 변수에 저장합니다.
        self.drawing.append(tmp_ellipse)
        self.drawing.append(tmp_line)
        # 캔버스에 저장된 해당 좌표 정보들을 추가합니다.
        self.canvas.add(tmp_ellipse)
        self.canvas.add(tmp_line)
        # 추가하여 변경된 그림을 추론을 위해 저장합니다.
        self.capture_canvas()

    # Clear 버튼을 눌렀을 때 캔버스와 모든 리스트 변수도 모두 초기화시키고 화면에 보여질 실시간 추론 결과도 공백으로 바꿉니다.
    def new_canvas(self):
        self.canvas.clear()
        self.drawing.clear()
        self.undolist.clear()
        self.pred_realtime = ''

    # PNG 이미지 저장을 할 떄마다 예측모델이 이미지 추론을 진행합니다.
    def capture_canvas(self):
        # 이미지를 CANVAS.PNG 이름으로 저장합니다.
        self.export_to_png(".\\image\\CANVAS.PNG")
        # png2numpy() 함수를 통해 변환된 NumPy 행렬을 입력 데이터로 넣기 위해 4차원으로 재조정합니다.
        processed = png2numpy().reshape(1, 28, 28, 1)
        # 입력 데이터에 대한 각 클래스의 추론 확률을 불러옵니다.
        self.pred_probab = model.predict(processed)[0]
        # 가장 높은 확률의 추론 데이터의 클래스를 확인합니다.
        self.pred_class = list(self.pred_probab).index(max(self.pred_probab))
        print("실시간 추론 결과: [1위] " + class_name[self.pred_class] + " - " + str(max(self.pred_probab)))
        self.pred_realtime = class_name[self.pred_class]

# PNG 확장자를 모델 입력 데이터로 최적화시킨 NumPy로 변환시키는 함수입니다.
def png2numpy():
    # PNG 이미지 파일을 NumPy 행렬로 변환시키며, 각 픽셀은 RGB 값으로 할당된다.
    img = cv2.imread('.\\image\\CANVAS.PNG')
    # RGB 값들로 구성된 NumPy 행렬을 회색조 값으로 구성되 NumPy 행렬로 변환합니다.
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 하얀색 배경이 255 값으로 할당되어 있어, 아래의 코드는 값들을 반전시키며 np.uint8을 통해 최대값을 1로 변환시킵니다.
    img = (img < 128).astype(np.uint8)

    # coords는 행과 열이 영벡터가 아닌 동안의 벡터의 시작점을 [x, y] 행렬로 값을 추출하고, 이들의 값 차이가 바로 너비와 높이가 된다.
    coords = cv2.findNonZero(img)
    # 그림이 시작되는 x값, y값, 그림의 너비 w 및 높이 h를 획득합니다.
    x, y, w, h = cv2.boundingRect(coords)

    # 너비와 높이의 크기를 비교하여 그림을 중심에 위치할 수 있도록 설정합니다.
    if h > w:
        norm = np.zeros((h + 2, h + 2), dtype=np.float32)
        norm[1:-1, int((h - w) / 2) + 1:int((h - w) / 2) + 1 + w] = img[y:y + h, x:x + w]
    else:
        norm = np.zeros((w + 2, w + 2), dtype=np.float32)
        norm[int((w - h) / 2) + 1:int((w - h) / 2) + 1 + h, 1:-1] = img[y:y + h, x:x + w]

    # 동일한 비율로 cropping 된 그림을 모델 입력 데이터에 맞게 1px 테두리 패딩의 28x28 픽셀 대응 2차원 NumPy 행렬로 변환시킨다.
    img = cv2.resize(norm, (26, 26), interpolation=cv2.INTER_AREA)
    img = np.pad(img, pad_width=1, mode='constant', constant_values=0)
    return img

# 캔버스에 그림을 그리기 전에 주제어를 제공하는 등의 스크린을 담당합니다.
class ProjectReady(Screen):
    # KIVY 언어 내에서 할당된 변수를 아래와 같은 방식으로 할당한다; string 형식.
    show_keyword = StringProperty()

    def __init__(self, **kwargs):
        super(ProjectReady, self).__init__(**kwargs)
        # 무작위로 섞인 키워드를 순서대로 반복없이 선별하는 count 속성을 통해 초기 주제어를 설정합니다.
        self.count = 0
        self.show_keyword = class_name[rand_int[self.count]]

    def update_keyword(self):
        # 다음 순서의 키워드를 선별하기 위해 count 속성에 +1을 하고, 새로운 키워드를 가져옵니다.
        self.count += 1
        self.show_keyword = class_name[rand_int[self.count]]

# 게임이 종료될 때 나타나는 스크린 화면에 대한 클래스입니다.
class ProjectEnd(Screen):
    pass

# 캔버스에 그림을 그려 컴퓨터가 맞은 추론을 하였을 때 나타나는 스크린 화면에 대한 클래스입니다.
class ProjectCorrect(Screen):
    pass

# 캔버스에 그림을 그려 컴퓨터가 제 시간 내에 추론을 하지 못하였을 때 나타나는 스크린 화면에 대한 클래스입니다.
class ProjectWrong(Screen):
    pass

# KIVY 형식의 어플리케이션을 실제로 실행가능하도록 수행하는 App 클래스로 형성된 ProjectMain() 클래스입니다.
# 어플리케이션의 주된 기능 및 함수들은 이곳에 포함되어 개발됩니다.
class ProjectMain(App):
    # 실시간으로 추론 결과를 화면에 보여지도록 하는 String 전용 변수입니다.
    pred_realtime = StringProperty()

    # 맞춘 문제 개수를 카운트 하기 위한 숫자 전용 변수입니다.
    correct = NumericProperty()

    # 카운트다운을 위한 숫자 전용 변수입니다.
    time = NumericProperty()

    rand_int_count = NumericProperty()

    # ProjectMain()의 __init__은 속성 초기값을 설정하며, 직접 self.attribute_name 등을 통해 속성을 만들 수도 있습니다.
    def __init__(self, **kwargs):
        # ProjectMain()이 속해있는 App() 슈퍼클래스의 __init__ 속성을 모두 ProjectMain().__init__에 불러옵니다.
        super(ProjectMain, self).__init__(**kwargs)
        # count 변수는 문제의 개수를 카운트하기 위한 것입니다.
        self.count = 0
        self.correct = 0
        self.pred_realtime = ''
        self.start = 0
        self.time = 0

    # build() 매소드는 App 클래스 내에 작성 및 내포된 코드를 통해 어플리케이션을 실행시킵니다.
    # return 값을 특정 위젯으로 지정하면, 해당 위젯을 root 위젯으로 설정하고 KIVY 창에 나타납니다.
    def build(self):
        # KIVY 어플리케이션 창 이름을 지정합니다.
        self.title = 'KIVY Canvas'
        # ProjectReady() 및 ProjectCanvas() 클래스를 ProjectMain() 클래스 내의 속성(attribute)에 정의합니다.
        # ProjectReady() 및 ProjectEnd()은 Screen 클래스이며, 각자 이름은 'ready'와 'end'입니다.
        # ProjectCorrect() 및 ProjectWrong()은 Screen 클래스이며, 각자 이름은 'got_correct'와 'got_wrong'입니다.
        # 이는 ScreenManager() 클래스가 스크린을 스크린 속성의 name 을 통해 제어/관리를 하기 때문입니다.
        self.ready = ProjectReady(name='ready')
        self.end = ProjectEnd(name='end')
        self.got_correct = ProjectCorrect(name='got_correct')
        self.got_wrong = ProjectWrong(name='got_wrong')
        self.canvas = SettingsScreen(name='canvas')

        # ProjectReady()의 카운팅 속성에 접속을 하여 수정을 가능토록 하며, 게임을 새로 시작할 시 필요합니다.
        self.ready.count = 0

        # ProjectMain() 클래스에 0.35초만에 화면을 슬라이드 천이이동시키는 transition 속성을 부여합니다.
        self.transition = SlideTransition(duration=0.35)
        # 이름 "root"라는 ScreenManager()은 어플리케이션 내에서 여러 스크린을 제어 및 관리하기 위해 사용됩니다.
        # 그 중에서 "root"의 스크린 천이방식은 transition 속성을 통해 이루어집니다(즉, 0.35초만의 슬라이드 천이).
        root = ScreenManager(transition=self.transition)
        # ProjectReady() 및 End(), Correct()과 Wrong()을 속성을 통해" root"에 넣어 ScreenManager()로 제어가 가능합니다.
        root.add_widget(self.ready)
        root.add_widget(self.end)
        root.add_widget(self.got_correct)
        root.add_widget(self.got_wrong)
        root.add_widget(self.canvas)

        # 클래스 매소드 self.Is_predicting을 매초마다 실행하며, 본 클래스 매소드가 추론이 옳고 그름을 결정한다.
        Clock.schedule_interval(self.is_predicting, 1)

        # build() 메소드의 return 값이 "root"로 정해지며, 이제 해당 어플리케이션의 뿌리(root)는 "root"입니다.
        return root

    # ProjectCanvas() 화면으로 전환하였을 경우, 20초
    def is_predicting(self, *args):
        # 타이머를 실행시키는데, 계산법은 CPU 에서 지속적으로 측정된 클래스 시행 시간을 self.start 라는 캔버스를 불러왔는데 걸린
        # 동일한 CPU 측정 시간을 빼서 정수화 시킨 것이다. Clock.schedule_interval(self.is_predicting, 1) 문으로 인해 매초마다
        # int(time.time() - self.start)은 1초씩 증가하게 되는데, 이를 20초에 빼서 20초 타이머로 만들었다.
        self.time = 20 - int(time.time() - self.start)

        # 본격적인 추론 작업은 오로지 ProjectCanvas() 스크린이 현재 화면에 나탄났을 때에만 진행한다.
        if self.root.current == 'canvas':
            # 타이머가 0이 되기 전에 경우에서...
            if self.time != 0:
                # 추론 결과가 키워드와 동일하면...
                if self.canvas.children[1].pred_realtime == self.ready.show_keyword:
                    # 맞춘 문제 카운트를 +1 하고, 정답 맞춤 화면인 ProjectCorrect() 스크린으로 전환합니다.
                    self.correct += 1
                    self.rand_int_count += 1
                    self.transition.direction = 'right'
                    self.root.current = 'got_correct'
            # 그러나 타이머가 0이 되었을 시...
            else:
                # 때마침 추론 결과가 키워드와 동일할 경우를 대비하여...
                if self.canvas.children[1].pred_realtime == self.ready.show_keyword:
                    # 맞춘 문제 카운트를 +1 하고, 정답 맞춤 화면인 ProjectCorrect() 스크린으로 전환합니다.
                    self.correct += 1
                    self.rand_int_count += 1
                    self.transition.direction = 'right'
                    self.root.current = 'got_correct'
                # 하지만 추론 결과가 키워드와 전혀 동일하지 않으면...
                else:
                    # 정답 틀림 화면인 ProjectWrong() 스크린으로 전환합니다.
                    self.rand_int_count += 1
                    self.transition.direction = 'right'
                    self.root.current = 'got_wrong'

    # 대기화면 ProjectReady()에서 'start' 버튼을 누르면 대기화면을 치우도록 시행되는 클래스 매소드입니다.
    def load_canvas(self):
        # 스크린 천이이동을 왼쪽으로 가게 합니다.
        self.transition.direction = 'left'

        # count 속성에 +1을 하여 카운트합니다.
        self.count += 1
        # start 속성은 20초 시간 카운트다운을 위한 것입니다.
        self.start = time.time()

        # ScreenManager()의 current 속성은 "root"에 현재 보여질 화면을 의미합니다.
        # 그러므로 "root"의 현재 화면을 ProjectCanvas()로 설정하여, 버튼을 클릭하면 바로 캔버스가 나타나게 합니다.
        self.root.current = 'canvas'

    # 캔버스 화면 ProjectCanvas()에서 대기화면 ProjectReady()로 화면 전환을 하는데 시행되는 클래스 매소드입니다.
    def load_ready(self):
        # 만일 count 속성으로 카운팅된 숫자가 5, 즉 5개의 문제를 모두 풀었으면 load_end() 클래스 매소드를 시행합니다.
        if self.count == 5:
            self.load_end()
        # 만일 5개의 문제를 풀지 않은 상태일 때 시행됩니다.
        else:
            # 대기화면에 나타날 키워드를 update_keyword() 클래스 매소드를 통해 임의로 새로 할당합니다.
            self.ready.update_keyword()
            # 기준의 캔버스를 새로운 캔버스로 덮어씁니다.
            self.canvas.children[1].new_canvas()
            # 화면 전환을 오른쪽 방향으로 진행합니다.
            self.transition.direction = 'right'
            # 현재 보여질 화면의 이름은 'ready'입니다.
            self.root.current = 'ready'

    # ProjectEnd()를 불러오는 클래스 매소드입니다.
    def load_end(self):
        self.transition.direction = 'right'
        self.root.current = 'end'

    # ProjectEnd() 스크린에서 AGAIN 버튼을 눌렀을 때, 문제를 처음부터 다시 풀도록 모든 속성을 초기화시키는 클래스 매소드입니다.
    def again(self):
        # 모든 것(캔버스, 카운팅, 키워드 등)들을 초기화시킵니다.
        self.canvas.children[1].new_canvas()
        self.count = 0
        self.correct = 0
        self.ready.update_keyword()
        self.transition.direction = 'right'
        self.root.current = 'ready'
        self.ready.count = 0

        # 무작위로 섞은 인덱스를 다시 한 번 무작위로 섞습니다.
        np.random.shuffle(rand_int)

    # ProjectEnd() 스크린 화면에서 FINISH 버튼을 눌렀을 때, 시스템을 종료하는 정적 클래스 매소드(self 구성이 없는 함수)입니다.
    @staticmethod
    def end():
        sys.exit(1)

# 본 스크립트가 외부 스크립트가 아닌 주요 스크립트로 실행될 때에만 위의 프로그램을 정상적으로 실행시킵니다.
if __name__ == '__main__':
    # run() 매소드는 개발환경 필요없이 독립적으로 실행할 수 있도록 합니다.
    ProjectMain().run()


from django.conf.urls import url
from django.urls import path

from .views import startpage, UserRegisterView, logout_view, UserLoginView, user_help_view,\
    contact_view, contact_success_view, contact_error_view, howitworks_startpage_view, contact_startpage_view,\
    contact_startpage_success_view, contact_startpage_error_view, faq_startpage_view

urlpatterns = [
    # landing page/startpage
    path('', startpage, name="startpage_view"),
    path('how-it-works/', howitworks_startpage_view, name="howitworks_startpage_view"),
    path('faq/', faq_startpage_view, name="faq_startpage_view"),
    path('contact/', contact_startpage_view, name="contact_startpage_view"),

    path('contact-success/', contact_startpage_success_view, name="contact_startpage_success_view"),
    path('contact-error/', contact_startpage_error_view, name="contact_startpage_error_view"),

    path('register-account/', UserRegisterView.as_view(), name="register_account"),
    path('login/', UserLoginView.as_view(), name="login_view"),
    path('logout/', logout_view, name="logout_view"),

    # inside app
    path('help/', user_help_view, name="help_view"),
    path('contact-app/', contact_view, name="contact_view"),

    path('contact-app-success/', contact_success_view, name="contact_success_view"),
    path('contact-app-error/', contact_error_view, name="contact_error_view"),

]


rateUtoE = None
rateEtoU = None

while True:
    command = input("Give a command: ")
    command = command.split(" ")
    try:
        if (len(command) == 3) and (command[0] == "USD") and (command[2] == "EUR"):
            rateUtoE = float(command[1])
        elif (len(command) == 3) and (command[0] == "EUR") and (command[2] == "USD"):
            rateEtoU = float(command[1])
        elif (len(command) == 2) and (command[1] == "USD"):
            usd = float(command[0])
            if (rateUtoE == None):
                print("No USD-EUR rate defined yet!")
            else:
                print("{:.2f} USD = {:.2f} EUR".format(usd, usd*rateUtoE))
        elif (len(command) == 2) and (command[1] == "EUR"):
            eur = float(command[0])
            if (rateEtoU == None):
                print("No EUR-USD rate defined yet!")
            else:
                print("{:.2f} EUR = {:.2f} USD".format(eur, eur*rateEtoU))
        elif (len(command) == 1) and (command[0] == "quit"):
            break
        else:
            print("Illegal command!")
    except ValueError:
        print("Illegal command!")


#Jonthan Salmon

from image_loader import load_image
import pygame
from pygame.locals import *

NOTE_HALF_X = 212
NOTE_HALF_Y = 112

#This is the popup box that shows when the timer on the main class hit's 0
#the positioning for the alert is static as of now and changes in screen resolution
#is a problem
class Alert(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_image('timeout.png')
        self.rect = self.image.get_rect()
        self.x =  int(pygame.display.Info().current_w /2) - NOTE_HALF_X
        self.y =  int(pygame.display.Info().current_h /3) - NOTE_HALF_Y
        self.rect.topleft = self.x, self.y


# encoding: utf-8
import ply.lex as lex
import ply.yacc as yacc
import os
import codecs

# Token definition
'''
tokens = [
'STDIN','AND','PLUS_ONE', 'MINUS_ONE', 'STRING','ASSIGN','BACKSLASH','BETWEEN','COLON','DOLLAR','DOUBLEQUOTE',
'EOL','EQ','EXP' ,'FLOAT', 'CONST_ASSIGN','GREATER_OR_EQUAL','IDENTIFIER',
'INTEGER','LEFT_BRACE','LEFT_PAR' ,'LESS_OR_EQUAL','LESS_THAN','MINUS',
'MORE_THAN','MULTILINE_COMMENT' ,'NEQ','OR','PLUS','POINT','QUOTE',
'RIGHT_BRACE','RIGHT_PAR' ,'SEMICOLON','SINGLE_LINE_COMMENT',
'STAR'
]
'''
tokens = [
'STDIN','AND','PLUS_ONE', 'MINUS_ONE', 'STRING','ASSIGN','BETWEEN','DOLLAR',
'EQ','FLOAT', 'CONST_ASSIGN','GREATER_OR_EQUAL','IDENTIFIER',
'INTEGER','LEFT_BRACE','LEFT_PAR' ,'LESS_OR_EQUAL','LESS_THAN','MINUS',
'MORE_THAN' ,'NEQ','OR','PLUS',
'RIGHT_BRACE','RIGHT_PAR',
'STAR'
]
errors_arr = []

# This hash is used to represent the reserved words,
# since the regex is just the word matching, the documentation said
# it was lest expensive to do it this way.
reserved = {
 'use': 'USE',
 'constant': 'CONSTANT',
 'else': 'ELSE',
 'if': 'IF',
 'print': 'PRINT',
 'while': 'WHILE',
 'true': 'TRUE',
 'false': 'FALSE'
}

tokens = tokens + list(reserved.values())

# definition of the regex to define every token in the token list
t_STDIN = r'<STDIN>'
t_STRING = r'\".*?\"'
t_AND = r'&&'
t_ASSIGN = r'='
t_CONST_ASSIGN = r'=>'
#t_BACKSLASH = r'\\'
t_BETWEEN = r'\/'
#t_COLON = r':'
t_DOLLAR = r'\$'
#t_DOUBLEQUOTE = r'\"'
#t_EOL = r'\n'
t_PLUS_ONE = r'\+\+'
t_MINUS_ONE = r'--'
t_EQ = r'=='
#t_EXP = r'\*\*'
t_FLOAT = r'[+-]?[0-9]+\.[0-9]+'
t_GREATER_OR_EQUAL = r'>='
t_INTEGER = r'[0-9]+'
t_LEFT_BRACE = r'\{'
t_LEFT_PAR = r'\('
t_LESS_OR_EQUAL = r'<='
t_LESS_THAN = r'<'
t_MINUS = r'-'
t_MORE_THAN = r'>'
t_NEQ = r'!='
t_OR = r'\|\|'
t_PLUS = r'\+'
#t_POINT = r'\.'
#t_QUOTE = r'\''
t_RIGHT_BRACE = r'\}'
t_RIGHT_PAR = r'\)'
#t_SEMICOLON = r';'
t_STAR = r'\*'

# characters that are going to be ignored in all the program
# in this case tab and space
t_ignore  = ' \t\n'

#since almost every alphanumeric string can be an identifier,
# we need to make sure that it's not a reserved word
# If so, we need to return it with the correct data type
def t_IDENTIFIER(t):
    r'[a-zA-Z_][a-zA-Z0-9_]*'
    t.type = reserved.get(t.value, 'IDENTIFIER')
    return t

#The comment definition of both comment cases
# 'pass' is just for detecting, but dont returning anything

def t_ignore_SINGLE_LINE_COMMENT(t):
    r'\#.*'
    pass

def t_ignore_MULTILINE_COMMENT(t):
    r'\/\*([^*]|[\r\n])*\*\/+'
    pass

def t_newline(t):
    r'\n+'
    t.lexer.lineno += len(t.value)
#last case, none of the token rules was achieved by a char
def t_error(t):
    s = "Symbol not found '%s'" % t.value[0]
    errors_arr.append(s)
    t.lexer.skip(1)

#now we have to define the function for reading the files
'''
def prepareArray(dir,arr):
    for i in range(len(arr)):
        arr[i] = dir+'/'+arr[i]

    return arr

def menuArray(arr):
    print("Choose test to run\n")
    for i in range(len(arr)):
        print(str(i) + ' ' + arr[i])
    answer = input("Escoge un archivo\n")
    return arr[answer]

#we define the path where we should look for the test
dir = 'tests'
arr = os.listdir(dir)
prepareArray(dir, arr)
a = menuArray(arr)
print ("you chose: " + a + "\n OUTPUT: \n")
file_test = codecs.open(a, 'r', 'utf-8')
str = file_test.read()
file_test.close()
lexer = lex.lex()
lexer.input(str)

while True:
    tok = lexer.token()
    if not tok:
        break
    print(tok)
    '''
lexer = lex.lex()


import sys
sys.stdin = open("D3_12221_input.txt", "r")

T = int(input())
for test_case in range(T):
    A, B = map(int, input().split())
    ans = A * B
    if A > 9 or B > 9:
        ans = - 1
    print("#{} {}".format(test_case + 1, ans))


import pytest

from schedsim.common import TaskGraph, TaskOutput
from schedsim.communication import InstantNetModel
from schedsim.simulator import Simulator
from schedsim.worker import Worker
from schedsim.schedulers import StaticScheduler
from schedsim.simulator import TaskAssignment

@pytest.fixture
def plan1():
    """
        a1/1 a2/3/3
        |    |
        a3/1 | a4/1/6
        |\  / /|
        o o |/ |
        | a5/1 a6/6 a7/2
        |  \   |   /
        |   \  |  /
         \--- a8/1
    """  # noqa
    task_graph = TaskGraph()

    a1, a2, a3, a4, a5, a6, a7, a8 = [
        task_graph.new_task("a{}".format(i + 1),
                            duration=duration, expected_duration=duration,
                            outputs=[TaskOutput(size, size) for size in outputs])
        for i, (duration, outputs) in enumerate([
            (2, [1]),  # a1
            (3, [3]),  # a2
            (2, [1, 1]),  # a3
            (1, [6]),  # a4
            (1, [1]),  # a5
            (6, [1]),  # a6
            (1, [2]),  # a7
            (1, [])   # a8
        ])
    ]

    a3.add_input(a1)
    a5.add_inputs([a3.outputs[0], a2, a4])
    a6.add_input(a4)
    a8.add_inputs([a5, a6, a7, a3.outputs[1]])

    task_graph.validate()

    return task_graph

def plan_reverse_cherry1():
    """
        a1/10/1  a2/10/1
          \     /
           \   /
             a3
    """  # noqa
    task_graph = TaskGraph()
    a1 = task_graph.new_task("a1", 10, 1)
    a2 = task_graph.new_task("a2", 10, 1)
    a3 = task_graph.new_task("a3", 1)

    a3.add_input(a1)
    a3.add_input(a2)
    return task_graph

def do_sched_test(task_graph, workers, scheduler,
                  netmodel=None, trace=False, return_simulator=False,
                  min_scheduling_interval=None, scheduling_time=None):

    if netmodel is None:
        netmodel = InstantNetModel()

    if isinstance(workers, int):
        workers = [Worker() for _ in range(workers)]
    elif isinstance(workers[0], int):
        workers = [Worker(cpus=cpus) for cpus in workers]
    else:
        assert isinstance(workers[0], Worker)
    simulator = Simulator(task_graph, workers, scheduler, netmodel,
                          trace=trace,
                          scheduling_time=scheduling_time,
                          min_scheduling_interval=min_scheduling_interval)
    result = simulator.run()
    if return_simulator:
        return simulator
    else:
        return result

def task_by_name(plan, name):
    return [t for t in plan.tasks if t.name == name][0]

def fixed_scheduler(assignments):

    class FixScheduler(StaticScheduler):

        def static_schedule(self):
            workers = self.simulator.workers
            return [
                TaskAssignment(workers[definition[0]], *definition[1:])
                for definition in assignments
            ]

    return FixScheduler()


# uncompyle6 version 3.7.4
# Python bytecode 3.4 (3310)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/ale/progr/github/wasp-general/wasp_general/task/scheduler/task_source.py
# Compiled at: 2017-10-10 07:17:45
# Size of source mod 2**32: 15841 bytes
from wasp_general.version import __author__, __version__, __credits__, __license__, __copyright__, __email__
from wasp_general.version import __status__
from datetime import datetime, timedelta, MAXYEAR, timezone
from calendar import monthrange, weekday
from wasp_general.verify import verify_type, verify_value
from wasp_general.datetime import utc_datetime
from wasp_general.thread import WCriticalResource
from wasp_general.task.scheduler.proto import WTaskSourceProto, WScheduleRecord, WScheduleTask, WSchedulerServiceProto

class WBasicTaskSource(WTaskSourceProto):

    @verify_type(scheduler=WSchedulerServiceProto)
    def __init__(self, scheduler_service):
        self._WBasicTaskSource__service = scheduler_service

    def scheduler_service(self):
        return self._WBasicTaskSource__service

class WCronSchedule:
    __calendar__ = {1: 31,  2: 29,  3: 31,  4: 30,  5: 31,  6: 30,  7: 31,  8: 31,  9: 30,  10: 31,  11: 30,  12: 31}

    @verify_type(start_datetime=(datetime, None), minute=(int, None), hour=(int, None), day_of_month=(int, None))
    @verify_type(day_of_week=(int, None), month=(int, None))
    @verify_value(minute=lambda x: x is None or 0 <= x <= 59)
    @verify_value(hour=lambda x: x is None or 0 <= x <= 23)
    @verify_value(day_of_month=lambda x: x is None or 1 <= x <= 31)
    @verify_value(day_of_week=lambda x: x is None or 1 <= x <= 7)
    @verify_value(month=lambda x: x is None or 1 <= x <= 12)
    def __init__(self, start_datetime=None, minute=None, hour=None, day_of_month=None, day_of_week=None, month=None):
        if month is not None:
            if day_of_month is not None and day_of_month > WCronSchedule.__calendar__[month]:
                raise ValueError('Invalid day and month combination')
        self._WCronSchedule__start_datetime = start_datetime if start_datetime is not None else self.now()
        self._WCronSchedule__next_start = None
        self._WCronSchedule__minute = minute
        self._WCronSchedule__hour = hour
        self._WCronSchedule__day_of_month = day_of_month
        self._WCronSchedule__day_of_week = day_of_week
        self._WCronSchedule__month = month
        self.update()

    def start_datetime(self):
        return self._WCronSchedule__start_datetime

    @verify_type(start_datetime=datetime)
    def _set_start_datetime(self, start_datetime):
        self._WCronSchedule__start_datetime = start_datetime
        self._WCronSchedule__next_start = None

    @verify_type('paranoid', year=int, month=int, day=int, hour=int, minute=int)
    @verify_value('paranoid', year=lambda x: x > 0)
    @verify_value('paranoid', month=lambda x: x is None or 1 <= x <= 12)
    @verify_value('paranoid', day=lambda x: x is None or 1 <= x <= 31)
    @verify_value('paranoid', hour=lambda x: x is None or 0 <= x <= 23)
    @verify_value('paranoid', minute=lambda x: x is None or 0 <= x <= 59)
    def _datetime(self, year, month, day, hour, minute):
        return datetime(year, month, day, hour, minute)

    def next_start(self):
        return self._WCronSchedule__next_start

    def minute(self):
        return self._WCronSchedule__minute

    def hour(self):
        return self._WCronSchedule__hour

    def day_of_month(self):
        return self._WCronSchedule__day_of_month

    def day_of_week(self):
        return self._WCronSchedule__day_of_week

    def month(self):
        return self._WCronSchedule__month

    def no_frequency(self):
        result = self.minute() is None and self.hour() is None and self.day_of_month() is None
        return result is True and self.day_of_week() is None and self.month() is None

    def final_datetime(self):
        return datetime(MAXYEAR, 12, 31, 23, 59)

    @classmethod
    def now(cls):
        return datetime.now()

    def update(self):
        if self.no_frequency() is True:
            return
        for year, month in self.month_iterator():
            for day in self.day_iterator(year, month):
                for hour, minute in self.time_iterator(year, month, day):
                    self._WCronSchedule__next_start = self._datetime(year, month, day, hour, minute)
                    return

    @verify_type(omit_skipped=bool)
    def complete(self, omit_skipped=True):
        if self.no_frequency() is True:
            return
        next_start = self.next_start()
        seconds_last_minute = next_start.second
        seconds_last_hour = next_start.minute * 60 + seconds_last_minute
        seconds_last_day = next_start.hour * 24 * 60 * 60 + seconds_last_hour
        time_shift = 0
        if self.month() is not None:
            year = next_start.year
            month = next_start.month
            if month < 12:
                month += 1
            else:
                year += 1
                month = 1
            time_shift = (self._datetime(year, month, 1, 0, 0) - next_start).total_seconds()
        else:
            if self.day_of_week() is not None:
                time_shift = 604800 - seconds_last_day
            else:
                if self.day_of_month() is not None:
                    time_shift = 86400 - seconds_last_day
                else:
                    if self.hour() is not None:
                        time_shift = 3600 - seconds_last_hour
                    elif self.minute() is not None:
                        time_shift = 60 - seconds_last_minute
            time_shift += 1
            new_start = next_start + timedelta(seconds=time_shift)
            if omit_skipped is True:
                now = self.now()
                if now > new_start:
                    new_start = now
        self._set_start_datetime(new_start)
        self.update()

    def month_iterator(self):
        if self.no_frequency():
            return
        start_datetime = self.start_datetime()
        start_year = start_datetime.year
        start_month = start_datetime.month
        final_datetime = self.final_datetime()
        max_year = final_datetime.year
        max_month = final_datetime.month
        month = self.month()
        year = start_year
        if month is not None:
            if month < start_month:
                year += 1
            if year > max_year or year == max_year and month > max_month:
                return
            while year < max_year or year == max_year and month < max_month:
                yield (
                 year, month)
                year += 1

        else:
            month = start_month
            while year < max_year or year == max_year and month < max_month:
                yield (
                 year, month)
                if month < 12:
                    month += 1
                else:
                    year += 1
                    month = 1

    def day_iterator(self, year, month):
        if self.no_frequency():
            return
        start_datetime = self.start_datetime()
        days_in_month = monthrange(year, month)[1]
        day_of_month = self.day_of_month()
        day_of_week = self.day_of_week()
        final_datetime = self.final_datetime()
        if year == final_datetime.year:
            if month == final_datetime.month:
                days_in_month = final_datetime.day
        start_day = start_datetime.day
        if year != start_datetime.year or month != start_datetime.month:
            start_day = 1
        if day_of_month is None and day_of_week is None:
            day = start_day
            while day <= days_in_month:
                yield day
                day += 1

        else:
            if day_of_month is not None and day_of_week is None:
                if start_day <= days_in_month:
                    yield day_of_month
            else:
                if day_of_month is not None and day_of_week is not None:
                    if start_day <= days_in_month:
                        if weekday(year, month, day_of_month) == day_of_week:
                            yield day_of_month
                else:
                    current_weekday = weekday(year, month, start_day)
                    delta = day_of_week - current_weekday
                    if delta < 0:
                        delta += 7
                    day = start_day + delta
                    while day <= days_in_month:
                        yield day
                        day += 7

    def time_iterator(self, year, month, day):
        start_datetime = self.start_datetime()
        max_hour = 23
        max_minute = 59
        hour = self.hour()
        minute = self.minute()
        final_datetime = self.final_datetime()
        if year == final_datetime.year:
            if month == final_datetime.month and day == self.final_datetime():
                max_hour = final_datetime.hour
                max_minute = final_datetime.minute
        start_hour = start_datetime.hour
        start_minute = start_datetime.minute
        if year != start_datetime.year or month != start_datetime.month or day != start_datetime.day:
            start_hour = 0
            start_minute = 0
        if hour is None and minute is None:
            hour = start_hour
            minute = start_minute
            while (start_hour <= hour < max_hour or hour) == max_hour:
                if start_minute <= minute <= max_minute:
                    yield (
                     hour, minute)
                    if minute < 59:
                        minute += 1
                else:
                    minute = 0
                    hour += 1

        else:
            if hour is not None and minute is None:
                minute = start_minute
                if start_hour <= hour <= max_hour:
                    while minute <= max_minute:
                        yield (
                         hour, minute)
                        minute += 1

            elif hour is not None and minute is not None:
                if not start_hour <= hour < max_hour:
                    pass
        if hour == max_hour:
            if start_minute <= minute <= max_minute:
                yield (
                 hour, minute)
        else:
            hour = start_hour
            if start_minute > minute:
                hour += 1
            while (start_hour <= hour < max_hour or hour) == max_hour:
                if start_minute <= minute <= max_minute:
                    yield (
                     hour, minute)
                    hour += 1

    @classmethod
    @verify_type(scheduled=str)
    def from_string(cls, scheduled):
        return cls.from_string_tokens(*filter(lambda x: len(x) > 0, scheduled.strip().split(' ')))

    @classmethod
    @verify_type(tokens=str)
    def from_string_tokens(cls, *tokens):
        if len(tokens) != 5:
            raise ValueError('Malformed cron-schedule')
        tokens = [int(x) if x != '*' else None for x in tokens]
        if len(tokens) != 5:
            raise ValueError('Malformed cron-schedule')
        return cls(cls.now(), minute=tokens[0], hour=tokens[1], day_of_month=tokens[2], day_of_week=tokens[3], month=tokens[4])

class WCronLocalTZSchedule(WCronSchedule):
    pass

class WCronUTCSchedule(WCronSchedule):

    @verify_type('paranoid', start_datetime=(datetime, None), minute=(int, None), hour=(int, None))
    @verify_type('paranoid', day_of_month=(int, None), day_of_week=(int, None), month=(int, None))
    @verify_value('paranoid', minute=lambda x: x is None or 0 <= x <= 59)
    @verify_value('paranoid', hour=lambda x: x is None or 0 <= x <= 23)
    @verify_value('paranoid', day_of_month=lambda x: x is None or 1 <= x <= 31)
    @verify_value('paranoid', day_of_week=lambda x: x is None or 1 <= x <= 7)
    @verify_value('paranoid', month=lambda x: x is None or 1 <= x <= 12)
    @verify_value(start_datetime=lambda x: x.tzinfo is not None and x.tzinfo == timezone.utc)
    def __init__(self, start_datetime=None, minute=None, hour=None, day_of_month=None, day_of_week=None, month=None):
        WCronSchedule.__init__(self, start_datetime, minute=minute, hour=hour, day_of_month=day_of_month, day_of_week=day_of_week, month=month)

    @verify_type(start_datetime=datetime)
    @verify_value(start_datetime=lambda x: x.tzinfo is not None and x.tzinfo == timezone.utc)
    def _set_start_datetime(self, start_datetime):
        WCronSchedule._set_start_datetime(self, start_datetime)

    @verify_type('paranoid', year=int, month=int, day=int, hour=int, minute=int)
    @verify_value('paranoid', year=lambda x: x > 0)
    @verify_value('paranoid', month=lambda x: x is None or 1 <= x <= 12)
    @verify_value('paranoid', day=lambda x: x is None or 1 <= x <= 31)
    @verify_value('paranoid', hour=lambda x: x is None or 0 <= x <= 23)
    @verify_value('paranoid', minute=lambda x: x is None or 0 <= x <= 59)
    def _datetime(self, year, month, day, hour, minute):
        return utc_datetime(datetime(year, month, day, hour, minute), local_value=False)

    @classmethod
    def now(cls):
        return utc_datetime()

class WCronScheduleRecord(WScheduleRecord):

    @verify_type('paranoid', task=WScheduleTask, task_group_id=(str, None))
    @verify_value('paranoid', on_drop=lambda x: x is None or callable(x))
    @verify_value('paranoid', on_wait=lambda x: x is None or callable(x))
    @verify_type(schedule=WCronSchedule, omit_skipped=bool)
    @verify_value(schedule=lambda x: isinstance(x, WCronLocalTZSchedule) or isinstance(x, WCronUTCSchedule))
    def __init__(self, cron_schedule, task, policy=None, task_group_id=None, on_drop=None, on_wait=None, omit_skipped=True):
        WScheduleRecord.__init__(self, task, policy=policy, task_group_id=task_group_id, on_drop=on_drop, on_wait=on_wait)
        self._WCronScheduleRecord__schedule = cron_schedule
        self._WCronScheduleRecord__omit_skipped = omit_skipped

    def cron_schedule(self):
        return self._WCronScheduleRecord__schedule

    def next_start(self):
        cron = self.cron_schedule()
        next_start = cron.next_start()
        if isinstance(cron, WCronLocalTZSchedule):
            return utc_datetime(dt=next_start)
        if isinstance(cron, WCronUTCSchedule):
            return next_start
        raise RuntimeError('Corrupted object!')

    def complete(self):
        self.cron_schedule().complete(omit_skipped=self._WCronScheduleRecord__omit_skipped)

class WCronTaskSource(WBasicTaskSource, WCriticalResource):

    @verify_type('paranoid', scheduler_service=WSchedulerServiceProto)
    def __init__(self, scheduler_service):
        WBasicTaskSource.__init__(self, scheduler_service=scheduler_service)
        WCriticalResource.__init__(self)
        self._WCronTaskSource__tasks = []
        self._WCronTaskSource__next_task = None

    @verify_type(record=WCronScheduleRecord)
    def add_record(self, record):
        self._WCronTaskSource__add_record(record)
        self.scheduler_service().update(task_source=self)

    @WCriticalResource.critical_section()
    @verify_type('paranoid', record=WCronScheduleRecord)
    def __add_record(self, record):
        self._WCronTaskSource__tasks.append(record)
        self._WCronTaskSource__update(record)

    @verify_type('paranoid', task=(WCronScheduleRecord, None))
    def __update(self, task=None):
        if task is not None:
            next_start = task.next_start()
            if self._WCronTaskSource__next_task is None or next_start < self._WCronTaskSource__next_task.next_start():
                self._WCronTaskSource__next_task = task
        else:
            if len(self._WCronTaskSource__tasks) > 0:
                next_task = self._WCronTaskSource__tasks[0]
                for task in self._WCronTaskSource__tasks[1:]:
                    if next_task.next_start() is None:
                        next_task = task
                    elif task.next_start() is not None and task.next_start() < next_task.next_start():
                        next_task = task
                        continue

                self._WCronTaskSource__next_task = next_task
            else:
                self._WCronTaskSource__next_task = None

    @WCriticalResource.critical_section()
    def tasks_planned(self):
        return len(self._WCronTaskSource__tasks)

    @WCriticalResource.critical_section()
    def has_records(self):
        if self._WCronTaskSource__next_task is not None:
            next_start = self._WCronTaskSource__next_task.next_start()
            if next_start is not None and next_start <= utc_datetime():
                result = [
                 self._WCronTaskSource__next_task]
                self._WCronTaskSource__next_task.complete()
                self._WCronTaskSource__update()
                return tuple(result)

    @WCriticalResource.critical_section()
    def next_start(self):
        if self._WCronTaskSource__next_task is not None:
            return self._WCronTaskSource__next_task.next_start()

class WInstantTaskSource(WBasicTaskSource, WCriticalResource):
    __lock_acquiring_timeout__ = 5

    @verify_type('paranoid', scheduler_service=WSchedulerServiceProto)
    def __init__(self, scheduler_service):
        WBasicTaskSource.__init__(self, scheduler_service=scheduler_service)
        WCriticalResource.__init__(self)
        self._WInstantTaskSource__records = []

    @verify_type('paranoid', record=WScheduleRecord)
    def add_record(self, record):
        self._WInstantTaskSource__add_record(record)
        self.scheduler_service().update(self)

    @verify_type(record=WScheduleRecord)
    @WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)
    def __add_record(self, record):
        self._WInstantTaskSource__records.append(record)

    @WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)
    def has_records(self):
        if len(self._WInstantTaskSource__records) > 0:
            result = self._WInstantTaskSource__records.copy()
            self._WInstantTaskSource__records = []
            return tuple(result)

    @WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)
    def next_start(self):
        if len(self._WInstantTaskSource__records) > 0:
            return utc_datetime()

    @WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)
    def tasks_planned(self):
        return len(self._WInstantTaskSource__records)


'''
Created on Nov 14, 2012

@package: security
@copyright: 2012 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Ioan v. Pocol

Contains the setup files for security.
'''

# --------------------------------------------------------------------

NAME = 'Security'
GROUP = 'Security'
VERSION = '1.0'
DESCRIPTION = 'This plugin provides the basic security models.'
KEYWORDS = ['Ally', 'REST', 'plugin', 'support', 'security']
AUTHOR = 'Ioan Pocol'
AUTHOR_EMAIL = "gabriel.nistor@sourcefabric.org",
INSTALL_REQUIRES = ['ally-api >= 1.0', 'support-sqlalchemy >= 1.0']


import pygame

pygame.init()

class Button:
    def __init__(self, rect, color= (100, 100, 100), selected_color= (0, 100, 0), text= '', text_color= (200, 200, 200), text_size= None):
        self.rect = rect
        self.color = color
        self.selected_color = selected_color
        self.text = text

        if text_size == None:
            self.text_size = round(rect.height * rect.width * 0.005)
        else:
            self.text_size = text_size

        self.text_color = text_color
        self.on_down = False
        self.on_up = False
        self.selected = False

    def draw(self, window):
        if not self.selected:
            pygame.draw.rect(window, self.color, self.rect)
        else:
            pygame.draw.rect(window, self.selected_color, self.rect)
        if self.text != '':
            self.draw_text(window)

    def draw_text(self, surface):
        font = pygame.font.SysFont('calibri', self.text_size)
        text_render = font.render(self.text, 1, self.text_color)
        text_rect = text_render.get_rect()
        text_rect.center = self.rect.center
        surface.blit(text_render, text_rect)

    def turn_select(self):
        if self.selected:
            self.selected = False
        else:
            self.selected = True

    def click(self, event, mx, my, color_change = True, color_down = (100, 100, 200), color_up= (100, 100, 100)):
        if self.rect.collidepoint((mx, my)):
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if color_change:
                        self.color = color_down

                    self.on_down = True
                    self.on_up = False
                    return False

            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    if color_change:
                        self.color = color_up

                    self.on_down = False
                    self.on_up = True

                    return True


import os

from util import get_newest,readImage,one_hot,average
from model.loss_metric import *
from arg_parser import arg_parser

a = arg_parser()

metric_dict = {'Precision': Precision, 'IoU': IOU, 'DSC': DSC};metric_keys = list(metric_dict.keys())
model_dict = {'unet':'Unet', 'unet_se':'Unet-SE', 'uplus':'Unet++', \
              'r2u':'R2Unet', 'ce':'CEnet', 'wnet':'Wnet', 'wnet_r':'Wnet_raw', \
              'att':'Attention-Unet', 'att_se':'Attention-Unet-SE', 'attwnet':'Attention-Wnet', 'att_old': 'Attention-Unet-old'}
target_dict = {'HN_OAR': 'HaN_OAR', 'Lu_OAR': 'Thoracic_OAR', 'HN_GTV': 'Naso_GTV', 'Lu_GTV': 'Lung_GTV'}
num_class_dict = {'HaN_OAR': 23, 'Thoracic_OAR': 7, 'Lung_GTV': 2, 'Naso_GTV': 2}

a.add_map('--model', model_dict)
a.add_map('--target', target_dict)

ret_dict = a()

model_key = ret_dict['--model']
target = ret_dict['--target']
num_class = num_class_dict[target]

label_root_path = os.path.join(r'E:\dataset\zhongshan_hospital\CSTRO\test', 'HaN_OAR')
test_list = os.listdir(label_root_path)
predict_root_path = get_newest(os.path.join('build', '{}-{}'.format(model_key, target), 'test_result'))

metric_list = {key:[] for key in metric_keys}
metric_channelwise_list = {key:[] for key in metric_keys}
f_dict = {key:open('{}/{}.txt'.format(predict_root_path, key), 'w') for key in metric_keys}

for key in metric_keys:
    f = f_dict[key]
    f.write('name ')
    for i in range(1, num_class):
        f.write('OAR%d '%(i))
    f.write('average\n')

count = 0
for patient in test_list:
    predict_path = os.path.join(predict_root_path, patient, 'predict.nii.gz')
    label_path = os.path.join(label_root_path, patient, 'label.nii.gz')

    predict = readImage(predict_path).astype(np.uint8)
    label = readImage(label_path)

    predict = one_hot(predict)
    label = one_hot(label)

    for key in metric_keys:
        f = f_dict[key]
        temp_list = []
        temp_string = 'patient{} '.format(patient)
        for i in range(1, num_class):
            metric = metric_dict[key](label[..., i], predict[..., i])
            temp_string += '%.4f '%(metric)
            temp_list.append(metric)
        avg = average(temp_list)
        temp_string += '%.4f\n'%(avg)
        metric_channelwise_list[key].append(temp_list)
        metric_list[key].append(avg)
        f.write(temp_string)

    count += 1
    print('patient{} done {}/{}'.format(patient, count, len(test_list)))

for key in metric_keys:
    f = f_dict[key]
    temp_string = 'average '
    for i in range(1, num_class):
        temp_string += '%.4f '%(average([sub[i-1] for sub in metric_channelwise_list[key]]))
    temp_string += '%.4f\n'%(average(metric_list[key]))
    f.write(temp_string)
    f.close()


from .point import *
from .line  import *

class Circle:
    def __init__(self, p, r):
        self.p = p
        self.r = r

    def contains(self, p):
        return (self.p - p).norm() < self.r

    @staticmethod
    def circum(p, q, r):
        z1 = (q + p) / 2.0
        z2 = (r + p) / 2.0
        l1 = Line(z1, z1 + (q - p).rot(math.pi / 2.0))
        l2 = Line(z2, z2 + (r - p).rot(math.pi / 2.0))
        c = l1.intersect_LL(l2)
        r = (p - c).norm()
        return Circle(c, r)


import tkinter as tk
from tkinter import font
from tkinter import messagebox
x = 0
def add(ent, y):
    global  x
    x += y
    ent.delete(0,'end')
    ent.insert(tk.END,str(x))

root = tk.Tk()
defaultFont = font.nametofont("TkDefaultFont")
defaultFont.configure(size = 25)
root.option_add("*Font", defaultFont)
e1 = tk.Entry(root)
add(e1, 0)
e1.grid(row=0,column=1,columnspan = 1)

tk.Button(root,text='1',command= lambda: add(e1,1)).grid(row=1,column=0)
tk.Button(root,text='2',command= lambda: add(e1,2)).grid(row=1,column=1)
root.mainloop()


from pathlib import Path

FLASK_PORT = 5285
ROOT_API_AWS = 'https://e84nb9yy7f.execute-api.us-east-1.amazonaws.com/dev'
ROOT_API_FLASK = f'http://localhost:{FLASK_PORT}'
LOCAL_AWS_PROFILE = 'tristengeven'
AWS_REGION = 'us-east-1'
APP_NAME = 'hellolambda'
S3_SITE_BUCKET = 'hellolambda.tristeneven.com'
CORS_ACCEPTABLE_ORIGINS = ['hellolambda.tristeneven.com']
PRODUCTION_DOMAINS = ['hellolambda.com', 'www.hellolambda.com']

TEST_PATH_PREFIX = '/test'

ROOTP = Path(__file__).parent.parent
SITE_ASSETS_DIR = ROOTP / 'hellolambdaapi/assets'

EMAIL = {
    'notification_addr': 'test@gmail.com',
    'from_addr': 'test2@gmail.com',
    'feedback_subject': 'Hellolambda Form Content'
}

DYNAMO_TABLE_NAME = 'hellolambda'

# Event limiter
MAX_DYNAMO_PER_DAY = 2000
MAX_EMAIL_PER_DAY = 100

# Global - Ugly but easy, and easier than flask.g
is_debug_server = None


# Create a custom initializer on the sub-class and then call the parent class's initializer via super
# Creating Superclass

class Vehicle:
    def __init__(self, name, price):
        self.name = name
        self.price = price

# Create a custom initializer on the sub-class and then call the parent class's initializer via super
# Creating subclasses
class Car(Vehicle):

    def __init__(self, name, price, model, year, color):
        self.model = model
        self.year = year
        self.color = color
        super().__init__(name, price)

if __name__ == "__main__":
    car1 = Car("Honda", 23000, "EX", "2020", "Black")

    print("Vehicle name: {}, price: {}".format(car1.name, car1.price))
    print("Vehicle name: {}, model: {}, year: {}, price: {}, color: {}".format(car1.name, car1.model, car1.year, car1.price, car1.color))


"""
Name: 'Eurocom Interchange File'
Blender: 2.90.1
Group: 'Export'
Tooltip: 'Blender EIF Exporter for EuroLand'
Authors: Swyter and Jmarti856
"""
import bpy
import os
import math
import datetime
import bmesh
from mathutils import *
from math import *
from pathlib import Path
from bpy_extras.io_utils import axis_conversion
from bpy import context
from pprint import pprint
from decimal import Decimal
from mathutils import Euler

def _write(context, filepath,
            EXPORT_GLOBAL_MATRIX,
        ):

    #===============================================================================================
    #  GLOBAL VARIABLES
    #===============================================================================================
    ProjectContextScene = bpy.context.scene

    # Axis Conversion
    InvertAxisRotationMatrix = Matrix(((1, 0, 0),(0, 0, 1),(0, 1, 0)))

    #===============================================================================================
    #  MAIN
    #===============================================================================================
    def WriteFile():
        # Stop edit mode
        if bpy.ops.object.mode_set.poll():
            bpy.ops.object.mode_set(mode='OBJECT')

        #Create new file
        with open(filepath, 'w') as out:
            #Start writing
            AmbientValue = bpy.context.scene.world.light_settings.ao_factor
            out.write('*EUROCOM_INTERCHANGE_FILE 100\n')
            out.write('*COMMENT Eurocom Interchange File Version 1.00 %s\n' % (datetime.datetime.utcnow()).strftime('%A %B %d %Y %H:%M'))
            out.write('\n')
            out.write('*OPTIONS {\n')
            out.write('\t*COORD_SYSTEM %s\n' % "LH")
            out.write('}\n')
            out.write('\n')
            out.write('*SCENE {\n')
            out.write('\t*FILENAME "%s"\n' % (bpy.data.filepath))
            out.write('\t*FIRSTFRAME %d\n' % (ProjectContextScene.frame_start))
            out.write('\t*LASTFRAME %d\n' % (ProjectContextScene.frame_end))
            out.write('\t*FRAMESPEED %d\n' % (ProjectContextScene.render.fps))
            out.write('\t*STATICFRAME %d\n' % (ProjectContextScene.frame_current))
            out.write('\t*AMBIENTSTATIC %.6f %.6f %.6f\n' %(AmbientValue, AmbientValue, AmbientValue))
            out.write('}\n')
            out.write('\n')

            #===============================================================================================
            #  MATERIAL LIST
            #===============================================================================================
            MaterialIndex = 0
            out.write('*MATERIALS {\n')
            for mat in bpy.data.materials:
                if hasattr(mat.node_tree, 'nodes'):
                    DiffuseColor = mat.diffuse_color
                    ImageNode = mat.node_tree.nodes.get('Image Texture', None)

                    #Material has texture
                    if (ImageNode is not None):
                        ImageName = ImageNode.image.name
                        out.write('\t*MATERIAL %d {\n' % (MaterialIndex))
                        out.write('\t\t*NAME "%s"\n' % (os.path.splitext(ImageName)[0]))
                        out.write('\t\t*COL_DIFFUSE %.6f %.6f %.6f\n' % (DiffuseColor[0], DiffuseColor[1], DiffuseColor[2]))

                        #Check if the texture exists
                        if (os.path.exists(bpy.path.abspath(ImageNode.image.filepath))):
                            out.write('\t\t*TWOSIDED\n')
                            out.write('\t\t*MAP_DIFFUSE "%s"\n' % (bpy.path.abspath(ImageNode.image.filepath)))
                        out.write('\t\t*MAP_DIFFUSE_AMOUNT 1.0\n')

                        #Check if use Alpha
                        if mat.blend_method.startswith('ALPHA'):
                            out.write('\t\t*MAP_HASALPHA\n')

                        MaterialIndex +=1
                        out.write('\t}\n')

                    #Material has no texture
                    else:
                        Color = DiffuseColor[0] + DiffuseColor[1] + DiffuseColor[2]
                        out.write('\t*MATERIAL %d {\n' % (MaterialIndex))
                        out.write('\t\t*NAME "%s"\n' % (mat.name))
                        out.write('\t\t*COL_DIFFUSE %.6f %.6f %.6f\n' % (DiffuseColor[0], DiffuseColor[1], DiffuseColor[2]))
                        out.write('\t}\n')
                        MaterialIndex +=1
            out.write('}\n')
            out.write('\n')

            #===============================================================================================
            #  MESH DATA
            #===============================================================================================
            for obj in ProjectContextScene.objects:
                if obj.type == 'MESH':
                    if hasattr(obj, 'data'):
                        #===========================================[Clone Object]====================================================
                        depsgraph = bpy.context.evaluated_depsgraph_get()
                        ob_for_convert = obj.evaluated_get(depsgraph)

                        try:
                            MeshObject = ob_for_convert.to_mesh()
                        except RuntimeError:
                            MeshObject = None

                        if MeshObject is None:
                            continue

                        #===========================================[Apply Matrix]====================================================
                        MeshObject.transform(EXPORT_GLOBAL_MATRIX)
                        MeshObject.flip_normals()

                        #===========================================[Get Object Data]====================================================
                        #Get vertex list without duplicates
                        VertexList = []
                        for ObjVertex in MeshObject.vertices:
                            VertexList.append(ObjVertex.co)

                        #Get UVs list without duplicates
                        UVList = []
                        if hasattr(MeshObject.uv_layers.active, 'data'):
                            if len(MeshObject.uv_layers):
                                for layer in MeshObject.uv_layers:
                                    uv_layer = layer.data
                                    for pl_count, poly in enumerate(MeshObject.polygons):
                                        for li_count, loop_index in enumerate(poly.loop_indices):
                                            UVList.append(
                                                (uv_layer[loop_index].uv.x, 1.0 - uv_layer[loop_index].uv.y)
                                            )
                                UVList = list(dict.fromkeys(UVList))

                        #Get vertex color list without duplicates
                        VertexColList = []
                        if len(MeshObject.vertex_colors):
                            if hasattr(MeshObject.vertex_colors.active, 'data'):
                                for layer in MeshObject.vertex_colors:
                                    for vertex in layer.data:
                                        VertexColList.append(
                                            (vertex.color[0] * .5, vertex.color[1] * .5, vertex.color[2] * .5, vertex.color[3])
                                        )
                                VertexColList = list(dict.fromkeys(VertexColList))

                        FaceFormat = 'V'
                        #===========================================[Print Object Data]====================================================
                        out.write('*MESH {\n')
                        out.write('\t*NAME "%s"\n' % obj.name)
                        out.write('\t*VERTCOUNT %d\n' % len(VertexList))
                        out.write('\t*UVCOUNT %d\n' % len(UVList))
                        out.write('\t*VERTCOLCOUNT %d\n' % len(VertexColList))
                        out.write('\t*FACECOUNT %d\n' % len(MeshObject.polygons))
                        out.write('\t*TRIFACECOUNT %d\n' % sum(len(p.vertices) - 2 for p in MeshObject.polygons))

                        if len(MeshObject.uv_layers) > 0:
                            out.write('\t*FACELAYERSCOUNT %d\n' % len(MeshObject.uv_layers))
                        else:
                            out.write('\t*FACELAYERSCOUNT %d\n' % 1)

                        if len(MeshObject.uv_layers) > 1:
                            out.write('\t*FACESHADERCOUNT %d\n' % len(MeshObject.material_slots))

                        #Print Vertex List
                        out.write('\t*VERTEX_LIST {\n')
                        for VertexData in VertexList:
                            out.write('\t\t%.6f %.6f %.6f\n' % (VertexData.x, VertexData.y, VertexData.z))
                        out.write('\t}\n')

                        #Print UV data
                        out.write('\t*UV_LIST {\n')
                        if (len(UVList) > 0):
                            FaceFormat += 'T'
                            for uv in UVList:
                                out.write('\t\t%.6f %.6f\n' % (uv[0], uv[1]))
                        out.write('\t}\n')

                        #Print Vertex Color List
                        out.write('\t*VERTCOL_LIST {\n')
                        if(len(VertexColList) > 0):
                            FaceFormat += 'C'
                            for col in VertexColList:
                                out.write('\t\t%.6f %.6f %.6f %.6f\n' % (col[0], col[1], col[2], col[3]))
                        out.write('\t}\n')

                        if len(obj.material_slots) > 0:
                            FaceFormat += 'M'
                            FaceFormat += 'F'

                        #Print Shader faces
                        if (len(MeshObject.uv_layers) > 1):
                            ShaderIndex = 0
                            MaterialIndex = 0
                            out.write('\t*FACESHADERS {\n')
                            for mat in MeshObject.material_slots:
                                out.write('\t\t*SHADER %d {\n' % ShaderIndex)

                                if mat.material.blend_method == 'OPAQUE':
                                    out.write('\t\t\t%d %s\n' % (bpy.data.materials.find(mat.name),"Non"))
                                else:
                                    out.write('\t\t\t%d %s\n' % (bpy.data.materials.find(mat.name),"Alp"))
                                out.write('\t\t}\n')

                                #update Counter
                                MaterialIndex +=1
                            out.write('\t}\n')

                        #Get FaceFormat
                        out.write('\t*FACEFORMAT %s\n' % FaceFormat)

                        #Print Face List, the difficult part ;P
                        out.write('\t*FACE_LIST {\n')
                        for MeshPolys in MeshObject.polygons:
                            #Write vertices ---V
                            out.write('\t\t%d ' % (len(MeshPolys.vertices)))
                            for vert in MeshPolys.vertices:
                                out.write('%d ' % vert)

                            #Write UVs ---T
                            if ('T' in FaceFormat):
                                for vert_idx, loop_idx in enumerate(MeshPolys.loop_indices):
                                    for layer in MeshObject.uv_layers:
                                        uv_coords = layer.data[loop_idx].uv
                                        out.write('%d ' % UVList.index((uv_coords.x, 1.0 - float(uv_coords.y))))

                            #Write Colors ---C
                            if ('C' in FaceFormat):
                                for color_idx, loop_idx in enumerate(MeshPolys.loop_indices):
                                    # swy: this is wrong; it should be the same layer count as any other face format block, can't be a different size. me.vertex_colors != me.uv_layers
                                    for layerIndex in MeshObject.vertex_colors:
                                        vertex = layerIndex.data[loop_idx]
                                        out.write('%d ' % VertexColList.index((vertex.color[0] * .5, vertex.color[1] * .5, vertex.color[2] * .5, vertex.color[3])))
                            # swy: we're missing exporting (optional) face normals here

                            if ('M' in FaceFormat):
                                for layer in MeshObject.uv_layers:
                                    out.write('%d ' % MeshPolys.material_index)

                            # swy: we're missing exporting an optional shader index here

                            #Write Flags ---F
                            if ('F' in FaceFormat):
                                flags = 0

                                if obj.material_slots[MeshPolys.material_index].material.use_backface_culling:
                                    flags |= 1 << 16
                                out.write('%d ' % flags)

                            out.write('\n')
                        out.write('\t}\n')
                    out.write('}\n')
                    out.write('\n')

            for obj in ProjectContextScene.objects:
                if obj.type == 'MESH':
                    if hasattr(obj, 'data'):
                        #===============================================================================================
                        #  GEOM NODE
                        #===============================================================================================
                        out.write('*GEOMNODE {\n')
                        out.write('\t*NAME "%s"\n' % (obj.name))
                        out.write('\t*MESH "%s"\n' % (obj.name))
                        out.write('\t*WORLD_TM {\n')
                        out.write('\t\t*TMROW0 %.6f %.6f %.6f %.6f\n' % (1,0,0,0))
                        out.write('\t\t*TMROW1 %.6f %.6f %.6f %.6f\n' % (0,1,0,0))
                        out.write('\t\t*TMROW2 %.6f %.6f %.6f %.6f\n' % (0,0,1,0))
                        out.write('\t\t*TMROW3 %.6f %.6f %.6f %.6f\n' % (0,0,0,1))
                        out.write('\t\t*POS %.6f %.6f %.6f\n' % (0,0,0))
                        out.write('\t\t*ROT %.6f %.6f %.6f\n' % (0,0,0))
                        out.write('\t\t*SCL %.6f %.6f %.6f\n' % (1,1,1))
                        out.write('\t}\n')
                        out.write('\t*USER_FLAGS_COUNT %u\n' % 1)
                        out.write('\t*USER_FLAGS {\n')
                        out.write('\t\t*SET 0 0x00000000\n')
                        out.write('\t}\n')
                        out.write('}\n')

            for obj in ProjectContextScene.objects:
                if obj.type == 'MESH':
                    if hasattr(obj, 'data'):
                        #===============================================================================================
                        #  PLACE NODE
                        #===============================================================================================
                        out.write('*PLACENODE {\n')
                        out.write('\t*NAME "%s"\n' % (obj.name))
                        out.write('\t*MESH "%s"\n' % (obj.name))
                        out.write('\t*WORLD_TM {\n')

                        #Jump to the first frame
                        ProjectContextScene.frame_set(ProjectContextScene.frame_start)

                        ConvertedMatrix = obj.rotation_euler.to_matrix()
                        rot_mtx = InvertAxisRotationMatrix @ ConvertedMatrix
                        RotationMatrix = rot_mtx.transposed()
                        loc_conv = InvertAxisRotationMatrix @ obj.location

                        #Print Roation matrix
                        out.write('\t\t*TMROW0 %.6f %.6f %.6f %.6f\n' % (RotationMatrix[0].x, (RotationMatrix[0].y * -1), RotationMatrix[0].z, 0))
                        out.write('\t\t*TMROW1 %.6f %.6f %.6f %.6f\n' % (RotationMatrix[1].x, RotationMatrix[1].y, RotationMatrix[1].z, 0))
                        out.write('\t\t*TMROW2 %.6f %.6f %.6f %.6f\n' % ((RotationMatrix[2].x * -1), (RotationMatrix[2].y * -1), (RotationMatrix[2].z) * -1, 0))
                        out.write('\t\t*TMROW3 %.6f %.6f %.6f %.6f\n' % (loc_conv.x, loc_conv.y, loc_conv.z, 1))

                        # swy: these aren't actually used or read by this version of the importer
                        out.write('\t\t*POS %.6f %.6f %.6f\n' % (loc_conv.x, loc_conv.y, loc_conv.z))
                        out.write('\t\t*ROT %.6f %.6f %.6f\n' % (radians(obj.rotation_euler.x), radians(obj.rotation_euler.y), radians(obj.rotation_euler.z)))
                        out.write('\t\t*SCL %.6f %.6f %.6f\n' % (obj.scale.x, obj.scale.y, obj.scale.z))
                        out.write('\t}\n')
                        out.write('}\n')
            #Close File
            out.flush()
            out.close()
    WriteFile()

def save(context,
            filepath,
            *,
            global_matrix=None,
        ):

    _write(context, filepath,
            EXPORT_GLOBAL_MATRIX=global_matrix,
        )

    return {'FINISHED'}
if __name__ == '__main__':
    save({}, str(Path.home()) + '/Desktop/EurocomEIF.eif')


T = input ()
for t in xrange (1, T + 1):
  d = {}
  n = input ()
  for i in range(2 * n - 1):
    a = map(int, raw_input().split())
    for j in a:
      if j not in d:
        d[j] = 0
      d[j] += 1
  ans = []
  for i in d:
    if d[i] % 2 != 0:
      ans.append(i)
  ans.sort()
  ans = map(str, ans)
  print("Case #%i: %s" % (t, " ".join(ans)))


#infile = open("input.txt", "r")
outfile = open("output.txt", "w")

def findBase(base, num, n):
    result = 0
    mult = 1
    for i in range (n):
        result += mult * num[n-1-i]
        mult *= base
    return result

def printResult(num, primeDiv, n):
    for i in range (n):
        print(str(num[i]), end='')
    for i in range (2, 11, 1):
        print(" ", end='')
        print(str(primeDiv[i]), end='')
    print('')

def printToFile(num, primveDiv, n):
    for i in range (n):
        outfile.write(str(num[i]))
    for i in range (2, 11, 1):
        outfile.write(" ")
        outfile.write(str(primeDiv[i]))
    outfile.write("\n")

def findPrime(num):
    maxDiv = min(num, 10000)
    for i in range (3, maxDiv, 2):
        if (num%i == 0):
            return i

    return -1

n = 32
j = 500

a = [0 for i in range (n)]
a[n-1] = 1
a[0] = 1

count = 0
numBase = 0

while(count < j):
    for i in range (2, n, 1):
        if(a[n-i] == 0):
            a[n-i] = 1
            break
        a[n-i] = 0
    isPrime = False
    primeDiv = [0 for i in range(11)]
    for i in range (2, 11, 1):
        numBase = findBase(i, a, n)
        primeDiv[i] = findPrime(numBase)
        if(primeDiv[i] == -1):
            isPrime = True
            break
    if (isPrime):
        continue
    #printResult(a, primeDiv, n)
    printToFile(a, primeDiv, n)
    print(str(count))
    count += 1

outfile.close()


import random
from keras.datasets import cifar10

class DataProvider(object):
    def __init__(self, images, labels):
        self.n_sample = len(labels)
        self.queue = list(range(self.n_sample))
        random.shuffle(self.queue)

        self.images = images
        self.labels = labels
        self.epoch_count = 0

    def next_batch(self, batch_size):
        if len(self.queue) < batch_size:
            self.queue = list(range(self.n_sample))
            self.epoch_count += 1
        target_indices = self.queue[:batch_size]
        del self.queue[:batch_size]
        return self.images[target_indices], self.labels[target_indices]

class Cifar10Provider(DataProvider):

    def __init__(self):
        (x_train, y_train), (x_test, y_test) = cifar10.load_data()

        # Data reshape
        self.y_train, self.y_test = [y.reshape([-1]) for y in [y_train, y_test]]

        # Data Normalization
        self.x_train, self.x_test = [x / 255. for x in [x_train, x_test]]

        super(Cifar10Provider, self).__init__(self.x_train, self.y_train)

        print('image shape : {}, label shape : {} '.format(x_train.shape, y_train.shape))
        print('image shape : {}, label shape : {} '.format(x_test.shape, y_test.shape))
        print('train minimun : {}, train_maximum : {} '.format(x_train.min(), x_train.max()))
        print('tests minimun : {}, test_maximum : {} '.format(x_test.min(), x_test.max()))


from automation import __version__
from automation import *
import re

def test_version():
    assert __version__ == '0.1.0'

def test_email_format():

    with open('automation/assest/Email.txt','r') as emails:
        emails=emails.read()
        emails=emails.split()

    for email in emails:
        match = re.search(r'[\w.+-]+@[\w-]+\.[\w.-]+', email)
        assert bool(match)

def test_phone_format():

    with open('automation/assest/phone.txt','r') as phones:
        phones=phones.read()
        phones=phones.split()

    for phone in phones:
        match = re.search(r'\d{3}-\d{3}-\d{4}$', phone)
        assert bool(match)


from envs.custom_env_dir.custom_dqn import DeepQNetwork
from envs.custom_env_dir.replay_memory import ReplayBuffer
import numpy as np
import torch as T
from datetime import datetime
import os

class DQNAgent(object):
    def __init__(self, gamma, epsilon, lr, n_actions, input_dims, optimizer, fc1_dims, fc2_dims,
                 mem_size, batch_size, chkpt_dir, replace, eps_min, eps_dec,
                 algo, env_name):

        self.gamma = gamma
        self.epsilon = epsilon
        self.lr = lr
        self.n_actions = n_actions
        self.input_dims = input_dims
        self.batch_size = batch_size
        self.eps_min = eps_min
        self.eps_dec = eps_dec
        self.replace_target_cnt = replace
        self.algo = algo
        self.env_name = env_name
        self.chkpt_dir = chkpt_dir
        cwd = os.getcwd()
        self.action_space = [i for i in range(n_actions)]
        self.learn_step_counter = 0
        now = datetime.now().strftime('%Y%m%d_%H%M')

        # Replay memory
        self.memory = ReplayBuffer(mem_size, input_dims, n_actions)

        # Q-network / online network
        self.q_eval = DeepQNetwork(self.lr, self.n_actions,
                                    input_dims=self.input_dims,
                                    name=optimizer+'_gamma'+str(gamma)+'_lr'+\
                                       (('%.15f' % lr).rstrip('0').rstrip('.'))+\
                                       '_replace'+str(replace)+'_HL['+str(fc1_dims)+\
                                       ' ,'+str(fc2_dims)+']_q_eval.pt',chkpt_dir=self.chkpt_dir,\
                                       fc1_dims=fc1_dims, fc2_dims=fc2_dims, seed=1, optimizer=optimizer)

        # Target network
        self.q_next = DeepQNetwork(self.lr, self.n_actions,
                                    input_dims=self.input_dims,
                                    name=optimizer+'_gamma'+str(gamma)+'_lr'+\
                                       (('%.15f' % lr).rstrip('0').rstrip('.'))+\
                                       '_replace'+str(replace)+'_HL['+str(fc1_dims)+\
                                       ' ,'+str(fc2_dims)+']_q_next.pt',chkpt_dir=self.chkpt_dir,\
                                       fc1_dims=fc1_dims, fc2_dims=fc2_dims, seed=1, optimizer=optimizer)

    # Function for action selection
    def choose_action(self, observation):
        # Apply e-greedy action selection
        if np.random.random() > self.epsilon:
            state = T.tensor([observation],dtype=T.float).to(self.q_eval.device)
            actions = self.q_eval.forward(state)
            action = T.argmax(actions).item()
        else:
            action = np.random.choice(self.action_space)

        return action

    # Store state transitions in replay memory
    def store_transition(self, state, action, reward, state_):
        self.memory.store_transition(state, action, reward, state_)

    # Function samples mini-batch of transitions from replay memory
    def sample_memory(self):
        state, action, reward, new_state = \
                                self.memory.sample_buffer(self.batch_size)

        states = T.tensor(state).to(self.q_eval.device)
        rewards = T.tensor(reward).to(self.q_eval.device)
        actions = T.tensor(action).to(self.q_eval.device)
        states_ = T.tensor(new_state).to(self.q_eval.device)

        return states, actions, rewards, states_

    # Function updates weights of the target network every C steps
    def replace_target_network(self):
        if self.learn_step_counter % self.replace_target_cnt == 0:
            self.q_next.load_state_dict(self.q_eval.state_dict())

    # Function decrements epsilon during training process
    def decrement_epsilon(self):
        self.epsilon = self.epsilon - self.eps_dec \
                           if self.epsilon > self.eps_min else self.eps_min

    # Function stores current model parameters
    def save_models(self):
        self.q_eval.save_checkpoint()
        self.q_next.save_checkpoint()

    # Function stores final agent at the end of each training run
    def save_models_final(self):
        self.q_eval.save_checkpoint_final()
        self.q_next.save_checkpoint_final()

    def load_models(self):
        self.q_eval.load_checkpoint()
        self.q_next.load_checkpoint()

    def load_models_final(self):
        self.q_eval.load_checkpoint_final()
        self.q_next.load_checkpoint_final()

    def learn(self):
        if self.memory.mem_cntr < self.batch_size:
            return

        # sets gradient of optimizer object to zero
        self.q_eval.optimizer.zero_grad()

        self.replace_target_network()

        states, actions, rewards, states_ = self.sample_memory()
        indices = np.arange(self.batch_size)

        # q_eval ist the main DQN (online network)
        q_pred = self.q_eval.forward(states)[indices, actions]

        # q_next is the target network
        q_next = self.q_next.forward(states_).max(dim=1)[0]
        q_target = rewards + self.gamma*q_next

        loss = self.q_eval.loss(q_target, q_pred).to(self.q_eval.device)
        loss.backward()
        self.q_eval.optimizer.step()
        self.learn_step_counter += 1

        self.decrement_epsilon()


# -*- coding: utf-8 -*-
"""
Created on Sat Mar  1 15:30:23 2014

@author: kyle
"""
import urllib2
import alsaaudio, wave, time
import audiotools

def transcribe_voice(audio):
    """
    Takes the filepath to a 16000hz flac audio file as a string, sends it to the google
    voice recognition service, and returns the transcription and confidence of the result
    as two elements in a list.
    """
    flac=open(audio,"rb").read()
    header = {'Content-Type' : 'audio/x-flac; rate=16000'}
    req = urllib2.Request("http://www.google.com/speech-api/v1/recognize?lang=en" , flac, header)
    data = urllib2.urlopen(req)
    tResult=data.read()
    front=tResult.find('"utterance":') #the next few lines process the string to return only the text and confidence.
    back=tResult.find('"confidence":')
    s1=tResult[front+13:back-2]
    s2=tResult[back+13:len(tResult)-4]
    return[s1,float(s2)]

def record():
    """ Output:
            A recording in .wav format
    """

    inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE) #Represents the PCM device on the laptop
    inp.setchannels(1)
    inp.setrate(16000) #Sampling rate = CD quality
    inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
    inp.setperiodsize(1024)

    w = wave.open('test.wav', 'w')
    w.setnchannels(1)
    w.setsampwidth(2)
    w.setframerate(16000)

    now = time.time()
    future = now + 5  #Sets up a stopwatch so that the recording stops after 5 seconds

    while time.time() < future:
        l, data = inp.read()
        w.writeframes(data) #Writes data to the file

def convert_wav_to_flac(audio):
    """
    Takes the path of a wav audio file, then converts it to flac 16000hz and names it temp.flac
    Note, you must install the audiotools package.
    http://sourceforge.net/projects/audiotools/files/
    """
    audiotools.open(audio).convert("temp.flac",audiotools.FlacAudio)
    #Damn that was simple.

if __name__=='__main__':
    record()
    convert_wav_to_flac('test.wav')
    print(transcribe_voice('temp.flac'))


import logging
import time

from selenium import webdriver

import config

def screenshot(case):
    """"""
    t = time.strftime("%Y%m%d-%H%M%S")
    img_path = config.BASE_DIR + "/screenshot/{}-{}.png".format(case._testMethodName, t)
    DriverUtil.get_driver().get_screenshot_as_file(img_path)

def get_tips_msg():
    """
    获取弹出框的提示消息
    :return: 消息文本内容
    """
    msg = DriverUtil.get_driver().find_element_by_class_name("layui-layer-content").text
    return msg

def exist_text(text):
    """
    判断页面中是否存在指定的文本内容
    :param text: 文本内容
    :return: True:存在; False:不存在
    """
    try:
        xpath = "//*[contains(text(), '{}')]".format(text)
        element = DriverUtil.get_driver().find_element_by_xpath(xpath)
        return element is not None
    except Exception as e:
        print("current page not contains [{}]".format(text))
        logging.exception(e)
        return False

def switch_new_window():
    """
    切换到新窗口
    """
    # 等待一下新窗口的打开
    time.sleep(3)
    driver = DriverUtil.get_driver()
    driver.switch_to.window(driver.window_handles[-1])

class DriverUtil:
    """
    浏览器驱动工具类
    """
    _driver = None
    _auto_quit = True

    @classmethod
    def get_driver(cls):
        """
        获取浏览器驱动对象，并完成初始化设置
        :return: 浏览器驱动对象
        """
        if cls._driver is None:
            logging.info("init driver...")
            cls._driver = webdriver.Chrome()
            cls._driver.maximize_window()
            cls._driver.implicitly_wait(30)
            cls._driver.get(config.INDEX_URL)
        return cls._driver

    @classmethod
    def quit_driver(cls):
        """
        关闭浏览器驱动
        """
        if cls._auto_quit and cls._driver is not None:
            cls._driver.quit()
            cls._driver = None

    @classmethod
    def set_auto_quit(cls, auto_quit):
        """设置是否自动退出驱动"""
        cls._auto_quit = auto_quit


from turtle import *

shape ("arrow")
speed (-1)

for i in range (3,7,1):
    if i % 2 == 0:
        color ("green")
    else:
        color ("red")
    for j in range (i):
        forward (100)
        left (360/i)

mainloop()


import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2

plt.figure(figsize=(5,5))#figsize设置图片的大小

plt.xlim((-1.2))#设置坐标轴的范围
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)#将x坐标的数值改为新建立的new_ticks
plt.yticks([-2,-1.8,-1,1.22,3],
           ['$really bad$','bad','normal ','good','really good'])#$来优化字体，能识别反斜杠\+空格，r表示正则表达

l1,=plt.plot(x,y2,label='up')#label中的up表示图的名字
l2,=plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='down')#两条线画一个figure里面

plt.legend(handles=[l1,l2],labels=['aa','bb'],loc='best')#打印图历  handles表示将l1，l2表示的线框起来
##lables表示给l1和l2给定一个新的图历名字来代替以前的
##loc表示图历位置，best表示寻找最佳位置，upper right 表示右上角

plt.show()


'''Train CIFAR10/100 with PyTorch using standard Contrastive Learning. This script tunes the L2 reg weight of the
final classifier.'''
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn

import math
import os
import argparse

from models import *
from configs import get_datasets
from evaluate import train_clf, encode_feature_averaging

parser = argparse.ArgumentParser(description='Final evaluation with feature averaging.')
parser.add_argument("--num-workers", type=int, default=2, help='Number of threads for data loaders')
parser.add_argument("--load-from", type=str, default='ckpt.pth', help='File to load from')
parser.add_argument("--num-passes", type=int, default=10, help='Number of passes to average')
parser.add_argument("--reg-lower", type=float, default=-7, help='Minimum log regularization parameter (base 10)')
parser.add_argument("--reg-upper", type=float, default=-3, help='Maximum log regularization parameter (base 10)')
parser.add_argument("--num-steps", type=int, default=10, help='Number of log-linearly spaced reg parameters to try')
args = parser.parse_args()

# Load checkpoint.
print('==> Loading settings from checkpoint..')
assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'
resume_from = os.path.join('./checkpoint', args.load_from)
checkpoint = torch.load(resume_from)
args.dataset = checkpoint['args']['dataset']
args.arch = checkpoint['args']['arch']

device = 'cuda' if torch.cuda.is_available() else 'cpu'

# Data
print('==> Preparing data..')
_, testset, clftrainset, num_classes, stem = get_datasets(args.dataset, test_as_train=True)

testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=False, num_workers=args.num_workers,
                                         pin_memory=True)
clftrainloader = torch.utils.data.DataLoader(clftrainset, batch_size=1000, shuffle=False, num_workers=args.num_workers,
                                             pin_memory=True)

# Model
print('==> Building model..')
##############################################################
# Encoder
##############################################################
if args.arch == 'resnet18':
    net = ResNet18(stem=stem)
elif args.arch == 'resnet34':
    net = ResNet34(stem=stem)
elif args.arch == 'resnet50':
    net = ResNet50(stem=stem)
else:
    raise ValueError("Bad architecture specification")
net = net.to(device)

if device == 'cuda':
    repr_dim = net.representation_dim
    net = torch.nn.DataParallel(net)
    net.representation_dim = repr_dim
    cudnn.benchmark = True

print('==> Loading encoder from checkpoint..')
net.load_state_dict(checkpoint['net'])

best_acc = 0
X, y = encode_feature_averaging(clftrainloader, device, net, num_passes=args.num_passes)
X_test, y_test = encode_feature_averaging(testloader, device, net, num_passes=args.num_passes)
for reg_weight in torch.exp(math.log(10) * torch.linspace(args.reg_lower, args.reg_upper, args.num_steps,
                                                          dtype=torch.float, device=device)):
    clf = train_clf(X, y, net.representation_dim, num_classes, device, reg_weight=reg_weight)
    raw_scores = clf(X_test)
    _, predicted = raw_scores.max(1)
    correct = predicted.eq(y_test).sum().item()
    acc = 100 * correct / predicted.shape[0]
    print('Test accuracy', acc, '%')
    if acc > best_acc:
        best_acc = acc
print("Best test accuracy", best_acc, "%")