from tkinter import *

woodc = "burlywood"
brickc = "red"
leatherc = "black"
metalc = "silver"
clothc = "beige"

class GUI:

	def resolve(self):
		self.textfeld.delete(1.0, END)
		rwood = self.backend.calc(self.backend.wood)
		rbrick = self.backend.calc(self.backend.brick)
		rleather = self.backend.calc(self.backend.leather)
		rmetal = self.backend.calc(self.backend.metal)
		rcloth = self.backend.calc(self.backend.cloth)
		self.textfeld.insert(END, ["T2", "T3","T4","T5","T6","T7","T8"])
		self.textfeld.insert(END, "\n")
		self.textfeld.insert(END, rwood)
		self.textfeld.insert(END, "\n")
		self.textfeld.insert(END, rbrick)
		self.textfeld.insert(END, "\n")
		self.textfeld.insert(END, rleather)
		self.textfeld.insert(END, "\n")
		self.textfeld.insert(END, rmetal)
		self.textfeld.insert(END, "\n")
		self.textfeld.insert(END, rcloth)
		self.textfeld.insert(END, "\n")

	def clear(self):
		self.textfeld.delete(1.0, END)
		self.backend.__init__()

	def __init__(self, root, backend):
		self.backend = backend

		#Frame um die Eingabeanordnung zusammenzufassen
		intab = Frame(root)
		intab.pack(side=LEFT, fill=Y)

		#TextBox zur Ausgabe
		self.textfeld = Text(root, height = 10, width = 25)
		self.textfeld.pack(side=LEFT, fill=BOTH, expand=1)

		#submit button
		submit = Button(intab, text="Submit", command=self.resolve)
		submit.grid(row=6, column=0, columnspan = 2)

		clear = Button(intab, text="Clear", command=self.clear)
		clear.grid(row=6, column=2, columnspan = 2)

		#table outline horiz
		labelt0 = Label(intab, text="Tier")
		labelt2 = Label(intab, text="T2")
		labelt3 = Label(intab, text="T3")
		labelt4 = Label(intab, text="T4")
		labelt5 = Label(intab, text="T5")
		labelt6 = Label(intab, text="T6")
		labelt7 = Label(intab, text="T7")
		labelt8 = Label(intab, text="T8")

		labelt0.grid(row=0, column=0)
		labelt2.grid(row=0, column=1)
		labelt3.grid(row=0, column=2)
		labelt4.grid(row=0, column=3)
		labelt5.grid(row=0, column=4)
		labelt6.grid(row=0, column=5)
		labelt7.grid(row=0, column=6)
		labelt8.grid(row=0, column=7)

		#table outline vert
		labelWood = Label(intab, text="Wood", bg=woodc, fg="black")
		labelBrick = Label(intab, text="Brick", bg=brickc, fg="white")
		labelLeather = Label(intab, text="Leather", bg=leatherc, fg="white")
		labelMetal = Label(intab, text="Metal", bg=metalc, fg="black")
		labelCloth = Label(intab, text="Cloth", bg=clothc, fg="black")

		labelWood.grid(row=1, sticky=NSEW)
		labelBrick.grid(row=2, sticky=NSEW)
		labelLeather.grid(row=3, sticky=NSEW)
		labelMetal.grid(row=4, sticky=NSEW)
		labelCloth.grid(row=5, sticky=NSEW)

		#Buttons
		#Wood
		t2Wood = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(2, "wood", t2Wood))
		t2Wood.bind("<Button-3>", lambda a: self.backend.submat(2, "wood", t2Wood))
		t2Wood.grid(row=1, column=1)

		t3Wood = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(3, "wood", t3Wood))
		t3Wood.bind("<Button-3>", lambda a: self.backend.submat(3, "wood", t3Wood))
		t3Wood.grid(row=1, column=2)

		t4Wood = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(4, "wood", t4Wood))
		t4Wood.bind("<Button-3>", lambda a: self.backend.submat(4, "wood", t4Wood))
		t4Wood.grid(row=1, column=3)

		t5Wood = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(5, "wood", t5Wood))
		t5Wood.bind("<Button-3>", lambda a: self.backend.submat(5, "wood", t5Wood))
		t5Wood.grid(row=1, column=4)

		t6Wood = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(6, "wood", t6Wood))
		t6Wood.bind("<Button-3>", lambda a: self.backend.submat(6, "wood", t6Wood))
		t6Wood.grid(row=1, column=5)

		t7Wood = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(7, "wood", t7Wood))
		t7Wood.bind("<Button-3>", lambda a: self.backend.submat(7, "wood", t7Wood))
		t7Wood.grid(row=1, column=6)

		t8Wood = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(8, "wood", t8Wood))
		t8Wood.bind("<Button-3>", lambda a: self.backend.submat(8, "wood", t8Wood))
		t8Wood.grid(row=1, column=7)

		#Brick
		t2Brick = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(2, "brick", t2Brick))
		t2Brick.bind("<Button-3>", lambda a: self.backend.submat(2, "brick", t2Brick))
		t2Brick.grid(row=2, column=1)

		t3Brick = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(3, "brick", t3Brick))
		t3Brick.bind("<Button-3>", lambda a: self.backend.submat(3, "brick", t3Brick))
		t3Brick.grid(row=2, column=2)

		t4Brick = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(4, "brick", t4Brick))
		t4Brick.bind("<Button-3>", lambda a: self.backend.submat(4, "brick", t4Brick))
		t4Brick.grid(row=2, column=3)

		t5Brick = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(5, "brick", t5Brick))
		t5Brick.bind("<Button-3>", lambda a: self.backend.submat(5, "brick", t5Brick))
		t5Brick.grid(row=2, column=4)

		t6Brick = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(6, "brick", t6Brick))
		t6Brick.bind("<Button-3>", lambda a: self.backend.submat(6, "brick", t6Brick))
		t6Brick.grid(row=2, column=5)

		t7Brick = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(7, "brick", t7Brick))
		t7Brick.bind("<Button-3>", lambda a: self.backend.submat(7, "brick", t7Brick))
		t7Brick.grid(row=2, column=6)

		t8Brick = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(8, "brick", t8Brick))
		t8Brick.bind("<Button-3>", lambda a: self.backend.submat(8, "brick", t8Brick))
		t8Brick.grid(row=2, column=7)

		#Leather
		t2Leather = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(2, "leather", t2Leather))
		t2Leather.bind("<Button-3>", lambda a: self.backend.submat(2, "leather", t2Leather))
		t2Leather.grid(row=3, column=1)

		t3Leather = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(3, "leather", t3Leather))
		t3Leather.bind("<Button-3>", lambda a: self.backend.submat(3, "leather", t3Leather))
		t3Leather.grid(row=3, column=2)

		t4Leather = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(4, "leather", t4Leather))
		t4Leather.bind("<Button-3>", lambda a: self.backend.submat(4, "leather", t4Leather))
		t4Leather.grid(row=3, column=3)

		t5Leather = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(5, "leather", t5Leather))
		t5Leather.bind("<Button-3>", lambda a: self.backend.submat(5, "leather", t5Leather))
		t5Leather.grid(row=3, column=4)

		t6Leather = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(6, "leather", t6Leather))
		t6Leather.bind("<Button-3>", lambda a: self.backend.submat(6, "leather", t6Leather))
		t6Leather.grid(row=3, column=5)

		t7Leather = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(7, "leather", t7Leather))
		t7Leather.bind("<Button-3>", lambda a: self.backend.submat(7, "leather", t7Leather))
		t7Leather.grid(row=3, column=6)

		t8Leather = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(8, "leather", t8Leather))
		t8Leather.bind("<Button-3>", lambda a: self.backend.submat(8, "leather", t8Leather))
		t8Leather.grid(row=3, column=7)

		#Metal
		t2Metal = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(2, "metal", t2Metal))
		t2Metal.bind("<Button-3>", lambda a: self.backend.submat(2, "metal", t2Metal))
		t2Metal.grid(row=4, column=1)

		t3Metal = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(3, "metal", t3Metal))
		t3Metal.bind("<Button-3>", lambda a: self.backend.submat(3, "metal", t3Metal))
		t3Metal.grid(row=4, column=2)

		t4Metal = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(4, "metal", t4Metal))
		t4Metal.bind("<Button-3>", lambda a: self.backend.submat(4, "metal", t4Metal))
		t4Metal.grid(row=4, column=3)

		t5Metal = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(5, "metal", t5Metal))
		t5Metal.bind("<Button-3>", lambda a: self.backend.submat(5, "metal", t5Metal))
		t5Metal.grid(row=4, column=4)

		t6Metal = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(6, "metal", t6Metal))
		t6Metal.bind("<Button-3>", lambda a: self.backend.submat(6, "metal", t6Metal))
		t6Metal.grid(row=4, column=5)

		t7Metal = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(7, "metal", t7Metal))
		t7Metal.bind("<Button-3>", lambda a: self.backend.submat(7, "metal", t7Metal))
		t7Metal.grid(row=4, column=6)

		t8Metal = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(8, "metal", t8Metal))
		t8Metal.bind("<Button-3>", lambda a: self.backend.submat(8, "metal", t8Metal))
		t8Metal.grid(row=4, column=7)

		#Cloth
		t2Cloth = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(2, "cloth", t2Cloth))
		t2Cloth.bind("<Button-3>", lambda a: self.backend.submat(2, "cloth", t2Cloth))
		t2Cloth.grid(row=5, column=1)

		t3Cloth = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(3, "cloth", t3Cloth))
		t3Cloth.bind("<Button-3>", lambda a: self.backend.submat(3, "cloth", t3Cloth))
		t3Cloth.grid(row=5, column=2)

		t4Cloth = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(4, "cloth", t4Cloth))
		t4Cloth.bind("<Button-3>", lambda a: self.backend.submat(4, "cloth", t4Cloth))
		t4Cloth.grid(row=5, column=3)

		t5Cloth = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(5, "cloth", t5Cloth))
		t5Cloth.bind("<Button-3>", lambda a: self.backend.submat(5, "cloth", t5Cloth))
		t5Cloth.grid(row=5, column=4)

		t6Cloth = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(6, "cloth", t6Cloth))
		t6Cloth.bind("<Button-3>", lambda a: self.backend.submat(6, "cloth", t6Cloth))
		t6Cloth.grid(row=5, column=5)

		t7Cloth = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(7, "cloth", t7Cloth))
		t7Cloth.bind("<Button-3>", lambda a: self.backend.submat(7, "cloth", t7Cloth))
		t7Cloth.grid(row=5, column=6)

		t8Cloth = Button(intab, text="0", repeatdelay=100, repeatinterval=10, command= lambda: self.backend.addmat(8, "cloth", t8Cloth))
		t8Cloth.bind("<Button-3>", lambda a: self.backend.submat(8, "cloth", t8Cloth))
		t8Cloth.grid(row=5, column=7)


