import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.title("Temperature Converter")
root.geometry("900x510")

PRIMARY_COLOR = "Black"
SECONDARY_COLOR = "yellow"
PRIME_SHADE = "#303030"
SECONDARY_SHADE = "#136C38"

def getFont(size = 9, bold = False):
    return ("TkDefaultFont", size, "bold" if bold else "normal")

def validate(P):
    empty = P ==""
    digit = empty or P[-1].isdigit()
    minus = P == "-" and len(P) == 1
    decimal = P.count(".") == 1
    out = empty or digit or minus or decimal
    return out

calFunc = {
    "cf": lambda x: (x * 9/5) + 32,
    "fc": lambda x: (x - 32) * 5/9,
    "ck": lambda x: x + 273.15,
    "kc": lambda x: x - 273.15
}

calFunc["fk"] = lambda x: calFunc["ck"](calFunc["fc"](x))
calFunc["kf"] = lambda x: calFunc["cf"](calFunc["kc"](x))

def convert(fromInpt, fromUnitVar, toUnitVar, resultVar):
    fromU = fromUnitVar.get().lower()
    toU = toUnitVar.get()[0].lower()

    try:
        val = float(fromInpt.get())
    except ValueError:
        resultVar.set("Error !!")
        return

    if fromU == toU:
        res = val
    else:
        res = calFunc[fromU + toU](val)

    resultVar.set(f"{res:.2f}")  # Format the result to 2 decimal places

reg = root.register(validate)

borderFrame = tk.Frame(root, bg = SECONDARY_COLOR, width=450, height=510)
borderFrame.place(x=0, y=0)

leftFrame = tk.Frame(borderFrame, bg = PRIMARY_COLOR, width = 440, height = 500)
leftFrame.place(x=5, y=5)

enterLabel = tk.Label(leftFrame, text="Enter Temperature", bg=PRIMARY_COLOR, fg=SECONDARY_COLOR, font = getFont(16, True))
enterLabel.place(x=30, y=30)

degLabel = tk.Label(leftFrame, text = "Degree", bg=PRIMARY_COLOR, fg=SECONDARY_COLOR, font = getFont(9))
degLabel.place(x = 30, y = 120)

inputEntry = tk.Entry(leftFrame, bg = PRIME_SHADE,fg = "#ffffff", insertbackground ="#ffffff", borderwidth = 5, relief = "flat", validatecommand=(reg, "%P"), validate = "key")
inputEntry.place(x = 30, y = 160, width = 265, height = 42)

unitVar = tk.StringVar(root)
unitVar.set("C")

convertVar = tk.StringVar(root)
convertVar.set("Fahrenheit")

s = ttk.Style()
s.configure("unit.TMenuButton", background = SECONDARY_COLOR)
s.configure("unit.TMenuButton", relief = "flat")

s.configure("covertTo.TMenuButton", relief = "flat")
s.configure("covertTo.TMenuButton", background = PRIME_SHADE)
s.configure("covertTo.TMenuButton", foreground = "#ffffff")
s.configure("covertTo.TMenuButton", width = 320)

unitMenu = ttk.OptionMenu(leftFrame, unitVar, "C","C","F","K")
unitMenu.place(x=300, y=160, width=110, height=42)

convertLabel = tk.Label(leftFrame, text = "Convert To", bg = PRIMARY_COLOR , fg = SECONDARY_COLOR, font = getFont(9))
convertLabel.place(x=30, y=280)

convertMenu = ttk.OptionMenu(leftFrame, convertVar, "Fahrenheit", "Celsius", "Kelvin" )
convertMenu.place(x=30, y=320, width=380, height=42)

convertButton = tk.Button(leftFrame, text="Convert", bg=SECONDARY_COLOR, fg=PRIMARY_COLOR, font=getFont(12), relief="flat", activebackground=SECONDARY_SHADE , bd=0)
convertButton.place(x=150, y=420, width=140, height=40)

rightFrame = tk.Frame(root, bg=SECONDARY_COLOR,width=450,height=510)
rightFrame.place(x=450, y=0)

resultVar = tk.StringVar(root)
resultVar.set("")

resultLabel = tk.Label(rightFrame, textvariable=resultVar, bg=SECONDARY_COLOR, fg=PRIMARY_COLOR, font=getFont(64, True))
resultLabel.place(relx=0.5, rely=0.4901, anchor= tk.CENTER)

convertButton.configure(command= lambda:convert(inputEntry, unitVar,convertVar,resultVar))

root.mainloop()


import math
from utils import *

def bleu(candidate, references, n, weights):

    pn = []
    bp = brevity_penalty(candidate, references)
    for i in range(n):
        pn.append(modified_precision(candidate, references, i + 1))
    if len(weights) > len(pn):
        tmp_weights = []
        for i in range(len(pn)):
            tmp_weights.append(weights[i])
        bleu_result = calculate_bleu(tmp_weights, pn, n, bp)
        return str(bleu_result) + " (warning: the length of weights is bigger than n)"
    elif len(weights) < len(pn):
        tmp_weights = []
        for i in range(len(pn)):
            tmp_weights.append(0)
        for i in range(len(weights)):
            tmp_weights[i] = weights[i]
        bleu_result = calculate_bleu(tmp_weights, pn, n, bp)
        return str(bleu_result) + " (warning: the length of weights is smaller than n)"
    else:
        bleu_result = calculate_bleu(weights, pn, n, bp)
        return str(bleu_result)

#BLEU
def calculate_bleu(weights, pn, n, bp):
    sum_wlogp = 0
    for i in range(n):
        if pn[i] != 0:
            sum_wlogp += float(weights[i]) * math.log(pn[i])
    bleu_result = bp * math.exp(sum_wlogp)
    return bleu_result

#Exact match
def calculate_exactmatch(candidate, reference):
    candidate_words = split_sentence(candidate, 1)
    reference_words = split_sentence(reference, 1)
    count = 0
    total = 0
    for word in reference_words:
        if word in candidate_words:
            count += 1
    for word in candidate_words:
        total += candidate_words[word]

    if total == 0:
        return "0 (warning: length of candidate's words is 0)"
    else:
        return count / total

#F1
def calculate_f1score(candidate, reference):
    candidate_words = split_sentence(candidate, 1)
    reference_words = split_sentence(reference, 1)
    word_set = set()
    for word in candidate_words:
        word_set.add(word)
    for word in reference_words:
        word_set.add(word)

    tp = 0
    fp = 0
    fn = 0
    for word in word_set:
        if word in candidate_words and word in reference_words:
            tp += candidate_words[word]
        elif word in candidate_words and word not in reference_words:
            fp += candidate_words[word]
        elif word not in candidate_words and word in reference_words:
            fn += reference_words[word]

    if len(candidate_words) == 0:
        return "0 (warning: length of candidate's words is 0)"
    elif len(reference_words) == 0:
        return 0
    else:
        precision = tp / (tp + fp)
        recall = tp / (tp + fn)
        if tp == 0:
            return 0
        else:
            return 2 * precision * recall / (precision + recall)


import time
import threading

from PyQt5.QtCore import QCoreApplication, QTimer, Qt

from pcr.constants.constant import Command, State, StateOper

from pcr.hid import hid_controller as hid
import pcr.hid.tx_action as TxAction
import pcr.hid.rx_action as RxAction

from pcr.task import PCRTask

# Timer Loop time definitions
TIMER_DURATION = 100 # 100ms

class PCRTimer(QTimer):

    def __init__(self):
        super().__init__()
        self.task = PCRTask.instance()

        self.task.mainUI.frame_camctrl.init_display()

        # Must be use precise timer
        self.setTimerType(Qt.TimerType.PreciseTimer)
        self.setInterval(TIMER_DURATION)
        self.timeout.connect(self.run)

        self.cnt = 0

    def read_buffer(self):
        raw_data = hid.read()

        if raw_data:
            RxAction.set_buffer(raw_data) #Set info
            self.task.state = RxAction.rx_buffer['State'] #Set state
        else: #if get rx_buffer nothing
            pass

    def send_buffer(self):
        command = self.task.command

        if command == Command.NOP:
            tx_buffer = TxAction.make_nop()

        elif command == Command.TASK_WRITE:
            tx_buffer = TxAction.make_taskWrite(self.task.protocol[self.task.action_num],
                                                        self.task.preheat,
                                                        self.task.action_num)
            print(f"--self.task.preheat : {self.task.preheat}")
        elif command == Command.TASK_END:
            tx_buffer = TxAction.make_taskEnd()

        elif command == Command.GO:
            tx_buffer = TxAction.make_go()

        elif command == Command.STOP:
            tx_buffer = TxAction.make_stop()

        hid.write(tx_buffer)

    def run(self):
        # read buffer
        self.read_buffer()

        # check status
        self.task.check_status()

        # calc temperature
        self.task.calc_temp()

        # line task
        self.task.line_task()

        # calc time
        self.task.calc_time()

        # Camera shot check
        self.task.check_shot()

        # send buffer
        self.send_buffer()


import ast
import csv
import os
import random
import re

import pygame
import numpy as np

from config import Conf, GS
from controls import Controllers
from variables import Gen, ExitCtr, Frames, Sprites, DoFlag
from sim_objects import Robot, Ball, Goal, Score, SysInfo
from config import FrameStepReturn as fsr
X = Conf.X
Y = Conf.Y

