class minHeap:
    def __init__(self) -> None:
        self.heap = []

    def __bool__(self) -> bool:
        return bool(len(self.heap))

    def __str__(self) -> str:
        return f"{self.heap}"

    def add(self, val) -> None:
        self.heap.append(val)
        self.heap.sort()

    def pop(self):
        return self.heap.pop(0)

class Solution:
    def minimumEffortPath(self, heights: list[list[int]]) -> int:
        row = len(heights)
        column = len(heights[0])
        effort_ary = [[float("inf")] * column for _ in range(row)]
        effort_ary[0][0] = 0
        heap = minHeap()
        heap.add([0, 0, 0])
        while heap:
            curr = heap.pop()
            right = [curr[1], curr[2] + 1]
            left = [curr[1], curr[2] - 1]
            up = [curr[1] - 1, curr[2]]
            down = [curr[1] + 1, curr[2]]

            if right[1] < column:
                cost = max(
                    curr[0],
                    abs(heights[curr[1]][curr[2]] - heights[right[0]][right[1]]),
                )
                if cost < effort_ary[right[0]][right[1]]:
                    effort_ary[right[0]][right[1]] = cost
                    heap.add([cost, right[0], right[1]])

            if down[0] < row:
                cost = max(
                    curr[0],
                    abs(heights[curr[1]][curr[2]] - heights[down[0]][down[1]]),
                )
                if cost < effort_ary[down[0]][down[1]]:
                    effort_ary[down[0]][down[1]] = cost
                    heap.add([cost, down[0], down[1]])

            if left[1] >= 0:
                cost = max(
                    curr[0],
                    abs(heights[curr[1]][curr[2]] - heights[left[0]][left[1]]),
                )
                if cost < effort_ary[left[0]][left[1]]:
                    effort_ary[left[0]][left[1]] = cost
                    heap.add([cost, left[0], left[1]])

            if up[0] >= 0:
                cost = max(
                    curr[0],
                    abs(heights[curr[1]][curr[2]] - heights[up[0]][up[1]]),
                )
                if cost < effort_ary[up[0]][up[1]]:
                    effort_ary[up[0]][up[1]] = cost
                    heap.add([cost, up[0], up[1]])

            if curr[1] == row - 1 and curr[2] == column - 1:
                break

        return effort_ary[-1][-1]

if __name__ == "__main__":
    test_cases = [
        [
            [1, 2, 2],
            [3, 8, 2],
            [5, 3, 5],
        ],
        [
            [1, 2, 3],
            [3, 8, 4],
            [5, 3, 5],
        ],
        [
            [1, 2, 1, 1, 1],
            [1, 2, 1, 2, 1],
            [1, 2, 1, 2, 1],
            [1, 2, 1, 2, 1],
            [1, 1, 1, 2, 1],
        ],
    ]
    test_results = [
        2,
        1,
        0,
    ]

    for test, result in zip(test_cases, test_results):
        a = Solution()
        assert a.minimumEffortPath(test) == result

    print("Passed")


import rospy

import actionlib
import moveit_msgs.msg
from cob_manipulation_msgs.msg import QueryGraspsAction, QueryGraspsGoal

def query_grasps_client():
    client = actionlib.SimpleActionClient('query_grasps', QueryGraspsAction)
    client.wait_for_server()

    goal = QueryGraspsGoal()
    #goal.object_name="peanuts"
    #goal.gripper_type = "sdh"
    goal.object_name="pringles"
    goal.gripper_type = "sdhx"
    #goal.grasp_id = 2
    goal.num_grasps = 0
    goal.threshold = 0

    client.send_goal(goal)
    client.wait_for_result()
    return client.get_result()

if __name__ == '__main__':
    try:
        rospy.init_node('query_grasps_client')
        result = query_grasps_client()
        print("Result:")
        print(result)
        #print len(result.grasp_list)
    except rospy.ROSInterruptException:
        print("program interrupted before completion")


# coding: utf-8

import os

def merge(array: int, start: int, mid: int, end: int):
    print('做merge')
    print()
    target_len = end - start + 1
    left_list = []
    right_list = []
    result = []

    for i in range(start, mid + 1):
        left_list.append(array[i])

    for i in range(mid + 1, end + 1):
        right_list.append(array[i])

    while len(result) != target_len:
        if len(right_list) == 0 and len(left_list) != 0:
            result.append(left_list.pop(0))
            continue
        if len(left_list) == 0 and len(right_list) != 0:
            result.append(right_list.pop(0))
            continue
        if len(left_list) != 0 and len(right_list) != 0:
            if left_list[0] <= right_list[0]:
                result.append(left_list.pop(0))
            else:
                result.append(right_list.pop(0))

    # print(result)
    for i in range(start,end+1):
        array[i] = result.pop(0)

def sorter_left(array: list, start_index: int, end_index: int, big_mid: int):
    curr_mid = (start_index + end_index) // 2
    # print('@@@@@@@@@@')
    # print('@中間:', curr_mid)
    # print('@左:', start_index, '@右:', end_index)

    if start_index < end_index:
        # print('@中間:', curr_mid)
        # print('@左:', start_index, '@右:', end_index)
        sorter_left(array, start_index, curr_mid, big_mid)
        sorter_left(array,curr_mid + 1, end_index,big_mid)
        # print('做比較 - 中間:', curr_mid, '左:', start_index, '右:', end_index)
        if curr_mid != big_mid:
            print('------------------')
            print('中間:', curr_mid)
            print('左:', start_index, '右:', end_index)
            merge(array, start_index, curr_mid, end_index)
            # return
        else:
            print('$$$')

        # merge(array, start_index, middle, end_index)
    else:
        print('開始:',start_index,'結束:',end_index)
        print('**** 跳出')

def merge_sort(array: list):
    total_len = len(array)

    big_mid = (len(array) - 1) // 2

    # sort左邊
    sorter_left(array, 0, len(array) - 1, big_mid)

a = [7, 4, 8, 5, 6, 5, 3]
# a = [4, 7, 8, 5, 6, 5, 3, 4, 7, 8, 5, 6, 5, 3, 4, 7, 8, 5, 6, 5, 3]
merge_sort(a)
print(a)


from tqdm import tqdm
import torch
import torch.optim as optim
from accelerate import Accelerator
from torch_geometric.loader import DataLoader
from torch.utils.data import random_split
import argparse
import os
from utils import *
from dataset import Dataset
from model import GCN
import pandas as pd
import numpy as np
from sklearn.metrics import r2_score
from torch.utils.tensorboard import SummaryWriter

# function to parse arguments
def parse_args():
    pass

# function to load dataset
def load_dataset(name, k, batch_size, train_ratio, test_ratio):
    # get dataset
    dataset = Dataset(root="../data", name=name, k=k)
    # get train and test size
    train_size = int(train_ratio * len(dataset))
    test_size = dataset.len() - train_size
    # get train and test dataset
    train_dataset, test_dataset = random_split(dataset, [train_size, test_size])
    # get train and test loader
    train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=16)
    test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, drop_last=True, num_workers=16)
    return train_loader, test_loader

# train model, report r2 score, MAE and loss to summary writer without function
def train_model(model, name, train_loader, test_loader, epochs, accelerator, writer_dir, lr=0.001):

    # set optimizer and loss function
    optimizer = optim.Adam(model.parameters(), lr=lr)

    # mae for loss, mse and r2 for evaluation, all reported
    mae = torch.nn.L1Loss()
    mse = torch.nn.MSELoss()

    # writer for tensorboard
    writer = SummaryWriter(writer_dir)

    # accelerator
    model, optimizer, train_loader, test_loader = accelerator.prepare(model, optimizer, train_loader, test_loader)

    # train loop
    for epoch in tqdm(range(epochs)):

        # set model to train
        model.train()

        # collect losses
        train_losses_mae = []
        train_losses_mse = []

        for data in train_loader:

            # get data
            x, edge_attr, edge_index, batch_index, y = data.x, data.edge_attr, data.edge_index, data.batch, data.y

            # reshape y
            # y = y.reshape(-1, 3)
            y = y.reshape(-1, 2)

            # get output
            output = model(x, edge_attr, edge_index, batch_index)

            # calculate loss for x and y  dims
            loss_mae = mae(output[:, :2], y[:, :2])
            loss_mse = mse(output[:, :2], y[:, :2])

            # collect losses
            train_losses_mae.append(accelerator.gather(loss_mae.item()))
            train_losses_mse.append(accelerator.gather(loss_mse.item()))

            # zero grad
            optimizer.zero_grad()

            # backpropagate
            accelerator.backward(loss_mae)

            # step optimizer
            optimizer.step()

        # get avg traiin loss
        avg_train_mae = np.mean(train_losses_mae)
        avg_train_mse = np.mean(train_losses_mse)

        print(f"Epoch {epoch+1}/{epochs}")
        print(f"Train MSE: {avg_train_mse:.4f}, Train MAE: {avg_train_mae:.4f}")

        # log to tensorboard
        if accelerator.is_main_process:
            writer.add_scalar(f"{name}_Train MSE", avg_train_mse, epoch)
            writer.add_scalar(f"{name}_Train MAE", avg_train_mae, epoch)

        # set model to eval
        model.eval()

        # collect losses
        test_losses_mae = []
        test_losses_mse = []
        test_r2_scores = []

        # no grad
        with torch.no_grad():
            for data in test_loader:

                # get data
                x, edge_attr, edge_index, batch_index, y = data.x, data.edge_attr, data.edge_index, data.batch, data.y

                # reshape y
                # y = y.reshape(-1, 3)
                y = y.reshape(-1, 2)

                # get output
                output = model(x, edge_attr, edge_index, batch_index)

                # calculate loss for x and y  dims
                loss_mae = mae(output[:, :2], y[:, :2])
                loss_mse = mse(output[:, :2], y[:, :2])

                # collect losses
                test_losses_mae.append(accelerator.gather(loss_mae.item()))
                test_losses_mse.append(accelerator.gather(loss_mse.item()))

                # get r2 score
                r2 = r2_score(y[:, :2].cpu().numpy(), output[:, :2].cpu().numpy())
                test_r2_scores.append(r2)

            # get avg test loss
            avg_test_mae = np.mean(test_losses_mae)
            avg_test_mse = np.mean(test_losses_mse)
            avg_test_r2 = np.mean(test_r2_scores)

            print(f"Test MSE: {avg_test_mse:.4f}, Test MAE: {avg_test_mae:.4f}, Test R2: {avg_test_r2:.4f}")

            # log to tensorboard
            if accelerator.is_main_process:
                writer.add_scalar(f"{name}_Test MSE", avg_test_mse, epoch)
                writer.add_scalar(f"{name}_Test MAE", avg_test_mae, epoch)
                writer.add_scalar(f"{name}_Test R2", avg_test_r2, epoch)

    # close writer
    writer.close()

    # save model
    accelerator.wait_for_everyone()
    if accelerator.is_main_process:
        # save model
        accelerator.save_model(model, f"./weights/{name}.pt")


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#File Name:shell_sort.py
#Created Time:2019-09-20 02:42:45

'''
将待排序数组按照步长 gap 进行分组，然后将每组的元素利用直接插入排序的方法进行排序,
每次将 gap 折半减小，循环上述操作，当 gap = 1时，利用直接插入方法，完成排序。

总体实现应该 由 三个循环完成
1. 第一层循环：将 gap 依次折半，对序列进行分组，直到 gap = 1
2. 第二，三层循环，则是直接插入排序的两层循环

'''

