import abc

import six
from dagster_spark.configs_spark import spark_config
from dagster_spark.utils import flatten_dict
from pyspark.sql import SparkSession

from dagster import Field, check, resource

def spark_session_from_config(spark_conf=None):
    spark_conf = check.opt_dict_param(spark_conf, 'spark_conf')
    builder = SparkSession.builder
    flat = flatten_dict(spark_conf)
    for key, value in flat:
        builder = builder.config(key, value)

    return builder.getOrCreate()

class PySparkResourceDefinition(six.with_metaclass(abc.ABCMeta)):
    def __init__(self, spark_conf):
        self._spark_session = spark_session_from_config(spark_conf)

    @property
    def spark_session(self):
        return self._spark_session

    @property
    def spark_context(self):
        return self.spark_session.sparkContext

    def stop(self):
        self._spark_session.stop()

    @abc.abstractmethod
    def get_compute_fn(self, fn, solid_name):
        pass

class SystemPySparkResource(PySparkResourceDefinition):
    def get_compute_fn(self, fn, solid_name):
        return fn

@resource(
    {
        'spark_conf': spark_config(),
        'stop_session': Field(
            bool,
            is_optional=True,
            default_value=True,
            description='Whether to stop the Spark session on pipeline completion. '
            'Defaults to True.',
        ),
    }
)
def pyspark_resource(init_context):
    pyspark = SystemPySparkResource(init_context.resource_config['spark_conf'])
    try:
        yield pyspark
    finally:
        if init_context.resource_config['stop_session']:
            pyspark.stop()


"""
TITLE: Set.add()

INPUT:
7
UK
China
USA
France
New Zealand
UK
France

OUTPUT:
5

"""

n = int(input())
myset = set()
for _ in range(n):
    myset.add(input())
print(len(myset))


from operator import attrgetter

from django.contrib.auth import get_user_model
from django.db.models import (
    CASCADE, SET_NULL, BooleanField, CharField, CheckConstraint, DateTimeField,
    F, ForeignKey, IntegerChoices, IntegerField, JSONField, ManyToManyField,
    Model, Q, SlugField, TextField, UniqueConstraint)
from django.db.models.fields import URLField
from django.db.models.fields.related import OneToOneField
from django.urls import reverse
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from django.utils.translation import pgettext_lazy
from mdanchors import AnchorConverter

from drugcombinator.managers import DrugManager, InteractionManager
from drugcombinator.modelfields import ListField
from drugcombinator.tasks import ping_webarchive
from drugcombinator.utils import get_libravatar_url, markdown_allowed

class LastModifiedModel(Model):
    last_modified = DateTimeField(
        auto_now=True,
        verbose_name=_("last modification")
    )

    class Meta:
        abstract = True

class Drug(LastModifiedModel):
    name = CharField(
        max_length=128,
        verbose_name=_("name")
    )
    slug = SlugField(
        unique=True,
        verbose_name=_("identifier")
    )
    description = TextField(
        default='',
        blank=True,
        verbose_name=_("description"),
        help_text=markdown_allowed()
    )
    risks = TextField(
        default='',
        blank=True,
        verbose_name=_("general risks"),
        help_text=format_lazy(
            '{text}
{notice}',
            text=_(
                "Risks specific to combinations involving this substance "
                "that do not depend on a specific interaction."),
            notice=markdown_allowed()
        )
    )
    effects = TextField(
        default='',
        blank=True,
        verbose_name=_("general effects"),
        help_text=format_lazy(
            '{text}
{notice}',
            text=_(
                "Effects specific to combinations involving this "
                "substance that do not depend on a specific "
                "interaction."),
            notice=markdown_allowed()
        )
    )
    aliases = ListField(
        verbose_name=_("aliases"),
        help_text=_("One alias per line. No need to duplicate case.")
    )
    interactants = ManyToManyField(
        'self',
        symmetrical=True,
        through='Interaction',
        verbose_name=_("interactants")
    )
    category = ForeignKey(
        'Category',
        SET_NULL,
        null=True,
        blank=True,
        related_name='drugs',
        verbose_name=_("category")
    )
    common = BooleanField(
        default=True,
        verbose_name=_("common"),
        help_text=_(
            "Common substances are displayed as buttons in the app.")
    )

    # History manager will be added through simple_history's register
    # function in translation.py, after the translated fields are
    # added by modeltranslation
    objects = DrugManager()

    def __str__(self):
        return self.name

    @property
    def interactions(self):
        return Interaction.objects.filter(
            Q(from_drug=self) | Q(to_drug=self)
        )

    # In Django 3.1.0, the Drug.interactants field accessor only returns
    # Drug objects from the Interaction.to_drug field, but misses ones
    # from the Interaction.from_drug field. This property is a
    # workaround, as this limitation may be removed at framework level
    # one day.
    @property
    def all_interactants(self):
        return (
            self.interactants.all()
            | Drug.objects.filter(
                interactions_from__in=self.interactions_to.all()
            )
        )

    def get_absolute_url(self, namespace=None):
        name = 'drug'
        if namespace:
            name = f"{namespace}:{name}"

        return reverse(name, kwargs={'slug': self.slug})

    class Meta:
        verbose_name = _("substance")
        ordering = ('slug',)

class Interaction(LastModifiedModel):
    class Synergy(IntegerChoices):
        UNKNOWN = (0, pgettext_lazy("synergy", "Unknown"))
        NEUTRAL = (1, pgettext_lazy("synergy", "Neutral"))
        ADDITIVE = (5, _("Additive"))
        DECREASE = (2, _("Decrease"))
        INCREASE = (3, _("Increase"))
        MIXED = (4, _("Mixed"))

    class Risk(IntegerChoices):
        UNKNOWN = (0, pgettext_lazy("risk", "Unknown"))
        NEUTRAL = (1, pgettext_lazy("risk", "Neutral"))
        CAUTION = (2, _("Caution"))
        UNSAFE = (3, _("Unsafe"))
        DANGEROUS = (4, _("Dangerous"))

    class Reliability(IntegerChoices):
        UNKNOWN = (0, pgettext_lazy("reliability", "Unknown"))
        HYPOTHETICAL = (1, _("Hypothetical"))
        INFERRED = (2, _("Inferred"))
        PROVEN = (3, _("Proven"))

    from_drug = ForeignKey(
        'Drug',
        CASCADE,
        related_name='interactions_from',
        verbose_name=_("first interactant")
    )
    to_drug = ForeignKey(
        'Drug',
        CASCADE,
        related_name='interactions_to',
        verbose_name=_("second interactant")
    )
    names = ListField(
        verbose_name=_("slang names"),
        help_text=_(
            "One name per line. The first one can be emphasized in the "
            "app.")
    )
    risk = IntegerField(
        choices=Risk.choices,
        default=Risk.UNKNOWN,
        verbose_name=_("risks")
    )
    synergy = IntegerField(
        choices=Synergy.choices,
        default=Synergy.UNKNOWN,
        verbose_name=_("synergy")
    )
    risk_reliability = IntegerField(
        choices=Reliability.choices,
        default=Reliability.UNKNOWN,
        verbose_name=_("risks reliability")
    )
    effects_reliability = IntegerField(
        choices=Reliability.choices,
        default=Reliability.UNKNOWN,
        verbose_name=_("synergy and effects reliability")
    )
    risk_description = TextField(
        default='',
        blank=True,
        verbose_name=_("risks description"),
        help_text=markdown_allowed()
    )
    effect_description = TextField(
        default='',
        blank=True,
        verbose_name=_("effects description"),
        help_text=markdown_allowed()
    )
    notes = TextField(
        default='',
        blank=True,
        verbose_name=_("notes"),
        help_text=_(
            "This field is only displayed on this admin site and is "
            "shared between all users and languages.")
    )
    is_draft = BooleanField(
        default=True,
        verbose_name=_("draft"),
        help_text=_(
            "In case of work-in-progress, uncertain or incomplete "
            "data.")
    )
    uris = JSONField(
        default=dict,
        editable=False,
        verbose_name=_("URIs"),
        help_text=_(
            "URIs extracted from these interaction data texts, mapped "
            "to their last Wayback Machine snapshot date.")
    )

    # History manager will be added throug simple_history's register
    # function in translation.py, after the translated fields are
    # added by modeltranslation
    objects = InteractionManager()

    def __str__(self):
        return f"{self.from_drug.name} + {self.to_drug.name}"

    def get_absolute_url(self, namespace=None):
        name = 'combine'
        if namespace:
            name = f"{namespace}:{name}"

        return reverse(name, kwargs={
            'slugs': (self.from_drug.slug, self.to_drug.slug)
        })

    def other_interactant(self, drug):
        index = self.interactants.index(drug)
        return self.interactants[not index]

    @property
    def slug(self):
        return f"{self.from_drug.slug}_{self.to_drug.slug}"

    @property
    def interactants(self):
        return (self.from_drug, self.to_drug)

    @interactants.setter
    def interactants(self, interactants):
        interactants = sorted(interactants, key=attrgetter('slug'))
        self.from_drug, self.to_drug = interactants

    def sort_interactants(self):
        # The interactants property setter will handle interactants
        # reordering
        self.interactants = self.interactants

    def extract_uris(self):
        """Extract URIs from this model `risk_description` and
        `effect_description` text fields."""

        return set().union(*map(
            lambda field: AnchorConverter(field).uris,
            (self.risk_description, self.effect_description)
        ))

    def update_uris(self):
        """Update stored URIs according to this model text fields.

        If a URI was already extracted, it will not be modified.
        Unused URIs will be removed.
        New URIs will be added with a `None` value.
        """
        self.uris = {
            uri: getattr(self.uris, uri, None)
            for uri in self.extract_uris()
        }

    def schedule_webarchive_ping(self):
        ping_webarchive(self.id, self.uris)()

    def save(self, process_uris=True, *args, **kwargs):
        self.sort_interactants()

        if process_uris:
            self.update_uris()

        super().save(*args, **kwargs)

        if process_uris:
            self.schedule_webarchive_ping()

    @classmethod
    def get_dummy_risks(cls):
        return [cls(risk=risk) for risk in cls.Risk.values]

    @classmethod
    def get_dummy_synergies(cls):
        return [cls(synergy=synergy) for synergy in cls.Synergy.values]

    class Meta:
        constraints = (
            CheckConstraint(
                check=~Q(from_drug=F('to_drug')),
                name='interactants_inequals'
            ),
            UniqueConstraint(
                fields=('from_drug', 'to_drug'),
                name='interactants_unique_together'
            )
        )
        verbose_name = _("interaction")

class Category(LastModifiedModel):
    name = CharField(
        max_length=128,
        verbose_name=_("name")
    )
    slug = SlugField(
        unique=True,
        verbose_name=_("identifier")
    )
    description = TextField(
        default='',
        blank=True,
        verbose_name=_("description")
    )

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _("category")
        verbose_name_plural = _("categories")

class Note(LastModifiedModel):
    title = CharField(
        max_length=128,
        default=_("Untitled note"),
        verbose_name=_("title")
    )
    content = TextField(
        default='',
        blank=True,
        verbose_name=_("content"),
        help_text=_(
            "Notes are only displayed on this admin site and are shared "
            "between all users and languages.")
    )
    related_drugs = ManyToManyField(
        'Drug',
        related_name='notes',
        blank=True,
        verbose_name=_("involved substances"),
        help_text=_(
            "If this note involves specific substances, you can "
            "optionally set them here.")
    )

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = _("note")

class Contributor(Model):
    user = OneToOneField(
        get_user_model(),
        CASCADE,
        related_name='profile',
        verbose_name=_("user")
    )
    page = URLField(
        default='',
        blank=True,
        max_length=128,
        verbose_name=_("personal page"),
        help_text=_(
            "This link may be used in public contributors lists.")
    )
    display = BooleanField(
        default=False,
        verbose_name=_("show publicly"),
        help_text=_("Show this profile in public contributors lists.")
    )

    @property
    def avatar_url(self):
        return get_libravatar_url(
            email=self.user.email,
            https=True,
            size=150,
            default='identicon'
        )

    def __str__(self):
        return self.user.username

    class Meta:
        verbose_name = _("contributor profile")
        verbose_name_plural = _("contributor profiles")


#Start with an empty list and add in each new input (check if the data is valid)
my_list = []
total = 0
for i in range(7):
    while True:
        day_sales = input(f"Sales for day {i+1}: ")
        if day_sales.isdigit():
            days_sales = int(day_sales)
            if days_sales >= 0:
                my_list.append(days_sales)
                total += days_sales
                break

        print("Sorry, that is not a valid number. Please try again.")

print(my_list)
average = total / 7
highest = max(my_list)
lowest = min(my_list)
print("")
print(f"Total sales: {total}")
print(f"Average sales per day: {average:.2f}")
print(f"Highest sales day: {highest} (day {my_list.index(highest) + 1})")
print(f"Lowest sales day: {lowest} (day {my_list.index(lowest) + 1})")


