#!/usr/bin/env python
from colour import Color
import system.settings as settings
from math import sqrt
from random import randint
from random import shuffle

_led_mapping = None

def get_unpacked_model(model):
        name = model['name']
        if name == "large_cube":
            sides = ['top', 'north', 'west', 'south', 'east']
            mapping = [None] * 5
            for i in range(5):
                mapping[i] = [-1] * 50
                for j in range(5):
                    side = sides[j]
                    for k in range(10):
                        mapping[i][10*j + k] = model['led-groups'][side][i][k]
            return mapping
        else:
            return None

def create_electrode_mapping(presenter):
    global _led_mapping
    model = settings.LED_MODEL
    n_elct = settings.NEURAL_ELECTRODES_TOTAL
    n_leds = settings.LEDS_TOTAL

    mapping = get_unpacked_model(settings.LED_MODEL)
    if mapping is None:
        print("No dot mapping for model, neural data will be stripy")
        return

    leds_per_electrode = n_leds//n_elct
    leds_last_electrode = leds_per_electrode
    if n_leds % n_elct != 0:
        leds_last_electrode += 1

    _led_mapping = [None] * n_elct
    led_pos = [None] * n_elct
    last_index = [0,0]
    step = int(sqrt(settings.NEURAL_ELECTRODES_TOTAL*len(mapping)*len(mapping[0])))
    for i in range(n_elct):
        x = last_index[0]
        y = last_index[1]
        last_index[1] += step
        if last_index[1] >= 5:
            last_index[1] = 0
            last_index[0] += step

        if x >= 50 or mapping[y][x] == -1:
            x = randint(0,49)
            y = randint(0,4)
            while mapping[y][x] == -1:
                x = randint(0,49)
                y = randint(0,4)

        _led_mapping[i] = [mapping[y][x]]
        led_pos[i] = [[x,y]]
        mapping[y][x] = -1

    # Grow each electrode seed

    check_pattern = [[-1,0],[1,0],[0,-1],[0,1]]
    while True:
        temp = check_pattern.pop(0)
        check_pattern.append(temp)
        change = False
        for i in range(n_elct):
            done = False
            led_chosen = -1
            x = -1
            y = -1
            for j in range(len(_led_mapping[i])):
                #shuffle(check_pattern)
                for move in check_pattern:
                    x = led_pos[i][j][0] + move[0]
                    y = led_pos[i][j][1] + move[1]
                    if not (0 <= y <= 4 and 0 <= x <= 49):
                        continue
                    led_chosen = mapping[y][x]
                    if led_chosen != -1:
                        change = True
                        done = True
                        _led_mapping[i].append(led_chosen)
                        led_pos[i].append([x,y])
                        mapping[y][x] = -1
                        break
                if done:
                    break

        if not change:
            break

    """
    electrodes = leds_per_electrode
    if i == n_elct - 1:
        electrodes = leds_last_electrode
    _led_mapping[i] = [-1] * electrodes
    while mapping[last_index[1]][last_index[0]] == -1:
        last_index[1] += 1
        if last_index[1] >= 5:
            last_index[1] = 0
            last_index[0] += 1
            if last_index[0] >= 50:
                print('LEDs out of bounds when creating mapping!')
                exit(-1)
    for j in range(electrodes):
    """

def color_grouping(index, values, value_per_group):
    if values[index] <= value_per_group:
        return 0
    elif value_per_group < values[index] <= 2 * value_per_group:
        return 1
    elif 2 * value_per_group < values[index] <= 3 * value_per_group:
        return 2
    elif 3 * value_per_group < values[index] <= 4 * value_per_group:
        return 3
    elif 4 * value_per_group < values[index] <= 5 * value_per_group:
        return 4
    elif 5 * value_per_group < values[index] <= 6 * value_per_group:
        return 5
    elif 6 * value_per_group < values[index] <= 7 * value_per_group:
        return 6
    elif 7 * value_per_group < values[index] <= 8 * value_per_group:
        return 7
    elif 8 * value_per_group < values[index] <= 9 * value_per_group:
        return 8
    else:
        return 9

def generate_color_gradient():
    color1 = Color(settings.PLOT_COLOR_FROM)
    return list(color1.range_to(Color(settings.PLOT_COLOR_TO), 10))

def data_to_hex(data):
    colors = generate_color_gradient()
    hex_data = [0] * settings.NEURAL_ELECTRODES_TOTAL
    for i in range(len(data)):
        hex_data[i] = colors[int(data[i])].get_hex_l()
    return hex_data

def data_to_bytearray(input_data, output_data):
    global _led_mapping
    hex_array = data_to_hex(input_data)
    num_leds = settings.LEDS_TOTAL
    num_leds_cluster = int(num_leds / settings.NEURAL_ELECTRODES_TOTAL)

    if _led_mapping is not None:
        for i in range(len(hex_array)):
            leds = _led_mapping[i]
            for j in range(len(leds)):
                index = leds[j]*3
                output_data[index:index+3] = bytearray.fromhex(hex_array[i][1:])
    else:
        for i in range(len(hex_array)):
            for j in range(num_leds_cluster):
                index = i * 3 * num_leds_cluster + 3 * j
                output_data[index:index + 3] = bytearray.fromhex(hex_array[i][1:])

'''
def handle_large_cube(hex_array, output_data):
    electrodes_per_side = int(settings.NEURAL_ELECTRODES_TOTAL/5)
    last_side = electrodes_per_side + settings.NEURAL_ELECTRODES_TOTAL - electrodes_per_side*5
    sides = ['top', 'north', 'west', 'south', 'east']
    model = settings.LED_MODEL['led-groups']
    for i in range(5):
        side_leds = model[sides[i]]
        height = len(side_leds)
        width = len(side_leds[0])
        begin = electrodes_per_side*i
        electrodes_for_side = electrodes_per_side
        if i == 5:
            electrodes_for_side = last_side

        leds_per_electrode = height*width/electrodes_for_side
        led_cube_edge = sqrt(leds_per_electrode)

        for i in range(electrodes_for_side):
            electrode = hex_array[begin + i][1:]
            curr_hor = i%(width / led_cube_edge)
            curr_vert = i/(width / led_cube_edge)
            for k in range(int(led_cube_edge+0.5)):
                for l in range(int(led_cube_edge+0.5)):
                    led_ver = int(led_cube_edge*curr_vert+k)
                    if led_ver >= width:
                        led_ver = width-1
                    led_hor = int(leds_per_electrode*curr_hor+l)
                    if led_hor >= height:
                        led_hor = height-1
                    index = side_leds[led_hor][led_ver]
                    output_data[index:index+3] = bytearray.fromhex(electrode)
'''


from scipy.spatial import distance
import numpy as np
import tensorflow as tf
import os
import heapq
import pickle
import matplotlib.pyplot as plt
import time
import cv2
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, MaxPooling2D, LSTM, GRU, Merge
from keras.layers import BatchNormalization, Activation
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Sequential, Model
from keras.optimizers import Adam, RMSprop, SGD
from keras.layers.merge import Concatenate
from keras.models import load_model
from keras.layers import merge
from keras.layers.core import Permute
from keras.layers.core import RepeatVector
from keras.layers.wrappers import TimeDistributed
from keras.callbacks import History
from keras.utils import plot_model, multi_gpu_model
from keras import backend as k
from keras.applications.vgg16 import VGG16
from keras import optimizers

from train.utils import circle_group_model_input, log_group_model_input, group_model_input
from train.utils import get_traj_like, get_obs_pred_like
from train.utils import person_model_input, model_expected_ouput, preprocess
from train.vehicle_utils import preprocess_vehicle,get_traj_like_vehicle,get_obs_vehicle_like,vehicle_model_input,\
    vehicle_model_expected_ouput,veh2ped_group_model_input,veh2ped_circle_group_model_input

import train.data_process as dp
import train.veh_data_process as vdp

os.environ["CUDA_VISIBLE_DEVICES"] = '0'  # 只有编号为1的GPU对程序是可见的，在代码中gpu[0]指的就是这块儿GPU
config=tf.ConfigProto()
config.gpu_options.allow_growth=True
config.gpu_options.per_process_gpu_memory_fraction=0.5
k.tensorflow_backend.set_session(tf.Session(config=config))

# FDE 最终位移误差（final displacement error）
def calculate_FDE(test_label, predicted_output, test_num, show_num):
    total_FDE = np.zeros((test_num, 1))
    for i in range(test_num):
        predicted_result_temp = predicted_output[i]
        label_temp = test_label[i]
        total_FDE[i] = distance.euclidean(predicted_result_temp[-1], label_temp[-1])  # 计算两个阵列之间的欧几里德距离

    show_FDE = heapq.nsmallest(show_num, total_FDE)   # 在total_FDE中找到最小的show_num的数
    show_FDE = np.reshape(show_FDE, [show_num, 1])

    return np.average(show_FDE)

# ADE 平均位移误差（Average displacement error）
def calculate_ADE(test_label, predicted_output, test_num, predicting_frame_num, show_num):
    total_ADE = np.zeros((test_num, 1))
    for i in range(test_num):
        predicted_result_temp = predicted_output[i]
        label_temp = test_label[i]
        ADE_temp = 0.0
        for j in range(predicting_frame_num):
            ADE_temp += distance.euclidean(predicted_result_temp[j], label_temp[j])
        ADE_temp = ADE_temp / predicting_frame_num
        total_ADE[i] = ADE_temp

    show_ADE = heapq.nsmallest(show_num, total_ADE)
    show_ADE = np.reshape(show_ADE, [show_num, 1])

    return np.average(show_ADE)

