import math
from time import sleep, perf_counter

from pyanaconda.modules.common.task.task_interface import TaskInterface
from pyanaconda.modules.common.task.task import Task, ValidationTask, AbstractTask

__all__ = ["sync_run_task", "async_run_task", "wait_for_task", "AbstractTask", "Task",
           "ValidationTask", "TaskInterface"]

def sync_run_task(task_proxy, callback=None):
    """Run a remote task synchronously.

    The given callback will be called every iteration.

    :param task_proxy: a proxy of the remote task
    :param callback: a callback
    :raise: a remote error
    """
    task_proxy.Start()

    while task_proxy.IsRunning:

        if callback:
            callback(task_proxy)

        sleep(0.1)

    task_proxy.Finish()

def async_run_task(task_proxy, callback):
    """Run a remote task asynchronously.

    The callback is called once the task is done. You should always
    call the Finish method of the remote task in your callback and
    handle the remote errors.

    Example of the callback:

        def callback(task_proxy):
            try:
                task_proxy.Finish()
            except RemoteError as e:
                pass

    :param task_proxy: a proxy of the remote task
    :param callback: a callback with a task_proxy argument
    """
    def _callback():
        callback(task_proxy)

    task_proxy.Stopped.connect(_callback)
    task_proxy.Start()

def wait_for_task(task_proxy, timeout=math.inf):
    """Wait for an existing and running task with optional timeout.

    If the timeout exception is raised, the task is not done. To call its Finish method and
    receive potential errors from its run, you can attach callbacks to the tasks's signals.
    Alternatively, you can give up re-raising the errors entirely.

    :param task_proxy: a proxy of the remote task
    :param float timeout: stop waiting after this time in seconds
    :raise TimeoutError: when the task did not finish before timeout
    """
    start = perf_counter()
    end = start + timeout

    while task_proxy.IsRunning and perf_counter() <= end:
        sleep(0.1)

    if task_proxy.IsRunning:
        raise TimeoutError()

    task_proxy.Finish()


def f(x):
    return x[0]

intervals = [[3, 10]]
newInterval = [4, 8]
intervals.append(newInterval)
l = sorted(intervals, key=f)

ans = []
c = l[0]
for i in range(len(l)):
    n = l[i]
    if n[0] <= c[1]:
        c[1] = max(c[1], n[1])
    else:
        ans.append(c)
        c = l[i]
n = c
if n[0] <= c[1]:
    c[1] = max(c[1], n[1])
    ans.append(c)
else:
    ans.append(c)
# return(ans)
print(ans)


"""This module provides class for working with Device Widget Window."""

__author__ = "Ilya Molodkin"
__date__ = "2023-04-22"
__version__ = "1.0"
__license__ = "MIT License"

import traceback
from typing import Optional, Dict, List

from PySide6.QtGui import QCloseEvent
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QMessageBox

from ui.widgets.Mixins import LoadUiMixin, FormSubmitMixin
from utils.utils import set_cbox_value

class DeviceWidget(QWidget, LoadUiMixin, FormSubmitMixin):
    """The `DeviceWidget` class is used to display a device window
    :param parent: reference to the parent widget in which the class instance is created
    :type parent: Widget
    """
    def __init__(self, parent=None) -> None:
        super().__init__()
        self.parent: QWidget = parent
        self.guid: Optional[str] = None
        self.setWindowModality(Qt.ApplicationModal)
        self.ui: QWidget = self.load_ui(ui_file="DeviceWidget.ui")
        self.ui.protocol_cbox.addItems(['Modbus RTU', 'Modbus TCP'])
        self.ui.protocol_cbox.setCurrentIndex(0)
        self.ui.protocol_cbox.currentIndexChanged.connect(self.protocol_cbox_changed)
        self.ui.port_cbox.addItems(self.parent.serial.config.keys())
        self.ui.ip_label.setHidden(True)
        self.ui.ip_input.setHidden(True)
        self.ui.address_input.setText('1')
        self.ip_input_value: str = ''
        self.ui.ip_input.textChanged.connect(self.ip_check)
        self.address_input_value: str = ''
        self.ui.address_input.textChanged.connect(self.address_check)
        self.ui.submit_btn.clicked.connect(self.submit)

    def fill_widget(self, guid: str, data: Dict) -> None:
        """The method fills interface elements with device parameters from the `data` dictionary
        :param guid:    unique device identifier
        :type guid:     str
        :param data:    dictionary with device parameters
        :type data:     Dict

        :return:        nothing
        :rtype:         None

        .. note::
            The data structure in the `data` dictionary:
            {
                "active": true,
                "address": 1,
                "interface": null,
                "ip": "127.0.0.1",
                "name": "Some Device Name",
                "protocol": "Modbus TCP",
                "registers": {
                    ...
                }
            },
            {
                "active": false,
                "address": 1,
                "interface": COM1,
                "ip": null,
                "name": "Some Other Device Name",
                "protocol": "Modbus RTU",
                "registers": {
                    ...
                }
            }
        """
        self.guid: str = guid
        self.ui.device_input.setText(data['name'])
        set_cbox_value(self.ui.protocol_cbox, data['protocol'])

        if data['ip']:
            self.ui.ip_input.setText(data['ip'])
            self.ui.ip_label.setHidden(False)
            self.ui.ip_input.setHidden(False)
            self.ui.port_label.setHidden(True)
            self.ui.port_cbox.setHidden(True)
        else:
            set_cbox_value(self.ui.port_cbox, data['interface'])
            self.ui.ip_label.setHidden(True)
            self.ui.ip_input.setHidden(True)
            self.ui.port_label.setHidden(False)
            self.ui.port_cbox.setHidden(False)
        self.ui.address_input.setText(str(data['address']))

    def protocol_cbox_changed(self) -> None:
        """
        The method is called on the combobox change event and brings other controls in line with the
        newly set value

        :return:        nothing
        :rtype:         None
        """
        hide_port: bool = bool(self.ui.protocol_cbox.currentIndex())
        self.ui.ip_input.setText('')
        self.ui.port_label.setHidden(hide_port)
        self.ui.port_cbox.setHidden(hide_port)
        self.ui.ip_label.setHidden(not hide_port)
        self.ui.ip_input.setHidden(not hide_port)

    def ip_check(self, text: str) -> None:
        """
        The method is called on the event of changing the ip-address input field, checks its
        correctness and does not allow user to enter an incorrect ip-address
        :param text:    new ip-address
        :type text:     str

        :return:        nothing
        :rtype:         None
        """
        octets: str = text.split('.')
        if len(octets) > 4:
            self.ui.ip_input.setText(self.ip_input_value)
            return None

        for octet in octets:
            if octet != '':
                if not octet.isdigit() or int(octet) > 255:
                    self.ui.ip_input.setText(self.ip_input_value)
                    return None
        self.ip_input_value: str = text
        return None

    def address_check(self, text: str) -> None:
        """
        The method is called on the event of the device address input field change and checks its
        correctness.
        It does not allow user to enter an incorrect address (0 <= text <= 247)

        :param text:    new address
        :type text:     str

        :return:        nothing
        :rtype:         None
        """
        if text.isdigit():
            if 0 <= int(text) <= 247:
                self.address_input_value = text
                return None
        self.ui.address_input.setText(self.address_input_value)
        return None

    def form_check(self) -> Optional[str]:
        """The method checks the correctness of filling all interface elements

        :return:            None if there are no errors, or a string describing the error
        :rtype:             Optional[str]
        :raises ValueError: if the form is filled out incorrectly
        """
        try:
            if not self.ui.device_input.text():
                raise ValueError('Поле "Устройство" не может быть пустым.')
            if self.ui.protocol_cbox.currentText() == 'Modbus RTU':
                if not self.ui.port_cbox.currentText():
                    raise ValueError('Поле "Порт" не может быть пустым.')
            elif self.ui.protocol_cbox.currentText() == 'Modbus TCP':
                ip_octets: List = self.ui.ip_input.text().split('.')
                if len(ip_octets) != 4:
                    raise ValueError('Указан неверный IP-адрес')
                for ip_octet in ip_octets:
                    if int(ip_octet) > 255:
                        raise ValueError('Указан неверный IP-адрес')
            else:
                raise ValueError('Указан неверный протокол.')
            if self.ui.address_input.text():
                if int(self.ui.address_input.text()) > 255:
                    raise ValueError('Адрес не может быть больше 255')
            else:
                raise ValueError('Поле "Адрес" не может быть пустым.')
        except ValueError as e:
            return e.args[0]
        return None

    def do_submit(self) -> None:
        """
        Processes the form submission by extracting the data from the form fields, creating
        a dictionary object and then calling the corresponding configuration object's method
        to create or update a device based on the extracted data.

        :return:    nothing
        :rtype:     None
        """
        interface: Optional[str] = None
        address: str = self.ui.address_input.text()
        protocol: str = self.ui.protocol_cbox.currentText()
        if protocol == 'Modbus RTU':
            interface = self.ui.port_cbox.currentText()
            ip = None
        else:
            ip: str = self.ui.ip_input.text()

        name: str = self.ui.device_input.text()
        data: Dict = {'address': int(address),
                      'protocol': protocol,
                      'interface': interface,
                      'ip': ip,
                      'name': name,
                      'active': True}
        if self.guid:
            result: str = self.parent.config.change_device_data(self.guid, data)
            if result:
                msgBox: QMessageBox = QMessageBox()
                msgBox.setText(result)
                msgBox.exec_()
            else:
                self.parent.tables['devices_tb'].load()
                self.close()
        else:
            data['registers']: Dict = {'01 Read Coils': None,
                                       '02 Read Discrete Inputs': None,
                                       '03 Read Holding Registers': None,
                                       '04 Read Input Registers': None, }
            result: Optional[str] = self.parent.config.create_device_data(data)
            try:
                if result:
                    raise LookupError(
                        'Error@DeviceWidget.submit.',
                        f'{result}'
                    )
                self.parent.tables['devices_tb'].load()
                self.close()
            except LookupError as e:
                print(f'{type(e).__name__} occurred, args={str(e.args)}\n\
                        {traceback.format_exc()}')
                msgBox: QMessageBox = QMessageBox()
                msgBox.setText(e.args[1])
                msgBox.exec_()

    def closeEvent(self, event: QCloseEvent) -> None:
        """Handles the window close event, deletes its own instance in parent's variable
        :param event: A QCloseEvent object that represents the window close event
        :type event: QCloseEvent

        :return: nothing
        :rtype: None
        """
        _ = event
        self.parent.widgets['device_widget'] = None


import face_recognition as fc
import cv2
from multiprocessing import Process, Pool
import sys

INPUT_VIDEO = sys.argv[1] # input video
INPUT_IMAGE = sys.argv[2] # input image
INPUT_NAME = sys.argv[3] # input name

# Create an output movie file (make sure resolution/frame rate matches input video!)
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# output_movie = cv2.VideoWriter('output.avi', fourcc, 29.97, (640, 360))

# Load some sample pictures and learn how to recognize them.
input_image = fc.load_image_file(INPUT_IMAGE)
input_face_encoding = fc.face_encodings(input_image)[0]

known_faces = [input_face_encoding]