# import system modules
import traceback
import os
import sys
import errno
import subprocess
import time
import signal
import functools
# import I/O modules
import RPi.GPIO as GPIO
import smbus2
import spidev
# import utility modules
import math
import numpy as np
import scipy.constants as const
from dataclasses import dataclass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result
        return wrapper
    return decorator

@dataclass
class LidarConfig:
    # dimensions
    height: int = 80
    width: int = 104  # not including header pixel
    Ndata: int = 2
    Nlight: int = 12000
    # timing
    T0_pulse: int = 8
    Light_pulse: int = 7
    VTX3_pulse: int = 28
    ADC_delay: int = 1
    light_offset: float = 0.5
    extrst_pulse: int = 16384
    frame_blank: int = 255

    def generate_reg_map(self):
        light_offset_int = math.ceil(self.light_offset)
        light_offset_half = self.light_offset % 1 > 0
        return (
            (0x00, 0b11100011),  # stop operation
            (0x07, 0b11000000),  # unknown?
            (0x08, (self.extrst_pulse >> 8) & 0xFF),  # ext_reset
            (0x09, (self.extrst_pulse) & 0xFF),
            (0x0A, (self.width >> 8) & 0xFF),  # H_pixel_num
            (0x0B, (self.width) & 0xFF),
            (0x0C, (self.height >> 8) & 0xFF),  # V_pixel_num
            (0x0D, (self.height) & 0xFF),
            (0x0E, 0x25),  # HST_offset
            (0x0F, 0b10110111),  # light_pattern
            (0x10, (self.frame_blank) & 0xFF),  # frame blanking
            (0x11, (self.frame_blank >> 8) & 0xFF),
            (0x12, (self.ADC_delay) & 0x1F),  # ADC_delay_cfg
            (0x13, (0b0100 << 4) | ((self.Nlight >> 16) & 0x0F)),  # LV_delay, Nlight
            (0x14, (self.Nlight >> 8) & 0xFF),
            (0x15, (self.Nlight) & 0xFF),
            (0x16, (self.Ndata) & 0xFF),  # Ndata (must be >1, otherwise only reset value is read and VTX won't trigger)
            (0x17, (self.T0_pulse) & 0xFF),  # VTX1
            (0x18, (self.T0_pulse) & 0xFF),  # VTX2
            (0x19, (self.VTX3_pulse >> 8) & 0xFF),  # VTX3
            (0x1A, (self.VTX3_pulse) & 0xFF),
            (0x1B, (self.Light_pulse) & 0xFF),  # light_pulse_width
            (0x1D, light_offset_int & 0xFF),  # light_pulse_offset
            (0x1F, (self.T0_pulse >> 1) & 0x7F),  # P4_half_delay, P4_delay
            (0x20, (0b0 << 7) | ((light_offset_half << 6) & 0x40) | (0b1001)),  # L/A, Light_pulse_half_delay, H_pixel_blanking
            # (0x21, 0x00),  # T1 (linear only)
            # (0x22, 0x00),  # PHIS (linear only)
            # (0x23, 0x00),  # T2 (linear only)
            (0x24, 0b00001111),  # timing signal enable: light/VTX1/VTX2/VTX3
            (0x00, 0b11000011),  # start clock divider
            (0x00, 0b10000011),  # start clock
            (0x00, 0b00000011),  # start timing gen
        )

