from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf

# pylint: disable=no-name-in-module
from tensorflow.python.framework import tensor_shape
from tensorflow.python.keras.layers import Wrapper
from tensorflow.python.layers.convolutional import Conv1D
from tensorflow.python.ops import variable_scope
from tensorflow.python.keras.engine.base_layer import Layer
from tensorflow.python.eager import context
from tensorflow.python.ops import nn_impl
from tensorflow.python.keras import initializers
from tensorflow.python.keras.engine.base_layer import InputSpec
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import ops

# ***NOTE***: The WeightNorm Class is copied from this PR:
# https://github.com/tensorflow/tensorflow/issues/14070
# Once this becomes part of the official TF release, it will be removed
class WeightNorm(Wrapper):
    """This wrapper reparameterizes a layer by decoupling the weight's
    magnitude and direction. This speeds up convergence by improving the
    conditioning of the optimization problem.

    Weight Normalization: A Simple Reparameterization to Accelerate
    Training of Deep Neural Networks: https://arxiv.org/abs/1602.07868
    Tim Salimans, Diederik P. Kingma (2016)

    WeightNorm wrapper works for keras and tf layers.

    ```python
      net = WeightNorm(tf.keras.layers.Conv2D(2, 2, activation='relu'),
             input_shape=(32, 32, 3), data_init=True)(x)
      net = WeightNorm(tf.keras.layers.Conv2D(16, 5, activation='relu'),
                       data_init=True)
      net = WeightNorm(tf.keras.layers.Dense(120, activation='relu'),
                       data_init=True)(net)
      net = WeightNorm(tf.keras.layers.Dense(n_classes),
                       data_init=True)(net)
    ```

    Arguments:
      layer: a layer instance.
      data_init: If `True` use data dependent variable initialization

    Raises:
      ValueError: If not initialized with a `Layer` instance.
      ValueError: If `Layer` does not contain a `kernel` of weights
      NotImplementedError: If `data_init` is True and running graph execution
    """

    def __init__(self, layer, data_init=False, **kwargs):
        if not isinstance(layer, Layer):
            raise ValueError(
                "Please initialize `WeightNorm` layer with a "
                "`Layer` instance. You passed: {input}".format(input=layer)
            )

        if not context.executing_eagerly() and data_init:
            raise NotImplementedError(
                "Data dependent variable initialization is not available for " "graph execution"
            )

        self.initialized = True
        if data_init:
            self.initialized = False

        self.layer_depth = None
        self.norm_axes = None
        super(WeightNorm, self).__init__(layer, **kwargs)
        self._track_trackable(layer, name="layer")

    def _compute_weights(self):
        """Generate weights by combining the direction of weight vector
        with it's norm"""
        with variable_scope.variable_scope("compute_weights"):
            self.layer.kernel = (
                nn_impl.l2_normalize(self.layer.v, axis=self.norm_axes) * self.layer.g
            )

    def _init_norm(self, weights):
        """Set the norm of the weight vector"""
        from tensorflow.python.ops.linalg_ops import norm

        with variable_scope.variable_scope("init_norm"):
            # pylint: disable=no-member
            flat = array_ops.reshape(weights, [-1, self.layer_depth])
            # pylint: disable=no-member
            return array_ops.reshape(norm(flat, axis=0), (self.layer_depth,))

    def _data_dep_init(self, inputs):
        """Data dependent initialization for eager execution"""
        from tensorflow.python.ops.nn import moments
        from tensorflow.python.ops.math_ops import sqrt

        with variable_scope.variable_scope("data_dep_init"):
            # Generate data dependent init values
            activation = self.layer.activation
            self.layer.activation = None
            x_init = self.layer.call(inputs)
            m_init, v_init = moments(x_init, self.norm_axes)
            scale_init = 1.0 / sqrt(v_init + 1e-10)

        # Assign data dependent init values
        self.layer.g = self.layer.g * scale_init
        self.layer.bias = -1 * m_init * scale_init
        self.layer.activation = activation
        self.initialized = True

    # pylint: disable=signature-differs
    def build(self, input_shape):
        """Build `Layer`"""
        input_shape = tensor_shape.TensorShape(input_shape).as_list()
        self.input_spec = InputSpec(shape=input_shape)

        if not self.layer.built:
            self.layer.build(input_shape)
            self.layer.built = False

            if not hasattr(self.layer, "kernel"):
                raise ValueError(
                    "`WeightNorm` must wrap a layer that" " contains a `kernel` for weights"
                )

            # The kernel's filter or unit dimension is -1
            self.layer_depth = int(self.layer.kernel.shape[-1])
            self.norm_axes = list(range(self.layer.kernel.shape.ndims - 1))

            self.layer.v = self.layer.kernel
            self.layer.g = self.layer.add_variable(
                name="g",
                shape=(self.layer_depth,),
                initializer=initializers.get("ones"),
                dtype=self.layer.kernel.dtype,
                trainable=True,
            )

            with ops.control_dependencies([self.layer.g.assign(self._init_norm(self.layer.v))]):
                self._compute_weights()

            self.layer.built = True

        super(WeightNorm, self).build()
        self.built = True

    # pylint: disable=arguments-differ
    def call(self, inputs):
        """Call `Layer`"""
        if context.executing_eagerly():
            if not self.initialized:
                self._data_dep_init(inputs)
            self._compute_weights()  # Recompute weights for each forward pass

        output = self.layer.call(inputs)
        return output

    def compute_output_shape(self, input_shape):
        return tensor_shape.TensorShape(self.layer.compute_output_shape(input_shape).as_list())

class TCN:
    """
    This class defines core TCN architecture.
    This is only the base class, training strategy is not implemented.
    """

    def __init__(self, max_len, n_features_in, hidden_sizes, kernel_size=7, dropout=0.2):
        """
        To use this class,
            1. Inherit this class
            2. Define the training losses in build_train_graph()
            3. Define the training strategy in run()
            4. After the inherited class object is initialized,
               call build_train_graph followed by run

        Args:
            max_len: Maximum length of sequence
            n_features_in: Number of input features (dimensions)
            hidden_sizes: Number of hidden sizes in each layer of TCN (same for all layers)
            kernel_size: Kernel size of convolution filter (same for all layers)
            dropout: Dropout, fraction of activations to drop
        """
        self.max_len = max_len
        self.n_features_in = n_features_in
        self.hidden_sizes = hidden_sizes
        self.kernel_size = kernel_size
        self.dropout = dropout
        self.n_hidden_layers = len(self.hidden_sizes)
        receptive_field_len = self.calculate_receptive_field()
        if receptive_field_len < self.max_len:
            print(
                "Warning! receptive field of the TCN: "
                "%d is less than the input sequence length: %d."
                % (receptive_field_len, self.max_len)
            )
        else:
            print(
                "Receptive field of the TCN: %d, input sequence length: %d."
                % (receptive_field_len, self.max_len)
            )
        self.layer_activations = []

        # toggle this for train/inference mode
        self.training_mode = tf.placeholder(tf.bool, name="training_mode")

        self.sequence_output = None

    def calculate_receptive_field(self):
        """

        Returns:

        """
        return 1 + 2 * (self.kernel_size - 1) * (2 ** self.n_hidden_layers - 1)

    def build_network_graph(self, x, last_timepoint=False):
        """
        Given the input placeholder x, build the entire TCN graph
        Args:
            x: Input placeholder
            last_timepoint: Whether or not to select only the last timepoint to output

        Returns:
            output of the TCN
        """
        # loop and define multiple residual blocks
        with tf.variable_scope("tcn"):
            for i in range(self.n_hidden_layers):
                dilation_size = 2 ** i
                in_channels = self.n_features_in if i == 0 else self.hidden_sizes[i - 1]
                out_channels = self.hidden_sizes[i]
                with tf.variable_scope("residual_block_" + str(i)):
                    x = self._residual_block(
                        x,
                        in_channels,
                        out_channels,
                        dilation_size,
                        (self.kernel_size - 1) * dilation_size,
                    )
                    x = tf.nn.relu(x)
                self.layer_activations.append(x)
            self.sequence_output = x

            # get outputs
            if not last_timepoint:
                prediction = self.sequence_output
            else:
                # last time point size (batch_size, hidden_sizes_encoder)
                width = self.sequence_output.shape[1].value
                lt = tf.squeeze(
                    tf.slice(self.sequence_output, [0, width - 1, 0], [-1, 1, -1]), axis=1
                )
                prediction = tf.layers.Dense(
                    1,
                    kernel_initializer=tf.initializers.random_normal(0, 0.01),
                    bias_initializer=tf.initializers.random_normal(0, 0.01),
                )(lt)

        return prediction

    def _residual_block(self, x, in_channels, out_channels, dilation, padding):
        """
        Defines the residual block
        Args:
            x: Input tensor to residual block
            in_channels: Number of input features (dimensions)
            out_channels: Number of output features (dimensions)
            dilation: Dilation rate
            padding: Padding value

        Returns:
            Output of residual path
        """
        xin = x
        # define two temporal blocks
        for i in range(2):
            with tf.variable_scope("temporal_block_" + str(i)):
                x = self._temporal_block(x, out_channels, dilation, padding)

        # sidepath
        if in_channels != out_channels:
            x_side = tf.layers.Conv1D(
                filters=out_channels,
                kernel_size=1,
                padding="same",
                strides=1,
                activation=None,
                dilation_rate=1,
                kernel_initializer=tf.initializers.random_normal(0, 0.01),
                bias_initializer=tf.initializers.random_normal(0, 0.01),
            )(xin)
        else:
            x_side = xin

        # combine both
        return tf.add(x, x_side)

    def _temporal_block(self, x, out_channels, dilation, padding):
        """
        Defines the temporal block, which is a dilated causual conv layer,
        followed by relu and dropout
        Args:
            x: Input to temporal block
            out_channels: Number of conv filters
            dilation: dilation rate
            padding: padding value

        Returns:
            Tensor output of temporal block
        """
        # conv layer
        x = self._dilated_causal_conv(x, out_channels, dilation, padding)

        x = tf.nn.relu(x)

        # dropout
        batch_size = tf.shape(x)[0]
        x = tf.layers.dropout(
            x,
            rate=self.dropout,
            noise_shape=[batch_size, 1, out_channels],
            training=self.training_mode,
        )

        return x

    # define model
    def _dilated_causal_conv(self, x, n_filters, dilation, padding):
        """
        Defines dilated causal convolution
        Args:
            x: Input activation
            n_filters: Number of convolution filters
            dilation: Dilation rate
            padding: padding value

        Returns:
            Tensor output of convolution
        """
        input_width = x.shape[1].value
        with tf.variable_scope("dilated_causal_conv"):
            # define dilated convolution layer with left side padding
            x = tf.pad(x, tf.constant([[0, 0], [padding, 0], [0, 0]]), "CONSTANT")
            x = WeightNorm(
                Conv1D(
                    filters=n_filters,
                    kernel_size=self.kernel_size,
                    padding="valid",
                    strides=1,
                    activation=None,
                    dilation_rate=dilation,
                    kernel_initializer=tf.initializers.random_normal(0, 0.01),
                    bias_initializer=tf.initializers.random_normal(0, 0.01),
                )
            )(x)

        assert x.shape[1].value == input_width

        return x

    def build_train_graph(self, *args, **kwargs):
        """
        Placeholder for defining training losses and metrics
        """
        raise NotImplementedError("Error! losses for training must be defined")

    def run(self, *args, **kwargs):
        """
        Placeholder for defining training strategy
        """
        raise NotImplementedError("Error! training routine must be defined")

