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

import rospy
import sys
import moveit_commander
from moveit_ros_planning_interface import _moveit_move_group_interface
import tf
import copy
import threading
import numpy as np
import json
import cmath
import math
from geometry_msgs.msg import PoseStamped,Pose,PointStamped
from sensor_msgs.msg import JointState

class draw_face_demo:
    def __init__(self):

        rospy.init_node('draw_face_demo',anonymous = True)

        moveit_commander.roscpp_initialize(sys.argv)

        self.arm = moveit_commander.MoveGroupCommander('ur3_arm')

        self.end_effector_link = self.arm.get_end_effector_link()

        self.reference_frame = 'base_link'

        self.arm.allow_replanning(False)

        self.arm.set_max_velocity_scaling_factor(0.5)
        self.arm.set_max_acceleration_scaling_factor(0.5)

        self.arm.set_goal_position_tolerance(0.01)
        self.arm.set_goal_orientation_tolerance(0.05)

        self.arm.set_start_state_to_current_state()

        self.draw_plan = self.arm.plan()
        self.max_fraction_plan = self.arm.plan()

        self.waypoints = []

    def draw_face_test(self):

        self.arm.set_named_target("write")
        self.arm.go()
        rospy.sleep(1.0)

        start_point = self.arm.get_current_pose().pose

        start_pointX = start_point.position.x
        start_pointY = start_point.position.y
        start_pointZ = start_point.position.z

        filename = '/home/cjw/PycharmProjects/Face_Painting/image/draw.txt'

        fraction = 0.0
        max_fraction = 0.0

        write_point = self.arm.get_current_pose().pose

        self.waypoints.append(copy.deepcopy(write_point))
        write_point.position.x += 0.10
        self.waypoints.append(copy.deepcopy(write_point))

        with open(filename,'r') as file_to_read:

            list = []

            while True:

                lines = file_to_read.readline()
                if not lines:
                    break

                item = [j for j in lines.split(",")]
                point_x = json.loads(item[0])
                point_y = json.loads(item[1])

                if point_x != 0 or point_y != 0:

                    point_x = (150 - point_x) / (150*10.0) + write_point.position.y - 0.02
                    point_y = (150 - point_y) / (150*10.0) + write_point.position.z - 0.05

                    # point_x = point_x / (436*10.0) + write_point.position.y - 0.02
                    # point_y = point_y / (452*10.0) + write_point.position.z - 0.05

                list.append([point_x,point_y])
            print(len(list))
            print("!------------------!")
            for k in range(0,len(list)-1,1):

                if list[k][0] == 0 and list[k][1] == 0:
                    write_point.position.x -= 0.02
                    self.waypoints.append(copy.deepcopy(write_point))

                    k += 1

                    if( (list[k][0] != 0.0 and list[k][1] != 0.0) and (list[k+1][0] == 0.0 and list[k+1][1] == 0.0)):
                        print("Only one point , Pass!!!!")
                        k += 2
                            # continue

                    write_point.position.y = list[k][0]
                    write_point.position.z = list[k][1]

                    self.waypoints.append(copy.deepcopy(write_point))

                    write_point.position.x += 0.02
                    self.waypoints.append(copy.deepcopy(write_point))
                else:

                    write_point.position.y = list[k][0]
                    write_point.position.z = list[k][1]

                    self.waypoints.append(copy.deepcopy(write_point))

        write_point.position.x -= 0.02
        self.waypoints.append(copy.deepcopy(write_point))

        for l in range(0,100):

            (self.draw_plan, fraction) = self.arm.compute_cartesian_path(
                                         self.waypoints,   # self.waypoints to follow
                                         0.001,        # eef_step
                                         0.0)         # jump_threshold

            if fraction > max_fraction:
                max_fraction = fraction
                self.max_fraction_plan = self.draw_plan

            if fraction == 1.0:
                break

        print(max_fraction)
        if max_fraction == 1.0:
            self.arm.execute(self.max_fraction_plan,wait=True)
            del self.waypoints[:]
        else:
            del self.waypoints[:]

        rospy.sleep(3.0)

if __name__ == "__main__":

    test = draw_face_demo()
    test.draw_face_test()


# -*- coding: utf-8 -*-
import copy

import numpy as np

from .parameters import REAXFF_PARAM_DTYPE

__all__ = ['get_default_step_size']

def get_default_step_size(optimization_level: int=0) -> dict:
    """
    Get the default step size by the optimization level

    Parameters
    ----------
    optimization_level
        optimization level range from 0 to 5
        where level 0 is the QEq parameters

    Returns
    -------
    step_size: np.ndarray
        np.ndarray object of the step size

    See Also
    --------
    __get_default_step_size_reaxff_helper

    """

    category_by_level = __get_step_size_by_optimization_level(
        optimization_level)

    pmove = map(lambda category:
                __get_default_step_size_reaxff_helper(category),
                category_by_level.values())

    step_size = dict(zip(REAXFF_PMOVE_CATEGORY.keys(), pmove))

    return step_size

def __get_default_step_size_reaxff_helper(pmove: dict) -> np.ndarray:
    """
    Helper function for packing the step_size from dictionary to np.ndarray

    Parameters
    ----------
    pmove

    Returns
    -------
    np.ndarray

    """

    return np.fromiter(zip(pmove.keys(), pmove.values()),
                       dtype=REAXFF_PARAM_DTYPE)

def __get_step_size_by_optimization_level(
        optimization_level: int=0) -> dict:
    """

    Parameters
    ----------
    optimization_level
        level of the optimization range from 0 to 5

    Returns
    -------
    category_by_level
        a dictionary object of step size

    See Also
    --------
    __get_step_sizes_by_optimization_level_helper

    """

    if not isinstance(optimization_level, int):
        optimization_level = int(optimization_level)

    category_by_level = copy.deepcopy(REAXFF_PMOVE_CATEGORY)

    if optimization_level == 0:

        atom_param_to_be_optimized = ['gammaEEM', 'chiEEM', 'etaEEM']

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['atoms'], atom_param_to_be_optimized)

        for key in filter(lambda key: key not in 'atoms',
                          category_by_level.keys()):

            __get_step_sizes_by_optimization_level_helper(
                category_by_level[key], [])

    elif optimization_level == 1 or optimization_level == 2:

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['atoms'],
            ['cov.r', 'Rvdw', 'Evdw', 'alfa', 'gammavdW'])

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['bonds'], ['Edis1', 'Edis2', 'Edis3'])

        if optimization_level == 1:
            for key in filter(lambda key: key not in ['atoms', 'bonds'],
                              category_by_level.keys()):

                __get_step_sizes_by_optimization_level_helper(
                    category_by_level[key], [])

        else:
            __get_step_sizes_by_optimization_level_helper(
                category_by_level['off-diagonal'],
                ['Ediss', 'Ro', 'gamma'])

            __get_step_sizes_by_optimization_level_helper(
                category_by_level['angles'], ['Thetao', 'ka', 'kb'])

            for key in filter(lambda key: key in ['torsions', 'hydrogen'],
                              category_by_level.keys()):

                __get_step_sizes_by_optimization_level_helper(
                    category_by_level[key], [])

    elif optimization_level >= 3:

        atom_param_to_be_optimized = [
            'cov.r', 'Rvdw', 'Evdw', 'cov.r2', 'cov.r3']

        if optimization_level >= 4:

            atom_param_to_be_optimized.extend([
                'Eunder', 'Eover', 'Elp', 'ovun',
                '13BO1', '13BO2', '13BO3', 'val1',
                'val3', 'val4'])

            if optimization_level >= 5:
                atom_param_to_be_optimized.extend(['alfa', 'gammavdW'])

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['atoms'], atom_param_to_be_optimized)

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['bonds'],
            ['Edis1', 'Edis2', 'Edis3', 'pbe1',
             'pbo5', '13corr', 'pbo6', 'povon1',
             'pbe2', 'pbo3', 'pbo4', 'pbo1', 'pbo2'])

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['off-diagonal'],
            ['Ediss', 'Ro', 'gamma', 'rsigma', 'rpi', 'rpi2'])

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['angles'],
            ['Thetao', 'ka', 'kb', 'pv1', 'pv2', 'valbo', 'pv3'])

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['torsions'],
            ['V1', 'V2', 'V3', 'V2BO', 'vconj'])

        __get_step_sizes_by_optimization_level_helper(
            category_by_level['hydrogen'],
            ['Rhb', 'Dehb', 'vhb1', 'vhb2'])

    return category_by_level

def __get_step_sizes_by_optimization_level_helper(
        category: dict, parameter_to_be_optimized: list) -> dict:
    """
    Set the step size of the parameters not to be optimized to zero

    Parameters
    ----------

    category
        step_size of one category of parameters

    parameter_to_be_optimized
        list of names of the parameter to be optimized

    Returns
    -------
    category
    """

    for key in filter(lambda key: key not in parameter_to_be_optimized,
                      category.keys()):

        category[key] = 0.0

    return category

REAXFF_TYPE_PMOVE = {
    'cov.r': 0.005, 'valency': 0.0, 'a.m': 0.0, 'Rvdw': 0.01,
    'Evdw': 0.01, 'gammaEEM': 0.01, 'cov.r2': 0.01, '#el.': 0.0,
    'alfa': 0.1, 'gammavdW': 0.1, 'valency2': 0.0, 'Eunder': 3.0,
    'Eover': 3.0, 'chiEEM': 0.01, 'etaEEM': 0.01, 'n.u.1': 0.0,
    'cov.r3': 0.01, 'Elp': 0.1, 'Heatinc.': 0.0, '13BO1': 0.1,
    '13BO2': 0.1, '13BO3': 0.1, 'n.u.2': 0.0, 'n.u.3': 0.0,
    'ovun': 0.5, 'val1': 0.01, 'n.u.4': 0.0, 'val3': 0.01,
    'val4': 0.01, 'n.u.5': 0.0, 'n.u.6': 0.0, 'n.u.7': 0.0}

REAXFF_BOND_PMOVE = {
    'Edis1': 0.01, 'Edis2': 0.1, 'Edis3': 0.01, 'pbe1': 0.01,
    'pbo5': 0.01, '13corr': 0.0, 'pbo6': 0.01, 'povon1': 0.01,
    'pbe2': 0.5, 'pbo3': 0.01, 'pbo4': 0.01, 'n.u.1': 0.0,
    'pbo1': 0.01, 'pbo2': 0.01, 'ovcorr': 0.0}

REAXFF_DIAG_PMOVE = {
    'Ediss': 0.01, 'Ro': 0.01, 'gamma': 0.01, 'rsigma': 0.01,
    'rpi': 0.01, 'rpi2': 0.01}

REAXFF_ANGLE_PMOVE = {
    'Thetao': 0.01, 'ka': 0.1, 'kb': 0.1, 'pv1': 0.1,
    'pv2': 0.1, 'valbo': 0.1, 'pv3': 0.01}

REAXFF_TORSIONS_PMOVE = {
    'V1': 0.1, 'V2': 0.1, 'V3': 0.1, 'V2BO': 0.01, 'vconj': 0.01,
    'n.u.1': 0.0, 'n.u.2': 0.0}

REAXFF_HYDROGEN_BOND_PMOVE = {
    'Rhb': 0.01, 'Dehb': 0.01, 'vhb1': 0.01, 'vhb2': 0.0}

REAXFF_PMOVE_CATEGORY = {
    'atoms': REAXFF_TYPE_PMOVE,
    'bonds': REAXFF_BOND_PMOVE,
    'off-diagonal': REAXFF_DIAG_PMOVE,
    'angles': REAXFF_ANGLE_PMOVE,
    'torsions': REAXFF_TORSIONS_PMOVE,
    'hydrogen': REAXFF_HYDROGEN_BOND_PMOVE}