#Jimmy Gieske
expr = str('expression')      #define expr
Anslist = list()            #create new list to save answers
while expr != 'end':          #run until expr = end
    expr = str(input("(type end to stop) enter expression in form of number+number: ")) #user inputs expression
    end = len(expr)-1
    if expr.find('+') == 0 or expr.find('*') == 0 or expr.find('-') == 0 or expr.find('/') == 0:
        print('you done goofed')     #if there is a one of the things at the front then print

    elif expr.find('+') == end or expr.find('*') == end or expr.find('-') == end or expr.find('/') == end:
        print('you done goofed')

    elif expr[expr.find("+")] == '+':    #if there is a + do this stuff
        num1 = int(expr[:expr.find("+")])      #num1 is from the begining to the +
        num2 = int(expr[(expr.find("+")+1):])   #num2 is from the + (plus 1) to the ed
        ans = num1 + num2                      #addiion
        print(expr,'=',ans)                    #print answer
        Q = str(ans)                         # set ans as a string
        A = str(expr + '=' + Q)             #set A as the expression anad answer in a single string
        Anslist.insert(0,A)                   #add A to this list

    elif expr[expr.find("*")] == '*':      #if there is a * do this stuff
        nums1 = int(expr[:expr.find("*")])
        num2 = int(expr[(expr.find("*")+1):])
        ans = num1 * num2
        print(expr,'=',ans)
        Q = str(ans)
        A = str(expr + '=' + Q)
        Anslist.insert(0,A)

    elif expr[expr.find("/")] == '/':      #if there is a / do this stuff
        num1 = int(expr[:expr.find("/")])
        num2 = int(expr[(expr.find("/")+1):])
        ans = num1 / num2
        print(expr,'=',ans)
        Q = str(ans)
        A = str(expr + '=' + Q)
        Anslist.insert(0,A)

    elif expr[expr.find("-")] == '-':      #if there is a - do this stuff
        num1 = int(expr[:expr.find("-")])
        num2 = int(expr[(expr.find("-")+1):])
        ans = num1 - num2
        print(expr,'=',ans)
        Q = str(ans)
        A = str(expr + '=' + Q)
        Anslist.insert(0,A)

    elif expr == 'end':     #if end is typed in, the program prints goodbye and ends
        print('goodbye')

    elif expr == 'last':            # if last is typed in, it prints the last 3 expression and answers
        print(Anslist[0:3])

    else :
        print('You did something wrong')       #if no sign print and run again


from typing import Any, List, Optional

from llama_index.bridge.pydantic import Field, PrivateAttr
from llama_index.callbacks import CallbackManager
from llama_index.embeddings.base import DEFAULT_EMBED_BATCH_SIZE, BaseEmbedding
from llama_index.embeddings.huggingface_utils import (
    DEFAULT_INSTRUCT_MODEL,
    get_query_instruct_for_model_name,
    get_text_instruct_for_model_name,
)

class InstructorEmbedding(BaseEmbedding):
    query_instruction: Optional[str] = Field(
        description="Instruction to prepend to query text."
    )
    text_instruction: Optional[str] = Field(
        description="Instruction to prepend to text."
    )
    cache_folder: Optional[str] = Field(
        description="Cache folder for huggingface files."
    )

    _model: Any = PrivateAttr()

    def __init__(
        self,
        model_name: str = DEFAULT_INSTRUCT_MODEL,
        query_instruction: Optional[str] = None,
        text_instruction: Optional[str] = None,
        embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
        cache_folder: Optional[str] = None,
        device: Optional[str] = None,
        callback_manager: Optional[CallbackManager] = None,
    ):
        try:
            from InstructorEmbedding import INSTRUCTOR
        except ImportError:
            raise ImportError(
                "InstructorEmbedding requires instructor to be installed.\n"
                "Please install transformers with `pip install InstructorEmbedding`."
            )
        self._model = INSTRUCTOR(model_name, cache_folder=cache_folder, device=device)

        super().__init__(
            embed_batch_size=embed_batch_size,
            callback_manager=callback_manager,
            model_name=model_name,
            query_instruction=query_instruction,
            text_instruction=text_instruction,
            cache_folder=cache_folder,
        )

    @classmethod
    def class_name(cls) -> str:
        return "InstructorEmbedding"

    def _format_query_text(self, query_text: str) -> List[str]:
        """Format query text."""
        instruction = self.text_instruction

        if instruction is None:
            instruction = get_query_instruct_for_model_name(self.model_name)

        return [instruction, query_text]

    def _format_text(self, text: str) -> List[str]:
        """Format text."""
        instruction = self.text_instruction

        if instruction is None:
            instruction = get_text_instruct_for_model_name(self.model_name)

        return [instruction, text]

    def _embed(self, instruct_sentence_pairs: List[List[str]]) -> List[List[float]]:
        """Embed sentences."""
        return self._model.encode(instruct_sentence_pairs).tolist()

    def _get_query_embedding(self, query: str) -> List[float]:
        """Get query embedding."""
        query_pair = self._format_query_text(query)
        return self._embed([query_pair])[0]

    async def _aget_query_embedding(self, query: str) -> List[float]:
        """Get query embedding async."""
        return self._get_query_embedding(query)

    async def _aget_text_embedding(self, text: str) -> List[float]:
        """Get text embedding async."""
        return self._get_text_embedding(text)

    def _get_text_embedding(self, text: str) -> List[float]:
        """Get text embedding."""
        text_pair = self._format_text(text)
        return self._embed([text_pair])[0]

    def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
        """Get text embeddings."""
        text_pairs = [self._format_text(text) for text in texts]
        return self._embed(text_pairs)


import pika

from pydantic import BaseModel

from nasajon.settings import logger, RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_VHOST

from nsj_gcf_utils.json_util import json_dumps

class AsynServiceBase:

    def __init__(self, async_queue_name: str, queue_ttl=86400, queue_delay=900):
        super().__init__()
        self._async_queue_name = async_queue_name
        self._async_queue_name_delay = f"{async_queue_name}_delay"
        self._queue_ttl = queue_ttl * 1000
        self._queue_delay = queue_delay * 1000

    def handle_message_befor_enqueue(self, msg: BaseModel) -> BaseModel:
        return msg

    def enqueue(self, msg: BaseModel):

        msg = self.handle_message_befor_enqueue(msg)

        with pika.BlockingConnection(
            pika.ConnectionParameters(
                host=RABBITMQ_HOST,
                virtual_host=RABBITMQ_VHOST,
                port=RABBITMQ_PORT)
        ) as connection:
            channel = connection.channel()

            # Criando a fila para processamento das mensagens
            channel.queue_declare(
                queue=self._async_queue_name,
                durable=True,
                arguments={
                    "x-message-ttl": self._queue_ttl,
                    'x-dead-letter-exchange': '',
                    'x-dead-letter-routing-key': self._async_queue_name_delay
                }
            )

            # Criando a fila de mortos (para atraso dos erros)
            channel.queue_declare(
                queue=self._async_queue_name_delay,
                durable=True,
                arguments={
                    "x-message-ttl": self._queue_delay,
                    'x-dead-letter-exchange': '',
                    'x-dead-letter-routing-key': self._async_queue_name
                }
            )

            # Publicando a mensagem (e garantindo o roteamento para a fila de mortos)
            channel.basic_publish(
                exchange='',
                routing_key=self._async_queue_name,
                body=json_dumps(msg),
                properties=pika.BasicProperties(
                    delivery_mode=pika.spec.PERSISTENT_DELIVERY_MODE
                )
            )
            logger.info("Nova mensagem enfileirada.")
            logger.debug(f"Dados da mensagem enfileirada: {json_dumps(msg)}")


import random

from type import Type
import pygame

class Model:
    def __init__(self, x_coordinate, y_coordinate):
        self.type = random.choice(list(Type))
        self.x_coordinate = x_coordinate
        self.y_coordinate = y_coordinate
        self.x_speed, self.y_speed = 1, 1
        self.WIDTH, self.HEIGHT = 80, 60
        self.scaled_image = pygame.transform.scale(self.type.value, (self.WIDTH, self.HEIGHT))
        self.rect = pygame.Rect(self.x_coordinate, self.y_coordinate, self.WIDTH, self.HEIGHT)

    # def collision(self, second:Model):
    #     if abs(second.rect.top - self.rect.bottom) < 10 and self.y_speed > 0:
    #         self.y_speed *= -1
    #     if abs(second.rect.bottom - self.rect.top) < 10 and self.y_speed < 0:
    #         self.y_speed *= -1
    #     if abs(second.rect.right - self.rect.left) < 10 and self.x_speed < 0:
    #         self.x_speed *= -1
    #     if abs(second.rect.left - self.rect.right) < 10 and self.x_speed > 0:
    #         self.x_speed *= -1


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 31 10:32:17 2021

