import pygame
import random
from sprites import *
import os

class Game:
    def __init__(self):
        self.settings()
        pygame.init()
        pygame.mixer.init()
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.clock = pygame.time.Clock()
        self.running = True
        self.font_name = pygame.font.match_font('arial')
        self.load_data()

    def settings(self):
        """
        Задание начальных переменных
        :return: None
        """
        self.width = 1920
        self.height = 1080
        self.fps = 60

    def load_data(self):
        """
        Загрузка всех файлов, необходимых для проекта
        :return:
        """
        self.dir = os.path.dirname(__file__)
        self.fon = pygame.transform.scale(self.load_image('1.gif'),
                                          (self.width, self.height))

        img_dir = os.path.join(self.dir, 'img')
        self.player_1_sprite = LoadImage(os.path.join('img', 'player1_sprite.png'))
        self.player_2_sprite = LoadImage(os.path.join('img', 'player2_sprite.png'))
        self.blocks_sprite = LoadImage(
            os.path.join('img', 'platformIndustrial_sheet2.png'))
        self.weapon_sprite = LoadImage(
            os.path.join('img', 'Ak47 Custom Sheet.png'))

    def new(self):
        names = ['map.txt', 'map1.txt']
        with open(os.path.join(self.dir, random.choice(names)), 'r') as map1:
            self.blocks = map1.readlines()
        self.all_sprites = pygame.sprite.LayeredUpdates()
        self.platforms = pygame.sprite.Group()
        self.guns = pygame.sprite.Group()
        self.bullet_player_1 = pygame.sprite.Group()
        self.bullet_player_2 = pygame.sprite.Group()
        self.clouds = pygame.sprite.Group()
        self.player_1 = Player(self, self.player_1_sprite, 100)
        self.player_2 = Player(self, self.player_2_sprite, 1700)
        for y_cord, block_s in enumerate(self.blocks):
            for x_cord, block in enumerate(block_s):
                if block == '#':
                    Block(self, x_cord * 70 - 95, y_cord * 70 - 25)

        Weapon(self, 100, 500)
        Weapon(self, 900, 700)
        self.mob_timer = 0
        self.run()

    def run(self):
        self.playing = True
        while self.playing:
            self.clock.tick(self.fps)
            self.events()
            self.update()
            self.draw()
        pygame.mixer.music.fadeout(500)

    def update(self):
        self.all_sprites.update()
        self.control(self.player_1, self.bullet_player_2)
        self.control(self.player_2, self.bullet_player_1)
        if len(self.platforms) == 0:
            self.playing = False

    def control(self, player, gr_plr):
        """
        Контроль за основными столкновениями
        :param player: объект игрока
        :param gr_plr: группа со всеми объектами
        :return: None
        """
        if player.vel.y > 0:
            intersections = pygame.sprite.spritecollide(player, self.platforms, False)
            if intersections:
                for lowest in intersections:
                    for intersection in intersections:
                        if intersection.rect.bottom > lowest.rect.bottom:
                            lowest = intersection
                        if player.pos.x < lowest.rect.right + 10 and player.pos.x > lowest.rect.left - 10:
                            if player.pos.y < lowest.rect.centery:
                                player.pos.y = lowest.rect.top
                                player.vel.y = 0
                                player.jumping = False

        intersections = pygame.sprite.spritecollide(player, gr_plr, False)
        if intersections:
            player.kill()
            self.playing = False

        intersections = pygame.sprite.spritecollide(player, self.guns, False)
        for weapon in intersections:
            if not player.have_gun and not weapon.collected:
                player.have_gun = True
                weapon.collected = True
                weapon.weapon_owner = player

        if len(self.platforms) == 0:
            self.playing = False

    def events(self):
        """

        :return:
        """
        self.player_1.animate()
        self.player_1.acc = vector(0, 0.7)
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.player_1.acc.x = -1
        if keys[pygame.K_RIGHT]:
            self.player_1.acc.x = 1
        self.moving_player(self.player_1)
        self.player_2.animate()
        self.player_2.acc = vector(0, 0.7)
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            self.player_2.acc.x = -1
        if keys[pygame.K_d]:
            self.player_2.acc.x = 1

        self.moving_player(self.player_2)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.player_1.jump()
                if event.key == pygame.K_w:
                    self.player_2.jump()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_KP0 and self.player_1.have_gun:
                    a = Bullet(self, self.player_1.rect.x + 48, self.player_1.rect.y + 64,
                               self.player_1.side, self.bullet_player_1)
                if event.key == pygame.K_v and self.player_2.have_gun:
                    a = Bullet(self, self.player_2.rect.x + 48, self.player_2.rect.y + 64,
                               self.player_2.side, self.bullet_player_2)

    def moving_player(self, obj_player):
        """
        Отвечает за перенос игрока с одной стороны на другую в случае выхода за карту
        :param obj_player: Объект игрока
        :return: None
        """

        obj_player.acc.x += obj_player.vel.x * -0.12
        obj_player.vel += obj_player.acc
        if abs(obj_player.vel.x) < 0.1:
            obj_player.vel.x = 0
        obj_player.pos += obj_player.vel + 0.5 * obj_player.acc
        if obj_player.pos.x > 1920 + obj_player.rect.width / 2:
            obj_player.pos.x = 0 - obj_player.rect.width / 2
        if obj_player.pos.x < 0 - obj_player.rect.width / 2:
            obj_player.pos.x = 1920 - obj_player.rect.width / 2

        obj_player.rect.midbottom = obj_player.pos

    def draw(self):
        """
        Отрисовка всех элементов игры
        :return:
        """
        self.screen.blit(self.fon, (0, 0))
        self.all_sprites.draw(self.screen)
        pygame.display.flip()

    def load_image(self, name, colorkey=None):
        file_name = os.path.join('img', name)
        if not os.path.isfile(file_name):
            print(f"Файл с изображением '{file_name}' не найден")
            sys.exit()
        image = pygame.image.load(file_name)
        return image

    def start_screen(self):
        fon = pygame.transform.scale(self.load_image('fon.png'),
                                     (self.width, self.height))
        self.screen.blit(fon, (0, 0))
        font = pygame.font.Font(None, 30)
        text_coord = 50
        while True:
            for event in pygame.event.get():
                if not event.type == pygame.QUIT:
                    return

            pygame.display.flip()
            self.clock.tick(60)

g = Game()
g.start_screen()
while g.running:
    g.new()
    g.start_screen()

pygame.quit()


class Arranging_module():
    categorize_obj = None

    #key_value in dictonary
    #google_category []
    #category []
    def reverse_obs(category_list): #output list of google categories
        #for map_object in map_objects: #toremove
            #google_category = map_object["google_category"]
            #categorise(category_list, map_object)

            # transform category list into fitting google categories

    #def categorise(category_list, map_object):  # file path = path to file category.txt
        file_path = "categories.txt"
        fitting_categories = []
        try:
            with open(file_path, "r") as file:

                file_contents = file.read()
                lines = file_contents.strip().split('\n')
                for line in lines:
                    list = line.split(',')
                    if list[0] in category_list:
                        fitting_categories.extend(list[1:])
                return fitting_categories
                #map_object["category"] = fitting_categories

        except FileNotFoundError:
            print(f"File '{file_path}' not found.")
        except IOError:
            print(f"Error reading file '{file_path}'.")
        # map_object[]
    def categorize_obj2(map_objects):

        # helping function, input is google category, output is our category, if doesn't fit to any of our category output should be null
        # it returns list of categories which are related with google category, as it can happen that one google category fit for 2 or more of our categories
        def categorise(google_category, map_object):  # file path = path to file category.txt
            file_path = "categories.txt"
            fitting_categories = []
            try:
                with open(file_path, "r") as file:

                    file_contents = file.read()
                    lines = file_contents.strip().split('\n')
                    for line in lines:
                        list = line.split(',')
                        for elem in list:
                            if elem == google_category:
                                fitting_categories.append(list[0])
                    map_object["category"] = fitting_categories

            except FileNotFoundError:
                print(f"File '{file_path}' not found.")
            except IOError:
                print(f"Error reading file '{file_path}'.")

        for map_object in map_objects:
            google_category = map_object["google_category"]
            categorise(google_category,map_object)

            #extract google categories from map object

            #map_object[]
    def sort_asc(criterion,map_objects):
        map_objects = sorted(map_objects, key=lambda x: x[criterion]) #ascending_sort

    def sort_desc(criterion,map_objects):
        map_objects = sorted(map_objects, key=lambda x: x[criterion], reverse=True) #descending_sort

    # def start_arranging_module(**m_object_list):
    #     # -2 for None object
    #
    #     pass

    # def provide_objects():
    #     pass

#provide_object()


import copy
import logging

from django.utils.translation import ugettext_lazy as _
from rest_framework import viewsets

from backend.components.bcs import k8s
from backend.templatesets.legacy_apps.configuration.serializers import K8sSecretCreateOrUpdateSLZ
from backend.templatesets.legacy_apps.instance.constants import K8S_SECRET_SYS_CONFIG
from backend.uniapps import utils as app_utils
from backend.uniapps.application.base_views import BaseAPI
from backend.uniapps.application.utils import APIResponse
from backend.uniapps.resource.constants import DEFAULT_SEARCH_FIELDS
from backend.utils.errcodes import ErrorCode

from .base import ResourceOperate

logger = logging.getLogger(__name__)

class Secrets(viewsets.ViewSet, BaseAPI, ResourceOperate):

    category = 'secret'
    cate = 'K8sSecret'
    sys_config = K8S_SECRET_SYS_CONFIG

    def get_secrets_by_cluster_id(self, request, params, project_id, cluster_id):
        """查询secrets"""
        search_fields = copy.deepcopy(DEFAULT_SEARCH_FIELDS)

        search_fields.append("data.data")
        params.update({"field": ",".join(search_fields)})
        client = k8s.K8SClient(request.user.token.access_token, project_id, cluster_id, env=None)
        resp = client.get_secret(params)

        if resp.get("code") != ErrorCode.NoError:
            logger.error(u"bcs_api error: %s" % resp.get("message", ""))
            return resp.get("code", ErrorCode.UnknownError), resp.get("message", _("请求出现异常!"))
        data = resp.get("data") or []
        return 0, data

    def get(self, request, project_id):
        """ 获取项目下所有的secrets """
        cluster_dicts = self.get_project_cluster_info(request, project_id)
        cluster_data = cluster_dicts.get('results', {}) or {}

        data = []
        params = dict(request.GET.items())
        is_decode = request.GET.get('decode')
        is_decode = True if is_decode == '1' else False
        # get project namespace info
        namespace_dict = app_utils.get_ns_id_map(request.user.token.access_token, project_id)

        for cluster_info in cluster_data:
            cluster_id = cluster_info.get('cluster_id')
            # 当参数中集群ID存在时，判断集群ID匹配成功后，继续后续逻辑
            if params.get('cluster_id') and params['cluster_id'] != cluster_id:
                continue
            cluster_env = cluster_info.get('environment')
            code, cluster_secrets = self.get_secrets_by_cluster_id(request, params, project_id, cluster_id)
            # 单个集群错误时，不抛出异常信息
            if code != ErrorCode.NoError:
                continue
            self.handle_data(
                request,
                cluster_secrets,
                self.cate,
                project_id,
                cluster_id,
                is_decode,
                cluster_env,
                cluster_info.get('name', ''),
                namespace_dict=namespace_dict,
            )
            data += cluster_secrets

        # 按时间倒序排列
        data.sort(key=lambda x: x.get('createTime', ''), reverse=True)
        return APIResponse({"code": ErrorCode.NoError, "data": {"data": data, "length": len(data)}, "message": "ok"})

    def delete_secret(self, request, project_id, cluster_id, namespace, name):
        return self.delete_resource(request, project_id, cluster_id, namespace, name)

    def batch_delete_secrets(self, request, project_id):
        return self.batch_delete_resource(request, project_id)

    def update_secret(self, request, project_id, cluster_id, namespace, name):
        self.slz = K8sSecretCreateOrUpdateSLZ
        return self.update_resource(request, project_id, cluster_id, namespace, name)


