from rest_framework import viewsets, filters, status
from rest_framework.response import Response
from .models import Poll, Choice, Vote
from .serializers import PollSerializer, VoteSerializer, VoteConfirmationSerializer
from django.core.mail import send_mail
from rest_framework.decorators import action
from rest_framework.views import APIView

from pathlib import Path
import environ
import os

env = environ.Env()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

class PollViewSet(viewsets.ModelViewSet):
    queryset = Poll.objects.all()
    serializer_class = PollSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['title', 'description', 'choices__text']
    ordering = ['-expiry_date']
    paginate_by = 10
    paginate_by_param = 'page_size'
    max_paginate_by = 100

    def get_queryset(self):
        return super().get_queryset().order_by('-expiry_date')

class VoteViewSet(viewsets.ViewSet):
    def create(self, request):
        serializer = VoteSerializer(data=request.data)
        if serializer.is_valid():
            choice_id = serializer.validated_data['choice_id']
            email = serializer.validated_data['email']
            try:
                choice = Choice.objects.get(id=choice_id)
            except Choice.DoesNotExist:
                return Response({'error': 'Choice does not exist.'}, status=status.HTTP_404_NOT_FOUND)

            vote = Vote.objects.create(
                choice=choice,
                email=email,
                otp=Vote.generate_otp()
            )
            send_mail(
                'Your One-Time Password for Voting',
                f'Your OTP is {vote.otp}. It will expire in 10 minutes.',
                env('EMAIL_ADDRESS'),
                [email],
                fail_silently=False,
            )
            return Response({'message': 'OTP has been sent to your email.', 'uuid': str(vote.uuid)}, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class VoteConfirmationView(APIView):
    def post(self, request):
        serializer = VoteConfirmationSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        uuid = serializer.validated_data['uuid']
        otp = serializer.validated_data['otp']

        try:
            vote = Vote.objects.get(uuid=uuid)
        except Vote.DoesNotExist:
            return Response({'error': 'Invalid vote UUID.'}, status=status.HTTP_400_BAD_REQUEST)

        if otp != vote.otp:
            return Response({'error': 'Invalid OTP.'}, status=status.HTTP_400_BAD_REQUEST)

        if vote.is_otp_expired():
            return Response({'error': 'OTP expired.'}, status=status.HTTP_400_BAD_REQUEST)

        vote.confirmed = True
        vote.save()
        return Response({'success': 'Vote confirmed.'})


import random

RUNS = 10
COLLECTION_SIZE = 10000

def coupon_collector(n):
    collection = set()
    boxes = 0
    while len(collection) < n:
        r = random.randint(1, n)
        collection.add(r)
        boxes += 1
    return boxes

def main():
    total = 0
    for i in range(RUNS):
        result = coupon_collector(COLLECTION_SIZE)
        print(result)
        total += result
    print('Average for this run: ', total/RUNS)

if __name__ == '__main__':
    main()


from django.shortcuts import render
import tensorflow as tf
from numpy import *
import base64
from PIL import Image, ImageFilter
from django.http import JsonResponse
import pandas as pd

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.optimizers import Adam
from keras.utils import np_utils

#for image compare
from skimage import measure
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
import random
from pathlib import Path
from resizeimage import resizeimage

# Create your views here.

def refresh_model(request):
    train_data = pd.read_csv('train.csv')
    test_data = pd.read_csv('test.csv')
    y_train  = train_data.iloc[:, 0].values
    x_train = train_data.iloc[:, 1:].values
    x_train = x_train.reshape(len(x_train), 32, 32)
    y_test  = test_data.iloc[:, 0].values
    x_test = test_data.iloc[:, 1:].values
    x_test = x_test.reshape(len(x_test), 32, 32)
    x_train = tf.keras.utils.normalize(x_train, axis = 1)
    x_test = tf.keras.utils.normalize(x_test, axis = 1)
    x_train = x_train.reshape(len(x_train), 32, 32, 1)
    x_test = x_test.reshape(len(x_test), 32, 32, 1)

    number_of_classes = 46
    y_train = np_utils.to_categorical(y_train, number_of_classes)
    y_test = np_utils.to_categorical(y_test, number_of_classes)
    model = Sequential()
    model.add(Conv2D(32, (5, 5), input_shape=(x_train.shape[1], x_train.shape[2], 1), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Conv2D(32, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(number_of_classes, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])
    model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=10, batch_size=200)
    model.save('nepali_character_recognition_model.h5')
    return JsonResponse({'result': "Model refreshed successfully."})

def show_main_page(request):
        context = {
        "title": "DIGIT RECOGNITION APP"
        }
        return render(request, 'main_app/index.html', context)

def predict_digit(request):
        result = list(request.POST.keys())

        if(request.method == 'POST'):
                character_recognition_model = tf.keras.models.load_model('nepali_character_recognition_model.h5')
                data = result[0][22:]
                img = base64.b64decode(data)

                fh = open("png_image.png", "wb")
                fh.write(img)
                fh.close()
                #print("Success: PNG image of canvas created.")

                im = Image.open("png_image.png")
                rgb_im = im.convert('RGB')
                rgb_im.save('jpg_image.jpg')
                #print("Success: PNG image converted to RGB.")

                im=Image.open('jpg_image.jpg')
                img = array(im.resize((32, 32), Image.ANTIALIAS).convert("L"))
                data = img.reshape([1, 1024])
                data = (data/255)
                data = reshape(data, (32, 32))

                data = data.reshape(1, 32, 32, 1)
                #print(data)
                #print("Success: Data generated form RGB image.")

                predictions = character_recognition_model.predict(data)
                prediction = argmax(predictions[0])

                top_two_predictions = np.argpartition(predictions[0], -2)[-2:]
                first_prediction = str(top_two_predictions[1])
                second_prediction = str(top_two_predictions[1])
                print(top_two_predictions)

                # start image compare ================================================================================================================================================================================

                #retrieving the canvas image-------------------------------------------------------------
                #converting canvas img to 32 by 32 bit (size of training dataset)
                with open('jpg_image.jpg', 'r+b') as f:
                        with Image.open(f) as image:
                                cover = resizeimage.resize_cover(image, [32, 32])
                                cover.save('user_image.png', image.format)

                user_image = cv2.imread("user_image.png")
                user_image = cv2.cvtColor(user_image, cv2.COLOR_BGR2GRAY)
                cv2.imwrite('C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Temp\\canvas_image.png', user_image)
                #---------------------------------------------------------------------------------------

                # prediction.item() contains the character label predicted by the model
                print("==============================================================================================================================")
                print("Model prediction: " + first_prediction)
                similarity = image_compare(first_prediction)
                print('probability: ' + str(predictions[0][int(first_prediction)]))
                print("==============================================================================================================================")
                # end image compare=========================================================================================================================================================

                return JsonResponse({'result': first_prediction, 'probability': str(predictions[0][int(first_prediction)]), 'similarity': similarity})

def train_model(request):
        character_recognition_model = tf.keras.models.load_model('nepali_character_recognition_model.h5')
        canvas_data = uint8(request.POST.get('canvas_data'))

        im=Image.open('colors.jpg')
        img = array(im.resize((32, 32), Image.ANTIALIAS).convert("L"))
        data = img.reshape([1, 1024])
        data = (data/255)
        data = reshape(data, (32, 32))
        data = data.reshape(1, 32, 32, 1)
        number_of_classes = 46
        canvas_data = canvas_data.reshape(1, 1)
        canvas_data = np_utils.to_categorical(canvas_data, number_of_classes)
        print(canvas_data.shape)
        character_recognition_model.fit( data, canvas_data, epochs = 1)
        character_recognition_model.save('nepali_character_recognition_model.h5')
        print("SUCCESS: model fit.")
        return JsonResponse({'result':"Model Trained"})

def image_compare(prediction):
    # retrieving the image of that predicted character from the train dataset------
    p = 'C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Test' + '\\' + prediction
    path = Path(p)
    files = os.listdir(path)
    index = random.randrange(0, len(files))
    avg_similarity = 0

    for i in range(0, len(files)):
        predicted_character_image = cv2.imread("Test\\" + prediction + "\\" + files[i])
        predicted_character_image = cv2.cvtColor(predicted_character_image, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Temp\\original_image.png', predicted_character_image)

    # predicted_character_image = cv2.imread("Test\\" + prediction + "\\" + files[index])
    # predicted_character_image = cv2.cvtColor(predicted_character_image, cv2.COLOR_BGR2GRAY)
    # cv2.imwrite('C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Temp\\original_image.png', predicted_character_image)
    # #------------------------------------------------------------------------

        original = cv2.imread("Temp\\original_image.png")
        image_to_compare = cv2.imread("Temp\\canvas_image.png")

        # 1) Check if 2 images are equals
        if original.shape == image_to_compare.shape:
            # print("The images have same size and channels")
            difference = cv2.subtract(original, image_to_compare)
            b, g, r = cv2.split(difference)

        # 2) Check for similarities between the 2 images
        sift = cv2.xfeatures2d.SIFT_create()
        kp_1, desc_1 = sift.detectAndCompute(original, None)
        kp_2, desc_2 = sift.detectAndCompute(image_to_compare, None)

        index_params = dict(algorithm=0, trees=5)
        search_params = dict()
        flann = cv2.FlannBasedMatcher(index_params, search_params)

        matches = flann.knnMatch(desc_1, desc_2, k=2)

        good_points = []
        for m, n in matches:
            if m.distance < 0.75*n.distance:
                good_points.append(m)

        # Define how similar they are
        number_keypoints = 0
        if len(kp_1) <= len(kp_2):
            number_keypoints = len(kp_1)
        else:
            number_keypoints = len(kp_2)

        print("Similarity: ", len(good_points) / number_keypoints * 100)

        similarity = len(good_points) / number_keypoints * 100
        result = cv2.drawMatches(original, kp_1, image_to_compare, kp_2, good_points, None)
        cv2.imwrite("Temp\\feature_matching_"+str(i)+".jpg", result)
        avg_similarity = avg_similarity + similarity

    avg_similarity = avg_similarity/len(files)
    print("average_similarity: " + str(avg_similarity))
    return avg_similarity


import sys

sys.path.append("../../gym-pybullet-drones")

import numpy as np
import os

from gym_pybullet_drones.utils.Logger import Logger

class CustomLogger(Logger):
    """
    Class for logging of custom data
    """

    def __init__(self,
                 ARGS,
                 logging_freq_hz: int,
                 path = " ",
                 num_drones: int = 1,
                 duration_sec: int = 0,
                 ):
        """
        Constructor
        """

        super().__init__(logging_freq_hz=logging_freq_hz,
                         num_drones=num_drones,
                         duration_sec=duration_sec)

        self.__path = path
        # initialize target for each drone (static)
        self.targets = np.zeros((num_drones, 3, 1))
        # initialize successful flag for each drone, should be set if drone is at target at the end of the simulation
        self.successful = np.zeros(num_drones)
        # initialize required time to reach the target for each drone
        self.transition_times = np.zeros(num_drones)
        # initialize travelled distance
        self.distance_travelled = np.zeros(num_drones)
        # store number of drones
        self.num_drones = num_drones
        # store ARGS of this simulation
        self.ARGS = ARGS

        self.__positions = {}
        self.__control_positions = {}
        self.__times = {}
        self.crashed = {}

    def log_static(self,
                   drone: int,
                   successful: bool,
                   transition_time: any,
                   distance_travelled: float,
                   target, crashed):
        """Logs entries of simulation result

        Parameters:
            drone: int
                ID of the drone associated to the log entry
            successful: bool
                flag indicating if the drone reached it's target
            transition_time: float
                float containing the time needed to reach the target
            distance_travelled: float
                float containing the total distance travelled to reach the target
            target: np.array
                position of target
            crashed: bool
                flag if drone has crashed"""

        if drone < 0 or drone >= self.NUM_DRONES:
            print("[ERROR] in CustomLogger.log(), invalid data")

        # logs successful flag
        self.successful[drone] = successful
        # logs transition_times
        self.transition_times[drone] = transition_time
        # logs travelled distance
        self.distance_travelled[drone] = distance_travelled
        # log targets
        self.targets[drone] = np.transpose([target])

        self.crashed[drone] = crashed

    def log_position(self, ID, time, position, control_position):
        if ID not in self.__positions.keys():
            self.__positions[ID] = []
            self.__control_positions[ID] = []
            self.__times[ID] = []

        self.__positions[ID].append(position)
        self.__control_positions.append(control_position)
        self.__times[ID].append(time)

    def save_log(self):
        with open(os.path.join(self.__path, "Metadata.txt", 'w')) as f:
            for successful in self.successful:
                f.write(str(successful) + " ")
            f.write("\n")

            for transition_time in self.transition_times:
                f.write(str(transition_time) + " ")
            f.write("\n")

            for distance_travelled in self.distance_travelled:
                f.write(str(distance_travelled) + " ")
            f.write("\n")

            for targets in self.targets:
                f.write(str(targets) + " ")
            f.write("\n")

        for ID in self.__positions:
            with open(os.path.join(self.__path, "Position" + str() + ".txt", 'w')) as f:
                for i in range(len(self.__positions[ID])):
                    f.write(str(self.__times[ID][i]) + " " + str(self.__positions[ID][i][0])
                            + " " + str(self.__positions[ID][i][1])
                            + " " + str(self.__positions[ID][i][2]) + "\n")

        for ID in self.__control_positions:
            with open(os.path.join(self.__path, "ControlPosition" + str() + ".txt", 'w')) as f:
                for i in range(len(self.__control_positions[ID])):
                    f.write(str(self.__times[ID][i]) + " " + str(self.__control_positions[ID][i][0])
                            + " " + str(self.__control_positions[ID][i][1])
                            + " " + str(self.__control_positions[ID][i][2]) + "\n")


import numpy as np
import matplotlib.pyplot as plt

# 梯度下降法
def gradient_descent_method():
    # 导入数据
    points = np.genfromtxt('data.csv', delimiter=',')

    # 模型的超参数，可以调整
    # 步长
    alpha = 0.0001
    # 起始点
    initial_w = 0
    initial_b = 0
    # 迭代次数
    num_iter = 10

    w, b, cost_list = grad_desc(points, initial_w, initial_b, alpha, num_iter)

    print('w is:', w)
    print('b is:', b)

    cost = compute_cost(w, b, points)

    print('cost is:', cost)

    # 以list的下标作为x
    plt.plot(cost_list)
    plt.show()

    x = points[:, 0]
    y = points[:, 1]

    # 用plt画出散点图
    plt.scatter(x, y)
    # 针对每一个x，计算出预测的y值
    pred_y = w * x + b

    # c是颜色
    plt.plot(x, pred_y, c='r')
    plt.show()

def compute_cost(w, b, points):
    """
    损失函数(是系数的函数)
    https://i.loli.net/2019/07/11/5d26a3c6594ba82985.jpg
    :param w: 参数
    :param b: 参数
    :param points: 数据
    :return:
    """
    total_cost = 0
    M = len(points)

    # 逐点计算平方损失误差，求平均值
    for i in range(M):
        x = points[i, 0]
        y = points[i, 1]
        total_cost += (y - w * x - b) ** 2

    return total_cost / M

def grad_desc(points, initial_w, initial_b, alpha, num_iter):
    """
    梯度下降算法函数
    :param points:
    :param initial_w:
    :param initial_b:
    :param alpha:
    :param num_iter:
    :return:
    """
    w = initial_w
    b = initial_b
    # 保存所有的损失函数值，用来显示下降的过程
    cost_list = []

    for i in range(num_iter):
        cost_list.append(compute_cost(w, b, points))
        w, b = step_grad_desc(w, b, alpha, points)

    return [w, b, cost_list]

def step_grad_desc(current_w, current_b, alpha, points):
    sum_grad_w = 0
    sum_grad_b = 0
    M = len(points)

    # 每个点代入公式求和
    for i in range(M):
        x = points[i, 0]
        y = points[i, 1]
        sum_grad_w += (current_w * x + current_b - y) * x
        sum_grad_b += current_w * x + current_b - y

    # 用公式求当前梯度
    grad_w = 2 / M * sum_grad_w
    grad_b = 2 / M * sum_grad_b

    # 梯度下降，更新当前的w和b
    updated_w = current_w - alpha * grad_w
    updated_b = current_b - alpha * grad_b

    return updated_w, updated_b

if __name__ == '__main__':
    gradient_descent_method()


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0019_article_imgname'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='article',
            name='imgName',
        ),
    ]


def binary(data, key):
    low = 0
    high = len(data) - 1
    middle = (low + high)

    while low <= high:
        if key == data[middle]:
            return middle
        elif data[middle] < key:
            low = middle + 1
        else:
            high = middle - 1

        middle = (low + high)
    return None

my_data = [1,7,10,35,44,67,80,120]
print(binary(my_data,120))


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# OUTPUT_PATH_FULL = "Training/outputFull"
OUTPUT_PATH_FULL = "Testing/outputFull"
half_window_size = 180

training_set = [101, 106, 108, 109, 112, 115, 118, 119, 201, 203, 205, 207, 208, 209, 215, 220, 223, 230]
testing_set = [105, 111, 113, 121, 200, 202, 210, 212, 213, 214, 219, 221, 222, 228, 231, 232, 233, 234]

differences = np.empty((1, 0))

total_frame = pd.DataFrame()

for PATIENT_NUM in testing_set:
    df = pd.read_csv("{}/{}output_full_baselined_split_{}.csv".format(OUTPUT_PATH_FULL, PATIENT_NUM, half_window_size))

    # Drop fist column that gets generated when saving as csv
    df = df.drop(df.columns[0], axis=1)

    total_frame = total_frame.append(df)

    print(PATIENT_NUM)

print(total_frame.shape)
total_frame.to_csv("{}/combined_output_full_baselined_split_{}.csv".format(OUTPUT_PATH_FULL, half_window_size))


# definisi class
class mahasiswa():
   jml_mhs=0

   def __init__(self,nama,nis):
      self.nama=nama
      self.nis=nis
      self.jml_mhs+=1

# main program

yusril=mahasiswa("Yusril A",185512)
adam=mahasiswa("Adam S",185513)
bimo=mahasiswa("Bimo A",185514)

print(mahasiswa.jml_mhs)
print(yusril.__dict__)
print(adam.__dict__)
print(bimo.__dict__)


from genius_invocation.utils import *
if TYPE_CHECKING:
    from genius_invocation.game.game import GeniusGame
    from genius_invocation.game.player import GeniusPlayer

def get_dict(game: 'GeniusGame'):
    message = {'game':{}, 1:{}, 0:{}}

    message['game']['round']: int = game.round
    message['game']['round_phase']: str = game.game_phase.value
    message['game']['active_player']: int = game.active_player_index
    message['game']['first_player']: int = game.first_player

    for idx in [0, 1]:
        player = game.players[idx]
        message[idx]["dice_zone"]: List[str] = [DiceType(dice).name for dice in player.dice_zone.show()] if player.dice_zone.num()>0 else []
        message[idx]["card_zone"]: int = player.card_zone.num()
        message[idx]["hand_zone"]: List[str] = [card.name_ch for card in player.hand_zone.card]
        message[idx]["summon_zone"]: List[List[str]] = [[summon.name_ch,  str(summon.show())]for summon in player.summon_zone.space]
        message[idx]["support_zone"]: List[List[str]] = [[support.name_ch,  str(support.show())]for support in player.support_zone.space]
        message[idx]["character_zone"]: List[List[str]] = []
        for character in player.character_list:
            m = [Elementals_to_str(character.elemental_application),
             character.name_ch,
             character.show(),
             str(character.power),
            ]
            if character.character_zone.weapon_card != None:
                m.append(character.character_zone.weapon_card.show())
            if character.character_zone.artifact_card != None:
                m.append(character.character_zone.artifact_card.show())
            if character.talent == True:
                m.append("Has Talent")
            for skill in character.skills:
                m.append(skill.name_ch)
            for status in character.character_zone.status_list:
                m.append(f"{status.name_ch}:{status.show()}")
            if character.is_active:
                for status in player.team_combat_status.shield:
                    m.append(f"{status.name_ch}:{status.show()}")
                for status in player.team_combat_status.space:
                    m.append(f"{status.name_ch}:{status.show()}")
            message[idx]["character_zone"].append(m)
    return message


import socket
import protocols
import json
import getopt
import sys

class Client:
    MIN_PLAYERS = 1
    MAX_PLAYERS = 4
    MIN_STAGES = 1
    MAX_STAGES = 10
    NO_NAME = ""
    DEFAULT_IP = '127.0.0.1'
    DEFAULT_PORT = 8080

    def __init__(self, number_of_players, number_of_stages, player_name, server_hostname, server_port):
        self.number_of_players = number_of_players
        self.number_of_stages = number_of_stages
        self.player_name = player_name
        self.my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.my_socket.connect((server_hostname, server_port))
        self.end = False

    def send_join_message(self):
        message = {"header": protocols.JOIN, "name": self.player_name}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_welcome_message(self, message):
        menu = message["menu"]
        options_range = message["options range"]
        print("{}".format(menu))
        print("options range: {}".format(options_range))
        self.send_server_option()

    @staticmethod
    def choose_options():
        correct_input = False
        option = None
        while not correct_input:
            try:
                user_input = int(input("Choose an option: "))
                if user_input == 1:
                    option = 1
                    correct_input = True
                    print("You created a new game")
                elif user_input == 2:
                    option = 2
                    correct_input = True
                elif user_input == 3:
                    option = 3
                    correct_input = True
                    print("You exit from the server")
                else:
                    print("This option is not valid. You must choose 1, 2 or 3")
            except ValueError:
                print("This option is not valid. You must choose 1, 2 or 3")
        return option

    def send_server_option(self):
        message = {"header": protocols.SEND_SERVER_OPTION, "option": self.choose_options(),
                   "number of players": self.number_of_players, "number of stages": self.number_of_stages}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_choose_character(self, message):
        menu = message["menu"]
        options_range = message["options range"]
        print("{}".format(menu))
        print("options range: {}".format(options_range))
        self.send_character()

    @staticmethod
    def choose_characters():
        correct_input = False
        option = None
        while not correct_input:
            try:
                user_input = int(input("Choose one character to play: "))
                if user_input == 1:
                    correct_input = True
                    option = 1
                    print("Your character is Bookworm")
                elif user_input == 2:
                    correct_input = True
                    option = 2
                    print("Your character is Worker")
                elif user_input == 3:
                    correct_input = True
                    option = 3
                    print("Your character is Procrastinator")
                elif user_input == 4:
                    correct_input = True
                    option = 4
                    print("Your character is Whatsapper")
                else:
                    print("This is an invalid option")
            except ValueError:
                print("This is an invalid option")
        return option

    def send_character(self):
        message = {"header": protocols.SEND_CHARACTER, "option": self.choose_characters()}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_send_games(self, message):
        available_games = message["games list"]
        games_id = message["games id"]
        print("\t\t\t--- SERVER GAME LIST ---")
        print("{}".format(available_games))
        print("options range: {}".format(games_id))
        self.send_game_choice()

    def choose_game(self):
        try:
            user_input = int(input("Choose a game: "))
            return user_input
        except ValueError:
            print("This option is not valid. You will exit from the server.")
            self.end = True

    def send_game_choice(self):
        message = {"header": protocols.SEND_GAME_CHOICE, "game id": self.choose_game()}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_send_valid_game(self, message):
        joined = message["joined"]
        if joined:
            print("joined: {}".format(joined))
        if not joined:
            print("The game you tried to join is full.")
            self.end = True

    @staticmethod
    def control_server_message(message):
        msg = message["message"]
        print(msg)

    def control_your_turn_message(self, message):
        msg = message["message"]
        options_range = message["options range"]
        print("{}".format(msg))
        print("options range: {}".format(options_range))
        self.send_character_command()

    @staticmethod
    def choose_command():
        correct_input = False
        user_input = ""
        while not correct_input:
            user_input = input()
            if user_input == 'a':
                correct_input = True
            elif user_input == 's':
                correct_input = True
            else:
                print("The character is not valid. Please, enter 'a' to attack or 's' to use your skill")
        return user_input

    def send_character_command(self):
        message = {"header": protocols.SEND_CHARACTER_COMMAND, "command": self.choose_command()}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_send_end_game_message(self, message):
        win = message["win"]
        if win:
            print("***************************************************************************")
            print("\t\tAll enemies have been defeated. You won!")
            print("***************************************************************************")
        else:
            print("***************************************************************************")
            print("\t\tAll players have been defeated. Try again")
            print("***************************************************************************")
        self.end = True

    def control_send_dc_server(self, message):
        reason = message["reason"]
        print(reason)
        self.end = True

    def send_dc_me(self):
        message = {"header": protocols.SEND_DC_ME}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_message(self, message):
        header = message["header"]
        print("{} message received".format(header))
        if header == protocols.WELCOME:
            self.control_welcome_message(message)
        elif header == protocols.CHOOSE_CHARACTER:
            self.control_choose_character(message)
        elif header == protocols.SEND_GAMES:
            self.control_send_games(message)
        elif header == protocols.SEND_VALID_GAME:
            self.control_send_valid_game(message)
        elif header == protocols.SERVER_MSG:
            self.control_server_message(message)
        elif header == protocols.YOUR_TURN:
            self.control_your_turn_message(message)
        elif header == protocols.SEND_END_GAME:
            self.control_send_end_game_message(message)
        elif header == protocols.SEND_DC_SERVER:
            self.control_send_dc_server(message)
        else:
            print("Invalid message received")

    def start(self):
        name = self.player_name
        message = {"header": protocols.JOIN, "name": name}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())
        while not self.end:
            try:
                buffer = protocols.recv_one_message(self.my_socket)
                message = json.loads(buffer.decode())
                self.control_message(message)
            except TypeError:
                self.end = True
                print("Server was disconnected")
            except KeyboardInterrupt:
                self.end = True
                self.send_dc_me()
        self.my_socket.close()