class SimMaster:
    def __init__(self, index=-1, algorithm=GS.TYPE_NET):
        self.index = index  # Used to denote process instance
        self.initialized = False  # Used to determine if first call or not

        self.robots = []  # To be used later to control multiple robots
        self.robot = None  # Used to control first robot
        self.balls = []
        self.ball = None
        self.goals = []

        self.controller = None
        self.clock = None
        self.score = None
        self.sys_info = None
        self.rect = None
        self.num_reset = -1

        self.start_robot = None
        self.start_ball = None

        self.robot_xy = []
        self.ball_xy = []
        self.recorded_times = []
        self.pos_offset = Conf.RBT_SIZE[0]

        # Record information for later benchmarking neural net against "math"
        self.game_records = [
            (
                GS.ROBOT_START, GS.BALL_START,
                GS.TIME_TO_SCORE, GS.SIDE_SCORE, GS.METHOD
            )
        ]
        self.good_data_file = f"{Conf.CSV_FOLDER}/good_{algorithm}{index}.csv"
        self.bad_data_file = f"{Conf.CSV_FOLDER}/bad_{algorithm}{index}.csv"

        self.net = {
            Conf.DIRECTION: "",
            Conf.THETA: 0,
            Conf.DIST: 0,
            Conf.KICK: 0,
            Conf.CONT: 0,
        }
        self.algorithm = algorithm
        self.ball_bounce_x = 0
        self.is_goal_scored = False
        self.is_accurate_sent = False

        if len(self.robot_xy) != len(self.ball_xy):
            raise IndexError("None matching data set for ball and robot pos")

    def _init(self):
        if self.initialized:  # If already initialize exit
            return
        self.initialized = True
        pygame.init()

        # Set up simulation window
        height = Conf.HEIGHT + Conf.PADDING
        width = Conf.WIDTH + Conf.PADDING
        Gen.screen = pygame.display.set_mode((width, height))
        Gen.screen.fill(Conf.WHITE)

        # Field border rectangle dimensions
        self.rect = (Conf.ORIGIN[X], Conf.ORIGIN[Y], Conf.WIDTH, Conf.HEIGHT)

        # Create all simulation objects
        self.robots = [Robot(side=Conf.LEFT)]
        self.robot = self.robots[0]
        self.balls = [Ball(master=self)]
        self.ball = self.balls[0]
        self.goals = [Goal(Conf.LEFT), Goal(Conf.RIGHT)]
        self.score = Score()
        self.sys_info = SysInfo(self)
        self.controller = Controllers(self.robot)

        # Set up some variables for neural net step function
        if self.robot.side == Conf.LEFT:
            self.ball_bounce_x = Conf.FIELD_RIGHT - self.ball.rect.width
        else:
            self.ball_bounce_x = Conf.ORIGIN[X] + self.ball.rect.width

        self.rest_positions()
        # Create clock for consistent loop intervals
        self.clock = pygame.time.Clock()

    def start_man_calc(self):  # manual and calculated
        self._init()
        while ExitCtr.gen:
            # Control robot
            self.controller.manual_control()
            if DoFlag.auto_calc:
                self.controller.calculated_control()

            # Update game state
            Sprites.every.update()
            Frames.update()

            if DoFlag.update_frame:
                # Control loop intervals
                self.clock.tick(Conf.FPS)  # Comment out to remove fps limit

                # Update drawing if required
                Gen.screen.fill(Conf.WHITE)  # Reset screen for fresh drawings

                # Draw field borders
                pygame.draw.rect(Gen.screen, Conf.BLACK, self.rect, 1)

                # Draw everything and update the display
                Sprites.every.draw(Gen.screen)
                pygame.display.update()

        self.exit()

    def frame_step(self, action):
        """
        param:
        action --> tuple(
            direction --> 0 (left), 1 (right)
            angle --> 1 - 12 (0 to 180/angle_increment )
            distance --> 0 to 60 (0 to 300/move_dist)
            kick --> 0 (don't kick) or 1 (kick)
            continue --> 0 (don't continue) or 1 (continue)
        )

        return:
        x --> 0 to 600 (x coordinate)
        y --> 0 to 400 (y coordinate)

        # Ball relative conditions
        ball_flag --> 0 (not seen) or 1 (seen)
        ball_theta --> 0 to 360/angle_increment
        ball_dist --> 0 to 600/move_dist

        # Own goal relative conditions
        own_goal_theta --> 0 to 360/angle_increment
        own_goal_dist --> 0 to 600/move_dist

        # Opponent goal conditions
        opp_goal_theta --> 0 to 360/angle_increment
        opp_goal_dist --> 0 to 600/move_dist

        # Kick results given 0 or 1 for only one frame
        is_kick_success --> 0 (null) or 2 (miss) or 1 (hit)
        is_kick_accurate --> 0 (null) or 2 (bad miss) or 1 (near miss)

        # State flags
        is_kicking --> 0 (not kicking) or 1 (is kicking)
        is_moving --> 0 (not moving) or 1 (is moving)
        is_ball_moved -- > 0 (not moved recently) or 1 (moved recently)
        is_goal_scored --> 2 (own goal scored) 0 (not scored) or 1 (scored)

        time --> time since start (calculated based on frames)
        """
        # Attempt to instantiate which will only be done if not done already
        self._init()

        NULL = 0
        STATE1 = 1
        STATE2 = 2

        # Reset goal to not scored
        self._goal_scored(reset=True)

        # Get action commands
        direction, theta, dist, kick, cont = action
        theta *= Conf.DIR_OFFSET
        dist *= Conf.MOVE_DIST
        if direction == 1:
            direction = Conf.RIGHT
        elif direction == 0:
            direction = Conf.LEFT
        else:
            raise ValueError(
                f"{direction} is not a valid option. Must be 0 or 1"
            )

        # Create return away
        ret_val = np.zeros(fsr.NUM_VAL)
        ret_val[fsr.ACT_DIR] = action[0]
        ret_val[fsr.ACT_THETA] = action[1]
        ret_val[fsr.ACT_DIST] = action[2]
        ret_val[fsr.ACT_KICK] = action[3]
        ret_val[fsr.ACT_CONT] = action[4]

        # Get vector positions (relative positions)
        to_ball_s, _, _ = self.controller.get_vec()
        ball_dist, ball_theta = to_ball_s.as_polar()

        if not cont:
            # Validate data
            if ret_val[fsr.ACT_THETA] > 360/Conf.DIR_OFFSET:
                print(
                    f"Warning {ret_val[fsr.ACT_THETA]} out of range "
                    f"{360/Conf.DIR_OFFSET}"
                )
            if ret_val[fsr.ACT_DIST] > Conf.WIDTH/Conf.MOVE_DIST:
                print(
                    f"Warning {ret_val[fsr.ACT_DIST]} out of range "
                    f"{Conf.WIDTH/Conf.MOVE_DIST}"
                )
            self.net[Conf.DIRECTION] = direction
            self.net[Conf.THETA] = theta * Conf.DIR_OFFSET
            self.net[Conf.DIST] = dist * Conf.MOVE_DIST
            self.net[Conf.KICK] = kick

        # In case no kick was performed set to null value
        ret_val[fsr.IS_KICK_ACCURATE] = ret_val[fsr.IS_KICK_SUCCESS] = NULL
        if Frames.time() - Gen.last_kick_time < Conf.KICK_COOLDOWN:
            ret_val[fsr.IS_KICKING] = 1
        elif self.net[Conf.KICK] == 1:
            is_kicked = self.robot.kick()
            self.net[Conf.KICK] = False
            Gen.last_kick_time = Frames.time()

            # If within kick range
            if is_kicked:
                ret_val[fsr.IS_KICK_SUCCESS] = STATE1
            else:
                ret_val[fsr.IS_KICK_SUCCESS] = STATE2

        elif self.net[Conf.THETA] > 0:
            self.robot.move(self.net[Conf.DIRECTION])
            self.net[Conf.THETA] -= Conf.DIR_OFFSET
        elif self.net[Conf.DIST] > 0:
            self.robot.move(Conf.FORWARD)
            self.net[Conf.DIST] -= Conf.MOVE_DIST

        # Update game state
        Sprites.every.update()
        Frames.update()

        # Update drawing if required
        if DoFlag.update_frame:
            self.clock.tick(Conf.FPS)  # Regulate FPS if desired
            Gen.screen.fill(Conf.WHITE)  # Reset screen for fresh drawings

            # Draw field borders
            pygame.draw.rect(Gen.screen, Conf.BLACK, self.rect, 1)

            # Draw everything and update the display
            Sprites.every.draw(Gen.screen)
            pygame.display.update()

        # Update return Values
        to_ball, to_goal, to_own_goal = self.controller.get_vec()
        ret_val[fsr.BALL_DIST], ret_val[fsr.BALL_THETA] = to_ball.as_polar()
        ret_val[fsr.OPP_GOAL_DIST], ret_val[fsr.OPP_GOAL_THETA] = (
            to_goal.as_polar()
        )
        ret_val[fsr.OWN_GOAL_DIST], ret_val[fsr.OWN_GOAL_THETA] = (
            to_own_goal.as_polar()
        )
        if self.robot.move_angle < -90 and ball_theta > 90:  # Edge case
            if self.robot.move_angle + 360 - ball_theta <= Conf.HALF_VIS_THETA:
                ret_val[fsr.BALL_FLAG] = STATE1
        elif self.robot.move_angle > 90 and ball_theta < -90:  # Edge case
            if ball_theta + 360 - self.robot.move_angle <= Conf.HALF_VIS_THETA:
                ret_val[fsr.BALL_FLAG] = STATE1
        elif abs(self.robot.move_angle - ball_theta) <= Conf.HALF_VIS_THETA:
            # If within field of view
            ret_val[fsr.BALL_FLAG] = STATE1

        # If ball_start_pos != current_ball_pos then ball moving
        if to_ball != to_ball_s:
            ret_val[fsr.IS_BALL_MOVED] = STATE1

        # If still has angle change or distance change then moving
        if self.net[Conf.THETA] > 0 or self.net[Conf.DIST] > 0:
            ret_val[fsr.IS_MOVING] = STATE1

        # Check if goal scored this frame
        if self.is_goal_scored:
            if (  # If close to opponent goal then scored and accurate
                    self.ball.side == self.robot.side
            ):
                ret_val[fsr.IS_GOAL_SCORED] = STATE1
                ret_val[fsr.IS_KICK_ACCURATE] = STATE1
            else:  # If not close to target then own goal
                ret_val[fsr.IS_GOAL_SCORED] = STATE2
                ret_val[fsr.IS_KICK_ACCURATE] = NULL
        elif (  # if ball in wall bounce x location  check next condition
                # If ball is within range of y value
                self.controller.goal_cen.y
                - 1 * self.controller.goal.rect.height
                < self.balls[0].rect.centery <
                self.controller.goal_cen.y
                + 1 * self.controller.goal.rect.height
        ):
            if (  # If hit the wall close to the goal
                    self.ball.rect.centerx > self.ball_bounce_x
                    and self.robot.side == Conf.LEFT
            ):
                if not self.is_accurate_sent:
                    ret_val[fsr.IS_KICK_ACCURATE] = STATE1
                    self.is_accurate_sent = True
            elif (
                    self.ball.rect.centerx < self.ball_bounce_x
                    and self.robot.side == Conf.RIGHT
            ):
                if not self.is_accurate_sent:
                    ret_val[fsr.IS_KICK_ACCURATE] = STATE1
                    self.is_accurate_sent = True
            else:  # If not against respective wall accuracy was not sent
                self.is_accurate_sent = False
        else:
            if (
                    self.ball.rect.centerx > self.ball_bounce_x
                    and self.robot.side == Conf.LEFT
            ):
                if not self.is_accurate_sent:
                    ret_val[fsr.IS_KICK_ACCURATE] = STATE2
                    self.is_accurate_sent = True
            elif (
                    self.ball.rect.centerx < self.ball_bounce_x
                    and self.robot.side == Conf.RIGHT
            ):
                if not self.is_accurate_sent:
                    ret_val[fsr.IS_KICK_ACCURATE] = STATE2
                    self.is_accurate_sent = True
            else:
                self.is_accurate_sent = False

        ret_val[fsr.X] = self.robot.rect.centerx
        ret_val[fsr.Y] = self.robot.rect.centery
        ret_val[fsr.TIME] = Frames.time()
        return ret_val

    def score_goal(self, score_time, score_side):
        self._goal_scored()
        self.score.update_score(score_side)
        record = (
            self.start_robot,
            self.start_ball,
            score_time,
            score_side,
            self.algorithm
        )
        self.game_records.append(record)
        self.rest_positions()

    def rest_positions(self):
        self.num_reset += 1
        for robot in Sprites.robots:
            if self.num_reset < len(self.robot_xy):
                robot.rect.centerx, robot.rect.centery = (
                    self.robot_xy[self.num_reset]
                )
            else:  # get random pos
                # Random y position within offset
                robot.rect.centery = random.randint(
                    self.pos_offset + Conf.ORIGIN[Y],
                    Conf.FIELD_BOT - self.pos_offset
                )
                # Random x pos based on side
                if robot.side == Conf.LEFT:
                    robot.rect.centerx = random.randint(
                        self.pos_offset + Conf.ORIGIN[X], Conf.CENTER[X]
                    )
                    robot.direction_angle = 0
                    robot.place_dir_arrow()
                else:
                    robot.rect.centerx = random.randint(
                        Conf.CENTER[X], Conf.FIELD_RIGHT - self.pos_offset
                    )
                    robot.direction_angle = 180
                    robot.place_dir_arrow()
            # Ensure robots always start facing same direction
            if robot.side == Conf.LEFT:
                robot.direction_angle = 0
                robot.place_dir_arrow()
            else:
                robot.direction_angle = 180
                robot.place_dir_arrow()
            robot.check_bounds()

        for ball in Sprites.balls:
            if self.num_reset < len(self.ball_xy):
                # For each goal set the xy position
                ball.rect.centerx, ball.rect.centery = (
                    self.ball_xy[self.num_reset]
                )
            else:
                # Get random position
                ball.rect.centerx = random.randint(
                    self.pos_offset + Conf.ORIGIN[X],
                    Conf.FIELD_RIGHT - self.pos_offset
                )
                ball.rect.centery = random.randint(
                    self.pos_offset + Conf.ORIGIN[Y],
                    Conf.FIELD_BOT - self.pos_offset
                )
            ball.move_dist = 0
        self.start_robot = (self.robot.rect.centerx, self.robot.rect.centery)
        self.start_ball = (
            self.balls[0].rect.centerx, self.balls[0].rect.centery
        )

    def _goal_scored(self, reset=False):
        if reset:
            self.is_goal_scored = False
        else:
            self.is_goal_scored = True

    def load(self, algorithm=GS.TYPE_MAN):
        if algorithm == GS.TYPE_NONE:
            print("NOTHING DONE")
            return
        if self.algorithm == algorithm:
            print(
                "WARNING YOU ARE LOADING THE SAME TYPE OF ALGORITHM AS TO THE"
                " ONE YOU WILL BE SAVING"
            )
        for root, dirs, files in os.walk(Conf.CSV_FOLDER):
            for file in files:
                if f"good_{algorithm}" in file:
                    # index_loc = re.search(r"\d+.", file).span()
                    with open(f"{Conf.CSV_FOLDER}/{file}") as f:
                        data = list(csv.reader(f))
                    robot_xy = data[0].index(GS.ROBOT_START)
                    ball_xy = data[0].index(GS.BALL_START)
                    time_to_score = data[0].index(GS.TIME_TO_SCORE)
                    for record in data[1:]:
                        self.robot_xy.append(
                            ast.literal_eval(record[robot_xy])
                        )
                        self.ball_xy.append(ast.literal_eval(record[ball_xy]))
                        self.recorded_times.append(
                            ast.literal_eval(record[time_to_score])
                        )
        num_records = len(self.robot_xy)
        rec_per_proc = num_records // Conf.NUM_PROC
        if self.index >= 0:
            if self.index == 0:
                self.robot_xy = self.robot_xy[:rec_per_proc]
                self.ball_xy = self.ball_xy[:rec_per_proc]
                self.recorded_times = self.recorded_times[:rec_per_proc]
            elif self.index+1 == Conf.NUM_PROC:
                i = self.index
                self.robot_xy = self.robot_xy[rec_per_proc*i:]
                self.ball_xy = self.ball_xy[rec_per_proc*i:]
                self.recorded_times = self.recorded_times[rec_per_proc*i:]
            else:
                i = self.index
                j = self.index + 1
                self.robot_xy = self.robot_xy[rec_per_proc*i:rec_per_proc*j]
                self.ball_xy = self.ball_xy[rec_per_proc*i:rec_per_proc*j]
                self.recorded_times = self.recorded_times[
                                        rec_per_proc*i:rec_per_proc*j
                                      ]

    def save(self):
        if self.algorithm == GS.TYPE_NONE:
            print("No data type so not saving")
        delete_index = []
        bad_data = [self.game_records[0]]
        side_index = bad_data[0].index(GS.SIDE_SCORE)
        index = 0
        for record in self.game_records[1:]:
            index += 1
            if record[side_index] != self.robot.side:
                delete_index.append(index)
        delete_index.reverse()
        for index in delete_index:
            bad_data.append(self.game_records.pop(index))

        good_data = self.game_records
        if not os.path.isdir(Conf.CSV_FOLDER):
            os.mkdir(Conf.CSV_FOLDER)
        elif os.path.isfile(self.good_data_file):
            if len(good_data) > 1:
                good_data = self.game_records[1:]
            else:
                good_data = []
        if os.path.isfile(self.bad_data_file):
            bad_data.pop()

        with open(self.good_data_file, 'a') as file:
            writer = csv.writer(file)
            writer.writerows(good_data)
        with open(self.bad_data_file, 'a') as file:
            writer = csv.writer(file)
            writer.writerows(bad_data)

    def exit(self):
        if DoFlag.save_data:
            self.save()
        pygame.quit()