class Solution:
    def move(self, r, c, d):
        if d > self.max_d:
            return 0
        if r < 0 or c <0 or r >= self.m or c >= self.n:
            return 1
        self.q.append([r,c,d])
        return 0

    def findPaths(self, m: int, n: int, max_d: int, r: int, c: int) -> int:
        self.m = m
        self.n = n
        self.q = []
        self.v = [[0]*n]*m
        self.max_d = max_d

        self.q.append([r,c,0])
        output = 0
        while len(self.q) > 0:
            r,c,d = self.q.pop(0)
            output += self.move(r,c-1,d+1)
            output += self.move(r-1,c,d+1)
            output += self.move(r,c+1,d+1)
            output += self.move(r+1,c,d+1)
        return output

print(Solution().findPaths(2,2,2,0,0))
print(Solution().findPaths(1,3,3,0,1))
print(Solution().findPaths(7,5,10,5,0))


from flask import Flask, render_template
import requests
import os

# master_ip = os.environ.get('MASTER_IP', '10.146.0.5:8080')
master_ip = os.environ.get('MASTER_IP', 'localhost:8001')
namespace = os.environ.get('NAMESPACE', 'default')

app = Flask(__name__)

@app.route('/')
def rolling_update_demo():
    data = requests.get('http://{}/api/v1/namespaces/{}/pods'.format(master_ip, namespace))
    pod_dict = data.json()
    items = pod_dict['items']
    ip_list = [item['status']['podIP'] for item in items if 'rolling-express' in item['metadata']['name']]
    server_list = []
    for ip in ip_list:
        page = requests.get('http://{}:8080'.format(ip))
        server_list.append(page.json())
    # server_list.append(dict([('Hostname', 'host1'), ('Color', 'blue')]))
    # server_list.append(dict([('Hostname', 'host2'), ('Color', 'blue')]))

    return render_template('index.html', servers=server_list)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

#class heatmap(self, plot_Timestamp):

#http://stackoverflow.com/questions/8653092/using-matplotlib-axes-with-ginput-and-imshow
class MyMplCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100, data=None, column_name=None):
        self.fig, self.axes = plt.subplots(figsize=(width, height), dpi=dpi)
        self.data = data
        self.column_name = column_name
        self.compute_initial_figure()

        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass

class HeatMapMplCanvas (MyMplCanvas):

    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)

    # https://plot.ly/python/heatmaps-contours-and-2dhistograms-tutorial/
    def compute_initial_figure(self):
        dt = self.data
        column_name = self.column_name

        df_in = dt[column_name].reset_index()
        z_day = dt[column_name].reset_index(drop=True)

        the_months, the_days, Z_dayXmonth = self.dates_to_dayXmonth(df_in, z_day)

        extent = [the_months[0], the_months[-1], the_days[0], the_days[-1]]

        self.axes.clear()
        self.axes.set_title(column_name)

        #http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html
        cax = self.axes.imshow(Z_dayXmonth, interpolation='none', extent=extent, origin='low', aspect=0.25)
        cbar = self.fig.colorbar(cax)

    def plot_Heatmap(self, column_name):

        hc = HeatMapMplCanvas(self.main_widget, width=5, height=4, dpi=100, data=self.df_day, column_name=column_name)

        #http://stackoverflow.com/questions/4528347/clear-all-widgets-in-a-layout-in-pyqt
        for i in reversed( range(self.qvBoxLayout.count()) ):
            self.qvBoxLayout.itemAt(i).widget().deleteLater()

        self.qvBoxLayout.addWidget(hc)


# 정수 N 입력
# 00시00분00초부터 N시59분59초까지 3이 단 하나라도 포함되어 있으면 카운트

#%%
n = int(input())
count=0;

#%%
for hour in range(n+1):
    for minute in range(60):
        for second in range(60):
            time = str(hour) + str(minute) + str(second)
            if '3' in time:
                count+=1

#%%
print(count)

python for coding test/Imple_page_113.py


from django.db import models
from django.contrib.auth import get_user_model
from datetime import time

"""
    Models for ThroughTheEyeOf Website

    All strings have a limit of 64 characters
    unless otherwise specified
"""

class Album(models.Model):
    """
    Contains:
        * album_title - String containing the name of the album
        * album_description - Description of the album
        * album_owner - Reference to the User Object who 'owns' this album
    """
    album_description = models.CharField(max_length=64)
    album_owner = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
        related_name='album_owner',
    )

    album_title = models.CharField(max_length=64)
    album_tags = models.CharField(max_length=256, blank=True, null=True)
    closed = models.BooleanField(default=False)

class Photo(models.Model):
    """
    Contains:
        * photo_time - Integer time of the photo taken
            Example: 2:34pm is stored as 1434 military time
        * photo_location - String name of location of where photo was taken
        * photo_album - Foreign Key Reference to the Album Model
            that 'owns' the photo
    """
    photo_date = models.DateField(auto_now=False, null=True)
    photo_time = models.TimeField(auto_now=False, null=True)
    photo_timezone = models.CharField(max_length=64, blank=False, default='UTC')
    photo_utc_time = models.TimeField(null=True)
    photo_location = models.CharField(blank=True, max_length=128, null=True)
    photo_path = models.CharField(max_length=256,null=True)
    photo_album = models.ForeignKey(
        Album,
        on_delete=models.CASCADE,
        related_name='photo_album',
    )


from A.B import *
S(23, 'azder', 's_')

def dfs(cnt, flag, hap):
    global ans
    if cnt == n:
        if hap < ans:
            ans = hap
        return

    if hap >= ans:
        return

    for i in range(n):
        if i in flag:
            continue
        flag[cnt] = i
        dfs(cnt + 1, flag, hap + board[cnt][i])
        flag[cnt] = -1

for test_case in range(1, int(input()) + 1):
    n = int(input())
    board = [list(map(int ,input().split())) for _ in range(n)]
    ans = 10e999
    flag = [-1] * n
    dfs(0,flag,0)

    print(f'#{test_case} {ans}')

E(23, 'azder', 's_')


# coding:utf8
from tkinter import *
from tkinter.constants import *

class APP:
    def __init__(self, master):
        list1 = ["青菜", "白菜", "菠菜", "黄瓜", "青菜", "白菜",
                 "菠菜", "黄瓜", "青菜", "白菜", "菠菜", "黄瓜"]
        frame = Frame(master)
        frame.pack(padx=5, pady=5)

        # 添加一个滚动条Scrollbar,靠右，填充。
        sb = Scrollbar(frame)
        sb.pack(side=RIGHT, fill=Y)

        # listbox 生成列表选框,selectmode设置选择模式，SINGLE单选，EXTENDED多选
        lb = Listbox(frame, width=30, selectmode=EXTENDED,
                     yscrollcommand=sb.set)
        lb.pack(fill=BOTH)
        sb.config(command=lb.yview)

        # insert 添加选项
        for key in list1:
            lb.insert(END, key)

        # 打印所有选项
        print(lb.get(0, END))
        # 删除选中的选项
        b1 = Button(frame, text="删除它", command=lambda x=lb: x.delete(ACTIVE))
        b1.pack(side=LEFT)

root = Tk()
win = APP(root)
root.mainloop()


from kubernetes import client, config
import time
import os

MINIO_ACCESS_KEY=os.environ.get("MINIO_ACCESS_KEY")
MINIO_SECRET_KEY=os.environ.get("MINIO_SECRET_KEY")

def create_deployment(apps_v1_api,env_vars=None):

    if env_vars is None:
        env_vars = {"MINIO_ACCESS_KEY":MINIO_ACCESS_KEY,"MINIO_SECRET_KEY":MINIO_SECRET_KEY}
    env_list = []
    for env_name, env_value in env_vars.items():
        env_list.append( client.V1EnvVar(name=env_name, value=env_value) )

    volume = client.V1Volume(
        name="data"
    )

    container = client.V1Container(
        name="minio",
        image="minio/minio",
        args=["server","/data"],
        volume_mounts=[client.V1VolumeMount(name="data",mount_path="/data")],
        env=env_list,
        image_pull_policy="Always",
        ports=[client.V1ContainerPort(container_port=9000)],
    )

    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "minio"}),
        spec=client.V1PodSpec(volumes=[volume],containers=[container]))

    spec = client.V1DeploymentSpec(
        selector=client.V1LabelSelector(match_labels={"app":"minio"}),
        replicas=1,
        template=template)

    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name="minio-deployment",labels={"app":"minio"}),
        spec=spec)

    apps_v1_api.create_namespaced_deployment(
        namespace="default", body=deployment
    )

def create_service():
    core_v1_api = client.CoreV1Api()
    body = client.V1Service(
        api_version="v1",
        kind="Service",
        metadata=client.V1ObjectMeta(
            labels={"app":"minio"},
            name="minio-service"
        ),
        spec=client.V1ServiceSpec(
            type="NodePort",
            selector={"app": "minio"},
            ports=[client.V1ServicePort(
                protocol="TCP",
                port=9000,
                target_port=9000,
                node_port=31000
            )]
        )
    )

    core_v1_api.create_namespaced_service(namespace="default", body=body)

def create_ingress(networking_v1_beta1_api):

    body = client.NetworkingV1beta1Ingress(
        api_version="networking.k8s.io/v1beta1",
        kind="Ingress",
        metadata=client.V1ObjectMeta(name="minio-ingress", labels={"app":"minio"}, annotations={
            "nginx.ingress.kubernetes.io/rewrite-target": "/"
        }),
        spec=client.NetworkingV1beta1IngressSpec(
            rules=[client.NetworkingV1beta1IngressRule(
                host="minio.kubernetes.local",
                http=client.NetworkingV1beta1HTTPIngressRuleValue(
                    paths=[client.NetworkingV1beta1HTTPIngressPath(
                        path="/",
                        backend=client.NetworkingV1beta1IngressBackend(
                            service_port=9000,
                            service_name="minio-service")

                    )]
                )
            )
            ]
        )
    )
    networking_v1_beta1_api.create_namespaced_ingress(
    namespace="default",
    body=body
    )