class ArgsError(Exception):
    def __init__(self, msg):
        super().__init__("Error: {}".format(msg))

def parse_args():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "p:s:n:i:o:", ["players=", "stages=", "name=", "ip=", "port="])
    except getopt.GetoptError:
        raise ArgsError("You enter wrong arguments. Finishing program")

    number_of_players = Client.MIN_PLAYERS
    number_of_stages = Client.MIN_STAGES
    ip_address = Client.DEFAULT_IP
    port_address = Client.DEFAULT_PORT
    player_name = Client.NO_NAME
    try:
        for o, a in opts:
            if o in ("-p", "--players"):
                number_of_players = int(a)
            if o in ("-s", "--stages"):
                number_of_stages = int(a)
            if o in ("-n", "--name"):
                player_name = str(a)
            if o in ("-i", "--ip"):
                ip_address = str(a)
            if o in ("-o", "--port"):
                port_address = int(a)
    except ValueError:
        raise ArgsError("Type of arguments is wrong. Finishing program")
    return number_of_players, number_of_stages, player_name, ip_address, port_address

if __name__ == '__main__':
    try:
        players, stages, nick, ip, port = parse_args()
        if (players < Client.MIN_PLAYERS or players > Client.MAX_PLAYERS) and \
                (Client.MIN_STAGES <= stages <= Client.MAX_STAGES):
            raise ArgsError("The number of players must be between 1 and 4. Finishing program")
        elif (Client.MIN_PLAYERS <= players <= Client.MAX_PLAYERS) and \
                (stages < Client.MIN_STAGES or stages > Client.MAX_STAGES):
            raise ArgsError("The number of stages must be between 1 and 10. Finishing program")
        elif (players < Client.MIN_PLAYERS or players > Client.MAX_PLAYERS) and \
                (stages < Client.MIN_STAGES or stages > Client.MAX_STAGES):
            raise ArgsError("The number of players must be between 1 and 4. "
                            "The number of stages must be between 1 and 10. Finishing program")
        elif nick == Client.NO_NAME:
            raise ArgsError("You must introduce a name for the player. Finishing program")
        client = Client(players, stages, nick, ip, port)
        client.start()
    except ArgsError as err:
        print(err)
    except KeyboardInterrupt:
        print("Client closed by CTRL+C")
    except ConnectionRefusedError:
        print("This server is not connected. Try again")


