# Make scheduling decisions

import copy
import random
import time

from shakenfist.config import config
from shakenfist import db
from shakenfist import exceptions
from shakenfist import logutil
from shakenfist import util

LOG, _ = logutil.setup(__name__)

class Scheduler(object):
    def __init__(self):
        self.refresh_metrics()

    def refresh_metrics(self):
        metrics = {}

        for node in db.get_nodes():
            node_name = node['fqdn']
            try:
                metrics[node_name] = db.get_metrics(node_name)
            except exceptions.ReadException:
                pass

        self.metrics = metrics
        self.metrics_updated = time.time()

    def _has_sufficient_cpu(self, cpus, node):
        max_cpu = (self.metrics[node].get('cpu_max', 0) *
                   config.get('CPU_OVERCOMMIT_RATIO'))
        current_cpu = self.metrics[node].get('cpu_total_instance_vcpus', 0)
        if current_cpu + cpus > max_cpu:
            return False
        return True

    def _has_sufficient_ram(self, memory, node):
        # There are two things to track here... We must always have
        # RAM_SYSTEM_RESERVATION gb of RAM for operating system tasks -- assume
        # there is no overlap with existing VMs when checking this. Note as
        # well that metrics are in MB...
        available = (self.metrics[node].get('memory_available', 0) -
                     (config.get('RAM_SYSTEM_RESERVATION') * 1024))
        if available - memory < 0.0:
            return False

        # ...Secondly, if we're using KSM and over committing memory, we
        # shouldn't overcommit more than by RAM_OVERCOMMIT_RATIO
        instance_memory = (
            self.metrics[node].get('memory_total_instance_actual', 0) + memory)
        if (instance_memory / self.metrics[node].get('memory_max', 0) >
                config.get('RAM_OVERCOMMIT_RATIO')):
            return False

        return True

    def _has_sufficient_disk(self, instance, node):
        requested_disk = 0
        for disk in instance.db_entry.get('block_devices', {}).get('devices', []):
            # TODO(mikal): this ignores "sizeless disks", that is ones that
            # are exactly the size of their base image, for example CD ROMs.
            if 'size' in disk:
                if not disk['size'] is None:
                    requested_disk += int(disk['size'])

        if requested_disk > (int(self.metrics[node].get('disk_free', '0')) / 1024 / 1024 / 1024):
            return False
        return True

    def _find_most_matching_networks(self, requested_networks, candidates):
        if not candidates:
            return []

        # Find number of matching networks on each node
        candidates_network_matches = {}
        for node in candidates:
            candidates_network_matches[node] = 0

            # Make a list of networks for the node
            present_networks = []
            for inst in list(db.get_instances(only_node=node)):
                for iface in db.get_instance_interfaces(inst['uuid']):
                    if not iface['network_uuid'] in present_networks:
                        present_networks.append(iface['network_uuid'])

            # Count the requested networks present on this node
            for network in present_networks:
                if network in requested_networks:
                    candidates_network_matches[node] += 1

        # Store candidate nodes keyed by number of matches
        candidates_by_network_matches = {}
        for node in candidates:
            matches = candidates_network_matches[node]
            candidates_by_network_matches.setdefault(matches, []).append(node)

        # Find maximum matches of networks on a node
        max_matches = max(candidates_by_network_matches.keys())

        # Check that the maximum is not just the network node.
        # (Network node always has every network.)
        net_node = db.get_network_node()['fqdn']
        if (max_matches == 1 and
                candidates_by_network_matches[max_matches][0] == net_node):
            # No preference, all candidates are a reasonable choice
            return candidates

        # Return list of candidates that has maximum networks
        return candidates_by_network_matches[max_matches]

    def _find_most_matching_images(self, requested_images, candidates):
        candidates_image_matches = {}

        img_meta = db.get_image_metadata_all()
        if not img_meta:
            # No images in the cluster so return the original candidate list
            return candidates

        # Determine number of matching images per node
        for node in candidates:
            candidates_image_matches[node] = 0

            present_images = []
            for key, meta in img_meta.items():
                if not key.endswith('/' + node):
                    continue
                present_images.append(meta['url'])

            for image in present_images:
                if image in requested_images:
                    candidates_image_matches[node] += 1

        # Create dict of candidate lists keyed by number of image matches
        candidates_by_image_matches = {}
        for node in candidates:
            matches = candidates_image_matches[node]
            candidates_by_image_matches.setdefault(matches, [])
            candidates_by_image_matches[matches].append(node)

        # If no matches, return the original candidate list
        if len(candidates_by_image_matches) == 0:
            return candidates

        # Return all candidates that have the highest number of image matches
        max_matches = max(candidates_by_image_matches.keys())
        return candidates_by_image_matches[max_matches]

    def place_instance(self, instance, network, candidates=None):
        with util.RecordedOperation('schedule', instance):
            log_ctx = LOG.withObj(instance)

            diff = time.time() - self.metrics_updated
            if diff > config.get('SCHEDULER_CACHE_TIMEOUT'):
                self.refresh_metrics()

            if candidates:
                log_ctx.info('Scheduling %s forced as candidates' %
                             candidates)
                db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                             'Forced candidates', None, str(candidates))
                for node in candidates:
                    if node not in self.metrics:
                        raise exceptions.CandidateNodeNotFoundException(node)
            else:
                candidates = []
                for node in self.metrics.keys():
                    candidates.append(node)
            log_ctx.info('Scheduling %s start as candidates' % candidates)
            db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                         'Initial candidates', None, str(candidates))
            if not candidates:
                raise exceptions.LowResourceException('No nodes with metrics')

            # Can we host that many vCPUs?
            for node in copy.copy(candidates):
                max_cpu = self.metrics[node].get('cpu_max_per_instance', 0)
                if instance.db_entry['cpus'] > max_cpu:
                    candidates.remove(node)
            log_ctx.info('Scheduling %s have enough actual CPU' % candidates)
            db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                         'Have enough actual CPU', None, str(candidates))
            if not candidates:
                raise exceptions.LowResourceException(
                    'Requested vCPUs exceeds vCPU limit')

            # Do we have enough idle CPU?
            for node in copy.copy(candidates):
                if not self._has_sufficient_cpu(
                        instance.db_entry['cpus'], node):
                    candidates.remove(node)
            log_ctx.info('Scheduling %s have enough idle CPU' % candidates)
            db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                         'Have enough idle CPU', None, str(candidates))
            if not candidates:
                raise exceptions.LowResourceException(
                    'No nodes with enough idle CPU')

            # Do we have enough idle RAM?
            for node in copy.copy(candidates):
                if not self._has_sufficient_ram(
                        instance.db_entry['memory'], node):
                    candidates.remove(node)
            log_ctx.info('Scheduling %s have enough idle RAM' % candidates)
            db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                         'Have enough idle RAM', None, str(candidates))
            if not candidates:
                raise exceptions.LowResourceException(
                    'No nodes with enough idle RAM')

            # Do we have enough idle disk?
            for node in copy.copy(candidates):
                if not self._has_sufficient_disk(instance, node):
                    candidates.remove(node)
            log_ctx.info('Scheduling %s have enough idle disk' % candidates)
            db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                         'Have enough idle disk', None, str(candidates))
            if not candidates:
                raise exceptions.LowResourceException(
                    'No nodes with enough disk space')

            # What nodes have the highest number of networks already present?
            if network:
                requested_networks = []
                for net in network:
                    network_uuid = net['network_uuid']
                    if network_uuid not in requested_networks:
                        requested_networks.append(network_uuid)

                candidates = self._find_most_matching_networks(
                    requested_networks, candidates)
                log_ctx.info('Scheduling %s have most matching networks'
                             % candidates)
                db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                             'Have most matching networks', None,
                             str(candidates))

            # What nodes have the base image already?
            requested_images = []
            for disk in instance.db_entry['block_devices']['devices']:
                if disk.get('base'):
                    requested_images = disk.get('base')

            candidates = self._find_most_matching_images(
                requested_images, candidates)
            log_ctx.info('Scheduling %s have most matching images' % candidates)
            db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                         'Have most matching images', None, str(candidates))

            # Avoid allocating to network node if possible
            net_node = db.get_network_node()
            if len(candidates) > 1 and net_node['fqdn'] in candidates:
                candidates.remove(net_node['fqdn'])
                log_ctx.info('Scheduling %s are non-network nodes' % candidates)
                db.add_event('instance', instance.db_entry['uuid'], 'schedule',
                             'Are non-network nodes', None, str(candidates))

            # Return a shuffled list of options
            random.shuffle(candidates)
            return candidates


import numpy as np

class Loss:
    def __init__(self, func="categorical_cross_entropy") -> None:
        self.predicted = None
        self.trues = None
        self.func = func
        self.batch_loss = 0.0
        self.der_loss = None
        self.gradients = None

    def calc_loss(self, model_output, trues, layers):
        self.predicted = model_output
        self.trues = trues

        self.batch_loss = np.mean(getattr(self, self.func)()) # averages the sample losses to represent the batch loss

        for layer in layers:
            self.batch_loss += layer.reg_loss

        self.gradients = getattr(self, f"der_{self.func}")() # starts back propagation

    def categorical_cross_entropy(self):
        # used when there are multiple classes (categories) where one class is the correct answer. ex: a cat class and a dog class
        pred_clipped = np.clip(self.predicted, 1e-7, 1 - 1e-7) # ensures there are no values == 0 which would result in inf when log() used

        # get relevant pred values.  IE those that correspond to our desired trues
        if len(self.trues.shape) == 1: # if true given in a one dimensional array where idx = row and value = column (one-hot encoded)
            # pred = [[.9, .1], [.7, .3], [.2, .8]], true = [0, 0, 1]
            relevants = pred_clipped[range(len(self.trues)), self.trues]
        elif len(self.trues.shape) == 2: # if true given in an explicit 2-dimensional array
            # pred = [[.9, .1], [.7, .3], [.2, .8]], true = [[1, 0], [1, 0], [0, 1]]
            relevants = np.sum(pred_clipped * self.trues, axis=1)

        return(-np.log(relevants))

    def der_categorical_cross_entropy(self):
        # the derivative of CCE is simply -1 * true/pred
        # If labels are sparse, turn them into one-hot vector
        if len(self.trues.shape) == 1:
            self.trues = np.eye(len(self.predicted[0]))[self.trues]

        return (-self.trues / self.predicted) / len(self.trues) # we div by # samples to normalize the gradient for the optimizer

    def binary_cross_entropy(self):
        # self.trues must be a list of lists of binary values, each value corresponding to a respective neuron. eg [[0], [1]]

        # used when each neuron represents two classes, yes/no typically. One neuron = cat or not cat, but could also represent cat or dog
        pred_clipped = np.clip(self.predicted, 1e-7, 1 - 1e-7) # ensures there are no values == 0 which would result in inf when log() used

        if len(self.trues.shape) == 1:
            self.trues = np.eye(len(self.predicted[0]))[self.trues]

        sample_losses = -(self.trues * np.log(pred_clipped) + (1 - self.trues) * np.log(1 - pred_clipped)) # -1 * ( (true * log(pred)) + ((1-true) * log(1-pred)) )

        return np.mean(sample_losses, axis=-1)

    def der_binary_cross_entropy(self):
        pred_clipped = np.clip(self.predicted, 1e-7, 1 - 1e-7) # ensures there are no values == 0 which would result in inf when log() used
        gradients = -(self.trues / pred_clipped - (1 - self.trues) / (1 - pred_clipped)) / len(self.predicted[0])

        return gradients / len(self.predicted)

    def mean_squared_error(self):
        # (∑ (true - pred)**2) / num_outputs  ie == the mean of the squared differences of true and predicted values
        return np.mean((self.trues - self.predicted)**2, axis=-1)

    def der_mean_squared_error(self):
        num_samples = len(self.predicted)
        num_outputs = len(self.predicted[0])

        gradients = -2 * (self.trues - self.predicted) / num_outputs # ∂/∂x of (∑ (true - pred)**2) / num_outputs = -2 * (true-predicted) / num_outputs

        return gradients / num_samples # normalize by number of samples

    def mean_absolute_error(self):
        # like MSE, but less aggressive because it is linear rather than exponential.
        # It is used less frequently than MSE, but can also be paired with linear activation functions for scalar output
        # (∑ |true - pred|) / num_outputs  ie == the mean of the abs(differences) of true and predicted values
        return np.mean(np.abs(self.trues - self.predicted), axis=-1)

    def der_mean_absolute_error(self):
        num_samples = len(self.predicted)
        num_outputs = len(self.predicted[0])

        gradients = -np.sign(self.trues - self.predicted) / num_outputs # ∂/∂x = -1/num_outputs * (1 if diff>0 and -1 if diff<0) (bc derivative of abs val)

        return gradients / num_samples