def main(output_name, frame_start, frame_end):
    # Open the input movie file
    input_movie = cv2.VideoCapture(INPUT_VIDEO)
    length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))

    # # Create an output movie file (make sure resolution/frame rate matches input video!)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    output_movie = cv2.VideoWriter(output_name, fourcc, 29.97, (640, 360))

    # Load some sample pictures and learn how to recognize them.
    input_image = fc.load_image_file(INPUT_IMAGE)
    input_face_encoding = fc.face_encodings(input_image)[0]

    known_faces = [input_face_encoding]

    # Initialize some variables
    face_locations = []
    face_encodings = []
    face_names = []
    frame_number = frame_start  # подать в аргумент начало а также конец
    input_movie.set(1, frame_start)
    while True:
        # Grab a single frame of video
        ret, frame = input_movie.read()
        frame_number += 1
        if frame_number >= frame_start:

            # Quit when the input video file ends
            if frame_number >= frame_end:
                break

            # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
            rgb_frame = frame[:, :, ::-1]

            # Find all the faces and face encodings in the current frame of video
            face_locations = fc.face_locations(rgb_frame)
            face_encodings = fc.face_encodings(rgb_frame, face_locations)

            face_names = []
            for face_encoding in face_encodings:
                # See if the face is a match for the known face(s)
                match = fc.compare_faces(known_faces, face_encoding, tolerance=0.50)

                # If you had more than 2 faces, you could make this logic a lot prettier
                # but I kept it simple for the demo
                name = None
                if match[0]:
                    name = INPUT_NAME

                face_names.append(name)

            # Label the results
            for (top, right, bottom, left), name in zip(face_locations, face_names):
                if not name:
                    continue

                # Draw a box around the face
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

                # Draw a label with a name below the face
                cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (0, 0, 255), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)

            print("Writing frame  {} / {}".format(frame_number, frame_end))
            output_movie.write(frame)
    # All done!
    input_movie.release()
    cv2.destroyAllWindows()
        # # Write the resulting image to the output video file
        # print("Writing frame {} / {}".format(frame_number, length))
        # output_movie.write(frame)

# def video_writer():
#     print("Writing frame {} / {}".format(frame_number, length))
#     output_movie.write(frame)

if __name__ == "__main__":

    # Open the input movie file
    input_movie = cv2.VideoCapture(INPUT_VIDEO)
    length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))

    video_part = int(length / 3)

    p1 = Process(target=main, args=('output1.avi', 0, video_part))
    p2 = Process(target=main, args=('output2.avi', video_part, video_part*2))
    p3 = Process(target=main, args=('output3.avi', video_part*2, video_part*3))
    # p4 = Process(target=main, args=('output4.avi', video_part*3, video_part*4))

    p1.start()
    p2.start()
    p3.start()
    # p4.start()

    p1.join()
    p2.join()
    p3.join()
    # p4.join()
    # # Write the resulting image to the output video file
    # for i in range(0, int(length/2)):
    #     print("Writing frame {} / {}".format(i, int(length/2)))
    #     output_movie.write(begin_arr[i])
    #
    # for i in range(0, int(length/2)):
    #     print("Writing frame {} / {}".format(int(length/2), length))
    #     output_movie.write(end_arr[i])


matrixSum = lambda matrix: sum([col for row in [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] for col in row[0:row.index(0) if 0 in row else len(row)]])

# Okay, that is the most ugliest function I have made and it doesn't explain my thinking.
# Hence, a normal function.
#
# def matrixSum(matrix):
#     #Getting the transpose of matrix i.e swapping the rows and columns
#     matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
#
#     cost = 0
#     #We travel through each element of matrix
#     for row in matrix:
#         for col in row:
#             #We don't want to consider any of the rooms BELOW a free room
#             #But since I took transpose, we don't want to consider any of the room
#             #RIGHT of or AFTER a free room
#             if col == 0:
#                 break
#             cost += col
#
#     return cost
#
# Yo, I swear, if I lose, I will cry :"(


#!/usr/bin/env python3
"""Experiment with the boosting ML methods using Streamlit

Author: Peter Volgyesi <peter.volgyesi@gmail.com>

"""
import time
import re
from pathlib import Path
from urllib.parse import urlparse

import boto3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import streamlit as st

from sklearn.experimental import enable_hist_gradient_boosting  # noqa
from sklearn import (
    linear_model,
    ensemble,
    metrics,
    preprocessing,
    pipeline,
    model_selection,
    inspection
)

KNOWN_DATASETS = {
    "PXV_10_15_19 (lab-based)": (
        "s3://cpac/ORIG/"
        "SpinePredictions_500taks_PXV_1S_10_15_19/"
        "lumbar_results_PXV_10_15_19.csv"
    ),
    "PXV_10_15_19 V2 (wearables)": (
        "s3://cpac/ORIG/"
        "SpinePredictions_500taks_PXV_1S_10_15_19/"
        "lumbar_results2_PXV_10_15_19.csv"
    ),
    "PXV_10_15_19 V3 (lab-based subset)": (
        "s3://cpac/ORIG/"
        "SpinePredictions_500taks_PXV_1S_10_15_19/"
        "lumbar_results3_PXV_10_15_19.csv"
    )
}

META_PATTERNS = [
    "Trial_Name.*",
    "Trial_Index.*",
    "Trial_Type.*",
    "Mass.*"
]

TARGET_PATTERNS = [
    "Pelvis_Moment_X.*",
    "Pelvis_Moment_Y.*",
    "Pelvis_Moment_Z.*"
]

@st.cache(persist=True, show_spinner=False)
def load_dataset(s3_uri):
    """Download CSV dataset from S3"""
    parts = urlparse(s3_uri)
    path = parts.path.lstrip(" /")
    filename = Path(path).name
    bucket = parts.netloc
    with st.spinner(f"Loading {filename}"):
        s3 = boto3.resource('s3')
        s3_obj = s3.Object(bucket, path).get()
        return pd.read_csv(s3_obj["Body"])

def select_solumns(df):
    """Select target and feature columns"""
    st.sidebar.header("Select columns")
    metas = []
    features = []
    targets = []
    for column in df.columns:
        kind = features
        for pattern in META_PATTERNS:
            if re.match(pattern, column):
                kind = metas
        for pattern in TARGET_PATTERNS:
            if re.match(pattern, column):
                kind = targets
        kind.append(column)

    selected_target = st.sidebar.selectbox("Target", targets)
    selected_features = st.sidebar.multiselect(
        "Features", features, default=features)

    return selected_target, selected_features, metas

@st.cache(persist=True)
def _filter_dataset(
    df_orig,
    target,
    trial_name,
    filter_idp,
    filter_walk,
    filter_nan,
    target_range):

    df = df_orig.copy()
    if filter_idp:
        df = df[~df[trial_name].str.startswith("IDP")]
    if filter_walk:
        df = df[~df[trial_name].str.contains("walk")]
    if filter_nan:
        df = df.dropna()
    df = df[df[target].between(*target_range)]
    return df

def filter_dataset(df, target, features, metas):
    """Keep only relevant data"""
    st.sidebar.header("Select filters")
    filter_idp = st.sidebar.checkbox(
        "Remove 'IDP' trials", value=True)
    filter_walk = st.sidebar.checkbox(
        "Remove 'walk' trials", value=True)
    filter_nan = st.sidebar.checkbox(
        "Remove trials with NaN", value=True)

    # TODO: plot target distribution
    target_vals = df[target]
    def_low, def_high = target_vals.quantile(0.01), target_vals.quantile(0.99)
    target_range = st.sidebar.slider(
        "Valid target range",
        df[target].min(), df[target].max(),
        (def_low, def_high))

    # TODO: hack
    trial_name = metas[0]

    return _filter_dataset(
        df, target, trial_name, filter_idp, filter_walk,
        filter_nan, target_range)

def train_test_split(df, metas):
    """Split dataset to train/test subsets"""
    st.sidebar.header("Train - Test Split")
    # TODO: hack
    trial_name = metas[0]

    meta_options = df[trial_name].unique().tolist()

    # TODO: hack
    default_option = [option for option in meta_options
                     if re.match("S0[0-9]_5kg", option)]
    test_meta = st.sidebar.multiselect(
        "Select Test Set", meta_options, default=default_option)
    is_test = df[trial_name].isin(test_meta)
    return df[~is_test], df[is_test]

def analyze_feature(df, feature):
    """Analyze and plot a single feature"""
    with st.spinner(f"Analyzing {feature}"):
        sns.distplot(df[feature])
        st.pyplot()

def gradient_boosting(df_train, df_test, target, features):
    #st.header("Gradient Boosting (Histogram-based)")
    st.header("Results")
    t_start = time.time()
    with st.spinner("Training in progress..."):
        X_train = df_train[features]
        y_train = df_train[target]

        model = pipeline.Pipeline([
            ('scaler', preprocessing.StandardScaler()),
            ('gboost', ensemble.HistGradientBoostingRegressor(max_iter=200))
        ]).fit(X_train, y_train)
        t_train = time.time() - t_start

    t_start = time.time()
    with st.spinner("Testing in progress...."):
        X_test = df_test[features]
        y_test = df_test[target]
        y_test_pred = model.predict(X_test)
        mse = metrics.mean_squared_error(y_test_pred, y_test)
        r2 = metrics.r2_score(y_test_pred, y_test)
        t_test = time.time() - t_start

    st.write(f"**MSE**: {mse:.2f}")
    st.write(f"**R^2 Score**: {r2:.3f}")
    st.write(f"_Time train: {t_train:.3f} s, test: {t_test:.3f} s_")

    ax = sns.jointplot(y_test, y_test_pred, alpha=0.1, s=1.0, color="black")
    #sns.jointplot(y_test, y_test_pred, kind="hex")
    #sns.jointplot(y_test, y_test_pred, kind="reg")
    ax.set_axis_labels("Actual Pelvis Moment", 'Predicted Pelvis Moment')
    #ax.ax_joint.legend_.remove()
    ax.ax_joint.grid()
    #ax.ax_marg_x.set_title(f"Correlation of actual vs. predicted moments")
    st.pyplot()

    st.sidebar.header("Feature importances")
    do_imps = st.sidebar.checkbox(
        "Compute Feature Importance", value=False)

    if do_imps:
        n_repeats = st.sidebar.number_input(
            label="Repeats",
            value=10,
            min_value=1
        )

        st.header("Feature importances")
        st.write("The permutation feature importance is defined to be the "
                "decrease in a model score when a single feature value is "
                "randomly shuffled.")

        with st.spinner("Computing permutation importance...."):
            imps = inspection.permutation_importance(
                model,
                X_test,
                y_test,
                n_repeats=n_repeats,
                random_state=42,
                n_jobs=-1
            )
            sorted_imps_idx = imps.importances_mean.argsort()

        fig, ax = plt.subplots()
        ax.boxplot(imps.importances[sorted_imps_idx].T,
            vert=False, showfliers=False,
            labels=X_test.columns[sorted_imps_idx])
        fig.tight_layout()
        st.pyplot()

def main():
    """Life starts here"""
    st.title("CPAC - Gradient Boosting Regression")

    st.sidebar.header("Select dataset")
    dataset_name = st.sidebar.selectbox("Dataset",
                                        tuple(KNOWN_DATASETS.keys()))
    df = load_dataset(KNOWN_DATASETS[dataset_name])

    target, features, metas = select_solumns(df)
    df = filter_dataset(df, target, features, metas)

    st.header("Dataset Information")
    #st.write(f"**Number of samples**: {len(df):,}")
    #st.write(f"**Meta fields**: {', '.join(metas)}")
    st.write(df.describe())

    # st.header("Features")
    # st.write(f"**Number of selected features**: {len(features)}")
    # show_feature = st.selectbox("", features)
    # analyze_feature(df, show_feature    )

    st.header("Train - Test Sets")
    df_train, df_test = train_test_split(df, metas)
    n_train, n_test = len(df_train), len(df_test)
    st.write(f"{n_train:,} (**{n_train / (n_train + n_test):.0%}**) - "
             f"{n_test:,} (**{n_test / (n_train + n_test):.0%}**)")

    gradient_boosting(df_train, df_test, target, features)

def sandbox():
    import time
    my_bar = st.progress(0)
    for percent_complete in range(100):
        time.sleep(0.01)
        my_bar.progress(percent_complete + 1)

    with st.spinner('Wait for it...'):
        time.sleep(2)
    st.success("Done")
    with st.spinner('Take two...'):
        time.sleep(2)

if __name__ == "__main__":
    main()
    #sandbox()


# -*- coding:utf-8 -*-
from .exceptions import ParseException
from .lexer import (
    Open,
    OpenClose,
    Close
)
from .nodes import (
    Command,
    _Root,
    Def,
    Import,
    PyImport,
    Yield,
    Block
)
from .utils import get_unquoted_string, Gensym