## 例子例子

# """
# 接口返回信息:
# {code:"201",data:["2021-03-03 19:23"]}
# #显示服务器实时时间
# """

from flask import Flask, jsonify

from config.configs import AUTH_key

import time

# """
# 插件注册
def register_plugin(app):
  @app.route(AUTH_key+'/uploader',methods=['GET','POST'])
  def upload_file_1():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            #filename = secure_filename(file.filename)
            #获得文件名
            filename=file.filename

            #获得全路径
            basedir = os.path.abspath(os.path.dirname(__file__))
            #生成随机时间
            randname=time.strftime("%Y.%m.%d.%H.%M.%S", time.localtime())+str(random.randint(1,233333))
            #来个文件名
            file_dir = os.path.join(app.config['UPLOAD_FOLDER'],randname+"_"+filename)
            #try:
            file.save(file_dir)
            all_path=basedir+"\\"+file_dir #全部目录
            str1="上传文件成功!
\n"+"文件目录:" +all_path+"
正在尝试打印:"+"
"

            if ispic(all_path):
                str1+="[dayi]检测到了你上传了图片文件，正在暴力转为pdf
\n"
                all_path_tmp=all_path
                all_path=con_pic2pdf(all_path)
                if(all_path=="[error]"):
                    str1+="[error!!]转换pdf失败，你这是图片还是啥？
