import os
import time

# initialize the config file (or add one if not present)

def initialize_cfile():

    print("Initializing...")

    if not os.path.isfile("config.txt"):

            with open("config.txt", mode='a') as cfile:

                cfile.write("## Config file - CRYPER\n\n")
                cfile.write('# Any and all crypto currencies or government currencies shall be referred to as assets from this point on.\n\n\n')
                cfile.write('## USER DEFAULT SECTION ##\n\n')
                cfile.write('# Enter the API key provided by https://www.coinapi.io/\napi_key = \n\n')
                cfile.write('# Run mode flags are either \'a\' for all assets or \'x\' to view exchange rates for any two given currencies.\nrun_mode = \n\n')
                cfile.write('# Set this flag as your preferred asset that you wish to see the exchange rate of, IN ALL CAPS! ex. BTC, DOGE, USD, etc. Only has effect when the run mode is set to \'x\'. Equal to \'-c\' option. \ncrypto_currency = \n\n')
                cfile.write('# Set this flag as your preferred asset to match against, IN ALL CAPS. ex. DOGE, BTC, USD, etc. Equal to \'-m\' option. \nmatch_currency = \n\n')

                print("Configuration done!")
                time.sleep(1)
                os.system('clear')

    else:

        print("OK")
        time.sleep(1)
        os.system('clear')

def initialize_executable():

    destination_path = '/usr/local/bin/'

    script_loc = str(os.path.realpath('cryper.py'))
    init_loc = str(os.path.realpath('INIT.py'))
    ihcparser_loc = str(os.path.realpath('IHCparser.py'))

    if os.path.isdir(destination_path):
        pass

    else:
        os.system(destination_path)

    with open(script_loc) as main_file, open(init_loc) as init_mod, open(ihcparser_loc) as parser_mod:

        if os.path.isfile(destination_path) and os.path.isfile(destination_path) and os.path.isfile(destination_path):

            pass

        else:

            print('Attempting to change to executable')
            os.system('sudo chmod 755 ' + script_loc)
            os.system('sudo chmod 755 ' + init_loc)
            os.system('sudo chmod 755 ' + ihcparser_loc)
            os.system('sudo cp -i --preserve ' + script_loc + ' ' + destination_path + 'cryper')
            os.system('sudo cp -i --preserve ' + init_loc + ' ' + destination_path)
            os.system('sudo cp -i --preserve ' + ihcparser_loc + ' ' + destination_path)
            os.system('sudo touch ' + destination_path + '__init__.py')

            print('OK')
            time.sleep(1)
            os.system('clear')

            if os.path.isfile(destination_path + 'cryper') and os.path.isfile(destination_path + 'INIT.py') and os.path.isfile(destination_path + 'IHCparser.py'):

                print('OK')
                time.sleep(1)
                os.system('clear')

            else:
                print('Something went wrong.')


#!/usr/bin/python3

import os
import sys
import string
from pathlib import Path

word_freqs = []

with open(os.path.join(Path.cwd(), 'res/ignore-words.txt')) as f:
    ignore_words = f.read().split(',')
ignore_words.extend(list(string.ascii_lowercase))

for line in open(sys.argv[1]):
    start_index = None
    i = 0
    for c in line:
        if start_index == None:
            if c.isalnum():
                start_index = i
        else:
            if not c.isalnum():
                found = False
                word = line[start_index:i].lower()
                if word not in ignore_words:
                    pair_index = 0
                    for pair in word_freqs:
                        if word == pair[0]:
                            pair[1] += 1
                            found = True
                            break
                        pair_index += 1
                    if not found:
                        word_freqs.append([word, 1])
                    elif len(word_freqs) > 1:
                        for n in reversed(range(pair_index)):
                            if word_freqs[pair_index][1] > word_freqs[n][1]:
                                word_freqs[n], word_freqs[pair_index] = word_freqs[pair_index], word_freqs[n]
                                pair_index = n
                start_index = None
        i += 1

for wf in word_freqs[0:25]:
    print(f"{wf[0]} - {wf[1]}")


import argparse
import os

import numpy as np
import open3d.ml as _ml3d
import open3d.ml.torch as ml3d

def parse_args():
    parser = argparse.ArgumentParser(
        description = "Applies Object Detection Models (PointPillars \
                        or PointRCNN(requires cuda) on Raw Kitti Data \
                        Frame")

    parser.add_argument('--model', help = "Object Detection model\
                                                PointPillars or \
                                                PointRCNN",
                        default = 'PointPillars',
                        required = False)

    parser.add_argument('--dataset_path', help = "Path to Datataset \n\
                                                eg: './sampledatasets/0001'",
                        default = './sample_datasets/0001')

    parser.add_argument('--frame', help = "Select Frame from dataset",
                        default = 1, type = int)

    parser.add_argument('--fv', help = "To Visualise Front-View Only",
                        default = 1, type = int)

    parser.add_argument('--cam2cam_calib_path', help = "Path to cam_to_cam \
                                                calibration file")

    parser.add_argument('--velo2cam_calib_path', help = "Path to velo_to_cam \
                                                calibration file")

    parser.add_argument('--config_path', help = "Path to Configuration File")

    parser.add_argument('--ckpt_path', help = "Path to pretrained model")

    parser.add_argument('--device', help = "Specify device (cpu or cuda)",
                        default = 'cpu')

    args, _ = parser.parse_known_args()

    dict_args = vars(args)
    for k in dict_args:
        v = dict_args[k]
        print("{}: {}".format(k, v) if v is not None else "{} not provided".
              format(k))

    return args

def get_calib(dataset_path, calib_1, calib_2):
    if calib_1 is not None:
        cam2cam_calib_path = calib_1
    else:
        cam2cam_calib_path = dataset_path + "/calib_cam_to_cam.txt"
    if calib_2 is not None:
        velo2cam_calib_path = calib_2
    else:
        velo2cam_calib_path = dataset_path + "/calib_velo_to_cam.txt"

    with open(cam2cam_calib_path, 'r') as f:
        lines = f.readlines()

    P2 = list(filter(lambda a: 'P_rect_02' in a, lines))
    P2 = P2[0].strip().split(' ')[1:]
    P2 = np.array(P2, dtype=np.float32).reshape(3, 4)
    P2 = np.concatenate((P2, np.array([[0., 0., 1., 0.]],
                                        dtype=np.float32)), axis=0)

    _rect_4x4 = list(filter(lambda a: 'R_rect_00' in a, lines))
    _rect_4x4 = _rect_4x4[0].strip().split(' ')[1:]
    rect_4x4 = np.eye(4, dtype=np.float32)
    rect_4x4[:3, :3] = np.array(_rect_4x4, dtype=np.float32).reshape(3, 3)

    with open(velo2cam_calib_path, 'r') as f:
        lines = f.readlines()

    _Tr_velo2cam_R = list(filter(lambda a: 'R' in a, lines))
    _Tr_velo2cam_R = _Tr_velo2cam_R[0].strip().split(' ')[1:]
    _Tr_velo2cam_T = list(filter(lambda a: 'T' in a, lines))
    _Tr_velo2cam_T = _Tr_velo2cam_T[0].strip().split(' ')[1:]
    _Tr_velo2cam = _Tr_velo2cam_R + _Tr_velo2cam_T
    Tr_velo_to_cam = np.eye(4, dtype=np.float32)
    Tr_velo_to_cam[:3] = np.array(_Tr_velo2cam,
                                dtype=np.float32).reshape(3, 4)

    world_cam = np.transpose(rect_4x4 @ Tr_velo_to_cam)
    cam_img = np.transpose(P2)

    return {'world_cam': world_cam, 'cam_img': cam_img}

def extract_pc_data(dataset_path, frame, fv):
    data_path = dataset_path + "/velodyne_points/data/"

    count = 0
    for files in os.listdir(data_path):

        if files.startswith('0') and files.endswith('.bin'):
            if count==frame:
                pc_file = data_path + files

                points = np.fromfile(pc_file, dtype=np.float32, count=-1,
                                    sep='', offset=0)
                X = points[0::4]
                Y = points[1::4]
                Z = points[2::4]
                W = points[3::4]

                pc = np.zeros((np.size(X), 4))
                pc[:, 0] = X
                pc[:, 1] = Y
                pc[:, 2] = Z
                pc[:, 3] = W

            else:
                count += 1

    if fv == 1:
        point_cloud_range = [0, -39.68, -3, 69.12, 39.68, 1]
        min_val = np.array(point_cloud_range[:3])
        max_val = np.array(point_cloud_range[3:])
        pcd = np.array(pc[:, 0:4], dtype=np.float32)
        pcd = pcd[np.where(
                    np.all(np.logical_and(pc[:, :3] >= min_val,
                                            pc[:, :3] < max_val),
                                            axis=-1))]
        return pcd

    return pc

def main(args):
    if args.config_path is not None:
        cfg_path = args.config_path
    else:
        cfg_path = "configs/" + args.model.lower() + ".yml"
    if args.ckpt_path is not None:
        ckpt_path = args.ckpt_path
    else:
        ckpt_path = "./pretrained_ckpt/" + args.model.lower() + ".pth"

    cfg = _ml3d.utils.Config.load_from_file(cfg_path)
    model_ = _ml3d.utils.get_module("model", args.model, "torch")
    model = model_(device = args.device, **cfg.model)
    pipeline = ml3d.pipelines.ObjectDetection(model, device = args.device,
                                                **cfg.pipeline)
    pipeline.load_ckpt(ckpt_path = ckpt_path)

    calib = get_calib(args.dataset_path, args.cam2cam_calib_path,
                        args.velo2cam_calib_path)

    points = extract_pc_data(args.dataset_path, args.frame, args.fv)

    data = {
            'point': points,
            'calib': calib
        }

    results = pipeline.run_inference(data)[0]

    vis = ml3d.vis.Visualizer()
    vis.visualize([{
        'name': "Kitti_Frame_" + str(args.frame),
        'points': points
        }], bounding_boxes = results)

    return

if __name__ == '__main__':
    args = parse_args()
    main(args)


from pprint import pprint
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
import re

def run_driver():
    chrome_options = Options()  # add options for chrome driver

    chrome_options.add_argument('--headless')  # no window
    chrome_options.add_argument('--log-level=3')  # no logging

    driver = webdriver.Chrome('chromedriver.exe', options=chrome_options)
    return driver

def create_local_html_page(page_filename, page_source):
    with open(page_filename + '.html',mode= 'w',encoding='UTF-8') as file:
        file.write(page_source)  # make local .html

def get_local_html_page(page_filename, url):

    driver = run_driver()

    driver.get(url)
    create_local_html_page(page_filename, driver.page_source)
    path_to_local_html_page = str('file://' + os.getcwd() + '\\' + page_filename + '.html')

    driver.get(path_to_local_html_page)

    return driver

def delete_local_html_page(page_path):
    os.remove(page_path)

def get_albums(yandex_username):
    url = 'https://music.yandex.ru/users/' + yandex_username + '/albums/'

    driver = get_local_html_page('album_page', url)

    mu_json = driver.execute_script('return Mu')

    albums_artists = {}

    albums_ids = mu_json['pageData']['albumIds']

    for album_id in albums_ids:  # fill albums_artists
        try:
            driver.get('https://music.yandex.ru/album/' + str(album_id))

            albums_artists[album_id] = {}

            albums_artists[album_id]['album_title'] = driver.find_element_by_xpath(
                    "//h1[@class='deco-typo']").text  # get album name

            albums_artists[album_id]['artist_name'] = driver.find_element_by_xpath(
                    "//span[@class='d-artists']//a[@class='d-link deco-link']").text  # get artist name

        except:
            raise Exception

    delete_local_html_page('album_page.html')
    driver.quit()

    return  albums_artists