class CommonLayers:
    """
    Class that contains the common layers for language modeling -
            word embeddings and projection layer
    """

    def __init__(self):
        """
        Initialize class
        """
        self.word_embeddings_tf = None
        self.num_words = None
        self.n_features_in = None

    def define_input_layer(
        self, input_placeholder_tokens, word_embeddings, embeddings_trainable=True
    ):
        """
        Define the input word embedding layer
        Args:
            input_placeholder_tokens: tf.placeholder, input to the model
            word_embeddings: numpy array (optional), to initialize the embeddings with
            embeddings_trainable: boolean, whether or not to train the embedding table

        Returns:
            Embeddings corresponding to the data in input placeholder
        """
        with tf.device("/cpu:0"):
            with tf.variable_scope("embedding_layer", reuse=False):
                if word_embeddings is None:
                    initializer = tf.initializers.random_normal(0, 0.01)
                else:
                    initializer = tf.constant_initializer(word_embeddings)
                self.word_embeddings_tf = tf.get_variable(
                    "embedding_table",
                    shape=[self.num_words, self.n_features_in],
                    initializer=initializer,
                    trainable=embeddings_trainable,
                )

                input_embeddings = tf.nn.embedding_lookup(
                    self.word_embeddings_tf, input_placeholder_tokens
                )
        return input_embeddings

    def define_projection_layer(self, prediction, tied_weights=True):
        """
        Define the output word embedding layer
        Args:
            prediction: tf.tensor, the prediction from the model
            tied_weights: boolean, whether or not to tie weights from the input embedding layer

        Returns:
            Probability distribution over vocabulary
        """
        with tf.device("/cpu:0"):
            if tied_weights:
                # tie projection layer and embedding layer
                with tf.variable_scope("embedding_layer", reuse=tf.AUTO_REUSE):
                    softmax_w = tf.matrix_transpose(self.word_embeddings_tf)
                    softmax_b = tf.get_variable("softmax_b", [self.num_words])
                    _, l, k = prediction.shape.as_list()
                    prediction_reshaped = tf.reshape(prediction, [-1, k])
                    mult_out = tf.nn.bias_add(tf.matmul(prediction_reshaped, softmax_w), softmax_b)
                    projection_out = tf.reshape(mult_out, [-1, l, self.num_words])
            else:
                with tf.variable_scope("projection_layer", reuse=False):
                    projection_out = tf.layers.Dense(self.num_words)(prediction)
        return projection_out


#!/usr/bin/env python3

# pyre-strict

import asyncio
import logging
import sys
from typing import Any, Union

import click

__version__ = "0.6.9"
LOG: logging.Logger = logging.getLogger(__name__)

def _handle_debug(
    ctx: Union[click.core.Context, None],
    param: Union[click.core.Option, click.core.Parameter, None],
    debug: Union[bool, int, str],
) -> Union[bool, int, str]:
    """Turn on debugging if asked otherwise INFO default"""
    log_level = logging.DEBUG if debug else logging.INFO
    logging.basicConfig(
        format="[%(asctime)s] %(levelname)s: %(message)s (%(filename)s:%(lineno)d)",
        level=log_level,
    )
    return debug

async def async_main(debug: bool) -> int:
    return 0

# Some typing stub issue I can't work out - https://github.com/pallets/click/issues/2558
# Fix for 8.1.6 dosen't seem to fix me - To look into
@click.command(context_settings={"help_option_names": ["-h", "--help"]})  # type: ignore
@click.option(
    "--debug",
    is_flag=True,
    callback=_handle_debug,
    show_default=True,
    help="Turn on debug logging",
)
@click.pass_context
def main(ctx: click.core.Context, **kwargs: Any) -> None:
    LOG.debug(f"Starting {sys.argv[0]}")
    ctx.exit(asyncio.run(async_main(**kwargs)))

if __name__ == "__main__":  # pragma: no cover
    main()


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        def iter(l1, l2, remain):
            if l1 == None and l2 == None and remain == 0: return None
            n1 = l1.val if l1 else 0
            n2 = l2.val if l2 else 0
            sum = n1+n2+remain
            node1 = l1.next if l1 else None
            node2 = l2.next if l2 else None
            return ListNode(sum%10,iter(node1, node2, sum//10))

        return iter(l1,l2,0)


#!/usr/bin/python
# -*- coding: utf-8 -*-
""" @brief  Precision and Recall
    @ref    https://en.wikipedia.org/wiki/Precision_and_recall
            Modified from https://github.com/lyst/lightfm and https://github.com/jfkirk/tensorrec
    @author <ariel kalingking> akalingking@gmail.com """
import numpy as np
import pandas as pd
from scipy import sparse

__all__ = ["precision_at_k", "recall_at_k", "rank_matrix"]

def rank_matrix(mat):
    assert isinstance(mat, (np.ndarray,))
    mat_ = pd.DataFrame(data=mat)
    mat_ = mat_.rank(axis=1, ascending=False)
    return mat_.values

def precision_at_k(predicted_ranks, interactions, k=10, preserve_rows=False):
    assert isinstance(interactions, (sparse.coo_matrix, sparse.csr_matrix))
    assert isinstance(predicted_ranks, (np.ndarray,))

    relevant = interactions > 0
    ranks = sparse.csr_matrix(predicted_ranks * relevant.A)
    ranks.data = np.less(ranks.data, (k + 1), ranks.data)

    precision = np.squeeze(np.array(ranks.sum(axis=1))).astype(float) / k

    if not preserve_rows:
        precision = precision[relevant.getnnz(axis=1) > 0]

    return precision.mean()

def recall_at_k(predicted_ranks, interactions, k=10, preserve_rows=False):
    assert isinstance(interactions, (sparse.coo_matrix, sparse.csr_matrix))
    assert isinstance(predicted_ranks, (np.ndarray,))

    relevant = interactions > 0
    ranks = sparse.csr_matrix(predicted_ranks * relevant.A)
    ranks.data = np.less(ranks.data, (k + 1), ranks.data)
    retrieved = np.squeeze(relevant.getnnz(axis=1))
    hit = np.squeeze(np.array(ranks.sum(axis=1)))

    if not preserve_rows:
        hit = hit[relevant.getnnz(axis=1) > 0]
        retrieved = retrieved[relevant.getnnz(axis=1) > 0]

    return (hit.astype(float) / retrieved.astype(float)).mean()


import logging

import cv2
import numpy

from inquire.detection.ButtonState import ButtonState
from inquire.detection.RecognizedElement import RecognizedElement

try:
    from robot.api.logger import info

    robot_logger = True
except ImportError:
    robot_logger = False
    logging.basicConfig(level=logging.INFO)

class TextElement(RecognizedElement):
    """
    TextElement Class. It's used to store the information about the found Text, like it's state,...
    """

    def __init__(self, text: str | None,
                 image: numpy.ndarray,
                 rectangle: tuple = (0, 0, 0, 0),
                 confidence: float | None = None,
                 colours: list | None = None,
                 state: ButtonState | None = None,
                 binary_image: numpy.ndarray | None = None,
                 render_bin: int = 0):
        super().__init__(image=image,
                         rectangle=rectangle,
                         confidence=confidence,
                         colours=colours,
                         state=state,
                         binary_image=binary_image,
                         render_bin=render_bin)
        self.text = text

    def __str__(self):
        if self.rectangle != (0, 0, 0, 0):
            return f'({self.text}, conf:{self.confidence}, rec:{self.rectangle})'
        else:
            return f'({self.text}, conf:{self.confidence})'

    def __repr__(self):
        return self.__str__()

    @staticmethod
    def concatenate_horizontal(img_list: list[numpy.ndarray]) -> numpy.ndarray:
        h_min = min(img.shape[0] for img in img_list)
        im_list_resize = []
        for img in img_list:
            if img.size == 0:
                if robot_logger:
                    info(f'textelement merging encountered empty fields', html=True)
                else:
                    logging.info(f'textelement merging encountered empty fields')
                continue
            width = int(img.shape[1] * h_min / img.shape[0])
            resized_img = cv2.resize(img, (width, h_min), interpolation=cv2.INTER_CUBIC)
            im_list_resize.append(resized_img)
        # im_list_resize = [cv2.resize(img, (int(img.shape[1] * h_min / img.shape[0]), h_min),
        #                              interpolation=cv2.INTER_CUBIC)
        #                   for img in img_list]
        concat = cv2.hconcat(im_list_resize)
        return concat

    def do_they_align_horizontally(self, element: 'TextElement') -> bool:
        if (element.rectangle[1] + element.rectangle[3] < self.rectangle[1]) or (
                element.rectangle[1] > self.rectangle[1] + self.rectangle[3]):
            return False
        else:
            return True

    def do_they_align_vertically(self, element: 'TextElement') -> bool:
        if (element.rectangle[0] + element.rectangle[2] < self.rectangle[0]) or (
                element.rectangle[0] > self.rectangle[0] + self.rectangle[2]):
            return False
        else:
            return True

    def append_text_element(self, element: 'TextElement') -> None:
        """
        TODO img, rectangle
        Append the text and confidence level of the given text element to the current one. (Merges)
        :param element: Another TextElement to append
        :type element: TextElement
        :return:
        :rtype: None
        """
        if element.text is not None:
            self.text += " " + element.text
        if element.confidence is not None:
            self.confidence = (self.confidence + element.confidence) / 2
        self.rectangle = (min(self.rectangle[0], element.rectangle[0]),
                          min(self.rectangle[1], element.rectangle[1]),
                          self.rectangle[2] + element.rectangle[2],
                          self.rectangle[3] + element.rectangle[3])
        self.image = self.concatenate_horizontal([self.image, element.image])


from selectivesearch import selective_search as ss

def selective_search(image):
    """A wrapper for the selective_search function in the selectivesearch
    library with fixed parameters.

    Returns a set of tuples (x, y, w, h) corresponding to candidate
    locations of objects in the input image.
    """
    regions = ss(image, scale=400, sigma=0.5, min_size=256)[1]
    candidates = set()
    for region in regions:
        if region["rect"] in candidates:
            continue

        # ignore elongated areas
        x, y, w, h = region["rect"]
        if w/h > 1.2 or h/w > 1.2:
            continue

        candidates.add(region["rect"])

    return candidates


from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import landing_page.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            landing_page.routing.websocket_urlpatterns
        )
    ),
})
# Channels
#ASGI_APPLICATION = 'sitotest.routing.application'


import os
import bpy
from mathutils import Vector
import numpy as np

import sys
sys.path.append('.')
from blender import BlenderWrapper

