from tensorpack.tfutils.summary import add_moving_summary
from tensorpack import *
from tensorpack.tfutils.gradproc import MapGradient, SummaryGradient
from tensorpack.tfutils import (
    get_current_tower_context, optimizer)
from tensorpack.utils.gpu import get_nr_gpu
import tensorflow.contrib.slim as slim
import tensorflow.contrib.rnn as rnn
import sys
import os
import multiprocessing
import tensorpack.dataflow
import tensorflow as tf
import numpy as np
import gym
import cv2
import tensorflow.contrib.rnn as rnn
import VAE

STEPS_PER_EPOCH = 100
BATCH_SIZE = 8
ACTION_DIM = 3
Z_DIM = 32
SEQ_LEN = 20
MIX_GAUSSIANS = 5

class RNNDataflow(RNGDataFlow, Callback):
    def __init__(self, env):
        self.env = env
        # self.pred = OnlinePredictor(PredictConfig(
        #     model=FusedModel(),
        #     session_init=get_model_loader('train_log/auto_encoder/checkpoint'),
        #     input_names=['state_in'],
        #     output_names=['AutoEncoder/encoding']
        # ))

    def _setup_graph(self):
        # op = self.graph.get_operations()
        # print([m.values() for m in op])
        self.pred = self.trainer.get_predictor(
            ['state_in'], ['AutoEncoder/encoding'])
        # OnlinePredictor(['state_in:0'], ['tower0/AutoEncoder/output:0'])

    def get_data(self):
        while True:
            episode_z_buffer = []
            episode_a_buffer = []
            self.env.reset()
            # observation = self.env.state
            # img = cv2.resize(observation, (64, 64))
            # img = img.astype(np.float32) / 255.
            # episode_z_buffer.append(self.pred([img[None, :, :, :]])[0][0])
            while True:
                action = self.env.action_space.sample()
                observation, reward, done, info = self.env.step(action)
                img = cv2.resize(observation, (64, 64))
                img = img.astype(np.float32) / 255.

                if self.env.env.t < 1.:
                    continue

                episode_a_buffer.append(action)
                episode_z_buffer.append(self.pred([img[None, :, :, :]])[0][0])

                if done:
                    episode_a_buffer.pop(0)
                    episode_a = np.asarray(episode_a_buffer, dtype=np.float32)
                    episode_z = np.asarray(episode_z_buffer, dtype=np.float32)
                    for i in range(len(episode_a_buffer) // SEQ_LEN + 1):
                        sample_idx = np.random.randint(len(episode_a_buffer), size=SEQ_LEN)
                        # print(len(episode_a_buffer))
                        yield [np.zeros([64, 64, 3], dtype=np.float32),
                                episode_a[sample_idx],
                                episode_z[sample_idx],
                                episode_z[sample_idx + 1]]
                    break

class Model(ModelDesc):
    def inputs(self):
        return [tf.placeholder(tf.float32, [None, SEQ_LEN, ACTION_DIM], 'action_input'),
                tf.placeholder(tf.float32, [None, SEQ_LEN, Z_DIM], 'z_input'),
                tf.placeholder(tf.float32, [None, SEQ_LEN, Z_DIM], 'z_target')]

    def build_graph(self, action, z_in, z_target):
        scope = 'MDN-RNN'
        with tf.variable_scope(scope):
            hidden_dim = 256
            cell = rnn.BasicLSTMCell(hidden_dim)
            init_state = rnn.LSTMStateTuple(tf.placeholder_with_default(tf.zeros(tf.stack([tf.shape(action)[0], hidden_dim]), name='cz'),
                                                     shape=[None, hidden_dim], name='c'),
                                            tf.placeholder_with_default(
                                                tf.zeros(tf.stack([tf.shape(action)[0], hidden_dim]), name='hz'),
                                                shape=[None, hidden_dim], name='h'))
            x = tf.concat([slim.fully_connected(action, 32), z_in], axis=-1)
            x_list = tf.unstack(x, axis=1)

            outputs, last_state = rnn.static_rnn(cell, x_list, init_state)
            last_state = tf.identity('last_state')

            # is_training = get_current_tower_context().is_training
            # if not is_training:
            #     return

            # B * S * H
            outputs = tf.stack(outputs, axis=1)
            # outputs = tf.Print(outputs, [tf.shape(outputs)], summarize=10)
            # elements in in z are independent mix-gaussians
            dense = slim.fully_connected(tf.reshape(outputs, [-1, hidden_dim]), 3 * Z_DIM * MIX_GAUSSIANS, activation_fn=None)
            mean = tf.reshape(dense[:, :Z_DIM * MIX_GAUSSIANS], [-1, MIX_GAUSSIANS, Z_DIM])
            sigma = tf.reshape(tf.exp(dense[:, Z_DIM * MIX_GAUSSIANS:2*Z_DIM * MIX_GAUSSIANS]), [-1, MIX_GAUSSIANS, Z_DIM])
            pi = tf.nn.softmax(tf.reshape(dense[:, -Z_DIM * MIX_GAUSSIANS:], [-1, MIX_GAUSSIANS, Z_DIM]), axis=1)

            # sample from mixture of gaussian
            z = tf.reshape(tf.tile(z_target, [1, 1, MIX_GAUSSIANS]), [-1, MIX_GAUSSIANS, Z_DIM])
            # z = tf.Print(z, [tf.shape(z), tf.shape(mean)], summarize=10)
            # a const positive scalar (2pi)^(-D/2) is omitted
            probs = pi * tf.exp(-tf.square(z - mean) / (2 * tf.square(sigma) + 1e-8)) / (sigma + 1e-8)

            # (B * S) * Z
            probs = tf.reduce_sum(probs, axis=1)

        loss = tf.reduce_sum(-tf.log(probs), name='loss')
        add_moving_summary(loss)

        return loss

    def optimizer(self):
        lr = tf.get_variable('learning_rate', initializer=1e-4, trainable=False)
        opt = tf.train.AdamOptimizer(lr)
        gradprocs = [MapGradient(lambda grad: tf.clip_by_average_norm(grad, 0.3))]
        # SummaryGradient()]
        opt = optimizer.apply_grad_processors(opt, gradprocs)
        return opt

class FusedModel(ModelDesc):
    def __init__(self):
        self.mdn_rnn_model = Model()
        self.vae_model = VAE.Model()

    def inputs(self):
        return self.vae_model.inputs() + self.mdn_rnn_model.inputs()

    def build_graph(self, img, action, z_in, z_target):
        self.vae_model.build_graph(img)
        return self.mdn_rnn_model.build_graph(action, z_in, z_target)

    def optimizer(self):
        return self.mdn_rnn_model.optimizer()

def train():
    dirname = os.path.join('train_log', 'mdn-rnn')
    logger.set_logger_dir(dirname)

    # assign GPUs for training & inference
    nr_gpu = get_nr_gpu()
    if nr_gpu > 0:
        train_tower = list(range(nr_gpu)) or [0]
        logger.info("[Batch-SL] Train on gpu {}".format(
            ','.join(map(str, train_tower))))
    else:
        logger.warn("Without GPU this model will never learn! CPU is only useful for debug.")
        train_tower = [0], [0]

    ds = RNNDataflow(gym.make('CarRacing-v0'))
    # if os.name == 'nt':
    #     dataflow = PrefetchData(ds, nr_proc=multiprocessing.cpu_count() // 2,
    #                             nr_prefetch=multiprocessing.cpu_count() // 2)
    # else:
    #     dataflow = PrefetchDataZMQ(ds, nr_proc=multiprocessing.cpu_count() // 2)
    dataflow = BatchData(ds, BATCH_SIZE)
    config = TrainConfig(
        model=FusedModel(),
        dataflow=dataflow,
        callbacks=[
            ModelSaver(),
            EstimatedTimeLeft(),
            ds,
            # ScheduledHyperParamSetter('learning_rate', [(20, 0.0003), (120, 0.0001)]),
            # ScheduledHyperParamSetter('entropy_beta', [(80, 0.005)]),
            # HumanHyperParamSetter('learning_rate'),
        ],
        session_init=get_model_loader('train_log/auto_encoder/checkpoint'),
        steps_per_epoch=STEPS_PER_EPOCH,
        max_epoch=100,
    )
    trainer = AsyncMultiGPUTrainer(train_tower) if nr_gpu > 1 else SimpleTrainer()
    launch_train_with_config(config, trainer)

if __name__ == '__main__':
    train()


#!/usr/bin/env python

# ros
import rospy
from std_msgs.msg import String
from trajectory_msgs.msg import MultiDOFJointTrajectory, MultiDOFJointTrajectoryPoint
from geometry_msgs.msg import Pose, Twist, Transform
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Imu
from gazebo_msgs.msg import ModelState
from unreal_cv_ros.msg import UeSensorRaw
from sensor_msgs.msg import PointCloud2
from std_srvs.srv import Empty
from gazebo_msgs.srv import SetModelState, GetModelState
import tf

# Python
import sys
import math
import numpy as np
import time
from collections import deque

class SimulationManager:

    def __init__(self):
        '''  Initialize ros node and read params '''
        # Parse parameters
        self.ns_gazebo = rospy.get_param('~ns_gazebo', "/gazebo")
        self.ns_mav = rospy.get_param('~ns_mav', "/firefly")
        self.regulate = rospy.get_param('~regulate', False)  # Manage odom throughput for unreal_ros_client
        self.monitor = rospy.get_param('~monitor', False)  # Measure performance of unreal pipeline
        self.initial_position = rospy.get_param('~initial_position', [0, 0, 0])  # x, y, z [m]

        if self.monitor:
            self.horizon = rospy.get_param('~horizon', 10)  # How many messages are kept for monitoring

            # Monitoring arrays
            self.mon_client_rate_real = deque(maxlen=self.horizon)
            self.mon_client_rate_ros = deque(maxlen=self.horizon)
            self.mon_client_prev_real = None
            self.mon_client_prev_ros = None
            self.mon_client_delay_ros = deque(maxlen=self.horizon)
            self.mon_client_time = deque(maxlen=self.horizon)
            self.mon_sensor_rate_real = deque(maxlen=self.horizon)
            self.mon_sensor_rate_ros = deque(maxlen=self.horizon)
            self.mon_sensor_prev_real = None
            self.mon_sensor_prev_ros = None
            self.mon_sensor_delay_ros = deque(maxlen=self.horizon)
            self.mon_sensor_time = deque(maxlen=self.horizon)

            # Subscribers
            self.ue_raw_sub = rospy.Subscriber("ue_raw_in", UeSensorRaw, self.mon_raw_callback, queue_size=10)
            self.ue_out_sub = rospy.Subscriber("ue_out_in", PointCloud2, self.mon_out_callback, queue_size=10)

            # Printing service
            rospy.Service('~display_monitor', Empty, self.mon_print_handle)

        if self.regulate:
            # Subscribers and publishers
            self.odom_sub = rospy.Subscriber("odom_in", Odometry, self.odom_callback, queue_size=10)
            self.odom_pub = rospy.Publisher("~odom_out", Odometry, queue_size=10)

        # Run the startup
        self.ready_pub = rospy.Publisher("~simulation_ready", String, queue_size=10)
        self.launch_simulation()

    def launch_simulation(self):
        # Wait for Gazebo services
        rospy.loginfo("Starting unreal MAV simulation setup coordination...")
        rospy.wait_for_service(self.ns_gazebo + "/unpause_physics")
        rospy.wait_for_service(self.ns_gazebo + "/set_model_state")

        # Prepare initialization trajectory command
        traj_pub = rospy.Publisher(self.ns_mav + "/command/trajectory", MultiDOFJointTrajectory, queue_size=10)
        traj_msg = MultiDOFJointTrajectory()
        traj_msg.joint_names = ["base_link"]
        transforms = Transform()
        transforms.translation.x = self.initial_position[0]
        transforms.translation.y = self.initial_position[1]
        transforms.translation.z = self.initial_position[2]
        point = MultiDOFJointTrajectoryPoint([transforms], [Twist()], [Twist()], rospy.Duration(0))
        traj_msg.points.append(point)

        # Prepare initialization Get/SetModelState service
        set_model_srv = rospy.ServiceProxy(self.ns_gazebo + "/set_model_state", SetModelState)
        get_model_srv = rospy.ServiceProxy(self.ns_gazebo + "/get_model_state", GetModelState)
        mav_name = self.ns_mav[np.max([i for i in range(len(self.ns_mav)) if self.ns_mav[i] == "/"]) + 1:]
        pose = Pose()
        pose.position.x = self.initial_position[0]
        pose.position.y = self.initial_position[1]
        pose.position.z = self.initial_position[2]
        model_state_set = ModelState(mav_name, pose, Twist(), "world")

        # Wake up gazebo
        rospy.loginfo("Waiting for gazebo to wake up ...")
        unpause_srv = rospy.ServiceProxy(self.ns_gazebo + "/unpause_physics", Empty)
        while not unpause_srv():
            rospy.sleep(0.1)
        rospy.loginfo("Waiting for gazebo to wake up ... done.")

        # Wait for drone to spawn (imu is publishing)
        rospy.loginfo("Waiting for MAV to spawn ...")
        rospy.wait_for_message(self.ns_mav + "/imu", Imu)
        rospy.loginfo("Waiting for MAV to spawn ... done.")

        # Initialize drone stable at [0, 0, 0]
        rospy.loginfo("Waiting for MAV to stabilize ...")
        dist = 10  # Position and velocity
        while dist >= 0.1:
            traj_msg.header.stamp = rospy.Time.now()
            traj_pub.publish(traj_msg)
            set_model_srv(model_state_set)
            rospy.sleep(0.1)
            state = get_model_srv(mav_name, "world")
            pos = state.pose.position
            twist = state.twist.linear
            dist = np.sqrt((pos.x - self.initial_position[0]) ** 2 + (pos.y - self.initial_position[1]) ** 2 +
                           (pos.z - self.initial_position[2]) ** 2) + np.sqrt(
                twist.x ** 2 + twist.y ** 2 + twist.z ** 2)
        rospy.loginfo("Waiting for MAV to stabilize ... done.")

        # Wait for unreal client
        rospy.loginfo("Waiting for unreal client to setup ...")
        rospy.wait_for_message("ue_out_in", PointCloud2)
        rospy.loginfo("Waiting for unreal client to setup ... done.")

        # Finish
        self.ready_pub.publish(String("Simulation Ready"))
        rospy.loginfo("Unreal MAV simulation setup successfully.")

    def mon_raw_callback(self, ros_data):
        # Measure walltime and rostime between callbacks
        time_real = time.time()
        time_ros = rospy.get_time()
        if self.mon_client_prev_real is None:
            # Initialization
            self.mon_client_prev_real = time_real
            self.mon_client_prev_ros = time_ros
            return

        self.mon_client_rate_real.append(time_real - self.mon_client_prev_real)
        self.mon_client_prev_real = time_real
        self.mon_client_rate_ros.append(time_ros - self.mon_client_prev_ros)
        self.mon_client_prev_ros = time_ros
        self.mon_client_delay_ros.append(time_ros - ros_data.header.stamp.to_sec())
        self.mon_client_time.append(time_ros)

    def mon_out_callback(self, ros_data):
        # Measure walltime and rostime between callbacks
        time_real = time.time()
        time_ros = rospy.get_time()
        if self.mon_sensor_prev_real is None:
            # Initialization
            self.mon_sensor_prev_real = time_real
            self.mon_sensor_prev_ros = time_ros
            return

        self.mon_sensor_rate_real.append(time_real - self.mon_sensor_prev_real)
        self.mon_sensor_prev_real = time_real
        self.mon_sensor_rate_ros.append(time_ros - self.mon_sensor_prev_ros)
        self.mon_sensor_prev_ros = time_ros
        self.mon_sensor_delay_ros.append(time_ros - ros_data.header.stamp.to_sec())
        self.mon_sensor_time.append(time_ros)

    def mon_print_handle(self, _):
        print("=" * 14 + " performance monitor " + "=" * 14)
        print("Fields: [Hz] / [s]   avg  -  std  -  min  -  max ")
        values = 1.0 / np.array(self.mon_client_rate_real)
        if len(values) > 0:
            print("Client rate (wall): {0:05.2f} - {1:05.2f} - {2:05.2f} - {3:05.2f}"
                  .format(np.mean(values), np.std(values), np.min(values), np.max(values)))
        values = 1.0 / np.array(self.mon_client_rate_ros)
        if len(values) > 0:
            print("Client rate  (ros): {0:05.2f} - {1:05.2f} - {2:05.2f} - {3:05.2f}"
                  .format(np.mean(values), np.std(values), np.min(values), np.max(values)))
        values = np.array(self.mon_client_delay_ros)
        if len(values) > 0:
            print("Client delay (ros): {0:05.2f} - {1:05.2f} - {2:05.2f} - {3:05.2f}"
                  .format(np.mean(values), np.std(values), np.min(values), np.max(values)))
        values = 1.0 / np.array(self.mon_sensor_rate_real)
        if len(values) > 0:
            print("Sensor rate (wall): {0:05.2f} - {1:05.2f} - {2:05.2f} - {3:05.2f}"
                  .format(np.mean(values), np.std(values), np.min(values), np.max(values)))
        values = 1.0 / np.array(self.mon_sensor_rate_ros)
        if len(values) > 0:
            print("Sensor rate  (ros): {0:05.2f} - {1:05.2f} - {2:05.2f} - {3:05.2f}"
                  .format(np.mean(values), np.std(values), np.min(values), np.max(values)))
        values = np.array(self.mon_sensor_delay_ros)
        if len(values) > 0:
            print("Sensor delay (ros): {0:05.2f} - {1:05.2f} - {2:05.2f} - {3:05.2f}"
                  .format(np.mean(values), np.std(values), np.min(values), np.max(values)))
        print("=" * 49)
        return []

if __name__ == '__main__':
    rospy.init_node('simulation_manager', anonymous=True)
    sm = SimulationManager()
    rospy.spin()


from datetime import timedelta

from sql import Literal, Join
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction
from trytond.model import ModelView, ModelSQL, fields
from trytond.pyson import Eval, Not, Bool, PYSONEncoder, Equal
from trytond.wizard import (Wizard, StateView, StateTransition, Button,
                            StateAction)

from .reports import DailyPatientRegister

__all__ = ['PatientRegisterModel', 'PatientRegisterWizard',
           'PatientRegisterFilterView', 'PatientRegisterFilteredWizard',
           'AppointmentReport', 'OpenAppointmentReportStart',
           'OpenAppointmentReport', 'StartEndDateModel', 'PRFDisease',
           'PRFProcedure']

class StartEndDateModel(ModelView):
    '''Generic ModelView that has start and end date fields. '''
    __name__ = 'healthjm.report.startenddate_generic'

    on_or_after = fields.Date('Start date', required=True)
    on_or_before = fields.Date('End date')
    institution = fields.Many2One('gnuhealth.institution', 'Institution',
                                  required=True, states={'readonly':True})

    @classmethod
    def __setup__(cls):
        super(StartEndDateModel, cls).__setup__()
        cls._error_messages.update({
            'required_institution':'''Institution is required.\n
Your user account is not assigned to an institution.
This assignment is needed before you can use this report.
Please contact your system administrator to have this resolved.'''
            })

    @staticmethod
    def default_institution():
        HealthInst = Pool().get('gnuhealth.institution')
        try:
            institution = HealthInst.get_institution()
        except AttributeError:
            self.raise_user_error('required_institution')
        return institution

class PatientRegisterModel(StartEndDateModel):
    '''Patient Evaluation Register'''
    __name__ = 'healthjm.report.patientregister.start'
    specialty = fields.Selection('get_specialty_list', 'Specialty')

    @fields.depends('institution')
    def get_specialty_list(self):
        if self.institution:
            return [(x.specialty.id, x.specialty.name)
                    for x in self.institution.specialties]
        else:
            return []

class PatientRegisterWizard(Wizard):
    '''Evaluation Register Wizard'''
    __name__ = 'healthjm.report.patientregister.wizard'
    start = StateView('healthjm.report.patientregister.start',
        'health_jamaica.healthjm_form_patientregister_report_start', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Generate Report', 'generate_report', 'tryton-ok',
                    default=True),
        ])
    generate_report = StateAction(
                            'health_jamaica.healthjm_report_patientregister')

    def transition_generate_report(self):
        return 'end'

    def do_generate_report(self, action):
        # specify data that will be passed to .parse on the report object
        data = {'start_date':self.start.on_or_after,
                'end_date':self.start.on_or_after,
                'specialty':None,
                'facility':None,
                'x_extra_criteria': False}

        if self.start.on_or_before:
            data['end_date'] = self.start.on_or_before

        if self.start.specialty:
            data['specialty'] = self.start.specialty

        if self.start.institution:
            data['institution'] = self.start.institution.id
        else:
            self.start.raise_user_error('required_institution')
            return 'start'

        return action, data