def get_my_playlists_id(yandex_username):
    url = 'https://music.yandex.ru/users/'+ yandex_username + '/playlists/'

    driver = get_local_html_page('playlist_page', url)

    mu_json = driver.execute_script('return Mu')
    # get playlist ids
    my_playlists_id = mu_json['pageData']['playlistIds']

    return my_playlists_id

def get_my_playlists(yandex_username):
    # get playlist ids
    my_playlists_id = get_my_playlists_id(yandex_username)
    my_playlists_for_spotify = {}

    for pl_id in my_playlists_id:
        # создадим ссылку на плейлист
        my_playlist_url = 'https://music.yandex.ru/users/' + yandex_username + '/playlists/' + str(pl_id)
        # создадим и перейдем на локальную страницу плейлиста
        driver = get_local_html_page('my_playlist', my_playlist_url)
        # получим массив с данными плейлистов
        mu_json = driver.execute_script('return Mu')

        # создадим словарь, в который запишем название трека и имя исполнителя
        my_playlists = {}
        # получим из json значение id трека и id плейлиста в формате track_id:playlist_id
        all_track_ids = mu_json['pageData']['playlist']['trackIds']
        # получим название плейлиста
        playlist_name = mu_json['pageData']['playlist']['title']

        for i in all_track_ids:
        # получим id трека
            track_id = re.findall(r'\d+(?=:)', i)[0]
        # перейдем на страницу трека
            driver.get(''.join(['https://music.yandex.ru/track/', track_id]))
        # создадим вложенный словарь для каждого плейлиста
            my_playlists[i] = {}
        # запишем в словарь название трека
            try:
                my_playlists[i]['track_name'] = \
                driver.find_elements_by_xpath("//span[@class='']//a[@class='d-link deco-link']")[0].text
            except:
                my_playlists[i]['track_name'] = ['']
                # запишем в словарь имя исполнителя
            try:
                my_playlists[i]['artist_name'] = driver.find_elements_by_xpath(
                    "//span[@class='d-artists']//a[@class='d-link deco-link']")[0].text
            except:
                my_playlists[i]['track_name'] = ['']

            # запишем в словарь название плейлиста, его треки и имена исполнителей
        my_playlists_for_spotify[playlist_name] = my_playlists

        # удалим локальный html-файл
        delete_local_html_page('my_playlist.html')

        # закроем браузер
        driver.quit()

    return my_playlists_for_spotify

def get_liked_playlists_data(yandex_username):
    url = 'https://music.yandex.ru/users/' + yandex_username + '/playlists/'

    driver = get_local_html_page('playlist_page', url)

    mu_json = driver.execute_script('return Mu')

    liked_playlists_data = {}

    bookmarked_playlists_data = mu_json['pageData']['bookmarks']

    for i in range(len(bookmarked_playlists_data)):
        try:
            # создадим вложенный словарь для каждого плейлиста
            liked_playlists_data[i] = {}
            # запишем во вложенный словарь id плейлиста
            liked_playlists_data[i]['id'] = bookmarked_playlists_data[i]['kind']
            # запишем во вложенный словарь имя пользователя
            liked_playlists_data[i]['yandex_username'] = bookmarked_playlists_data[i]['owner']['login']
            # запишем во вложенный словарь название плейлиста
            liked_playlists_data[i]['playlist_title'] = bookmarked_playlists_data[i]['title']
        except:
            pass

        delete_local_html_page('playlist_page.html')

        return liked_playlists_data

def get_liked_playlists(yandex_username):
    liked_playlists_data = get_liked_playlists_data(yandex_username)

    liked_playlists_for_spotify = {}

    for key, value in liked_playlists_data.items():

        url = 'https://music.yandex.ru/users/' + \
               str(value['yandex_username']) + \
               '/playlists/' + str(value['id'])

        driver = get_local_html_page(str(key), url)

        mu_json = driver.execute_script('return Mu')

        liked_playlists = {}

        all_track_ids = mu_json['pageData']['playlist']['trackIds']
        playlist_name = mu_json['pageData']['playlist']['title']

        for i in all_track_ids:
            try:
                track_id = re.findall(r'\d+(?=:)', all_track_ids[i])[0]

                driver.get(''.join(['https://music.yandex.ru/track/', track_id]))

                liked_playlists[i] = {}

                try:
                    liked_playlists[i]['track_name'] = \
                    driver.find_elements_by_xpath("//span[@class='']//a[@class='d-link deco-link']")[0].text
                except:
                    liked_playlists[i]['track_name'] = ['']

                try:
                    liked_playlists[i]['artist_name'] = driver.find_elements_by_xpath(
                        "//span[@class='d-artists']//a[@class='d-link deco-link']")[0].text
                except:
                    liked_playlists[i]['artist_name'] = ['']

            except:
                pass

        liked_playlists_for_spotify[playlist_name] = liked_playlists

        delete_local_html_page(str(key) + '.html')

        driver.quit()

    return  liked_playlists_for_spotify

def get_liked_on_radio(yandex_username):

    liked_on_radio_id = 101

    liked_on_radio_for_spotify = {}

    url = 'https://music.yandex.ru/users/' + yandex_username + '/playlists/' + str(liked_on_radio_id)

    driver = get_local_html_page('liked_on_radio', url)

    mu_json = driver.execute_script('return Mu')

    liked_on_radio = {}

    all_track_ids = mu_json['pageData']['playlist']['trackIds']
    playlist_name = mu_json['pageData']['playlist']['title']

    for i in all_track_ids:
        try:
            track_id = re.findall(r'\d+(?=:)', i)[0]

            driver.get(''.join(['https://music.yandex.ru/track/', track_id]))

            liked_on_radio[i] = {}

            try:
                liked_on_radio[i]['track_name'] = \
                    driver.find_elements_by_xpath("//span[@class='']//a[@class='d-link deco-link']")[0].text
            except:
                liked_on_radio[i]['track_name'] = ['']

            try:
                liked_on_radio[i]['artist_name'] = driver.find_elements_by_xpath(
                    "//span[@class='d-artists']//a[@class='d-link deco-link']")[0].text
            except:
                liked_on_radio[i]['artist_name'] = ['']

        except:
            pass

    liked_on_radio_for_spotify[playlist_name] = liked_on_radio

    delete_local_html_page('liked_on_radio.html')

    driver.quit()

    return liked_on_radio_for_spotify


# Let -- Parse tree node strategy for printing the special form let

from Tree import Nil
from Tree import Environment
from Print import Printer
from Special import Special

class Let(Special):
    def __init__(self):
        pass

    def print(self, t, n, p):
        Printer.printLet(t, n, p)

    def eval(self, exp, env):
        env2 = Environment(env)
        cdrCdr = exp.getCdr().getCdr()
        cdrCar = exp.getCdr().getCar()
        expLen = Special.util.length(exp)
        if expLen < 3:
            self._error('expression is invalid')
            return Nil.getInstance()
        expLen = Special.util.length(cdrCar)
        if expLen < 1:
            self._error('expression is invalid')
            return Nil.getInstance()
        if self.det(cdrCar, env, env2) < 0:
            self._error('expression is invalid')
            return Nil.getInstance()
        return Special.util.begin(cdrCdr, env2)

    def det(self, cdrCar, env, env2):
        #cdrCar tests
        if cdrCar.isNull():
            return 0
        cdCarCar = cdrCar.getCar()
        if Special.util.length(cdCarCar) != 2:
            return -1

        a = cdCarCar.getCar()
        b = cdCarCar.getCdr().getCar().eval(env)
        env2.define(a, b)
        return self.det(cdrCar.getCdr(), env, env2)


"""Program used to test the implementation of our classes"""

import farm
from farm import Farm
import sensor
from sensor import Sensor
import score

def main():
    testfarm = Farm((0,0))
    senone = Sensor((44.790300, -92.931998))
    sentwo = Sensor((44.790300, -92.931998))
    senthree = Sensor((44.790300, -92.931998))

    testfarm.add_sensor(senone)
    testfarm.add_sensor(sentwo)
    testfarm.add_sensor(senthree)

    testfarm.pull_current()
    testfarm.pull_forecast()

    print("\n\n\nRandomized Example Sensor Data")
    print("------------------------------")

    i = 0
    while i < len(testfarm.sensors):
        print("sensor " + str(i + 1))
        print(testfarm.sensors[i].point)
        i += 1

    print("\n\n\nExample Aggregate Scores")
    print("------------------------")

    box = score.score(testfarm, senone.point, senone)

    list = []
    for datapoints in testfarm.future_forecast:
        box = score.aggregateScore(testfarm, datapoints, senone)
        list.append(box)

    print(list)

main()


import torch
import torch.nn as nn
import torch.nn.functional as F

from ...configs.model_configs import MODEL1_EMBEDDING_DIM, MODEL1_DECODER_HIDDEN_DIM, MODEL1_DECODER_NUM_LAYERS, MODEL1_DECODER_RNN_DROPOUT_P, MODEL1_DECODER_NUM_ATTENTION_HEAD, MODEL1_DECODER_ATTENTION_DROPOUT_P, MODEL1_ACTIVATION, MODEL1_DECODER_INPUT_FEEDING_FC_DROPOUT_P, MODEL1_DECODER_ATTENTIONAL_FC_OUT_DIM