class BlenderHelper(BlenderWrapper):

    def __init__(self):
        super().__init__()

        self.set_transparent_background()
        self.set_image_size(1800, 1090)

    ########################################################################
    ##                            Camera                                  ##
    ########################################################################
    def point_camera_to_origin(self):
        direction = (Vector((0.0, 0.0, 0.0)) - self.cam.location).normalized()
        euler_direction = direction.to_track_quat('-Z', 'Y').to_euler()

        if self.camera_roll is not None:
            euler_direction[0] = self.camera_roll
        if self.camera_pitch is not None:
            euler_direction[1] = self.camera_pitch
        if self.camera_yaw is not None:
            euler_direction[2] = self.camera_yaw

        self.set_cam_rotation(euler_direction)

    ########################################################################
    ##                             Image                                  ##
    ########################################################################
    def set_transparent_background(self):
        self.scene.render.image_settings.color_mode = 'RGBA'
        self.scene.render.film_transparent = True

        world = self.scene.world
        world_tree = bpy.data.worlds[world.name].node_tree
        background_node = world_tree.nodes.new("ShaderNodeBackground")

        background_node.inputs[0].default_value = (1, 1, 1, 0)

    ########################################################################
    ##                                UV                                  ##
    ########################################################################
    def fit_uv_to_bounds(self, active_ob=None):
        if active_ob is None:
            active_ob = self.obj_list[-1]

        self.select_object(active_ob)
        self.toggle_object_edit_mode()
        self.select_all_uv()
        bpy.ops.uv.pack_islands()
        self.deselect_all_uv()
        self.deselect_all_objects()

    def save_uv_layout(self, image_name, active_ob=None):
        if active_ob is None:
            active_ob = self.obj_list[-1]

        self.select_object(active_ob)
        self.toggle_object_edit_mode()
        bpy.ops.uv.export_layout(filepath=image_name, export_all=True, opacity=0.0)
        self.deselect_all_objects()

    def scale_uv_coords(self, scale, axis, mapping_node_name='mapping'):
        mapping_node = self.nodes[mapping_node_name]
        mapping_node.inputs['Scale'].default_value[axis] = scale

    def rotate_uv_coords(self, rotation, axis, mapping_node_name='mapping'):
        mapping_node = self.nodes[mapping_node_name]
        mapping_node.inputs['Rotation'].default_value[axis] = rotation

    def flip_uv(self, axis='x', active_ob=None):
        if active_ob is None:
            active_ob = self.obj_list[-1]

        self.select_object(active_ob)
        self.toggle_object_edit_mode()
        # self.select_all_uv()

        if axis == 'x':
            axis_rotation = (True, False, False)
        elif axis == 'y':
            axis_rotation = (False, True, False)

        bpy.ops.transform.mirror(constraint_axis=axis_rotation)

        # self.deselect_all_uv()
        self.deselect_all_objects()

    ########################################################################
    ##                          Checkerboard                              ##
    ########################################################################
    def attach_checkerboard_texture(self, checkerboard_type='color'):

        if checkerboard_type == 'color':
            image_type = 'COLOR_GRID'
        else:
            image_type = 'UV_GRID'

        self.set_color_by_texture()

        material = self.create_new_material('checkerboard_mat')

        texture_node    = self.create_node(name='texture', type='ShaderNodeTexImage', material=material)
        mapping_node    = self.create_node(name='mapping', type='ShaderNodeMapping', material=material)
        text_coord_node = self.create_node(name='texcoord', type='ShaderNodeTexCoord', material=material)

        shader_inputs = self.get_shader_inputs(material=material, shader_name='Principled BSDF')

        self.link_nodes(material, shader_inputs['Base Color'], texture_node.outputs["Color"])
        self.link_nodes(material, text_coord_node.outputs['UV'], mapping_node.inputs['Location'])
        self.link_nodes(material, mapping_node.outputs['Vector'], texture_node.inputs['Vector'])

        mapping_node.vector_type = 'TEXTURE'
        image = self.create_new_image(name='uv_texture', type=image_type)
        texture_node.image = image

        self.attach_material_to_object(material, self.obj_list[-1])

    def save_texture_image(self, filename, image_name='uv_texture'):
        image = self.images[image_name]
        image.save_render(filename)

    ########################################################################
    ##                          Rendering                                 ##
    ########################################################################
    def render_views_rotating(self, file_prefix, num_view=10, up_axis='Y'):
        rotation_step = 2.0 * np.pi /num_view
        for i in range(num_view):
            bpy.ops.transform.rotate(value=rotation_step, orient_axis=up_axis)
            filename = '{}_{}_{:02}.png'.format(file_prefix, up_axis, i)
            self.render(filename)

    ########################################################################


# Задание №7

import json

with open("lesson_5_hw_77.json", "w") as j_file:
    with open("lesson_5_hw_7.txt", "r") as f_o:
        subjects = {}
        middle = {}
        k, o = 0, 0
        line = f_o.read().split("\n")
        for i in line:
            i = i.split()
            profit = int(i[2]) - int(i[3])
            subjects[i[0]] = profit
            if profit > 0:
                k += profit
                o += 1
            middle["avegare"] = k / o
        all_list = [subjects, middle]
    json.dump(all_list, j_file)


def plot_heat_tree(heatmap_file, tree_file, output_file=None):
    '''
    Plot heatmap next to a tree. The order of the heatmap **MUST** be the same,
    as order of the leafs on the tree. The tree must be in the Newick format. If
    *output_file* is specified, then heat-tree will be rendered as a PNG,
    otherwise interactive browser will pop-up with your heat-tree.

    Parameters
    ----------
    heatmap_file: str
        Path to the heatmap file. The first row must have '#Names' as first
        element of the header.
            e.g. #Names, A, B, C, D
                row1, 2, 4, 0, 4
                row2, 4, 6, 2, -1

    tree_file: str
        Path to the tree file in Newick format. The leaf node labels should
        be the same as as row names in the heatmap file. E.g. row1, row2.

    output_file: str, optional
        If specified the heat-tree will be rendered in that file as a PNG image,
        otherwise interactive browser will pop-up. **N.B.** program will wait
        for you to exit the browser before continuing.
    '''
    import numpy

    from ete2.treeview.faces import add_face_to_node
    from ete2 import ClusterTree, TreeStyle, AttrFace, ProfileFace

    # To operate with numbers efficiently

    # Loads tree and array
    t = ClusterTree(tree_file, heatmap_file)

    # nodes are linked to the array table
    array =  t.arraytable

    # Calculates some stats on the matrix. Needed to establish the color
    # gradients.
    matrix_dist = [i for r in xrange(len(array.matrix))\
                   for i in array.matrix[r] if numpy.isfinite(i)]
    matrix_max = numpy.max(matrix_dist)
    matrix_min = numpy.min(matrix_dist)
    matrix_avg = matrix_min+((matrix_max-matrix_min)/2)

    # Creates a profile face that will represent node's profile as a
    # heatmap
    profileFace  = ProfileFace(matrix_max, matrix_min, matrix_avg, 1000, 14, "heatmap",colorscheme=2)

    nameFace = AttrFace("name", fsize=8)
    # Creates my own layout function that uses previous faces
    def mylayout(node):
        # If node is a leaf
        if node.is_leaf():
            # And a line profile
            add_face_to_node(profileFace, node, 0, aligned=True)
            node.img_style["size"]=0
            add_face_to_node(nameFace, node, 1, aligned=True)

    # Use my layout to visualize the tree
    ts = TreeStyle()
    ts.layout_fn = mylayout
    t.show(tree_style=ts)

heatmap = 'heatmap.txt'
tree_file = 'eg.tree'
plot_heat_tree(heatmap, tree_file)


from parlai.core.params import ParlaiParser
from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent
from parlai.core.worlds import create_task
from parlai.utils.conversations import Conversations
from parlai.utils.misc import TimeLogger
import random
import tempfile

def setup_args():
    """
    Set up conversion args.
    """
    parser = ParlaiParser()
    parser.add_argument(
        '-n',
        '--num-episodes',
        default=-1,
        type=int,
        help='Total number of episodes to convert, -1 to convert all examples',
    )
    parser.add_argument(
        '-of',
        '--outfile',
        default=None,
        type=str,
        help='Output file where to save, by default will be created in /tmp',
    )
    parser.add_argument(
        '-s1id', '--speaker-0-id', type=str, help='Speaker id of agent who speaks first'
    )
    parser.add_argument(
        '-s1id',
        '--speaker-1-id',
        type=str,
        help='Speaker id of agent who speaks second',
    )
    parser.add_argument(
        '--prepended-context',
        type='bool',
        default=False,
        help='specify if the context is prepended to the first act',
    )
    parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=10)
    parser.set_defaults(datatype='train:ordered')

    return parser

def dump_data(opt):
    """
    Dump task data to ACUTE-Eval.
    """
    # create repeat label agent and assign it to the specified task
    agent = RepeatLabelAgent(opt)
    world = create_task(opt, agent)
    task = opt.get('task')
    speaker_0_id = opt.get('speaker_0_id') or f'{task}_as_human'
    speaker_1_id = opt.get('speaker_1_id') or f'{task}_as_model'
    if opt['outfile'] is None:
        outfile = tempfile.mkstemp(
            prefix='{}_{}_'.format(opt['task'], opt['datatype']), suffix='.txt'
        )[1]
    else:
        outfile = opt['outfile']

    num_episodes = (
        world.num_episodes()
        if opt['num_episodes'] == -1
        else min(opt['num_episodes'], world.num_episodes())
    )
    log_timer = TimeLogger()

    print(f'[ starting to convert, saving output to {outfile} ]')
    dialogues = []
    for _ in range(num_episodes):
        episode = []
        episode_done = False
        while not episode_done:
            world.parley()
            acts = world.get_acts()
            text = acts[0].get('text')
            split_text = text.split('\n')
            label = random.choice(
                acts[0].get('labels', acts[0].pop('eval_labels', None))
            )
            if not episode and opt.get('prepended_context'):
                # first turn
                context = split_text[:-1]
                text = split_text[-1]
                context_turn = [
                    {'text': context, 'episode_done': False, 'id': 'context'}
                    for _ in range(2)
                ]
                episode.append(context_turn)
            turn = [
                {'text': text, 'episode_done': False, 'id': speaker_0_id},
                {'text': label, 'episode_done': False, 'id': speaker_1_id},
            ]
            episode.append(turn)
            if acts[0].get('episode_done', False):
                episode[-1][-1]['episode_done'] = True
                episode_done = True
                dialogues.append(episode)

            if log_timer.time() > opt['log_every_n_secs']:
                text, _log = log_timer.log(world.total_parleys, world.num_examples())
                print(text)

        if world.epoch_done():
            break

    Conversations.save_conversations(dialogues, outfile, opt)

def main():
    random.seed(42)
    # Get command line arguments
    parser = setup_args()
    opt = parser.parse_args()
    dump_data(opt)

if __name__ == '__main__':
    main()


import torch
import numpy  as np
from dptb.dataprocess.processor import Processor
from dptb.nnet.nntb import NNTB
from dptb.nnsktb.sknet import SKNet
from dptb.sktb.skIntegrals import SKIntegrals
from dptb.sktb.struct_skhs import SKHSLists
from dptb.hamiltonian.hamil_eig_sk_crt import HamilEig
from dptb.utils.constants import dtype_dict
from dptb.structure.structure import BaseStruct
from dptb.utils.tools import nnsk_correction
from abc import ABC, abstractmethod

from dptb.utils.index_mapping import Index_Mapings

from dptb.nnsktb.integralFunc import SKintHops
from dptb.nnsktb.onsiteFunc import onsiteFunc, loadOnsite
from dptb.nnsktb.skintTypes import all_skint_types, all_onsite_intgrl_types

class ModelAPI(ABC):
    def __init__(self) -> None:
        pass

    @abstractmethod
    def get_HR(self,**kwargs):
        pass

    @abstractmethod
    def get_HK(self, **kwargs):
        pass

    @abstractmethod
    def get_eigenvalues(self, **kwargs):
        pass