def CNN(img_rows, img_cols, img_channels=3):
    model = Sequential()
    img_shape = (img_rows, img_cols, img_channels)
    model.add(Conv2D(96, kernel_size=11, strides=4, input_shape=img_shape, padding="same"))
    model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
    model.add(BatchNormalization(momentum=0.8))
    model.add(Conv2D(256, kernel_size=5, strides=1, padding="same"))
    model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
    model.add(BatchNormalization(momentum=0.8))
    #    model.add(Conv2D(384, kernel_size=3, strides=1, padding="same"))
    #    model.add(Conv2D(384, kernel_size=3, strides=1, padding="same"))
    model.add(Conv2D(256, kernel_size=3, strides=1, padding="same"))
    model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
    model.add(Flatten(input_shape=img_shape))
    model.add(Dense(512, activation='relu'))
    model.add(Dense(256, activation='relu'))

    return model

# Parameter's Define
observed_frame_num = 8
predicting_frame_num = 12
train_data_num = 2  # 训练的数据

hidden_size = 128
tsteps = observed_frame_num#8
batch_size = 20

dimensions_1 = [720, 576] #[720,576] #eth hotel
# dimensions_1 = [224, 224]
dimensions_2 = [640, 480]  #eth univ
veh_neighborhood_size=128
grid_veh_size=4
neighborhood_size = 32
grid_size = 4
neighborhood_radius = 32
grid_radius = 4
# grid_radius_1 = 4
grid_angle = 45
circle_map_weights = [1, 2, 3, 4, 4, 3, 2, 1]
circle_map_weights=np.array(circle_map_weights)

opt = optimizers.RMSprop(lr=0.003)

# Starting load the datadut

PersonInput=[]
PersonExpectOutput=[]
Veh2PedInput=[]
Veh2PedExpectOutput=[]
GroupInput=[]

for datadir in range(train_data_num):
    data_dir=r'C:\Users\asus\Desktop\lstm\ss_lstm(changing)\datadut\0%s' %(datadir+1)
    veh_data, numveh = preprocess_vehicle(data_dir)
    raw_data, numPeds = preprocess(data_dir)
    check_veh = vdp.veh_DataProcesser(data_dir, observed_frame_num, predicting_frame_num)
    check = dp.DataProcesser(data_dir, observed_frame_num, predicting_frame_num)
    obs_veh = check_veh.obs_veh
    obs = check.obs
    pred_veh = check_veh.pred_veh
    pred = check.pred

    vehicle_input_raw = vehicle_model_input(obs_veh, observed_frame_num)
    person_input_raw = person_model_input(obs, observed_frame_num)
    group_circle_raw = circle_group_model_input(obs, observed_frame_num, neighborhood_size, dimensions_1,
                                              neighborhood_radius, grid_radius, grid_angle, circle_map_weights,
                                              raw_data)  # 圆形
    group_grid_1 = group_model_input(obs, observed_frame_num, neighborhood_size, dimensions_1, grid_size,
                                     raw_data)  # 矩形区域只写一个做存档
    # 车辆对行人的影响数据
    gruop_grid_veh2ped_raw = veh2ped_circle_group_model_input(obs, observed_frame_num, dimensions_1,
                                                            veh_neighborhood_size, grid_radius, grid_angle, raw_data,
                                                            veh_data,circle_map_weights)  # 圆形区域，若要矩形区域改成veh2ped_grid_model_input
    vehicle_expect_output_raw = vehicle_model_expected_ouput(pred_veh, predicting_frame_num) # 车辆
    expected_ouput_raw = model_expected_ouput(pred, predicting_frame_num)  # 行人

    group_input_raw = group_circle_raw
    veh2ped_group_input_raw = gruop_grid_veh2ped_raw

    PersonInput.append(person_input_raw)
    PersonExpectOutput.append(expected_ouput_raw)
    GroupInput.append(group_input_raw)
    Veh2PedInput.append(veh2ped_group_input_raw)
    Veh2PedExpectOutput.append(vehicle_expect_output_raw)

def all_run(epochs, predicting_frame_num, min_loss):

    person_input = np.concatenate(PersonInput)
    expected_ouput = np.concatenate(PersonExpectOutput)
    group_input = np.concatenate(GroupInput)
    vehicle_expect_output = np.concatenate(Veh2PedExpectOutput)
    veh2ped_group_input = np.concatenate(Veh2PedInput)
    # test_input = [group_input_10, person_input_10, veh2ped_group_input_10]
    # test_output = expected_ouput_10

    scene_scale = CNN(dimensions_1[1], dimensions_1[0])
    scene_scale.add(RepeatVector(tsteps))
    scene_scale.add(GRU(hidden_size,
                        input_shape=(tsteps, 512),
                        batch_size=batch_size,#all_run(epochs, predicting_frame_num, leave_dataset_index, map_index, show_num, min_loss)
                        return_sequences=False,
                        stateful=False,
                        dropout=0.2))

    group_model = Sequential()
    group_model.add(Dense(hidden_size, activation='relu', input_shape=(tsteps, 64)))#全连接层
    group_model.add(GRU(hidden_size,
                        input_shape=(tsteps, int(neighborhood_radius / grid_radius) * int(360 / grid_angle)),
                        batch_size=batch_size,
                        return_sequences=False,
                        stateful=False,
                        dropout=0.2))
    veh2ped_group_model = Sequential()
    veh2ped_group_model.add(Dense(hidden_size, activation='relu', input_shape=(tsteps, 256)))  # 全连接层
    veh2ped_group_model.add(GRU(hidden_size,
                        input_shape=(tsteps, int(veh_neighborhood_size / grid_radius) * int(360 / grid_angle)),
                        batch_size=batch_size,
                        return_sequences=False,
                        stateful=False,
                        dropout=0.2))
    person_model = Sequential() # 定义时间序列
    person_model.add(Dense(hidden_size, activation='relu', input_shape=(tsteps, 2)))
    person_model.add(GRU(hidden_size,
                         input_shape=(tsteps, 2),
                         batch_size=batch_size,
                         return_sequences=False,
                         stateful=False,
                         dropout=0.2))

    #myself
    vehicle_model=Sequential()
    vehicle_model.add(Dense(hidden_size, activation='relu', input_shape=(tsteps, 2)))
    vehicle_model.add(GRU(hidden_size,
                         input_shape=(tsteps, 2),
                         batch_size=batch_size,
                         return_sequences=False,
                         stateful=False,
                         dropout=0.2))
    # model.add(Merge([scene_scale, group_model, person_model], mode='sum'))
    model = Sequential()
    model.add(Merge([ group_model,
                      person_model,veh2ped_group_model], mode='sum'))
    model.add(RepeatVector(predicting_frame_num))
    model.add(GRU(128,
                input_shape=(predicting_frame_num, 2),
                batch_size=batch_size,
                return_sequences=True,
                stateful=False,
                dropout=0.2))
    model.add(TimeDistributed(Dense(2)))
    model.add(Activation('linear'))
    model.compile(loss='mse', optimizer=opt)
    # parallel=multi_gpu_model(model,gpus=2)
    print(model.summary())
    # for i in range(epochs):
    #     # history = model.fit([scene_input, group_input, person_input], expected_ouput,
    #                         #batch_size=batch_size,
    #                         #epochs=1,
    #                         #verbose=1,
    #                         #shuffle=False)
    #     history = model.fit([group_input, person_input,veh2ped_group_input], expected_ouput,
    #                         batch_size=batch_size,
    #                         epochs=1,
    #                         verbose=1,
    #                         shuffle=False)
    #     loss = history.history['loss']
    #     if loss[0] < min_loss:
    #         break
    #     else:
    #         continue
    #     model.reset_states()
    #     # parallel.reset_states()

    history = model.fit([group_input, person_input, veh2ped_group_input], expected_ouput,
                        batch_size=batch_size,
                        epochs=200,
                        verbose=1,
                        shuffle=False)
    # 绘制训练 & 验证的准确率值
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title('Model accuracy')
    plt.ylabel('Accuracy')
    plt.xlabel('Epoch')
    plt.legend(['Train', 'Test'], loc='upper left')
    plt.show()
    # 绘制训练 & 验证的损失值
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('Model loss')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend(['Train', 'Test'], loc='upper left')
    plt.show()

    # model.save('ss_map_' + str(map_index) + '_ETHUCY_' + str(leave_dataset_index) + 'testing_seg.h5')
    # plot_model(model, to_file='model.png')

    # model.save('testing_SS_LSTM_logmap_Zara1_1000epoc_batchsize_20.h5')
    model.save_weights("model_weights_1000epochs_090402.h5")
    print('The model has been saved in h5 files')
    print('Now u can predicted the reslut for runing the predicting.py pythonfile.')

all_run(1000, predicting_frame_num, 0)


from __future__ import print_function
import logging, sys
import argparse
import wget
import os
import xmltodict
import xml.etree.ElementTree as ET
from datetime import datetime
from collections import OrderedDict
from functools import partial
import time

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def wget_from_url(url, name=None):
    name = url.rsplit('/', 1)[-1] if not name else name
    if os.path.exists(name):
      os.remove(name)
    wget.download(url, out=name)

def download(option):
  motc_prefix = 'https://tisvcloud.freeway.gov.tw/history/motc20/'
  if option == 'static' or option == 'all':
    [wget_from_url(motc_prefix + x)
      for x in ['Section.xml',      # Basic information of road section
                'SectionShape.xml', # Map shape information of road section (wkt info)
                'SectionLink.xml',  # SectionID to LinkIDs information
                'ETag.xml',         # Etag information of LinkID
                'ETagPair.xml'
                ]]

  if option == 'dynamic' or option == 'all':
    [wget_from_url(motc_prefix + x)
      for x in ['LiveTraffic.xml',  # Real-time traffic information on road section
                'ETagPairLive.xml'
                ]]

  else:
    eprint('invalid download option (dynamic/static/all)')