def crea():

    config.load_kube_config()
    apps_v1_api = client.AppsV1Api()
    networking_v1_beta1_api = client.NetworkingV1beta1Api()

    create_deployment(apps_v1_api)
    create_service()
    create_ingress(networking_v1_beta1_api)

if __name__ == "__main__":
    crea()


"""
Decision_tree_node_class class.
represent node of the decision tree.
"""

class Decision_tree_node_class(object):
    def __init__(self,attribute, depth, is_leaf, pred, children_dict):
        """
        constructor.
        :param attribute: feature of node
        :param depth: depth of the node in the tree
        :param is_leaf: boolean - indicates if the node is a leaf
        :param pred: prediction in case the node is a leaf
        :param children_dict: pointers to children according to feature val.
        """
        self.attribute = attribute
        self.depth = depth
        self.is_leaf = is_leaf
        self.pred = pred
        self.children_dict = children_dict


import os
import nibabel as nib
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage

filepath = "D:/fullTumourNiftys"
def get_moment_of_inertia(nib_obj):
	intensity_data = nib_obj.get_data()
	CoM = scipy.ndimage.measurements.center_of_mass(intensity_data)
	indices = np.indices(intensity_data.shape)
	indices = np.moveaxis(indices,0,3)
	sqdist_from_CoM = np.zeros(intensity_data.shape)
	sqdist_from_CoM[:,:,:] = (indices[:,:,:,0]-CoM[0])**2+(indices[:,:,:,1]-CoM[1])**2+(indices[:,:,:,2]-CoM[2])**2
	return np.sum(intensity_data*sqdist_from_CoM)

patients = os.listdir(filepath)

fig,ax = plt.subplots()
for patient in patients:
	I_arr = []
	scans = os.listdir(os.path.join(filepath,patient))
	for scan in scans:
		nibfile = nib.load(os.path.join(filepath,patient,scan))
		I_arr.append(get_moment_of_inertia(nibfile))
	I_arr = I_arr/I_arr[0]
	ax.plot(I_arr,label = patient)

ax.set_xlabel("Scan Number")
ax.set_ylabel("Moment of Inertia (HU/px^2)")
ax.legend()

plt.show()


# Lab 15 Q1 (v)

import numpy as np

def main():
    data = np.genfromtxt('bikeSharing.csv', delimiter=',')

    for temp in range(1, 40, 5):
        analyseTemp(data, temp, temp + 4)

def analyseTemp(data, minValue, maxValue):
    # the temperature values stored in the array are multiplied by 41

    higherTempCondition = (data[:, 9] * 41) >= minValue

    lowerTempCondition = (data[:, 9] * 41) <= maxValue

    subset = data[higherTempCondition & lowerTempCondition]

    meanValue = np.mean(subset[:, 13])

    print("For temp in range ", minValue, "to", maxValue, "the mean number of casual users was ", meanValue)

main()


import unittest
import random

from wordplay.wordplay import Wordplay, formatCipher

class WordplayTest(unittest.TestCase):

  WORDLIST1 = 'wordlists/test1.txt'
  WORDLIST2 = 'wordlists/test2.txt'
  SOLUTION2 = 'wordlists/result2.txt'
  PALINDROMES = 'wordlists/one-word-palindromes.txt'
  BIGPALINDROME = 'wordlists/big-palindrome.txt'
  SOLUTION_BIGPALINDROME = 'wordlists/result-big-palindrome.txt'
  SIMPLE = 'wordlists/simple.txt'
  FAMOUS = 'wordlists/famous-palindromes.txt'

  def setUp(self):
    self._anagrams = dict()
    self.get(WordplayTest.WORDLIST1)
    self.get(WordplayTest.WORDLIST2)
    self.get(WordplayTest.PALINDROMES)
    self.get(WordplayTest.BIGPALINDROME)

  def _simplePalindrome(self, wp):
    charList = list("WASITABARORABATISAW")
    random.shuffle(charList)

    solution = set(self._getLines(WordplayTest.SOLUTION_BIGPALINDROME))
    for out in wp.solvePalindrome("".join(charList),200):
      self.assertTrue(out in solution)

  def get(self, path):
    return self._anagrams.setdefault(path, Wordplay(path,
      multipleWords=True))

  def test_aaBuiltCorrectly(self):
    for pair in self._anagrams.items():
      path = pair[0]
      anagram = pair[1]

      words = self._getLines(path)
      for word in words:
        self.assertTrue( anagram.has(word) )

  def test_simplePalindrome(self):
    wp = self.get(WordplayTest.PALINDROMES)
    for palindrome in self._getLines(WordplayTest.PALINDROMES):
      out = list( wp.solvePalindrome(palindrome) )
      self.assertTrue( palindrome in out )

  def test_bigPalindrome(self):
    wp = self.get(WordplayTest.BIGPALINDROME)
    self._simplePalindrome(wp)

  def test_realWorld(self):
    wp = self.get(WordplayTest.SIMPLE)
    self._simplePalindrome(wp)

  def test_sanity(self):
    wp = self.get(WordplayTest.SIMPLE)
    ciphers = self._getLines(WordplayTest.FAMOUS)

    for cipher in ciphers:
      charMap = formatCipher(cipher)
      for palindrome in wp.solvePalindrome(cipher):
        outCharMap = formatCipher(palindrome)
        self.assertEqual(charMap, outCharMap)

  def test_oneWord(self):
    anagram = self.get(WordplayTest.WORDLIST1)
    solution = self._getLines(WordplayTest.WORDLIST1)
    start = solution[0]
    out = list(anagram.solveAnagram(start, len(solution) + 1))
    self.assertEqual(sorted(solution),sorted(out))

  def test_twoWords(self):
    anagram = self.get(WordplayTest.WORDLIST2)
    solution = self._getLines(WordplayTest.SOLUTION2)
    start = solution[0]
    solution = set(solution)
    out = set(anagram.solveAnagram(start, len(solution) + 30))
    self.assertEqual(solution, out)

  def _getLines(self, filename):
    solution = []
    with open(filename) as fp:
      for line in fp:
        line = line.upper()
        line = line.strip()
        solution.append(line)
    return solution


import socket
import sys
import random
import time
import re
import os

MAX_SIZE = 512

opcodes = {
    'read': 1,
    'write': 2,
    'data': 3,
    'ack': 4,
    'error': 5
}

mode_strings = ['netascii', 'octet', 'mail']

def make_packet(opcode, block_num):
    '''
    This function takes opcode and block number
    as parameters and outputs a bytearray with the
    appropriate header values. You can then cusomize
    this bytearray by appending to it, for instance
    when opcode = 'data' and you want to send a payload
    with the packet header.

    In the case of opcode = 'ack', sending the result of
    make_packet('ack', block_num) is sufficient to follow TFTP.
    '''
    pack = bytearray()
    pack.append(0)
    pack.append(opcodes[opcode])
    pack.append(0)
    pack.append(block_num)
    return pack

def extract_filepath(data):
    '''
    Extracts file path from bytes data
    First decodes bytes into utf-8
    Then the regex searches for a match where
        1) First char is a-z or A-Z
        2) 0+ alphanumeric chars that are not . follow
        3) Then one .
        4) Then at least one but possibly more chars a-z or A-Z
    If there is more than one match, throw error,
    perhaps because more than one file name entered,
    and if no match, throw different error
    '''
    data_str = data.decode('utf-8')
    file_path = re.findall(r'([a-zA-Z][\w^\.]*\.[a-zA-Z]+)', data_str)
    if len(file_path) > 1:
        raise ValueError('Please make sure only one file name is entered')
    elif len(file_path) == 0:
        raise ValueError('Did not recognize valid file name')
    else:
        return file_path[0]

def transmit(packet, socket, client, timeout):
    '''
    This function acts as a timer for re-sending packets
    It sends the packet to the client using the socket,
    and then while there's no response and current time
    is less than retransmit time, it listens for a response.

    If there is no response before retransmit time, it calls
    transmit again, which re-sends the message and re-sets the timer

    If res received is has an ERROR opcode,
    system exits
    '''
    res = None
    socket.sendto(packet, client)
    retransmit = time.time() + timeout
    while res == None and time.time() < retransmit:
        res, client = socket.recvfrom(MAX_SIZE + 4)
    if res == None:
        transmit(packet, socket, client, timeout)
    else:
        if res[3] == opcodes['error']:
            sys.exit('Received ERROR response')
        return res, client

def handle_WRQ(file_name, client, socket, timeout):
    '''
    Function to handle incoming WRQs

    Initializes empty array and empty set of ACKed packets
    Then sends initial ACK 0 to indicate readiness
    and listens for the first DATA packet to be received

    Inside the main loop, the most recent incoming data packet
    has its block number checked against previously ACKed packets.
    If the number has been previously ACKed, server sends the ACK
    again and waits for a response. This will continue until the
    server receives a packet with an un-ACKed block number.

    The server then finds the size of the data packet. If it is > 4,
    i.e. it is more than just a header, the data from positions [4:]
    are appended to all_data. If the size of the packet is < 516, TFTP
    says that data transmission has finished, and the server sends a
    final ACK and closes the connection.

    If data is 516 bytes, however, the transaction continues. An ACK
    is sent for the packet, the packet block number is added to the set
    of ACKed packets, and the server listens for a response. Once a response
    comes through, it is checked against packs_acked as above, and the
    process repeats until a packet of size < 516 bytes is received and ACKed

    Once all data has been transmitted, handle_WRQ then writes all_data
    to a file with the same name as the one the client transferred

    Finally, the socket is closed.
    '''

    all_data = []
    packs_acked = set()

    res = make_packet('ack', 0)
    socket.sendto(res, client)
    print('Sent ACK 0')

    data, client = socket.recvfrom(MAX_SIZE + 4)
    print(f'Received DATA {data[3]}')

    while True:

        while data[3] in packs_acked:
            print(f'Sent ACK {data[3]}')
            data, client = transmit(make_packet('ack', data[3]), socket, client, timeout)
            print(f'Received DATA {data[3]}')
        if sys.getsizeof(data) > 4:
            all_data.append(data[4:])
        if sys.getsizeof(data) < 516:
            socket.sendto(make_packet('ack', data[3]), client)
            packs_acked.add(data[3])
            print(f'Sent ACK {data[3]} (Final ACK)')
            break
        packs_acked.add(data[3])
        print(f'Sent ACK {data[3]}')
        data, client = transmit(make_packet('ack', data[3]), socket, client, timeout)
        print(f'Received DATA {data[3]}')

    with open(file_name, 'w') as f:
        file_text = ''
        for item in all_data:
            item_str = item.decode('utf-8')
            file_text += item_str
        f.write(file_text)

    socket.close()
    print('Connection Closed')

    return