class DeePTB(ModelAPI):
    def __init__(self, dptb_checkpoint:str, proj_atom_anglr_m:dict,
                            sktbmode:str='nnsk', nnsk_checkpoint:str = None, sk_file_path=None):
        f=torch.load(dptb_checkpoint)
        model_config = f["model_config"]
        self.nntb = NNTB(**model_config)
        self.nntb.tb_net.load_state_dict(f['state_dict'])
        self.nntb.tb_net.eval()

        self.sktbmode = sktbmode
        self.unitenergy = model_config.get('unit','Hartree')

        if sktbmode == 'nnsk':
            f = torch.load(nnsk_checkpoint)
            model_config = f["model_config"]
            self.sknet = SKNet(**model_config)
            self.sknet.load_state_dict(f['state_dict'])
            self.sknet.eval()
            #for p in self.sknet.parameters():
            #    p.requires_grad = False

            indmap = Index_Mapings(proj_atom_anglr_m)
            bond_index_map, bond_num_hops =  indmap.Bond_Ind_Mapings()
            onsite_index_map, onsite_num = indmap.Onsite_Ind_Mapings()

            self.hops_fun = SKintHops(mode=model_config.get("skformula", "powerlaw"))
            self.onsite_db = loadOnsite(onsite_index_map)
            all_skint_types_dict, reducted_skint_types, self.sk_bond_ind_dict = all_skint_types(bond_index_map)

        else:
            skint = SKIntegrals(proj_atom_anglr_m = proj_atom_anglr_m, sk_file_path=sk_file_path)
            self.skhslist = SKHSLists(skint,dtype='tensor')
        self.hamileig = HamilEig(dtype=dtype_dict[model_config["dtype"]])

        self.if_HR_ready=False

    def get_HR(self, structure, env_cutoff, device='cpu', dtype=torch.float32):
        assert isinstance(structure, BaseStruct)
        self.structure = structure
        self.time_symm = structure.time_symm
        predict_process = Processor(mode='dptb', structure_list=structure, batchsize=1, kpoint=None, eigen_list=None, env_cutoff=env_cutoff, device=device, dtype=dtype)
        bond, bond_onsite = predict_process.get_bond()
        env = predict_process.get_env()
        batched_dcp = self.nntb.get_desciptor(env)
        # get hoppings (SK type bond integrals.)
        batch_bond_hoppings, batch_hoppings = self.nntb.hopping(batched_dcp=batched_dcp, batch_bond=bond)
        # get onsite energies
        batch_bond_onsites, batch_onsiteEs = self.nntb.onsite(batched_dcp=batched_dcp)

        if self.sktbmode == 'nnsk':
            coeffdict = self.sknet()
            sktb_onsiteEs = onsiteFunc(batch_bond_onsites, self.onsite_db)
            sktb_hoppings = self.hops_fun.get_skhops(batch_bond_hoppings, coeffdict, self.sk_bond_ind_dict)

            # combine the nn and sk part for the hamiltonian.
            onsiteEs, hoppings, onsiteSs, overlaps = \
                            nnsk_correction(nn_onsiteEs=batch_onsiteEs[0],
                                            nn_hoppings=batch_hoppings[0],
                                            sk_onsiteEs=sktb_onsiteEs[0],
                                            sk_hoppings=sktb_hoppings[0])
        else:
            # get the sk parameters.
            self.skhslist.update_struct(structure)
            self.skhslist.get_HS_list(bonds_onsite=np.asarray(batch_bond_onsites[0][:,1:]),
                                                bonds_hoppings=np.asarray(batch_bond_hoppings[0][:,1:]))
            # combine the nn and sk part for the hamiltonian.
            onsiteEs, hoppings, onsiteSs, overlaps = \
                            nnsk_correction(nn_onsiteEs=batch_onsiteEs[0],
                                            nn_hoppings=batch_hoppings[0],
                                            sk_onsiteEs=self.skhslist.onsiteEs,
                                            sk_hoppings=self.skhslist.hoppings,
                                            sk_onsiteSs=self.skhslist.onsiteSs,
                                            sk_overlaps=self.skhslist.overlaps)

        self.hamileig.update_hs_list(structure, hoppings, onsiteEs, overlaps, onsiteSs)
        self.hamileig.get_hs_blocks(bonds_onsite=np.asarray(batch_bond_onsites[0][:,1:]),
                                        bonds_hoppings=np.asarray(batch_bond_hoppings[0][:,1:]))

        self.if_HR_ready=True
        if not self.hamileig.use_orthogonal_basis:
            return self.hamileig.all_bonds, self.hamileig.hamil_blocks, None
        else:
            return self.hamileig.all_bonds, self.hamileig.hamil_blocks, self.hamileig.overlap_blocks

    # ToDo 现在版本的程序对于正交基和非正交基组的情况有些不兼容的地方。后续要修改！
    def get_HK(self, kpoints):
        assert self.if_HR_ready

        if not self.hamileig.use_orthogonal_basis:
            hkmat =  self.hamileig.hs_block_R2k(kpoints=kpoints, HorS='H', time_symm=self.time_symm, dtype=self.hamileig.dtype)
            skmat =  self.hamileig.hs_block_R2k(kpoints=kpoints, HorS='S', time_symm=self.time_symm, dtype=self.hamileig.dtype)
        else:
            hkmat =  self.hamileig.hs_block_R2k(kpoints=kpoints, HorS='H', time_symm=self.time_symm, dtype=self.hamileig.dtype)
            skmat = torch.eye(hkmat.shape[1], dtype=torch.complex64).unsqueeze(0).repeat(hkmat.shape[0], 1, 1)
        return hkmat, skmat

    def get_eigenvalues(self,kpoints,spindeg=2):
        assert self.if_HR_ready
        eigenvalues,_ = self.hamileig.Eigenvalues(kpoints, time_symm=self.time_symm,dtype=self.hamileig.dtype, unit=self.unitenergy)
        eigks = eigenvalues.detach().numpy()

        num_el = np.sum(self.structure.proj_atom_neles_per)
        nk = len(kpoints)
        numek = num_el * nk // spindeg
        sorteigs =  np.sort(np.reshape(eigks,[-1]))
        EF=(sorteigs[numek] + sorteigs[numek-1])/2
        return eigks, EF

class NNSK(ModelAPI):
    def __init__(self,checkpoint, proj_atom_anglr_m):
        f=torch.load(checkpoint)
        model_config = f["model_config"]
        self.onsitemode =  model_config['onsitemode']
        self.onsite_cutoff = model_config.get('onsite_cutoff',0.)
        self.model = SKNet(**model_config)
        self.model.load_state_dict(f['state_dict'])
        self.sk_options = f.get("sk_options", None)
        self.model.eval()
        self.unitenergy = model_config.get('unit', 'Hartree')

        if self.sk_options is not None:
            self.skformula = self.sk_options["skformula"]
            self.sk_cutoff = self.sk_options["sk_cutoff"]
            self.sk_decay_w = self.sk_options["sk_decay_w"]
        else:
            self.skformula = "varTang96"
            self.sk_cutoff = torch.tensor(6.0)
            self.sk_decay_w = torch.tensor(0.1)

        self.indmap = Index_Mapings(proj_atom_anglr_m)
        bond_index_map, bond_num_hops =  self.indmap.Bond_Ind_Mapings()
        self.onsite_strain_index_map, onsite_strain_num, onsite_index_map, onsite_num = self.indmap.Onsite_Ind_Mapings(onsitemode=self.onsitemode, atomtype=model_config.get("atom_type"))

        self.hops_fun = SKintHops(mode=self.skformula)
        self.onsite_db = loadOnsite(onsite_index_map)
        all_skint_types_dict, reducted_skint_types, self.sk_bond_ind_dict = all_skint_types(bond_index_map)

        self.hamileig = HamilEig(dtype=dtype_dict[model_config["dtype"]])
        self.if_HR_ready=False

    def get_HR(self, structure, device='cpu', dtype=torch.float32):
        assert isinstance(structure, BaseStruct)
        assert structure.onsitemode == self.onsitemode
        self.structure = structure
        self.time_symm = structure.time_symm
        predict_process = Processor(structure_list=structure, batchsize=1, kpoint=None, eigen_list=None, device=device, dtype=dtype,
        env_cutoff=self.onsite_cutoff, onsitemode=self.onsitemode, onsite_cutoff=self.onsite_cutoff, sorted_onsite="st", sorted_bond="st", sorted_env="st")

        batch_bond, batch_bond_onsites = predict_process.get_bond(sorted="st")
        if self.onsitemode == 'strain':
            batch_envs = predict_process.get_env(sorted="st")
            nn_onsiteE, onsite_coeffdict = self.model(mode='onsite')
            all_onsiteint_types_dcit, reducted_onsiteint_types, self.onsite_strain_ind_dict = all_onsite_intgrl_types(self.onsite_strain_index_map)
            batch_onsiteVs = self.hops_fun.get_skhops(batch_bonds=batch_envs, coeff_paras=onsite_coeffdict, sk_bond_ind=self.onsite_strain_ind_dict)
            batch_onsiteEs = onsiteFunc(batch_bonds_onsite=batch_bond_onsites, onsite_db=self.onsite_db, nn_onsiteE=None)

        else:
            nn_onsiteE, onsite_coeffdict = self.model(mode='onsite')
            batch_onsiteEs = onsiteFunc(batch_bonds_onsite=batch_bond_onsites, onsite_db=self.onsite_db, nn_onsiteE=nn_onsiteE)

        coeffdict = self.model(mode='hopping')
        batch_hoppings = self.hops_fun.get_skhops(batch_bonds=batch_bond, coeff_paras=coeffdict, sk_bond_ind=self.sk_bond_ind_dict, rcut=self.sk_cutoff, w=self.sk_decay_w)
        onsiteEs, hoppings = batch_onsiteEs[0], batch_hoppings[0]
        if self.onsitemode == 'strain':
            onsiteVs = batch_onsiteVs[0]
            self.hamileig.update_hs_list(struct=structure, hoppings=hoppings, onsiteEs=onsiteEs, onsiteVs=onsiteVs)
            self.hamileig.get_hs_blocks(bonds_onsite=np.asarray(batch_bond_onsites[0][:,1:]),
                                        bonds_hoppings=np.asarray(batch_bond[0][:,1:]),
                                        onsite_envs=np.asarray(batch_envs[0][:,1:]))
        else:
            self.hamileig.update_hs_list(struct=structure, hoppings=hoppings, onsiteEs=onsiteEs)
            self.hamileig.get_hs_blocks(bonds_onsite=np.asarray(batch_bond_onsites[0][:,1:]),
                                            bonds_hoppings=np.asarray(batch_bond[0][:,1:]))

        self.if_HR_ready=True

        if not self.hamileig.use_orthogonal_basis:
            return self.hamileig.all_bonds, self.hamileig.hamil_blocks, None
        else:
            return self.hamileig.all_bonds, self.hamileig.hamil_blocks, self.hamileig.overlap_blocks

    def get_HK(self, kpoints):
        assert self.if_HR_ready

        if not self.hamileig.use_orthogonal_basis:
            hkmat =  self.hamileig.hs_block_R2k(kpoints=kpoints, HorS='H', time_symm=self.time_symm)
            skmat =  self.hamileig.hs_block_R2k(kpoints=kpoints, HorS='S', time_symm=self.time_symm)
        else:
            hkmat =  self.hamileig.hs_block_R2k(kpoints=kpoints, HorS='H', time_symm=self.time_symm)
            skmat = torch.eye(hkmat.shape[1], dtype=torch.complex64).unsqueeze(0).repeat(hkmat.shape[0], 1, 1)
        return hkmat, skmat

    def get_eigenvalues(self,kpoints,spindeg=2):
        assert self.if_HR_ready
        eigenvalues,_ = self.hamileig.Eigenvalues(kpoints, time_symm=self.time_symm, dtype=self.hamileig.dtype, unit=self.unitenergy)
        eigks = eigenvalues.detach().numpy()

        num_el = np.sum(self.structure.proj_atom_neles_per)
        nk = len(kpoints)
        numek = num_el * nk // spindeg
        sorteigs =  np.sort(np.reshape(eigks,[-1]))
        EF=(sorteigs[numek] + sorteigs[numek-1])/2
        return eigks, EF


# -*- coding: utf-8 -*-
"""
Created on Mon May 09 08:58:28 2016

@author: Jonatan
"""

from __future__ import division
from spider_plot_2 import *