def read_file(file: str) -> list[list[str]]:
    """
    Чтение отчёта из CSV-файла и возврат списка из списка сотрудников
    :param file: Путь к CSV-файлу с отчётом
    :return: Список списков с информацией о сотрудниках
    """
    employees = []
    with open(file, 'r') as f:
        for line in f:
            employees.append((line[1:-2].split(";")))
    f.close()
    return employees[1:]

def hierarchy(employees: list[list[str]]) -> None:
    """
        Вывод иерархии команд
        :param employees: Список списков с информацией о сотрудниках
        :return: None
    """
    my_dict = {}
    for employ in employees:
        my_dict[employ[1]] = my_dict.get(employ[1], "") + ";" + employ[2]

    for dep in my_dict:
        my_dict[dep] = set(my_dict[dep][1:].split(";"))

    for dep in my_dict:
        print(f"Департамент:\n {dep}")
        print("Команды:")
        for team in my_dict[dep]:
            print(f"  - {team}")
        print()

def department_report(employees: list[list[str]]) -> dict:
    """
            Создание отчета по департаментам
            :param employees: Список списков с информацией о сотрудниках
            :return: словарь ключами которого являются департаменты,
                     а значением - список информации о ключе
    """
    my_dict = {}
    for employ in employees:
        if employ[1] in my_dict:
            my_dict[employ[1]][0] += 1
            my_dict[employ[1]][1] = min(my_dict[employ[1]][1], int(employ[5]))
            my_dict[employ[1]][2] = max(my_dict[employ[1]][2], int(employ[5]))
            my_dict[employ[1]][3] += int(employ[5])
        else:
            my_dict[employ[1]] = [1, int(employ[5]), int(employ[5]), int(employ[5])]
    for dep in my_dict:
        my_dict[dep][3] = round(my_dict[dep][3] / my_dict[dep][0])

    for department, data in my_dict.items():
        print(f'Департамент:{department}\n'
              f'Численность:{data[0]}\n'
              f'Зарплатная вилка min={data[1]} - max={data[2]}\n'
              f'Средняя зарплата:{data[3]}\n')

    return my_dict

def save_department_report(employees: list[list[str]], file_path: str) -> None:
    """
        Сохранение сводного отчёта по департаментам в CSV-файл.
        :param employees: Список списков с информацией о сотрудниках
        :param file_path: Путь для сохранения CSV-файла
    """

    report = {}
    for employ in employees:
        if employ[1] in report:
            report[employ[1]][0] += 1
            report[employ[1]][1] = min(report[employ[1]][1], int(employ[5]))
            report[employ[1]][2] = max(report[employ[1]][2], int(employ[5]))
            report[employ[1]][3] += int(employ[5])
        else:
            report[employ[1]] = [1, int(employ[5]), int(employ[5]), int(employ[5])]
    for dep in report:
        report[dep][3] = round(report[dep][3] / report[dep][0])

    with open(file_path, 'w') as file:
        file.write('Департамент;Численность;Зарплатная вилка(min-max); Средняя зарплата\n')
        for line in report:
            file.write(line + ";" + str(report[line][0]) + ";"
                       + str(report[line][1]) + '-' + str(report[line][2]) + ";" + str(report[line][3]) + '\n')

if __name__ == '__main__':
    FILE = 'Corp_Summary.csv'
    choice = input("Введите \n'1',если хотите вывести департаменты и все команды, которые входят в него\n"
                   "'2', если хотите вывести сводный отчёт по департаментам\n"
                   "'3', если хотите сохранить сводный отчет\n")

    Staff = read_file(FILE)
    if choice == '1':
        hierarchy(Staff)
    elif choice == '2':
        department_report(Staff)
    elif choice == '3':
        name = input("Сохранить отчет как\n")
        save_department_report(Staff, name+".csv")
    else:
        print("Ошибка: выбран неправильный пункт меню")


import tkinter as tk
from tkinter import filedialog

class Notepad:
    def __init__(self, master):
        self.master = master
        self.master.title("메모장")
        self.master.geometry("500x500")
        self.filename = ""

        self.text = tk.Text(self.master)
        self.text.pack(expand=True, fill="both")

        self.create_menu()

    def create_menu(self):
        menubar = tk.Menu(self.master)

        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="새로 만들기", command=self.new_file)
        filemenu.add_command(label="열기", command=self.open_file)
        filemenu.add_command(label="저장", command=self.save_file)
        filemenu.add_separator()
        filemenu.add_command(label="종료", command=self.master.quit)
        menubar.add_cascade(label="파일", menu=filemenu)

        self.master.config(menu=menubar)

    def new_file(self):
        self.text.delete("1.0", tk.END)
        self.filename = ""

    def open_file(self):
        filetypes = [("텍스트 파일", "*.txt"), ("모든 파일", "*.*")]
        self.filename = filedialog.askopenfilename(filetypes=filetypes)
        if self.filename:
            with open(self.filename, "r") as f:
                self.text.delete("1.0", tk.END)
                self.text.insert("1.0", f.read())

    def save_file(self):
        if not self.filename:
            filetypes = [("텍스트 파일", "*.txt"), ("모든 파일", "*.*")]
            self.filename = filedialog.asksaveasfilename(filetypes=filetypes)
        if self.filename:
            with open(self.filename, "w") as f:
                f.write(self.text.get("1.0", tk.END))

def main():
    root = tk.Tk()
    app = Notepad(root)
    root.mainloop()

if __name__ == "__main__":
    main()


import slo
import cursor
import keyboard
import root
from rootobject import rootobject
from rootobject import textformat
from rootobject import alert
from rootobject import pointer
from rootobject.buckerwindow import text
from rootobject.buckerwindow import textarea

import pygame
import math

resize_d = 'R_D'
resize_s = 'R_S'