import functools
import torch.nn as nn
from torch.optim import lr_scheduler

def get_scheduler(optimizer, opts, cur_ep=-1):
    if opts.lr_policy == 'lambda':
        def lambda_rule(ep):
            lr_l = 1.0 - max(0, ep - opts.n_ep_decay) / float(opts.n_ep - opts.n_ep_decay + 1)
            return lr_l

        scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule, last_epoch=cur_ep)
    elif opts.lr_policy == 'step':
        scheduler = lr_scheduler.StepLR(optimizer, step_size=opts.n_ep_decay, gamma=0.1, last_epoch=cur_ep)
    else:
        return NotImplementedError('no such learn rate policy')
    return scheduler

def meanpoolConv(inplanes, outplanes):
    sequence = []
    sequence += [nn.AvgPool2d(kernel_size=2, stride=2)]
    sequence += [nn.Conv2d(inplanes, outplanes, kernel_size=1, stride=1, padding=0, bias=True)]
    return nn.Sequential(*sequence)

def convMeanpool(inplanes, outplanes):
    sequence = []
    sequence += conv3x3(inplanes, outplanes)
    sequence += [nn.AvgPool2d(kernel_size=2, stride=2)]
    return nn.Sequential(*sequence)

def get_norm_layer(layer_type='instance'):
    if layer_type == 'batch':
        norm_layer = functools.partial(nn.BatchNorm2d, affine=True)
    elif layer_type == 'instance':
        norm_layer = functools.partial(nn.InstanceNorm2d, affine=False)
    elif layer_type == 'none':
        norm_layer = None
    else:
        raise NotImplementedError('normalization layer [%s] is not found' % layer_type)
    return norm_layer

def get_non_linearity(layer_type='relu'):
    if layer_type == 'relu':
        nl_layer = functools.partial(nn.ReLU, inplace=True)
    elif layer_type == 'lrelu':
        nl_layer = functools.partial(nn.LeakyReLU, negative_slope=0.2, inplace=False)
    elif layer_type == 'elu':
        nl_layer = functools.partial(nn.ELU, inplace=True)
    else:
        raise NotImplementedError('nonlinearity activitation [%s] is not found' % layer_type)
    return nl_layer

def conv3x3(in_planes, out_planes):
    return [nn.ReflectionPad2d(1), nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=0, bias=True)]

def gaussian_weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1 and classname.find('Conv') == 0:
        m.weight.data.normal_(0.0, 0.02)


from django.urls import path, include

from .views import *

from mainapp.apps import MainappConfig

app_name = MainappConfig.name

urlpatterns = [
    path("", MainPageView.as_view(), name='main'),
    path("doc_site/", DocSitePageView.as_view(), name='docs'),
    path("contacts/", ContactsPageView.as_view(), name='contacts'),
    path("news/", NewsPageView.as_view(), name='news'),
    path("news/<int:pk>/", NewsPageDetailView.as_view(), name="news_detail"),
    path("courses_list/", CoursesPageView.as_view(), name='courses'),
    path("courses/<int:pk>/", CoursesDetailView.as_view(), name="courses_detail"),
]


RAW_DIR = "data/raw"
TRANSFORMED_DIR = "data/transformed"

DATA_SOURCES = {
    "communes": {
        "url": "https://data.public.lu/en/datasets/r/15304974-6ea1-4e19-b368-8f20278d0eca",
        "format": "xlsx",
        "first_value": (6, 0), # row, col
        "columns": [
            "commune_cadastrale",
            "commune_administrative",
            "code_section",
            "nom_section",
            "nom_section_pretty",
            "code_abbreviation",
        ],
    },
    "prices_rent": {
        "url": "https://data.public.lu/fr/datasets/r/94e4a229-c564-4dd2-99b5-6b6e9d29eafd",
        "format": "xls",
        "first_value": (0, 2), # row, col
        "sheets": [str(sheet) for sheet in list(range(2009, 2021))],
        "skip_until": "Commune",
        "stop_on": "nan",
        "columns": ["year", "commune", "num_offer", "rent_abs", "rent_m2"],
    },
}

RABBITMQ_HOST = "rabbitmq"
RABBITMQ_PORT = 5672
RABBITMQ_USER = "guest"
RABBITMQ_PASS = "guest"
RABBITMQ_QUEUE = "communes_polling_queue"

ES_HOST = "elasticsearch"
ES_MAPPINGS = {
    "communes": {
        "properties": {
            "commune_cadastrale": {"type": "text"},
            "commune_administrative": {"type": "text"},
            "code_abbreviation": {"type": "text"},
            "sections": {
                "type": "nested",
                "properties": {
                    "code_section": {"type": "text"},
                    "nom_section": {"type": "text"},
                    "nom_section_pretty": {"type": "text"},
                },
            },
        }
    },
    "communes_rentals": {
        "properties": {
            "commune_administrative": {"type": "text"},
            "year": {"type": "integer"},
            "num_offer": {"type": "integer"},
            "rent_abs": {"type": "float"},
            "rent_m2": {"type": "float"},
        },
    },
}


import requests
import json
from config import keys

class ConverterException(Exception):
    pass

class Converter:
    @staticmethod
    def calculate_rate(message):
        data = message.text.split()

        if len(data) != 3:
            raise ConverterException('Ошибка ввода данных.')
        else:
            base, quote, amount = data
            base = base.lower()
            quote = quote.lower()
        try:
            amount = float(amount)

        except ValueError:
            raise ConverterException('Ошибка ввода данных. Сумма должна быть числом.')
        else:
            if amount < 0:
                raise ConverterException('Ошибка ввода данных. Сумма должна быть положительной.')

        if base == quote:
            raise ConverterException(f'Указана одинаковая валюта для пересчета - {base}')
        if base not in keys.keys():
            raise ConverterException(f'Неправильно указано название валюты - {base}')
        if quote not in keys.keys():
            raise ConverterException(f'Неправильно указано название валюты - {quote}')

        path = f'https://min-api.cryptocompare.com/data/price?fsym={keys[base]}&tsyms={keys[quote]}'
        r = requests.get(path).content
        result = json.loads(r)
        final_sum = amount * result[keys[quote]]
        return f'{base} в сумме {amount:.2f} = {quote} в сумме {final_sum:.2f}'


#!/usr/bin/env python3

import argparse

def main():
    """ Read in the submarine diagnostics provided by the given file. Report
        the submarine's power consumption by first determining the gamma and
        epsilon rates. Then multiply them together to get the power rating.
    """
    ###########################################################################
    # Command line argument parser
    ###########################################################################

    description = "Read in the submarine diagnostics provided by the given file. Report\n" \
                  "the submarine's power consumption by first determining the gamma and\n" \
                  "epsilon rates. Then multiply them together to get the power rating."

    parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("file", help="Text file with diagnostic data.")

    args = parser.parse_args()

    ###########################################################################
    # Read in directions
    ###########################################################################

    try:
        with open(args.file, 'r') as FILE:
            diagnostic_data = [value.strip() for value in FILE.readlines()]
    except Exception:
        raise

    ###########################################################################
    # Interpret diagnostic data
    ###########################################################################

    # Check if there is enough data
    if len(diagnostic_data) < 1:
        print("Not enough diagnostic data to determine gamma and epsilon rates.")
        exit(1)

    # Initialize a bit counter. Each bit starts at 0. If a "1" is read, increment
    # the bit counter by 1. If a "0" is read, decrement the bit counter by 1.
    #
    # This method is used because the data is read in from the files as rows of
    # data. The gamma and epsilon rates are determined by columns of data. This
    # method will aggregate the column values (gamma and epsilon rates) by
    # reading each row.
    bit_counter = [0] * len(diagnostic_data[0])

    # Read each line of diagnostic data
    for line_number, bits in enumerate(diagnostic_data, 1):
        # Read each bit
        for index, bit in enumerate(bits):
            # Bit value is 1
            if bit == "1":
                bit_counter[index] += 1
            # Bit value is 0
            elif bit == "0":
                bit_counter[index] -= 1
            # Invalid bit value
            else:
                print("ERROR: Invalid bit value found on line number {} bit number {}.".format(line_number, index+1))

    ###########################################################################
    # Determine gamma and epsilon rates
    ###########################################################################

    # Binary strings of the gamma and epsilon rates
    gamma_rate_bin_str = ""
    epsilon_rate_bin_str = ""

    # Read each bit count and determine if a 1 or 0 should be added to the gamma
    # and epsilon rates
    for bit_position, bit_count in enumerate(bit_counter):
        # Gamma gets a 1; epsilon gets a 0
        if bit_count > 0:
            gamma_rate_bin_str += "1"
            epsilon_rate_bin_str += "0"
        # Gamma gets a 0; epsilon gets a 1
        elif bit_count < 0:
            gamma_rate_bin_str += "0"
            epsilon_rate_bin_str += "1"
        # Even number of 0s and 1s found
        else:
            print("ERROR: Equal number of 1s and 0s found in bit position {}.".format(bit_position))
            exit(2)

    ###########################################################################
    # Report
    ###########################################################################

    gamma_rate = int(gamma_rate_bin_str, 2)
    epsilon_rate = int(epsilon_rate_bin_str, 2)

    print("Gamma rate:        {}".format(gamma_rate))
    print("Epsilon rate:      {}".format(epsilon_rate))
    print("Power consumption: {}".format(gamma_rate * epsilon_rate))

    exit(0)

if __name__ == '__main__':
    main()


#THE WORKING OF KNN IN A SIMPLE CODE
#HERE YOU SHOULD TAKE THE VALUE OF K AS AN ODD NUMBER
#this code is for the binary classsification
import math
import matplotlib.pyplot as plt
def euclidean_distance(x,y,z,w):
    return math.sqrt((x-y)**2+(z-w)**2)
def nearest_number(distance,train_coordinates,n):  #here n denotes the number of coordinates to be checked
    m=distance
    i=0
    checked=[]
    while  i<n:
        l=m.index(min(m))
        checked.append(train_coordinates[l])
        del(distance[l])
        del(train_coordinates[l])
        i=i+1
    return checked

import random
#now i generate around 3000 random coordinates in the range(0-200) and a binary class classification
train_coordinates=[]

for j in range(3000):
    sample=[]
    x_coordinate=random.randint(0,3000)
    y_coordinate=random.randint(0,3000)
    pos_class=[0,1,2]   #------------------------->change this for increasing the number of classes
    class1=random.choice(pos_class)  #this alloctes the class to the sample

    sample.append(x_coordinate)
    sample.append(y_coordinate)
    sample.append(class1)
    train_coordinates.append(sample)   #this creates a superset of all the sample spaces

#now we generate the test cases where i generate the random x  and y coordinates

#i choose to make a test sample of around 20
test_sample=[]
for j in range(20):
    test=[]
    x=random.randint(0,3000)
    y=random.randint(0,3000)
    test.append(x)
    test.append(y)
    test_sample.append(test)
test_sample_class=[]   #this will store the classes of the test cases
neighbours=int(input("ENTER THE NUMBER OF NEIGHBOURS FOR CHECKING :: "))  #take the number to be considered while taking the distance

#now i generate the distance of each element in the test sample to the train coordinates
all_distances=[]  #this shows all the distances
for i in range(len(test_sample)):
    distance_between_sample=[]
    for j in range(len(train_coordinates)):
        m=train_coordinates[j]
        z=test_sample[i]
        z2=train_coordinates[j]
        m=euclidean_distance(z[0],z2[0],z[1],z2[1])
        distance_between_sample.append(m)
    #now i know the distances of the test sample with all the coordinates

    s=nearest_number(distance_between_sample,train_coordinates,neighbours)
    #this returns the coordinates which are nearest to the test coordinate
    class_coordinate=[]
    for i in range(len(s)):
        m4=s[i]
        class_coordinate.append(m4[2])
    if class_coordinate.count(0)>class_coordinate.count(1):
        test_sample_class.append(0)
    else:
        test_sample_class.append(1)