def extract_data(xml_file, callback=None):
  if not callback:
    eprint('The callback option is needed (a function to deal with the xml root)')
    sys.exit('Error on extract_data')

  tree = ET.parse(xml_file)
  root = tree.getroot()
  prefix = root.tag.split('}', 1)[0] + '}'
  return callback(root=root, prefix=prefix)

def shapes_process(root, prefix=''):
  Dict = {}
  for child in root.find(prefix + 'SectionShapes'):
    section_id = child.find(prefix + 'SectionID').text
    shape = child.find(prefix + 'Geometry').text

    logging.debug(f' SectionID: {section_id}, Shape: {shape}')

    Dict[section_id] = shape
  return Dict

def livetraffic_process(root, prefix=''):
  Dict = {}
  for child in root.find(prefix + 'LiveTraffics'):
    section_id = child.find(prefix + 'SectionID').text
    travel_time = child.find(prefix + 'TravelTime').text
    congestion_level = child.find(prefix + 'CongestionLevel').text
    travel_speed = child.find(prefix + 'TravelSpeed').text

    logging.debug(f' SectiondID: {section_id}, travel time: {travel_time}, congestion: {congestion_level}, travel speed: {travel_speed}')

    Dict[section_id] = {'TravelTime': travel_time, 'CongestionLevel': congestion_level, 'TravelSpeed': travel_speed}
  return Dict

def linkid_process(root, prefix=''):
  Dict = {}
  for child in root.find(prefix + 'SectionLinks'):
    sec_id = child.find(prefix + 'SectionID').text
    link_ids = child.find(prefix + 'LinkIDs')
    result = [l.text for l in link_ids.findall(prefix + 'LinkID')]

    logging.debug(f' SectionID: {sec_id}, linkIDs: {result}')

    Dict[sec_id] = result
  return Dict

def etag_process(root, prefix=''):
  Dict = {}
  for child in root.find(prefix + 'ETags'):
    etag_id = child.find(prefix + 'ETagGantryID').text
    link_id = child.find(prefix + 'LinkID').text
    road_id = child.find(prefix + 'RoadID').text

    logging.debug(f' Etag: {etag_id}, LinkID: {link_id}, RoadID: {road_id}')

    Dict [etag_id] = {'LinkID': link_id, 'RoadID': road_id}
  return Dict

def etag_pair_live_process(root, prefix=''):
  Dict = {}
  for child in root.find(prefix + 'ETagPairLives'):
    etag_pair_id = child.find(prefix + 'ETagPairID').text
    start_status = child.find(prefix + 'StartETagStatus').text
    end_status = child.find(prefix + 'EndETagStatus').text

    count = 0
    flows = {}
    for flow in child.find(prefix + 'Flows'):
      vehicle_type = flow.find(prefix + 'VehicleType').text
      vehicle_count = flow.find(prefix + 'VehicleCount').text
      count += int(vehicle_count)

      flows[vehicle_type] = {'VehicleCount': vehicle_count}

    # logging.debug(f' Etag: {etag_id}, LinkID: {link_id}, RoadID: {road_id}')

    Dict [etag_pair_id] = {'StartETagStatus': start_status,
                           'EndETagStatus': end_status,
                           'VehicleCount': count,
                           'Flows': flows
                          }
  return Dict

def etag_pair_process(root, prefix=''):
  Dict = OrderedDict()
  for child in root.find(prefix + 'ETagPairs'):
    etag_pair_id = child.find(prefix + 'ETagPairID').text
    start_etag = child.find(prefix + 'StartETagGantryID').text
    end_etag = child.find(prefix + 'EndETagGantryID').text
    description = child.find(prefix + 'Description').text
    distance = child.find(prefix + 'Distance').text
    start_link_id = child.find(prefix + 'StartLinkID').text
    end_link_id = child.find(prefix + 'EndLinkID').text

    logging.debug(f' Etag: {etag_pair_id}, description: {description}')

    Dict [etag_pair_id] = {'StartETagGantryID': start_etag,
                           'EndETagGantryID': end_etag,
                           'Description': description,
                           'Distance': distance,
                           'StartLinkID': start_link_id,
                           'EndLinkID': end_link_id
                          }
  return Dict

# The default road for id_process is 國道 1 號 (000010)
def id_process(root, road='000010', prefix=''):
  Dict = {'N': OrderedDict(), 'S': OrderedDict()}

  for child in root.find(prefix + 'Sections'):
    road_id = child.find(prefix + 'RoadID').text

    # only the giving road will be processed
    if road_id != road:
      continue

    road_direction = child.find(prefix + 'RoadDirection').text
    section_id = child.find(prefix + 'SectionID').text
    _sec = child.find(prefix + 'RoadSection')
    start, end = _sec.find(prefix + 'Start').text, _sec.find(prefix + 'End').text
    sec_length = child.find(prefix + 'SectionLength').text

    logging.debug(f' SectionID: {section_id}, RoadID: {road_id}, ({start}, {end}), Length: {sec_length}')

    Dict[road_direction][section_id] = {'RoadID': road_id, 'Start': start, 'End': end, 'Length': sec_length}
  return Dict

# Date, Time, Congestion, Speed
def collect_dynamic_traffic(traffic_list, save='./data'):
  etag_pair = extract_data('ETagPair.xml', callback=etag_pair_process)
  while True:
    allfiles = OrderedDict()
    for traffic in traffic_list:
      for i in traffic:
        allfiles[i[0]] = open(f"{save}/travel_time_{i[0]}.txt", "a")

    # download dynamic data
    download('dynamic')
    live_traffic = extract_data('LiveTraffic.xml', callback=livetraffic_process)
    etag_pair_live = extract_data('ETagPairLive.xml', callback=etag_pair_live_process)
    etag_description_to_count = {}
    for key, value in etag_pair_live.items():
      if key in etag_pair:
        etag_description_to_count[etag_pair[key]['Description']] = value['VehicleCount']

    # record time
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")

    for key, value in etag_description_to_count.items():
      f = open(f"{save}/etag_{key}.txt", "a")
      f.write(f'{current_time} {value}\n')
      f.flush()
      f.close()

    for traffic in traffic_list:
      new_traffic = []
      for key, value in traffic:
        if key in live_traffic:
          new_traffic.append((key, value))
      traffic = new_traffic

      t_s = OrderedDict([(key, live_traffic[key]['TravelTime']) for key, value in traffic])
      l_s = OrderedDict([(key, live_traffic[key]['CongestionLevel']) for key, value in traffic])
      s_s = OrderedDict([(key, live_traffic[key]['TravelSpeed']) for key, value in traffic])

      for key, _ in traffic:
        tt = allfiles[key]
        tt.write(f'{current_time} {t_s[key]} {l_s[key]} {s_s[key]}\n')
        tt.flush()
        tt.close()
    time.sleep(120)

# e.g. 台北交流道, 新竹交流道
def traffic_of_two_points(start, end, section_ids):
  # e.g. section_ids = extract_data('Section.xml', callback=partial(id_process, road='000010'))
  ## Create an inverse table from section_ids
  last_elem = next(reversed(section_ids['S'].items()))

  inverse_table = OrderedDict([(value['Start'], (i, key)) for i, (key, value) in enumerate(section_ids['S'].items())] + \
                              [(last_elem[1]['End'], (len(section_ids['S']), last_elem[0]))])

  x1 = inverse_table[start]
  x2 = inverse_table[end]

  direction = ('S', 1) if x1[0] < x2[0] else ('N', -1)
  fix = 1 if direction[0] == 'N' else 0

  traffic = list(section_ids[direction[0]].items())[x1[0]-fix:x2[0]-(fix if x2[0] != 0 else 0):direction[1]] +\
            ([list(section_ids[direction[0]].items())[x2[0]]] if x2[0] == 0 else [])

  return traffic

logging.disable(logging.DEBUG)

def main():
  parser = argparse.ArgumentParser(description='MOTC extractor example')
  parser.add_argument('--download', type=str, default='none', metavar='N',
                      help='Download the data from MOTC (static/dynamic/all)')
  # parser.add_argument('--save-dict', action='store_true', default=False,
  #                       help='For Saving the current dict')
  parser.add_argument('--debug', action='store_true', default=False,
                        help='Debug info')
  parser.add_argument('--collect', action='store_true', default=False,
                        help='Collect dynamic traffic to data/')
  args = parser.parse_args()

  # if args.debug:
  #   logging.enable(logging.DEBUG)

  # Usage
  ## Download the data from motc (static / dynamic / all)
  ## dynamic: only the real-time information will be downloaded from MOTC
  ## static: the static information ...
  ## all: dynamic + static
  if args.download != 'none':
    download(args.download)

  ## Extract the Section IDs information on giving road (e.g. 國道 1 號: 000010) -> OrderedDict(key=section_id)
  section_ids = extract_data('Section.xml', callback=partial(id_process, road='000010'))

  ## Extract the Live Traffic information -> Dict(key=section_id)
  live_traffic = extract_data('LiveTraffic.xml', callback=livetraffic_process)

  ## Extract the Live Traffic information -> Dict
  shapes = extract_data('SectionShape.xml', callback=shapes_process)

  ## Extract the Mapping of SectionID to LinkID -> Dict
  section_links = extract_data('SectionLink.xml', callback=linkid_process)

  etag_pair_live = extract_data('ETagPairLive.xml', callback=etag_pair_live_process)

  etag_pair = extract_data('ETagPair.xml', callback=etag_pair_process)

  etag_description_to_count = {}
  for key, value in etag_pair_live.items():
    if key in etag_pair:
      etag_description_to_count[etag_pair[key]['Description']] = value['VehicleCount']
  # print(etag_description_to_count)

  if args.collect:
    tl = [traffic_of_two_points('基隆端', '高雄端', section_ids), traffic_of_two_points('高雄端', '基隆端', section_ids)]
    collect_dynamic_traffic(tl)

  # print('Travel Time: ', sum([int(live_traffic[key]['TravelTime']) for key, value in traffic]))