class LidarControl:

    # physical
    width: int = int(104)  # not including header pixel
    height: int = int(80)
    Ndata: int = int(2)
    T_0: float = 8 / 60 * 1e-6
    # I/O
    i2c_dev = []
    i2c_channel = 1
    i2c_address_lidar = 0x2A
    spi_dev = []
    spi_channel = 0
    spi_device_MCU = 0
    pin_sensor_rst_P = 4
    pin_mcu_rst_N = 23

    def __init__(self, config=LidarConfig()):
        self.width = config.width
        self.height = config.height
        self.Ndata = config.Ndata
        self.T_0 = config.T0_pulse / 60 * 1e-6
        self.config = config

    def __del__(self):
        print("LiDAR clean up called.")
        try:
            self.spi_dev.close()
            GPIO.cleanup()
        except Exception as err:
            print("Fail to clean GPIO.")
            print(err)

    def connect_GPIO(self):
        GPIO.setmode(GPIO.BCM)

    def connect_sensor(self, i2c_ch=1, i2c_addr=0x2A, pin_sensor_rst=4):
        self.i2c_channel = i2c_ch
        self.i2c_address_lidar = i2c_addr
        self.pin_sensor_rst_P = pin_sensor_rst
        try:
            GPIO.setup(self.pin_sensor_rst_P, GPIO.OUT, initial=0)  # sensor reset (P)
        except Exception as err:
            print("Error:", err)
            print("Sensor rst pin initialization failed!")
            raise RuntimeError("GPIO not available!")
        else:
            print("Sensor rst pin initialized.")
        try:
            i2c_sensor = smbus2.SMBus(self.i2c_channel)
        except FileNotFoundError as err:
            print("FileNotFoundError", err)
            if err.errno == 2:
                print("I2C not enabled. Check raspi-config.")
            raise RuntimeError("I2C bus not available!")
        except Exception as err:
            print("Error:", err)
            print("I2C initialization failed!")
            raise RuntimeError("I2C bus init failed!")
        else:
            print("I2C initialized.")
            self.i2c_dev = i2c_sensor

    def connect_MCU(self, spi_ch=0, spi_num=0, pin_mcu_rst=23):
        self.spi_channel = spi_ch
        self.spi_device_MCU = spi_num
        self.pin_mcu_rst_N = pin_mcu_rst
        try:
            GPIO.setup(self.pin_mcu_rst_N, GPIO.OUT, initial=1)  # MCU reset (N)
        except Exception as err:
            print("Error:", err)
            print("MCU rst pin initialization failed!")
            raise RuntimeError("GPIO not available!")
        else:
            print("MCU rst pin initialized.")
        try:
            spi_mcu = spidev.SpiDev()
            spi_mcu.open(self.spi_channel, self.spi_device_MCU)
        except Exception as err:
            print("Error:", err)
            print("SPI initialization failed!")
            raise RuntimeError("SPI bus init failed!")
        else:
            spi_mcu.max_speed_hz = 5000000
            spi_mcu.mode = 0b11
            spi_mcu.bits_per_word = 8
            spi_mcu.lsbfirst = False
            print(f"SPI initialized at {spi_mcu.max_speed_hz}Hz.")
            self.spi_dev = spi_mcu

    def reset_device(self, sensor=True, mcu=False):
        if sensor:
            GPIO.output(self.pin_sensor_rst_P, 1)
        if mcu:
            GPIO.output(self.pin_mcu_rst_N, 0)
        time.sleep(0.01)
        if sensor:
            GPIO.output(self.pin_sensor_rst_P, 0)
        if mcu:
            GPIO.output(self.pin_mcu_rst_N, 1)
        time.sleep(0.01)
        print("Devices reset.")

    @timeout(5)
    def load_MCU(self, binary_path="dvp2proc2spi_lnk.elf"):
        try:
            # specifically ask for dual-core reset-halt-run in openocd
            # otherwise core 1 will crash after boot (bug in openocd?)
            openocd_cmd = f"program {binary_path} verify; " + \
                "reset halt; " + \
                "rp2040.core1 arp_reset assert 0; " + \
                "rp2040.core0 arp_reset assert 0; " + \
                "exit"
            load_cmd = ["openocd",
                        "-f", "interface/raspberrypi-swd.cfg",
                        "-f", "target/rp2040.cfg",
                        "-c", openocd_cmd]
            subprocess.run(load_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
        except Exception as err:
            print("Error:", err)
            print("Load binary failed!")
            raise RuntimeError("MCU binary loading failed!")
        else:
            print("MCU binary loaded.")

    def setup_sensor(self):
        try:
            lidar_reg_map = self.config.generate_reg_map()
            # write regs and check step-by-step
            for instruction in lidar_reg_map:
                self.i2c_dev.write_byte_data(self.i2c_address_lidar, instruction[0], instruction[1])
                if instruction[1] != self.i2c_dev.read_byte_data(self.i2c_address_lidar, instruction[0]):
                    raise Exception(f"Register validation failed! @{instruction}")
        except OSError as err:
            print("OSError", err)
            if err.errno == 121:
                print("I2C: No response from device! Check wiring on GPIO2/3.")
            raise RuntimeError("I2C device not connected!")
        except Exception as err:
            print("Error:", err)
            print("I2C unknown error!")
            raise RuntimeError("I2C unknown error!")
        else:
            print("I2C data sent.")

    @timeout(10)
    def acquire_data(self):
        # [F1..F4] [VTX1,VTX2] [Y] [X]
        data = np.zeros((4, 2, self.height, self.width), dtype=np.int16)
        # progress info
        print(f" - Trigger Frame capture and SPI read.")
        # command MCU to start frame capturing
        time.sleep(0.01)  # wait for MCU to flush FIFO
        self.spi_dev.writebytes([0x01])
        # query frame state
        timeout_counter = 0
        while True:
            frame_state = self.spi_dev.readbytes(1)
            time.sleep(0.01)  # wait for MCU to flush FIFO
            if frame_state[0] == (0x11):
                break
            else:
                timeout_counter += 1
                # re-trigger if there is a timeout (SPI command lost)
                if (timeout_counter > 250):
                    timeout_counter = 0
                    self.spi_dev.writebytes([0x01])
                    print(f" - Re-trigger Frame capture.")
        # data transfering
        data_stream = np.zeros((4, self.height, 2 * (self.width + 1)), dtype=np.int16)
        for subframe in range(0, 4):
            for line in range(0, self.height):
                temp = self.spi_dev.readbytes(4 * (self.width + 1))
                temp = np.array(temp, dtype=np.int16)
                data_stream[subframe, line, :] = (temp[1::2] << 8) | temp[0::2]
        data[:, 0, :, :] = data_stream[:, :, 2::2]
        data[:, 1, :, :] = data_stream[:, :, 3::2]
        data[[0, 2], :, :, :] = data[[2, 0], :, :, :]
        return data


from django.contrib import admin

from .models import CalendarEvent, CalendarEventAttendee, UserCalendar

class CalendarEventAttendeeInline(admin.TabularInline):
    model = CalendarEventAttendee
    extra = 0

    autocomplete_fields = (
        'user',
    )

class UserCalendarInline(admin.TabularInline):
    model = UserCalendar
    extra = 0

    readonly_fields = (
        "uuid",
    )

@admin.register(CalendarEvent)
class CalendarEvent(admin.ModelAdmin):
    inlines = (
        CalendarEventAttendeeInline,
    )

    autocomplete_fields = (
        'organizer',
    )


from train import get_model
from torchvision import transforms
from PIL import Image
import matplotlib.pyplot as plt
import torch
import os
from torchvision.models import resnet18, ResNet18_Weights
import torch.nn as nn
import numpy as np

class Make_Test(nn.Module):
    def __init__(self, weight_path):
        super(Make_Test, self).__init__()
        self.transform = transforms.Compose([
            transforms.Resize(size=(224, 224)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])

        self.model = get_model()
        self.model.load_state_dict(torch.load(weight_path))
        self.d = {
            0: 'cat',
            1: 'dog'
        }

    def forward(self, image_path):
        image = plt.imread(image_path)
        image = Image.fromarray(image)
        image = self.transform(image).unsqueeze(0)
        self.model.eval()

        out = 0 if self.model(image).squeeze(-1).item() < 0.5 else 1
        return self.d[out]

def visuzalize_loss():
    train_loss = np.load('Accuracy/test_losses.npy')
    train_acc = np.load('test1/test_accs.npy')
    plt.plot(train_loss)
    plt.plot(train_acc)
    plt.show()

def visualize(mk_test, data_path):
    fig = plt.figure(figsize=(9, 9))
    rows, cols = 4, 4

    for i in range(1, rows * cols + 1):
        img = plt.imread(os.path.join("test1", data_path[i - 1]))
        label = mk_test(os.path.join("test1", data_path[i - 1]))
        fig.add_subplot(rows, cols, i)
        plt.imshow(img)
        plt.title(label)
        plt.axis(False)
    plt.show()

if __name__ == '__main__':
    folder = "test1"
    cnt = 0
    mk_test = Make_Test(r"E:\Python test Work\Hieu\Weight\model.pt")
    data_path = os.listdir(folder)[16:32]
    visualize(mk_test, data_path)


from math import cos, pi, sin
import pygame as pg

from constants import consts as c
from id_mapping import id_map
from images import img as i
from ui.game_ui import ui

def move_player(keys_pressed):
    if keys_pressed[pg.K_UP] or keys_pressed[pg.K_w]:
        c.player_y -= c.player_speed * c.dt
        if c.player_y < 0:
            c.player_y = 0

    if keys_pressed[pg.K_DOWN] or keys_pressed[pg.K_s]:
        c.player_y += c.player_speed * c.dt
        if c.player_y + c.sh > c.num_cells * c.cell_length:
            c.player_y = c.num_cells * c.cell_length - c.sh

    if keys_pressed[pg.K_LEFT] or keys_pressed[pg.K_a]:
        c.player_x -= c.player_speed * c.dt
        if c.player_x < 0:
            c.player_x = 0

    if keys_pressed[pg.K_RIGHT] or keys_pressed[pg.K_d]:
        c.player_x += c.player_speed * c.dt
        if c.player_x + c.sw > c.num_cells * c.cell_length:
            c.player_x = c.num_cells * c.cell_length - c.sw

def get_pointer_params():
    mouse_x, mouse_y = pg.mouse.get_pos()
    cell_row = int((mouse_y + c.player_y) / c.cell_length)
    cell_col = int((mouse_x + c.player_x) / c.cell_length)
    cell_x = cell_col * c.cell_length - c.player_x + 2
    cell_y = cell_row * c.cell_length - c.player_y + 2

    return cell_row, cell_col, cell_x, cell_y

def draw_action(cell_x, cell_y):
    pg.draw.circle(c.screen, c.action_color, (cell_x + c.cell_length // 2, cell_y + c.cell_length // 2), 4 * c.cell_length // 5, 2)

    if c.const_state == 1:
        c.screen.blit(i.images[id_map["conveyor"]][c.rot_state], (cell_x - 1, cell_y - 1))
        ui.render_text("Place Conveyor: (L/R) to rotate")

    if c.const_state == 2:
        c.screen.blit(i.images[id_map["conveyor_underground"]][c.rot_state], (cell_x - 1, cell_y - 1))
        translations = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        x = cell_x + translations[c.rot_state][0] * c.ug_state * c.cell_length
        y = cell_y - translations[c.rot_state][1] * c.ug_state * c.cell_length
        c.screen.blit(i.images[id_map["conveyor_underground"]][c.rot_state + 4], (x, y))
        pg.draw.circle(c.screen, c.action_color, (x + c.cell_length // 2, y + c.cell_length // 2), 4 * c.cell_length // 5, 2)
        ui.render_text("Place Underground Conveyor: (L/R) to rotate (Shift/Ctrl) to change length")

    elif c.const_state == 3:
        c.screen.blit(i.images[id_map["splitter"]][c.rot_state], (cell_x - 1, cell_y - 1))
        translations = [[(-1, 1), (1, 1)], [(1, -1), (1, 1)], [(1, -1), (-1, -1)], [(-1, 1), (-1, -1)]]
        x1 = cell_x + translations[c.rot_state][0][0] * c.cell_length
        y1 = cell_y - translations[c.rot_state][0][1] * c.cell_length
        x2 = cell_x + translations[c.rot_state][1][0] * c.cell_length
        y2 = cell_y - translations[c.rot_state][1][1] * c.cell_length
        pg.draw.rect(c.screen, c.target_color, (x1, y1, c.cell_length, c.cell_length), 3)
        pg.draw.rect(c.screen, c.target_color, (x2, y2, c.cell_length, c.cell_length), 3)
        ui.render_text("Place Splitter: (L/R) to rotate")

    elif c.const_state == 4:
        c.screen.blit(i.images[id_map["arm"]], (cell_x - 1, cell_y - 1))
        angle = ((1 - (c.rot_state + 2) % 4) * pi / 2) % (2 * pi)

        start_x = cell_x + c.cell_length // 2
        start_y = cell_y + c.cell_length // 2
        end_x = start_x + c.cell_length * cos(angle)
        end_y = start_y - c.cell_length * sin(angle)

        pg.draw.line(c.screen, c.arm_color, (start_x, start_y), (end_x, end_y), 2)
        draw_source(cell_x, cell_y, c.rot_state)
        draw_target(cell_x, cell_y, c.rot_state)
        ui.render_text("Place Arm: (L/R) to rotate")

    elif c.const_state == 5:
        c.screen.blit(i.images[id_map["mine"]], (cell_x - 1, cell_y - 1))
        draw_target(cell_x, cell_y, c.rot_state)
        ui.render_text("Place Mine: (L/R) to rotate")

    elif c.const_state == 6:
        c.screen.blit(i.images[id_map["furnace"]], (cell_x - 1, cell_y - 1))
        draw_target(cell_x, cell_y, c.rot_state)
        ui.render_text("Place Furnace: (L/R) to rotate")

    elif c.const_state == 7:
        c.screen.blit(i.images[id_map["factory"]], (cell_x - 1, cell_y - 1))
        draw_target(cell_x, cell_y, c.rot_state)
        ui.render_text("Place Factory: (L/R) to rotate")

def draw_target(cell_x, cell_y, state):
    translations = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    x = cell_x + translations[state][0] * c.cell_length
    y = cell_y + translations[state][1] * c.cell_length
    pg.draw.rect(c.screen, c.target_color, (x, y, c.cell_length, c.cell_length), 3)

def draw_source(source_x, source_y, state):
    translations = [(0, 1), (-1, 0), (0, -1), (1, 0)]
    x = source_x + translations[state][0] * c.cell_length
    y = source_y + translations[state][1] * c.cell_length
    pg.draw.rect(c.screen, c.source_color, (x, y, c.cell_length, c.cell_length), 3)

def draw_gridlines():
    for x in range(0, c.num_cells * c.cell_length, c.cell_length):
        pg.draw.line(c.screen, c.grid_color, (x - c.player_x, 0), (x - c.player_x, c.sh))
    for y in range(0, c.num_cells * c.cell_length, c.cell_length):
        pg.draw.line(c.screen, c.grid_color, (0, y - c.player_y), (c.sw, y - c.player_y))


from manimlib.imports import *

#Visualización de Gráficas (Va después de Gráficas)

def Range(in_val,end_val,step=1):
    return list(np.arange(in_val,end_val+step,step))

### VISUALIZACIÓN DE GRÁFICAS (DIVIDO EN 3 CLASES, PERO ES UN SÓLO VIDEO) ###

#EJEMPLO 1 R -> R#
class Visualización_Gráficas_1(GraphScene,Scene):
    def setup(self):
        Scene.setup(self)
        GraphScene.setup(self)

    CONFIG = {
        "y_max" : 20,
        "y_min" : 0,
        "x_max" : 5,
        "x_min" : 0,
        "y_tick_frequency" : 1,
        "x_tick_frequency" : 1,
        "axes_color" : BLUE,
        "graph_origin" : np.array((-2.5,-3,0))
    }

    def construct (self):

        titulo = TextMobject("Visualización de Gráficas").scale(1.5)

        text1_1 = TextMobject("Recordemos que dada una función")
        text1_2 = TexMobject(r"f:A \subset \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}",color=YELLOW).next_to(text1_1,DOWN)
        text1_3 = TextMobject("la gráfica de $f$ es subconjunto de ", "$\mathbb{R}^{n+m}$").next_to(text1_2,DOWN)
        text1_3[1].set_color(YELLOW)
        text1 = VGroup(text1_1,text1_2,text1_3).move_to(0.5*UP)

        funcion_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}").move_to(1*DOWN)
        funcion_2 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1,DOWN)
        funcion_3 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2,DOWN)
        funciones = VGroup(funcion_1,funcion_2,funcion_3)

        text3 = TextMobject("Ahora, veamos algunos ejemplos")

        text4_1 = TextMobject("Consideremos una recta $x=$ ", "$x_0$", ",").move_to(3.3*UP+2.5*RIGHT)
        text4_2 = TextMobject("¿qué pasa si ", "$x_0$", " pertenece al dominio de $f$?").next_to(text4_1,DOWN)
        text4_1[1].set_color(GREEN_E)
        text4_2[1].set_color(GREEN_E)
        text4 = VGroup(text4_1,text4_2).scale(0.8)

        text5 = TextMobject('''Cada recta intersecta a la gráfica\n
                                en un sólo punto ''').move_to(3.3*UP+2.5*RIGHT).scale(0.8)
        text6 = TextMobject('''¿Qué pasará si $x_0$ no pertenece\n
                             al dominio de $f$?''').move_to(3.3*UP+2.5*RIGHT).scale(0.8)

        #PRIMERA CAJA
        funciones.bg =SurroundingRectangle(funciones, buff = 0.8*SMALL_BUFF, color=WHITE)
        Caja = VGroup(funciones.bg,funciones)

        #CAJA UPPER LEFT PRE EJEMPLO

        funciones_copy_0 = funciones.copy().to_corner(UL)
        funciones_copy_0.bg = SurroundingRectangle(funciones_copy_0, buff = 0.8*SMALL_BUFF, color=WHITE)
        Caja_0 = VGroup(funciones_copy_0.bg,funciones_copy_0)

        #CAJA EJEMPLO 1

        funcion_1_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}",color=YELLOW)
        funcion_2_1 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1_1,DOWN)
        funcion_3_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_1,DOWN)
        funciones_1 = VGroup(funcion_1_1,funcion_2_1,funcion_3_1).to_corner(UL)
        funciones_1.bg =SurroundingRectangle(funciones_1, buff = 0.8*SMALL_BUFF, color=WHITE)
        Caja_1 = VGroup(funciones_1.bg,funciones_1)

        #Texto ejemplo función
        ejemplo_1_1 = TexMobject(r"f(x)=x^{2}",color=YELLOW)
        ejemplo_1_2 = TexMobject(r"G_{f}:=\{(x,f(x))\in \mathbb{R}^{2}|x\in[0,4]\}",color=YELLOW).next_to(ejemplo_1_1,DOWN)
        ejemplo_1 = VGroup(ejemplo_1_1,ejemplo_1_2).move_to(2.8*UP+2*RIGHT)
        #OBJETOS PARA EJEMPLO 1
        dot_1_1 = Dot().set_color(WHITE).move_to(np.array((1.1,-1.8,0)))
        dot_1_x1 = Dot().set_color(WHITE).move_to(np.array((1.1,-3,0)))
        dot_1_y1 = Dot().set_color(WHITE).move_to(np.array((-2.5,-1.8,0)))
        linea_1_x1 = DashedLine(dot_1_x1.get_top(),dot_1_1.get_bottom(),buff=0.1)
        linea_1_x1.set_color(WHITE)
        linea_1_y1 = DashedLine(dot_1_y1.get_right(),dot_1_1.get_left(),buff=0.1)
        linea_1_y1.set_color(WHITE)
        text_dot_1_x1 = TexMobject(r"x=2").move_to(dot_1_x1.get_bottom()+0.5*DOWN).scale(0.75)
        text_dot_1_y1 = TexMobject(r"f(2)=4").move_to(dot_1_y1.get_left()+1.2*LEFT).scale(0.75)
        text_dot_1_1 = TexMobject(r"(2,f(2))").move_to(dot_1_1.get_top()+0.4*UP+0.5*LEFT).scale(0.75)

        dot_1_2 = Dot().set_color(WHITE).move_to(np.array((2.9,-0.3,0)))
        dot_1_x2 = Dot().set_color(WHITE).move_to(np.array((2.9,-3,0)))
        dot_1_y2 = Dot().set_color(WHITE).move_to(np.array((-2.5,-0.3,0)))
        linea_1_x2 = DashedLine(dot_1_x2.get_top(),dot_1_2.get_bottom(),buff=0.1)
        linea_1_x2.set_color(WHITE)
        linea_1_y2 = DashedLine(dot_1_y2.get_right(),dot_1_2.get_left(),buff=0.1)
        linea_1_y2.set_color(WHITE)
        text_dot_1_x2 = TexMobject(r"x=3").move_to(dot_1_x2.get_bottom()+0.5*DOWN).scale(0.75)
        text_dot_1_y2 = TexMobject(r"f(3)=9").move_to(dot_1_y2.get_left()+1.2*LEFT).scale(0.75)
        text_dot_1_2 = TexMobject(r"(3,f(3))").move_to(dot_1_2.get_top()+0.4*UP+0.5*LEFT).scale(0.75)

        text_dots_1_1 = VGroup(text_dot_1_1,text_dot_1_2)
        text_dots_1_2 = TextMobject('''$(2,f(2))\\in G_{f}$ \n
                                    $(3,f(3))\\in G_{f}$''').to_edge(LEFT).scale(0.75)
        text_grafica_1 = TexMobject(r"G_{f}",color=YELLOW).move_to(ejemplo_1.get_bottom()+0.75*DOWN+3*RIGHT)

        ###Rectas verticales
        dot_dom_1 = Dot().set_color(GREEN_E).move_to((1.5,-3.0,0))
        dot_dom_2 = Dot().set_color(GREEN_E).move_to((4,-3.0,0))
        dot_func_1 = Dot().move_to((1.5,-1.5,0))
        dot_func_2 = Dot().move_to((4,0.9,0))
        linea_vert_1 = Line((1.5,-3.5,0),(1.5,1.5,0)).set_color(GREEN_E)
        linea_vert_2 = Line((4,-3.5,0),(4,1.5,0)).set_color(GREEN_E)
        RectVert = VGroup(dot_dom_1,dot_dom_2,dot_func_1,dot_func_2,linea_vert_1,linea_vert_2)
        #Secuencia de Animación
        self.play(Write(titulo))
        self.wait(3)
        self.play(FadeOut(titulo))
        self.play(Write(text1))
        self.wait(9)
        self.play(FadeOut(text1))
        self.play(Write(text3))
        self.wait(3)
        self.play(Write(funciones))
        self.wait(0.5)
        self.play(ShowCreation(funciones.bg))
        self.wait(0.5)
        self.play(FadeOut(text3))
        self.play(ReplacementTransform(Caja,Caja_0))
        #EJEMPLO 1
        self.play(ReplacementTransform(Caja_0,Caja_1))
        self.setup_axes(animate=True)
        graph = self.get_graph(lambda x : x**2,
                                    color = YELLOW,
                                    x_min = 0,
                                    x_max = 4
                                    )
        self.play(FadeIn(ejemplo_1))
        self.play(FadeIn(dot_1_1),FadeIn(dot_1_x1),FadeIn(text_dot_1_x1),FadeIn(dot_1_y1),FadeIn(text_dot_1_y1))
        self.wait(2)
        self.play(ShowCreation(linea_1_x1),ShowCreation(linea_1_y1))
        self.play(FadeIn(text_dot_1_1))
        self.wait(2)
        self.play(FadeIn(dot_1_2),FadeIn(dot_1_x2),FadeIn(text_dot_1_x2),FadeIn(dot_1_y2),FadeIn(text_dot_1_y2))
        self.wait(2)
        self.play(ShowCreation(linea_1_x2),ShowCreation(linea_1_y2))
        self.play(FadeIn(text_dot_1_2))
        self.wait(2)
        self.play(FadeOut(text_dot_1_x1),FadeOut(text_dot_1_x2),FadeOut(text_dot_1_y1),FadeOut(text_dot_1_y2))
        self.play(ReplacementTransform(text_dots_1_1,text_dots_1_2))
        self.wait(3)
        self.play(FadeOut(linea_1_x1),FadeOut(linea_1_x2),FadeOut(linea_1_y1),FadeOut(linea_1_y2),FadeOut(dot_1_x1),FadeOut(dot_1_x2),FadeOut(dot_1_y1),FadeOut(dot_1_y2))
        self.play(
            ShowCreation(graph),
            run_time = 3
        )
        self.play(FadeIn(text_grafica_1))
        self.wait()
        self.play(FadeOut(ejemplo_1),FadeOut(dot_1_1),FadeOut(dot_1_2),FadeOut(text_dots_1_2))
        self.play(Write(text4))
        self.wait(6.5)
        self.play(FadeIn(dot_dom_1))
        self.play(ShowCreation(linea_vert_1))
        self.play(FadeOut(text4))
        self.play(FadeIn(text5))
        self.wait(5)
        self.play(FadeIn(dot_func_1))
        self.play(FadeIn(dot_dom_2))
        self.play(ShowCreation(linea_vert_2))
        self.play(FadeIn(dot_func_2))
        self.wait(2.5)
        self.play(FadeOut(RectVert))
        self.play(FadeOut(text5))
        self.play(FadeIn(text6))
        self.wait(7)
        self.play(FadeOut(text_grafica_1),FadeOut(self.axes),FadeOut(graph),FadeOut(text6))