# -*- coding: utf-8 -*-
from __future__ import absolute_import
import base64

__all__ = ['clean_string', "ESRange", "ESRangeOp", "string_b64encode", "string_b64decode"]

def string_b64encode(s):
    """
    This function is useful to convert a string to a valid id to be used in ES.
    You can use it to generate an ID for urls or some texts
    """
    return base64.urlsafe_b64encode(s).strip('=')

def string_b64decode(s):
    return base64.urlsafe_b64decode(s + '=' * (len(s) % 4))

# Characters that are part of Lucene query syntax must be stripped
# from user input: + - && || ! ( ) { } [ ] ^ " ~ * ? : \
# See: http://lucene.apache.org/java/3_0_2/queryparsersyntax.html#Escaping
SPECIAL_CHARS = [33, 34, 38, 40, 41, 42, 45, 58, 63, 91, 92, 93, 94, 123, 124, 125, 126]
UNI_SPECIAL_CHARS = dict((c, None) for c in SPECIAL_CHARS)
STR_SPECIAL_CHARS = ''.join([chr(c) for c in SPECIAL_CHARS])

class EqualityComparableUsingAttributeDictionary(object):
    """
    Instances of classes inheriting from this class can be compared
    using their attribute dictionary (__dict__). See GitHub issue
    128 and http://stackoverflow.com/q/390640
    """

    def __eq__(self, other):
        if type(other) is type(self):
            return self.__dict__ == other.__dict__
        return False

    def __ne__(self, other):
        return not self == other

class ESRange(EqualityComparableUsingAttributeDictionary):
    def __init__(self, field, from_value=None, to_value=None, include_lower=None,
                 include_upper=None, boost=None, **kwargs):
        self.field = field
        self.from_value = from_value
        self.to_value = to_value
        self.include_lower = include_lower
        self.include_upper = include_upper
        self.boost = boost

    def serialize(self):
        filters = {}
        if self.from_value is not None:
            filters['from'] = self.from_value
        if self.to_value is not None:
            filters['to'] = self.to_value
        if self.include_lower is not None:
            filters['include_lower'] = self.include_lower
        if self.include_upper is not None:
            filters['include_upper'] = self.include_upper
        if self.boost is not None:
            filters['boost'] = self.boost
        return self.field, filters

class ESRangeOp(ESRange):
    def __init__(self, field, op, value, boost=None):
        from_value = to_value = include_lower = include_upper = None
        if op == "gt":
            from_value = value
            include_lower = False
        elif op == "gte":
            from_value = value
            include_lower = True
        if op == "lt":
            to_value = value
            include_upper = False
        elif op == "lte":
            to_value = value
            include_upper = True
        super(ESRangeOp, self).__init__(field, from_value, to_value,
            include_lower, include_upper, boost)

def clean_string(text):
    """
    Remove Lucene reserved characters from query string
    """
    if isinstance(text, unicode):
        return text.translate(UNI_SPECIAL_CHARS).strip()
    return text.translate(None, STR_SPECIAL_CHARS).strip()

def keys_to_string(data):
    """
    Function to convert all the unicode keys in string keys
    """
    if isinstance(data, dict):
        for key in list(data.keys()):
            if isinstance(key, unicode):
                value = data[key]
                val = keys_to_string(value)
                del data[key]
                data[key.encode("utf8", "ignore")] = val
    return data


# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy

from fets_paper_figures import my_violin_plot, prep_plots, other_font_size
from fets_paper_figures import save_at_dpi, dice_or_jaccard

def main(data_pardir, output_pardir, jaccard ):

    BINARY_DICE='Tumor Sub-Compartment'

    new_metric_names, metrics, region_label_dict, IN_DF_DICE_OR_JACCARD, DICE_OR_JACCARD = dice_or_jaccard(jaccard)

    final_consensus_val_df = pd.read_csv(os.path.join(data_pardir, 'final_consensus_val_df.csv'))
    init_val_df = pd.read_csv(os.path.join(data_pardir, 'init_val_df.csv'))

    percent_increases = {}

    for binary_dice in ['Average', 'ET', 'TC', 'WT']:
        init_score = init_val_df.groupby([BINARY_DICE]).mean().loc[binary_dice][IN_DF_DICE_OR_JACCARD]
        con_score = final_consensus_val_df.groupby([BINARY_DICE]).mean().loc[binary_dice][IN_DF_DICE_OR_JACCARD]
        percent_increases[binary_dice] = 100 * (con_score/init_score - 1)

    prep_plots()

    temp_df = final_consensus_val_df.sort_values(by=BINARY_DICE)

    temp_df = temp_df.replace(to_replace='binary_' + IN_DF_DICE_OR_JACCARD + '_ET', value='ET')
    temp_df = temp_df.replace(to_replace='binary_' + IN_DF_DICE_OR_JACCARD + '_TC', value='TC')
    temp_df = temp_df.replace(to_replace='binary_' + IN_DF_DICE_OR_JACCARD + '_WT', value='WT')

    temp_df = temp_df.append(init_val_df)

    temp_df = temp_df.sort_values(BINARY_DICE)

    temp_df = temp_df.replace(to_replace='initial', value='Public Initial Model')
    temp_df = temp_df.replace(to_replace='singlet_0', value='Full Federation Consensus').sort_values(by=BINARY_DICE)

    my_pal = [(0.00392156862745098, 0.45098039215686275, 0.6980392156862745),
            (0.8705882352941177, 0.5607843137254902, 0.0196078431372549)]

    box_shifts={0: 0.1273, 1: -0.1273}
    meanline_shifts = {0: 0.5, 1: -0.5 }

    # getting p values for comparisons
    pvalues = {}
    for metric in temp_df[BINARY_DICE].unique():
        samples_1 = temp_df[(temp_df["Model Type"] == "Public Initial Model") & (temp_df[BINARY_DICE] == metric)][IN_DF_DICE_OR_JACCARD].values
        samples_2 = temp_df[(temp_df["Model Type"] == 'Full Federation Consensus') & (temp_df[BINARY_DICE] == metric)][IN_DF_DICE_OR_JACCARD].values
        if len(samples_1) != len(samples_2):
            print("lengths of samples_1 and samples_2 are: ", len(samples_1), len(samples_2))
        stat, pvalue = scipy.stats.wilcoxon(samples_1, samples_2)
        m1, m2 = np.mean(samples_1), np.mean(samples_2)
        sd1, sd2 = np.std(samples_1), np.std(samples_2)
        pvalues[metric] = pvalue

    temp_df = temp_df.rename({IN_DF_DICE_OR_JACCARD: DICE_OR_JACCARD}, axis=1)

    ax = my_violin_plot(x_column=BINARY_DICE,
                    y_column=DICE_OR_JACCARD,
                    data=temp_df,
                    hue='Model Type',
                    hatch='/',
                    mean_marker_size=20,
                    palette=my_pal,
                    sorting_key= lambda x: x.apply(lambda x: {"Public Initial Model": 0,
                                                        "Full Federation Consensus": 1}[x]),
                    order=['Average', 'ET', 'TC', 'WT'],
                    shrink_factor=0.3,
                    group_size=2,
                    box_width=0.3,
                    shifts=box_shifts)

    ax.set(ylim=(0, 1.16))

    ax.legend(bbox_to_anchor= (.53, .10))

    ax.set_title("Out-Of-Sample Data")

    meanline_length = 0.35

    if jaccard:

        vert_text_loc = {'Average': 0.53, 'ET': 0.51, 'TC': 0.46, 'WT': 0.632}

        hor_text_loc = {'Average': 0.107, 'ET': 0.34, 'TC': 0.585, 'WT': 0.83}

        hor_arrow_loc = {'Average': 0.0, 'ET': 1.0, 'TC': 2.0, 'WT': 3.0}

        arrow_length = {'Average': 0.13, 'ET': 0.103, 'TC': 0.15, 'WT': 0.11}

        vert_arrow_loc = {'Average': 0.555, 'ET': 0.53, 'TC': 0.48, 'WT': 0.65}

        vert_meanline_loc = {'Average': {0: 0.631, 1: 0.7},
                            'ET': {0: 0.598, 1: 0.7},
                            'TC': {0: 0.568, 1: 0.7},
                            'WT': {0: 0.726, 1: 0.8}}
        hor_meanline_loc = {'Average': {0: (-0.73 + meanline_length), 1: (-0.3 + meanline_length)},
                            'ET': {0: 0.8, 1: 1.2},
                            'TC': {0: 1.8, 1: 2.2},
                            'WT': {0: 2.8, 1: 3.2}}

    else:

        vert_text_loc = {'Average': 0.58, 'ET': 0.54, 'TC': 0.53, 'WT': 0.675}

        hor_text_loc = {'Average': 0.095, 'ET': 0.34, 'TC': 0.58, 'WT': 0.82}

        hor_arrow_loc = {'Average': 0.0, 'ET': 1.0, 'TC': 2.0, 'WT': 3.0}

        arrow_length = {'Average': 0.118, 'ET': 0.083, 'TC': 0.144, 'WT': 0.11}

        vert_arrow_loc = {'Average': 0.625, 'ET': 0.598, 'TC': 0.568, 'WT': 0.726}

        vert_meanline_loc = {'Average': {0: 0.631, 1: 0.7},
                            'ET': {0: 0.598, 1: 0.7},
                            'TC': {0: 0.568, 1: 0.7},
                            'WT': {0: 0.726, 1: 0.8}}
        hor_meanline_loc = {'Average': {0: (-0.73 + meanline_length), 1: (-0.3 + meanline_length)},
                            'ET': {0: 0.8, 1: 1.2},
                            'TC': {0: 1.8, 1: 2.2},
                            'WT': {0: 2.8, 1: 3.2}}

    for binary_dice in ['Average', 'ET', 'TC', 'WT']:
        text_insert = f'{percent_increases[binary_dice]:.0f}%\nGain'
        ax.text(hor_text_loc[binary_dice],
                vert_text_loc[binary_dice],
                text_insert,
                transform=ax.transAxes,
                fontsize=other_font_size,
                color='red',
                verticalalignment='top')

        plt.arrow(x=hor_arrow_loc[binary_dice],
                y=vert_arrow_loc[binary_dice],
                dx=0,
                dy=arrow_length[binary_dice],
                length_includes_head=True,
                head_width=0.04,
                head_length=0.03,
                color='red')

        ax.set_ylim(top=1.0, bottom=0.0)

    handles, labels = ax.get_legend_handles_labels()
    cut = int(len(handles)/2)
    ax.legend(handles=handles[:cut] + cut*[None], labels=labels[:cut]+cut*[None], loc='lower left')

    fpath = os.path.join(output_pardir, 'init_scores_versus_consensus_against_holdout_violin' + DICE_OR_JACCARD + '.pdf')

    print(f"\nThe p-values for each tumor region of the difference in the means between the public initial model and the final consensus are: {pvalues}\n\n")
    print("Saving output file at: ", fpath)
    save_at_dpi(fpath=fpath)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_pardir', '-dp', type=str, help='Absolute path to the data parent directory.', default="../")
    parser.add_argument('--output_pardir', '-op', type=str, help='Absolute path to the output parent directory.', default="../../output")
    parser.add_argument('--jaccard', '-j', action='store_true', help='Whether or not to convert DICE scores to Jaccard index.')
    args = parser.parse_args()
    main(**vars(args))