class Decoder1(nn.Module):
    def __init__(
        self,
        vocab_size: int,
        embedding_dim: int = MODEL1_EMBEDDING_DIM,
        hidden_dim: int = MODEL1_DECODER_HIDDEN_DIM,
        num_layers: int = MODEL1_DECODER_NUM_LAYERS,
        rnn_dropout_p: float = MODEL1_DECODER_RNN_DROPOUT_P,
        num_attention_head: int = MODEL1_DECODER_NUM_ATTENTION_HEAD,
        attention_dropout_p: float = MODEL1_DECODER_ATTENTION_DROPOUT_P,
        activation: str = MODEL1_ACTIVATION,
        input_feeding_fc_dropout_p: float = MODEL1_DECODER_INPUT_FEEDING_FC_DROPOUT_P,
        attentional_fc_out_dim: int = MODEL1_DECODER_ATTENTIONAL_FC_OUT_DIM,
        ) -> None:
        """Decoder RNN using LSTM.\n
        Expected to create batch_size of singleton outputs in decoding.
        """
        super(Decoder1, self).__init__()
        self.rnn = nn.LSTM(
            input_size=embedding_dim,
            hidden_size=hidden_dim,
            num_layers=num_layers,
            batch_first=True,
            dropout=rnn_dropout_p,
            bidirectional=False
            )

        self.attention = nn.MultiheadAttention(
            embed_dim=hidden_dim,
            num_heads=num_attention_head,
            dropout=attention_dropout_p,
            kdim=hidden_dim, # by assumption of using Encoder1, which matches Decoder1 hidden_dim
            vdim=hidden_dim, # by assumption of using Encoder1, which matches Decoder1 hidden_dim
            batch_first=True
            )

        self.input_feeding_fc = nn.Linear(attentional_fc_out_dim+embedding_dim, embedding_dim)
        self.input_feeding_fc_dropout = nn.Dropout(p=input_feeding_fc_dropout_p)

        if activation == "gelu":
            self.activation = F.gelu
        elif activation == "relu":
            self.activation = F.relu
        else:
            raise NotImplementedError(f"Activation function not supported. Expects 'relu' or 'gelu'. Got {activation}")

        self.attentional_fc = nn.Linear(hidden_dim+hidden_dim, attentional_fc_out_dim) # the context vector embedding dim is hidden_dim (see self.attention), hidden state dim is hidden_dim (see self.rnn), output dim is set to attentional_fc_out_dim.

        self.logits_fc = nn.Linear(attentional_fc_out_dim, vocab_size)

    def forward(
        self,
        embedded: torch.Tensor,
        hidden: torch.Tensor,
        cell: torch.Tensor,
        padded_encoder_outputs: torch.Tensor,
        attention_key_padding_masks: torch.Tensor,
        prev_attentional_vectors: torch.Tensor = None,
        ):
        r"""Expects `embedded` to be a tensor with shape [batch size, 1, embedding_dim].

        `hidden` is expected to be a tensor with shape [num_layers, batch size, hidden_dim]

        `cell` is expected to be a tensor with shape [num_layers, batch size, hidden_dim]

        `padded_encoder_outputs` is expected to be returned by a `pad_packed_sequence` call. The shape is expected to be [batch size, longest source seq len, kdim=hidden_dim]. The attention mask will deal with the handling of paddings.

        `attention_key_padding_mask` is expected to be returned by the helper function `compute_attention_key_padding_mask` when called on the sequence length tensor obtained as the other returned output of the `pad_packed_sequence` call used to create `padded_encoder_outputs`.

        `prev_attentional_vectors` is expected to be a tensor with shape [batch size, 1, attentional_fc_out_dim].

        Returns a 5-tuple of Tensors:

        hidden                  with shape [num_layers, batch size, hidden_dim]

        cell                    with shape [num_layers, batch size, hidden_dim]

        attn_output_weights     with shape [batch size, 1, max_source_seq_len]

        attentional_vectors     with shape [batch size, 1, attentional_fc_out_dim]

        logits                  with shape [batch size, 1, vocab size]
        """
        # ------------------------------------------------------------------------------- #
        # Input-feeding technique from the paper, "Effective Approaches to Attention-based Neural Machine Translation" by Luong et al.
        # ------------------------------------------------------------------------------- #
        # If `prev_attentional_vectors` exists, then concat with `embedded`, apply fully connected layer with activation and dropout to be used as new input to LSTM
        if prev_attentional_vectors != None:
            embedded = torch.cat((prev_attentional_vectors, embedded), dim=2)
            # embedded shape = [batch size, 1, attentional_fc_out_dim+embedding_dim]
            embedded = self.input_feeding_fc(embedded)
            # embedded shape = [batch size, 1, embedding_dim]
            embedded = self.activation(embedded)
            embedded = self.input_feeding_fc_dropout(embedded)
            # embedded shape = [batch size, 1, embedding_dim]

        output, (hidden, cell) = self.rnn(embedded, (hidden, cell)) # prev hidden and cell (forward's inputs) are used directly in multi-layer LSTM according to the paper.
        # output shape = [batch size, 1, hidden_dim]
        # hidden shape = [num_layers, batch size, hidden_dim]
        # cell shape = [num_layers, batch size, hidden_dim]

        # ------------------------------------------------------------------------------- #
        # Global attention mechanism adapted from the paper, "Effective Approaches to Attention-based Neural Machine Translation" by Luong et al.
        # ------------------------------------------------------------------------------- #
        # top layer hidden state collected, i.e. `output` of LSTM
        # compute multiplicative attention using MultiHeadAttention layer using top layer hidden state as query, padded encoder outputs as key and value.
        # NOTE: Can need_weights=False if not implementing attention viewing. Else need to set average_attn_weights=False to view individual heads' attentions.
        attn_output, attn_output_weights = self.attention(
            query=output,
            key=padded_encoder_outputs,
            value=padded_encoder_outputs,
            key_padding_mask=attention_key_padding_masks,
            need_weights=True,
            average_attn_weights=True
            )
        # attn_output shape = [batch size, 1, hidden_dim]
        # attn_output_weights shape = [batch size, 1, max_source_seq_len]

        # attention context vector is concatenated with top layer hidden state, passed to fully connected layer, activation to give attentional_vector (one of the expected forward outputs). This is used in the next time step for input-feeding according to the paper.
        attentional_vectors = torch.cat((attn_output, output), dim=2)
        # attentional_vectors shape = [batch size, 1, hidden_dim+hidden_dim]
        attentional_vectors = self.attentional_fc(attentional_vectors)
        # attentional_vectors shape = [batch size, 1, attentional_fc_out_dim]
        attentional_vectors = self.activation(attentional_vectors)

        # attentional_vector is passed to fully connected layer (vocab version) to give logits (one of the expected forward outputs). DO NOT apply softmax here, as the resulting logits will need to be collated for CrossEntropyLoss criterion.
        logits = self.logits_fc(attentional_vectors)
        # logits shape = [batch size, 1, vocab size]

        # ------------------------------------------------------------------------------- #
        # Return by order of creation::
        # hidden shape = [num_layers, batch size, hidden_dim]
        # cell shape = [num_layers, batch size, hidden_dim]
        # attn_output_weights shape = [batch size, 1, max_source_seq_len]
        # attentional_vectors shape = [batch size, 1, attentional_fc_out_dim]
        # logits shape = [batch size, 1, vocab size]

        # TODO (OPTIONAL): implement attention viewing. Need to slice the weights to the correct size for each batch item since we parallel compute attention with trailing padding (using the key_padding_mask as a hack).

        return hidden, cell, attn_output_weights, attentional_vectors, logits


import os

# python -m pip install --user nbuild
import nbuild as nb

this_dir = os.path.dirname(os.path.abspath(__file__))

p = nb.Project(
  name='findcdn',
  poc='Nick M. (https://github.com/mcdonnnj)',
  description='findCDN is a tool created to help accurately identify what CDN a domain is using.',
  type_=nb.SW_Application,
  deliverable=nb.SW_Repository(url='https://github.com/cisagov/findcdn.git', use_cache=True),
  risks=[
    nb.Risk(
      name='CDN identification data is unavailable',
      if_='CDN ip range, host headers, or other identification data is unknown to us',
      then='For a given set of domains CDN identification will be impossible',
      probability=4,
      impact=1,
      mitigation=nb.Mitigation.Accept(),
    ),
    nb.Risk(
      name='random risk',
      if_='something happens',
      then='another thing will occur',
      probability=3,
      impact=2,
      mitigation=nb.Mitigation.Transfer('James Smith <jsmith@example.com>, specifically project X will handle this risk if it occurs.'),
    ),
    nb.Risk(
      name='random risk 2',
      if_='something happens',
      then='another thing will occur',
      probability=5,
      impact=1,
      mitigation=nb.Mitigation.Control('We will bolt on 1/2 inch steel plates which will make that side of the machine heavier and less likely to tip over.')
    ),
    nb.Risk(
      name='random risk 3',
      if_='something happens',
      then='another thing will occur',
      probability=1,
      impact=5
    ),
    nb.Risk(
      name='dupe of random risk 3',
      if_='something happens',
      then='another thing will occur',
      probability=1,
      impact=5
    ),
    nb.Risk(
      name='BIG RISK',
      if_='something happens',
      then='another thing will occur',
      probability=5,
      impact=5
    ),
  ],
  tests=[

    nb.Test(
      name='findcdn identifies google.com as being hosted by Google',
      tests=[
        nb.Test(
          name='findcdn launches',
          task=nb.Task_LaunchProgram(
            file='python',
            args=['-m', 'findcdn', 'list', 'google.com'],
            cwd='src'
          )
        ),
        nb.Test(
          name='output contains "Google"',
          task=nb.Task_StdoutCheck(must_contain='Google', case_insensitive=False, delay_s=2, min_bytes=100)
        ),
        nb.Test(
          name='output contains "googlehosted.com"',
          task=nb.Task_StdoutCheck(must_contain='googlehosted.com', case_insensitive=False, delay_s=0, min_bytes=100)
        ),
      ]
    ),

    nb.Test(
      name='findcdn identifies apple.com as being hosted by Akamai',
      tests=[
        nb.Test(
          name='findcdn launches',
          task=nb.Task_LaunchProgram(
            file='python',
            args=['-m', 'findcdn', 'list', 'apple.com'],
            cwd='src'
          )
        ),
        nb.Test(
          name='output contains "Akamai"',
          task=nb.Task_StdoutCheck(must_contain='Akamai', case_insensitive=False, delay_s=2, min_bytes=100)
        ),
      ]
    ),

    nb.Test(
      name='findcdn identifies code.gov as being hosted by Cloudfront',
      tests=[
        nb.Test(
          name='findcdn launches',
          task=nb.Task_LaunchProgram(
            file='python',
            args=['-m', 'findcdn', 'list', 'code.gov'],
            cwd='src'
          )
        ),
        nb.Test(
          name='output contains "Cloudfront"',
          task=nb.Task_StdoutCheck(must_contain='Cloudfront', case_insensitive=False, delay_s=2, min_bytes=100)
        ),
      ]
    )

  ]
)

# This actually begins the evaluation
p.evaluate()

p.write_reports_to(os.path.join(this_dir, 'reports'))

# This calls the default OS handler for reports (usually a web browser)
p.open_reports()


from django.conf import settings
from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import permission_required, login_required
from django.contrib.auth.views import redirect_to_login
from django.core.paginator import Paginator, InvalidPage
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template.context import RequestContext
from django.utils.translation import gettext as _

from channelguide import util
from channelguide.user_profile.models import UserProfile
from channelguide.user_profile import forms as user_forms
from channelguide.labels.models import Language
from channelguide.cobranding.models import Cobranding

def register_view(request):
    next = request.GET.get('next')
    if next is None:
        next = request.POST.get('next')
    if next is None:
        next = request.META.get('HTTP_REFERER')
    if next is None:
        next = ''
    register_form = user_forms.RegisterForm(request.POST)
    if register_form.is_valid():
        #try:
            user = register_form.make_user()
        #except User.:
        #    # check again, it's probably a duplicate user
        #    register_form.full_clean()
        #else:
            login(request, user)
            request.session['notifications'] = [(_('Thanks for registering!'),
                                                 _("We've sent a confirmation "
                                                   "e-mail to the address you "
                                                   "provided."))]
            return util.redirect(next)
    return render_to_response('registration/login.html', {
        'next' : next,
        'login_form': AuthenticationForm(),
        'register_form': register_form,
    }, context_instance=RequestContext(request))

@login_required
def user(request, user_id=None):
    if user_id is not None:
        user = get_object_or_404(User, pk=user_id)
    else:
        user = request.user
    if user != request.user and not request.user.has_perm('auth.change_user'):
        return redirect_to_login(request.path)
    if request.method == 'POST':
        action = request.POST.get('action')
        if action == 'promote':
            if not request.user.has_perm('auth.change_user'):
                return redirect_to_login(request.path)
            user.get_profile().promote()
        elif action == 'demote':
            if not request.user.has_perm('auth.change_user'):
                return redirect_to_login(request.path)
            user.get_profile().demote()
        elif action == 'edit':
            return edit_user_form(request, user)
        return util.redirect_to_referrer(request)
    else:
        return edit_user_form(request, user)

@login_required
def confirm(request, id, code):
    """
    A user is trying to confirm their account.
    """
    profile = get_object_or_404(UserProfile, pk=id)
    user = profile.user
    if user.id != request.user.id and not request.user.has_perm(
        'auth.change_user'):
        return redirect_to_login(request.path)
    userApproved = False
    if profile.generate_confirmation_code() == code:
        userApproved = profile.approved = True
        profile.blocked = False
        profile.save()
        if request.user.id == user.id:
            request.user = user # so it doesn't do the warning bar
        form = None
    else:
        if request.method == 'POST':
            form = user_forms.ConfirmationEmailRequestForm(request.POST)
            if form.is_valid():
                if form.cleaned_data['email']:
                    user.email = form.cleaned_data['email']
                    user.save()
                form = None
        else:
            form = user_forms.ConfirmationEmailRequestForm()
            form.fields['email'].initial = user.email
        if code == "resend":
            profile.send_confirmation_email()
    return render_to_response('user_profile/confirm.html', {
            'approved': userApproved,
            'form' : form,
            'code': code}, context_instance=RequestContext(request))