\n"
                    str1+="[error!!]我也不知道咋了这是，给你继续执行了吧
\n"
                    all_path=all_path_tmp

            if all_path.split('.')[-1] in ["doc","docx"]:
                all_path = con_doc2pdf(all_path)

            # if all_path.split('.')[-1] in ["ppt","pptx"]:
            #     all_path = con_ppt2pdf(all_path)

            # if all_path.split('.')[-1] in ["xls","xlsx"]:
            #     all_path = con_xls2pdf(all_path)
            # 暂时还没实现

            if all_path.split('.')[-1] == "txt":
                all_path = con_txt2pdf(all_path)

            if request.form.get("blackAndWhitePrinting"):
                str1 += "正在将文档转化为黑白
"
                if all_path.split('.')[-1] != "pdf":
                    str1 += "你上传的格式暂时不支持黑白打印，已经跳过文档处理
\n"
                else:
                    all_path = con2BW(all_path)
                    if all_path == 'Error':
                        str1 += '转换失败了
'
                        return render_template("echo.html",echo_str=str1)

            if not request.form.get("printAllPages"):
                pass
                # 页码选择

            print_info=print_file(all_path)#打印

            if request.form.get("deleteAfterPrinting"):
                os.remove(all_path)

            str1+=print_info
            return render_template("echo.html",echo_str=str1)
        else:
            str1="不合法文件类型！，当前合法类型："
            str1+=str(ALLOWED_EXTENSIONS)
            return render_template("echo.html",echo_str=str1)
    else:
        return render_template('upload.html')

#加载插件
def load_plugin(app):
  register_plugin(app)


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

import pandas as pd
import sys

file = sys.argv[1]

sensors = pd.read_csv(file)

sensors["combined"] = sensors.deviceuid + '##'

sensors.head()

l = [''.join(sensors['combined'])]
l = (", ".join(str(f) for f in l))        #removes brackets
l = l[:-2]				  #removes final 2 characters

print(l)


import re

from utils.output import ListOutput, ListOutputItem

GREP_PLUGIN_RE = re.compile('\] (.*?).grep\(uri=".*"\) took (.*?)s to run')

def get_grep_plugin_performance(scan_log_filename, scan):
    scan.seek(0)

    grep_plugin_times = {}

    for line in scan:
        match = GREP_PLUGIN_RE.search(line)
        if match:
            plugin_name = match.group(1)
            run_time = float(match.group(2))

            if plugin_name in grep_plugin_times:
                grep_plugin_times[plugin_name] += run_time
            else:
                grep_plugin_times[plugin_name] = run_time

    def sort_by_second(a, b):
        return cmp(b[1], a[1])

    times = grep_plugin_times.items()
    times.sort(sort_by_second)

    times_top_10 = times[:10]
    times_top_10 = sum(total_run_time for plugin_name, total_run_time in times_top_10)

    output = ListOutput('grep_plugin_performance')

    output.append(ListOutputItem('Top10 most time consuming plugins run for (seconds)', times_top_10))

    times = dict(times)
    output.append(ListOutputItem('Plugins run time information (in seconds)', times))

    return output


from typing import List

# 높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라.
inputValue = [0,1,0,2,1,0,1,3,2,1,2,1]
# inputValue = [1,2,1,2,3,1,0,2]

# => 6

def trap(self, height: List[int]) -> int:
    if not height:
        return 0

    volume = 0
    # 인덱스
    left, right = 0, len(height) - 1
    # 최대 길이 = 현재 위치 길이
    left_max, right_max = height[left], height[right]

    while left < right:
        # 현재 위치 길이 vs 최대 길이
        left_max, right_max = max(height[left], left_max), max(height[right], right_max)
        # 더 높은 쪽을 향해 투 포인터 이동
        if left_max <= right_max:
            volume += left_max - height[left]
            left += 1
        else:
            volume += right_max - height[right]
            right -= 1
    print(left_max,right_max)
    return volume

def trap2(self, height: List[int]) -> int:
    stack = []
    volume = 0
    for i in range(len(height)):
        print(inputValue)
        print(i,'>>','stack',stack)
        print(i,'>>','현재위치의 높이:',height[i])

        # 변곡점을 만나는 경우 (현재 위치의 높이가 이전 위치의 높이보다 크면 이전 위치를 꺼내어 탑으로 둔다.)
        while stack and height[i] > height[stack[-1]]:
            print(i,'>>','현재위치의 높이:',height[i],'height[stack[-1]]:', height[stack[-1]])
            # 스택에서 꺼낸다.
            top = stack.pop()
            print(i,'>>','top:',top)
            print(i,'>>','length',len(stack))
            if not len(stack):
                break

            # 이전과의 차이만큼 물 높이 처리
            distance = i - stack[-1] - 1
            print(i,'>>','distance:',distance)
            # 지금 높이? 이전이전 높이? - 최고높이
            print(i,'>>','현재위치의 높이:',height[i],'height[stack[-1]]:', height[stack[-1]],'height[top]:', height[top])
            waters = min(height[i], height[stack[-1]]) - height[top]

            volume += distance * waters

        stack.append(i)
    return volume

print(trap2('',inputValue))


import logging
logger = logging.getLogger(__name__)
import json
import zlib
from zipfile import ZipFile
import re

from production import db
from production import utils

def main():
    logging.basicConfig(
        level=logging.INFO,
        format='%(levelname).1s %(module)10.10s:%(lineno)-4d %(message)s')

    conn = db.get_conn()
    cur = conn.cursor()

    legends = {}
    for part_number, part_name in (1, 'initial'), (2, 'teleports'), (3, 'clones'):
        with ZipFile(utils.project_root() / 'tasks' / f'part-{part_number}-{part_name}.zip') as z:
            with z.open(f'part-{part_number}-legend.txt') as fin:
                for line in fin:
                    name, legend = line.decode().split(' - ', maxsplit=1)
                    legends[name] = legend.rstrip()

            for filename in z.namelist():
                if filename.endswith('-legend.txt'):
                    continue
                m = re.match(r'(prob-\d{3}).desc$', filename)
                assert m, filename
                name = m.group(1)

                with z.open(filename, 'r') as fin:
                    task = fin.read().decode()

                data = zlib.compress(task.encode())
                extra = dict(legend=legends[name])

                cur.execute('''
                    INSERT INTO tasks(
                        name, data, extra, invocation_id, time)
                    VALUES (%s, %s, %s, %s, NOW())
                    ON CONFLICT DO NOTHING
                    RETURNING id
                    ''',
                    [name, data, json.dumps(extra), db.get_this_invocation_id(conn)])
                res = cur.fetchall()
                if res:
                    [[task_id]] = res
                    logger.info(f'Uploaded {name!r} as /task/{task_id}')
                else:
                    logger.info(f'Task {name!r} already exists')

    db.record_this_invocation(conn, status=db.Stopped())
    conn.commit()

if __name__ == '__main__':
    main()


# @title: Memory management on the device
# @author: Shaurya

from numba import vectorize
import numpy as np
from time import perf_counter

# timeit
def timeit(f):
    def decorate(*args,**kwargs):
        start=perf_counter()
        result=f(*args,**kwargs)
        end=perf_counter()
        try:
            print(f'Time taken to execute {f.__name__}: {end-start}s')
        except AttributeError as e:
            print("GPU bound problem ")
            print(e)
            print('Time taken to execute: %.2fs'%(end-start))
        return result
    return decorate

@timeit
@vectorize(['float32(float32,float32)'],target='cuda')
def add_ufunc(x,y):
    return x+y

n=1000000
x=np.arange(n).astype(np.float32)
y=2*x
add_ufunc(x,y)

# Numba can create its own GPU array object but not as fully fledged as a Cupy array
from numba import cuda
x_device=cuda.to_device(x)
y_device=cuda.to_device(y)
print(x_device)
print(y_device)
print(x_device.shape)

add_ufunc(x_device,y_device)

# we are still allocating device array for the output and copying
# it back to the CPU
#? define the output buffer
out_device=cuda.device_array(shape=(n,),dtype=np.float32)
out_device.shape
out_device.alloc_size
add_ufunc(x_device,y_device,out=out_device)

# if we want to get it back to the CPU, we can use the copy_to_host() method
out_host=out_device.copy_to_host()
out_host.shape

#! CuPy interoperability
import cupy as cp
x_cp=cp.asarray(x)
y_cp=cp.asarray(y)

out_cp=cp.empty_like(y_cp)
out_cp.shape
y_cp.shape
x_cp.shape

x_cp.__cuda_array_interface__

add_ufunc(x_cp,y_cp,out=out_cp)


#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Cristina De Saint Germain
@email: crsaintc8@gmail.com