# # 6.4 Sequence processing with convnets
# # (https://nbviewer.jupyter.org/github/fchollet/deep-learning-with-python-notebooks/
# # blob/master/6.4-sequence-processing-with-convnets.ipynb)

import os

import numpy as np
import pandas as pd
from tensorflow.keras import layers
from tensorflow.keras.datasets import imdb
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing import sequential

from ivory.utils.path import cache_dir
from ivory.utils.keras.history import plot_history

# ### Implementing a 1D convnet
max_features = 10000  # number of words to consider as features
max_len = 500  # cut texts after this number of words

print("Loading data...")
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), "train sequences")
print(len(x_test), "test sequences")

print("Pad sequences (samples x time)")
x_train = sequence.pad_sequences(x_train, maxlen=max_len)
x_test = sequence.pad_sequences(x_test, maxlen=max_len)
print("x_train shape:", x_train.shape)
print("x_test shape:", x_test.shape)

# -
model = Sequential()
model.add(layers.Embedding(max_features, 128, input_length=max_len))
model.add(layers.Conv1D(32, 7, activation="relu"))
model.add(layers.MaxPooling1D(5))
model.add(layers.Conv1D(32, 7, activation="relu"))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(1))

model.summary()

# -
model.compile(optimizer=RMSprop(lr=1e-4), loss="binary_crossentropy", metrics=["acc"])
history = model.fit(x_train, y_train, epochs=10, batch_size=128, validation_split=0.2)

# -
plot_history(history, "acc") | plot_history(history, "loss")

# ### Combining CNNs and RNNs to process long sequences

base_dir = cache_dir("keras/ch6/data/weather/zip")
dfs = []
for name in os.listdir(os.path.join(base_dir)):
    df = pd.read_csv(os.path.join(base_dir, name), encoding="cp932")
    dfs.append(df)
df = pd.concat(dfs)
float_data = df.iloc[:, 1:].values
mean = float_data[:200000].mean(axis=0)
float_data -= mean
std = float_data[:200000].std(axis=0)
float_data /= std

def generator(
    data, lookback, delay, min_index, max_index, shuffle=False, batch_size=128, step=6
):
    if max_index is None:
        max_index = len(data) - delay - 1
    i = min_index + lookback
    while 1:
        if shuffle:
            rows = np.random.randint(min_index + lookback, max_index, size=batch_size)
        else:
            if i + batch_size >= max_index:
                i = min_index + lookback
            rows = np.arange(i, min(i + batch_size, max_index))
            i += len(rows)

        samples = np.zeros((len(rows), lookback // step, data.shape[-1]))
        targets = np.zeros((len(rows),))
        for j, row in enumerate(rows):
            indices = range(rows[j] - lookback, rows[j], step)
            samples[j] = data[indices]
            targets[j] = data[rows[j] + delay][1]
        yield samples, targets

lookback = 1440
step = 6
delay = 144
batch_size = 128

train_gen = generator(
    float_data,
    lookback=lookback,
    delay=delay,
    min_index=0,
    max_index=200000,
    shuffle=True,
    step=step,
    batch_size=batch_size,
)
val_gen = generator(
    float_data,
    lookback=lookback,
    delay=delay,
    min_index=200001,
    max_index=300000,
    step=step,
    batch_size=batch_size,
)
test_gen = generator(
    float_data,
    lookback=lookback,
    delay=delay,
    min_index=300001,
    max_index=None,
    step=step,
    batch_size=batch_size,
)

# !This is how many steps to draw from `val_gen`
# !in order to see the whole validation set:
val_steps = (300000 - 200001 - lookback) // batch_size

# !This is how many steps to draw from `test_gen`
# !in order to see the whole test set:
test_steps = (len(float_data) - 300001 - lookback) // batch_size

# -
model = Sequential()
model.add(
    layers.Conv1D(32, 5, activation="relu", input_shape=(None, float_data.shape[-1]))
)
model.add(layers.MaxPooling1D(3))
model.add(layers.Conv1D(32, 5, activation="relu"))
model.add(layers.MaxPooling1D(3))
model.add(layers.Conv1D(32, 5, activation="relu"))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(1))

model.compile(optimizer=RMSprop(), loss="mae")
history = model.fit_generator(
    train_gen,
    steps_per_epoch=500,
    epochs=20,
    validation_data=val_gen,
    validation_steps=val_steps,
)

# -
plot_history(history, "loss")

# -
# !This was previously set to 6 (one point per hour).
# !Now 3 (one point per 30 min).
step = 3
lookback = 720  # Unchanged
delay = 144  # Unchanged

train_gen = generator(
    float_data,
    lookback=lookback,
    delay=delay,
    min_index=0,
    max_index=200000,
    shuffle=True,
    step=step,
)
val_gen = generator(
    float_data,
    lookback=lookback,
    delay=delay,
    min_index=200001,
    max_index=300000,
    step=step,
)
test_gen = generator(
    float_data,
    lookback=lookback,
    delay=delay,
    min_index=300001,
    max_index=None,
    step=step,
)
val_steps = (300000 - 200001 - lookback) // 128
test_steps = (len(float_data) - 300001 - lookback) // 128
# -
model = Sequential()
model.add(
    layers.Conv1D(32, 5, activation="relu", input_shape=(None, float_data.shape[-1]))
)
model.add(layers.MaxPooling1D(3))
model.add(layers.Conv1D(32, 5, activation="relu"))
model.add(layers.GRU(32, dropout=0.1, recurrent_dropout=0.5))
model.add(layers.Dense(1))

model.summary()

# -
model.compile(optimizer=RMSprop(), loss="mae")
history = model.fit_generator(
    train_gen,
    steps_per_epoch=500,
    epochs=20,
    validation_data=val_gen,
    validation_steps=val_steps,
)

# -
plot_history(history, "loss")


# -*- coding: utf8 -*

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import InvalidSelectorException

from SelenTest import SelenTest
from selen_logging import log_save

def get_new_test(name:str) -> object:
    test = SelenTest(name, webdriver)
    log_save(test, test.print_info(), "info")
    return test

def start_browser(test:object, browser:str):
    if (browser == "chrome"):
        test.browser = test.webdriver.Chrome()
    elif (browser == "firefox"):
        test.browser = test.webdriver.Firefox()
    test.browser.set_page_load_timeout(30)
    log_save(test, "Start " + browser, "info")

def open_url(test:object, url:str):
    test.browser.get(url)
    log_save(test, "Open " + url, "Info")

def find_element_xpath(test:object, pattern:str) -> object:
    element = None
    try:
        element = WebDriverWait(test.browser, 10).until(
            lambda x: x.find_element(By.XPATH, pattern)
        )
        log_save(test, 'Find element, pattern: {0}'.format(pattern), "info")
    except TimeoutException as ex:
        log_save(test, 'Not find element, pattern: {0}'.format(pattern), "error")
    except InvalidSelectorException as ex:
        log_save(test, 'Invalid pattern: {0}'.format(pattern), "error")

    return element

def get_attributes(test:object, pattern:str) -> dict:
    attr = {}

    element = find_element_xpath(test, pattern)
    if (element != None):
        js_code = """
        let attr = arguments[0].attributes;
        let items = {};
        for (let i = 0; i < attr.length; i++) {
            items[attr[i].name] = attr[i].value;
        }
        return items;
        """

        attr = test.browser.execute_script(js_code, element)

    return attr

def click(test:object, pattern:str):
    element = find_element_xpath(test, pattern)
    if (element != None):
        element.click()
        log_save(test, "Element click, (pattern: {0})".format(pattern), "info")

def input_keys(test:object, pattern:str, keys:str):
    element = find_element_xpath(test, pattern)
    if (element != None):
        element.send_keys(keys)
        log_save(test, "Send keys, (pattern: {0}, keys: {1})".format(pattern, keys), "info")

def get_text_in_field(test:object, pattern:str) -> str:
    text = ""
    element = find_element_xpath(test, pattern)

    if (element != None):
       text = element.get_attribute('value')

    return text


# -*- coding: utf-8 -*-

from PyQt5 import QtWidgets, QtCore, QtGui
from plib import rect
from plib import platform

class Ball(QtWidgets.QGraphicsPixmapItem):
    width = 20
    def __init__(self, parent, x1 = None, y1 = None):
        QtWidgets.QWidget.__init__(self)
        if x1 == None and y1 == None:
            self.setPos(parent.geometry().width() / 2, parent.geometry().height() / 2)

        elif x1 != None and y1 !=None:
            self.setPos(x1, y1)

        pixmap = QtGui.QPixmap("./plib/pix/ball.png")
        self.setPixmap(pixmap.scaled(Ball.width, Ball.width, QtCore.Qt.KeepAspectRatio))

        self.parent = parent

        self.r = Ball.width / 2

        self.ballPreviousPosition = QtCore.QPointF()

    def collidingEvent(self):
        """ Function check is it collision and returning True if is collision and False in opposite"""
        collidingItems = self.collidingItems() # list with all items

        isCollision = False

        for i in range(0, len(self.collidingItems())):
            distance = pow(pow(self.getPreviousPosition().x() - self.pos().x(), 2) + pow(self.getPreviousPosition().y() - self.pos().y(), 2), 0.5)
            if type(collidingItems[i]) is rect.Rect or type(collidingItems[i]) is platform.Platform:
                isCollision = True

                rectPixmap = collidingItems[i]

                middleRectY = rectPixmap.y() + rectPixmap.getHeight() / 2
                middleBallY = self.y() + self.width / 2

                middleRectX = rectPixmap.x() + rectPixmap.getWidth() / 2
                middleBallX = self.x() + self.width / 2

                # collision on right or left edge of the rect
                if abs(middleBallY - middleRectY) < rectPixmap.getHeight() / 2 and -(rectPixmap.x() + rectPixmap.getWidth()) + self.x() < 3:
                    shiftX = -self.x() + self.getPreviousPosition().x()
                    shiftY = self.y() - self.getPreviousPosition().y()

                # collision on bottom or top edge of the rect
                elif abs(middleBallX - middleRectX) < rectPixmap.getWidth() / 2 + Ball.width / 2 and -(rectPixmap.y() + rectPixmap.getHeight()) + self.y() < 3 :

                    # distance between previous position and present position must be the same !!!!
                    if abs(middleBallX - middleRectX) < rectPixmap.getWidth() / 2 - Ball.width / 2: # if in setting of middle of rect
                        shiftX = self.x() - self.getPreviousPosition().x()
                        shiftY = -self.y() + self.getPreviousPosition().y()
                    elif abs(middleBallX - middleRectX) < rectPixmap.getWidth() / 2 and abs(middleBallX - middleRectX) > rectPixmap.getWidth() / 2 - Ball.width / 2: # if in setting of the corner
                        shiftX = 1.5 * (self.x() - self.getPreviousPosition().x())
                        shiftY = -self.y() + self.getPreviousPosition().y()
                        shift = pow(pow(shiftX, 2) + pow(shiftY, 2), 0.5)

                        shiftX = shiftX * distance / shift
                        shiftY = shiftY * distance / shift

                        print("I'm in 2")

                    else: # if in the setting of the corner and rect Ball corner
                        shiftX = 2 * (self.x() - self.getPreviousPosition().x())
                        shiftY = -(-self.y() + self.getPreviousPosition().y())
                        print("I'm in")

                        shift = pow(pow(shiftX, 2) + pow(shiftY, 2), 0.5)

                        shiftX = shiftX * distance / shift
                        shiftY = shiftY * distance / shift

                else:
                    shiftX = self.x() - self.getPreviousPosition().x()
                    shiftY = self.y() - self.getPreviousPosition().y()

                self.setPreviousPosition(QtCore.QPointF(self.x(), self.y()))
                self.setPos(self.x() + shiftX, self.y() + shiftY)

                if type(collidingItems[i]) is rect.Rect:
                    self.parent.box.remove(collidingItems[i])
                    self.scene().removeItem(collidingItems[i])
                    self.parent.points = self.parent.points + 100
                    self.parent.msgToStatusBar.emit(str(self.parent.points))

        return isCollision

    def getPreviousPosition(self):
        return self.ballPreviousPosition

    def setPreviousPosition(self, pointf):
        """point is QtCore.QtPointF type"""
        self.ballPreviousPosition = pointf


from flask_restful import Resource
from flask import request
import pika
import json
import time

class Controller(Resource):
  def post(self):
    body = request.get_json()
    f = open("analyze_data.json", "r")
    analyze_data = json.load(f)
    f.close()
    analyze_data[body['label'] + str(round(time.time() * 1000))] = {
      'pending': True,
      'title': body['label'],
      'g_drive_id': body['g_drive_id']
    }
    with open('analyze_data.json', 'w', encoding='utf8') as json_file:
      json.dump(analyze_data, json_file, ensure_ascii=False)
    send_data = json.dumps({
      'label': body['label'] + str(round(time.time() * 1000)),
      'g_drive_id': body['g_drive_id']
    })
    print(send_data)
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='rabbitmq'))
    channel = connection.channel()
    channel.queue_declare(queue='addNewCsv')
    channel.basic_publish(exchange='', routing_key='addNewCsv', body=send_data)
    connection.close()


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