class Parser(object):
    node_classes = {}
    command_node = Command

    def __init__(self):
        self.gensym = Gensym()

    @classmethod
    def register(cls, nodeclass):
        cls.node_classes[nodeclass.get_class_name()] = nodeclass

    def create_node(self, token):
        if token.name in self.node_classes:
            factory = self.node_classes[token.name]
            return factory(name=self.get_node_name(token), attrs=token.attrs)
        else:
            factory = self.command_node
            return self._create_node_for_command_node(factory, name=token.name, attrs=token.attrs)

    def _create_node_for_command_node(self, factory, name, attrs):
        # treating. :params attributes as block node
        blocks = []
        for k in list(attrs.keys()):
            if k.startswith(":"):
                block_node_name = "{}.{}".format(name, k[1:])  # :foo -> <node>.foo
                block_node = self.node_classes["block"](name=block_node_name)
                block_node.add_child(get_unquoted_string(attrs.pop(k)))
                blocks.append(block_node)
        new_node = factory(name=name, attrs=attrs)
        for b in blocks:
            new_node.add_child(b)
        return new_node

    def get_node_name(self, token):
        if hasattr(token, "attrs") and "name" in token.attrs:
            return get_unquoted_string(token.attrs["name"])
        else:
            return self.gensym(token.name)

    def __call__(self, tokens):
        root = _Root("*root")
        iterator = iter(tokens)
        self._construct([root], iterator)
        return root

    def is_open(self, token):
        return isinstance(token, Open)

    def is_close(self, token):
        return isinstance(token, Close)

    def is_openclose(self, token):
        return isinstance(token, OpenClose)

    def _construct(self, stack, iterator):
        for token in iterator:
            if self.is_open(token):
                newnode = self.create_node(token)
                stack[-1].add_child(newnode)
                stack.append(newnode)
            elif self.is_close(token):
                stack.pop()
            elif self.is_openclose(token):
                newnode = self.create_node(token)
                stack[-1].add_child(newnode)
            else:
                stack[-1].add_child(token)
        if len(stack) != 1:
            raise ParseException("unmatched tag: stack={}".format(stack))

Parser.register(Def)
Parser.register(Yield)
Parser.register(Import)
Parser.register(PyImport)
Parser.register(Block)


#Faça um programa que leia 5 números e informe a soma e a média dos números.

list = []
for i in range(5):
    x = int(input('Número: '))
    list.append(x)
mx = max(list)
print(f'Soma: {sum(list)}')
print(f'Maior: {mx}')
print(f'Média {(sum(list)/5):.2f}')


#################################
##### Name: Zitong Liao
##### Uniqname: liaozt
#################################
import sqlite3
import csv
import json
import requests
import secret

## CONSTANTS ##
DBNAME = 'media.db'
BECHDELCSV = 'movies.csv'
CACHE_FNAME = 'media_cache.json'

## CLASS ##
class Media:

    def __init__(self, title="No Title", author="No Author", year="No Release Year", summary="None"):
        self.title = title
        self.author = author
        self.year = year
        self.summary = summary

    def __str__(self):
        return self.title + " by " + self.author + " (" + self.year + ")"

class Movie (Media):

    def __init__(self, title="No Title", author="No Author", year="No Release Year",
                 summary="None", rating="No Rating", genres="None", img_url="None", status="No Data"):

        super().__init__(title, author, year, summary)
        self.rating = rating
        self.genres = genres
        self.img_url = img_url
        self.status = status

    def __str__(self):
        return super().__str__() + " [" + self.rating + "]"

class Book (Media):
    def __init__(self, title="No Title", author="No Author", year="No Release Year",
                 summary="None", pages=0):
        super().__init__(title, author, year, summary)
        self.pages = pages

    def __str__(self):
        return super().__str__() + " [" + str(self.pages) + "]"

# Initialize cache file
try:
    cache_file = open(CACHE_FNAME, 'r')
    cache_contents = cache_file.read()
    CACHE_DICTION = json.loads(cache_contents)
    cache_file.close()
except:
    CACHE_DICTION = {}

def init_db():
    '''Initialize media.db file (creating tables for Books, Movies, and BechdelStats.)

    Parameters
    ----------
    none

    Returns
    -------
    none
    '''
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()

    # Drop tables
    statement = '''
        DROP TABLE IF EXISTS 'Books';
    '''
    cur.execute(statement)

    statement = '''
        DROP TABLE IF EXISTS 'Movies';
    '''
    cur.execute(statement)

    statement = '''
        DROP TABLE IF EXISTS 'BechdelStats';
    '''
    cur.execute(statement)

    conn.commit()

    # Create tables
    statement = '''
        CREATE TABLE Books (
            Id INTEGER PRIMARY KEY AUTOINCREMENT,
            Title TEXT NOT NULL,
            Year TEXT NOT NULL,
            Author TEXT NOT NULL,
            Description BLOB,
            MovieId INTEGER,
            FOREIGN KEY(MovieId) REFERENCES Movie(Id)
        );
    '''
    cur.execute(statement)

    statement = '''
            CREATE TABLE Movies (
                Id INTEGER PRIMARY KEY AUTOINCREMENT,
                Title TEXT NOT NULL,
                Year TEXT NOT NULL,
                Director TEXT NOT NULL,
                Rating TEXT,
                Genre TEXT,
                Plot BLOB,
                PosterURL TEXT,
                BechdelId INTEGER NOT NULL,
                FOREIGN KEY(BechdelId) REFERENCES BechdelStats(Id)
            );
        '''
    cur.execute(statement)

    statement = '''
        CREATE TABLE BechdelStats (
            Id INTEGER PRIMARY KEY AUTOINCREMENT,
            Title TEXT NOT NULL,
            Year INT NOT NULL,
            Status TEXT NOT NULL,
            Budget REAL NOT NULL,
            GrossIncome REAL NOT NULL
        );
    '''
    cur.execute(statement)

    conn.commit()
    conn.close()

def insert_bechdel_stats_into_db():
    '''Read CSV file into media.db

    Parameters
    ----------
    none

    Returns
    -------
    none
    '''
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()

    # Insert data to Bechdel Stats table
    with open(BECHDELCSV, encoding='utf-8') as csv_data_file:
        csv_reader = csv.reader(csv_data_file)
        next(csv_reader)

        for bechdel_movie in csv_reader:
            year = bechdel_movie[0]
            title = bechdel_movie[2]
            status = bechdel_movie[5]
            budget = bechdel_movie[6]
            gross = bechdel_movie[7]

            insertion = (None, title, year, status, budget, gross)
            statement = 'INSERT INTO "BechdelStats" '
            statement += 'VALUES (?, ?, ?, ?, ?, ?)'

            cur.execute(statement, insertion)
            conn.commit()

    conn.close()

def insert_movies_into_db():
    '''Make requests to Open Movie Database API for movies on the Bechdel list into media.db.

    Parameters
    ----------
    none

    Returns
    -------
    none
    '''
    titles_list = []
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()

    titles_list = get_bechdel_titles(cur, titles_list)

    for title in titles_list:
        movie_resp = make_request_using_cache(title[0], "movie")

        if movie_resp["Response"] == "True" and title[0] == movie_resp["Title"]:

            #Look up foreign key for BechdelId in BechdelStats table
            statement = "SELECT Id FROM BechdelStats WHERE Title=?"
            result = cur.execute(statement, (movie_resp["Title"],))
            for row in result:
                bechdel_id = int(row[0])

            insertion = (None, movie_resp["Title"], movie_resp["Year"], movie_resp["Director"], movie_resp["Rated"],
                   movie_resp["Genre"], movie_resp["Plot"], movie_resp["Poster"], bechdel_id)
            statement = 'INSERT INTO "Movies" '
            statement += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
            cur.execute(statement, insertion)
            conn.commit()

    conn.close()

def insert_books_into_db():
    '''Make requests to Google Books API for books on the Bechdel list

    Parameters
    ----------
    none

    Returns
    -------
    none
    '''
    titles_list = []
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()
    book_is_found = False

    #titles_list = get_bechdel_titles(cur, titles_list)
    statement = "SELECT Movies.Title FROM Movies"
    results = cur.execute(statement)
    movie_titles_tuple = results.fetchall()

    #Process title data by converting immutable tuple to mutable list
    for title in movie_titles_tuple:
        titles_list.append(list(title))

    for title in titles_list:
        title[0]=title[0].replace(" ", "-")

    for title in titles_list:
        book_resp = make_request_using_cache(title[0], "book")

        #Select an edition of the book based on returned results
        if "items" in book_resp.keys(): #Ensures book_resp has returned books, not an error resp
            #Loop through all of the books returned to find the one the referenced in movie list
            for book in book_resp["items"]:
                book_title = book["volumeInfo"]["title"].replace(" ", "-")

                if  title[0] == book_title and "subtitle" not in book["volumeInfo"] and \
                        book_is_found == False:
                    try:
                        book_year = book["volumeInfo"]["publishedDate"]
                    except:
                        book_year = "Unknown"
                    try:
                        book_author = book["volumeInfo"]["authors"][0]
                    except:
                        book_author = "Unknown"
                    try:
                        book_description = book["volumeInfo"]["description"]
                    except:
                        book_description = "None"

                    book_is_found = True

                    #Look up foreign key for movie_id from Movies table
                    statement = "SELECT Id FROM Movies WHERE Title=?"
                    result = cur.execute(statement, (book_title,))
                    for row in result:
                        movie_id = int(row[0])

                    #Insert book into media.db
                    insertion = (None, book_title, book_year, book_author, book_description, movie_id)
                    statement = 'INSERT INTO "Books" '
                    statement += "VALUES (?, ?, ?, ?, ?, ?)"
                    cur.execute(statement, insertion)
                    conn.commit()

            #Reset so that next title in title_list will search for matching book
            book_is_found = False
    conn.close()

def get_bechdel_titles(cur, titles_list):
    '''Query database for all titles of movies in the Bechdel test data set.

    Parameters
    ----------
    cur
        DB cursor

    titles_list
        the (empty) list of titles

    Returns
    -------
    list
        a list of titles in the data set
    '''
    statement = "SELECT BechdelStats.Title FROM BechdelStats"
    results = cur.execute(statement)
    titles_tuple = results.fetchall()

    for title in titles_tuple:
        titles_list.append(list(title))

    for title in titles_list:
        title[0]=title[0].replace(" ", "-")

    return titles_list

def make_request_using_cache(title, media_type):
    '''Make request or retrieve previous request from cache

    Parameters
    ----------
    title
        title of the media

    media_type
        string to distinguish book from movie title

    Returns
    -------
    Jason
        Jason file
    '''
    if media_type == "movie":
        url = "http://www.omdbapi.com/?apikey=" + secret.OMDB_API_KEY + "&t=" + title
    elif media_type == "book":
        url = "https://www.googleapis.com/books/v1/volumes?q=" + title
    unique_id = url

    if unique_id in CACHE_DICTION:
        print("Getting cached data from " + unique_id + "...")
        return CACHE_DICTION[unique_id]

    print("Making a request for new data from " + url + "...")

    resp = requests.get(url)
    CACHE_DICTION[unique_id] = json.loads(resp.text)
    dumped_json_cache = json.dumps(CACHE_DICTION)
    fw = open(CACHE_FNAME,"w")
    fw.write(dumped_json_cache)
    fw.close()
    return CACHE_DICTION[unique_id]