@author: Edgar Sanchez
"""
import os
import matplotlib.pyplot as plt

def count(func):
    def wrapper(*args, **kwargs):
        wrapper.counter += 1    # executed every time the wrapped function is called
        return func(*args, **kwargs)
    wrapper.counter = 0         # executed only once in decorator definition time
    return wrapper

def save_train_traj(path, df_model_training, valid=True):
    if not os.path.exists(path):
        os.makedirs(path)
    df_model_training.to_csv(path+'/Training.csv')

    # Save training curve
    train_loss = df_model_training['Train_loss'].to_list()
    if valid:
        valid_loss = df_model_training['Valid_loss'].to_list()

    fig = plt.figure()
    plt.plot(train_loss, label='Training')
    if valid:
        plt.plot(valid_loss, label='Validation')
    plt.xlabel('Epoch')
    plt.ylabel('Loss function')
    plt.yscale('log')
    plt.legend()
    plt.close(fig)
    fig.savefig(path+'/Training.png')


# This module is used to visualize the data and save the figures.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mtick

# A function to visualize an accuracy metric of a given model on reduced and original data
def plot_data(data, xlabel, ylabel, xlabels, legends, title, target_file, display=False, save=True, percentage=True):

    # Width of the bars
    bar_width = 1 / (data.shape[0] + 1)
    # Colors of the bars
    colors = ["#064E3B", "#312E81", "#78350F", "#7F1D1D"]
    # Patterns of the bars
    patterns = ["/", "\\", "-", "|"]
    # Average of each metric
    averages = np.zeros((data.shape[0], data.shape[1]))
    # Standard Deviation of each metric
    stds = np.zeros((data.shape[0], data.shape[1]))

    # Calculate the average and standard deviation of each metric
    for i in range(data.shape[0]):
        for j in range(data.shape[1]):
            averages[i, j] = data[i, j].mean()
            stds[i, j] = data[i, j].std()

    # Define the position of each bar
    positions = np.arange(len(averages[0]))

    # Init a figure object
    fig = plt.figure(figsize=(16, 9), dpi=120)

    # Plot the bars and error bars for each metric
    for i in range(data.shape[0]):
        # Plot the bars for original data metrics
        plt.bar(positions + i * bar_width, averages[i], color=colors[i], hatch=patterns[i], width=bar_width,
                label=legends[i], alpha=0.3)
        # Plot the error bars for original data metrics
        plt.errorbar(positions + i * bar_width, averages[i], yerr=stds[i], fmt="none",
                     ecolor=colors[i], capsize=10, capthick=0.5)
        # Display the values as labels for each bar
        for j in range(len(averages[i])):
            # get only 2 digits after the decimal point
            if percentage:
                label = "{:.2f}".format(averages[i, j])
                label = label + "%"
                plt.text(x=j + i * bar_width - bar_width / 2 + 0.01, y=101, s=label, fontsize=13,
                         fontweight="bold", color=colors[i])
            else:
                label = "{:.0f}".format(averages[i, j])
                yposition = averages[i, j] + stds[i, j] + (averages.max(initial=0) + stds.max(initial=0)) * 0.01
                plt.text(x=j + i * bar_width - bar_width / 2 + 0.06, y=yposition, s=label, fontsize=13,
                         fontweight="bold", color=colors[i])

    # Define labels and title
    # plt.xlabel(xlabel, fontsize=18, fontweight="bold")
    # plt.ylabel(ylabel, fontsize=18, fontweight="bold")
    plt.tick_params(axis="both", which="major", labelsize=22)
    if percentage:
        plt.axis([-bar_width, averages.shape[1] - bar_width, 0, 120])
    else:
        plt.axis([-bar_width, averages.shape[1] - bar_width, 0, (averages.max(initial=0) + stds.max(initial=0)) * 1.2])
    plt.xticks([r + (averages.shape[0] - 1) * 0.5 * bar_width for r in range(averages.shape[1])], xlabels)
    # plt.title(title, fontsize=16, fontweight="bold")

    # Add a legend for each bar group
    plt.legend(loc="upper left", ncol=2, fontsize="16")

    if percentage:
        # Plot a 100% thin dotted line
        plt.plot([-bar_width, averages.shape[0] + averages.shape[1] * bar_width], [100, 100], color="#000000",
                 linestyle="-.", linewidth=0.1)
        # Display data as percentages
        plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter())

    # Display the figure
    if display:
        plt.show()

    # Save the figure to pdf and jpg formats
    if save:
        fig.savefig(target_file + ".pdf", format="pdf", dpi=120)
        fig.savefig(target_file + ".jpg", format="jpg", dpi=120)

    # Close the figure
    plt.close(fig)

# Set the default font family to Times New Roman
plt.rcParams["font.family"] = "serif"
plt.rcParams["font.serif"] = ["Times New Roman"] + plt.rcParams["font.serif"]


import random
from stockfish import Stockfish
import chess

class Player:
    def __init__(self, controller="random", customFunction=None):
        # "random", "gp", "alphazero", "*anyother we're planning to implement"
        self.controller = controller
        self.customFunction = customFunction
        # add any other variables as needed
        self.stockfish = Stockfish('./stockfish-10-win/Windows/stockfish_10_x64.exe')

    def choose_move(self, board, moves):
        if self.controller == "random":
            chosenMoveIndex = random.randint(0, len(moves)-1)
            chosenMove = moves[chosenMoveIndex]
            return chosenMove
        elif self.controller == "custom":
            return self.customFunction(board, moves)
        elif self.controller == "stockfish":
            self.stockfish.set_fen_position(board.fen())
            uciStr = self.stockfish.get_best_move()
            move = chess.Move.from_uci(uciStr)
            return move
        elif self.controller == "player":
            while True:
                print(board)
                move = input("Input a move, or input m for a list of possible moves: ")
                if move == 'm':
                    for move in moves:
                        print(move)
                    continue
                try:
                    move = chess.Move.from_uci(move)
                    if move in moves:
                        return move
                    else:
                        print("Invalid move")
                except:
                    print("Invalid move")
                    continue
        else:
            # implement controller's movement choice
            pass


import numpy as np
from abc import ABC, abstractmethod
from .geometry import *
from .tools import distance, istypes, unsupported

__all__ = ["AbstractConstraint", "SamePointConstraint", "SameLengthConstraint",
           "IntersectsConstraint"]

class AbstractConstraint(ABC):
    def __init__(self, *objects):
        self.objects = objects

    # error should always be non-negative, trying to minimize it
    def error(self, objects):
        objects = [object.compute(objects) for object in self.objects]
        # squaring keeps non-negative and improves tendency to satisfy
        # all constraints well rather than a few poorly and others greatly
        err = self._error(objects)
        if err is not None:
            return err**2
        else:
            unsupported(self, objects)

    @abstractmethod
    def _error(self, points):
        pass

class SamePointConstraint(AbstractConstraint):
    def _error(self, objects):
        return distance(objects[0], objects[1])

class SameLengthConstraint(AbstractConstraint):
    def _error(self, objects):
        return objects[0].length() - objects[1].length()

class IntersectsConstraint(AbstractConstraint):
    def _error(self, objects):
        if istypes(objects, [Circle, Point]):
            return distance(objects[0].center, objects[1]) - objects[0].radius
        elif istypes(objects, [Point, Circle]):
            return self._error(objects[::-1])


import torch
from torch.nn import init
from torch import nn
import os
from scipy.io import loadmat
import random
import numpy as np

def weight_init(m):
    if isinstance(m, nn.Linear):
        m.reset_parameters()

def train_test_split(gt: np.ndarray, size: int = None, ratio: int = None):
    """
    :param gt: 高光谱图像的groundtruth
    :param size: 每类样本的大小
    :return: train_gt(训练样本标签), test_gt(测试样本标签)
    """
    train_gt = np.zeros_like(gt)
    test_gt = np.zeros_like(gt)
    test_gt[:] = gt[:]
    random.seed(666)
    for i in np.unique(gt):
        if i != 0:
            indices = list(zip(*np.nonzero(gt == i)))
            num = size if size else int(len(indices) * ratio)
            samples = random.sample(indices, min(num, len(indices)))
            x = tuple(zip(*samples))
            train_gt[x] = gt[x]
            test_gt[x] = 0
    return train_gt, test_gt

def pad(d_in, kernel, stride):
    r = (d_in - kernel) % stride
    if r == 0:
        padding=  0
    else:
        m = stride - r
        padding = m // 2 if m % 2 == 0 else (m + stride) // 2
    return padding


#!/usr/bin/env python3
import threading
import time
import os
import sys
import datetime
import argparse
import shlex
import warnings
import configparser
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from conf import ConfigHelper, OptionDialog
from configload import configload
from wakeup import Waker
from schedule import Schedule
import monitor

# CLI options
options = argparse.ArgumentParser(
        description='Advanced wakeup alarm system written in PyQt5')
options.add_argument('-c','--config',
                     metavar='CONF', help='specify config file')
options.add_argument('-v','--verbose', action='store_true',
                     help='output more details')
options.parse_args()

verbose = options.parse_args().verbose
path = ''

class Dashboard(QWidget):
    wake = pyqtSignal()
    def __init__(self):
        super().__init__()
        self.setWindowTitle('StayAwake')
        title = QLabel('StayAwake')
        version = QLabel("Version: 0.5.1")
        title.setStyleSheet("font: 30pt")

        self.wake.connect(self.create_confirmation_dialog)
        self.microsleep_count = 0

        self.path = ''
        pathwin32 = os.path.expandvars('%USERPROFILE%\AppData\Roaming\stayawake\stayawake.conf')

        if sys.platform.startswith("linux"):
            if os.path.isfile('stayawake.conf'):
                self.path = 'stayawake.conf'
                self.path = os.path.abspath(self.path)
            elif os.path.isfile(os.path.expandvars('$HOME/.config/stayawake/stayawake.conf')):
                self.path = os.path.expandvars('$HOME/.config/stayawake/stayawake.conf')
            else:
                self.path = "/etc/stayawake.conf"

        if sys.platform.startswith("win32"):
            pathwin32 = os.path.expandvars('%USERPROFILE%\AppData\Roaming\stayawake\stayawake.conf')
            if os.path.isfile('stayawake.conf'):
                self.path = 'stayawake.conf'
            elif os.path.isfile(pathwin32):
                self.path = pathwin32

        if sys.platform.startswith("darwin"):
            if os.path.isfile('stayawake.conf'):
                self.path = 'stayawake.conf'
            elif os.path.isfile(os.path.expandvars('$HOME/.config/stayawake/stayawake.conf')):
                self.path = os.path.expandvars('$HOME/.config/stayawake/stayawake.conf')
            else:
                self.path = "/etc/stayawake.conf"
        # Alias for option values
        settings = configload(self.path)
        self.max_inactivity = datetime.timedelta(seconds=settings['max_inactivity'])
        self.alarm_dir = settings['alarm_dir']
        self.volume_max_command = settings['volume_max_command']
        self.play_command = settings['play_command']
        self.schedule_name = settings['schedule_name']
        self.sleep_names = settings['sleep_names']
        self.schedule = Schedule(settings['schedule'], settings['sleep_names'])

        configpath_label = QLabel("Configuration file:\n" + os.path.abspath(self.path))
        configpath_label.setStyleSheet("font: 10pt")
        self.vbox = QVBoxLayout()
        self.vbox.setContentsMargins(30, 30, 30, 30)

        self.vbox.addWidget(title)
        self.vbox.addWidget(version)
        self.vbox.addWidget(configpath_label)
        self.setLayout(self.vbox)

        self.schedule_box = QGroupBox("Schedule Information")
        self.vbox1 = QVBoxLayout()
        self.status_box = QGroupBox("Status")
        vbox2 = QVBoxLayout()
        self.monitor_box = QGroupBox("Activity Monitor")
        vbox3 = QVBoxLayout()

        # Top section
        self.schedule_name_label = QLabel("Schedule: " + self.schedule_name)
        self.schedule_times_label = QLabel(self.schedule.prettify())
        self.vbox1.addWidget(self.schedule_name_label)
        self.vbox1.addWidget(self.schedule_times_label)
        self.schedule_box.setLayout(self.vbox1)
        self.vbox.addWidget(self.schedule_box)

        # Middle section
        self.now_label = QLabel()
        self.next_label = QLabel()
        self.remaining_label = QLabel()
        vbox2.addWidget(self.now_label)
        vbox2.addWidget(self.next_label)
        vbox2.addWidget(self.remaining_label)
        self.status_box.setLayout(vbox2)
        self.vbox.addWidget(self.status_box)

        # Bottom section
        self.timer_label = QLabel()
        vbox3.addWidget(self.timer_label)
        self.wakeups_label = QLabel()
        vbox3.addWidget(self.wakeups_label)
        self.monitor_box.setLayout(vbox3)
        self.vbox.addWidget(self.monitor_box)

        options_button = QPushButton("Options..")
        options_button.clicked.connect(self.on_options)
        self.vbox.addWidget(options_button)

        configure_button = QPushButton("Configure..")
        configure_button.clicked.connect(self.on_configure)
        self.vbox.addWidget(configure_button)

        self.show()

        timer = QTimer(self)
        timer.timeout.connect(self.update)
        timer.start(100)

    def update(self):
        'Update datetime and time remaining until next sleep'
        now = datetime.datetime.now()
        diff = now - monitor.la
        awake_msg = "Hey! You should be asleep now. What are you doing?"
        self.now_label.setText(str(datetime.datetime.now())[:19])
        if self.schedule.isAsleep():
            self.next_label.setText(awake_msg)
            self.remaining_label.setText(awake_msg)
            self.timer_label.setText(awake_msg)
        else:
            self.next_label.setText('Next Sleep: ' + self.schedule.next())
            self.remaining_label.setText(self.schedule.remaining() + ' remaining')
            if monitor.la < now:
                self.timer_label.setText(str(diff.seconds)
                    + '.' + str(diff.microseconds)[:1]
                    + 's / ' + str(self.max_inactivity.seconds) + 's')

    def on_suspend(self):
        'Callback function when the Apply button is pressed'
        monitor.la = datetime.datetime.now()\
                + datetime.timedelta(minutes=self.dialog.suspend_spinbox.value())
        self.timer_label.setText('The monitor will resume at:\n'
            + str(monitor.la)[:19])
        if self.dialog.suspend_spinbox.value() != 0:
            print('[' + str(datetime.datetime.now().time())[:8] + ']'\
                + ' Monitor suspended for '
                + str(self.dialog.suspend_spinbox.value())
                + ' minutes until '
                + str(monitor.la)[:19])
        self.dialog.suspend_spinbox.setValue(0)

    def on_cancel(self):
        'Callback function when Reset button is pressed'
        monitor.la = datetime.datetime.now()
        self.dialog.suspend_spinbox.setValue(0)
        print(('[' + str(datetime.datetime.now().time())[:8] + ']'\
                + ' Monitor suspension is reset, now resuming...'))

    def on_options(self):
        'Callback function when Options button is pressed'
        self.dialog = OptionDialog(self)
        self.dialog.show()

    def on_flex(self):
        'Callback function when Flex in Options is Applied'
        self.schedule.pristine()
        self.schedule.flex_next_sleep(self.dialog.flex_spinbox.value())
        self.schedule_times_label.setText(self.schedule.prettify())
        print('[' + str(datetime.datetime.now().time())[:8] + ']' +
                ' Next sleep flexed ' + str(self.dialog.flex_spinbox.value())
                + ' minutes')
        self.dialog.flex_spinbox.setValue(0)

    def on_pristine(self):
        'Callback function to restore the schedule into its pristine state'
        self.dialog.flex_spinbox.setValue(0)
        self.schedule.pristine()
        self.schedule_times_label.setText(self.schedule.prettify())
        print('[' + str(datetime.datetime.now().time())[:8] + ']' + ' Schedule reset to pristine conditions')

    def on_configure(self):
        self.conf_helper = ConfigHelper()
        self.conf_helper.show()

    def create_confirmation_dialog(self):
        val = QMessageBox.question(self, 'Confirm Microsleep', "Was that an actual microsleep?", QMessageBox.Yes | QMessageBox.No)
        if val == QMessageBox.Yes:
            self.microsleep_count += 1
        if val == QMessageBox.No:
            pass

    def get_confirmation_dialog(self):
        self.wake.emit()

app = QApplication(sys.argv)
window = Dashboard()

def main():
    start_time = datetime.datetime.now()
    ringing = False
    prev_ringing = False
    waking = False
    wakeups = 0
    w = Waker(window.alarm_dir, window.volume_max_command, window.play_command)

    while not window.schedule.isAsleep():
        diff = datetime.datetime.now() - monitor.la
        if diff >= window.max_inactivity:
            # Label colour change
            window.timer_label.setStyleSheet("color: #fff;" +
                    "background-color: #f00")
            # Alarm playing
            prev_ringing = ringing
            ringing = 1
            w.wakeup()
            if(prev_ringing != ringing):
                wakeups += 1
                waking = True

        if diff < window.max_inactivity:
            if(waking):
                window.get_confirmation_dialog();
                waking = False
            prev_ringing = ringing
            ringing = 0
            window.timer_label.setStyleSheet("")
            w.exit()
        window.wakeups_label.setText(str(window.microsleep_count) + " microsleeps in this session since " + str(start_time)[5:19])
        time.sleep(1)

mouseactivity = threading.Thread(target=monitor.MouseMonitor)
mouseactivity.daemon = True
mouseactivity.start()

keyboardactivity = threading.Thread(target=monitor.KeyboardMonitor)
keyboardactivity.daemon = True
keyboardactivity.start()

main = threading.Thread(target=main)
main.daemon = True
main.start()

sys.exit(app.exec_())


from sklearn.linear_model import LogisticRegression
import numpy as np
import csv
from sklearn import preprocessing
from sklearn.externals import joblib

def read_csv(filename):
  """
  - params filename: filename of the file
  - params type: string
  - return: numpy ndarray
  """
  with open(filename, mode='r') as f:
    csv_reader = csv.reader(f)
    points = []
    labels = []
    for row in csv_reader:
      row = list(map(lambda x: float(x), row))
      points.append(row[:len(row) - 1])
      labels.append([row[-1]])
    points = np.array(points)
    labels = np.array(labels)
  return points, labels

def load_dataset(files):
  data, labels = None, None
  for filename in files:
    temp_point, temp_label = read_csv(filename)
    if data is None:
      data, labels = temp_point, temp_label
    else:
      data = np.vstack((data, temp_point))
      labels = np.vstack((labels, temp_label))
  return data, labels

def train_test():
  all_acc = []
  for idx in range(5):
    train_files = ['../data/fold-{}.csv'.format(i) for i in range(5)]
    train_files = list(filter(lambda x: x != '../data/fold-{}.csv'.format(idx), train_files))
    test_files = ['../data/fold-{}.csv'.format(idx)]
    train_data, train_labels = load_dataset(train_files)
    test_data, test_labels = load_dataset(test_files)
    clf = LogisticRegression(random_state=0, solver='lbfgs', multi_class='multinomial').fit(train_data, train_labels)
    result = clf.predict(test_data)
    result = result.reshape((-1, 1))
    acc = result == test_labels
    acc = acc.sum() / test_labels.shape[0]
    all_acc.append(acc)
  print(sum(all_acc) / len(all_acc))

def train_model():
  train_files = ['../data/fold-{}.csv'.format(i) for i in range(5)]
  train_data, train_labels = load_dataset(train_files)
  result = []
  idx = 0
  with open('../data/test set.csv', 'r') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
      if idx > 0:
        row = list(map(lambda x: float(x), row))
        result.append(row)
      idx += 1
  result = np.array(result)
  result = preprocessing.scale(result)
  clf = LogisticRegression(random_state=0, solver='lbfgs', multi_class='multinomial').fit(train_data, train_labels)
  predicted = clf.predict(result)
  predicted = predicted.reshape((-1, 1))
  with open('../result/result.csv', 'w', newline='') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow(['id', 'predicted'])
    for i in range(predicted.shape[0]):
      csv_writer.writerow([i + 1, predicted[i, 0]])

if __name__ == "__main__":
  # train_test()
  train_model()


import os
import numpy as np
import paddle
import paddle.fluid as fluid
from paddle.fluid import core

paddle.enable_static()

MODEL_NAME = "inference_model"
MODEL_FILE = "model.pdmodel"
PARAMS_FILE = "model.pdiparams"

def main(argv=None):
    # Load model
    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
    model_dir = "./paddle_model/" + MODEL_NAME
    print("model dir:", model_dir)
    if len(MODEL_FILE) == 0 and len(PARAMS_FILE) == 0:
        [program, feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(model_dir, exe)
    else:
        [program, feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(
             model_dir,
             exe,
             model_filename=MODEL_FILE,
             params_filename=PARAMS_FILE)
    print("--- feed_target_names ---")
    print(feed_target_names)
    print("--- fetch_targets ---")
    print(fetch_targets)
    # Preprocess

    input_tensor1 = np.ones([1024,4]).astype(np.float32)
    input_tensor2 = np.ones([1024,17,3]).astype(np.float32)
    input_tensor3 = np.ones([1024,17,4]).astype(np.float32)
    input_tensor4 = np.ones([1024,17,8,12]).astype(np.float32)

    input_tensors = {"x2paddle_goal_input":input_tensor1,"x2paddle_adc_input":input_tensor2,"x2paddle_path_input":input_tensor3,"x2paddle_obs_input":input_tensor4}
    # Inference
    output_tensors = exe.run(program=program,
                             feed=input_tensors,
                             fetch_list=fetch_targets,
                             return_numpy=False)
    # Postprocess
    for output_tensor in output_tensors:
        output_data = np.array(output_tensor)
        print(output_data.shape)
        print(output_data)
    print("Done.")

if __name__ == '__main__':
    main()


# Useful imports
import numpy as np
import matplotlib.pyplot as plt
from math import log, exp, sin, cos, sqrt, pi, e

#//////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////

# Creating arrays
numberOfElements = int(input("Enter the length of the list: "))
a = np.zeros(numberOfElements, float)
print(a)

t = np.empty(4, float)
print(t)

r = [1.0, 1.5, -2.2]
a = np.array(r, float)

a = np.array([[1, 2, 3], [4, 5, 6]], int)
print(a)

a = np.zeros([2, 2], int)
a[0, 1] = 1
a[1, 0] = -1
print(a)

#//////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////

# Useful arithmetic

# x = float(input("Enter the value of x: "))
# Exponents: x**y           [===>]  x^y
# Integer part of x/y       [===>]  x//y = floor(x/y)
# Remainder of x/y          [===>]  x%y
# x/y = x//y + (x%y)/y
# math.log(argument,base)   [===>]  math.log(y,x)

#//////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////

# If statements

x = int(input("Enter a whole number no greater than ten: "))

if x > 10:
    print("You entered a number greater than ten.")
    print("Let me fix that for you.")
    x = 10
print("Your number is", x)

#//////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////

# Arrays vs Lists

# a.size returns the product of the dimensions of an array, a
# a.shape returns the dimensions of an array, a in the form (row, col)
# Arrays start counting at 0. so, a[n] returns the (n+1)th element of a
# the map(x,y) takes a function x, and applies it to every element in a

# Pro list
# 1) The number of elements in an array is fixed. You cannot add elements to an array once it is created, or remove them
# 2) The elements of an array must all be of the same type, such as all floats or all integers. You cannot mix elements of different types in the same array and you cannot change the type of the elements once an array is created

# Pro array
# 1) Arrays can be two-dimensional, like matrices in algebra
# 2) Arrays behave roughly like vectors or matrices

#//////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////

# Plotting

# plt.plot([List of values], c = [color], label = [Title])
# plt.ylabel([y axis title])
# plt.xlabel([x axis title])
# plt.legend()
# plt.show()

#//////////////////////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////////////////////////

# Derivatives of functions

#from scipy.misc import derivative

#df_dx = derivative(f, x0=1.0, dx=1e-8, n=1)


from util import Point2HTMLSize, Storage as S

DEFAULTS = S(FONT = 'Times New Roman',
             SIZE = 12,
             BACK = (255, 255, 255),
             FORE = (0, 0, 0))

def tohex(t, n = 3):
    return ''.join('%02x' % c for c in t[:n])

pointsize_map = {
    8: 1,
    10: 2,
    12: 3,
    14: 4,
    18: 5,
    24: 6,
    36: 7,
    38: 7
}

def aimsize(n):
    n = int(n)

    try:
        return pointsize_map[n]
    except KeyError:
        return Point2HTMLSize(n)

def to_aimhtml(s, fmt, body_bgcolor = False, replace_newlines=False):
    '''
    Given a string, and a fmt dictionary containing color and font information, returns "AIM" html.

    AIM html is a limited subset of HTML displayed by AIM clients.
    '''
    before, after = '', ''

    fontface = fontsize = fontfore = fontback = None

    face = fmt.get('face', DEFAULTS.FONT)
    if face != DEFAULTS.FONT: fontface = face

    size = fmt.get('size', DEFAULTS.SIZE)
    if size != DEFAULTS.SIZE: fontsize = size

    back = fmt.get('backgroundcolor', DEFAULTS.BACK)
    if back != DEFAULTS.BACK: fontback = back

    fore = fmt.get('foregroundcolor', DEFAULTS.FORE)
    if fore != DEFAULTS.FORE: fontfore = fore

    bodyattrs = None

    if fontface or fontsize or fontback or fontfore:
        if body_bgcolor and fontback and fontback != (255, 255, 255):
            bodyattrs = 'BGCOLOR="#%s"' % tohex(fontback)

        fontattrs = ' '.join(filter(lambda s: bool(s),
                                    [(('face="%s"'   % fontface)          if fontface else ''),
                                     (('size="%s"'   % aimsize(fontsize)) if fontsize else ''),
                                     (('color="#%s"' % tohex(fontfore))   if fontfore else ''),
                                     (('back="#%s"'  % tohex(fontback))   if (not body_bgcolor and fontback and
                                                                       fontback[:3] != (255, 255, 255)) else '')
                                     ]))

        fontattrs = fontattrs.strip()

        if fontattrs:
            before += '' % fontattrs
            after  += ''

    for a in ('bold', 'underline', 'italic'):
        if fmt.get(a, False):
            tag = a[0]
            before += '<%s>' % tag
            after   = '</%s>' % tag + after

    if bodyattrs:
        before = ('' % bodyattrs) + before
        after  += ''

    if replace_newlines:
        last = lambda _s: _s.replace('\n', '
')
    else:
        last = lambda _s: _s

    return last(''.join([before, s, after]))


import numpy as np
import torch

# Numpy like API with derivatives and GPU acceleration.
a = torch.Tensor([[1., 2.], [-1., 3.]], device='cuda')
a.requires_grad = True

b = torch.randn(2, 2, requires_grad=True).cuda()

c = a + b
d = torch.full_like(a, 15., requires_grad=True)

# From numpy.
e_np = np.ones((2, 2), dtype=np.single)
e = torch.from_numpy(e_np).to('cuda')

# Broadcasting.
f = ((e + 2) ** 1.3) * d

# ML functions.
g = torch.nn.functional.relu(c)
h = torch.nn.functional.linear(f, g).sum()

# Perform backward pass.
h.backward()

a.grad
  # ----> The gradient tensor.
b.grad
  # ----> The gradient tensor.
c.grad
  # ----> None, c is not a leaf.
d.grad
  # ----> The gradient tensor.
e.grad
  # ----> None, did not require gradient.


from django.shortcuts import render
from News.newsApp import NewsApp

newsApp = NewsApp()

# Create your views here.
def news(request):
    content = {
        'daily_news': newsApp.news
    }

    return render(request, 'news.html', content)


import contextlib
import re
from typing import NamedTuple, Optional

import discord
from redbot.core.commands import Context, BadArgument, MemberConverter

_discord_member_converter_instance = MemberConverter()
_id_regex = re.compile(r"([0-9]{15,21})$")
_mention_regex = re.compile(r"<@!?([0-9]{15,21})>$")

class MemberOrID(NamedTuple):
    member: Optional[discord.Member]
    id: int

    @classmethod
    async def convert(cls, ctx: Context, argument: str):

        with contextlib.suppress(Exception):
            m = await _discord_member_converter_instance.convert(ctx, argument)
            return cls(m, m.id)

        match = _id_regex.match(argument) or _mention_regex.match(argument)
        if match:
            return cls(None, int(match.group(1)))

        raise BadArgument()


class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        path= []
        result = []
        candidates.sort()
        def backtrack(i,path,total):
            if total==target and path not in result:
                result.append(path[:])
                return
            if total>target:
                return
            for j in range(i,len(candidates)):
                if j>i and candidates[j]==candidates[j-1]:
                    continue
                path.append(candidates[j])
                backtrack(j+1,path,total+candidates[j])
                path.pop()
        backtrack(0,path,0)
        return result


from sklearn.datasets import load_boston
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score

# 1. 데이터
datasets = load_boston()
x = datasets.data
y = datasets.target
x_train, x_test, y_train, y_test =  train_test_split(x, y, train_size=0.7, shuffle=True, random_state=66)

'''
print(x)
print(y)
print(x.shape) # (506, 13)
print(y.shape) # (506,)

print(datasets.feature_names) # 열 별로 이름 나옴
#['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT']
print(datasets.DESCR)
'''

# 2. 모델구성
model = Sequential()
model.add(Dense(5, input_dim=13))
model.add(Dense(10))
model.add(Dense(20))
model.add(Dense(20))
model.add(Dense(10))
model.add(Dense(5))
model.add(Dense(1))

import time
# 3. 컴파일, 훈련
model.compile(loss = 'mse', optimizer='adam')

start_time = time.time() # 현재 시간 리턴
model.fit(x_train, y_train, epochs=50, batch_size=1,
          verbose=1) # 중간 과정 보일지 말지 정함 defualt는 1
# 인간 눈에 보여주기위해 딜레이를 걸기 때문에 verbose를 켤 경우 통상적으로 더 느려진다
# 2 : 프로그래스 바 제외
# 3이상 : epoch만 표시
end_time = time.time()

# 4. 평가, 예측
loss = model.evaluate(x_test, y_test)
print('loss: ', loss)

print('걸린 시간 : ', end_time - start_time) # 시간 체킹

'''
verbose 0 걸린 시간 :  8.758423805236816 / 출력 없다.
verbose 1 걸린시간 :  10.278096199035645 / 프로그래스바 o, loss o, epoch o
verbose 2 걸린 시간 :  8.228228092193604 / 프로그래스바 x, loss o, epoch o
verbose 3 걸린 시간 :  8.138976812362671 / 프로그래스바 x, loss x, epoch o
'''


#%%
import os
import mlflow
import mlflow.sklearn
from random import random, randint
from mlflow import log_metric, log_param, log_artifacts

#%%
if __name__ == "__main__":
    ri = randint(0, 100)
    r = random()

    log_param('param1', ri)

    print(ri, r)
    log_metric("foo", r)
    log_metric("foo", r+1)
    log_metric("foo", r+2)

    path = "outputs"

    os.makedirs(path, exist_ok=True)

    with open(f"{path}/test.txt", "w") as f:
        f.write("hello world")

    log_artifacts(f"{path}")


# Required Imports
import sys

sys.path.append("../")
import os
import numpy as np
import open3d as o3d
import cv2
import argparse
import importlib.util
from yolo.detect import get_bounding_boxes
import time
import importlib.util
import json

CALIB_DIR = "../data/salsa/calib"

def dynamic_load(source_path):
	spec = importlib.util.spec_from_file_location(
		f"dynamic_source_{source_path}", source_path
	)
	module_object = importlib.util.module_from_spec(spec)
	spec.loader.exec_module(module_object)
	return module_object

def get_oriented_boxes(depth_im, intrinsics, coords):
	bounding_boxes = []
	for i in range(len(coords)):
		bounding_box_coords = o3d.utility.Vector3dVector([])
		points = []
		top_left = coords[i][0]
		bottom_right = coords[i][3]
		center_x = (top_left[0] + bottom_right[0]) // 2
		center_y = (top_left[1] + bottom_right[1]) // 2
		height = top_left[1] - bottom_right[1]
		width = top_left[0] - bottom_right[0]
		z1 = depth_im[int(center_y)][int(center_x)]
		pt_x1 = (
			(center_x - ints.intrinsic_matrix[0, 2]) * z1 / ints.intrinsic_matrix[0, 0]
		)
		pt_y1 = (
			(center_y - ints.intrinsic_matrix[1, 2]) * z1 / ints.intrinsic_matrix[1, 1]
		)
		mesh_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(
			size=0.05, origin=[-pt_x1, pt_y1, z1]
		)
		bounding_boxes.append(mesh_frame)

	return bounding_boxes

if __name__ == "__main__":
	DATASET = sys.argv[1]
	record = sys.argv[2]
	traj_name = sys.argv[3]

	if DATASET == "lab":
		sources = [
			(
				os.path.abspath(os.path.join(CALIB_DIR, "cam1_lab.py")),
				[640, 480],
				os.path.abspath("../data/lab/test_images/lab.jpg"),
				os.path.abspath("../data/lab/test_depth/lab_depth.npy"),
			)
		]
	elif DATASET == "salsa":
		sources = [
			(
				os.path.abspath(os.path.join(CALIB_DIR, "cam1.py")),
				[1024, 768],
				os.path.abspath("../data/salsa/test_images/0_1.jpg"),
				os.path.abspath("../data/salsa/test_depth/0_1_disp.npy"),
			)
		]

	vis = o3d.visualization.Visualizer()
	vis.create_window()

	for i, intr_tuple in enumerate(sources):
		conf_fname, resolution, img, depth_map = intr_tuple
		module_object = dynamic_load(conf_fname)

		intrinsics = module_object.intrinsics
		intrinsics = resolution + [
			intrinsics[1][1],
			intrinsics[0][0],
			intrinsics[0][-1],
			intrinsics[1][-1],
		]
		ints = o3d.camera.PinholeCameraIntrinsic()
		ints.set_intrinsics(*intrinsics)
		extrinsics = module_object.extrinsics

		print(eval('f"' + img + '"'))
		color_im = cv2.imread(eval('f"' + img + '"'))
		color_im = cv2.cvtColor(color_im, cv2.COLOR_BGR2RGB)
		color_im = o3d.geometry.Image(color_im)

		depth_im = np.load(eval('f"' + depth_map + '"'))
		depth_im_temp = depth_im
		depth_im = o3d.geometry.Image(depth_im)
		rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(
			color_im, depth_im, depth_scale=1, convert_rgb_to_intensity=False
		)

		geometries = []
		curr_pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd, ints)
		curr_pcd = curr_pcd.voxel_down_sample(voxel_size=0.001)
		curr_pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
		geometries.append(curr_pcd)

		os.chdir("/Users/Mokshith/Documents/launchpad/Watchman/3dprojection")

		frame_folder = "cam1" if DATASET == "salsa" else "lab"

		if DATASET == "salsa":
			frame_locations = sorted(
				os.listdir("./cam1_frames/"),
				key=lambda x: int(x.replace("frame", "").replace(".jpg", "")),
			)
		elif DATASET == "lab":
			frame_locations = sorted(
				os.listdir("./lab_frames/"),
				key = lambda x: int(x.replace(".jpg", ""))
			)
			frame_locations = frame_locations[0::10]

		coords = get_bounding_boxes(
			"cam1_frames/frame0.jpg" if DATASET == "salsa" else "lab_frames/003970.jpg"
		)
		bounding_boxes = (
			get_oriented_boxes(depth_im_temp, ints, coords)
			+ get_oriented_boxes(depth_im_temp, ints, coords)
			+ get_oriented_boxes(depth_im_temp, ints, coords)
		)
		for box in bounding_boxes:
			geometries.append(box)

		curr_loc = -1
		changer = 1

		camera_params = []

		for geom in geometries:
			vis.add_geometry(geom)
		cur_trajectory = o3d.io.read_pinhole_camera_trajectory(
			os.path.abspath(traj_name)
		)

		print(
			"Trajectory:",
			cur_trajectory,
		)

		def move_forward(vis):
			global curr_loc
			global curr_pcd
			global bounding_boxes
			global changer

			curr_loc += 1

			if curr_loc % 5:
				return

			ctr = vis.get_view_control()

			if record == "play":
				ctr.convert_from_pinhole_camera_parameters(
					cur_trajectory.parameters[
						(curr_loc // 5) % (len(cur_trajectory.parameters))
					]
				)
			else:
				cur_params = ctr.convert_to_pinhole_camera_parameters()
				camera_params.append(cur_params)
				print(time.time())

				if curr_loc // 100 > 10:
					vis.register_animation_callback(None)
					print("Done sampling")
					traj = o3d.camera.PinholeCameraTrajectory()
					traj.parameters = camera_params
					o3d.io.write_pinhole_camera_trajectory(
						traj_name, traj
					)

			if curr_loc % (10 if DATASET == "salsa" else 20) == 0:
				coords = np.load(
					os.path.join(
						"{}_preds/".format(frame_folder),
						frame_locations[
							(curr_loc // (10 if DATASET == "salsa" else 20))
							% len(frame_locations)
						],
					).replace("jpg", "npy")
				)
				bounding_boxes_temp = get_oriented_boxes(depth_im_temp, ints, coords)

				for i in range(len(bounding_boxes_temp)):
					bounding_boxes[i].paint_uniform_color(np.array([0, 1, 0]))
					bounding_boxes[i].translate(
						bounding_boxes_temp[i].get_center(), relative=False
					)

				for i in range(len(bounding_boxes_temp), len(bounding_boxes)):
					bounding_boxes[i].paint_uniform_color(np.array([0, 0, 0]))
					bounding_boxes[i].translate(
						np.array([1e3, 1e3, 1e3]), relative=False
					)

				for geom in bounding_boxes:
					vis.update_geometry(geom)

		vis.register_animation_callback(move_forward)
		vis.run()
		vis.destroy_window()


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

import re
from collections import Counter

def parse(path):
    result = {'polymer': Counter(), 'pairs': [], 'repls': []}
    with open(path) as f:
        for line in f:
            line = line.strip()
            if re.search(r"->", line):
                a, c, b = re.findall(r"\w", line)
                result['pairs'].append(a + c)
                result['repls'].append((a + b, b + c))
            elif re.match(r"\w+", line):
                for i in range(len(line)):
                    result['polymer'].update({line[i:i+2]: 1})
    return result

sample_input = parse('../resources/day14_ex.txt')
puzzle_input = parse('../resources/day14.txt')

def step(polymer, pairs, repls):
    result = Counter()
    for pair, count in polymer.items():
        if pair in pairs:
            idx = pairs.index(pair)
            repl = repls[idx]
            result.update({repl[0]: count, repl[1]: count})
        else:
            result.update({pair: count})
    return {'polymer': result, 'pairs': pairs, 'repls': repls}

def solve(data, steps):
    result = data
    for i in range(steps):
        result = step(**result)
    letters = Counter()
    for pair, count in result['polymer'].items():
        letters.update({pair[0]: count})
    counts = letters.values()
    return max(counts) - min(counts)

print("Day 14\n"
      "[Part 1] Example: %d, Puzzle: %d\n"
      "[Part 2] Example: %d, Puzzle: %d"
      %(solve(sample_input, 10), solve(puzzle_input, 10),
        solve(sample_input, 40), solve(puzzle_input, 40)))


#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program.  If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Document."""