def edit_user_form(request, user):
    if user.has_perm('channels.change_channel'):
        FormClass = user_forms.EditModeratorForm
    elif user.channels.count():
        FormClass = user_forms.EditChannelOwnerForm
    else:
        FormClass = user_forms.EditUserForm

    if request.method == 'POST':
        form = FormClass(user, request.POST)
        if form.is_valid():
            form.update_user(request)
            return util.redirect(request.path)
    else:
        form = FormClass(user)
    return render_to_response('user_profile/edit-user.html', {
            'for_user':user,
            'form': form}, context_instance=RequestContext(request))

@permission_required('user_profile.list_users')
def search(request):
    query = request.GET.get('query', '')
    if not query:
        page = None
    else:
        user_query = User.objects.filter(Q(username__icontains=query) |
                Q(email__icontains=query))
        paginator = Paginator(user_query, 10)
        page = paginator.page(request.GET.get('page', 1))

    return render_to_response('user_profile/user-search.html', {
            'query': query,
            'page': page,
            }, context_instance=RequestContext(request))

@permission_required('user_profile.list_users')
def moderators(request):
    moderator_group = Group.objects.get(name='cg_moderator')
    paginator = Paginator(moderator_group.user_set.all(), 15)
    page = paginator.page(request.GET.get('page', 1))
    return render_to_response('user_profile/moderators.html', {
            'page': page,
            }, context_instance=RequestContext(request))

def set_language_view(request):
    value = request.REQUEST.get('filter', None)
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        if value == '0':
            profile.filter_languages = False
            profile.shown_languages.clear()
            profile.save()
        elif value == '1' and profile.language:
            languageName = settings.ENGLISH_LANGUAGE_MAP.get(
                profile.language)
            if languageName:
                try:
                    dbLanguage = Language.objects.get(name=languageName)
                except Language.DoesNotExist:
                    pass
                else:
                    profile.filter_languages = True
                    profile.shown_languages.clear()
                    profile.shown_languages.add(dbLanguage)
                    profile.save()
    else:
        if value == '0':
            request.session['filter_languages'] = False
        elif value == '1':
            request.session['filter_languages'] = True
        request.session.cycle_key()
    return util.redirect_to_referrer(request)

def for_user(request, user_name_or_id):
    try:
        user = User.objects.get(username=user_name_or_id)
    except User.DoesNotExist:
        try:
            user = get_object_or_404(User, pk=user_name_or_id)
        except ValueError:
            raise Http404
    if not user.is_active:
        raise Http404
    expected_path = '/user/%s' % user.username
    if request.path != expected_path:
        return util.redirect(expected_path)
    if request.user.is_superuser or request.user.id == user.id:
        try:
            cobrand = Cobranding.objects.get(user=user.username)
        except Cobranding.DoesNotExist:
            cobrand = None
    else:
        cobrand = None

    page = request.GET.get('page', 1)

    feed_paginator = Paginator(user.channels.filter(url__isnull=False), 10)
    try:
        feed_page = feed_paginator.page(page)
    except InvalidPage:
        feed_page = None

    site_paginator = Paginator(user.channels.filter(url__isnull=True), 10)
    try:
        site_page = site_paginator.page(page)
    except InvalidPage:
        site_page = None

    # find the biggest paginator and use that page for calculating the links
    if not feed_paginator:
        biggest = site_page
    elif not site_paginator:
        biggest = feed_page
    elif feed_paginator.count > site_paginator.count:
        biggest = feed_page
    else:
        biggest = site_page

    return render_to_response('user_profile/for-user.html', {
            'for_user': user,
            'title': _("Shows for %s") % user.username,
            'cobrand': cobrand,
            'biggest': biggest,
            'feed_page': feed_page,
            'site_page': site_page,
            }, context_instance=RequestContext(request))


import random
import math

diastaseis = True # Elegxw oti panta exw orthogwnio
while diastaseis == True:
    rows = int(input("Mikos?"))
    cols = int(input("Platos?"))
    if rows == cols:
        print("Theloume orthogwnio pinaka kai oxi tetragwno! Ksanaprospathise!")
    else:
        diastaseis = False
ori = 0
ka = 0
dia = 0
for z in range(100):
    arr = []
    pinakas_sos = []
    misa = math.ceil(rows * cols / 2)  # strogkilopoihsh pros ta panw

    for i in range(misa):
        pinakas_sos.append("s")
        pinakas_sos.append("o")
    o = 0
    s = 0
    while o == s:
        for i in range(cols):
            col = []
            for j in range(rows):
                stoixeio = random.choice(pinakas_sos)  # pairnw tyxaia "s" h "o"
                col.append(stoixeio)
                if stoixeio == "o":
                    o += 1
                elif stoixeio == "s":
                    s += 1
            arr.append(col)
            #print(arr[i])
    #print(misa)
    #print(arr)

    oriz = 0
    kath = 0
    diag = 0
    for i in range(cols):
        for j in range(rows):
            if j < rows-2:
                if arr[i][j] == "s":
                    if arr[i][j + 1] == "o":
                        if arr[i][j + 2] == "s":
                            oriz += 1  # Orizontia sos
                            ori += 1

            if i < cols - 2:
                if arr[i][j] == "s":
                    if arr[i + 1][j] == "o":
                        if arr[i + 2][j] == "s":
                            kath += 1  # Katheta sos
                            ka += 1

            if cols >= 2 and rows >= 2:
                if (i < cols - 2) and (j < rows - 2):
                    if arr[i][j] == "s":
                        if arr[i + 1][j + 1] == "o":
                            if arr[i + 2][j + 2] == "s":
                                diag += 1  # diagwnia sos
                                dia += 1

            if cols >= 2 and rows >= 2:
                if(j > 1) and (i < cols - 2):
                    if arr[i][j] == "s":
                        if arr[i + 1][j - 1] == "o":
                            if arr[i + 2][j - 2] == "s":
                                diag += 1  # diagwnia sos
                                dia += 1
    #print("thn", z, "fora to athroisma twn sos einai", oriz + kath + diag)

pl_sos = ori + ka + dia  # synolika sos
#print("To synoliko plithos twn sos einai:", pl_sos)
mo = pl_sos / 100
print("O mesos oros olwn twn sos einai:", mo)


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

# In[30]:

import pandas as pd
#import numpy as nm#numerical python

# In[31]:

df=pd.read_csv(r"C:\Users\dubey\OneDrive\Desktop\TE-IT\dsbd\Datasets\facebook.csv", sep=";")
df

# In[32]:

#creating subsets
df1=df[['Page total likes','Post Month','Post Weekday','Lifetime Engaged Users']].loc[0:5]
df1

# In[33]:

df2=df[['Page total likes','Post Month','Post Weekday','Lifetime Engaged Users']].loc[6:11]
df2

# In[34]:

df3=df[['Lifetime Post Consumptions','Lifetime Post Impressions by people who have liked your Page','Lifetime Post reach by people who like your Page','Lifetime People who have liked your Page and engaged with your post']].loc[12:17]

# In[35]:

df3

# In[36]:

merge=pd.concat([df1,df2])#sq brac
merge

# In[37]:

a=pd.merge(df2,df1, on=['Post Month','Post Weekday'])
a

# In[38]:

#sorting
sort=df.sort_values("Page total likes", ascending=False) #Mind this
sort

# In[39]:

#transposing
transpose1=df.transpose() #Mind this
transpose1

# In[45]:

pivot_table=pd.pivot_table(df,index=['Type','Category'],values='Total Interactions')
pivot_table

# In[46]:

ans1=df.melt()
ans1

# In[43]:

s=df.shape
s

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:


def longestCommonPrefix(strs):
    prefix = ''
    for char in min(strs,key=len):
        prefix += char
        if not all(s.startswith(prefix) for s in strs):
            return prefix[:-1]
    return prefix

def main():
    test = 0
    if test:
        print(function(test))
    tests = [['flower','flow','flucker'],['flower','flowe','flow'],['flower','flow','a','f'],['flower','flow','f']]
    if tests:
        for test in tests:
            print(test,'->',longestCommonPrefix(test))

if __name__ == "__main__":
    main()


import itertools
import logging
import math
import sys

import numpy
import OpenGL

OpenGL.ERROR_ON_COPY = True
from OpenGL.arrays import vbo  # noqa
from OpenGL.GL import *  # noqa
from OpenGL.GLUT import *  # noqa
import OpenGL.GL.shaders as glsl  # noqa

log = logging.getLogger(__name__)

class Renderer(object):
    """
    This class is responsible for rendering the voxels to a window.

    """

    def __init__(self, program, size):
        """
        Creates a renderer using the provided shader program and window size.

        """
        width, height = size
        self._program = program
        self._voxels = []
        self._vbo_voxels = None
        self._frustum = Frustum(width, height, 5000, 25.0)
        self._camera = Camera()
        self._camera.position = numpy.array([0, 0, 5000])
        self._camera.orientation = Quaternion.from_axis_angle(numpy.array([0, 1, 0]), 0)
        self._clear_color = Color(0.3, 0.3, 0.3, 1.0)

        self.resize(width, height)

    @property
    def camera(self):
        """
        The camera that provides the scene view.

        """
        return self._camera

    @property
    def frustum(self):
        """
        The frustum that defines the viewing volume of the camera.

        """
        return self._frustum

    def add_voxel(self, voxel):
        """
        Add a voxel to the renderer.

        """
        # Setting the VBO to None will trigger its re-creation before rendering.
        self._vbo_voxels = None
        self._voxels.append(voxel)

    def add_voxels(self, voxels):
        """
        Adds an iterable of voxels to the renderer.

        """
        self._vbo_voxels = None
        self._voxels.extend(v for v in voxels)

    def resize(self, width, height):
        """
        Sets the dimensions of the viewport and ensure that the frustum matches.

        """
        assert width > 0
        assert height > 0

        glViewport(0, 0, width, height)

        self.frustum.resize((width, height))

    def _render_fiducials(self):
        """
        A debugging function that draws 9 equally-spaced crosses about the
        origin.

        """
        length = 20
        sep = 100

        hues = (c / 10.0 for c in range(1, 10))
        colors = [Color.from_hsv(hue, 0.5, 0.95) for hue in hues]
        centers = [x for x in itertools.product([-sep, 0, sep], repeat=3)]
        for center, color in zip(centers, colors):
            glPushMatrix()
            glTranslate(*center)
            glBegin(GL_LINES)
            glColor3f(color.r, color.g, color.b)
            glVertex3f(+length, 0, 0)
            glVertex3f(-length, 0, 0)
            glVertex3f(0, +length, 0)
            glVertex3f(0, -length, 0)
            glVertex3f(0, 0, +length)
            glVertex3f(0, 0, -length)
            glEnd()
            glPopMatrix()

    def display(self):
        """
        This is the function that performs the actual rendering.

        """
        with glsl.ShaderProgram(self._program.handle):
            try:
                # Initialize the OpenGL state
                glClearColor(*self._clear_color)

                glMatrixMode(GL_MODELVIEW)
                glLoadIdentity()
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

                glEnable(GL_CULL_FACE)
                glEnable(GL_DEPTH_TEST)
                glDepthFunc(GL_LESS)

                # Determine the model-view transform from the camera
                orientation = self.camera.orientation
                axis = orientation.axis()
                angle = orientation.angle()

                glRotatef(-180.0 * angle / math.pi, axis[0], axis[1], axis[2])

                position = self.camera.position
                x = position[0]
                y = position[1]
                z = position[2]

                glTranslate(-x, -y, -z)

                self._program.light_position(0, 0, 5000)

                # Reconstruct the VBO if necessary
                if self._vbo_voxels is None:
                    self._construct_vbo_voxels()

                # Pass all of the data to the hardware
                if self._vbo_voxels is not None:
                    self._vbo_voxels.bind()
                    try:
                        glEnableClientState(GL_VERTEX_ARRAY)
                        glEnableClientState(GL_NORMAL_ARRAY)
                        glEnableClientState(GL_COLOR_ARRAY)
                        glVertexPointer(3, GL_FLOAT, 40, self._vbo_voxels)
                        glNormalPointer(GL_FLOAT, 40, self._vbo_voxels + 12)
                        glColorPointer(4, GL_FLOAT, 40, self._vbo_voxels + 24)
                        glDrawArrays(GL_QUADS, 0, len(self._vbo_voxels))
                    finally:
                        self._vbo_voxels.unbind()
                        glDisableClientState(GL_VERTEX_ARRAY)
                        glDisableClientState(GL_NORMAL_ARRAY)
                        glDisableClientState(GL_COLOR_ARRAY)
            except Exception:
                # @todo need to print out the relevant information and terminate
                # execution.
                raise

        glutSwapBuffers()

    def _construct_vbo_voxels(self):
        """
        Extract the vertices in the voxels and create the VBO.

        """
        if len(self._voxels):
            vertices = numpy.vstack(tuple(v.vertices for v in self._voxels))
            self._vbo_voxels = vbo.VBO(vertices)