def shell_sort(L):
    length = len(L)
    # gap 初值一半设置为序列长度的一半
    gap = length//2
    while gap >= 1:
        # 从 L[gap] 开始
        for x in range(gap,length):
            # 从 x-gap 开始与选定元素开始倒序比较，每个比较元素之间间隔 gap
            for i in range(x-gap,-1,-gap):
                if L[i] > L[i+gap]:
                    L[i],L[i+gap] = L[i+gap],L[i]
        gap = gap//2

if __name__ == '__main__':
    L = [25,21,25,4,16,12,8,49,3]
    shell_sort(L)
    print(L)


"""
This scenario develops in an urban environment consisting of a two-lane road
in alternating directions. The actors are three: Ego, Pedestrian and JamCar.
Ego is a level 3 self-driving car, while JamCar is a traditional car driven
by Andrea, a human being whose characteristics are not specified. The pedestrian
crosses the street without a pedestrian crossing. Ego stops to let the Pedestrian pass.
Injecting causal invoices to Andrea, aboard JamCar, further sub-scenarios are generated.
"""

import os
import time
from scenariogeneration import xosc, prettyprint, ScenarioGenerator, esmini
from controller.midleware import *
from config import XOSC_DIR, ESMINI_DIR

class Scenario(ScenarioGenerator):

    def __init__(self, ego_name: str = 'Ego', pedestrian_name: str = 'Ped1', other_vehicle: str = 'JamCar'):
        ScenarioGenerator.__init__(self)
        self._ego_name = ego_name
        self._pedestrian_name = pedestrian_name
        self._jam_vehicle_name = other_vehicle
        self._param_declaration = None
        self._catalog = None
        self._road = None
        self._entities = xosc.Entities()
        self._pedestrian_maneuver_group = None
        self._ego_maneuver_group = None
        self._jam_maneuver_group = None
        self._act = None
        self._init = xosc.Init()
        self._story = None
        self._storyboard = None
        self._scenario = None

    def __str__(self):
        return "Scenario 01"

    def base_scenario_factory(self, save_scenario_file=False,
                              print_scenario=False,
                              run_scenario_file=True,
                              injected_init_function=None,
                              injected_event_function=None,
                              *args, **kwargs):
        """
        Factory to generate scenario.
        Order of methods execution is mandatory.

        :param run_scenario_file:
        :param injected_event_function:
        :param injected_init_function:
        :param save_scenario_file:
        :param print_scenario:
        :return:
        """
        self._create_parameters()
        self._create_catalogs()
        self._create_road()
        self._create_ego_entity()
        self._create_pedestrian_entity()
        self._create_jam_vehicle_entity()
        self._create_init_ego()
        self._create_init_pedestrian()

        # Only jam vehicle change behavior
        self.create_init_jam_vehicle() if not injected_init_function else injected_init_function()

        self._add_ego_event()
        self._add_pedestrian_event()

        # Only jam vehicle change behavior
        self.add_jam_vehicle_base_event() if not injected_event_function else injected_event_function(*args, **kwargs)
        # ??? self.add_jam_vehicle_accelerate_event()
        # self.add_jam_vehicle_brake_and_accelerate_event()
        # self.add_jam_vehicle_slow_down_event()
        # self.add_jam_vehicle_lane_change_left_event()
        # self.add_jam_vehicle_lane_change_right_event()
        # self.add_jam_vehicle_hiccups_event()

        self._create_act()
        self._create_story()
        self._create_storyboard()
        self._create_scenario()

        if print_scenario:
            self._print_scenario()

        if save_scenario_file:
            self._write_scenario()

        if run_scenario_file:
            self._run_scenario()

        return self._scenario

    def _create_parameters(self):
        self._param_declaration = xosc.ParameterDeclarations()
        self._param_declaration.add_parameter(xosc.Parameter('HostVehicle', xosc.ParameterType.string, 'car_white'))
        self._param_declaration.add_parameter(xosc.Parameter('HostSpeed', xosc.ParameterType.double, 10.0))
        self._param_declaration.add_parameter(xosc.Parameter('PedestrianSpeed', xosc.ParameterType.double, 1.5))
        self._param_declaration.add_parameter(xosc.Parameter('JamVehicle', xosc.ParameterType.string, 'van_red'))

    def _create_catalogs(self):
        self._catalog = xosc.Catalog()
        self._catalog.add_catalog('VehicleCatalog', '../xosc/Catalogs/Vehicles')
        self._catalog.add_catalog('RouteCatalog', '../xosc/Catalogs/Routes')

    def _create_road(self):
        self._road = xosc.RoadNetwork(roadfile="../xodr/fabriksgatan.xodr", scenegraph="../models/fabriksgatan.osgb")

    @add_scenario_object
    def _create_ego_entity(self):
        bounding_box = xosc.BoundingBox(2.0, 5.0, 1.8, 1.4, 0.0, 0.9)
        front_axle = xosc.Axle(0.523598775598, 0.8, 1.68, 2.98, 0.4)
        rear_axle = xosc.Axle(0.523598775598, 0.8, 1.68, 0, 0.4)
        vehicle = xosc.Vehicle(self._ego_name, xosc.VehicleCategory.car, bounding_box, front_axle, rear_axle,
                               max_speed=69,
                               max_acceleration=30,
                               max_deceleration=10,
                               mass=None)
        ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
        PROP_DIR = os.path.join(ROOT_DIR, "esmini/resources/models/car_white.osgb")
        # cf_vehicle.add_property_file(PROP_DIR)
        # cf_vehicle.add_property("model_id", "1")
        # self._entities.add_scenario_object(self._ego_name, xosc.CatalogReference('VehicleCatalog', '$HostVehicle'))
        self._entities.add_scenario_object(self._ego_name, vehicle)
        return vehicle

    @add_scenario_object
    def _create_pedestrian_entity(self):
        pedestrian_bounding_box = xosc.BoundingBox(0.5, 0.6, 1.8, 0.06, 0.0, 0.923)
        pedestrian = xosc.Pedestrian(self._pedestrian_name, 'EPTa', 80, xosc.PedestrianCategory.pedestrian,
                                     pedestrian_bounding_box)

        pedestrian.properties.add_property('control', 'internal')
        pedestrian.properties.add_file('../models/walkman.osgb')
        self._entities.add_scenario_object(self._pedestrian_name, pedestrian)
        return pedestrian

    @add_scenario_object
    def _create_jam_vehicle_entity(self):
        bounding_box = xosc.BoundingBox(1.8, 4.5, 1.5, 1.3, 0.0, 0.8)
        front_axle = xosc.Axle(0.523598775598, 0.8, 1.68, 2.98, 0.4)
        rear_axle = xosc.Axle(0.523598775598, 0.8, 1.68, 0, 0.4)
        vehicle = xosc.Vehicle(self._jam_vehicle_name, xosc.VehicleCategory.car, bounding_box, front_axle, rear_axle,
                               max_speed=70,
                               max_acceleration=10,
                               max_deceleration=30,
                               mass=None)
        ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
        PROP_DIR = os.path.join(ROOT_DIR, "esmini/resources/models/car_white.osgb")
        # cf_vehicle.add_property_file(PROP_DIR)
        # cf_vehicle.add_property("model_id", "1")
        # self._entities.add_scenario_object(self._ego_name, xosc.CatalogReference('VehicleCatalog', '$HostVehicle'))
        self._entities.add_scenario_object(self._jam_vehicle_name, vehicle)
        return vehicle

    @add_init_action
    def _create_init_ego(self):
        step_time = xosc.TransitionDynamics(xosc.DynamicsShapes.step, xosc.DynamicsDimension.time, 1)
        # catalog_reference = xosc.CatalogReference('RoutesAtFabriksgatan', 'HostStraightRoute')

        route = xosc.Route('ego_route')
        wp1 = xosc.LanePosition(63, 0, 1, 0)
        wp2 = xosc.LanePosition(0, 0, 1, 2)
        route.add_waypoint(wp1, xosc.RouteStrategy.shortest)
        route.add_waypoint(wp2, xosc.RouteStrategy.shortest)

        # self._init.add_init_action(self._ego_name, xosc.AssignRouteAction(catalog_reference))
        self._init.add_init_action(self._ego_name, xosc.AssignRouteAction(route))
        #
        # La TeleportAction non funziona se alla entity è associata una traiettoria
        self._init.add_init_action(self._ego_name, xosc.TeleportAction(xosc.LanePosition(0, 0, 1, 0)))
        #
        self._init.add_init_action(self._ego_name, xosc.AbsoluteSpeedAction(10, step_time))
        return self._init.initactions.get(self._ego_name), self._ego_name

    @add_init_action
    def _create_init_pedestrian(self, lane_position_s=150, lane_position_offset=0.5, lane_position_lane_id=3,
                                lane_position_road_id=0, orientation: xosc.Orientation = None):

        pedestrian_orientation = xosc.Orientation(0, 0, 0,
                                                  xosc.ReferenceContext.relative) if not orientation else orientation
        lane_position = xosc.LanePosition(lane_position_s,
                                          lane_position_offset,
                                          lane_position_lane_id,
                                          lane_position_road_id,
                                          pedestrian_orientation)
        #
        # La TeleportAction non funziona se alla entity è associata una traiettoria
        self._init.add_init_action(self._pedestrian_name, xosc.TeleportAction(lane_position))
        #
        return self._init.initactions.get(self._pedestrian_name), self._pedestrian_name

    @add_init_action
    def create_init_jam_vehicle(self, *args, **kwargs):
        lane_position_s = kwargs['lane_position_s'] if 'lane_position_s' in kwargs else 280
        lane_position_offset = kwargs['lane_position_offset'] if 'lane_position_offset' in kwargs else 0
        lane_position_lane_id = kwargs['lane_position_lane_id'] if 'lane_position_lane_id' in kwargs else -1
        lane_position_road_id = kwargs['lane_position_road_id'] if 'lane_position_road_id' in kwargs else 2
        absolute_speed_action = kwargs['absolute_speed_action'] if 'absolute_speed_action' in kwargs else 10

        step_time = xosc.TransitionDynamics(xosc.DynamicsShapes.step, xosc.DynamicsDimension.time, 1)
        route = xosc.Route('jam_route')
        wp1 = xosc.LanePosition(lane_position_s, lane_position_offset, lane_position_lane_id, lane_position_road_id)
        wp2 = xosc.LanePosition(100, 0, -1, 0)
        route.add_waypoint(wp1, xosc.RouteStrategy.shortest)
        route.add_waypoint(wp2, xosc.RouteStrategy.shortest)

        self._init.add_init_action(self._jam_vehicle_name, xosc.AssignRouteAction(route))
        # self._init.add_init_action(self._jam_vehicle_name, xosc.TeleportAction(xosc.LanePosition(lane_position_s,
        #                                                                                lane_position_offset,
        #                                                                                lane_position_lane_id,
        #                                                                                lane_position_road_id)))
        self._init.add_init_action(self._jam_vehicle_name, xosc.AbsoluteSpeedAction(absolute_speed_action, step_time))
        return self._init.initactions.get(self._jam_vehicle_name), self._jam_vehicle_name

    def _add_pedestrian_event(self):
        pedestrian_condition = xosc.EntityTrigger('ped_walk_event',
                                                  0.0,
                                                  xosc.ConditionEdge.rising,
                                                  xosc.TraveledDistanceCondition(5),
                                                  self._ego_name,
                                                  xosc.TriggeringEntitiesRule.any)
        p_trigger_condition = xosc.ConditionGroup()
        p_trigger_condition.add_condition(pedestrian_condition)
        pedestrian_event = xosc.Event('ped_walk_event', xosc.Priority.overwrite, maxexecution=1)
        pedestrian_event.add_trigger(p_trigger_condition)

        pedestrian_transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.rate,
                                                                2)
        pedestrian_action_walk_speed = xosc.AbsoluteSpeedAction(1.5, pedestrian_transition_dynamic)
        pedestrian_event.add_action('walk_speed', pedestrian_action_walk_speed)

        trajectory = xosc.Trajectory('ped_traj', False)
        a_time = [0, 0, 0, 0, 0, 0]
        positions = [
            xosc.LanePosition(15, 0.5, 3, 0, xosc.Orientation(0, 0, 0, xosc.ReferenceContext.relative)),
            xosc.LanePosition(10.5, 0.5, 3, 0, xosc.Orientation(0, 0, 0, xosc.ReferenceContext.relative)),
            xosc.LanePosition(10, 0.0, 3, 0, xosc.Orientation(1.57, 0, 0, xosc.ReferenceContext.relative)),
            xosc.LanePosition(10, 0.0, -3, 0, xosc.Orientation(4.71, 0, 0, xosc.ReferenceContext.relative)),
            xosc.LanePosition(9.5, -0.5, -3, 0, xosc.Orientation(3.14, 0, 0, xosc.ReferenceContext.relative)),
            xosc.LanePosition(0, -0.5, -3, 0, xosc.Orientation(3.14, 0, 0, xosc.ReferenceContext.relative)),
        ]
        shape = xosc.Polyline(time=a_time, positions=positions)
        trajectory.add_shape(shape)
        pedestrian_action_walk_route = xosc.FollowTrajectoryAction(trajectory, xosc.FollowMode.position)
        pedestrian_event.add_action('walk_route', pedestrian_action_walk_route)

        pedestrian_maneuver = xosc.Maneuver('ped_maneuver')
        pedestrian_maneuver.add_event(pedestrian_event)

        self._pedestrian_maneuver_group = xosc.ManeuverGroup('ped_mangroup', 1, selecttriggeringentities=False)
        self._pedestrian_maneuver_group.add_maneuver(pedestrian_maneuver)
        self._pedestrian_maneuver_group.add_actor(self._pedestrian_name)

    def _add_ego_event(self):
        prefix = "brake"
        ego_maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        ego_condition = xosc.EntityTrigger('{0}_Condition'.format(prefix),
                                           0.0,
                                           xosc.ConditionEdge.rising,
                                           xosc.TimeToCollisionCondition(1.7, xosc.Rule.lessThan, True, True,
                                                                         self._pedestrian_name),
                                           self._ego_name,
                                           xosc.TriggeringEntitiesRule.any
                                           )
        e_trigger_condition = xosc.ConditionGroup()
        e_trigger_condition.add_condition(ego_condition)

        ego_event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite, maxexecution=1)
        ego_event.add_trigger(e_trigger_condition)

        ego_transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.rate, -5)
        ego_action_brake = xosc.AbsoluteSpeedAction(0, ego_transition_dynamic)
        ego_event.add_action('{0}_Action'.format(prefix), ego_action_brake)

        ego_maneuver.add_event(ego_event)

        ego_condition = xosc.SimulationTimeCondition(8, xosc.Rule.greaterThan)
        ego_trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix),
                                        0,
                                        xosc.ConditionEdge.rising,
                                        ego_condition)

        ego_event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite, maxexecution=1)
        ego_event.add_trigger(ego_trigger)

        ego_transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.time, 1)
        ego_action_brake = xosc.AbsoluteSpeedAction(10, ego_transition_dynamic)
        ego_event.add_action('{0}_Action'.format(prefix), ego_action_brake)

        ego_maneuver.add_event(ego_event)

        self._ego_maneuver_group = xosc.ManeuverGroup('brake-for-ped_mangroup', maxexecution=1,
                                                      selecttriggeringentities=False)
        self._ego_maneuver_group.add_maneuver(ego_maneuver)
        self._ego_maneuver_group.add_actor(self._ego_name)

    @add_object_event
    def add_jam_vehicle_base_event(self):
        # todo: Da rivedere...
        prefix = "base_event"
        maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        condition = xosc.SimulationTimeCondition(6, xosc.Rule.greaterThan)
        trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

        event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
        event.add_trigger(trigger)

        transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.time, 10)
        action = xosc.AbsoluteSpeedAction(0, transition_dynamic)
        event.add_action('{0}_Action'.format(prefix), action)

        maneuver.add_event(event)

        self._jam_maneuver_group = xosc.ManeuverGroup('{0}_maneuver_group'.format(prefix))
        self._jam_maneuver_group.add_maneuver(maneuver)
        self._jam_maneuver_group.add_actor(self._jam_vehicle_name)

        return event, self._jam_vehicle_name

    @add_object_event
    def add_jam_vehicle_brake_and_accelerate_event(self, *args, **kwargs):
        speed_after_brake = kwargs['speed_after_brake'] if 'speed_after_brake' in kwargs else 0
        speed_to_accelerate = kwargs['speed_to_accelerate'] if 'speed_to_accelerate' in kwargs else 10

        prefix = "brake_and_accelerate"
        maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        condition = xosc.SimulationTimeCondition(2, xosc.Rule.greaterThan)
        trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

        event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
        event.add_trigger(trigger)

        transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.step, xosc.DynamicsDimension.time, 10)
        action = xosc.AbsoluteSpeedAction(speed_after_brake, transition_dynamic)
        event.add_action('{0}_Action'.format(prefix), action)

        maneuver.add_event(event)

        condition = xosc.SimulationTimeCondition(4, xosc.Rule.greaterThan)
        trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

        event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
        event.add_trigger(trigger)

        transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.time, 10)
        action = xosc.AbsoluteSpeedAction(speed_to_accelerate, transition_dynamic)
        event.add_action('{0}_Action'.format(prefix), action)

        maneuver.add_event(event)

        self._jam_maneuver_group = xosc.ManeuverGroup('{0}_maneuver_group'.format(prefix))
        self._jam_maneuver_group.add_maneuver(maneuver)
        self._jam_maneuver_group.add_actor(self._jam_vehicle_name)

        return event, self._jam_vehicle_name

    @add_object_event
    def add_jam_vehicle_slow_down_event(self, *args, **kwargs):
        prefix = "slow_down"
        maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        condition = xosc.SimulationTimeCondition(1, xosc.Rule.greaterThan)
        trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

        event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
        event.add_trigger(trigger)

        transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.time, 10)
        action = xosc.AbsoluteSpeedAction(0, transition_dynamic)
        event.add_action('{0}_Action'.format(prefix), action)

        maneuver.add_event(event)

        self._jam_maneuver_group = xosc.ManeuverGroup('{0}_maneuver_group'.format(prefix))
        self._jam_maneuver_group.add_maneuver(maneuver)
        self._jam_maneuver_group.add_actor(self._jam_vehicle_name)

        return event, self._jam_vehicle_name

    @add_object_event
    def add_jam_vehicle_accelerate_event(self, *args, **kwargs):
        absolute_speed_action_value = kwargs['absolute_speed_action_value'] if 'absolute_speed_action_value' in kwargs else 50
        prefix = "accelerate"
        maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        condition = xosc.SimulationTimeCondition(1, xosc.Rule.greaterThan)
        trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

        event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
        event.add_trigger(trigger)

        transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.time, 10)
        action = xosc.AbsoluteSpeedAction(absolute_speed_action_value, transition_dynamic)
        event.add_action('{0}_Action'.format(prefix), action)

        maneuver.add_event(event)

        self._jam_maneuver_group = xosc.ManeuverGroup('{0}_maneuver_group'.format(prefix))
        self._jam_maneuver_group.add_maneuver(maneuver)
        self._jam_maneuver_group.add_actor(self._jam_vehicle_name)

        return event, self._jam_vehicle_name

    @add_object_event
    def add_jam_vehicle_lane_change_left_event(self, *args, **kwargs):
        absolute_change_lane_value = kwargs['absolute_change_lane_value'] \
            if 'absolute_change_lane_value' in kwargs else 1

        prefix = "lane_change_left"
        maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        condition = xosc.SimulationTimeCondition(1, xosc.Rule.greaterThan)
        trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

        event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
        event.add_trigger(trigger)

        transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.sinusoidal, xosc.DynamicsDimension.time, 10)

        action = xosc.AbsoluteLaneChangeAction(absolute_change_lane_value, transition_dynamic)
        event.add_action('{0}_Action'.format(prefix), action)

        maneuver.add_event(event)

        self._jam_maneuver_group = xosc.ManeuverGroup('{0}_maneuver_group'.format(prefix))
        self._jam_maneuver_group.add_maneuver(maneuver)
        self._jam_maneuver_group.add_actor(self._jam_vehicle_name)

        return event, self._jam_vehicle_name

    @add_object_event
    def add_jam_vehicle_lane_change_right_event(self, *args, **kwargs):
        absolute_change_lane_value = kwargs['absolute_change_lane_value'] \
            if 'absolute_change_lane_value' in kwargs else -2

        prefix = "lane_change_right"
        maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        condition = xosc.SimulationTimeCondition(1, xosc.Rule.greaterThan)
        trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

        event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
        event.add_trigger(trigger)

        transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.sinusoidal, xosc.DynamicsDimension.distance, 10)
        action = xosc.AbsoluteLaneChangeAction(absolute_change_lane_value, transition_dynamic)
        event.add_action('{0}_Action'.format(prefix), action)

        maneuver.add_event(event)

        self._jam_maneuver_group = xosc.ManeuverGroup('{0}_maneuver_group'.format(prefix))
        self._jam_maneuver_group.add_maneuver(maneuver)
        self._jam_maneuver_group.add_actor(self._jam_vehicle_name)

        return event, self._jam_vehicle_name

    @add_object_event
    def add_jam_vehicle_hiccups_event(self):
        event = None
        prefix = "hiccups"
        maneuver = xosc.Maneuver('{0}_Maneuver'.format(prefix))

        for i in range(10):
            condition = xosc.SimulationTimeCondition(i, xosc.Rule.greaterThan)
            trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

            event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
            event.add_trigger(trigger)

            transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.distance, 10)
            action = xosc.AbsoluteSpeedAction(0, transition_dynamic)
            event.add_action('{0}_Action'.format(prefix), action)

            maneuver.add_event(event)

            condition = xosc.SimulationTimeCondition(i+1, xosc.Rule.greaterThan)
            trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

            event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
            event.add_trigger(trigger)

            transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.distance, 10)
            action = xosc.AbsoluteSpeedAction(30, transition_dynamic)
            event.add_action('{0}_Action'.format(prefix), action)

            maneuver.add_event(event)

            condition = xosc.SimulationTimeCondition(i+2, xosc.Rule.greaterThan)
            trigger = xosc.ValueTrigger('{0}_Condition'.format(prefix), 0, xosc.ConditionEdge.rising, condition)

            event = xosc.Event('{0}_Event'.format(prefix), xosc.Priority.overwrite)
            event.add_trigger(trigger)

            transition_dynamic = xosc.TransitionDynamics(xosc.DynamicsShapes.linear, xosc.DynamicsDimension.distance, 10)
            action = xosc.AbsoluteSpeedAction(0, transition_dynamic)
            event.add_action('{0}_Action'.format(prefix), action)

            maneuver.add_event(event)

        self._jam_maneuver_group = xosc.ManeuverGroup('{0}_maneuver_group'.format(prefix))
        self._jam_maneuver_group.add_maneuver(maneuver)
        self._jam_maneuver_group.add_actor(self._jam_vehicle_name)

        return event, self._jam_vehicle_name

    def _create_act(self):
        start_trigger = xosc.ValueTrigger('ActStartCondition', 0.0, xosc.ConditionEdge.none,
                                          xosc.SimulationTimeCondition(0.0, xosc.Rule.greaterThan))

        entity_condition = xosc.ReachPositionCondition(xosc.LanePosition(0, 0, -3, 0), 5.0)
        stop_trigger = xosc.EntityTrigger('QuitCondition', 0.0, xosc.ConditionEdge.rising, entity_condition,
                                          self._pedestrian_name, xosc.TriggeringEntitiesRule.any)

        self._act = xosc.Act('LTAPActNPC', starttrigger=start_trigger)
        self._act.add_maneuver_group(self._ego_maneuver_group)
        self._act.add_maneuver_group(self._pedestrian_maneuver_group)
        self._act.add_maneuver_group(self._jam_maneuver_group)

    def _create_story(self):
        self._story = xosc.Story('LTAPStory')
        self._story.add_act(self._act)
        story_parameter = xosc.Parameter('owner', xosc.ParameterType.string, 'NPC')
        self._story.parameter.add_parameter(story_parameter)

    def _create_storyboard(self):
        self._storyboard = xosc.StoryBoard(self._init,
                                           xosc.ValueTrigger('stop_simulation', 0, xosc.ConditionEdge.rising,
                                                             xosc.SimulationTimeCondition(15, xosc.Rule.greaterThan),
                                                             'stop'))
        self._storyboard.add_story(self._story)

    def _create_scenario(self):
        self._scenario = xosc.Scenario('adapt_speed_example', 'Angelo Carboπe',
                                       self._param_declaration,
                                       entities=self._entities,
                                       storyboard=self._storyboard,
                                       roadnetwork=self._road,
                                       catalog=self._catalog)

    def _print_scenario(self):
        prettyprint(self._scenario.get_element())

    def _write_scenario(self):
        time_str = time.strftime("%Y%m%d-%H%M%S")
        # write the OpenSCENARIO file as xosc using current script name
        file_name = os.path.join(XOSC_DIR, os.path.basename(__file__).replace('.py', '_{0}.xosc'.format(time_str)))
        self._scenario.write_xml(file_name)
        # self._scenario.write_xml("../xosc/" + os.path.basename(__file__).replace('.py', '.xosc'))

    def _run_scenario(self):
        esmini(self._scenario, os.path.join(ESMINI_DIR))