from telegram import PhotoSize, TelegramObject

class Document(TelegramObject):
    """This object represents a general file (as opposed to photos, voice messages and audio files).

    Attributes:
        file_id (:obj:`str`): Unique file identifier.
        thumb (:class:`telegram.PhotoSize`): Optional. Document thumbnail.
        file_name (:obj:`str`): Original filename.
        mime_type (:obj:`str`): Optional. MIME type of the file.
        file_size (:obj:`int`): Optional. File size.

    Args:
        file_id (:obj:`str`): Unique file identifier
        thumb (:class:`telegram.PhotoSize`, optional): Document thumbnail as defined by sender.
        file_name (:obj:`str`, optional): Original filename as defined by sender.
        mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
        file_size (:obj:`int`, optional): File size.
        **kwargs (:obj:`dict`): Arbitrary keyword arguments.

    """
    _id_keys = ('file_id',)

    def __init__(self,
                 file_id,
                 thumb=None,
                 file_name=None,
                 mime_type=None,
                 file_size=None,
                 **kwargs):
        # Required
        self.file_id = str(file_id)
        # Optionals
        self.thumb = thumb
        self.file_name = file_name
        self.mime_type = mime_type
        self.file_size = file_size

        self._id_attrs = (self.file_id,)

    @classmethod
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Document, cls).de_json(data, bot)

        data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot)

        return cls(**data)


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