def handle_RRQ(file_path, client, socket, timeout):
    '''
    This function tries to open file_path, and if
    it succeeds, saves its content as doc. Doc is then
    converted into bytes and split into 512-byte segments,
    each of which is given the required 4-byte TFTP header
    for a total packet size of 516 bytes

    These packets are added into a queue and then in turn
    sent to the client while
        1) Neither server nor client has timed out
        2) The # of ACKed packets < # total packets

    After transmitting a packet, if a response is not
    received within timeout number of seconds, the packet
    will be sent again

    Each packet is sent in order, and each subsequent packet is
    only sent once an ACK has been received for the preceding packet

    If all packets are sent and ACKed with no error,
    a success message is printed and the socket is closed.

    Else, an error is raised and the socket is closed.
    '''
    try:
        with open(file_path, 'rb') as f:
            doc = f.read()
    except:
        raise ValueError('Could not find file')

    doc_bytes = bytearray(doc)
    num_packets = len(doc_bytes) // 512 + 1
    packets = [x for x in range(num_packets)]
    for i in range(num_packets):
        packet = make_packet('data', i + 1)
        packet += bytearray(doc_bytes[:512])
        packets[i] = packet
        doc_bytes = doc_bytes[512:]

    # if total data bytes divisible by 512, must send final packet with data size 0
    doc_mod = len(doc_bytes) % 512
    if doc_mod == 0:
        packet = make_packet('data', len(packets))
        packets.append(packet)

    iter_pack = iter(packets)
    packs_acked = set()
    while len(packs_acked) < num_packets:
        packet = next(iter_pack, packet)
        pack_acked = packet[3] in packs_acked
        while pack_acked == False:
            res, client = transmit(packet, socket, client, timeout)
            print(f'Sent DATA {packet[3]}')
            while res[3] != packet[3]:
                res, client = transmit(packet, socket, client, timeout)
                print(f'Re-sent DATA {packet[3]}')
            if res[1] == opcodes['ack'] and res[3] == packet[3]:
                print(f'Received ACK {res[3]}')
                packs_acked.add(packet[3])
                pack_acked = True

    if max(packs_acked) == num_packets:
        print('All packets sent and ACKed')
    else:
        if len(packs_acked) > 0:
            err_ins = max(packs_acked)
        else:
            err_ins = None
        raise RuntimeError(f'An Error Occurred: Last outbound packet ACKed was {err_ins}')

    socket.close()
    print('Connection closed')

    return

def main():
    '''
    This function listens for incoming requests on the provided port number
    and once a request comes in, spins up another socket on which to complete
    the transaction and continues listening for new requests on the main port

    Depending on if the request is a RRQ or WRQ, the server calls either
    handle_RRQ or handle_WRQ using the new socket
    '''

    host = socket.gethostname()
    port = int(sys.argv[1])
    timeout = int(sys.argv[2]) / 1000
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet and UDP socket
    s.bind((host, port))

    print(f'Listening on port {port}...')
    print(f'Timeout {timeout} secs')

    while True:
        data, client = s.recvfrom(MAX_SIZE + 4) # 4 bytes for header, plus MAX_SIZE for data
        _s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        new_port = random.randint(1024, 65535)
        while new_port == port:
            new_port = random.randint(1024, 65535)
        _s.bind((host, new_port))
        print(f'Connection on port {new_port}')
        file_path = extract_filepath(data)
        if data[1] == opcodes['read']:
            handle_RRQ(file_path, client, _s, timeout)
        elif data[1] == opcodes['write']:
            handle_WRQ(file_path, client, _s, timeout)

if __name__ == '__main__':
    main()


def add_time(start_time, duration, starting_day=None):
    # Parse start time
    start_time_parsed, am_pm = start_time.split(" ")
    start_time_hours, start_time_minutes = map(int, start_time_parsed.split((":")))

    # Parse duration
    duration_hours, duration_minutes = map(int, duration.split(':'))

    # Total time
    total_minutes = start_time_minutes + duration_minutes
    total_hours = start_time_hours + duration_hours
    if total_minutes > 60:
        total_minutes = total_minutes % 60
        total_hours += 1

    # Days later
    if am_pm == "PM":
        total_hours += 12
    days_later = total_hours // 24
    if days_later == 1:
        days_later_str = f' (next day)'
    elif days_later > 1:
        days_later_str = f' ({days_later} days later)'
    else:
        days_later_str = ''

    # Define hours in AM PM period
    print(total_hours/24)
    total_hours = total_hours % 24
    print(total_hours)
    if total_hours>=0 and total_hours<12:
        am_pm = "AM"
        if total_hours == 0:
            total_hours = 12
    else:
        am_pm = "PM"
        if total_hours != 12:
            total_hours -= 12

    # Add day of week if given
    if starting_day:
        starting_day = starting_day.lower()
        weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
        start_weekday = weekdays.index(starting_day)
        end_weekday = (start_weekday + days_later) % 7
        day_of_week_str = f', {weekdays[end_weekday].capitalize()}'
    else:
        day_of_week_str = ''

    full_str=f'{total_hours}:{total_minutes:02d} {am_pm}{day_of_week_str}{days_later_str}'
    return full_str


import enum
import warnings
import weakref

from absl import logging
from dm_control import mjcf
from dm_control.composer import observation
from dm_control.rl import control
import dm_env
import numpy as np

warnings.simplefilter('always', DeprecationWarning)

_STEPS_LOGGING_INTERVAL = 10000

HOOK_NAMES = ('initialize_episode_mjcf',
              'after_compile',
              'initialize_episode',
              'before_step',
              'before_substep',
              'after_substep',
              'after_step')

_empty_function = lambda: None

def _empty_function_with_docstring():
  """Some docstring."""

_EMPTY_CODE = _empty_function.__code__.co_code
_EMPTY_WITH_DOCSTRING_CODE = _empty_function_with_docstring.__code__.co_code

def _callable_is_trivial(f):
  return (f.__code__.co_code == _EMPTY_CODE or
          f.__code__.co_code == _EMPTY_WITH_DOCSTRING_CODE)

class ObservationPadding(enum.Enum):
  INITIAL_VALUE = -1
  ZERO = 0

class EpisodeInitializationError(RuntimeError):
  """Raised by a `composer.Task` when it fails to initialize an episode."""

class _Hook:

  __slots__ = ('entity_hooks', 'extra_hooks')

  def __init__(self):
    self.entity_hooks = []
    self.extra_hooks = []

class _EnvironmentHooks:
  """Helper object that scans and memoizes various hooks in a task.

  This object exist to ensure that we do not incur a substantial overhead in
  calling empty entity hooks in more complicated tasks.
  """

  __slots__ = (('_task', '_episode_step_count') +
               tuple('_' + hook_name for hook_name in HOOK_NAMES))

  def __init__(self, task):
    self._task = task
    self._episode_step_count = 0
    for hook_name in HOOK_NAMES:
      slot_name = '_' + hook_name
      setattr(self, slot_name, _Hook())
    self.refresh_entity_hooks()

  def refresh_entity_hooks(self):
    """Scans and memoizes all non-trivial entity hooks."""
    for hook_name in HOOK_NAMES:
      hooks = []
      for entity in self._task.root_entity.iter_entities():
        entity_hook = getattr(entity, hook_name)
        # Ignore any hook that is a no-op to avoid function call overhead.
        if not _callable_is_trivial(entity_hook):
          hooks.append(entity_hook)
      getattr(self, '_' + hook_name).entity_hooks = hooks

  def add_extra_hook(self, hook_name, hook_callable):
    if hook_name not in HOOK_NAMES:
      raise ValueError('{!r} is not a valid hook name'.format(hook_name))
    if not callable(hook_callable):
      raise ValueError('{!r} is not a callable'.format(hook_callable))
    getattr(self, '_' + hook_name).extra_hooks.append(hook_callable)

  def initialize_episode_mjcf(self, random_state):
    self._task.initialize_episode_mjcf(random_state)
    for entity_hook in self._initialize_episode_mjcf.entity_hooks:
      entity_hook(random_state)
    for extra_hook in self._initialize_episode_mjcf.extra_hooks:
      extra_hook(random_state)

  def after_compile(self, physics, random_state):
    self._task.after_compile(physics, random_state)
    for entity_hook in self._after_compile.entity_hooks:
      entity_hook(physics, random_state)
    for extra_hook in self._after_compile.extra_hooks:
      extra_hook(physics, random_state)

  def initialize_episode(self, physics, random_state):
    self._episode_step_count = 0
    self._task.initialize_episode(physics, random_state)
    for entity_hook in self._initialize_episode.entity_hooks:
      entity_hook(physics, random_state)
    for extra_hook in self._initialize_episode.extra_hooks:
      extra_hook(physics, random_state)

  def before_step(self, physics, action, random_state):
    self._episode_step_count += 1
    if self._episode_step_count % _STEPS_LOGGING_INTERVAL == 0:
      logging.info('The current episode has been running for %d steps.',
                   self._episode_step_count)
    self._task.before_step(physics, action, random_state)
    for entity_hook in self._before_step.entity_hooks:
      entity_hook(physics, random_state)
    for extra_hook in self._before_step.extra_hooks:
      extra_hook(physics, action, random_state)

  def before_substep(self, physics, action, random_state):
    self._task.before_substep(physics, action, random_state)
    for entity_hook in self._before_substep.entity_hooks:
      entity_hook(physics, random_state)
    for extra_hooks in self._before_substep.extra_hooks:
      extra_hooks(physics, action, random_state)

  def after_substep(self, physics, random_state):
    self._task.after_substep(physics, random_state)
    for entity_hook in self._after_substep.entity_hooks:
      entity_hook(physics, random_state)
    for extra_hook in self._after_substep.extra_hooks:
      extra_hook(physics, random_state)

  def after_step(self, physics, random_state):
    self._task.after_step(physics, random_state)
    for entity_hook in self._after_step.entity_hooks:
      entity_hook(physics, random_state)
    for extra_hook in self._after_step.extra_hooks:
      extra_hook(physics, random_state)