def p2h_spider():
    """ Make a spider plot where the different scenarios are compared
    for different scenarios.
    """

    d = Drawing(400, 400)
    sp = SpiderChart()
    sp.x = 50
    sp.y = 50
    sp.width = 300
    sp.height = 300
    sp.data = [[1, 2, 3], [8, 3, 5], [5, 9, 1]]
    sp.labels = ['Base case', 'Hydro min = 0', 'With accumulation']
    sp.strands.strokeWidth
    d.add(sp)
    return d

if __name__ == '__main__':
    d = p2h_spider()
    from reportlab.graphics.renderPDF import drawToFile
    drawToFile(d, 'p2h_spider.pdf')


import cv2
import numpy as np

img1 = cv2.imread('pratica02/cameraman.tif', cv2.IMREAD_UNCHANGED)
img2 = cv2.imread('pratica02/morangos.tif', cv2.IMREAD_UNCHANGED)

imgCinza = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

# python exibe em BGR => B=0 G=1 R=2
red2 = (img2[:, :, 2])
blue2 = (img2[:, :, 0])
green2 = (img2[:, :, 1])
stacked = np.dstack((blue2, green2, red2))
print(red2.dtype, blue2.dtype, green2.dtype)
x, y, channels = img2.shape
average = np.zeros((x, y))

# extracting the mean pixel per pixel on each of RGB channels. the mean of the channels translate into the grayscale image

for i in range(x):
    for j in range(y):
        average[i, j] = (int(red2[i, j]) +
                         int(blue2[i, j]) + int(green2[i, j]))/3

# same approach but way simpler using numpy.mean

imgCinzaMean = np.uint8(np.mean(img2, axis=2))

average = np.uint8(average)

# the 3 should look exactly the same
cv2.imshow('original grayscale img', imgCinza)
cv2.imshow('gray image using for loop', average)
cv2.imshow('gray image using np.mean', imgCinzaMean)
cv2.waitKey(0)


from hx711 import HX711
from time import sleep, strftime
from datetime import datetime, timedelta
from datetime import timezone
from output import Output
import numpy
import os
import logging

fileRW = Output()

logger = logging.getLogger(__name__)

class sensor:
    def __init__(self):
        # Sets up scales
        global hx
        self.No_Tare = False
        hx = HX711(5, 6)
        hx.set_reading_format("LSB", "MSB")
        hx.set_reference_unit(451)  # calibrated on 1000g
        hx.reset()
        hx.tare()

        check = os.path.isfile("/home/pi/weight.csv")  # checks if file exists
        if check == False:
            open("/home/pi/weight.csv", "x")  # if not creates file
        check = os.path.isfile("/home/pi/tare_weight.csv")  # checks if file exists
        # removed file checking as w+ method creates
    def tare_weight(self):
        hx.store_offset() # store the offset in a file
        return

    def get_time(self):
        d = datetime.now(timezone.utc)
        x = d.strftime("%Y %m %d %H %M %S")
        logger.debug("Raw time: %s", d)
        logger.debug("Refined time: %s", x)
        return x

    def read(self):
        val = hx.get_weight_no_tare(5) # use stored data
        # reslove zero values for negatives
        if val < 0:
            val = 0
        t = self.get_time()# false removed no debugging
        tup_weight = (t, val)
        hx.power_down()
        hx.power_up()
        logger.debug("Data: %s", val)
        logger.debug("Combined: %s", tup_weight)
        sleep(0.5)
        return tup_weight

    def write(self, filename, iterations=10):
        i = 0
        while i <= iterations:
            data = self.read()
            logger.debug("Data to write: %s", data)
            fileRW.write("/home/pi/" + filename, data)  # append
            i += 1
            logger.debug("this is the iteration: %s", i)

    def avrg(self, readfile, writefile):
        # declarations
        sum_count = 0  # declare before sum_count
        valid_number = 0  # decalare before use to avoid negative division
        count = True
        starttime = ""  # declare before use to avoid undeclared error
        times = fileRW.read("/home/pi/" + readfile, 0)
        data = fileRW.read("/home/pi/" + readfile, 1)
        start = times[0]  # set to 1st time incase no weight readings
        data_array = numpy.array(data).astype(numpy.float)
        # find the mean
        numpy_average = numpy.median(data_array)  # Complete avarage
        Q1 = numpy.percentile(data_array, 25, interpolation='midpoint') # quarter at 25%
        Q3 = numpy.percentile(data_array, 75, interpolation='midpoint')
        logger.debug("Median is... %s", numpy_average)
        logger.debug("Q1 value is .... %s", Q1)
        logger.debug("Q3 value is .... %s", Q3)
        j = 0
        for i in numpy.nditer(data_array):  # why data array when data is list ??
            if i > Q1 and i < Q3 :  # Only use values in IQR
                sum_count = sum_count + i  # count the sum
                valid_number = valid_number + 1  # count the number
                if count == True:  # need to get index of i then lookup timestamp
                    start = times[j]
                    count = False
                logger.debug(i)
            else:
                logger.debug("Do not use")
            j += 1
        if valid_number == 0:
            # check for zero division
            valid_number = 1
            starttime = datetime.strptime(
                start, "%Y %m %d %H %M %S"
            )  # 1st item in list times
        # calculate averages
        sp_average = sum_count / valid_number  # gives average weight of hedgehog
        tup_weight_refined = ("Average Weight", start, "%.2f" % sp_average)
        fileRW.write("/home/pi/" + writefile, tup_weight_refined)
        # delete file after use to give clean start for next average
        os.remove("/home/pi/" + readfile)
        logger.debug(sum_count)
        logger.debug(valid_number)
        logger.debug("The real average is: %s", sp_average)
        logger.debug("Start time is: %s", starttime)
        logger.debug("The combined data is: %s", tup_weight_refined)
        return tup_weight_refined  # http post this value


import os

from tests.e2e.terraform.alicloud.testing import _test_template

root = os.path.dirname(os.path.abspath(__file__))
tf_plan_path = os.path.join(root, "main.tfplan")

tpl = {
    "ROSTemplateFormatVersion": "2015-09-01",
    "Resources": {
        "alicloud_ecs_activation.example": {
            "Type": "ALIYUN::ECS::Activation",
            "Properties": {
                "Description": "terraform-example",
                "InstanceCount": 10,
                "InstanceName": "terraform-example",
                "IpAddressRange": "0.0.0.0/0",
                "TimeToLiveInHours": 4,
            },
        }
    },
}

def test_template():
    t = _test_template(root, tf_plan_path)
    assert t == tpl


from matplotlib import pyplot as plt
import scipy.stats as spstats

from loomio import *
from socialchoice import *
from timeseries import *

legend_fontsize = 7

formats = ['.-', 's-']
markersizes = [9, 5]

class NetDelib(object):

    def __init__(self):
        self.plot_mean = False

    def plot_errorbar(self, data, data_labels, ylabel, title):
        for i, d in enumerate(data):
            if self.plot_mean:
                y = d.mean()
            else:
                y = d.y()
            plt.errorbar(range(4), y, yerr=d.yerr95(), label=data_labels[i], capsize=6)
        plt.xticks(range(4))
        plt.xlabel('Round')
        plt.ylabel(ylabel)
        plt.grid()
        plt.legend(fontsize=legend_fontsize)
        plt.title(title)

    def plot(self, data, data_labels, ylabel, title, ylim=None):
        for i, d in enumerate(data):
            if self.plot_mean:
                y = d.mean()
            else:
                y = d.y()
            plt.plot(range(4), y, formats[i], label=data_labels[i], markersize=markersizes[i])
        plt.xticks(range(4))
        plt.xlabel('Round')
        plt.ylabel(ylabel)
        if ylim:
            plt.ylim(ylim)
        plt.grid()
        plt.legend(fontsize=legend_fontsize)
        plt.title(title)

    def plot_kendall(self, ylim=None):
        self.plot(
            [self.kendall_control, self.kendall_random],
            ['Control', 'Random-Pod'],
            'Kendall Correlation',
            self.title + ' (Kendall)', ylim=ylim)

    def plot_spearman(self, ylim=None):
        self.plot(
            [self.spearman_control, self.spearman_random],
            ['Control', 'Random-Pod'],
            'Spearman Correlation',
            self.title + ' (Spearman)', ylim=ylim)

    def plot_ballot(self, ylim=None):
        self.plot(
            [self.ballot_control, self.ballot_random],
            ['Control', 'Random-Pod'],
            'Ballot Correlation',
            self.title + ' (Ballot)', ylim=ylim)

    def plot_crossing(self, ylim=None):
        self.plot(
            [self.crossing_control, self.crossing_random],
            ['Control', 'Random-Pod'],
            'Crossing Correlation',
            self.title + ' (Crossing)', ylim=ylim)

    def plot_tideman(self, ylim=None):
        self.plot(
            [self.tideman_control, self.tideman_random],
            ['Control', 'Random-Pod'],
            'Tideman Fraction',
            self.title + ' (Tideman)', ylim=ylim)

class NetDelibAgreement(NetDelib):

    def __init__(self, df_score):

        super().__init__()

        self.title = 'Agreement'
        self.bootstrap_runs = 0

        self.control_profiles = [
            Profile.from_score(df_score[(df_score.stage == stage) & (df_score.treatment == 1)])
            for stage in sorted(set(df_score.stage))]

        self.random_profiles = [
            Profile.from_score(df_score[(df_score.stage == stage) & (df_score.treatment == 2)])
            for stage in sorted(set(df_score.stage))]

        self.kendall_control = TimeSeriesResult()
        self.spearman_control = TimeSeriesResult()
        self.tideman_control = TimeSeriesResult()
        self.ballot_control = TimeSeriesResult()
        self.crossing_control = TimeSeriesResult()

        print('Single Group')
        print('round\tkendall\tspearman\ttideman\tballot\tcrossing')
        for stage, profile in enumerate(self.control_profiles):

            self.kendall_control.add_y(profile.agreement_kendall())
            self.spearman_control.add_y(profile.agreement_spearman())
            self.tideman_control.add_y(Tideman(profile).agreement_tideman())
            self.ballot_control.add_y(profile.agreement_ballot())
            self.crossing_control.add_y(profile.agreement_crossing())

            for run in range(self.bootstrap_runs):
                p = profile.sample_bootstrap()
                self.kendall_control.add_sample(stage, p.agreement_kendall())
                self.spearman_control.add_sample(stage, p.agreement_spearman())
                self.tideman_control.add_sample(stage, Tideman(p).agreement_tideman())
                self.ballot_control.add_sample(stage, p.agreement_ballot())
                self.crossing_control.add_sample(stage, p.agreement_crossing())

            print("{}\t{}\t{}\t{}\t{}\t{}".format(
                stage,
                self.kendall_control.y()[stage],
                self.spearman_control.y()[stage],
                self.tideman_control.y()[stage],
                self.ballot_control.y()[stage],
                self.crossing_control.y()[stage]))

        self.kendall_random = TimeSeriesResult()
        self.spearman_random = TimeSeriesResult()
        self.tideman_random = TimeSeriesResult()
        self.ballot_random = TimeSeriesResult()
        self.crossing_random = TimeSeriesResult()
        print('\nRandom Pod')
        print('round\tkendall\tspearman\ttideman\tballot\tcrossing')
        for stage, profile in enumerate(self.random_profiles):

            self.kendall_random.add_y(profile.agreement_kendall())
            self.spearman_random.add_y(profile.agreement_spearman())
            self.tideman_random.add_y(Tideman(profile).agreement_tideman())
            self.ballot_random.add_y(profile.agreement_ballot())
            self.crossing_random.add_y(profile.agreement_crossing())

            for run in range(self.bootstrap_runs):
                p = profile.sample_bootstrap()
                self.kendall_random.add_sample(stage, p.agreement_kendall())
                self.spearman_random.add_sample(stage, p.agreement_spearman())
                self.tideman_random.add_sample(stage, Tideman(p).agreement_tideman())
                self.ballot_random.add_sample(stage, p.agreement_ballot())
                self.crossing_random.add_sample(stage, p.agreement_crossing())

            print("{}\t{}\t{}\t{}\t{}\t{}".format(
                stage,
                self.kendall_random.y()[stage],
                self.spearman_random.y()[stage],
                self.tideman_random.y()[stage],
                self.ballot_random.y()[stage],
                self.crossing_random.y()[stage]))