import bokeh
from bokeh.embed import components as plot_html
from bokeh.models import ColumnDataSource, HoverTool, FactorRange
from bokeh.palettes import viridis, Paired
from bokeh.plotting import figure
from collections import defaultdict
import csv
from flask import Flask, request, render_template, redirect
from hashlib import sha1
import io
from math import pi
import numpy as np
import pandas as pd
import re
from urllib.parse import quote as url_quote

app = Flask(__name__)
filename = 'latest-personality-test.csv'
points = {'Stämmer inte alls': 1,
          'Stämmer dåligt': 2,
          'Stämmer delvis': 3,
          'Stämmer bra': 4,
          'Stämmer precis': 5 }

def csv2df(data):
    rf = io.StringIO(data)
    rd = csv.reader(rf)
    rows = []
    for i,row in enumerate(rd):
        if i == 0:
            columns = [re.sub(r'^.*\d+\.* (.+)\]', r'\1', e) for e in row]
            continue
        else:
            row = [(points[e] if e in points else (np.nan if not e else e)) for e in row]
        rows += [row]
    def cleanup(s):
        s = s.replace('Tidsstämpel','Timestamp')
        s = 'id' if any(ss in s.lower() for ss in 'email e-mail epost e-post id-n'.split()) else s
        return s
    columns = [cleanup(c) for c in columns]
    answers = pd.DataFrame(rows, columns=columns)

    # drop previous answers
    ids = answers['id']
    drop_idx = []
    for i,user in zip(ids.index, ids):
        for j,prev_user in zip(ids.index[:i], ids):
            if prev_user == user:
                if j not in drop_idx:
                    drop_idx.append(j)
    for i in reversed(drop_idx):
        answers = answers.drop(i)

    pd.set_option('display.width', 200)
    pd.set_option('display.max_columns', 500)
    pd.set_option('display.max_rows', 500)
    # print(answers)

    return answers

