from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ProfilManager(models.Manager):
    def create_profil(self, user):
        profil = self.create(user=user)
        return profil

class Profail(models.Model):
    user=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
    photo=models.ImageField(upload_to="static/user_photo/",blank=True,default="static\img\images.png")
    address=models.CharField(max_length=200,default='user')
    phone_number = models.CharField(max_length=20,default='user')
    objects=ProfilManager()
    def __str__(self):
        return str(self.user)


from pathlib import Path
import numpy as np
import cv2
from isegm.data.base import ISDataset
from isegm.data.sample import DSample

class TubesDataset(ISDataset):
    def __init__(self, dataset_path, split, custom_augmentor=None, **kwargs):
        super(TubesDataset, self).__init__(**kwargs)
        self.dataset_path = Path(dataset_path)
        self._data_path = self.dataset_path / split
        self._images_path = self._data_path / 'images'
        self._insts_path = self._data_path / 'masks'
        self.dataset_samples = [x.name for x in sorted(self._images_path.glob('*.png'))]
        self._custom_augmentor = custom_augmentor

    def get_sample(self, index) -> DSample:
        image_name = self.dataset_samples[index]
        mask_name = image_name.replace("image", "mask")
        image_path = str(self._images_path / image_name)
        mask_path = str(self._insts_path / mask_name)

        image = cv2.imread(image_path, 0)
        image = np.repeat(image[:, :, np.newaxis], 3, axis=2)
        instances_mask = cv2.imread(mask_path, 0)
        instances_mask[instances_mask > 0] = 1

        if image is None or len(image.shape) != 3:
            print(f"Failed to read {image_path}")
        if instances_mask is None or len(instances_mask.shape) != 2:
            print(f"Failed to read {mask_path}")

        return DSample(image, instances_mask, object_ids=[1], sample_id=index,
                       custom_augmentor=self._custom_augmentor)


import torch
import torch.nn as nn
import numpy as np
import itertools
import logging
from crowd_sim.envs.policy.policy import Policy
from crowd_sim.envs.utils.action import ActionRot, ActionXY
from crowd_sim.envs.utils.state import ObservableState, FullState

def mlp(input_dim, mlp_dims, last_relu=False):
    layers = []
    mlp_dims = [input_dim] + mlp_dims
    for i in range(len(mlp_dims) - 1):
        layers.append(nn.Linear(mlp_dims[i], mlp_dims[i + 1]))
        if i != len(mlp_dims) - 2 or last_relu:
            layers.append(nn.ReLU())
    net = nn.Sequential(*layers)
    return net

class ValueNetwork(nn.Module):
    def __init__(self, input_dim, mlp_dims):
        super().__init__()
        self.value_network = mlp(input_dim, mlp_dims)

    def forward(self, state_input):
        # input size: (batch_size, # of humans, state_length)
        if isinstance(state_input, tuple):
            state = state_input[0]
        else:
            state = state_input

        value = self.value_network(state.squeeze(dim=1))
        return value

class CADRL(Policy):
    def __init__(self):
        super().__init__()
        self.name = 'CADRL'
        self.trainable = True
        self.multiagent_training = None
        self.kinematics = None
        self.epsilon = None
        self.gamma = None
        self.sampling = None
        self.speed_samples = None
        self.rotation_samples = None
        self.query_env = None
        self.action_space = None
        self.rotation_constraint = None
        self.speeds = None
        self.rotations = None
        self.action_values = None
        self.with_om = None
        self.cell_num = None
        self.cell_size = None
        self.om_channel_size = None
        self.self_state_dim = 6
        self.human_state_dim = 7
        self.joint_state_dim = self.self_state_dim + self.human_state_dim

    def configure(self, config):
        self.set_common_parameters(config)
        self.model = ValueNetwork(self.joint_state_dim, config.cadrl.mlp_dims)
        self.multiagent_training = config.cadrl.multiagent_training
        logging.info('Policy: CADRL without occupancy map')

    def set_common_parameters(self, config):
        self.gamma = config.rl.gamma
        self.kinematics = config.action_space.kinematics
        self.sampling = config.action_space.sampling
        self.speed_samples = config.action_space.speed_samples
        self.rotation_samples = config.action_space.rotation_samples
        self.query_env = config.action_space.query_env
        self.rotation_constraint = config.action_space.rotation_constraint
        self.cell_num = config.om.cell_num
        self.cell_size = config.om.cell_size
        self.om_channel_size = config.om.om_channel_size

        logging.info('Query environment: {}'.format(self.query_env))

    def set_device(self, device):
        self.device = device
        self.model.to(device)

    def set_epsilon(self, epsilon):
        self.epsilon = epsilon

    def build_action_space(self, v_pref):
        """
        Action space consists of 25 uniformly sampled actions in permitted range and 25 randomly sampled actions.
        """
        holonomic = True if self.kinematics == 'holonomic' else False
        speeds = [(np.exp((i + 1) / self.speed_samples) - 1) / (np.e - 1) * v_pref for i in range(self.speed_samples)]
        if holonomic:
            rotations = np.linspace(0, 2 * np.pi, self.rotation_samples, endpoint=False)
        else:
            rotations = np.linspace(-self.rotation_constraint, self.rotation_constraint, self.rotation_samples)

        action_space = [ActionXY(0, 0) if holonomic else ActionRot(0, 0)]
        for rotation, speed in itertools.product(rotations, speeds):
            if holonomic:
                action_space.append(ActionXY(speed * np.cos(rotation), speed * np.sin(rotation)))
            else:
                action_space.append(ActionRot(speed, rotation))

        self.speeds = speeds
        self.rotations = rotations
        self.action_space = action_space

    def propagate(self, state, action):
        if isinstance(state, ObservableState):
            # propagate state of humans
            next_px = state.px + action.vx * self.time_step
            next_py = state.py + action.vy * self.time_step
            next_state = ObservableState(next_px, next_py, action.vx, action.vy, state.radius)
        elif isinstance(state, FullState):
            # propagate state of current agent
            # perform action without rotation
            if self.kinematics == 'holonomic':
                next_px = state.px + action.vx * self.time_step
                next_py = state.py + action.vy * self.time_step
                next_state = FullState(next_px, next_py, action.vx, action.vy, state.radius,
                                       state.gx, state.gy, state.v_pref, state.theta)
            else:
                next_theta = state.theta + action.r
                next_vx = action.v * np.cos(next_theta)
                next_vy = action.v * np.sin(next_theta)
                next_px = state.px + next_vx * self.time_step
                next_py = state.py + next_vy * self.time_step
                next_state = FullState(next_px, next_py, next_vx, next_vy, state.radius, state.gx, state.gy,
                                       state.v_pref, next_theta)
        else:
            raise ValueError('Type error')

        return next_state

    def predict(self, state):
        """
        Input state is the joint state of robot concatenated by the observable state of other agents

        To predict the best action, agent samples actions and propagates one step to see how good the next state is
        thus the reward function is needed

        """
        if self.phase is None or self.device is None:
            raise AttributeError('Phase, device attributes have to be set!')
        if self.phase == 'train' and self.epsilon is None:
            raise AttributeError('Epsilon attribute has to be set in training phase')

        if self.reach_destination(state):
            return ActionXY(0, 0) if self.kinematics == 'holonomic' else ActionRot(0, 0)
        if self.action_space is None:
            self.build_action_space(state.self_state.v_pref)
        if not state.human_states:
            assert self.phase != 'train'
            return self.select_greedy_action(state.self_state)

        probability = np.random.random()
        if self.phase == 'train' and probability < self.epsilon:
            max_action = self.action_space[np.random.choice(len(self.action_space))]
        else:
            self.action_values = list()
            max_min_value = float('-inf')
            max_action = None
            for action in self.action_space:
                next_self_state = self.propagate(state.self_state, action)
                if self.query_env:
                    next_human_states, reward, done, info = self.env.onestep_lookahead(action)
                else:
                    next_human_states = [self.propagate(human_state, ActionXY(human_state.vx, human_state.vy))
                                         for human_state in state.human_states]
                    reward = self.compute_reward(next_self_state, next_human_states)
                batch_next_states = torch.cat([torch.Tensor([next_self_state + next_human_state]).to(self.device)
                                              for next_human_state in next_human_states], dim=0)

                # VALUE UPDATE
                outputs = self.model(self.rotate(batch_next_states))
                min_output, min_index = torch.min(outputs, 0)
                min_value = reward + pow(self.gamma, self.time_step * state.self_state.v_pref) * min_output.data.item()
                self.action_values.append(min_value)
                if min_value > max_min_value:
                    max_min_value = min_value
                    max_action = action

        if self.phase == 'train':
            self.last_state = self.transform(state)

        return max_action

    def select_greedy_action(self, self_state):
        # find the greedy action given kinematic constraints and return the closest action in the action space
        direction = np.arctan2(self_state.gy - self_state.py, self_state.gx - self_state.px)
        distance = np.linalg.norm((self_state.gy - self_state.py, self_state.gx - self_state.px))
        if self.kinematics == 'holonomic':
            speed = min(distance / self.time_step, self_state.v_pref)
            vx = np.cos(direction) * speed
            vy = np.sin(direction) * speed

            min_diff = float('inf')
            closest_action = None
            for action in self.action_space:
                diff = np.linalg.norm(np.array(action) - np.array((vx, vy)))
                if diff < min_diff:
                    min_diff = diff
                    closest_action = action
        else:
            rotation = direction - self_state.theta
            # if goal is not in the field of view, always rotate first
            if rotation < self.rotations[0]:
                closest_action = ActionRot(self.speeds[0], self.rotations[0])
            elif rotation > self.rotations[-1]:
                closest_action = ActionRot(self.speeds[0], self.rotations[-1])
            else:
                speed = min(distance / self.time_step, self_state.v_pref)

                min_diff = float('inf')
                closest_action = None
                for action in self.action_space:
                    diff = np.linalg.norm(np.array((np.cos(action.r) * action.v, np.sin(action.r) * action.v)) -
                                          np.array((np.cos(rotation) * speed), np.sin(rotation) * action.v))
                    if diff < min_diff:
                        min_diff = diff
                        closest_action = action

        return closest_action

    def transform(self, state):
        """
        Take the state passed from agent and transform it to tensor for batch training

        :param state:
        :return: tensor of shape (len(state), )
        """
        state = torch.Tensor([state.self_state + state.human_states[0]]).to(self.device)
        state = self.rotate(state)
        return state

    def rotate(self, state):
        """
        Transform the coordinate to agent-centric.
        Input state tensor is of size (batch_size, state_length)

        """
        # 'px', 'py', 'vx', 'vy', 'radius', 'gx', 'gy', 'v_pref', 'theta', 'px1', 'py1', 'vx1', 'vy1', 'radius1'
        #  0     1      2     3      4        5     6      7         8       9     10      11     12       13
        batch = state.shape[0]
        dx = (state[:, 5] - state[:, 0]).reshape((batch, -1))
        dy = (state[:, 6] - state[:, 1]).reshape((batch, -1))
        rot = torch.atan2(state[:, 6] - state[:, 1], state[:, 5] - state[:, 0])

        dg = torch.norm(torch.cat([dx, dy], dim=1), 2, dim=1, keepdim=True)
        v_pref = state[:, 7].reshape((batch, -1))
        vx = (state[:, 2] * torch.cos(rot) + state[:, 3] * torch.sin(rot)).reshape((batch, -1))
        vy = (state[:, 3] * torch.cos(rot) - state[:, 2] * torch.sin(rot)).reshape((batch, -1))

        radius = state[:, 4].reshape((batch, -1))
        if self.kinematics == 'unicycle':
            theta = (state[:, 8] - rot).reshape((batch, -1))
        else:
            theta = torch.zeros_like(v_pref)

        vx1 = (state[:, 11] * torch.cos(rot) + state[:, 12] * torch.sin(rot)).reshape((batch, -1))
        vy1 = (state[:, 12] * torch.cos(rot) - state[:, 11] * torch.sin(rot)).reshape((batch, -1))
        px1 = (state[:, 9] - state[:, 0]) * torch.cos(rot) + (state[:, 10] - state[:, 1]) * torch.sin(rot)
        px1 = px1.reshape((batch, -1))
        py1 = (state[:, 10] - state[:, 1]) * torch.cos(rot) - (state[:, 9] - state[:, 0]) * torch.sin(rot)
        py1 = py1.reshape((batch, -1))
        radius1 = state[:, 13].reshape((batch, -1))
        radius_sum = radius + radius1
        da = torch.norm(torch.cat([(state[:, 0] - state[:, 9]).reshape((batch, -1)), (state[:, 1] - state[:, 10]).
                                  reshape((batch, -1))], dim=1), 2, dim=1, keepdim=True)
        new_state = torch.cat([dg, v_pref, theta, radius, vx, vy, px1, py1, vx1, vy1, radius1, da, radius_sum], dim=1)
        return new_state