def permute_opts(name='diseases'):
    return [
        ('OR', 'Include ANY of the selected %s (OR)' % name),
        ('AND', 'Include ALL of the selected %s (AND)' % name)]
        # ('nor', 'Include None of the selected %s (NOR)' % name)]

class PatientRegisterFilterView(PatientRegisterModel):
    'Patient Evaluation Register (by Disease)'
    __name__ = 'healthjm.report.patientregister_filtered.start'
    dp_perm = fields.Selection(
        [('dp', 'Both Diseases and Procedures'), ('d', 'Diseases Only'),
         ('p', 'Procedures Only'), ('o', 'Either Diseases or Procedures')],
        'Filter by', sort=False)
    diseases = fields.One2Many(
        'healthjm.report.patientregister_filtered.disease_o2m', 'prf',
        'Selected Diseases', states={'readonly': Equal(Eval('dp_perm'), 'p')})
    procedures = fields.One2Many(
        'healthjm.report.patientregister_filtered.procedure_o2m', 'prf',
        'Selected Procedures', states={'readonly': Equal(Eval('dp_perm'), 'd')})

    disease_perm = fields.Selection(permute_opts(), 'Disease option', sort=False)
    procedure_perm = fields.Selection(permute_opts('procedures'),
                                      'Procedure option', sort=False)

    @staticmethod
    def default_disease_perm():
        return 'AND'

    @staticmethod
    def default_procedure_perm():
        return 'AND'

    @staticmethod
    def default_dp_perm():
        return 'o'

