import simpy
import random
from collections import deque

from framework.utils import Location
from framework.Node import Node, EnergyProfile
from framework.Gateway import Gateway
from framework.TransmissionInterface import AirInterface
from framework.Backend import Server, Application
from framework.LoRaParameters import LoRaParameters
from framework.Environment import *
import os.path
import pickle

class Simulation:
    ENVIRONMENT_TYPE = ["temp"]

    def __init__(self, nodes_positions, gateway_positions, step_time, connection, config_name, distance, num_steps, environment="temp", offset=2000, update_rate = UPDATA_RATE):
        self.nodes = []
        self.gateways = []
        assert step_time >= offset + 3000
        self.step_time = step_time
        self.offset = offset
        self.steps = 0
        self.name = config_name + "_update_" + str(update_rate)
        self.update_rate = update_rate
        self.num_steps = num_steps
        self.sim_env = simpy.Environment()
        self.channel_nodes = {}
        for channel in range(Gateway.NO_CHANNELS):
            self.channel_nodes[channel] = []
        assert environment in Simulation.ENVIRONMENT_TYPE
        if environment == "temp":
            self.environment = TempEnvironment( Location(distance, -distance),
                                               Location(-distance, distance), 296.15, self.num_steps * self.step_time, update_rate, dx=GRID)
        else:
            assert False, "%s environment is not implemented" %(environment)
        link = []
        for loc in connection:
            for l2 in connection[loc]:
                link.append([nodes_positions.index(loc), nodes_positions.index(l2)])
        self.app = Application(list(range(len(nodes_positions))), link, update_rate)
        self.server = Server(self.gateways, self.sim_env, self.app)
        self.air_interface = AirInterface(self.sim_env, self.gateways, self.server)
        config_file = './config/'+config_name+'_lora_'+ str(Gateway.NO_CHANNELS) +'.pickle'
        lora_para_exist = False
        # if os.path.exists(config_file):
        if False:
            lora_para = pickle.load(open(config_file, 'rb'))
            lora_para_exist = True
        else:
            lora_para_exist = True
            lora_para = [ LoRaParameters(i % Gateway.NO_CHANNELS, sf=9 + i %2) for i in range(len(nodes_positions))]
        for i in range(len(nodes_positions)):
            node = Node(i, EnergyProfile(0.1), lora_para[i],
                                   self.air_interface, self.sim_env, nodes_positions[i], True)
            self.channel_nodes[lora_para[i].channel].append(node)
            node.last_payload_sent = self.environment.sense(nodes_positions[i], self.sim_env.now)
            self.nodes.append(node)
        for i in range(len(gateway_positions)):
            self.gateways.append(Gateway(i, gateway_positions[i], self.sim_env))

        self.constructed_field = {}
        self.real_field = {}
        self.temp_field = None

        if not lora_para_exist:
            print("Start generating new lora configuration file for " + config_name)
            self.pre_adr(1000, True, percentage=0.4)
            pickle.dump([n.para for n in self.nodes], open(config_file, 'wb'))
            self.reset()

    def node_states(self, *args, **kwargs):
        return list(a.get_status(*args, **kwargs) for a in self.nodes)

    def step(self, actions):
        assert len(self.nodes) == len(actions)
        assert self.sim_env.now == self.steps * self.step_time
        self.constructed_field = self.field_reconstruction()
        self.temp_field = self.environment.T_field[int(self.sim_env.now//self.update_rate)]
        self.steps += 1
        send_index = [idx for idx, send in enumerate(actions) if send]
        for i in range(len(self.nodes)):
            self.sim_env.process(self._node_send_sensed_value(i, actions[i]))
        self.sim_env.run(self.step_time * self.steps)
        received = []
        for i in send_index:
            if self.nodes[i].packet_to_send.received:
                received.append(i)
                # if self.nodes[i].last_payload_change:
                #     reward += np.exp(-20/np.absolute(self.nodes[i].last_payload_change))
        return send_index, received

    def _node_send_sensed_value(self, node_index, send):
        node = self.nodes[node_index]
        value = node.sense(self.environment)
        self.real_field[node_index] = value
        time = self.sim_env.now
        yield self.sim_env.timeout(np.random.randint(self.offset))
        if send:
            packet = node.create_unique_packet({'value':value, 'time': time}, False, False)
            yield self.sim_env.process(node.send(packet))
        yield self.sim_env.timeout(self.step_time * self.steps - self.sim_env.now)

    def _node_send_test(self, node_index):
        yield self.sim_env.timeout(np.random.randint(self.offset))
        node = self.nodes[node_index]
        packet = node.create_unique_packet(None, True, True)
        yield self.sim_env.process(node.send(packet))
        yield self.sim_env.timeout(self.step_time * self.steps - self.sim_env.now)

    def pre_adr(self, rounds: int, show=False, percentage=0.8):
        assert rounds > 50
        N = int(len(self.nodes) * percentage)
        for i in range(len(self.nodes)):
            self.nodes[i].adr = True
        record_per = []
        for i in range(rounds):
            assert self.sim_env.now == self.steps * self.step_time
            self.steps += 1
            send = []
            for channel in self.channel_nodes:
                list_of_nodes = self.channel_nodes[channel]
                send.extend(random.sample(list_of_nodes, int(percentage*len(list_of_nodes))))
            send_node = [n.id for n in send]
            for j in send_node:
                self.sim_env.process(self._node_send_test(j))
            self.sim_env.run(self.step_time * self.steps)
            count = 0
            for j, idx in enumerate(send_node):
                if self.nodes[idx].last_packet_success:
                    count += 1
            record_per.append(1 - count/len(send_node))
        latest_per = record_per[-50:]

        count = 0
        threshold = 0.3
        while not self._check_adr_convergence(latest_per, threshold):
            for i in range(50):
                assert self.sim_env.now == self.steps * self.step_time
                self.steps += 1
                send_node = random.sample(range(len(self.nodes)), N)
                for j in send_node:
                    self.sim_env.process(self._node_send_test(j))
                self.sim_env.run(self.step_time * self.steps)
                count = 0
                for j, idx in enumerate(send_node):
                    if self.nodes[idx].last_packet_success:
                        count +=1
                latest_per[i] = 1 - count/len(send_node)
            count += 1
            if count == int(10/percentage) or count == 30:
                self.reset(True)
                plt.figure(figsize=(5, 5))
                plt.scatter(range(len(record_per)), record_per)
                plt.title("Running ADR...")
                plt.xlabel("iterations")
                plt.ylabel("Packet error rate")
                plt.show()
                return self.pre_adr(rounds, show, percentage)
            record_per.extend(latest_per)
        if np.average(record_per[-50:-1]) > 0.6:
            self.reset(True)
            plt.figure(figsize=(5, 5))
            plt.scatter(range(len(record_per)), record_per)
            plt.title("Running ADR...")
            plt.xlabel("iterations")
            plt.ylabel("Packet error rate")
            plt.show()
            return self.pre_adr(rounds, show, percentage)
        if show:
            plt.figure(figsize=(5,5))
            plt.scatter(range(len(record_per)), record_per)
            plt.title("Running ADR...")
            plt.xlabel("iterations")
            plt.ylabel("Packet error rate")
        for i in range(len(self.nodes)):
            self.nodes[i].adr = False
        return record_per

    def reset(self, reset_lora=False):
        self.sim_env = simpy.Environment()
        self.steps = 0
        for i in range(len(self.nodes)):
            self.nodes[i].reset(self.sim_env)
            self.nodes[i].last_payload_sent = self.environment.sense(self.nodes[i].location, 0)
            if reset_lora:
                self.nodes[i].para = LoRaParameters(i % Gateway.NO_CHANNELS, sf=12)
        for i in range(len(self.gateways)):
            self.gateways[i].reset(self.sim_env)
        self.server.reset(self.sim_env)
        self.air_interface.reset(self.sim_env)

    def _check_adr_convergence(self, mean, difference):
        return np.max(mean) - np.min(mean) < difference

    def field_reconstruction(self):
        prediction = self.app.fusion_center.field_reconstruct(self.step_time * (self.steps))
        return prediction

    def eval_positive(self):
        diff = np.fromiter(self.real_field.values(), dtype=float)- np.fromiter(self.constructed_field.values(), dtype=float)
        return diff


#Knapsack 알고리즘

#물건의 수, 가능 최대 무게 입력
N, K = map(int, input().split())

p = [[0,0]]
kn = [[0]*(K+1) for _ in range(N+1)]

# 물건 정보 입력
for i in range(N):
    p.append(list(map(int, input().split())))

for i in range(1, N+1): # 물건 수
    for j in range(1, K+1): # 물건 무게
        w = p[i][0]
        v = p[i][1]

        if j < w: # 넣을려는 물건 무게가 가능 무게보다 클 때
            kn[i][j] = kn[i-1][j] # 물건을 넣지 않는다
        else:
            # max ( 이전 배낭을 그대로 가지고 감, 이전배낭에서 현재 넣을 무게만큼 배낭에서 빼고 현재 물건을 넣는다.)
            kn[i][j] = max(kn[i-1][j], kn[i-1][j-w] + v)

# print(p)
# print(kn)
print(kn[N][K])

'''
    SOLUTION

    물건을 배낭에 담을 때
    1) 현재 배낭의 허용 무게보다 넣을 물건의 무게가 더 크다면 넣지 않는다
    2) 그렇지 않다면, 다음중 더 나은 가치를 선택하여 넣는다.
      2-1) 현재 넣을 물건의 무게만큼 배낭에서 뺀다. 그리고 현재 물건을 넣는다.
      2-2) 현재 물건을 넣지 않고 이전 배낭 그대로 가지고 간다.

    입력값
    4 7         => 물건 개수, 가방 최대 무게
    6 13        => 무게, 가치
    4 8
    3 6
    5 12

    p = [[0, 0], [6, 13], [4, 8], [3, 6], [5, 12]]
    kn = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 13, 13], [0, 0, 0, 0, 8, 8, 13, 13], [0, 0, 0, 6, 8, 8, 13, 14], [0, 0, 0, 6, 8, 12, 13, 14]]
                                      1번 물건을 넣었을 때                 2번 물건을 넣었을 때
    kn[N][K] = 14
'''


import cv2
import numpy as np
import math
from tablero import Tablero

class Juego:

    def __init__ (self):
        self.tablero=Tablero(600, 600)
        self.jugador=0
        self.resultadosfinales=False
        self.partidaterminada=False

    def evento_raton(self, event, x, y, flags, param):

        if event == cv2.EVENT_LBUTTONDOWN:
            if(self.resultadosfinales==True):
                self.partidaterminada=True
            else:

                self.tablero.ponerficharaton(self.jugador,x,y)

                if self.jugador==0:
                    self.jugador=1
                else:
                    self.jugador=0

class qlearning3enraya():

    def __init__ (self, iteraciones):
        self.totalpartidas=iteraciones
        self.contjuego=0
        self.contj1=0
        self.contj2=0
        self.contemp=0

    def jugar(self):
        while (self.contjuego<self.totalpartidas):
            self.contjuego=self.contjuego+1

            juego=Juego()

            juego.tablero.imprimetablero(self.contjuego, self.contj1, self.contj2, self.contemp)
            jugador=juego.jugador

            #Loop mientras no termine la partida
            while (juego.partidaterminada is False):

                cv2.setMouseCallback('imagen', juego.evento_raton)

                finpartida, juggana, posicion =juego.tablero.estresenraya()

                if jugador != juego.jugador:
                    accion=''

                    #print('cambio de jugador')

                    jugador=juego.jugador

                    if (finpartida):
                        juego.resultadosfinales=True

                        if (juggana is None):
                            print('EMPATE')
                            accion='EMPATE'
                            self.contemp=self.contemp+1

                        else:
                            print(f'Fin de la partida!! Gana el jugador {juggana}. Tablero en posicion {posicion}')
                            accion='JUG-'+str(juggana+1)

                            if juggana==0:
                                self.contj1=self.contj1+1
                            else:
                                self.contj2=self.contj2+1

                    juego.tablero.imprimetablero(self.contjuego, self.contj1, self.contj2, self.contemp, accion)

                k = cv2.waitKey(20) & 0xFF

        cv2.destroyAllWindows()

tresenraya=qlearning3enraya(iteraciones=3)
tresenraya.jugar()


def change_whitespace(input:str, strlen: int):
    new_str = []
    for c in input:
        if c == ' ':
            new_str.append("%20")
        else:
            new_str.append(c)
    return ''.join(new_str)

if __name__ == "__main__":
    print(change_whitespace("Mr John Smith", 13))


from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals

import numpy as np
import os

from os import listdir
from os.path import isfile, join
import sklearn.cluster as sc
import pickle

from AGCN.utils.data_loader import PointcloudLoader
from AGCN.models import Graph

from AGCN.utils import provider as pd
from AGCN.utils.save import save_to_disk, load_from_disk

# ShapeNet Part Segmentation
BASE_DIR = os.path.join(os.environ["HOME"], 'AGCN/data/3Dmesh/part_seg_shapenet/hdf5_data')
TRAIN_FILES = pd.getDataFiles(os.path.join(BASE_DIR, 'train_hdf5_file_list.txt'))
TEST_FILES = pd.getDataFiles(os.path.join(BASE_DIR, 'test_hdf5_file_list.txt'))

NUM_CATEGORIES = 16
CLUSTER_NUM = 100

TRAIN_NUM = 6000
TEST_NUM = 512

class ShapeNetLoader(PointcloudLoader):
    """
    This class of loader is for Point Cloud data, which is usually lots of binary files stay in
    a folder. Each binary file is a point cloud object, reading it, you get a nddarray of 3D points, each rwo of which
    is a point in laser receivers.
    Input: folder directory
    Output: ConvMol instance for each point cloud object. Features is intensity, adjacency matrix, degree
    are manually learned and set by clustering.
    """

    def featurize(self, shard_size=1024):
        """
        Args:
            input_folder: folder name of binary files (graph object)
            data_dir: where to save generated data frame
            shard_size: number of graphs in one shard
        Returns: creatd Train and Test dataset
        """
        assert os.path.exists(self.processed_data_dir)
        assert os.path.exists(self.data_dir)

        train_dir = os.path.join(self.processed_data_dir, 'train')
        test_dir = os.path.join(self.processed_data_dir, 'test')
        if not os.path.exists(train_dir):
            os.makedirs(train_dir)
        if not os.path.exists(test_dir):
            os.makedirs(test_dir)

        metadata_rows = []
        all_X, all_y, all_seg, all_y_one_hot = [], [], [], []
        for shard_num, (shard, y, seg, y_1h) in enumerate(self.get_shards(TRAIN_FILES, shard_size)):
            """shard is ndarray of 3D mesh point 3-dimension, [pc_id, point_id, (x,y,z)]
                y is the class id for each sample (3D mesh), int type
            """
            print('Featurizing Training Data , Shard - %d' % shard_num)
            X, seg = self.featurize_shard(shard, seg)

            """ save shard (x,y,ids, w)"""
            basename = "shard-%d" % shard_num
            metadata_rows.append(self.write_data_to_disk(train_dir, basename, X, y, seg, y_1h))

            """ stack to list"""
            all_X.append(X)
            all_y.append(y)
            all_seg.append(seg)
            all_y_one_hot.append(y_1h)

        """ save the meta data of training dataset to local """
        meta_data1 = list()
        meta_data1.append(metadata_rows)
        with open(os.path.join(train_dir, 'meta.pkl'), 'wb') as f:
            pickle.dump(meta_data1, f)

        """ return a Dataset contains all X, y, w, ids"""
        all_X = np.concatenate(all_X)
        all_y = np.squeeze(np.concatenate(all_y))
        all_seg = np.squeeze(np.vstack(all_seg))
        all_y_one_hot = np.squeeze(np.vstack(all_y_one_hot))
        assert all_X.shape[0] == all_y.shape[0] == all_seg.shape[0] == all_y_one_hot.shape[0]

        train_dataset = dict()
        train_dataset['X'] = all_X
        train_dataset['y'] = all_y
        train_dataset['seg_mask'] = all_seg
        train_dataset['one_hot_y'] = all_y_one_hot

        metadata_rows = []
        all_X, all_y, all_seg, all_y_one_hot = [], [], [], []
        for shard_num, (shard, y, seg, y_1h) in enumerate(self.get_shards(TEST_FILES, shard_size)):
            """shard is ndarray of 3D mesh point 3-dimension, [pc_id, point_id, (x,y,z)]
                y is the class id for each sample (3D mesh), int type [pc_id, part_id of point]
            """

            print('Featurizing Testing Data , Shard - %d' % shard_num)
            X, seg = self.featurize_shard(shard, seg)

            """ save shard (x,y,ids, w)"""
            basename = "shard-%d" % shard_num
            metadata_rows.append(self.write_data_to_disk(test_dir, basename, X, y, seg, y_1h))

            """ stack to list"""
            all_X.append(X)
            all_y.append(y)
            all_seg.append(seg)
            all_y_one_hot.append(y_1h)

        """ save the meta data to local """
        meta_data2 = list()
        meta_data2.append(metadata_rows)
        with open(os.path.join(test_dir, 'meta.pkl'), 'wb') as f:
            pickle.dump(meta_data2, f)

        """ return a Dataset contains all X, y, w, ids"""
        all_X = np.concatenate(all_X)
        all_y = np.squeeze(np.concatenate(all_y))
        all_seg = np.squeeze(np.vstack(all_seg))
        all_y_one_hot = np.squeeze(np.vstack(all_y_one_hot))
        assert all_X.shape[0] == all_y.shape[0] == all_seg.shape[0] == all_y_one_hot.shape[0]

        test_dataset = dict()
        test_dataset['X'] = all_X
        test_dataset['y'] = all_y
        test_dataset['seg_mask'] = all_seg
        test_dataset['one_hot_y'] = all_y_one_hot

        return train_dataset, test_dataset

    def get_shards(self, file_list, shard_size):

        """ shuffle the data files"""
        file_idxs = np.arange(0, len(file_list))
        np.random.shuffle(file_idxs)  # randomly extract data from files

        """read all data"""
        all_data, all_label, all_seg, all_one_hot_label = [], [], [], []
        for fn in file_idxs:
            # load the point cloud from the file, current_data -> data from one file
            current_data, current_label, current_seg = pd.loadDataFile_with_seg(os.path.join(BASE_DIR, file_list[fn]))
            # remove redundant dimensions
            current_label = np.squeeze(current_label)
            current_seg = np.squeeze(current_seg)

            # shuffle data order
            cur_data, cur_labels, order = pd.shuffle_data(current_data, np.squeeze(current_label))
            current_seg = current_seg[order, ...]

            # create one-hot class label
            cur_labels_one_hot = self.convert_label_to_one_hot(current_label)
            cur_labels_one_hot = np.squeeze(cur_labels_one_hot)

            all_data.append(current_data)
            all_label.append(current_label)
            all_seg.append(current_seg)
            all_one_hot_label.append(cur_labels_one_hot)

        """ create numpy for all data and label"""
        all_data = np.squeeze(np.vstack(all_data))
        all_seg = np.squeeze(np.vstack(all_seg))
        all_one_hot_label = np.squeeze(np.vstack(all_one_hot_label))
        all_label = np.squeeze(np.hstack(all_label))
        assert all_label.shape[0] == all_data.shape[0] == all_seg.shape[0] == all_one_hot_label.shape[0]

        "generate shard data, label, seg_mask, one_hot labels"
        shard_num = 0

        start_idx = shard_num * shard_size
        end_idx = (shard_num + 1) * shard_size
        while end_idx < all_data.shape[0]:
            sel_data = all_data[start_idx:end_idx, :, :]  # ready data
            sel_labels = all_label[start_idx:end_idx]       # corresponding labels
            sel_seg = all_seg[start_idx:end_idx, :]
            sel_one_hot_labels = all_one_hot_label[start_idx:end_idx, :]
            shard_num += 1
            start_idx = shard_num * shard_size
            end_idx = (shard_num + 1) * shard_size
            yield sel_data, sel_labels, sel_seg, sel_one_hot_labels
        # end exceed the bound of pc_names, return all
        yield all_data[start_idx:, :, :], all_label[start_idx:], all_seg[start_idx:, :], all_one_hot_label[start_idx:, :]

    @staticmethod
    def write_data_to_disk(
                           data_dir,
                           basename,
                           X=None,
                           y=None,
                           seg=None,
                           y_1h=None):

        out_X = "%s-X.joblib" % basename
        save_to_disk(X, os.path.join(data_dir, out_X))

        out_y = "%s-y.joblib" % basename
        save_to_disk(y, os.path.join(data_dir, out_y))

        out_seg = "%s-seg.joblib" % basename
        save_to_disk(seg, os.path.join(data_dir, out_seg))

        out_y_1h = "%s-y1h.joblib" % basename
        save_to_disk(y_1h, os.path.join(data_dir, out_y_1h))

        # note that this corresponds to the _construct_metadata column order
        return {'basename': basename, 'X': out_X, 'y': out_y, 'seg_mask': out_seg, 'one_hot_y': out_y_1h}

    def convert_label_to_one_hot(self, labels):
        label_one_hot = np.zeros((labels.shape[0], self.n_classes))
        for idx in range(labels.shape[0]):
            label_one_hot[idx, labels[idx]] = 1
        return label_one_hot

    def featurize_shard(self, shard, seg_mask):

        """
        convert ndarray (n-sample, n_point of sample, 3-d)
        :param shard: ndarray, point cloud raw data
        :return: graph object for each sample
        """
        cluster_num = CLUSTER_NUM  # min_node in this folder is 13 precomputed
        clusterer = sc.AgglomerativeClustering(n_clusters=cluster_num)

        X = []  # to save the graph object
        S = []  # list of new mask
        n_samples = shard.shape[0]
        for pc_id in range(n_samples):
            # iterate each pc in shard
            P = np.squeeze(shard[pc_id, :, :])
            mask = np.squeeze(seg_mask[pc_id, :])
            if P.shape[0] > cluster_num:
                # clustering on original cloud
                cluster_indicators = clusterer.fit_predict(P)  # labels of original points
                new_points = []
                Point_mask = []
                for i in range(cluster_num):
                    """ each cluster center is the new point after clustering"""
                    idx = np.where(cluster_indicators == i)
                    coord = np.mean(P[idx], axis=0)
                    part_id = np.argmax(np.bincount(mask[idx])).astype(np.int32)
                    new_points.append(coord)
                    Point_mask.append(part_id)  # this point at coord belongs to part_id
                new_PC = np.asarray(new_points).astype(np.float32)
                new_mask = np.asarray(Point_mask).astype(np.int32)
                assert new_PC.shape[0] <= cluster_num and new_PC.shape[0] == new_mask.shape[0]
            else:
                # do not need a clustering, use original points
                new_PC = P
                new_mask = mask

            # create graph on point cloud
            adj_list, adj_matrix = self.get_adjacency(new_PC)
            X.append(Graph(new_PC, adj_list, max_deg=cluster_num, min_deg=0))
            S.append(new_mask)

        return np.asarray(X), np.asarray(S),

    @staticmethod
    def get_adjacency(points):
        n_p = points.shape[0]

        # pre-learn the distance matrix, use mean as threshold to generate adjacency matrix, i.e. who connect who
        sum_dist = []
        for i in range(n_p):
            for j in range(i + 1):
                sum_dist += [np.linalg.norm(points[i] - points[j])]
                # input points are new points after clustering
        d_lim = np.mean(sum_dist)

        adj_matrix = np.zeros((n_p, n_p))
        adj_list = [[] for _ in range(n_p)]
        for i in range(n_p):
            for j in range(i + 1, n_p):
                if np.linalg.norm(points[i] - points[j]) < d_lim:
                    adj_matrix[i][j] = True
                    # adjacency list has redundancy
                    adj_list[i].append(j)
                    adj_list[j].append(i)

        return adj_list, adj_matrix

    def load_back_from_disk(self, data_dir, istrain=True):
        """
        load data backas Train/test from disk
        :return: Train/Test STDiskDataset
        """
        """load back metadata_df"""
        meta_data = pickle.load(open(os.path.join(data_dir, 'meta.pkl'), 'rb'))
        metadata_rows = meta_data[0]

        """itershard by loading from disk"""
        all_X, all_y, all_seg, all_y_1h = [], [], [], []

        for _, row in enumerate(metadata_rows):
            # each row is a dict, contains file name for X, y, seg, y_one_hot
            X = np.array(load_from_disk(os.path.join(data_dir, row['X'])))
            y = np.array(load_from_disk(os.path.join(data_dir, row['y'])))
            seg = np.array(load_from_disk(os.path.join(data_dir, row['seg_mask'])))
            y_1h = np.array(load_from_disk(os.path.join(data_dir, row['one_hot_y'])))

            """ stack to list"""
            all_X.append(X)
            all_y.append(y)
            all_seg.append(seg)
            all_y_1h.append(y_1h)

        """ return a Dataset contains all X, y, w, ids"""
        if istrain:
            cut = TRAIN_NUM
        else:
            cut = TEST_NUM
        all_X = np.concatenate(all_X)
        all_y = np.squeeze(np.concatenate(all_y))
        all_seg = np.squeeze(np.vstack(all_seg))
        all_y_1h = np.squeeze(np.vstack(all_y_1h))
        assert all_X.shape[0] == all_y.shape[0] == all_seg.shape[0] == all_y_1h.shape[0]

        dataset = dict()
        dataset['X'] = all_X[cut:]
        dataset['y'] = all_y[cut:]
        dataset['seg_mask'] = all_seg[cut:]
        dataset['one_hot_y'] = all_y_1h[cut:]

        return dataset

    def load(self):
        """Load chemical datasets. Raw data is given as SMILES format."""

        meta_data = []
        if len(os.listdir(self.processed_data_dir)) != 0:

            print("Loading Saved Data from Disk.......")

            """ pre-defined location for saving the train and test data"""
            train_dir = os.path.join(self.processed_data_dir, 'train')
            test_dir = os.path.join(self.processed_data_dir, 'test')

            train = self.load_back_from_disk(data_dir=train_dir, istrain=True)
            test = self.load_back_from_disk(data_dir=test_dir, istrain=False)

            meta_data = pickle.load(open(os.path.join(self.processed_data_dir, 'meta.pkl'), 'rb'))
            max_atom = meta_data[0]

        else:
            print("Loading and Featurizing Data.......")
            # loader = dc.data.CSVLoader(
            #     tasks=self.tasks, smiles_field=self.smiles_field, featurizer=self.Featurizer)
            train, test = self.featurize(shard_size=256)

            """max_atom is the max atom of molecule in all_dataset """
            max_atom = CLUSTER_NUM  # because we do clustering, so it is the cluster center number
            meta_data.append(max_atom)
            with open(os.path.join(self.processed_data_dir, 'meta.pkl'), 'wb') as f:
                pickle.dump(meta_data, f)

        return train, test, max_atom


import io

from telegram import Update, CallbackQuery
from telegram.ext import ContextTypes, CallbackContext
from telegram.error import Forbidden

from Constants.Env import ID_ADMIN
from Models.User import User
from Models.Reservation import Reservation

class AdminController:

    # Verify if this user is admin
    @staticmethod
    def is_from_admin(user_id) -> bool:
        return user_id == ID_ADMIN

    # Comunication with users
    async def forward_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
        id = update.effective_user.id
        if( not AdminController.is_from_admin(id) ):
            return
        for chat_id in User.get_all_users_chat_id():
            (user_id,) = chat_id
            try:
                await context.bot.send_message( chat_id=user_id, text=update.message.text.removeprefix("/forward "))
            except Forbidden:
                print(f"User blocked the bot : {update.effective_user.id}")

    async def forward_message_and_clean_reservations(update: Update, context: ContextTypes.DEFAULT_TYPE):
        id = update.effective_user.id
        if( not AdminController.is_from_admin(id) ):
            return

        Reservation.clean()
        for chat_id in User.get_all_users_chat_id():
            (user_id,) = chat_id
            try:
                await context.bot.send_message( chat_id=user_id, text=update.message.text.removeprefix("/forward_clean "))
            except Forbidden:
                print(f"User blocked the bot : {update.effective_user.id}")

    # Admin Utilities
    async def clean(update: Update, context: ContextTypes.DEFAULT_TYPE):
        id = update.effective_user.id
        if( not AdminController.is_from_admin(id) ):
            return
        Reservation.clean()

    async def get_locations(update: Update, context: ContextTypes.DEFAULT_TYPE):
        locations = Reservation.get_all_locations()
        answer = "ðŸŒ‰ Puentes a parar:\n --------------------------------------\n"
        for location, in locations:
            answer += f"- {location}\n"
        await update.message.reply_text(answer)

    async def get_list_reservation(update: Update, context: ContextTypes.DEFAULT_TYPE):
        all_reservation = Reservation.get_all_reservations()
        answer = "ðŸŸ© Listado de reservas \nOrden | Nombre | Puente | Reservado por \n --------------------------------------------------\n"
        for reservation in all_reservation:
            order, name, location, reserved_by = reservation
            answer += f"{order}  {name} || Puente: {location} || Por {reserved_by}\n"
        await update.message.reply_text(answer)

    @staticmethod
    async def get_list_reservation_file(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
        all_reservation = Reservation.get_all_reservations()
        answer = "ðŸŸ© Listado de reservas \nOrden | Nombre | Puente \n --------------------------------------------------\n"
        for reservation in all_reservation:
            order, name, location, *rest = reservation
            answer += f"{order}  {name} || Puente: {location}\n"

        list_txt = io.BytesIO(answer.encode())
        list_txt.name = "Lista.txt"
        await update.message.reply_document(document=list_txt, filename="Lista Guagua Pinar")


# @author: Gautam Patel
# Problem Description URL: https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem
#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
    cnt = 0
    c_len = len(c)
    idx = 0
    while idx <= c_len-1:
        if idx+2 < c_len and c[idx+2] == 0:
            cnt += 1
            idx += 2
        elif idx+1 < c_len and c[idx+1] == 0:
            cnt += 1
            idx += 1
        else:
            idx += 1
    return cnt

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    c = list(map(int, input().rstrip().split()))

    result = jumpingOnClouds(c)

    fptr.write(str(result) + '\n')

    fptr.close()


"""
Module to store the functions that will make up a 'from scratch'
implementation of the k-nearest neighbors model for predictions
from a vector dataset
"""

from collections import Counter
from math import pow
from math import sqrt
from math import fsum
from operator import itemgetter

def euclidean_distance(vector1, vector2, length):
    """
    Compute distance between two vector of arbitrary length
    containing an arbitrary number of numerical values

    Args:
        vector1 (list): first vector
        vector2 (list): second vector
        length (int): length of vectors

    Returns:
        float representing the euclidean distance between the two vectors
    """
    distance = fsum([
        pow((vector1[i] - vector2[i]), 2) for i in range(length)
    ])
    return sqrt(distance)

def find_k_neighbors(query,
                     dataset,
                     k,
                     vector_length,
                     return_distances=False):
    """
    Return k vectors from dataset nearest to the query vector

    Args:
        query (list): vector for which neighbors will be found
        dataset (list): collection of vectors from which neighbors will
            be found
        k (int): number of neighbors to be returned
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        return_distances (bool): optional argument to enable find_k_neighbors
            to return distance values

    Returns:
        list of k vectors found to be nearest neighbors
    """
    distances = []
    for row in dataset:
        eu_dist = euclidean_distance(query, row, vector_length)
        distances.append((row, eu_dist))
    distances.sort(key=itemgetter(1))
    neighbors = [row[0] for row in distances[:k]]
    if return_distances:
        return neighbors, [row[1] for row in distances[:k]]
    else:
        return neighbors

def calc_category_frequency(dataset, vector_length, category_index=-1):
    """
    Return frequencies of the category variables in dataset

    Args:
        dataset (list): collection of vectors from which neighbors will
            be found
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        category_index (int): optional argument to select a specific element
            by index as the predicted category in the dataset rows;
            default is index in position one beyond length of query vector

    Returns:
        Counter object with frequencies of the category values in dataset
    """
    if category_index < 0:
        category_index = vector_length
    frequencies = Counter(
        [row[category_index] for row in dataset]
    )
    return frequencies

def predict_category_from_knn(query,
                              dataset,
                              k,
                              vector_length,
                              category_index=-1):
    """
    Return a category for query vector by knn algorithm applied to dataset

    Args:
        query (list): vector for which neighbors will be found
        dataset (list): collection of vectors from which neighbors will
            be found
        k (int): number of neighbors to be returned
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        category_index (int): optional argument to select a specific element
            by index as the predicted category in the dataset rows;
            default is index in position one beyond length of query vector

    Returns:
        nested list with knn "votes" by category sorted by descending votes
    """
    if category_index < 0:
        category_index = vector_length
    neighbors = find_k_neighbors(query, dataset, k, vector_length)
    votes = calc_category_frequency(neighbors,
                                    vector_length,
                                    category_index=category_index)
    predictions = [[key, value] for key, value in votes.iteritems()]
    predictions.sort(key=itemgetter(1))
    return predictions

def predict_knn_classes_from_set(test_set,
                                 training_set,
                                 k,
                                 vector_length,
                                 category_index=-1):
    """loop over the test set and generate predictions for each feature row

    Args:
        test_set (list): collection of vectors for which predictions are made
        dataset (list): collection of vectors from which neighbors will
            be found
        k (int): number of neighbors to be returned
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        category_index (int): optional argument to select a specific element
            by index as the predicted category in the dataset rows;
            default is index in position one beyond length of query vector
    """
    if category_index < 0:
        category_index = vector_length
    test_set_predictions = []
    for row in test_set:
        predictions = predict_category_from_knn(row,
                                                training_set,
                                                k,
                                                vector_length,
                                                category_index=category_index)
        prediction = predictions[0][0]
        test_set_predictions.append(prediction)
    return test_set_predictions


def find_it(seq):
    slovar = {}
    for value in seq:
        if value not in slovar:
            slovar[value] = 0
        slovar[value] += 1
    for odd in slovar:
        if slovar[odd] % 2 != 0:
            return odd

# another option
def find_it(seq):
    for i in seq:
        if seq.count(i)%2!=0:
            return i

print(find_it([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]))
print(find_it([1,1,2,-2,5,2,4,4,-1,-2,5]))
print(find_it([20,1,1,2,2,3,3,5,5,4,20,4,5]))
print(find_it([10]))


class Node:

    def __init__(self, data):
        self.data = data
        self.nextNode = None

class LinkedList:

    def __init__(self):
        # Initially first node/head value is null because the linked list is empty
        self.head = None
        # At the beginning number of noder is 0. Which means there ios no item in the linked list datastructure
        self.numofNodes = 0

    def insert_start(self, data):
        """ This method is going to get data and insert it into the linked list. Time complexity is O(1)"""

        # We will first increment the number of nodes
        self.numofNodes = self.numofNodes + 1

        # Then we instantiate the new node
        new_node = Node(data)

        # We need to check if this is the first node of the linked list or not that is if [head node is null or not]
        if not self.head:
            self.head = new_node
        else:
            # If head node is not empty,
            new_node.nextNode = self.head
            self.head = new_node

    def insert_end(self, data):

        # We will first increment the number of nodes
        self.numofNodes = self.numofNodes + 1

        new_node = Node(data)

        actual_node = self.head # Pointing to the Fist node of the linked list

        while actual_node.nextNode is not None:
            actual_node = actual_node.nextNode

        actual_node.nextNode = new_node

    def remove(self, data):

        if self.head is None:
            return

        actual_node = self.head
        previous_node = None

        while ((actual_node is not None) and (actual_node.data != data)):
            previous_node = actual_node
            actual_node = actual_node.nextNode

        # This is a search miss, that is the item is not present in the linked list
        if actual_node is None:
            return

        self.numofNodes = self.numofNodes - 1

        if previous_node is None:
            self.head = actual_node.nextNode
        else:
            previous_node.nextNode = actual_node.nextNode

    def siz_of_list(self):
        return self.numofNodes

    def traverse(self):

        actual_node = self.head

        # while we are not at the end of the list
        # We will print the actual node
        while actual_node is not None:
            print(actual_node.data)
            actual_node = actual_node.nextNode

linked_list = LinkedList()
linked_list.insert_start(10)
linked_list.insert_start(5)
linked_list.insert_start(3)
linked_list.insert_end(3)
linked_list.traverse()
print(linked_list.siz_of_list())
print("----------------")

linked_list.remove(3)
linked_list.traverse()
print(linked_list.siz_of_list())


import os

def captura_dados():

    #lendo dados do usuarios

    texto_usuario = input('Informe um numero: ')
    print('voce escreveu => ', texto_usuario)
    print( type(texto_usuario))

    inteiro_usuario = input('Informe um numero: ')
    print('Voce infomormou => ', inteiro_usuario)
    print(type(inteiro_usuario))

    #Convertendo strings para numeros inteiros

    inteiro_usuario = input('Informe um numero: ')

    # try para tentar executar e nao parar se der erro

    try:
        inteiro_usuario = int(inteiro_usuario)
    except:
        print('Erro ao tentar converter numero para float')

    # Convertendo strings para numeros quebrados

    float_usuario = input('Informe numero float: ')

    try:
        float_usuario = float(float_usuario)
    except:
        print('Erro ao tentar converter numero para float')

    print('Voce digitou => ', float_usuario)
    print(type(float_usuario))

if __name__ =='__main__':
    os.system('clear')

    captura_dados()


import subprocess
import sys
from optparse import OptionParser

usage = "usage: python teardown_cluster.py -n <stack_name>"

parser = OptionParser(usage=usage)

parser.add_option("-n", "--stackname",
                  action="store", type="string", dest="stackname", default=None,
                  help="stackname of cloudformation cluster to delete")

arg_parameters = sys.argv[1:]

(opts, args) = parser.parse_args(arg_parameters)

if opts.stackname is None:
    print("Please provide a stackname to teardown")
    sys.exit(1)

subprocess.call(["aws", "cloudformation", "delete-stack", "--stack-name", opts.stackname, "--region", "us-east-1"])


import networkx as nx

def cal_degree_distribution(graph):
    '''
    计算度分布
    '''
    degree_count = {}
    for i in range(nx.number_of_nodes(graph)):
        deg = graph.degree(i)
        if deg in degree_count: degree_count[deg] += 1
        else: degree_count[deg] = 1
    degree_count = sorted(degree_count.items())
    ave = nx.number_of_edges(graph) * 2 / nx.number_of_nodes(graph)

    with open('result/degree_distribution.txt', 'w', encoding = 'utf-8') as out_file:
        print('The average of degree:%.2f'%ave, file = out_file)
        for l in degree_count:
            print('%3d : %4d'% (l[0], l[1]), file = out_file)

def cal_views_distribution(node_info):
    '''
    计算views属性的分布
    '''
    views_count = {}
    total = 0
    for node in node_info:
        total += int(node['views'])
        views = int(node['views']) // 1000
        if views in views_count: views_count[views] += 1
        else: views_count[views] = 1
    ave = total / len(node_info)
    count_list = sorted(views_count.items())

    with open('result/views_distribution.txt', 'w', encoding = 'utf-8') as out_file:
        print('The average of views:%.2f'%ave, file = out_file)
        for l in count_list:
            print('%dK-%dK : %d' % (l[0], l[0] + 1,  l[1]), file = out_file)


def my_except_hook(exctype, value, traceback):
    sys.__excepthook__(exctype, value, traceback)

def main():

    ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
    DATA_FILENAME = 'data.json'

    root = Tk()
    root.withdraw()

    if not os.path.exists(DATA_FILENAME):

        print("Choose default destination folder:")

        folder_selected = get_directory.get_dir()

        data = {
            'path': f'{folder_selected}'
        }
        save_to_json(DATA_FILENAME, data)

    mode = 'mp3'
    input_text = 'mp4'

    links = []
    q = ''

    while q != "e":

        ydl_opts = config.return_config(mode)

        DEFAULT_PATH = ydl_opts['DEFAULT_PATH']

        q = input(
            f"Insert links \n *-download given links\n l-clear links list\n c-clear default dir\n m-switch to {input_text}\n d-change default dir (current: {DEFAULT_PATH})\n e-exit\n{links}\n: ")

        if q == 'c':
            for i in os.listdir(DEFAULT_PATH):
                if i.endswith('.mp3') or i.endswith('.mp4'):
                    os.remove(f'{DEFAULT_PATH}/{i}')

        elif q == '*':
            if not links:
                print("List is empty!")
                time.sleep(1)
            else:
                downloader.download(links, ydl_opts)
            print("Done!")
            time.sleep(1)
            links.clear()

        elif q == 'e':
            quit()

        elif q == 'l':  # lowercase L
            links = []

        elif q == 'm':
            if mode == 'mp3':
                mode = 'mp4'
                input_text = 'mp3'
            else:
                mode = 'mp3'
                input_text = 'mp4'

        elif q == 'd':
            folder_selected = get_directory.get_dir()

            data = {
                'path': f'{folder_selected}'
            }

            save_to_json(DATA_FILENAME, data)

        else:
            if check_url(q):
                links.append(q)
            else:
                print("Invalid URL!")
                time.sleep(1)

        os.system('cls')

if __name__ == "__main__":
    import sys
    import os
    import time
    from tkinter import filedialog
    from tkinter import *
    from url_check import check_url
    import config
    import downloader
    import get_directory
    from save_to_json import save_to_json

    sys.excepthook = my_except_hook

    if len(sys.argv) > 1:
        import main_commandLine
        main_commandLine.run()
    else:
        main()
else:
    print("Package is not yet importable.")


import difflib

SIMILARITY_THRESHOLD = 0.7
known_artists = [
    'Nikolay Lugansky', 'Gregory Sokolov', 'Kamil Pacholec',
    'Bruce Xiao Liu', 'Ray Chen', 'Emil Gilels'
]
known_composers = [
    'Dmitri Shostakovich', 'Fryderyk Chopin', 'Felix Mendelssohn',
    'Sergei Rachmaninoff', 'Antonín Dvořák', 'Johann Sebastian Bach',
    'Ludwig Beethoven', 'Itzhak Perlman'
]
known_people = known_artists + known_composers + [

]

class NameReplacer:
    artists_surnames = []
    initials = 1
    surname = 2
    full_name = 3
    abreviated = 4

    def similar(seq1: str, seq2: str) -> float:
        return difflib.SequenceMatcher(a=seq1.lower(), b=seq2.lower()).ratio()

    def generate_abreviation(person: str, mode: int) -> str:
        """Generates the abreviation using initials.
            mode: abreviated
            ex. Johann Sebastian Bach -> J.S.Bach
        """
        out_name = ''
        if mode == NameReplacer.initials:
            for word in person.split():
                if len(word) > 0:
                    out_name += word[0] + '.'
            out_name = out_name[:-1]

        elif mode == NameReplacer.surname:
            out_name = person.split()[-1]
            #print(out_name)

        elif mode == NameReplacer.full_name:
            out_name = person

        elif mode == NameReplacer.abreviated:
            for word in person.split()[:-1]:
                if len(word) > 0:
                    out_name += word[0] + '.'
            out_name += person.split()[-1]

        return out_name

    def replace(in_name: str, mode: int = None) -> str:
        """Genrates the name in a standarized form. Given the given string is similar enough.
            ex. Rachmaninov -> S.Rachmaninoff
        """
        if not mode:
            mode = NameReplacer.full_name
        max_value = -1
        out_name = in_name
        for person in known_people:
            mutations = [person, person.split()[-1], person[0]+'.'+person.split()[-1]]
            for mutation in mutations:
                temp = NameReplacer.similar(mutation, in_name)
                if temp > SIMILARITY_THRESHOLD and temp > max_value:
                    out_name = person
                    max_value = temp
        return out_name


import csv
import json
from collections import Counter

def paisSelva():
    archivo_csv= open("areaselvatica.csv","r",encoding="utf-8")
    csvreader = csv.reader(archivo_csv, delimiter=",")

    archivo_json = open("archivoJsonS.txt","x")
    dic={}

    for linea in csvreader:
        if linea[61] !="":
            dic[linea[0]]=float(linea[61])
    dic = Counter(dic)

    json.dump(dic.most_common(11), archivo_json)

    archivo_csv.close()

    archivo_json.close()

def paisRural():

    archivo_csv = open("rural.csv","r",encoding="utf-8")
    csvreader = csv.reader(archivo_csv, delimiter=",")

    archivo_json = open("archivoJsonR.txt","x")

    for linea in csvreader:
        if linea[62] !="":
            if int(linea[62])>60000000:
                json.dump(linea[0], archivo_json)

    archivo_csv.close()

    archivo_json.close()


#!/usr/bin/env python3

from sys import argv, exit
from svgnarrative import Model
import json

earth_prefix = 'earth'

def read_description (filename):
    with open(filename) as fo:
        return json.load(fo)

# handle command-line arguments
if len(argv) != 6:
    print('Syntax: %s PATH_TO_JSON_DESCRIPTION PATH_TO_TEMPLATE PATH_TO_MAP PATH_TO_ROAST OUTPUT_FILENAME' % argv[0])
    print('        %s ../var/coffees/kenya_matunda.json ../var/templates/default.svg ../var/templates/roast.svg ../var/templates/World_map_blank_with_blue_sea.svg kenya_matunda.svg' % argv[0])
    exit(1)
description_filename = argv[1]
template_filename    = argv[2]
map_filename         = argv[3]
roast_filename       = argv[4]
output_filename      = argv[5]

template    = Model(template_filename)
earth       = Model(map_filename)
roast       = Model(roast_filename)
description = read_description(description_filename)

template.set_text('name', description['name'])
template.insert(earth, earth_prefix, 15, 10, 0.03)
template.fill(map(lambda o: '%s%s' % (earth_prefix, o), description['origin']), '#880000')
for i in range(2):
    roast_prefix = 'roast%d' % i
    template.insert(roast, roast_prefix, 5, 60+70*i)
    template.set_text('%stspan2411-1-5'%roast_prefix, description['date'] if 'date' in description else '')

    for j in range(1, 6):
        template.set_text('%stemp%d'%(roast_prefix, j), '')

    for j in range(1, 5):
        template.set_text('%stime%d'%(roast_prefix, j), '')

template.store(output_filename)


"""
计算器
编译者：PengPeng3g
v1.0 增加加法
v2.0 增加减，乘，除法
v3.0 可以多部计算，但需更改代码
v4.0 在v2.0的基础上更改，精简v2.0的代码
v5.0 精简代码
v6.0 精简代码
v7.0 增加循环节
当前版本：v7.0
"""
a=True

while a:

    diyigejiashu=int(input('加数'))

    diergejiashu=int(input('加数'))

    print('和', diyigejiashu+diergejiashu)

    beichushu=int(input('被除数'))

    chushu=int(input('除数'))

    print('商',beichushu/chushu)

    diyigechengshu=int(input('因数'))

    diergechengshu=int(input('因数'))

    print('积',diyigechengshu*diergechengshu)

    beijianshu=int(input('被减数'))

    jianshu=int(input('减数'))

    print('差',beijianshu-jianshu)

    b=input("是否继续计算？")

    if b == "是":
        a = True
    else:
        a = False


"""
Project: apparel shop test 2.
Author:Devam A

Description:

"""
list_of_apparels = ['T-shirt', 'Shirt', 'Jacket']
list_of_sizes = ['Large', 'Medium', 'Small']
list_of_colour = ['Red', 'Blue', 'Green', 'Yellow', 'White']

user_name = input("ENTER YOUR NAME:")
print(f"WELCOME TO THE APPAREL SHOP,{user_name.title()}.")
main_menu = """
SELECT ANY ONE OPTION FROM THE MENU:
1. ADD ITEM TO THE CART.
2. VIEW THE CART.
3. EXIT THE PROGRAM.
-->"""
apparel_type = """
TYPE OF THE APPAREL:
1. T-shirt.
2. Shirt.
3. Jacket.
-->"""
apparel_size = """
SIZE OF THE APPAREL:
1. Large.
2. Medium.
3. Small.
-->"""
apparel_colour = """
COLOUR OF THE APPAREL:
1. Red.
2. Blue.
3. Green.
4. Yellow.
5. White.
-->"""
def type_of_apparel(number):
    return list_of_apparels[number - 1]
def size_of_apparel(number):
    return list_of_sizes[number - 1]
def colour_of_apparel(number):
    return list_of_colour[number - 1]
cart = {"Apparel Type":0, "Apparel Size":0, "Apparel Colour":0}
user_input = 1
while user_input != 3:

    user_input = int(input(main_menu))
    if user_input == 1:
        apparel_type_user_input = int(input(apparel_type))
        value = type_of_apparel(user_input)
        cart["Apparel Type"] = value
        apparel_size_user_input = int(input(apparel_size))
        value = size_of_apparel(user_input)
        cart["Apparel Size"] = value
        apparel_colour_user_input = int(input(apparel_colour))
        value = colour_of_apparel(user_input)
        cart["Apparel Colour"] = value
        print("ITEM ADDED TO CART SUCCESSFULLY")
    elif user_input == 2:
        print(f" you have selected {cart['Apparel Type']} apparel of size {cart['Apparel Size']} with {cart['Apparel Colour']} colour")

else:
    input("THANK YOU!!! COME AGAIN..")


import gzip
import json
import os
import time
from pathlib import Path

import boto3

COGNITO_STAGING_POOL = os.getenv("COGNITO_STAGING_POOL", "eu-west-1_mAQcge0PR")

DATA_LOCATION = os.getenv("BIOMAGE_DATA_PATH", "./data")
PULL = "PULL"

class Summary(object):
    """
    Utility singleton class used to report which files have been updated as a result of
    a given data management command.
    """

    changed_files = []
    cmd = ""
    origin = ""
    experiment_id = ""

    @classmethod
    def set_command(cls, cmd, origin, experiment_id):
        cls.cmd = cmd
        cls.origin = origin
        cls.experiment_id = experiment_id

    @classmethod
    def add_changed_file(cls, file):
        cls.changed_files.append(file)

    @classmethod
    def report_changes(cls):
        print(f"From {cls.origin}")
        print(f" * experiment {cls.experiment_id:^40s} -> {cls.cmd:>10s}")

        if len(cls.changed_files) < 1:
            print("Already up to date.")
            return

        print("Changes:")
        for file in cls.changed_files:
            print(f"{file:<70s} | Updated")

def save_cfg_file(dictionary, dst_file):
    local_file = os.path.join(DATA_LOCATION, dst_file)

    # try to create experiment folder, ignores if already exists (same as mkdir -p)
    Path(os.path.dirname(local_file)).mkdir(parents=True, exist_ok=True)

    with open(local_file, "w") as f:
        # We sort & indent the result to make it easier to inspect & debug the files
        # neither sorting nor indentation is used to check if two confis are equal
        json.dump(dictionary, f)

# If the config file was found => retun  (config file, true)
# Otherwise => (None, False)
def load_cfg_file(file):
    filepath = os.path.join(DATA_LOCATION, file)
    if os.path.exists(filepath) and not os.path.getsize(filepath) == 0:
        with open(os.path.join(DATA_LOCATION, file)) as f:
            return json.load(f), True

    return None, False

def set_modified_date(file_location, date):
    """
    Change the last-modified file parameter to date
    """
    mod_time = time.mktime(date.timetuple())

    os.utime(file_location, (mod_time, mod_time))

def get_local_S3_path(key):
    return os.path.join(DATA_LOCATION, key)

def is_modified(obj, key):
    """
    We check if the file in S3 has changed by comparing the last modified date
    which should be enough for our goals.
    Using E-tags would require either to download the file anyway to compute it or
    storing them in a local DB which seemed too complex. Moreover, there isn't a
    standard e-tag computation readily available and they can change among buckets,
    regions, etc...
    so it does not seem worth it.
    """
    local_file = get_local_S3_path(key)

    if not os.path.exists(local_file):
        return True

    if int(obj.last_modified.strftime("%s")) != int(os.path.getmtime(local_file)):
        return True

    return False

def download_S3_rds(s3_obj, key, filepath):
    local_file = get_local_S3_path(filepath)

    # try to create experiment folder, ignores if already exists (same as mkdir -p)
    Path(os.path.dirname(local_file)).mkdir(parents=True, exist_ok=True)

    with gzip.open(local_file, "wb") as f:
        f.write(s3_obj.get()["Body"].read())

    set_modified_date(file_location=local_file, date=s3_obj.last_modified)

def download_S3_json(s3_obj, key, filepath):
    local_file = get_local_S3_path(filepath)

    # try to create experiment folder, ignores if already exists (same as mkdir -p)
    Path(os.path.dirname(local_file)).mkdir(parents=True, exist_ok=True)

    s3_obj.download_file(local_file)

    set_modified_date(file_location=local_file, date=s3_obj.last_modified)

def get_cognito_username(email):
    client = boto3.client("cognito-idp")
    user_name = client.admin_get_user(Username=email, UserPoolId=COGNITO_STAGING_POOL)[
        "Username"
    ]

    return user_name

def get_experiment_project_id(experiment_id, source_table):

    table = boto3.resource("dynamodb").Table(source_table)

    project_id = table.get_item(
        Key={"experimentId": experiment_id}, ProjectionExpression="projectId"
    ).get("Item")["projectId"]

    return project_id

def add_user_to_rbac(user_name, cfg):
    if "rbac_can_write" in cfg:
        if user_name not in cfg["rbac_can_write"]["SS"]:
            cfg["rbac_can_write"]["SS"].append(user_name)
    for val in cfg.values():
        if isinstance(val, dict):
            add_user_to_rbac(user_name, val)

def add_env_user_to_experiment(cfg):
    email = os.getenv("BIOMAGE_EMAIL")
    if not email:
        raise ValueError(
            "biomage email not available to patch experiment permissions."
            + ' Set the environment variable "BIOMAGE_EMAIL" with the email you use to log in into cellenics'
            + " and try again."
        )

    user_name = get_cognito_username(email=email)

    add_user_to_rbac(user_name=user_name, cfg=cfg)

    return cfg


from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import pickle
import datetime
import pytz
import AssistantSpeak as ASpeak

#Some Constant Variables
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

MONTHS = ["january", "february", "march", "april", "may", "june","july", "august", "september","october","november", "december"]

DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

DAY_EXTENTIONS = ["rd", "th", "st", "nd"]

# Authenticating google Calender with the key given in the credentials.json
def authenticate_google():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)

        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    return service

# Gets and checks for the event entry from the google Calender
def get_events(day, service):
    # Call the Calendar API
    date = datetime.datetime.combine(day, datetime.datetime.min.time())
    end_date = datetime.datetime.combine(day, datetime.datetime.max.time())
    utc = pytz.UTC
    date = date.astimezone(utc)
    end_date = end_date.astimezone(utc)

    events_result = service.events().list(calendarId='primary', timeMin=date.isoformat(), timeMax=end_date.isoformat(),
                                        singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        ASpeak.speak('No upcoming events found.')
        print('No upcoming events found')
    else:
        ASpeak.speak(f"You have {len(events)} events on this day.")

        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            startsplit = start.split("+",1)
            start = startsplit[0]
            #print(start.replace("T", " "), event['summary'])
            start_time = str(start.split("T")[1].split("-")[0])

            # integrating 'am' and 'pm'
            if int(start_time.split(":")[0]) < 12:
                start_time = startsplit[1] + " am"
            else:
                start_time = str(int(start_time.split(":")[0])-12) + start_time.split(":")[1]
                start_time = startsplit[1] + " pm"

            ASpeak.speak(event["summary"] + " at " + start_time)
            #start_time = start_time.replace("T", " ")
            #print(event["summary"] + " at " + start_time)

#Gets the date from the user [COMPLEX :( ]
def get_date(text):
    text = text.lower()
    today = datetime.date.today()

    if text.count("today") > 0:
        return today

    day = -1
    day_of_week = -1
    month = -1
    year = today.year

    for word in text.split():
        if word in MONTHS:
            month = MONTHS.index(word) + 1
        elif word in DAYS:
            day_of_week = DAYS.index(word)
        elif word.isdigit():
            day = int(word)
        else:
            for ext in DAY_EXTENTIONS:
                found = word.find(ext)
                if found > 0:
                    try:
                        day = int(word[:found])
                    except:
                        pass

    if month < today.month and month != -1:  # if the month mentioned is before the current month set the year to the next
        year = year+1

    if month == -1 and day != -1:  # if we didn't find a month, but we have a day
        if day < today.day:
            month = today.month + 1
        else:
            month = today.month

    # if we only found a dta of the week
    if month == -1 and day == -1 and day_of_week != -1:
        current_day_of_week = today.weekday()
        dif = day_of_week - current_day_of_week

        if dif < 0:
            dif += 7
            if text.count("next") >= 1:
                dif += 7

        return today + datetime.timedelta(dif)

    if day != -1:
        return datetime.date(month=month, day=day, year=year)


"""
COSC413 Assignment 1
Jamie McCloskey
RSA encryption, decryption, and authentication
Reads plaintext from the file text.txt and performs a demonstration of RSA with random key pairs
"""

import random

""" Number of times we run the composite-checking algorithm
We have about (1/4)^100 chance of false positives
"""
PRIME_TRIALS = 100

def modular_pow(base, p, mod):
    """ Computes base^p mod mod using repeated squaring
    """
    ans = 1
    index = 0
    while 1 << index <= p:
        if p & (1 << index):
            ans = (ans * base) % mod
        index += 1
        base = (base * base) % mod
    return ans

def euclid(a, b):
    """ Finds x and y such that ax + by = gcd(a,b)
        Returns the tuple (gcd(a,b), x, y)
    """
    last_b1, b1 = 1, 0
    last_b2, b2 = 0, 1
    last_b3, b3 = a, b
    while b3 != 0:
        q = last_b3 // b3
        last_b1, b1 = b1, last_b1 - q * b1
        last_b2, b2 = b2, last_b2 - q * b2
        last_b3, b3 = b3, last_b3 - q * b3

    return last_b3, last_b1, last_b2

def is_witness(a, k, q, n):
    """ Is a a Miller-Rabin witness to the compositeness of n?
    """
    x = modular_pow(a, q, n)
    if x == 1 or x == n - 1:
        return False
    for r in range(k):
        x = (x * x) % n
        if x == 1:
            return True
        if x == n - 1:
            return False
    return True

def is_prime(n):
    """ Determines if a number n is probably prime, using the Miller-Rabin test.
    """
    if n < 2:
        return False
    if n == 2 or n == 3:
        return True
    if n % 2 == 0:
        return False

    k = 0
    q = n - 1
    while q % 2 == 0:
        q //= 2
        k += 1

    for i in range(PRIME_TRIALS):
        a = random.randint(2, n - 2)
        if is_witness(a, k, q, n):
            return False
    return True

def modular_inverse(n, mod):
    gcd, d, y = euclid(n, mod)
    while d < 0:
        d += mod
    return d

def encrypt(m, e, n):
    return modular_pow(m, e, n) % n

p, q, e, n, phi, d = None, None, None, None, None, None

def refresh(p_, q_, e_):
    global p, q, e, n, phi, d
    if not all([p_, q_, e_]):
        return
    p, q, e = p_, q_, e_
    n = p * q
    phi = (p - 1) * (q - 1) if p != q else p * (p - 1)
    d = modular_inverse(e, phi)

def main():
    global p, q, e, n, phi, d

    cmd = ""
    while cmd != "Quit".lower():
        cmd = input().lower()
        if cmd.startswith("P=".lower()):
            p = int(cmd[2:])
            refresh(p, q, e)
        elif cmd.startswith("Q=".lower()):
            q = int(cmd[2:])
            refresh(p, q, e)
        elif cmd.startswith("E=".lower()):
            e = int(cmd[2:])
            refresh(p, q, e)

        elif cmd.startswith("IsPPrime".lower()):
            print("Yes") if is_prime(p) else print("No")
        elif cmd.startswith("IsQPrime".lower()):
            print("Yes") if is_prime(q) else print("No")

        elif cmd == "PrintP".lower():
            print(p)
        elif cmd == "PrintQ".lower():
            print(q)
        elif cmd == "PrintE".lower():
            print(e)

        elif cmd.startswith("PrintN".lower()):
            print(n)
        elif cmd.startswith("PrintPhi".lower()):
            print(phi)
        elif cmd.startswith("PrintD".lower()):
            print(d)

        elif cmd.startswith("EncryptPublic=".lower()):
            m = int(cmd[14:])
            print(encrypt(m, e, n))
        elif cmd.startswith("EncryptPrivate=".lower()):
            m = int(cmd[15:])
            print(encrypt(m, d, n))

if __name__ == '__main__':
    main()


from functools import partial
from .utils import download, make_cache_path

def _zenodo_url(record, name):
	return f'https://zenodo.org/record/{record}/files/{name}'

class Zoo:
	_initialized = False

	_numberbatch_lang_codes = [
		'af', 'ang', 'ar', 'ast', 'az', 'be', 'bg', 'ca', 'cs', 'cy', 'da',
		'de', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fil', 'fo',
		'fr', 'fro', 'ga', 'gd', 'gl', 'grc', 'gv', 'he', 'hi', 'hsb', 'hu',
		'hy', 'io', 'is', 'it', 'ja', 'ka', 'kk', 'ko', 'ku', 'la', 'lt', 'lv',
		'mg', 'mk', 'ms', 'mul', 'nl', 'no', 'non', 'nrf', 'nv', 'oc', 'pl',
		'pt', 'ro', 'ru', 'rup', 'sa', 'se', 'sh', 'sk', 'sl', 'sq', 'sv', 'sw',
		'ta', 'te', 'th', 'tr', 'uk', 'ur', 'vi', 'vo', 'xcl', 'zh'
	]

	_embeddings = {
	}

	@staticmethod
	def _init():
		if Zoo._initialized:
			return

		from fasttext.util.util import valid_lang_ids as ft_valid_lang_ids
		for lang in ft_valid_lang_ids:
			Zoo._embeddings[f'fasttext-{lang}'] = {
				'constructor': PretrainedFastText,
				'lang': lang
			}

			Zoo._embeddings[f'fasttext-{lang}-mini'] = {
				'constructor': CompressedFastTextVectors,
				'url': _zenodo_url(4905385, f'fasttext-{lang}-mini')
			}

		for lang in Zoo._numberbatch_lang_codes:
			Zoo._embeddings[f'numberbatch-19.08-{lang}'] = {
				'constructor': partial(Word2VecVectors, binary=True),
				'url': _zenodo_url(4911598, f'numberbatch-19.08-{lang}.zip'),
				'name': f'numberbatch-19.08-{lang}'
			}

		for d in [50, 100, 200, 300]:
			Zoo._embeddings[f'glove-6B-{d}'] = {
				'constructor': partial(Word2VecVectors, binary=True),
				'url': _zenodo_url(4925376, f'glove.6B.{d}d.zip'),
				'name': f'glove-6B-{d}'
			}

		for name, sizes in {
			'42B': [300],
			'840B': [300],
			'twitter.27B': [25, 50, 100, 200]}.items():

			for size in sizes:
				Zoo._embeddings[f'glove-{name}-{size}'] = {
					'constructor': PretrainedGloVe,
					'name': name,
					'ndims': size
				}

		Zoo._initialized = True

	@staticmethod
	def _download(url, force_download=False):
		cache_path = make_cache_path()

		download_path = cache_path / "models"
		download_path.mkdir(exist_ok=True, parents=True)

		return download(url, download_path, force_download=force_download)

	@staticmethod
	def list():
		Zoo._init()
		return tuple(sorted(Zoo._embeddings.keys()))

	@staticmethod
	def load(name, force_download=False):
		Zoo._init()
		spec = Zoo._embeddings.get(name)
		if spec is None:
			raise ValueError(f"unknown embedding name {name}")
		kwargs = dict((k, v) for k, v in spec.items() if k not in ("constructor", "url"))
		if "url" in spec:
			kwargs["path"] = Zoo._download(spec["url"], force_download)
		return spec["constructor"](**kwargs)


from collections import defaultdict
import os

runtest = False
stardate = 25
if runtest:
    print("USING TESTDATA")
dataname = f"dec{stardate}{'test' if runtest else ''}.txt"

filename = f'{os.path.dirname(os.path.abspath(__file__))}\\{dataname}'
data = open(filename, "r").read().splitlines()

def decode(s) -> int:
    values = {
        "=": -2,
        "-": -1,
        "0": 0,
        "1": 1,
        "2": 2
    }
    return sum(values[c] * (5 ** p) for p, c in enumerate(s[::-1]))

snafu = {
    0: "0",
    1: "1",
    2: "2",
    3: "=",
    4: "-"
}

def encode(n):
    if n == 0:
        return ""
    d, r = divmod(n, 5)
    if r in [3, 4]:
        d += 1
    return encode(d) + snafu[r]

def star1():
    n = sum(decode(_) for _ in data)
    return encode(n)

print("star1:", star1())


from django.conf import settings
from django.conf.urls.defaults import patterns, include, handler404
from django.views.generic.simple import direct_to_template, redirect_to

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('channelguide.guide.views',
    (r'^$', 'frontpage.index'),
    (r'^admin/(.*)$', admin.site.root),
    (r'^favicon.ico$', redirect_to, {'url': '/images/favicon.ico'}),
    (r'^frontpage$', 'frontpage.index'),
    (r'^frontpage/edit-header$', 'frontpage.edit_header'),
    (r'^audio/', include('channelguide.guide.audio_urlconf')),
    (r'^firsttime$', 'firsttime.index'),
    (r'^accounts/', include('channelguide.user_profile.urls')),
    (r'^accounts/', include('django.contrib.auth.urls')),
    (r'^languages/', include('channelguide.labels.languages.urls')),
    (r'^notes/', include('channelguide.notes.urls')),
    (r'^watch/', include('channelguide.cobranding.urls')),
    (r'^i18n/setlang/?', 'i18n.set_language'),
    (r'^api/', include('channelguide.api.urls')),
    (r'^recommend/', include('channelguide.recommendations.urls')),
    (r'^ping/', include('channelguide.watched.urls')),
    (r'^submit/?', include('channelguide.submit.urls')),
    (r'^share/', include('channelguide.sharing.urls')),
    (r'^genres/', include('channelguide.labels.categories.urls')),
    (r'^tags/', include('channelguide.labels.tags.urls')),
    (r'^dmca$', direct_to_template,
     {'template': 'guide/dmca.html'}))

urlpatterns += patterns('channelguide.moderate.views',
    (r'^moderate$', 'index'),
    (r'^how-to-moderate$', 'how_to_moderate'),
    (r'^moderate/', include('channelguide.moderate.urls')))

urlpatterns += patterns('channelguide.search.views',
    (r'^search$', 'search'),
    (r'^search-more-channels$', redirect_to, {'url': '/search'}),
    (r'^search-more-items$', redirect_to, {'url': '/search'}))

urlpatterns += patterns('channelguide.user_profile.views',
    (r'^user/(.*)$', 'for_user'))

# new channel pages
urlpatterns += patterns('channelguide.channels.views',
                        (r'^popular/?$', 'filtered_listing', {
                    'filter': 'name',
                    'default_sort': '-popular',
                    'title': 'Popular Shows'}),
                        (r'^toprated/?$', 'filtered_listing', {
                    'filter': 'name',
                    'default_sort': '-rating',
                    'title': 'Top-Rated Shows'}),
                        (r'^feeds/?$', 'filtered_listing', {
                    'filter': 'feed',
                    'value': True,
                    'title': 'Feeds'}),
                        (r'^sites/?$', 'filtered_listing', {
                     'filter': 'feed',
                     'value':  False,
                     'title': 'Sites'}),
                        (r'^new/?$', 'filtered_listing', {
                    'filter': 'name',
                    'default_sort': '-age',
                    'title': 'New Shows'}),
                        (r'^featured/?$', 'filtered_listing', {
                    'filter': 'featured',
                    'value': True,
                    'title': 'Featured Shows'}),
                        (r'^hd/?$', 'filtered_listing', {
                    'filter': 'hd',
                    'value': True,
                    'title': 'High-Definition Shows'}),
                        (r'^(feeds|sites)/', include('channelguide.channels.urls')),
                        )

urlpatterns += patterns('channelguide.channels.playback',
                        (r'^items/(\d+)/?$', 'item'))

# donation pages
def donate_render(request, template):
    context = {'request': request,
               'google_analytics_ua': settings.GOOGLE_ANALYTICS_UA,
               'BASE_URL': settings.BASE_URL,
               'BASE_URL_FULL': settings.BASE_URL_FULL,
               'PAYPAL_URL': 'https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=donate%40pculture%2eorg&item_name=Tax%20Deductible%20Donation%20to%20Miro&page_style=MiroStore&no_shipping=1&return=https%3a%2f%2fwww%2emiroguide%2ecom%2fdonate%2fthanks&no_note=1&tax=0&currency_code=USD&lc=US&bn=PP%2dDonationsBF&charset=UTF%2d8',
               'CC_URL': 'https://www.getmiro.com/about/donate/cc-guide.html',
              }
    return direct_to_template(request,
                              template=template,
                              extra_context = context)

def donate_thanks(request):
    response = donate_render(request, template='donate/thanks.html')
    if 'donate_donated' not in request.COOKIES:
        response.set_cookie('donate_donated', 'yes', max_age=60*60*24*30,
                            secure=settings.USE_SECURE_COOKIES or None)
    return response

urlpatterns += patterns('',
                        (r'^donate$', donate_render, {
    'template': 'donate/donate.html'}),
                        (r'^donate/special$', donate_render, {
    'template': 'donate/special.html'}),
                        (r'^donate/biz$', donate_render, {
    'template': 'donate/biz.html'}),
                        (r'^donate/thanks$', donate_thanks),
                        )

# RSS feeds
from channelguide.guide import feeds

urlpatterns += patterns('',
    (r'^rss/(?P<name>new|featured|popular|toprated)/?', redirect_to,
     {'url': 'http://feeds.feedburner.com/miroguide/%(name)s'}))

urlpatterns = urlpatterns + patterns('',
    (r'^(?:rss|feeds)(?:_real)?/(?P<url>.*)$', feeds.cached_feed,
        {'feed_dict':
            {   'new': feeds.NewChannelsFeed,
                'features': feeds.FeaturedChannelsFeed,
                'featured': feeds.FeaturedChannelsFeed,
                'popular': feeds.PopularChannelsFeed,
                'toprated': feeds.TopRatedChannelsFeed,
                'categories': feeds.CategoriesFeed,
                'tags': feeds.TagsFeed,
                'languages': feeds.LanguagesFeed,
                'search': feeds.SearchFeed,
                'recommend': feeds.RecommendationsFeed}
        }),
    # be backwards compatible even though we're using /feeds/* for something
    # else now
    (r'^feeds/(?P<name>(new|featured|popular|toprated|categories|tags|languages|search|recommend).*)$',
     redirect_to, {'url': '/rss/%(name)s'}),
    (r'^feeds/features/?$', redirect_to, {'url': '/rss/featured'}),
)

# backwards compatible URLs
urlpatterns += patterns('',
                        (r'^browse/$', redirect_to, {'url': None}),
                        (r'^category-peek-fragment$', redirect_to,
                         {'url': None}),
                        (r'^channels/', include('channelguide.channels.urls')),
                        (r'^categories/', include('channelguide.labels.categories.urls')),
                        (r'^cobranding/', include('channelguide.cobranding.urls')))

js_info_dict = {
    'packages': ('channelguide.guide',),
}

urlpatterns += patterns('',
    (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
)

handler500 = 'channelguide.guide.views.errors.error_500'

if settings.DEBUG:
    import os
    static_patterns = []
    for dir in ('css', 'images', 'js', 'movies', 'swf'):
        static_patterns.append((r'^%s/(?P<path>.*)$' % dir,
            'django.views.static.serve',
            {'document_root': os.path.join(settings.STATIC_DIR, dir)}))
    urlpatterns.extend(patterns ('', *static_patterns))
    urlpatterns += patterns('',
                            (r'^media/(?P<path>.*)$',
                             'django.views.static.serve',
                             {'document_root': settings.MEDIA_ROOT}))


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

import os
import sys
import json
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QUrl
import requests
import threading
from .utils import registerContext, duration_to_string
from dwidgets import dthread
import copy
from log import logger

songlist = {
    u'新歌榜': 'http://music.haosou.com/data/top/top_new.json',
    u'热歌榜': 'http://music.haosou.com/data/top/top_hot.json',
    u'咪咕音乐榜': 'http://music.haosou.com/data/top/top_migu.json',
    u'网络流行榜': 'http://music.haosou.com/data/top/top_internet.json',
    u'中国歌曲排行榜': 'http://music.haosou.com/data/top/top_zggqphb.json',
    u'日本ORICON': 'http://music.haosou.com/data/top/top_gongxin.json',
    u'英国UK Official': 'http://music.haosou.com/data/top/top_uk.json',
    u'美国The Billboard': 'http://music.haosou.com/data/top/top_bill.json',
    u'Channel V': 'http://music.haosou.com/data/top/top_channelv.json',
    u'香港中文龙虎榜': 'http://music.haosou.com/data/top/top_zwlhb.json',
    u'经典老歌': 'http://music.haosou.com/data/top/top_classic.json'
}

class Web360ApiWorker(QObject):

    #py2py
    playMediaContent = pyqtSignal('QVariant')
    swicthMediaContent = pyqtSignal('QVariant')

    addMediaContents = pyqtSignal(list)
    addMediaContent = pyqtSignal('QVariant')
    addMediaContentToFavorite = pyqtSignal('QVariant')
    removeMediaContentFromFavorite = pyqtSignal('QString')

    downloadSongConetent = pyqtSignal(dict)
    resultsCollected = pyqtSignal(int, dict)

    # qml2py
    playMusicByIdSignal = pyqtSignal(int)
    playMusicByIdsSignal = pyqtSignal('QString')
    playSonglistByNameSignal = pyqtSignal('QString')
    playSonglistByIdSignal = pyqtSignal(int)
    playAlbumByIdSignal = pyqtSignal(int)
    addFavoriteSignal = pyqtSignal(int)
    removeFavoriteSignal = pyqtSignal(int)
    downloadSongSignal = pyqtSignal(int)
    downloadSongsSignal = pyqtSignal('QString')

    __contextName__ = 'Web360ApiWorker'

    @registerContext
    def __init__(self, parent=None):
        super(Web360ApiWorker, self).__init__(parent)
        self.playedMusics = {}
        self.recommendedMusics = {}
        self.recommendedmusicIds = {}
        self._results = {}
        self._musicIds = []
        self.initConnect()

    def initConnect(self):
        self.playMusicByIdSignal.connect(self.playMusicById)
        self.playMusicByIdsSignal.connect(self.playMusicByIds)
        self.playSonglistByNameSignal.connect(self.playMusicBySonglistName)
        self.playSonglistByIdSignal.connect(self.playMusicBySonglistId)
        self.playAlbumByIdSignal.connect(self.playMusicByAlbumId)

        self.addFavoriteSignal.connect(self.addMusicToFavorite)
        self.removeFavoriteSignal.connect(self.removeMusicFromFavorite)

        self.downloadSongSignal.connect(self.downloadSong)
        self.downloadSongsSignal.connect(self.downloadSongs)

        self.resultsCollected.connect(self.collectResult)

    @classmethod
    def md5(cls, musicId):
        import hashlib
        s = 'id=%s_projectName=linuxdeepin' % (musicId)
        md5Value = hashlib.md5(s)
        return md5Value.hexdigest()

    @classmethod
    def md5s(cls, musicIds):
        import hashlib
        s = 'ids=%s_projectName=linuxdeepin' % (musicIds)
        md5Value = hashlib.md5(s)
        return md5Value.hexdigest()

    @classmethod
    def getUrlByID(cls, musicId):
        sign = cls.md5(musicId)
        params = {
            'id': musicId,
            'src': 'linuxdeepin',
            'sign': sign
        }

        url = 'http://s.music.haosou.com/player/songForPartner?id=%s&src=%s&sign=%s'\
            %(params['id'], params['src'], params['sign'])
        return url

    @classmethod
    def getUrlByIDs(cls, musicIds):
        sign = cls.md5s(musicIds)
        params = {
            'ids': musicIds,
            'src': 'linuxdeepin',
            'sign': sign
        }

        url = 'http://s.music.haosou.com/player/songlistForPartner?ids=%s&src=%s&sign=%s'\
            %(params['ids'], params['src'], params['sign'])
        return url

    @classmethod
    def getDownloadUrl(self, musicId):
        url = "http://s.music.haosou.com/player/zdown?projectName=linuxdeepin&id=%s" % musicId
        return url

    @classmethod
    def request(cls, url, count=5):
        result = None
        ret = None
        i = 0
        while i < count:
            try:
                ret = requests.get(url)
                result = ret.json()
                if isinstance(result, dict):
                    break
                else:
                    i = i + 1
            except ValueError:
                result = ret.text
                break
            except:
                i = i + 1
        return result

    def getResultById(self, musicId):
        url = self.getUrlByID(musicId)
        result = self.getResultByUrl(url)

        return result

    @classmethod
    def getResultByUrl(cls, url):
        tags = cls.request(url)
        if isinstance(tags, list) and not tags:
            tags = None
        else:
            tags.update({'url': url})

        return tags

    @pyqtSlot(int)
    def playMusicById(self, musicId):
        self.playMediaById(musicId)

    @dthread
    @pyqtSlot('QString')
    def playMusicByIds(self, musicIds):
        print(threading.currentThread())
        url = self.getUrlByIDs(musicIds)
        songLists = self.request(url)

        results = []
        for song in songLists:
            url = self.getUrlByID(song['songId'])
            song.update({'url': url})
            results.append(song)

        if results:
            self.addMediaContents.emit(results)
            url = self.getUrlByID(songLists[0]['songId'])
            self.playMediaByUrl(url)

    @dthread
    @pyqtSlot(int)
    def playMediaById(self, musicId):
        result = self.getResultById(musicId)
        if result:
            self.addMediaContent.emit(result)
            self.playMediaContent.emit(result)

    @dthread
    @pyqtSlot('QString')
    def playMediaByUrl(self, url):
        result = self.getResultByUrl(url)
        if result:
            self.playMediaContent.emit(result)

    @dthread
    @pyqtSlot('QString')
    def switchMediaByUrl(self, url):
        result = self.getResultByUrl(url)
        if result:
            self.swicthMediaContent.emit(result)

    @classmethod
    def getSongList(self, ret):
        results = []
        if 'songList' in ret:
            for song in ret['songList']:
                url = self.getUrlByID(song['songId'])
                tags = song
                tags.update({'url': url})
                results.append(tags)
        return results

    @dthread
    @pyqtSlot('QString')
    def playMusicBySonglistName(self, songlistName):
        if songlistName in songlist:
            url = songlist[songlistName]
            result = self.request(url)
            if result:
                header = 'cb_' + url.split('/')[-1].split('.')[0]
                content = result[len(header) + 1: -1]
                ret = json.loads(content)
                results = self.getSongList(ret)
                self.addMediaContents.emit(results)
                url = self.getUrlByID(ret['songList'][0]['songId'])
                self.playMediaByUrl(url)

    @dthread
    @pyqtSlot(int)
    def playMusicBySonglistId(self, songlistId):
        url = "http://s.music.haosou.com/list/intfDetail?id=%d" % songlistId
        ret = self.request(url)
        if ret:
            results = self.getSongList(ret)
            self.addMediaContents.emit(results)
            url = self.getUrlByID(ret['songList'][0]['songId'])
            self.playMediaByUrl(url)

    @dthread
    @pyqtSlot(int)
    def playMusicByAlbumId(self, albumId):
        url = "http://s.music.haosou.com/album/intfDetail?id=%d" % albumId
        ret = self.request(url)
        if ret:
            results = self.getSongList(ret)
            if results:
                for result in results:
                    result.update({
                        'singerId': ret['singerId'],
                        'singerName': ret['singerName'],
                        'albumId': ret['albumId'],
                        'albumName': ret['albumName']
                    })
                self.addMediaContents.emit(results)
                url = self.getUrlByID(ret['songList'][0]['songId'])
                self.playMediaByUrl(url)

    @pyqtSlot(int)
    def addMusicToFavorite(self, musicId):
        url = self.getUrlByID(musicId)
        tags = self.request(url)
        tags.update({'url': url})
        self.addMediaContentToFavorite.emit(tags)

    @pyqtSlot(int)
    def removeMusicFromFavorite(self, musicId):
        url = self.getUrlByID(musicId)
        self.removeMediaContentFromFavorite.emit(url)

    @dthread
    @pyqtSlot(int)
    def downloadSong(self, musicId):
        url = self.getDownloadUrl(musicId)
        result = self.request(url)
        if 'data' in result:
            self.downloadSongConetent.emit(result['data'])

    @dthread
    @pyqtSlot(int)
    def requestSong(self, musicId):
        url = self.getDownloadUrl(musicId)
        result = self.request(url)
        if 'data' in result:
            self.resultsCollected.emit(musicId, result['data'])

    @pyqtSlot('QString')
    def downloadSongs(self, musicIds):
        _musicIds = musicIds.split('_')
        for musicId in _musicIds:
            if musicId not in self._musicIds:
                self._musicIds.append(int(musicId))
                self.requestSong(int(musicId))

    @pyqtSlot(int, dict)
    def collectResult(self, musicId, result):
        self._results[musicId] = result
        _rmusicIds = copy.deepcopy(self._results.keys())
        _rmusicIds.sort()
        _musicIds = copy.deepcopy(self._musicIds)
        _musicIds.sort()

        if _rmusicIds == _musicIds:
            for musicId in self._musicIds:
                result = self._results[musicId]
                self.downloadSongConetent.emit(result)

            self._results = {}
            self._musicIds = []


import ujson
from aioredis import Redis
from constants.redis_key import JingXi
from app.deps import Depend
from app.schemas.response import CommonResponse, EmptyResponse
from app.src.jingxi.keyword_search import KeywordSearch
from fastapi import APIRouter

router = APIRouter(prefix="/jingxi", tags=["jingxi"])

@router.get("/keywordSearch", response_model=CommonResponse, name="关键词搜索")
async def keyword_search(
    keyword: str, page: int = 1, cache: Redis = Depend.redis30, session=Depend.session
):
    cache_key = f"{keyword}-{page}"
    data = await cache.hget(JingXi.KEYWORD_SEARCH_CACHE_HASH, cache_key)
    if data:
        return ujson.loads(data)
    else:
        KS = KeywordSearch(session)
        res = await KS.request(keyword, page)
        if res:
            content = CommonResponse(data=res.json())
            await cache.hset(
                JingXi.KEYWORD_SEARCH_CACHE_HASH, cache_key, content.json()
            )
            return content
        return EmptyResponse()


#Imports
import re
import pandas as pd
import json
import multiprocessing
import string
from gensim.models import Word2Vec
from gensim.models.phrases import Phrases, Phraser
from time import time
from collections import defaultdict
import numpy as np
import pdb

#Import Scikit
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split

#Import natural language toolkit
import nltk
nltk.download('punkt')

#Import spacy and load web model
import spacy
#Must download in terminal before loading it
spacy.load("en_core_web_sm")
from spacy.vocab import Vocab

#For timing processes
t = time()

#loading data
df = pd.read_csv("casual_data_windows.csv")
df = df.dropna().reset_index(drop=True)

#Loading spacy nlp
nlp = spacy.load("en_core_web_sm")

#Creating sentences to train w2v
sent = [row.split() for row in df['Person1']]
phrases = Phrases(sent, min_count=30, progress_per=10000)
bigram = Phraser(phrases)
sentences = bigram[sent]

biggestLen = 31
currentLen = 0
index = 0
vecsX = []
vecsY = []
sent = []

#Create X and y arrays
X = []
y = []

#Check num cores in computer for w2v model input
cores = multiprocessing.cpu_count()

#Create model
w2vModel = Word2Vec(min_count=20,
                  window=2,
                  size=300,
                  sample=6e-5,
                  alpha=0.03,
                  min_alpha=0.0007,
                  negative=20,
                  workers=cores-1)

# --------------------------------------------------------------------------------------

#Build vocab in Word2Vec model
print("Starting to build vocab...")
w2vModel.build_vocab(sentences, progress_per=10000)
#Print time taken to build vocab
print('Time to build vocab: {} mins'.format(round((time() - t) / 60, 2)))

# --------------------------------------------------------------------------------------

#Train Word2Vec Model
print("Starting to train Word2Vec...")
w2vModel.train(sentences, total_examples=w2vModel.corpus_count,
          epochs=20, report_delay=1)
print('Time to train the model: {} mins'.format(round((time() - t) / 60, 2)))

w2vModel.init_sims(replace=True)

print(len(df['Person1']))
print("Appending Data...")

#Append Vectorized data into X and y training sets
for x in range(0, int(len(df['Person1']) / 560)):
  for i in range(0, len(df['Person1'][x].split(" "))):
      if x < len(df['Person1']) - 1 and i < len(df['Person1'][x].split(" ")):
          vecsX.append(nlp(df['Person1'][x][i].lower()).vector_norm)
          print(x)

  for e in range(0, biggestLen - len(df['Person1'][x].split(" "))):
      vecsX.append(nlp("unnapliccable").vector_norm)

  X.append(vecsX)
  vecsX = []

  for l in range(0, len(df['Person1'][x].split(" "))):
      if x < len(df['Person1']) - 1 and l < len(df['Person1'][x].split(" ")):
          vecsY.append(nlp(df['Person1'][x][l].lower()).vector_norm)
          print(x)

  for r in range(0, biggestLen - len(df['Person1'][x].split(" "))):
      vecsY.append(nlp("unnapliccable").vector_norm)

  y.append(vecsY)
  vecsY = []

print('Time to append data: {} mins'.format(round((time() - t) / 60, 2)))
# sentend = np.ones

#Split train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)

#Create and fit model
clf = MLPRegressor().fit(X_train, y_train)

#User Input
inp = input("Say something:")

#Data cleaning
for k in range(0, len(inp.split(" "))):
  sent.append(nlp(inp[k].lower()).vector_norm)

for i in range(0, biggestLen - len(inp.split(" "))):
  sent.append(nlp("unnapliccable").vector_norm)

sent = [sent]

#Predicting
predictions = clf.predict(sent)
pdb.set_trace()
# outputlist = [w2vModel.wv.similar_by_vector([predictions[0][i], predictions[0][i]], topn=1)[0][0] for i in range(biggestLen)]
# output = ' '.join(outputlist)