# V 모든 윈도우(창) 오브젝트
class BuckerWindow(rootobject.RootObject):
    close = pygame.transform.scale(pygame.image.load('./res/image/icon/close.png'), (20, 20)).convert_alpha()
    text_format = rootobject.default_text_format

    def __init__(self, program: str):
        self.program = program

        self.x = 0
        self.y = 0
        self.title_height = 24
        self.width = 150
        self.height = 150
        self.title = 'BuckerWindow'
        self.normal_border_color = slo.bucker['window']['normal_border_color']
        self.highlighted_border_color = slo.bucker['window']['highlighted_border_color']
        self.background_color = slo.bucker['window']['background_color']

        self.exit = False

        if self.title == 'BuckerWindow':
            self.title = self.program.split('/')[-1]
            if '\\' in self.title:
                self.title = self.program.split('//')[-1]

        self.directory = self.program[:-len(self.title) - 1]

        self.elements = []
        try:
            self.build_program(self.program)
        except SyntaxError:
            self.exit = True

        self.highlighted_object = None

        self.width += 2
        self.height += self.title_height + 1

        self.target_x = self.x
        self.target_y = self.y

        self.x_moving = True
        self.y_moving = True

        self.x = cursor.position[0] - self.width / 2
        self.y = cursor.position[1] - self.height / 2

        self.text_format.color = self.background_color

        self.moving = False
        self.original_x = None
        self.original_y = None
        self.start_moving_x = None
        self.start_moving_y = None

        self.window = pygame.Surface((0, 0))
        self.surface = pygame.Surface((self.width - 2, self.height - self.title_height - 1))
        self.surface.fill(self.background_color)

        self.resize_mode = None
        self.original_width = self.width
        self.original_height = self.height
        self.width_target = self.width
        self.height_target = self.height
        self.width_move = False
        self.height_move = False

        self.minimum_width = 100
        self.minimum_height = 100

        self.build_surface()

    def tick(self):
        if self.x_moving:
            self.x += (self.target_x - self.x) / (root.display.display_fps / slo.slo['appearance']['motion_speed'])
            if math.fabs(self.x - self.target_x) < 1:
                self.x = self.target_x
                self.x_moving = False

        if self.y_moving:
            self.y += (self.target_y - self.y) / (root.display.display_fps / slo.slo['appearance']['motion_speed'])
            if math.fabs(self.y - self.target_y) < 1:
                self.y = self.target_y
                self.y_moving = False

        if self.exit:
            self.y_moving = True
            self.target_y = root.display.size[1] + 1

            if root.display.size[1] <= self.y:
                self.destroy()

        if self.moving:
            self.target_x = cursor.position[0] - self.start_moving_x + self.original_x
            self.target_y = cursor.position[1] - self.start_moving_y + self.original_y

            self.x_moving = True
            self.y_moving = True

        if keyboard.keydown_key == pygame.K_q and (keyboard.lctrl or keyboard.rctrl) and rootobject.highlighted_object == self:
            self.exit = True

        if cursor.fpressed[0]:
            if self.x <= cursor.position[0] <= self.x + self.width:
                if self.y <= cursor.position[1] <= self.y + self.title_height and rootobject.get_on_cursor_window() == self:
                    self.moving = True
                    self.original_x = self.x
                    self.original_y = self.y
                    self.start_moving_x = cursor.position[0]
                    self.start_moving_y = cursor.position[1]

            if rootobject.get_on_cursor_window() == self:
                self.ahead()

            self.highlighted_object = None

        if cursor.epressed[0]:
            self.moving = False

            if self.x + self.width - self.title_height <= cursor.position[0] <= self.x + self.width and self.y <= cursor.position[1] <= self.y + self.title_height and rootobject.get_on_cursor_window() == self:
                self.exit = True

            self.resize_mode = None

        if rootobject.get_on_cursor_window() == self:
            if self.x + self.width - 6 <= cursor.position[0] and self.y < cursor.position[1] < self.y + self.height:
                pointer.pointer.mode = pointer.resize_width
                if cursor.fpressed[0]:
                    self.resize_mode = resize_d
                    self.original_width = self.width
            elif self.y + self.height - 6 <= cursor.position[1] and self.x < cursor.position[0] < self.x + self.width:
                pointer.pointer.mode = pointer.resize_height
                if cursor.fpressed[0]:
                    self.resize_mode = resize_s
                    self.original_height = self.height
            else:
                pointer.pointer.mode = pointer.normal
        else:
            pointer.pointer.mode = pointer.normal

        if self.resize_mode is not None:
            if self.resize_mode == resize_d:
                self.width_target = self.original_width + (cursor.position[0] - cursor.sposition[0])
                self.width_move = True
                if self.width_target < self.minimum_width:
                    self.width_target = self.minimum_width
            elif self.resize_mode == resize_s:
                self.height_target = self.original_height + (cursor.position[1] - cursor.sposition[1])
                self.height_move = True
                if self.height_target < self.minimum_height:
                    self.height_target = self.minimum_height

        if self.width_move:
            self.width += (self.width_target - self.width) / (root.display.display_fps / slo.slo['appearance']['motion_speed'])
            if math.fabs(self.width_target - self.width) < 1:
                self.width = self.width_target
                self.width_move = False
                self.build_surface()

        if self.height_move:
            self.height += (self.height_target - self.height) / (root.display.display_fps / slo.slo['appearance']['motion_speed'])
            if math.fabs(self.height_target - self.height) < 1:
                self.height = self.height_target
                self.height_move = False
                self.build_surface()

        if self.resize_mode is not None or self.width_move or self.height_move:
            self.build_surface()

        for element in self.elements:
            element.tick()

    def render(self):
        root.window.blit(self.window, (self.x, self.y))

        self.surface.fill(self.background_color)

        for element in self.elements:
            element.render()

        root.window.blit(self.surface, (1 + self.x, self.title_height + self.y))

    def build_surface(self):
        title_surface = self.text_format.render(self.title)

        border_color = self.highlighted_border_color if rootobject.highlighted_object == self else self.normal_border_color

        self.surface = pygame.Surface((round(self.width - 2), round(self.height - 1 - self.title_height)))

        self.window = pygame.Surface((self.width, self.height))
        self.window.fill(self.background_color)
        pygame.draw.rect(self.window, border_color, ((0, 0), (self.width, self.title_height)))
        pygame.draw.line(self.window, border_color, (0, 0), (0, self.height), 1)
        pygame.draw.line(self.window, border_color, (0, self.height), (self.width, self.height), 3)
        pygame.draw.line(self.window, border_color, (self.width, 0), (self.width, self.height), 3)
        self.window.blit(self.close, (self.width - self.close.get_width() - 2, 2))
        self.window.blit(title_surface, (rootobject.center(self.width, title_surface.get_width()), 0))

    def build_program(self, path):
        def exception(message):
            rootobject.add_object(alert.Alert(self.title, f'현재 실행하고 있는 프로그램의 {line_number + 1}번째 줄에 다음과 같은 오류가 발견되었습니다: \n' + str(message)))
            raise SyntaxError(message)

        try:
            code = open(path, 'r').read().split('\n')
        except UnicodeDecodeError:
            code = open(path, 'r', encoding='utf-8').read().split('\n')

        variables = {}

        for line_number in range(len(code)):
            line = code[line_number]

            if '?' in line: line = line[:line.index('?')]
            if len(line) <= 0: continue
            while line[-1] == ' ': line = line[:-1]

            sline = line.split()
            if sline[0] == 'set-raw':
                if len(sline) < 3:
                    exception('set-raw 구문의 변수 이름 또는 변수 값이 지정되어 있지 않습니다.')

                try:
                    variables[sline[1]] = eval(' '.join(sline[2:]))
                except Exception as e:
                    exception(str(e))

            elif sline[0] == 'set':
                if len(sline) < 3:
                    exception('set 구문의 변수 이름 또는 변수 값이 지정되어 있지 않습니다.')

                if sline[1] == 'TextFormat':
                    keys = ('font', 'size', 'color')

                    arguments = {}
                    for key in keys:
                        arguments[key] = None

                    for _i in range(len(sline)):
                        _i += 3
                        try:
                            word = sline[_i]
                        except IndexError:
                            break

                        if _i % 2 == 0:
                            if '_' in word: word = word.replace('_', ' ')
                            if '\\ ' in word: word = word.replace('\\ ', '_')

                            if last_key in keys:
                                if word[0] == '$':
                                    arguments[last_key] = variables[word]
                                else:
                                    arguments[last_key] = eval(word)
                        else:
                            last_key = word

                    arguments['font'] = arguments['font'].replace('|', '/')

                    if arguments['font'][0] == '%':
                        arguments['font'] = self.directory + arguments['font'][1:]

                    variables[sline[2]] = textformat.TextFormat(font=arguments['font'], size=arguments['size'], colour=arguments['color'])

            elif sline[0] == 'window-set':
                # noinspection PyBroadException
                try:
                    if sline[1] == 'x': self.x = eval(' '.join(sline[2:]))
                    elif sline[1] == 'y': self.y = eval(' '.join(sline[2:]))
                    elif sline[1] == 'title_height': self.title_height = eval(' '.join(sline[2:]))
                    elif sline[1] == 'width': self.width = eval(' '.join(sline[2:]))
                    elif sline[1] == 'height': self.height = eval(' '.join(sline[2:]))
                    elif sline[1] == 'title': self.title = eval(' '.join(sline[2:]))
                    elif sline[1] == 'border_color': self.normal_border_color = eval(' '.join(sline[2:]))
                    elif sline[1] == 'background_color': self.background_color = eval(' '.join(sline[2:]))
                    elif sline[1] == 'highlighted_background_color': self.highlighted_border_color = eval(' '.join(sline[2:]))
                except Exception as e:
                    exception(e)

            elif sline[0] == 'window-add':
                if len(sline) < 2:
                    exception('window-add 구문의 변수형이 지정되어 있지 않습니다.')

                arguments = {}
                last_key = ''

                if sline[1] == 'TextArea':
                    keys = ('x', 'y', 'width', 'height', 'value', 'text_format', 'background_color', 'writable')

                    for key in keys:
                        arguments[key] = None

                    for _i in range(len(sline)):
                        _i += 2
                        try:
                            word = sline[_i]
                        except IndexError:
                            break

                        if _i % 2 == 1:
                            if '_' in word: word = word.replace('_', ' ')
                            if '\\ ' in word: word = word.replace('\\ ', '_')

                            if last_key in keys:
                                if word[0] == '$':
                                    arguments[last_key] = variables[word]
                                else:
                                    arguments[last_key] = eval(word)
                        else:
                            last_key = word

                    self.elements.append(textarea.TextArea(x=arguments['x'], y=arguments['y'], width=arguments['width'], height=arguments['height'], value=arguments['value'], text_format=arguments['text_format'], background_color=arguments['background_color'], writable=arguments['writable'], window=self))
                elif sline[1] == 'Text':
                    keys = ('x', 'y', 'text', 'text_format')

                    for key in keys:
                        arguments[key] = None

                    for _i in range(len(sline)):
                        _i += 2
                        try:
                            word = sline[_i]
                        except IndexError:
                            break

                        if _i % 2 == 1:
                            if '_' in word: word = word.replace('_', ' ')
                            if '\\ ' in word: word = word.replace('\\ ', '_')

                            if last_key in keys:
                                if word[0] == '$':
                                    if word not in variables.keys():
                                        exception(f'{word}라는 변수는 지정되지 않았습니다.\n변수 형에 언더바(_)를 사용했을 가능성이 있습니다.')
                                    arguments[last_key] = variables[word]
                                else:
                                    try:
                                        arguments[last_key] = eval(word)
                                    except NameError as e:
                                        exception(f'{e}')
                        else:
                            last_key = word

                    self.elements.append(text.Text(x=arguments['x'], y=arguments['y'], text=arguments['text'], text_format=arguments['text_format'], window=self))
                else:
                    exception(f'변수형 {sline[1]}을(를) 알 수 없습니다.')

            else:
                exception(f'명령어 {sline[0]}을(를) 알 수 없습니다.')

        return False


from tkinter import *
from time import *

def update():
    time_str = strftime('%I:%M:%S %p')
    time_label.config(text=time_str)
    day_str = strftime('%d %b %Y, %A')
    day_label.config(text=day_str)
    zone_str = strftime('%Z')
    zone_label.config(text=zone_str)

    window.after(1000, update)

window = Tk()
window.config(background='black')
time_label = Label(window, font=('Arial', 50), fg='green', bg='black')
time_label.pack()
day_label = Label(window, font=('Arial', 25), fg='whiteSmoke',bg='black')
day_label.pack()
zone_label = Label(window, font=('courier', 20), fg='whiteSmoke',bg='black')
zone_label.pack()

update()

window.mainloop()


an = 1
count = 1
qntd = 1
b = 0
decisao = 'S'
a1 = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite qual a razão da PA: '))
print('Os 10 primeiro termos dessa PA com o primeiro termo {} e a razão {} são: '.format(a1, r))
a10 = a1 + (an - 1)*r
print(a10, end=', ')
an += 1
while an != 0 and qntd != 0:
    a10 = a1 + (an - 1)*r
    print(a10, end='')
    print(', ' if an != 0 else '', end='')
    an += 1
    count += 1
    if an == 11 and an != qntd+b:
        decisao = str(input('Deseja que sejam mostrados mais alguns termos da PA? (S/N)')).strip().upper()[0]
        if decisao == 'S':
            qntd = int(input('Quantos termos deseja que sejam mostrados? '))
            b = an
        elif decisao == 'N':
            an = 0
            qntd = 0
    if an == qntd+b:
        decisao = str(input('Deseja que sejam mostrados mais alguns termos da PA? (S/N)')).strip().upper()[0]
        if decisao == 'S':
            qntd = int(input('Quantos termos deseja que sejam mostrados a mais? '))
            b = an
        elif decisao == 'N':
            an = 0
            qntd = 0
print('\nA quantidade total de termos mostradas para esta PA foi de {}.'.format(count))

Atividades - Python/Exerc.026 - Progressão Aritimática com WHILE.py


import os

import numpy as np
import pandas as pd
import pymarketstore as pymkts

client = pymkts.Client(f"http://127.0.0.1:{os.getenv('MARKETSTORE_PORT',5993)}/rpc",
                       grpc=(os.getenv("USE_GRPC", "false") == "true"))

def test_leakage_limit_nrecords():
    data = np.array(
        [(pd.Timestamp("2019-01-01 01:02:03").value / 10 ** 9, 1, 2, 0)],
        dtype=[("Epoch", "i8"), ("Bid", "f4"), ("Ask", "f4"), ("Nanoseconds", "i4")],
    )
    data2 = np.array(
        [(pd.Timestamp("2019-01-01 01:02:03").value / 10 ** 9, 3, 4, 100_000_000)],
        dtype=[("Epoch", "i8"), ("Bid", "f4"), ("Ask", "f4"), ("Nanoseconds", "i4")],
    )
    client.write(data, "DEBUG/1Sec/TICK", isvariablelength=True)
    client.write(data2, "DEBUG/1Sec/TICK", isvariablelength=True)

    param = pymkts.Param(
        "DEBUG",
        "1Sec",
        "TICK",
        start=pd.Timestamp("2019-01-01 01:02:03.100000000"),
        limit=1,
        limit_from_start=True,
    )
    reply = client.query(param)
    df = reply.first().df()
    print(df)
    # if wrong, it means the first tick leaks outside of the interval starting within
    # `start` parameter
    cond1 = (
            (df.shape[0] == 1) and (df.Bid[0] == 3) and (df.Nanoseconds[0] == 100_000_000)
    )

    assert cond1

    param = pymkts.Param(
        "DEBUG",
        "1Sec",
        "TICK",
        end=pd.Timestamp("2019-01-01 01:02:03.000000000"),
        limit=1,
        limit_from_start=False,
    )
    reply = client.query(param)
    df = reply.first().df()
    print(df)
    # if wrong, it means the second tick leaks outside of the interval ending within
    # `end` parameter
    cond2 = (df.shape[0] == 1) and (df.Bid[0] == 1) and (df.Nanoseconds[0] == 0)

    assert cond2