def calc_scores(answers):
    answers = answers.copy()
    c = pd.read_csv('categories.csv', sep='\t')
    for i,question,scale,subscale,sign in zip(c.index, c['Fraga'], c['Scales'], c['SubScales'], c['Sign']):
        apply_sign = lambda x: 6-x if sign=='-' else x
        answers[question] = apply_sign(answers[question])

    answers = answers.set_index('id')

    # print(answers)
    # questions = set(c['Fraga'])
    # for col in answers.columns:
        # if col not in questions:
            # answers = answers.drop(col, axis=1)
    scores = answers.T

    _cat10 = [line.split('=') for line in open('small-ten.txt', encoding='utf8')]
    _cat10 = {k.strip():[w.strip() for w in vs.split(',')] for k,vs in _cat10}
    cat10 = defaultdict(list)
    for k,v in _cat10.items():
        for vv in v:
            cat10[vv] += [k]
    cat10 = dict(cat10)
    for i,question,scale,subscale,sign in zip(c.index, c['Fraga'], c['Scales'], c['SubScales'], c['Sign']):
        scores.loc[question, 'scales'] = scale.capitalize()
        subscales = cat10[subscale.capitalize()]
        scores.loc[question, 'subscales'] = subscales[0]
        for i,ss in enumerate(subscales[1:]):
            # print('subscaling again', ss, question+str(i))
            k = question+str(i)
            # print(scores.loc[question, :])
            scores.loc[k] = scores.loc[question, :]
            scores.loc[k, 'subscales'] = ss

    # remove timestamp, sex, etc.
    clean_scores = scores.dropna(subset=['scales']).copy()
    for col in clean_scores.columns:
        clean_scores[col] = clean_scores[col].astype(float, errors='ignore')

    scores_main = clean_scores.groupby(['scales']).mean()
    scores_sub = clean_scores.groupby(['scales','subscales']).mean()
    for main in scores_main.index:
        v = scores_main.loc[main]
        scores_sub.loc[(main,'*'), :] = v
    scores_sub = scores_sub.sort_index()
    percentile = (scores_sub.rank(axis=1)-1) * 99 // (len(scores_sub.columns)-1) + 1
    scores_sub['mean'] = scores_sub.mean(axis=1)
    scores_sub = scores_sub.join(percentile, rsuffix='-percentile')
    cnt = len(answers)

    # print(scores_sub)

    return scores_sub, cnt

def intify(i):
    try:
        return int(i)
    except:
        return np.nan