def search_media_from_db (title=''):
    '''Query the database for movies and books, and create a list of objects

    Parameters
    ----------
    sortby
        column to sort by

    sortorder
        ascending or descending values

    Returns
    -------
    list
        media_list
    '''
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()
    movie_obj_list = []
    book_obj_list = []
    media_list = []

    statement = "SELECT * FROM Movies WHERE Title LIKE '%{search}%'".format(search=title)
    movie_results = cur.execute(statement)
    movie_results_list = movie_results.fetchall()
    for movie_tuple in movie_results_list:

        statement = "SELECT BechdelStats.Status FROM BechdelStats JOIN Movies ON Movies.BechdelId=BechdelStats.Id" \
                    " WHERE Movies.BechdelId=" + str(movie_tuple[8])
        stats_results = cur.execute(statement)
        status_results_list = stats_results.fetchall()

        movie_obj_list.append(Movie(movie_tuple[1], movie_tuple[3], movie_tuple[2], movie_tuple[6],
                                             movie_tuple[4], movie_tuple[5], movie_tuple[7], status_results_list[0][0]))

    statement = "SELECT * FROM Books WHERE Title LIKE '%{search}%'".format(search=title)
    book_results = cur.execute(statement)
    book_results_list = book_results.fetchall()
    for book_tuple in book_results_list:
        book_obj_list.append(Book(book_tuple[1], book_tuple[3], book_tuple[2], book_tuple[4]))

    conn.close()

    for book in book_obj_list:
        media_list.append(["book", book.title, book.author, book.year[:4], book.summary, "", "", "UNKNOWN"])
    for movie in movie_obj_list:
        media_list.append(["movie", movie.title, movie.author, movie.year, movie.summary, movie.rating, movie.genres,
                           movie.status])

    sort_col = 1

    media_list.sort(key=lambda row: row[sort_col], reverse=False)

    return media_list

def get_media_from_db (sortby='Title', sortorder='desc'):
    '''Query the database for movies and books, and create a list of objects

    Parameters
    ----------
    sortby
        column to sort by

    sortorder
        ascending or descending values

    Returns
    -------
    list
        media_list
    '''
    conn = sqlite3.connect(DBNAME)
    cur = conn.cursor()
    movie_obj_list = []
    book_obj_list = []
    media_list = []

    statement = "SELECT * FROM Movies"
    movie_results = cur.execute(statement)
    movie_results_list = movie_results.fetchall()
    for movie_tuple in movie_results_list:

        statement = "SELECT BechdelStats.Status FROM BechdelStats JOIN Movies ON Movies.BechdelId=BechdelStats.Id" \
                    " WHERE Movies.BechdelId=" + str(movie_tuple[8])
        stats_results = cur.execute(statement)
        status_results_list = stats_results.fetchall()

        movie_obj_list.append(Movie(movie_tuple[1], movie_tuple[3], movie_tuple[2], movie_tuple[6],
                                             movie_tuple[4], movie_tuple[5], movie_tuple[7], status_results_list[0][0]))

    statement = "SELECT * FROM Books"
    book_results = cur.execute(statement)
    book_results_list = book_results.fetchall()
    for book_tuple in book_results_list:
        book_obj_list.append(Book(book_tuple[1], book_tuple[3], book_tuple[2], book_tuple[4]))

    conn.close()

    for book in book_obj_list:
        media_list.append(["book", book.title, book.author, book.year[:4], book.summary, "", "", "UNKNOWN"])
    for movie in movie_obj_list:
        media_list.append(["movie", movie.title, movie.author, movie.year, movie.summary, movie.rating, movie.genres,
                           movie.status])

    if sortby == 'type':
        sort_col = 0
    elif sortby == 'title':
        sort_col = 1
    elif sortby == 'author':
        sort_col = 2
    elif sortby == 'status':
        sort_col = 7
    else:
        sort_col = 1

    rev = (sortorder == 'desc')
    media_list.sort(key=lambda row: row[sort_col], reverse=rev)

    return media_list

if __name__ == "__main__":
    init_db()
    insert_bechdel_stats_into_db()
    insert_movies_into_db()
    insert_books_into_db()


import numpy as np
import copy
import matplotlib.pyplot as plt
import functii as fc
from PIL import Image
from scipy import ndimage
from scipy.io import loadmat
from sklearn.model_selection import train_test_split

# Loading the dataset into a variable and separate the inputs from outputs
mnist = loadmat("mnist-original.mat")
mnist_data = mnist["data"].T
mnist_data_pt_calcule = mnist["data"]
mnist_label = mnist["label"][0].reshape(70000, 1)

matrice_raspuns = np.zeros((mnist_label.shape[0], 10))
for i in range(len(mnist_label)):
    matrice_raspuns[i][int(mnist_label[i][0])] = 1

# Splitting the dataset into the trainset and testset
X_train, X_test, Y_train, Y_test = train_test_split(
    mnist_data, matrice_raspuns, random_state=4
)

# Transposing the matrices, to put each input/output in a column
X_train = X_train.T
Y_train = Y_train.T
X_test = X_test.T
Y_test = Y_test.T

# Centering and standardizing the dataset
X_train = X_train / 255
X_test = X_test / 255

parameters, costs = fc.L_layer_model(X_train, Y_train, 2, 20, 0.09, 4301, True)

Y_train_pred = fc.predict(X_train, Y_train, parameters)
Y_test_pred = fc.predict(X_test, Y_test, parameters)

# saving the parameters
with open("Valori_w_si_b.txt", "wb") as f:
    for i in parameters:
        np.save(f, parameters[i])

para = {}
with open("Valori_w_si_b.txt", "rb") as d:
    for i in range(1, 4):
        para["W" + str(i)] = np.load(d)
        para["b" + str(i)] = np.load(d)


# import all the libraries
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from glob import glob
from tqdm import tqdm

data_x = glob("images/*")

for path in tqdm(data_x, total=len(data_x)):
    name=path.split("\\")[-1].split('.')[0]
    extension=path.split(".")[-1]

    # to open the image
    image = Image.open(path)

    width=image.width
    height=image.height

    # image watermark
    size = (200, 100)
    crop_image = Image.open("logo.jpeg")
    # to keep the aspect ration in intact
    crop_image.thumbnail(size)

    # add watermark
    copied_image = image.copy()
    # base image

    x=width-200
    y=height-65

    copied_image.paste(crop_image, (x,y))
    # pasted the crop image onto the base image
    copied_image.save(f"watermark.{extension}")

    break

# # to open the image
# image = Image.open("images.jpeg")

# width=image.width
# height=image.height

# # image watermark
# size = (200, 100)
# crop_image = Image.open("logo.jpeg")
# # to keep the aspect ration in intact
# crop_image.thumbnail(size)

# # add watermark
# copied_image = image.copy()
# # base image

# x=width-200
# y=height-65

# copied_image.paste(crop_image, (x, y))
# # pasted the crop image onto the base image
# # plt.imshow(copied_image)
# copied_image.save("watermark.jpeg")


import time
from datetime import date
import pyautogui

seg1 = 97008923329
seg2 = 91281210707
ter1 = 98697198016
ter2 = 94416817691
qua1 = 92904660131
sex1 = 92109319047
sex2 = 98111556931
hj = date.today()
hj.weekday()
h = int(time.strftime('%H', time.localtime()))
m = int(time.strftime('%M', time.localtime()))
v = 0
if hj.weekday() == 0:
    if h == 18 or h == 19 or h == 20 and m < 25:
        v = seg1
        print("Aula de 'ALPOO LAB' com o professor Alécio")
        print("Tenha uma boa aula!")
    elif h == 20 and m > 25 or h == 21:
        v = seg2
        print("Aula de 'ALPOO LAB' com o professor Alécio")
        print("Tenha uma boa aula!")
elif hj.weekday() == 1:
    if h == 18 or h == 19 or h == 20 and m < 25:
        v = ter1
        print("Aula de 'LPBD' com o professor Robson")
        print("Tenha uma boa aula!")
    elif h == 20 and m > 25 or h == 21:
        v = ter2
        print("Aula de 'LPBD LAB' com o professor Robson")
        print("Tenha uma boa aula!")
elif hj.weekday() == 2:
    if h == 18 or h == 19 or h == 20 and m < 25:
        v = qua1
        print("Aula de 'ALPOO LAB' com o professor Gustavo")
        print("Tenha uma boa aula!")
elif hj.weekday() == 4:
    if h == 18 or h == 19 or h == 20 and m < 25:
        v = sex1
        print("Aula de 'ED' com o professor Gley")
        print("Tenha uma boa aula!")
    elif h == 20 and m > 25 or h == 21:
        v = sex2
        print("Aula de 'ED LAB' com o professor Gley e Pedro")
        print("Tenha uma boa aula!")
elif hj.weekday() == 5:
    print("Hoje é Sábado")
    print("Não tem aula!")
    input("Aperte ENTER para finalizar!")
elif hj.weekday() == 6:
    print("Hoje é Domingo")
    print("Não tem aula!")
    input("Aperte ENTER para finalizar!")
else:
    v = 0

if v == 0:
    time.sleep(2)

else:
    time.sleep(2)
    pyautogui.click(770, 750)
    time.sleep(1)
    pyautogui.click(700, 360)
    time.sleep(1.5)
    pyautogui.typewrite(str(v))
    pyautogui.hotkey("tab")
    pyautogui.hotkey("tab")
    pyautogui.hotkey("ctrl", "a")
    pyautogui.hotkey("delete")
    pyautogui.typewrite("Rafael Gomes D919HH-7 CC4P-68")
    pyautogui.hotkey("enter")
    time.sleep(5)


#Config
import ConfigParser, platform
import logging

class Config():
    log = logging.getLogger('Config')

    def __init__(self, pytelqueues, configfile = 'pyTelQueues.cfg'):
        self._pytelqueues, self._configfile = (pytelqueues, configfile)

        self._config = ConfigParser.ConfigParser()
        self._config.read(self._configfile)
        self.fastagi_port = self.read_config_var('fastagi', 'port', 4573, 'int')
        self.redishost = self.read_config_var('redis', 'host', '127.0.0.1', 'str') #should be localhost
        self.redisport = self.read_config_var('redis', 'port', 6379, 'int')
        self.log.debug('Config loaded')

    def defaulting(self, section, variable, default, quiet = False):
        if quiet == False:
            self.log.debug("%s not set in [%s] defaulting to: %s" %
                    (variable, section, default))

    def read_config_var(self, section, variable, default, type = 'str', quiet = False):
        try:
            if type == 'str':
                return self._config.get(section,variable)
            elif type == 'bool':
                return self._config.getboolean(section,variable)
            elif type == 'int':
                return int(self._config.get(section,variable))
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
            self.defaulting(section, variable, default, quiet)
            return default


class Instr:
    def __init__(self, instrName, value):
        self.instrName = instrName
        self.value = value
        self.visited = False

class Program:
    def __init__(self, listOfInstructions):
        self.instructions = listOfInstructions
        self.acc = 0
        self.iP = 0 # instruction pointer
        self.visitedInstructions = dict()
    def runInstr(self, instrName, value):
        self.visitedInstructions[self.iP] = True
        nextInstrOffset = 1
        if instrName == "nop":
            nextInstrOffset = 1 # Can't have an empty if-statement
        elif instrName == "acc":
            self.acc += value
        elif instrName == "jmp":
            nextInstrOffset = value
        else:
            raise InvalidArgument("Instruction not supported: " + instrName)

        self.iP += nextInstrOffset
        return True
    def runStep(self):
        if self.iP in self.instructions:
            return False
        (instrName, value) = self.instructions[self.iP]
        return self.runInstr(instrName,value)

    def runStepDebug(self):
        if self.iP in self.visitedInstructions:
            print("Stopped running due to duplicate instruction encountered")
            print("#POST: ACC: "+ str(self.acc) + ", IP: " + str(self.iP) + "###")
            return False
        print("#PRE: ACC: "+ str(self.acc) + ", IP: " + str(self.iP) + "###")
        (instrName, value) = self.instructions[self.iP]
        retRes = self.runInstr(instrName,value)
        print("#POST: ACC: "+ str(self.acc) + ", IP: " + str(self.iP) + "###")
        return retRes

instructions = []

with open("input.txt") as file_in:
    for line in file_in:
        line = line.rstrip()
        (instr, value) = line.split()
        value = int(value)
        instructions.append( (instr, value) )

prg = Program(instructions)
while prg.runStepDebug():
    x = 1


import hydra
import pytorch_lightning as pl
from hydra.utils import instantiate
from pytorch_lightning.callbacks import ModelCheckpoint