class NetDelibInitEvolution(NetDelib):

    def __init__(self, df_score):

        super().__init__()

        self.title = 'Agreement w/ Initial'
        self.bootstrap_runs = 10
        self.plot_mean = True

        df_control = df_score[df_score.treatment == 1]
        df_random = df_score[df_score.treatment == 2]
        self.control_collection = make_preference_sequence_collection(df_control)
        self.random_collection = make_preference_sequence_collection(df_random)

        participant_ids = self.control_collection.participant_ids()
        self.kendall_control = TimeSeriesResult()
        self.spearman_control = TimeSeriesResult()
        self.ballot_control = TimeSeriesResult()
        self.crossover_control = TimeSeriesResult()
        for stage in range(0, 4):
            for participant_id in participant_ids:
                initial_preference = self.control_collection[participant_id][0]
                try:
                    stage_preference = self.control_collection[participant_id][stage]
                    r, p = spstats.kendalltau(initial_preference.ranks(), stage_preference.ranks())
                    self.kendall_control.add_sample(stage, r)
                    r, p = spstats.spearmanr(initial_preference.ranks(), stage_preference.ranks())
                    self.spearman_control.add_sample(stage, r)
                    r = 1 - 2 * initial_preference.ballot_dissimilarity(stage_preference)
                    self.ballot_control.add_sample(stage, r)
                    r = 1 - 2 * initial_preference.crossover_dissimilarity(stage_preference)
                    self.crossover_control.add_sample(stage, r)
                except:
                    continue

        participant_ids = self.random_collection.participant_ids()
        self.kendall_random = TimeSeriesResult()
        self.spearman_random = TimeSeriesResult()
        self.ballot_random = TimeSeriesResult()
        self.crossover_random = TimeSeriesResult()
        for stage in range(0, 4):
            for participant_id in participant_ids:
                initial_preference = self.random_collection[participant_id][0]
                try:
                    stage_preference = self.random_collection[participant_id][stage]
                    r, p = spstats.kendalltau(initial_preference.ranks(), stage_preference.ranks())
                    self.kendall_random.add_sample(stage, r)
                    r, p = spstats.spearmanr(initial_preference.ranks(), stage_preference.ranks())
                    self.spearman_random.add_sample(stage, r)
                    r = 1 - 2 * initial_preference.ballot_dissimilarity(stage_preference)
                    self.ballot_random.add_sample(stage, r)
                    r = 1 - 2 * initial_preference.crossover_dissimilarity(stage_preference)
                except:
                    continue


# 무인도 여행 BFS
from collections import deque
dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)]
score = 0

def bfs(maps, visited, x, y):
    global score
    queue = deque()
    queue.append((x, y))
    visited[x][y] = 0
    score = int(maps[x][y])
    while queue:
        x, y = queue.popleft()
        for d in dirs:
            nx = x+d[0]
            ny = y+d[1]
            if nx < 0 or ny < 0 or nx >= len(visited) or ny >= len(visited[0]):
                continue
            if visited[nx][ny] == 0:
                continue
            if visited[nx][ny] == 1:
                visited[nx][ny] = 0
                score += int(maps[nx][ny])
                queue.append((nx, ny))

def solution(maps):
    global score
    answer = []
    visited = [[0]*len(maps[i]) for i in range(len(maps))]
    for i in range(len(maps)):
        for j in range(len(maps[i])):
            if maps[i][j] != 'X':
                visited[i][j] = 1

    for i in range(len(maps)):
        for j in range(len(maps[i])):
            if visited[i][j] == 1:
                bfs(maps, visited, i, j)
                answer.append(score)
                score = 0
    answer.sort()
    print(answer)
    return [-1] if answer == [] else answer

solution(["X591X", "X1X5X", "X231X", "1XXX1"])


import itertools

N, M = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if (M != 0):
    cd = [list(map(int, input().split())) for _ in range(M)]
else:
    cd = list(list())

groups = list(list())
for i in range(1, N + 1):
    conn_list = [item for item in cd if item[0] == i or item[1] == i]
    if (len(conn_list) == 0):
        conn_list.append([i])
    conn_list = list(set(itertools.chain.from_iterable(conn_list)))
    indexes = [index for index, group in enumerate(
        groups) if not set(conn_list).isdisjoint(set(group))]
    if len(indexes) == 0:
        groups.append([i])
        indexes = [index for index, group in enumerate(
            groups) if not set(conn_list).isdisjoint(set(group))]
    if (len(indexes) > 1):
        for j in range(len(indexes) - 1, 0, -1):
            groups[indexes[0]].extend(groups[indexes[j]])
            groups[indexes[0]] = list(set(groups[indexes[0]]))
            del groups[indexes[j]]
    for item in conn_list:
        groups[indexes[0]].append(item)
        groups[indexes[0]] = list(set(groups[indexes[0]]))

flag = True
for group in groups:
    sum_a = sum([item for index, item in enumerate(a) if index+1 in group])
    sum_b = sum([item for index, item in enumerate(b) if index+1 in group])
    if sum_a != sum_b:
        flag = False
        break

if (flag):
    print('Yes')
else:
    print('No')


from flask import Flask
from flask_restful import Api
from helpers.crossdomain import *
from messenger_webhook import MessengerWebhook

application = Flask(__name__, template_folder='template', static_url_path='/static')
application.config.from_object(__name__)
application.config['SECRET_KEY'] = '1ex13eu103me91i-sdf'
application.url_map.strict_slashes = False
api = Api(application, decorators=[crossdomain(origin="*")])

api.add_resource(
    MessengerWebhook,
    f'/messenger-webhook',
    endpoint=f'/messenger-webhook'
)

def main():
    pass

main()

if __name__ == "__main__":

    print("------------------- Local Application Start ---------------------")
    application.run(host='0.0.0.0', debug=True)


import glob
import re
import traceback
from pathlib import Path
from typing import List, Union

import fitz
import utils
from constants import cmd_output_path
from loguru import logger

def convert_to_image_pdf(doc_path: Union[str, List[str]], dpi: int = 300, page_range: str = "all", output_path: str = None):
    try:
        path_list = []
        if isinstance(doc_path, str):
            if "*" in doc_path:
                path_list = glob.glob(doc_path)
            else:
                path_list = [doc_path]
        elif isinstance(doc_path, list):
            for p in doc_path:
                if "*" in p:
                    path_list.extend(glob.glob(p))
                else:
                    path_list.append(p)
        for path in path_list:
            doc: fitz.Document = fitz.open(path)
            writer: fitz.Document = fitz.open()
            roi_indices = utils.parse_range(page_range, doc.page_count)
            toc = doc.get_toc(simple=True)
            logger.debug(toc)
            for page_index in range(doc.page_count):
                page = doc[page_index]
                new_page = writer.new_page(width=page.rect.width, height=page.rect.height)
                if page_index in roi_indices:
                    pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72))
                    pix.set_dpi(dpi, dpi)
                    new_page.insert_image(new_page.rect, pixmap=pix)
                else:
                    writer.insert_pdf(doc, from_page=page_index, to_page=page_index)
            if output_path is None:
                p = Path(path)
                output_path = str(p.parent / f"{p.stem}-图片型.pdf")
            writer.set_toc(toc)
            writer.ez_save(output_path)
        utils.dump_json(cmd_output_path, {"status": "success", "message": ""})
    except:
        logger.error(traceback.format_exc())
        utils.dump_json(cmd_output_path, {"status": "error", "message": traceback.format_exc()})

def convert_pdf2png(doc_path: str, dpi: int = 300, page_range: str = "all", output_path: str = None):
    try:
        path_list = []
        if isinstance(doc_path, str):
            if "*" in doc_path:
                path_list = glob.glob(doc_path)
            else:
                path_list = [doc_path]
        elif isinstance(doc_path, list):
            for p in doc_path:
                if "*" in p:
                    path_list.extend(glob.glob(p))
                else:
                    path_list.append(p)
        for path in path_list:
            doc: fitz.Document = fitz.open(path)
            roi_indices = utils.parse_range(page_range, doc.page_count)
            p = Path(path)
            if output_path is None:
                output_dir = p.parent / f"{p.stem}-png"
                output_dir.mkdir(exist_ok=True, parents=True)
            else:
                output_dir = Path(output_path)
                output_dir.mkdir(exist_ok=True, parents=True)
            for i in roi_indices:
                page = doc[i]
                pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72))
                pix.set_dpi(dpi, dpi)
                pix.save(str(output_dir / f"{p.stem}-page-{i+1}.png"))
            utils.dump_json(cmd_output_path, {"status": "success", "message": ""})
    except:
        logger.error(traceback.format_exc())
        utils.dump_json(cmd_output_path, {"status": "error", "message": traceback.format_exc()})

def convert_pdf2svg(doc_path: str, dpi: int = 300, page_range: str = "all", output_path: str = None):
    try:
        path_list = []
        if isinstance(doc_path, str):
            if "*" in doc_path:
                path_list = glob.glob(doc_path)
            else:
                path_list = [doc_path]
        elif isinstance(doc_path, list):
            for p in doc_path:
                if "*" in p:
                    path_list.extend(glob.glob(p))
                else:
                    path_list.append(p)
        for path in path_list:
            doc: fitz.Document = fitz.open(path)
            roi_indices = utils.parse_range(page_range, doc.page_count)
            p = Path(path)
            if output_path is None:
                output_dir = p.parent / f"{p.stem}-svg"
                output_dir.mkdir(exist_ok=True, parents=True)
            else:
                output_dir = Path(output_path)
                output_dir.mkdir(exist_ok=True, parents=True)
            for i in roi_indices:
                page = doc[i]
                out = page.get_svg_image(matrix=fitz.Matrix(dpi/72, dpi/72))
                with open(str(output_dir / f"{p.stem}-page-{i+1}.svg"), "w") as f:
                    f.write(out)
            utils.dump_json(cmd_output_path, {"status": "success", "message": ""})
    except:
        logger.error(traceback.format_exc())
        utils.dump_json(cmd_output_path, {"status": "error", "message": traceback.format_exc()})