#EJEMPLO 2 R^2 -> R#
class Visualización_Gráficas_2(ThreeDScene,Scene):
    def setup(self):
        Scene.setup(self)
        ThreeDScene.setup(self)
    def acomodar_textos(self,objeto):
        self.add_fixed_in_frame_mobjects(objeto)
        self.play(Write(objeto))
    def FadeOutWrite3D(self,objeto1,objeto2):
        self.play(FadeOut(objeto1))
        self.acomodar_textos(objeto2)
    def punto3D(self):
        bola = ParametricSurface(
            lambda u, v: np.array([
                0.075*np.cos(v) * np.sin(u),
            0.075*np.sin(v) * np.sin(u),
            0.075*np.cos(u)
            ]),v_min=0,v_max=TAU,u_min=0.001,u_max=PI-0.001,
            resolution=(12,24),fill_opacity=1,stroke_color=GREEN_E,fill_color=GREEN_E)
        return bola
    def punto3D_2(self):
        bola = ParametricSurface(
            lambda u, v: np.array([
                0.075*np.cos(v) * np.sin(u),
            0.075*np.sin(v) * np.sin(u),
            0.075*np.cos(u)
            ]),v_min=0,v_max=TAU,u_min=0.001,u_max=PI-0.001,
            resolution=(12,24),fill_opacity=1,stroke_color=GOLD_E,fill_color=GOLD_E)
        return bola
    def construct(self):

        #Caja Ejemplo 1 (Para transición de cajas)
        funcion_1_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}",color=YELLOW)
        funcion_2_1 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1_1,DOWN)
        funcion_3_1 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_1,DOWN)
        funciones_1 = VGroup(funcion_1_1,funcion_2_1,funcion_3_1).to_corner(UL)
        funciones_1.bg =SurroundingRectangle(funciones_1, buff = 0.8*SMALL_BUFF, color=WHITE)
        Caja_1 = VGroup(funciones_1.bg,funciones_1)

        #CAJA EJEMPLO 2
        funcion_1_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}")
        funcion_2_2 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}",color=YELLOW).next_to(funcion_1_2,DOWN)
        funcion_3_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_2,DOWN)
        funciones_2 = VGroup(funcion_1_2,funcion_2_2,funcion_3_2).to_corner(UL)
        funciones_2.bg =SurroundingRectangle(funciones_2, buff = 0.8*SMALL_BUFF, color=WHITE)
        Caja_2 = VGroup(funciones_2.bg,funciones_2)

        #EJEMPLO 2

        ejemplo_2_1 = TexMobject(r"f(x,y)=\sin(x)\cos(y)",color=YELLOW)
        ejemplo_2_2 = TexMobject(r"G_{f}:=\{(x,y,f(x,y))\in \mathbb{R}^{3}|(x,y)\in A\}",color=YELLOW).next_to(ejemplo_2_1,DOWN)
        ejemplo_2 = VGroup(ejemplo_2_1,ejemplo_2_2).move_to(3.3*UP+3.6*RIGHT).scale(0.8)

        ###Líneas verticales
        text_1 = TextMobject("Consideremos una recta $(x,y,z)=($", "$x_0$",",","$y_0$","$,0)+\\alpha\\hat{z}$, con $\\alpha\\in\\mathbb{R}$").move_to(3.5*UP+2*RIGHT)
        text_1[1].set_color(GREEN_E)
        text_1[3].set_color(GREEN_E)
        text_1_1 = TextMobject("¿qué pasa si ", "$(x_0,y_0)$"," pertence al dominio de $f$?").next_to(text_1,DOWN)
        text_1_1[1].set_color(GREEN_E)
        text_1 = VGroup(text_1,text_1_1).scale(0.7)

        text_2 = TextMobject("La recta intersecta  la gráfica en un sólo punto").move_to(3.3*UP+2*RIGHT).scale(0.6)
        text_3 = TextMobject("¿Qué pasará si ", "$(x_0,y_0)$"," no pertence al dominio de $f$?").move_to(3.3*UP+2*RIGHT).scale(0.6)
        text_3[1].set_color(GREEN_E)
        Superficie = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                np.sin(u)*np.cos(v)
            ]),v_min=-2.5,v_max=4,u_min=-3,u_max=5,checkerboard_colors=[GOLD_E,GOLD_E],
            resolution=(20, 50))
        Superficie2 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                np.sin(u)*np.cos(v)
            ]),v_min=-2.5,v_max=4,u_min=-3,u_max=5,checkerboard_colors=[GOLD_E,GOLD_E],
            resolution=(20, 50),fill_opacity=0.5)

        axes = ThreeDAxes(x_min=-3,x_max=6,y_min=-3,y_max=6,z_min=-3,z_max=3,num_axis_pieces=40)
        #Creo que es redundante lo del color=WHITE en los Dot, pero no importa
        dot_2_1 = Dot().set_color(RED).move_to(np.array((3*PI/2,2.5,0.8)))
        dot_2_x1 = Dot().set_color(WHITE).move_to(np.array((3*PI/2,0,0)))
        dot_2_y1 = Dot().set_color(WHITE).move_to(np.array((0,2.5,0)))
        dot_2_z1 = Dot().set_color(WHITE).move_to(np.array((0,0,0.8)))
        dot_2_xy1 = Dot().set_color(WHITE).move_to(np.array((3*PI/2,2.5,0)))
        linea_2_x1 = DashedLine(dot_2_x1.get_center(),dot_2_xy1.get_center(),buff=0.1,rate=0.25)
        linea_2_x1.set_color(WHITE)
        linea_2_y1 = DashedLine(dot_2_y1.get_center(),dot_2_xy1.get_center(),buff=0.1)
        linea_2_y1.set_color(WHITE)
        linea_2_z1 = DashedLine(dot_2_z1.get_center(),dot_2_1.get_center(),buff=0.1)
        linea_2_z1.set_color(WHITE)
        linea_2_xy1 = DashedLine(dot_2_xy1.get_center(),dot_2_1.get_center(),buff=0.1)
        linea_2_xy1.set_color(WHITE)
        text_dot_2_x1 = TexMobject(r"x=\frac{3\pi}{2}").move_to(dot_2_x1.get_top()+0.5*UP).scale(0.75)
        text_dot_2_y1 = TexMobject(r"y=2.5").move_to(dot_2_y1.get_left()+1*RIGHT).scale(0.75)
        text_dot_2_z1 = TexMobject(r"f(x,y)=0.8").move_to(dot_2_z1.get_left()+1.5*LEFT).scale(0.75)
        text_dot_2_1 = TexMobject(r"(x,y,f(x,y))",color=RED).move_to(dot_2_1.get_right()+0.8*UP).scale(0.75)
        text_dot_2_xy1 = TexMobject(r"(x,y)\in A").move_to(dot_2_xy1.get_top()+0.5*RIGHT+0.5*UP).scale(0.75)
        gpo_coordxy_2_1 = VGroup(text_dot_2_x1,text_dot_2_y1)
        gpo_coordxyz_2_1 = VGroup(text_dot_2_xy1, text_dot_2_z1)

        text_grafica_2 = TexMobject(r"G_{f}",color=GOLD_E).move_to(4.75*RIGHT+1*DOWN)
        ###Objetos Rectas

        dot_dom_1 = self.punto3D().move_to((PI/2,0,0))
        dot_func_1 = self.punto3D_2().move_to((PI/2,0,1))
        dot_dom_2 = self.punto3D().move_to((0,5,0))
        linea_vert_1 = Line((PI/2,0,-3),(PI/2,0,3)).set_color(GREEN_E)
        linea_vert_2 = Line((0,5,-3),(0,5,3)).set_color(GREEN_E)
        RectVert = VGroup(dot_dom_1,dot_dom_2,dot_func_1,linea_vert_1)

        #EJEMPLO 2
        self.add(Caja_1)
        self.wait(0.5)
        self.play(ReplacementTransform(Caja_1,Caja_2))
        self.add_fixed_in_frame_mobjects(Caja_2)
        self.play(FadeIn(ejemplo_2))
        self.add_fixed_in_frame_mobjects(ejemplo_2)
        self.set_camera_orientation(phi=55 * DEGREES,theta=-50*DEGREES,distance=50)
        self.play(ShowCreation(axes))
        self.wait()
        self.play(FadeIn(dot_2_x1),FadeIn(text_dot_2_x1))
        self.wait(1.5)
        self.play(FadeIn(dot_2_y1),FadeIn(text_dot_2_y1))
        self.wait(1.5)
        self.play(FadeIn(dot_2_z1),FadeIn(text_dot_2_z1))
        self.wait(1.5)
        self.begin_ambient_camera_rotation(rate=0.04)
        self.play(FadeIn(dot_2_xy1),ReplacementTransform(gpo_coordxy_2_1,text_dot_2_xy1))
        self.play(FadeIn(linea_2_x1))
        self.play(FadeIn(linea_2_y1))
        self.play(FadeIn(dot_2_1))
        self.play(FadeIn(linea_2_xy1),FadeIn(linea_2_z1))
        self.wait(2)
        self.play(ReplacementTransform(gpo_coordxyz_2_1,text_dot_2_1))
        self.wait(3.5)
        self.play(FadeOut(dot_2_xy1),FadeOut(dot_2_x1),FadeOut(dot_2_y1),FadeOut(dot_2_z1),FadeOut(linea_2_x1),FadeOut(linea_2_xy1),FadeOut(linea_2_y1),FadeOut(linea_2_z1),FadeOut(text_dot_2_1))
        self.play(ShowCreation(Superficie))
        self.add_fixed_in_frame_mobjects(text_grafica_2)
        self.wait(23)
        self.stop_ambient_camera_rotation()
        self.play(FadeOut(dot_2_1),FadeOut(text_grafica_2),FadeOut(ejemplo_2))
        self.wait()
        self.acomodar_textos(text_1)
        self.wait(12)
        self.move_camera(phi=75 * DEGREES,theta=-50*DEGREES,distance=50,frame_center=[0,0,1])
        self.play(ReplacementTransform(Superficie,Superficie2))
        self.begin_ambient_camera_rotation(rate=0.04)
        self.play(FadeIn(dot_dom_1))
        self.play(ShowCreation(linea_vert_1))
        self.FadeOutWrite3D(text_1,text_2)
        self.play(FadeIn(dot_func_1))
        self.wait(4.5)
        self.play(FadeOut(dot_dom_1),FadeOut(dot_func_1),FadeOut(linea_vert_1))
        self.FadeOutWrite3D(text_2,text_3)
        self.wait(5)
        self.play(FadeIn(dot_dom_2))
        self.wait(1.5)
        self.play(ShowCreation(linea_vert_2))
        self.stop_ambient_camera_rotation
        self.wait(5)
        self.play(FadeOut(axes),FadeOut(Superficie2),FadeOut(text_3),FadeOut(dot_dom_2),FadeOut(linea_vert_2))