from data_modules import ImageDataModule
from modules.common.callback import GenerateImageCallback

@hydra.main(config_path='configs', config_name='config.yaml')
def main(cfg):
    pl.seed_everything(cfg.seed)

    model = instantiate(cfg.method.model)
    dm = ImageDataModule(cfg.method.data)
    dm.setup()

    wandb_logger = instantiate(cfg.logger)
    wandb_logger.watch(model, log='gradients', log_freq=100)

    model_checkpoint = ModelCheckpoint(
        filename=f'{cfg.method.name}' + '{epoch:04d}-{val_loss:.4f}',
        dirpath=f'saved_models',
        monitor='val_loss',
        save_top_k=5,
        save_last=True,
    )
    image_callback = GenerateImageCallback(
        val_images=next(iter(dm.val_dataloader()))[0],
        save_dir='generated_images'
    )

    trainer = pl.Trainer(
        logger=wandb_logger,
        callbacks=[model_checkpoint, image_callback],
        deterministic=True,
        **cfg.trainer
    )
    trainer.fit(model=model, datamodule=dm)

if __name__ == '__main__':
    main()


n,q = map(int, input().split())
event = [list(map(int, input().split())) for i in range(q)]

yellow = []
red = []

for i in range(q):
    player = event[i][1]
    # yellow
    if event[i][0] == 1:
        if player in yellow:
            red.append(player)
        else:
            yellow.append(player)
    if event[i][0] == 2:
        red.append(player)
    if event[i][0] == 3:
        if player in red:
            print("Yes")
        else:
            print("No")
    # print("yellow")
    # print(yellow)
    # print("red")
    # print(red)
    # print("-------")


buah = {'Apel':'5000>Apel',
 'Jeruk':'8500>Jeruk',
 'Mangga':'7800>Mangga',
 'duku':'6500>Duku'}

data = list(buah.values())
data.sort()

for x in data:
    print(x)

buaha =[5000,8500,7800,6500]
rerata= sum(buaha)/len(buaha)
print('rata rata = ',+int(rerata))

while True:
    print('Masukkan nama buah:', end='')
    nama = input()
    print('Masukan kg: ', end='')
    kilo = int(input())
    if nama == '':
        break

    if nama in hargabuah:
        print('Harga: Rp',hargabuah[nama]+kilo)


def diss(x , y, sx, sy):
    dis = abs(x-sx) + abs(y-sy)
    return int(dis)

def rbcall(n, m, sx, sy, d):
    for i in range(1, n+1):
        if diss(i, 1, sx, sy) <= d:
            return 1
    for i in range(1, m+1):
        if diss(n, i, sx, sy) <= d:
            return 1
    return 2

def ulcall(n, m, sx, sy, d):
    for i in range(1, m+1):
        # print('       ', 1, i)
        # print(diss(1, i, sx, sy), d)
        if diss(1, i, sx, sy) <= d:
            return 1
    for i in range(1, n+1):
        # print('       ', i, m)
        # print(diss(i, m, sx, sy), d)
        if diss(i, m, sx, sy) <= d:
            return 1
    return 2

t = int(input())
for _ in range(0, t):
    n, m, sx, sy, d = list(map(int, input().split()))

    if rbcall(n, m, sx, sy, d) == 2:
        # print('rb', end = ' ')
        print(n+m-2)
    elif ulcall(n, m, sx, sy, d) == 2:
        # print('ul', end= ' ')
        print(n+m-2)
    else:
        print(-1)

"""
B. Deadly Laser
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
The robot is placed in the top left corner of a grid, consisting of n rows and m columns, in a cell (1,1).

In one step, it can move into a cell, adjacent by a side to the current one:

(x,y)→(x,y+1);
(x,y)→(x+1,y);
(x,y)→(x,y−1);
(x,y)→(x−1,y).
The robot can't move outside the grid.

The cell (sx,sy) contains a deadly laser. If the robot comes into some cell that has distance less than or equal to d to the laser, it gets evaporated. The distance between two cells (x1,y1) and (x2,y2) is |x1−x2|+|y1−y2|.

Print the smallest number of steps that the robot can take to reach the cell (n,m) without getting evaporated or moving outside the grid. If it's not possible to reach the cell (n,m), print -1.

The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than d to the laser.

Input
The first line contains a single integer t (1≤t≤104) — the number of testcases.

The only line of each testcase contains five integers n,m,sx,sy,d (2≤n,m≤1000; 1≤sx≤n; 1≤sy≤m; 0≤d≤n+m) — the size of the grid, the cell that contains the laser and the evaporating distance of the laser.

The laser is neither in the starting cell, nor in the ending cell ((sx,sy)≠(1,1) and (sx,sy)≠(n,m)). The starting cell (1,1) always has distance greater than d to the laser (|sx−1|+|sy−1|>d).

Output
For each testcase, print a single integer. If it's possible to reach the cell (n,m) from (1,1) without getting evaporated or moving outside the grid, then print the smallest amount of steps it can take the robot to reach it. Otherwise, print -1.

Example
inputCopy
3
2 3 1 3 0
2 3 1 3 1
5 5 3 4 1
outputCopy
3
-1
8
"""

Codeforce_Coding/1721B - Deadly Laser.py


#!/usr/bin/env python3

# read file and assign numbers to
with open('puzzle1.txt','r') as puznums:
    numbers = puznums.readlines()

# define goal numbers should total when added
goal = 2020

# function to add two numbers
def two_number(num1,num2):
    return num1 + num2

#function to add three numbers
def three_number(num1,num2,num3):
    return two_number(num1, num2) + num3

# function for part one of challenge
def part_one():
    # part one: 2 numbers sum to goal
    print(f'Part 1: Two numbers sum to {goal}')
    for num1 in numbers:
        num1 = int(num1)
        for num2 in numbers:
            num2 = int(num2)
            if two_number(num1, num2) == goal:
                product = num1 * num2
                print(f'Found it! {num1} and {num2} sum to {goal}!')
                print(f'Multiplied together they equal {product}')
                break
            else:
                continue
            break
        else:
            continue
        break

# function for part two of challenge
def part_two():
    # part 2: three numbers sum to goal
    print(f'Part 2: Three numbers sum to {goal}')
    for num1 in numbers:
        num1 = int(num1)
        for num2 in numbers:
            num2 = int(num2)
            for num3 in numbers:
                num3 = int(num3)
                if three_number(num1,num2,num3) == goal:
                    product = (num1 * num2 * num3)
                    print(f'Found it! {num1}, {num2}, and {num3} sum up to {goal}')
                    print(f'Multiplied together they equal {product}')
                    break
                else:
                    continue
                break
            else:
                continue
            break
        else:
            continue
        break

# define main function
def main():
    part_one()
    # line separator to clearly separate part one and two answers
    print('\n-----\n')
    part_two()

# call main function
main()


from common.logger import Logger
from neo4j import GraphDatabase
from parser.grammar import GrammarItem
import config

class Neo4jDatabase:
    def __init__(self):
        self.connection = GraphDatabase.driver(f"bolt://{config.NEO4J_HOST}", auth=(config.NEO4J_USER, config.NEO4J_PASSWORD))
        self.logger = Logger().logger
        self.logger.info("Neo4j ready to query")

    def close(self):
        self.connection.close()

    def create_node(self, rule: GrammarItem):
        query = """MERGE (node:RuleItem {type: rule.type_name, word: rule.word})"""
        with self.connection.session() as session:
            session.build_index(query, rule=rule)

    def create_connection(self, a: GrammarItem, b: GrammarItem):
        query = """
        MERGE (a:RuleItem {type: a.type_name, word: a.word});
        MERGE (b:RuleItem {type: b.type_name, word: b.word});
        MERGE (a)-[r:DEP {dep: a.token.dep_}]->(b)
        ON CREATE SET r.count = 1
        ON MATCH SET r.count = r.count + 1
        """
        with self.connection.session() as session:
            session.build_index(query, a=a, b=b)


# Decode Davis Weather Station data from wireless ISS weather station

# MSB in first byte that dictates what data is sent in bytes 3-4
ISS_CAP_VOLTS    = 0x2
ISS_UV_INDEX     = 0x4
ISS_RAIN_SECONDS = 0x5
ISS_SOLAR_RAD    = 0x6
ISS_OUT_TEMP     = 0x8
ISS_WIND_GUST    = 0x9
ISS_HUMIDITY     = 0xA
ISS_RAIN_COUNT   = 0xE

SENSOR_OFFLINE   = 0xFF

# Error message values
ERR_WRONG_PACKET = -100
ERR_OUT_OF_RANGE = -101
ERR_INVALID_DATA = -102

# ---------------------------------------------------------------------------------------------
# Davis station ID
# In header byte, bits 0-2 determine station ID
def stationID(rawData):
    ID = rawData[0] & 0x7
    ID += 1 # Davis station IDs start at 1, in the raw data, they start at 0.  Add 1 to return the actual ID
    return(ID)

# ---------------------------------------------------------------------------------------------
# Battery status is bit 3 in header
def batteryStatus(rawData):
    bat = (rawData[0] & 8) >> 3
    return(bat)

# ---------------------------------------------------------------------------------------------
# Seconds between bucket tips, used to calculate rain rate in inches per hour
# Goes up to 15 minutes/900 seconds (I think).
# Data decoding is kind of wonky. The data comes in differently depending on if it's raining hard or not
def rainRate(rawData):
    #Verify packet contains rain rate data
    if (rawData[0] >> 4) != ISS_RAIN_SECONDS:
        return (-100)  ## Wrong packet type - doesn't contain rain rate seconds

    if ( rawData[4] & 0x40 == 0 ):
        rainRateSeconds =  (rawData[3] >> 4) + rawData[4] - 1         # Light rain
    else:
        rainRateSeconds = rawData[3] + ((rawData[4] >> 4) - 4) * 256  # Heavy rain

    if (rainRateSeconds < 0 or rainRateSeconds > 3600): # check for realistic range
        return(ERR_OUT_OF_RANGE)

    return(rainRateSeconds)

# ---------------------------------------------------------------------------------------------
# Different formula for rain rate
def rainRate2(rawData):
    # Verify packet contains rain rate data
    if (rawData[0] >> 4) != ISS_RAIN_SECONDS:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain rain rate seconds

    if ( rawData[4] & 0x40 == 0 ):
        rainRateSeconds =  ((rawData[4] & 0x30) / 16 * 250) + rawData[3]        # Light Rain
    else:
        rainRateSeconds = (((rawData[4] & 0x30) / 16 * 250) + rawData[3]) / 16  # Heavy Rain

    if (rainRateSeconds < 0 or rainRateSeconds > 3600): # check for realistic range
        return(ERR_OUT_OF_RANGE)

    return(rainRateSeconds)

# ---------------------------------------------------------------------------------------------
# Counter 0-127 that increments each time bucket tips.  Each bucket tip is 0.01"
# Uses first 3 bits of byte 3
def rainCounter(rawData):
    # Verify packet contains rain rate data
    if (rawData[0] >> 4) != ISS_RAIN_COUNT:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain rain counter

    rainCntr = rawData[3] & 0x7F # Return first 3 bits of byte 3

    if (rainCntr < 0 or rainCntr > 127): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return (rainCntr)

# ---------------------------------------------------------------------------------------------
# Counter 0-127 that increments each time bucket tips.  Each bucket tip is 0.01"
# This function returns the inches instead of the count
# Uses first 3 bits of byte 3
# ---- NOT USED ---
def rainInch(rawData):
    # Verify packet contains rain rate data
    if (rawData[0] >> 4) != ISS_RAIN_COUNT:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain rain counter

    rainCountInch = (rawData[3] & 0x7F) / 100.0 # Counter is first 3 bits

    if (rainCountInch < 0 or rainCountInch > 1.27): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return (rainCountInch)