if __name__ == '__main__':
  main()


import pandas as pd
import numpy as np
import math
import copy
import time

import util
import apply_model
import calculus

def produce_cont_relevances(inputDf, model, col):
 reles=np.zeros((len(model["conts"][col]),len(inputDf)))

 reles[0][(inputDf[col]<=model["conts"][col][0][0])] = 1 #d(featpred)/d(pt)
 for i in range(len(model["conts"][col])-1):
  x = inputDf[col]
  x1 = model["conts"][col][i][0]
  x2 = model["conts"][col][i+1][0]
  subset = (x>=x1) & (x<=x2)
  #print(reles[subset][:,1])
  reles[i][subset] = (x2 - x[subset])/(x2 - x1) #d(featpred)/d(pt)
  reles[i+1][subset] = (x[subset] - x1)/(x2 - x1) #d(featpred)/d(pt)
 reles[-1][(inputDf[col]>=model["conts"][col][-1][0])] = 1 #d(featpred)/d(pt)

 return np.transpose(reles) #roundabout way of doing this but the rest of the function doesn't flow as naturally if x and y don't switch places

def produce_cont_relevances_dict(inputDf, model):
 opDict = {}

 for col in model["conts"]:
  opDict[col]=produce_cont_relevances(inputDf, model, col)

 return opDict

def produce_cat_relevances(inputDf, model, col):
 reles=np.zeros((len(model["cats"][col]["uniques"])+1,len(inputDf)))

 skeys = apply_model.get_sorted_keys(model, col)
 for i in range(len(skeys)):
  reles[i][inputDf[col].isin([skeys[i]])] = 1 #d(featpred)/d(pt)
 reles[-1][~inputDf[col].isin(skeys)] = 1 #d(featpred)/d(pt)

 return np.transpose(reles) #roundabout way of doing this but the rest of the function doesn't flow as naturally if x and y don't switch places

def produce_cat_relevances_dict(inputDf, model):
 opDict = {}

 for col in model["cats"]:
  opDict[col]=produce_cat_relevances(inputDf, model, col)

 return opDict

def sum_and_listify_matrix(a):
 return np.array(sum(a)).tolist()

def produce_total_relevances_dict(contReleDict, catReleDict):
 op = {"conts":{},"cats":{}}
 for col in contReleDict:
  print(sum(contReleDict[col]))
  op["conts"][col] = sum_and_listify_matrix(contReleDict[col])
 for col in catReleDict:
  op["cats"][col] = sum_and_listify_matrix(catReleDict[col])
 print(op)
 return op

def produce_wReleDict(releDict, w):
 wReleDict = {}
 for col in releDict:
  wReleDict[col]=w*releDict[col]
 return wReleDict

def train_model(inputDf, target, nrounds, lrs, startingModels, weights=None, grad=calculus.Poisson_grad):

 models = copy.deepcopy(startingModels)

 if weights==None:
  weights = np.ones(len(inputDf))
 w = np.array(np.transpose(np.matrix(weights)))
 sw = sum(weights)

 contReleDictList=[]
 catReleDictList=[]
 totReleDictList=[]

 contWReleDictList=[]
 catWReleDictList=[]
 totWReleDictList=[]

 print("initial relevances setup")

 for model in models:
  cord = produce_cont_relevances_dict(inputDf,model)
  card = produce_cat_relevances_dict(inputDf,model)

  contReleDictList.append(cord)
  catReleDictList.append(card)
  totReleDictList.append(produce_total_relevances_dict(cord, card))

  cowrd = produce_wReleDict(cord, w)
  cawrd = produce_wReleDict(card, w)

  contWReleDictList.append(cowrd)
  catWReleDictList.append(cawrd)
  totWReleDictList.append(produce_total_relevances_dict(cowrd, cawrd))

 for i in range(nrounds):

  print("epoch: "+str(i+1)+"/"+str(nrounds))
  for model in models:
   apply_model.explain(model)

  print("initial pred and effect-gathering")

  preds=[]
  overallPred=pd.Series([0]*len(inputDf))
  contEffectsList=[]
  catEffectsList=[]

  for m in range(len(models)):

   contEffects = apply_model.get_effects_of_cont_cols_from_relevance_dict(contReleDictList[m],models[m])
   contEffectsList.append(contEffects)
   catEffects = apply_model.get_effects_of_cat_cols_from_relevance_dict(catReleDictList[m],models[m])
   catEffectsList.append(catEffects)

   pred = apply_model.pred_from_effects(models[m]["BASE_VALUE"], len(inputDf), contEffects, catEffects)
   preds.append(pred)
   overallPred += pred

  gradient = grad(overallPred, np.array(inputDf[target])) #d(Loss)/d(pred)

  for m in range(len(models)):

   model=models[m]
   pred=preds[m]

   print("adjust conts")

   for col in model["conts"]:

    effectOfCol = contEffectsList[m][col]

    peoc = pred/effectOfCol #d(pred)/d(featpred)

    finalGradients = np.matmul(np.array(peoc*gradient),contWReleDictList[m][col]) #d(Loss)/d(pt) = d(Loss)/d(pred) * d(pred)/d(featpred) * d(featpred)/d(pt)

    for k in range(len(finalGradients)):
     totRele = totWReleDictList[m]["conts"][col][k]
     if totRele>0:
      models[m]["conts"][col][k][1] -= finalGradients[k]*lrs[m]/totRele #and not /sw

   print("adjust cats")

   for col in model["cats"]:

    effectOfCol = catEffectsList[m][col]

    peoc = pred/effectOfCol #d(pred)/d(featpred)

    finalGradients = np.matmul(np.array(peoc*gradient),catWReleDictList[m][col]) #d(Loss)/d(pt) = d(Loss)/d(pred) * d(pred)/d(featpred) * d(featpred)/d(pt)

    skeys = apply_model.get_sorted_keys(model, col)

    #all the uniques . . .
    for k in range(len(skeys)):
     totRele = totWReleDictList[m]["cats"][col][k]
     if totRele>0:
      models[m]["cats"][col]["uniques"][skeys[k]] -= finalGradients[k]*lrs[m]/totRele #and not /sw

    # . . . and "OTHER"
    totRele = totWReleDictList[m]["cats"][col][-1]
    if totRele>0:
     models[m]["cats"][col]["OTHER"] -= finalGradients[-1]*lrs[m]/totRele #and not /sw
 return models

if __name__ == '__main__':
 df = pd.DataFrame({"x":[1,2,3,4,5,6,7,8,9],"y":[1,2,3,4,5,6,7,8,9]})
 models = [{"BASE_VALUE":1.0,"conts":{"x":[[1,5],[5,5],[9,5]]}, "cats":[]}]
 newModels = train_model(df, "y",100, [2], models,weights=[1,2,3,4,5,6,7,8,9])
 for newModel in newModels:
  apply_model.explain(newModel)