class _CommonEnvironment:
  """Common components for RL environments."""

  def __init__(self, task, time_limit=float('inf'), random_state=None,
               n_sub_steps=None,
               raise_exception_on_physics_error=True,
               strip_singleton_obs_buffer_dim=False,
               delayed_observation_padding=ObservationPadding.ZERO,
               legacy_step: bool = True):
    """Initializes an instance of `_CommonEnvironment`.

    Args:
      task: Instance of `composer.base.Task`.
      time_limit: (optional) A float, the time limit in seconds beyond which an
        episode is forced to terminate.
      random_state: Optional, either an int seed or an `np.random.RandomState`
        object. If None (default), the random number generator will self-seed
        from a platform-dependent source of entropy.
      n_sub_steps: (DEPRECATED) An integer, number of physics steps to take per
        agent control step. New code should instead override the
        `control_substep` property of the task.
      raise_exception_on_physics_error: (optional) A boolean, indicating whether
        `PhysicsError` should be raised as an exception. If `False`, physics
        errors will result in the current episode being terminated with a
        warning logged, and a new episode started.
      strip_singleton_obs_buffer_dim: (optional) A boolean, if `True`,
        the array shape of observations with `buffer_size == 1` will not have a
        leading buffer dimension.
      delayed_observation_padding: (optional) An `ObservationPadding` enum value
        specifying the padding behavior of the initial buffers for delayed
        observables. If `ZERO` then the buffer is initially filled with zeroes.
        If `INITIAL_VALUE` then the buffer is initially filled with the first
        observation values.
      legacy_step: If True, steps the state with up-to-date position and
        velocity dependent fields. See Page 6 of
        https://arxiv.org/abs/2006.12983 for more information.
    """
    if not isinstance(delayed_observation_padding, ObservationPadding):
      raise ValueError(
          f'`delayed_observation_padding` should be an `ObservationPadding` '
          f'enum value: got {delayed_observation_padding}')

    self._task = task
    if not isinstance(random_state, np.random.RandomState):
      self._random_state = np.random.RandomState(random_state)
    else:
      self._random_state = random_state
    self._hooks = _EnvironmentHooks(self._task)
    self._time_limit = time_limit
    self._raise_exception_on_physics_error = raise_exception_on_physics_error
    self._strip_singleton_obs_buffer_dim = strip_singleton_obs_buffer_dim
    self._delayed_observation_padding = delayed_observation_padding
    self._legacy_step = legacy_step

    if n_sub_steps is not None:
      warnings.simplefilter('once', DeprecationWarning)
      warnings.warn('The `n_sub_steps` argument is deprecated. Please override '
                    'the `control_timestep` property of the task instead.',
                    DeprecationWarning)
    self._overridden_n_sub_steps = n_sub_steps

    self._recompile_physics_and_update_observables()

  def add_extra_hook(self, hook_name, hook_callable):
    self._hooks.add_extra_hook(hook_name, hook_callable)

  def _recompile_physics_and_update_observables(self):
    """Sets up the environment for latest MJCF model from the task."""
    self._physics_proxy = None
    self._recompile_physics()
    if isinstance(self._physics, weakref.ProxyType):
      self._physics_proxy = self._physics
    else:
      self._physics_proxy = weakref.proxy(self._physics)

    if self._overridden_n_sub_steps is not None:
      self._n_sub_steps = self._overridden_n_sub_steps
    else:
      self._n_sub_steps = self._task.physics_steps_per_control_step

    self._hooks.refresh_entity_hooks()
    self._hooks.after_compile(self._physics_proxy, self._random_state)
    self._observation_updater = self._make_observation_updater()
    self._observation_updater.reset(self._physics_proxy, self._random_state)

  def _recompile_physics(self):
    """Creates a new Physics using the latest MJCF model from the task."""
    if getattr(self, '_physics', None):
      self._physics.free()
    self._physics = mjcf.Physics.from_mjcf_model(
        self._task.root_entity.mjcf_model)
    self._physics.legacy_step = self._legacy_step

  def _make_observation_updater(self):
    pad_with_initial_value = (
        self._delayed_observation_padding == ObservationPadding.INITIAL_VALUE)
    return observation.Updater(
        self._task.observables, self._task.physics_steps_per_control_step,
        self._strip_singleton_obs_buffer_dim, pad_with_initial_value)

  @property
  def physics(self):
    """Returns a `weakref.ProxyType` pointing to the current `mjcf.Physics`.

    Note that the underlying `mjcf.Physics` will be destroyed whenever the MJCF
    model is recompiled. It is therefore unsafe for external objects to hold a
    reference to `environment.physics`. Attempting to access attributes of a
    dead `Physics` instance will result in a `ReferenceError`.
    """
    return self._physics_proxy

  @property
  def task(self):
    return self._task

  @property
  def random_state(self):
    return self._random_state

  def control_timestep(self):
    """Returns the interval between agent actions in seconds."""
    if self._overridden_n_sub_steps is not None:
      return self.physics.timestep() * self._overridden_n_sub_steps
    else:
      return self.task.control_timestep

class Environment(_CommonEnvironment, dm_env.Environment):
  """Reinforcement learning environment for Composer tasks."""

  def __init__(self, task, time_limit=float('inf'), random_state=None,
               n_sub_steps=None,
               raise_exception_on_physics_error=True,
               strip_singleton_obs_buffer_dim=False,
               max_reset_attempts=1,
               delayed_observation_padding=ObservationPadding.ZERO,
               legacy_step: bool = True):
    """Initializes an instance of `Environment`.

    Args:
      task: Instance of `composer.base.Task`.
      time_limit: (optional) A float, the time limit in seconds beyond which
        an episode is forced to terminate.
      random_state: (optional) an int seed or `np.random.RandomState` instance.
      n_sub_steps: (DEPRECATED) An integer, number of physics steps to take per
        agent control step. New code should instead override the
        `control_substep` property of the task.
      raise_exception_on_physics_error: (optional) A boolean, indicating whether
        `PhysicsError` should be raised as an exception. If `False`, physics
        errors will result in the current episode being terminated with a
        warning logged, and a new episode started.
      strip_singleton_obs_buffer_dim: (optional) A boolean, if `True`,
        the array shape of observations with `buffer_size == 1` will not have a
        leading buffer dimension.
      max_reset_attempts: (optional) Maximum number of times to try resetting
        the environment. If an `EpisodeInitializationError` is raised
        during this process, an environment reset is reattempted up to this
        number of times. If this count is exceeded then the most recent
        exception will be allowed to propagate. Defaults to 1, i.e. no failure
        is allowed.
      delayed_observation_padding: (optional) An `ObservationPadding` enum value
        specifying the padding behavior of the initial buffers for delayed
        observables. If `ZERO` then the buffer is initially filled with zeroes.
        If `INITIAL_VALUE` then the buffer is initially filled with the first
        observation values.
      legacy_step: If True, steps the state with up-to-date position and
        velocity dependent fields.
    """
    super().__init__(
        task=task,
        time_limit=time_limit,
        random_state=random_state,
        n_sub_steps=n_sub_steps,
        raise_exception_on_physics_error=raise_exception_on_physics_error,
        strip_singleton_obs_buffer_dim=strip_singleton_obs_buffer_dim,
        delayed_observation_padding=delayed_observation_padding,
        legacy_step=legacy_step)
    self._max_reset_attempts = max_reset_attempts
    self._reset_next_step = True

  def reset(self):
    failed_attempts = 0
    while True:
      try:
        return self._reset_attempt()
      except EpisodeInitializationError as e:
        failed_attempts += 1
        if failed_attempts < self._max_reset_attempts:
          logging.error('Error during episode reset: %s', repr(e))
        else:
          raise

  def _reset_attempt(self):
    self._hooks.initialize_episode_mjcf(self._random_state)
    self._recompile_physics_and_update_observables()
    with self._physics.reset_context():
      self._hooks.initialize_episode(self._physics_proxy, self._random_state)
    self._observation_updater.reset(self._physics_proxy, self._random_state)
    self._reset_next_step = False
    return dm_env.TimeStep(
        step_type=dm_env.StepType.FIRST,
        reward=None,
        discount=None,
        observation=self._observation_updater.get_observation())

  # TODO(b/129061424): Remove this method.
  def step_spec(self):
    """DEPRECATED: please use `reward_spec` and `discount_spec` instead."""
    warnings.warn('`step_spec` is deprecated, please use `reward_spec` and '
                  '`discount_spec` instead.', DeprecationWarning)
    if (self._task.get_reward_spec() is None or
        self._task.get_discount_spec() is None):
      raise NotImplementedError
    return dm_env.TimeStep(
        step_type=None,
        reward=self._task.get_reward_spec(),
        discount=self._task.get_discount_spec(),
        observation=self._observation_updater.observation_spec(),
    )

  def step(self, action):
    """Updates the environment using the action and returns a `TimeStep`."""
    if self._reset_next_step:
      self._reset_next_step = False
      return self.reset()

    self._hooks.before_step(self._physics_proxy, action, self._random_state)
    self._observation_updater.prepare_for_next_control_step()

    try:
      for i in range(self._n_sub_steps):
        self._substep(action)
        # The final observation update must happen after all the hooks in
        # `self._hooks.after_step` is called. Otherwise, if any of these hooks
        # modify the physics state then we might capture an observation that is
        # inconsistent with the final physics state.
        if i < self._n_sub_steps - 1:
          self._observation_updater.update()
      physics_is_divergent = False
    except control.PhysicsError as e:
      if not self._raise_exception_on_physics_error:
        logging.warning(e)
        physics_is_divergent = True
      else:
        raise

    self._hooks.after_step(self._physics_proxy, self._random_state)
    self._observation_updater.update()

    if not physics_is_divergent:
      reward = self._task.get_reward(self._physics_proxy)
      discount = self._task.get_discount(self._physics_proxy)
      terminating = (
          self._task.should_terminate_episode(self._physics_proxy)
          or self._physics.time() >= self._time_limit
      )
    else:
      reward = 0.0
      discount = 0.0
      terminating = True

    obs = self._observation_updater.get_observation()

    if not terminating:
      return dm_env.TimeStep(dm_env.StepType.MID, reward, discount, obs)
    else:
      self._reset_next_step = True
      return dm_env.TimeStep(dm_env.StepType.LAST, reward, discount, obs)

  def _substep(self, action):
    self._hooks.before_substep(
        self._physics_proxy, action, self._random_state)
    self._physics.step()
    self._hooks.after_substep(self._physics_proxy, self._random_state)

  def action_spec(self):
    """Returns the action specification for this environment."""
    return self._task.action_spec(self._physics_proxy)

  def reward_spec(self):
    """Describes the reward returned by this environment.

    This will be the output of `self.task.reward_spec()` if it is not None,
    otherwise it will be the default spec returned by
    `dm_env.Environment.reward_spec()`.

    Returns:
      A `specs.Array` instance, or a nested dict, list or tuple of
      `specs.Array`s.
    """
    task_reward_spec = self._task.get_reward_spec()
    if task_reward_spec is not None:
      return task_reward_spec
    else:
      return super().reward_spec()

  def discount_spec(self):
    """Describes the discount returned by this environment.

    This will be the output of `self.task.discount_spec()` if it is not None,
    otherwise it will be the default spec returned by
    `dm_env.Environment.discount_spec()`.

    Returns:
      A `specs.Array` instance, or a nested dict, list or tuple of
      `specs.Array`s.
    """
    task_discount_spec = self._task.get_discount_spec()
    if task_discount_spec is not None:
      return task_discount_spec
    else:
      return super().discount_spec()

  def observation_spec(self):
    """Returns the observation specification for this environment.

    Returns:
      An `OrderedDict` mapping observation name to `specs.Array` containing
      observation shape and dtype.
    """
    return self._observation_updater.observation_spec()