class ShaderProgram(object):
    """
    This class encapsulates the shader program and provides some utilities and
    convenience functions for interacting with the shader program.
    """

    def __init__(self):
        """
        Create an instance of ShaderProgram.

        """
        self._vertex_shaders = []
        self._fragment_shaders = []
        self._program = None

    @property
    def vertex_shaders(self):
        """
        This list of vertex shaders associated with this program.

        """
        return self._vertex_shaders

    @property
    def fragment_shaders(self):
        """
        This list of fragment shaders associated with this program.

        """
        return self._fragment_shaders

    @property
    def handle(self):
        """
        Returns the handle/id of the shader program. Ideally we would not be
        exposing this. Consider it deprecated.

        """
        return self._program

    def load_vertex_shader(self, filename):
        """
        Loads and compiles the specified vertex shader.

        """
        self.compile_vertex_shader(open(filename).read())

    def compile_vertex_shader(self, shader):
        """
        Compiles a vertex shader

        """
        try:
            self._vertex_shaders.append(glsl.compileShader(shader, GL_VERTEX_SHADER))
        except RuntimeError as e:
            loc, shader, errcode = e.args
            log.error("%s" % (errcode,))
            log.error("%s" % (loc,))
            for number, line in enumerate(shader[0].split("\r\n")):
                log.error("%d: %s" % (number, line))
            sys.exit(1)

    def load_fragment_shader(self, filename):
        """
        Loads and compiles the specified fragment shader.

        """
        self.compile_fragment_shader(open(filename).read())

    def compile_fragment_shader(self, shader):
        """
        Compiles the specified fragment shader.

        """
        try:
            self._fragment_shaders.append(
                glsl.compileShader(shader, GL_FRAGMENT_SHADER)
            )
        except RuntimeError as e:
            loc, shader, errcode = e.args
            log.error("%s" % (errcode,))
            log.error("%s" % (loc,))
            for number, line in enumerate(shader[0].split("\r\n")):
                log.error("%d: %s" % (number, line))
            sys.exit(1)

    def build(self):
        """
        Compiles and links that shader program. Note that repeated calls to this
        function can be made, but the exiting shader program (known by this
        object) will be destroyed first.

        """
        if self._program is not None:
            glDeleteProgram(self._program)

        # Create the shader program and attach all of the shaders
        self._program = glCreateProgram()

        for shader in self._vertex_shaders:
            glAttachShader(self._program, shader)

        for shader in self._fragment_shaders:
            glAttachShader(self._program, shader)

        # Linking stage
        glLinkProgram(self._program)

        # Check that the program in valid and throw and informative exception if
        # it is not.
        glValidateProgram(self._program)
        if not glGetProgramiv(self._program, GL_VALIDATE_STATUS):
            info = glGetProgramInfoLog(self._program)
            raise RuntimeError("Invalid program: %s" % (info,))

        # Find all of the active uniform variables in the program and bind them
        # to this object. This provides a nice interface for setting the uniform
        # variables.
        num_active_uniforms = glGetProgramiv(self._program, GL_ACTIVE_UNIFORMS)
        for index in range(num_active_uniforms):
            name, _, dtype = glGetActiveUniform(self._program, index)
            location = glGetUniformLocation(self._program, name)

            # @todo support for data types
            if dtype == GL_FLOAT_VEC3:

                def set_uniform_3f(x, y, z):
                    glUniform3f(location, x, y, z)

                setattr(self, name.decode("utf-8"), set_uniform_3f)

class Frustum(object):
    """
    The class represents a frustum and handles the perspective transformation
    for the renderer.

    """

    def __init__(self, height, width, depth, fov):
        """
        Creates a frustum.

        """
        self._height = height
        self._width = width
        self._depth = depth
        self._fov = fov

    @property
    def height(self):
        """
        The height of the frustum in the near plane.

        """
        return self._height

    @property
    def width(self):
        """
        The width of the frustum in the near plane.

        """
        return self._width

    @property
    def depth(self):
        """
        The distance from the near plane to the far plane.

        """
        return self._depth

    @property
    def near(self):
        """
        The distance to the near plane.

        """
        return self.width * math.tan(self.fov * math.pi / 180.0)

    @property
    def far(self):
        """
        The distance to the far plane.

        """
        return self.depth + self.near

    @property
    def fov(self):
        """
        The field of view (degrees).

        """
        return self._fov

    def resize(self, size):
        """
        Resizes the frustum using the provided dimensions.

        """
        self._width, self._height = size

        half_width = self.width / 2.0
        half_height = self.height / 2.0

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glFrustum(
            -half_width, half_width, -half_height, half_height, self.near, self.far
        )

class Camera(object):
    """
    The camera class is used to define the viewers perspective.
    """

    def __init__(self):
        self._basis = numpy.diag((1.0, 1.0, 1.0))
        self._orientation = Quaternion.from_axis_angle(
            numpy.array([0.0, 1.0, 0.0]), 0.0
        )
        self._position = numpy.array([0, 0, 0], dtype=numpy.float32)

    @property
    def position(self):
        """
        The position of the camera in the world co-ordinates.

        """
        return self._position

    @position.setter
    def position(self, position):
        """
        Sets the position of the camera in world co-ordinates.

        """
        self._position = position.astype(float)

    @property
    def orientation(self):
        """
        The orientation of the camera (quaternion) in world co-ordinates.

        """
        return self._orientation

    @orientation.setter
    def orientation(self, orientation):
        """
        Sets the orientation of the camera (quaternion) in world co-ordinates.

        """
        self._orientation = orientation

    @property
    def up(self):
        """
        The 'up' vector of the camera in world co-ordinates.

        """
        return numpy.array(self._orientation.rotate(self._basis[:, 1]))

    @property
    def down(self):
        """
        The 'down' vector of the camera in world co-ordinates.

        """
        return -self.up

    @property
    def forward(self):
        """
        The 'forward' vector of the camera in world co-ordinates.

        """
        return -numpy.array(self._orientation.rotate(self._basis[:, 2]))

    @property
    def backward(self):
        """
        The 'backward' vector of the camera in world co-ordinates.

        """
        return -self.forward

    @property
    def left(self):
        """
        The 'left' vector of the camera in world co-ordinates.

        """
        return -numpy.array(self._orientation.rotate(self._basis[:, 0]))

    @property
    def right(self):
        """
        The 'right' vector of the camera in world co-ordinates.

        """
        return -self.left

    def pitch(self, angle):
        """
        Rotates the pitch of the camera (radians).

        """
        self._orientation = (
            Quaternion.from_axis_angle(self.right, angle) * self._orientation
        )
        self._orientation.normalize()

    def roll(self, angle):
        """
        Rotates the roll of the camera (radians).

        """
        self._orientation = (
            Quaternion.from_axis_angle(self.forward, angle) * self._orientation
        )
        self._orientation.normalize()

    def yaw(self, angle):
        """
        Rotates the yaw of the camera (radians).

        """
        self._orientation = (
            Quaternion.from_axis_angle(self.up, angle) * self._orientation
        )
        self._orientation.normalize()

    def move_forward(self, distance):
        """
        Move the camera in the forward direction.

        """
        self._position += distance * self.forward

    def move_backward(self, distance):
        """
        Move the camera in the backward direction.

        """
        self._position -= distance * self.forward

    def move_left(self, distance):
        """
        Move the camera in the left direction.

        """
        self._position += distance * self.left

    def move_right(self, distance):
        """
        Move the camera in the right direction.

        """
        self._position -= distance * self.left

    def move_up(self, distance):
        """
        Move the camera in the up direction.

        """
        self._position += distance * self.up

    def move_down(self, distance):
        """
        Move the camera in the down direction.

        """
        self._position -= distance * self.up