from tqdm import tqdm

def Jaccard_Similarity(doc1, doc2, threshold=0.0):
    #ref: https://studymachinelearning.com/jaccard-similarity-text-similarity-metric-in-nlp/
    # List the unique words in a document
    words_doc1 = set(doc1.lower().split())
    words_doc2 = set(doc2.lower().split())

    # Find the intersection of words list of doc1 & doc2
    intersection = words_doc1.intersection(words_doc2)

    # Find the union of words list of doc1 & doc2
    union = words_doc1.union(words_doc2)

    ##IF Both Strings are empty return 0
    if(len(union)==0):
        return 0.0

    # Calculate Jaccard similarity score
    # using length of intersection set divided by length of union set

    jaccard_score = float(len(intersection)) / len(union)
    if(threshold>0.0):
        if (jaccard_score>threshold):
            return 1.0
        else:
            return 0.0
    return jaccard_score

def calculate_overlap_scores(s1):
    subject_overlap_scores = []
    predicate_overlap_scores = []
    object_overlap_scores = []
    overall_overlap_scores = []

    subject_overlap_scores_b = []
    predicate_overlap_scores_b = []
    object_overlap_scores_b = []
    overall_overlap_scores_b = []

    subject_coverage_scores = []
    predicate_coverage_scores = []
    object_coverage_scores = []
    overall_coverage_scores = []

    for i in tqdm(range(len(s1))):
        jaccard_subject_score = 0
        jaccard_predicate_score = 0
        jaccard_object_score = 0
        jaccard_overall_score = 0

        jaccard_subject_score_b = 0
        jaccard_predicate_score_b = 0
        jaccard_object_score_b = 0
        jaccard_overall_score_b = 0

        jaccard_subject_coverage_score = 0
        jaccard_predicate_coverage_score = 0
        jaccard_object_coverage_score = 0
        jaccard_overall_coverage_score = 0

        jaccard_subject_scores_list = []
        jaccard_predicate_scores_list = []
        jaccard_object_scores_list = []
        jaccard_overall_scores_list = []

        jaccard_subject_scores_list_b = []
        jaccard_predicate_scores_list_b = []
        jaccard_object_scores_list_b = []
        jaccard_overall_scores_list_b = []

        jaccard_subject_coverage_scores_list = []
        jaccard_predicate_coverage_scores_list = []
        jaccard_object_coverage_scores_list = []
        jaccard_overall_coverage_scores_list = []

        ctx_triples=s1['passage_triples'].iloc[i]
        question_triples = s1['query_triples'].iloc[i]

        for question_triple in question_triples:
            question_subject = question_triple[0]
            question_predicate = question_triple[1]
            question_object = question_triple[2]

            question_subject_coverage = 0
            question_predicate_coverage = 0
            question_object_coverage = 0
            question_overall_coverage = 0

            for ctx_triple in ctx_triples:
                ctx_subject = ctx_triple[0]
                ctx_predicate = ctx_triple[1]
                ctx_object = ctx_triple[2]

                temp_subject_score = Jaccard_Similarity(ctx_subject, question_subject)
                temp_predicate_score = Jaccard_Similarity(ctx_predicate, question_predicate)
                temp_object_score = Jaccard_Similarity(ctx_object, question_object)

                jaccard_subject_scores_list.append(temp_subject_score)
                jaccard_predicate_scores_list.append(temp_predicate_score)
                jaccard_object_scores_list.append(temp_object_score)
                temp_average_score = (temp_subject_score + temp_predicate_score + temp_object_score) / 3
                jaccard_overall_scores_list.append(temp_average_score)

                ###Threshold based method
                threshold = 0.8
                temp_subject_b_score = Jaccard_Similarity(ctx_subject, question_subject, threshold=threshold)
                temp_predicate_b_score = Jaccard_Similarity(ctx_predicate, question_predicate, threshold=threshold)
                temp_object_b_score = Jaccard_Similarity(ctx_object, question_object, threshold=threshold)

                jaccard_subject_scores_list_b.append(temp_subject_b_score)
                jaccard_predicate_scores_list_b.append(temp_predicate_b_score)
                jaccard_object_scores_list_b.append(temp_object_b_score)

                if(temp_subject_b_score==1 and temp_predicate_b_score==1 and temp_object_b_score==1):
                    jaccard_overall_scores_list_b.append(1)
                else:
                    jaccard_overall_scores_list_b.append(0)

                ###Till Here

                ###Coverage based method
                if(temp_subject_b_score==1):
                    question_subject_coverage = 1
                if(temp_predicate_b_score==1):
                    question_predicate_coverage = 1
                if(temp_object_b_score==1):
                    question_object_coverage = 1

            jaccard_subject_coverage_scores_list.append(question_subject_coverage)
            jaccard_predicate_coverage_scores_list.append(question_predicate_coverage)
            jaccard_object_coverage_scores_list.append(question_object_coverage)

            if(question_subject_coverage==1 and question_predicate_coverage==1 and question_object_coverage==1):
                jaccard_overall_coverage_scores_list.append(1)
            else:
                jaccard_overall_coverage_scores_list.append(0)

            ###Till Here

        if(len(jaccard_subject_scores_list)>0):
            jaccard_subject_score = sum(jaccard_subject_scores_list) / len(jaccard_subject_scores_list)
        if(len(jaccard_predicate_scores_list)>0):
            jaccard_predicate_score = sum(jaccard_predicate_scores_list) / len(jaccard_predicate_scores_list)
        if(len(jaccard_object_scores_list)>0):
            jaccard_object_score = sum(jaccard_object_scores_list) / len(jaccard_object_scores_list)
        if(len(jaccard_overall_scores_list)>0):
            jaccard_overall_score = sum(jaccard_overall_scores_list) / len(jaccard_overall_scores_list)

      ###Threshold based method

        if(len(jaccard_subject_scores_list_b)>0):
            jaccard_subject_score_b = sum(jaccard_subject_scores_list_b) / len(jaccard_subject_scores_list_b)
        if(len(jaccard_predicate_scores_list_b)>0):
            jaccard_predicate_score_b = sum(jaccard_predicate_scores_list_b) / len(jaccard_predicate_scores_list_b)
        if(len(jaccard_object_scores_list_b)>0):
            jaccard_object_score_b = sum(jaccard_object_scores_list_b) / len(jaccard_object_scores_list_b)
        if(len(jaccard_overall_scores_list_b)>0):
            jaccard_overall_score_b = sum(jaccard_overall_scores_list_b) / len(jaccard_overall_scores_list_b)

      ##Coverage based method

        if(len(jaccard_subject_coverage_scores_list)>0):
            jaccard_subject_coverage_score = sum(jaccard_subject_coverage_scores_list) / len(jaccard_subject_coverage_scores_list)
        if(len(jaccard_predicate_coverage_scores_list)>0):
            jaccard_predicate_coverage_score = sum(jaccard_predicate_coverage_scores_list) / len(jaccard_predicate_coverage_scores_list)
        if(len(jaccard_object_coverage_scores_list)>0):
            jaccard_object_coverage_score = sum(jaccard_object_coverage_scores_list) / len(jaccard_object_coverage_scores_list)
        if(len(jaccard_overall_coverage_scores_list)>0):
            jaccard_overall_coverage_score = sum(jaccard_overall_coverage_scores_list) / len(jaccard_overall_coverage_scores_list)

        subject_overlap_scores.append(jaccard_subject_score)
        predicate_overlap_scores.append(jaccard_predicate_score)
        object_overlap_scores.append(jaccard_object_score)
        overall_overlap_scores.append(jaccard_overall_score)

        subject_overlap_scores_b.append(jaccard_subject_score_b)
        predicate_overlap_scores_b.append(jaccard_predicate_score_b)
        object_overlap_scores_b.append(jaccard_object_score_b)
        overall_overlap_scores_b.append(jaccard_overall_score_b)

        ##Coverage based method
        subject_coverage_scores.append(jaccard_subject_coverage_score)
        predicate_coverage_scores.append(jaccard_predicate_coverage_score)
        object_coverage_scores.append(jaccard_object_coverage_score)
        overall_coverage_scores.append(jaccard_overall_coverage_score)

    #answer_contains = s1['answer_contain'].to_list()
    #s1 = pd.DataFrame()
    s1['subject_overlap_score']=subject_overlap_scores
    s1['predicate_overlap_score']=predicate_overlap_scores
    s1['object_overlap_score']=object_overlap_scores
    s1['overall_overlap_score']=overall_overlap_scores

    # s1['subject_overlap_score_b']=subject_overlap_scores_b
    # s1['predicate_overlap_score_b']=predicate_overlap_scores_b
    # s1['object_overlap_score_b']=object_overlap_scores_b
    # s1['overall_overlap_score_b']=overall_overlap_scores_b

    s1['subject_coverage_score']=subject_coverage_scores
    s1['predicate_coverage_score']=predicate_coverage_scores
    s1['object_coverage_score']=object_coverage_scores
    s1['overall_coverage_score']=overall_coverage_scores
    #s1['answer_contain'] = answer_contains

    s1.head(10)
    return s1


import os
import json
import click
from flask import current_app
from flask.cli import with_appcontext

@click.command("init-settings")
@with_appcontext
def init_settings_command():
    init_settings()
    click.echo("Initialized Settings")

def init_settings():
    settings = dict(
        receipt_image="images/logo.jpeg"
    )
    save_settings(settings)

def save_settings(settings):
    settings_path = os.path.join(current_app.instance_path, "settings.json")
    with open(settings_path, "w+") as settings_file:
        json.dump(settings, settings_file, indent=4)

def get_settings():
    settings_path = os.path.join(current_app.instance_path, "settings.json")
    with open(settings_path, "r") as settings_file:
        settings = json.load(settings_file)

    return settings


# use a hashtable to filter out duplicate items

# define a set of items that we want to reduce duplicates
items = ["apple", "pear", "orange", "banana", "apple",
         "orange", "apple", "pear", "banana", "orange",
         "apple", "kiwi", "pear", "apple", "orange"]

# create a hashtable to perform a filter
fruits = {}

# loop over each item and add to the hashtable
for item in items:
    fruits[item] = 0

# create a set from the resulting keys in the hashtable
result = set(fruits.keys())
print(result)

07.Data Structures & Algorithms/Foundation Algorithms - Lynda/06.Other Algorithms/Filter.py


import asyncio

import looptime

class MyEventLoop(looptime.LoopTimeEventLoop, asyncio.SelectorEventLoop):
    pass

def test_initial_time_is_zero_by_default():
    loop = MyEventLoop()
    assert loop.time() == 0

def test_initial_time_is_customized():
    loop = MyEventLoop(start=123)
    assert loop.time() == 123

def test_double_init_patches_once():
    original_loop = asyncio.SelectorEventLoop()
    original_select = original_loop._selector.select

    looptime_loop = looptime.patch_event_loop(original_loop)
    patched_select_1 = looptime_loop._selector.select
    assert patched_select_1 is not original_select

    looptime_loop.setup_looptime()
    patched_select_2 = looptime_loop._selector.select
    assert patched_select_2 is not original_select
    assert patched_select_2 is patched_select_1