from Head import Head
from TailPart import TailPart

class Snake:
    def __init__(self, canvas, root):
        self.canvas = canvas
        self.root = root
        self.head = Head(canvas, root)
        self.tail_parts = []

        self.move_tail_parts()

    def add_new_tail_part(self):
        only_head_exists = len(self.tail_parts) == 0
        if only_head_exists:
            prev_tail_part = self.head.square
        else:
            prev_tail_part = self.tail_parts[len(self.tail_parts) - 1].square

        prev_tail_part_position = self.canvas.coords(prev_tail_part)
        self.tail_parts.append(TailPart(self.canvas, prev_tail_part_position[0], prev_tail_part_position[1]))

    def move_tail_parts(self):

        for i in range(len(self.tail_parts) - 1, -1, -1):
            if i == 0:
                prev_tail_part = self.head.square
            else:
                prev_tail_part = self.tail_parts[i - 1].square

            prev_tail_part_position = self.canvas.coords(prev_tail_part)
            self.tail_parts[i].move(prev_tail_part_position)
        self.root.after(80, self.move_tail_parts)

    def remove_tail_parts(self):
        for part in self.tail_parts:
            self.canvas.delete(part.square)
        self.tail_parts.clear()


import torch
import os
import pandas as pd
import numpy as np
import pytorch_lightning as pl

from decouple import config
from torch.utils.data import Dataset, DataLoader
from transformers import BertForSequenceClassification
from transformers import AutoTokenizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from torch.optim import AdamW
from datetime import datetime
from typing import Any

# atribui valores padrão
DEFAULTS: dict[str, Any] = {
    'seed': config('SEED', cast=int, default=42),
    'padding': config('PADDING', default='max_length', cast=str),
    'truncation': config('TRUNCATION', default=True, cast=bool),
    'truncation_side': config('TRUNCATION_SIDE', default='right', cast=str),
    'return_tensors': config('RETURN_TENSORS', default='pt', cast=str),
    'max_tokens': config('MAX_TOKENS', default=512, cast=int),
    'batch_size': config('BATCH_SIZE', default=16, cast=int),
    'num_workers': config('MAX_TOKENS', default=512, cast=int),
    'split_size': config('SPLIT_SIZE_BERT', default=.2, cast=float),
    'learning_rate': config('LEARNING_RATE_BERT', default=2e-5, cast=float),
    'max_epochs': config('MAX_EPOCHS', default=5, cast=int),
    'enable_checkpointing': config('ENABLE_CHECKPOINTING', default=True, cast=bool),
}

# configure global seed
pl.seed_everything(DEFAULTS['seed'])

# helper functions
def get_variable_name(variable):
    for name in globals():
        if id(globals()[name]) == id(variable):
            return name
    for name in locals():
        if id(locals()[name]) == id(variable):
            return name
    return None

def check_possible_variable(variable, possible_values):
    if variable not in possible_values:
        raise ValueError(f"Only followed values are allowed for '{get_variable_name(variable)}': {possible_values}.")

def cria_logger(experimento: str, id: str):
    logger = pl.loggers.TensorBoardLogger(
        save_dir=os.getcwd(),
        name=experimento,
        version=id
    )
    return logger

class CreateDataset(Dataset):
    """
    Class that handles dataset, tokenizing and batching for BERT.
    Inherits from torch.utils.data.Dataset
    """

    def __init__(
            self,
            dataframe: pd.DataFrame,
            tokenizer,
            max_tokens: int,
            class_col: str,
            padding: str = DEFAULTS['padding'],
            truncation: bool = DEFAULTS['truncation'],
            truncation_side: str = DEFAULTS['truncation_side'],
            return_tensors: str = DEFAULTS['return_tensors'],
    ):

        check_possible_variable(
            truncation_side,
            ['left', 'right', 'combined']
        )

        self.dataframe = dataframe.copy()
        self.tokenizer = tokenizer
        self.max_tokens = max_tokens
        self.padding = padding
        self.class_col = class_col
        self.return_tensors = return_tensors
        self.truncation = truncation
        self.truncation_side = truncation_side

        if truncation_side == 'combined':
            self.truncation = False

        if type(tokenizer) == str:
            self.tokenizer = AutoTokenizer.from_pretrained(
                tokenizer,
                truncation_side=truncation_side
            )
        else:
            self.tokenizer = tokenizer

    def __len__(self):
        return len(self.dataframe)

    def __getitem__(self, index: int):

        conteudo = self.dataframe.iloc[index]['conteudo']
        label = self.dataframe.iloc[index][self.class_col]

        # tokenização
        encoding = self.tokenizer.encode_plus(
            conteudo,
            add_special_tokens=True,
            max_length=self.max_tokens,
            padding=self.padding,
            truncation=self.truncation,
            return_attention_mask=True,
            return_tensors=self.return_tensors
        )

        input_ids = encoding["input_ids"].flatten()
        attention_mask = encoding["attention_mask"].flatten()

        if self.truncation_side == 'combined':
            a = input_ids[0:255]
            c = input_ids[-1:]
            b = input_ids[-256:]
            input_ids = torch.cat([a, c, b])
            a = attention_mask[0:255]
            c = attention_mask[-1:]
            b = attention_mask[-256:]
            attention_mask = torch.cat([a, c, b])

        return dict(
            input_ids=input_ids,
            attention_mask=attention_mask,
            label=torch.tensor(label),
            conteudo=conteudo
        )

# noinspection PyPep8Naming
class DataModuler(pl.LightningDataModule):
    """Encapsulates all data loading logic and returns the necessary data loaders."""

    def __init__(
            self,
            X: np.ndarray,
            y: np.ndarray,
            tokenizer,
            split_size: float = DEFAULTS['split_size'],
            max_tokens: int = DEFAULTS['max_tokens'],
            batch_size: int = DEFAULTS['batch_size'],
            num_workers: int = DEFAULTS['num_workers'],
            padding: str = DEFAULTS['padding'],
            truncation: bool = DEFAULTS['truncation'],
            truncation_side: str = DEFAULTS['truncation_side']
    ):
        super().__init__()
        self.X = X
        self.y = y
        self.max_tokens = max_tokens
        self.batch_size = batch_size
        self.split_size = split_size
        self.num_workers = num_workers
        self.tokenizer = tokenizer
        self.padding = padding
        self.truncation = truncation
        self.truncation_side = truncation_side

        self.validation_dataframe = None
        self.train_dataframe = None
        self.train_dataset = None
        self.validation_dataset = None

    def prepare_data(self):
        print("Preparando dados...")
        print('...')

        # SPLIT
        # conteudo e classes
        X = self.X
        y = self.y

        print(f'Total de registros {len(X)}')
        print(f'Realizando split em {self.split_size * 100}%...')
        print('...')

        # split em conjunto de treinamento e conjunto de testes
        X_train, X_test, y_train, y_test = train_test_split(
            X,
            y,
            test_size=self.split_size,
            random_state=DEFAULTS['seed'],
            shuffle=True,
            stratify=y
        )

        # verificando tamanhos
        print(f'A base de treinamento possui {len(X_train)} exemplos')
        print(f'A base de validação possui {len(X_test)} exemplos')
        print('...')

        self.train_dataframe = pd.DataFrame(data={
            'conteudo': X_train.reshape(-1),
            'classe': y_train.reshape(-1)
        }
        )

        self.validation_dataframe = pd.DataFrame(data={
            'conteudo': X_test.reshape(-1),
            'classe': y_test.reshape(-1)
        }
        )

    def setup(self, stage=None):
        self.prepare_data()

        self.train_dataset = CreateDataset(
            dataframe=self.train_dataframe,
            tokenizer=self.tokenizer,
            max_tokens=self.max_tokens,
            class_col='classe',
            padding=self.padding,
            truncation=self.truncation,
            truncation_side=self.truncation_side
        )

        self.validation_dataset = CreateDataset(
            dataframe=self.validation_dataframe,
            tokenizer=self.tokenizer,
            max_tokens=self.max_tokens,
            class_col='classe',
            padding=self.padding,
            truncation=self.truncation,
            truncation_side=self.truncation_side
        )

        print('Datasets prontos!')
        print('')
        print('')

    def train_dataloader(self):
        return DataLoader(
            self.train_dataset,
            batch_size=self.batch_size,
            shuffle=True,
            num_workers=self.num_workers,
        )

    def val_dataloader(self):
        return DataLoader(
            self.validation_dataset,
            batch_size=self.batch_size,
            shuffle=False,
            num_workers=self.num_workers
        )

# noinspection PyTypeChecker
class BERTClassifier(pl.LightningModule):

    def __init__(
            self,
            model_name: str,
            num_classes: int,
            batch_size: int = DEFAULTS['batch_size'],
            freeze_bert: bool = False,
            lr: float = DEFAULTS['learning_rate'],
    ):
        super().__init__()

        self.bert = BertForSequenceClassification.from_pretrained(
            model_name,
            num_labels=num_classes,
            output_hidden_states=True,
            problem_type="single_label_classification"
        )

        self.batch_size = batch_size
        self.save_hyperparameters()
        self.lr = lr

        if freeze_bert:
            for param in self.bert.parameters():
                param.requires_grad = False

    def forward(self, input_ids, attention_mask):
        outputs = self.bert(
            input_ids=input_ids,
            attention_mask=attention_mask
        )
        logits = outputs.logits
        return logits

    def training_step(self, batch, batch_idx):

        input_ids = batch['input_ids']
        attention_mask = batch['attention_mask']
        labels = batch['label']

        output = self.bert(
            input_ids=input_ids,
            attention_mask=attention_mask,
            labels=labels
        )

        loss = output.loss

        log_dict = {
            'epoch': float(self.current_epoch) + 1,
            'train_loss': float(loss),
        }

        self.log_dict(log_dict, batch_size=self.batch_size)

        return loss

    def validation_step(self, batch, batch_idx):

        input_ids = batch['input_ids']
        attention_mask = batch['attention_mask']
        labels = batch['label']

        output = self.bert(
            input_ids=input_ids,
            attention_mask=attention_mask,
            # labels=labels
        )

        preds = torch.argmax(output.logits, dim=1)
        report = classification_report(
            labels.cpu(),
            preds.cpu(),
            output_dict=True,
            zero_division=0,
            digits=3
        )

        log_dict = {
            'epoch': float(self.current_epoch) + 1,
            'val_acc': report['accuracy'],
            'val_precision': report['macro avg']['precision'],
            'val_recall': report['macro avg']['recall'],
            'val_f1-score': report['macro avg']['f1-score'],
        }

        self.log_dict(log_dict, batch_size=self.batch_size)

    def configure_optimizers(self):
        optimizer = AdamW(
            self.parameters(),
            lr=self.lr
        )
        return optimizer