# ---------------------------------------------------------------------------------------------
# There is a dead zone on the wind vane. No values are reported between 8 and 352 degrees inclusive.
# These values correspond to received byte values of 1 and 255 respectively
# Byte 2 is always wind direction,
def windDirection(rawData):
    if ( rawData[2] == 0 ):
        return (0)
    else:
        windDir = (rawData[2] * 1.40625) + 0.3

    if (windDir < 0 or windDir > 360):  # check for valid range
        return(ERR_OUT_OF_RANGE)

    return (windDir)

# ---------------------------------------------------------------------------------------------
# Wind speed in MPH is always byte 1
def windSpeed(rawData):

    speed = rawData[1]

    if (speed < 0 or speed > 240): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return (speed)

# ---------------------------------------------------------------------------------------------
# Wind is in byte 3, no manipulation needed
def windGusts(rawData):
    # Verify packet contains wind gust data
    if (rawData[0] >> 4) != ISS_WIND_GUST:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain wind gust data

    gust = rawData[3]
    if (gust < 0 or gust > 240): # check for valid range
         return(ERR_OUT_OF_RANGE)

    return (gust)

# ---------------------------------------------------------------------------------------------
# Help wtih 2's complement:
#   https://stackoverflow.com/questions/54297651/python-2s-complement-conversion
def temperature(rawData):

    # Verify packet contains temperature data
    if (rawData[0] >> 4) != ISS_OUT_TEMP:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain temperature data

    # Temp F in 1/10 degrees, ie 320 = 32.0F
    # check for negative temperature
    if (rawData[3] >= 128):
        # Temp is negative, binary number is 2's complements
        byte_mask = ~0xFFFF
        outsideTemperature = ( ((rawData[3] << 8) + rawData[4]) | byte_mask) >> 4
    else: # temp is positive
    #    outsideTemperature = (rawData[3] * 256 + rawData[4]) >> 4
        outsideTemperature = ((rawData[3] << 8) + rawData[4]) >> 4

    outsideTemperature = outsideTemperature / 10.0 # convert from tenths to degrees

    if (outsideTemperature < -100 or outsideTemperature > 130): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return(outsideTemperature)

# ---------------------------------------------------------------------------------------------
def humidity(rawData):
    # Verify packet contains humidity data
    if (rawData[0] >> 4) != ISS_HUMIDITY:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain humidity data

    rh = ((rawData[4] >> 4) * 256 + rawData[3]) / 10.0

    if (rh < 0 or rh > 100): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return (rh)

# ---------------------------------------------------------------------------------------------
# Solar radiation in Watts/Meter^2
def solarRadiation(rawData):
    # Verify packet contains humidity data
    if (rawData[0] >> 4) != ISS_SOLAR_RAD:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain solar radiation data

    if ( rawData[3] == SENSOR_OFFLINE ):
        return(0)
    else:
        tt = rawData[3] * 256 + rawData[4]
        tt = tt >> 4
        solarRad = (tt - 4) / 2.27 - 0.2488

    if (solarRad < 0 or solarRad > 2000): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return (solarRad)

# ---------------------------------------------------------------------------------------------
def uvIndex(rawData):
    # Verify packet contains humidity data
    if (rawData[0] >> 4) != ISS_UV_INDEX:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain UV Index data

    if ( rawData[3] == SENSOR_OFFLINE ):
        return(0)
    else:
        tt = rawData[3] * 256 + rawData[4]
        tt = tt >> 4;
        uvi = (tt-4) / 200.0

    if (uvi < 0 or uvi > 16): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return(uvi)

# ---------------------------------------------------------------------------------------------
# The ISS-internal goldcap capacitor - store the energy needed during the night,  Vue only
def capVoltage(rawData):
    # Verify packet contains humidity data
    if (rawData[0] >> 4) != ISS_CAP_VOLTS:
        return (ERR_WRONG_PACKET)  # Wrong packet type - doesn't contain capacitor voltage data

    volts = ((rawData[3] * 4) + ((rawData[4] & 0xC0) / 64.0)) / 100.0

    if (volts < 0 or volts > 10): # check for valid range
        return(ERR_OUT_OF_RANGE)

    return (volts)

# ---------------------------------------------------------------------------------------------
# CRC check, returns True if CRC matches, False if not
#
# Could also use the crcmod library. See: https://bit.ly/2TgB8VB
# First Method
#    import crcmod
#    crcfun = crcmod.mkCrcFun(0x11021, rev=False, initCrc=0, xorOut=0)
#    result = crcfun(b'\x82\x00\x3a\x0a\x89\x00')
# Second method
#    import crcmod.predefined
#    crc = crcmod.predefined.mkCrcFun('xmodem')
#    result = crc(b'\x82\x00\x3a\x0a\x89\x00')
# or
#    bytestring = "\x82\x00\x3a\x0a\x89\x00"
#    result = crc(bytestring)

def crc16_ccitt(rawData):
    # calculate the crc of the first 6 bytes of data
    crc = 0
    length = 6 # data is in first 6 bytes, crc in last 2

    i = 0
    for byteData in rawData:
        if i == length:
            break

        crc ^= (byteData << 8)
        i += 1

        k = 0
        while k < 8:
            k += 1
            if(crc & 0x8000):
                crc = (crc << 1) ^ 0x1021
            else:
                crc = crc << 1
        crc = crc & 0xFFFF  # Makes crc look like unsigned 16-bit integer

    # Extract the CRC from the last 2 bytes of packet
    crcSent = rawData[6] * 256 + rawData[7]

    if (crc == crcSent and crc != 0):
        return (True)
    else:
        return (False)


import argparse

from terial import models
from terial import config
from terial.database import session_scope
from tqdm import tqdm
from collections import defaultdict
import torch

parser = argparse.ArgumentParser()
parser.add_argument('--cuda', action='store_true')
parser.add_argument('--thres', default=0.1)
args = parser.parse_args()

def main():
    with session_scope() as sess:
        exemplars = sess.query(models.Exemplar).order_by(
            models.Exemplar.id).filter_by(exclude=False).all()

    print(f"Fetched {len(exemplars)} exemplars. Loading features...")

    feats = []
    for e1 in tqdm(exemplars):
        f1 = e1.load_data(config.EXEMPLAR_ALIGN_DATA_NAME)
        feats.append(f1)

    feats = torch.tensor(feats).squeeze()
    if args.cuda:
        feats = feats.cuda()

    print(f"Computed {feats.size(0)} features each with {feats.size(1)} dims.")
    print(f"Computing duplicates...")
    duplicates = defaultdict(list)
    duplicate_dists = defaultdict(list)

    for i, f in enumerate(tqdm(feats)):
        dists = (feats - f.unsqueeze(0).expand(*feats.size())).pow(2).sum(dim=1)
        dists[i] = 99999
        duplicate_inds = torch.nonzero(dists < 0.1)
        if len(duplicate_inds) > 0:
            duplicates[i].extend(duplicate_inds[:, 0].tolist())
            duplicate_dists[i].extend(dists[duplicate_inds][:, 0].tolist())

    print(f"Found duplicates from {len(duplicates)} exemplars.")
    yy = input("Commit, this cannot be undone (easily)? (y/n) ")
    if yy != 'y':
        return

    with session_scope() as sess:
        for i, dup_list in duplicates.items():
            e1 = exemplars[i]

            # Refetch from DB and check if it's already excluded.
            # If th
            e1 = sess.query(models.Exemplar).get(e1.id)
            if e1.exclude:
                continue

            for j in dup_list:
                e2 = exemplars[j]
                print(f'Set exemplar {e2.id}.exclude = True')
                sess.query(models.Exemplar).get(e2.id).exclude = True
                sess.commit()
                # print(e1.id, e2.id)

if __name__ == '__main__':
    main()


import time
import game
import math
import sheep
import random
import caveman
import visualize
from game import game_
from sheep import collision
from caveman import cmnaive
from sheep import sheepmoves
from sheep import checknearest
from visualize import recreate
from visualize import creategrid
from caveman import cmbayesian