import playsound
import pyautogui as pt
import keyboard
from time import sleep
import os
# import pyttsx3 as tts
from gtts import gTTS

def speak(text):
    tts = gTTS(text=text, lang='en-in')
    filename = "voices.mp3"
    tts.save(filename)
    playsound.playsound(filename)
    os.remove(filename)

def Spotify(name):
    speak("Playing it sir")
    os.startfile("C:\\Users\\surya\\AppData\\Roaming\\Spotify\\Spotify.exe")
    sleep(7)
    pt.click(x=82, y=123)
    sleep(1)
    pt.click(x=595, y=36)
    keyboard.write(name)
    sleep(4)
    pt.click(x=867, y=449)
    pt.click(x=867, y=449)


import os
import sys
#import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
#import pyproj
import numpy as np
import re

os.chdir("/Users/Eyota/projects/thesis")

#Bring in metros
mettot = pd.io.parsers.read_csv("output/metrototals.csv")
mettot = mettot.set_index('id')
mettot['shortname'] = mettot['MSAName'].apply(lambda x: re.search('^.*?[-,]',x).group(0)[:-1] + re.search(', [A-Z][A-Z]',x).group(0))

mettot['netchange'] = mettot['e_in_0910'] - mettot['e_out_0910']
mettot['pctchange'] = 1.0*mettot['netchange'] / mettot['pop']

topmet = mettot.sort('e_in_0910', ascending = False)[['shortname','pop','e_in_0910','e_out_0910','netchange']].iloc[0:20]
for var in ['pop','e_in_0910','e_out_0910','netchange']:
    topmet[var] = topmet[var].apply(lambda x: "{:,}".format(int(round(x))))
topmet.columns = ['MSA','Population','In-migrants','Out-migrants','Net Migration']
latex = file('output/tables/top_10_metros_in.tex', 'w')
latex.write(topmet.iloc[0:10].to_latex(index = False).replace('lllll','lrrrr')
)
latex.close()
topmet.to_csv('output/tables/top_10_metros_in.csv')
toppct = mettot.sort('pctchange', ascending = False)[['shortname','pop','e_in_0910','e_out_0910','netchange','pctchange']].iloc[0:20]
toppct_big = mettot[mettot['pop'] > 100000].sort('pctchange', ascending = False)[['shortname','pop','e_in_0910','e_out_0910','netchange','pctchange']].iloc[0:20]

mettot.sort('netchange', ascending = False)[['shortname','netchange']].iloc[0:10]

mettot.sort('netchange')[['shortname','netchange']].iloc[0:10]

mettot['gross'] = mettot['e_in_0910'] + mettot['e_out_0910']
mettot['absnet'] = mettot['netchange'].apply(abs)

1.0*mettot['absnet'].sum() / mettot['gross'].sum()   #7.1 percent

#In and out mig rate
mettot['inrate'] = 1.0* mettot['e_in_0910'] / mettot['pop']

mettot.sort('inrate', ascending = False)[['shortname','pop','e_in_0910','e_out_0910','netchange','inrate']].iloc[0:20]


import pandas as pd
import numpy as np
from textwrap import wrap
import re
import time

def parse_move(move):
    values = re.findall(r'\d+', move)
    return values

def parse_box_list(boxes_list):
    boxes_list = boxes_list[:-1]
    row_lists = []
    for row in boxes_list:
        new_val = wrap(row,4,replace_whitespace=False, drop_whitespace=False)
        for i in range(len(new_val)):
            new_val[i] = new_val[i].replace('[','')
            new_val[i] = new_val[i].replace(']','')
            new_val[i] = new_val[i].replace(' ','')
        row_lists.append(new_val)
    column_lists = [''] * 9
    for i in range(len(row_lists)):
        for j in range(0,9):
            column_lists[j]+=row_lists[i][j]
    return column_lists

def get_state_df(boxes_list):
    state_lists = parse_box_list(boxes_list)
    column_names= ['1','2','3','4','5','6','7','8','9']
    df = pd.DataFrame(state_lists).T
    df.columns = column_names
    return df

def perform_move(amount, column1, column2):
    return column1

if __name__ == "__main__":

    start_time = time.time()

    with open('input.txt') as file:
        lines = file.read().splitlines()

    # Get the current box state and store into a dataframe
    boxes_list = lines[:lines.index('')]
    df = get_state_df(boxes_list)
    df['NumberOfBoxes'] = 0
    df['FromColumn'] = 1
    df['ToColumn'] = 2

    moves_list = lines[lines.index('')+1:]
    for move in moves_list:
        values = parse_move(move)
        new_row = {'1': '',
                   '2': '',
                   '3': '',
                   '4': '',
                   '5': '',
                   '6': '',
                   '7': '',
                   '8': '',
                   '9': '',
                   'NumberOfBoxes': values[0],
                   'FromColumn': values[1],
                   'ToColumn': values[2]}
        df = df.append(new_row, ignore_index=True)

    print(df)
    print("--- Execution: %.4f ms ---" % (float(time.time() - start_time)*1000))
    #print(moves_list)


from bson import ObjectId

from src.model import Nypd
from ..contracts import nypd_contract as c

_NYPD_DOCUMENT_BINDINGS = {
    'id': c.ID,
    'date': c.DATE,
    'time': c.TIME,
    'precinct': c.PRECINCT,
    'offense_code': c.OFFENSE_CODE,
    'offense_description': c.OFFENSE_DESCRIPTION,
    'crime_outcome': c.CRIME_OUTCOME,
    'level_offense': c.LEVEL_OFFENSE,
    'borough': c.BOROUGH,
    'latitude': c.LATITUDE,
    'longitude': c.LONGITUDE,
    'age': c.AGE,
    'race': c.RACE,
    'sex': c.SEX
}

_UNSAFE_NYPD_FIELDS = [c.ID]

def nypd_from_document(doc: dict) -> Nypd:
    if doc is None:
        doc = {}

    def get_prop(k):
        if k == c.ID:
            return str(doc[c.ID]) \
                if c.ID in doc else None
        return doc.get(k)

    return Nypd(**{model_property: get_prop(doc_field)
                     for model_property, doc_field in _NYPD_DOCUMENT_BINDINGS.items()})

def nypd_to_document(nypd: Nypd, strip_unsafe=True) -> dict:
    doc = {doc_field: getattr(nypd, model_property)
           for model_property, doc_field in _NYPD_DOCUMENT_BINDINGS.items()
           if doc_field not in _UNSAFE_NYPD_FIELDS}

    if not strip_unsafe:
        doc[c.ID] = ObjectId(nypd.id)

    return doc


import tkinter as tk
import math

# Kích thước ban đầu của hình tròn
circle_radius = 50

# Vị trí ban đầu của hình tròn
circle_x, circle_y = 200, 200

# Kích thước ban đầu của hình tròn thứ hai
circle_radius_2 = 50

# Vị trí ban đầu của hình tròn thứ hai
circle_x_2, circle_y_2 = 100, 100

# Biến để kiểm tra xem thông báo đã được hiển thị hay chưa
notification_displayed = False

# Hàm để di chuyển hình tròn và thay đổi kích thước
def move_and_adjust_circles(event):
    global circle_radius, circle_x, circle_y, circle_radius_2, circle_x_2, circle_y_2, notification_displayed
    key = event.keysym
    if key == "Left":
        circle_x -= 10
    elif key == "Right":
        circle_x += 10
    elif key == "Up":
        circle_y -= 10
    elif key == "Down":
        circle_y += 10
    elif key == "k":
        circle_radius += 10
    elif key == "m" and circle_radius > 10:
        circle_radius -= 10
    elif key == "a":
        circle_x_2 -= 10
    elif key == "d":
        circle_x_2 += 10
    elif key == "w":
        circle_y_2 -= 10
    elif key == "s":
        circle_y_2 += 10
    elif key == "i":
        circle_radius_2 += 10
    elif key == "h" and circle_radius_2 > 10:
        circle_radius_2 -= 10

    # Kiểm tra xem hai hình tròn có chạm nhau không
    distance = math.sqrt((circle_x - circle_x_2) ** 2 + (circle_y - circle_y_2) ** 2)

    if distance < (circle_radius + circle_radius_2) and not notification_displayed:
        # Nếu chạm nhau và thông báo chưa được hiển thị, hiển thị thông báo
        canvas.create_text(200, 350, text="cxzc", fill="red", tags="message")
        notification_displayed = True

        # Đẩy hai hình tròn ra xa nhau
        angle = math.atan2(circle_y_2 - circle_y, circle_x_2 - circle_x)
        circle_x -= 20 * math.cos(angle)
        circle_y -= 20 * math.sin(angle)
        circle_x_2 += 20 * math.cos(angle)
        circle_y_2 += 20 * math.sin(angle)
    elif distance >= (circle_radius + circle_radius_2) and notification_displayed:
        # Nếu không chạm nhau và thông báo đã được hiển thị, xóa thông báo và thiết lập lại biến kiểm tra
        canvas.delete("message")
        notification_displayed = False

    # Cập nhật vị trí và kích thước của hình tròn thứ nhất
    canvas.coords(circle, circle_x - circle_radius, circle_y - circle_radius, circle_x + circle_radius,
                  circle_y + circle_radius)
    canvas.coords(label, circle_x, circle_y)

    # Cập nhật vị trí và kích thước của hình tròn thứ hai
    canvas.coords(circle_2, circle_x_2 - circle_radius_2, circle_y_2 - circle_radius_2, circle_x_2 + circle_radius_2,
                  circle_y_2 + circle_radius_2)
    canvas.coords(label_2, circle_x_2, circle_y_2)

# Tạo cửa sổ tkinter
root = tk.Tk()
root.title("Di chuyển và điều chỉnh kích thước hai hình tròn")

# Tạo canvas để vẽ hình tròn
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

# Vẽ hình tròn màu đỏ
circle = canvas.create_oval(circle_x - circle_radius, circle_y - circle_radius, circle_x + circle_radius,
                            circle_y + circle_radius, fill="red")

# Tạo nhãn để hiển thị tên
label = canvas.create_text(circle_x, circle_y, text="Hình Tròn Đỏ", fill="white")

# Vẽ hình tròn màu xanh
circle_2 = canvas.create_oval(circle_x_2 - circle_radius_2, circle_y_2 - circle_radius_2, circle_x_2 + circle_radius_2,
                              circle_y_2 + circle_radius_2, fill="blue")

# Tạo nhãn để hiển thị tên
label_2 = canvas.create_text(circle_x_2, circle_y_2, text="Hình Tròn Xanh", fill="white")

# Bắt sự kiện nhấn phím
root.bind("<Key>", move_and_adjust_circles)

# Đặt focus vào cửa sổ để bắt đầu nhận sự kiện từ bàn phím
canvas.focus_set()

# Chạy ứng dụng tkinter
root.mainloop()


import os, sys
import matplotlib

import matplotlib.pyplot as plt
RESULTS_DIR = '../../../bin/execution_times/'
TABLES_DIR = './'

matplotlib.use("pgf")
matplotlib.rcParams.update({
    "pgf.texsystem": "pdflatex",
    'font.family': 'serif',
    'font.size' : 18,
    'text.usetex': True,
    'pgf.rcfonts': False,
})