#%matplotlib notebook
#from matplotlib import style
#style.use('fivethirtyeight')
import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

import datetime as dt

# Reflect Tables into SQLAlchemy ORM

# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

engine = create_engine("sqlite:///Resources/hawaii.sqlite")

# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)

# We can view all of the classes that automap found
Base.classes.keys()

# Save references to each table
Measurement = Base.classes.measurement
Station = Base.classes.station

# Saving this here
# Measurement.__table__.columns.keys()

# Create our session (link) from Python to the DB
session = Session(engine)

# Exploratory Climate Analysis

# Design a query to retrieve the last 12 months from 08-23-2017 of precipitation data and plot the results
# Calculate the date 1 year ago from today
today_not_today = dt.date(2017, 8, 23)
one_year_before_tnt = today_not_today - dt.timedelta(days=365)

########
# NOTE # Adding the station to the filter redueced the data points from 2021 to 343
########
# Perform a query to retrieve the data and precipitation scores
query_results = session.query(Measurement.date, Measurement.prcp).\
    filter(Measurement.date >= one_year_before_tnt).\
    filter(Measurement.date <= today_not_today).filter(Measurement.station == 'USC00513117').all()

# Save the query results as a Pandas DataFrame and set the index to the date column
year_of_rain_df = pd.DataFrame(query_results)
year_of_rain_df.set_index('date', inplace=True)

# Sort the dataframe by date
year_of_rain_df.sort_index(ascending=True, inplace=True)

# Use Pandas Plotting with Matplotlib to plot the data
year_of_rain_df.plot.bar(rot=90)

plt.xlabel("Date", fontsize = 20)
plt.ylabel("Precipitation", fontsize = 20)
plt.title('Year of Rain', fontsize = 20)

plt.rcParams['figure.figsize'] = (20,12)
plt.rc('xtick',labelsize=10)
plt.rc('ytick',labelsize=20)

# Rotate the xticks for the dates
# See the rot=90 added to plot command above

# Show plot
plt.show()

# Use Pandas to calcualte the summary statistics for the precipitation data
year_of_rain_df.describe()

# How many stations are available in this dataset?
rows = session.query(Station).count()
print(f'Total stations = {rows}')

# What are the most active stations?
# List the stations and the counts in descending order.

# Get station IDs
stations = engine.execute('SELECT station FROM station').fetchall()

station_freq = []
for station in stations:
    station_count = session.query(Measurement.station).filter(Measurement.station == station[0]).count()
    station_freq.append((station[0], station_count))

station_freq.sort(key=lambda x: x[1], reverse=True)
# So they are listed in a column
for station in station_freq:
    print(f'{station}')

# Using the station id from the previous query, calculate the lowest temperature recorded,
# highest temperature recorded, and average temperature most active station?
temps_from_station = session.query(Measurement.tobs).filter(Measurement.station == station_freq[0][0]).all()

# Sort the returned temps and get high/low values
temps_from_station.sort()
lowest_temp = temps_from_station[0]
highest_temp = temps_from_station[len(temps_from_station) - 1]

# Get average temp for the station with the most measurements
temp_total = 0
for temps in temps_from_station:
    temp_total = temp_total + temps[0]
average_temp = temp_total/(len(temps_from_station))
temp_results = [lowest_temp, highest_temp, average_temp]
print(temp_results)

# Choose the station with the highest number of temperature observations.
# Query the last 12 months of temperature observation data for this station and plot the results as a histogram
temps_from_station_12m = session.query(Measurement.tobs).filter((Measurement.date >= one_year_before_tnt) & \
                                                            (Measurement.date <= today_not_today) & \
                                                            (Measurement.station == station_freq[0][0])).all()

temps_from_station_12m.sort()
lowest_temp_12m = temps_from_station_12m[0]
highest_temp_12m = temps_from_station_12m[len(temps_from_station_12m) - 1]

temps_array = np.asarray(temps_from_station_12m, dtype = float)

plt.hist(temps_array, bins=12)

plt.xlabel("Temperature", fontsize=20)
plt.ylabel("Frequency", fontsize=20)
plt.yticks(np.arange(0, 80, step=10))
plt.title('Year of Temps', fontsize=20)
plt.show()

# Write a function called `calc_temps` that will accept start date and end date in the format '%Y-%m-%d'
# and return the minimum, average, and maximum temperatures for that range of dates
def calc_temps(start_date, end_date):
    """TMIN, TAVG, and TMAX for a list of dates.

    Args:
        start_date (string): A date string in the format %Y-%m-%d
        end_date (string): A date string in the format %Y-%m-%d

    Returns:
        TMIN, TAVE, and TMAX
    """

    return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\
        filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()
print(calc_temps('2012-02-28', '2012-03-05'))

# Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax
# for your trip using the previous year's data for those same dates.
# calc_temps(one_year_before_tnt, today_not_today)

# Plot the results from your previous query as a bar chart.
# Use "Trip Avg Temp" as your Title
# Use the average temperature for the y value
# Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr)
# calc_temp_results = calc_temps(one_year_before_tnt, today_not_today)
# ltemp = calc_temp_results[0][0]
# atemp = calc_temp_results[0][1]
# htemp = calc_temp_results[0][2]

# y_axis = [atemp, 1.0, 1.0]
# x_axis = [" ", " ", " "]
# myerr = (htemp - ltemp)
# print(myerr)
# temp_handle = plt.bar(x_axis, y_axis, width=1.0, yerr=myerr)

# plt.rcParams['figure.figsize'] = (5, 12)

## Optional Challenge Assignment

# Calculate the rainfall per weather station for your trip dates using the previous year's matching dates.
# Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation

# Create a query that will calculate the daily normals
# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)

def daily_normals(date):
    """Daily Normals.

    Args:
        date (str): A date string in the format '%m-%d'

    Returns:
        A list of tuples containing the daily normals, tmin, tavg, and tmax

    """

    sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]
    return session.query(*sel).filter(func.strftime("%m-%d", Measurement.date) == date).all()

daily_normals("01-01")

# calculate the daily normals for your trip
# push each tuple of calculations into a list called `normals`

# Set the start and end date of the trip

# Use the start and end date to create a range of dates

# Stip off the year and save a list of %m-%d strings

# Loop through the list of %m-%d strings and calculate the normals for each date

# Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index

# Plot the daily normals as an area plot with `stacked=False`


import sys
import threading
import time

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from numpy import matlib as m

from src.neuralNetwork import NeuralNetwork