# scenario = Scenario()
# scenario.base_scenario_factory(save_scenario_file=True,
#                                print_scenario=False,
#                                run_scenario_file=True,
#                                injected_init_function=scenario.create_init_jam_vehicle,
#                                injected_event_function=scenario.add_jam_vehicle_brake_and_accelerate_event,
#                                lane_position_s=280,
#                                lane_position_offset=0,
#                                lane_position_lane_id=-1,
#                                lane_position_road_id=2,
#                                absolute_speed_action=10,
#                                speed_after_brake=2,
#                                speed_to_accelerate=30)


n = list(input())
n = [int(i) for i in n]
nlen = len(n)

ans = -1
for i in range(2**nlen):
    x = []
    y = []
    for j in range(nlen):
        if i>>j & 1:
            x.append(n[j])
        else:
            y.append(n[j])
    x.sort(reverse=True)
    y.sort(reverse=True)
    if len(x) > 0 and len(y) >0:
        x = int("".join([str(k) for k in x]))
        y = int("".join([str(k) for k in y]))
        ans = max(ans,x*y)

print(ans)


from setuptools import setup, find_packages
import os

version = '0.1dev'

setup(
    name='uu.staticmap',
    version=version,
    description="Plone add-on; includes view for Google Static Map.",
    long_description=(
        open("README.txt").read() + "\n" +
        open(os.path.join("doc", "HISTORY.txt")).read()
        ),
    # Get more strings from
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        "Programming Language :: Python",
        "Framework :: Plone",
        ],
    keywords='',
    author='Sean Upton',
    author_email='sean.upton@hsc.utah.edu',
    url='http://bazaar.launchpad.net/~seanupton/+junk/uu.staticmap',
    license='GPL',
    packages=find_packages(exclude=['ez_setup']),
    namespace_packages=['uu'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'setuptools',
        'Products.CMFPlone',
        # -*- Extra requirements: -*-
    ],
    extras_require = {
        'test': ['plone.app.testing'],
    },
    entry_points="""
    # -*- Entry points: -*-
    [z3c.autoinclude.plugin]
    target = plone
    """,
    )


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="textfield_parser",
    version="0.0.29",
    author="Thorsten Hapke",
    author_email="thorsten.hapke@sap.com",
    description="Parsing Textfields",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/thhapke/textfield_parser",
    keywords = ['textfield parsing'],
    packages=setuptools.find_packages(),
    install_requires=[],
    classifiers=[
    	'Programming Language :: Python :: 3.5',
    	'Programming Language :: Python :: 3.6',
    	'Programming Language :: Python :: 3.7',
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
)