def read_times(filename):
    sum_s = 0
    sum_b = 0
    n = 0
    with open(filename) as f:
        for r in f:
            s, b = map(float, r.split())
            sum_s += s
            sum_b += b
            n += 1

    return sum_s/n, sum_b/n

def plot_times(sizes, solution, baseline):

    plt.title("Execution time with different input sizes")

    fig, ax1 = plt.subplots()
    ax1.set_xlabel('Input size (number of tweets)')

    color = 'darkslategrey'
    ax1.set_ylabel('Basic A-Priori time (s)', color=color)
    ax1.plot(sizes, baseline, color=color, marker='o')
    ax1.tick_params(axis='y', labelcolor=color)

    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

    color = 'midnightblue'
    ax2.set_ylabel('Efficient A-Priori time (s)', color=color)  # we already handled the x-label with ax1
    ax2.set_ylim([0, 5.9])
    ax2.plot(sizes, solution, color=color, marker='X')
    ax2.tick_params(axis='y', labelcolor=color)

    fig.tight_layout()  # otherwise the right y-label is slightly clipped
    plt.savefig(f"{TABLES_DIR}times.pgf")
    # plt.plot(sizes, solution)
    # plt.plot(sizes, baseline)

if __name__ == '__main__':
    base = ((sys.argv[0][:sys.argv[0].rfind('/') + 1]).rstrip('/') or '.') + '/'
    TABLES_DIR = f"{base}{TABLES_DIR}"

    sizes = []
    solution = []
    baseline = []
    for filename in sorted(os.listdir(f'{base}{RESULTS_DIR}'), key = int):
        sizes.append(int(filename))
        s, b = read_times(f"{base}{RESULTS_DIR}{filename}")
        solution.append(s)
        baseline.append(b)
    plot_times(sizes, solution, baseline)


#!/usr/bin/env python

import numpy
import matplotlib.pyplot as plt

eV_per_Ha = 27.211396641

file = open('energies.txt', 'r')
data = file.readlines()
file.close()

T1s = []
S1s = []

# Compute T1 and S1 relative energies
for i in range(1,len(data)):
   t = data[i].split()
   abs_S0 = float(t[1])
   abs_T1 = float(t[2])
   abs_S1 = float(t[3])
   T1s.append( (abs_T1 - abs_S0)*eV_per_Ha )
   S1s.append( (abs_S1 - abs_S0)*eV_per_Ha )

T1s = numpy.asarray(T1s)
T1_average = numpy.mean(T1s)
T1_SD = numpy.std(T1s)
S1s = numpy.asarray(S1s)
S1_average = numpy.mean(S1s)
S1_SD = numpy.std(S1s)

# Calculate and plot T1 histogram
n, bins, patches = plt.hist(T1s, 20, facecolor='red')
plt.title('T1 energy distribution over G09 functional')
plt.xlabel('T1 relative energy (eV)')
plt.ylabel('Number')
plt.text(1.1, 50, 'E = %6.3f $\pm$ %6.3f eV' % (T1_average, T1_SD))
plt.savefig('T1s.png')
plt.close()

# Calculate and plot S1 histogram
n, bins, patches = plt.hist(S1s, 20, facecolor='blue')
plt.title('S1 energy distribution over G09 functional')
plt.xlabel('S1 relative energy (eV)')
plt.ylabel('Number')
plt.text(2.0, 50, 'E = %6.3f $\pm$ %6.3f eV' % (S1_average, S1_SD))
plt.savefig('S1s.png')


from clases import SFRegion2D, SFRegion3D
import auxFuncts
import numpy as np
import argparse

#load and initialization
parser = argparse.ArgumentParser()
parser.add_argument('--fname', required=True)
args = parser.parse_args()
inp = auxFuncts.readInput(args.fname)
spl=args.fname.split('.')
#print(spl)
ofil='.'.join(spl[:-1])+'.out'
ofilplot='.'.join(spl[:-1])+'.pdf'
print(ofil)
auxFuncts.checkInput(inp)
headerOutput='x  y  cluster'
if(inp['coord']=='Ra Dec'):
    headerOutput='ra  dec  cluster'
pts=np.genfromtxt(inp['filename'], skip_header=1, delimiter='\t')
if(inp['dim']==2):
    sfR2D=SFRegion2D(pts, inp['coord'])
    print('2D region created')
    print('Q parameter',sfR2D.q)
    if(inp['eps']=='None'):
        assert sfR2D.q <inp['Qlim'], "Check input Q limit for structure searching."
        sfR2D.calculateRho()
        print('RHO',sfR2D.rho)
        sfR2D.calculateEps()
        print('EPS',sfR2D.eps)
        sfR2D.setSignif(inp['Signif'])
        print('SIGNIF', sfR2D.signif)
        sfR2D.calculateNmin()
        print('NMIN',sfR2D.Nmin)
        sfR2D.detectStructs()
        npts=pts.shape[0]
        salid = np.hstack((pts,sfR2D.db.labels_.reshape(npts,1)))
        np.savetxt(ofil,salid,header=headerOutput)
        sfR2D.plotStructs(ofilplot)
    elif(inp['eps']>0):
        assert inp['Nmin']>0, "please input also a minimum number of points for dbscan"
        sfR2D.calculateRho()
        sfR2D.setEps(inp['eps'])
        sfR2D.setNmin(inp['Nmin'])
        print(sfR2D.eps)
        print(sfR2D.Nmin)
        sfR2D.detectStructs()
        npts=pts.shape[0]
        salid = np.hstack((pts,sfR2D.db.labels_.reshape(npts,1)))
        np.savetxt(ofil,salid,header=headerOutput)
        sfR2D.plotStructs(ofilplot)
    else:
        print('invalid value of eps, check documentation')
elif(inp['dim']==3):
    sfR3=SFRegion3D(pts, inp['coord'])
    print('2D region created')
    print('Q parameter',sfR3.q)
    sfR3.calculateRho()
    print('RHO',sfR3.rho)
    sfR3.calculateEps()
    print('EPS',sfR3.eps)
    sfR3.setSignif(inp['Signif'])
    print('SIGNIF', sfR3.signif)
    sfR3.calculateNmin()
    print('NMIN',sfR3.Nmin)
    sfR3.detectStructs()
    npts=pts.shape[0]
    salid = np.hstack((pts,sfR3.db.labels_.reshape(npts,1)))
    np.savetxt(ofil,salid,header=headerOutput)
    sfR3.plotStructs()
else:
    print('Now, only 2 or 3 dimensions')


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

# In[4]:

n = int(input())
s = [int(input()) for _ in range(n)]

# dp테이블만들기
# 계단이 1,2개인 경우
if n<3:
    print(sum(s))
# 아닌경우 점화식이용
else:
    dp = [0]*n
    dp[0] = s[0]
    dp[1] = s[0] + s[1]
    for i in range(2,n):
        dp[i] = max(dp[i-3]+s[i-1]+s[i], dp[i-2]+s[i])
    print(dp[n-1])

# In[ ]:


#!/usr/bin/env python3

import sys
import os
from argparse import ArgumentParser
from traintasticmanualbuilder.utils import detect_version

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: " + sys.argv[0] + " <format>", file=sys.stderr)
        sys.exit(1)

    args = sys.argv[2:]  # remove program name and format

    # Standard options:
    parser = ArgumentParser()
    parser.add_argument('--base-dir', default=os.path.join(os.path.dirname(__file__), 'traintasticmanual'))
    parser.add_argument('--output-dir')
    parser.add_argument('--language', default='en-us')
    parser.add_argument('--version', default=detect_version())

    if sys.argv[1] == 'html-single-page':
        from traintasticmanualbuilder.htmlsinglepage import HTMLSinglePageBuilder
        HTMLSinglePageBuilder(parser.parse_args(args)).build()
    else:
        print("Unknown format: " + sys.argv[1], file=sys.stderr)
        sys.exit(1)


# Jack McNamee - G00359656
# The Shunting Yard Algorithm for regular expressions

def shunting(infix):
    """ Return the infix reg expression in postfix """

    # convert the input to a stack-ish list and reverse
    infix = list(infix)[::-1]

    # operator stack
    operators = []

    # output list
    postfix = []

    # operator precedence
    prec = {'*':70, '?':60, '+':50, '.':40, '|':30, ')':20, '(':10}

    # loop through the input one char at a time
    while infix:
        # pop a char from the input
        char = infix.pop()

        # decide what to do based on the char
        if char == '(':
            # push an open brack to operators[]
            operators.append(char)

        elif char == ')':
            # pop operators[] until an open bracket is found
            while operators[-1] != '(':
                postfix.append(operators.pop())
            # remove the open bracket
            operators.pop()

        elif char in prec:
            # push any operators on operators[]
            # with higher precedence to the output
            while operators and prec[char] < prec[operators[-1]]:
                postfix.append(operators.pop())
            # push char to operators[]
            operators.append(char)

        else:
            # push the char to the output(postfix)
            postfix.append(char)

    # pop all operators to the output
    while operators:
        postfix.append(operators.pop())

    # convert postfix to a string
    return ''.join(postfix)


from litex.gen import *

from litex.gen.flow.actor import *
from litex.gen.flow.network import *
from litex.gen.actorlib import structuring, spi
from litex.gen.bank.description import *
from litex.gen.bank.eventmanager import *

from litex.soc.interconnect import stream
from litex.soc.interconnect import dma_lasmi

from liteusb.common import *

class LiteUSBDMAWriter(Module, AutoCSR):
    def __init__(self, lasmim):
        self.sink = sink = stream.Endpoint(user_description(8))

        # Pack data
        pack_factor = lasmim.dw//8
        pack = structuring.Pack(phy_description(8), pack_factor, reverse=True)
        cast = structuring.Cast(pack.source.payload.layout, lasmim.dw)

        # DMA
        writer = dma_lasmi.Writer(lasmim)
        self._reset = CSR()
        self.dma = InsertReset(spi.DMAWriteController(writer, mode=spi.MODE_SINGLE_SHOT))
        self.comb += self.dma.reset.eq(self._reset.r & self._reset.re)

        # Remove last/length/dst fields from payload
        self.comb += [
            pack.sink.valid.eq(sink.valid),
            pack.sink.payload.eq(sink.payload),
            sink.ready.eq(pack.sink.ready)
        ]

        # Graph
        g = DataFlowGraph()
        g.add_pipeline(pack, cast, self.dma)
        self.submodules += CompositeActor(g)

        # IRQ
        self.submodules.ev = EventManager()
        self.ev.done = EventSourcePulse()
        self.ev.finalize()
        self.comb += self.ev.done.trigger.eq(sink.valid & sink.last)

        # CRC
        self._crc_failed = CSRStatus()
        self.sync += \
            If(sink.valid & sink.last,
                self._crc_failed.status.eq(sink.error)
            )