class View(QDialog):

    selectedFields = []
    neuralNetwork = None
    inputLayout = None
    modelResult = None
    plotCanvas = None
    threadFinishedSignal = pyqtSignal(tuple)
    errorDialogSignal = pyqtSignal(str)
    teaching = False
    taught = False

    def __init__(self):
        super().__init__()
        self.title = 'NAI PRO2'
        self.width = 720
        self.height = 580
        self.horizontalGroupBox = QGroupBox("Grid")

        # initialize 3 main sections
        self.inputGroupBox = QGroupBox("Teach settings")
        self.inputGroupBox.setFixedWidth(self.width//2)
        self.panel = QGroupBox("Classification")
        self.plot = QGroupBox("Error plot")

        self.initUI()

        self.threadFinishedSignal.connect(self.on_teaching_finish)
        self.errorDialogSignal.connect(self.error_dialog)

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(600, 300, self.width, self.height)

        # Create main layout
        windowLayout = QGridLayout()
        windowLayout.addWidget(self.inputGroupBox, 0, 0)
        windowLayout.addWidget(self.panel, 0, 1)
        windowLayout.addWidget(self.plot, 1, 0, 1, 2)

        # Add plot to main layout
        self.plotCanvas = PlotCanvas(self)
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        layout.addWidget(self.plotCanvas)
        self.plot.setLayout(layout)

        # Initialize main layouts
        self.create_settings()
        self.create_panel()

        self.setLayout(windowLayout)
        self.show()

    def create_settings(self):
        # Create settings section and add widgets to layout
        self.inputLayout = QFormLayout()
        self.inputLayout.addRow(QLabel("Epochs amount"), QLineEdit("700"))
        self.inputLayout.addRow(QLabel("Error threshold"), QLineEdit("0.5"))
        self.inputLayout.addRow(QLabel("Learning factor"), QLineEdit("0.5"))
        self.inputLayout.addRow(QLabel("Number of hidden layers"), QLineEdit("17"))
        self.inputLayout.addRow(QLabel("Steepness factor"), QLineEdit("1"))

        statusLabel = QLabel("untaught")
        statusLabel.setStyleSheet("color: red; font-weight: bold;")
        self.inputLayout.addRow(QLabel("Model status"), statusLabel)

        teachButton = QPushButton("Teach")
        teachButton.setFixedHeight(40)
        teachButton.clicked.connect(self.teach_click)

        self.inputLayout.addRow(None, teachButton)
        self.inputGroupBox.setLayout(self.inputLayout)

    def create_panel(self):
        # Create settings section and add widgets to layout

        mainGrid = QGridLayout()

        # Generate clickable grid
        clickableGrid = QGridLayout()
        clickableGrid.setSpacing(0)

        for col in range(4):
            for row in range(6):
                id = row * 4 + col
                btn = MyQPushButton("")
                btn.setFixedWidth(25)
                btn.setFixedHeight(25)
                btn.setAccessibleName(str(id))
                btn.setStyleSheet("background-color: white;")
                clickableGrid.addWidget(btn, row, col)
                btn.clicked.connect(self.grid_button_click)
                self.selectedFields.append(0)

        mainGrid.addLayout(clickableGrid, 0, 0)
        mainGrid.setSpacing(10)

        label = QLabel("Draw a digit")
        label.setAlignment(Qt.AlignCenter)
        mainGrid.addWidget(label, 1, 0)

        label = QLabel("Model result")
        label.setAlignment(Qt.AlignCenter)
        mainGrid.addWidget(label, 1, 1)

        label = QLabel("?")
        label.setAlignment(Qt.AlignCenter)
        label.setStyleSheet("font-size:60px")
        mainGrid.addWidget(label, 0, 1)
        self.modelResult = label

        classifyButton = QPushButton("Classify")
        classifyButton.setFixedHeight(40)
        classifyButton.clicked.connect(self.classify_click)
        mainGrid.addWidget(classifyButton, 2, 0, 1, 2)

        self.panel.setLayout(mainGrid)

    def teach_click(self):
        if not self.teaching:
            threading.Thread(target=self.execute_teach).start()
        else:
            self.error_dialog('Teaching is in progress!')

    def on_teaching_finish(self, learn_data):
        self.teaching = False
        self.taught = True
        info = "Elapsed time: {:.2f}s \nAchieved error: {:.4f}\nEpochs: {:d}".format(learn_data[2], learn_data[0][len(learn_data[0]) - 1], learn_data[1])

        msgBox = QMessageBox()
        msgBox.setText('Neural network has been taught and is ready to classify!')
        msgBox.setWindowTitle("Teaching successful")
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setDetailedText(info)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()

    def execute_teach(self):
        # Teaching thread
        try:
            # Fetch data from textboxes
            maxEpoch = int(self.inputLayout.itemAt(0, QFormLayout.FieldRole).widget().text())
            maxError = float(self.inputLayout.itemAt(1, QFormLayout.FieldRole).widget().text())
            alpha = float(self.inputLayout.itemAt(2, QFormLayout.FieldRole).widget().text())
            lambd = float(self.inputLayout.itemAt(4, QFormLayout.FieldRole).widget().text())
            hiddenLayers = int(self.inputLayout.itemAt(3, QFormLayout.FieldRole).widget().text())

            # Set model status
            modelStatusText = self.inputLayout.itemAt(5, QFormLayout.FieldRole).widget()
            modelStatusText.setText("Teaching in progress...")
            modelStatusText.setStyleSheet("color: red; font-weight: bold;")
            self.teaching = True

            # Start teaching
            startTime = time.time()
            self.neuralNetwork = NeuralNetwork(hiddenLayers, alpha, maxError, maxEpoch, lambd)
            errors, epochs = self.neuralNetwork.teach()
            elapsedTime = time.time() - startTime

            # Draw plot
            self.plotCanvas.plot(errors)

            # Change model status
            modelStatusText.setText("Taught")
            modelStatusText.setStyleSheet("color: green; font-weight: bold;")

            self.threadFinishedSignal.emit((errors, epochs, elapsedTime))

        except ValueError:
            self.errorDialogSignal.emit('Please enter valid values')
        except:
            self.errorDialogSignal.emit('An error has occurred while teaching')

    def error_dialog(self, msg):
        msgBox = QMessageBox()
        msgBox.setText(msg)
        msgBox.setWindowTitle("Error")
        msgBox.setIcon(QMessageBox.Critical)
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()

    def classify_click(self):
        if not self.taught:
            if self.teaching:
                self.error_dialog('Please wait until teaching process finishes')
            else:
                self.error_dialog('Please teach neural network before starting classification')
            return

        result = self.neuralNetwork.classify_input(m.mat(self.selectedFields))
        if result == -1:
            self.modelResult.setText("?")
        else:
            self.modelResult.setText(str(result))

    def grid_button_click(self):
        sending_button = self.sender()
        sending_button.setInserted(not sending_button.isInserted())
        self.selectedFields[int(sending_button.accessibleName())] = 1 if sending_button.isInserted() else 0

        sending_button.setStyleSheet("background-color: red;") \
            if sending_button.isInserted() else sending_button.setStyleSheet("background-color: white;")

class MyQPushButton(QPushButton):

    __inserted = False

    def isInserted(self):
        return self.__inserted

    def setInserted(self, inserted):
        self.__inserted = inserted

class PlotCanvas(FigureCanvas):

    def __init__(self, parent=None):
        FigureCanvas.__init__(self, Figure())
        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        self.setParent(parent)
        self.plot([1])
        self.draw()

    def plot(self, data):
        ax = self.figure.add_subplot(111)
        ax.plot(data, 'r-')
        self.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = View()
    sys.exit(app.exec_())


from threading import Thread
from download import objects, dl_utils
import hashlib
import zlib
import time
import logging
import os
from copy import copy

class DLWorker():
    def __init__(self, data, path, api_handler, gameId, submit_downloaded_size, endpoint):
        self.data = data
        self.path = path
        self.api_handler = api_handler
        self.submit_downloaded_size = submit_downloaded_size
        self.gameId = gameId
        self.completed = False
        self.endpoint = endpoint
        self.logger = logging.getLogger("DOWNLOAD_WORKER")
        self.downloaded_size = 0

    def do_stuff(self, is_dependency=False):
        item_path = os.path.join(self.path, self.data.path)
        if self.verify_file(item_path):
            size = 0
            for chunk in self.data.chunks:
                size += chunk['compressedSize']
            self.submit_downloaded_size(size)
            self.completed = True
            return
        if os.path.exists(item_path):
            os.remove(item_path)

        for index in range(len(self.data.chunks)):
            chunk = self.data.chunks[index]
            compressed_md5 = chunk['compressedMd5']
            md5 = chunk['md5']
            self.downloaded_size = chunk['compressedSize']
            download_path = os.path.join(
                self.path, self.data.path+f'.tmp{index}')
            dl_utils.prepare_location(
                dl_utils.parent_dir(download_path), self.logger)
            if is_dependency:
                url = dl_utils.get_dependency_link(self.api_handler, dl_utils.galaxy_path(compressed_md5))
            else:
                parameters = copy(self.endpoint['parameters'])
                parameters['path'] += "/" + dl_utils.galaxy_path(compressed_md5)
                url = dl_utils.merge_url_with_params(self.endpoint['url_format'], parameters)
            self.get_file(url, download_path, compressed_md5, md5, index)
            if not is_dependency:
                self.submit_downloaded_size(self.downloaded_size)
        path = os.path.join(self.path, self.data.path)
        with open(path, 'ab') as output_file:
            for index in range(len(self.data.chunks)):
                self.decompress_file(path+f'.tmp{index}', output_file)
        self.completed = True

    def decompress_file(self, compressed, output_file):
        if os.path.exists(compressed):
            file = open(compressed, 'rb')
            dc = zlib.decompress(file.read(), 15)
            output_file.write(dc)
            file.close()
            os.remove(compressed)

    def get_file(self, url, path, compressed_sum='', decompressed_sum='', index=0):
        isExisting = os.path.exists(path)
        if isExisting and (dl_utils.calculate_sum(path, hashlib.md5) == compressed_sum):
            return
        elif isExisting:
            os.remove(path)
        with open(path, 'ab') as f:
            response = self.api_handler.session.get(
                url, stream=True, allow_redirects=True)
            total = response.headers.get('Content-Length')
            if total is None:
                f.write(response.content)
            else:
                total = int(total)
                for data in response.iter_content(chunk_size=max(int(total/1000), 1024*1024)):
                    f.write(data)
            f.close()
            isExisting = os.path.exists(path)
            if isExisting and (dl_utils.calculate_sum(path, hashlib.md5) != compressed_sum):
                self.logger.warning(
                    f'Checksums dismatch for compressed chunk of {path}')
                if isExisting:
                    os.remove(path)
                self.get_file(url, path, compressed_sum,
                              decompressed_sum, index)
            elif not isExisting:
                self.get_file(url, path, compressed_sum,
                              decompressed_sum, index)
    def verify_file(self, item_path):
        if os.path.exists(item_path):
            calculated = None
            should_be = None
            if len(self.data.chunks) > 1:
                if self.data.md5:
                    should_be = self.data.md5
                    calculated = dl_utils.calculate_sum(item_path, hashlib.md5)
                elif self.data.sha256:
                    should_be = self.data.sha256
                    calculated = dl_utils.calculate_sum(item_path, hashlib.sha256)
            else:
                # In case if there are sha256 sums in chunks
                if 'sha256' in self.data.chunks[0]:
                    calculated = dl_utils.calculate_sum(item_path, hashlib.sha256)
                    should_be = self.data.chunks[0]['sha256']
                elif 'md5' in self.data.chunks[0]:
                    calculated = dl_utils.calculate_sum(item_path, hashlib.md5)
                    should_be = self.data.chunks[0]['md5']
            return calculated == should_be
        else:
            return False

class DLWorkerV1():
    def __init__(self, data, path, download_link, api_handler, gameId, submit_downloaded_size):
        self.data = data
        self.path = path
        self.api_handler = api_handler
        self.submit_downloaded_size = submit_downloaded_size
        self.gameId = gameId
        self.completed = False
        self.logger = logging.getLogger("DOWNLOAD_WORKER_V1")
        self.download_link = download_link
        self.downloaded_size = 0

    def do_stuff(self, is_dependency=False):
        if self.data['path'].startswith('/'):
            self.data['path'] = self.data['path'][1:]
        item_path = os.path.join(self.path, self.data['path'])
        if self.verify_file(item_path):
            self.completed = True
            if not is_dependency:
                self.submit_downloaded_size(int(self.data['size']))
            return
        else:
            if os.path.exists(item_path):
                os.remove(item_path)
        dl_utils.prepare_location(
                dl_utils.parent_dir(item_path), self.logger)
        self.get_file(item_path)
        if not is_dependency:
            self.submit_downloaded_size(int(self.data['size']))

    def get_file(self, item_path):
        headers = {
            "Range": dl_utils.get_range_header(self.data['offset'], self.data['size'])
        }
        with open(item_path, 'ab') as f:
            response = self.api_handler.session.get(self.download_link, headers=headers, stream=True, allow_redirects=True)
            total = response.headers.get('Content-Length')
            if total is None:
                f.write(response.content)
            else:
                total = int(total)
                for data in response.iter_content(chunk_size=max(int(total/1000), 1024*1024)):
                    f.write(data)
            f.close()
            if os.path.exists(item_path):
                if not self.verify_file(item_path):
                    self.logger.warning(f'Checksums dismatch for compressed chunk of {item_path}')
                    os.remove(item_path)
                    self.get_file(item_path)

    def verify_file(self, item_path):
        if os.path.exists(item_path):
            calculated = dl_utils.calculate_sum(item_path, hashlib.md5)
            should_be = self.data['hash']
            return calculated == should_be
        return False


class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        res = 0

        def traverse(n, p):
            nonlocal res
            if not n:
                return
            if not n.left and not n.right:
                if n == p.left:
                    res += n.val

            traverse(n.left, n)
            traverse(n.right, n)
        traverse(root, TreeNode(right=root))
        return res

binary-tree/traversal-preorder-inorder-postorder/404. Sum of Left Leaves.py


# 학습 데이터의 일부분을 빼서 Validation set 을 만드는 스크립트이다.

import os
from os import listdir
from os.path import join
from utils.utils import load_BGR, make_dirs
from random import *
import shutil

train_dirs =      '/home/lab/works/datasets/ssd2/ntire/train/splited_none_overlaped'

validation_dirs = '/home/lab/works/datasets/ssd2/ntire/validation/from_ntire_trainset'

image_count = 140

# 폴더 안의 이미지 수 확인을 위해 임의의 폴더의 이미지 개수 확인.
train_folder_dirs = [join(train_dirs, x) for x in sorted(listdir(train_dirs))]
temp = [join(train_folder_dirs[0], x) for x in sorted(listdir(train_folder_dirs[0]))]
total_img_count = len(temp)
print(total_img_count)

# 0 부터 이미지의 최대 개수 사이의 숫자 중 임의의 숫자 140장 뽑음.
picked_img_from_trainset = set()
while len(picked_img_from_trainset) < image_count:
    picked_img_from_trainset.add(randint(0, total_img_count-1))

for train_folder_dir in train_folder_dirs:
    print('-----------------------------------')
    folder_basename = os.path.basename(train_folder_dir)
    img_dirs = [join(train_folder_dir, x) for x in sorted(listdir(train_folder_dir))]

    img_folder_dir_new = make_dirs(validation_dirs + '/' + folder_basename)

    for i in picked_img_from_trainset:
        fullname = img_dirs[i]
        basename = os.path.basename(img_dirs[i])
        changedname = img_folder_dir_new + '/' + basename
        print(fullname)
        print(changedname)
        shutil.move(fullname, changedname)

#
#
# # 학습 데이터셋의 주소
# train_gt_dir =    '/home/lab/works/datasets/ssd2/ntire/train/splited_none_overlaped/GroundTruth'
# train_noisy_dir = '/home/lab/works/datasets/ssd2/ntire/train/splited_none_overlaped/Noisy'
#
# # 새로 만들 Validation 이미지들의 저장될 주소.
# validation_gt_dir = make_dirs('/home/lab/works/datasets/ssd2/NTIRE_challenge_DB/sRGB/validation/GroundTruth')
# validation_noisy_dir = make_dirs('/home/lab/works/datasets/ssd2/NTIRE_challenge_DB/sRGB/validation/Noisy')
#
# train_gt_img_dirs = [join(train_gt_dir, x) for x in sorted(listdir(train_gt_dir))]
# train_noisy_img_dirs = [join(train_noisy_dir, x) for x in sorted(listdir(train_noisy_dir))]
#
# # 생성할 validation 이미지들의 개수
#
# picked_img_from_trainset = set()
#
# while len(picked_img_from_trainset) < 50:
#     picked_img_from_trainset.add(randint(0, len(train_gt_img_dirs)-1))
#
# print(picked_img_from_trainset)
#
# for i in picked_img_from_trainset:
#     # gt 옮겨주기.
#     fullname = train_gt_img_dirs[i]
#     basename = os.path.basename(train_gt_img_dirs[i])
#     changedname = validation_gt_dir + '/' + basename
#     shutil.move(fullname, changedname)
#
#     # noisy 옮겨주기
#     fullname = train_noisy_img_dirs[i]
#     basename = os.path.basename(train_noisy_img_dirs[i])
#     changedname = validation_noisy_dir + '/' + basename
#     shutil.move(fullname, changedname)
#


from turtle import Turtle

ALINGMENT = "center"
FONT: tuple[str, int, str] = ('Arial', 50, 'normal')

class ScoreBoard(Turtle):
    """
    This class represents the scoreboard in the game.

    Attributes:
        l_score (int): Left player's score.
        r_score (int): Right player's score.

    Methods:
        update_scoreboard(): Update the scoreboard with the current scores.
        l_point(): Increment the left player's score by 1 and update the scoreboard.
        r_point(): Increment the right player's score by 1 and update the scoreboard.
    """

    def __init__(self):
        """
        Initializes a new instance of the ScoreBoard class.
        """
        super().__init__()
        self.color("white")
        self.penup()
        self.hideturtle()
        self.l_score = 0
        self.r_score = 0
        self.update_scoreboard()

    def update_scoreboard(self):
        """
        Update the scoreboard with the current scores.
        """
        self.clear()
        self.goto(x=-100, y=200)
        self.write(align=ALINGMENT, arg=self.l_score, font=FONT)
        self.goto(x=100, y=200)
        self.write(align=ALINGMENT, arg=self.r_score, font=FONT)

    def l_point(self):
        """
        Increment the left player's score by 1 and update the scoreboard.
        """
        self.l_score += 1
        self.update_scoreboard()

    def r_point(self):
        """
        Increment the right player's score by 1 and update the scoreboard.
        """
        self.r_score += 1
        self.update_scoreboard()


from collections import defaultdict
from nltk.tokenize import word_tokenize
from random import sample

ENG_ALPHA = 'abcdefghijklmnopqrstuvwxyzé'

def get_lines(filename):
    '''returns a list of items from each line in the lexicon or the corpus.'''
    items = []
    with open(filename, encoding='unicode-escape') as f: #I could not find an encoding to decode 'É'
        for line in f:
            line = line.strip()
            if '\x83' in line: #to decode 'É'
                line = line.replace('\x83', 'é')
            items.append(line)
    return items

class AutoCorrect:

    def __init__(self, word_list=get_lines('usenglish.txt'), alpha=ENG_ALPHA):
        self.word_list = word_list
        self.alpha = alpha

    def insertion(self, word):
        #return a list of suggestions to alternative spellings for words with edit distance 1
        alternatives = []
        for i in range(len(word)+1):
            for letter in self.alpha:
                possible_word = word[:i] + letter + word[i:]
                if possible_word in self.word_list:
                    alternatives.append(possible_word)
        return alternatives

    def deletion(self, word):
        alternatives = []
        for i in range(len(word)):
            possible_word = word[:i] + word[i+1:]
            if possible_word in self.word_list:
                alternatives.append(possible_word)
        return alternatives

    def substitution(self, word):
        alternatives = []
        for i in range(len(word)):
            for letter in self.alpha:
                possible_word = word[:i] + letter + word[i+1:]
                if possible_word in self.word_list:
                    alternatives.append(possible_word)
        return alternatives

    def swapping(self, word):
        alternatives = []
        letters = list(word)
        for i in range(len(letters)-1):
            letters[i], letters[i+1] = letters[i+1], letters[i]
            possible_word = ''.join(letters)
            if possible_word in self.word_list:
                alternatives.append(possible_word)
        return alternatives

    def call_operation(self, word):
        #call the operation methods, put the elements of the lists in a set, and return that set.
        all_alternatives = set()
        all_alternatives.update(self.insertion(word))
        print(all_alternatives)
        all_alternatives.update(self.deletion(word))
        print(all_alternatives)
        all_alternatives.update(self.substitution(word))
        print(all_alternatives)
        all_alternatives.update(self.swapping(word))
        print(all_alternatives)
        return all_alternatives

def tokenize(sents):
    return [word_tokenize(sent) for sent in sents]

def populate_dict(tokenized_sents):
    bigram_frequency = defaultdict(int)
    for sent in tokenized_sents:
        for i in range(len(sent)-1): #last punctuation
            bigram_frequency[(sent[i].lower(), sent[i+1].lower())] += 1
    return bigram_frequency

def fetch_next(bigrams, input_word):
    suggestions = {}
    for (word, next_word), count in bigrams.items():
        if word == input_word:
            if len(suggestions) < 3:
                suggestions[count] = next_word
            elif count > min(suggestions): #only with a non-empty dictionry
                suggestions.pop(min(suggestions)) #remove the less frequent option
                suggestions[count] = next_word
    return list(suggestions.values())

def main():
    a = AutoCorrect()
    #tie everything together, run until interrupted
    tokenized_sents = tokenize(get_lines('UNv1.0.testset.en'))
    bigrams = populate_dict(tokenized_sents)
    while True:
        word = input('Type a word: ')
        if word not in get_lines('usenglish.txt'):
            suggestions = a.call_operation(word)
            if len(suggestions) > 3:
                print(sample(suggestions, 3))
            else:
                print(suggestions)
        else:
            print(fetch_next(bigrams, word))

if __name__ == "__main__":
    main()


import turtle

def square(coast):
    for i in range(4):
        t.forward(coast)
        t.left(90)

def squares(starting_size, nb):
    for i in range(1, nb):
        square(i * starting_size)

t = turtle.Turtle()

squares(40, 10)

turtle.done()


from django.contrib import admin
from django.utils.translation import gettext, gettext_lazy as _
from django.contrib.auth.admin import UserAdmin

from .models import User, PersistentId
from .admin_inlines import PersistentIdInline

@admin.register(User)
class CustomUserAdmin(UserAdmin):
    readonly_fields = ('date_joined', 'last_login',)
    list_display = ('username', 'email', 'is_active',
                    'is_staff', 'is_superuser', )
    list_editable = ('is_active', 'is_staff', 'is_superuser',)
    inlines = [PersistentIdInline,]
    fieldsets = (
        (None, {'fields': (('username', 'is_active', 'is_staff', 'is_superuser', ),
                           ('password'),
                           ('origin'),
                           )
                }),
        (_('Anagrafica'), {'fields': (('first_name', 'last_name'),
                                          'email',
                                         ('taxpayer_id',)
                                        )
                          }),

        (_('Permissions'), {'fields': ('groups', 'user_permissions'),
                            'classes':('collapse',)
                            }),

        (_('Date accessi sistema'), {'fields': (('date_joined',
                                                 'last_login', ))
                                    }),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2'),
        }),
    )

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