#EJEMPLO 3 R -> R^2#
class Visualización_Gráficas_3(ThreeDScene,Scene):
    def setup(self):
        Scene.setup(self)
        ThreeDScene.setup(self)
    def FadeOutWrite3D(self,objeto1,objeto2):
        self.play(FadeOut(objeto1))
        self.acomodar_textos(objeto2)
    def acomodar_textos(self,objeto):
        self.add_fixed_in_frame_mobjects(objeto)
        self.play(Write(objeto))
    def construct(self):

        #CAJA EJEMPLO 2
        funcion_1_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}")
        funcion_2_2 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}",color=YELLOW).next_to(funcion_1_2,DOWN)
        funcion_3_2 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}").next_to(funcion_2_2,DOWN)
        funciones_2 = VGroup(funcion_1_2,funcion_2_2,funcion_3_2).to_corner(UL)
        funciones_2.bg =SurroundingRectangle(funciones_2, buff = 0.8*SMALL_BUFF, color=WHITE)
        Caja_2 = VGroup(funciones_2.bg,funciones_2)

        #Caja ejemplo 3
        funcion_1_3 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}")
        funcion_2_3 = TexMobject(r"f:A \subset \mathbb{R}^{2} \rightarrow \mathbb{R}").next_to(funcion_1_3,DOWN)
        funcion_3_3 = TexMobject(r"f:A \subset \mathbb{R} \rightarrow \mathbb{R}^{2}",color=YELLOW).next_to(funcion_2_3,DOWN)
        funciones_3 = VGroup(funcion_1_3,funcion_2_3,funcion_3_3).to_corner(UL)
        funciones_3.bg =SurroundingRectangle(funciones_3, buff = 0.8*SMALL_BUFF, color=WHITE)
        Caja_3 = VGroup(funciones_3.bg,funciones_3)

        text_3 = TextMobject('''No es común en clase graficar funciones de $\\mathbb{R}\\rightarrow\\mathbb{R}^2$\n
                                por la dificultad de hacer los dibujos en pizarrón''')
        text_4 = TextMobject('''Generalmente se trabaja con la imagen de la\n
                                función, dibujando las curvas correspondientes\n
                                 en el plano del contradominio ''')
        text_5 = TextMobject('''En este y otros videos podemos usar\n
                                 la gráfica de este tipo de funciones ''')

        text_6 = TextMobject("Consideremos algunos puntos de la gráfica").move_to(3.3*UP+2*RIGHT).scale(0.8)
        text_7 = TextMobject('''Análogo a los casos anteriores, podemos tomar \n
                                planos paralelos al plano $xy$''').move_to(3.3*UP+2*RIGHT).scale(0.8)
        text_8 = TextMobject('''La intersección de la gráfica con estos\n
                                 planos sólo puede ser un punto''').move_to(3.3*UP+2*RIGHT).scale(0.8)
        text_9 = TextMobject('''Si fuera más de un punto,\n
                                $f$ no sería función''').move_to(3.3*UP+RIGHT).scale(0.8)
        text_10 = TextMobject('''Si la intersección fuera el vacío,\n
                                 el punto correspondiente en el eje t\n
                                 no sería parte del dominio ''').move_to(3.3*UP).scale(0.7)
        #EJEMPLO 3

        ejemplo_3_1 = TexMobject(r"f(t)=\frac{t}{4\pi}(\cos(t),\sin(t))",color=YELLOW)
        ejemplo_3_2 = TexMobject(r"G_{f}:=\{(t,f(t))\in \mathbb{R}^{3}|t\in A\}",color=YELLOW).next_to(ejemplo_3_1,DOWN)
        ejemplo_3 = VGroup(ejemplo_3_1,ejemplo_3_2).move_to(3.2*UP).scale(0.65)

        ejemplo_3_10=ejemplo_3.copy().move_to(3.2*UP+4*RIGHT)

        #EJES
        axes_2 = ThreeDAxes(x_min=-3.5,x_max=3.2,y_min=-3.5,y_max=3.5,z_min=0,z_max=5*PI,num_axis_pieces= 30)

        #AQUÍ VAN TODAS LOS PLANOS, PUNTOS Y LA CURVA
        curva_1 = ParametricFunction(
                lambda u : np.array([
                (u/(4*PI))*math.cos(u),
                (u/(4*PI))*math.sin(u),
                u
            ]),color=YELLOW,t_min=0,t_max=4*PI,
            )

        plano_1 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                PI/2
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=BLUE_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_1 = Dot(color=RED).move_to((0,1*1*PI/(8*PI),PI/2))

        plano_2 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                PI
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=TEAL_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_2 = Dot(color=RED).move_to((-1*2*PI/(8*PI),0,PI))

        plano_3 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                3*PI/2
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=GREEN_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_3 = Dot(color=RED).move_to((0,-1*3*PI/(8*PI),3*PI/2))

        plano_4 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                2*PI
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=YELLOW_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_4 = Dot(color=RED).move_to((1*4*PI/(8*PI),0,4*PI/2))

        plano_5 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                5*PI/2
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=GOLD_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_5 = Dot(color=RED).move_to((0,1*5*PI/(8*PI),5*PI/2))

        plano_6 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                3*PI
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=RED_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_6 = Dot(color=RED).move_to((-1*6*PI/(8*PI),0,6*PI/2))

        plano_7 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                7*PI/2
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=MAROON_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_7 = Dot(color=RED).move_to((0,-1*7*PI/(8*PI),7*PI/2))

        plano_8 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                8*PI/2
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=PURPLE_E,fill_opacity=0.25,
            resolution=(1, 1))

        punto_8 = Dot(color=RED).move_to((1*8*PI/(8*PI),0,8*PI/2))

        plano_9 = ParametricSurface(
            lambda u, v: np.array([
                u,
                v,
                9*PI/2
            ]),v_min=-1.5,v_max=1.5,u_min=-1.5,u_max=1.5,fill_color=PURPLE_E,fill_opacity=0.25,
            resolution=(1, 1))

        planos = VGroup(plano_1,plano_2,plano_3,plano_4,plano_5,plano_6,plano_7,plano_8)
        puntos = VGroup(punto_1,punto_2,punto_3,punto_4,punto_5,punto_6,punto_7,punto_8)
        #Etiquetas ejes
        #POR EL MOVIMIENTO DE CÁMARA, TUVE QUE HACER VARIOS DEL MISMO
        eje_x_1 = TexMobject(r"x").scale(0.75).move_to((3.2,0.25,0))
        eje_x_2 = TexMobject(r"x").scale(0.75).move_to((-2.6,1,0))
        eje_x_3 = TexMobject(r"x").scale(0.75).move_to((-2.4,0.75,0))
        eje_y_1 = TexMobject(r"y").scale(0.75).move_to((0.3,3.5,0))
        eje_y_2 = TexMobject(r"y").scale(0.75).move_to((1,-3.3,0))
        eje_y_3 = TexMobject(r"y").scale(0.75).move_to((1.3,-3.5,0))
        eje_z_1 = TexMobject(r"t").scale(0.75).move_to((4.7,2,0))
        eje_z_2 = TexMobject(r"t").scale(0.75).move_to((4.7,1.6,0))
        ejes_1 = VGroup(eje_x_1,eje_y_1)
        ejes_2 = VGroup(eje_x_2,eje_y_2,eje_z_1)
        ejes_3 = VGroup(eje_x_3,eje_y_3,eje_z_2)

        #Etiquetas Planos
        text_plano_1 = TexMobject(r"t_1").move_to((-3.65,-3,0)).scale(0.75)
        text_plano_2 = TexMobject(r"t_2").move_to((-2.1,-2.4,0)).scale(0.75)
        text_plano_3 = TexMobject(r"t_3").move_to((-0.62,-1.9,0)).scale(0.75)
        text_planos_1 = VGroup(text_plano_1,text_plano_2,text_plano_3)
        text_plano_4 = TexMobject(r"t_4").move_to((0.7,-1.4 ,0)).scale(0.75)
        text_plano_5 = TexMobject(r"t_5").move_to((2,-1,0)).scale(0.75)
        text_plano_6 = TexMobject(r"t_6").move_to((3.15,-0.5,0)).scale(0.75)
        text_plano_7 = TexMobject(r"t_7").move_to((4.25,-0.05,0)).scale(0.75)
        text_plano_8 = TexMobject(r"t_8").move_to((5.2,0.4,0)).scale(0.75)
        text_planos_2 = VGroup(text_plano_4,text_plano_5,text_plano_6,text_plano_7,text_plano_8,text_plano_1,text_plano_2,text_plano_3)
        text_planos_i = TexMobject(r"\forall i, t_i \in A").move_to((4,-2.5,0)).scale(1.25)

        text_grafica_3 = TexMobject(r"G_{f}",color=YELLOW).move_to(eje_z_2.get_left()+2.5*LEFT)

        #EJEMPLO 3
        self.add(Caja_2)
        self.wait(0.5)
        self.play(ReplacementTransform(Caja_2,Caja_3))
        self.add_fixed_in_frame_mobjects(Caja_3)
        self.play(Write(text_3))
        self.wait(9.5)
        self.play(FadeOut(text_3))
        self.play(Write(text_4))
        self.wait(8.5)
        self.play(FadeOut(text_4))
        self.play(Write(text_5))
        self.wait(7.2)
        self.play(FadeOut(text_5))
        self.wait(0.5)
        self.play(FadeIn(ejemplo_3_10))
        self.set_camera_orientation(phi=0)
        self.play(ShowCreation(axes_2),FadeIn(ejes_1))
        self.wait(0.5)
        self.play(ShowCreation(curva_1))
        self.wait(19)
        self.play(FadeOut(ejes_1),FadeOut(ejemplo_3_10))
        self.move_camera(phi=142 * DEGREES,theta=55*DEGREES,gamma=-60*DEGREES,frame_center=(0.5,0,5),run_time=3)
        self.acomodar_textos(ejes_2)
        self.wait(2.5)
        self.acomodar_textos(text_6)
        self.wait(4)
        self.play(FadeOut(curva_1),FadeIn(puntos))
        self.wait(0.5)
        self.play(FadeOut(ejes_2))
        self.move_camera(phi=115*DEGREES,theta=32*DEGREES,gamma=-70*DEGREES,frame_center=(0,-0.1,6),run_time=2)
        self.wait()
        self.FadeOutWrite3D(text_6,text_7)
        self.wait(6.5)
        self.play(FadeIn(plano_1))
        self.acomodar_textos(text_plano_1)
        self.acomodar_textos(text_planos_i)
        self.play(FadeIn(plano_2))
        self.acomodar_textos(text_plano_2)
        self.FadeOutWrite3D(text_7,text_8)
        self.wait(6.5)
        self.play(FadeIn(plano_3))
        self.acomodar_textos(text_plano_3)
        self.play(FadeIn(plano_4))
        self.acomodar_textos(text_plano_4)
        self.FadeOutWrite3D(text_8,text_9)
        self.wait(5.7)
        self.play(FadeIn(plano_5))
        self.acomodar_textos(text_plano_5)
        self.play(FadeIn(plano_6))
        self.acomodar_textos(text_plano_6)
        self.FadeOutWrite3D(text_9,text_10)
        self.wait(8.75)
        self.play(FadeIn(plano_7))
        self.acomodar_textos(text_plano_7)
        self.play(FadeIn(plano_8))
        self.acomodar_textos(text_plano_8)
        self.play(FadeIn(plano_9))
        self.play(ShowCreation(curva_1),run_time=2)
        self.wait(2)
        self.play(FadeOut(plano_9))
        self.play(FadeOut(text_planos_2),FadeOut(text_planos_i),FadeOut(text_10))
        self.move_camera(phi=142 * DEGREES,theta=55*DEGREES,gamma=-60*DEGREES,frame_center=(0,-0.8,5),run_time=2)
        self.acomodar_textos(ejes_3)
        self.wait(2.5)
        self.play(FadeOut(planos))
        self.acomodar_textos(text_grafica_3)
        self.wait(3)
        self.play(
            *[FadeOut(mob)for mob in self.mobjects]
        )
        self.wait()