class LiteUSBDMAReader(Module, AutoCSR):
    def __init__(self, lasmim, tag):
        self.source = source = stream.Endpoint(user_description(8))

        reader = dma_lasmi.Reader(lasmim)
        self.dma = spi.DMAReadController(reader, mode=spi.MODE_SINGLE_SHOT)

        pack_factor = lasmim.dw//8
        packed_dat = structuring.pack_layout(8, pack_factor)
        cast = structuring.Cast(lasmim.dw, packed_dat)
        unpack = structuring.Unpack(pack_factor, phy_description(8), reverse=True)

        # Graph
        cnt = Signal(32)
        self.sync += \
            If(self.dma.generator._shoot.re,
                cnt.eq(0)
            ).Elif(source.valid & source.ready,
                cnt.eq(cnt + 1)
            )
        g = DataFlowGraph()
        g.add_pipeline(self.dma, cast, unpack)
        self.submodules += CompositeActor(g)
        self.comb += [
            source.valid.eq(unpack.source.valid),
            source.last.eq(cnt == (self.dma.length*pack_factor-1)),
            source.length.eq(self.dma.length*pack_factor),
            source.data.eq(unpack.source.data),
            source.dst.eq(tag),
            unpack.source.ready.eq(source.ready)
        ]

        # IRQ
        self.submodules.ev = EventManager()
        self.ev.done = EventSourcePulse()
        self.ev.finalize()
        self.comb += self.ev.done.trigger.eq(source.valid & source.last)

class LiteUSBDMA(Module, AutoCSR):
    def __init__(self, port, lasmim_dma_wr, lasmim_dma_rd):
        self.submodules.writer = LiteUSBDMAWriter(lasmim_dma_wr)
        self.submodules.reader = LiteUSBDMAReader(lasmim_dma_rd, port.tag)
        self.submodules.ev = SharedIRQ(self.writer.ev, self.reader.ev)
        self.comb += [
            port.source.connect(self.writer.sink),
            self.reader.source.connect(port.sink)
        ]


import re
import string
from collections import defaultdict

filename = 'CS210_Project_Three_Input_File.txt'
newfile = 'frequency.dat'

def ListFrequency():
    # Creates defaultdict named item_frequencies
    item_frequencies = defaultdict(int)

    # Opens file
    with open(filename, "r") as infile:
        # Reads each item without counting newline
	    lines = infile.read().splitlines()
	    for row in lines:
            # Adds frequency of item
		    item_frequencies[row] += 1

    # Prints each item and its frequency
    for item, freq in item_frequencies.items():
        print(item + ": " + str(freq))
    return 0

def ItemFrequency(v):
    count = 0

    # Opens file
    with open(filename, 'r') as infile:
        lines = infile.read().splitlines()
        for row in lines:
            # String must equal "row" to be added to "count"
            if v == row:
                count += 1

    # Prints user input and how many times the input appears in the list
    print(v, count)
    return 0

def FileTransfer():
    item_frequencies = defaultdict(int)

    # Opens file and reads each item
    with open(filename, "r") as infile:
	    lines = infile.read().splitlines()
	    for row in lines:
            # Adds frequency of item to defaultdict
		    item_frequencies[row] += 1

    # Writes item and its frequency onto the new file, frequency.dat
    with open(newfile, 'w') as outfile:
        for item, freq in item_frequencies.items():
            outfile.write(item + " " + str(freq) + "\n")

    return 0


from ths.nn.sequences.processcnnw1d import ProcessTweetsCNN1D
import tensorflow as tf
import sys

def main(epochs):
    print("Working:")
    #P = ProcessTweetsWord2VecOnePass2DCNNv2_1("data/cleantextlabels3.csv", "trained/embedding3.csv")
    #P = ProcessTweetsCNN1D("data/cleantextlabels7.csv", "data/glove.6B.50d.txt")
    #P = ProcessTweetsWord2VecTwoPassLSTMv2_1("data/cleantextlabels4.csv", "trained/embedding3-50d.csv")
    P = ProcessTweetsCNN1D("data/cleantextlabels7.csv", "data/glove.6B.100d.txt")

    #Bueno el model12cnnv2
    # Excelente el de modellstmatt1 con attention
    # El mejor fue modellstmatt2 con attention
    # also good modellstmatt3
    # el 4 con dropout
    # 2, 3 y 4 son buenos
    P.process("trained/modelcnnincepw8.json", "trained/modelcnnincepw8.h5", plot=False, epochs=epochs, vect_dimensions=100)
#joderme
if __name__ == "__main__":

    with tf.device('/GPU:1'):
        argv = sys.argv
        if len(argv) > 1:
            epochs = int(argv[1])
        else:
            epochs = 16
        main(epochs)


# Import Tools
# Use Flask to render a template
from flask import Flask, render_template, redirect, url_for

# Use PyMongo to interact with our Mongo database
from flask_pymongo import PyMongo

# Convert from Jupyter notebook to Python to use scraping code
import scraping

# Setup Flask
app = Flask(__name__)

# Use flask_pymongo to set up mongo connection
app.config["MONGO_URI"] = "mongodb://localhost:27017/mars_app"
mongo = PyMongo(app)

# Define the route for the HTML page
@app.route("/")
def index():
   mars = mongo.db.mars.find_one()
   return render_template("index.html", mars=mars)

# Set up scraping route
# Define it with def scrape()
@app.route("/scrape")
def scrape():
   mars = mongo.db.mars
   mars_data = scraping.scrape_all()
   mars.update_one({}, {"$set":mars_data}, upsert=True)
   return redirect('/', code=302)
if __name__ == "__main__":
   app.run()


import cv2
import numpy as np

import Vision as vis

# get img from the webcam
cap_size  = (1200, 1000)
map_shape = [1200,  800]
cap       = cv2.VideoCapture(2)                       # put 1 if an external webcam is used
cap.set(cv2.CAP_PROP_FRAME_WIDTH, cap_size[0])        # width
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,cap_size[1])        # height
cap.set(cv2.CAP_PROP_AUTO_EXPOSURE,1)                 # set auto exposure

robot_pos = np.array([])

while True :
    success, img = cap.read()
    if success :
        success2, true_map = vis.get_clean_map(img, map_shape)                  # get a clean map
        if success2 :
            robot_pos = vis.robot_detection(true_map)                           # find the robot, annotate on map
            goal_pos  = vis.goal_detection(true_map)                            # find the goal, annotate on map
            if robot_pos.size :
                obs_map = vis.get_global_search_map(true_map, robot_pos)        # find obstacles
                cv2.imshow("Obstacles", obs_map)

            true_map = vis.annotate_map(true_map, robot_pos, goal_pos)

        cv2.imshow("Map", true_map)
        cv2.imshow("Raw", img)                                    # display

    else:
        print("Couldn't capture image")
        break

    if (cv2.waitKey(1) & 0xFF) == ord('q'):                       # quit when 'Q' key is pressed
        break

cap.release()
cv2.destroyAllWindows()


# Importing Packages
import numpy as np
import matplotlib.pyplot as plt

from matplotlib import cm

def ploting(fx,bounds,step,plot_step):

    X = np.arange(bounds[0][0], bounds[0][1], plot_step)
    Y = np.arange(bounds[1][0], bounds[1][1], plot_step)
    X, Y = np.meshgrid(X, Y)
    Z=np.zeros_like(X)

    for i in range(len(X)):
       for j in range(len(Y)):
         matchig_pixcel_L,matchig_pixcel_L,z=fx([X[i,j],Y[i,j]],step)
         Z[i,j]=z

    # Plotting the Animation
    fig = plt.figure(figsize=(15, 7))
    ax1 = fig.add_subplot(121, projection='3d')
    mycmap = plt.get_cmap('gist_earth')
    surf=ax1.plot_surface(X, Y, Z, cmap=mycmap,linewidth=0.01)

    plt.colorbar(surf, shrink=0.5, aspect=5,ax=ax1)
    plt.show()


# https://leetcode.com/problems/teemo-attacking/

class Solution(object):

    # Submitted by @Jiganesh

    # TC : O(N)
    # SC : O(1)

    '''
    Runtime: 224 ms, faster than 52.38% of Python online submissions for Teemo Attacking.
    Memory Usage: 14.7 MB, less than 65.31% of Python online submissions for Teemo Attacking.
    '''
    def findPoisonedDuration(self, timeSeries, duration):
        """
        :type timeSeries: List[int]
        :type duration: int
        :rtype: int
        """

        totalTime = 0
        n = len(timeSeries)

        for i in  range(n):
            if (i != n-1)  and (timeSeries[i]+duration-1>= timeSeries[i+1]):
                totalTime+=timeSeries[i+1]-timeSeries[i]
            else:
                totalTime += duration

        return totalTime

        '''
        Example

        timeSeries = [1,5,7,8]  duration = 4

        poisonEffect remains from [t , t+ duration-1] (inclusive)

        poisonEffect Duration
        [1-4]  poison effect = 4
        [5-8]  poison effect 5 to 8 but after attack of 7 it will reset so it will be [5-7] poison effect = 2
               (5,6) because on 7 there will be next attack and this will be added in next part
        [7-10] poison effect 7 to 10 but after attack of 8 it will reset so it will be [7-8] poison effect =1
               (7) because on 8 there will be next attack and this will be added in next part
        [8-11] last element in timeSeries so it will have full duration poison effect = 4

        Hence Answer will be 11

        '''


#Escreva um programa que receba como entrada a quantidade de
#residentes na casa de cada funcionário de uma empresa, até que seja informado o
#número zero. Assegure que o usuário não informe uma quantidade inválida de residentes (por exemplo, número negativo).
#Em seguida, o programa deve exibir a quantidade média de residentes das casas dos
#funcionários e quantos funcionários moram em uma casa com 5 ou mais residentes.
func=0
func2=0
res=0
n=1
while n>0:
    n= int(input("Quantas pessoas moram com você?(apenas números naturais): "))
    if n>0:
        res=res+n
        func=func+1
    if n>=5:
        func2=func2+1
    while n<0:
        print("ERRO: O valor informado deve ser maior que zero")
        n= int(input("Quantas pessoas moram com você?(apenas números naturais)"))

media=res/func

print("\nVocê digitou 0, o programa se encerrou\n")
print("A média dos residêntes dos funcionários é {:.02f}, e {} funcionários moram com 5 pessoas ou mais".format(media, func2))


import json
import os
import re
import sys

stopwords = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours', 'yourself',
             'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers', 'herself', 'it', 'its', 'itself',
             'they',
             'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', 'these', 'those',
             'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does',
             'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at',
             'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',
             'above',
             'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then',
             'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',
             'most',
             'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't',
             'can', 'will', 'just', 'don', 'should', 'now', ]
punctuations = ['!', '"', '#', '$', '%', '&', '\'', ',', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=',
                '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']

dictionary = {}
spamCount = 0
spamFileno = 0
hamCount = 0
hamFileno = 0
uniquewords = set()
initialDict = {}
probabilityDict = {}

def appendfunc():
    for x in range(0, len(content)):
        if content[x] not in stopwords:
            if content[x] in punctuations:
                content[x] = content[x].replace(content[x], " ")
            bagofwords.append(content[x])

def initialList(initialDict):
    global spamCount, hamCount
    if (hamFlag == 1):
        initialDict['ham'] = initialDict['ham'] + 1

    if (spamFlag == 1):
        initialDict['spam'] = initialDict['spam'] + 1

    return initialDict

def assignZero():
    initialDict = {'spam': 0, 'ham': 0}

    return initialDict

def writeJSON(condProb):
    with open('nbmodel.txt', 'w+') as f:
        json.dump(condProb, f)

def calculatep():
    for x in range(0, len(bagofwords)):
        uniquewords.add(bagofwords[x])
        if bagofwords[x] not in dictionary:
            initialDict = assignZero()

        else:
            initialDict = dictionary[bagofwords[x]]
        initialDict = initialList(initialDict)
        dictionary[bagofwords[x]] = initialDict
        # print(initialDict)print the spam and ham count of a word
        # print(dictionary)
        # prints the word along with how many times it occours in spam and ham
        # print(len(uniqueSet))