checkpoint_callback = pl.callbacks.ModelCheckpoint(
    verbose=True,
    monitor="val_f1-score",
    save_top_k=1,
    mode='max',
    save_on_train_epoch_end=False
)

# noinspection PyPep8Naming
def prepare_bert_objects(
        X,
        y,
        model_name: str,
        split_size: float = DEFAULTS['split_size'],
        max_tokens: int = DEFAULTS['max_tokens'],
        batch_size: int = DEFAULTS['batch_size'],
        lr: float = DEFAULTS['learning_rate'],
        id=None,
        experimento: str = "",
        tokenizer=None,
        fast_dev_run=False,  # recommended for debugging purposes
        num_workers=DEFAULTS['num_workers'],
        padding=DEFAULTS['padding'],
        truncation=DEFAULTS['truncation'],
        truncation_side=DEFAULTS['truncation_side'],
        devices="auto",
        max_epochs=DEFAULTS['max_epochs'],
        enable_checkpointing=DEFAULTS['enable_checkpointing'],
        callback=checkpoint_callback,
):

    num_classes = np.unique(y).shape[0]

    if id is None:
        now = datetime.now().strftime('%y-%m-%d_%H%M%S')
        id = f"{model_name.replace('/', '-')}__{max_tokens}__{truncation_side}__{now}"

    # modelo
    model = BERTClassifier(
        model_name=model_name,
        batch_size=batch_size,
        num_classes=num_classes,
        lr=lr
    )

    # data_moduler
    data_module = DataModuler(
        X,
        y,
        split_size=split_size,
        tokenizer=tokenizer,
        max_tokens=max_tokens,
        num_workers=num_workers,
        batch_size=batch_size,
        padding=padding,
        truncation=truncation,
        truncation_side=truncation_side
    )

    # trainer
    trainer = pl.Trainer(
        max_epochs=max_epochs,
        accelerator="auto",  # if not set is set to auto
        devices=devices,  # if not set is set to auto
        benchmark=True,  # can increase the speed of your system if your input sizes don’t change
        enable_checkpointing=enable_checkpointing,
        fast_dev_run=fast_dev_run,
        callbacks=[callback],
        logger=cria_logger(
            experimento=experimento,
            id=id
        ),
    )

    return model, data_module, trainer

def test_report(model, dataloader, device):
    """Use it to test the model over validation dataloader."""
    y_real = []
    y_preds = []

    total = len(dataloader)
    print(f"Total de {total} batches.")

    for i, batch in enumerate(dataloader):

        y_real.extend(batch['label'].tolist())

        logits = model(
            batch['input_ids'].to(device),
            batch['attention_mask'].to(device)
            )
        preds = torch.argmax(logits, dim=1).tolist()
        y_preds.extend(preds)

        if i % 200 == 0 and not i == 0:
            print(f"Batch {i}/{total} done....")

    print("Done!")
    print("")
    print("")
    print(classification_report(y_real, y_preds))
    report = classification_report(y_real, y_preds, output_dict=True, digits=3)

    return report, y_real, y_preds


from collections import deque
from itertools import combinations
n,m,g,r=map(int,input().split())
board=[list(map(int,input().split())) for _ in range(n)]
dx=[-1,0,1,0];dy=[0,-1,0,1]
energy=[]
for i in range(n):
    for j in range(m):
        if board[i][j]==2:energy.append((i,j))

result=-2e10
def bfs():
    flower=0;q=deque()
    spread=[[[0,0] for _ in range(m)] for _ in range(n)]
    for i in r_list:
        x,y=energy[i]
        spread[x][y][1]=7 #red
        q.append((x,y))
    for i in g_list:
        x,y=energy[i]
        spread[x][y][1]=8 #green
        q.append((x,y))

    while q:
        x,y=q.popleft()
        if spread[x][y][1]==9: continue #flower
        for i in range(4):
            nx=x+dx[i];ny=y+dy[i]
            if 0<=nx<n and 0<=ny<m and board[nx][ny]!=0:
                if spread[nx][ny][1]==0: # 호수
                    spread[nx][ny][0],spread[nx][ny][1] = spread[x][y][0]+1,spread[x][y][1]
                    q.append((nx,ny))
                elif spread[nx][ny][1]==7:
                    if spread[x][y][1]==8 and spread[x][y][0]+1==spread[nx][ny][0]: # 초록 배양액이 퍼졌을 때 시간이 같다면
                        spread[nx][ny][1]=9;flower+=1
                elif spread[nx][ny][1]==8:
                    if spread[x][y][1]==7 and spread[x][y][0]+1==spread[nx][ny][0]: # 빨간 배양액이 퍼졌을 때 시간이 같다면
                        spread[nx][ny][1]=9;flower+=1
    return flower

for a in combinations(range(len(energy)),r+g):
    for b in combinations(range(r+g),r):
        r_list=[];g_list=[]
        for i in range(r+g):
            if i in b: r_list.append(a[i])
            else:g_list.append(a[i])
        result=max(result,bfs())
print(result)


# Не забудьте импортировать numpy и сразу задать seed 2021
import numpy as np
np.random.seed(2021)
# В simple сохранте случайное число в диапазоне от 0 до 1
simple = None
simple = np.random.rand()
# Сгенерируйте 120 чисел в диапазоне от -150 до 2021, сохраните их
# в переменную randoms
randoms = None
randoms = np.random.uniform(-150, 2021, size=120)
# Получите массив из случайных целых чисел от 1 до 100 (включительно)
# из 3 строк и 2 столбцов. Сохраните результат в table
table = None
table = np.random.randint(1,101,size=(3,2))
# В переменную even сохраните четные числа от 2 до 16 (включительно)
even = None
even = np.array([2, 4, 6, 8, 10, 12, 14, 16])
# Перемешайте числа в even так, чтобы массив even изменился
np.random.shuffle(even)
# Получите из even 3 числа без повторений. Сохраните их в переменную select
select = None
select = np.random.choice(even, size=3,replace=False)
# Получите переменную triplet, которая должна содержать перемешанные
# значения из массива select (сам select измениться не должен)
triplet = None
triplet = np.random.permutation(select)


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

''' !!! works only if python was compiled with UCS2 unicode !!! '''
uni_range = 0xFFFF

default_a_string = u"abcdefghijklmnopqrstuvwxyząćęłńóśżź "

class Alphabet:

	def __init__(self, a_string):

		self.a_string = a_string
		self.uni_lut = [-1 for i in xrange(0, uni_range)]

		for i in xrange(0, len(self.a_string)):
			self.uni_lut[ord(self.a_string[i])] = i

		'''self.uni_lut = {}
		for i in xrange(0, uni_range):
			c = unichr(i)
			self.uni_lut[c] = self.a_string.find(c)'''

	def lookup(self, uni_character):

		return self.uni_lut[ord(uni_character)]
		#return self.uni_lut[uni_character]

default_alphabet = Alphabet(default_a_string)


from bosot.bayesian_optimization.base_candidate_generator import CandidateGenerator
import numpy as np
import logging

logger = logging.getLogger(__name__)

class EvolutionaryOptimizerObjects:
    def __init__(self, population_size, num_offspring, candidate_generator: CandidateGenerator) -> None:
        self.candidate_generator = candidate_generator
        self.population_size = population_size
        self.num_offspring = num_offspring
        self.survival_rate = 1 / (self.num_offspring + 1)
        self.current_maximizer = None
        self.current_maximizer_value = -1 * np.infty

    def maximize(self, func, steps):
        logger.info("EA - Start optimization")

        population = self.candidate_generator.get_initial_for_evolutionary_opt(n_initial=self.population_size)
        for step in range(0, steps):
            print("Step " + str(step + 1) + "/" + str(steps))
            if step > 0:
                survivors = self.select(population, function_values)
                population = self.reproduce(survivors)
            function_values = func(population)
            fittest_index = np.argmax(function_values)
            fittest_individual = population[fittest_index]
            fitness_fittest_indiviudal = function_values[fittest_index]
            logger.info("Current maximizer: ")
            logger.info(fittest_individual)
            logger.info("Function value maximizer:")
            logger.info(fitness_fittest_indiviudal)
            if self.current_maximizer_value < fitness_fittest_indiviudal:
                self.current_maximizer_value = fitness_fittest_indiviudal
                self.current_maximizer = fittest_individual

        logger.info("EA - Optimization complete")
        return self.current_maximizer, self.current_maximizer_value

    def select(self, population, function_values):
        sorted_indexes = np.argsort(function_values)
        n = sorted_indexes.shape[0]
        num_survive = int(self.population_size * self.survival_rate)
        survivor_indexes = sorted_indexes[n - num_survive : n]
        survivors = []
        for index in survivor_indexes:
            survivors.append(population[index])
        return survivors

    def reproduce(self, survivors):
        new_generation = []
        for survivor in survivors:
            new_generation += self.candidate_generator.get_around_candidate_for_evolutionary_opt(survivor, self.num_offspring)
        return new_generation + survivors


#kimhaeun
#22100224
#problem3
import random

randNum=[]
a=0
b=0
c=0

def dice():
    dice_n=[1,2,3,4,5,6]
    for i in range(3):
        randNum.append(random.choice(dice_n))
    global a
    global b
    global c
    a=randNum[0]
    b=randNum[1]
    c=randNum[2]
    hint=(a+b)*c
    print("랜덤 숫자를 생성하였습니다.")
    print("a=",a,",c=",c,"(a+b)*c=",hint)

dice()

for i in range(3):
    guess_b=int(input("b의 값은?"))
    if b!=guess_b:
        print("틀렸습니다.")
    else:
        print("정답입니다.")
        YN=int(input("계속 진행하시겠습니까? (Yes:1. No:2)"))
        if YN==1:
            dice()
        else:
            break

3주차/성온이 화이팅/코로나 이전/과제_퀴즈_수업내코딩/과제_퀴즈_수업내코딩/quiz3_22100224_kimhaeun/problem2.py


from gtk import ImageMenuItem
from gettext import gettext as _