@admin.register(PersistentId)
class PersistentIdAdmin(admin.ModelAdmin):
    list_display = ('user', 'persistent_id', 'recipient_id', 'created')
    list_filter = ('created',)


import tkinter.ttk as ttk
from turtle import title
from datetime import datetime
from datetime import date
import time
import threading
from threading import Event
import threading
from plyer import notification

class Reminder:
    def __init__(self, parent, uniqueID, expired, hours, minutes, ampm, date, title, description, count):
        self.parent = parent
        self.hours = hours
        self.min = minutes
        if(int(hours) > 12):
            self.ampm = "PM"
        else:
            self.ampm = ampm
        self.date = date
        self.title = title
        self.desc = description
        self.row = count
        self.alarm_time = ""
        self.expired = expired
        self.stop_event = Event()
        self.displayhours = self.hours
        self.uniqueID = uniqueID

        self.check_expire()
        self.daemon = threading.Thread(target=self.alarm, args=(self.stop_event,), daemon=True, name="Alarm")

        if(self.expired == False):
            self.daemon.start()
        else:
            pass

    def check_expire(self):
        if(0 <= int(self.hours) < 10 and self.ampm == "AM" and self.hours[0] != "0"):
            self.displayhours = self.hours
            self.hours = "0" + self.hours
        elif(1 <= int(self.hours) < 12 and self.ampm == "PM"):
            self.displayhours = self.hours
            self.hours = int(self.hours) + 12
        elif(int(self.hours) == 12 and self.ampm == "AM"):
            self.displayhours = self.hours
            self.hours = "00"

        current_date = date.today()
        current_date.strftime("%m/%d/%Y")
        reminder_date = datetime.strptime(self.date, "%m/%d/%Y").date()
        current_time = datetime.now().strftime("%H:%M")
        reminder_time = str(self.hours) + ":" + self.min
        if(current_date > reminder_date):
            self.expired = True
        elif((current_date == reminder_date) and (current_time >= reminder_time)):
            self.expired = True
        else:
            self.expired = False

    def alarm(self, event):
        self.alarm_time = str(self.hours) + ":" + self.min + ":00"

        if(self.expired == False):
            while not event.is_set():
                time.sleep(1)
                current_time = datetime.now()
                print(current_time)
                now = current_time.strftime("%H:%M:%S") # Set to 24 hour to accept both 12 hour as well
                date = current_time.strftime("%m/%d/%Y")
                if(now == self.alarm_time and date == self.date):
                    print(self.alarm_time)
                    notification.notify(title=self.title, message=self.desc, timeout=1)
                    self.expired = True
                    self.parent.remind_button_list[self.row].configure(bg="tomato")
                    break
        else:
            self.stop_event.clear()

    def update(self):
        if(self.daemon.is_alive()):
            self.stop_event.set()
            self.daemon.join()
            self.stop_event.clear()
            self.daemon = threading.Thread(target=self.alarm, args=(self.stop_event,), daemon=True, name="Alarm")
            self.daemon.start()
        else:
            self.daemon = threading.Thread(target=self.alarm, args=(self.stop_event,), daemon=True, name="Alarm")
            self.daemon.start()

    def open(self, calendar, hentry, mentry, drop, tentry, dentry):
        hentry.configure(bg="white")
        mentry.configure(bg="white")
        tentry.configure(bg="white")
        dentry.configure(bg="white")

        hentry.delete(0, "end")
        mentry.delete(0, "end")
        tentry.delete(0, "end")
        dentry.delete(1.0, "end")

        calendar.selection_set(self.date)
        if(self.hours == "00" and self.ampm == "AM"):
            hentry.insert(0, "12")
        elif(self.ampm == "PM" and int(self.hours) > 12):     # Might need
            hentry.insert(0, (str(int(self.hours) - 12)))
        else:
            hentry.insert(0, self.hours)
        mentry.insert(0, self.min)
        drop.set(self.ampm)
        tentry.insert(0, self.title)
        dentry.insert(1.0, self.desc)

    def saveToFile(self):
        remind_file_name = "C:\See Anchor\\Reminders\\" + self.title + "_" + str(self.uniqueID) + ".txt"
        f = open(remind_file_name, 'w')
        f.write(str(self.uniqueID) + "\n")
        f.write(str(self.expired) + "\n")
        f.write(str(self.hours) + "\n")
        f.write(str(self.min) + "\n")
        f.write(self.ampm + "\n")
        f.write(self.date + "\n")
        f.write(self.title + "\n")
        f.write(self.desc + "\n")
        f.close()