__author__ = 'heroico'

import logging

def configureLogging(level=5):
    logger = logging.getLogger()
    logger.setLevel(level)

    # create console handler and set level to info
    handler = logging.StreamHandler()
    handler.setLevel(level)
    formatter = logging.Formatter("%(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)


#!/usr/bin/env python3
from flask import Flask
import json

app = Flask(__name__)

@app.route('/<variable>')
def ret_coords(variable):
    with open("json_updated.json") as f:
        json_data = f.read()
    json_data = json.loads(json_data)

    lat, lon = variable.split(",")
    lat = "{0:.4f}".format(float(lat))
    lon = "{0:.4f}".format(float(lon))

    j = lat+lon

    if j in json_data:
        new_json = json.dumps(json_data[j])

    return new_json


import pathos

import dotdot
from neuromodel import Offers, Model, ReplicatedModel, run_model

ΔA, ΔB, n = (0, 20), (0, 20), 4000
offers = Offers(ΔA=ΔA, ΔB=ΔB, n=n, random_seed=0)

def compute_fig6_data(w_p, model_class=Model):
    """

    If the result filename already exists, the computation will be skipped.
    :param model_class:  set to ReplicatedModel if you want to replicate the published figures.
                         set to Model to use the 'corrected' model, as described in the article.
    """
    model = model_class(n=n, ΔA=ΔA, ΔB=ΔB, random_seed=1, w_p=w_p)

    filename='data/fig6_{}[{}]{}.pickle'.format(w_p, n, model.desc)
    return run_model(model, offers, history_keys=('r_2', 'r_I'), filename=filename)

if __name__ == '__main__':
        def aux(args):
            compute_fig6_data(args['w_p'], model_class=args['model_class'])

        runs=[{'model_class': model, 'w_p': w_p} for w_p in [1.55, 1.70, 1.85]
                                                 for model in [Model, ReplicatedModel]]
        pool = pathos.multiprocessing.Pool()
        pool.map(aux, runs)


# -*- coding: UTF-8
#特定の文字列の出現数を調べてみる
#複数のキーワードの出現数の合計を求められるようにする

from pathlib import Path
terms = { 'for':0, 'if':0, 'else':0 }
path = Path()
for filepath in path.glob( '*.py' ):
    rfile = open( filepath,encoding='utf-8' )
    text = rfile.read()
    rfile.close()
    for term in terms:
        cnt = text.count( term )
        terms[term] += cnt
print( terms )


# 15) Заполнить массив из 12 элементов случайными числами в интервале [-12..12]
# и выполнить циклический сдвиг ВПРАВО на 4 элемента.

array = []

for repeat in range(10):
    number = input("Number: ")
    if -12 < int(number) < 12:
        array.append(int(number))

# ['1', '2', '3', '-4', '5', '-7', '9', '0', '8', '-1']

for number in array:
    if int(number) < 0:
        array[int(number)] = int(number)*-1
print(array)


import datetime

from sqlalchemy import (
    ForeignKey,
    Table,
    Column,
    Integer,
    DateTime,
    Enum,
    Text,
    create_engine,
)
from sqlalchemy.orm import relationship, registry

from app.domain.model import User, App, AppAuthorization

mapper_registry = registry()

applications = Table(
    "authorizations",
    mapper_registry.metadata,
    Column("id", Integer, primary_key=True),
    Column("name", Enum(App)),
    Column("user_id", ForeignKey("users.id")),
    Column(
        "updated_at",
        DateTime,
        default=datetime.datetime.now,
        onupdate=datetime.datetime.now,
    ),
    Column("created_at", DateTime, default=datetime.datetime.now),
)

users = Table(
    "users",
    mapper_registry.metadata,
    Column("id", Text, primary_key=True),
    Column("password", Text),
    Column("first_name", Text),
    Column("last_name", Text),
    Column("email", Text, unique=True),
    Column(
        "updated_at",
        DateTime,
        default=datetime.datetime.now,
        onupdate=datetime.datetime.now,
    ),
    Column("created_at", DateTime, default=datetime.datetime.now),
)

def start_mappers():
    operation_mapper = mapper_registry.map_imperatively(AppAuthorization, applications)
    account_mapper = mapper_registry.map_imperatively(
        User,
        users,
        properties={
            "_applications_auth": relationship(operation_mapper, collection_class=set)
        },
    )

def set_up_db(uri: str) -> None:
    engine = create_engine(uri)
    mapper_registry.metadata.create_all(engine)


import sys
import re

if len(sys.argv) < 4:
    print('''Usage: %s <syscall-name> <perf-counter-name> <expected-perf-events-between-syscalls>
Exits with status 0 if exactly the expected number of perf events occur between
every pair of consecutive system calls of the given type.''' % sys.argv[0])
    sys.exit(2)

syscall = sys.argv[1]
counter = sys.argv[2]
expected_count = int(sys.argv[3])

last_perfctr_value = -1
syscall_re = re.compile("`SYSCALL: (\\w+)' \\(state:0\\)")
perfctr_re = re.compile(counter + ":(\\d+)")

while True:
    line = sys.stdin.readline()
    if not line:
        sys.exit(0)
    m = syscall_re.search(line)
    if m:
        if m.group(1) == syscall:
            line = sys.stdin.readline()
            m = perfctr_re.search(line)
            if m:
                v = int(m.group(1))
                if last_perfctr_value >= 0 and v - last_perfctr_value != expected_count:
                    print("Mismatch: saw %d %ss between %ss (from %d to %d), expected %d" % \
                      (v - last_perfctr_value, counter, syscall, last_perfctr_value, v, expected_count))
                    sys.exit(1)
                last_perfctr_value = v
        else:
            # Ignore nonconsecutive syscalls. In the cpuid test, we have
            # two batches of geteuid32s; one injected by rr itself to detect
            # a buggy system, and a separate one for the test. We need to
            # ignore the geteuid32 pair that spans the gap between the batches.
            last_perfctr_value = -1


"""
This module imports data from files to db.
"""

import os, glob
import traceback
from sqlalchemy import delete
from muddery.common.utils.exception import MudderyError, ERR
from muddery.common.utils import readers
from muddery.server.database.worlddata_db import WorldDataDB
from muddery.server.utils.logger import logger

def import_file(fullname, file_type=None, table_name=None, clear=True, except_errors=False, **kwargs):
    """
    Import data from a data file to the db model

    Args:
        fullname: (string) file's full name
        file_type: (string) set file's type. If it's None, get the file's type from filename.
        table_name: (string) the type of the file. If it's None, the function will get
                   the file type from the extension name of the file.
        clear: (boolean) clear old data.
        except_errors: (boolean) except error records and load other records.
    """
    def get_field_types(model_obj, field_names):
        """
        Get field types by field names.

        type = 0    means common field
        type = 1    means Boolean field
        type = 2    means Integer field
        type = 3    means Float field
        type = 4    means ForeignKey field, not support
        type = 5    means ManyToManyField field, not support
        type = -1   means field does not exist
        """
        field_types = []
        for field_name in field_names:
            field_type = -1

            try:
                # get field info
                field = model_obj.__table__.columns[field_name]

                if field.type.python_type == bool:
                    field_type = 1
                elif field.type.python_type == int:
                    field_type = 2
                elif field.type.python_type == float:
                    field_type = 3
                else:
                    field_type = 0
            except Exception as e:
                field_type = -1
                logger.log_err("Field %s error: %s" % (field_name, e))

            field_types.append(field_type)

        return field_types

    def parse_record(field_names, field_types, values):
        """
        Parse text values to field values.
        """
        record = {}
        for item in zip(field_names, field_types, values):
            field_name = item[0]
            # skip "id" field
            if field_name == "id":
                continue

            field_type = item[1]
            value = item[2]

            try:
                # set field values
                if field_type == -1:
                    # not support this field
                    continue
                elif field_type == 0:
                    # default
                    record[field_name] = value
                elif field_type == 1:
                    # boolean value
                    if value:
                        upper = value.upper()
                        if upper == 'TRUE' or upper == 'T':
                            record[field_name] = True
                        elif upper == 'FALSE' or upper == 'F':
                            record[field_name] = False
                        else:
                            record[field_name] = (int(value) != 0)
                elif field_type == 2:
                    # interger value
                    if value:
                        record[field_name] = int(value)
                elif field_type == 3:
                    # float value
                    if value:
                        record[field_name] = float(value)
            except Exception as e:
                raise Exception("%s '%s' error: %s" % (field_name, value, e))

        return record

    def import_data(session, model, data_iterator):
        """
        Import data to a table.

        Args:
            model_obj: (model) model object.
            data_iterator: (list) data list.

        Returns:
            None
        """
        try:
            # read title
            titles = next(data_iterator)
            field_types = get_field_types(model, titles)

            # import values
            with session.begin():
                for index, values in enumerate(data_iterator):
                    # skip blank lines
                    if not "".join(values):
                        continue

                    try:
                        data = parse_record(titles, field_types, values)
                        record = model(**data)
                        session.add(record)
                        session.flush()
                    except Exception as e:
                        msg = "Import %s line %s error: %s" % (model.__tablename__, index + 2, e)
                        if except_errors:
                            print(msg)
                            logger.log_warn(msg)
                        else:
                            logger.log_err(msg)
                            raise MudderyError(ERR.import_data_error, msg)
        except StopIteration:
            # reach the end of file, pass this exception
            pass

    # separate name and ext name
    try:
        filename, ext_name = os.path.splitext(fullname)
        if not table_name:
            table_name = filename
        if not file_type:
            if ext_name:
                file_type = ext_name[1:].lower()
    except:
        pass

    # get model
    session = WorldDataDB.inst().get_session()
    model = WorldDataDB.inst().get_model(table_name)

    if clear:
        stmt = delete(model)
        session.execute(stmt)

    reader_class = readers.get_reader(file_type)
    if not reader_class:
        # Does support this file type.
        raise(MudderyError(ERR.import_data_error, "Unknown file type."))

    reader = reader_class(fullname)
    if not reader:
        # Does support this file type.
        raise(MudderyError(ERR.import_data_error, "Does not support this file type."))

    logger.log_debug("Importing %s" % table_name)
    try:
        import_data(session, model, reader)
    finally:
        reader.close()

def import_data_path(path, clear=True, except_errors=False):
    """
    Import data from path.

    Args:
        path: (string) data path.
        clear: (boolean) clear old data.
        except_errors: (boolean) except error records and load other records.
    """
    # import tables one by one
    tables = WorldDataDB.inst().get_tables()
    for table_name in tables:
        file_names = glob.glob(os.path.join(path, table_name) + ".*")

        if file_names:
            print("Importing %s" % file_names[0])
            import_file(file_names[0], table_name=table_name, clear=clear, except_errors=except_errors)

def import_table_path(path, table_name, clear=True, except_errors=False):
    """
    Import a table's data from a path.

    Args:
        path: (string) data path.
        table_name: (string) table's name.
        clear: (boolean) clear old data.
    """
    if clear:
        WorldDataDB.inst().clear_table(table_name)

    if not os.path.isdir(path):
        return

    for file_name in os.listdir(path):
        file_name = os.path.join(path, file_name)
        if os.path.isdir(file_name):
            # if it is a folder
            continue

        print("Importing %s" % file_name)
        try:
            import_file(file_name, table_name=table_name, clear=False, except_errors=except_errors)
        except Exception as e:
            print("Import error: %s" % e)


import math
import re

title_offset=0
category_offset=0
externallink_offset=0

def write_correct_index(current_word, current_index, total_docs, offset, dict_file, text_file, title_dict_file, title_file,category_dict_file, category_file):#, external_file, reference_file):
    index=""
    title_index=""
    category_index=""

    global title_offset
    global category_offset
    if(len(current_index)>0):
        idf = math.log10(total_docs/len(current_index))
        for doc in current_index:
            if doc!="":
                cnts = re.split(r'[.]',doc)
                if cnts[1]!="":
                    tf = 1 + math.log10(int(cnts[1]))
                    wt = tf*idf;
                    index = index + "," + cnts[0] + ":" + str('%.2f' %wt)
                if cnts[2]!="":
                    ttf = 1 + math.log10(int(cnts[2]))
                    wtt = ttf*idf;
                    title_index = title_index + "," + cnts[0] + ":" + str('%.2f' %wtt)
                if cnts[3]!="":
                    ctf = 1 + math.log10(int(cnts[3]))
                    wtc = ctf*idf;
                    category_index = category_index + "," + cnts[0] + ":" + str('%.2f' %wtc)

    if index!="":
        index = current_word+index+"\n"
        dict_file.write(current_word+":"+str(offset)+"\n")
        text_file.write(index)
        offset+=len(index)
    if title_index!="":
        title_index = current_word+title_index+"\n"
        title_file.write(title_index)
        title_dict_file.write(current_word+":"+str(title_offset)+"\n")
        title_offset+=len(title_index)
    if category_index!="":
        category_index = current_word+category_index+"\n"
        category_file.write(category_index)
        category_dict_file.write(current_word+":"+str(category_offset)+"\n")
        category_offset+=len(category_index)

    return offset

def merge_chunks(n, total_docs):
    text_file = open('./index/body.txt','w')
    dict_file = open('./index/dict_body.txt', 'w')
    title_file = open('./index/title.txt', 'w')
    title_dict_file = open('./index/dict_title.txt', 'w')
    category_file = open('./index/category.txt', 'w')
    category_dict_file = open('./index/dict_category.txt', 'w')

    offset = 0
    to_bring = [1 for j in range(n)]
    notend = [1 for j in range(n)]
    lines = []
    files = [open("./chunks/chunk"+str(i)+".txt", 'r') for i in range(n)]

    while (1):
        i=0
        for fl in files:
            if to_bring[i]==1 and notend[i]==1:
                line = fl.readline()
                if not line:
                    notend[i]=0
                    continue
                wrds = re.split(r'[,\n]+',line);
                lines.append([i]+wrds)
                to_bring[i]=0
            i+=1;

        t=0
        for k in notend:
            t=t+k
        if t==0 and not lines:
            break;

        lines.sort(key = lambda x:x[1])

        current_word = lines[0][1]
        current_index = lines[0][2:]
        to_bring[lines[0][0]] = 1

        for line in lines[1:]:
            if line[1]==current_word:
                current_index = current_index + line[2:]
                to_bring[line[0]] = 1

        lines = [x for x in lines if x[1]!=current_word]

        offset = write_correct_index(current_word, current_index, total_docs, offset, dict_file, text_file, title_dict_file, title_file, category_dict_file, category_file)#, external_file, reference_file)


from django.http.response import HttpResponse
from django.shortcuts import render
from datetime import datetime
from django.utils.crypto import get_random_string
from urllib.parse import urlparse
from django.utils import timezone, dateparse
from .logger import log_pageview
from .models import LogEntry

COOKIE_NAME = 'visitor_id'
COOKIE_AGE = 3600 * 24 * 365

def create_visitor_id():
    return get_random_string(length=5, allowed_chars=u'abcdefghijklmnopqrstuvwxyz0123456789')

def get_page_from_url(url):
    parsed_url = urlparse(url)
    page = parsed_url.path

    if parsed_url.query:
        page += '?' + parsed_url.query

    return page

def contact(request):
    return render(request, "contact.html")

def track_get_image(request):
    image_data = open("images/transparent.gif", "rb").read()
    response = HttpResponse(image_data, content_type="image/gif")

    referer = request.META.get('HTTP_REFERER')

    if not referer:
        return response

    visitor_id = request.COOKIES.get(COOKIE_NAME)

    if not visitor_id:
        visitor_id = create_visitor_id()
        response.set_cookie(COOKIE_NAME, value=visitor_id, max_age=COOKIE_AGE)

    page = get_page_from_url(referer)

    log_pageview(page, visitor_id)

    return response

def report(request):
    from_datetime_string = request.GET.get("from_datetime")
    to_datetime_string = request.GET.get("to_datetime")

    log_entries = LogEntry.objects.all()
    if from_datetime_string:
        from_datetime = dateparse.parse_datetime(from_datetime_string)
        from_datetime = timezone.make_aware(from_datetime)
        log_entries = log_entries.filter(created_at__gte=from_datetime)

    if to_datetime_string:
        to_datetime = dateparse.parse_datetime(to_datetime_string)
        to_datetime = timezone.make_aware(to_datetime)
        log_entries = log_entries.filter(created_at__lte=to_datetime)

    context = {"log_entries": log_entries,
               "from_datetime": from_datetime_string, "to_datetime": to_datetime_string}
    return render(request, "report.html", context)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from urllib.parse import urlparse, urlunparse, ParseResult as URL

from casket import logger

from plantpot import Plantpot, bad_request, Redirect
from clients.kvstore import (
    insert as kv_insert,
    retrieve as kv_retrieve,
)
from clients.monstermac import sha256_monstermac
from schemas.oauth import NewLoginReq
from lib.tokens import build_login_token

URL_TIMEOUT = int(os.environ.get("PLANTPOT_OAUTH_URL_TIMEOUT", "120"))
LOGIN_TOKEN_SALT_PATH = os.environ.get('PLANTPOT_LOGIN_TOKEN_SALT_PATH',
                                       '/run/secrets/logintokensalt')
LOGIN_TOKEN_SALT = open(LOGIN_TOKEN_SALT_PATH, 'rb').read()

app = Plantpot('oauth')

@app.json(
    path="/login",
    methods=['POST'],
    pass_context=True,
    require_session_id=True,
    req_schema=NewLoginReq,
    resp_status="202 Created",
)
def new_login(ctx, body, session_id):
    url = urlparse(body['currentUrl'])
    kv_insert(ctx, 'oauth', {session_id: url}, URL_TIMEOUT)

@app.endpoint(
    path='/login',
    methods=['GET'],
    pass_context=True,
    require_session_id=True,
)
def login(ctx, session_id):
    url = kv_retrieve(ctx, 'oauth', session_id)[session_id].value
    if url is None:
        raise bad_request(
            "Missing Session Id",
            "no attempted oauth login for this session id found")

    login_id = sha256_monstermac(os.urandom(16))[:16]
    login_tk = build_login_token(LOGIN_TOKEN_SALT, login_id)

    if url.query:
        query = url.query + '&login_tk=' + login_tk
    else:
        query = 'login_tk=' + login_tk

    url = urlunparse(
        URL(
            url.scheme,
            url.netloc,
            url.path,
            url.params,
            query,
            url.fragment,
        ))

    return Redirect(url)


import pygame, json, math, socket

# Axes
ROLL_AXIS         = 0 # Xbox: left stick H
PITCH_AXIS        = 1 # Xbox: left stick V
HOVER_AXIS        = 2 # Xbox: left trigger
YAW_AXIS          = 3 # Xbox: right stick H
GAS_AXIS          = 4 # Xbox: right stick V

# Buttons
RESET_BUTTON      = 7 # Xbox: 'Start'
QUIT_BUTTON       = 6 # Xbox: 'Back'
TAKE_OFF_BUTTON   = 8 # Xbox: 'Xbox logo'

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

seq = 0
def send_state(state):
  global seq, sock
  seq += 1
  HOST, PORT = ('127.0.0.1', 5560)
  print('state is', json.dumps({'seq': seq, 'state': state}))
  sock.sendto(json.dumps({'seq': seq, 'state': state}), (HOST, PORT))

def main():
  pygame.init()

  n_joysticks = pygame.joystick.get_count()
  print('Joysticks: %i' % (n_joysticks,))

  if n_joysticks < 1:
    print('No joysticks found :(')
    return

  joystick = pygame.joystick.Joystick(0)
  joystick.init()

  print('Found: %s' % (joystick.get_name(),))

  print('Assuming an xbox controller. See top of file for details of change.')
  print('Use Back button to quit')

  state = {
      'roll': 0.0,
      'pitch': 0.0,
      'yaw': 0.0,
      'gas': 0.0,
      'take_off': False,
      'reset': False,
      'hover': True,
      };

  # Create a state timer
  STATE_TICK_EVENT = pygame.USEREVENT
  pygame.time.set_timer(STATE_TICK_EVENT, 50)

  while True:
    e = pygame.event.wait()
    if e.type == pygame.JOYBUTTONDOWN:
      if e.button == TAKE_OFF_BUTTON:
        state['take_off'] = True
      elif e.button == RESET_BUTTON:
        state['reset'] = True
      elif e.button == QUIT_BUTTON:
        print('Quitting')
        return
    elif e.type == pygame.JOYBUTTONUP:
      if e.button == TAKE_OFF_BUTTON:
        state['take_off'] = False
      elif e.button == RESET_BUTTON:
        state['reset'] = False
    elif e.type == pygame.JOYAXISMOTION:
      surface = None
      sign = 1.0

      if e.axis == ROLL_AXIS:
        surface = 'roll'
      elif e.axis == PITCH_AXIS:
        surface = 'pitch'
      elif e.axis == YAW_AXIS:
        surface = 'yaw'
      elif e.axis == GAS_AXIS:
        surface = 'gas'
        sign = -1.0
      elif e.axis == HOVER_AXIS:
        state['hover'] = e.value < -0.5

      if surface is not None:
        state[surface] = sign * e.value

    max_shift = 0.0
    for x in ('roll', 'pitch', 'yaw', 'gas'):
      max_shift = max(max_shift, abs(state[x]))

    state['hover'] = max_shift < 1e-1
    #if state['hover']:
    #  state['gas'] = 0.0

    send_state(state)

if __name__ == '__main__':
  main()


import math
from typing import Tuple

import numpy as np
import torch

def frustum2planes(frustum):
    planes = {}
    # normal towards inside
    # near
    a = frustum[3] - frustum[0]
    b = frustum[1] - frustum[0]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[0])
    planes["near"] = np.array([normal[0], normal[1], normal[2], d])

    # far
    a = frustum[5] - frustum[4]
    b = frustum[7] - frustum[4]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[4])
    planes["far"] = np.array([normal[0], normal[1], normal[2], d])

    # left
    a = frustum[5] - frustum[1]
    b = frustum[0] - frustum[1]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[1])
    planes["left"] = np.array([normal[0], normal[1], normal[2], d])

    # right
    a = frustum[3] - frustum[2]
    b = frustum[6] - frustum[2]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[2])
    planes["right"] = np.array([normal[0], normal[1], normal[2], d])

    # top
    a = frustum[4] - frustum[0]
    b = frustum[3] - frustum[0]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[0])
    planes["top"] = np.array([normal[0], normal[1], normal[2], d])

    # bottom
    a = frustum[2] - frustum[1]
    b = frustum[5] - frustum[1]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[1])
    planes["bottom"] = np.array([normal[0], normal[1], normal[2], d])

    return planes