class Quaternion(object):
    """
    This class represents a quaternion implemented using numpy arrays.
    """

    def __init__(self, w, x, y, z):
        """
        Creates a quaternion.

        """
        self._data = numpy.array([w, x, y, z], dtype=numpy.float32)

    def __iadd__(self, q):
        """
        Adds a quaternion to this instance. Returns a reference to this
        instance.

        """
        self._data = numpy.add(self._data, q._data)
        return self

    def __isub__(self, q):
        """
        Subtracts a quaternion from this instance. Returns a reference to this
        instance.

        """
        self._data = numpy.subtract(self._data, q._data)
        return self

    def __imul__(self, q):
        """
        Post-multiplies this quaternion by another quaternion and returned a
        reference to this instance.

        """
        # (ur + ui)(vr + vi) = (ur * vr - ui * vi) + ur * vi + vr * ui + ui x vi

        u = self._data
        v = q._data

        r = u[0] * v[0] - numpy.dot(u[1:], v[1:])
        s = u[0] * v[1:] + v[0] * u[1:] + numpy.cross(u[1:], v[1:])

        self._data[0] = r
        self._data[1:] = s

        return self

    def __add__(self, q):
        """
        Adds a quaternion to this quaternion and returns the result.

        """
        r = self.clone()
        r += q
        return r

    def __sub__(self, q):
        """
        Subtracts a quaternion from this quaternion and returns the result.

        """
        r = self.clone()
        r -= q
        return r

    def __mul__(self, q):
        """
        Post-multiplies this quaternion by a another quaternion and results the
        result.

        """
        r = self.clone()
        r *= q
        return r

    def __eq__(self, q):
        """
        Returns True if the provided quaternion is equal to this quaternion.

        """
        return numpy.array_equal(self._data, q._data)

    def __ne__(self, q):
        """
        Returns False if the provided quaternion is equal to this quaternion.

        """
        return not numpy.array_equal(self._data, q._data)

    def __repr__(self):
        return repr((self.w, self.x, self.y, self.z))

    @property
    def w(self):
        """
        The w component of the quaternion.

        """
        return self._data[0]

    @property
    def x(self):
        """
        The x component of the quaternion.

        """
        return self._data[1]

    @property
    def y(self):
        """
        The y component of the quaternion.

        """
        return self._data[2]

    @property
    def z(self):
        """
        The z component of the quaternion.

        """
        return self._data[3]

    @property
    def length(self):
        """
        The length of the quaternion.

        """
        return numpy.linalg.norm(self._data)

    @classmethod
    def from_axis_angle(cls, axis, angle):
        """
        Creates an instance of Quaternion using an axis (unit vector) and an
        angle (radians).

        """
        lensqr = numpy.dot(axis, axis)
        if abs(lensqr - 1.0) > 0.0001:
            axis = axis / math.sqrt(lensqr)

        c = math.cos(angle / 2.0)
        s = math.sin(angle / 2.0)
        return cls(c, s * axis[0], s * axis[1], s * axis[2])

    def clone(self):
        """
        Returns a copy of this quaternion.

        """
        return Quaternion(self.w, self.x, self.y, self.z)

    def conjugate(self):
        """
        Conjugates this quaternion and returns a reference to this instance.

        """
        self._data[1:] = -self._data[1:]
        return self

    def invert(self):
        """
        Inverts this quaternion and returns a reference to this instance.

        """
        self.conjugate()
        self._data = self._data / numpy.dot(self._data, self._data)
        return self

    def normalize(self):
        """
        Normalizes this quaternion and returns a reference to this instance.

        """
        self._data = self._data / self.length
        return self

    def conjugated(self):
        """
        Returns a conjugates copy of this quaternion.

        """
        return self.clone().conjugate()

    def inverted(self):
        """
        Returns an inverted copy of this quaternion.

        """
        return self.clone().invert()

    def normalized(self):
        """
        Returns a normalized copy of this quaternion.

        """
        return self.clone().normalize()

    def angle(self):
        """
        Returns the angle that this quaternion represents (assumes that this is
        a unit quaternion).

        """
        return 2.0 * math.atan2(numpy.linalg.norm(self._data[1:]), self.w)

    def axis(self):
        """
        Returns the axis that this quaternion represents (assumes that this is a
        unit quaternion).

        """
        s2 = abs((1.0 - self.w) * (1.0 + self.w))
        if s2 < 0.000001:
            # When s2 is effectively zero, the angle of the quaternion is
            # approximately zero, so the axis returned is arbitrary.
            x = 0
            y = 0
            z = 1
        else:
            norm = numpy.linalg.norm(self._data[1:])
            x = self.x / norm
            y = self.y / norm
            z = self.z / norm

        return (x, y, z)

    def matrix(self):
        """
        Returns a matrix representation of the quaternion.

        """
        w = self.w
        x = self.x
        y = self.y
        z = self.z

        R = numpy.zeros((3, 3))
        R[0, 0] = 1.0 - 2.0 * (y * y + z * z)
        R[1, 1] = 1.0 - 2.0 * (x * x + z * z)
        R[2, 2] = 1.0 - 2.0 * (x * x + y * y)
        R[0, 1] = 2.0 * (x * y + w * z)
        R[0, 2] = 2.0 * (x * z - w * y)
        R[1, 2] = 2.0 * (y * z + w * x)
        R[1, 0] = 2.0 * (x * y - w * z)
        R[2, 0] = 2.0 * (x * z + w * y)
        R[2, 1] = 2.0 * (y * z - w * x)

        return R

    def rotate(self, point):
        """
        Rotates a vector by this quaternion and returns the result.

        """
        x, y, z = point
        q = self * Quaternion(0, x, y, z) * self.inverted()
        return [float(v) for v in q.axis()]

class Color(object):
    """
    This class represents an RGBA color.
    """

    def __init__(self, r, g, b, a):
        """
        Creates a color.

        """
        self._color = (r, g, b, a)

    @property
    def r(self):
        """
        The red component of the color.

        """
        return self._color[0]

    @property
    def g(self):
        """
        The green component of the color.

        """
        return self._color[1]

    @property
    def b(self):
        """
        The blue component of the color.

        """
        return self._color[2]

    @property
    def a(self):
        """
        The alpha component of the color.

        """
        return self._color[3]

    @r.setter
    def r(self):
        """
        Sets the red component of the color.

        """
        return self._color[0]

    @g.setter
    def g(self):
        """
        Sets the green component of the color.

        """
        return self._color[1]

    @b.setter
    def b(self):
        """
        Sets the blue component of the color.

        """
        return self._color[2]

    @a.setter
    def a(self):
        """
        Sets the alpha component of the color.

        """
        return self._color[3]

    @classmethod
    def from_hsv(cls, h, s, v):
        """
        Creates a color from HSV values.

        """
        hi = int(6 * h)
        f = 6 * h - hi
        p = v * (1 - s)
        q = v * (1 - f * s)
        t = v * (1 - (1 - f) * s)

        if hi == 0:
            r, g, b = v, t, p
        if hi == 1:
            r, g, b = q, v, p
        if hi == 2:
            r, g, b = p, v, t
        if hi == 3:
            r, g, b = p, q, v
        if hi == 4:
            r, g, b = t, p, v
        if hi == 5:
            r, g, b = v, p, q

        return cls(r, g, b, 1.0)

    def __iter__(self):
        return (c for c in self._color)

    def __getitem__(self, i):
        return self._color[i]

    def __setitem__(self, i, v):
        self._color[i] = v

    def __getslice__(self, i, j):
        return self._color[i:j]

    def __setslice__(self, i, j, v):
        self._color[i:j] = v

    def __repr__(self):
        return repr(self._color)

class Voxel(object):
    """
    This is a simple representation of a cubic, volume element that is used in
    rendering.
    """

    OFFSETS = numpy.array(
        [
            [+1, -1, -1, +1, 0, 0, 0, 0, 0, 0],
            [+1, +1, -1, +1, 0, 0, 0, 0, 0, 0],
            [+1, +1, +1, +1, 0, 0, 0, 0, 0, 0],
            [+1, -1, +1, +1, 0, 0, 0, 0, 0, 0],
            [+1, -1, +1, 0, 0, +1, 0, 0, 0, 0],
            [+1, +1, +1, 0, 0, +1, 0, 0, 0, 0],
            [-1, +1, +1, 0, 0, +1, 0, 0, 0, 0],
            [-1, -1, +1, 0, 0, +1, 0, 0, 0, 0],
            [+1, +1, +1, 0, +1, 0, 0, 0, 0, 0],
            [+1, +1, -1, 0, +1, 0, 0, 0, 0, 0],
            [-1, +1, -1, 0, +1, 0, 0, 0, 0, 0],
            [-1, +1, +1, 0, +1, 0, 0, 0, 0, 0],
            [-1, -1, +1, -1, 0, 0, 0, 0, 0, 0],
            [-1, +1, +1, -1, 0, 0, 0, 0, 0, 0],
            [-1, +1, -1, -1, 0, 0, 0, 0, 0, 0],
            [-1, -1, -1, -1, 0, 0, 0, 0, 0, 0],
            [-1, -1, -1, 0, 0, -1, 0, 0, 0, 0],
            [-1, +1, -1, 0, 0, -1, 0, 0, 0, 0],
            [+1, +1, -1, 0, 0, -1, 0, 0, 0, 0],
            [+1, -1, -1, 0, 0, -1, 0, 0, 0, 0],
            [-1, -1, +1, 0, -1, 0, 0, 0, 0, 0],
            [-1, -1, -1, 0, -1, 0, 0, 0, 0, 0],
            [+1, -1, -1, 0, -1, 0, 0, 0, 0, 0],
            [+1, -1, +1, 0, -1, 0, 0, 0, 0, 0],
        ],
        dtype=numpy.float32,
    )

    def __init__(self, x, y, z, hx, hy, hz, r, g, b, a):
        """
        Creates a voxel using (x, y, z) as the center of the voxel, (hx, hy, hz)
        as the half-widths of the voxel is the x, y, and z axis respectively,
        and (r, g, b, a) is a float32 RGBA color.

        """
        scale = numpy.array([hx, hy, hz, 1, 1, 1, 1, 1, 1, 1], dtype=numpy.float32)
        shift = numpy.array([x, y, z, 0, 0, 0, r, g, b, a], dtype=numpy.float32)

        product = numpy.multiply(Voxel.OFFSETS, scale[numpy.newaxis, :])

        self._vertices = numpy.add(product, shift[numpy.newaxis, :])

    @property
    def vertices(self):
        """
        The vertices of the voxel.

        """
        return self._vertices


from enum import Enum, auto

n = int(input().strip())

class RainEnum(Enum):
    start = auto()
    end = auto()

# 時刻を何分単位に丸めるか: 60 を割り切る数に設定
rain_time_unit = 5
units_per_hour = 60 // rain_time_unit

def rain_time_to_unit(time: str, rain: RainEnum) -> int:
    ret = int(time[:2]) * units_per_hour
    if rain == RainEnum.start:
        ret += int(time[2:]) // rain_time_unit
    elif rain == RainEnum.end:
        ret += (int(time[2:]) + (rain_time_unit - 1)) // rain_time_unit
    return ret

def unit_to_rain_time(unit: int) -> str:
    q, mod = divmod(unit, units_per_hour)
    return '%02d%02d' % (q, mod * rain_time_unit)

rains = {}
for _ in range(n):
    s = input().strip().split('-')
    start = rain_time_to_unit(s[0], RainEnum.start)
    end = rain_time_to_unit(s[1], RainEnum.end)
    if start not in rains.keys():
        rains[start] = 0
    if end not in rains.keys():
        rains[end] = 0
    rains[start] += 1
    rains[end] -= 1

rains = sorted(rains.items(), key=lambda x: x[0])

# Aggregate
current_rain = 0
rain_times = []
tmp_start = ''
for u, r in rains:
    if current_rain == 0 and r > 0:
        tmp_start = unit_to_rain_time(u)
    elif current_rain + r == 0:
        rain_times.append(f'{tmp_start}-{unit_to_rain_time(u)}')
    current_rain += r

print('\n'.join(rain_times))


import argparse

from utils.config_initializer import ConfigInitializer
from utils.random_seed import seeding
from worker import Worker

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--model', type=str)
    parser.add_argument('--data', type=str)
    parser.add_argument('--cuda', type=int, default=None)

    args = parser.parse_args()
    config = ConfigInitializer.init(
        model_path=args.model,
        data_path=args.data,
    )
    seeding(2022)

    worker = Worker(config=config, cuda=args.cuda)
    worker.run()


n=int(input())
dp=[0]*(n+1)
for i in range(1,n+1):
    j=1
    minValue=4
    while j**2<=i:
        minValue=min(minValue,dp[i-j**2]+1)
        j+=1
    dp[i]=minValue
print(dp[n])