from datetime import datetime, date, timedelta
from django import forms
from django.contrib.auth import get_user_model
from django_registration.forms import RegistrationFormUniqueEmail

from reservations.models import Reservation
from rooms.models import Room

CustomUser = get_user_model()

class MyCustomUserForm(RegistrationFormUniqueEmail):

    first_name = forms.CharField(
        max_length=64,
        required=True,
        help_text="Requerido, por favor poné tu nombre",
        label="Nombre",
    )
    last_name = forms.CharField(
        max_length=64,
        required=True,
        help_text="Requerido, por favor poné tu apellido",
        label="Apellido",
    )

    class Meta(RegistrationFormUniqueEmail.Meta):
        model = CustomUser
        fields = ("email", "first_name", "last_name", "password1", "password2")
        help_texts = {
            "email": "Requerida. Luego será usada para entrar al sitio.",
            "password1": "No te preocupes: si te la olvidas podrás recuperarla.",
            "password2": "La misma que pusiste antes (para asegurarnos que la escribiste bien)",
        }
        labels = {
            "first_name": "Nombre",
            "last_name": "Apellido",
            "email": "Dirección de email",
            "password1": "Contraseña",
            "password2": "Repetir contraseña",
        }

class ReservationValidationFormMixin(forms.ModelForm):
    """Mixin to validate a reservation: dates and room"""

    def clean(self):
        cleaned_data = super().clean()
        if len(self.errors):
            return
        # cc_myself = cleaned_data.get("cc_myself")
        # subject = cleaned_data.get("subject")
        rooms = cleaned_data.get("rooms")
        from_date = cleaned_data.get("from_date")
        to_date = cleaned_data.get("to_date")

        if from_date >= to_date:
            self.add_error(
                "from_date", "La fecha Desde tiene que ser anterior a la de Hasta"
            )

        if self.instance:
            reservations = Reservation.objects.exclude(id=self.instance.id)
        else:
            reservations = Reservation.objects.all()

        potential_conflicts = reservations.filter(
            to_date__gt=from_date, from_date__lt=to_date
        )

        reserved_rooms_ids = set(
            potential_conflicts.values_list("rooms__id", flat=True)
        )
        conflicting_rooms = reserved_rooms_ids.intersection(
            set(rooms.values_list("id", flat=True))
        )

        if conflicting_rooms:
            rooms = ", ".join(
                str(r) for r in Room.objects.filter(id__in=reserved_rooms_ids)
            )
            msg = "En ese período hay conflictos con reservas de: {}".format(rooms)
            self.add_error("rooms", msg)

class MyReservationAdminForm(ReservationValidationFormMixin):
    pass

class ReservationCreationForm(ReservationValidationFormMixin):
    from_date = forms.DateField(
        label="Desde",
        widget=forms.DateInput(attrs={"type": "date"}),
        help_text="Fecha de la primer noche",
        required=True,
    )
    to_date = forms.DateField(
        label="Hasta",
        widget=forms.DateInput(attrs={"type": "date"}),
        help_text="Fecha de salida (esa noche no se usa habitación)",
        required=True,
    )

    class Meta:
        model = Reservation
        # fields = ["from_date", "to_date", "rooms", "notes"]
        exclude = ("user",)
        help_texts = {
            "from_date": "Fecha de la primer noche",
            "to_date": "Fecha de salida (esa noche no se usa habitación)",
            "rooms": "Seleccione múltiples habitaciones dejando apretado Ctrl",
            "notes": "Opcional. Cualquier mensaje que consideres oportuno.",
        }

TARGET_YEAR = datetime.now().year + 1
TURNS_START = date(TARGET_YEAR, 1, 1)

class TurnsPreparationForm(forms.Form):
    """Form for the definition of holiday turns."""

    year = forms.IntegerField(
        label="Año para el que calcular los turnos",
        required=True,
        min_value=2000,
        max_value=2100,
        initial=TARGET_YEAR,
    )
    date_start = forms.DateField(
        label="Día concreto en que empieza el primer turno",
        required=True,
        widget=forms.DateInput(attrs={"type": "date"}),
        initial=TURNS_START,
    )
    turn_length = forms.IntegerField(
        label="Largo (en días) deseado para cada turno",
        required=True,
        min_value=1,
        max_value=365,
        initial=8,
    )

class TurnsCreationForm(forms.Form):
    """Form for the creation of holiday turns"""

    year = forms.IntegerField(
        label="Año para el que calcular los turnos",
        required=True,
        widget=forms.widgets.Input(attrs={"readonly": True}),
    )
    date_start = forms.DateField(
        label="Día concreto en que empieza el primer turno",
        required=True,
        widget=forms.widgets.Input(attrs={"readonly": True}),
    )
    turn_length = forms.IntegerField(
        label="Largo (en días) deseado para cada turno",
        required=True,
        widget=forms.widgets.Input(attrs={"readonly": True}),
    )


import tkinter
from tkinter import *
from tkinter import messagebox
from tkinter import font

tk = tkinter
main = Tk()  # Name of main window
main.title("House event calculator")  # Title
main.geometry("450x270")  # Size of the window in pixels
main.configure(bg="#D2D4DA")  # Background colour
main.resizable(False, False) #Makes window unable to resize in x and y direction just to keep the user from interfering with the structure in the window

All_events = [] #list in which I will hold my HouseEvent object
names_list = ["Lampada Games", "House Trivia"] #list for holding Event names to be used in drop down
ph_list = [75, 66] #List for holding points of teams for use in Leader board
ku_list = [60, 68] #                   ''
kw_list = [72, 74] #                   ''
ru_list = [68, 73] #                   ''

#----------------------Frames----------------------#
#Frames are like containers from html they help keep things organized
entry_frame = LabelFrame(main, background="#D2D4DA")
entry_frame.grid(row=0, column=0, padx=10, pady=10, sticky=W)

det_frame = LabelFrame(main, background="#D2D4DA")
det_frame.grid(row=1, column=0, columnspan=2, padx=10, pady=10, sticky=N)

lead_frame = LabelFrame(main, background="#D2D4DA")
lead_frame.grid(row=0, column=1, padx=10, pady=10, sticky=E)

#----------------------Widgets----------------------#
    #-entry_frame labels-#
tk.Label(entry_frame, text="Name of Event", font=("Fixedsys", 12), background="#D2D4DA").grid(column=0, row=0, sticky=W)
tk.Label(entry_frame, text="Is it a sport", font=("Fixedsys", 10), background="#D2D4DA").grid(column=0, row=1, sticky=W)
tk.Label(entry_frame, text="Pohutukawa", font=("Fixedsys", 12), background="#FA6C38").grid(column=0, row=2, sticky=W)
tk.Label(entry_frame, text="Kauri", font=("Fixedsys", 12), background="#62A8F9").grid(column=0, row=3, sticky=W)
tk.Label(entry_frame, text="Kowhai", font=("Fixedsys", 12), background="#FFBC1F").grid(column=0, row=4, sticky=W)
tk.Label(entry_frame, text="Rimu", font=("Fixedsys", 12), background="#01F472").grid(column=0, row=5, sticky=W)
    #-det_frame lables-#
tk.Label(det_frame, text="Event Name", font=("Fixedsys", 12), background="#D2D4DA").grid(column=0, row=0, sticky=W)

entry_1 = tk.Entry(entry_frame, font="Fixedsys", background="#E9E9ED")