if False:
 df = pd.DataFrame({"x":[1,2,3,4,5,6,7,8,9],"y":[2,2,2,2,2,2,2,2,2]})
 models = [{"BASE_VALUE":1.0,"conts":{"x":[[2,1],[5,1],[8,1]]}, "cats":[]}]
 print(produce_cont_relevances(df, models[0], "x"))

 df = pd.DataFrame({"x":["cat","dog","cat","mouse","rat"],"y":[2,2,2,2,2]})
 models = [{"BASE_VALUE":1.0,"conts":{}, "cats":{"x":{"uniques":{"cat":1,"mouse":1,"dog":1},"OTHER":1}}}]
 print(produce_cat_relevances(df, models[0], "x"))

 df = pd.DataFrame({"x":[1,2,3,4,5,6,7,8,9],"y":[2,2,2,2,2,2,2,2,2]})
 models = [{"BASE_VALUE":1.0,"conts":{"x":[[2,1],[5,2],[8,1]]}, "cats":[]}]
 reles = produce_cont_relevances(df, models[0], "x")
 print(apply_model.get_effect_of_this_cont_col_from_relevances(reles, models[0], "x"))

 df = pd.DataFrame({"x":["cat","dog","cat","mouse","rat"],"y":[2,2,2,2,2]})
 models = [{"BASE_VALUE":1.0,"conts":{}, "cats":{"x":{"uniques":{"cat":2,"mouse":1,"dog":3},"OTHER":1.5}}}]
 reles = produce_cat_relevances(df, models[0], "x")
 print(apply_model.get_effect_of_this_cat_col_from_relevances(reles, models[0], "x"))

 df = pd.DataFrame({"x":[1,2,3],"y":[2,2,2]})
 models = [{"BASE_VALUE":1.0,"conts":{"x":[[0,1],[4,1]]}, "cats":[]}]
 newModels = train_model(df, "y",50, [2.0], models)
 for newModel in newModels:
  apply_model.explain(newModel)

 df = pd.DataFrame({"x":[1,2,3],"y":[2,3,4]})
 models = [{"BASE_VALUE":1.0,"conts":{"x":[[0,1],[4,1]]}, "cats":[]}]
 newModels = train_model(df, "y",100, [2.0], models)
 for newModel in newModels:
  apply_model.explain(newModel)

 df = pd.DataFrame({"x":[1,2],"y":[2,2]})
 models = [{"BASE_VALUE":1.0,"conts":{"x":[[1,1],[2,1]]}, "cats":[]}]
 newModels = train_model(df, "y",100, [2.0], models)
 for newModel in newModels:
  apply_model.explain(newModel)

 df = pd.DataFrame({"x":[1, 995,996,997,998,999,1000],"y":[2,2,2,2,2,2,2]})
 models = [{"BASE_VALUE":1.0,"conts":{"x":[[1,1],[1000,1]]}, "cats":[]}]
 newModels = train_model(df, "y",50, [1.5], models)
 for newModel in newModels:
  apply_model.explain(newModel)

 df = pd.DataFrame({"x":[1,2,3,4],"y":[1+1,2+1.2,3+1.4,4+1.6]})
 models = [{"BASE_VALUE":2,"conts":{"x":[[1,1],[4,1]]}, "cats":[]},{"BASE_VALUE":1,"conts":{"x":[[1,1],[4,1]]}, "cats":[]}]
 newModels = train_model(df, "y",100, [1.5, 1.5], models)
 for newModel in newModels:
  apply_model.explain(newModel)

 df = pd.DataFrame({"x":["cat","dog","cat","mouse","rat"],"y":[2.0,3.0,2.0,1.0,1.5]})
 models = [{"BASE_VALUE":1.0,"conts":{}, "cats":{"x":{"uniques":{"cat":1,"mouse":1,"dog":1},"OTHER":1}}}]
 newModels = train_model(df, "y",100, [0.5], models)
 for newModel in newModels:
  apply_model.explain(newModel)

 df = pd.DataFrame({"x":[1,2,3,4],"y":[1+1,2+1.2,3+1.4,4+1.6]})
 models = [{"BASE_VALUE":2,"conts":{"x":[[1,1],[4,3]]}, "cats":[]},{"BASE_VALUE":1,"conts":{"x":[[1,0.4],[4,0.6]]}, "cats":[]}]
 newModels = train_model(df, "y",100, [0,0], models, 10.0)
 for newModel in newModels:
  apply_model.explain(newModel)


from utils.constants import SECTOR_TYPES, EXIT_FLAGS, PLAYER_FLAGS
from utils.utils import GET_ALL_ROOM_EXITS, HAS_PLR_FLAG, MOB_IN_ROOM, GET_MOBS_IN_ROOM, CAN_SEE

SYMBOLS = {
	'you' : '{c[{b@{c]{n',
	SECTOR_TYPES['SECT_INSIDE'] : '{c[{w.{c]{n',
	SECTOR_TYPES['SECT_CITY'] : '{c[{WC{c]{n',
	SECTOR_TYPES['SECT_FIELD'] : '{c[{g,{c]{n',
	SECTOR_TYPES['SECT_FOREST']: '{c[{gY{c]{n',
	SECTOR_TYPES['SECT_HILLS']: '{c[{Mm{c]{n',
	SECTOR_TYPES['SECT_MOUNT']: '{c[{rM{c]{n',
	SECTOR_TYPES['SECT_SWIM']: '{c[{c~{c]{n',
	SECTOR_TYPES['SECT_SKY']: '{c[{W^{c]{n',
	SECTOR_TYPES['SECT_UNDRWATER']: '{c[{B~{c]{n',
	'HAS_MOB' : '{c[{m!{c]{n'

}

CLOSED = {
	'north' : "___",
	'south': '^^^',
	'east' : '|  ',
	'west' : '  |'
}

class Map(object):

	def __init__(self, ch, max_width=9, max_length=9):
		self.ch = ch
		self.max_width = max_width
		self.max_length = max_length
		self.worm_has_mapped = {}
		self.curX = None
		self.curY = None
		self.isClosed = [False, '']

		#{room: [posx, posy]}
		if self.check_grid():
			self.grid = self.create_grid()
			self.draw_room_on_map(ch.location, ((min(max_width, max_length) - 1) / 2))

	def update_pos(self, room, exit_name):
		#self.ch.msg("%r" % exit_name)
		self.curX, self.curY = self.worm_has_mapped[room][0], self.worm_has_mapped[room][1]
		if exit_name == 'east':
			self.curY += 1
		elif exit_name == 'west':
			self.curY -= 1
		elif exit_name == 'north':
			self.curX -= 1
		elif exit_name == 'south':
			self.curX += 1

	def draw_room_on_map(self, room, max_distance):
		closed_door = self.draw(room)
		if closed_door: max_distance = 0
		if max_distance == 0:
			#self.ch.msg("%r" % self.worm_has_mapped)
			#self.ch.msg("returning")
			return

		for Exit in GET_ALL_ROOM_EXITS(room):
			#self.ch.msg("%r leads to %r" % (Exit, Exit.destination))
			if self.has_drawn(Exit.destination): continue
			if Exit.name.lower() == 'up' or Exit.name.lower() == 'down': continue

			if not HAS_PLR_FLAG(self.ch, PLAYER_FLAGS['REDIT']):
				if EXIT_FLAGS['HIDDEN'] in Exit.db.exit_flags: continue

			if Exit.db.door_open is False:
				self.isClosed = [True, Exit.name.lower()]

			self.update_pos(room, Exit.name.lower())
			self.draw_room_on_map(Exit.destination, max_distance - 1)

	def draw(self, room):
		# first draw initial ch location on map
		if room == self.ch.location:
			self.start_loc_on_grid()
			self.worm_has_mapped[room] = [self.curX, self.curY]
			return
		self.worm_has_mapped[room] = [self.curX, self.curY]

		if self.curX == self.origX and self.curY == self.origY: return
		#self.ch.msg("%r" % self.worm_has_mapped[room])

		see_mobs = False
		if MOB_IN_ROOM(room):
			for mob in GET_MOBS_IN_ROOM(room):
				if CAN_SEE(self.ch, mob):
					see_mobs = True

		if see_mobs:
			self.grid[self.curX][self.curY] = SYMBOLS['HAS_MOB']
		else:
			self.grid[self.curX][self.curY] = SYMBOLS[room.db.sector_type]

		if self.isClosed[0]:
			self.grid[self.curX][self.curY] = CLOSED[self.isClosed[1]]
			self.isClosed = [False, ""]
			return True

	def start_loc_on_grid(self):
		x = self.median(self.max_width)
		y = self.median(self.max_length)
		self.grid[int(x)][int(y)] = SYMBOLS['you']
		self.curX = int(x); self.curY = int(y)
		self.origX = int(x); self.origY = int(y)
		#self.ch.msg("%r %r" % (self.curX, self.curY))

	def has_drawn(self, room):
		# check to see if drawn room is in list of drawn rooms
		# return true or false
		return True if room in self.worm_has_mapped.keys() else False

	def median(self, num):
		lst = sorted(range(0, num))
		n = len(lst)
		m = n -1
		return (lst[n/2] + lst[m/2]) / 2.0

	def check_grid(self):
		# pass check to see if maxw and maxl are prime numbers:
		if self.max_length % 2 != 0 or self.max_width % 2 != 0: return True
		else: return False

	def create_grid(self):
		board = []
		for row in range(self.max_width):
			board.append([])
			for column in range(self.max_length):
				board[row].append('   ')
		return board

	def show_map(self):
		map_string = ""
		for row in self.grid:
			map_string += "".join(row)
			map_string += "\n"

		return map_string
		#self.ch.msg("%s" % map_string)

class WorldMap(object):
	"""
	This will be the world map where players can traverse through tamriel
	"""
	pass


from google.protobuf.internal.enum_type_wrapper import EnumTypeWrapper
from ipywidgets import interact, FloatText
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from copy import deepcopy

# Pour récupérer les données
import numpy as np
import matplotlib.pyplot as plt
import csv