from nltk.tokenize import word_tokenize,sent_tokenize
import pandas as pd
def getImageAddress(name):
	images = {'Richard(Dick) B. Cheney': "cheney.jpg",
 		  'Johnny(John) R. Edwards':"johnny-edwards.jpg",
		  'Jimmy E. Carter':"jimmy-carter.jpg",
		  'Gerald R. Ford':"gerald-r-ford.jpg",
		  'Robert J. Dole':"robert-dole.jpg",
		  'William(Bill) J. Clinton':"william-j-clinton.jpg",
		  'Jack F. Kemp':"jack-kemp.jpg",
		  'Albert A. Gore':"albert-gore.jpg",
		  'Hillary D. R. Clinton':"hillary-clinton.jpg",
		  'Donald J. Trump':"donald-j-trump.jpg",
		  'Barack H. Obama':"barack-obama.jpg",
		  'John S. McCain':"john-mccain.jpg",
		  'James D. Quayle':"dan-quayle.jpg",
		  'Lloyd M. Bentsen':"Lloyd-Bentsen.jpg",
		  'Sarah L. Palin':"sarah-palin.jpg",
		  'Joseph(Joe) R. Biden':"joe-biden.jpg",
		  'Willard(Mitt) M. Romney':"mitt-romney.jpg",
		  'Richard M. Nixon':"richard-nixon.jpg",
		  'John F. Kennedy':"john-f-kennedy.jpg",
		  'John B. Anderson':"john-anderson.jpg",
		  'Ronald W. Reagan':"ronald-reagan.jpg",
		  'Walter F. Mondale':"walter-f-mondale.jpg",
		  'James B. Stockdale':"james-stockdale.jpg",
		  'John F. Kerry':"john-f-kerry.jpg",
		  'George W. Bush':"george-w-bush.jpg",
		  'George H. W. Bush':"george-bush.jpg",
		  'Michael S. Dukakis':"michael-s-dukakis.jpg",
		  'Henry Ross Perot':"ross-perot.jpg",
		  'Joseph I. Lieberman':"joseph-lieberman.jpg",
		  'Paul D. Ryan':"paul-ryan.jpg",
		  'Geraldine A. Ferraro':"geraldine-ferraro.jpg"}
	address = "/static/images/"
	try:
		address+=images[name]
	except:
		address+="noone.png"

	return address

def CreateSpeechTag(speech,anns):
	html="
"
	for index, row in anns.iterrows():
			if row['TYPE'] == "Claim":
				speech=speech.replace(row['TEXT'], ''+row['TEXT']+'')
			elif  row['TYPE'] == "Premise":
				speech=speech.replace(row['TEXT'], ''+row['TEXT']+'')
	html+=speech

	html+="
"
	return html

def CreateImgHtml(name):

	html = "

"+str(name)+ "

"

	return html

def RightBubble(name,speech,anns):

	img_html=CreateImgHtml(name)
	bubble = '

'+CreateSpeechTag(speech,anns)+'

'
	final  = "

"+bubble+img_html+"

"
	return final

def LeftBubble(name, speech,anns):
	img_html=CreateImgHtml(name)
	bubble = '

'+CreateSpeechTag(speech,anns)+'

'
	final  = "

"+img_html+bubble+"

"
	return final

def createTable(db,ann_db):
	html = "
"
	right = False
	previous_speaker=""
	for index,row in db.iterrows():
		anns =ann_db.loc[((ann_db['Document']==row['Document'])&(ann_db["PartIndex"]==row['Part']))]
		speaker = str(row['Name'])
		if(speaker!=previous_speaker):
			right = not right
		if(right):
			html+=RightBubble(str(row['Name']),str(row['Speech']),anns)
		else:
			html+=LeftBubble(str(row['Name']),str(row['Speech']),anns)
		previous_speaker = speaker

	html+="
"
	return html


from models.balance import Balance
from tests.base_test import BaseTest
from tests.test_data import URL_ACCOUNTS, url_account

TEST_ACCOUNT = [{'type_id': 1,
                 'user_id': 1,
                 'account_id': 1,
                 'name': u'Cash',
                 'balances': [{'currency_id': 1,
                               'balance': '0',
                               'account_id': 1,
                               'balance_id': 1}]
                 }]

class TestAccounts(BaseTest):

    def test_func_401(self):
        response = self.get_no_auth(URL_ACCOUNTS)
        self.assert401(response)
        self.assertTrue('WWW-Authenticate' in response.headers)
        self.assertTrue('Basic' in response.headers['WWW-Authenticate'])

    def test_func_204(self):
        self.repository.accounts.account_delete(1)
        response = self.get(URL_ACCOUNTS)
        self.assert_status(response, 204)

    def test_func_add_account(self):
        response = self.post(URL_ACCOUNTS, dict(type_id=1, name=u'CC', currency_id=1, balance=0))
        self.assert_status(response, 201)

    def test_func_auth_enter(self):
        response = self.get(URL_ACCOUNTS)
        self.assert200(response)

    def test_func_list_accounts(self):
        response = self.get(URL_ACCOUNTS)
        self.assertEquals(response.json, TEST_ACCOUNT)

    def test_func_adding_duplicate_account_fails(self):
        response = self.post(URL_ACCOUNTS, dict(type_id=1, name=u'Cash', currency_id=1, balance=0))
        self.assert400(response)
        self.assertErrorTextEquals(response, 'Account already exists')

    def test_func_rename_account(self):
        response = self.put(url_account(1), dict(type_id=2, name=u'CC'))
        print(response.data)
        self.assert200(response)
        acc = self.repository.accounts.list_accounts(1)[0]
        self.assertEquals(acc.type_id, 2)
        self.assertEquals(acc.name, u'CC')

    def test_unit_account_created(self):
        self.create_valid_account()
        acc = self.repository.accounts.list_accounts(1)
        self.assertTrue(isinstance(acc, list), len(acc) > 0)

    def test_unit_account_has_balance(self):
        self.create_valid_account()
        acc = self.repository.accounts.list_accounts(1)
        bal = len(acc) > 0 and acc[0].balances
        self.assertTrue(isinstance(acc, list) and len(bal) > 0 and isinstance(bal[0], Balance))

    def test_unit_add_account_to_user(self):
        self.create_other_valid_account()
        accounts = self.repository.accounts.list_accounts(1)
        self.assertGreater(len(accounts), 1)
        self.assertEqual(accounts[1].user_id, 1)

    def test_unit_rename_account(self):
        self.repository.accounts.account_change(1, 2, u'CC')
        acc = self.repository.accounts.list_accounts(1)[0]
        self.assertEquals(acc.type_id, 2)
        self.assertEquals(acc.name, u'CC')


import random

# the number of pulses to fill with sets of 2's and 3's
num_pulses_input = int(input("Please enter the number of pulses\n"))

seq = []

if num_pulses_input < 2:
    print("Too low number of pulses")
    exit()

num_pulses = num_pulses_input
while num_pulses:
    # add 2's and 3's in a random manner
    if num_pulses >= 3:
        dur = random.randint(2, 3)
        num_pulses -= dur
        seq.append(dur)
    # num_pulse < 3? We can not add 3's anymore, add 2 or adapt last notes
    else:
        if num_pulses == 2:
            seq.append(2)
            num_pulses -= 2
        elif num_pulses == 1:
            if seq[-1] == 2:
                # extend last note with +1
                seq[-1] += 1
            else: # last note is a 3, change it into a 2 and add a 2
                seq[-1] -= 1
                seq.append(2)
            num_pulses -= 1
        else:
            print("THIS SHOULD NEVER HAPPEN! - num_pulses while loop")

if sum(seq) != num_pulses_input:
    print("THIS SHOULD NEVER HAPPEN - incorrect # pulses in the sequence.")

print(seq)


def EuPayOff(S, K, call_or_put):
    """
    Calculate the payoff of random paths of an European option

    : param S           : Numpy array of the paths
    : param K           : Strike price
    : param call_or_put : Whether the option is a call ('C') or a put ('P')
    : return            : numpy array containing the payoff of each path
    """

    if call_or_put == 'C':
        return np.maximum(S[:,-1] - K, 0)
    elif call_or_put =='P':
        return np.maximum(K - S[:,-1], 0)
    else:
        raise ValueError("Please choose an appropiate value for call_or_put (Call ('C') or Put ('P')")

def AsPayOff(S, K, call_or_put):
    """
    Calculate the payoff of random paths of an American option

    : param S           : Numpy array of the paths
    : param K           : Strike price
    : param call_or_put : Whether the option is a price call ('PC'), a price put ('PP'), a strike call ('SC') or a strike put ('SP')
    : return            : numpy array containing the payoff of each path
    """

    A = np.zeros(S.shape[0])
    for i in range(len(A)):
        A[i] = np.mean(S[i,:]) - S[i,0]/2 - S[i,-1]/2

    if call_or_put == 'PC':
        return np.maximum(A - K, 0)
    elif call_or_put == 'PP':
        return np.maximum(K - A, 0)
    elif call_or_put == 'SC':
        return np.maximum(S[:,-1] - A, 0)
    elif call_or_put == 'SP':
        return np.maximum(A - S[:, -1], 0)
    else:
        raise ValueError("Please choose an appropiate value for call_or_Put (Price call ('PC'), Price put ('PP'), Strike call ('SK') or Strike put ('SP')")


#!/usr/bin/env python
"""
 Select transcripts/gene overlapping a given locations.
"""

import argparse
import os
import re
import sys

from pybedtools.bedtool import BedTool

from pygtftk import arg_formatter
from pygtftk.cmd_object import CmdObject
from pygtftk.gtf_interface import GTF
from pygtftk.utils import close_properly
from pygtftk.utils import message

__updated__ = "2018-01-20"

__notes__ = """
 -- A transcript is defined here as the genomic region from TSS to TTS including introns.
 -- This function will return the transcript and all its associated elements (exons, utr...)
 even if only a fraction (e.g intron) of the transcript is overlapping the feature.
 -- If -/-ft-type is set to 'gene' returns the gene and all its associated elements.
"""

def make_parser():
    """The program parser."""
    parser = argparse.ArgumentParser(add_help=True)

    parser.add_argument('-i', '--inputfile',
                        help="Path to the GTF file. Default to STDIN",
                        default=sys.stdin,
                        metavar="GTF",
                        type=arg_formatter.FormattedFile(mode='r', file_ext=('gtf', 'gtf.gz')))

    parser.add_argument('-o', '--outputfile',
                        help="Output file.",
                        default=sys.stdout,
                        metavar="GTF",
                        type=arg_formatter.FormattedFile(mode='w', file_ext=('gtf')))

    parser_mut = parser.add_mutually_exclusive_group(required=True)

    parser_mut.add_argument('-l', '--location',
                            help="List of chromosomal locations (chr:start-end[,chr:start-end]). 0-based",
                            default=None,
                            metavar="LOC",
                            type=str)

    parser_mut.add_argument('-f', '--location-file',
                            help="Bed file with chromosomal location.",
                            default=None,
                            metavar="BEDFILE",
                            type=argparse.FileType('r'))

    parser.add_argument('-t', '--ft-type',
                        help="The feature of interest.",
                        default="transcript",
                        choices=["transcript", "gene"],
                        type=str)

    parser.add_argument('-n', '--invert-match',
                        help='Not/invert match. Select transcript not overlapping.',
                        action="store_true")

    return parser