is_sport = tk.StringVar()
is_sport.set("Yes")
Radiobutton(entry_frame, text="Yes", variable=is_sport, value="Yes", font=("Fixedsys", 12), background="#D2D4DA").grid(column=1, row=1,)
Radiobutton(entry_frame, text="No", variable=is_sport, value="No", font=("Fixedsys", 12), background="#D2D4DA").grid(column=2, row=1,)

spin_1 = Spinbox(entry_frame, from_=0, to=100, increment=1, wrap=YES, state="readonly", font=("Fixedsys"), width=15, readonlybackground="#E9E9ED", foreground="#FA6C38")
spin_2 = Spinbox(entry_frame, from_=0, to=100, increment=1, wrap=YES, state="readonly", font=("Fixedsys"), width=15, readonlybackground="#E9E9ED", foreground="#0656B1")
spin_3 = Spinbox(entry_frame, from_=0, to=100, increment=1, wrap=YES, state="readonly", font=("Fixedsys"), width=15, readonlybackground="#E9E9ED", foreground="#E09D00")
spin_4 = Spinbox(entry_frame , from_=0, to=100, increment=1, wrap=YES, state="readonly", font=("Fixedsys"), width=15, readonlybackground="#E9E9ED", foreground="#1C9C76")

# using geometry manager to arange input widgets because we cant use .grid() on them directly because they are needed as variables
entry_1.grid(column=1, row=0, columnspan=2, padx=2)
spin_1.grid(column=1, row=2,columnspan=2)
spin_2.grid(column=1, row=3,columnspan=2)
spin_3.grid(column=1, row=4,columnspan=2)
spin_4.grid(column=1, row=5,columnspan=2)

#--Leader board--##
Label(lead_frame, text="Leaderboard", font=("Fixedsys", 15), background="#D2D4DA").grid(column=0, row=0, columnspan=2, pady=10)
Label(lead_frame, text="Pohutukawa", font=("Fixedsys", 11), background="#FA6C38").grid(column=0, row=1, sticky=W, pady=5)
Label(lead_frame, text="Kauri", font=("Fixedsys", 11), background="#62A8F9").grid(column=0, row=2, sticky=W, pady=5)
Label(lead_frame, text="Kowhai", font=("Fixedsys", 11), background="#FFBC1F").grid(column=0, row=3, sticky=W, pady=5)
Label(lead_frame, text="Rimu", font=("Fixedsys", 11), background="#01F472").grid(column=0, row=4, sticky=W, pady=5)
Label(lead_frame, text= sum(ph_list), font=("Fixedsys", 12), background="#FA6C38").grid(column=1, row=1, sticky=W, pady=5, padx= 3)
Label(lead_frame, text= sum(ku_list), font=("Fixedsys", 12), background="#62A8F9").grid(column=1, row=2, sticky=W, pady=5, padx= 3)
Label(lead_frame, text= sum(kw_list), font=("Fixedsys", 12), background="#FFBC1F").grid(column=1, row=3, sticky=W, pady=5, padx= 3)
Label(lead_frame, text= sum(ru_list), font=("Fixedsys", 12), background="#01F472").grid(column=1, row=4, sticky=W, pady=5, padx= 3)

#-----------defining the class using which I will create my house event objects-----------#
class HouseEvent:
    def __init__(self, name, eventtype, ph_points, ku_points, kw_points, ru_points, who_won):
        self.name = name
        self.eventtype = eventtype
        self.ph_points = ph_points
        self.ku_points = ku_points
        self.kw_points = kw_points
        self.ru_points = ru_points
        self.who_won = who_won

    def get_name(self):
        # the_thing = "Name : " + self.name + "/nIs it a sport : " + self.eventtype
        return(["Name : " + self.name, "Is a sport : " + self.eventtype, "Pohutukawa Points : " + str(self.ph_points), "Kauri Points : " + str(self.ku_points), "Kowhai Points : " + str(self.kw_points), "Rimu Points : " + str(self.ru_points), "Winner : " + self.who_won])

    def get_event_type(self):
        return(self.eventtype)

    def get_ph_pt(self):
        return(self.ph_points)

    def get_ku_pt(self):
        return(self.ku_points)

    def get_kw_pt(self):
        return(self.kw_points)

    def get_ru_pt(self):
        return(self.ru_points)

    def get_who_won(self):
        return(self.who_won)

#--Pre made house events--#
All_events.append(HouseEvent("Lampada Games", "Yes", 75, 60, 72, 68, "Pohutukawa"))
All_events.append(HouseEvent("House Trivia", "No", 66, 68, 74, 73, "Kowhai"))
#----------------Drop down to select which events details need to be accessed----------------#
value_inside = tkinter.StringVar()
# Set the default value of the variable
value_inside.set("Select an event")
# Create the optionmenu widget and passing
# the options_list and value_inside to it.
question_menu_1 = tkinter.OptionMenu(det_frame, value_inside, *names_list)
question_menu_1.config(font="Fixedsys", background="#D2D2DA", activebackground="#E9E9ED")
question_menu_1.grid(row=0, column=1)

#Function that takes the users input and uses the class constructor the make an object and then append it to the list we created above
def make_obj():
    global value_inside
    global question_menu_1
    name = entry_1.get()
    event_type = is_sport.get()
    points_ph = int(spin_1.get())
    points_ku = int(spin_2.get())
    points_kw = int(spin_3.get())
    points_ru = int(spin_4.get())
    #validating name input
    if name.strip() != "" and name not in names_list and len(name) <= 20:
        #Sorting Scores
        points_list = [('Pohutukawa', points_ph), ('Kauri', points_ku),("Kowhai", points_kw), ('Rimu', points_ru)]
        points_list.sort(reverse=YES, key = lambda x: x[1])
        #Validating Points input
        if points_ph == 0 and points_ku == 0 and points_kw == 0 and points_ru == 0:
            messagebox.showerror("Points Error", "Please enter points")
        else:
            names_list.append(str(name))
            first_check = None
            second_check = None
            third_check = None

            if points_list[0][1] == points_list[1][1]:
                first_check = True

                if points_list[1][1] == points_list[2][1]:
                    second_check = True

                    if points_list[2][1] == points_list[3][1]:
                        third_check = True

                    else:
                        third_check = False

                else:
                    second_check = False

            else:
                first_check = False
                second_check = False
                third_check = False
            #Setting the winner variable by first finding out if there are multiple winners and then setting the winner as the singular or multiple winners found
            if points_list[0][1] != 0:

                if first_check == True:
                    if second_check == True:
                        if third_check == True:
                            winners = "All teams tied"
                        else:
                            winners = points_list[0][0] +", "+ points_list[1][0] + ", " + points_list[2][0]
                    else:
                        winners = points_list[0][0]+", "+ points_list[1][0]
                else:
                    winners = points_list[0][0]
            else:
                winners = 0

            #Creating the House event object and appending it to a list for it to be stored
            All_events.append(HouseEvent(name, event_type, points_ph, points_ku, points_kw, points_ru, winners))
            #Adding scores to house points list for leader board
            ph_list.append(points_ph)
            ku_list.append(points_ku)
            kw_list.append(points_kw)
            ru_list.append(points_ru)
            # Variable to keep track of the option

            # Create the optionmenu widget and passing
            # the options_list and value_inside to it
            Label(lead_frame, text= sum(ph_list), font=("Fixedsys", 12), background="#FA6C38").grid(column=1, row=1, sticky=W)
            Label(lead_frame, text= sum(ku_list), font=("Fixedsys", 12), background="#62A8F9").grid(column=1, row=2, sticky=W)
            Label(lead_frame, text= sum(kw_list), font=("Fixedsys", 12), background="#FFBC1F").grid(column=1, row=3, sticky=W)
            Label(lead_frame, text= sum(ru_list), font=("Fixedsys", 12), background="#01F472").grid(column=1, row=4, sticky=W)
            #Destroying previous option menu so that when we add a new one with the updated list there is no overlap
            question_menu_1.destroy()
            value_inside = tkinter.StringVar()
            value_inside.set("Select an event")
            #This option menu has to be put in because the one that is there previously will now be missing an event
            question_menu_1 = tkinter.OptionMenu(det_frame, value_inside, *names_list)
            question_menu_1.config(font="Fixedsys", background="#D2D2DA", activebackground="#E9E9ED")
            question_menu_1.grid(row=0, column=1)
    #Erorr messages if the data is not valid
    elif name in names_list:
        messagebox.showerror("Name Error", "An event with this name already exists please chose another name")
    elif name.strip() == "":
       messagebox.showerror("Name Error", "You must enter a name for the event")
    elif len(name) > 20:
       messagebox.showerror("Name Error", "Your name is too long it must be 20 characters only")

#Function for showing event details. It takes the string var from the option menu then uses a class function get_info() to pull information from the desired object and show it in an infobox
def info_func():
    entry = value_inside.get()
    for info in All_events:
        if entry == info.name:
            global question_menu_1
            question_menu_1.destroy()
            question_menu_1 = tkinter.OptionMenu(det_frame, value_inside, *names_list)
            question_menu_1.grid(row=0, column=1)
            question_menu_1.config(font="Fixedsys", background="#D2D2DA", activebackground="#E9E9ED")
            tkinter.messagebox.showinfo("Event Details", "\n".join(info.get_name()))

#button for saving event it calls the make_obj function and creates each event as an object
tk.Button(entry_frame, text="Save Event", command=make_obj, font=("Fixedsys"), background="#C7C7D1", activebackground="#E9E9ED").grid(row=7, column=0,columnspan=3, pady=5)
#Button for showing details it calls the info_func which shows a infobox with information. Refer to the comments for the info_func() for more details on how that works
tk.Button(det_frame, text="Show Details", command=info_func, font=("Fixedsys"), background="#C7C7D1", activebackground="#E9E9ED").grid(column=0, row=1, columnspan=2)

main.mainloop()


def dfs(node,parent,ptaken):
	if dp[node][ptaken]!=-1:
		return dp[node][ptaken]
	taking,nottaking=1,0
	total=0
	tways
	for neig in graph[node]:
		if neig!=parent:
			taking+=dfs(neig,node,1)
			nottaking+=dfs(neig,node,0)

	if ptaken:
		dp[node][ptaken]=min(taking,nottaking)
	else:
		dp[node][ptaken]=taking
	return dp[node][ptaken]

if __name__ == '__main__':
	n=int(input())
	graph=[[]for ii in range(n)]
	for i in range(n-1):
		a,b=map(int,input().split())
		a=a-1
		b=b-1
		graph[a].append(b)
		graph[b].append(a)

	dp=[[-1 for i in range(2)]for j in range(n)]
	print(dfs(0,-1,1))


from data.image_folder_dataset import ImageFolderDataset
from processing.XDoG import PARAM_DEFAULT
import pytorch_lightning as pl
from torch.utils.data import DataLoader
import torch