# # `RL_model_decision_functions.py`

# In[1]:

"""
Functions for converting counts to probabilities, evaluating agent decision and outcomes
"""

# from utils import *
import random
from random import choices

#########################
## softmax probability ##
#########################

def softmax(x, beta = 1):
    """Compute softmax values for each sets of scores in x."""
    return np.exp(x * beta) / np.sum(np.exp(x * beta), axis=0)

def get_softmax_probabilities(df, columns):
    """
    create a softmax dataframe to store the probabilities for choosing
    rock, paper, or scissors move.
    This general sofm function is used for human_reward_move model.
    """
    vals = df[columns]
    vals = vals.apply(softmax,axis=1,beta=4)
    return vals

def get_softmax_probabilities_3b(df):
    """
    create a softmax dataframe to store the probabilities for choosing
    rock, paper, or scissors move.
    This sofm function is used for human_reward_past_cur_move model.
    """
    distribution = []
    # assign vals to store reward list
    # Since first round has no previous moves, we add even probability to it
    vals=[[0.33,0.33,0.33]]
    for i in range(2,df.shape[0],2):
        # agent's previous move
        pre_move=df.get('player_move').iloc[i-2]
        # avoid Nan pre_move
        if pre_move != 'none' and not pd.isna(pre_move):
            # get the reward combination with specific pre_move
            reward_cols=[f'{pre_move}_rock_reward',f'{pre_move}_paper_reward',f'{pre_move}_scissors_reward']
            val = df[reward_cols].iloc[i].tolist()
            vals.append(val) # append reward value to vals
        else:
            # if there's no pre_move, use the last reward list (val)
            val=vals[-1]
            vals.append(val)
    # convert reward list to softmax probability
    soft_max=[softmax(x) for x in vals]
    # create a softmax distribution dataframe
    sofm = pd.DataFrame(soft_max, columns = ['softmax_prob_rock', 'softmax_prob_paper', 'softmax_prob_scissors'])

    # only human rows
    df_new = df[df.is_bot == 0].reset_index()
    # concate human rows and softmax distribution
    df_new = pd.concat([df_new,sofm], axis = 1)
    return df_new

def get_softmax_probabilities_3c(df):
    '''
    generate softmax probability distribution of each round so we can sample moves from the distribution
    '''
    # df.dropna(axis = 0)
    distribution = []
    vals=[[0.33,0.33,0.33]] # has deleted one default prob list
    for i in range(2,df.shape[0],2):
        pre_move=df.get('player_move').iloc[i-1] # -1 instead of -2 since opponent_pre
        if pre_move != 'none' and not pd.isna(pre_move):
            reward_cols=[f'opponent_{pre_move}_rock_reward',f'opponent_{pre_move}_paper_reward',f'opponent_{pre_move}_scissors_reward']
            val = df[reward_cols].iloc[i].tolist()
            vals.append(val)
        else:
            val=vals[-1]
            vals.append(val)
    soft_max=[softmax(x) for x in vals]
    sofm = pd.DataFrame(soft_max, columns = ['softmax_prob_rock', 'softmax_prob_paper', 'softmax_prob_scissors'])

    # strip only human df outside of the function
    df_new = df[df.is_bot == 0].reset_index()
    df_new = pd.concat([df_new,sofm], axis = 1)
    return df_new

def get_softmax_probabilities_mix(df_agent_past,df_opponent_past):
    """
    choose human_reward_past or opponent_reward_past based on which strategy has higher reward
    """

    distribution = []
    vals=[[0.33,0.33,0.33]] # has deleted one default prob list
    for i in range(2,max(df_agent_past.shape[0],df_agent_past.shape[0]),2):
        oppo_pre_move=df_agent_past.get('player_move').iloc[i-1]
        agent_pre_move=df_agent_past.get('player_move').iloc[i-2]

        if agent_pre_move != 'none' and oppo_pre_move!= 'none' and not pd.isna(oppo_pre_move) and not pd.isna(agent_pre_move):
            agent_reward_cols=[f'{agent_pre_move}_rock_reward',
                         f'{agent_pre_move}_paper_reward',
                         f'{agent_pre_move}_scissors_reward'] #df_agent_past only has bot 0
            oppo_reward_cols=[f'opponent_{oppo_pre_move}_rock_reward',
                         f'opponent_{oppo_pre_move}_paper_reward',
                         f'opponent_{oppo_pre_move}_scissors_reward']# df_opponent_past has bot=0&1,so index not match
            val_agent=df_agent_past[agent_reward_cols].iloc[i].tolist()
            val_oppo = df_opponent_past[oppo_reward_cols].iloc[i].tolist()
            if sum(val_agent)>sum(val_oppo):
                val=val_agent
            else:
                val=val_oppo
            vals.append(val)
        else:
            val=vals[-1]
            vals.append(val)

    soft_max=[softmax(x) for x in vals]
    sofm = pd.DataFrame(soft_max, columns = ['softmax_prob_rock', 'softmax_prob_paper', 'softmax_prob_scissors'])

    # strip only human df outside of the function
    df_new = df_agent_past[df_agent_past.is_bot == 0].reset_index()
    df_new = pd.concat([df_new,sofm], axis = 1)
    return df_new

def get_softmax_probabilities_combined(df):
    # df.dropna(axis = 0)
    distribution = []
    vals=[[0.33,0.33,0.33]] # has deleted one default prob list
    for i in range(2,df.shape[0],2):
        oppo_pre_move=df.get('player_move').iloc[i-1]
        agent_pre_move=df.get('player_move').iloc[i-2]

        if agent_pre_move != 'none' and not pd.isna(oppo_pre_move) and not pd.isna(agent_pre_move):
            reward_cols=[f'opponent_{oppo_pre_move}_{agent_pre_move}_rock_reward',\
                         f'opponent_{oppo_pre_move}_{agent_pre_move}_paper_reward',\
                         f'opponent_{oppo_pre_move}_{agent_pre_move}_scissors_reward']
            val = df[reward_cols].iloc[i].tolist()
            vals.append(val)
        else:
            val=vals[-1]
            vals.append(val)
    soft_max=[softmax(x) for x in vals]
    sofm = pd.DataFrame(soft_max, columns = ['softmax_prob_rock', 'softmax_prob_paper', 'softmax_prob_scissors'])

    # strip only human df outside of the function
    df_new = df[df.is_bot == 0].reset_index()
    df_new = pd.concat([df_new,sofm], axis = 1)
    return df_new

#############################
### Move choice functions ###
#############################

def pick_move(df, sofm):
    """
    pick agent move based of the softmax probability distribution
    """
    moves = np.array([])
    for i in range(df.shape[0]):
        move_choices = ['rock', 'paper', 'scissors']
        distribution = sofm.iloc[i].tolist()
        chosen_move = choices(move_choices, distribution)
        moves = np.append(moves, chosen_move)
    df = df.assign(agent_move = moves)
    return df

def pick_move_v2(df):
    moves = np.array([])
    for i in range(df.shape[0]):
        move_choices = ['rock', 'paper', 'scissors']
        distribution = df[['softmax_prob_rock', 'softmax_prob_paper', 'softmax_prob_scissors']].iloc[i].tolist() # get ith [rock_prob,paper_prob,scissors_prob] from input df
        chosen_move = random.choices(move_choices, distribution)
        moves = np.append(moves, chosen_move)
    df = df.assign(agent_move = moves) # agent_move stores sampled moves
    return df

def assign_agent_outcomes(df):
    """
    Assign outcomes for the agent based on agent move choices.
    df should include only human rows, since agent outcomes are irrelevant for simulating bots
    """
    df.assign(agent_outcome = '')
    df=df.assign(agent_outcome=df.apply(lambda x: evaluate_outcome(x['agent_move'], x['opponent_move']), axis=1))
    return df

# In[ ]:


# The implementation of ICDM 2019 paper "Relation Structure-Aware Heterogeneous Graph Neural Network" RSHN.
# @Time   : 2021/3/1
# @Author : Tianyu Zhao
# @Email  : tyzhao@bupt.edu.cn
import dgl
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from dgl import function as fn
from dgl.utils import expand_as_pair
from dgl.nn.functional import edge_softmax
from . import HeteroEmbedLayer, BaseModel, register_model
from ..utils import get_nodes_dict, coarsened_line_graph

@register_model('RSHN')
class RSHN(BaseModel):
    '''
    Note that
    The four KG dataset in dgl(AIFB, MUTAG, BGS, AM) do not have nodes/edges feature.
    So we should initialize the feature use nn.Parameter, dimension is the hyper-parameter.
    '''

    @classmethod
    def build_model_from_args(cls, args, hg):
        rshn = cls(get_nodes_dict(hg), 10,
                   args.dim, args.num_classes, args.num_node_layer, args.num_edge_layer, dropout=args.dropout
            )
        cl = coarsened_line_graph(rw_len=args.rw_len, batch_size=args.batch_size, n_dataset=args.dataset,
                                  symmetric=True)
        cl_graph = cl.get_cl_graph(hg).to(args.device)
        cl_graph = cl.init_cl_graph(cl_graph)
        rshn.cl_graph = cl_graph

        linear_e1 = nn.Linear(in_features=cl_graph.num_nodes(), out_features=args.dim, bias=False)
        nn.init.xavier_uniform_(linear_e1.weight)
        rshn.linear_e1 = linear_e1
        return rshn

    def __init__(self, n_nodes, in_feats2, dim, num_classes, num_node_layer, num_edge_layer, dropout):
        super(RSHN, self).__init__()
        # map the node feature
        self.h_n_dict = HeteroEmbedLayer(n_nodes, dim)
        # map the edge feature
        self.num_node_layer = num_node_layer
        self.edge_layers = nn.ModuleList()
        for i in range(num_edge_layer):
            self.edge_layers.append(AGNNConv())

        self.node_layers = nn.ModuleList()
        for i in range(num_node_layer):
            self.node_layers.append(GraphConv(in_feats=dim, out_feats=dim, activation=th.tanh))

        self.dropout = dropout

        self.emd2pred = nn.Linear(dim, num_classes)
        self.init_para()

    def init_para(self):
        nn.init.xavier_uniform_(self.emd2pred.weight)

    def forward(self, hg, n_feats=None):

        # For full graph training, directly use the graph
        if n_feats is None:
            # full graph training
            n_feats = self.h_n_dict()

        # Forward of n layers of CompGraphConv

        for layer in self.edge_layers:
            h = self.cl_graph.ndata['h']
            h_e = self.cl_graph.edata['w']
            h = th.relu(layer(self.cl_graph, h, h_e))
            h = F.dropout(h, p=self.dropout, training=False)

        edge_weight = {}
        for i, e in enumerate(hg.canonical_etypes):
            edge_weight[e] = h[i].expand(hg.num_edges(e), -1)
        temp = self.h_n_dict()
        n_feats = {}
        for n in hg.ntypes:
            n_feats[n] = temp[n]
        if hasattr(hg, 'ntypes'):
            #edge_weight = F.embedding(hg.edata[dgl.ETYPE].long(), h)

            # full graph training
           # edge_weight = self.linear_e1(edge_weight)
            for layer in self.node_layers:
                n_feats = layer(hg, n_feats, edge_weight)
                n_feats = F.dropout(n_feats, p=self.dropout, training=False)
        else:
            # minibatch training
            pass
        n_feats = self.emd2pred(n_feats)
        n_feats = F.dropout(n_feats, p=self.dropout, training=False)
        return n_feats