print(test_sample_class)  #this will print the list along with the classes to which it belongs

#this part is for plotting the graph
x_final_class0=[]
x_final_class1=[]
y_final_class0=[]
y_final_class1=[]
for i in range(len(train_coordinates)):
    z=train_coordinates[i]
    if z[2]==0:
        x_final_class0.append(z[0])
        y_final_class0.append(z[1])
    else:
        x_final_class1.append(z[0])
        y_final_class1.append(z[1])
x_test=[]
y_test=[]
for i in range(len(test_sample)):
    m3=test_sample[i]
    x_test.append(m3[0])
    y_test.append(m3[1])

plt.scatter(x_final_class0,y_final_class0,color='red',label='CLASS 0 ELEMENTS')
plt.scatter(x_final_class1,y_final_class1,color='blue',label='CLASS 1 ELEMENTS')
plt.scatter(x_test,y_test,color='black',label='TEST CASES')
plt.legend(loc='best')
plt.xlabel('X COORDINATE')
plt.ylabel('Y COORDINATE')
plt.show()


@bot.message_handler(commands=['fecha'])
def command_fecha(m):
    cid = m.chat.id
    x = datetime.datetime.now()
    switcher = {
        1: "enero",
        2: "febrero",
        3: "marzo",
        4: "abril",
        5: "mayo",
        6: "junio",
        7: "julio",
        8: "agosto",
        9: "septiembre",
        10: "octubre",
        11: "noviembre",
        12: "diciembre"
    }
    mes = switcher[x.month]
    fecha = "Estamos a %s de %s" % (x.day, mes)
    bot.send_message(cid, fecha)


import os
import random

ALL_SKILLS = [
    "Asian Cooking",
    "French Baking",
    "Mediterranean cooking",
    "Latin American cooking"
]
class Player:
    def __init__(self, name):
        self.money = 500
        self.reputation = 2
        self.exp = 0
        self.name = name
        self.skills = {}

def main():
    new_name = input("What is your monster's name? ")
    new_name = new_name.capitalize()
    player = Player(new_name)

    os.system('clear')
    should_continue = True
    while should_continue:
        choices = [
            "Do some training",
            "Enter a cooking contest",
            "View profile",
            "Exit"
        ]
        print("Hello {}! What would you like to do today? ".format(player.name))
        answer = choose(choices)
        if answer == 0:
            increase = perform_training(player)
            player.exp += increase
            if player.money <= 0:
                print("You broke. You lose the game!")
                break

        if answer == 1:
            increase = enter_contest(player)
            player.reputation += increase
            if player.reputation == 0:
                print("Your reputation is 0. You lose the game!")
                break
            if player.money <= 0:
                print("You broke. You lose the game!")
                break
        if answer == 2:
            show_profile(player)
        if answer == 3:
            should_continue = False
            break
        input("Press enter to continue")

        os.system('clear')
    print("Bye")

def choose(valid_choices):
    print_ordered_choices(valid_choices)
    selection = get_valid_choice(valid_choices)
    return selection

def print_ordered_choices(choice_list):
    for index in range(len(choice_list)):
        element = choice_list[index]
        print("{}. {}".format(index + 1, element))

def get_valid_choice(choices):
    should_ask = True
    while should_ask:
        ask = input("Please enter your choice ")
        ask = int(ask)
        if ask in range(1, len(choices) + 1):
            index = ask - 1
            return index
        print("Sorry, that is not a valid choice")

def perform_training(player):
    player.money -= 50
    print('It costs 50 for training')
    new_skill = random.choice(ALL_SKILLS)
    #player.skills.append(new_skill)
    #check if player has new skill
    #if yes then increase level by 1
    #if no then add a new skill to key and value 1
    # { 'french_cooking': 1 }
    if new_skill in player.skills:
        player.skills[new_skill] += 1
    else:
        player.skills[new_skill] = 1
    increase = 10
    print('Yay you trained hard!  You gained {} exp points and learned {}'.format(increase, new_skill))
    return increase

def enter_contest(player):
    player.money -= 100

    """
pick a theme for the contest
use randomly choose a theme
check if the player has the skill in the theme
if yes give them extra 10 *10 (skill bonus = skill level *10)
add skill bonus to result 115
print (you receive extra bonus since you haave ..skill)
    """

    print("It costs 100 for entry fee")
    rand_theme = random.choice(ALL_SKILLS)
    if rand_theme in player.skills:
        skill_bonus = player.skills[rand_theme]*10
        print("You receive {} extra bonus since you have the {} skill".format(skill_bonus, rand_theme))
    else:
        skill_bonus = 0
    rand = random.randint(0, 100)
    result = rand + player.exp + skill_bonus

    if result > 50:
        player.money += 200
        print("You win! Congrats you got 200!")
        show_emotions("happy", player)
        return 1
    else:
        print("Loser!")
        show_emotions("sad", player)
        return -1

def show_profile(player):
    print("Money: {}".format(player.money))
    print("Exp: {}".format(player.exp))
    print("Reputation: {}".format(player.reputation))
    print("Skills:")
    print_skills(player)

def show_emotions(emotion, player):
    if emotion == "happy":
        print("{} jumps up and down with glee!".format(player.name))
    if emotion == "sad":
        print("{} pouts and gazes down!".format(player.name))

def print_skills(player):
    for skill, level in player.skills.items():
        print("{}: {}".format(skill, level))

main()


from flask import Flask, jsonify
from transformers import T5ForConditionalGeneration, T5Tokenizer
import json

app = Flask(__name__)

# Load the pre-trained T5 model & tokenizer
question_model = T5ForConditionalGeneration.from_pretrained('priya_t5_squad_v1')
question_tokenizer = T5Tokenizer.from_pretrained('t5-base', model_max_length=1024)

# Defining the get_question_from_answer function
def get_question_from_answer(answer, context):
    text = f"context: {context} answer: {answer} </s>"
    max_len = 256
    encoding = question_tokenizer.encode_plus(
        text,
        max_length=max_len,
        pad_to_max_length=True,
        truncation=True,
        truncation_strategy="longest_first",
        return_tensors="pt"
    )
    input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
    outs = question_model.generate(
        input_ids=input_ids,
        attention_mask=attention_mask,
        early_stopping=True,
        num_beams=5,
        num_return_sequences=1,
        no_repeat_ngram_size=2,
        max_length=200
    )
    dec = [question_tokenizer.decode(ids) for ids in outs]
    question = dec[0].replace("question:", "").strip()
    return question

# Main route for serving questions and answers
@app.route('/')
def index():
    # Reading a JSON file
    file_path = "C:\\Users\\91999\\Downloads\\interviewerSchema.json.json"

    # Read the JSON file
    with open(file_path, "r") as file:
        data = json.load(file)

    # Check if Python, Django, NumPy, and scikit-learn (sklearn) skills are present in the schema
    python_skill_present = any(skill.get("python") for skill in data.get("skills", {}).get("Techskills", []))
    django_skill_present = any(skill.get("django") for skill in data.get("skills", {}).get("Techskills", []))
    numpy_skill_present = any(skill.get("numpy") for skill in data.get("skills", {}).get("Techskills", []))
    sklearn_skill_present = any(skill.get("sklearn") for skill in data.get("skills", {}).get("Techskills", []))

    # Generate questions and answers
    questions_and_answers = []

    # Generate Python questions
    if python_skill_present:
        python_answers = [
            "In Python, the self keyword is used as a convention to refer to the instance of a class within the class itself.",
            "Decorators in python are a way to modify or enhance the behavior of functions or classes without directly modifying their source code.",
            "PEP 8 is a style guide for Python code and PEP 8 specifically focuses on the style conventions for writing Python code.",
            "Python uses private heap space to manage memory.",
            "In Python, inheritance is a mechanism that allows a class to inherit properties (attributes and methods) from another class."
        ]
        for answer in python_answers:
            generated_question = get_question_from_answer(answer, "Python")
            generated_question = generated_question.replace("<pad> ", "").replace("</s>", "")
            questions_and_answers.append({"question": generated_question, "answer": answer})

    # Generate Django questions
    if django_skill_present:
        django_answers = [
            "Django provides built-in support for internationalization (i18n) and localization (l10n), it includes features for translating text, handling date and number formatting based on different locales, and switching between multiple languages in the application",
            "The Django admin site is an automatically generated administration interface that allows authorized users to manage the application's data models.",
            "Django follows a slightly modified version of the MVC architectural pattern, known as Model-View-Template (MVT). Models represent the data structure, views handle the business logic and interaction with models, and templates handle the presentation layer.",
            "Django middleware is a component that sits between the web server and the view function, allowing you to process requests and responses globally.",
            "Django's template system allows developers to separate the presentation logic from the Python code."
        ]
        for answer in django_answers:
            generated_question = get_question_from_answer(answer, "Django")
            generated_question = generated_question.replace("<pad> ", "").replace("</s>", "")
            questions_and_answers.append({"question": generated_question, "answer": answer})

    # Generate NumPy questions
    if numpy_skill_present:
        numpy_answers = [
            "NumPy stands for Numerical Python and it is a powerful library in Python for numerical computations, Its main purpose is to provide efficient and convenient handling of large arrays and matrices of numerical data, along with a collection of mathematical functions to operate on these arrays.",
            "A NumPy array is a grid of values, all of the same data type, and indexed by a tuple of non-negative integers. It is the fundamental data structure in NumPy and provides several advantages over regular Python lists, including faster execution of operations, optimized memory usage, and a wide range of mathematical functions and operations specifically designed for arrays.",
            "A one-dimensional array in NumPy is a simple list of values, while a multi-dimensional array represents a table of elements with rows and columns, similar to a matrix. Multi-dimensional arrays can have any number of dimensions, such as 2D for matrices or 3D for representing volumes of data.",
            "You can reshape or resize a NumPy array using the np.reshape() function or by directly modifying the shape attribute of the array. For example: new_arr = np.reshape(arr, (2, 3)) or arr.shape = (2, 3)",
            "NumPy provides several functions to generate arrays with specific patterns or values, such as np.zeros(), np.ones(), np.arange(), np.linspace(), np.random.rand(), np.random.randint(), and np.eye()."
        ]
        for answer in numpy_answers:
            generated_question = get_question_from_answer(answer, "NumPy")
            generated_question = generated_question.replace("<pad> ", "").replace("</s>", "")
            questions_and_answers.append({"question": generated_question, "answer": answer})

    # Generate scikit-learn (sklearn) questions
    if sklearn_skill_present:
        sklearn_answers = [
            "sklearn provides various modules and components, including datasets for loading and exploring datasets, preprocessing for data preprocessing techniques, model_selection for model selection and evaluation, metrics for performance evaluation metrics, estimators for machine learning algorithms, and ensemble for ensemble methods, among others.",
            "Estimator objects in sklearn are used to fit models to data and make predictions. They encapsulate the learning algorithms and have methods such as fit() to train the model, predict() to make predictions, and score() to evaluate the model's performance.",
            "sklearn provides a datasets module that offers various datasets for practice and experimentation. You can use functions like load_iris(), load_digits(), or fetch_california_housing() to load datasets. Once loaded, you can explore the dataset attributes, such as data, target, feature_names, and target_names.",
            "sklearn offers several preprocessing techniques, including scaling features with StandardScaler or MinMaxScaler, handling missing values with SimpleImputer, encoding categorical variables with OneHotEncoder or LabelEncoder, and reducing dimensionality with techniques like Principal Component Analysis (PCA).",
            "The Pipeline module in scikit-learn allows you to chain multiple preprocessing steps and machine learning models into a single object. It helps in organizing and automating the workflow, enabling easier model building, training, and evaluation."
        ]
        for answer in sklearn_answers:
            generated_question = get_question_from_answer(answer, "scikit-learn")
            generated_question = generated_question.replace("<pad> ", "").replace("</s>", "")
            questions_and_answers.append({"question": generated_question, "answer": answer})

    # If none of the skills are present in the schema
    else:
        return "No Python, Django, NumPy, and scikit-learn tech skill found in the JSON schema."

    # Render the questions and answers as JSON
    return jsonify(questions_and_answers)