if __name__ == "__main__":
	begin = time.time()
	print("please wait for training")
	print("..........")
	print(".....")
	#store the cpts
	x_move = {} #x_move
	y_move = {} #y_move
	ss_move = {}#ss_move
	#store the sheep's probability
	sheep_X = sheep_Y = {}
	#store the caveman1 probability
	caveman1_X = caveman1_Y = {}
	#store the caveman2 probability
	caveman2_X = caveman2_Y = {}
	#store distance from corner
	c0 = {}
	#store distance from caveman 1
	c1 = {}
	#store distance from caveman2
	c2 = {}
	iter = 0
	n = 8 # size of maze
	for itr in range(500):
		start = game_()
		for i in range(50):
			iter += 1
			caveman1_x = start.caveman1[0]
			caveman1_y = start.caveman1[1]
			caveman2_x = start.caveman2[0]
			caveman2_y = start.caveman2[1]
			sx = start.sheep[0]
			sy = start.sheep[1]
			c_0 = int(checknearest(start.sheep))
			c_1 = int(math.dist(start.sheep, start.caveman1))
			c_2 = int(math.dist(start.sheep, start.caveman2))
			if str(sx) in sheep_X :
				sheep_X[str(sx)] = sheep_X[str(sx)]+1
			else:
				sheep_X[str(sx)] = 1

			if str(sy) in sheep_Y:
				sheep_Y[str(sy)] = sheep_Y[str(sy)]+1
			else:
				sheep_Y[str(sy)] = 1

			if str(caveman1_x) in caveman1_X:
				caveman1_X[str(caveman1_x)] = caveman1_X[str(caveman1_x)]+1
			else:
				caveman1_X[str(caveman1_x)] = 1

			if str(caveman1_y) in caveman1_Y:
				caveman1_Y[str(caveman1_y)] = caveman1_Y[str(caveman1_y)]+1
			else:
				caveman1_Y[str(caveman1_y)] = 1

			if str(caveman2_x) in caveman2_X:
				caveman2_X[str(caveman2_x)] = caveman2_X[str(caveman2_x)]+1
			else:
				caveman2_X[str(caveman2_x)] = 1

			if str(caveman2_y) in caveman2_Y:
				caveman2_Y[str(caveman2_y)] = caveman2_Y[str(caveman2_y)]+1
			else:
				caveman2_Y[str(caveman2_y)] = 1

			if str(c_0) in c0:
				c0[str(c_0)] = c0[str(c_0)]+1
			else:
				c0[str(c_0)] = 1

			if str(c_1) in c1:
				c1[str(c_1)] = c1[str(c_1)]+1
			else:
				c1[str(c_1)] = 1

			if str(c_2) in c2:
				c2[str(c_2)] = c2[str(c_2)]+1
			else:
				c2[str(c_2)] = 1

			caveman1 = cmnaive(start, 1)
			caveman2 = cmnaive(start, 2, caveman1)
			sheep = sheepmoves(start, caveman1, caveman2)
			start.newposition(caveman1,caveman2,sheep[0])

			x_move_key = str(sx)+str(caveman1_x)+str(caveman2_x)
			y_move_key = str(sy)+str(caveman1_y)+str(caveman2_y)
			ss_move_key = str(sx)+str(sy)+str(c_0)+str(c_1)+str(c_2)

			#updating CPT
			if 'w' in sheep[1]: #left
				if x_move_key+'w' in x_move:
					x_move[x_move_key+'w'] = x_move[x_move_key+'w']+1
				else:
					x_move[x_move_key+'w'] = 1
			elif 'e' in sheep[1]: #right
				if x_move_key+'e' in x_move:
					x_move[x_move_key+'e'] = x_move[x_move_key+'e']+1
				else:
				 	x_move[x_move_key+'e'] = 1

			if 'n' in sheep[1]: #up
				y_move[y_move_key+'n'] = y_move[y_move_key+'n']+1 if y_move_key+'n' in y_move else 1
			elif 's' in sheep[1]: #down
				y_move[y_move_key+'s'] = y_move[y_move_key+'s']+1 if y_move_key+'s' in y_move else 1

			if sheep[1] == 'stay': #0 step
				if ss_move_key+'0' in ss_move:
					ss_move[ss_move_key+'0'] = ss_move[ss_move_key+'0']+1
				else:
					ss_move[ss_move_key+'0'] = 1
			else:
				if ss_move_key+str(len(sheep[1])//2) in ss_move:
					ss_move[ss_move_key+str(len(sheep[1])//2)] = ss_move[ss_move_key+str(len(sheep[1])//2)]+1
				else:
				 	ss_move[ss_move_key+str(len(sheep[1])//2)] =1

			if collision(caveman1,caveman2,sheep[0]):
				break

	#update all CPTs
	for key in x_move:
		x_move[key] = x_move[key]/iter/(sheep_X[key[0]]/iter)/(caveman1_X[key[1]]/iter)/(caveman2_X[key[2]]/iter)
	for key in y_move:
		y_move[key] = y_move[key]/iter/(sheep_Y[key[0]]/iter)/(caveman1_Y[key[1]]/iter)/(caveman2_Y[key[2]]/iter)
	for key in ss_move:
		ss_move[key] = ss_move[key]/iter/(sheep_X[key[0]]/iter)/(sheep_Y[key[1]]/iter)/(c0[key[2]]/iter)/(c1[key[3]]/iter)/(c2[key[4]]/iter)

	delay = 0.1
	grid, rect, screen, wid = creategrid(n)
	for i in range(5):
		print('Game ',i+1,':')
		start = game_()
		win = False
		o = 50
		t = 0
		for i in range(o):
			sx = str(start.sheep[0])
			sy = str(start.sheep[1])
			caveman1_x = str(start.caveman1[0])
			caveman1_y = str(start.caveman1[1])
			caveman2_x = str(start.caveman2[0])
			caveman2_y = str(start.caveman2[1])
			c_0 = str(int(checknearest(start.sheep)))
			c_1 = str(int(math.dist(start.sheep, start.caveman1)))
			c_2 = str(int(math.dist(start.sheep, start.caveman2)))

			ss_move_key = sx+sy+c_0+c_1+c_2
			x_move_key = sx+caveman1_x+caveman2_x
			y_move_key = sy+caveman1_y+caveman2_y

			step = 0
			if ss_move_key+'0' in ss_move:
				prob = ss_move[ss_move_key+'0']
			else:
				prob = 0
			if ss_move_key+'1' in ss_move:
				if prob < ss_move[ss_move_key+'1']:
					step = 1
					prob = ss_move[ss_move_key+'1']
			if ss_move_key+'2' in ss_move:
				if prob < ss_move[ss_move_key+'2']:
					step = 2

			if step > 0:
				d_x = 'w'
				if x_move_key+'w' in x_move:
					prob = x_move[x_move_key+'w']
				else:
						prob = 0

				if x_move_key+'e' in x_move:
					if prob < x_move[x_move_key+'e']:
						d_x = 'e'
						prob = x_move[x_move_key+'e']
				prob = 0

				if y_move_key+'n' in y_move:
					prob = y_move[y_move_key+'n']
				else:
					prob = 0

				if y_move_key+'s' in y_move:
					if prob < y_move[y_move_key+'s']:
						d_y = 's'

			ps = start.sheep	#predicted sheep move
			if step > 0:
				if d_x == 'w':
					ps = (ps[0]-step,ps[1])
				else:
					ps = (ps[0]+step,ps[1])

				if d_x == 'n':
					ps = (ps[0],ps[1]-step)
				else:
					ps = (ps[0],ps[1]+step)

			new_n = random.randint(1,100)
			if new_n < 80:
				caveman1 = cmbayesian(start, ps)
			else:
				caveman1 = cmnaive(start, 1)

			caveman2 = cmnaive(start, 2, caveman1)

			sheep = sheepmoves(start, caveman1, caveman2)

			start.newposition(caveman1,caveman2,sheep[0])

			recreate(grid, rect, screen, 8, start.game_ , delay, wid)

			if collision(caveman1,caveman2,sheep[0]):
				print('Winner : Caveman')
				t = 1
				end = time.time()
				print(end- begin)
				break
		if (t==0):
			print('Winner : Sheep')
			end = time.time()
			print(end- begin)


from time import sleep
from Controller import Controller
from Client import Client
from Parser import Parser

def test():
    robotic_arm = Controller(
            sg90_pin=15,
            sg90_min_angle=-90,
            sg90_max_angle=90,
            sg90_min_pulse_width=500/1000000,
            sg90_max_pulse_width=2500/1000000,
            sg90_rotate_angle=0,
            sg90_name='Gripper',
            dcmotor_backward_pin=20,
            dcmotor_forward_pin=16,
            dcmotor_ena=21,
            dcmotor_pwm=True,
            dcmotor_clockwise=True,
            dcmotor_rotate_angle=0,
            limitsw_pin1=6,
            limitsw_pin2=7,
            limitsw_start_delay=.5,
            mg996r_base_pin=24,
            mg996r_base_min_angle=-90,
            mg996r_base_max_angle=90,
            mg996r_base_min_pulse_width=700/1000000,
            mg996r_base_max_pulse_width=2537/1000000,
            mg996r_base_rotate_angle=0,
            mg996r_base_name='Joint_1',
            mg996r_arm_pin=25,
            mg996r_arm_min_angle=90,
            mg996r_arm_max_angle=-90,
            mg996r_arm_min_pulse_width=700/1000000,
            mg996r_arm_max_pulse_width=2537/1000000,
            mg996r_arm_rotate_angle=0,
            mg996r_arm_name='Joint_2')
    try:
        print('dc clockwise 90')
        robotic_arm.control_dcmotor('clockwise', 90)
        sleep(5)

        print('joint_1 90') # forward
        robotic_arm.control_base(90)
        sleep(5)

        print('joint_1 0') # perpendicular
        robotic_arm.control_base(0)
        sleep(5)

        print('joint_2 0') # forward
        robotic_arm.control_arm(0)
        sleep(5)

        print('joint_2 90') # perpendicular
        robotic_arm.control_arm(90)
        sleep(5)

        print('gripper close')
        robotic_arm.control_gripper('close')
        sleep(5)

        print('gripper open')
        robotic_arm.control_gripper('open')
        sleep(5)

        print('dc anti-clockwise 90')
        robotic_arm.control_dcmotor('anti-clockwise', 90)
        sleep(5)

    except:
        exit(1)

def main():
    robotic_arm = Controller(
            sg90_pin=15,
            sg90_min_angle=-90,
            sg90_max_angle=90,
            sg90_min_pulse_width=500/1000000,
            sg90_max_pulse_width=2500/1000000,
            sg90_rotate_angle=0,
            sg90_name='Gripper',
            dcmotor_backward_pin=20,
            dcmotor_forward_pin=16,
            dcmotor_ena=21,
            dcmotor_pwm=True,
            dcmotor_clockwise=True,
            dcmotor_rotate_angle=0,
            limitsw_pin1=6,
            limitsw_pin2=7,
            limitsw_start_delay=.5,
            mg996r_base_pin=24,
            mg996r_base_min_angle=-90,
            mg996r_base_max_angle=90,
            mg996r_base_min_pulse_width=700/1000000,
            mg996r_base_max_pulse_width=2537/1000000,
            mg996r_base_rotate_angle=0,
            mg996r_base_name='Joint_1',
            mg996r_arm_pin=25,
            mg996r_arm_min_angle=90,
            mg996r_arm_max_angle=-90,
            mg996r_arm_min_pulse_width=700/1000000,
            mg996r_arm_max_pulse_width=2537/1000000,
            mg996r_arm_rotate_angle=0,
            mg996r_arm_name='Joint_2')
    client = Client(subs=['controlCode'])
    parser = Parser(robotic_arm)
    def on_run():
        try:
            code = client.sub("controlCode")
            if code != None:
                if type(code) == bytes:
                    code = code.decode('utf-8')
                parser.parse(code)
                client.pub("controlCode", "")
            else:
                # print("Idle")
                pass
            sleep(1)
        except KeyboardInterrupt:
            raise KeyboardInterrupt

    try:
        client.connect(on_run)
    except KeyboardInterrupt:
        print('Terminated')
        exit(1)
    except Exception as err:
        print('Unknown error: ', err)

if __name__ == '__main__':
    main()
    test()


"""RectangleArea"""
def main():
    """process"""
    rec_ax, rec_ay, width_a, height_a = (int(i) for i in input().split())
    rec_bx, rec_by, width_b, height_b = (int(i) for i in input().split())
    toprec_ax, toprec_ay = rec_ax + width_a, rec_ay + height_a
    toprec_bx, toprec_by = rec_bx + width_b, rec_by + height_b
    if toprec_ax >= rec_bx and toprec_ay >= rec_by:
        width = min(toprec_ax, toprec_bx) - max(rec_ax, rec_bx)
        height = min(toprec_ay, toprec_by) - max(rec_ay, rec_by)
        print(int(width * height))
    else:
        print("no overlapping")

main()


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

import json
import os
import re
import shutil
import subprocess as sp
import sys
import time

import textwrap
import requests
import yaml
from requests.packages.urllib3.exceptions import InsecureRequestWarning

try:
    import xml.etree.cElementTree as eTree
except ImportError:
    import xml.etree.ElementTree as eTree

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

LOGS = [('[op_panel]', '/var/log/op_panel'),
        ('[cluster_manager]', '/var/log/cluster_manager'),
        ('[op_worker]', '/var/log/op_worker')]
LOG_LEVELS = ['debug', 'info', 'error']
ONEPANEL_OVERRIDE = 'ONEPANEL_OVERRIDE'

GENERATED_CONFIG_SOURCES_PATH = '_build/default/rel/op_panel/etc/autogenerated.config'
VM_ARGS_SOURCES_PATH = '_build/default/rel/op_panel/etc/vm.args'

GENERATED_CONFIG_PACKAGES_PATH = '/etc/op_panel/autogenerated.config'
VM_ARGS_PACKAGES_PATH = '/etc/op_panel/vm.args'

class AuthenticationException(ValueError):
    pass

def log(message, end='\n'):
    sys.stdout.write(message + end)
    sys.stdout.flush()

def replace(file_path, pattern, value):
    with open(file_path, 'rw+') as f:
        content = f.read()
        content = re.sub(pattern, value, content)
        f.seek(0)
        f.truncate()
        f.write(content)

def set_node_name(file_path):
    hostname = sp.check_output(['hostname', '-f']).rstrip('\n')
    replace(file_path, r'-name .*', '-name onepanel@{0}'.format(hostname))

def config_file_initialized(file_path):
    with open(file_path, 'r') as f:
        content = f.read()
        return bool(re.search(r'{config_initialized,\s*true}', content))

def generate_config_file(file_path):
    content = ('% MACHINE GENERATED FILE. DO NOT MODIFY.\n'
               '% Use overlay.config for custom configuration.\n\n'
               '[{onepanel, [{config_initialized, true}')

    advertise_address = os.environ.get('ONEPANEL_ADVERTISE_ADDRESS')
    if advertise_address:
        content += ',\n{{advertise_address, "{0}"}}'.format(advertise_address)

    generate_test_web_cert = os.environ.get('ONEPANEL_GENERATE_TEST_WEB_CERT')
    if generate_test_web_cert:
        domain = os.environ.get('ONEPANEL_GENERATED_CERT_DOMAIN')
        flag = 'true' if generate_test_web_cert == 'true' else 'false'
        content += ',\n{{generate_test_web_cert, {0}}}'.format(flag)
        content += ',\n{{test_web_cert_domain, "{0}"}}'.format(domain)

    trust_test_ca = os.environ.get('ONEPANEL_TRUST_TEST_CA')
    if trust_test_ca:
        flag = 'true' if trust_test_ca == 'true' else 'false'
        content += ',\n{{treat_test_ca_as_trusted, {0}}}'.format(flag)

    content += '\n]}].'

    with open(file_path, 'w') as f:
        f.write(content)

def start_onepanel():
    log('Starting op_panel...')
    with open(os.devnull, 'w') as null:
        if os.environ.get(ONEPANEL_OVERRIDE):
            sp.check_call([os.path.join(os.environ.get(ONEPANEL_OVERRIDE),
                           "_build/default/rel/op_panel/bin/op_panel"),
                           'start'])
        else:
            sp.check_call(['service', 'op_panel', 'start'], stdout=null,
                          stderr=null)

    wait_for_rest_listener()
    log('[  OK  ] op_panel started')

def wait_for_rest_listener():
    first = True
    connected = False
    while not connected:
        try:
            requests.get('https://127.0.0.1:9443/api/v3/onepanel/', verify=False)
        except requests.ConnectionError:
            if first:
                log('Waiting for op_panel server to be available\n'
                    '(may require starting other cluster nodes)\n')
                first = False
            time.sleep(1)
        else:
            connected = True

def format_step(step):
    service, action = step.split(':')
    return '* {0}: {1}'.format(service, action)

def get_users(config):
    users_config = config.get('onepanel', {}).get('users', {})
    users = [('admin', 'password')]

    for username, props in users_config.items():
        if props.get('userRole', '') == 'admin':
            users.append((username, props.get('password', '')))

    return users

def do_request(users, request, *args, **kwargs):
    for (username, password) in users:
        r = request(*args, auth=(username, password), **kwargs)
        if r.status_code != 401 and r.status_code != 403:
            return r

    raise AuthenticationException('Authorization error.\n'
                     'Please ensure that valid admin credentials are present\n'
                     'in the onepanel.users section of the configuration.')

def get_batch_config():
    batch_config = os.environ.get('ONEPROVIDER_CONFIG', '')
    batch_config = yaml.load(batch_config)
    if not batch_config:
        return {}

    # insert interactiveDeployment mark if not present
    onepanel_config = batch_config.get('onepanel', {})
    if 'interactiveDeployment' not in onepanel_config:
        onepanel_config['interactiveDeployment'] = False
        batch_config['onepanel'] = onepanel_config

    return batch_config

# returns False if configuration was skipped because of existing deployment
def configure(config):
    users = get_users(config)
    r = do_request(users, requests.post,
                   'https://127.0.0.1:9443/api/v3/onepanel/provider/configuration',
                   headers={'content-type': 'application/x-yaml'},
                   data=yaml.dump(config),
                   verify=False)

    if r.status_code == 409:
        return False

    if r.status_code != 201 and r.status_code != 204:
        raise ValueError(
            'Failed to start configuration process, the response was:\n'
            '  code: {0}\n'
            '  body: {1}\n'
            'For more information please check the logs.'.format(r.status_code,
                                                                 r.text))
    loc = r.headers['location']
    status = 'running'
    steps = []
    resp = {}

    log('\nConfiguring oneprovider:')
    while status == 'running':
        r = do_request(users, requests.get,
                       'https://127.0.0.1:9443' + loc,
                       verify=False)
        if r.status_code != 200:
            raise ValueError('Unexpected configuration error\n{0}'
                             'For more information please check the logs.'.format(r.text))
        else:
            resp = json.loads(r.text)
            status = resp.get('status', 'error')
            for step in resp.get('steps', []):
                if steps and step == steps[0]:
                    steps = steps[1:]
                else:
                    log(format_step(step))
            steps = resp.get('steps', [])
            time.sleep(1)

    if status != 'ok':
        raise ValueError('Error: {error}\nDescription: {description}\n'
                         'Module: {module}\nFunction: {function}\nDetails by host: {hosts}\n'
                         'For more information please check the logs.'.format(
            error=resp.get('error', 'unknown'),
            description=resp.get('description', '-'),
            module=resp.get('module', '-'),
            function=resp.get('function', '-'),
            hosts=format_error_hosts(resp.get('hosts', {}))))
    return True

def format_error_hosts(hosts):
    s = '\n'
    for host, details in hosts.iteritems():
        description = textwrap.fill(details.get('description', ''),
                                    initial_indent='\t', subsequent_indent='\t')
        s = s + '* {host}\n\t{error}:\n{description}\n'.format(
            host=host, error=details.get('error', ''), description=description)
    return s

# Throws on connection nerror
def wait_for_workers(config):
    url = 'https://127.0.0.1:9443/api/v3/onepanel/provider/nagios'
    while not nagios_up(url, config):
        time.sleep(1)

def nagios_up(url, config):
    users = get_users(config)

    try:
        r = do_request(users, requests.get, url, verify=False)
        if r.status_code != requests.codes.ok:
            return False

        healthdata = eTree.fromstring(r.text)
        return healthdata.attrib['status'] == 'ok'
    except ValueError:
        log("Cannot track cluster start progress since there are no valid "
            "credentials in batch configuration")

def get_container_id():
    with open('/proc/self/cgroup', 'r') as f:
        return f.readline().split('/')[-1].rstrip('\n')

def inspect_container(container_id):
    try:
        result = sp.check_output(['curl', '-s', '--unix-socket',
                                  '/var/run/docker.sock',
                                  'http:/containers/{0}/json'.
                                 format(container_id)])
        return json.loads(result)
    except Exception:
        return {}

def show_ip_address(json):
    ip = '-'
    try:
        ip = sp.check_output(['hostname', '-i']).rstrip('\n')
        ip = json['NetworkSettings']['Networks'].items()[0][1]['IPAddress']
    except Exception:
        pass
    log('* IP Address: {0}'.format(ip))

def show_ports(json):
    ports = json.get('NetworkSettings', {}).get('Ports', {})
    ports_format = []
    for container_port in ports:
        host = ports[container_port]
        if host:
            for host_port in host:
                ports_format.append('{0}:{1} -> {2}'.format(host_port['HostIp'],
                                                            host_port[
                                                                'HostPort'],
                                                            container_port))
        else:
            ports_format.append(container_port)
    ports_str = '\n         '.join(ports_format) if ports_format else '-'
    log('* Ports: {0}'.format(ports_str))

def show_details():
    log('\nContainer details:')

    container_id = get_container_id()
    json = inspect_container(container_id)

    show_ip_address(json)
    show_ports(json)

def infinite_loop(log_level):
    logs = []
    if log_level in LOG_LEVELS:
        log('\nLogging on \'{0}\' level:'.format(log_level))
        for log_prefix, log_dir in LOGS:
            log_file = os.path.join(log_dir, log_level + '.log')
            logs.append((log_prefix, log_file, None, None))

    while True:
        logs = print_logs(logs)
        time.sleep(1)

def print_logs(logs):
    new_logs = []

    for log_prefix, log_file, log_fd, log_ino in logs:
        try:
            if os.stat(log_file).st_ino != log_ino:
                if log_fd:
                    log_fd.close()
                log_fd = open(log_file, 'r')
                log_ino = os.stat(log_file).st_ino

            log_line = log_fd.readline()
            while log_line:
                log('{0} {1}'.format(log_prefix, log_line), end='')
                log_line = log_fd.readline()

            new_logs.append((log_prefix, log_file, log_fd, log_ino))
        except:
            new_logs.append((log_prefix, log_file, None, None))

    return new_logs

if __name__ == '__main__':
    try:
        sp.call(['/root/persistence-dir.py', '--copy-missing-files'])

        if os.environ.get(ONEPANEL_OVERRIDE):
            app_config_path = os.path.join(os.environ.get(ONEPANEL_OVERRIDE),
                                           GENERATED_CONFIG_SOURCES_PATH)

            vm_args_path = os.path.join(os.environ.get(ONEPANEL_OVERRIDE),
                                        VM_ARGS_SOURCES_PATH)
        else:
            app_config_path = GENERATED_CONFIG_PACKAGES_PATH
            vm_args_path = VM_ARGS_PACKAGES_PATH

        if not config_file_initialized(app_config_path):
            generate_config_file(app_config_path)

        set_node_name(vm_args_path)

        start_onepanel()

        batch_mode = os.environ.get('ONEPANEL_BATCH_MODE', 'false')
        if batch_mode.lower() == 'true':
            batch_config = get_batch_config()
            try:
                if configure(batch_config):
                    log('\nCongratulations! New oneprovider deployment successfully started.')
                else:
                    log("\nWaiting for existing cluster to start...")
                    wait_for_workers(batch_config)
                    log('Existing oneprovider deployment resumed work.')
            except AuthenticationException as e:
                log('The launch script cannot access onepanel to manage the deployment process.\n'
                    'Please ensure that valid admin credentials are present\n'
                    'in the onepanel.users section of the configuration\n'
                    'or oversee the cluster status manually.')

        show_details()

    except Exception as e:
        log('\n{0}'.format(e))
        if os.environ.get('ONEPANEL_DEBUG_MODE', 'false').lower() == 'true':
            pass
        else:
            sys.exit(1)

    log_level = os.environ.get('ONEPANEL_LOG_LEVEL', 'info').lower()

    infinite_loop(log_level)


import praw
import shutil
import requests
import urllib
import os

from settings import config

image_extentions = ['.jpg','.jpeg','.png']

class RedditScraper:
    def __init__(self, client_id, client_secret, user_agent, subreddits_list, limit):
        self.client_id = client_id
        self.client_secret = client_secret
        self.user_agent = user_agent
        self.subreddits_list = subreddits_list
        self.limit = limit
        self.bot = praw.Reddit(client_id=self.client_id,client_secret=self.client_secret,user_agent=self.user_agent)
        print("Reddit Image Scan Bot Initialized!")

    def collect_img(self):
        #self.all = self.reddit.subreddit('nocontextpics').top(limit=10)
        print('collecting data...')
        image_extentions = ['.jpg','.jpeg','.png']
        for subreddit_name in self.subreddits_list:
            self.image_urls = []
            self.image_ids = []
            subreddit = self.bot.subreddit(subreddit_name)
            posts = subreddit.hot(limit = self.limit)
            for post in posts:
                _, ext = os.path.splitext(post.url)
                if ext in image_extentions:
                    self.image_urls.append(post.url)
                    self.image_ids.append(post.id)
            self.save(subreddit=subreddit_name)

    def save(self, subreddit):
        print('Writing data to disk..')
        image_extentions = ['.jpg','.jpeg','.png']
        dirpath = os.path.join('./', subreddit)
        if not os.path.exists(dirpath):
            os.mkdir(dirpath)

        if(len(self.image_ids) > 0):
            images_path = os.path.join(dirpath, 'images/')
            if not os.path.exists(images_path):
                os.mkdir(images_path)

        for index, url in enumerate(self.image_urls):
            _, ext = os.path.splitext(url)
            print(str(self.image_urls[index]))
            if ext in image_extentions:
                try:
                    print ('downloading', self.image_urls[index])
                    urllib.request.urlretrieve(self.image_urls[index], images_path + self.image_ids[index] + ext)
                except:
                    print('something went wrong while downloading this', self.image_urls[index])
        print('finished writing data')
def main():
    reddit_bot = RedditScraper(config.client_id,config.client_secret,config.user_agent,['nocontextpics', 'pics'], 1)
    reddit_bot.collect_img()

if __name__ == "__main__":
    main()


from PIL import Image

def contraste(ruta):
    imagen = Image.open(ruta)
    pixels = imagen.load()

    anchura = imagen.width
    altura= imagen.height
    maximo = 0
    minimo = 10000000
    for x in range(0,anchura):
        for y in range(0,altura):
            color = imagen.getpixel((x,y))
            gris = round((color[0]+color[1]+color[2])/3)
            if gris > maximo:
                maximo = gris
            if gris < minimo:
                minimo = gris
    print("maximo:"+str(maximo))
    print("mínimo:"+str(minimo))
    pedestal = minimo
    multiplo = 255/(maximo-minimo)
    for x in range(0,anchura):
        for y in range(0,altura):
            color = imagen.getpixel((x,y))
            pixels[x,y] = (
                round((color[0]-pedestal)*multiplo),
                round((color[1]-pedestal)*multiplo),
                round((color[2]-pedestal)*multiplo)
                )

    imagen.save(ruta)
    imagen.close()

contraste("foto.jpg")