class AGNNConv(nn.Module):
    def __init__(self,
                 init_beta=1,
                 eps=0.,
                 train_eps=True,
                 learn_beta=True):
        super(AGNNConv, self).__init__()
        if learn_beta:
            self.beta = nn.Parameter(th.Tensor(init_beta))
        else:
            self.register_buffer('beta', th.Tensor(init_beta))
        if train_eps:
            self.eps = th.nn.Parameter(th.Tensor([eps]))
        else:
            self.register_buffer('eps', th.Tensor([eps]))

    def forward(self, graph, feat, edge_weight):

        with graph.local_scope():
            feat_src, feat_dst = expand_as_pair(feat, graph)

            graph.srcdata['h'] = feat_src
            graph.srcdata['norm_h'] = F.normalize(feat_src, p=2, dim=-1)
            if isinstance(feat, tuple) or graph.is_block:
                graph.dstdata['norm_h'] = F.normalize(feat_dst, p=2, dim=-1)

            e = self.beta * edge_weight

            graph.edata['p'] = edge_softmax(graph, e, norm_by='src')
            graph.update_all(fn.u_mul_e('norm_h', 'p', 'm'), fn.sum('m', 'h'))
            rst = graph.dstdata.pop('h')
            rst = (1 + self.eps) * feat + rst
            return rst

class GraphConv(nn.Module):
    def __init__(self,
                 in_feats,
                 out_feats,
                 activation=None,
                 ):
        super(GraphConv, self).__init__()
        self._in_feats = in_feats
        self._out_feats = out_feats

        self.weight1 = nn.Parameter(th.Tensor(in_feats, out_feats))
        self.weight2 = nn.Parameter(th.Tensor(in_feats, out_feats))

        self.reset_parameters()

        self.activation = activation

    def reset_parameters(self):
        nn.init.xavier_uniform_(self.weight1)
        nn.init.xavier_uniform_(self.weight2)

    def forward(self, graph, feat, edge_weight=None):

        with graph.local_scope():

            aggregate_fn = fn.copy_src('h', 'm')
            if edge_weight is not None:
                #assert edge_weight.shape[0] == graph.number_of_edges()
                graph.edata['_edge_weight'] = edge_weight
                aggregate_fn = fn.u_sub_e('h', '_edge_weight', 'm')

            feat_src, feat_dst = expand_as_pair(feat, graph)

            # aggregate first then mult W
            graph.srcdata['h'] = feat_src
            graph.apply_edges(lambda edges: {'h': edges.data['_edge_weight'] * 2})
            graph.update_all(aggregate_fn, fn.sum(msg='m', out='h'))
            rst = graph.dstdata['h']
            rst = th.matmul(feat_src, self.weight1) + th.matmul(rst, self.weight2)

            if self.activation is not None:
                rst = self.activation(rst)

            return rst


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

# @File  : scheduler_task_history.py
# @Author: gaofzhan
# @Email: gaofeng.a.zhang@ericssoin.com
# @Date  : 2020/12/17 14:49
# @Desc  :
from flask import request, make_response
from backend.customer.myCustomer import APiMethodView
from backend.myBluePrint.ericic_v2.service.scheduler_task_history_service import SchedulerTaskHistoryService

class SchedulerTaskHistoryView(APiMethodView):

    def get(self, *args, **kwargs):
        cid = request.args.get('cid')
        _filter = request.args.get('filter')
        _filter = _filter if _filter in ['static', 'dynamic'] else None
        offset = request.args.get('offset', 0)
        limit = request.args.get('limit', 50)
        try:
            limit = int(limit)
            offset = int(offset)
        except Exception:
            limit = 50
            offset = 0
        res = SchedulerTaskHistoryService.get_history_by_cid(cid, _filter, limit, offset)
        return make_response(dict(status=True, code=200, data=res['data'], total_num=res['total_num'])), 200


from compound import *
from compound.i.iOx import *
from compound.i.iAc import *
from compound.i.iSa import *
from database.compounds.gases import *
from database.compounds.solubility import *
from element import *
from reaction import *
from tools.comps import simple
from tools.reacts import *

def r_1(comps: 'list(Compound)', is_input):
    """`iSiMe + (`iSaNo_, `iSaCo_) -> `iSiMe + (`iSaNo_, `iSaCo_)"""
    react: str

    if is_input:
        iSiMe1 = Compound("Zn")
        iSaNo1 = Compound("Cu(NO3)2")
        if len(comps) == 1:
            if "iSi" in comps[0].comp_type:
                iSiMe1 = comps[0]
                me = list(iSiMe1.formula.consist.keys())[0].name
                me_oxs = get_me_oxs(me)

                if me_oxs == 0:
                    return ""
                if is_me_activer("Cu", 2, me, me_oxs):
                    return ""
            else:
                iSaNo1 = comps[0]
                ((me, me_oxs), (an, _)) = iSa_oxs(iSaNo1.formula)
                if not is_me_activer("Zn", 2, me, me_oxs) or "Zn" in an:
                    if not is_me_activer("Mg", 2, me, me_oxs):
                        return ""
                    else:
                        iSiMe1 = Compound("Mg")
        else:
            if "iSi" in comps[0].comp_type:
                iSiMe1 = comps[0]
                iSaNo1 = comps[1]
            else:
                iSiMe1 = comps[1]
                iSaNo1 = comps[0]
        if not is_ionic_soluble(iSaNo1):
            return ""

        me1 = list(iSiMe1.formula.consist.keys())[0].name
        me1_oxs = get_me_oxs(me1)
        if me1_oxs == 0:
            return ""
        ((me2, me2_oxs), (an, an_oxs)) = iSa_oxs(iSaNo1.formula)

        if not is_me_activer(me1, me1_oxs, me2, me2_oxs):
            return ""
        if not is_me_activer("Na", 1, me1, me1_oxs):
            return ""

        iSiMe2 = Compound(simple(me2))
        iSaNo2 = Compound(iSaNo_create(me1, me1_oxs, an, an_oxs))

        react = f"{iSiMe1} + {iSaNo1} -> {iSiMe2} + {iSaNo2}"
    else:
        iSiMe2 = Compound("Cu")
        iSaNo2 = Compound("Zn(NO3)2")
        if len(comps) == 1:
            if "iSi" in comps[0].comp_type:
                iSiMe2 = comps[0]
                me = list(iSiMe2.formula.consist.keys())[0].name
                me_oxs = get_me_oxs(me)
                if me_oxs == 0:
                    return ""

                if not is_me_activer("Zn", 2, me, me_oxs):
                    if not is_me_activer("Mg", 2, me, me_oxs):
                        return ""
                    else:
                        iSaNo2 = Compound("Mg(NO3)2")
            else:
                iSaNo2 = comps[0]
                ((me, me_oxs), _) = iSa_oxs(iSaNo2.formula)
                if is_me_activer("Cu", 2, me, me_oxs):
                    return ""
        else:
            if "iSi" in comps[0].comp_type:
                iSiMe2 = comps[0]
                iSaNo2 = comps[1]
            else:
                iSiMe2 = comps[0]
                iSaNo2 = comps[1]

        me2 = list(iSiMe2.formula.consist.keys())[0].name
        me2_oxs = get_me_oxs(me2)
        if me2_oxs == 0:
            return ""
        ((me1, me1_oxs), (an, an_oxs)) = iSa_oxs(iSaNo2.formula)

        if not is_me_activer(me1, me1_oxs, me2, me2_oxs):
            return ""
        if not is_me_activer("Na", 1, me1, me1_oxs):
            return ""

        iSiMe1 = Compound(simple(me1))
        iSaNo1 = Compound(iSaNo_create(me2, me2_oxs, an, an_oxs))

        if not is_ionic_soluble(iSaNo1):
            return ""

        react = f"{iSiMe1} + {iSaNo1} -> {iSiMe2} + {iSaNo2}"

    return Reaction(react)

def r_2(comps: 'list(Compound)', is_input):
    """(`iSaNo_, `iSaAmm_, `iSaCo_) + (`iSaNo__, `iSaAmm__, `iSaCo__) -> """\
    """(`iSaNo_, `iSaAmm_, `iSaCo_) + (`iSaNo__, `iSaAmm__, `iSaCo__)"""
    react: str

    if is_input:
        iSaNo1 = Compound("Na2SO4")
        iSaNo2 = Compound("BaCl2")
        if len(comps) == 1:
            iSaNo1 = comps[0]
            ((me, _), (an, an_oxs)) = iSa_oxs(iSaNo1.formula)
            if me == "Ba" and an != "SO4":
                iSaNo2 = Compound("Na2SO4")
            elif an not in ["F", "SO4", "NO3"]:
                iSaNo2 = Compound("AgNO3")
            else:
                if an == "SO4":
                    iSaNo2 = Compound("BaCl2")
                elif an == "F":
                    iSaNo2 = Compound("MgCl2")
                elif an == "NO3":
                    iSaNo2 = Compound("SnCl2")
        else:
            iSaNo1 = comps[0]
            iSaNo2 = comps[1]

        ((me1, me1_oxs), (an1, an1_oxs)) = iSa_oxs(iSaNo1.formula)
        ((me2, me2_oxs), (an2, an2_oxs)) = iSa_oxs(iSaNo2.formula)

        if not is_ionic_soluble(iSaNo1) or not is_ionic_soluble(iSaNo2):
            return ""

        iSaNo3 = Compound(iSaNo_create(me2, me2_oxs, an1, an1_oxs))
        iSaNo4 = Compound(iSaNo_create(me1, me1_oxs, an2, an2_oxs))

        react = f"{iSaNo1} + {iSaNo2} -> {iSaNo3} + {iSaNo4}"

        xg = Reaction(react)

        if not is_exchange(xg.outp):
            return ""
    else:
        iSaNo3 = Compound("NaCl")
        iSaNo4 = Compound("BaSO4")
        if len(comps) == 1:
            iSaNo3 = comps[0]
            ((me, _), (an, _)) = iSa_oxs(iSaNo3.formula)
            if an == "SO4":
                if me != "Ba":
                    iSaNo4 = Compound("CaCO3")
                else:
                    iSaNo4 = Compound("NaCl")
        else:
            iSaNo3 = comps[0]
            iSaNo4 = comps[1]

        ((me1, me1_oxs), (an2, an2_oxs)) = iSa_oxs(iSaNo3.formula)
        ((me2, me2_oxs), (an1, an1_oxs)) = iSa_oxs(iSaNo4.formula)

        iSaNo1 = Compound(iSaNo_create(me2, me2_oxs, an2, an2_oxs))
        iSaNo2 = Compound(iSaNo_create(me1, me1_oxs, an1, an1_oxs))

        if not is_ionic_soluble(iSaNo1) or not is_ionic_soluble(iSaNo2):
            return ""

        react = f"{iSaNo1} + {iSaNo2} -> {iSaNo3} + {iSaNo4}"

        xg = Reaction(react)

        if not is_exchange(xg.outp):
            return ""

    return Reaction(react)