def probdistribution():
    for key in dictionary:
        finalList = {}
        initialDict = dictionary[key]
        finalList['spam'] = (initialDict['spam'] + 1) / float(spamCount + len(uniquewords))
        finalList['ham'] = (initialDict['ham'] + 1) / float(hamCount + len(uniquewords))
        probabilityDict[key] = finalList
    writeJSON(probabilityDict)

for root, dirs, files in os.walk(sys.argv[1]):
    for i in range(0, len(files)):
        bagofwords = []
        hamFlag = 0
        spamFlag = 0
        if files[i] not in ['README.md', '.DS_Store', 'README.txt', 'LICENSE']:
            filename = root + '/' + files[i]
            # print(filename)
            f = open(filename, 'r', encoding="latin1")
            # print("hello")
            content = f.read()
            content = content.lower()

            content = content.split()
            # print contents
            appendfunc()

            # print(bagofwords)
            if (re.search(r'(.)*spam(.)*', root)):
                spamFlag = 1
                spamCount = spamCount + len(bagofwords)
                spamFileno = spamFileno + 1
            elif (re.search(r'(.)*ham(.)*', root)):
                hamFlag = 1
                hamCount = hamCount + len(bagofwords)
                hamFileno = hamFileno + 1
                # print(spamFileno)
                # print(hamFileno)
            calculatep()
probdistribution()
# print(probabilityDict)

# print("done")


from sklearn.decomposition import PCA
import numpy as np
import matplotlib.pyplot as plt

class PriorFalsification:
    '''
    This class contains methods to perform and visualize prior falsification based on PCA
    '''

    def __init__(self, zprior, zobs, npc=None):
        '''
        This function constructs the prior falsification object and performs PCA on the data
        Inputs:
            zprior: an [NxD] matrix of prior data realizations
            zobs: a [QxD] array of observed data
            npc (optional): integer specifying number of principal components to compute. If not specified then N principal components are used.

        Output:
            PF: PosteriorFalsification object with the following attributes:
                - eigvecs: a [DxC] matrix of principal component eigenvectors
                - Sprior: a [NxC] matrix of prior data scores
                - Sobs: a [QxC] array of observed data scores
                - eigvals: a [1xC] array of eigenvalues
                - var: a [1xC] array of component-wise variance fraction
                - cumvar: a [1xC] array of cumulative variance fraction
                - npc: integer specifying the number of PCs calculated
                - pca: sklearn.decomposition.PCA object fitted to zprior

        Defintion of dimensions:
            D: data dimensionality
            Q: number of observed data samples
            N: number of prior realizations
            C: number of principal components to calculate
        '''
        self.pca = PCA(n_components=npc)
        self.pca.fit(zprior)
        self.Sprior = self.pca.transform(zprior)
        self.Sobs = self.pca.transform(zobs)
        self.eigvecs = self.pca.components_
        self.eigvals = self.pca.explained_variance_
        self.var = self.pca.explained_variance_ratio_
        self.cumvar = np.cumsum(self.var)
        self.npc = self.Sprior.shape[1]

    def plot_scores(self, c1=0, c2=1):
        '''
        This function plots a scatter plot of prior and observed PC scores

        Inputs:
            c1 (optional): integer of first PC to plot (starting from 0)
            c2 (optional): integer of second PC to plot (starting from 0)

        '''

        plt.scatter(
            self.Sprior[:,c1], self.Sprior[:,c2],
            label='Prior',
            edgecolor='k',
            c=(0.5,0.5,0.5)
            )

        plt.scatter(
            self.Sobs[:,c1], self.Sobs[:,c2], 500,
            label='Obs',
            marker='*',
            edgecolor='k',
            c=(225/255,223/255,0/255)
            )

        plt.xlabel('PC '+str(c1+1)+' Score ('+str(np.round(self.var[c1]*100,2))+'%)',fontsize=16)
        plt.ylabel('PC '+str(c2+1)+' Score ('+str(np.round(self.var[c2]*100,2))+'%)',fontsize=16)
        plt.legend(fontsize=14)

    def plot_scree(self, npcs=None):
        '''
        This function generates a scree plot

        Inputs:
            npcs (optional): integer specifying the number of PCs to plot
        '''

        if npcs is None:
            n = self.npc
        else:
            n = npcs

        pc = list(range(0,n+1))
        variance =  np.concatenate((np.array([0]),self.cumvar[:n]))

        plt.plot(pc,variance,'-k',linewidth=4)
        plt.ylim((0,1))
        plt.xlabel('Principal Component Number',fontsize=14)
        plt.ylabel('Cumulative Variance Fraction',fontsize=14)
        plt.xticks(fontsize=12)
        plt.yticks(fontsize=12)


"""
def write_to_file(text):
    try:
        file = open('random_file.txt', 'a')
        file.write(text)
    except IOError:
        print("ERROR: Can't Open File.")
    finally:
        file.close()
        print(file.closed)
write_to_file("\nLast line and that;s all.")
"""
"""
file_name = "random_file.txt"
with open(file_name, "r") as file:
    reader = file.read()
print(file.closed)
print(reader)
# """
# store = ""
file_name = "some_random_file.txt"
# for i in range(65, 90+1):
#     store += chr(i)

with open (file_name, "r") as file:
    writer = file.read()
print(writer)

# for i in range(0, 10):
#     print(i)

# for ch in range(97, 123):
#     print(chr(ch))


#---------------------------------------------ASSIGNMENT 3-----------------------------------------
# If the marks obtained by a student in five different subjects are input through the keyboard,
# find out the aggregate marks and percentage marks obtained by the student.
# Assume that the maximum marks that can be obtained by a student in each subject is 100.

sub_1 = int(input("Enter the marks between 0 to 100 of Subject 1 : "))
sub_2 = int(input("Enter the marks between 0 to 100 of Subject 2 : "))
sub_3 = int(input("Enter the marks between 0 to 100 of Subject 3 : "))
sub_4 = int(input("Enter the marks between 0 to 100 of Subject 4 : "))
sub_5 = int(input("Enter the marks between 0 to 100 of Subject 5 : "))
total = sub_1 + sub_2 + sub_3 + sub_4 + sub_5
percentage  = total/5

print("Aggregate marks = ",total,"out of 500")
print("Percentage = ",percentage)


"""
Draw a horizontal rule
"""
from typing import Dict

def draw_horizontal_rule(obj_axis, p, p_rule):
    # type: (object, Dict) -> object
    """Draw a horizontal rule

    Args:
        obj_axis (object): a matplotlib axis object
        p (dict): parameters
        p_rule (dict): styles of the rule

    Returns:
        a matplotlib.patches.Polygon object
    """
    return obj_axis.axhline(
        p['at'],
        xmin=p['min'],
        xmax=p['max'],
        alpha=p_rule['opacity'],
        color=p_rule['color'],
        linestyle=p_rule['line']['style'],
        linewidth=p_rule['line']['width'],
        zorder=p_rule['which_layer']
        )


class Solution:
    def numIslands(self, grid) -> int:
        # 11110
        # 11010
        # 11000
        # 00000
        if not grid: return 0
        res = 0
        row = len(grid)
        col = len(grid[0])
        visit = [[False for _ in range(col)] for _ in range(row)]

        def helper(x, y):
            if x > row - 1 or x < 0 or y > col - 1 or y < 0 or grid[x][y] == "0" or visit[x][y]:
                return
            else:
                visit[x][y] = True
                helper(x + 1, y)
                helper(x - 1, y)
                helper(x, y + 1)
                helper(x, y - 1)

        for i in range(row):
            for j in range(col):
                if grid[i][j] == "1" and not visit[i][j]:
                    helper(i, j)
                    res += 1

        print(visit)
        print(res)
        # return res

# 11000
# 11000
# 00100
# 00011
grid = [["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"]]
Solution().numIslands(grid)


from functools import cache
from pyinstrument import Profiler

from src.instance_loader import InstanceLoader
from src.config import Config
from src.optimizer import Optimizer
from src.main import formulations
from typing import Dict, Set, List

def minimal_formulation_analysis(formulation_name: str) -> None:
    """
    Find all minimal sets of constraints for a given formulation.
    Minimal in the sense that removing any constraint from the set makes the formulation invalid
    (optimal value is better than the real one).

    Args:
        formulation_name: name of the formulation to analyze.
    """

    assert not config.n_instances_main, f'Cannot run minimal_formulation_analysis with n_instances != None'
    instance_loader = InstanceLoader(config)
    all_instances = instance_loader.load_instances()
    instance_names = ['small_R12hom_imp3_K3T2', 'small_R12hom_alt2_K2T2', 'small_RC12het_altimpinc3_K3T4',
                      'small_R12het_altimpinc3_K2T3']
    instances = [v for k, v in all_instances.items() if any(name in k for name in instance_names)]
    assert len(instances) == len(instance_names), f'Something went wrong when filtering instances.'

    # Get set of all constraints
    temp_formulation = formulations.get(formulation_name)(instances[0])
    temp_formulation.formulate()
    all_constraints = set(temp_formulation.constraints.keys())

    @cache
    def minimal_set(current_constraints: str) -> List[str]:
        """
        Find all minimal sets of constraints given a set of current constraints.
        Algorithm: for each constraint, test if the formulation is valid without it. If it is, call minimal_set on the
        remaining constraints. If no constraint can be removed, return current_constraints is a minimal set.

        Args:
            current_constraints: set of current constraints (string representation). It is assumed to be valid.

        Returns:
            List of all minimal sets of constraints.
        """
        # Retrieve current constraints
        current_constraints = eval(current_constraints)

        # Build the activations dictionary
        activations = {c: True if c in current_constraints else False for c in all_constraints}

        ans = []
        for constraint in current_constraints:
            activations[constraint] = False
            if formulation_is_valid(str(activations)):
                ans += minimal_set(str(current_constraints - {constraint}))
            activations[constraint] = True

        if not ans:
            return [str(current_constraints)]
        return ans

    @cache
    def formulation_is_valid(activations: str) -> bool:
        """
        Checks if the formulation is valid for the given instances and activations.
        Valid means that the optimal value of the problem corresponds to the known one.

        Args:
            activations: dictionary of constraints to activate or not (string representation).

        Returns:
            True if the formulation is valid for the given instances and activations, False otherwise.
        """
        # Retrieve activations
        activations = eval(activations)

        assert config.exception_when_non_optimal, f'Cannot validate formulation without exception_when_non_optimal.'
        for instance in instances:
            formulation = formulations.get(formulation_name)(instance, activations)
            optimizer = Optimizer(formulation, config)
            try:
                optimizer.run()
            except ValueError as e:
                return False

        return True

    ans = set(minimal_set(str(all_constraints)))
    final_list = []
    for a in ans:
        final_list.append((len(eval(a)), eval(a)))
    print(f'All constraints: \n  {len(all_constraints)}: {str(all_constraints)}')
    print(f'Minimal sets:')
    for size, s in sorted(final_list):
        print(f'  {size}: {str(s)}')

    # Print the corresponding activations for the yaml file
    for i, a in enumerate(ans):
        print(f'Minimal set {i}\n{formulation_name}:')
        for c in all_constraints:
            print(f'  {c}: {"true" if c in eval(a) else "false"}')

if __name__ == '__main__':
    prof = Profiler()
    prof.start()

    config = Config()
    minimal_formulation_analysis(config.formulation)

    prof.stop()
    print(prof.output_text(unicode=True, color=True))