def frustum_culling(points, frustum):
    frustum_planes = frustum2planes(frustum)
    points = np.concatenate([points, np.ones((len(points), 1))], 1)
    flags = np.ones(len(points))
    for key, plane in frustum_planes.items():
        flag = np.dot(points, plane) >= 0
        flags = np.logical_and(flags, flag)

    return points[flags][:, :3]

def frustum_transform(frustum, transform):
    eight_points = np.concatenate([frustum, np.ones((8, 1))], 1).transpose()
    frustum = np.dot(transform, eight_points).transpose()
    return frustum[:, :3]

def generate_frustum(image_size, intrinsic_inv, depth_min, depth_max, transform=None):
    x = image_size[0]
    y = image_size[1]

    eight_points = np.array([[0 * depth_min, 0 * depth_min, depth_min, 1.0],
                             [0 * depth_min, y * depth_min, depth_min, 1.0],
                             [x * depth_min, y * depth_min, depth_min, 1.0],
                             [x * depth_min, 0 * depth_min, depth_min, 1.0],
                             [0 * depth_max, 0 * depth_max, depth_max, 1.0],
                             [0 * depth_max, y * depth_max, depth_max, 1.0],
                             [x * depth_max, y * depth_max, depth_max, 1.0],
                             [x * depth_max, 0 * depth_max, depth_max, 1.0]]).transpose()

    frustum = np.dot(intrinsic_inv, eight_points)

    if transform is not None:
        frustum = np.dot(transform, frustum)

    frustum = frustum.transpose()

    return frustum[:, :3]