def extraction_csv(nom_fichier, n):

    # ouverture du fichier

    fichier = open(nom_fichier, 'r')

    # Lecture du fichier

    contenu = csv.reader(fichier, delimiter=";")

    # Définition de nos tableau d'entree

    investissement = []
    cout_tonne_remuee = []
    ratio_sterile = []
    cout_traitement = []
    charges_fixes = []
    prix_or = []
    taux_recuperation_or = []
    prop_or_paye_dore = []
    nombre_grammes_once = []
    taux_actualisation = []
    tonnage_geol = []
    teneur_minerai_geol = []
    taux_recup = []
    dilution_minerai = []
    rythme_prod_annee = []
    premiere_annee_prod = []

    # Récupération des données sous forme de listes

    for row in contenu:

        if row[0] == "Tonnage de minerai geologique":
            tonnage_geol.append(float(row[2]))
        if row[0] == "Teneur du minerai geologique":
            teneur_minerai_geol.append(float(row[2]))
        if row[0] == "Taux de recuperation du gisement":
            taux_recup.append(float(row[2]))
        if row[0] == "Dilution du minerai":
            dilution_minerai.append(float(row[2]))
        if row[0] == "Rythme de production annuelle de minerai":
            rythme_prod_annee.append(float(row[2]))
        if row[0] == "Premiere annee de production":
            premiere_annee_prod.append(float(row[2]))
        if row[0] == "Investissement initial pour l'exploitation":
            investissement.append(float(row[2]))
        if row[0] == "Cout par tonne remuee dans la mine a ciel ouvert":
            cout_tonne_remuee.append(float(row[2]))
        if row[0] == "Ratio sterile sur minerai dans la mine a ciel ouvert":
            ratio_sterile.append(float(row[2]))
        if row[0] == "Cout de traitement par tonne de minerai":

            cout_traitement.append(float(row[2]))
        if row[0] == "Charges fixes annuelles":
            charges_fixes.append(float(row[2]))
        if row[0] == "Prix de vente de l'or":
            prix_or.append(float(row[2]))
        if row[0] == "Taux de recuperation de l'or dans le traitement":
            taux_recuperation_or.append(float(row[2]))
        if row[0] == "Proportion d'or paye dans le dore":
            prop_or_paye_dore.append(float(row[2]))
        if row[0] == "Nombre de grammes dans une once":
            nombre_grammes_once.append(float(row[2]))
        if row[0] == "Taux d'actualisation":
            taux_actualisation.append(float(row[2]))
    fichier.close()

    # On prend des valeurs constantes dans un premier temps sur n années.
    for i in range(n-1):
        investissement.append(0)
    investissement = np.array(investissement)
    cout_tonne_remuee = np.array(n*cout_tonne_remuee)
    ratio_sterile = np.array(n*ratio_sterile)
    cout_traitement = np.array(n*cout_traitement)
    charges_fixes = np.array(n*charges_fixes)
    prix_or = np.array(n*prix_or)
    taux_recuperation_or = np.array(n*taux_recuperation_or)
    prop_or_paye_dore = np.array(n*prop_or_paye_dore)
    nombre_grammes_once = np.array(n*nombre_grammes_once)
    taux_actualisation = np.array(n*taux_actualisation)
    tonnage_geol = np.array(n*tonnage_geol)
    teneur_minerai_geol = np.array(n*teneur_minerai_geol)
    taux_recup = np.array(n*taux_recup)
    dilution_minerai = np.array(n*dilution_minerai)
    premiere_annee_prod = np.array(n*premiere_annee_prod)
    rythme_prod_annee = np.array(n*rythme_prod_annee)
    for j in range(0,int(premiere_annee_prod[0])):
        rythme_prod_annee[j]=0
    retour = np.zeros(n)
    tonnage_indus = tonnage_geol * taux_recup/100 * (dilution_minerai/100 + np.ones(n))
    retour[0] += tonnage_indus[0]

    k=1
    while k<n and (retour[k-1]-rythme_prod_annee[k-1])>=0:
        retour [k]=retour[k-1]-rythme_prod_annee[k-1]
        k+=1
    if retour[k-1]-rythme_prod_annee[k-1]<0:
        rythme_prod_annee[k-1]=retour[k-1]
        for i in range(k,n):
            retour[i]=0
            rythme_prod_annee[i]=0

    # Creation du dictionnaire

    entree = {}
    entree["investissement"] = investissement
    entree["cout_tonne_remuee"] = cout_tonne_remuee
    entree["ratio_sterile"] = ratio_sterile
    entree["cout_traitement"] = cout_traitement
    entree["charges_fixes"] = charges_fixes
    entree["prix_or"] = prix_or
    entree["taux_recuperation_or"] = taux_recuperation_or
    entree["prop_or_paye_dore"] = prop_or_paye_dore
    entree["nombre_grammes_once"] = nombre_grammes_once
    entree["taux_actualisation"] = taux_actualisation
    entree["tonnage_geol"] = tonnage_geol
    entree["teneur_minerai_geol"] = teneur_minerai_geol
    entree["taux_recup"] = taux_recup
    entree["dilution_minerai"] = dilution_minerai
    entree["rythme_prod_annee"] = rythme_prod_annee
    entree["premiere_annee_prod"] = premiere_annee_prod

    return entree

class entree:
    def __init__(self, params):
        self.n = len(params.get('ratio_sterile'))
        self.investissement = params.get('investissement')
        self.cout_tonne_remuee = params.get('cout_tonne_remuee')
        self.ratio_sterile = params.get('ratio_sterile')
        self.cout_traitement = params.get('cout_traitement')
        self.charges_fixes = params.get('charges_fixes')
        self.prix_or = params.get('prix_or')
        self.taux_recuperation_or = params.get('taux_recuperation_or')
        self.prop_or_paye_dore = params.get('prop_or_paye_dore')
        self.nombre_grammes_once = params.get('nombre_grammes_once')
        self.taux_actualisation = params.get('taux_actualisation')
        self.tonnage_geol = params.get('tonnage_geol')
        self.teneur_minerai_geol = params.get('teneur_minerai_geol')
        self.taux_recup = params.get('taux_recup')
        self.dilution_minerai = params.get('dilution_minerai')
        self.rythme_prod_annee = params.get('rythme_prod_annee')
        self.premiere_annee_prod = params.get('premiere_annee_prod')

    def __repr__(self):
        return f"** investissement initiale pour l'exploitation ** : {self.investissement[0]} M$  , \n \n  ** prix de l'or ** = {self.prix_or[0]} $/oz, \n \
            \n ** Ratio sterile sur minerai dans la mine à ciel ouvert ** = {self.ratio_sterile[0]},\n \
    \n  ** Teneur du minerai geologique ** = {self.teneur_minerai_geol[0]} g/t,  \n \n  ** Taux de récuperation du gisement ** = {self.taux_recup[0]} %,\n \n ** Dilution du minerai ** = {self.dilution_minerai[0]}, \n \n  **  Rythme de production annuelle de minerai ** = {self.rythme_prod_annee[0]} Mt/an,\n \n ** Coût par tonne remuee dans la mine à ciel ouvert ** = {self.cout_tonne_remuee[0]} $/t roche, \n \n ** Taux d'actualisation ** = {self.taux_actualisation[0]} % \n \n ** Charges fixes annuelles ** = {self.charges_fixes[0]} M$/an. "

    def cout_exploitation_tonne_minerai(self):
        return self.cout_tonne_remuee * (self.ratio_sterile + np.ones(self.n))

    def teneur_minerai_industriel(self):
        return self.teneur_minerai_geol/(self.dilution_minerai/100 + np.ones(self.n))

    def tonnage_industriel(self):
        return self.tonnage_geol * self.taux_recup/100 * (self.dilution_minerai/100 + np.ones(self.n))

    def qte_or_paye(self):
        return self.teneur_minerai_industriel() * self.taux_recuperation_or/100 * self.prop_or_paye_dore/100

    def recette_tonne_minerai(self):
        return self.qte_or_paye() * self.prix_or / self.nombre_grammes_once

    def dep_operatoiresMCO(self):
        return self.rythme_prod_annee * self.cout_exploitation_tonne_minerai()

    def dep_operatoiresTraitement(self):
        return self.rythme_prod_annee * self.cout_traitement

    def charges_fixes_(self):
        k=1
        token = True
        for j in range(1,self.n):
            if self.rythme_prod_annee[j]==0 and token:
                k=j
                token = False
        if k==1:
            new = np.copy(self.charges_fixes)
            new[0]=0
            for j in range(1,self.n):
                new[j]=self.charges_fixes[1]
            return new
        else:
            new = np.copy(self.charges_fixes)
            new[0]=0
            new[k-1]=self.charges_fixes[0]*self.rythme_prod_annee[k-1]/self.rythme_prod_annee[k-2]
            for j in range(k,self.n):
                new[j]=0
            return new

    def dep_operatoiresTotale(self):
        return self.charges_fixes_() + self.dep_operatoiresTraitement() + self.dep_operatoiresMCO()

    def recette(self):
        return self.rythme_prod_annee * self.recette_tonne_minerai()

    def cash_flow(self):
        cash = self.recette() - self.dep_operatoiresTotale()-self.investissement
        return cash

# investissement pas pris en compte, revoir formule

    def cumul_cash_flow(self):
        cumul = self.cash_flow()
        sortie = np.zeros(self.n)

        for i in range(self.n):
            sortie[i] = np.sum(cumul[:i])
        return sortie

    def taux_actualisation_(self):
        actua = 1 / (np.ones(self.n) + self.taux_actualisation/100)
        final = np.zeros(self.n)
        N = len(actua)
        for i in range(N):
            final[i] = np.product(actua[:i])
        return final

    def cash_flow_actu(self):
        CF = self.cash_flow()
        facteur = self.taux_actualisation_()
        CFA = np.copy(CF)
        return facteur * CFA

    def cumul_cash_flow_actu(self):
        cumul = self.cash_flow_actu()
        sortie = np.zeros(self.n)
        N = len(cumul)
        for i in range(N):
            sortie[i] = np.sum(cumul[:i])
        return sortie

    def dri(self):
        cumul = self.cumul_cash_flow_actu()
        dr = 0
        while dr < self.n:
            if cumul[dr] >= 0:
                return dr
            else:
                dr += 1
        return -1         # -1 pour signaler que le délai de retour n'est jamais atteint

    def tri(self):
        N = self.n
        Tri=[]
        CF = self.cash_flow()
        for i in range(N):
            a = 0.0
            b = 0.35
            c = (a+b)/2
            epsilon = 0.1
            k = 0 #nombre itération
            p = 100
            def f(x):
                taux = np.zeros(self.n) #initialisation
                for k in range(N):
                    taux[k] = 1/(1+x)**k
                actu = taux * CF
                return np.sum(actu[:i])
            if f(b)*f(a) < 0:
                while abs(f(c)) > epsilon and k <p:
                    if f(c)*f(a) > 0 :
                        a = c
                        c = (b+c)/2

                    else :
                        b = c
                        c= (a+c)/2
                    k += 1
                tri = c
                Tri.append(tri)
            else : Tri.append(0)
        return Tri


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