class ImageDataModule(pl.LightningDataModule):
  def __init__(self,
              data_dir = "portraits/",
              batch_size = 32,
              split_ratios = [.8, .1, .1],
              image_size=128,
              training_sizes=None,
              hatch_pattern_path="./processing/textures/",
              sketch_params=PARAM_DEFAULT,
              *args,
              **kwargs):

    super().__init__()
    self.data_dir = data_dir
    self.batch_size = batch_size
    self.split_ratios = split_ratios
    self.image_size = image_size
    self.training_sizes = training_sizes
    self.hatch_pattern_path = hatch_pattern_path

  def prepare_data(self):
    self.train_set, self.val_set, self.test_set = \
      ImageFolderDataset(
        path=self.data_dir,
        mode='train',
        ratios=self.split_ratios,
        image_size=self.image_size,
        training_sizes=self.training_sizes,
        hatch_pattern_path=self.hatch_pattern_path), \
      ImageFolderDataset(
        path=self.data_dir,
        mode='val',
        ratios=self.split_ratios,
        image_size=self.image_size,
        hatch_pattern_path=self.hatch_pattern_path), \
      ImageFolderDataset(
        path=self.data_dir,
        mode='test',
        ratios=self.split_ratios,
        image_size=self.image_size,
        hatch_pattern_path=self.hatch_pattern_path)

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

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

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

  def test_dataloader(self):
    return DataLoader(
      self.test_set,
      batch_size=self.batch_size,
      shuffle=False,
      num_workers=2,)

  def teardown(self, stage = None):
    pass


from networkx.generators.random_graphs import fast_gnp_random_graph
import random
import networkx as nx
import matplotlib.pyplot as plt
import pylab

class Graph:
    def __init__(self, vertices):
        self.V = vertices
        self.graph = []

    def add_edge(self, start, end, weight):
        self.graph.append([start, end, weight])

    def find(self, parent, i):
        if parent[i] == i:
            return i
        return self.find(parent, parent[i])

    def apply_union(self, parent, rank, x, y):
        xroot = self.find(parent, x)
        yroot = self.find(parent, y)
        if rank[xroot] < rank[yroot]:
            parent[xroot] = yroot
        elif rank[xroot] > rank[yroot]:
            parent[yroot] = xroot
        else:
            parent[yroot] = xroot
            rank[xroot] += 1

    def kruskal_algo(self):
        result = []
        i, e = 0, 0
        self.graph = sorted(self.graph, key=lambda item: item[2])
        parent = []
        rank = []
        for node in range(self.V):
            parent.append(node)
            rank.append(0)
        while e < self.V - 1:
            start, end, weight = self.graph[i]
            i = i + 1
            x = self.find(parent, start)
            y = self.find(parent, end)
            if x != y:
                e = e + 1
                result.append([start, end, weight])
                self.apply_union(parent, rank, x, y)
        return result

def create_weighted_graph(n):
    p = 0.6
    w_edges = []
    l = [0, 0, 0]

    mode = int(input("Enter the mode: 1 - if you want random weights; 2 - if you want to input it yourself: "))

    gr = fast_gnp_random_graph(n, p)

    print("The list of all edges:", gr.edges)
    uw_edges = list(gr.edges())
    length = len(gr.edges)

    for i in range(0, length):
        l = [0, 0, 0]
        for j in range(0, 3):
            if j == 2:
                if mode == 1:
                    l[j] = random.randint(1, 7)
                if mode == 2:
                    l[j] = int(input("Enter the weight of the edge: "))
            else:
                l[j] = uw_edges[i][j]
        w_edges.append(l)

    return w_edges, length

def print_graph(w_edges, length, res):
    G = nx.Graph()
    for i in range(0, length):
        G.add_edges_from([(str(w_edges[i][0]), str(w_edges[i][1]))], weight = w_edges[i][2])

    edge_labels=dict([((u,v,),d['weight'])
                     for u,v,d in G.edges(data=True)])

    red_edges = []
    for i in range(0, len(res)):
        red_edges.append((str(res[i][0]), str(res[i][1])))

    edge_colors = ['r' if edge in red_edges else 'b' for edge in G.edges()]

    pos=nx.circular_layout(G)
    node_labels = {node:node for node in G.nodes()}
    nx.draw_networkx_labels(G, pos, labels=node_labels)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
    nx.draw(G, pos, node_color='blue', node_size=1200, edge_color=edge_colors, edge_cmap=plt.cm.Reds)
    pylab.show()

def main():

    n = int(input("Enter the amount of nodes:"))
    g = Graph(n)

    w_edges, length = create_weighted_graph(n)

    for i in range(0, length):
        g.add_edge(w_edges[i][0], w_edges[i][1], w_edges[i][2])

    print("The minimal tree:\n")
    res = g.kruskal_algo()
    res_weight = 0
    res_len = len(res)
    for start, end, weight in res:
        res_weight += weight
        print("%d - %d: %d" % (start, end, weight))
    print('The weight of the tree:', res_weight)

    print_graph(w_edges, length, res)

if __name__ == '__main__':
    main()


import cv2
import numpy as np
import os
import PySimpleGUI as sg

def main(cascade, names, timeout):
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    # Read the trained .yml file that was generated previously
    recognizer.read('trainer/trainer.yml')
    # Give the type of cascade we are using at this time
    faceCascade = cv2.CascadeClassifier(cascade)
    font = cv2.FONT_HERSHEY_SIMPLEX
    #indicate id counter
    id = 0
    # Initialize and start realtime video capture
    cam = cv2.VideoCapture(0)
    cam.set(3, 480) # set video widht
    cam.set(4, 350) # set video height
    # Define min window size to be recognized as a face
    minW = 0.01*cam.get(3)
    minH = 0.01*cam.get(4)
    # Loop until we kill the program
    count = 0
    recognized = 0
    num_of_times = []
    while count <= int(timeout):
        ret, img =cam.read()
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

        faces = faceCascade.detectMultiScale(
            gray,
            scaleFactor = 1.2,
            minNeighbors = 5,
            minSize = (int(minW), int(minH)),
        )
        for(x,y,w,h) in faces:
            cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
            id, confidence = recognizer.predict(gray[y:y+h,x:x+w])

            # If confidence is less then 70 ==> "0" : perfect match
            # The smaller the number confidence needs to be less than, the harder it is to get a match
            if (confidence < 100):
                id = names[id - 1]
                id = id.replace('\n', '')
                num_of_times.append(id)
                recognized = recognized + 1
            else:
                id = "unknown"

            cv2.putText(
                        img,
                        str(id),
                        (x+5,y-5),
                        font,
                        1,
                        (255,255,255),
                        2
                    )

        cv2.imshow('camera',img)
        k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
        if k == 27:
            break
        if recognized == 20:
            highest_count = 0
            loop_count = 0
            for i in names:
                current = num_of_times.count(i)
                if(current > highest_count):
                    highest_count = current
                    id = str(names[loop_count])
                loop_count = loop_count + 1
            break
        count = count + 1
    # Do a bit of cleanup
    if count > int(timeout):
        id = "unknown"
    print("\n [INFO] Exiting Program and cleanup stuff")
    cam.release()
    cv2.destroyAllWindows()
    return(str(id))


import random
import time
import arcade

from dino_playground import Dino, Ground, Ptera , Cactus

class Game(arcade.Window):
    def __init__(self):
        self.w = 1300
        self.h = 600
        self.gravity = 0.2
        super().__init__(self.w , self.h , 'Dino')
        arcade.set_background_color(arcade.color.BLACK)
        self.background_image_night = arcade.load_texture(":resources:images/cybercity_background/far-buildings.png")
        self.background_image_day = arcade.load_texture(':resources:images/backgrounds/abstract_2.jpg')
        self.time_backgroundChange = time.time()
#ground
        self.ground_list =arcade.SpriteList()
        for i in range(0,1400,120):
            ground = Ground(i,40)
            self.ground_list.append(ground)
#dino
        self.dino = Dino()
        self.die_sound = arcade.load_sound(':resources:sounds/gameover3.wav')
        self.jumping_sound = arcade.load_sound(':resources:sounds/jump2.wav')
        self.my_physics_engine = arcade.PhysicsEnginePlatformer(self.dino , self.ground_list , gravity_constant=self.gravity)
#ptera
        self.ptera_list = arcade.SpriteList()
        self.ptera_time1 = time.time()
#cactus
        self.cactus_list = arcade.SpriteList()
        self.cactus_time1 = time.time()
#score
        self.score = 0
        self.high_score = self.score
        self.time = time.time()
        self.score_speed = 0