class PopupMenuItem(ImageMenuItem):

	def __init__(self, editor):
		ImageMenuItem.__init__(self, _("_Lines"))
		self.__init_attributes(editor)
		self.__set_properties()
		self.__sigid1 = self.__menuitem1.connect("activate", self.__activate_cb)
		self.__sigid2 = self.__menuitem2.connect("activate", self.__activate_cb)
		self.__sigid3 = self.__menuitem3.connect("activate", self.__activate_cb)
		self.__sigid4 = self.__menuitem4.connect("activate", self.__activate_cb)
		self.__sigid5 = self.__menuitem5.connect("activate", self.__activate_cb)
		self.__sigid6 = self.__menuitem6.connect("activate", self.__activate_cb)
		self.__sigid7 = self.__menuitem7.connect("activate", self.__activate_cb)
		self.__sigid8 = self.__view.connect("focus-in-event", self.__destroy_cb)

	def __init_attributes(self, editor):
		self.__editor = editor
		self.__view = editor.textview
		from gtk import Menu, Image
		self.__menu = Menu()
		self.__image = Image()
		self.__menuitem1 = self.__editor.create_menuitem(_("_Join Line (alt + j)"))
		self.__menuitem2 = self.__editor.create_menuitem(_("D_uplicate Line (ctrl + u)"))
		self.__menuitem3 = self.__editor.create_menuitem(_("_Delete Line (alt + d)"))
		self.__menuitem4 = self.__editor.create_menuitem(_("Free Line _Below (alt + o)"))
		self.__menuitem5 = self.__editor.create_menuitem(_("Free Line _Above (alt + shift + o)"))
		self.__menuitem6 = self.__editor.create_menuitem(_("Delete Cursor to Line _End (alt + End)"))
		self.__menuitem7 = self.__editor.create_menuitem(_("Delete _Cursor to Line Begin (alt + Home)"))
		return

	def __set_properties(self):
		self.set_property("name", "Line Operation Menuitem")
		from gtk import STOCK_JUSTIFY_CENTER
		self.__image.set_property("stock", STOCK_JUSTIFY_CENTER)
		self.set_image(self.__image)
		self.set_submenu(self.__menu)
		self.__menu.append(self.__menuitem1)
		self.__menu.append(self.__menuitem2)
		self.__menu.append(self.__menuitem3)
		self.__menu.append(self.__menuitem4)
		self.__menu.append(self.__menuitem5)
		self.__menu.append(self.__menuitem6)
		self.__menu.append(self.__menuitem7)
		if self.__editor.readonly: self.set_property("sensitive", False)
		return

	def __activate_cb(self, menuitem):
		if menuitem == self.__menuitem1:
			self.__editor.trigger("join-line")
		elif menuitem == self.__menuitem2:
			self.__editor.trigger("duplicate-line")
		elif menuitem == self.__menuitem3:
			self.__editor.trigger("delete-line")
		elif menuitem == self.__menuitem4:
			self.__editor.trigger("free-line-below")
		elif menuitem == self.__menuitem5:
			self.__editor.trigger("free-line-above")
		elif menuitem == self.__menuitem6:
			self.__editor.trigger("delete-cursor-to-end")
		elif menuitem == self.__menuitem7:
			self.__editor.trigger("delete-cursor-to-start")
		return True

	def __destroy_cb(self, *args):
		self.__editor.disconnect_signal(self.__sigid1, self.__menuitem1)
		self.__editor.disconnect_signal(self.__sigid2, self.__menuitem2)
		self.__editor.disconnect_signal(self.__sigid3, self.__menuitem3)
		self.__editor.disconnect_signal(self.__sigid4, self.__menuitem4)
		self.__editor.disconnect_signal(self.__sigid5, self.__menuitem5)
		self.__editor.disconnect_signal(self.__sigid6, self.__menuitem6)
		self.__editor.disconnect_signal(self.__sigid7, self.__menuitem7)
		self.__editor.disconnect_signal(self.__sigid8, self.__view)
		self.destroy()
		del self
		self = None
		return False


from langchain.chat_models import AzureChatOpenAI
from langchain.schema import (AIMessage,
  HumanMessage,
  SystemMessage,
  BaseMessage)
from langchain.prompts.chat import (
  SystemMessagePromptTemplate,
  HumanMessagePromptTemplate,
  )
import os

from dotenv import load_dotenv

load_dotenv()

BASE_URL = os.environ["BASE_URL"]
DEPLOYMENT_NAME = os.environ["DEPLOYMENT_NAME"]
API_KEY = os.environ["API_KEY"]

model1 = AzureChatOpenAI(
openai_api_base=BASE_URL,
openai_api_version="2023-05-15",
deployment_name=DEPLOYMENT_NAME,
openai_api_key=API_KEY,
openai_api_type="azure",
temperature = 0)

llm = model1

def prompt_categorizer(text:str|None=None, set_of_tasks = set(["Summarization of given Information", "Creative Writing", "Interpret or Write Code",
                                                         "Natural Language Question"]) )->str:

 string_list = ""

 for i in list(set_of_tasks):
   string_list += i + "\n"

 Sys_Temp = "The User is prompting an Artificial Inteligence Model in a variety of tasks that need to be classified as: {types} \
 First, you will decompose the prompt into small specific and concrete tasks, in the following format: \
 To accomplish this prompt one needs to do the following tasks: \n \
Task 1: <Summary of task 1> ( <Type of Task 1> ) \n \
... \n \
Task N: <Summary of task N> ( <Type of Task N )"

 System_Prompt_template = SystemMessagePromptTemplate.from_template(template = Sys_Temp, )
 initial_prompt = System_Prompt_template.format_messages(types = string_list)[0]
 messages = [initial_prompt, HumanMessage(content = text)]
 result = llm(messages)#.content
 messages.append(result)

 formatting_prompt = "Good, now take each task presented and from that write a python list in the following form: \
 [<Type of task 1>, <Type of task 2>, ... ,<Type of task N>] \
 Be sure to respect each element of punctuation and formatting."

 Get_Tasks = "Good, now take each task presented and from that write a list in the following form: \
 [<Description of Task 1>; <Description of Task 2>; ... ;<Description of Task N>] \
 Be sure to separate each task by the character \";\" . Do not include the type of the task in this list."

 messages_class = messages +A[( HumanMessage(content = formatting_prompt) )]
 messages_tasks = messages + [HumanMessage(content = Get_Tasks)]

 result_class = llm(messages_class)
 result_class = result_class.content.replace("\"","").replace("\'","").strip("[]").split(", ")

 result_tasks = llm(messages_tasks)
 result_tasks = result_tasks.content.replace("\"","").replace("\'","").replace("\n","").strip("[]").split("; ")

 return zip(result_tasks,result_class)

if "__name__" == "__main__":
  AA = prompt_categorizer("Please explain to me the plot of the movie Cars.")
  dict(AA)


from typing import Union
import aioipfs

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject

from galacteek import log
from galacteek import ensure

from galacteek.ipfs import ipfsOp

from galacteek.ipfs.cidhelpers import IPFSPath
from galacteek.ipfs.cidhelpers import getCID
from galacteek.ipfs.cidhelpers import cidDowngrade
from galacteek.ipfs.mimetype import MIMEType
from galacteek.ipfs.mimetype import detectMimeType
from galacteek.ipfs.ipfssearch import objectMetadata

from galacteek.ipfs.stat import StatInfo
from galacteek.ipfs.stat import UnixFsStatInfo

from galacteek.crypto.qrcode import IPFSQrDecoder

class ResourceAnalyzer(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.app = QApplication.instance()
        self.qrDecoder = IPFSQrDecoder()

    @ipfsOp
    async def __call__(self, ipfsop, pathRef: Union[IPFSPath, str],
                       fetchExtraMetadata=False,
                       statType: list = ['object'],
                       mimeTimeout=10):
        """
        :param IPFSPath pathRef: path of the resource to analyze
        :param str statType: list of types of stat calls to perform
            (object or files)
        """

        if isinstance(pathRef, IPFSPath):
            ipfsPath = pathRef
        elif isinstance(pathRef, str):
            ipfsPath = IPFSPath(pathRef, autoCidConv=True)
        else:
            log.debug('Invalid path: {path}'.format(path=pathRef))
            return None, None

        path = ipfsPath.objPath
        mHashMeta = await self.app.multihashDb.get(path)

        if mHashMeta:
            # Already have metadata for this object
            typeStr = mHashMeta.get('mimetype')
            mimetype = MIMEType(typeStr) if typeStr else None
            statInfo = mHashMeta.get('stat')
            filesStatInfo = mHashMeta.get('filesStat')
            if 'object' in statType:
                return mimetype, StatInfo(statInfo)
            elif 'files' in statType:
                return mimetype, UnixFsStatInfo(filesStatInfo)
        else:
            mimetype = await detectMimeType(
                path,
                timeout=mimeTimeout
            )

            if 'object' in statType:
                statInfo = await ipfsop.objStatInfo(path)
                if not statInfo:
                    log.debug('Stat failed for {path}'.format(
                        path=path))
                    return mimetype, None
            elif 'files' in statType:
                statInfo = await ipfsop.filesStatInfo(ipfsPath.objPath)
            else:
                raise ValueError('Invalid stat type')

            await ipfsop.sleep()

            # Store retrieved information in the metadata store
            # TODO: use an RDF graph (ideally with automatic purge system)

            metaMtype = mimetype.type if mimetype and mimetype.valid else None

            if 'object' in statType:
                await self.app.multihashDb.store(
                    path,
                    mimetype=metaMtype,
                    stat=statInfo.stat
                )
            elif 'files' in statType:
                await self.app.multihashDb.store(
                    path,
                    mimetype=metaMtype,
                    filesStat=statInfo.stat
                )

            # Fetch additional metadata in another task

            if fetchExtraMetadata and statInfo and statInfo.valid:
                ensure(self.fetchMetadata(path, statInfo))

        return mimetype, statInfo

    async def fetchMetadata(self, path, sInfo):
        if sInfo is None:
            return

        cidobj = getCID(sInfo.cid)
        cid = cidDowngrade(cidobj)

        if not cid:
            return

        metadata = await objectMetadata(str(cid))

        if metadata:
            await self.app.multihashDb.store(
                path,
                objmetadata=metadata
            )

    @ipfsOp
    async def decodeQrCodes(self, ipfsop, path):
        try:
            data = await ipfsop.catObject(path)

            if data is None:
                log.debug('decodeQrCodes({path}): could not fetch QR')
                return

            if not self.qrDecoder:
                # No QR decoding support
                log.debug('decodeQrCodes: no QR decoder available')
                return

            # Decode the QR codes in the image if there's any
            return await self.app.loop.run_in_executor(
                self.app.executor, self.qrDecoder.decode, data)
        except aioipfs.APIError as err:
            log.debug(f'decodeQrCodes({path}): IPFS error: {err.message}')


class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children

class Solution(object):
    depVal = 0
    def _maxDepth(self, root, curDepth):
        if root is not None:
            if self.depVal is None:
                self.depVal = curDepth
            else:
                self.depVal = max(self.depVal, curDepth)
            for child in root.children:
                self._maxDepth(child, curDepth + 1)

    def maxDepth(self, root):
        depVal = 0
        self._maxDepth(root, 1)
        return self.depVal

leetcode/LC_559 Maximum Depth of N-ary Tree.py