# Enregistrement Materiel
class Materiel:

    def __init__(self):
        self.marque = ""
        self.modele = ""
        self.numero_serie = ""
        self.numero_tag = ""
        self.materiel = []

    def enregistrement_materiel(self):
        print("Materiel")
        self.marque = input("Entrée la marque: ")
        self.modele = input("Entrée le modèle: ")
        self.numero_serie = input("Entrée le numéro de sèrie: ")
        self.numero_tag = input("Entrée le numéro de Tag: ")
        self.materiel =[self.marque, self.modele, self.numero_serie, self.numero_tag]

    def modification_materiel(self):

        self.marque = input("Entrée la marque a modifier:")
        self.modele = input("Entrée le modèle a modifier:")
        self.numero_serie = input("Entrée le numéro de sèrie à modifier: ")
        self.numero_tag = input("Entrée le numéro de Tag à modifier: ")
        self.materiel = [self.marque,self.modele,self.numero_serie,self.numero_tag]

    def effacement_materiel(self):
        self.nLigneEff = int(input("Entrée la ligne à efffacer: "))
        self.nLigneEff = str(self.nLigneEff)  # transforme le nLigneEff en string

# Suivi du materiel
class Suivi(Materiel):

    def __init__(self):
        self.date_envoi = ""
        self.date_reception = ""
        self.status_envoi = "En-cours de réparation"

    def envoi_materiel(self):
        self.enregistrement_materiel()
        self.date_envoi = input("Entrée la date d'envoi:")
        self.materiel.append(self.date_envoi)
        self.date_reception = ""
        self.materiel.append(self.date_reception)
        self.status_envoi = "En-cours de réparation"
        self.materiel.append(self.status_envoi)
    def recu_materiel(self):
        self.date_reception = input("Entrée la date de récéption: ")

# Stockage de materiel dans la base donnée sqlite3
class Base_Donnee_Materiel(Suivi):

    def __init__(self):
        self.db_materiel = "DbTest3.db"
        self.connection_db = sqlite3.connect(self.db_materiel)
        self.curso_db_materiel = self.connection_db.cursor()

    def creation_db_materiel(self):

        # Création de table Materiel
        try:
            self.curso_db_materiel.execute('''CREATE TABLE STOCK_MATERIEL
                                       (
                                       Marque VARCHAR(50),
                                       Modele VARCHAR(50),
                                       Numero_Serie VARCHAR(50),
                                       Numero_Tag VARCHAR(50),
                                       Date_Envoi DATE,
                                       Date_Reception DATE,
                                       Status VARCHAR(100)
                                       )''')
            self.connection_db.commit()
        except sqlite3.OperationalError:
            print("Table exite déja !!!")
    @property
    def affichage_db_materiel(self):
        nligne = 1
        for db in self.curso_db_materiel.execute("SELECT * FROM STOCK_MATERIEL"):
            print("{}  | {} ".format(nligne, db))
            nligne = nligne + 1

    # Enregistrement d'un materriel dans la base donnée
    def enregistrement_materiel_db(self):
        self.envoi_materiel()
        self.curso_db_materiel.execute('''INSERT INTO STOCK_MATERIEL (
        Marque,
        Modele,
        Numero_Serie,
        Numero_Tag,
        Date_Envoi,
        Date_Reception,
        Status
        ) VALUES(?,?,?,?,?,?,?)''',(
            self.materiel[0],
            self.materiel[1],
            self.materiel[2],
            self.materiel[3],
            self.materiel[4],
            self.materiel[5],
            self.materiel[6]))
        self.connection_db.commit()

    # Modification d'un materriel dans la base donnée
    def modification_materiel_db(self):
        self.affichage_db_materiel
        self.ligneModifier = int(input("Entrée la ligne à modifier: "))
        self.modification_materiel()
        self.date_envoi =  input("Entrée nouvelle date d'envoi: ")
        self.date_reception = ""
        self.materiel.append(self.date_envoi)
        self.materiel.append(self.date_reception)
        self.status_envoi = "En-cours de réparation"
        self.materiel.append(self.status_envoi)
        self.materiel.append(self.ligneModifier)

        print(self.materiel)
        self.curso_db_materiel.execute('''UPDATE STOCK_MATERIEl SET
        Marque = ?,
        Modele = ?,
        Numero_Serie = ?,
        Numero_Tag = ?,
        Date_Envoi = ?,
        Date_Reception = ?,
        Status = ? WHERE rowid = ?
        ''',(self.materiel[0],
            self.materiel[1],
            self.materiel[2],
            self.materiel[3],
            self.materiel[4],
            self.materiel[5],
            self.materiel[6],
            self.materiel[7]))
        self.connection_db.commit()
        self.affichage_db_materiel
    # Effacement d'un materriel dans la base donnée
    def effacement_materiel_db(self):
        self.effacement_materiel()
        for lgDel in self.curso_db_materiel.execute('''SELECT * FROM STOCK_MATERIEL WHERE rowid = ?''',(self.nLigneEff)):
            print(f"{lgDel}")
        print("Etre vous sur de vouloir supprimer cette ligne ")
        print(" OUI ou NON ")
        print("Tapez O pour oui ,N pour non")
        self.qtVerfEff = str(input(": ")).upper()
        if self.qtVerfEff == "O":
            self.curso_db_materiel.execute('''DELETE FROM STOCK_MATERIEL WHERE rowid = ?''',(self.nLigneEff))
            self.connection_db.commit()
        else:
            pass

def main():
    try:
     #testEnvvoi = Suivi()
     #testEnvvoi.envoi_materiel()
     testBD = Base_Donnee_Materiel()
     testBD.creation_db_materiel()
     testBD.affichage_db_materiel
     testBD.enregistrement_materiel_db()

     testBD.effacement_materiel_db()
    except KeyboardInterrupt:
        print("\nstop de l'APP")

# Execution de l'application

main()


r"""
Limongi & Chieffi (2018), ApJS, 237, 13 core collapse supernova (CCSN) yields

**Signature**: from vice.yields.ccsne import LC18

Importing this module will automatically set the CCSN yield settings for all
elements to the IMF-averaged yields calculated with the Limongi & Chieffi
(2018) yield table for [M/H] = 0 stars. This will adopt an upper mass limit of
100 :math:`M_\odot`.

.. tip:: By importing this module, the user does not sacrifice the ability to
	specify their yield settings directly.

.. note:: This module is not imported with a simple ``import vice`` statement.

Contents
--------
set_params : <function>
	Update the parameters with which the yields are calculated
"""

from __future__ import absolute_import
try:
	__VICE_SETUP__
except NameError:
	__VICE_SETUP__ = False

if not __VICE_SETUP__:

	__all__ = ["set_params", "test"]
	from ...._globals import _RECOGNIZED_ELEMENTS_
	from .. import fractional as __fractional
	from .. import settings as __settings
	from .tests import test

	def set_params(**kwargs):
		r"""
		Update the parameters with which the yields are calculated from the
		Limongi & Chieffi (2018) [1]_ data.

		**Signature**: vice.yields.ccsne.LC18.set_params(\*\*kwargs)

		Parameters
		----------
		kwargs : varying types
			Keyword arguments to pass to vice.yields.ccsne.fractional.

		Raises
		------
		* TypeError
			- 	Received a keyword argument "study". This will always be "LC18"
				when called from this module.

		Other exceptions are raised by vice.yields.ccsne.fractional.

		Example Code
		------------
		>>> import vice
		>>> from vice.yields.ccsne import LC18
		>>> LC18.set_params(m_lower = 0.3, m_upper = 40, IMF = "salpeter")

		.. seealso:: vice.yields.ccsne.fractional

		.. [1] Limongi & Chieffi (2018), ApJS, 237, 17
		"""
		if "study" in kwargs.keys():
			raise TypeError("Got an unexpected keyword argument: 'study'")
		else:
			for i in range(len(_RECOGNIZED_ELEMENTS_)):
				__settings[_RECOGNIZED_ELEMENTS_[i]] = __fractional(
					_RECOGNIZED_ELEMENTS_[i], study = "LC18", **kwargs)[0]

	set_params()

else:
	pass


# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt

from __future__ import unicode_literals
import frappe
from frappe import _

no_cache = 1

def get_context(context):
	if frappe.session.user=='Guest':
		context['start_btn'] = 'Anmelden'
	else:
		user = frappe.session.user
		context["me"] = True
		context["user_data"] = frappe.get_doc("User", frappe.session.user)
		spieler = frappe.db.sql("""SELECT `name` FROM `tabTeamPlaner Mitglied` WHERE `mail` = '{user}'""".format(user=frappe.session.user), as_dict=True)
		context["spieler_data"] = frappe.get_doc("TeamPlaner Mitglied", spieler[0].name)
	return context


"""Contains the `SlepianNoiseSouthAmerica` class."""
import numpy as np
import numpy.typing as npt
import pydantic

import sleplet._string_methods
import sleplet._validation
import sleplet.functions.slepian_south_america
import sleplet.noise
import sleplet.slepian.region
from sleplet.functions.fp import Fp