# Run the Flask app
if __name__ == '__main__':
    app.run(debug=True)


import tensorflow as tf

import math

# The output classes.representing the digits from 0 to 9
NUMCLASS = 10;

##
IMAGE_SIZE = 28;
IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE;

def inference(images,hidden1_unit,hidden2_unit):
    """build the graph

    Args:
      images:Image placeholder.Size[batchsize*IMAGE_PIEXLS]
      hidden1_unit:Size of first hidden layer.
      hidden2_unit:Size of second hidden layer.

    Returns:
      softmax_linear: Output tensor with the computed logits.
    """
    #hidden1
    with tf.name_scope('hidden1'):
        weights = tf.Variable(tf.truncated_normal([IMAGE_PIXELS,hidden1_unit],
            stddev = 1/math.sqrt(float(hidden2_unit))),name = 'weights');
        bias = tf.Variable(tf.zeros([hidden1_unit]),name = 'bias');
        hidden1 = tf.nn.relu(tf.matmul(images,weights)+bias);

    #hidden2
    with tf.name_scope('hidden2'):
        weights = tf.Variable(tf.truncated_normal([hidden1_unit,hidden2_unit],
            stddev = 1/math.sqrt(float(hidden2_unit))),name = 'weights');
        bias = tf.Variable(tf.zeros([hidden2_unit]),name = 'bias');
        hidden2 = tf.nn.relu(tf.matmul(hidden1,weights)+bias);

    #softmax layer
    with tf.name_scope('softmax_layer'):
        weights = tf.Variable(tf.truncated_normal([hidden2_unit,NUMCLASS],
            stddev = 1/math.sqrt(float(hidden2_unit))),name ='weights');
        bias = tf.Variable(tf.zeros([NUMCLASS]),name = 'bias');
        logits = tf.matmul(hidden2,weights)+bias;
    return logits;

def loss(labels,logits):

    """Calculates the loss from the logits and the labels.

    Args:
    labels: Labels tensor, int32 - [batch_size].
    logits: Logits tensor, float - [batch_size, NUM_CLASSES].

    Return: Loss tensor of type float

    """
    labels = tf.to_int64(labels)
    with tf.name_scope('loss'):
        cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = labels, name='xentropy')
        loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')
    return loss

def training(loss,learning_rate):
    """Sets up the training Ops.
    Creates a summarizer to track the loss over time in TensorBoard.
    Creates an optimizer and applies the gradients to all trainable variables.
    The Op returned by this function is what must be passed to the
    `sess.run()` call to cause the model to train.
    Args:
        loss: Loss tensor, from loss().
        learning_rate: The learning rate to use for gradient descent.
    Returns:
        train_op: The Op for training.
    """

    tf.summary.scalar('loss',loss);
    # Create the gradient descent optimizer with the given learning rate.
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    # Create a variable to track the global step.
    global_step = tf.Variable(0, name='global_step', trainable=False)
    # Use the optimizer to apply the gradients that minimize the loss
    # (and also increment the global step counter) as a single training step.
    train_op = optimizer.minimize(loss, global_step=global_step)
    return train_op

def evaluation(labels,logits):
    """Evaluate the quality of the logits at predicting the label.
    Args:
        logits: Logits tensor, float - [batch_size, NUM_CLASSES].
        labels: Labels tensor, int32 - [batch_size], with values in the
        range [0, NUM_CLASSES).
    Returns:
        A scalar int32 tensor with the number of examples (out of batch_size)
        that were predicted correctly.
    """
    # For a classifier model, we can use the in_top_k Op.
    # It returns a bool tensor with shape [batch_size] that is true for
    # the examples where the label is in the top k (here k=1)
    # of all logits for that example.
    correct = tf.nn.in_top_k(logits, labels, 1)
    # Return the number of true entries.
    #cast(x,dtype),transform x into dtype.
    return tf.reduce_sum(tf.cast(correct, tf.int32))


import configparser

import pandas as pd
import os
import calendar

cfg = configparser.ConfigParser()
cfg.read('cfg.ini')
class Read_file:
    def obter_ultimo_dia_mes(self, mes, ano):
        mes = int(mes)
        ano = int(ano)
        ultimo_dia = calendar.monthrange(int(ano), int(mes))[1]
        return f'{ultimo_dia:02d}/{mes:02d}/{ano}'

    def gerar_numero_sequencial(self, inicio=1):
        contador = inicio
        while True:
            yield contador
            contador += 1

    def escrever_arquivo_texto(self, nome_arquivo, linhas):
        # Verificar se o arquivo já existe
        if not os.path.exists(nome_arquivo):
            # Criar o arquivo caso ele não exista
            with open(nome_arquivo, 'w') as file:
                pass

        # Escrever as linhas no arquivo
        with open(nome_arquivo, 'w') as file:
            for linha in linhas:
                file.write(linha + '\n')
    def buscar_arquivo_hodometro_horimetro(self, pastas_iniciais, pasta_destino, codEntidade):
        reade_file = Read_file()
        nome_arquivo = 'HodometroHorimetro.txt'
        print(pastas_iniciais)
        txt = []
        controle = reade_file.gerar_numero_sequencial()
        for pasta_inicial in [pastas_iniciais]:
            for raiz, diretorios, arquivos in os.walk(pasta_inicial):
                if nome_arquivo in arquivos:
                    caminho_arquivo = os.path.join(raiz, nome_arquivo)
                    # print(f'Arquivo encontrado: {caminho_arquivo}')
                    df = pd.read_csv(caminho_arquivo, sep="|", header=None,dtype="str")  # header=None se quiser colocar sem cabeçalho
                    df = df.fillna('')
                    df = df.astype(str)
                    df = df.get([1, 2, 3, 4, 6, 7, 8, 9])

                    competencia = df[3].iloc[0] #iloc pra tranformar series de pandas em formato python para fazer cast
                    ano = df[4].iloc[0]

                    frota = df[1].astype(int).iloc[0]
                    CdControle = next(controle)
                    CdTipoLancamento = 1  # 0=Manual/1=Expostação SimAm
                    DtLancamento = reade_file.obter_ultimo_dia_mes(competencia, ano)
                    VlrDeclarado = df[8].iloc[0].replace('.', ',')
                    DsNotaExplicativa = df[9].iloc[0]
                    CdControleSimam = df[2].iloc[0]
                    IsTrocaAcumulador = 1  # 0=Sim/1=Não
                    VlrAcumuladorInicial = df[6].iloc[0].replace('.', ',')
                    VlrAcumuladorFinal = df[7].iloc[0].replace('.', ',')
                    NovoValorAcumuladorInicial = ''
                    DtLeituraAcumulador = ''

                    txt.append(str(codEntidade)+'|'+str(frota)+'|'+str(CdControle)+'|'+str(CdTipoLancamento)+'|'+str(DtLancamento)+'|'+str(VlrDeclarado)+'|'+str(DsNotaExplicativa)+'|'\
                          +str(CdControleSimam)+'|'+str(IsTrocaAcumulador)+'|'+str(VlrAcumuladorInicial)+'|'+str(VlrAcumuladorFinal)+'|'+str(NovoValorAcumuladorInicial)+'|'+str(DtLeituraAcumulador))

        reade_file.escrever_arquivo_texto(pasta_destino+'VeiculoControleSimAm.txt', txt)
        return f'{pasta_destino}VeiculoControleSimAm.txt gerado com sucesso...'

    def buscar_arquivo_consumo(self, pastas_iniciais, pasta_destino, codEntidade):
        reade_file = Read_file()
        nome_arquivo = 'ConsumoCombustivel.txt'
        txt = []
        for pasta_inicial in [pastas_iniciais]:
            for raiz, diretorios, arquivos in os.walk(pasta_inicial):
                if nome_arquivo in arquivos:
                    caminho_arquivo = os.path.join(raiz, nome_arquivo)

                    df = pd.read_csv(caminho_arquivo, sep="|", header=None,dtype="str")  # header=None se quiser colocar sem cabeçalho
                    df = df.fillna('')
                    df = df.astype(str)

                    frota = df[2].astype(int).iloc[0]
                    NrSequencial = df[1].astype(int).iloc[0]
                    NrMes = df[5].iloc[0]  # iloc pra tranformar series de pandas em formato python para fazer cast
                    NrAno = df[6].iloc[0]
                    IdTipoCategoriaObjetoDespesa = df[3].iloc[0]
                    IdTipoObjetoDespesa = df[4].iloc[0]
                    NrQuantidade = df[7].iloc[0].replace('.', ',')
                    txt.append(str(codEntidade) + '|' + str(NrSequencial) + '|' + str(frota)+ '|' + str(NrMes) + '|' + str(NrAno) + '|' + str(IdTipoCategoriaObjetoDespesa)+ '|' + str(IdTipoObjetoDespesa) + '|' + str(NrQuantidade) + '|')

        reade_file.escrever_arquivo_texto(pasta_destino+'ConsumoCombustivel.txt', txt)
        return f'{pasta_destino}ConsumoCombustivel.txt gerado com sucesso...'


from datetime import datetime

import factory
import pytz
from django.db.models import signals
from django.test import TestCase
from tests.fixtures import SIEMENS_DWI_SERIES, SIEMENS_DWI_SERIES_PATH
from tests.models import Subject

from django_dicom.models import Image, Series
from django_mri.models import Scan, Session

class SessionModelTestCase(TestCase):
    @classmethod
    @factory.django.mute_signals(signals.post_save)
    def setUpTestData(cls):
        Image.objects.import_path(
            SIEMENS_DWI_SERIES_PATH, progressbar=False, report=False
        )
        cls.series = Series.objects.first()
        cls.subject, _ = Subject.objects.from_dicom_patient(cls.series.patient)
        header = cls.series.image_set.first().header.instance
        session_time = datetime.combine(
            header.get("StudyDate"), header.get("StudyTime")
        ).replace(tzinfo=pytz.UTC)
        session = Session.objects.create(
            subject=cls.subject, time=session_time
        )
        cls.scan = Scan.objects.create(dicom=cls.series, session=session)

    def setUp(self):
        self.session = self.scan.session

    ##########
    # Fields #
    ##########

    # time
    def test_time_value(self):
        result = self.session.time
        expected = SIEMENS_DWI_SERIES["study_time"]
        self.assertEqual(result, expected)

    # comments
    def test_comments_value(self):
        result = self.session.comments
        expected = None
        self.assertEqual(result, expected)

    def test_comments_blank_and_null(self):
        field = Session._meta.get_field("comments")
        self.assertTrue(field.blank)
        self.assertTrue(field.null)

    def test_comments_max_length(self):
        field = Session._meta.get_field("comments")
        self.assertEqual(field.max_length, 1000)

    # subject_id
    def test_subject_id_blank_and_null(self):
        field = Session._meta.get_field("subject_id")
        self.assertTrue(field.blank)
        self.assertTrue(field.null)

    ##############
    # Properties #
    ##############

    def test_study_groups(self):
        result = self.session.study_groups
        self.assertEqual(len(result), 0)
        self.assertIsNone(result.first())