class PRFDisease(ModelView):
    'Patient Evaluation Register - Diseases'
    __name__ = 'healthjm.report.patientregister_filtered.disease_o2m'
    prf = fields.Many2One('healthjm.report.patientregister_filtered.start',
                          'PRF', readonly=True)
    pathology = fields.Many2One('gnuhealth.pathology', 'Disease',
                                required=True)
    invert = fields.Boolean('Invert',
                            help='exclude rather than include this one')

class PRFProcedure(ModelView):
    'Patient Evaluation Register - Procedures'
    __name__ = 'healthjm.report.patientregister_filtered.procedure_o2m'
    prf = fields.Many2One('healthjm.report.patientregister_filtered.start',
                          'PRF', readonly=True)
    procedure = fields.Many2One('gnuhealth.procedure', 'Procedure',
                                required=True)
    invert = fields.Boolean('Invert',
                            help='exclude rather than include this one')

class PatientRegisterFilteredWizard(PatientRegisterWizard):
    '''Evaluation Register Wizard'''
    __name__ = 'healthjm.report.patientregister_filtered.wizard'

    start = StateView(
        'healthjm.report.patientregister_filtered.start',
        'health_jamaica.healthjm_form_patientregisterflt_report_start', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Generate Report', 'generate_report', 'tryton-ok',
                   default=True),
        ])
    generate_report = StateAction(
        'health_jamaica.healthjm_report_patientregister_filtered')

    def transition_generate_report(self):
        return 'end'

    def do_generate_report(self, action):
        def make_disease_domain(disease):
            if disease.invert:
                return (['AND', ('diagnosis', '!=', disease.pathology.id),
                        ('secondary_conditions.pathology', '!=',
                         disease.pathology.id)],
                        u'Not(%s [%s])' % (disease.pathology.name,
                                           disease.pathology.code))
            else:
                return (['OR', ('diagnosis', '=', disease.pathology.id),
                        ('secondary_conditions.pathology', '=',
                         disease.pathology.id)],
                        u'%s [%s]' % (disease.pathology.name,
                                      disease.pathology.code))

        def make_procedure_domain(procedure):
            if procedure.invert:
                return (('procedures.procedure', '=', procedure.procedure.id),
                        u'Not(%s [%s])' % (procedure.description,
                                           procedure.name))
            else:
                return (('procedures.procedure', '=', procedure.procedure.id),
                        u'%s [%s]' % (procedure.procedure.description,
                                      procedure.procedure.name))

        bad_action, data = super(
            PatientRegisterFilteredWizard, self).do_generate_report(action)

        search_criteria = {'disease': [], 'procedure': []}
        search_criteria_names = {'disease': [], 'procedure': []}

        if self.start.dp_perm in ('dp', 'd', 'o') and self.start.diseases:
            for disease in self.start.diseases:
                criteria, name = make_disease_domain(disease)
                search_criteria['disease'].append(criteria)
                search_criteria_names['disease'].append(name)
            if len(search_criteria_names['disease']) == 1:
                search_criteria['disease'] = search_criteria['disease'][0]
            else:
                search_criteria['disease'].insert(0, self.start.disease_perm)

        if self.start.dp_perm in ('dp', 'p', 'o') and self.start.procedures:
            for proc in self.start.procedures:
                criteria, name = make_procedure_domain(proc)
                search_criteria['procedure'].append(criteria)
                search_criteria_names['procedure'].append(name)
            if len(search_criteria_names['procedure']) == 1:
                search_criteria['procedure'] = search_criteria['procedure'][0]
            else:
                search_criteria['procedure'].insert(0,
                                                    self.start.procedure_perm)

        data.update(x_extra_criteria=True, x_search_criteria=search_criteria,
                    x_selected=search_criteria_names,
                    x_dp_perm=self.start.dp_perm,
                    x_encounter_fields=['patient.name.du.simple_address',
                    'patient.name.du.address_subdivision.name'],
                    x_selected_count=dict(
                        [(a, len(b))
                         for a, b in search_criteria_names.items()]))

        return action, data

class AppointmentReport(ModelSQL, ModelView):
    'Appointment Report'
    __name__ = 'gnuhealth.appointment.report'
    speciality = fields.Many2One('gnuhealth.specialty', 'Specialty')

    @classmethod
    def table_query(cls):
        pool = Pool()
        xaction = Transaction()
        appointment = pool.get('gnuhealth.appointment').__table__()
        party = pool.get('party.party').__table__()
        patient = pool.get('gnuhealth.patient').__table__()
        join1 = Join(appointment, patient)
        join1.condition = join1.right.id == appointment.patient
        join2 = Join(join1, party)
        join2.condition = join2.right.id == join1.right.name
        where = Literal(True)
        if xaction.context.get('date_start'):
            where &= (appointment.appointment_date >=
                    xaction.context['date_start'])
        if xaction.context.get('date_end'):
            where &= (appointment.appointment_date <
                    xaction.context['date_end'] + timedelta(days=1))
        if xaction.context.get('healthprof'):
            where &= \
                appointment.healthprof == xaction.context['healthprof']

        if xaction.context.get('specialty', False):
            where &= appointment.speciality == xaction.context['specialty']

        return join2.select(
            appointment.id,
            appointment.create_uid,
            appointment.create_date,
            appointment.write_uid,
            appointment.write_date,
            join2.right.ref,
            join1.right.id.as_('patient'),
            join2.right.sex,
            appointment.appointment_date,
            appointment.appointment_date.as_('appointment_date_time'),
            appointment.healthprof,
            appointment.speciality,
            where=where)

class OpenAppointmentReportStart(ModelView):
    'Open Appointment Report'
    __name__ = 'gnuhealth.appointment.report.open.start'
    specialty = fields.Many2One('gnuhealth.specialty', 'Specialty',
                                states={'required':Not(Bool(Eval('healthprof')))})
    healthprof = fields.Many2One('gnuhealth.healthprofessional', 'Health Professional',
        required=False, states={'required':Not(Bool(Eval('specialty')))})

class OpenAppointmentReport(Wizard):
    'Open Appointment Report'
    __name__ = 'gnuhealth.appointment.report.open'

    def do_open_(self, action):
        action_dict = {'date_start': self.start.date_start,
            'date_end': self.start.date_end }
        if self.start.healthprof:
            action_dict['healthprof'] = self.start.healthprof.id
            action['name'] += ' - {}'.format(self.start.healthprof.name.name)

        if self.start.specialty:
            action_dict['specialty'] = self.start.specialty.id
            action['name'] += ' - {}'.format(self.start.specialty.name)

        action['pyson_context'] = PYSONEncoder().encode(action_dict)
        return action, {}


from typing import Any, Union