def chart_scores(title, scores, student_id=None, details=True):
    # print(scores)

    p = figure()
    data = {}
    if student_id is None:
        # Mr. Hulten
        data['mean'] = scores['mean']
        tooltips = [('Medelvärde', '@mean{1.1}')]
    else:
        # Student
        data['mean'] = scores[student_id]
        tooltips = [('Resultat', '@mean{1.1}'), ('Percentil', '@percentile')]
    # print('details:', details)
    # print('score:')
    # print(scores)
    m = data['mean']
    print(m)
    # print(type(m))
    if details:
        data['scales'] = factors = [(a,b.replace('*',a)) for a,b in scores.index]
        xrng = FactorRange(*factors)
    else:
        m = m.reset_index()
        m = m[m['subscales'] == '*'].drop('subscales', axis=1).set_index('scales')
        data['scales'] = m.index
        xrng = FactorRange(*m.index)
        print('**************')
        print(m)
        data['mean'] = m[m.columns[0]].values
    if student_id:
        s = scores[student_id+'-percentile']
        print(s)
        if not details:
            s = s.reset_index()
            s = s[s['subscales'] == '*'].drop('subscales', axis=1).set_index('scales')
            s = s[s.columns[0]]
        print(s)
        print(type(s))
        data['percentile'] = [intify(i) for i in s]
        for i in s:
            print(i)
        print('------>', data['percentile'])
    data['color'] = viridis(len(data['mean']))
    print(data)
    source = ColumnDataSource(data=data)
    p = figure(title=title, x_range=xrng, y_range=(0,5), sizing_mode='stretch_both', toolbar_location=None, tools='')
    p.xaxis.major_label_orientation = pi/3
    bar = p.vbar(x='scales', top='mean', color='color', width=0.9, source=source)
    p.add_tools(HoverTool(renderers=[bar], tooltips=tooltips, mode='vline'))
    script,div = plot_html(p)
    return script+div

def cipher(s):
    enc = sha1()
    enc.update(('q !A' + s + '~').encode())
    return enc.hexdigest()[2:14]

@app.route('/hulten-big-five/upload', methods=['GET', 'POST'])
def upload_big_five_csv():
    if request.method == 'POST':
        submitted_file = request.files['file']
        if submitted_file.filename:
            r = submitted_file.read()
            try:
                data = r.decode()
            except:
                data = r.decode('iso-8859-1')
            with open(filename, 'wt', encoding='utf8') as f:
                f.write(data)
            return redirect('/hulten-big-five/mr-hulten-himself')
    return render_template('main.html')

@app.route('/hulten-big-five/mr-hulten-himself')
def show_latest_group():
    details = request.args.get('details', '')
    data = open(filename, 'rt', encoding='utf8').read()
    answers = csv2df(data)
    scores,cnt = calc_scores(answers)
    mail_template = open('mail_template.txt', encoding='utf8').read().splitlines()
    subject = mail_template[0].split('=')[-1].strip()
    mail_body = '\r\n'.join(mail_template[1:]).strip()
    subject = url_quote(subject)
    mail_body = url_quote(mail_body)
    cips = [(student_id,cipher(student_id)) for student_id in answers['id']]
    extra_html = '
Individuella resultat
\n'
    extra_html += '

Student	Resultat
\n'
    for student_id,cip in cips:
        url = '%shulten-big-five/student/%s' % (request.url_root, cip)
        body = mail_body.replace('---', url)
        extra_html += '
%s	%s
\n' % (student_id, subject, body, student_id, url, url)
    extra_html += '
\n
\n'
    title = 'Personlighetstest: medelvärde för %i svar' % cnt
    scores_html = chart_scores(title, scores, details=details)
    return render_template('mean.html', plot=scores_html, details='checked' if details else '', bokeh_version=bokeh.__version__, footer=extra_html)

@app.route('/hulten-big-five/student/<cipher_id>')
def show_student(cipher_id):
    details = request.args.get('details', '')
    with open(filename, 'rt', encoding='utf8') as f:
        data = f.read()
        answers = csv2df(data)
        student_id = [sid for sid in answers['id'] if cipher(sid)==cipher_id][0]
        scores,cnt = calc_scores(answers)
        scores = scores[[c for c in scores.columns if student_id in c]]
        title = 'Personlighetstest: %s jämfört med övriga %i svar' % (student_id, cnt-1)
        scores_html = chart_scores(title, scores, student_id=student_id, details=details)
        return render_template('mean.html', plot=scores_html, details='checked' if details else '', bokeh_version=bokeh.__version__, footer='')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)


import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from sympy import pprint, Symbol, Function, Derivative, dsolve, solve, diff
import sympy as sp
from sympy.interactive import printing
printing.init_printing(use_latex = True)

f = Function('f');
x = Symbol('x');

# ODE model 1
def model1(y, x):
    dydx = 1 + x -y;
    return dydx;

model = f(x).diff(x) + 1 + x - f(x);
y_general = dsolve(model, f(x));
print('The general solution: ')
pprint(y_general);

y_special = dsolve(model,f(x), ics={f(0):0});
print('The special solution: ')
pprint(y_special);

# solution = solve(y_special.subs([(f(x), 1)]), x)
# print(solution)

# model 1
plt.figure(1)
# Direction field parameters
X_start = -15;
X_end = 15;
N_X_points = 30; # number of points in X direction
Y_start = -15;
Y_end = 15;
N_Y_points = N_X_points; # number of points in Y direction

X, Y = np.meshgrid(np.linspace(X_start, X_end, N_X_points), np.linspace(Y_start, Y_end, N_Y_points));
delta_X = np.ones((N_X_points, N_Y_points)); # direction vector x component
delta_Y = model1(Y, X); # direction vector y component
vector_normalization = np.sqrt(np.power(delta_X, 2) + np.power(delta_Y, 2));
delta_X = delta_X / vector_normalization; # normalized direction vector x component
delta_Y = delta_Y / vector_normalization; # normalized direction vector y component

# Plot direction field
plt.quiver(X, Y, delta_X, delta_Y, angles="xy");#, scale_units='xy', scale = 1);

# Plot integral curves
x_start = -8;
x_end = 12;
y_start = -15;
y_end = 15;
N_int_curves = 15; # number of solutions to plot
x = np.linspace(x_start, x_end, N_X_points * 100); # evaluate solution y(x) at x
y0_vector = np.linspace(y_start, y_end, N_int_curves); # vector of initial solutions
for solution_no in range(N_int_curves):
    y0 = y0_vector[solution_no]; # initial condition
    y = odeint(model1, y0, x, args=());
    plt.plot(x, y)

plt.xlim([X_start, X_end])
plt.ylim([Y_start, Y_end])
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid()
plt.show()


import ftplib
import json
import time
import os
from datetime import datetime
from dotenv import load_dotenv
import sys
import time

# Return SGP30 sensor data in JSON
def sgp30_log():
    result = sgp30.get_air_quality()
    return "SGP30", { "C02": + result.equivalent_co2, "TVOC": result.total_voc }

# Return MICS6814 sensor data in JSON
def mics_log():
    result = gas.read_all()
    return "MICS6814", { "Oxidising": result.oxidising, "Reducing": result.reducing, "NH3": result.nh3, "ADC": result.adc }

# Return BMP280 sensor data in JSON
def bmp280_log():
    return "BMP280", { "Temperature": bmp280.get_temperature(), "Pressure": bmp280.get_pressure() }

sensors = [sgp30_log, mics_log, bmp280_log]

# Attempt to import all required sensors
try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus
try:
    from bmp280 import BMP280
    bmp280 = BMP280(i2c_dev=SMBus(1))
except ImportError:
    sensors.remove(bmp280_log)
try:
    from mics6814 import MICS6814
    gas = MICS6814()
except ImportError:
    sensors.remove(mics_log)
try:
    from sgp30 import SGP30
    sgp30 = SGP30()

    print("Sensor warming up, please wait...")
    def crude_progress_bar():
        sys.stdout.write('.')
        sys.stdout.flush()
    sgp30.start_measurement(crude_progress_bar)
    sys.stdout.write('\n')
except ImportError:
    sensors.remove(sgp30_log)

log_path = "/rems/readings/weather.json"
log_data = { "data": {}, "time": datetime.now().strftime("%H:%M:%S") }

# Load environment variables from the .env file
load_dotenv()
HOST = os.getenv('HOST')
USER = os.getenv('USER')
PASS = os.getenv('PASS')

# FTP code to transfer weather.json to webserver
def transfer_file(file):
    try:
        ftp = ftplib.FTP(str(HOST))
        ftp.login(str(USER), str(PASS))
        ftp.storlines(f'STOR {log_path}', file)
        ftp.quit()
    except:
        print("Failed to transfer!")

while True:
    file_handle = open(log_path, "w")

    # Add sensor data to JSON object
    file_handle.seek(0)
    log_data["time"] = datetime.now().strftime("%H:%M:%S")
    for sensor in sensors:
       res = sensor()

       log_data["data"][res[0]] = res[1]

    # Write out JSON to file
    file_handle.write(json.dumps(log_data))
    file_handle.flush()

    # Trasfer file to webserver
    file_handle.truncate()
    transfer_file(file_handle)

    file_handle.close()
    time.sleep(5)


from gi.repository import Gtk

# ------------------------------------------------------------------------
#
# Gramps Modules
#
# ------------------------------------------------------------------------
from gramps.gen.config import config as global_config
from gramps.gen.const import GRAMPS_LOCALE as glocale
from gramps.gen.display.name import displayer as name_displayer
from gramps.gen.utils.alive import probably_alive
from gramps.gui.ddtargets import DdTargets

# ------------------------------------------------------------------------
#
# Plugin Modules
#
# ------------------------------------------------------------------------
from ..actions import action_handler
from ..common.common_const import _GENDERS
from ..common.common_utils import get_person_color_css
from ..common.common_vitals import format_date_string
from ..menus.menu_utils import (
    add_associations_menu,
    add_ldsords_menu,
    add_names_menu,
    add_parents_menu,
    add_partners_menu,
    add_person_menu_options,
    menu_item,
)
from .card_reference import ReferenceCard

_ = glocale.translation.sgettext