Created on 6/04/2014
"""

import rospy
import smach
import math

from navigation_states.nav_to_poi import nav_to_poi
from navigation_states.nav_to_poi_say import nav_to_poi_say

#from navigation_states.enter_room import EnterRoomSM
from speech_states.ask_question import AskQuestionSM
from speech_states.say import text_to_say
from restaurant_guide_phase import restaurantGuide
from restaurant_navigation import RestaurantNavigation
from restaurant_order_phase import RestaurantOrder
from manipulation_states.move_head_form import move_head_form

# Some color codes for prints, from http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
ENDC = '\033[0m'
FAIL = '\033[91m'
OKGREEN = '\033[92m'

class DummyStateMachine(smach.State):
    def __init__(self):
        smach.State.__init__(self, outcomes=['succeeded','aborted', 'preempted'],
            input_keys=[],
            output_keys=[])

    def execute(self, userdata):
        rospy.loginfo("Dummy state just to change to other state")  # Don't use prints, use rospy.logXXXX

        rospy.sleep(3)
        return 'succeeded'

class RestaurantSM(smach.StateMachine):
    """
    Executes a SM that does the Restaurant.

    The robot is guided through the environment, showing 5 locations.
    2 locations are for objects and 3 for delivery.

    In the ordering location, the robot listen for a order. Then it goes to the
    different objects locations and search for the object. If the object is found, it takes to
    the deliver location.

    The order contains 3 object and 2 location places.

    Required parameters:
    No parameters.

    Optional parameters:
    No optional parameters

    No input keys.
    No output keys.
    No io_keys.
    """
    def __init__(self):
        smach.StateMachine.__init__(self, ['succeeded', 'preempted', 'aborted'])

        with self:
            self.userdata.tts_wait_before_speaking=0
            self.userdata.tts_text=None
            self.userdata.tts_lang=None
            self.userdata.nav_to_poi_name=None
            self.userdata.standard_error='OK'
            self.userdata.grammar_name="restaurant.gram"
            # We must initialize the userdata keys if they are going to be accessed or they won't exist and crash!
            self.userdata.loop_iterations = 0

            # Must we say something to start? "I'm ready" or something
            # Must we wait for the spoken order?

           # Guide phase
            smach.StateMachine.add(
                 'guide_phase',
                 restaurantGuide(),
                 transitions={'succeeded': 'start_restaurant', 'aborted': 'aborted',
                 'preempted': 'preempted'})

            # Go to ordering location, i thinc it will not be necessary
            smach.StateMachine.add(
                'start_restaurant',
                nav_to_poi_say(tts="i am going to the ordering poi",poi_name='ordering'),
                transitions={'succeeded': 'ask_order', 'aborted': 'ask_order',
                'preempted': 'preempted'})

            # Ask for order
            smach.StateMachine.add(
                'ask_order',
                RestaurantOrder(),
                transitions={'succeeded': 'navigation_phase', 'aborted': 'aborted',
                'preempted': 'preempted'})

            # Navigation Phase
            smach.StateMachine.add(
                'navigation_phase',
                RestaurantNavigation(),
                transitions={'succeeded': 'leaving_ordering', 'aborted': 'aborted',
                'preempted': 'preempted'})

            # Leaving the arena
            smach.StateMachine.add(
                'leaving_ordering',
                nav_to_poi('ordering'),
                transitions={'succeeded': 'succeeded', 'aborted': 'aborted',
                'preempted': 'preempted'})


# Created by zhai at 2018/1/12
# Email: zsp1197@163.com
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from Tools import *
from BeeTools import *
import os
path = '/home/uftp/hubei/ori'
users_list = os.listdir(path)

has_meter=False
has_normal=False

for user in users_list:
    user_path=os.path.join(path,user)
    appliances_list = os.listdir(user_path)
    appliances_list=[appliance for appliance in appliances_list if appliance.split(sep='.')[-1]=='xls']
    print(appliances_list)
    for appliance_file_name in appliances_list:
        if('meter' in appliance_file_name):
            if(not has_meter):
                meter=read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))
                has_meter=True
            else:
                meter=aggregate_with_resample([meter,read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))])
        else:
            if(not has_normal):
                normal=read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))
                has_normal=True
            else:
                normal=aggregate_with_resample([normal,read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))])
    meter.plot(label='meter')
    normal.plot(label='sum of appliances')
    print(user)
    normal_consumption=ps_consumption(normal)
    meter_consumption=ps_consumption(meter)
    print(normal_consumption)
    print(meter_consumption)
    print(normal_consumption/meter_consumption)
    plt.title(user)
    plt.legend()
    # plt.show()
    plt.show(block=False)
print()


from setuptools import setup, find_packages

install_requires = [
    "redis==5.0.1",
    "typing_extensions==4.8.0",
    "pydantic==2.4.2",
    "pydantic_core==2.10.1",
    "elasticsearch==8.10.0",
    "flask==3.0.0",
    "flask-socketio==5.3.6",
    "pytest==7.4.2",
    "kazoo==2.9.0"
]

setup(
    name='noauth',
    version='0.1.0',
    packages=find_packages(exclude=['tests', 'tests.*']),
    install_requires=install_requires,
    tests_require=[
        'pytest',
    ],
)


#! /usr/bin/env python

"""
@author: David Diaz Vico
@license: MIT
"""

import argparse
from sacred.observers import FileStorageObserver

from skdatasets import fetch
from skdatasets.utils.estimator import json2estimator
from skdatasets.utils.experiment import experiment

def main(
    dataset=fetch, estimator=json2estimator, observers=[FileStorageObserver(".results")]
):
    parser = argparse.ArgumentParser(description="Run an experiment.")
    parser.add_argument("-r", "--repository", type=str, help="repository")
    parser.add_argument("-c", "--collection", type=str, default=None, help="collection")
    parser.add_argument("-d", "--dataset", type=str, help="dataset")
    parser.add_argument("-e", "--estimator", type=str, help="estimator")
    args = parser.parse_args()
    e = experiment(dataset, estimator)
    e.observers.extend(observers)
    e.run(
        config_updates={
            "dataset": {
                "repository": args.repository,
                "collection": args.collection,
                "dataset": args.dataset,
            },
            "estimator": {"estimator": args.estimator},
        }
    )

if __name__ == "__main__":
    main()


from sys import stdin

def main():
    input = stdin.readline
    s = input()[:-1]
    n = s.count('R')
    if n == 2:
        if s[1] == 'S':
            print(1)
        else:
            print(2)
    else:
        print(n)

if __name__=='__main__':
    main()


import csv
import sys
from bs4 import BeautifulSoup
import urllib,urllib2
import geopy,geopy.distance
from optparse import OptionParser

#get_html return the html code of a given page with adresse: url
def get_html(url):
    request = urllib2.Request(url)
    request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
    request.add_header('Content-Type','')
    response = urllib2.urlopen(request)
    return(response)

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                          help="write report to FILE", metavar="FILE")

(options, args) = parser.parse_args()
filename=options.filename
rootname=filename.split('.')[0]

f = open(filename, 'r')
csvfile=csv.reader(f)
header=csvfile.next()
output="nautical distance,country,port,long,lat\n"

#while True:
#    try:
#        geolocator = geopy.Nominatim()
#        location = geolocator.geocode("Trieste")
#        break
#    except:
#        pass
#
#print("Trieste:"+str(location.latitude)+","+str( location.longitude)+"\n")
#trieste=(location.latitude,location.longitude)
#output=output+"trieste"+","+str(location.latitude)+","+str( location.longitude)+","+"0"+"\n"

for row in csvfile:
    place=""
    if(row[2]==""):
        place=row[1]
    else:
        place=row[2]

    print(place)
    while True:
        try:
            geolocator = geopy.Nominatim()
            location = geolocator.geocode(place)
            print("here")
            break
        except :
            e = sys.exc_info()[0]
            if e == geopy.exc.GeocoderQueryError:
                break
            print("fail"+str(e))
            pass
    if(location is not None ):
        cur=(location.latitude,location.longitude)
        #dist=geopy.distance.vincenty(trieste,cur)
        #print("distance:"+str(dist))
        output=output+row[0]+",\""+row[1]+"\",\""+row[2]+"\","+str(location.latitude)+","+str( location.longitude)+"\n"

of = open(""+rootname+"-loc.csv", 'w')
of.write(output)
of.close


from turtle import Turtle

class DotedLine:
    def __init__(self):
        t = Turtle()
        t.hideturtle()
        t.color("white")
        t.speed(0)
        t.penup()
        t.goto(0, -400)
        t.pensize(10)
        t.left(90)

        while t.position()[1] < 420:
            t.pendown()
            t.fd(20)
            t.penup()
            t.fd(30)


from controller.reroute import reset
from spoofer.spoof import spoofed
from utils.debug import dbg, WARNING, SUCCESS, INFO

def spoofer_reset():
    if len(spoofed) > 0:
        dbg("Resetting routing..", WARNING)

        for item in spoofed:
            src = spoofed[item]['info'][0]
            dest = spoofed[item]['info'][1]
            reset(src, dest)
            dbg("Rerouted 'Target: %s > Destination: %s'" % (src, dest), INFO)
            reset(dest, src)
            dbg("Rerouted 'Destination: %s > Target: %s'" % (dest, src), INFO)
        dbg("All done.", SUCCESS)


import mock
import pytest

from paasta_tools import firewall_logging

@mock.patch.object(firewall_logging, "lookup_service_instance_by_ip")
def test_syslog_to_paasta_log(mock_lookup_service_instance_by_ip, mock_log):
    syslog_data = fake_syslog_data("my-hostname", SRC="1.2.3.4")
    mock_lookup_service_instance_by_ip.return_value = ("myservice", "myinstance")

    firewall_logging.syslog_to_paasta_log(syslog_data, "my-cluster")

    assert mock_log.mock_calls == [
        mock.call(
            service="myservice",
            component="security",
            level="debug",
            cluster="my-cluster",
            instance="myinstance",
            line="my-hostname: my-prefix IN=docker0 SRC=1.2.3.4",
        )
    ]

@mock.patch.object(firewall_logging, "lookup_service_instance_by_ip")
def test_syslog_to_paasta_log_no_container(
    mock_lookup_service_instance_by_ip, mock_log
):
    syslog_data = fake_syslog_data("my-hostname", SRC="1.2.3.4")
    mock_lookup_service_instance_by_ip.return_value = (None, None)
    firewall_logging.syslog_to_paasta_log(syslog_data, "my-cluster")
    assert mock_log.mock_calls == []

def test_parse_syslog_undecodable():
    assert (
        firewall_logging.parse_syslog(b"<4>Jun  6 07:52:38 myhost \xba~\xa6r") is None
    )

@pytest.mark.parametrize(
    "syslog_data",
    [
        "<4>Jun  6 07:52:38 myhost someothermessage: hello world",
        "<4>Jun  6 07:52:38 myhost kernel: hello world",
        "<4>Jun  6 07:52:38 myhost kernel [0.0]: hello world",
    ],
)
@mock.patch.object(firewall_logging, "lookup_service_instance_by_ip")
def test_syslog_to_paasta_log_bad_message(
    mock_lookup_service_instance_by_ip, syslog_data, mock_log
):
    firewall_logging.syslog_to_paasta_log(syslog_data.encode(), "my-cluster")
    assert mock_lookup_service_instance_by_ip.mock_calls == []
    assert mock_log.mock_calls == []

@mock.patch.object(
    firewall_logging,
    "services_running_here",
    return_value=[
        ("service1", "instance1", "00:00:00:00:00", "1.1.1.1"),
        ("service1", "instance2", "00:00:00:00:00", "2.2.2.2"),
    ],
)
@mock.patch.object(firewall_logging, "log")
def test_lookup_service_instance_by_ip(my_mock_log, mock_services_running_here):
    assert firewall_logging.lookup_service_instance_by_ip("1.1.1.1") == (
        "service1",
        "instance1",
    )
    assert firewall_logging.lookup_service_instance_by_ip("2.2.2.2") == (
        "service1",
        "instance2",
    )
    assert firewall_logging.lookup_service_instance_by_ip("3.3.3.3") == (None, None)
    assert my_mock_log.info.mock_calls == [
        mock.call("Unable to find container for ip 3.3.3.3")
    ]

def test_parse_args():
    assert firewall_logging.parse_args([]).listen_host == "127.0.0.1"
    assert firewall_logging.parse_args([]).listen_port == 1516
    assert firewall_logging.parse_args([]).verbose is False
    assert firewall_logging.parse_args(["-v"]).verbose is True
    assert firewall_logging.parse_args(["-p", "1234"]).listen_port == 1234
    assert firewall_logging.parse_args(["-l", "0.0.0.0"]).listen_host == "0.0.0.0"

@mock.patch.object(firewall_logging, "logging")
def test_setup_logging(logging_mock):
    firewall_logging.setup_logging(True)
    assert logging_mock.basicConfig.mock_calls == [mock.call(level=logging_mock.DEBUG)]

@mock.patch.object(firewall_logging, "MultiUDPServer")
def test_run_server(udpserver_mock):
    firewall_logging.run_server("myhost", 1234)
    assert udpserver_mock.mock_calls == [
        mock.call(("myhost", 1234), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
    ]

@mock.patch.object(firewall_logging, "logging")
@mock.patch.object(firewall_logging, "MultiUDPServer")
@mock.patch.object(firewall_logging, "signal")
def test_main_single_worker(signal_mock, udpserver_mock, logging_mock):
    firewall_logging.main(["-w", "1"])
    assert logging_mock.basicConfig.mock_calls == [
        mock.call(level=logging_mock.WARNING)
    ]
    assert udpserver_mock.mock_calls == [
        mock.call(("127.0.0.1", 1516), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
    ]

@mock.patch.object(firewall_logging, "logging")
@mock.patch.object(firewall_logging, "MultiUDPServer")
@mock.patch.object(firewall_logging.os, "fork", return_value=0)
@mock.patch.object(firewall_logging, "signal")
def test_main_two_workers(signal_mock, fork_mock, udpserver_mock, logging_mock):
    firewall_logging.main(["-w", "2"])
    assert logging_mock.basicConfig.mock_calls == [
        mock.call(level=logging_mock.WARNING)
    ]
    assert udpserver_mock.mock_calls == [
        mock.call(("127.0.0.1", 1516), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
        mock.call(("127.0.0.1", 1516), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
    ]

def fake_syslog_data(hostname, **kwargs):
    prefix = (
        f"<4>Jun  6 07:52:38 {hostname} kernel: [2736265.340132] my-prefix IN=docker0 "
    )
    fields_str = " ".join(map("=".join, kwargs.items()))
    return (prefix + fields_str + " \n").encode()

@pytest.yield_fixture
def mock_log():
    with mock.patch.object(firewall_logging, "_log", autospec=True) as mock_log:
        yield mock_log


import streamlit as st
import time
import numpy as np
import pandas as pd

def yes_or_no_q(question):
    '''질문에 대한 답을 리턴해줍니다.'''
    answer = st.radio(question, ['네', '아니요'])
    if answer == '네':
        return 1
    elif answer == '아니요':
        return 0

def question(placeholder):

    # 초기 설정
    base_df = pd.DataFrame(columns = ['BMI', 'Smoking', 'AlcoholDrinking', 'Stroke',
                                    'PhysicalHealth', 'MentalHealth', 'DiffWalking', 'Sex',
                                    'PhysicalActivity', 'SleepTime', 'Asthma', 'KidneyDisease',
                                    'SkinCancer', 'AgeCategory_1824', 'AgeCategory_2529',
                                    'AgeCategory_3034', 'AgeCategory_3539', 'AgeCategory_4044',
                                    'AgeCategory_4549', 'AgeCategory_5054', 'AgeCategory_5559',
                                    'AgeCategory_6064', 'AgeCategory_6569', 'AgeCategory_7074',
                                    'AgeCategory_7579', 'AgeCategory_80orolder',
                                    'Race_AmericanIndianAlaskanNative', 'Race_Asian', 'Race_Black',
                                    'Race_Hispanic', 'Race_Other', 'Race_White', 'GenHealth_Excellent',
                                    'GenHealth_Fair', 'GenHealth_Good', 'GenHealth_Poor',
                                    'GenHealth_Verygood', 'Diabetic_No', 'Diabetic_Noborderlinediabetes',
                                    'Diabetic_Yes', 'Diabetic_Yesduringpregnancy'])

    base_df.loc[0, ['AgeCategory_1824', 'AgeCategory_2529',
                    'AgeCategory_3034', 'AgeCategory_3539', 'AgeCategory_4044',
                    'AgeCategory_4549', 'AgeCategory_5054', 'AgeCategory_5559',
                    'AgeCategory_6064', 'AgeCategory_6569', 'AgeCategory_7074',
                    'AgeCategory_7579', 'AgeCategory_80orolder',
                    'Race_AmericanIndianAlaskanNative', 'Race_Asian', 'Race_Black',
                    'Race_Hispanic', 'Race_Other', 'Race_White', 'GenHealth_Excellent',
                    'GenHealth_Fair', 'GenHealth_Good', 'GenHealth_Poor',
                    'GenHealth_Verygood', 'Diabetic_No', 'Diabetic_Noborderlinediabetes',
                    'Diabetic_Yes', 'Diabetic_Yesduringpregnancy']] = 0

    with placeholder.form("my_form"):
        # 몸무게
        weight = st.number_input('몸무게를 입력해주세요(단위 : kg)')
        # 키
        height = st.number_input(label = '키를 입력해주세요(단위 : cm)')
        # 나이(범주화 필요)
        AgeCategory = st.number_input('당신의 나이는 몇 살입니까(만 나이)?')
        if AgeCategory <= 24:
            base_df.loc[0, 'AgeCategory_1824'] = 1
        elif AgeCategory <= 29:
            base_df.loc[0, 'AgeCategory_2529'] = 1
        elif AgeCategory <= 34:
            base_df.loc[0, 'AgeCategory_3034'] = 1
        elif AgeCategory <= 39:
            base_df.loc[0, 'AgeCategory_3539'] = 1
        elif AgeCategory <= 44:
            base_df.loc[0, 'AgeCategory_4044'] = 1
        elif AgeCategory <= 49:
            base_df.loc[0, 'AgeCategory_4549'] = 1
        elif AgeCategory <= 54:
            base_df.loc[0, 'AgeCategory_5054'] = 1
        elif AgeCategory <= 59:
            base_df.loc[0, 'AgeCategory_5559'] = 1
        elif AgeCategory <= 64:
            base_df.loc[0, 'AgeCategory_6064'] = 1
        elif AgeCategory <= 69:
            base_df.loc[0, 'AgeCategory_6569'] = 1
        elif AgeCategory <= 74:
            base_df.loc[0, 'AgeCategory_7074'] = 1
        elif AgeCategory <= 79:
            base_df.loc[0, 'AgeCategory_7579'] = 1
        else:
            base_df.loc[0, 'AgeCategory_80orolder'] = 1

        # 신체 부상
        PhysicalHealth = int(st.number_input('지난 30일 동안 질병과 부상을 포함해 아픈 일수는 며칠입니까?'))
        base_df.loc[0, 'PhysicalHealth'] = PhysicalHealth
        # 정신건강
        MentalHealth = int(st.number_input('지난 30일 동안 정신 건강이 좋지 않았던 횟수(일수)는 며칠입니까?'))
        base_df.loc[0, 'MentalHealth'] = MentalHealth
        # 수면 시간
        SleepTime = st.number_input('최근 한달 간 평균 수면시간을 입력해주세요(단위 : 시간)')
        base_df.loc[0, 'SleepTime'] = SleepTime
        # 인종
        Race = st.selectbox('당신의 인종은 무엇입니까?', ['아시안', '백인', '히스패닉', '흑인', '기타', '알래스카/미국 원주민'])
        if Race == '아시안':
            base_df.loc[0, 'Race_Asian'] = 1
        elif Race == '백인':
            base_df.loc[0, 'Race_White'] = 1
        elif Race == '히스패닉':
            base_df.loc[0, 'Race_Hispanic'] = 1
        elif Race == '흑인':
            base_df.loc[0, 'Race_Black'] = 1
        elif Race == '기타':
            base_df.loc[0, 'Race_Other'] = 1
        elif Race == '알래스카/미국 원주민':
            base_df.loc[0, 'Race_AmericanIndianAlaskanNative'] = 1

        # 당뇨
        Diabetic = st.selectbox('당뇨병인 적이 한번이라도 있습니까?', ['네', '아니요', '애매하다', '임신 중에만 당뇨병이였다(여성만 해당)'])
        if Diabetic == '네':
            base_df.loc[0, 'Diabetic_Yes'] = 1
        elif Diabetic == '아니요':
            base_df.loc[0, 'Diabetic_No'] = 1
        elif Diabetic == '애매하다':
            base_df.loc[0, 'Diabetic_Noborderlinediabetes'] = 1
        elif Diabetic == '임신 중에만 당뇨병이였다(여성만 해당)':
            base_df.loc[0, 'Diabetic_Yesduring pregnancy'] = 1

        # 건강
        GenHealth = st.selectbox('본인이 느끼기에 당신의 건강 정도는?', ['훌륭하다', '아주 좋다' , '좋다' , '그저 그렇다' , '나쁘다'])
        if GenHealth == '훌륭하다':
            base_df.loc[0, 'GenHealth_Excellent'] = 1
        elif GenHealth == '아주 좋다':
            base_df.loc[0, 'GenHealth_Verygood'] = 1
        elif GenHealth == '좋다':
            base_df.loc[0, 'GenHealth_Good'] = 1
        elif GenHealth == '그저 그렇다':
            base_df.loc[0, 'GenHealth_Fair'] = 1
        elif GenHealth == '나쁘다':
            base_df.loc[0, 'GenHealth_Poor'] = 1

        # 흡연 여부
        Smoking = yes_or_no_q('당신은 평생 동안 적어도 100개 이상의 담배를 피우셨습니까?')
        base_df.loc[0, 'Smoking'] = Smoking
        # 술
        AlcoholDrinking = yes_or_no_q('당신은 과음자입니까?(남성은 주에 14잔 이상 , 여성은 주에 7잔 이상')
        base_df.loc[0, 'AlcoholDrinking'] = AlcoholDrinking
        # 뇌졸중
        Stroke = yes_or_no_q('당신은 뇌졸중 경험이 있습니까?')
        base_df.loc[0, 'Stroke'] = Stroke
        # 운동능력
        DiffWalking = yes_or_no_q('계단을 오를 때 힘들다고 느끼십니까?')
        base_df.loc[0, 'DiffWalking'] = DiffWalking
        # 육체활동
        PhysicalActivity = yes_or_no_q('운동을 하십니까?')
        base_df.loc[0, 'PhysicalActivity'] = PhysicalActivity
        # 천식
        Asthma = yes_or_no_q('천식에 걸린 적이 있습니까?')
        base_df.loc[0, 'Asthma'] = Asthma
        # 신장 질환
        KidneyDisease = yes_or_no_q('신장 질환이 있습니까?')
        base_df.loc[0, 'KidneyDisease'] = KidneyDisease
        # 피부암
        SkinCancer = yes_or_no_q('피부암에 걸린 적이 있습니까?')
        base_df.loc[0, 'SkinCancer'] = SkinCancer
        # 성별
        Sex = st.radio('당신의 성별은 무엇입니까?', ['남자', '여자'])
        if Sex == '남자':
            Sex = 1
        else :
            Sex = 0
        base_df.loc[0, 'Sex'] = Sex
        # BMI
        if height > 0:
            # BMI 계산 및
            BMI = round(weight / ((height/100) ** 2) , 2)
        else:
            BMI = 0
        base_df.loc[0, 'BMI'] = BMI

        time.sleep(4)
        submitted = st.form_submit_button("AI 예측")

        # base_df 조정(다른 컬럼 조정)
        base_df = base_df.append(base_df.loc[[0,0,0,0,0]]).reset_index(drop = True)

        # 당신이 담배를 피우지 않았다면
        if base_df.at[0, 'Smoking'] == 1:
            base_df.at[1, 'Smoking'] = 0

        # 당신이 과음을 하지 않는다면
        if base_df.at[0, 'AlcoholDrinking'] == 1:
            base_df.at[2, 'AlcoholDrinking'] = 0

        # 잠이 부족한 당신이 수면을 취한다면
        if base_df.at[0, 'SleepTime'] <= 6:
            base_df.at[3, 'SleepTime'] = 9

        # 당신이 정상 범주의 BMI 지수를 가질 경우
        if (base_df.at[0, 'BMI'] < 18.5) or (base_df.at[0, 'BMI'] > 25):
            base_df.at[4, 'BMI'] = 22

        # 당신이 운동을 한다면
        if base_df.at[0, 'PhysicalActivity'] == 0:
            base_df.at[5, 'PhysicalActivity'] = 1

        return base_df, submitted


import os

extra_cpppath = []
if 'CPATH' in os.environ:
    extra_cpppath = filter(bool, os.environ['CPATH'].split(os.pathsep))

env = Environment(
    CXX="g++",
    CCFLAGS=[
        '-std=c++11',
        '-Wall',
        #'-O3',
        #'-ggdb',
        '-fPIC',
        '-Wno-deprecated',
        '-Wno-reorder',
        #'-Wsuggest-override',
        '-mfpmath=sse,387',
        '-funroll-loops',
        '-fomit-frame-pointer',
        '-lpthread',
        '-msse3',
        '-D_LARGEFILE_SOURCE',
        '-D_FILE_OFFSET_BITS=64'
        #, '-fprofile-arcs',
        #'-ftest-coverage'
    ],
    #LDFLAGS=[
    #    '-lgcov',
    #    '-fprofile-arcs'
    #],
    CPPPATH=['#.', '#../dep/gtest/include','#../dep']+extra_cpppath,
    LIBPATH=['#../dep/gtest/build', '/usr/local/lib'],
    LIBS=[
      'gtest',
      'pthread'
      #, 'gcov'
    ]
)

AddOption('--mode',
          dest='mode',
          type='string',
          nargs=1,
          default='debug',
          action='store',
          metavar='DIR',
          help='modifies compile flags, possible values: debug (default), optimized, coverage')

mode_raw = GetOption('mode')
mode = mode_raw if mode_raw is not None else "debug"

#documentation: compile in coverage mode using
#scons [-j30] --mode=coverage
#available modes: coverage, debug (default), optimized

if mode=="debug":
  env.Append(CCFLAGS = '-ggdb')
if mode=="optimized":
  env.Append(CCFLAGS = '-O3')
if mode=="coverage":
  env.Append(CCFLAGS = '-fprofile-arcs')
  env.Append(CCFLAGS = '-ftest-coverage')
  env.Append(LIBS = 'gcov')
  env.Append(LDFLAGS='-lgcov')
  env.Append(LDFLAGS='-fprofile-arcs')

cpp = Glob("main/*/*.cpp")
cpp.extend(Glob("main/*/*/*.cpp"))
cpp.extend(Glob("main/*/*/*/*.cpp"))
objs = env.Object(cpp)

cpp_test = Glob("test/*/*.cpp")
cpp_test.extend(Glob("test/*/*/*.cpp"))
cpp_test.extend(Glob("test/*/*/*/*.cpp"))

AddOption('--test-filter',
          dest='test-filter',
          type='string',
          nargs=1,
          action='store',
          metavar='DIR',
          help='filter to these tests, comma separated (no space)')

test_filter_raw = GetOption('test-filter')
test_filter = set(test_filter_raw.split(',')) if test_filter_raw is not None else None

for src in cpp_test:
    src_str = str(src)
    relative_path = os.path.relpath(src_str, os.path.commonprefix([src_str, Dir('#').abspath]))
    env.Object(relative_path)
    program_name = os.path.basename(os.path.splitext(relative_path)[0])
    if test_filter is None or program_name in test_filter:
        env.Program("test/"+program_name, [relative_path]+['#../bin/'+str(i) for i in objs])


import numpy as np
from defines import *

param_grid = {}

# CART
param_grid['cart'] = {
    "max_features": np.linspace(start=0.1, stop=1.0, num=99),
    "max_depth": range(1, 51),
    "min_samples_split": range(2, 21),
    "min_samples_leaf": range(1, 21),
    "random_state": [SEED_CART]
}

# Random Forests
param_grid['rf'] = {
    "max_features": np.linspace(start=0.1, stop=1.0, num=99),
    "max_leaf_nodes": range(2, 51),
    "min_samples_split": range(2, 21),
    "min_samples_leaf": range(1, 21),
    "n_estimators": range(50, 151),
    "random_state":[SEED_RF],
}

# Naive Bayes
param_grid['nb'] = {
    "priors":  [None]
}

# Support Vector Machine
param_grid['svm'] = {
    "kernel": ["rbf", "sigmoid"],
    "C": np.logspace(-9, 9, num=10, base=10),
}

# Artificial Neural Nets (Multi Layer Perceptron Classifier)
param_grid['mlp'] = {
    "hidden_layer_sizes": [(100,), (100,100,), (100,100,100,100,), (100,100,100,100,100,)],
    "activation": ['identity', 'logistic', 'tanh', 'relu'],
    "max_iter": range(100,400,50)
}

#K-Nearest Neighbors
param_grid['knn'] = {
    "n_neighbors": range(1,10),
    "weights": ["uniform", "distance"]
}


from kivy.uix.screenmanager import Screen
from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.toolbar import MDToolbar
from kivymd.icon_definitions import md_icons
from kivymd.uix.button import MDFillRoundFlatButton
from kivymd.uix.label import MDLabel
from kivymd.uix.textfield.textfield import MDTextField

class IMCApp(MDApp):
    def calcul_IMC(self, args) -> None:
        self.weightTextField.text = self.weightTextField.text.replace(',','.')
        self.heightTextField.text = self.heightTextField.text.replace(',','.')

        try:
            weight = float(self.weightTextField.text)
            height = float(self.heightTextField.text)
            imc = round(weight / (height**2), 2)
            comment = ""
            if imc < 18.5:
                comment = "Insuffisance pondérale"
            elif imc < 25:
                comment = "Corpulence normale"
            elif imc < 30:
                comment = "Surpoids"
            elif imc < 35:
                comment = "Obésité modérée"
            elif imc < 40:
                comment = "Obésité sévère"
            else:
                comment = "Obésité morbide"

            self.labelIMC.text = f"Votre IMC est de : {str(imc)}\n {comment}"
        except:
            pass

    def resetFields(self) -> None:
        self.weightTextField.text = ""
        self.heightTextField.text = ""
        self.labelIMC.text = "Remplissez les champs et cliquez sur le bouton ;)"

    def build(self):
        screen = Screen()

        # Top Toolbar
        self.toolbar = MDToolbar(title="Calcultateur d'IMC")
        self.toolbar.pos_hint = {"top": 1}
        self.toolbar.right_action_items= [
            ["rotate-3d-variant", lambda _: self.resetFields()]
        ]
        screen.add_widget(self.toolbar)

        # Bouton calculer IMC
        self.calculateIMCButton = MDFillRoundFlatButton(
            text="Calculer mon IMC...",
            pos_hint={"center_x": 0.5, "center_y": 0.2},
            on_press=self.calcul_IMC
        )
        screen.add_widget(self.calculateIMCButton)

        # champ de texte poids
        self.weightTextField = MDTextField(
            hint_text="Entrer votre poids (kg)",
            halign="center",
            pos_hint={"center_x": 0.5, "center_y": 0.4},
            icon_right="scale",
            required = True,
            size_hint = (.8, 1)
        )
        screen.add_widget(self.weightTextField)

        # champ de texte taille
        self.heightTextField = MDTextField(
            hint_text="Entrer votre taille (m)",
            halign="center",
            pos_hint={"center_x": 0.5, "center_y": 0.6},
            icon_right="arrow-expand-vertical",
            required = True,
            size_hint = (.8, 1)
        )
        screen.add_widget(self.heightTextField)

        # label résultat IMC
        self.labelIMC = MDLabel(
            text="Remplissez les champs et cliquez sur le bouton ;)",
            pos_hint={"center_x": 0.5, "center_y": 0.8},
            halign="center",
            size_hint =(.8, 1)
        )
        screen.add_widget(self.labelIMC)

        return screen

IMCApp().run()


#The complete source code for mplwidget.py is:
# Python Qt4 bindings for GUI objects
from PyQt5 import QtGui, QtCore, QtWidgets
# import the Qt4Agg FigureCanvas object, that binds Figure to
# Qt4Agg backend. It also inherits from QWidget
import matplotlib as MPL
MPL.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
# Matplotlib Figure object
from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):
    """Class to represent the FigureCanvas widget"""
    def __init__(self):
        # setup Matplotlib Figure and Axis after defining standard font properties
        font = {'family' : 'serif',
                'weight' : 'bold',
                'size'   : 8}
        axes = {'labelsize' : 12,
                'labelcolor' : 'green'}

        #MPL.rc('font', **font)  # pass in the font dict as kwargs
        #MPL.rc('axes', **axes)
        MPL.rcParams['figure.facecolor'] = 'white'
        MPL.rcParams['figure.autolayout'] = 'TRUE'
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        # initialization of the canvas
        FigureCanvas.__init__(self, self.fig)
        # we define the widget as expandable
        FigureCanvas.setSizePolicy(self,
        QtWidgets.QSizePolicy.Preferred,
        QtWidgets.QSizePolicy.Preferred)
        # notify the system of updated policy
        FigureCanvas.updateGeometry(self)

class MplWidget(QtWidgets.QWidget):
    """Widget defined in Qt Designer"""
    def __init__(self, parent = None):
        # initialization of Qt MainWindow widget
        QtWidgets.QWidget.__init__(self, parent)
        # set the canvas to the Matplotlib widget
        self.canvas = MplCanvas()

        ## create a vertical box layout
        self.hbl = QtWidgets.QHBoxLayout()
        self.vbl = QtWidgets.QVBoxLayout()
        self.loadButton = QtWidgets.QPushButton('load curve')
        self.loadButton.setMaximumWidth(100)
        self.loadButton.clicked.connect(self.loadCurve)
        self.labelLayout = QtWidgets.QHBoxLayout()
        # create Labels to show data points from picker
        self.curveLabel = QtWidgets.QLabel('curve: ')
        self.dataLabel = QtWidgets.QLabel('data point: ')
        self.labelLayout.addWidget(self.curveLabel)
        self.labelLayout.addWidget(self.dataLabel)
        self.labelLayout.addWidget(self.loadButton)

        self.vbl.addLayout(self.labelLayout)
        # create a tabWidget as central widget
        self.tab = QtWidgets.QTabWidget()
        # add TabWidget to vertical box
        self.hbl.addWidget(self.tab)
        # add mpl Widget to vertical box
        self.tab.addTab(self.canvas, 'curves')
        # add a tab for data table
        self.dataTable = QtWidgets.QTableWidget()
        self.tab.addTab(self.dataTable, 'data')
        # set the layout to th vertical box
        self.vbl.addLayout(self.hbl)

        self.setLayout(self.vbl)

        self.clip = QtWidgets.QApplication.clipboard()

        self.canvas.mpl_connect('pick_event', self.on_pick)

    def on_pick(self, event):
        # The event received here is of the type
        # matplotlib.backend_bases.PickEvent
        #
        # It carries lots of information, of which we're using
        # only a small amount here.
        #
        thisline = event.artist
        if thisline is not self.legend.legend:
            xdata, ydata = thisline.get_data()
            ind = event.ind
            self.curveLabel.setText('curve: {}'.format(thisline.get_label()))
            self.dataLabel.setText('selected point: x = {}  y = {}'.format(xdata[ind[0]], ydata[ind[0]]))

    def keyPressEvent(self, e):
        if (e.modifiers() & QtCore.Qt.ControlModifier):
            selected = self.dataTable.selectedRanges()

            if e.key() == QtCore.Qt.Key_C: #copy
                s = ""

                for r in range(selected[0].topRow(), selected[0].bottomRow()+1):
                    for c in range(selected[0].leftColumn(), selected[0].rightColumn()+1):
                        try:
                            s += str(self.dataTable.item(r,c).text()) + "\t"
                        except AttributeError:
                            s += "\t"
                    s = s[:-1] + "\n" #eliminate last '\t'
                self.clip.setText(s)

    def loadCurve(self):
        pass


a=[]
b=[]
c=0
for i in range(int(input())):
    x,y=map(int,input().split(" "))
    a.append(x)
    b.append(y)
for i in a:
    for j in b:
        if i==j:
            c+=1
print(c)


import os
import argparse

from tqdm import tqdm
from PIL import Image

def prepreprocess(src_path, result_path, upscale_factor):
    src_path_list = os.listdir(src_path)
    for file_name in tqdm(src_path_list):
        image = Image.open(os.path.join(src_path, file_name)).convert('RGB')
        image_w, image_h = image.size
        image_size = (int(image_w / upscale_factor), int(image_h / upscale_factor))
        image = image.resize(image_size, Image.BICUBIC)
        image.save(os.path.join(result_path, file_name))

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='prepreprocess script')
    parser.add_argument('--src_path', default='./datasets/Set5/', type=str,
                    help='path of source image files')
    parser.add_argument('--result_path', default='./datasets/Set5_X2/', type=str,
                    help='path of output ')
    parser.add_argument('--upscale_factor', default=2, type=int,
                    help='upscale_factor')
    args = parser.parse_args()

    if not os.path.exists(args.src_path):
        print("---", "ERROR! the input path is not exist", "---")
        exit(-1)
    if not os.path.exists(args.result_path):
        os.makedirs(args.result_path)

    prepreprocess(args.src_path, args.result_path, args.upscale_factor)


import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

objPath = "./dataset/xatlas-web/models"

FilePath = os.path.join(objPath, "matteonormb.obj")

def load_data(FILE_PATH):
    with open(FILE_PATH) as file:
        points = []
        while 1:
            line = file.readline()
            if not line:
                break
            strs = line.split(" ")
            if strs[0] == "v":
                points.append((float(strs[1]), float(strs[2]), float(strs[3])))
            if strs[0] == "vt":
                break
    # points原本为列表，需要转变为矩阵，方便处理
    points = np.array(points)
    return points

points = load_data(FilePath)

x = points[:][0]
y = points[:][1]
z = points[:][2]

print(x,y,z)


def encode(tiles, model):
    features = model.predict(tiles)
    features = features.ravel()
    return features

class Model:
    __name__ = "CNN base model"

    def __init__(self, base, batch_size=1):
        from tensorflow.keras import backend as K

        self.base = base
        self.model, self.preprocess = self.load_model()
        self.batch_size = batch_size
        self.data_format = K.image_data_format()

    def load_model(self):
        if self.base == "resnet50":
            from tensorflow.keras.applications.resnet50 import (
                ResNet50,
                preprocess_input,
            )

            cnn_base_model = ResNet50(
                include_top=False, weights="imagenet", pooling="avg"
            )
        elif self.base == "vgg16":
            from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input

            cnn_base_model = VGG16(include_top=False, weights="imagenet", pooling="avg")
        elif self.base == "inception_v3":
            from tensorflow.keras.applications.inception_v3 import (
                InceptionV3,
                preprocess_input,
            )

            cnn_base_model = InceptionV3(
                include_top=False, weights="imagenet", pooling="avg"
            )
        elif self.base == "xception":
            from tensorflow.keras.applications.xception import (
                Xception,
                preprocess_input,
            )

            cnn_base_model = Xception(
                include_top=False, weights="imagenet", pooling="avg"
            )
        else:
            raise ValueError("{} is not a valid model".format(self.base))
        return cnn_base_model, preprocess_input

    def predict(self, x):
        from tensorflow.keras import backend as K

        if self.data_format == "channels_first":
            x = x.transpose(0, 3, 1, 2)
        x = self.preprocess(x.astype(K.floatx()))
        return self.model.predict(x, batch_size=self.batch_size, verbose=False)