Límite y continuidad en funciones multivariable/visualizacion.py


from flask import Blueprint, render_template, request
import logging
import functions

loader_blueprint = Blueprint('loader_blueprint', __name__, template_folder="templates")
logging.basicConfig(filename="basic.log")

@loader_blueprint.route("/post")
def post_page():
    return render_template("post_form.html")

@loader_blueprint.route("/uploaded", methods=['POST'])
def uploaded_page():
    try:
        content = request.form['content']
        picture = request.files.get("picture")
        filename = picture.filename
        try:
            functions.check_extension(filename)
        except functions.NotAllowedExtension:
            return f"Данный формат файла не поддерживается"
        except IndexError:
            logging.exception("Ошибка загрузки")
            return f"Файл не отправлен"

        picture.save(f"./uploads/{filename}")
        pic_path = f"/uploads/{filename}"
        functions.save_data(pic_path, content)
        return render_template("post_uploaded.html", content=content, pic_path=pic_path)
    except PermissionError:
        logging.exception("Ошибка загрузки")
        return "Ошибка загрузки"


#coding:utf-8
#用户输入摄氏温度

#接收用户输入
celsius = float(input("输入摄氏温度："))

#计算华氏温度
fahrenheit = (celsius*1.8) +32
print("%0.1f 摄氏温度转为华氏温度为%0.1f"%(celsius,fahrenheit))

"""
#coding:utf-8
fahrenheit = float(input("输入华氏温度："))

celsius = (fahrenheit - 32)/1.8
print("%0.1f华氏温度转为摄氏温度为%0.1f" %(fahrenheit,celsius))

"""


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

import random

class Lotery:
	""" this class is representing the process"""
	def __init__(self):
		self.ret__M = 0
		self.res__M = 0
		self.esp__M = 0
#retorno = step(process executou) - step(process exc = 0)
	def work(self, process):
		step = 0
		inc = 0
		ret = 0.0
		res = 0.0
		esp = 0.0
		while len(process) > 0:
			end = 1;
			lst = []
			for x in range(0, len(process), 1):
				if process[x].arr <= step:
					lst.append(x)
			i = random.randint(0, (len(lst)-1))
			#print("random: "+str(i))
			if process[lst[i]].start_exc < 0 :
				process[lst[i]].set_start_exc(step+1)
				res += (step - process[lst[i]].arr)
			if (process[lst[i]].exc == 1):
				process[lst[i]].dec_exc(1)
				step += 1
				inc = 1
			else:
				process[lst[i]].dec_exc(2)
				step += 2
				inc = 2
			if process[lst[i]].exc == 0:
				#print("processo: "+str(process[lst[i]].idt)+" Finalizou em "+str(step))
				ret += (step - process[lst[i]].arr)+1
				del process[lst[i]]
				for x in process:
					if x.arr <= step:
						if x.arr_aux%2 == 0 :
							esp += inc
						else:
							if inc == 2:
								esp += inc - x.arr_aux
								x.arr_to_pair()
							else:
								esp += inc
			else:
				for x in xrange(0,len(process)):
					if x != lst[i]:
						if process[x].arr <= step:
							if process[x].arr_aux%2 == 0 :
								esp += inc
							else:
								if inc == 2:
									esp += inc - process[x].arr_aux
									process[x].arr_to_pair()
								else:
									esp += inc
		return (ret, res, esp)


import numpy as np
import matplotlib
from matplotlib import pyplot as plt
plt.switch_backend('agg')
import matplotlib.patches
from scipy import stats
import pandas as pd
import math
from mpi4py import MPI
import sys
import itertools
import glob
import os

plt.ioff()

design = str(sys.argv[1])

all_IDs = ['3600687', '7000550', '7200799', '7200645', '3704614', '7202003']#np.genfromtxt('../structures_files/metrics_structures.txt', dtype='str').tolist()
nStructures = len(all_IDs)

percentiles = np.arange(0, 100)

os.chdir('../' + design)
directories = glob.glob('CMIP*_*')
directories.remove('CMIP3_070')
os.chdir('../output_analysis')
scenarios = len(directories)
if design == 'CMIP_curtailment':
    sow = 27

else:
    sow = 1

idx = np.arange(2, sow*2+2, 2)
historical = pd.read_csv('../structures_files/shortages.csv', index_col=0)

def alpha(i, base=0.2):
    l = lambda x: x + base - x * base
    ar = [l(0)]
    for j in range(i):
        ar.append(l(ar[-1]))
    return ar[-1]

def shortage_duration(sequence, threshold):
    cnt_shrt = [sequence[i] > threshold for i in
                range(len(sequence))]  # Returns a list of True values when there's a shortage
    shrt_dur = [sum(1 for _ in group) for key, group in itertools.groupby(cnt_shrt) if
                key]  # Counts groups of True values
    return shrt_dur

def plotSDC(synthetic, histData,  structure_name):
    n = 12
    # Reshape historic data to a [no. years x no. months] matrix
    f_hist = np.reshape(histData, (int(np.size(histData) / n), n))
    # Reshape to annual totals
    f_hist_totals = np.sum(f_hist, 1)
    # Calculate historical shortage duration curves
    F_hist = np.sort(f_hist_totals)  # for inverse sorting add this at the end [::-1]

    # Reshape synthetic data
    # Create matrix of [no. years x no. months x no. samples]
    synthetic_global = np.zeros([int(len(histData) / n), n, scenarios * sow])
    # Loop through every SOW and reshape to [no. years x no. months]
    for j in range(scenarios * sow):
        synthetic_global[:, :, j] = np.reshape(synthetic[:, j], (int(np.size(synthetic[:, j]) / n), n))
    # Reshape to annual totals
    synthetic_global_totals = np.sum(synthetic_global, 1)

    p = np.arange(100, -10, -10)

    # Calculate synthetic shortage duration curves
    F_syn = np.empty([int(len(histData) / n), scenarios * sow])
    F_syn[:] = np.NaN
    for j in range(scenarios * sow):
        F_syn[:, j] = np.sort(synthetic_global_totals[:, j])

    # For each percentile of magnitude, calculate the percentile among the experiments ran
    perc_scores = np.zeros_like(F_syn)
    for m in range(int(len(histData) / n)):
        perc_scores[m, :] = [stats.percentileofscore(F_syn[m, :], j, 'rank') for j in F_syn[m, :]]

    P = np.arange(1., len(histData)/12 + 1) * 100 / (len(histData)/12)

    ylimit = np.max(F_syn)
    fig, (ax1) = plt.subplots(1, 1, figsize=(14.5, 8))
    # ax1
    handles = []
    labels = []
    color = '#000292'
    for i in range(len(p)):
        ax1.fill_between(P, np.min(F_syn[:, :], 1), np.percentile(F_syn[:, :], p[i], axis=1), color=color, alpha=0.1)
        ax1.plot(P, np.percentile(F_syn[:, :], p[i], axis=1), linewidth=0.5, color=color, alpha=0.3)
        handle = matplotlib.patches.Rectangle((0, 0), 1, 1, color=color, alpha=alpha(i, base=0.1))
        handles.append(handle)
        label = "{:.0f} %".format(100 - p[i])
        labels.append(label)
    #Plot 50th percentile line separately
    ax1.plot(P, np.percentile(F_syn[:, :], p[5], axis=1), linewidth=0.7, color=color, alpha=0.7, linestyle='dashed')
    ax1.plot(P, F_hist, c='black', linewidth=2, label='Historical record')
    ax1.set_ylim(0, ylimit)
    ax1.set_xlim(0, 100)
    ax1.legend(handles=handles, labels=labels, framealpha=1, fontsize=8, loc='upper left',
               title='Frequency in experiment', ncol=2)
    ax1.set_xlabel('Shortage magnitude percentile', fontsize=20)
    ax1.set_ylabel('Annual shortage (Million $m^3$)', fontsize=20)

    fig.suptitle('Shortage magnitudes for ' + structure_name, fontsize=16)
    plt.subplots_adjust(bottom=0.2)
    fig.savefig('../' + design + '/ShortagePercentileCurves/' + structure_name + '_' + design + '.svg')
    fig.savefig('../' + design + '/ShortagePercentileCurves/' + structure_name + '_' + design + '.png')
    fig.clf()

# Begin parallel simulation
comm = MPI.COMM_WORLD

# Get the number of processors and the rank of processors
rank = comm.rank
nprocs = comm.size

# Determine the chunk which each processor will neeed to do
count = int(math.floor(nStructures / nprocs))
remainder = nStructures % nprocs

# Use the processor rank to determine the chunk of work each processor will do
if rank < remainder:
    start = rank * (count + 1)
    stop = start + count + 1
else:
    start = remainder * (count + 1) + (rank - remainder) * count
    stop = start + count

for i in range(start, stop):
    histData = historical.loc[all_IDs[i]].values[-768:] * 1233.4818 / 1000000
    synthetic = np.zeros([len(histData), scenarios * sow])
    for j in range(scenarios):
        path = '../' + design + '/Infofiles/' + all_IDs[i] + '/' + all_IDs[i] + '_info_' + directories[j] + '.txt'
        data = np.loadtxt(path)
        synthetic[:, j * sow:j * sow + sow] = data[:, idx] * 1233.4818 / 1000000
    plotSDC(synthetic, histData, all_IDs[i])


import random
from scipy import linalg
import numpy as np
import scipy

class Hill:
    def find_multiplicative_inverse(self, determinant, len_alfabeto):
        print(f"DETERMINANTE: {determinant}")
        for i in range(len_alfabeto):
            inverse = determinant * i
            if int(round(inverse % len_alfabeto, 1)) == 1:
                print(
                    f"multiplicative_inverse:{i}\tlen_alfabeto:{len_alfabeto}")
                return i
        raise Exception("Não encontrado inverse multiplicative")

    def matrix_cofactor(self, matrix):
        try:
            determinant = np.linalg.det(matrix)
            if(determinant != 0):
                cofactor = None
                cofactor = np.linalg.inv(matrix).T * determinant
                # return cofactor matrix of the given matrix
                return cofactor
            else:
                raise Exception("singular matrix")
        except Exception as e:
            print("could not find cofactor matrix due to", e)

    def get_inverse(self, matriz, len_alfabeto):
        return matriz.I

    def mult_matrix(self, matriz1, matriz2, len_alfabeto):
        return matriz1 * matriz2 % len_alfabeto

    def normalize_text(self, text, len_matriz):
        len_text = len(text)
        resto = len_text % len_matriz
        if(resto != 0):
            for _ in range(len_matriz-resto):
                text = text+'o'
            pass
        else:
            pass
        # print(text)
        len_text = len(text)
        return text, len_text

    def one_matriz_convert(self, lenx, leny, alfabeto, text):
        arrays = []
        for _ in range(lenx):
            row = []
            for _ in range(leny):
                # print(text[0],alfabeto.index(text[0]));
                row.append(alfabeto.index(text[0]))
                text = text[1:]
                # print(text);
                pass
            arrays.append(row)
        local_matriz = np.array(arrays, dtype=np.float64)
        return local_matriz, text

    def convert_text_to_matrizes(self, text, shape, alfabeto):
        len_matriz = shape[0]*shape[1]
        text, len_text = self.normalize_text(text, len_matriz)
        num_natrizes = int(len_text/len_matriz)
        matrizes = []
        for _ in range(num_natrizes):
            local_matriz, text = self.one_matriz_convert(
                shape[0], shape[1], alfabeto, text)
            matrizes.append(local_matriz)
            pass
        return matrizes

    def convert_matriz_to_text(self, matriz, alfabeto):
        text = ''
        for row in matriz.A:
            for col in row:
                text += alfabeto[int(col % len(alfabeto))]
        return text

    def encript(self, text, matriz, alfabeto):
        len_alfabeto = len(alfabeto)
        matrizes = self.convert_text_to_matrizes(text, matriz.shape, alfabeto)
        matriz_cripto = []
        for matriz_text in matrizes:
            cripto = matriz_text * matriz
            matriz_cripto.append(cripto)
        cripto_text = ''
        for matriz_c in matriz_cripto:
            cripto_text += self.convert_matriz_to_text(matriz_c, alfabeto)
        return cripto_text

    def matrix_cofactor(self, matrix):
        return np.linalg.inv(matrix) * np.linalg.det(matrix)

    def get_adjungate_matrix(self, matriz, determinant):
        x = matriz.A
        c = [[i for i in range(3)] for j in range(3)]
        for i in range(3):
            for j in range(3):
                c[i][j] = (-1)*(i+j)*determinant

    def decript(self, cripto_text, matriz, alfabeto):
        print(cripto_text)
        cripto_text="syi"
        len_alfabeto = len(alfabeto)
        determinant = int(round(np.linalg.det(matriz), 1)) % len_alfabeto
        multiplicative_inverse = self.find_multiplicative_inverse(
            determinant, len_alfabeto)
        matriz_inv = np.conj(matriz).T
        cofactor = self.matrix_cofactor(
            matriz) % len_alfabeto
        invert_key_matrix = cofactor*multiplicative_inverse%len_alfabeto
        print(
            f"det:{determinant}\tinverse:{multiplicative_inverse}\tinv:{invert_key_matrix}\ncofactor:\n{cofactor}")
        matriz_inv = matriz_inv*multiplicative_inverse
        matrizes_cript = self.convert_text_to_matrizes(
            cripto_text, matriz.shape, alfabeto)
        matriz_decripto = []
        for matriz_text in matrizes_cript:
            decripto = self.mult_matrix(matriz_text, invert_key_matrix, len_alfabeto)
            matriz_decripto.append(decripto)
        decripto_text = ''
        for matriz_d in matriz_decripto:
            decripto_text += self.convert_matriz_to_text(matriz_d, alfabeto)
        return decripto_text