# ------------------------------------------------------------------------
#
# PersonCard Class
#
# ------------------------------------------------------------------------
class PersonCard(ReferenceCard):
    """
    The PersonCard exposes some of the basic facts about a Person.
    """

    def __init__(self, grstate, groptions, person, reference_tuple=None):
        ReferenceCard.__init__(
            self, grstate, groptions, person, reference_tuple=reference_tuple
        )
        self.relation = groptions.relation
        self.backlink = groptions.backlink
        self.context = groptions.option_space.split(".")[1]
        self.__add_person_title(person)
        self.__add_person_facts(person)
        if groptions.age_base:
            self.__load_age_at_event()
        self.enable_drag()
        self.dnd_drop_targets.append(DdTargets.EVENT.target())
        self.dnd_drop_targets.append(DdTargets.PERSON_LINK.target())
        self.enable_drop(
            self.eventbox, self.dnd_drop_targets, self.drag_data_received
        )
        self.set_css_style()

    def __add_person_title(self, person):
        """
        Add person title.
        """
        display_name = name_displayer.display(person)
        name = self.get_link(display_name, "Person", person.handle)
        name_box = Gtk.HBox(spacing=2)
        if self.groptions.card_number:
            label = Gtk.Label(
                use_markup=True,
                label=self.title_markup.format(
                    "%s." % str(self.groptions.card_number)
                ),
            )
            name_box.pack_start(label, False, False, 0)
        if self.get_option("sex-mode") == 1:
            name_box.pack_start(
                Gtk.Label(
                    use_markup=True,
                    label=self.title_markup.format(_GENDERS[person.gender]),
                ),
                False,
                False,
                0,
            )
        name_box.pack_start(name, False, False, 0)
        if self.get_option("sex-mode") == 2:
            name_box.pack_start(
                Gtk.Label(
                    use_markup=True,
                    label=self.title_markup.format(_GENDERS[person.gender]),
                ),
                False,
                False,
                0,
            )
        self.widgets["title"].pack_start(name_box, True, True, 0)

    def __add_person_facts(self, person):
        """
        Add person facts.
        """
        event_cache = []
        for event_ref in person.get_primary_event_ref_list():
            event_cache.append(self.fetch("Event", event_ref.ref))
        self.birth, self.death, self.living = self.__get_birth_death(
            event_cache
        )
        if self.get_option("event-format") == 0:
            self.__load_years()
        else:
            self.__load_fields("facts", "lfield-", event_cache)
            if "active" in self.groptions.option_space:
                self.__load_fields("extra", "mfield-", event_cache)
        del event_cache

    def _child_drop_handler(self, dnd_type, obj_or_handle, data):
        """
        Handle drop processing for a person.
        """
        if DdTargets.EVENT.drag_type == dnd_type:
            action = action_handler("Person", self.grstate, self.primary)
            action.add_new_event(None, obj_or_handle)
            return True
        if DdTargets.PERSON_LINK.drag_type == dnd_type:
            action = action_handler("Person", self.grstate, self.primary)
            action._add_new_person_reference(obj_or_handle)
            return True
        return self._primary_drop_handler(dnd_type, obj_or_handle, data)

    def __load_age_at_event(self):
        """
        Parse and if have birth load age field.
        """
        if self.birth:
            self.load_age(
                self.birth.get_date_object(), self.groptions.age_base
            )

    def __load_years(self):
        """
        Parse and load birth and death dates only.
        """
        text = format_date_string(self.birth, self.death)
        self.add_fact(self.get_label(text))

    def __get_birth_death(self, event_cache):
        """
        Extract birth and death events.
        """
        birth = False
        death = False
        living = True
        birth_ref = self.primary.obj.get_birth_ref()
        death_ref = self.primary.obj.get_death_ref()
        for event in event_cache:
            event_handle = event.handle
            if birth_ref and event_handle == birth_ref.ref:
                birth = event
            elif death_ref and event_handle == death_ref.ref:
                death = event
                living = False
            elif event.get_type().is_death_fallback():
                living = False

        if living:
            living = probably_alive(self.primary.obj, self.grstate.dbstate.db)
        return birth, death, living

    def __load_fields(self, grid_key, option_prefix, event_cache):
        """
        Parse and load a set of facts about a person.
        """
        args = {
            "event_format": self.get_option("event-format"),
            "event_cache": event_cache,
            "have_birth": self.birth,
            "have_death": self.death,
        }
        key = "%sskip-birth-alternatives" % option_prefix
        args.update({"skip_birth_alternates": self.get_option(key)})
        key = "%sskip-death-alternatives" % option_prefix
        args.update({"skip_death_alternates": self.get_option(key)})
        self.load_grid(grid_key, option_prefix, args=args)

    def get_color_css(self):
        """
        Determine color scheme to be used if available."
        """
        if not self.grstate.config.get("display.use-color-scheme"):
            return ""

        return get_person_color_css(
            self.primary.obj,
            living=self.living,
            home=self.relation,
        )

    def add_custom_actions(self, context_menu):
        """
        Add action menu items for the person based on the context in which
        they are present in relation to the active person.
        """
        action = action_handler("Person", self.grstate, self.primary)
        if self.grstate.config.get("menu.set-home-person"):
            home_person = self.grstate.dbstate.db.get_default_person()
            if (
                home_person is None
                or home_person.handle != self.primary.obj.handle
            ):
                context_menu.append(
                    menu_item(
                        "go-home",
                        _("Set home person"),
                        action.set_default_person,
                    )
                )
        context_menu.append(
            menu_item(
                "gramps-event",
                _("Add a new primary event"),
                action.add_new_event,
            )
        )
        context_menu.append(
            menu_item(
                "gramps-event",
                _("Add as participant to an existing event"),
                action.add_existing_event,
            )
        )
        if self.groptions.backlink:
            family = self.grstate.dbstate.db.get_family_from_handle(
                self.groptions.backlink
            )
            add_person_menu_options(
                self.grstate, context_menu, self.primary, family, self.context
            )
        add_parents_menu(self.grstate, context_menu, self.primary)
        add_partners_menu(self.grstate, context_menu, self.primary)
        add_associations_menu(self.grstate, context_menu, self.primary)
        add_names_menu(self.grstate, context_menu, self.primary)
        add_ldsords_menu(self.grstate, context_menu, self.primary)


import copy
lst = ['a', [1, 2], ['b', [2, 'c']], 'd']
lst_copy = copy.copy(lst)
lst_copy[0] = 'A'
lst_copy[1][1] += 10
lst_copy[2][1][0] *= 4
print(lst)
print(lst_copy)

import copy
lst = ['a', [1, 2], ['b', [2, 'c']], 'd']
lst_deepcopy = copy.deepcopy(lst)
lst_deepcopy[0] = 'A'
lst_deepcopy[1][1] += 10
lst_deepcopy[2][1][0] *= 4
print(lst)
print(lst_deepcopy)


from tkinter.constants import S
import cv2
# import pyautogui
import numpy as np
import tkinter as tk
import datetime
from PIL import Image, ImageTk,ImageGrab
class App:
    def __init__(self):
        # self.path = path
        self.window = tk.Tk()
        self.window.geometry("600x400")
        self.screen = MyFrame()
        self.r = False
        self.out = cv2.VideoWriter()
        self.label = tk.Label(self.window)
        self.label.pack()
        self.delay = 15
        self.path = "/home/danh/Desktop/record-app/app/"
        self.count = 1
    # @staticmethod
    def update(self):
        #print(self.r)
        #print(self.count)
        time = datetime.datetime.now()
        nameVideo = self.path + time.strftime("%d")+"-"+time.strftime("%m")+"-"+time.strftime("%Y")+"-"+time.strftime("%H")+"-"+time.strftime("%f")+".avi"
        frame_width,frame_height,frame,frameResized = self.screen.getframe()
        #print(frame_width,frame_height)
        if self.r == True:
            self.out = cv2.VideoWriter(nameVideo,cv2.VideoWriter_fourcc('M','J','P','G'), 30, (frame_width,frame_height))
            self.r = False
        if self.count % 2 == 0:
            self.out.write(frame)
        photo = ImageTk.PhotoImage(image = Image.fromarray(frameResized))
        self.label.image = photo
        self.label.configure(image=photo)
        self.label.place(x=0,y=0)
        self.window.after(self.delay,self.update)
    def run(self):
        self.createButton()
        self.update()
        # self.createButton()
        self.window.mainloop()
    def createButton(self):
        self.B1 = tk.Button(self.window,text="save",command=self.save)
        self.L1 = tk.Label(self.window,text="Path")
        self.P1 = tk.Entry(self.window)
        self.P1.place(x=70,y=300)
        self.L1.place(x=30,y=300)
        self.B1.place(x=250,y=300)
        if self.r == True:
            self.button = tk.Button(self.window,text="recording",command=self.record)
            self.button.place(x=500,y=0)
        else:
            self.button = tk.Button(self.window,text="record",command=self.record)
            self.button.place(x=500,y=0)
    def save(self):
        self.path = self.P1.get()
        print(self.path)

    def record(self):
        self.count += 1
        self.r = True if self.count % 2 == 0 else False
        #self.rText = "recording" if self.r == True else "record"
class MyFrame:
    def __init__(self):
        pass
    def getframe(self):
        img = ImageGrab.grab()
        frame = np.array(img)
        frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
        frameResized = cv2.resize(frame,(480,270))
        return frame.shape[1],frame.shape[0],frame,frameResized
if __name__ == "__main__":
    a = App()
    a.run()


from collections import defaultdict, deque
def solution(arrows):
    answer = 0
    move= [(0,1), (1,1), (1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1)]
    now = (0,0)

    q = deque()
    q.append(now)
    for arrow in arrows:
        for _ in range(2):
            new = (now[0] + move[arrow][0], now[1]+move[arrow][1])
            q.append(new)
            now=new

    visit = defaultdict(int)
    visit_edge = defaultdict(int)

    now = q.popleft()
    visit[now] = 1

    while q:
        new = q.popleft()
        if visit[new] == 1:
            if visit_edge[now,new] == 0:
                answer+=1
        visit[new] = 1
        visit_edge[now, new] = 1
        visit_edge[new, now] = 1
        now = new
    # print(visit,'\n',visit_edge)

    return answer


# name = input('please enter your name:')

# print('Hello,', name)

# print absolute value an integer:
# int 是将 input 输出的 str 类型转化为数字

b = input('请输入数字：')
a = int(b)
if a >= 100:
    print(a)
else:
    print(-a)


from testil import eq

from dimagi.utils.web import get_ip

def test_get_ip():
    # localhost default
    yield _test_get_ip, {}, '127.0.0.1'
    # garbage default
    yield _test_get_ip, {'REMOTE_ADDR': 'garbage'}, '10.0.0.1'
    # Use x-forwarded-for
    yield _test_get_ip, {'HTTP_X_FORWARDED_FOR': '54.13.132.27'}, '54.13.132.27'
    # Use remote address
    yield _test_get_ip, {'REMOTE_ADDR': '44.44.44.44'}, '44.44.44.44'
    # Use x-forwarded-for over remote address
    yield _test_get_ip, {'HTTP_X_FORWARDED_FOR': '54.13.132.27', 'REMOTE_ADDR': '44.44.44.44'}, '54.13.132.27'
    # Use x-forwarded-for first IP address if many
    yield _test_get_ip, {'HTTP_X_FORWARDED_FOR': '54.13.132.27, 10.200.40.12'}, '54.13.132.27'
    # Use x-forwarded-for first IP address if many (even if no space)
    yield _test_get_ip, {'HTTP_X_FORWARDED_FOR': '54.13.132.27,10.200.40.12'}, '54.13.132.27'

def _test_get_ip(request_meta, expected_value):
    class FakeRequest:
        def __init__(self):
            self.META = request_meta

    eq(get_ip(FakeRequest()), expected_value)