def r_3(comps: 'list(Compound)', is_input):
    """`iSaNo -> (`iOxBa_, `iOxAm_) + (`iOxAc__, `iOxAm__)"""
    react: str

    if is_input:
        iSaNo = comps[0]

        if Element("O") not in iSaNo.formula.consist:
            return ""

        ((me, me_oxs), (an, an_oxs)) = iSa_oxs(iSaNo.formula)
        if Element(me).elem_sub_type == "AlkMe":
            return ""

        iAc = Compound(iAc_create(an, an_oxs))
        (nme, nme_oxs) = iAc_el_oxs(iAc.formula)
        if nme == "N":
            return ""

        iOxBa = Compound(iOx_create(me, me_oxs))
        iOxAc = Compound(iOx_create(nme, nme_oxs))

        react = f"{iSaNo} -> {iOxBa} + {iOxAc}"
    else:
        iOxBa = Compound("CaO")
        iOxAc = Compound("CO2")
        if len(comps) == 1:
            if "iOxAc" in comps[0].comp_type:
                iOxAc = comps[0]
            else:
                iOxBa = comps[0]
        else:
            if "iOxAc" in comps[0].comp_type or \
               "iOxAm" in comps[0].comp_type and "iOxAc" not in comps[1].comp_type:
                iOxAc = comps[0]
                iOxBa = comps[1]
            else:
                iOxAc = comps[1]
                iOxBa = comps[0]

        (me, me_oxs) = iOx_oxs(iOxBa.formula)
        if Element(me).elem_sub_type == "AlkMe":
            return ""

        (nme, nme_oxs) = iOx_oxs(iOxAc.formula)
        if nme == "N":
            return ""
        iAc = Compound(iAc_el_create(nme, nme_oxs))
        (an, an_oxs) = iAc_oxs(iAc.formula)

        if an == "NO3":
            return ""

        iSaNo = Compound(iSaNo_create(me, me_oxs, an, an_oxs))

        react = f"{iSaNo} -> {iOxBa} + {iOxAc}"

    return Reaction(react, "t ")

def r_4(comps: 'list(Compound)', is_input):
    """`iSaNo + `iOxAc -> `iSaNo + `iOxAc"""
    react: str

    if is_input:
        iSaNo1 = Compound("Na2CO3")
        iOxAc1 = Compound("SO3")
        if len(comps) == 1:
            if "iOx" in comps[0].comp_type:
                iOxAc1 = comps[0]
            else:
                iSaNo1 = comps[0]
        else:
            if "iOx" in comps[0].comp_type:
                iOxAc1 = comps[0]
                iSaNo1 = comps[1]
            else:
                iOxAc1 = comps[1]
                iSaNo1 = comps[0]

        ((me, me_oxs), (an1, an1_oxs)) = iSa_oxs(iSaNo1.formula)
        iAc1 = Compound(iAc_create(an1, an1_oxs))
        if iAc1.comp_type == "iAcNox":
            return ""
        (nme1, nme1_oxs) = iAc_el_oxs(iAc1.formula)
        if nme1 == "N":
            return ""

        (nme2, nme2_oxs) = iOx_oxs(iOxAc1.formula)
        if nme2 == "N":
            return ""
        iAc2 = Compound(iAc_el_create(nme2, nme2_oxs))
        if iAc2.comp_type == "iAcNox":
            return ""
        (an2, an2_oxs) = iAc_oxs(iAc2.formula)

        if is_gase(iOxAc1):
            return ""

        iOxAc2 = Compound(iOx_create(nme1, nme1_oxs))
        iSaNo2 = Compound(iSaNo_create(me, me_oxs, an2, an2_oxs))

        react = f"{iSaNo1} + {iOxAc1} -> {iSaNo2} + {iOxAc2}"

        xg = Reaction(react)

        if find_if(xg.outp, lambda c: is_gase(c)) == -1:
            return ""
    else:
        iSaNo2 = Compound("Na2SO4")
        iOxAc2 = Compound("CO2")
        if len(comps) == 1:
            if "iOx" in comps[0].comp_type:
                iOxAc2 = comps[0]
            else:
                iSaNo2 = comps[0]
        else:
            if "iOx" in comps[0].comp_type:
                iOxAc2 = comps[0]
                iSaNo2 = comps[1]
            else:
                iOxAc2 = comps[1]
                iSaNo2 = comps[0]

        ((me, me_oxs), (an2, an2_oxs)) = iSa_oxs(iSaNo2.formula)
        iAc2 = Compound(iAc_create(an2, an2_oxs))
        if iAc2.comp_type == "iAcNox":
            return ""
        (nme2, nme2_oxs) = iAc_el_oxs(iAc2.formula)
        if nme2 == "N":
            return ""

        (nme1, nme1_oxs) = iOx_oxs(iOxAc2.formula)
        if nme1 == "N":
            return ""
        iAc1 = Compound(iAc_el_create(nme1, nme1_oxs))
        if iAc1.comp_type == "iAcNox":
            return ""
        (an1, an1_oxs) = iAc_oxs(iAc1.formula)

        iSaNo1 = Compound(iSaNo_create(me, me_oxs, an1, an1_oxs))
        iOxAc1 = Compound(iOx_create(nme2, nme2_oxs))

        if is_gase(iOxAc1):
            return ""

        react = f"{iSaNo1} + {iOxAc1} -> {iSaNo2} + {iOxAc2}"

        xg = Reaction(react)

        if find_if(xg.outp, lambda c: is_gase(c)) == -1:
            return ""

    return Reaction(react, "t ")


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

titles = []
browser = webdriver.Firefox(executable_path='/Users/kat/Downloads/geckodriver')

NUM_PAGES = 36

for i in range(1, NUM_PAGES + 1):
	browser.get("http://www.quodb.com/search/ready%20when%20you%20are?p=" + str(i) +
				"&titles_per_page=20&phrases_per_title=1")

	timeout = 20
	try:
	    WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, "//tr")))
	except TimeoutException:
	    print("Timed out waiting for page to load")
	    browser.quit()

	elems = browser.find_elements_by_xpath("//small[@class='title']")

	for elem in elems:
		if ":" not in elem.text:
			idx_1 = elem.text.find("(")
			idx_2 = elem.text.find(")")
			if (idx_1 != -1) and (idx_2 != -1):
				try:
					year = int(elem.text[idx_1+1:idx_2])
					if year >= 1995 and year <= 2015:
						titles.append(elem.text)
				except:
					pass

browser.close()

for title in titles:
	print (title)


# -*- coding: utf-8 -*-
import Sofa
from stlib.physics.deformable import ElasticMaterialObject
from stlib.physics.constraints import FixedBox
from stlib.scene import Node
from softrobots.actuators import PullingCable
from stlib.physics.collision import CollisionMesh

from splib.loaders import loadPointListFromFile

class FingerController(Sofa.PythonScriptController):
    def __init__(self, node, cable ):
        self.cableconstraintvalue = cable.getObject("CableConstraint").findData('value')
        self.name = "FingerController"

    def onKeyPressed(self,c):
        if (c == "+"):
            self.cableconstraintvalue.value =  self.cableconstraintvalue.value[0][0] + 1.

        elif (c == "-"):
            displacement = self.cableconstraintvalue.value[0][0] - 1.
            if(displacement < 0):
                displacement = 0
            self.cableconstraintvalue.value = displacement

def Finger(parentNode=None, name="Finger",
           rotation=[0.0, 0.0, 0.0], translation=[0.0, 0.0, 0.0],
           fixingBox=[-5.0,0.0,0.0,10.0,15.0,20.0], pullPointLocation=[0.0,0.0,0.0]):

    finger = Node(parentNode, name)
    eobject = ElasticMaterialObject(finger,
                                   volumeMeshFileName="data/mesh/finger2/finger2.vtk",
                                   poissonRatio=0.3,
                                   youngModulus=18000,
                                   totalMass=0.5,
                                   surfaceColor=[0.0, 0.8, 0.7],
                                   surfaceMeshFileName="data/mesh/finger2/finger2.stl",
                                   rotation=rotation,
                                   translation=translation)

    FixedBox(eobject.node, atPositions=fixingBox, doVisualization=True)

    cable=PullingCable(eobject.node,
                 "PullingCable",
                 pullPointLocation=pullPointLocation,
                 rotation=rotation,
                 translation=translation,
                 cableGeometry=loadPointListFromFile("data/mesh/cable2.json"));

    FingerController(eobject.node, cable)

    CollisionMesh(eobject.node, name="CollisionMesh",
                 surfaceMeshFileName="data/mesh/finger2/finger2.stl",
                 rotation=rotation, translation=translation,
                 )

    return finger

def createScene(rootNode):
    from stlib.scene import MainHeader, ContactHeader
    MainHeader(rootNode, gravity=[0.0, -981.0, 0.0], plugins=["SoftRobots"])
    ContactHeader(rootNode, alarmDistance=4, contactDistance=3, frictionCoef=0.08)

    Finger(rootNode, translation=[1.0,0.0,0.0])
    return rootNode


#Pythonで、モックに差し替えたメソッドが呼ばれた回数や呼ばれた時の引数を検証する
#https://thinkami.hatenablog.com/entry/2017/03/18/063454

#メソッドが呼ばれた回数を検証
#メソッドが呼ばれた時の引数を検証
#メソッドが呼ばれた回数と引数を同時に検証
#メソッドが呼ばれていないことを検証

#fixture

#parametarise

from unittest.mock import patch

class Test(object):
    a = 100

    def aa(self,x,y):
        print(x * y)

with patch.object(Test,'a',200) as dummy:
    print("Test",Test.a)
    print("dummy",dummy)


import importlib
import pytest

import numpy as np
from sklearn.datasets import load_diabetes, load_iris

from frlearn.base import ClassSupervised, FeatureSelector, FeaturePreprocessor, MultiClassClassifier, MultiLabelClassifier, Unsupervised

algorithm_types = [
    'classifiers',
    'data_descriptors',
    'feature_preprocessors',
    'instance_preprocessors',
    'regressors'
]
algorithms = {}
for algorithm_type in algorithm_types:
    module = importlib.import_module('frlearn.' + algorithm_type)
    algorithms[algorithm_type] = [getattr(module, a) for a in module.__all__]

@pytest.fixture
def multiclass_data():
    return load_iris(return_X_y=True)

@pytest.fixture
def regression_data():
    return load_diabetes(return_X_y=True)

@pytest.mark.parametrize(
    'cls',
    [a for a in algorithms['classifiers'] if issubclass(a, MultiClassClassifier)],
)
def test_multiclass_classifier(multiclass_data, cls):
    X, y = multiclass_data
    clf = cls()
    model = clf(X, y)

    scores = model(X)
    assert scores.shape == (X.shape[0], 3)

@pytest.mark.parametrize(
    'cls',
    [a for a in algorithms['classifiers'] if issubclass(a, MultiLabelClassifier)],
)
def test_multilabel_classifier(multiclass_data, cls):
    X, y = multiclass_data
    Y = (y[:, None] == np.arange(3)).astype(int)
    Y[[109, 117, 131], 2] = 0
    Y[((X[:, 0] >= 6) & (y == 1)), 2] = 1
    Y[((X[:, 0] <= 6) & (y == 2)), 1] = 1

    clf = cls()
    model = clf(X, Y)

    scores = model(X)
    assert scores.shape == (X.shape[0], 3)

@pytest.mark.parametrize(
    'cls',
    algorithms['data_descriptors'],
)
def test_data_descriptor(multiclass_data, cls):
    X, y = multiclass_data
    descriptor = cls()
    model = descriptor(X[y == 0])

    scores = model(X)
    assert scores.shape == (X.shape[0], )

@pytest.mark.parametrize(
    'cls',
    algorithms['regressors'],
)
def test_regressor(regression_data, cls):
    X, y = regression_data
    regressor = cls()
    model = regressor(X, y)

    predictions = model(X)
    assert predictions.shape == (X.shape[0], )

@pytest.mark.parametrize(
    'cls',
    [a for a in algorithms['feature_preprocessors'] if issubclass(a, ClassSupervised) and issubclass(a, FeatureSelector)],
)
def test_supervised_feature_selector(multiclass_data, cls):
    X_orig, y_orig = multiclass_data

    preprocessor = cls()
    model = preprocessor(X_orig, y_orig)
    X = model(X_orig)
    assert X.shape[0] == X_orig.shape[0]
    assert X.shape[1] <= X_orig.shape[1]

@pytest.mark.parametrize(
    'cls',
    [a for a in algorithms['feature_preprocessors'] if issubclass(a, Unsupervised) and issubclass(a, FeaturePreprocessor)],
)
def test_unsupervised_feature_preprocessor(multiclass_data, cls):
    X_orig, y_orig = multiclass_data

    preprocessor = cls()
    model = preprocessor(X_orig)
    X = model(X_orig)
    assert X.shape[0] == X_orig.shape[0]

# TODO: add test for SAE (but SAE takes a long time to run)