def testando_fatores_iniciais(alfabeto):
    hill = Hill()
    len_alfabeto = len(alfabeto)
    matriz2 = np.array([[2,  2], [14, 26]], dtype=np.float64)
    # print(f"Testando fatores Iniciais\n {'_'*100}")
    matriz = np.array([[9, 4], [5, 7]], dtype=np.float64)
    print(f"matriz: \n{matriz}")
    matriz_inv = hill.get_inverse(matriz, len(alfabeto))
    print(f"Inversa:\n{matriz_inv}")
    print(
        f"Matriz e Inversa: \n{hill.mult_matrix(matriz, matriz_inv, len_alfabeto)}")
    print(f"Testando criptografia e decriptografia\n{'&'*100}")
    print(matriz2)
    cripto = hill.mult_matrix(matriz2, matriz, len_alfabeto)
    print(cripto)
    decripto = hill.mult_matrix(cripto, matriz_inv, len_alfabeto)
    print(decripto)
    return matriz_inv

hill = Hill()
alfabeto = 'abcdefghijklmnopqrstuvwxyz'

if(__name__ == '__main__'):
    matriz = np.matrix([[1,  0, 2],
                       [10,  20, 15],
                       [0, 1, 2]], dtype=np.float64)
    chave = 'cabababababasdaba'
    text = input()
    text = text.replace(' ', '')
    text="ret"
    print(f"PLAIN_TEXT: {text}")
    cripto_text = hill.encript(text, matriz, alfabeto)
    matriz_inv = hill.get_inverse(matriz, len(alfabeto))
    print(f"CRIPTED_TEXT: {cripto_text}")
    cripto_text ="syi"
    matriz = np.matrix([[0,  11, 15],
                       [7,  0, 1],
                       [4, 19, 0]], dtype=np.float64)
    print(f"Decriptando:")
    decripto_text = hill.decript(cripto_text, matriz, alfabeto)
    print(decripto_text)


import numpy as np
import pandas as pd
from collections import OrderedDict
import matplotlib as mlt
import matplotlib.pyplot as plt
from scipy import optimize

def get_data():
    data = OrderedDict(
        amount_spent =  [50,  10, 20, 5,  65,  70,  80,  81, 1],
        send_discount = [0,   1,  1,  1,  0,   0,   0,    0,   1]
        )
    df = pd.DataFrame.from_dict(data) # creating a dataframe
    X = df['amount_spent'].astype('float').values # converting the type to 'float'
    y = df['send_discount'].astype('float').values # converting the type to 'float'
    return (X,y) # returning the X , y

def get_theta(costFunction , X , y , iter = 400):

    options = {'maxiter':iter} # maximum number of iterations

    row , col = X.shape

    initial_theta = np.zeros(col)

    res = optimize.minimize(
        costFunction,
        initial_theta ,
        (X,y),
        jac=True,
        method='TNC',
        options = options
    )
    # the fun property of `OptimizeResult` object returns
    # the value of costFunction at optimized theta
    cost = res.fun

    # the optimized theta is in the x property
    theta = res.x

    return ( cost , theta )

def sigmoid(z):
    # convert input to a numpy array
    z = np.array(z)

    g = np.zeros(z.shape)

    g = 1 / (1 + np.exp(-z))

    return g

def costFunction(theta, X, y):

    m = y.size  # number of training examples

    J = 0
    grad = np.zeros(theta.shape) #

    h = sigmoid(X.dot(theta.T)) # sigmoid function

    J = (1 / m) * np.sum(-y.dot(np.log(h)) - (1 - y).dot(np.log(1 - h)))
    grad = (1 / m) * (h - y).dot(X)

    return J, grad

def load_data(url):
    df=pd.read_csv(url,header=None);
    return ( df.iloc[:,:-1] , df.iloc[:,-1])

def run():

    X , y = load_data('./marks.txt')

    ones = X[y==1] # features X where y == 1
    zeros = X[y==0] # features X where y == 0

    #X,y = get_data()
    row , col = X.shape
    # Add intercept term to X
    X = np.concatenate([np.ones((row, 1)), X], axis=1)

    (cost,theta)=get_theta(costFunction , X , y )

    print('cost => {} , theta => {}'.format(cost,theta) )

    #print(' x ',X[:,1:3]) # prints col 0 , 1

    # calculate min of X - 2 , max of X + 2
    x_treme = np.array([ np.min(X[:,1]) - 2 , np.max(X[:,1]) + 2 ])

    # calculate y extreme
    #y_treme = (-1. / theta[2]) * ( theta[1] * x_treme + theta[0] )

    y_treme = - (( np.dot(theta[1] ,x_treme) ) + theta[0] ) / theta[2]

    plt.plot(x_treme , y_treme)

    plt.scatter(ones[0],ones[1] , label="1's ")
    plt.scatter(zeros[0],zeros[1], label="0's ")

    plt.legend(loc="upper right")
    plt.show()

if __name__ == "__main__":
    run()


"""
    Implements a mixin for remote communication.
"""

import re
import json
import socket

whitespace_re = re.compile(r"\s+")

class RemoteActor:

    ENCODING = "utf-8"
    DECODER = json.JSONDecoder()

    def __init__(self, socket):
        """ Creates a new remote actor able to send and receive from the given socket
        :param socket: socket connection
        """
        self.socket = socket
        self.buffer = ""

    def parse(self, clear_on_partial=False):
        print(self.buffer)
        try:
            decoded, end = self.DECODER.raw_decode(self.buffer)
        except ValueError:
            print(self.buffer, "va")
            return False, False, False

        if not isinstance(decoded, bool) and (isinstance(decoded, int) or isinstance(decoded, float)) and end == len(self.buffer):
            if clear_on_partial:
                self.buffer = self.buffer[end:]
            return True, False, decoded
        else:
            print(decoded, "blah")
            self.buffer = self.buffer[end:]
            return True, True, decoded

    def send(self, data):
        """ Sends the given JSON object to the socket
        :param data: JSON object
        """
        encoded = json.dumps(data).encode(self.ENCODING)
        self.socket.send(encoded)

    def receive(self):
        """ Continuously receives bytes until a JSON object can be deserialized, at which point
          the deserialized object is returned. It is up to the caller to restrict the execution time.
        :return: deserialized JSON object
        """
        data = bytes()
        while True:
            try:
                data += self.socket.recv(1)
            except socket.timeout:
                something, complete, decoded = self.parse(True)
                print(something, complete, decoded)
                if something:
                    return decoded
                raise

            try:
                decoded = data.decode(self.ENCODING)
                self.buffer += decoded
                data = bytes()
            except UnicodeDecodeError:
                continue

            something, complete, decoded = self.parse()
            if something and complete:
                return decoded

    def receive_iterator(self):
        """ Continuously receives data and deserializes JSON objects as they come in """
        while True:
            yield self.receive()


import numpy as np
from torch.utils import data
import torch as t
import matplotlib.pyplot as plt
import h5py
from .utils.utils import mat2gray_nocrop, plot_img_with_labels
import os
import random
import ipdb
from .visualize_predictions import draw_label_img
from scipy.ndimage import gaussian_filter
import monai

def torch_randint(max_v):
    return t.randint(max_v, (1, 1)).view(-1).numpy()[0]

def torch_rand(size=1):
    return t.rand(size).numpy()

def augmentation(img, mask):
    img = img.numpy()
    mask = mask.numpy()
    r = [torch_randint(2), torch_randint(2), torch_randint(4)]
    if r[0]:
        img = np.fliplr(img)
        mask = np.fliplr(mask)
    if r[1]:
        img = np.flipud(img)
        mask = np.flipud(mask)
    img = np.rot90(img, k=r[2])
    mask = np.rot90(mask, k=r[2])

    # min_v = (torch_rand() * 0.96) - 0.48
    # max_v = 1 + (torch_rand() * 0.96) - 0.48
    # for k in range(img.shape[-1]):
    #    img[:, :, k] = mat2gray_nocrop(img[:, :, k], [min_v, max_v]) - 0.5

    """
    r = [torch_randint(2), torch_randint(2), torch_randint(4)]
    if r[0]:
        img = np.fliplr(img)
        mask = np.fliplr(mask)
    if r[1]:
        img = np.flipud(img)
        mask = np.flipud(mask)
    img = np.rot90(img, k=r[2])
    mask = np.rot90(mask, k=r[2])
    img = img.numpy()
    min_v = (torch_rand() * 0.96) - 0.48
    max_v = 1 + (torch_rand() * 0.96) - 0.48
    for k in range(img.shape[2]):

        img[:, :, k] = mat2gray_nocrop(img[:, :, k], [min_v, max_v]) - 0.5

    """
    """
    tmp_img = t.cat([img, label_img], dim=-1)

    transforms = monai.transforms.Compose(
        monai.transforms.RandAxisFlipd(keys=["image"], prob=0.5),
        monai.transforms.RandRotate90d(keys=["image"], prob=0.5),
        monai.transforms.RandGridDistortiond(
            keys=["image"], prob=0.5, distort_limit=0.2
        ),
        monai.transforms.OneOf(
            [
                monai.transforms.RandShiftIntensityd(
                    keys=["image"], prob=0.5, offsets=(0.1, 0.2)
                ),
                # monai.transforms.RandAdjustContrastd(
                #    keys=["image"], prob=0.5, gamma=(1.5, 2.5)
                # ),
                # monai.transforms.RandHistogramShiftd(keys=["image"], prob=0.5),
            ]
        ),
    )
    uba = transforms(dict(image=tmp_img))
    img = uba["image"][:, :, :3]
    # print(f"{img.shape=}")
    label_img = uba["image"][:, :, -2:]
    # print(f"{label_img.shape=}")
    """
    """
    if t.rand(1)[0] > 0.5:
        img = t.flipud(img)
        label_img = t.flipud(label_img)
    if t.rand(1)[0] > 0.5:
        img = t.fliplr(img)
        label_img = t.fliplr(label_img)
    if t.rand(1)[0] > 0.5:
        '''
        img = img + t.randn(img.shape) * 0.05
        img = t.clamp(img, 0, 1)
        '''
    if t.rand(1)[0] > 0.5:
        times = t.randint(4, (1,))[0]
        img = t.rot90(img, k=times)
        label_img = t.rot90(label_img, k=times)
    """
    return t.from_numpy(img.copy()), t.from_numpy(mask.copy())

class FociDataset(data.Dataset):
    def __init__(
        self,
        *,
        hdf5_filename: str,
        filenames: tuple[str, ...],
        split: str,
        crop_size: tuple[int, int],
        out_len: int,
    ):

        self.hdf5_filename = hdf5_filename
        self.split = split
        self.crop_size = crop_size
        self.filenames = filenames
        self.out_len = out_len
        self.h5data = None

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

    def __getitem__(self, idx):

        if self.h5data is None:
            self.h5data = h5py.File(self.hdf5_filename, "r")

        filename = self.filenames[idx]
        img = t.from_numpy(self.h5data[filename + "_image"][...]).permute(
            1, 2, 0
        )
        label = t.from_numpy(self.h5data[filename + "_label"][...]).permute(
            1, 2, 0
        )
        in_size = img.shape
        out_size = self.crop_size
        if not self.split == "test":
            r = [
                t.randint(in_size[i] - out_size[i], (1,))[0] for i in range(2)
            ]
            img = img[
                r[0] : r[0] + out_size[0], r[1] : r[1] + out_size[1], :,
            ]
            label = label[
                r[0] : r[0] + out_size[0],
                r[1] : r[1] + out_size[1],
                :,  # TODO: check this. Why do I need to swap the order of the two indices???
            ]
        if self.split == "train":
            img, label = augmentation(img, label)

        img = img.permute(2, 0, 1).float()
        label = label.permute(2, 0, 1).float()

        return img, label


#!/usr/bin/env python

from utils.analysis import AbsMovingAvg, Threshold, Derivative
from utils.chaser import Chaser