def generate_frustum_volume(frustum, voxel_size):
    max_x = np.max(frustum[:, 0]) / voxel_size
    max_y = np.max(frustum[:, 1]) / voxel_size
    max_z = np.max(frustum[:, 2]) / voxel_size
    min_x = np.min(frustum[:, 0]) / voxel_size
    min_y = np.min(frustum[:, 1]) / voxel_size
    min_z = np.min(frustum[:, 2]) / voxel_size

    dim_x = math.ceil(max_x - min_x)
    dim_y = math.ceil(max_y - min_y)
    dim_z = math.ceil(max_z - min_z)

    camera2frustum = np.array([[1.0 / voxel_size, 0, 0, -min_x],
                               [0, 1.0 / voxel_size, 0, -min_y],
                               [0, 0, 1.0 / voxel_size, -min_z],
                               [0, 0, 0, 1.0]])

    return (dim_x, dim_y, dim_z), camera2frustum

def compute_camera2frustum_transform(intrinsic: torch.Tensor, image_size: Tuple, depth_min: float, depth_max: float,
                                     voxel_size: float) -> torch.Tensor:
    frustum = generate_frustum(image_size, torch.inverse(intrinsic), depth_min, depth_max)
    _, camera2frustum = generate_frustum_volume(frustum, voxel_size)
    camera2frustum = torch.from_numpy(camera2frustum).float()

    return camera2frustum


import random
from functools import partial

import pytorch_lightning as pl
import torch
from einops import rearrange, repeat
from torch import Tensor
from torch import nn
from torch.optim.lr_scheduler import LambdaLR
from torch.nn import Conv2d
from torch.nn import TransformerEncoder
from torch.nn import TransformerEncoderLayer

from loss import p_loss
from helper import PositionalEncoding3D

class Model(pl.LightningModule):
    def __init__(
        self,
        learning_rate,
        transformer_layers,
        use_transformer,
        num_timesteps,
        p_loss,
        p_weight,
        p_reduction,
        p_anneal,
        activation,
        l1f_weight,
        l1o_weight,
        map_size,
        anneal_lr,
        weight_decay,
        full_decode,
        K_down,
        xy_resolution,
    ):
        super().__init__()
        self.learning_rate = learning_rate
        # This saves the input args into self.hparams
        self.save_hyperparameters()

        self.visualcortex = VisualCortex(128)
        self.split_forward = Split(128, 320)
        self.hc = Hippocampus(320)
        self.split_backward = Split(320, self.hparams.map_size)
        self.decoder = Decoder()

    def forward(self, input_videos: Tensor, full_res_decode: bool = False):
        """The model has 5 stages:
        --- Encoding: ---
        - a convolutional layers that extracts features from the input video
        - a perirhinal / parahippocampal split into space / time features + a MEC / LEC processing stage
        - a HC layer which integrates the MEC and LEC features
        --- Decoding: ---
        - a MEC / LEC split into space / time features + a perirhinal / parahippocampal processing stage
        - a reconstruction layer that reconstructs the input video
        """
        b, t, c, h, w = input_videos.shape
        # Encode input using visual cortex areas V1, V2, V4 and IT
        v1, v2, v4, it = self.visualcortex(input_videos)
        # Split V4 & IT into MEC and LEC
        (_, _), (mec, lec) = self.split_forward(v4, it)  # (ph, pr), (mec, lec)
        # Combine MEC and LEC into HC
        hc_transformed, hc = self.hc(mec, lec)
        # For feedback, split HC into MEC and LEC
        (_, _), (ph, pr) = self.split_backward(hc_transformed)  # (mec, lec), (ph, pr)
        # Decode pixelwise - most biologically unrealistic part of the model. Could be more realistic if it decodes patch/saccade wise
        pixels, weights, weights_softmax, weighted_pixels, time_indexes = self.decoder(
            ph, pr, full_res_decode
        )

        return {
            "pixels": pixels,
            "weights_softmax": weights_softmax,
            "weighted_pixels": weighted_pixels,
            "latents": (mec, lec, hc, hc_transformed, ph, pr),
            "time_indexes": time_indexes,
        }

    def loss(
        self,
        target: Tensor,
        pixels: Tensor,
        weights_softmax: Tensor,
        weighted_pixels: Tensor,
        time_indexes: Tensor,
        full_res_decode: bool,
        latents,
        **_,
    ):
        target = rearrange(target, "b t c h w -> b t h w c")
        if not full_res_decode:
            # downsample targets to match model output
            target = target[:, :, ::2, ::2, :]
            target = target.index_select(dim=1, index=time_indexes)

        # Compute the individual loss terms
        if self.hparams.p_anneal > 0:
            p = min(
                self.hparams.p_loss,
                (float(self.trainer.global_step + 1) / self.hparams.p_anneal) + 0.5,
            )
        elif self.hparams.p_anneal < 0:
            p = max(
                0.5,
                self.hparams.p_loss
                - (float(self.trainer.global_step + 1) / abs(self.hparams.p_anneal)),
            )
        else:
            p = self.hparams.p_loss

        # Combine p_loss and p_loss_prospective and p_loss_retrospective
        p_term = p_loss(
            target, weighted_pixels, p=p, reduction=self.hparams.p_reduction
        )

        # L2 loss on last two latents, PH & PR
        l1o_term = latents[-1].abs().mean()
        l1f_term = latents[-2].abs().mean()

        # Apply loss weights to get weighted loss terms
        losses = {
            "l2o_loss": l1o_term * self.hparams.l1o_weight,
            "l2f_loss": l1f_term * self.hparams.l1f_weight,
            "p_loss": self.hparams.p_weight * p_term.mean(),
        }
        # Sum the weighted loss terms to get the total loss
        losses["loss"] = sum(losses.values())
        return losses

    def step(self, batch, full_res_decode: bool = False):
        videos, mask, info = batch
        outputs = self(videos, full_res_decode)
        losses = self.loss(videos, full_res_decode=full_res_decode, **outputs)
        return {**losses, **outputs}

    def training_step(self, batch: Tensor, batch_idx: int):
        outputs = self.step(batch, full_res_decode=self.hparams.full_decode)
        return outputs

    def validation_step(self, batch: Tensor, batch_idx: int):
        outputs = self.step(batch, full_res_decode=True)
        self.log("val/loss", outputs["loss"], prog_bar=True, sync_dist=True)
        return outputs

    def configure_optimizers(self):
        # return torch.optim.Adam(self.parameters(), lr=self.learning_rate)
        optimizer = torch.optim.Adam(
            self.parameters(),
            lr=self.learning_rate,
            weight_decay=self.hparams.weight_decay,
        )

        def lr_foo(epoch):
            if self.hparams.anneal_lr:
                lr_scale = 0.95**epoch
            else:
                lr_scale = 1.0

            return lr_scale

        scheduler = LambdaLR(optimizer, lr_lambda=lr_foo)

        return [optimizer], [scheduler]