@pydantic.dataclasses.dataclass(config=sleplet._validation.Validation, kw_only=True)
class SlepianNoiseSouthAmerica(Fp):
    """
    Creates a noised Slepian region on the topographic map of the Earth of the
    South America region.
    """

    SNR: float = -10
    """A parameter which controls the level of signal-to-noise in the noised
    data."""

    def __post_init_post_parse__(self) -> None:
        super().__post_init_post_parse__()
        if (
            isinstance(self.region, sleplet.slepian.region.Region)
            and self.region.name_ending != "south_america"
        ):
            raise RuntimeError("Slepian region selected must be 'south_america'")

    def _create_coefficients(self) -> npt.NDArray[np.complex_ | np.float_]:
        sa = sleplet.functions.slepian_south_america.SlepianSouthAmerica(
            self.L,
            region=self.region,
            smoothing=self.smoothing,
        )
        noise = sleplet.noise._create_slepian_noise(
            self.L,
            sa.coefficients,
            self.slepian,
            self.SNR,
        )
        sleplet.noise.compute_snr(sa.coefficients, noise, "Slepian")
        return noise

    def _create_name(self) -> str:
        return (
            f"{sleplet._string_methods._convert_camel_case_to_snake_case(self.__class__.__name__)}"
            f"{sleplet._string_methods.filename_args(self.SNR, 'snr')}"
        )

    def _set_reality(self) -> bool:
        return False

    def _set_spin(self) -> int:
        return 0

    def _setup_args(self) -> None:
        if isinstance(self.extra_args, list):
            num_args = 1
            if len(self.extra_args) != num_args:
                raise ValueError(f"The number of extra arguments should be {num_args}")
            self.SNR = self.extra_args[0]


#
# Copyright (c) 2017, Prometheus Research, LLC
#

from rex.core import Extension

from ..util import record_to_dict
from ..validators import AssessmentDefinitionVal

__all__ = (
    'Definer',
)

class Definer(Extension):
    """
    An extension that allows developers to write code that in turn allows
    configuration authors to inject configurations segments into their
    definition that are determined at Mart creation time.
    """

    # The identifier of this Definer that configurations will use to invoke it.
    name = None

    @classmethod
    def enabled(cls):
        return cls.name is not None

    @classmethod
    def signature(cls):
        return cls.name

    @classmethod
    def get_assessments(cls, definer, definition, **options):
        """
        Retrieves Assessment definitions for the specified Mart Definition
        using the specified Definer. All definitions are validated and
        normalized.

        :param definer: the Definer to user
        :type definer: str
        :param definition:
            the Mart Definition to retrieve Assessment definitions for
        :type str: dict
        :rtype: list of dicts
        """

        assessments = cls.mapped()[definer]().assessments(
            definition,
            **options
        )

        validate = AssessmentDefinitionVal()
        return [
            record_to_dict(validate(assessment))
            for assessment in assessments
        ]

    def assessments(self, definition, **options):
        """
        Retrieves the Assessment definitions to use with the specified Mart
        Definition.

        This can/should be implemented by extensions.

        :param definition:
            the Mart Definition to retrieve Assessment definitions for
        :type str: dict
        :rtype: list of dicts
        """

        # pylint: disable=unused-argument,no-self-use

        return []  # pragma: no cover


# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
from typing import Dict, Any, Optional
import logging

from transformer_wikitext2.benchmark_definitions import benchmark_definitions
from syne_tune.experiments import ComparativeResults, PlotParameters, SubplotParameters

TMLR10_SETUPS = [
    "2 workers",
    "4 workers",
    "8 workers",
]

def metadata_to_setup(metadata: Dict[str, Any]) -> Optional[str]:
    return f"{metadata['n_workers']} workers"

TMLR10_METHOD_TO_SUBPLOT = {
    "RS": 0,
    "BO": 1,
    "ASHA": 2,
    "MOBSTER": 3,
}

def metadata_to_subplot(metadata: dict) -> Optional[int]:
    return TMLR10_METHOD_TO_SUBPLOT[metadata["algorithm"]]

if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)
    experiment_names = ("tmlr-10",)
    num_runs = 5
    download_from_s3 = False  # Set ``True`` in order to download files from S3
    # Plot parameters across all benchmarks
    plot_params = PlotParameters(
        xlabel="wall-clock time",
        aggregate_mode="iqm_bootstrap",
        grid=True,
    )
    # We would like to have 4 subfigures, one for each method
    plot_params.subplots = SubplotParameters(
        nrows=2,
        ncols=2,
        kwargs=dict(sharex="all", sharey="all"),
        titles=["RS", "BO", "ASHA", "MOBSTER"],
        title_each_figure=True,
        legend_no=[0],
    )
    # The creation of ``results`` downloads files from S3 (only if
    # ``download_from_s3 == True``), reads the metadata and creates an inverse
    # index. If any result files are missing, or there are too many of them,
    # warning messages are printed
    results = ComparativeResults(
        experiment_names=experiment_names,
        setups=TMLR10_SETUPS,
        num_runs=num_runs,
        metadata_to_setup=metadata_to_setup,
        plot_params=plot_params,
        metadata_to_subplot=metadata_to_subplot,
        download_from_s3=download_from_s3,
    )
    # Create comparative plot (single panel)
    benchmark_name = "transformer_wikitext2"
    benchmark = benchmark_definitions(sagemaker_backend=True)[benchmark_name]
    # These parameters overwrite those given at construction
    plot_params = PlotParameters(
        metric=benchmark.metric,
        mode=benchmark.mode,
        ylim=(5, 8),
    )
    results.plot(
        benchmark_name=benchmark_name,
        plot_params=plot_params,
        file_name=f"./odsc-comparison-sagemaker-{benchmark_name}.png",
    )


def Remove(duplicate):
    final_list = []
    for num in duplicate:
        if num not in final_list:
            final_list.append(num)
    return final_list
wordstring = input('Enter the string: ')
words = wordstring.split()
wordlist=[]
for i in words:
    wordlist.append(i.lower())
wordlist.sort()
word=[]
for w in wordlist:
    x=[w,wordlist.count(w)]
    word.append(x)
for i in Remove(word):
    for x in range(0,len(i),2):
        print(i[x],'',i[x+1])


"""How to start with NumPy

    * special arrays creation
    * random arrays
    * index slicing and making a copy from original"""

import numpy as np

def general():
    """Rank 1 aray"""
    first = np.array([0, 1.2, 2, 3, 4, 5])

    print(first.dtype)
    print(first.shape)
    print(type(first), "\n")

def special_type():
    """Different types of array construction"""
    zero = np.zeros((3, 4))
    print(zero, "\n")

    full = np.full((2, 3), 3.4)
    print(full, "\n")

    one = np.ones((3, 3))
    print(one)

# generates an array of values between:[0,1)
foo = np.random.random((4, 3))
print(foo, "\n")

# generates a array of integers of specified size with range: [low, high)
bar = np.random.randint(low=-5, high=6, size=(2, 3))
print(bar, "\n")

# generate a array of floats
uni = np.random.uniform(low=2, high=3, size=(3, 3))
print(uni, "\n")

def slicing():
    """or slice indexing, it just gives a refrence of that slice to new variable

    changing an element can change underlying array, to create a new copy
    see copy_slicing in this function, it does not change the underlying array"""

    original = np.array([[00, 1, 2, 3],
                        [10, 11, 12, 13],
                        [20, 21, 22, 23],
                         [31, 32, 33, 34]])

    # print(original,"\n")

    ex1 = original[1, :]
    print("Rank 1 array:\n", ex1, ex1.shape, "\n")

    print('Refrence Slicing (changes original array)')
    refrence_slice = original[1:3, 1:]
    print(refrence_slice)
    refrence_slice[1, 1] = -999
    print(refrence_slice, "\n")

    print('copy slicing (did not change original array)')
    copy_slice = np.array(original[1:3, 1:])
    copy_slice[1, 2] = -888
    print(copy_slice)
    print(original)

if __name__ == '__main__':

    general()
    special_type()
    slicing()


#!/usr/bin/env python
"""The setup script."""
import codecs
import os

from setuptools import setup, find_packages

def _get_tag():
    return os.getenv("TAG", "dev")

with codecs.open("README.md", "r", "utf-8") as readme_file:
    readme = readme_file.read()

with open("requirements.txt") as reqs:
    requirements = [line.strip() for line in reqs]

with open("requirements-dev.txt") as reqs:
    requirements_dev = [line.strip() for line in reqs if "requirements.txt" not in line.strip()]

setup(
    name="eduzen_bot",
    version=_get_tag(),
    # cmdclass=versioneer.get_cmdclass(),
    url="https://github.com/eduzen/bot",
    description="This is the eduzen_bot for telegram",
    long_description=readme,
    author="eduzen",
    author_email="eduardo.a.enriquez@gmail.com",
    packages=find_packages(include=["eduzen_bot*"]),
    include_package_data=True,
    install_requires=requirements,
    keywords="eduzen_bot",
    classifiers=[
        "Development Status :: 2 - Pre-Alpha",
        "Intended Audience :: Developers",
        "Natural Language :: Spanish",
        "Programming Language :: Python :: 3.6",
    ],
    test_suite="tests",
    tests_require=requirements + requirements_dev,
    entry_points={"database_scripts": ["initialize_db = eduzen_bot.scripts.initialize_db:main"]},
)


# -*- coding: utf-8 -*-

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.oauth import OAuth
from flask.ext.login import LoginManager

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view='login_facebook'

oauth = OAuth()

facebook = oauth.remote_app('facebook',
                            base_url='https://graph.facebook.com/',
                            request_token_url = None,
                            access_token_url='/oauth/access_token',
                            authorize_url='https://www.facebook.com/dialog/oauth',
                            consumer_key = app.config['FACEBOOK_APP_ID'],
                            consumer_secret = app.config['FACEBOOK_APP_SECRET'],
                            request_token_params = {'scope': 'email'}
)

from app import views, models, plugview