import spacy

from spacy import displacy

nlp=spacy.load("en_core_web_sm")

text='''Python is an interpreted, high-level and general-purpose programming language,
       Pythons design philosophy emphasizes code readability with ,
       its notable use of significant indentation.
       Its language constructs and object-oriented approach aim to
       help programmers write clear and
       logical code for small and large-scale projects'''

doc=nlp(text)

sentences=list(doc.sents)
print(sentences)

for token in doc:
    print(token.text)

ents=[(e.text,e.start_char,e.end_char,e.label_) for e in doc.ents]
print(ents)
#displacy.render(doc,style='ent',jupyter=True)


from typing import List, Optional, Callable

import torch
import torch.nn.functional as F

from config import RunConfig
from constants import OUT_INDEX, STRUCT_INDEX, STYLE_INDEX
from models.stable_diffusion import CrossImageAttentionStableDiffusionPipeline
from utils import attention_utils
from utils.adain import masked_adain, adain
from utils.model_utils import get_stable_diffusion_model
from utils.segmentation import Segmentor

class AppearanceTransferModel:

    def __init__(self, config: RunConfig, pipe: Optional[CrossImageAttentionStableDiffusionPipeline] = None):
        self.config = config
        self.pipe = get_stable_diffusion_model() if pipe is None else pipe
        self.register_attention_control()
        self.segmentor = Segmentor(prompt=config.prompt, object_nouns=[config.object_noun])
        self.latents_app, self.latents_struct = None, None
        self.zs_app, self.zs_struct = None, None
        self.image_app_mask_32, self.image_app_mask_64 = None, None
        self.image_struct_mask_32, self.image_struct_mask_64 = None, None
        self.enable_edit = False
        self.step = 0

    def set_latents(self, latents_app: torch.Tensor, latents_struct: torch.Tensor):
        self.latents_app = latents_app
        self.latents_struct = latents_struct

    def set_noise(self, zs_app: torch.Tensor, zs_struct: torch.Tensor):
        self.zs_app = zs_app
        self.zs_struct = zs_struct

    def set_masks(self, masks: List[torch.Tensor]):
        self.image_app_mask_32, self.image_struct_mask_32, self.image_app_mask_64, self.image_struct_mask_64 = masks

    def get_adain_callback(self):

        def callback(st: int, timestep: int, latents: torch.FloatTensor) -> Callable:
            self.step = st
            # Compute the masks using prompt mixing self-segmentation and use the masks for AdaIN operation
            if self.config.use_masked_adain and self.step == self.config.adain_range.start:
                masks = self.segmentor.get_object_masks()
                self.set_masks(masks)
            # Apply AdaIN operation using the computed masks
            if self.config.adain_range.start <= self.step < self.config.adain_range.end:
                if self.config.use_masked_adain:
                    latents[0] = masked_adain(latents[0], latents[1], self.image_struct_mask_64, self.image_app_mask_64)
                else:
                    latents[0] = adain(latents[0], latents[1])

        return callback

    def register_attention_control(self):

        model_self = self

        class AttentionProcessor:

            def __init__(self, place_in_unet: str):
                self.place_in_unet = place_in_unet
                if not hasattr(F, "scaled_dot_product_attention"):
                    raise ImportError("AttnProcessor2_0 requires torch 2.0, to use it, please upgrade torch to 2.0.")

            def __call__(self,
                         attn,
                         hidden_states: torch.Tensor,
                         encoder_hidden_states: Optional[torch.Tensor] = None,
                         attention_mask=None,
                         temb=None,
                         perform_swap: bool = False):

                residual = hidden_states

                if attn.spatial_norm is not None:
                    hidden_states = attn.spatial_norm(hidden_states, temb)

                input_ndim = hidden_states.ndim

                if input_ndim == 4:
                    batch_size, channel, height, width = hidden_states.shape
                    hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)

                batch_size, sequence_length, _ = (
                    hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
                )

                if attention_mask is not None:
                    attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
                    attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])

                if attn.group_norm is not None:
                    hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)

                query = attn.to_q(hidden_states)

                is_cross = encoder_hidden_states is not None
                if not is_cross:
                    encoder_hidden_states = hidden_states
                elif attn.norm_cross:
                    encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)

                key = attn.to_k(encoder_hidden_states)
                value = attn.to_v(encoder_hidden_states)

                inner_dim = key.shape[-1]
                head_dim = inner_dim // attn.heads
                should_mix = False

                # Potentially apply our cross image attention operation
                # To do so, we need to be in a self-attention alyer in the decoder part of the denoising network
                if perform_swap and not is_cross and "up" in self.place_in_unet and model_self.enable_edit:
                    if attention_utils.should_mix_keys_and_values(model_self, hidden_states):
                        should_mix = True
                        if model_self.step % 5 == 0 and model_self.step < 40:
                            # Inject the structure's keys and values
                            key[OUT_INDEX] = key[STRUCT_INDEX]
                            value[OUT_INDEX] = value[STRUCT_INDEX]
                        else:
                            # Inject the appearance's keys and values
                            key[OUT_INDEX] = key[STYLE_INDEX]
                            value[OUT_INDEX] = value[STYLE_INDEX]

                query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
                key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
                value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)

                # Compute the cross attention and apply our contrasting operation
                hidden_states, attn_weight = attention_utils.compute_scaled_dot_product_attention(
                    query, key, value,
                    edit_map=perform_swap and model_self.enable_edit and should_mix,
                    is_cross=is_cross,
                    contrast_strength=model_self.config.contrast_strength,
                )

                # Update attention map for segmentation
                if model_self.config.use_masked_adain and model_self.step == model_self.config.adain_range.start - 1:
                    model_self.segmentor.update_attention(attn_weight, is_cross)

                hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
                hidden_states = hidden_states.to(query[OUT_INDEX].dtype)

                # linear proj
                hidden_states = attn.to_out[0](hidden_states)
                # dropout
                hidden_states = attn.to_out[1](hidden_states)

                if input_ndim == 4:
                    hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)

                if attn.residual_connection:
                    hidden_states = hidden_states + residual

                hidden_states = hidden_states / attn.rescale_output_factor

                return hidden_states

        def register_recr(net_, count, place_in_unet):
            if net_.__class__.__name__ == 'ResnetBlock2D':
                pass
            if net_.__class__.__name__ == 'Attention':
                net_.set_processor(AttentionProcessor(place_in_unet + f"_{count + 1}"))
                return count + 1
            elif hasattr(net_, 'children'):
                for net__ in net_.children():
                    count = register_recr(net__, count, place_in_unet)
            return count

        cross_att_count = 0
        sub_nets = self.pipe.unet.named_children()
        for net in sub_nets:
            if "down" in net[0]:
                cross_att_count += register_recr(net[1], 0, "down")
            elif "up" in net[0]:
                cross_att_count += register_recr(net[1], 0, "up")
            elif "mid" in net[0]:
                cross_att_count += register_recr(net[1], 0, "mid")


import datetime

from django.shortcuts import render
from rest_framework import views,viewsets, status
from rest_framework.response import Response
from .models import Product, Availability
from .serializers import ProductSerializer, AvailabilitySerializer
from .authentication import StaticTokenAuthentication

from .datetimeIR import *
# Create your views here.

# Define a viewset that uses Token Authentication for Models.
class TokenAuthenticationViewSet(viewsets.ModelViewSet):
    authentication_classes = [StaticTokenAuthentication]

# Define an API view that uses Token Authentication for search api.
class TokenAuthenticationAPIView(views.APIView):
    authentication_classes = [StaticTokenAuthentication]

# Define a viewset for Product model using Token Authentication.
class ProductViewSet(TokenAuthenticationViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    # Override the destroy method to handle deletion
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"message": "Product deleted successfully."}, status=status.HTTP_204_NO_CONTENT)

# Define a viewset for Availability model using Token Authentication.
class AvailabilityViewSet(TokenAuthenticationViewSet):
    queryset = Availability.objects.all()
    serializer_class = AvailabilitySerializer

    # Create method for adding availability entries.
    def create(self, request, *args, **kwargs):
        data = request.data
        product_id = data.get('product')

        if not product_id:
            return Response({"error": "Product ID is required in the request data."}, status=status.HTTP_400_BAD_REQUEST)

        # Check if the date field contains a single date or a date range
        date = data.get('date')
        date_range = data.get('date_range')

        if date:
            date = jdatetime.datetime.strptime(date, '%Y-%m-%d')
            date = gregorian_converter(date)

            # Check if an Availability entry with the same date and product_id already exists
            if Availability.objects.filter(product_id=product_id, date=date).exists():
                return Response({"error": "Availability with the same date and product already exists."}, status=status.HTTP_400_BAD_REQUEST)

            # Create a single availability entry for a specific date
            Availability.objects.create(product_id=product_id, date=date, price=data.get('price'), available=data.get('available'))
        elif date_range:
            # Create multiple availability entries for a date range
            start_date = jdatetime.datetime.strptime(date_range.get('start_date'), '%Y-%m-%d')
            start_date = gregorian_converter(start_date)
            end_date = jdatetime.datetime.strptime(date_range.get('end_date'), '%Y-%m-%d')
            end_date = gregorian_converter(end_date)

            # Check if an Availability entry with the same date and product_id already exists for each date in the range
            if Availability.objects.filter(product_id=product_id, date=start_date).exists():
                return Response({"error": "Availability with the same date for the product already exists."}, status=status.HTTP_400_BAD_REQUEST)

            # Generate availability entries for each date in the range
            while start_date <= end_date:
                Availability.objects.create(product_id=product_id, date=start_date, price=data.get('price'), available=data.get('available'))
                start_date += datetime.timedelta(days=1)
        else:
            return Response({"error": "Either 'date' or 'date_range' is required in the request data."}, status=status.HTTP_400_BAD_REQUEST)

        return Response({"message": "Availability added successfully."}, status=status.HTTP_201_CREATED)

    # Override the destroy method to handle availability deletion.
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"message": "Availability deleted successfully."}, status=status.HTTP_204_NO_CONTENT)

# Define a view for searching available products and calculating the total price.
class SearchView(TokenAuthenticationAPIView):
    def post(self, request, *args, **kwargs):
        data = request.data
        start_date = jdatetime.datetime.strptime(data['start_date'], '%Y-%m-%d')
        start_date = gregorian_converter(start_date)
        end_date = jdatetime.datetime.strptime(data['end_date'], '%Y-%m-%d')
        end_date = gregorian_converter(end_date)
        adult_count = data['adult_count']
        child_count = data.get('child_count',0)
        infant_count = data.get('infant_count',0)

        # Filter available products based on date range and availability.
        available_products = Product.objects.filter(
            availability__date__range=(start_date, end_date),
            availability__available=True
        ).distinct()

        # print(Product.objects.all())
        # print(Availability.objects.all())

        result = []

        for product in available_products:
            availability_objects = Availability.objects.filter(
                product=product,
                date__range=(start_date, end_date),
                available=True
            )

            total_price = 0
            nights = len(availability_objects)-1

            for availability in availability_objects:
                if availability != availability_objects.last():
                    total_price += availability.price

            # If the adult count is begger than standard capacity, calculate the guests price
            guest_count = adult_count-product.standard_capacity
            if guest_count > 0:
                total_price += (product.adult_price * guest_count * nights)

            # Calculate the children price
            total_price += (product.child_price * child_count * nights)
            # Calculate the Infants price
            total_price += (product.infant_price * infant_count * nights)

            result.append({
                "product_name": product.name,
                "price": total_price,
            })

        return Response(result, status=status.HTTP_200_OK)