class Decoder(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.save_hyperparameters()
        self.mlp = MLP(
            in_features=self.hparams.map_size * 2 + 3,
            out_features=4,
            hidden_features=[512 for _ in range(5)],
            activation=self.hparams.activation,
        )

    def forward(
        self,
        object_latents: Tensor,
        temporal_latents: Tensor,
        full_size_decode: bool = False,
    ):
        T = temporal_latents.shape[1]  # self.hparams.num_timesteps
        Kd = self.hparams.K_down
        batch_size = object_latents.shape[0]
        if full_size_decode:
            OUTPUT_RES = self.hparams.xy_resolution
            Td = T
        else:
            OUTPUT_RES = self.hparams.xy_resolution // 2
            Td = T // 2
        assert object_latents.shape == (batch_size, 16, self.hparams.map_size)
        assert temporal_latents.shape == (batch_size, T, self.hparams.map_size)
        time_indexes = torch.tensor(
            sorted(random.sample(range(T), Td)), device=self.device
        )

        temporal_latents = temporal_latents.index_select(dim=1, index=time_indexes)
        object_indexes = torch.tensor(
            range(Kd), device=self.device
        )
        object_latents = object_latents.index_select(dim=1, index=object_indexes)

        object_latents = repeat(
            object_latents, "b k c -> b t k h w c", t=Td, h=OUTPUT_RES, w=OUTPUT_RES
        )
        temporal_latents = repeat(
            temporal_latents, "b t c -> b t k h w c", k=Kd, h=OUTPUT_RES, w=OUTPUT_RES
        )

        desired_shape = [batch_size, Td, Kd, OUTPUT_RES, OUTPUT_RES, 1]
        x_encoding, y_encoding, t_encoding = _build_xyt_indicators(
            desired_shape,
            time_indexes,
            self.device,
            object_latents.dtype,
            full_size_decode,
            T, self.hparams.xy_resolution,
        )

        x = torch.cat(
            [object_latents, temporal_latents, t_encoding, x_encoding, y_encoding],
            dim=5,
        )  # What, When, When, Where, Where

        x = rearrange(
            x, "b td k h w c -> (b td k h w) c", c=2 * self.hparams.map_size + 3
        )
        x = self.mlp(x)
        x = rearrange(
            x,
            "(b td k h w) c -> b td k h w c",
            td=Td,
            k=Kd,
            h=OUTPUT_RES,
            w=OUTPUT_RES,
            c=4,
        )
        pixels = x[..., 0:3]
        weights = x[..., 3]

        weights_sum = (-1 * weights[:, :, 1:, ...]).sum(dim=2)
        weights = torch.cat((weights_sum.unsqueeze(2), weights[:, :, 1:, ...]), dim=2)

        weights = torch.nn.functional.layer_norm(
            weights, [Td, Kd, OUTPUT_RES, OUTPUT_RES]
        )
        weights_softmax = torch.nn.functional.softmax(weights, dim=2)
        weighted_pixels = (pixels * weights_softmax.unsqueeze(-1)).sum(dim=2)

        assert weighted_pixels.shape == (batch_size, Td, OUTPUT_RES, OUTPUT_RES, 3)

        return pixels, weights, weights_softmax, weighted_pixels, time_indexes

def _create_position_encoding(range: Tensor, target_shape, dim):
    """Create a tensor of shape `target_shape` that is filled with values from `range` along `dim`."""
    assert len(range.shape) == 1
    assert len(range) == target_shape[dim]

    view_shape = [1 for _ in target_shape]
    view_shape[dim] = target_shape[dim]
    range = range.view(view_shape)
    encoding = range.expand(target_shape)
    assert encoding.shape == tuple(target_shape)
    return encoding

def _build_xyt_indicators(
    desired_shape,
    time_indexes,
    device,
    dtype,
    full_size_decode: bool,
    T, xy_resolution,
):
    # Form the T, X, Y indicators
    t_linspace = torch.linspace(0, 1, T, device=device, dtype=dtype)
    t_linspace = t_linspace.index_select(dim=0, index=time_indexes)
    t_encoding = _create_position_encoding(t_linspace, desired_shape, dim=1)

    xy_linspace = torch.linspace(-1, 1, xy_resolution, device=device, dtype=dtype)
    if not full_size_decode:
        # we decode every other pixel
        xy_linspace = xy_linspace[::2]
    x_encoding = _create_position_encoding(xy_linspace, desired_shape, dim=3)
    y_encoding = _create_position_encoding(xy_linspace, desired_shape, dim=4)
    return x_encoding, y_encoding, t_encoding

class VisualCortex(pl.LightningModule):
    """The encoder is a simple stack of convolutional layers."""

    def __init__(self, out_channels):
        super().__init__()
        self.save_hyperparameters()
        # Activation function
        if self.hparams.activation == "relu":
            self.activation = nn.ReLU()
        elif self.hparams.activation == "linear":
            self.activation = nn.Identity()
        elif self.hparams.activation == "leaky":
            self.activation = nn.LeakyReLU()
        else:
            raise ValueError("Activation function not supported")

        conv_layer = partial(Conv2d, kernel_size=4, stride=2, padding=(1, 1))
        self.v1 = conv_layer(in_channels=3, out_channels=out_channels)
        self.v2 = conv_layer(in_channels=out_channels, out_channels=out_channels)
        self.v4 = conv_layer(in_channels=out_channels, out_channels=out_channels)
        self.it = conv_layer(in_channels=out_channels, out_channels=out_channels)

    def forward(self, x: Tensor):
        b, t, c, h, w = x.shape
        x = rearrange(
            x, "b t c h w -> (b t) c h w", t=t, c=3, h=self.hparams.xy_resolution, w=self.hparams.xy_resolution
        )

        v1 = self.activation(self.v1(x))
        v2 = self.activation(self.v2(v1))
        v4 = self.activation(self.v4(v2))
        it = self.activation(self.it(v2))

        v4 = rearrange(v4, "(b t) c h w -> b t (h w) c", b=b, t=t)
        it = rearrange(it, "(b t) c h w -> b t (h w) c", b=b, t=t)

        return v1, v2, v4, it

class Split(pl.LightningModule):
    """Splits into ventral and dorsal streams"""

    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.save_hyperparameters()
        num_rsc = in_channels // 4
        self.rsc = nn.Parameter(torch.randn(num_rsc))

        self.linear_space = MLP(
            in_features=in_channels + num_rsc,
            out_features=out_channels,
            hidden_features=[1024],
            activation=self.hparams.activation,
        )
        self.linear_time = MLP(
            in_features=in_channels,
            out_features=out_channels,
            hidden_features=[1024],
            activation=self.hparams.activation,
        )

    def forward(self, x: Tensor, x_two=None):
        b, t, k, c = x.shape

        # Aggregate the temporal info to get the spatial features
        time_avg = torch.mean(x, dim=1)
        time_avg = rearrange(time_avg, "b k c -> (b k) c", b=b, k=k)
        # Concat with rsc parameters
        time_avg = torch.cat([time_avg, self.rsc.repeat(b * k, 1)], dim=1)

        # Aggregate the spatial info to get the temporal features
        if x_two is None:
            space_avg = torch.mean(x, dim=2)
        else:
            space_avg = torch.mean(x_two, dim=2)
        space_avg = rearrange(space_avg, "b t c -> (b t) c", b=b, t=t)

        # Apply the MLPs
        across_space = self.linear_space(time_avg)
        across_space = rearrange(across_space, "(b k) c -> b k c", b=b, k=k)
        across_time = self.linear_time(space_avg)
        across_time = rearrange(across_time, "(b t) c -> b t c", b=b, t=t)

        return (time_avg, space_avg), (across_space, across_time)

class Hippocampus(pl.LightningModule):
    """Integrates MEC and LEC information"""

    def __init__(self, in_channels):
        super().__init__()
        self.save_hyperparameters()
        # Activation function
        if self.hparams.activation == "relu":
            self.activation = nn.ReLU()
        elif self.hparams.activation == "linear":
            self.activation = nn.Identity()
        elif self.hparams.activation == "leaky":
            self.activation = nn.LeakyReLU()
        else:
            raise ValueError("Activation function not supported")

        self.in_channels = in_channels
        self.out_channels = 320
        self.xy_after_conv = 8
        self.xy_after_transformer = self.xy_after_conv // 2

        if self.hparams.use_transformer:
            # this template layer will get cloned inside the TransformerEncoder modules below.
            encoder_layer_template = TransformerEncoderLayer(
                d_model=self.out_channels,
                nhead=5,
                dim_feedforward=1024,
                dropout=0.0,
                batch_first=True,
                norm_first=True,
                activation=self.activation,
            )
            self.linear_layer = torch.nn.Linear(
                in_features=self.in_channels, out_features=self.out_channels, bias=False
            )

            self.transformer_1 = TransformerEncoder(
                encoder_layer=encoder_layer_template,
                num_layers=self.hparams.transformer_layers,
            )
            self.transformer_2 = TransformerEncoder(
                encoder_layer=encoder_layer_template,
                num_layers=self.hparams.transformer_layers,
            )

            self.position_encoding_1 = PositionalEncoding3D(self.out_channels)
            self.position_encoding_2 = PositionalEncoding3D(self.out_channels)
        else:
            self.linear_layer = torch.nn.Linear(
                in_features=self.in_channels, out_features=self.out_channels, bias=False
            )

            self.recurrent_1 = torch.nn.GRU(
                input_size=self.in_channels,
                hidden_size=self.out_channels,
                bias=True,
                batch_first=True,
                num_layers=self.hparams.transformer_layers,
                bidirectional=False,
            )
            self.recurrent_2 = torch.nn.GRU(
                input_size=self.in_channels,
                hidden_size=self.out_channels,
                bias=True,
                batch_first=True,
                num_layers=self.hparams.transformer_layers,
                bidirectional=False,
            )

            self.position_encoding_1 = PositionalEncoding3D(self.out_channels)
            self.position_encoding_2 = PositionalEncoding3D(self.out_channels)

    def forward(self, x1: Tensor, x2: Tensor):
        b, k, c2 = x1.shape
        b, t, c1 = x2.shape

        hc = torch.einsum("bkc,btc->btkc", x1, x2)

        # Hippocampus integrates mec and lec information
        if self.hparams.use_transformer:
            # x = repeat(x, "b c -> b t h w c", b=b, t=t, h=xy_after_conv, w=xy_after_conv)
            x = rearrange(
                hc,
                "b t (h w) c -> b t h w c",
                b=b,
                t=t,
                h=self.xy_after_conv,
                w=self.xy_after_conv,
            )

            # apply linear transformation to project ENCODER_CONV_CHANNELS to TRANSFORMER_CHANNELS
            x = self.linear_layer(x)

            # apply 3d position encoding before going through the first transformer
            x = x + self.position_encoding_1(x)
            x = rearrange(x, "b t h w c -> b (t h w) c", b=b, t=t, h=self.xy_after_conv, w=self.xy_after_conv, c=self.out_channels)  # fmt: skip
            x = self.transformer_1(x)

            # Original repo scaling
            x = rearrange(x, "b (t h w) c -> (b t) c h w", b=b, t=t, h=self.xy_after_conv, w=self.xy_after_conv, c=self.out_channels)  # fmt: skip
            x = torch.nn.functional.avg_pool2d(x, kernel_size=2) * 2
            x = rearrange(x, "(b t) c h w -> b t h w c", b=b, t=t, h=self.xy_after_transformer, w=self.xy_after_transformer, c=self.out_channels)  # fmt: skip

            x = x + self.position_encoding_2(x)
            x = rearrange(x, "b t h w c -> b (t h w) c", b=b, t=t, h=self.xy_after_transformer, w=self.xy_after_transformer, c=self.out_channels)  # fmt: skip
            x = self.transformer_2(x)
            x = rearrange(x, "b (t h w) c -> b t (h w) c", b=b, t=t, h=self.xy_after_transformer, w=self.xy_after_transformer, c=self.out_channels)  # fmt: skip
        else:
            x = rearrange(
                hc,
                "b t (h w) c -> b t h w c",
                b=b,
                t=t,
                h=self.xy_after_conv,
                w=self.xy_after_conv,
            )

            # apply linear transformation to project ENCODER_CONV_CHANNELS to TRANSFORMER_CHANNELS
            x = self.linear_layer(x)

            # apply 3d position encoding before going through the first transformer
            x = x + self.position_encoding_1(x)
            x = rearrange(x, "b t h w c -> b (t h w) c", b=b, t=t, h=self.xy_after_conv, w=self.xy_after_conv, c=self.out_channels)  # fmt: skip
            x, _ = self.recurrent_1(x)

            # Original repo scaling
            x = rearrange(x, "b (t h w) c -> (b t) c h w", b=b, t=t, h=self.xy_after_conv, w=xy_after_conv, c=self.out_channels)  # fmt: skip
            x = F.avg_pool2d(x, kernel_size=2) * 2
            x = rearrange(x, "(b t) c h w -> b t h w c", b=b, t=t, h=self.xy_after_transformer, w=self.xy_after_transformer, c=self.out_channels)  # fmt: skip

            x = x + self.position_encoding_2(x)
            x = rearrange(x, "b t h w c -> b (t h w) c", b=b, t=t, h=xy_after_transformer, w=xy_after_transformer, c=self.out_channels)  # fmt: skip
            x, _ = self.recurrent_2(x)
            x = rearrange(x, "b (t h w) c -> b t (h w) c", b=b, t=t, h=xy_after_transformer, w=xy_after_transformer, c=self.out_channels)  # fmt: skip

        return x, hc

class MLP(nn.Module):
    """Create a MLP with `len(hidden_features)` hidden layers, each with `hidden_features[i]` features."""

    def __init__(
        self,
        in_features: int,
        out_features: int,
        hidden_features,
        activation: nn.Module = torch.nn.ReLU(),
    ):
        super().__init__()
        if not isinstance(activation, torch.nn.Module):
            if activation == "relu":
                activation = nn.ReLU()
            elif activation == "linear":
                activation = nn.Identity()
            elif activation == "leaky":
                activation = nn.LeakyReLU()
            else:
                raise ValueError("Activation function not supported")

        layers: List[nn.Module] = []
        last_size = in_features
        for size in hidden_features:
            layers.append(nn.Linear(last_size, size))
            last_size = size
            layers.append(activation)
        # Don't put an activation after the last layer
        layers.append(nn.Linear(last_size, out_features))

        self.sequential = torch.nn.Sequential(*layers)

    def forward(self, x: Tensor):
        return self.sequential(x)


import random
import time
# init des  variable et liste vide nécéssaire
insertion = []
selection = []
sort = []
tailles = [100, 200, 500, 1000, 2000, 5000, 10000, 20000]

# def de la fonction liste qui  crée une liste random de longueur "n"
def liste(n):
    liste = [random.random() for i in range(n)]
    return liste

# def de la fonction swap
def swap(liste, i, j):
    aux = liste[i]
    liste[i] = liste[j]
    liste[j] = aux

# def des diférentes fonction de tri
def tri_insertion(liste):
    for i in range(1, len(liste)):
        j = i - 1
        while j >= 0 and liste[j + 1] < liste[j]:
            swap(liste, j, j + 1)
            j -= 1

def tri_selection(liste):
    for i in range(0, len(liste)):
        m = liste[i:].index(min(liste[i:]))
        swap(liste, i, m+i)

def tri_sort(liste):
    liste.sort()

# fonctions qui fait la dif de temps de calcul des dif fonction de tri
def tri(a, n):
    methode = None
    if a == "insertion":
        methode = tri_insertion

    elif a == "selection":
        methode = tri_selection

    elif a == "sort":
        methode = tri_sort

    t1 = time.time()
    methode(liste(n))
    t2 = time.time()
    return t2 - t1      # calcul de la dif de temps en dehors des if/elif/else


import os
from slack_sdk import WebClient
from slack_bolt.adapter.flask import SlackRequestHandler
from slack_bolt import App
from dotenv import find_dotenv, load_dotenv
from flask import Flask, request, render_template

import pinecone
from query_llm import query_similarity_search_QA_w_sources_OpenAI_Model

from slack_sdk.errors import SlackApiError

load_dotenv()
slack_client = WebClient(token=os.getenv("SLACK_BOT_TOKEN"))
response = slack_client.auth_test()
print(response["user_id"])

pinecone.init(
    api_key=str(os.environ['PINECONE_API_KEY']),
    environment=str(os.environ['PINECONE_ENV'])
)

app = App(token=os.environ["SLACK_BOT_TOKEN"])
flask_app = Flask(__name__)
handler = SlackRequestHandler(app)

# Decorator for handling direct bot message events
@app.event("message")
def handle_direct_message(event, say):
    if event.get("subtype") is None and event.get("channel_type") == "im":
        user_input = event["text"]
        user_id = event["user"]

        try:
            result = slack_client.conversations_history(channel=event["channel"], limit=16)
            chat_history = result["messages"]
            #print(chat_history)
        except SlackApiError as e:
            print("Error creating conversation: {}".format(e))

        n = len(chat_history)
        i = 1
        formattedChatHistory = []
        questionAndAnswer = {}
        while i < n:
            msg = chat_history[i]
            if "type" in msg and msg["type"] == "message" and "text" in msg:
                if "bot_id" in msg:
                    # case 1: there is an existing answer
                    if "answer" in questionAndAnswer:
                        formattedChatHistory.append(("", questionAndAnswer["answer"]))
                        questionAndAnswer = {"answer": msg["text"]}
                    # case 2: there is an existing question
                    elif "question" in questionAndAnswer:
                        formattedChatHistory.append((questionAndAnswer["question"], msg["text"]))
                        questionAndAnswer = {}
                    else: # case 3: no existing question or answer
                        questionAndAnswer = {"answer": msg["text"]}
                elif "client_msg_id" in msg:
                    # case 1: there is an existing answer
                    if "answer" in questionAndAnswer:
                        formattedChatHistory.append((msg["text"], questionAndAnswer["answer"]))
                        questionAndAnswer = {}
                    # case 2: there is an existing question
                    elif "question" in questionAndAnswer:
                        formattedChatHistory.append((questionAndAnswer["question"], ""))
                        questionAndAnswer = {"question": msg["text"]}
                    else: # case 3: no existing question or answer
                        questionAndAnswer = {"question": msg["text"]}

            i+=1
        formattedChatHistory.reverse()
        print(formattedChatHistory)
        result, chat_history_new = query_similarity_search_QA_w_sources_OpenAI_Model(user_input, formattedChatHistory)
        say(result)

@flask_app.route("/slack/events", methods=["POST"])
def slack_events():
    """
    Route for handling Slack events.
    This function passes the incoming HTTP request to the SlackRequestHandler for processing.

    Returns:
        Response: The result of handling the request.
    """
    if "type" in request.json and request.json["type"] == "url_verification":
        return request.json["challenge"]
    return handler.handle(request)

@flask_app.route("/", methods=["GET"])
def home():
    return render_template("index.html")

if __name__ == "__main__":
    # initialize pinecone
    pinecone.init(
        api_key=str(os.environ['PINECONE_API_KEY']),
        environment=str(os.environ['PINECONE_ENV'])
    )
    #chat_histories={}
    flask_app.run(port=3000)
    print("flask app running")


#Actividad 4
import csv

import sqlite3
from sqlite3 import Error

def conexion(filename = ":memory:"):
    try:
        con = sqlite3.connect(filename)
        print("Conexion realizada a ", filename)
    except Error:
        print(Error)
        con = None
    finally:
        return con

def insertaremple(con, dic):
    try:
        cur = con.cursor()

        cur.execute("insert into empleados values (?,?,?,?,?,?)", dic)
        con.commit()

    except sqlite3.IntegrityError as err:
        print("Error --> ", err )
        print("No se aniadieron los registros")

def importarcsv(con):

    cur = con.cursor()
    emplecsv = open("empleados.csv","w")
    cur.execute("SELECT * from empleados")
    rows = cur.fetchall()

    datos = [["ID,Nombre,Salario anual,Departamento,Categoria,Fecha de contratacion"]]
    datos.append(rows)
    with emplecsv:
        writer = csv.writer(emplecsv)
        writer.writerows(datos)

    emplecsv.close()
    con.commit()

def importeencsv(con):

    cur = con.cursor()

    cur.execute("SELECT distinct(departamento) from empleados")
    dep = cur.fetchall()
    dato = []

    for i in dep:
        cur.execute("SELECT distinct(categoria) from empleados where departamento = (?)", i)
        cat = cur.fetchall()
        for y in cat:

            cur.execute("SELECT sum(salario) from empleados where categoria = (?)", y)
            suel = cur.fetchall()
            importecsv = open("Resumen.csv","w")
            dato.append(i)
            dato.append(cat)
            dato.append(suel)

            with importecsv:
                writer = csv.writer(importecsv, delimiter=",")
                writer.writerows(dato)

    importecsv.close()

    con.commit()

def borrar(con):

    cur = con.cursor()

    cur.execute("delete from empleados")
    con.commit()


import cv2
import random
#for reading image -1 for og 0 for gs 1 for alpha
image = cv2.imread('assets/coca-cola-logo.png',-1)
#prints numpy array of pixels
print(image)
#prints height,width,channels(RGB)
print(image.shape)
#for first 100 rows
for i in range(100):
    #for all columns,shape[1] returns column no
    for j in range(image.shape[1]):
        image[i][j]=[ random.randint(0,255),random.randint(0,255),random.randint(0,255) ]

cv2.imshow("Image",image)
#for waiting till key pressed o=infinte
cv2.waitKey(0)
cv2.destroyAllWindows()


from django.contrib import admin
from django.contrib.admin import ModelAdmin
from .models import File, Directory

class DirectoryAdmin(ModelAdmin):
    list_display = [
        'parent',
        'path',
    ]

class FileAdmin(ModelAdmin):
    list_display = [
        'filename',
        'directory',
        'meta_index_date',
        'meta_track',
        'meta_track_total',
        'meta_title',
        'meta_artist',
        'meta_album',
        'meta_year',
        'meta_genre',
        'meta_duration',
    ]

admin.site.register(File, FileAdmin)
admin.site.register(Directory, DirectoryAdmin)