import os
import sys
parentDir = os.path.dirname(os.getcwd())
sys.path.append(parentDir)
def checkImport(lib):
    if not os.path.exists(os.path.join(parentDir, lib)):
        print("%s library not found." % lib)
        print("please clone github.com/andrewbooker/%s.git into %s" % (lib, parentDir))
        exit()

checkImport("mediautils")
from mediautils.mididevices import UsbMidiDevices, MidiOut

## ===== composer =====

checkImport("compositionutils")
from compositionutils.scale import Scale, Modes

tonic = "C"
mode = "aeolian"
print(tonic, mode)

noteSpan = 15
scale = Scale(noteSpan, tonic, Modes.named(mode))

class Consumer():
    def __init__(self, midiOut):
        self.midiOut = midiOut
        self.note = 0

    def on(self, velocity):
        self.note = scale.noteFrom(int(velocity * 100) % noteSpan)
        self.midiOut.note_on(self.note, int(26 + (velocity * 100)), 0)

    def off(self):
        self.midiOut.note_off(self.note, 0, 0)

## =====

midiDevices = UsbMidiDevices()
midiOut = MidiOut(midiDevices)
consumer = Consumer(midiOut.io)
chaser = Chaser(consumer, 0.6, 0.2)

import soundfile as sf

infile = sys.argv[1]
workingDir = os.path.dirname(infile)
print("loading %s" % infile)
(data, sampleRate) = sf.read(infile, dtype="float32")

for s in range(len(data)):
    chaser.add(data[s])

del midiOut
del midiDevices
print("done")


# Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.logger import logger
from opus_core.resources import Resources
from opus_core.storage_factory import StorageFactory
from numpy import array
import os

class GenerateTestData(object):
    """ I don't think this is used anywhere
    """

    def run(self, config, year, *args, **kwargs):
        """ """
        logger.start_block('Starting GenerateTestData.run(...)')

        cache_dir_w_year = os.path.join(config['cache_directory'],year.__str__())

        storage = StorageFactory().get_storage('flt_storage', storage_location = cache_dir_w_year )
        storage.write_table(table_name = 'persons',
                            table_data = {'person_id':    array([1,2,3]),
                                          'household_id': array([1,2,3]),
                                          'job_id':       array([4,5,6])
                                          }
                            )
        storage.write_table(table_name = 'households',
                            table_data = {'household_id':    array([1,2,3]),
                                          'building_id': array([1,2,3]),
                                          }
                            )
        storage.write_table(table_name = 'jobs',
                            table_data = {'job_id':    array([4,5,6]),
                                          'building_id': array([4,5,6]),
                                          }
                            )
        storage.write_table(table_name = 'buildings',
                            table_data = {'building_id':    array([1,2,3,4,5,6]),
                                          'parcel_id': array([1,2,3,4,5,6]),
                                          }
                            )
        storage.write_table(table_name = 'parcels',
                            table_data = {'parcel_id':    array([1,2,3,4,5,6]),
                                          'x_coord_sp': array([1.,2.,3.,4.,5.,6.]),
                                          'y_coord_sp': array([1.,2.,3.,4.,5.,6.]),
                                          'zone_id': array([1,1,1,3,3,3]),
                                          }
                            )

        logger.end_block()

# the following is needed, since it is called as "main" from the framework ...
if __name__ == "__main__":
    try: import wingdbstub
    except: pass
    from optparse import OptionParser
    from opus_core.file_utilities import get_resources_from_file
    parser = OptionParser()
    parser.add_option("-r", "--resources", dest="resources_file_name", action="store", type="string",
                      help="Name of file containing resources")
    parser.add_option("-y", "--year", dest="year", action="store", type="int",
                      help="Year in which to 'run' the travel model")
    (options, args) = parser.parse_args()
    resources = Resources(get_resources_from_file(options.resources_file_name))

    logger.enable_memory_logging()
    GenerateTestData().run(resources, options.year)


import numpy as np

import matplotlib.pyplot as plt
import matplotlib.patches as patches

import logic

UI_BOARD_SIZE = (8, 6)
UI_BOARD_OFFSET = 0.25
UI_BOARD_CELL_COLORS = [(0,0,0,0.4), (0,0.9,1,0.7)]

'''
UI front-end implementation
'''
class Board:
    def __init__(self):
        # Create figure and axes
        self.fig, self.ax = plt.subplots(figsize=UI_BOARD_SIZE)
        # Board background color
        self.ax.set_facecolor((0,0,0,0.15))
        # Hiding axes
        self.ax.get_xaxis().set_visible(False)
        self.ax.get_yaxis().set_visible(False)
        # Scale axes
        self.ax.set_xlim([0,1])
        self.ax.set_ylim([0,1])
        self.ax.set_aspect('equal', adjustable='box')

        # Board cells
        self.patches = []

        # Last board state - needed for differential update of board
        self.last_state = None

        # Connect to UI for mouse click event
        connection_id = self.fig.canvas.mpl_connect('button_press_event', self.on_click_cell)
        self.on_click_event_handler = None

        # Generation label
        self.lbl_generation = None

        # Next generation button
        axnext = plt.axes([0.45, 0.9, 0.2, 0.075])
        self.bnext = plt.Button(axnext, 'Next', color=(0, 1, 0.7, 0.7), hovercolor=(0, 1, 0.7, 1))
        self.bnext.label.set_fontsize(16)
        self.bnext.on_clicked(self.on_click_btn_next)

        # Reset button
        axreset = plt.axes([0.25, 0.9, 0.1, 0.075])
        self.breset = plt.Button(axreset, 'Reset', color=(1, 0.2, 0, 0.7), hovercolor=(1, 0.2, 0, 1))
        self.breset.label.set_fontsize(16)
        self.breset.on_clicked(self.on_click_btn_reset)

    def on_click_btn_next(self, event):
        if self.on_click_event_handler is None:
            raise ValueError
        self.on_click_event_handler(logic.EVENT_NEXT_CLICK)

    def on_click_btn_reset(self, event):
        if self.on_click_event_handler is None:
            raise ValueError
        self.on_click_event_handler(logic.EVENT_RESET_CLICK)

    def on_click_cell(self, event):
        if not event.inaxes == self.ax:
            return
        # Left mouse button click to change cell state
        if event.button == 1:
            x = int(np.floor((event.xdata - self.cell_margin[0]) / self.cell_width))
            y = int(np.floor((event.ydata - self.cell_margin[1]) / self.cell_height))
            if self.on_click_event_handler is None:
                raise ValueError
            self.on_click_event_handler(logic.EVENT_CELL_CLICK, data=(x, y))

    def set_click_event_handler(self, handler):
        self.on_click_event_handler = handler

    def redraw_board(self, state):
        # Update cell size and margin
        self.cell_width = 1. / state.shape[0]
        self.cell_height = 1. / state.shape[1]
        self.cell_margin = (self.cell_width * 0.05, self.cell_height * 0.05)

        # Remove all previously drawn patches
        [p.remove() for p in reversed(self.ax.patches)]

        # Add new patches
        for x in range(state.shape[0]):
            for y in range(state.shape[1]):
                rect = patches.Rectangle((x*self.cell_height + self.cell_margin[1], y*self.cell_width + self.cell_margin[0]),
                            self.cell_width*0.9, self.cell_height*0.9,
                            fill=True, facecolor=UI_BOARD_CELL_COLORS[state[x, y]])
                self.ax.add_patch(rect)
        self.patches = self.ax.patches

        # Update last state
        self.last_state = state.copy()

        plt.show()

    def redraw_ui_elements(self, generation=None):
        # UI elements, status, buttons
        if not generation is None:
            if not self.lbl_generation is None:
                self.lbl_generation.remove()

            self.lbl_generation = self.ax.annotate('%d' % generation,
                color='k', weight='bold', fontsize=16, ha='center', va='center',
                xy=(0.95, 1.08), xycoords=self.ax.transAxes, annotation_clip=False)

    def redraw(self, state, generation=None):
        # Redraw game board
        self.redraw_board(state)

        # UI elements, status, buttons
        if not generation is None:
            self.redraw_ui_elements(generation)

    def update(self, state, generation=None):
        # Redraw entire board if state dimension has changed
        if self.last_state is None or state.size != self.last_state.size:
            self.redraw(state, generation)

        # Update only those cells, that have changed since last state
        diff = np.subtract(state, self.last_state)
        changed_idx = list(zip(*diff.nonzero()))
        for xy in changed_idx:
            self.patches[xy[0] * state.shape[0] + xy[1]].set_facecolor(UI_BOARD_CELL_COLORS[state[xy[0], xy[1]]])

        # Update last state
        self.last_state = state.copy()

        # UI elements, status, buttons
        if not generation is None:
            self.redraw_ui_elements(generation)

        plt.show()


import pandas as pd
import pickle
from pathlib import Path

def preprocess_test_df(test_clin_df, test_prot_df, test_pep_df, save_data=False):

    if 'upd23b_clinical_state_on_medication' in test_clin_df.columns:
        # drop the medication column
        test_clin_df = test_clin_df.drop(columns=['upd23b_clinical_state_on_medication'])

    # create a column with the UniProt and Peptide name combined
    test_pep_df['peptide_uniprot'] = test_pep_df['Peptide'] + '_'+ test_pep_df['UniProt']

    # create a table with the visit_id as the index and the proteins or peptides as the feature and the abundance as the values
    train_prot_pivot = test_prot_df.pivot(index='visit_id', values='NPX', columns='UniProt')
    train_pep_pivot = test_pep_df.pivot(index='visit_id', values='PeptideAbundance', columns='peptide_uniprot')

    # combine the two tables on the visit_id
    full_prot_train_df = train_prot_pivot.join(train_pep_pivot)

    # fill nan with 0
    full_prot_train_df = full_prot_train_df.fillna(0)

    full_train_df = test_clin_df.merge(full_prot_train_df, how='inner', left_on='visit_id', right_on='visit_id')
    full_train_df = full_train_df.sample(frac=1).reset_index(drop=True)

    return full_train_df

test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test.csv')

prot_test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test_proteins.csv')

pep_test_df = pd.read_csv('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/raw/test_peptides.csv')

full_test_df = preprocess_test_df(test_df, prot_test_df, pep_test_df, save_data=False)

updr = 'updrs_1'
month = 0

for updr in ['updrs_1', 'updrs_2', 'updrs_3', 'updrs_4']:
    updr_df = full_test_df[full_test_df['updrs_test'] == updr]
    info_cols = ['visit_id', 'visit_month', 'patient_id', 'updrs_test', 'row_id', 'group_key']
    updr_info = updr_df[info_cols]
    model_df = updr_df.drop(columns=info_cols)

    for month in [0, 6, 12, 24]:
        # Load the saved model from file
        model_path = Path('~/parkinsons_proj_1/parkinsons_project/parkinsons_1/models/model_rf_reg_updrs_1_0.pkl')

        with open(model_path, 'rb') as f:
            rf_reg = pickle.load(f)

        # Use the imported model to make predictions
        y_pred = rfc.predict(model_df)

target = 'updrs_4'
train_df = pd.read_csv(f'~/parkinsons_proj_1/parkinsons_project/parkinsons_1/data/processed/train_{target}.csv')
train_df.head()


"""
Here I will read access tokens from txt file for safety
"""
import json

class Token:
    def __init__(self):
        with open('tokens.json', 'r') as f:
            data = json.loads(f.readline())
        self.community = data['comm_token']
        self.user = data['usr_token']
        self.comm_id = -167621445
        self.usr_id = 491551942

if __name__=='__main__':
    t = Token()


from openpyxl import load_workbook
# from openpyxl.cell import Cell

if __name__ == '__main__':
    wb = load_workbook('data/FINODAYS_Доп. материал для Почта Банк_Диалоги.xlsx')
    for sn in wb.sheetnames:
        print(sn)
        marks = []
        for row in wb[sn]:
            if row[1].value == 'CLIENT':
                print(row[2].value)
            elif row[2].value.startswith('Оценка'):
                marks.append(row[2].value)
        print('Оценки:', *marks, end='\n' + '-' * 50 + '\n')


with open("2021\Day_14\input.txt") as f:
    template = f.readline().strip()
    elements = {e.split()[0]:e.split()[-1] for e in f.read().splitlines() if e != ""}

# # Example data
# template = "NNCB"

# elements = {
#     "CH": "B",
#     "HH": "N",
#     "CB": "H",
#     "NH": "C",
#     "HB": "C",
#     "HC": "B",
#     "HN": "C",
#     "NN": "C",
#     "BH": "H",
#     "NC": "B",
#     "NB": "B",
#     "BN": "B",
#     "BB": "N",
#     "BC": "B",
#     "CC": "N",
#     "CN": "C",
# }

steps = 10
for s in range(steps):
    temp = ""
    for t in range(len(template)-1):
        part = template[t:t+2]
        temp += part[0]+ elements[part]
    template = temp + template[-1]

counts = dict.fromkeys(template,0)
counts = {c:template.count(c) for c in counts.keys()}
print(max(counts.values())-min(counts.values()))