def convert_svg2pdf(
        input_path: Union[str, List[str]],
        is_merge: bool = True,
        sort_method: str = 'name',
        sort_direction: str = 'asc',
        paper_size: str = "a4",
        orientation: str = "portrait",
        output_path: str = None):
    try:
        path_list = []
        if isinstance(input_path, str):
            if "*" in input_path:
                path_list = glob.glob(input_path)
            else:
                path_list = [input_path]
        elif isinstance(input_path, list):
            for p in input_path:
                if "*" in p:
                    path_list.extend(glob.glob(p))
                else:
                    path_list.append(p)

        if is_merge:
            if output_path is None:
                p = Path(path_list[0])
                output_path = str(p.parent / f"{p.stem}(等)-合并.pdf")
            writer: fitz.Document = fitz.open()
            new_path_list = path_list
            if sort_method == "custom":
                if sort_direction == "asc":
                    pass
                else:
                    new_path_list = new_path_list[::-1]
            elif sort_method == "name":
                if sort_direction == "asc":
                    new_path_list.sort()
                else:
                    new_path_list.sort(reverse=True)
            elif sort_method == "name_digit":
                new_path_list = sorted(new_path_list, key=lambda x: int(re.search(r"\d+$", Path(x).stem).group()))
                if sort_direction == "asc":
                    pass
                else:
                    new_path_list = new_path_list[::-1]
            # create time
            elif sort_method == "ctime":
                if sort_direction == "asc":
                    new_path_list.sort(key=lambda x: Path(x).stat().st_ctime)
                else:
                    new_path_list.sort(key=lambda x: Path(x).stat().st_ctime, reverse=True)
            # modify time
            elif sort_method == "mtime":
                if sort_direction == "asc":
                    new_path_list.sort(key=lambda x: Path(x).stat().st_mtime)
                else:
                    new_path_list.sort(key=lambda x: Path(x).stat().st_mtime, reverse=True)

            for path in new_path_list:
                with open(path, 'r') as f:
                    img = fitz.open(path)
                    if paper_size == "same":
                        w, h = img[0].rect.width, img[0].rect.height
                    else:
                        fmt = fitz.paper_rect(f"{paper_size}-l") if orientation == "landscape" else fitz.paper_rect(paper_size)
                        w, h = fmt.width, fmt.height
                    pdfbytes = img.convert_to_pdf()
                    pdf = fitz.open('pdf', pdfbytes)
                    page = writer.new_page(width=w, height=h)
                    page.show_pdf_page(img[0].rect, pdf, 0)

            writer.save(output_path, garbage=3, deflate=True)
        else:
            if output_path is None:
                p = Path(path_list[0])
                output_dir = p.parent
            else:
                output_dir = Path(output_path)
                output_dir.mkdir(exist_ok=True, parents=True)
            for path in path_list:
                img = fitz.open(path)
                pdfbytes = img.convert_to_pdf()
                pdf = fitz.open('pdf', pdfbytes)
                savepath = str(output_dir / f"{Path(path).stem}.pdf")
                pdf.save(savepath, garbage=3, deflate=True)
        utils.dump_json(cmd_output_path, {"status": "success", "message": ""})
    except:
        logger.error(traceback.format_exc())
        utils.dump_json(cmd_output_path, {"status": "error", "message": traceback.format_exc()})

def convert_png2pdf(**kwargs):
    convert_svg2pdf(**kwargs)

def convert_anydoc2pdf(input_path: str, output_path: str = None):
    """
    supported document types: PDF, XPS, EPUB, MOBI, FB2, CBZ, SVG
    """
    try:
        path_list = []
        if isinstance(input_path, str):
            if "*" in input_path:
                path_list = glob.glob(input_path)
            else:
                path_list = [input_path]
        elif isinstance(input_path, list):
            for p in input_path:
                if "*" in p:
                    path_list.extend(glob.glob(p))
                else:
                    path_list.append(p)
        for path in path_list:
            doc = fitz.open(path)
            b = doc.convert_to_pdf()  # convert to pdf
            pdf = fitz.open("pdf", b)  # open as pdf

            toc= doc.get_toc()  # table of contents of input
            pdf.set_toc(toc)  # simply set it for output
            meta = doc.metadata  # read and set metadata
            if not meta["producer"]:
                meta["producer"] = "PyMuPDF" + fitz.VersionBind

            if not meta["creator"]:
                meta["creator"] = "PyMuPDF PDF converter"
            meta["modDate"] = fitz.get_pdf_now()
            meta["creationDate"] = meta["modDate"]
            pdf.set_metadata(meta)

            # now process the links
            link_cnti = 0
            link_skip = 0
            for pinput in doc:  # iterate through input pages
                links = pinput.get_links()  # get list of links
                link_cnti += len(links)  # count how many
                pout = pdf[pinput.number]  # read corresp. output page
                for l in links:  # iterate though the links
                    if l["kind"] == fitz.LINK_NAMED:  # we do not handle named links
                        logger.info("named link page", pinput.number, l)
                        link_skip += 1  # count them
                        continue
                    pout.insert_link(l)  # simply output the others

            # save the conversion result
            if output_path is None:
                p = Path(path)
                output_path = str(p.parent / f"{p.stem}.pdf")
            pdf.save(output_path, garbage=4, deflate=True)
        utils.dump_json(cmd_output_path, {"status": "success", "message": ""})
    except:
        logger.error(traceback.format_exc())
        utils.dump_json(cmd_output_path, {"status": "error", "message": traceback.format_exc()})


import ROOT
from array import array

def buildMedianProfile(h):
    """build the median profile"""
    medianGr = ROOT.TGraphAsymmErrors()
    medianGr.SetName('{}_medianprof'.format(h.GetName()))
    medianGr.SetLineWidth(2)
    medianGr.SetMarkerStyle(20)

    #median and 1 sigma quantiles
    xq = array('d', [0.16,0.5,0.84])
    #storage for the x values that correspond to the above quantiles
    yq = array('d', [0.0 ,0.0,0.0 ])

    for xbin in xrange(1,h.GetNbinsX()+1):
        tmp=h.ProjectionY('tmp',xbin,xbin)
        tmp.GetQuantiles(3,yq,xq)
        xcen=h.GetXaxis().GetBinCenter(xbin)

        npts=medianGr.GetN()
        medianGr.SetPoint(npts,xcen,yq[1])
        medianGr.SetPointError(npts,0,0,yq[1]-yq[0],yq[2]-yq[1])
        tmp.Delete()
    return medianGr


# 라이브러리

import sys
print(sys.argv)

sys.exit()

print(sys.path)

print(sys.path.append("C:/Users/user/Desktop/python/chap05"))

import pickle
f = open("test.txt", 'wb')
data = {1: 'python', 2: 'you need'}
pickle.dump(data, f)
f.close()

import pickle
f = open("test.txt", 'rb')
data = pickle.load(f)
print(data)

import os
print(os.environ)

print(os.environ['PATH'])

print(os.chdir("C:\WINDOWS"))

print(os.getcwd())

print(os.system("dir"))

import os
f = os.popen("dir")
print(f.read())

import shutil
shutil.copy("test.txt", "test1.txt")


import torch
from torch import nn
from torch.utils.data import  Dataset, DataLoader
from ...base import device

class RandomDataset(Dataset):
    def __init__(self, size, length):
        self.len = length
        self.data = torch.randn(length, size)
    def __getitem__(self, index):
        return self.data[index]
    def __len__(self):
        return self.len

def get_rand_dataloader(dim_input, n_sample, batch_size):
    dataset = RandomDataset(dim_input, n_sample)
    return DataLoader(
        dataset=dataset,
        batch_size=batch_size,
        shuffle=True
    ), dataset

class Model(nn.Module):
    def __init__(self, dim_input, dim_output):
        super(Model, self).__init__()
        self.fc = nn.Linear(dim_input, dim_output)

    def forward(self, input):
        output = self.fc(input)
        print("\tIn Model: input shape", input.size(),
              "output shape", output.size())

        return output

class Hook:
    def __init__(self) -> None:
        self.input = []
    def __call__(self, module, args, out):
        assert isinstance(args, tuple)
        self.input.append(args[0])
        print(len(self.input))

def prepare(
    dim_input=5,
    dim_output=2,
    batch_size=30,
    n_sample=100,
    hooked=False
):
    model = Model(dim_input=dim_input, dim_output=dim_output)
    if hooked:
        for m in model.modules():
            if isinstance(m, nn.Linear):
                m.register_forward_hook(Hook())
    dataloader, dataset = get_rand_dataloader(dim_input=dim_input, n_sample=n_sample, batch_size=batch_size)
    return model, dataloader, dataset


from tkinter import Tk, StringVar, Label

def set_keysym(event):
    keysym.set(event.keysym)

root = Tk()
root.bind('<Key>', set_keysym)

keysym = StringVar()

label = Label(root)
label.configure(textvariable=keysym)
label.pack()

root.mainloop()


import boto3
import logging
import os

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def str2bool(value):
    return value.lower() in ("True",True,"False",False)

def lambda_handler(event, context):
    torun = event['torun']

    if torun == "true":
        awsregion = os.environ['AWS_REGION']

        dbservice = event['dbservice']
        cluster = event['cluster']
        dbinstance = event['dbinstance']
        application = event['application']
        environment = event['environment']
        dbclass = event['dbclass']
        engine = event['engine']
        subgrp = event['subgrp']
        dbparamgrp = event['dbparamgrp']
        autominor = str2bool(event['autominor'])
        copytagstosnap = str2bool(event['copytagstosnap'])
        enhancedmon = str2bool(event['enhancedmon'])
        perfinsights = str2bool(event['perfinsights'])

        cluster = event['cluster']

        tempdbinstance = dbinstance + "temp"

        rdsclient = boto3.client('rds', region_name=awsregion)

        if dbservice == 'aurora':
            if enhancedmon == "True" and perfinsights == "False":
                enhancedmoninterval = event['enhancedmoninterval']
                enhancedmonrolearn = event['enhancedmonrolearn']

                response = rdsclient.create_db_instance(
                    DBInstanceIdentifier=tempdbinstance,
                    DBInstanceClass=dbclass,
                    Engine=engine,
                    DBSubnetGroupName=subgrp,
                    DBParameterGroupName=dbparamgrp,
                    AutoMinorVersionUpgrade=autominor,
                    PubliclyAccessible=False,
                    Tags=[
                        {
                            'Key': 'refresh-application',
                            'Value': application
                        },
                        {
                            'Key': 'refresh-environment',
                            'Value': environment
                        },
                        {
                            'Key': 'refresh-instance',
                            'Value': 'to_modify_after_rename'
                        },
                        {
                            'Key': 'refresh',
                            'Value': 'true'
                        }
                    ],
                    DBClusterIdentifier=cluster,
                    MonitoringInterval=enhancedmoninterval,
                    MonitoringRoleArn=enhancedmonrolearn,
                    CopyTagsToSnapshot=copytagstosnap
                )
            elif enhancedmon == "True" and perfinsights == "True":
                enhancedmoninterval = event['enhancedmoninterval']
                enhancedmonrolearn = event['enhancedmonrolearn']

                perfinsightsretention = event['perfinsightsretention']
                perfinsightskmskeyid = event['perfinsightskmskeyid']

                response = rdsclient.create_db_instance(
                    DBInstanceIdentifier=tempdbinstance,
                    DBInstanceClass=dbclass,
                    Engine=engine,
                    DBSubnetGroupName=subgrp,
                    DBParameterGroupName=dbparamgrp,
                    AutoMinorVersionUpgrade=autominor,
                    PubliclyAccessible=False,
                    Tags=[
                        {
                            'Key': 'refresh-application',
                            'Value': application
                        },
                        {
                            'Key': 'refresh-environment',
                            'Value': environment
                        },
                        {
                            'Key': 'refresh-instance',
                            'Value': 'to_modify_after_rename'
                        },
                        {
                            'Key': 'refresh',
                            'Value': 'true'
                        }
                    ],
                    DBClusterIdentifier=cluster,
                    MonitoringInterval=enhancedmoninterval,
                    MonitoringRoleArn=enhancedmonrolearn,
                    EnablePerformanceInsights=perfinsights,
                    PerformanceInsightsRetentionPeriod=perfinsightsretention,
                    PerformanceInsightsKMSKeyId=perfinsightskmskeyid,
                    CopyTagsToSnapshot=copytagstosnap
                )
            elif enhancedmon == "False" and perfinsights == "True":
                perfinsightsretention = event['perfinsightsretention']
                perfinsightskmskeyid = event['perfinsightskmskeyid']

                response = rdsclient.create_db_instance(
                    DBInstanceIdentifier=tempdbinstance,
                    DBInstanceClass=dbclass,
                    Engine=engine,
                    DBSubnetGroupName=subgrp,
                    DBParameterGroupName=dbparamgrp,
                    AutoMinorVersionUpgrade=autominor,
                    PubliclyAccessible=False,
                    Tags=[
                        {
                            'Key': 'refresh-application',
                            'Value': application
                        },
                        {
                            'Key': 'refresh-environment',
                            'Value': environment
                        },
                        {
                            'Key': 'refresh-instance',
                            'Value': 'to_modify_after_rename'
                        },
                        {
                            'Key': 'refresh',
                            'Value': 'true'
                        }
                    ],
                    DBClusterIdentifier=cluster,
                    EnablePerformanceInsights=perfinsights,
                    PerformanceInsightsRetentionPeriod=perfinsightsretention,
                    PerformanceInsightsKMSKeyId=perfinsightskmskeyid,
                    CopyTagsToSnapshot=copytagstosnap
                )
            else:
                response = rdsclient.create_db_instance(
                    DBInstanceIdentifier=tempdbinstance,
                    DBInstanceClass=dbclass,
                    Engine=engine,
                    DBSubnetGroupName=subgrp,
                    DBParameterGroupName=dbparamgrp,
                    AutoMinorVersionUpgrade=autominor,
                    PubliclyAccessible=False,
                    Tags=[
                        {
                            'Key': 'refresh-application',
                            'Value': application
                        },
                        {
                            'Key': 'refresh-environment',
                            'Value': environment
                        },
                        {
                            'Key': 'refresh-instance',
                            'Value': 'to_modify_after_rename'
                        },
                        {
                            'Key': 'refresh',
                            'Value': 'true'
                        }
                    ],
                    DBClusterIdentifier=cluster,
                    CopyTagsToSnapshot=copytagstosnap
                )

            result = "Instance creation initiated"
        else:
            raise ValueError("Database service specified unknown or not supported by this function")

        return {
            "statusCode": 200,
            "body": result
        }

    else:
        result = "Instance creation skipped"

        return {
            "statusCode": 200,
            "body": result
        }