#flag
        self.flagDay = 0
        self.flagNight = 0
        self.game_over = False
        self.night = True
    #-------------------------------------------------------------------------------------------------------------------------------------#
    def on_draw(self):
        arcade.start_render()
        self.time_now = time.time()
        if self.game_over:
            if self.night:
                arcade.draw_text('YOU Lose', self.w//2-200, self.h//2, arcade.color.BLACK, 36 , width=400, font_name='Kenney Mini Square', align='center')
            else:
                arcade.draw_text('YOU Lose', self.w//2-200, self.h//2, arcade.color.BLACK, 36 , width=400, font_name='Kenney Mini Square', align='center')
        else:
            arcade.start_render()
            if self.time_now - self.time_backgroundChange > 15:
                self.time_backgroundChange = time.time()
                if self.night:
                    self.night = False
                else:
                    self.night = True
            if self.night:
                arcade.draw_lrwh_rectangle_textured(0, 0, self.w, self.h, self.background_image_night)
            else:
                arcade.draw_lrwh_rectangle_textured(0, 0, self.w, self.h, self.background_image_day)

            if self.night:
                arcade.draw_text('High_Score  %s  %s' %(str(self.high_score).zfill(5), str(self.score).zfill(5)), self.w-220, self.h-30, arcade.color.WHITE, 10 , width=400, font_name='Kenney Mini Square', align='left')
            else:
                arcade.draw_text('High_Score  %s  %s' %(str(self.high_score).zfill(5), str(self.score).zfill(5)), self.w-220, self.h-30, arcade.color.BLACK, 10 , width=400, font_name='Kenney Mini Square', align='left')

#ground
        for ground in self.ground_list:
            ground.draw()
#dino
        self.dino.draw()
#ptera
        for ptera in self.ptera_list :
            ptera.draw()
#cactus
        for cactus in self.cactus_list :
            cactus.draw()

    #-------------------------------------------------------------------------------------------------------------------------------------#
    def on_update(self, delta_time: float):

#dino
        self.dino.update_animation()
        self.my_physics_engine.update()

        self.time_score = time.time()
        if not self.game_over:
            self.score = int((self.time -self.time_score)*3)

#ptera
        if self.score > 100:
                self.ptera_time2 = time.time()
                if self.ptera_time2 - self.ptera_time1 > 10 :
                        new_ptera = Ptera(1300 , 1300)
                        self.ptera_list.append(new_ptera)
                        self.ptera_time1 = time.time()

                for ptera in self.ptera_list :
                        ptera.move()

        for ptera in self.ptera_list:
                if  arcade.check_for_collision(self.dino ,ptera) :
                        arcade.play_sound(self.die_sound)
                        self.game_over = True
                        self.ptera_time1 = time.time()
                        self.new_score = self.score
                        if self.new_score >= self.high_score :
                                self.high_score = self.score
                                arcade.set_background_color(arcade.color.WHITE)
                                #dino
                                self.dino = Dino()
                                self.die_sound = arcade.load_sound(':resources:sounds/gameover3.wav')
                                self.jumping_sound = arcade.load_sound(':resources:sounds/jump2.wav')
                                self.my_physics_engine = arcade.PhysicsEnginePlatformer(self.dino , self.ground_list , gravity_constant=self.gravity)
                        #ptera
                                self.ptera_list = arcade.SpriteList()
                                self.ptera_time1 = time.time()
                        #cactus
                                self.cactus_list = arcade.SpriteList()
                                self.cactus_time1 = time.time()
                        #score
                                self.score = 0
                                self.high_score = self.score

                        #flag
                                self.flagDay = 0
                                self.flagNight = 0

#cactus

        self.cactus_time2 = time.time()
        if self.cactus_time2 - self.cactus_time1 > 3 :
            new_cactus = Cactus(1300 , 1300)
            self.cactus_list.append(new_cactus)
            self.cactus_time1 = time.time()

        for cactus in self.cactus_list :
            cactus.move()
        for cactus in self.cactus_list:
                if  arcade.check_for_collision(self.dino ,cactus) :
                        arcade.play_sound(self.die_sound)
                        self.game_over = True
                        self.cactus_time1 = time.time()
                        self.new_score = self.score
                        if self.new_score >= self.high_score :
                                self.high_score = self.score
                                arcade.set_background_color(arcade.color.WHITE)
                                #dino
                                self.dino = Dino()
                                self.die_sound = arcade.load_sound(':resources:sounds/gameover3.wav')
                                self.jumping_sound = arcade.load_sound(':resources:sounds/jump2.wav')
                                self.my_physics_engine = arcade.PhysicsEnginePlatformer(self.dino , self.ground_list , gravity_constant=self.gravity)
                        #ptera
                                self.ptera_list = arcade.SpriteList()
                                self.ptera_time1 = time.time()
                        #cactus
                                self.cactus_list = arcade.SpriteList()
                                self.cactus_time1 = time.time()
                        #score
                                self.score = 0
                                self.high_score = self.score

                        #flag
                                self.flagDay = 0
                                self.flagNight = 0

    #-------------------------------------------------------------------------------------------------------------------------------------#
    def on_key_press(self, key, modifiers):

        if key == arcade.key.UP:
            if self.my_physics_engine.can_jump():
                self.dino.change_y = 8
                arcade.play_sound(self.jumping_sound)

        if key == arcade.key.DOWN:
            self.dino.texture = arcade.load_texture('dinoimage/17.png')
            self.dino.change_x = 0.00001

        if key == arcade.key.SPACE:
            self.game_over = False
            if self.score > self.high_score:
                self.high_score = self.score
            self.dino.write_highscore()
            self.score = 0
            self.time = time.time()

    #-------------------------------------------------------------------------------------------------------------------------------------#
    def on_key_release(self, key , modifiers):
        self.dino.change_x = 0

#-------------------------------------------------------------------------------------------------------------------------------------#
game = Game()
arcade.run()


#MaBe

#Criando a matriz
matriz = [[0, 0, 0], [0, 0, 0,], [0, 0, 0]]
for l in range(0, 3):
    for c in range(0,3):
        matriz[l][c] = int(input(f'Digite o valor da posição {(c, l)}: '))

#Organizando
for obj in range(0, 3):
    for i in range(0, 3):
        print(f'[{matriz[obj][i]}]', end=' ')
    print()

#Somando os valores pares
soma = 0
for id in range(0,3):
    for k in range(0, 3):
        if matriz[id][k] % 2 == 0:
            soma += matriz[id][k]

#Somando os valores da terceira coluna
ult = 0
for a in range(0,3):
    ult += matriz[a][2]

#Maior valor da segunda linha
maival = max(matriz[1])

print(f'Soma dos números pares: {soma}')
print(f'Soma dos valores da terceira coluna: {ult}')
print(f'Maior valor da segunda linha: {maival}')


from __future__ import print_function
import sys
import requests
import json
import yaml
import os
import base64

def update(session, headers, endpoint, HOST, projectname, configfile):
    with open(os.path.join(sys.path[0], configfile), 'r') as ymlfile:
            config = yaml.load(ymlfile)
    r = requests.get(HOST + endpoint.format('projects'), headers=headers, cookies=session)
    if r.status_code != 200:
        print("ERROR: Failed to fetch the project....")
        sys.exit(1)
    try:
        # Get Project ID
        projects = json.loads(r.text)["items"]
        project_exist = False
        for project in projects:
            if project["name"] == projectname:
               project_id = project["id"]
               project_exist = True
        if project_exist == False:
            print("ERROR: Project Name does not exist....")
            sys.exit(2)

        # Update encryption key and replication server
        rep = requests.get(HOST + endpoint.format('projects/{}/replicationConfigurations').format(project_id), headers=headers, cookies=session)
        for replication in json.loads(rep.text)["items"]:
            url = endpoint.format('projects/{}/replicationConfigurations/').format(project_id) + replication['id']
            replication["volumeEncryptionKey"] = config["replication"]["encryptionkey"]
            replication["volumeEncryptionAllowed"] = True
            replication["subnetId"] = config["replication"]["subnetID"]
            replication["replicatorSecurityGroupIDs"] = config["replication"]["securitygroupIDs"]
            eresult = requests.patch(HOST + url, data=json.dumps(replication), headers=headers, cookies=session)
            if eresult.status_code == 200:
               print("Encryption Key and replication server updated for project: " + projectname + "....")
            else:
               print("ERROR: Updating Encryption key or replication server failed....")

    except:
        print("ERROR: Updating project failed....")
        print(sys.exc_info())
        sys.exit(3)


import re
x = []
while True:
    try:
        y = input()
        if y == '':
            break
        try:
            x.append(int(y))
        except:
            lst = list(int(k) for k in re.findall(r'(-?\d+)', y))
            for i in lst:
                x.append(i)

    except EOFError:
        break

for i_array in x:
    for i in range(1, i_array+1):
      for j in range(1, i_array+1):
        common_v = 3

        if j == ((i_array+1)-i):
          common_v = 2
        elif j == i:
          common_v = 1

        print(common_v, end="")
      print("")


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

Description :
    Implementation of server on ports 8000, 80001
    The server on port 8000 based on the uuid of the clients is generating encrypted codes
    and send them to clients
    Then in the port 8001 there is the validation of uuid and the decrypted code that the client is sending
    if the validation is successful the message is been written to the log file

@author: Panagiotis Nikolaou

"""
import socket, select
import sys
from cryptography.fernet import Fernet
import re
import logging

logging.basicConfig(filename='server_comm.log', encoding='utf-8', level=logging.DEBUG)

def validation_server() -> None:
    # ports definition
    client_port_8000 = 8000
    client_port_8001 = 8001

    socket_list = []
    # host address
    host = '127.0.0.1'
    # amount of user connection on wait
    backlog = 50
    # buffer size
    buffer_size = 1024
    # fernet key generation for encryption/decryption
    f_key = Fernet(Fernet.generate_key())

    # loop through ports
    try:
        for item in client_port_8000, client_port_8001:
            # establish the connection
            try:
                socket_list.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
            except socket.error:
                print('Failed to create socket')
                sys.exit()
            print(f'Socket Created on port : {item}')
            # allows sockets in use binding
            socket_list[-1].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # bind to host / port
            socket_list[-1].bind((host, item))
            # listen for clients
            socket_list[-1].listen(backlog)
    except socket.error as message:
        if socket_list[-1]:
            socket_list[-1].close()
            socket_list = socket_list[:-1]
        print('Could not open socket: ' + message)
        sys.exit(1)

    while True:
        read, write, error = select.select(socket_list, [], [])

        for r_port in read:
            for item in socket_list:
                if r_port == item:
                    accepted_socket, address = item.accept()
                    print('New connection : ', address)
                    # detect the port
                    forward_port = accepted_socket.getsockname()[1]
                    if forward_port == 8000:
                        data = accepted_socket.recv(buffer_size)
                        print("UUID received from client")
                        # encrypt the uuid and send it to client as code
                        token = f_key.encrypt(data)
                        try:
                            accepted_socket.send(token)
                        except socket.error:
                            # Send failed
                            print('Client code send failed')
                            sys.exit()
                        print('Client code send successfully')
                    if forward_port == 8001:
                        # receive data as list
                        data = accepted_socket.recv(buffer_size).decode()
                        print("Data received from client")
                        # split the list items
                        data = list(data.split(','))
                        # decode with regular expression
                        quoted = re.compile("(?<=b')(.*?)(?=\')")
                        commands = quoted.findall(str(data))
                        uuid = commands[0]
                        encrypted_uuid = commands[1]
                        decrypted_uuid = f_key.decrypt(encrypted_uuid.encode())
                        message = commands[2]
                        # if the uuid of the client is equal to the fernet decrypted code then log the message
                        if decrypted_uuid.decode() == uuid:
                            print("Client validation succeeded. Logging message")
                            logging.info(message)
                    # close the connection
                    print("Closing socket")
                    accepted_socket.close()

if __name__ == "__main__":
    validation_server()


import os
import requests

from altruz import ALTRUZ, CMD_HELP
from altruz.helpers.pyrogram_help import get_arg
from altruz.core.main_cmd import altruz_on_cmd, e_or_r
from config import Config

# Help
CMD_HELP.update(
    {
        "paste": f"""
**Paste,**
  `paste` - To Paste Text to Hastebin
**Example:**
  `paste`,
   ⤷ Send text with command = `{Config.CMD_PREFIX}paste Paste this text`
   ⤷ Reply to a text file = `{Config.CMD_PREFIX}paste` (Reply to a text file)
   ⤷ Reply to a text message = `{Config.CMD_PREFIX}paste (Reply to a text message)
"""
    }
)

mod_file = os.path.basename(__file__)

@altruz_on_cmd(command="paste", modlue=mod_file)
async def paste(client, message):
    paste_msg = await e_or_r(altruz_message=message, msg_text="`Executing Command..`")
    replied_msg = message.reply_to_message
    tex_t = get_arg(message)
    message_s = tex_t
    if not tex_t:
        if not replied_msg:
            await paste_msg.edit("`Reply To File or Send This Command With Text!`")
            return
        if not replied_msg.text:
            file = await replied_msg.download()
            m_list = open(file, "r").read()
            message_s = m_list
            print(message_s)
            os.remove(file)
        elif replied_msg.text:
            message_s = replied_msg.text
    haste_url = "https://hastebin.com/documents"
    haste_paste = requests.post(haste_url, data=message_s.encode('utf-8'), timeout=3)
    hp_data = haste_paste.json()
    url_key = hp_data['key']
    pasted_url = f"https://hastebin.com/{url_key}"
    pasted_url_raw = f"https://hastebin.com/raw/{url_key}"
    await paste_msg.edit(f"**Pasted to Hastebin** \n\n**Hastebin Url:** [Click here]({pasted_url}) \n**Raw Url:** [Click here]({pasted_url_raw})", disable_web_page_preview=True)