import os

def restart_mongo(mongo_log_dir, db_dir, docker_name=None):
    cmd = None
    if docker_name is None:
        cmd = 'mongod --fork --logpath {} --dbpath {}'.format(
            mongo_log_dir, db_dir)
    else:
        # cmd = 'docker exec {} mongod --fork --logpath {} --dbpath {}'.format(
        #     docker_name, mongo_log_dir, db_dir)
        cmd = 'docker start {}'.format(docker_name)
    status = os.system(cmd)
    return status


import requests

def get_repos():
    r = requests.get("https://glittr.org/api/list")
    collection_list = r.json()
    return(collection_list)

def write_toc(collection_list, outfile):
    for category in collection_list:
        category_name = category['name']
        outfile.write(f"- [{category_name}](#{category_name.lower().replace(' ', '-')})\n")
        for topic in category['topics']:
            topic_name = topic['name']
            outfile.write(f"  - [{topic_name}](#{topic_name.lower().replace(' ', '-')})\n")

def write_collection(collection_list, outfile):
    for category in collection_list:
        category_name = category['name']
        outfile.write("\n## " + category_name + '\n\n')
        for topic in category['topics']:
            topic_name = topic['name']
            outfile.write("\n### " + topic_name + '\n\n')
            repo_list = topic['repositories']
            for repo in repo_list:
                if repo['website'] == '':
                    outfile.write(f"- [**{repo['author']['display_name'].strip()}** {repo['name']}]({repo['url']})\n")
                else:
                    outfile.write(f"- [**{repo['author']['display_name'].strip()}** {repo['name']}]({repo['url']}) | [website]({repo['website']})\n")

if __name__ == '__main__':
    collection_list = get_repos()

    output_file = 'README.md'

    with open(output_file, 'w') as outfile:
        with open('scripts/collection_header.md') as infile:
            for line in infile:
                outfile.write(line)
            write_toc(collection_list, outfile)
            write_collection(collection_list, outfile)


def get_score(letter):
  score = ord(letter) - 96
  if score <= 0:
    score += 58
  return score

def get_letter(arr):
  a = arr[0]
  b = arr[1]
  c = arr[2]
  return list(set(a).intersection(set(b)).intersection(set(c)))[0]

result = 0
i = 0
input = []
with open('input', 'r') as infile:
  for line in infile:
    input.append(line.strip())
    i += 1
    if i == 3:
      letter = get_letter(input)
      result += get_score(letter)
      i = 0
      input = []

print(result)


import sys
import dbus, dbus.exceptions, dbus.mainloop.glib
from gi.repository import GLib
from gatt_advert import Advertisement
from gatt_advert import register_ad_cb, register_ad_error_cb
from gatt_server import Service, Characteristic, BatteryService, Descriptor, CharacteristicUserDescriptionDescriptor
from gatt_server import register_app_cb, register_app_error_cb

BLUEZ_SERVICE_NAME =           'org.bluez'
DBUS_OM_IFACE =                'org.freedesktop.DBus.ObjectManager'
LE_ADVERTISING_MANAGER_IFACE = 'org.bluez.LEAdvertisingManager1'
GATT_MANAGER_IFACE =           'org.bluez.GattManager1'
GATT_CHRC_IFACE =              'org.bluez.GattCharacteristic1'
DBUS_PROP_IFACE =    	       'org.freedesktop.DBus.Properties'

# replace with the unique UUID of your app
uuid = '0000feea-0000-1000-8000-00805f9b34fb'
LOCAL_NAME = 'KW19-B'

mainloop = None

payloadstr= 'Testing pairing here!!!'
payload=payloadstr.encode('ascii')

class devCharacteristic(Characteristic):

    def __init__(self, bus, index, serviceUuid, service):
        Characteristic.__init__(self, bus, index, serviceUuid, ['read'], service)
        if index == 0:
            self.value = 'MOY-SBH4-1.7.5'.encode('ascii')
        elif index == 1:
            self.value = 'bc23428b'.encode('ascii')
        else:
            self.value = 'MOYOUNG-HS'.encode('ascii')

    def ReadValue(self, options):
        return self.value

class myCharacteristic(Characteristic):

    def __init__(self, bus, index, serviceUuid, service):
        Characteristic.__init__(self, bus, index, serviceUuid, ['read', 'write', 'notify'], service)
        self.value = payload

    def ReadValue(self, options):
        print('Characteristic Read: 00000')
        return '<'.encode('ascii')

    def WriteValue(self, value, options):
        #print('Characteristic Write: ' + repr(value))
        print("Characteristic Write: " + str(value))
        self.value = value

    def NotifyValue(self, value, options):
        print("Notify Characteristic Notify: " + str(value))
        self.value = value
        return self.value

    def StartNotify(self):
        if self.notifying:
            print ('Already notifying, nothing to do')
            return

        self.notifying = True
        print('started notifying!')
        self._update_hr_msrmt_simulation()

    def StopNotify(self):
        if not self.notifying:
            print ('Not notifying, nothing to do')
            return

        self.notifying = False
        self._update_hr_msrmt_simulation()

class myService(Service):
    def __init__(self, bus, index):
        Service.__init__(self, bus, index, uuid, True)
        self.add_characteristic(myCharacteristic(bus, 0, '0000fee1-0000-1000-8000-00805f9b34fb', self))
        self.add_characteristic(myCharacteristic(bus, 1, '0000fee2-0000-1000-8000-00805f9b34fb', self))
        self.add_characteristic(myCharacteristic(bus, 2, '0000fee3-0000-1000-8000-00805f9b34fb', self))
        self.add_characteristic(myCharacteristic(bus, 3, '00002a19-0000-1000-8000-00805f9b34fb', self))

class devService(Service):
    def __init__(self, bus, index):
        Service.__init__(self, bus, index, '180a', True)
        self.add_characteristic(devCharacteristic(bus, 0, '2a28', self))
        self.add_characteristic(devCharacteristic(bus, 1, '2a25', self))
        self.add_characteristic(devCharacteristic(bus, 2, '2a29', self))

class Application(dbus.service.Object):
    def __init__(self, bus):
        self.path = '/'
        self.services = []
        dbus.service.Object.__init__(self, bus, self.path)

    def get_path(self):
        return dbus.ObjectPath(self.path)

    def add_service(self, service):
        self.services.append(service)

    @dbus.service.method(DBUS_OM_IFACE, out_signature='a{oa{sa{sv}}}')
    def GetManagedObjects(self):
        response = {}
        for service in self.services:
            response[service.get_path()] = service.get_properties()
            chrcs = service.get_characteristics()
            for chrc in chrcs:
                response[chrc.get_path()] = chrc.get_properties()
        return response

class myApplication(Application):
    def __init__(self, bus):
        Application.__init__(self, bus)
        self.add_service(myService(bus, 0))
        self.add_service(devService(bus, 1))
        self.add_service(BatteryService(bus, 2))

class myAdvertisement(Advertisement):

    def __init__(self, bus, index):
        Advertisement.__init__(self, bus, index, 'peripheral')
        self.add_service_uuid(uuid)
        self.add_manufacturer_data(0x02ff, [0xff, 0x03])
        self.add_local_name(LOCAL_NAME)
        self.include_tx_power = True

def find_adapter(bus):
    remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'), DBUS_OM_IFACE)
    objects = remote_om.GetManagedObjects()

    for o, props in objects.items():
        if LE_ADVERTISING_MANAGER_IFACE in props and GATT_MANAGER_IFACE in props:
            return o
        print('Skip adapter:', o)
    return None

def main():
    global mainloop
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus()
    adapter = find_adapter(bus)
    if not adapter:
        print('BLE adapter not found')
        return

    service_manager = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter), GATT_MANAGER_IFACE)
    ad_manager = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter), LE_ADVERTISING_MANAGER_IFACE)

    app = myApplication(bus)
    adv = myAdvertisement(bus, 0)

    mainloop = GLib.MainLoop()

    service_manager.RegisterApplication(app.get_path(), {},
                                        reply_handler=register_app_cb,
                                        error_handler=register_app_error_cb)
    ad_manager.RegisterAdvertisement(adv.get_path(), {},
                                     reply_handler=register_ad_cb,
                                     error_handler=register_ad_error_cb)
    try:
        mainloop.run()
    except KeyboardInterrupt:
        adv.Release()

if __name__ == '__main__':
    main()


import pyraw_nano
import openpyxl
import openpyxl.utils
import argparse
import numpy as np

def badMatchedPixels(D_true, D_estimated, error_thresh):

    mask = D_true > 0
    mask = mask > 0
    error = np.abs(np.round(D_estimated.astype(np.int32)) - D_true.astype(np.int32),)
    error[~mask] = 0

    perc = error > error_thresh
    BMP = np.sum(perc) / np.sum(mask)
    return BMP * 100.0

def main():
    ArgParser = argparse.ArgumentParser()
    ArgParser.add_argument('width', help='width')
    ArgParser.add_argument('height', help='height')
    ArgParser.add_argument('num_of_cams', help='num of cams')
    ArgParser.add_argument('depthFromBlenderPath', help='depthFromBlenderPath')
    ArgParser.add_argument('depthFromGTParamsPath', help='depthFromGTParamsPath')
    ArgParser.add_argument('depthFromEstParamsPath', help='depthFromEstParamsPath')
    ArgParser.add_argument('resultsFilename', help='resultsFilename')
    Args = ArgParser.parse_args()

    W = int(Args.width)
    H = int(Args.height)
    pix_fmt = 'yuv420p16le'

    fnameX = 'v{view:01}_depth_'+str(W)+'x'+str(H)+'_'+str(pix_fmt)+'.yuv'
    fnameXX = 'v{view:02}_depth_'+str(W)+'x'+str(H)+'_'+str(pix_fmt)+'.yuv'

    # DM stands for DepthMap
    gtRenderDM    = Args.depthFromBlenderPath   + fnameXX
    calibParamsDM = Args.depthFromEstParamsPath + fnameX
    gtParamsDM    = Args.depthFromGTParamsPath  + fnameX

    ThresholdPerCent = [1, 2, 4]
    DepthMaxValue    = 2**16 - 1
    ThresholdValues  = [int(round(DepthMaxValue * (t/100))) for t in ThresholdPerCent]

    VIEWS = int(Args.num_of_cams)
    gtRenderDM_vs_calibParamsDM = []
    calibParamsDM_vs_gtParamsDM = []

    for view in range(VIEWS):
        gtRender    = pyraw_nano.imreadLuma(gtRenderDM   .format(view=view), W, H, 16, 420, 0)
        calibParams = pyraw_nano.imreadLuma(calibParamsDM.format(view=view), W, H, 16, 420, 0)
        gtParams    = pyraw_nano.imreadLuma(gtParamsDM   .format(view=view), W, H, 16, 420, 0)

        for threshold in ThresholdValues:
            gtRenderDM_vs_calibParamsDM.append([])
            gtRenderDM_vs_calibParamsDM[view].append(
                badMatchedPixels(gtRender, calibParams, threshold))

            calibParamsDM_vs_gtParamsDM.append([])
            calibParamsDM_vs_gtParamsDM[view].append(
                badMatchedPixels(calibParams, gtParams, threshold))

    wb = openpyxl.Workbook()
    ws = wb.create_sheet('gtRender_vs_calibParams')
    ws['A1'] = 'thresh'
    for i, t in enumerate(ThresholdPerCent):
            ws.cell(column=i+2, row=1, value=f"{t}%")

    for view in range(VIEWS):
        ws[f'A{view+2}'] = f'v{view}'
        for i, value in enumerate(gtRenderDM_vs_calibParamsDM[view]):
            ws.cell(column=i+2, row=view+2, value=value)

    ws.cell(column=1, row=VIEWS+2, value="AVERAGE")
    for i, value in enumerate(calibParamsDM_vs_gtParamsDM[view]):
         ColIdx = i+2
         ColLtr = openpyxl.utils.get_column_letter(ColIdx)
         ws.cell(column=ColIdx, row=VIEWS+2, value=f"=AVERAGE({ColLtr}2:{ColLtr}{VIEWS+1})")

    ws = wb.create_sheet('gtParams_vs_calibParams')
    ws['A1'] = 'thresh'
    for i, t in enumerate(ThresholdPerCent):
            ws.cell(column=i+2, row=1, value=f"{t}%")

    for view in range(VIEWS):
        ws[f'A{view+2}'] = f'v{view}'
        for i, value in enumerate(calibParamsDM_vs_gtParamsDM[view]):
            ws.cell(column=i+2, row=view+2, value=value)

    ws.cell(column=1, row=VIEWS+2, value="AVERAGE")
    for i, value in enumerate(calibParamsDM_vs_gtParamsDM[view]):
         ColIdx = i+2
         ColLtr = openpyxl.utils.get_column_letter(ColIdx)
         ws.cell(column=ColIdx, row=VIEWS+2, value=f"=AVERAGE({ColLtr}2:{ColLtr}{VIEWS+1})")

    del wb['Sheet']
    wb.save(Args.resultsFilename)