from student import Student
from course import Course
from teacher import Teacher
import bisect
import pickle

# Opening students.dat to populate students[] -- if this throws an error for you, run initialize_data.py to fix it
with open("students.dat", "rb") as fp:
    students = pickle.load(fp)

# Opening teachers.dat to populate teachers[]
with open("teachers.dat", "rb") as fp:
    teachers = pickle.load(fp)

logged_in = students[6]
print(logged_in.fname)

logged_in.addCourse(Course("Bio1"))
logged_in.addCourse(Course("Math1"))
logged_in.addCourse(Course("Chess1"))
students[5].addCourse(Course("Bio1"))
students[1].addCourse(Course("Bio1"))
students[4].addCourse(Course("EngLit"))
courses = []
courseSeeking = "Bio1"
enrolled = []
for student in students:
    for course in student.courses:
        if course.title not in courses:
            bisect.insort(courses, course.title)
        if course.title == courseSeeking:
            enrolled.append(f"{student.lname.title()}, {student.fname.title()}")
print("Students enrolled in " + courseSeeking + ": " + str(enrolled))
print(courses)

# PRINTING ALL COURSES LOGGED-IN STUDENT IS ENROLLED IN
# for courses in logged_in.courses:
#     print(courses.title)

# ADDING A GRADE TO A COURSE FOR A LOGGED-IN STUDENT
# gradeToAdd = 88
# inCourse = "Chess1"
# index = next(x for x in logged_in.courses if x.title == inCourse)
# index.addGrade(gradeToAdd)
# index.addGrade(93)
#
# print(logged_in)

# SEARCH STUDENTS FOR A PROPERTY
# madHatter = next(x for x in students if x.id == "0007")
# print(madHatter.lname)
#
# SAVE STUDENTS[] TO students.dat
# with open("students.dat", "rb") as fp:
#     students = pickle.load(fp)
#
# GETTING CURRENT USER'S INFO  -- ALREADY DEPRECATED WITH __str__ ADDITION
# currentuser = "0002"
# for item in students:
#     if item.id == currentuser:
#         print(item.fname, item.lname, item.id, item.gpa)
#         print(item.classes)
#
# SAVING TEACHERS[] TO teachers.dat
# with open("teachers.dat", "wb") as fp:
#       pickle.dump(teachers, fp)


from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from rest_framework.routers import DefaultRouter
from users import views
from .views import UserViewSet, custom_auth_token

router = DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = router.urls

urlpatterns += [
    url(r'^custom-auth-token/$', csrf_exempt(custom_auth_token)),
    url(r'^create-user$', views.create_user),
    url(r'^update-user-profile$', views.update_user_profile),
    url(r'^create-event-card$', views.create_event_card),
    url(r'^get-event-cards$', views.get_event_cards),
    url(r'^get-doctors$', views.get_doctors),
    url(r'^get-profile-data$', views.get_profile_data),
    url(r'^create-notification$', views.create_notification),
    url(r'^get-notifications$', views.get_notifications),
    url(r'^approve-notification$', views.approve_notification),
    url(r'^decline-notification$', views.decline_notification),
    url(r'^get-appointments$', views.get_appointments),
    url(r'^get-current-appointment$', views.get_current_appointment),
    url(r'^get-specializations$', views.get_specializations),
    url(r'^get-hospitals$', views.get_hospitals),
    url(r'^submit-feedback$', views.submit_feedback),
    url(r'^get-feedbacks$', views.get_feedbacks),
    url(r'^get-permission-for-feedback$', views.get_permission_for_feedback),
    url(r'^save-blank$', views.save_blank),
    url(r'^complete-appointment$', views.complete_appointment),
    url(r'^get-medical-records$', views.get_medical_records)
]


#!/usr/bin/env python
from time import gmtime, strftime
import platform
#import checks

TMP_DIR = 'tmp'
SMTP_TO = 'your@address.here'

SMTP_FROM = platform.node()
TIME = strftime('%Y-%m-%d %H:%M:%S', gmtime())

SUBJECT = dict()
SUBJECT['socket'] = 'ERROR connecting to %s:%s'
SUBJECT['url'] = 'ERROR getting URL %s'
SUBJECT['content'] = 'ERROR comparing content of %s'

BODY = dict()
BODY['socket'] = 'Host: %s\nDate: %s\n\nCould not connect to %s:%s\n\nError Message: %s' % (SMTP_FROM, TIME, '%s', '%s', '%s')
BODY['url'] = 'Host: %s\nDate: %s\n\nCould not open URL %s\n\nError Message: %s' % (SMTP_FROM, TIME, '%s', '%s')
BODY['content'] = 'Host: %s\nDate: %s\n\nThe content of URL %s differs too much!\n\nError Message: %s' % (SMTP_FROM, TIME, '%s', '%s')

FUNCTION = dict()
#FUNCTION['socket'] = check_socket
#FUNCTION['url'] = check_url
#FUNCTION['content'] = check_url_content


porcentajealto=0
porcentajeintermedio=0
porcentajebajo=0
precio_boleta=100
contador=0
while contador <10:
    edad=float(input("Digite su edad: "))
    if edad<5:
        print("No puede entrar")
    elif edad>=5 and edad <= 14:
        print("Tienes un 35% de descuento")
        descuento=0.35
        porcentajealto+= precio_boleta * descuento
    elif edad >= 15 and edad <= 19:
        print("Tienes un 25% de descuento")
        descuento=0.25
        porcentajeintermedio+= precio_boleta * descuento
    elif edad >= 20 and edad <=45:
        print("Tienes un 10% de descuento")
        descuento=0.10
        porcentajebajo+=precio_boleta * descuento
    elif edad >= 46  and edad <=65:
        print("Tienes un 25% de descuento")
        descuento=0.25
        porcentajeintermedio+=precio_boleta * descuento
    elif edad >= 66:
        print("Tienes un 35% de descuento")
        descuento=0.35
        porcentajealto+=precio_boleta * descuento
    contador+=1

cantidad_perdida=porcentajealto+porcentajeintermedio+porcentajebajo

print(f"La cantidad que perdio fue: {cantidad_perdida}")


from tkinter import *
from errorMessage import ErrorMessage
from asignarMedico import AsignarMedico
import connection as con
import customtkinter as ct

class IngresoMedico:
    def __init__(self, parent):
        self.parent = parent
        self.win = Toplevel(parent)
        self.win.title("Ingreso Medico")
        etiTitle = ct.CTkLabel(self.win, text="Ingreso medico", font=("Arial", 20, "bold"))

        etiNum_col = ct.CTkLabel(self.win, text="Numero colegiado")
        inputNum_col = ct.CTkEntry(self.win, width=200)

        etiNombre = ct.CTkLabel(self.win, text="Nombre")
        inputNombre = ct.CTkEntry(self.win, width=200)

        etiApellido = ct.CTkLabel(self.win, text="Apellido")
        inputApellido = ct.CTkEntry(self.win, width=200)

        etiEspecialidad = ct.CTkLabel(self.win, text="Especialidad")
        inputEspecialidad = ct.CTkEntry(self.win, width=200)

        etiTelefono = ct.CTkLabel(self.win, text="Telefono")
        inputTelefono = ct.CTkEntry(self.win, width=200)

        etiDireccion = ct.CTkLabel(self.win, text="Direccion")
        inputDireccion = ct.CTkEntry(self.win, width=200)

        etiEmail = ct.CTkLabel(self.win, text="Email")
        inputEmail = ct.CTkEntry(self.win, width=200)

        buttonSignup = ct.CTkButton(self.win, text="Registrar", command= lambda: self.inputMedico(inputNum_col, inputNombre, inputApellido, inputEspecialidad, inputTelefono, inputDireccion, inputEmail), width=100)
        buttonAsignar = ct.CTkButton(self.win, text="Asignar", command= lambda: AsignarMedico(self.win), width=100)
        buttonClose = ct.CTkButton(self.win, text="Close", command= lambda: self.close(), width=100)

        etiTitle.pack(pady=5)
        etiNum_col.pack()
        inputNum_col.pack(pady=5)
        etiNombre.pack()
        inputNombre.pack(pady=5)
        etiApellido.pack()
        inputApellido.pack(pady=5)
        etiEspecialidad.pack()
        inputEspecialidad.pack(pady=5)
        etiTelefono.pack()
        inputTelefono.pack(pady=5)
        etiDireccion.pack()
        inputDireccion.pack(pady=5)
        etiEmail.pack()
        inputEmail.pack(pady=5)
        buttonSignup.pack(pady=5)
        buttonAsignar.pack(pady=5)
        buttonClose.pack(pady=5)

        self.win.geometry("600x1000")

    def inputMedico(self,inputNum_col, inputNombre, inputApellido, inputEspecialidad, inputTelefono, inputDireccion, inputEmail):
        query = r"""insert into medico values('""" + inputNum_col.get() + r"""', '""" + inputNombre.get() + r"""', '""" + inputApellido.get() + r"""', '""" + inputEspecialidad.get() + r"""', '""" + inputTelefono.get() + r"""', '""" + inputDireccion.get() + r"""', '""" + inputEmail.get() + r"""');"""
        results = con.connect(query)
        if (results == ""):
            mensaje = "Se ha registrado correctamente"
            ErrorMessage(self.win, mensaje=mensaje)
        else:
            mensaje = "Ha ocurrido un error al registrar"
            ErrorMessage(self.win, mensaje=mensaje)

    def close(self):
        self.win.destroy()