class AtriStyles:
	def __init__(self, state: Union[Any, None]):
		self._setter_access_tracker = {}
		self._getter_access_tracker = {}
		self._state_is_none = state == None

		self.display: Union[str, None] = state["display"] if state != None and "display" in state else None
		self.flexDirection: Union[str, None] = state["flexDirection"] if state != None and "flexDirection" in state else None
		self.alignItems: Union[str, None] = state["alignItems"] if state != None and "alignItems" in state else None
		self.justifyContent: Union[str, None] = state["justifyContent"] if state != None and "justifyContent" in state else None
		self.flexWrap: Union[str, None] = state["flexWrap"] if state != None and "flexWrap" in state else None
		self.alignContent: Union[str, None] = state["alignContent"] if state != None and "alignContent" in state else None
		self.rowGap: Union[str, None] = state["rowGap"] if state != None and "rowGap" in state else None
		self.columnGap: Union[str, None] = state["columnGap"] if state != None and "columnGap" in state else None
		self.alignSelf: Union[str, None] = state["alignSelf"] if state != None and "alignSelf" in state else None
		self.flexGrow: Union[str, None] = state["flexGrow"] if state != None and "flexGrow" in state else None
		self.flexShrink: Union[str, None] = state["flexShrink"] if state != None and "flexShrink" in state else None
		self.order: Union[str, None] = state["order"] if state != None and "order" in state else None
		self.marginTop: Union[str, None] = state["marginTop"] if state != None and "marginTop" in state else None
		self.marginBottom: Union[str, None] = state["marginBottom"] if state != None and "marginBottom" in state else None
		self.marginRight: Union[str, None] = state["marginRight"] if state != None and "marginRight" in state else None
		self.marginLeft: Union[str, None] = state["marginLeft"] if state != None and "marginLeft" in state else None
		self.paddingTop: Union[str, None] = state["paddingTop"] if state != None and "paddingTop" in state else None
		self.paddingBottom: Union[str, None] = state["paddingBottom"] if state != None and "paddingBottom" in state else None
		self.paddingRight: Union[str, None] = state["paddingRight"] if state != None and "paddingRight" in state else None
		self.paddingLeft: Union[str, None] = state["paddingLeft"] if state != None and "paddingLeft" in state else None
		self.width: Union[str, None] = state["width"] if state != None and "width" in state else None
		self.height: Union[str, None] = state["height"] if state != None and "height" in state else None
		self.minWidth: Union[str, None] = state["minWidth"] if state != None and "minWidth" in state else None
		self.minHeight: Union[str, None] = state["minHeight"] if state != None and "minHeight" in state else None
		self.maxWidth: Union[str, None] = state["maxWidth"] if state != None and "maxWidth" in state else None
		self.maxHeight: Union[str, None] = state["maxHeight"] if state != None and "maxHeight" in state else None
		self.overflow: Union[str, None] = state["overflow"] if state != None and "overflow" in state else None
		self.fontFamily: Union[str, None] = state["fontFamily"] if state != None and "fontFamily" in state else None
		self.fontWeight: Union[str, None] = state["fontWeight"] if state != None and "fontWeight" in state else None
		self.fontSize: Union[str, None] = state["fontSize"] if state != None and "fontSize" in state else None
		self.textAlign: Union[str, None] = state["textAlign"] if state != None and "textAlign" in state else None
		self.color: Union[str, None] = state["color"] if state != None and "color" in state else None
		self.opacity: Union[str, None] = state["opacity"] if state != None and "opacity" in state else None
		self.fontStyle: Union[str, None] = state["fontStyle"] if state != None and "fontStyle" in state else None
		self.borderRadius: Union[str, None] = state["borderRadius"] if state != None and "borderRadius" in state else None
		self.borderWidth: Union[str, None] = state["borderWidth"] if state != None and "borderWidth" in state else None
		self.borderStyle: Union[str, None] = state["borderStyle"] if state != None and "borderStyle" in state else None
		self.borderColor: Union[str, None] = state["borderColor"] if state != None and "borderColor" in state else None
		self.backgroundImage: Union[str, None] = state["backgroundImage"] if state != None and "backgroundImage" in state else None
		self.backgroundColor: Union[str, None] = state["backgroundColor"] if state != None and "backgroundColor" in state else None
		self.backgroundClip: Union[str, None] = state["backgroundClip"] if state != None and "backgroundClip" in state else None
		self.backgroundOrigin: Union[str, None] = state["backgroundOrigin"] if state != None and "backgroundOrigin" in state else None
		self.backgroundAttachment: Union[str, None] = state["backgroundAttachment"] if state != None and "backgroundAttachment" in state else None
		self.backgroundPositionX: Union[str, None] = state["backgroundPositionX"] if state != None and "backgroundPositionX" in state else None
		self.backgroundPositionY: Union[str, None] = state["backgroundPositionY"] if state != None and "backgroundPositionY" in state else None
		self.backgroundRepeat: Union[str, None] = state["backgroundRepeat"] if state != None and "backgroundRepeat" in state else None
		self.position: Union[str, None] = state["position"] if state != None and "position" in state else None
		self.float: Union[str, None] = state["float"] if state != None and "float" in state else None
		self.clear: Union[str, None] = state["clear"] if state != None and "clear" in state else None
		self.top: Union[str, None] = state["top"] if state != None and "top" in state else None
		self.left: Union[str, None] = state["left"] if state != None and "left" in state else None
		self.bottom: Union[str, None] = state["bottom"] if state != None and "bottom" in state else None
		self.right: Union[str, None] = state["right"] if state != None and "right" in state else None
		self.zIndex: Union[str, None] = state["zIndex"] if state != None and "zIndex" in state else None
		self.outlineStyle: Union[str, None] = state["outlineStyle"] if state != None and "outlineStyle" in state else None
		self.outlineColor: Union[str, None] = state["outlineColor"] if state != None and "outlineColor" in state else None
		self.outlineOffset: Union[str, None] = state["outlineOffset"] if state != None and "outlineOffset" in state else None
		self.outlineWidth: Union[str, None] = state["outlineWidth"] if state != None and "outlineWidth" in state else None
		self.cursor: Union[str, None] = state["cursor"] if state != None and "cursor" in state else None
		self.boxSizing: Union[str, None] = state["boxSizing"] if state != None and "boxSizing" in state else None

		self._setter_access_tracker = {}
		self._getter_access_tracker = {}

	@property
	def display(self):
		self._getter_access_tracker["display"] = {}
		return self._display
	@display.setter
	def display(self, state):
		self._setter_access_tracker["display"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._display = state
	@property
	def flexDirection(self):
		self._getter_access_tracker["flexDirection"] = {}
		return self._flexDirection
	@flexDirection.setter
	def flexDirection(self, state):
		self._setter_access_tracker["flexDirection"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._flexDirection = state
	@property
	def alignItems(self):
		self._getter_access_tracker["alignItems"] = {}
		return self._alignItems
	@alignItems.setter
	def alignItems(self, state):
		self._setter_access_tracker["alignItems"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._alignItems = state
	@property
	def justifyContent(self):
		self._getter_access_tracker["justifyContent"] = {}
		return self._justifyContent
	@justifyContent.setter
	def justifyContent(self, state):
		self._setter_access_tracker["justifyContent"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._justifyContent = state
	@property
	def flexWrap(self):
		self._getter_access_tracker["flexWrap"] = {}
		return self._flexWrap
	@flexWrap.setter
	def flexWrap(self, state):
		self._setter_access_tracker["flexWrap"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._flexWrap = state
	@property
	def alignContent(self):
		self._getter_access_tracker["alignContent"] = {}
		return self._alignContent
	@alignContent.setter
	def alignContent(self, state):
		self._setter_access_tracker["alignContent"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._alignContent = state
	@property
	def rowGap(self):
		self._getter_access_tracker["rowGap"] = {}
		return self._rowGap
	@rowGap.setter
	def rowGap(self, state):
		self._setter_access_tracker["rowGap"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._rowGap = state
	@property
	def columnGap(self):
		self._getter_access_tracker["columnGap"] = {}
		return self._columnGap
	@columnGap.setter
	def columnGap(self, state):
		self._setter_access_tracker["columnGap"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._columnGap = state
	@property
	def alignSelf(self):
		self._getter_access_tracker["alignSelf"] = {}
		return self._alignSelf
	@alignSelf.setter
	def alignSelf(self, state):
		self._setter_access_tracker["alignSelf"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._alignSelf = state
	@property
	def flexGrow(self):
		self._getter_access_tracker["flexGrow"] = {}
		return self._flexGrow
	@flexGrow.setter
	def flexGrow(self, state):
		self._setter_access_tracker["flexGrow"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._flexGrow = state
	@property
	def flexShrink(self):
		self._getter_access_tracker["flexShrink"] = {}
		return self._flexShrink
	@flexShrink.setter
	def flexShrink(self, state):
		self._setter_access_tracker["flexShrink"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._flexShrink = state
	@property
	def order(self):
		self._getter_access_tracker["order"] = {}
		return self._order
	@order.setter
	def order(self, state):
		self._setter_access_tracker["order"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._order = state
	@property
	def marginTop(self):
		self._getter_access_tracker["marginTop"] = {}
		return self._marginTop
	@marginTop.setter
	def marginTop(self, state):
		self._setter_access_tracker["marginTop"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._marginTop = state
	@property
	def marginBottom(self):
		self._getter_access_tracker["marginBottom"] = {}
		return self._marginBottom
	@marginBottom.setter
	def marginBottom(self, state):
		self._setter_access_tracker["marginBottom"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._marginBottom = state
	@property
	def marginRight(self):
		self._getter_access_tracker["marginRight"] = {}
		return self._marginRight
	@marginRight.setter
	def marginRight(self, state):
		self._setter_access_tracker["marginRight"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._marginRight = state
	@property
	def marginLeft(self):
		self._getter_access_tracker["marginLeft"] = {}
		return self._marginLeft
	@marginLeft.setter
	def marginLeft(self, state):
		self._setter_access_tracker["marginLeft"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._marginLeft = state
	@property
	def paddingTop(self):
		self._getter_access_tracker["paddingTop"] = {}
		return self._paddingTop
	@paddingTop.setter
	def paddingTop(self, state):
		self._setter_access_tracker["paddingTop"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._paddingTop = state
	@property
	def paddingBottom(self):
		self._getter_access_tracker["paddingBottom"] = {}
		return self._paddingBottom
	@paddingBottom.setter
	def paddingBottom(self, state):
		self._setter_access_tracker["paddingBottom"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._paddingBottom = state
	@property
	def paddingRight(self):
		self._getter_access_tracker["paddingRight"] = {}
		return self._paddingRight
	@paddingRight.setter
	def paddingRight(self, state):
		self._setter_access_tracker["paddingRight"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._paddingRight = state
	@property
	def paddingLeft(self):
		self._getter_access_tracker["paddingLeft"] = {}
		return self._paddingLeft
	@paddingLeft.setter
	def paddingLeft(self, state):
		self._setter_access_tracker["paddingLeft"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._paddingLeft = state
	@property
	def width(self):
		self._getter_access_tracker["width"] = {}
		return self._width
	@width.setter
	def width(self, state):
		self._setter_access_tracker["width"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._width = state
	@property
	def height(self):
		self._getter_access_tracker["height"] = {}
		return self._height
	@height.setter
	def height(self, state):
		self._setter_access_tracker["height"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._height = state
	@property
	def minWidth(self):
		self._getter_access_tracker["minWidth"] = {}
		return self._minWidth
	@minWidth.setter
	def minWidth(self, state):
		self._setter_access_tracker["minWidth"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._minWidth = state
	@property
	def minHeight(self):
		self._getter_access_tracker["minHeight"] = {}
		return self._minHeight
	@minHeight.setter
	def minHeight(self, state):
		self._setter_access_tracker["minHeight"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._minHeight = state
	@property
	def maxWidth(self):
		self._getter_access_tracker["maxWidth"] = {}
		return self._maxWidth
	@maxWidth.setter
	def maxWidth(self, state):
		self._setter_access_tracker["maxWidth"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._maxWidth = state
	@property
	def maxHeight(self):
		self._getter_access_tracker["maxHeight"] = {}
		return self._maxHeight
	@maxHeight.setter
	def maxHeight(self, state):
		self._setter_access_tracker["maxHeight"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._maxHeight = state
	@property
	def overflow(self):
		self._getter_access_tracker["overflow"] = {}
		return self._overflow
	@overflow.setter
	def overflow(self, state):
		self._setter_access_tracker["overflow"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._overflow = state
	@property
	def fontFamily(self):
		self._getter_access_tracker["fontFamily"] = {}
		return self._fontFamily
	@fontFamily.setter
	def fontFamily(self, state):
		self._setter_access_tracker["fontFamily"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._fontFamily = state
	@property
	def fontWeight(self):
		self._getter_access_tracker["fontWeight"] = {}
		return self._fontWeight
	@fontWeight.setter
	def fontWeight(self, state):
		self._setter_access_tracker["fontWeight"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._fontWeight = state
	@property
	def fontSize(self):
		self._getter_access_tracker["fontSize"] = {}
		return self._fontSize
	@fontSize.setter
	def fontSize(self, state):
		self._setter_access_tracker["fontSize"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._fontSize = state
	@property
	def textAlign(self):
		self._getter_access_tracker["textAlign"] = {}
		return self._textAlign
	@textAlign.setter
	def textAlign(self, state):
		self._setter_access_tracker["textAlign"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._textAlign = state
	@property
	def color(self):
		self._getter_access_tracker["color"] = {}
		return self._color
	@color.setter
	def color(self, state):
		self._setter_access_tracker["color"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._color = state
	@property
	def opacity(self):
		self._getter_access_tracker["opacity"] = {}
		return self._opacity
	@opacity.setter
	def opacity(self, state):
		self._setter_access_tracker["opacity"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._opacity = state
	@property
	def fontStyle(self):
		self._getter_access_tracker["fontStyle"] = {}
		return self._fontStyle
	@fontStyle.setter
	def fontStyle(self, state):
		self._setter_access_tracker["fontStyle"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._fontStyle = state
	@property
	def borderRadius(self):
		self._getter_access_tracker["borderRadius"] = {}
		return self._borderRadius
	@borderRadius.setter
	def borderRadius(self, state):
		self._setter_access_tracker["borderRadius"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._borderRadius = state
	@property
	def borderWidth(self):
		self._getter_access_tracker["borderWidth"] = {}
		return self._borderWidth
	@borderWidth.setter
	def borderWidth(self, state):
		self._setter_access_tracker["borderWidth"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._borderWidth = state
	@property
	def borderStyle(self):
		self._getter_access_tracker["borderStyle"] = {}
		return self._borderStyle
	@borderStyle.setter
	def borderStyle(self, state):
		self._setter_access_tracker["borderStyle"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._borderStyle = state
	@property
	def borderColor(self):
		self._getter_access_tracker["borderColor"] = {}
		return self._borderColor
	@borderColor.setter
	def borderColor(self, state):
		self._setter_access_tracker["borderColor"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._borderColor = state
	@property
	def backgroundImage(self):
		self._getter_access_tracker["backgroundImage"] = {}
		return self._backgroundImage
	@backgroundImage.setter
	def backgroundImage(self, state):
		self._setter_access_tracker["backgroundImage"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundImage = state
	@property
	def backgroundColor(self):
		self._getter_access_tracker["backgroundColor"] = {}
		return self._backgroundColor
	@backgroundColor.setter
	def backgroundColor(self, state):
		self._setter_access_tracker["backgroundColor"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundColor = state
	@property
	def backgroundClip(self):
		self._getter_access_tracker["backgroundClip"] = {}
		return self._backgroundClip
	@backgroundClip.setter
	def backgroundClip(self, state):
		self._setter_access_tracker["backgroundClip"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundClip = state
	@property
	def backgroundOrigin(self):
		self._getter_access_tracker["backgroundOrigin"] = {}
		return self._backgroundOrigin
	@backgroundOrigin.setter
	def backgroundOrigin(self, state):
		self._setter_access_tracker["backgroundOrigin"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundOrigin = state
	@property
	def backgroundAttachment(self):
		self._getter_access_tracker["backgroundAttachment"] = {}
		return self._backgroundAttachment
	@backgroundAttachment.setter
	def backgroundAttachment(self, state):
		self._setter_access_tracker["backgroundAttachment"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundAttachment = state
	@property
	def backgroundPositionX(self):
		self._getter_access_tracker["backgroundPositionX"] = {}
		return self._backgroundPositionX
	@backgroundPositionX.setter
	def backgroundPositionX(self, state):
		self._setter_access_tracker["backgroundPositionX"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundPositionX = state
	@property
	def backgroundPositionY(self):
		self._getter_access_tracker["backgroundPositionY"] = {}
		return self._backgroundPositionY
	@backgroundPositionY.setter
	def backgroundPositionY(self, state):
		self._setter_access_tracker["backgroundPositionY"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundPositionY = state
	@property
	def backgroundRepeat(self):
		self._getter_access_tracker["backgroundRepeat"] = {}
		return self._backgroundRepeat
	@backgroundRepeat.setter
	def backgroundRepeat(self, state):
		self._setter_access_tracker["backgroundRepeat"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._backgroundRepeat = state
	@property
	def position(self):
		self._getter_access_tracker["position"] = {}
		return self._position
	@position.setter
	def position(self, state):
		self._setter_access_tracker["position"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._position = state
	@property
	def float(self):
		self._getter_access_tracker["float"] = {}
		return self._float
	@float.setter
	def float(self, state):
		self._setter_access_tracker["float"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._float = state
	@property
	def clear(self):
		self._getter_access_tracker["clear"] = {}
		return self._clear
	@clear.setter
	def clear(self, state):
		self._setter_access_tracker["clear"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._clear = state
	@property
	def top(self):
		self._getter_access_tracker["top"] = {}
		return self._top
	@top.setter
	def top(self, state):
		self._setter_access_tracker["top"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._top = state
	@property
	def left(self):
		self._getter_access_tracker["left"] = {}
		return self._left
	@left.setter
	def left(self, state):
		self._setter_access_tracker["left"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._left = state
	@property
	def bottom(self):
		self._getter_access_tracker["bottom"] = {}
		return self._bottom
	@bottom.setter
	def bottom(self, state):
		self._setter_access_tracker["bottom"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._bottom = state
	@property
	def right(self):
		self._getter_access_tracker["right"] = {}
		return self._right
	@right.setter
	def right(self, state):
		self._setter_access_tracker["right"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._right = state
	@property
	def zIndex(self):
		self._getter_access_tracker["zIndex"] = {}
		return self._zIndex
	@zIndex.setter
	def zIndex(self, state):
		self._setter_access_tracker["zIndex"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._zIndex = state
	@property
	def outlineStyle(self):
		self._getter_access_tracker["outlineStyle"] = {}
		return self._outlineStyle
	@outlineStyle.setter
	def outlineStyle(self, state):
		self._setter_access_tracker["outlineStyle"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._outlineStyle = state
	@property
	def outlineColor(self):
		self._getter_access_tracker["outlineColor"] = {}
		return self._outlineColor
	@outlineColor.setter
	def outlineColor(self, state):
		self._setter_access_tracker["outlineColor"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._outlineColor = state
	@property
	def outlineOffset(self):
		self._getter_access_tracker["outlineOffset"] = {}
		return self._outlineOffset
	@outlineOffset.setter
	def outlineOffset(self, state):
		self._setter_access_tracker["outlineOffset"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._outlineOffset = state
	@property
	def outlineWidth(self):
		self._getter_access_tracker["outlineWidth"] = {}
		return self._outlineWidth
	@outlineWidth.setter
	def outlineWidth(self, state):
		self._setter_access_tracker["outlineWidth"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._outlineWidth = state
	@property
	def cursor(self):
		self._getter_access_tracker["cursor"] = {}
		return self._cursor
	@cursor.setter
	def cursor(self, state):
		self._setter_access_tracker["cursor"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._cursor = state
	@property
	def boxSizing(self):
		self._getter_access_tracker["boxSizing"] = {}
		return self._boxSizing
	@boxSizing.setter
	def boxSizing(self, state):
		self._setter_access_tracker["boxSizing"] = {}
		if self._state_is_none == True and state != None:
			self._state_is_none = False
		self._boxSizing = state
	def _to_json_fields(self):
		# if the provided state is none, return empty dict
		if self._state_is_none == True:
			return {}
		return {
			"display": self._display,
			"flexDirection": self._flexDirection,
			"alignItems": self._alignItems,
			"justifyContent": self._justifyContent,
			"flexWrap": self._flexWrap,
			"alignContent": self._alignContent,
			"rowGap": self._rowGap,
			"columnGap": self._columnGap,
			"alignSelf": self._alignSelf,
			"flexGrow": self._flexGrow,
			"flexShrink": self._flexShrink,
			"order": self._order,
			"marginTop": self._marginTop,
			"marginBottom": self._marginBottom,
			"marginRight": self._marginRight,
			"marginLeft": self._marginLeft,
			"paddingTop": self._paddingTop,
			"paddingBottom": self._paddingBottom,
			"paddingRight": self._paddingRight,
			"paddingLeft": self._paddingLeft,
			"width": self._width,
			"height": self._height,
			"minWidth": self._minWidth,
			"minHeight": self._minHeight,
			"maxWidth": self._maxWidth,
			"maxHeight": self._maxHeight,
			"overflow": self._overflow,
			"fontFamily": self._fontFamily,
			"fontWeight": self._fontWeight,
			"fontSize": self._fontSize,
			"textAlign": self._textAlign,
			"color": self._color,
			"opacity": self._opacity,
			"fontStyle": self._fontStyle,
			"borderRadius": self._borderRadius,
			"borderWidth": self._borderWidth,
			"borderStyle": self._borderStyle,
			"borderColor": self._borderColor,
			"backgroundImage": self._backgroundImage,
			"backgroundColor": self._backgroundColor,
			"backgroundClip": self._backgroundClip,
			"backgroundOrigin": self._backgroundOrigin,
			"backgroundAttachment": self._backgroundAttachment,
			"backgroundPositionX": self._backgroundPositionX,
			"backgroundPositionY": self._backgroundPositionY,
			"backgroundRepeat": self._backgroundRepeat,
			"position": self._position,
			"float": self._float,
			"clear": self._clear,
			"top": self._top,
			"left": self._left,
			"bottom": self._bottom,
			"right": self._right,
			"zIndex": self._zIndex,
			"outlineStyle": self._outlineStyle,
			"outlineColor": self._outlineColor,
			"outlineOffset": self._outlineOffset,
			"outlineWidth": self._outlineWidth,
			"cursor": self._cursor,
			"boxSizing": self._boxSizing,
			}


import glob
import logging
import os.path as op
from datetime import datetime
from os import makedirs, remove
from typing import Optional
from zipfile import ZipFile, BadZipFile

from django.conf import settings

from addcorpus import extract, filters
from addcorpus.corpus import FieldDefinition, XMLCorpusDefinition
from addcorpus.es_mappings import keyword_mapping, main_content_mapping
from addcorpus.es_settings import es_settings

logger = logging.getLogger('indexing')

def rdf_description_extractor(tag, section='xml', **kwargs):
    '''rdf:Description extractor
    There are two rdf:Description tags available in the data:
        - description about the open data enrichment
        - description about the source
    There is only deterministic way to select the right one:
        - check the dcterms:format sibling tag'''
    return extract.XML(
        tag=tag,
        secondary_tag={'tag': 'dcterms:format', 'exact': f'text/{section}'},
        **kwargs
    )

class Rechtspraak(XMLCorpusDefinition):
    title = "Judicial system Netherlands"
    description = "Open data of (anonymised) court rulings of the Dutch judicial system"
    min_date = datetime(year=1900, month=1, day=1)
    max_date = datetime(year=2022, month=12, day=6)
    data_directory = settings.RECHTSPRAAK_DATA
    es_index = getattr(settings, 'RECHTSPRAAK_ES_INDEX', 'rechtspraak')
    image = 'rechtszaal.jpeg'
    description_page = 'rechtspraak.md'
    toplevel_zip_file = 'OpenDataUitspraken.zip'
    languages = ['nl']
    category = 'ruling'

    @property
    def es_settings(self):
        return es_settings(self.languages[:1], stopword_analysis=True, stemming_analysis=True)

    tag_toplevel = 'open-rechtspraak'

    def unpack(self,
               min_year: Optional[int] = None,
               max_year: Optional[int] = None,
               how: str = 'full',
               per_year: int = 5,
               per_archive: int = 5
               ):
        if not min_year:
            min_year = self.min_date.year
        if not max_year:
            max_year = self.max_date.year

        years = range(min_year, max_year+1)

        logger.info(f'Started unpacking with strategy: {how}')
        toplevel_file = op.join(self.data_directory, self.toplevel_zip_file)
        if not op.isfile(toplevel_file):
            logger.error(f'File {toplevel_file} does not exist, aborting.')
            raise FileNotFoundError()

        unpack_dir = op.join(self.data_directory, 'unpacked')
        makedirs(unpack_dir, exist_ok=True)

        # the toplevel archive contains folders per year
        # each containing more archives
        with ZipFile(toplevel_file, 'r') as zf:
            zipnames = zf.namelist()

            # process these per year
            years_archives = {
                year: [zn for zn in zipnames if zn.startswith(f'{year}/')]
                for year in years
            }

            # filter out empty years
            years_archives = {
                year: archives
                for year, archives in years_archives.items()
                if archives
            }

            # unpack a number of nested archives for each year
            # if unpacking a sample, limit to per_year
            for year, archives in years_archives.items():
                if how == 'sample':
                    archives = archives[:min(per_year, len(archives))]
                logger.info(
                    f'Unpacking year {year}, {len(archives)} archives.')
                for arch in archives:
                    # unpack the nested archive
                    if not op.exists(op.join(unpack_dir, arch)):
                        zf.extract(arch, unpack_dir)
                    else:
                        logger.warning(
                            f'Skipped existing {op.join(unpack_dir, arch)}')

                    # finally, unpack the nested archive
                    # containing XML data files
                    # if unpacking a sample, limit to per_archive
                    try:
                        with ZipFile(op.join(unpack_dir, arch)) as nestedz:
                            target_dir = op.join(unpack_dir, str(year))
                            if how == 'sample':
                                members = nestedz.namelist()
                                to_extract = members[:min(
                                    per_archive, len(members))]
                                nestedz.extractall(
                                    target_dir, members=to_extract)
                            else:
                                nestedz.extractall(target_dir)
                            remove(op.join(unpack_dir, arch))
                    except BadZipFile:
                        logger.warning(
                            f'skipping bad file {op.join(unpack_dir, arch)}')

    def sources(self, min_date: Optional[int] = None, max_date: Optional[int] = None):
        if not min_date:
            min_date = self.min_date
        if not max_date:
            max_date = self.max_date

        for year in range(min_date.year, max_date.year+1):
            glob_pattern = f'{self.data_directory}/unpacked/{year}/*.xml'
            files = glob.glob(glob_pattern)
            for f in files:
                yield f, {'year': year}

    fields = [
        FieldDefinition(
            name='id',
            display_name='ID',
            description='',
            es_mapping=keyword_mapping(),
            extractor=rdf_description_extractor('dcterms:identifier'),
            csv_core=True,
        ),
        FieldDefinition(
            name='has_content',
            display_name='Has text content',
            description='Document has available text content.',
            es_mapping={'type': 'boolean'},
            extractor=extract.Backup(
                extract.XML('uitspraak', flatten=True),
                extract.XML('conclusie', flatten=True),
                extract.Constant(False),
                transform=bool
            ),
            search_filter=filters.BooleanFilter(
                true='has content',
                false='does not have content',
                description=(
                    'Accept only articles that have available text content.'
                )
            ),
        ),
        FieldDefinition(
            name='year',
            display_name='Year',
            es_mapping={'type': 'integer'},
            extractor=extract.Metadata('year'),
            search_filter=filters.RangeFilter(min_date.year, max_date.year)
        ),
        FieldDefinition(
            name='date',
            display_name='Date',
            extractor=rdf_description_extractor('dcterms:date'),
            es_mapping={'type': 'date', 'format': 'yyyy-MM-dd'},
            results_overview=True,
            primary_sort=True,
            csv_core=True,
            search_filter=filters.DateFilter(
                min_date,
                max_date,
                description=(
                    'Accept only rulings with date in this range.'
                )
            ),

        ),
        FieldDefinition(
            name='issued',
            display_name='Publication Date',
            extractor=rdf_description_extractor('dcterms:issued'),
            es_mapping={'type': 'date', 'format': 'yyyy-MM-dd'},
            search_filter=filters.DateFilter(
                min_date,
                max_date,
                description=(
                    'Accept only rulings with publication date in this range.'
                )
            ),
        ),
        FieldDefinition(
            name='publisher',
            display_name='Publisher',
            extractor=rdf_description_extractor('dcterms:publisher'),
            es_mapping={'type': 'keyword'}
        ),
        FieldDefinition(
            name='creator',
            display_name='Court',
            extractor=rdf_description_extractor('dcterms:creator'),
            es_mapping={'type': 'keyword'},
            csv_core=True,
            results_overview=True,
            search_filter=filters.MultipleChoiceFilter(
                description='Accept only rulings of selected courts.',
                option_count=9999
            ),
            visualizations=['resultscount', 'termfrequency']
        ),
        FieldDefinition(
            name='zaaknr',
            display_name='Case Number',
            es_mapping=keyword_mapping(),
            extractor=rdf_description_extractor('psi:zaaknummer')
        ),
        FieldDefinition(
            name='type',
            display_name='Type',
            extractor=rdf_description_extractor('dcterms:type'),
            es_mapping={'type': 'keyword'},
            csv_core=True,
            results_overview=True,
            search_filter=filters.MultipleChoiceFilter(
                description='Accept only rulings of selected type.',
                option_count=2
            ),
            visualizations=['resultscount', 'termfrequency']
        ),
        FieldDefinition(
            name='procedure',
            display_name='(type of) Procedure',
            extractor=rdf_description_extractor('psi:procedure'),
            csv_core=True,
            es_mapping={'type': 'keyword'},
            search_filter=filters.MultipleChoiceFilter(
                description='Accept only rulings of selected procedure type.',
                option_count=44
            ),
            visualizations=['resultscount', 'termfrequency']
        ),
        FieldDefinition(
            name='spatial',
            display_name='Location',
            es_mapping=keyword_mapping(),
            extractor=rdf_description_extractor('dcterms:spatial')
        ),
        FieldDefinition(
            name='subject',
            display_name='Area of law',
            extractor=rdf_description_extractor('dcterms:subject'),
            csv_core=True,
            es_mapping={'type': 'keyword'},
            search_filter=filters.MultipleChoiceFilter(
                description='Accept only rulings within this area of law.',
                option_count=32
            ),
            visualizations=['resultscount', 'termfrequency']
        ),
        FieldDefinition(
            name='title',
            display_name='Title',
            extractor=rdf_description_extractor(
                'dcterms:title', section='html'),
            results_overview=True,
            search_field_core=True,
        ),
        FieldDefinition(
            name='abstract',
            display_name='Abstract',
            extractor=extract.XML(tag='inhoudsindicatie', flatten=True),
            results_overview=True,
        ),
        FieldDefinition(
            name='content',
            display_name='Content',
            display_type='text_content',
            es_mapping=main_content_mapping(True, True, True, 'nl'),
            extractor=extract.Backup(
                extract.XML('uitspraak', flatten=True),
                extract.XML('conclusie', flatten=True),
                extract.Constant('Content not available')
            ),
            csv_core=True,
            search_field_core=True,
        ),
        FieldDefinition(
            name='url',
            display_name='URL',
            es_mapping=keyword_mapping(),
            extractor=rdf_description_extractor(
                'dcterms:identifier', section='html')
        )
    ]


#Kmeans clustering

#importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

#read dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values
y = dataset.iloc[:, 4].values

#splitting datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)

wcss = []
for i in range(1,11):
    KCluster = KMeans(n_clusters=i, random_state=0, init='k-means++', max_iter=300, n_init=10)
    KCluster.fit(X)
    wcss.append(KCluster.inertia_)

#visualizing dataset
#plt.plot(range(1,11), wcss)
#plt.title('ELBOW METHOD')
#plt.xlabel('# of clusters')
#plt.ylabel('# of Sum Squared Distance')
#plt.show()

#applying kmeans to mall dataset
KCluster = KMeans(n_clusters=5, init='k-means++', random_state=0, max_iter=300, n_init=10)
y_kmeans = KCluster.fit_predict(X)

#visualizing clusters
plt.scatter(X[y_kmeans==0, 0], X[y_kmeans==0, 1], s=100, c='red', label='CLUSTER 1')
plt.scatter(X[y_kmeans==1, 0], X[y_kmeans==1, 1], s=100, c='blue', label='CLUSTER 2')
plt.scatter(X[y_kmeans==2, 0], X[y_kmeans==2, 1], s=100, c='green', label='CLUSTER 3')
plt.scatter(X[y_kmeans==3, 0], X[y_kmeans==3, 1], s=100, c='cyan', label='CLUSTER 4')
plt.scatter(X[y_kmeans==4, 0], X[y_kmeans==4, 1], s=100, c='magenta', label='CLUSTER 5')
plt.scatter(KCluster.cluster_centers_[:,0], KCluster.cluster_centers_[:, 1], s=300, c='yellow', label='centroid')
plt.title('Clusters of clients')
plt.xlabel('Annual income')
plt.ylabel('Spending income')
plt.legend()
plt.show()


import os
import sys
import re
import base
import random

from utils import hcf_auth
from utils import hcf_organisations
from utils import hcf_marketplace
from utils import hcf_space

class TestHcfMarketplace(base.BaseTest):

    """
    SetupClass prepares the following preconditions for
    Marketplace tests
    * Connect to the cluster URI target
    """

    @classmethod
    def setUpClass(cls):
        super(TestHcfMarketplace, cls).setUpClass()

        # Connect to the cluster URI target
        hcf_auth.connect_target(cls.cluster_url,
                                optional_args={'--skip-ssl-validation': ' '})
        # Log into Cluster using creds
        hcf_auth.login(optional_args={'-u': cls.username, '-p': cls.password})
        # Create organisation
        cls.setup_org = 'og_test_org' + str(random.randint(1024, 4096))
        out, err = hcf_organisations.create_org(cls.setup_org)
        out, err = hcf_auth.target(optional_args={'-o': cls.setup_org})
        # Create Space
        cls.setup_space = 'sp_test_space' + str(random.randint(1024, 4096))
        out, err = hcf_space.create_space(cls.setup_space)
        out, err = hcf_auth.target(optional_args={'-o': cls.setup_org,
                                                  '-s': cls.setup_space})

    @classmethod
    def tearDownClass(cls):
        super(TestHcfMarketplace, cls).tearDownClass()
        hcf_organisations.delete_org(cls.setup_org, input_data=b'yes\n')
        hcf_auth.logout(cls.cluster_url)

    def test_hcf_marketplace(self):
        # List all offerings
        out, err = hcf_marketplace.marketplace()
        self.verify("OK", out)
        self.verify(
            "Getting services from marketplace in org " + self.setup_org + ""
            " / space " + self.setup_space, out)

if __name__ == '__main__':
    base.unittest.main(verbosity=2)


import os

import pytest
from _decimal import Decimal

from blockapi.v2.api import PerpetualApi, perp_contract_address
from blockapi.v2.base import ApiException
from blockapi.v2.models import FetchResult

@pytest.fixture
def perp_api():
    return PerpetualApi('http://localhost:2048/')

test_address = '0x134089B387E22f52b1e06CC80d9a5F622032EF74'

def test_perp_contract_address():
    contract = perp_contract_address('PERP')
    assert contract == '0xbC396689893D065F41bc2C6EcbeE5e0085233447'

def test_perp_invalid_contract_raises():
    with pytest.raises(ValueError, match='Invalid contract name.'):
        perp_contract_address("abc")

def test_perp_has_coin(perp_api):
    assert perp_api.coin.symbol == 'PERP'

def filter_infura_key(request):
    if 'infura.io' in request.host:
        request.uri = 'https://mainnet.infura.io/v3/API_KEY_FILTERED'
    return request

@pytest.mark.integration
def test_fetch():
    key = os.environ.get('INFURA_API_KEY')
    api = PerpetualApi(f'https://mainnet.infura.io/v3/{key}')
    raw = api.fetch_balances(test_address)
    assert raw.data

@pytest.mark.integration
def test_fetch_error():
    api = PerpetualApi(f'https://mainnet.infura.io/v3/no-key')
    raw = api.fetch_balances(test_address)
    assert raw.status_code == 401
    assert (
        raw.errors[0]
        == '401 Client Error: Unauthorized for url: https://mainnet.infura.io/v3/no-key'
    )

def test_fetch_error_raises_from_get_balances():
    api = PerpetualApi(f'https://mainnet.infura.io/v3/no-key')
    with pytest.raises(ApiException) as exc:
        api.get_balance(test_address)

    assert exc.match('401 Client Error: Unauthorized for url')

def test_parse(perp_api):
    raw = FetchResult(
        status_code=200,
        data=dict(
            staking_claimable='1.10',
            vesting_claimable='2.02',
            vesting_locked='3.30',
        ),
    )

    parsed = perp_api.parse_balances(raw)

    assert parsed.data[0].balance == Decimal('3.12')
    assert parsed.data[1].balance == Decimal('3.30')


import math
import numpy as np
from statistics import median
from collections import Counter

def euclidean_distance(x1, x2):
    return np.sqrt(np.sum((x1-x2)**2))

# def predict(self, X):
#     predictions = [self._predict(x)for x in X]
#     return np.array(predictions)

def get_RDOS(p,x, y_train, k ):
    distance = [euclidean_distance(p, i)for i in x]

    k_indices = np.argsort(distance)[:k]
    # print(k_indices)
    k_nearest_labels = [y_train[i]for i in k_indices]

    # most_common = Counter(k_nearest_labels).most_common(1)
    # it returns the most commmon item in form of tuple
    # return most_common[0][0]

    # finding the forward density
    sorted_distance = sorted(distance)
    sorted_distance = list(filter(lambda a: a != 0.00, sorted_distance))
    fd_list = []
    for i in range(k):
        forward_density = (i+1)/sorted_distance[i]
        fd_list.append(forward_density)
    # finding the ranking of x by q
    N_x = []
    for k in k_indices:
        N_x.append(x[k])

    reverse_list = []
    for s in N_x:
        count, R = 0, 0
        if s in x:
            distance2 = [euclidean_distance(
                s, x_train)for x_train in x]
        distance2 = sorted(distance2)
        distance2 = list(filter(lambda a: a != 0.00, distance2))
        for dis in distance2:
            if dis < sorted_distance[count]:
                R += 1
        reverse_list.append(R)
        count += 1
    # calculating the RDOS values
    count = 0
    RDOS = []
    for i in range(4):
        count += 1
        RDOS.append((reverse_list[i]-count)/fd_list[i])

    return median(RDOS)

def delta(i,j,x, y_train, k):
    return abs(get_RDOS(i,x, y_train, k)-get_RDOS(j,x, y_train, k))

def infodist(x, y_train, k):
    dist = []
    answer = []
    for i in x:
        k_indices = []
        dist = []
        for j in x:
            dist.append(euclidean_distance(i,j)*(1+math.log(1+delta(i,j,x, y_train, k))))

        k_indices = np.argsort(dist)[:k]

        #print(k_indices)

        k_nearest_labels = []

        for i in k_indices:
            k_nearest_labels.append(y_train[i])

        most_common = Counter(k_nearest_labels).most_common(1)
            # it returns the most commmon item in form of tuple
        answer.append(most_common[0][0])

    return answer


import cv2
import numpy as np
import configparser

from utils import to_int, COLORS_HSV_VALUES, DRAWING_COLORS

drawingPoints = []  # x-coordinate, y-coordinate, drawingColorIndex in `DRAWING_COLORS` list

def get_contours_top_center_point(img):
    """
    Returns top center coordinates of the detected contour
    Optionally can show contour too
    """
    contours, heirarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # image, retrieval method, approximation-(where you can request for all info or we can request for compressed info)
    # RETR_EXTERNAL retrieves extremes outer contours, there are other retrieval methods too
    x, y, w, h = 0, 0, 0, 0
    # contours are saved in contours variable above
    for cnt in contours:
        area = cv2.contourArea(cnt) # Find area of contour
        # Now to neglect smaller shapes, if any
        if area > 500:
            # This will draw a blue line on the imgFinal image
            # cv2.drawContours(imgFinal, cnt, -1, (255, 0, 0), 3) # Draw the contours, params: img, contour, contour_index(-1 means all the contours), color, thickness

            # Now we will calculate curve length, it will help us approximate corners of our shape
            peri = cv2.arcLength(cnt, True)  # params: curve, closed or not
            corner_points = cv2.approxPolyDP(cnt, 0.02*peri, True) # contour, resolution(play around with to get good results), closed or not
            # Now we create bounding box around detected object
            # To draw bounding box, we need x and y and also width and height
            x, y, w, h = cv2.boundingRect(corner_points)
    # Now we want to draw from tip of object
    return x+w//2, y # Center coordinate and top point

def paintCanvas(drawingPoints, imgFinal):
    """
    Paints the image when the color is moved on the screen
    Looping is done as more than one can color can be present
    """
    for point in drawingPoints:
        cv2.circle(imgFinal, (point[0], point[1]), 7, DRAWING_COLORS[point[2]], cv2.FILLED) # params: image, center points, radius, color, thickness

def detect_color(img, imgFinal):
    """
    Here more than single color can be detected
    :return coordinates and index of drawingColor
    """
    # Convert to HSV, as it is easier to represent a color in it than in BGR color-space
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    counter = 0
    # To store current color details
    curr_points = []
    # Looping to detect all the colors mentioned in list
    for color in COLORS_HSV_VALUES:
        # Now we will used these values to filter out image, so we can get image in that particular color in that range
        lower_limit = np.array(color[0:3]) # First three
        upper_limit = np.array(color[3:6]) # Last three
        # This will filter out
        mask = cv2.inRange(imgHSV, lower_limit, upper_limit)
        # cv2.imshow(str(color[0]), mask) # As we can not have a generic name so we for now we just write Hue Min Value
        # Now we can also draw a boundary around the captured color
        x, y = get_contours_top_center_point(mask)
        # Draw a circle on the center on the top of the contour
        cv2.circle(imgFinal, (x, y), 7, DRAWING_COLORS[counter], cv2.FILLED) # params: image, center points, radius, color, thickness
        # If we have detected color and received it's top's center coordinates
        if x and y:
            # Append the details of the current color
            curr_points.append([x,y, counter])
        counter += 1
    return curr_points, imgFinal

def capture_and_paint():
    """
    Captures a video to perform futher operations
    Looping is done as video is just a sequence of images, so we need while loop to go through each frame
    """
    #
    while True:
        # Read each frame
        ret, frame = cap.read()
        # Make a copy original image, on which we can draw
        imgFinal = frame.copy()
        # Now detect color shown on screen
        curr_points, imgF = detect_color(frame, imgFinal) # Returns coordinates and index of the color
        if curr_points:
            # As more than one colors can be shown on the screen
            for point in curr_points:
                drawingPoints.append(point)
        if drawingPoints:
            paintCanvas(drawingPoints, imgF)

        # Now display the painted frame
        cv2.imshow("Result", imgFinal)

        # Now add delay and also add `q` button press to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

if __name__ == '__main__':
    config = configparser.ConfigParser()
    configFilePath = "/home/shantanu/stuff/projects/virtual-paint/config.ini"
    # Read config file
    config.read(configFilePath)
    frameWidth = to_int(config['video']['frameWidth'])
    frameHeight = to_int(config['video']['frameWidth'])
    brightness = to_int(config['video']['brightness'])

    # Capture using webcam
    cap = cv2.VideoCapture(0)
    # Set width and height of frame
    cap.set(3, frameHeight) # First param is Property Identifer for the video
    # Read here: https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-get
    # Or refer propID.txt
    cap.set(4, frameWidth)
    # Set the brightness
    cap.set(10, brightness)
    # Call the processing function
    capture_and_paint()


import random
import os
import glob
import argparse

# Find all files in dir with extension (to exclude other files)
def find_files_in(path, with_extension = ""):
    pattern = path + "/*." + with_extension
    return glob.glob(pattern)

# Makes directories
def make_dirs(path, train_dir_name = 'train', test_dir_name = 'test'):
    for dir_name in [train_dir_name, test_dir_name]:
        try:
            os.mkdir(path + "/" + dir_name)
        except OSError:
            print ("Creation of the directory %s failed" % path + "/" + dir_name)
        else:
            print ("Successfully created the directory %s " % path + "/" + dir_name)

# Selects randomly the files according to a preset policy
# Moves the files
def random_select(list_of_files, percentage_split, train_dir_path, test_dir_path):
    for file in list_of_files:
        path, filename = os.path.split(file)

        choices = ['test'] * int((percentage_split * 100)) + ['train'] * int(((1 - percentage_split) * 100))

        choice = random.choice(choices)

        is_training = choice == 'train'

        # Search for similar files to move them as well
        pattern = path + "/" + os.path.splitext(filename)[0] +".*"
        files = glob.glob(pattern)
        for file_i in files:
            _ , filename_i = os.path.split(file_i)
            if is_training:
                os.rename(file_i, train_dir_path + "/" + filename_i)
            else:
                os.rename(file_i, test_dir_path + "/" + filename_i)

def main(path, train_dir_name = "train", test_dir_name = "test", file_extension = "jpg", split_strategy = 0.5):
    file_paths = find_files_in(path, file_extension)
    make_dirs(path,train_dir_name, test_dir_name)
    random_select(file_paths, split_strategy, path + "/" + test_dir_name, path + "/" + train_dir_name)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument(
        '--path', type=str,
        help='path to images ',
        default=os.getcwd()
    )

    parser.add_argument(
        '--train_dir_name', type=str,
        help='Name of train data directory name ',
        default='train'
    )

    parser.add_argument(
        '--test_dir_name', type=str,
        help='Name of test data directory name ',
        default='test'
    )

    parser.add_argument(
        '--file_extension', type=str,
        help='The extension of the file you want to get handled ',
        default='jpg'
    )

    parser.add_argument(
        '--split_strategy', type=float,
        help='Percentage of split strategy to split training and test data ',
        default=0.5
    )

    args = vars(parser.parse_args())

    main(args["path"],args["train_dir_name"], args["test_dir_name"], args["file_extension"],
         args["split_strategy"])


import cv2
import time
import serial #导入模块
import serial.tools.list_ports

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
count = 0
count2 = 0
count3 = 0
state = 1
#1 = waiting for food
#2 = food is ready
#3 = dangerous
#4 = got food

ports = list(serial.tools.list_ports.comports())
print (ports)
for p in ports:
    print (p[1])
    if "SERIAL" in p[1] or"UART" in p[1] or "Arduino" in p[1] :
	    ser=serial.Serial(port=p[0])
	    break
    else :
	    print ("No Arduino Device was found connected to the computer")
time.sleep(5)
'''
def response(inp_data):
    if 'foodready' in inp_data:
        print('food is ready')
        state = 2
'''

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FPS, 30)
while state == 1:
    input_data = ser.readline()
    inp_data = str(input_data)
    ret, frame = cap.read()
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(frame, 1.3, 5)
    for (x,y,w,h) in faces:
        frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

    if len(faces) != 0:
        count += 1
        frame = cv2.circle(frame,(20,20),5,(0,0,255),5)
    else:
        count2 += 1

    if count2 >= 30:
        frame = cv2.circle(frame,(20,20),5,(0,255,0),5)
        print('delivery man is away')
        count = 0
        count2 = 0
        time.sleep(1)
        ser.write('0'.encode())
        time.sleep(1)

        if 'foodready' in inp_data:
            print('food is ready')
            state = 2
    elif count >= 30:
        print('alarm')
        count = 0
        count2 = 0
        count3 += 1
        #ser.write('1'.encode())
        time.sleep(1)

    elif count3 >= 3:
        print('dangerous situation')
        #ser.write('danger'.encode()) ###############

    print(count2)
    cv2.imshow('img',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    time.sleep(.5)

while state == 2:
    input_data = ser.readline()
    inp_data = str(input_data)
    print('come and get your food')
    time.sleep(3)
    if 'something' in inp_data:          ############
        print('user taken the food')
        state = 4
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

while state == 4:
    input_data = ser.readline()
    inp_data = str(input_data)
    #ser.write('gotfood'.encode())        ##########
    if 'something' in inp_data:    ###############
        print('close the cover')
        time.sleep(10)
        break
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


from direct.directnotify import DirectNotifyGlobal
from toontown.estate.DistributedFurnitureItemAI import DistributedFurnitureItemAI
from direct.distributed.ClockDelta import *
import BankGlobals

class DistributedBankAI(DistributedFurnitureItemAI):
    notify = DirectNotifyGlobal.directNotify.newCategory("DistributedBankAI")

    def __init__(self, air, furnitureMgr, item):
        DistributedFurnitureItemAI.__init__(self, air, furnitureMgr, item)
        self.avId = None
        self.movie = BankGlobals.BANK_MOVIE_CLEAR

    def avatarEnter(self):
        avId = self.air.getAvatarIdFromSender()
        if not self.avId:
            if not self.furnitureMgr.ownerId:
                self.b_setMovie(BankGlobals.BANK_MOVIE_NO_OWNER, avId, globalClockDelta.getRealNetworkTime())
                return
            elif self.furnitureMgr.ownerId != avId:
                self.b_setMovie(BankGlobals.BANK_MOVIE_NOT_OWNER, avId, globalClockDelta.getRealNetworkTime())
                return
            else:
                self.avId = avId
                self.b_setMovie(BankGlobals.BANK_MOVIE_GUI, avId, globalClockDelta.getRealNetworkTime())
                return
        else:
            if avId == self.avId:
                self.air.writeServerEvent('suspicious', avId=avId, issue='Tried to use bank while already using it!')
            self.sendUpdateToAvatarId(avId, 'freeAvatar', [])

    def freeAvatar(self):
        pass

    def setMovie(self, mode, avId, time):
        self.movie = mode
        if self.movie != BankGlobals.BANK_MOVIE_CLEAR:
            taskMgr.doMethodLater(2.0, self.clearMovie, 'clear-movie-%d' % self.getDoId())

    def clearMovie(self, task):
        self.b_setMovie(BankGlobals.BANK_MOVIE_CLEAR, 0, globalClockDelta.getRealNetworkTime())

    def b_setMovie(self, mode, avId, time):
        self.setMovie(mode, avId, time)
        self.d_setMovie(mode, avId, time)

    def d_setMovie(self, mode, avId, time):
        self.sendUpdate('setMovie', [mode, avId, time])

    def transferMoney(self, amount):
        avId = self.air.getAvatarIdFromSender()
        if avId != self.avId:
            self.air.writeServerEvent('suspicious', avId=avId, issue='Tried to transfer money while not using a bank!')
            return
        av = self.air.doId2do.get(avId)
        if not av:
            self.air.writeServerEvent('suspicious', avId=avId, issue='Tried to transfer money while not on the AI!')
            return
        if amount == 0: # No transfer needed.
            self.b_setMovie(BankGlobals.BANK_MOVIE_NO_OP, avId, globalClockDelta.getRealNetworkTime())
        elif amount > 0:
            self.b_setMovie(BankGlobals.BANK_MOVIE_DEPOSIT, avId, globalClockDelta.getRealNetworkTime())
            if av.money < amount:
                self.air.writeServerEvent('suspicious', avId=avId, issue='Toon tried to deposit more money than they have!')
            else:
                av.b_setMoney(av.money - amount)
                av.b_setBankMoney(av.bankMoney + amount)
        else:
            self.b_setMovie(BankGlobals.BANK_MOVIE_WITHDRAW, avId, globalClockDelta.getRealNetworkTime())
            if av.bankMoney + amount < 0:
                self.air.writeServerEvent('suspicious', avId=avId, issue='Toon tried to withdraw more money than they have!')
            else:
                av.b_setMoney(av.money - amount)
                av.b_setBankMoney(av.bankMoney + amount)

        self.avId = None


import pandas as pd
import pandas_profiling
import streamlit as st
from st_on_hover_tabs import on_hover_tabs
import os
from streamlit_pandas_profiling import st_profile_report

st.set_page_config(layout="wide")
st.markdown('<style>' + open('./style/style.css').read() + '</style>', unsafe_allow_html=True)
if os.path.exists('./data/dataset.csv'):
    df = pd.read_csv('./data/dataset.csv', index_col=None)
st.title("Tuto analyse automatisÃ©e de vos donnÃ©es ")
with st.sidebar:
    tabs = on_hover_tabs(tabName=['Charger les donnÃ©es', 'Analyser', 'Exporter'],
                         iconName=['upload file', 'analytics', 'download'], default_choice=0)
    st.image("./style/iiidata.png")

if tabs == 'Charger les donnÃ©es':
    file = st.file_uploader("Chargez vos donnÃ©es")
    separator = st.radio("Si votre dataset ne s'affiche pas correctement,sÃ©lectionner le bon sÃ©parateur",
                         [",", ";"])
    if file:
        df = pd.read_csv(file, index_col=None, sep = separator)
        df.to_csv('./data/dataset.csv', index=None)
        if len(df.columns) >= 2 :
            st.success("DonnÃ©es chargÃ©es correctement, vous pouvez passer Ã  l'analyse")
        else :
            st.error('Il semblerait que vous avez sÃ©lectionnÃ© le mauvais sÃ©parateur')
        st.dataframe(df)

elif tabs == 'Analyser':
    st.header("Rapport d'analyse exploratoire des donnÃ©es")
    profile_df = df.profile_report()
    st_profile_report(profile_df)
    profile_df.to_file("output.html")

elif tabs == 'Exporter':
    with open("output.html", "rb") as f:
        dl = st.download_button("TÃ©lÃ©charger le rapport ðŸ’¾ ", f, "rapport_analyse_data.html")
        st.balloons()
        # if dl :