@pytest.mark.parametrize(
    'cls',
    algorithms['instance_preprocessors'],
)
def test_supervised_instance_selector(multiclass_data, cls):
    X_orig, y_orig = multiclass_data
    preprocessor = cls()

    X, y = preprocessor(X_orig, y_orig)
    assert y.shape[0] == X.shape[0]
    assert X.shape[1] == X_orig.shape[1]
    assert X.shape[0] <= X_orig.shape[0]


import telepot
import requests
import telepot
from bs4 import BeautifulSoup

# 검색 키워드
search_word = '코인'

token = '1210533819:AAFRupwIS-v5JLRzK2WVt4OUStaEqtQhyS4'#위에서 발급받은 토큰 기입

StartMsg =   "암호화폐 관련 뉴스 보고싶어? : news \n" \
            "라고 검색해봐! "

# 기존에 보냈던 링크를 담아둘 리스트
old_links = []

def extract_links(old_links=[]):
    url = f'https://m.search.naver.com/search.naver?where=m_news&sm=mtb_jum&query={search_word}'
    req = requests.get(url)
    html = req.text
    soup = BeautifulSoup(html, 'html.parser')

    search_result = soup.select_one('#news_result_list')
    news_list = search_result.select('.bx > .news_wrap > a')

    links = []
    for news in news_list[:5]:
        link = news['href']
        links.append(link)

    new_links = []
    for link in links:
        if link not in old_links:
            new_links.append(link)

    return new_links

def main(msg):
    global old_links
    new_links = extract_links(old_links)
    msg_type, chat_type, chat_id, msg_data, msg_id = telepot.glance(msg, long=True)

    if msg_type == 'text':
        if msg['text'] == '/'+'start':
            bot.sendMessage(chat_id, StartMsg)
            print(msg)
        elif msg['text'] == 'news':
            if new_links:
                for link in new_links:
                    bot.sendMessage(chat_id, text=link)
                    print(msg)
            else:
                bot.sendMessage(chat_id, text='새로운 뉴스 없음')
                """old_links += new_links.copy()
                old_links = list(set(old_links))"""

bot = telepot.Bot(token)
bot.message_loop(main,run_forever=True)


# problem on kattis
# https://open.kattis.com/problems/distinctivecharacter
# breadth first search, bitwise

from collections import deque

def search(k):
    last = None

    while bfs:
        node = bfs.popleft()

        last = node

        for i in range(k):
            new_node = node ^ 1 << i

            if new_node not in seen:
                bfs.append(new_node)
                seen.add(new_node)

    return last

inp = raw_input().split()
n = int(inp[0])
k = int(inp[1])

bfs = deque()
seen = set()

for i in range(n):
    player = int(raw_input(), 2)
    bfs.append(player)
    seen.add(player)

ans = bin(search(k))[2:]

print(ans.zfill(k))


import strawberry
from strawberry.types import Info

from ..types import UpdateOrderInput, CreatedOrderIdType
from ..bl import OrderBL

from api.utils.graphql import IsAdmin, add_random_temp_id_for_response
from api.domains.addresses import AddressBL
from api.domains.requisite import RequisiteBL
from api.domains.transactions.features.promo import PromoBL
from api.domains.transactions import TransactionBL
from api.domains.products import ProductBL
from ...addresses.types import AddressInput

@strawberry.type
class OrderMutations:
    @strawberry.mutation(
        permission_classes=[IsAdmin],
        description='Update order info'
    )
    async def update_order(
            self,
            order: UpdateOrderInput,
            info: Info
    ) -> None:
        """ Update order mutation """
        return await OrderBL(info).update(order)

    @strawberry.mutation(
        description='Create new order'
    )
    async def create_order(
            self,
            payload: AddressInput,
            info: Info
    ) -> CreatedOrderIdType:
        """ Create order from cart """
        temp_user_id = add_random_temp_id_for_response(self.info)
        payload.address_id = await AddressBL(info).get_or_create(payload, temp_user_id)
        promo = None
        if payload.promo:
            promo = await PromoBL(info).find(payload.promo)
        requisite = await RequisiteBL(info).get_active(payload.payment_type)
        if not requisite:
            raise Exception('No requisites are available')
        amount = await ProductBL(info).calc_prices(payload.products)
        transaction_id = await TransactionBL(info).create(amount, requisite.id, promo)
        data = await OrderBL(info).create(payload, transaction_id)

        return CreatedOrderIdType(id=data['id'])


class Solution:
    def minScore(self, n: int, roads: List[List[int]]) -> int:
        parent= [i for i in range(n)]
        rank= [1 for i in range(n)]
        minimum= [float('inf') for i in range(n)]

        def find(node):
            if node != parent[node]:
                parent[node] = find(parent[node])
            return parent[node]

        def union(n1, n2, d):
            p1= find(n1)
            p2= find(n2)

            if rank[p2] > rank[p1]:
                p1, p2 = p2, p1

            if rank[p1] == rank[p2]:
                rank[p1]+=1

            parent[p2] = p1
            minimum[p1]= min([minimum[p1], minimum[p2], d])

        for s, e, d in roads:
            union(s-1, e-1, d)

        return minimum[find(0)]


import os
import numpy as np
import pylab as p
import simplejson as js
import pandas as pa
import yaml

from collections import defaultdict

from jobmon import redisbackend as rb

db = rb.RedisDataStore('localhost')
jobhash = db.select_jobfile()

resdir = os.path.join('/home/bana/largeresearch/results', jobhash)

p.close('all')

output = defaultdict(list)
other = defaultdict(list)
diffs = defaultdict(list)

for mydir in os.listdir(resdir):
    params = yaml.load(db.get_params(mydir))
    if len(params.values()) != 0:
        continue
    for fname in os.listdir(os.path.join(resdir,mydir)):
        data = js.loads(open(os.path.join(resdir,mydir,fname)).read())
        print(data['errors'])
        for k,v in data.iteritems():
            if k == 'errors':
                mpmerr = data['errors']['mpm']
                for kk,vv in data['errors'].iteritems():
                    output[kk].append(vv)
                    if kk != 'mpm':
                        diffs[kk].append((vv-mpmerr))
            else:
                other[k].append(v)

df = pa.DataFrame(output)
otherdf = pa.DataFrame(other)
diffdf = pa.DataFrame(diffs)

print(otherdf.describe())
df.boxplot()
p.figure()
#diffdf.boxplot()
key = {'gauss':'Normal OBC', 'svm':'SVM', 'knn':'3NN', 'lda':'LDA', 'mpm':'MP OBC',
        'mpm_prior':'MP OBC Prior'}

ind = np.arange(len(df.columns))
width = 0.7
p.grid(True)
p.bar(ind, df.mean(), width=width)
meanmin, meanmax = np.min(df.mean()), np.max(df.mean())
spread = meanmax-meanmin
p.ylim(meanmin-0.8*spread, meanmax+0.8*spread)
#p.bar(ind, df.mean(), width=width, yerr=df.std())
p.gca().set_xticks(ind+width/2.)
p.gca().set_xticklabels([key[x] for x in df.columns])
p.ylabel('Mean True error')
#p.title(jobhash[:6] + ' ' + db.get_description(jobhash) + ' ' + str(params))

p.show()


from db import db

from flask import Flask,render_template,jsonify,request,flash,redirect,url_for

cur =db.cursor()
def in_CSE(ph,

        Name ,
        ETC,
        ESC,
        course):

        cur =db.cursor()

        cur.execute("INSERT INTO  detail ( phone,name,subject1,subject2,subject3,subject4,subject5,subject6,ESC,ETC,Dept) VALUES (%s, %s, %s,%s,%s,%s,%s,%s,%s,%s,%s)", (ph,Name,"Mathematics for CSE","Physics for CSE Stream",
                        "Principles of Programming Using C",
                        "Communicative English",
                        "Samskrutika Kannada/Balake Kannada",
                        "Engineering Exploration",ETC,ESC,course))
        db.commit()
        return "True"

man_cse=[{"name":"22MATS11 - Mathematics for CSE" },{"name":"22PHYS12 - Physics for CSE Stream"},{"name":"22POP13 - Principles of Programming Using C"},{"name":"22CE16 - Communicative English - I "},{"name":"22KSK17 - Samskrutika Kannada/22KBK17 Balake Kannada"},{"name":"22EEX18 - Engineering Exploration "}]


"""new student and dorm room models

Revision ID: 426a10f0823e
Revises: 8cb9c80333a7
Create Date: 2023-11-29 13:05:24.789210

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '426a10f0823e'
down_revision = '8cb9c80333a7'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('student_room')
    with op.batch_alter_table('dorm_room', schema=None) as batch_op:
        batch_op.drop_constraint('dorm_room_ibfk_2', type_='foreignkey')
        batch_op.drop_column('student_id')

    with op.batch_alter_table('tbl_student', schema=None) as batch_op:
        batch_op.add_column(sa.Column('dorm_id', sa.Integer(), nullable=True))
        batch_op.add_column(sa.Column('room_id', sa.Integer(), nullable=True))
        batch_op.create_foreign_key(None, 'dorm_room', ['room_id'], ['id'])
        batch_op.create_foreign_key(None, 'dorm', ['dorm_id'], ['id'])

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('tbl_student', schema=None) as batch_op:
        batch_op.drop_constraint(None, type_='foreignkey')
        batch_op.drop_constraint(None, type_='foreignkey')
        batch_op.drop_column('room_id')
        batch_op.drop_column('dorm_id')

    with op.batch_alter_table('dorm_room', schema=None) as batch_op:
        batch_op.add_column(sa.Column('student_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True))
        batch_op.create_foreign_key('dorm_room_ibfk_2', 'tbl_student', ['student_id'], ['student_id'])

    op.create_table('student_room',
    sa.Column('student_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.Column('room_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.ForeignKeyConstraint(['room_id'], ['dorm_room.id'], name='student_room_ibfk_1'),
    sa.ForeignKeyConstraint(['student_id'], ['tbl_student.student_id'], name='student_room_ibfk_2'),
    mysql_collate='utf8mb4_general_ci',
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    # ### end Alembic commands ###


#!/usr/bin/env python3
# Convert a MOTHUR formatted count table into a "sparse" read_count tsv.

# import pandas as pd
import sys

def main():
    with open(sys.argv[1]) as handle:
        header_line = next(handle)
        library_ids = header_line.split()[2:]
        print('rrs_library_id', 'taxon_level', 'taxon_id', 'tally',
              sep='\t', file=sys.stdout)
        for line in handle:
            taxon_id, _, *tallies = line.split()
            for library_id, tally in zip(library_ids, tallies):
                if tally != '0':
                    print(library_id, 'unique', taxon_id, tally, sep='\t',
                          file=sys.stdout)

if __name__ == "__main__":
    main()


import os
import orjson
import vk_api
from vk_api.utils import get_random_id
from shanbot.settings import STATIC_FILES_FOLDER

picture_cache = dict()

class TextMessange(object):
    def __init__(self, vk, text, attachments=None, incoming_message=None,
                 to_id=None, keyboard=None):

        if incoming_message is None and to_id is None:
            raise AttributeError("Incoming_message and to_id are None")
        if text == "":
            raise AttributeError("Text field is empty")
        self.vk = vk
        self.text = text
        self.attachments = attachments
        self.incoming_message = incoming_message
        self.to_id = to_id
        self.keyboard = None if keyboard is None else keyboard.get_keyboard()

    def _send_message(self):
        peer_id = self.to_id if self.to_id is not None else self.incoming_message.from_id
        if isinstance(self.attachments, str):
            data = orjson.loads(self.attachments)
        else:
            data = self.attachments
        attachments = self._prepare_attachments(
            data["photo"]) if self.attachments is not None else None

        self.vk.messages.send(
            peer_id=peer_id,
            attachment=attachments,
            random_id=get_random_id(),
            message=self.text,
            keyboard=self.keyboard
        )

    def _prepare_attachments(self, attachment_dict):
        attachments = []
        upload = vk_api.VkUpload(self.vk)
        for pht in attachment_dict:
            if pht in picture_cache:
                photo = picture_cache[pht]
            else:
                path = os.path.join(STATIC_FILES_FOLDER, pht)
                photo = upload.photo_messages(photos=path)[0]
                picture_cache[pht] = photo
            attachments.append(
                'photo{}_{}_{}'.format(
                    photo['owner_id'], photo['id'], photo['access_key'])
            )
        return attachments

    def execute(self):
        self._send_message()


def stick(a):
    temp = [64]

    while sum(temp) > a:
        t = int(min(temp)/2)
        temp.remove(min(temp))
        temp.append(t)
        if sum(temp) < a:
            temp.append(t)

    return (len(temp))

n = int(input())
print(stick(n))