if __name__ == '__main__':
    main()


import sys
import argparse
import math
import numpy as np
import matplotlib.pyplot as plt

class Circle:
    def __init__(self, radius, xc, yc):
        self.radius = radius
        self.xc = xc
        self.yc = yc

    def calculate(self, t):
        angle = 2 * math.pi * t
        x = math.cos(angle) * self.radius + self.xc
        y = math.sin(angle) * self.radius + self.yc
        return x, y

class Ellipse:
    def __init__(self, radius_a, radius_b, xc, yc):
        self.radius_a = radius_a
        self.radius_b = radius_b
        self.xc = xc
        self.yc = yc

    def calculate(self, t):
        angle = 2 * math.pi * t
        x = math.cos(angle) * self.radius_a + self.xc
        y = math.sin(angle) * self.radius_b + self.yc
        return x, y

def circle(t, radius, center):
    angle = 2 * math.pi * t
    x = math.cos(angle)*radius + center[0]
    y = math.sin(angle)*radius + center[1]
    return x, y

def ellipse(t, a, b, center):
    angle = 2 * math.pi * t
    x = math.cos(angle)*a + center[0]
    y = math.sin(angle)*b + center[1]
    return x, y

def create_points(steps, function):
    points = []
    for i in range(steps):
        t = np.random.random()
        point = list((function.calculate(t)))
        points.append(point)

    return points

def create_points_ordered(begin, end, step, function):
    points = []
    t = begin
    while True:
        if t >= end:
            break
        point = list((function.calculate(t)))
        points.append(point)
        t += step

    return points

def shuffle_points(points):
    permutation = np.random.permutation(len(points))
    new_points = []
    for i in range(len(points)):
        new_points.append(points[permutation[i]])

    return new_points

def save_points(points, file_name):
    file = open(file_name, 'w')
    sample_number = len(points)
    var_number = len(points[0])

    file.write("{0} {1}\n".format(sample_number, var_number))
    for i in range(sample_number):
        line = " ".join([str(x) for x in points[i]])
        file.write(line + "\n")

    file.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Implicit function generator")
    parser.add_argument('--lower_bound', '-L', type=int,
                        help='lower bound integer for variable')
    parser.add_argument('--upper_bound', '-U', type=int,
                        help='upper bound integer for variable')
    parser.add_argument('--steps', '-S', type=int)
    parser.add_argument('--step_begin', '-SB', type=float)
    parser.add_argument('--step_end', '-SE', type=float)
    parser.add_argument('--step_step', '-SS', type=float)
    parser.add_argument('--method', '-M', default='circle', choices=['circle', 'ellipse'])
    parser.add_argument('--radius', '-R', type=float)
    parser.add_argument('--radius_a', '-RA', type=float)
    parser.add_argument('--radius_b', '-RB', type=float)
    parser.add_argument('--center_x', '-xc', type=float)
    parser.add_argument('--center_y', '-yc', type=float)
    parser.add_argument('--points_number', '-N', type=int)
    parser.add_argument('--shuffle')
    parser.add_argument('--save')

    args = parser.parse_args()
    function = None
    if args.method:
        if args.method.lower() == 'circle':
            if not args.radius or (not args.center_x and args.center_x != 0.0) or (not args.center_y and args.center_y != 0.0):
                print("You haven't provided all arguments!")
                exit(1)
            function = Circle(args.radius, args.center_x, args.center_y)
        elif args.method.lower() == 'ellipse':
            if not args.radius_a or not args.radius_b or not args.center_x or not args.center_y:
                print("You haven't provided all arguments!")
                exit(1)
            function = Ellipse(args.radius_a, args.radius_b, args.center_x, args.center_y)
        else:
            print('Method not supported!')
            exit(1)

    points = None
    if args.steps:
        points = create_points(args.steps, function)
    elif not args.step_begin or not args.step_end or not args.step_step:
        points = create_points_ordered(args.step_begin, args.step_end, args.step_step, function)
    else:
        print("Step not configured well!")
        exit(1)

    if args.shuffle:
        points = shuffle_points(points)

    if args.save:
        save_points(points, args.save)


#!/usr/bin/env python3
from src.compression.huffman import Huffman, Symbol
from math import ceil
import numpy as np
import json
import galois as gl
from typing import List

class Genetic_Algorithm:
    """A genetic algorithm for optimizing the code books for huffman"""

    def __init__ (self, symbol_length: int, number_of_agents: int, permutation_prob: float, base: int = 8):
        """"Initialize a list of agents (code_books). That will later be optimized"""
        self.symbol_length = symbol_length
        self.permuation_prob = permutation_prob
        self.code_books = [{} for _ in range(number_of_agents)]
        self.scores = [np.inf for _ in range(number_of_agents)]

    def compute_offspring(self, uncompressed_size: int) -> None:
        """Computes the new agents based on the scores."""
        # NOTE: might need to be reversed.
        against_identity = [(uncompressed_size - score) / uncompressed_size for score in self.scores]
        total_against_identity = sum(against_identity)
        probs = [rel_score  / total_against_identity for rel_score in against_identity]
        offspring = []
        for _ in range(len(self.code_books)):
            x, y = np.random.choice(self.code_books, probs, replace=False)
            offspring.append()

        self.code_books = offspring

    def recompute_scores(self, message: List[Symbol]) -> None:
        """Check how well each code_book performs for compression."""
        for idx, code_book in enumerate(self.code_books):
            huffman = Huffman(code_book, symbol_length=self.symbol_length, will_be_decompressed=False)
            self.scores[idx] = huffman.compress(message).shape[0]

    def run(self, message: List[Symbol], alphabeth: List[Symbol], encoding: str, max_iter: int = 2):
        """Run the genetic algorithm and return the best code_book as a json file."""
        # Perform the iterations.
        uncompressed_size = len(message) * (ceil(len(alphabeth) / self.base))
        for iter in range(1, max_iter + 1):
            print(f"Now at iteration: {iter}")
            self.recompute_scores(message)
            new_best = min(self.scores)
            print(f"  Best size: {new_best} [symbols]")
            print(f"   - Compared to original: {new_best / uncompressed_size * 100} %")
            self.compute_of_spring()

        # Store the best code_book as a json file.
        self.recompute_scores(message)
        max_idx = self.scores.index(min(self.scores))
        best_code_book = self.code_boks[max_idx]
        final_best = min(self.scores)
        print(f"Final best size: {final_best} [symbols]")
        print(f" - Compared to orignial: {final_best / uncompressed_size * 100} %")
        with open(f"{encoding}.json", "w+") as file:
            obj = {"base": self.base, "code_book": {key: list(val) for (key, val) in best_code_book.items()}}
            json.dump(obj, file)


from matplotlib.transforms import BlendedGenericTransform
from matplotlib import patches
from matplotlib.patches import Circle, Arc
import matplotlib.pyplot as plt
plt.rcParams['mathtext.fontset'] = 'cm'
import numpy as np
dtr = np.pi/180

import control

mygray = '#808B96'
grid_dict = {'linestyle':'dashed',\
             'color':mygray, \
             'linewidth':1.0, \
             'zorder':0, \
}