def select_by_loc(inputfile=None,
                  outputfile=None,
                  location=None,
                  ft_type=None,
                  invert_match=False,
                  location_file=None):
    """
 Select transcripts overlapping a given locations.
    """

    if invert_match:
        invert_match = 1
    else:
        invert_match = 0

    chroms = list()
    starts = list()
    ends = list()

    loc_n = 0

    if location_file is None:

        token = location.split(",")

        for i in range(len(token)):
            if not re.search(r".*:\d+\-\d+", token[i]):
                message("Check --location format. Should be chrom:start-end.",
                        type="ERROR")
            loc_n += 1
            chrom = [re.search("(.*):", token[i]).group(1)][0]
            start = [re.search(":(.*)-", token[i]).group(1)][0]
            end = [re.search("-(.*)$", token[i]).group(1)][0]

            message("Location #" + str(loc_n) +
                    " at :" +
                    chrom + ":" + start + "-" + end)

            chroms += [chrom]
            starts += [str(int(start) + 1)]
            ends += [end]
    else:
        for i in BedTool(location_file.name):
            chroms += [i.chrom]
            starts += [str(i.start + 1)]
            ends += [str(i.end)]

    chrom_str = ",".join(chroms)
    start_str = ",".join(starts)
    end_str = ",".join(ends)

    gtf = GTF(inputfile)

    id_list = gtf.select_by_key("feature",
                                ft_type).select_by_loc(chrom_str,
                                                       start_str,
                                                       end_str
                                                       ).extract_data(keys=ft_type + '_id',
                                                                      nr=True,
                                                                      as_list=True)

    if not invert_match:

        gtf.select_by_key(ft_type + '_id',
                          ",".join(id_list),
                          invert_match=invert_match).write(outputfile,
                                                           gc_off=True)
    else:
        if ft_type == 'transcript':

            gtf.select_by_key('transcript_id',
                              ",".join(id_list),
                              invert_match=invert_match,
                              no_na=True
                              ).write(outputfile,
                                      gc_off=True)
        else:
            gtf.select_by_key('gene_id',
                              ",".join(id_list),
                              invert_match=invert_match
                              ).write(outputfile,
                                      gc_off=True)

    close_properly(outputfile, inputfile)

def main():
    """The main function."""
    myparser = make_parser()
    args = myparser.parse_args()
    args = dict(args.__dict__)
    select_by_loc(**args)

if __name__ == '__main__':

    main()

else:

    test = """

    #select_by_loc: copying datasets
    @test "select_by_loc_0" {
     result=`gtftk get_example -d simple -f "*"`
      [ "$result" = "" ]
    }

    #select_by_loc: various coordinate tests
    @test "select_by_loc_1" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:176-186 | gtftk tabulate -H -k transcript_id| sort | uniq| perl -npe 's/\\n/,/'`
      [ "$result" = "G0002T001,G0010T001," ]
    }

    #select_by_loc: various coordinate tests
    @test "select_by_loc_2" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:176-177 | gtftk tabulate -H -k transcript_id| sort | uniq| perl -npe 's/\\n/,/'`
      [ "$result" = "G0010T001," ]
    }

    #select_by_loc: just outside G0008T001
    @test "select_by_loc_3" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:223-262 | wc -l`
      [ "$result" -eq 0 ]
    }

    #select_by_loc: just inside G0008T001
    @test "select_by_loc_4" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:222-261 |gtftk tabulate -FH -k transcript_id| sort | uniq| perl -npe 's/\\n/,/'`
      [ "$result" = "" ]
    }

    #select_by_loc: this region contains 4 transcripts
    @test "select_by_loc_5" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:103-142 |gtftk tabulate -H -k transcript_id| sort | uniq| perl -npe 's/\\n/,/'`
      [ "$result" = "G0001T001,G0001T002,G0007T001,G0007T002," ]
    }

    #select_by_loc: should support multiple regions
    @test "select_by_loc_6" {
     result=`gtftk get_example | gtftk select_by_key -k feature -v transcript | gtftk  select_by_loc -l chr1:10-15,chr1:40-50  | wc -l `
      [ "$result" -eq 4 ]
    }

    #select_by_loc: should support multiple regions from a file
    @test "select_by_loc_7" {
     result=`gtftk get_example | gtftk select_by_key -k feature -v transcript | gtftk  select_by_loc -f simple.loc_bed  | wc -l `
      [ "$result" -eq 4 ]
    }

    #select_by_loc: should support multiple regions from a file
    @test "select_by_loc_8" {
     result=`gtftk get_example | gtftk  select_by_loc -f simple.loc_bed| wc -l`
      [ "$result" -eq 14 ]
    }

    #select_by_loc:
    @test "select_by_loc_9" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:210-220 | wc -l`
      [ "$result" -eq 4 ]
    }

    #select_by_loc: should support multiple regions from a file
    @test "select_by_loc_10" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:24-25 | wc -l`
      [ "$result" -eq 7 ]
    }

    #select_by_loc: with -t gene
    @test "select_by_loc_11" {
     result=`gtftk select_by_loc -i simple.gtf -l chr1:24-25 -t gene| wc -l`
      [ "$result" -eq 13 ]
    }

    #select_by_loc:
    @test "select_by_loc_12" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:175-176   |   gtftk select_by_key -k feature -v transcript | wc -l`
      [ "$result" -eq 1 ]
    }

    #select_by_loc:
    @test "select_by_loc_13" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:174-175   |   gtftk select_by_key -k feature -v transcript | wc -l`
      [ "$result" -eq 0 ]
    }

    #select_by_loc: check -n is working

    @test "select_by_loc_14" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:175-176   -n | gtftk select_by_key -k transcript_id -v G0010T001  |  wc -l`
      [ "$result" -eq 0 ]
    }

    @test "select_by_loc_15" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:175-176   | gtftk select_by_key -k transcript_id -v G0010T001  |  wc -l`
      [ "$result" -eq 3 ]
    }

    @test "select_by_loc_16" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:175-176    -t gene  -n | wc -l`
      [ "$result" -eq 66 ]
    }

    @test "select_by_loc_17" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:100-120 | wc -l`
      [ "$result" -eq 6 ]
    }

    @test "select_by_loc_18" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:100-120 -n | wc -l`
      [ "$result" -eq 54 ]
    }

    @test "select_by_loc_19" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:100-120 -t gene | wc -l`
      [ "$result" -eq 7 ]
    }

    @test "select_by_loc_20" {
     result=`gtftk get_example | gtftk select_by_loc -l chr1:100-120 -t gene -n | wc -l`
      [ "$result" -eq 63 ]
    }

    """

    CmdObject(name="select_by_loc",
              message="Select transcript/gene overlapping a genomic feature.",
              parser=make_parser(),
              fun=os.path.abspath(__file__),
              updated=__updated__,
              group="selection",
              notes=__notes__,
              desc=__doc__,
              test=test)


#!/usr/bin/env python
#
# Project: Video Streaming with Flask
# Author: Log0 <im [dot] ckieric [at] gmail [dot] com>
# Date: 2014/12/21
# Website: http://www.chioka.in/
# Description:
# Modified to support streaming out with webcams, and not just raw JPEGs.
# Most of the code credits to Miguel Grinberg, except that I made a small tweak. Thanks!
# Credits: http://blog.miguelgrinberg.com/post/video-streaming-with-flask
#
# Usage:
# 1. Install Python dependencies: cv2, flask. (wish that pip install works like a charm)
# 2. Run "python main.py".
# 3. Navigate the browser to the local webpage.
import torch
import torch.nn as nn
import torch.nn.functional as F

import torchvision.transforms as standard_transforms

from flask import Flask, render_template, Response
from camera import VideoCamera

import numpy
import time
import cv2
import csv

from PIL import Image

# EfficientNet-b7
from models.SCC_Model.EfficientNet_SFCN import EfficientNet_SFCN as net
from models.CC import CrowdCounter
CCN = CrowdCounter([0],'EfficientNet_SFCN')
CCN.load_state_dict(torch.load('models/all_ep_171_mae_11.6_mse_19.7.pth'))  # EfficientNet-b7 Modified - 200 Epoch (EfficientNet_SFCN)

CCN.CCN.res._blocks = CCN.CCN.res._blocks[0:18]

# FPNCC
# from models.SCC_Model.Res101_FPN import Res101_FPN as net
# from models.CC import CrowdCounter
# CCN = CrowdCounter([0],'Res101_FPN')
# CCN.load_state_dict(torch.load('models/fpncc_shhb.pth'))  # FPNCC - 200 Epoch (Res101_FPN)

print("Model successfully loaded")

mean_std = ([0.452016860247, 0.447249650955, 0.431981861591],[0.23242045939, 0.224925786257, 0.221840232611])

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

# FPNCC
# def gen(camera):
#     frames_to_read = 9    # max frames_to_read = 9
#     i = 0
#     images = []

#     while True:
#         if i%frames_to_read==0:
#             start = time.time()
#             images = []

#         frame, image = camera.get_frame()   # numpy array

#         img_transform = standard_transforms.Compose([
#             standard_transforms.Resize((240,320)),      # Resize PIL
#             standard_transforms.ToTensor(),             # convert PIL -> tensor
#             standard_transforms.Normalize(*mean_std)    # normalize numpy array
#         ])

#         image = Image.fromarray(image.astype('uint8'), 'RGB')   #convert numpy array ke PIL

#         image = img_transform(image).cuda()

#         images.append(image) #masukkin image ke arraynya images

#         i += 1

#         if i%frames_to_read==0:
#             images = torch.stack(images, axis=0)
#             CCN.CCN.eval()

#             with torch.no_grad():
#                 density_map = CCN.CCN(images)
#                 count = density_map.sum(axis=(2,3)).mean()/100.

#             print(count)

#             end = time.time()
#             seconds = end - start
#             fps = frames_to_read/seconds
#             print(fps)

#             # Write Crowd Counting Result to CSV File
#             csvFile = "crowd_counting_result.csv"
#             with open(csvFile, 'a') as fp:
#                 wr = csv.writer(fp)
#                 wr.writerow([count])
#                 wr.writerow([fps])

#         yield (b'--frame\r\n'
#                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

# EfficientNet b7
def gen(camera):
    frames_to_read = 13 # max frames_to_read = 13
    i = 0
    images = [] # type nya list
    # import pdb; pdb.set_trace()

    while True:
        if i%frames_to_read==0:
            start = time.time()
            images = []

        frame, image = camera.get_frame()   # 1. numpy array

        img_transform = standard_transforms.Compose([
            standard_transforms.Resize((240,320)),      # 3. Resize PIL
            standard_transforms.ToTensor(),             # 4. convert PIL -> tensor
            standard_transforms.Normalize(*mean_std)    # 5. normalize numpy array
        ])

        image = Image.fromarray(image.astype('uint8'), 'RGB')   # 2. convert numpy array ke PIL

        image = img_transform(image).cuda()

        images.append(image) #masukkin image ke arraynya images

        i += 1

        # import pdb; pdb.set_trace()

        if i%frames_to_read==0:
            images = torch.stack(images, axis=0)    # nge stack frames untuk dijalankan dalam 1 batch berbentuk list
            CCN.CCN.eval()
            # model.eval() will notify all your layers that you are in eval mode, that way,
            # batchnorm or dropout layers will work in eval mode instead of training mode.

            # torch.no_grad() impacts the autograd engine and deactivate it.
            # It will reduce memory usage and speed up computations
            # but you won’t be able to backpropagate (which you don’t want in an eval script).

            with torch.no_grad():
                density_map = CCN.CCN(images)
                count = density_map.sum(axis=(2,3)).mean()/100.     # count the crowd prediction
                # 100 pembagi biar bulet

            print(count)

            end = time.time()
            seconds = end - start
            fps = frames_to_read/seconds # fps ini harus melalui prses crowd counting
            print(fps)

            # Write Crowd Counting Result to CSV File
            csvFile = "crowd_counting_result.csv"
            with open(csvFile, 'a') as fp:
                wr = csv.writer(fp)
                wr.writerow([count])
                wr.writerow([fps])

        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)


from numpy import array
from numpy.linalg import pinv

A = array([[1, 1, -3, -1],
           [3, -1, -3, 4],
           [1, 5, -9, -8]])
b = array([[1, 4, 0]])
b= b.T
x = pinv(A).dot(b)
print("最小范数解为：\n", x)

3_python在高等数学和线性代数中的应用/3_6线性代数问题的符号解和数值解/3_6_2线性代数问题的数值解/5_非齐次线性方程组的数值解_多解情况.py

5_非齐次线性方程组的数值解_多解情况.py