class root_locus_sketch(object):
    def __init__(self, ax=None, \
                 xmax=2, xmin=-5.5, ymax=5.5, ymin=-5.5, \
                 xlims=[-8,4], ylims=[-6,6], \
                 fontdict = {'size': 20, 'family':'serif'}, \
                 axis_lw=2, \
                 ):
        if ax is None:
            fig = plt.figure(figsize=(9,9))
            ax = fig.add_subplot(111)
        self.ax = ax
        self.xmin = xmin
        self.xmax = xmax
        self.ymin = ymin
        self.ymax = ymax
        self.xlims = xlims
        self.ylims = ylims
        self.axis_lw = axis_lw
        self.fontdict = fontdict

    def draw_arrow(self, start_coords, end_coords, \
                   fc='k', ec=None, lw=None, **plot_args):
        if not hasattr(self, 'hw'):
            self.set_arrow_lengths()
        if ec is None:
            ec = fc
        # if lw is None:
        #     lw = self.arrow_lw
        ##start_A = transform_coords(start_coords, HT)
        ##stop_A = transform_coords(end_coords, HT)
        dx = end_coords[0]-start_coords[0]
        dy = end_coords[1]-start_coords[1]

        self.ax.arrow(start_coords[0], start_coords[1], dx, dy, \
                      lw=lw, fc=fc, ec=ec, \
                      width=0.01, \
                      head_width=self.hw, head_length=self.hl, \
                      #overhang = self.ohg, \
                      length_includes_head=True, clip_on = False, \
                      **plot_args)

    def draw_axis(self):
        self.draw_arrow((0,0), (self.xmax,0), \
                        lw=self.axis_lw)
                        #fc=self.axis_color,
        #self.place_rotated_text(self.xmax+self.axis_label_shift, 0, xlabel, HT)
        self.draw_arrow((0,0), (0,self.ymax), \
                        lw=self.axis_lw)
        self.draw_arrow((0,0), (0,self.ymin), \
                        lw=self.axis_lw)
                        #fc=self.axis_color,
        #self.place_rotated_text(0, self.ymax+self.axis_label_shift, ylabel, HT)
        self.draw_arrow((0,0), (self.xmin,0), \
                        lw=self.axis_lw)

    def set_arrow_lengths(self):
        self.hw = 1./30.*(self.ymax-self.ymin)
        self.hl = 1./20.*(self.xmax-self.xmin)
        self.lw = 2. # axis line width
        self.ohg = 0.3 # arrow overhang

    def axis_off(self):
        self.ax.set_axis_off()

    def draw_marker(self, point, style='go', size=12, **plot_kwargs):
        self.ax.plot([np.real(point)],[np.imag(point)], \
                     style, markersize=size, **plot_kwargs)

    def draw_markers(self, point_list, style='go', size=12, **plot_kwargs):
        for point in point_list:
            self.draw_marker(point, style=style, size=size, **plot_kwargs)

    def add_text(self, point, text, xoffset=0, yoffset=0, \
                 fontdict=None):
        if fontdict is None:
            fontdict = self.fontdict
        self.ax.text(np.real(point)+xoffset, np.imag(point)+yoffset, \
                     text, fontdict=fontdict)

    def add_math_text(self, point, text, *args, **kwargs):
        if text[0] != '$':
            text = '$%s$' % text
        self.add_text(point, text, *args, **kwargs)

    def draw_point_with_label(self, point, text, style='go', size=12, \
                          xoffset=0, yoffset=0, \
                          fontdict=None):
        self.draw_marker(point, style=style, size=size)
        self.add_text(point, text, xoffset=xoffset, yoffset=yoffset, \
                      fontdict=fontdict)

    def draw_line(self, start, end, linestyle='k--', **plot_kwargs):
        self.ax.plot([np.real(start), np.real(end)], \
                     [np.imag(start), np.imag(end)], \
                     linestyle, **plot_kwargs)

    def draw_lines_to_point(self, point, pole_or_zero_list, \
                            linestyle='k--', **plot_kwargs):
        for pz in pole_or_zero_list:
            self.draw_line(pz, point, linestyle=linestyle, **plot_kwargs)

    def draw_poles(self, pole_list, style='rX', size=12, **plot_kwargs):
        for i, p in enumerate(pole_list):
            j = i+1
            self.ax.plot([np.real(p)],[np.imag(p)], \
                         style, markersize=size, **plot_kwargs)

    def draw_zeros(self, zero_list, style='ro', size=12, **plot_kwargs):
        self.draw_markers(zero_list, style=style, size=size, **plot_kwargs)

    def plot_branches(self, rmat, **plot_kwargs):
        self.ax.plot(np.real(rmat), np.imag(rmat), **plot_kwargs)

    def label_axes(self, real_point=None, imag_point=None, fontdict=None):
        if real_point is None:
            real_point = self.xmax-0.7j
        if imag_point is None:
            imag_point = 0.3+self.ymax*1j
        self.add_text(real_point, 'Re', fontdict=fontdict)
        self.add_text(imag_point, 'Im', fontdict=fontdict)

    def label_points(self, points, labels, offsets=None, fontdict=None):
        N = len(points)
        if offsets is None:
            offsets = [(0,0)]*N
        elif len(offsets) == 1:
            offsets = N*offsets

        for p, label, offset in zip(points, labels, offsets):
            self.add_text(p, label, xoffset=offset[0], yoffset=offset[1], \
                          fontdict=fontdict)

    def draw_vertical_gridlines(self, xlist=None, \
                                ymin=None, ymax=None, plot_kwargs=None):
        if plot_kwargs is None:
            plot_kwargs = grid_dict

        if ymax is None:
            ymax = self.ymax

        if ymin is None:
            ymin = self.ymin

        if xlist is None:
            xlist = np.arange(0,self.xmax,1)

        for x in xlist:
            self.ax.plot([x,x], [ymin,ymax], **plot_kwargs)

    def draw_horizontal_gridlines(self, ylist=None, \
                                xmin=None, xmax=None, plot_kwargs=None):
        if plot_kwargs is None:
            plot_kwargs = grid_dict

        if xmax is None:
            xmax = self.xmax

        if xmin is None:
            xmin = self.xmin

        if ylist is None:
            ylist = np.arange(self.ymin,self.ymax,1)

        for y in ylist:
            self.ax.plot([int(xmin),int(xmax)], [y,y], **plot_kwargs)

    def draw_xticks(self, ticks=None, dy=0.1, **plot_kwargs):
        kwargs = {'color':'k',\
                  'linewidth':2}
        kwargs.update(plot_kwargs)

        if ticks is None:
            ticks = np.arange(int(self.xmin), int(self.xmax), 1)

        for tick in ticks:
            start_tick = [tick, dy]
            end_tick = [tick, -dy]
            self.ax.plot([tick,tick], [dy,-dy], **kwargs)

    def draw_yticks(self, ticks=None, dx=0.1, **plot_kwargs):
        kwargs = {'color':'k',\
                  'linewidth':2}
        kwargs.update(plot_kwargs)

        if ticks is None:
            ticks = np.arange(int(self.ymin), int(self.ymax)+1, 1)

        for tick in ticks:
            self.ax.plot([-dx,dx], [tick,tick], **kwargs)

    def main_axis(self, ticks=True):
        self.set_arrow_lengths()
        self.axis_off()
        self.draw_axis()
        if ticks:
            self.draw_xticks()
            self.draw_yticks()
        self.label_axes()
        self.ax.set_xlim(self.xlims)
        self.ax.set_ylim(self.ylims)
        plt.tight_layout()

class root_locus_sketch_with_TF(root_locus_sketch):
    def __init__(self, G, ax=None, *args, **kwargs):
        root_locus_sketch.__init__(self, ax, *args, **kwargs)
        self.G = G

    def main(self, kvect=None, markerstyle='bX', linecolor='b',
             plot_branches=True, ticks=True):
        root_locus_sketch.main_axis(self, ticks=ticks)
        self.draw_poles(style=markerstyle)
        if plot_branches:
            self.plot_branches(kvect=kvect,color=linecolor)
        self.draw_zeros()

    def draw_poles(self, style='rX', size=12, **plot_kwargs):
        root_locus_sketch.draw_poles(self, self.G.pole(), style=style, size=size, **plot_kwargs)

    def draw_zeros(self, style='ro', size=12, **plot_kwargs):
        zlist = self.G.zero()
        if len(zlist) > 0:
            root_locus_sketch.draw_zeros(self, zlist, style=style, size=size, **plot_kwargs)

    def plot_branches(self, kvect=None, **plot_kwargs):
        rmat, kout = control.root_locus(self.G, kvect=kvect, Plot=False)
        self.ax.plot(np.real(rmat), np.imag(rmat), **plot_kwargs)

    def label_axes(self, real_point=None, imag_point=None, fontdict=None):
        if real_point is None:
            real_point = self.xmax-0.7j
        if imag_point is None:
            imag_point = 0.3+self.ymax*1j
        self.add_text(real_point, 'Re', fontdict=fontdict)
        self.add_text(imag_point, 'Im', fontdict=fontdict)

    def label_points(self, points, labels, offsets=None, fontdict=None):
        N = len(points)
        if offsets is None:
            offsets = [(0,0)]*N
        elif len(offsets) == 1:
            offsets = N*offsets

        for p, label, offset in zip(points, labels, offsets):
            self.add_text(p, label, xoffset=offset[0], yoffset=offset[1], \
                          fontdict=fontdict)

    def draw_vertical_gridlines(self, xlist=None, \
                                ymin=None, ymax=None, plot_kwargs=None):
        if plot_kwargs is None:
            plot_kwargs = grid_dict

        if ymax is None:
            ymax = self.ymax

        if ymin is None:
            ymin = self.ymin

        if xlist is None:
            xlist = np.arange(0,self.xmax,1)

        for x in xlist:
            self.ax.plot([x,x], [ymin,ymax], **plot_kwargs)

    def draw_horizontal_gridlines(self, ylist=None, \
                                xmin=None, xmax=None, plot_kwargs=None):
        if plot_kwargs is None:
            plot_kwargs = grid_dict

        if xmax is None:
            xmax = self.xmax

        if xmin is None:
            xmin = self.xmin

        if ylist is None:
            ylist = np.arange(self.ymin,self.ymax,1)

        for y in ylist:
            self.ax.plot([int(xmin),int(xmax)], [y,y], **plot_kwargs)

    def draw_xticks(self, ticks=None, dy=0.1, **plot_kwargs):
        kwargs = {'color':'k',\
                  'linewidth':2}
        kwargs.update(plot_kwargs)

        if ticks is None:
            ticks = np.arange(int(self.xmin), int(self.xmax), 1)

        for tick in ticks:
            start_tick = [tick, dy]
            end_tick = [tick, -dy]
            self.ax.plot([tick,tick], [dy,-dy], **kwargs)

    def draw_yticks(self, ticks=None, dx=0.1, **plot_kwargs):
        kwargs = {'color':'k',\
                  'linewidth':2}
        kwargs.update(plot_kwargs)

        if ticks is None:
            ticks = np.arange(int(self.ymin), int(self.ymax), 1)

        for tick in ticks:
            self.ax.plot([-dx,dx], [tick,tick], **kwargs)

class root_locus_sketch_with_TF_2(root_locus_sketch):
    def __init__(self, ax, G, *args, **kwargs):
        root_locus_sketch.__init__(self, ax, *args, **kwargs)
        self.G = G

    def draw_poles(self, style='rX', size=12, zorder=10, **kwargs):
        root_locus_sketch.draw_poles(self, self.G.pole(), style=style, \
                                     size=size, zorder=zorder, **kwargs)

    def draw_zeros(self, style='ro', size=12, zorder=10, **kwargs):
        root_locus_sketch.draw_poles(self, self.G.zero(), style=style, \
                                     size=size, zorder=zorder, \
                                     **kwargs)

    def add_test_point(self, point, style='go', size=12, \
                       label=None, label_offset=0+0j, \
                       **plot_kwargs):
        self.s0 = point
        self.draw_marker(point, style=style, size=size, **plot_kwargs)
        if label is not None:
            self.add_math_text(self.s0+label_offset, label)

    def draw_lines_to_test_point(self, linestyle='k--', **plot_kwargs):
        self.draw_lines_to_point(self.s0, self.G.pole(), \
                                 linestyle=linestyle, **plot_kwargs)
        self.draw_lines_to_point(self.s0, self.G.zero(), \
                                 linestyle=linestyle, **plot_kwargs)

    def build_label_list(self, N, pat):
        labels = []
        for i in range(N):
            j = i+1
            cur_str = pat % j
            labels.append(cur_str)
        return labels

    def make_phi_labels(self):
        N = len(self.G.pole())
        phi_labels = self.build_label_list(N, '\\phi_{%i}')
        return phi_labels

    def make_psi_labels(self):
        N = len(self.G.zero())
        psi_labels = self.build_label_list(N, '\\psi_{%i}')
        return psi_labels

    def label_angles_to_point(self, phi_labels, psi_labels, \
                              phi_offsets=None, psi_offsets=None, \
                              **kwargs):
        if phi_offsets is None:
            np = len(self.G.pole())
            phi_offsets = [0]*np
        if psi_offsets is None:
            nz = len(self.G.zero())
            psi_offsets = [0]*nz

        for p, label, po in zip(self.G.pole(), phi_labels, phi_offsets):
            self.add_math_text(p+po, label, **kwargs)
        for z, label, zo in zip(self.G.zero(), psi_labels, psi_offsets):
            self.add_math_text(z+zo, label, **kwargs)

class root_locus_sketch_two_pole_locations(root_locus_sketch):
    """A class for generating pole locations plots for comparing two
    TFs and their step responses."""
    def __init__(self, G1, G2, label_offsets=[0.2+0.2j, 0.2+0.2j], \
                 markers=['bo','g^'], inds=[1,2], \
                 **kwargs):
        root_locus_sketch.__init__(self, **kwargs)
        self.G1 = G1
        self.G2 = G2
        self.label_offsets = label_offsets
        self.markers = markers
        self.inds = inds

    def draw_and_label_poles(self):
        # get poles and force the imaginary part to be positive
        p1 = self.G1.pole()[0]
        p2 = self.G2.pole()[0]

        for p, m, lo, ind in zip([p1,p2], self.markers, \
                                  self.label_offsets, self.inds):
            p = np.real(p) + 1j*np.abs(np.imag(p))
            self.draw_marker(p, style=m)
            self.draw_marker(np.conj(p), style=m)
            mytext = '$G_{%i}$' % ind
            self.add_text(p, mytext, xoffset=np.real(lo), yoffset=np.imag(lo))

    def main(self, ticks=True):
        self.main_axis(ticks=ticks)
        self.draw_and_label_poles()