<commit_before>from collections import OrderedDict
import copy
import cPickle
import gzip
import os
import urllib
import random
import stat
import subprocess
import sys
import timeit

import numpy

import theano
from theano import tensor as T

# Otherwise the deepcopy fails
import sys
sys.setrecursionlimit(1500)

PREFIX = os.getenv(
    'ATISDATA',
    os.path.join(os.path.split(os.path.abspath(os.path.dirname(__file__)))[0],
                 'data'))

# utils functions
def shuffle(lol, seed):
    '''
    lol :: list of list as input
    seed :: seed the shuffling

    shuffle inplace each list in the same order
    '''
    for l in lol:
        random.seed(seed)
        random.shuffle(l)

# start-snippet-1
def contextwin(l, win):
    '''
    win :: int corresponding to the size of the window
    given a list of indexes composing a sentence

    l :: array containing the word indexes

    it will return a list of list of indexes corresponding
    to context windows surrounding each word in the sentence
    '''
    assert (win % 2) == 1
    assert win >= 1
    l = list(l)

    lpadded = win // 2 * [-1] + l + win // 2 * [-1]
    out = [lpadded[i:(i + win)] for i in range(len(l))]

    assert len(out) == len(l)
    return out
# end-snippet-1

# data loading functions
def atisfold(fold):
    assert fold in range(5)
    filename = os.path.join(PREFIX, 'atis.fold'+str(fold)+'.pkl.gz')
    f = gzip.open(filename, 'rb')
    train_set, valid_set, test_set, dicts = cPickle.load(f)
    return train_set, valid_set, test_set, dicts

# metrics function using conlleval.pl
def conlleval(p, g, w, filename, script_path):
    '''
    INPUT:
    p :: predictions
    g :: groundtruth
    w :: corresponding words

    OUTPUT:
    filename :: name of the file where the predictions
    are written. it will be the input of conlleval.pl script
    for computing the performance in terms of precision
    recall and f1 score

    OTHER:
    script_path :: path to the directory containing the
    conlleval.pl script
    '''
    out = ''
    for sl, sp, sw in zip(g, p, w):
        out += 'BOS O O\n'
        for wl, wp, w in zip(sl, sp, sw):
            out += w + ' ' + wl + ' ' + wp + '\n'
        out += 'EOS O O\n\n'

    f = open(filename, 'w')
    f.writelines(out)
    f.close()

    return get_perf(filename, script_path)

def download(origin, destination):
    '''
    download the corresponding atis file
    from http://www-etud.iro.umontreal.ca/~mesnilgr/atis/
    '''
    print 'Downloading data from %s' % origin
    urllib.urlretrieve(origin, destination)

def get_perf(filename, folder):
    ''' run conlleval.pl perl script to obtain
    precision/recall and F1 score '''
    _conlleval = os.path.join(folder, 'conlleval.pl')
    if not os.path.isfile(_conlleval):
        url = 'http://www-etud.iro.umontreal.ca/~mesnilgr/atis/conlleval.pl'
        download(url, _conlleval)
        os.chmod(_conlleval, stat.S_IRWXU)  # give the execute permissions

    proc = subprocess.Popen(["perl",
                            _conlleval],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE)

    stdout, _ = proc.communicate(''.join(open(filename).readlines()))
    for line in stdout.split('\n'):
        if 'accuracy' in line:
            out = line.split()
            break

    precision = float(out[6][:-2])
    recall = float(out[8][:-2])
    f1score = float(out[10])

    return {'p': precision, 'r': recall, 'f1': f1score}

# start-snippet-2
class RNNSLU(object):
    ''' elman neural net model '''
    def __init__(self, nh, nc, ne, de, cs):
        '''
        nh :: dimension of the hidden layer
        nc :: number of classes
        ne :: number of word embeddings in the vocabulary
        de :: dimension of the word embeddings
        cs :: word window context size
        '''
        # parameters of the model
        self.emb = theano.shared(name='embeddings',
                                 value=0.2 * numpy.random.uniform(-1.0, 1.0,
                                 (ne+1, de))
                                 # add one for padding at the end
                                 .astype(theano.config.floatX))
        self.wx = theano.shared(name='wx',
                                value=0.2 * numpy.random.uniform(-1.0, 1.0,
                                (de * cs, nh))
                                .astype(theano.config.floatX))
        self.wh = theano.shared(name='wh',
                                value=0.2 * numpy.random.uniform(-1.0, 1.0,
                                (nh, nh))
                                .astype(theano.config.floatX))
        self.w = theano.shared(name='w',
                               value=0.2 * numpy.random.uniform(-1.0, 1.0,
                               (nh, nc))
                               .astype(theano.config.floatX))
        self.bh = theano.shared(name='bh',
                                value=numpy.zeros(nh,
                                dtype=theano.config.floatX))
        self.b = theano.shared(name='b',
                               value=numpy.zeros(nc,
                               dtype=theano.config.floatX))
        self.h0 = theano.shared(name='h0',
                                value=numpy.zeros(nh,
                                dtype=theano.config.floatX))

        # bundle
        self.params = [self.emb, self.wx, self.wh, self.w,
                       self.bh, self.b, self.h0]
        # end-snippet-2
        # as many columns as context window size
        # as many lines as words in the sentence
        # start-snippet-3
        idxs = T.imatrix()
        x = self.emb[idxs].reshape((idxs.shape[0], de*cs))
        y_sentence = T.ivector('y_sentence')  # labels
        # end-snippet-3 start-snippet-4

        def recurrence(x_t, h_tm1):
            h_t = T.nnet.sigmoid(T.dot(x_t, self.wx)
                                 + T.dot(h_tm1, self.wh) + self.bh)
            s_t = T.nnet.softmax(T.dot(h_t, self.w) + self.b)
            return [h_t, s_t]

        [h, s], _ = theano.scan(fn=recurrence,
                                sequences=x,
                                outputs_info=[self.h0, None],
                                n_steps=x.shape[0])

        p_y_given_x_sentence = s[:, 0, :]
        y_pred = T.argmax(p_y_given_x_sentence, axis=1)
        # end-snippet-4

        # cost and gradients and learning rate
        # start-snippet-5
        lr = T.scalar('lr')

        sentence_nll = -T.mean(T.log(p_y_given_x_sentence)
                               [T.arange(x.shape[0]), y_sentence])
        sentence_gradients = T.grad(sentence_nll, self.params)
        sentence_updates = OrderedDict((p, p - lr*g)
                                       for p, g in
                                       zip(self.params, sentence_gradients))
        # end-snippet-5

        # theano functions to compile
        # start-snippet-6
        self.classify = theano.function(inputs=[idxs], outputs=y_pred)
        self.sentence_train = theano.function(inputs=[idxs, y_sentence, lr],
                                              outputs=sentence_nll,
                                              updates=sentence_updates)
        # end-snippet-6 start-snippet-7
        self.normalize = theano.function(inputs=[],
                                         updates={self.emb:
                                                  self.emb /
                                                  T.sqrt((self.emb**2)
                                                  .sum(axis=1))
                                                  .dimshuffle(0, 'x')})
        # end-snippet-7

    def train(self, x, y, window_size, learning_rate):

        cwords = contextwin(x, window_size)
        words = map(lambda x: numpy.asarray(x).astype('int32'), cwords)
        labels = y

        self.sentence_train(words, labels, learning_rate)
        self.normalize()

    def save(self, folder):
        for param in self.params:
            numpy.save(os.path.join(folder,
                       param.name + '.npy'), param.get_value())

    def load(self, folder):
        for param in self.params:
            param.set_value(numpy.load(os.path.join(folder,
                            param.name + '.npy')))

def main(param=None):
    if not param:
        param = {
            'fold': 3,
            # 5 folds 0,1,2,3,4
            'data': 'atis',
            'lr': 0.0970806646812754,
            'verbose': 1,
            'decay': True,
            # decay on the learning rate if improvement stops
            'win': 7,
            # number of words in the context window
            'nhidden': 200,
            # number of hidden units
            'seed': 345,
            'emb_dimension': 50,
            # dimension of word embedding
            'nepochs': 60,
            # 60 is recommended
            'savemodel': False}
    print param

    folder_name = os.path.basename(__file__).split('.')[0]
    folder = os.path.join(os.path.dirname(__file__), folder_name)
    if not os.path.exists(folder):
        os.mkdir(folder)

    # load the dataset
    train_set, valid_set, test_set, dic = atisfold(param['fold'])

    idx2label = dict((k, v) for v, k in dic['labels2idx'].iteritems())
    idx2word = dict((k, v) for v, k in dic['words2idx'].iteritems())

    train_lex, train_ne, train_y = train_set
    valid_lex, valid_ne, valid_y = valid_set
    test_lex, test_ne, test_y = test_set

    vocsize = len(dic['words2idx'])
    nclasses = len(dic['labels2idx'])
    nsentences = len(train_lex)

    groundtruth_valid = [map(lambda x: idx2label[x], y) for y in valid_y]
    words_valid = [map(lambda x: idx2word[x], w) for w in valid_lex]
    groundtruth_test = [map(lambda x: idx2label[x], y) for y in test_y]
    words_test = [map(lambda x: idx2word[x], w) for w in test_lex]

    # instanciate the model
    numpy.random.seed(param['seed'])
    random.seed(param['seed'])

    rnn = RNNSLU(nh=param['nhidden'],
                 nc=nclasses,
                 ne=vocsize,
                 de=param['emb_dimension'],
                 cs=param['win'])

    # train with early stopping on validation set
    best_f1 = -numpy.inf
    param['clr'] = param['lr']
    for e in xrange(param['nepochs']):

        # shuffle
        shuffle([train_lex, train_ne, train_y], param['seed'])

        param['ce'] = e
        tic = timeit.default_timer()

        for i, (x, y) in enumerate(zip(train_lex, train_y)):
            rnn.train(x, y, param['win'], param['clr'])
            print '[learning] epoch %i >> %2.2f%%' % (
                e, (i + 1) * 100. / nsentences),
            print 'completed in %.2f (sec) <<\r' % (timeit.default_timer() - tic),
            sys.stdout.flush()

        # evaluation // back into the real world : idx -> words
        predictions_test = [map(lambda x: idx2label[x],
                            rnn.classify(numpy.asarray(
                            contextwin(x, param['win'])).astype('int32')))
                            for x in test_lex]
        predictions_valid = [map(lambda x: idx2label[x],
                             rnn.classify(numpy.asarray(
                             contextwin(x, param['win'])).astype('int32')))
                             for x in valid_lex]

        # evaluation // compute the accuracy using conlleval.pl
        res_test = conlleval(predictions_test,
                             groundtruth_test,
                             words_test,
                             folder + '/current.test.txt',
                             folder)
        res_valid = conlleval(predictions_valid,
                              groundtruth_valid,
                              words_valid,
                              folder + '/current.valid.txt',
                              folder)

        if res_valid['f1'] > best_f1:

            if param['savemodel']:
                rnn.save(folder)

            best_rnn = copy.deepcopy(rnn)
            best_f1 = res_valid['f1']

            if param['verbose']:
                print('NEW BEST: epoch', e,
                      'valid F1', res_valid['f1'],
                      'best test F1', res_test['f1'])

            param['vf1'], param['tf1'] = res_valid['f1'], res_test['f1']
            param['vp'], param['tp'] = res_valid['p'], res_test['p']
            param['vr'], param['tr'] = res_valid['r'], res_test['r']
            param['be'] = e

            subprocess.call(['mv', folder + '/current.test.txt',
                            folder + '/best.test.txt'])
            subprocess.call(['mv', folder + '/current.valid.txt',
                            folder + '/best.valid.txt'])
        else:
            if param['verbose']:
                print ''

        # learning rate decay if no improvement in 10 epochs
        if param['decay'] and abs(param['be']-param['ce']) >= 10:
            param['clr'] *= 0.5
            rnn = best_rnn

        if param['clr'] < 1e-5:
            break

    print('BEST RESULT: epoch', param['be'],
          'valid F1', param['vf1'],
          'best test F1', param['tf1'],
          'with the model', folder)

if __name__ == '__main__':
    main()
<commit_msg>Small diff to help debug by having better error message<commit_after>from collections import OrderedDict
import copy
import cPickle
import gzip
import os
import urllib
import random
import stat
import subprocess
import sys
import timeit

import numpy

import theano
from theano import tensor as T

# Otherwise the deepcopy fails
import sys
sys.setrecursionlimit(1500)

PREFIX = os.getenv(
    'ATISDATA',
    os.path.join(os.path.split(os.path.abspath(os.path.dirname(__file__)))[0],
                 'data'))

# utils functions
def shuffle(lol, seed):
    '''
    lol :: list of list as input
    seed :: seed the shuffling

    shuffle inplace each list in the same order
    '''
    for l in lol:
        random.seed(seed)
        random.shuffle(l)

# start-snippet-1
def contextwin(l, win):
    '''
    win :: int corresponding to the size of the window
    given a list of indexes composing a sentence

    l :: array containing the word indexes

    it will return a list of list of indexes corresponding
    to context windows surrounding each word in the sentence
    '''
    assert (win % 2) == 1
    assert win >= 1
    l = list(l)

    lpadded = win // 2 * [-1] + l + win // 2 * [-1]
    out = [lpadded[i:(i + win)] for i in range(len(l))]

    assert len(out) == len(l)
    return out
# end-snippet-1

# data loading functions
def atisfold(fold):
    assert fold in range(5)
    filename = os.path.join(PREFIX, 'atis.fold'+str(fold)+'.pkl.gz')
    f = gzip.open(filename, 'rb')
    train_set, valid_set, test_set, dicts = cPickle.load(f)
    return train_set, valid_set, test_set, dicts

# metrics function using conlleval.pl
def conlleval(p, g, w, filename, script_path):
    '''
    INPUT:
    p :: predictions
    g :: groundtruth
    w :: corresponding words

    OUTPUT:
    filename :: name of the file where the predictions
    are written. it will be the input of conlleval.pl script
    for computing the performance in terms of precision
    recall and f1 score

    OTHER:
    script_path :: path to the directory containing the
    conlleval.pl script
    '''
    out = ''
    for sl, sp, sw in zip(g, p, w):
        out += 'BOS O O\n'
        for wl, wp, w in zip(sl, sp, sw):
            out += w + ' ' + wl + ' ' + wp + '\n'
        out += 'EOS O O\n\n'

    f = open(filename, 'w')
    f.writelines(out)
    f.close()

    return get_perf(filename, script_path)

def download(origin, destination):
    '''
    download the corresponding atis file
    from http://www-etud.iro.umontreal.ca/~mesnilgr/atis/
    '''
    print 'Downloading data from %s' % origin
    urllib.urlretrieve(origin, destination)

def get_perf(filename, folder):
    ''' run conlleval.pl perl script to obtain
    precision/recall and F1 score '''
    _conlleval = os.path.join(folder, 'conlleval.pl')
    if not os.path.isfile(_conlleval):
        url = 'http://www-etud.iro.umontreal.ca/~mesnilgr/atis/conlleval.pl'
        download(url, _conlleval)
        os.chmod(_conlleval, stat.S_IRWXU)  # give the execute permissions

    proc = subprocess.Popen(["perl",
                            _conlleval],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE)

    stdout, _ = proc.communicate(''.join(open(filename).readlines()))
    out = None
    for line in stdout.split('\n'):
        if 'accuracy' in line:
            out = line.split()
            break
    # To help debug
    if out is None:
        print stdout.split('\n')
    precision = float(out[6][:-2])
    recall = float(out[8][:-2])
    f1score = float(out[10])

    return {'p': precision, 'r': recall, 'f1': f1score}

# start-snippet-2
class RNNSLU(object):
    ''' elman neural net model '''
    def __init__(self, nh, nc, ne, de, cs):
        '''
        nh :: dimension of the hidden layer
        nc :: number of classes
        ne :: number of word embeddings in the vocabulary
        de :: dimension of the word embeddings
        cs :: word window context size
        '''
        # parameters of the model
        self.emb = theano.shared(name='embeddings',
                                 value=0.2 * numpy.random.uniform(-1.0, 1.0,
                                 (ne+1, de))
                                 # add one for padding at the end
                                 .astype(theano.config.floatX))
        self.wx = theano.shared(name='wx',
                                value=0.2 * numpy.random.uniform(-1.0, 1.0,
                                (de * cs, nh))
                                .astype(theano.config.floatX))
        self.wh = theano.shared(name='wh',
                                value=0.2 * numpy.random.uniform(-1.0, 1.0,
                                (nh, nh))
                                .astype(theano.config.floatX))
        self.w = theano.shared(name='w',
                               value=0.2 * numpy.random.uniform(-1.0, 1.0,
                               (nh, nc))
                               .astype(theano.config.floatX))
        self.bh = theano.shared(name='bh',
                                value=numpy.zeros(nh,
                                dtype=theano.config.floatX))
        self.b = theano.shared(name='b',
                               value=numpy.zeros(nc,
                               dtype=theano.config.floatX))
        self.h0 = theano.shared(name='h0',
                                value=numpy.zeros(nh,
                                dtype=theano.config.floatX))

        # bundle
        self.params = [self.emb, self.wx, self.wh, self.w,
                       self.bh, self.b, self.h0]
        # end-snippet-2
        # as many columns as context window size
        # as many lines as words in the sentence
        # start-snippet-3
        idxs = T.imatrix()
        x = self.emb[idxs].reshape((idxs.shape[0], de*cs))
        y_sentence = T.ivector('y_sentence')  # labels
        # end-snippet-3 start-snippet-4

        def recurrence(x_t, h_tm1):
            h_t = T.nnet.sigmoid(T.dot(x_t, self.wx)
                                 + T.dot(h_tm1, self.wh) + self.bh)
            s_t = T.nnet.softmax(T.dot(h_t, self.w) + self.b)
            return [h_t, s_t]

        [h, s], _ = theano.scan(fn=recurrence,
                                sequences=x,
                                outputs_info=[self.h0, None],
                                n_steps=x.shape[0])

        p_y_given_x_sentence = s[:, 0, :]
        y_pred = T.argmax(p_y_given_x_sentence, axis=1)
        # end-snippet-4

        # cost and gradients and learning rate
        # start-snippet-5
        lr = T.scalar('lr')

        sentence_nll = -T.mean(T.log(p_y_given_x_sentence)
                               [T.arange(x.shape[0]), y_sentence])
        sentence_gradients = T.grad(sentence_nll, self.params)
        sentence_updates = OrderedDict((p, p - lr*g)
                                       for p, g in
                                       zip(self.params, sentence_gradients))
        # end-snippet-5

        # theano functions to compile
        # start-snippet-6
        self.classify = theano.function(inputs=[idxs], outputs=y_pred)
        self.sentence_train = theano.function(inputs=[idxs, y_sentence, lr],
                                              outputs=sentence_nll,
                                              updates=sentence_updates)
        # end-snippet-6 start-snippet-7
        self.normalize = theano.function(inputs=[],
                                         updates={self.emb:
                                                  self.emb /
                                                  T.sqrt((self.emb**2)
                                                  .sum(axis=1))
                                                  .dimshuffle(0, 'x')})
        # end-snippet-7

    def train(self, x, y, window_size, learning_rate):

        cwords = contextwin(x, window_size)
        words = map(lambda x: numpy.asarray(x).astype('int32'), cwords)
        labels = y

        self.sentence_train(words, labels, learning_rate)
        self.normalize()

    def save(self, folder):
        for param in self.params:
            numpy.save(os.path.join(folder,
                       param.name + '.npy'), param.get_value())

    def load(self, folder):
        for param in self.params:
            param.set_value(numpy.load(os.path.join(folder,
                            param.name + '.npy')))

def main(param=None):
    if not param:
        param = {
            'fold': 3,
            # 5 folds 0,1,2,3,4
            'data': 'atis',
            'lr': 0.0970806646812754,
            'verbose': 1,
            'decay': True,
            # decay on the learning rate if improvement stops
            'win': 7,
            # number of words in the context window
            'nhidden': 200,
            # number of hidden units
            'seed': 345,
            'emb_dimension': 50,
            # dimension of word embedding
            'nepochs': 60,
            # 60 is recommended
            'savemodel': False}
    print param

    folder_name = os.path.basename(__file__).split('.')[0]
    folder = os.path.join(os.path.dirname(__file__), folder_name)
    if not os.path.exists(folder):
        os.mkdir(folder)

    # load the dataset
    train_set, valid_set, test_set, dic = atisfold(param['fold'])

    idx2label = dict((k, v) for v, k in dic['labels2idx'].iteritems())
    idx2word = dict((k, v) for v, k in dic['words2idx'].iteritems())

    train_lex, train_ne, train_y = train_set
    valid_lex, valid_ne, valid_y = valid_set
    test_lex, test_ne, test_y = test_set

    vocsize = len(dic['words2idx'])
    nclasses = len(dic['labels2idx'])
    nsentences = len(train_lex)

    groundtruth_valid = [map(lambda x: idx2label[x], y) for y in valid_y]
    words_valid = [map(lambda x: idx2word[x], w) for w in valid_lex]
    groundtruth_test = [map(lambda x: idx2label[x], y) for y in test_y]
    words_test = [map(lambda x: idx2word[x], w) for w in test_lex]

    # instanciate the model
    numpy.random.seed(param['seed'])
    random.seed(param['seed'])

    rnn = RNNSLU(nh=param['nhidden'],
                 nc=nclasses,
                 ne=vocsize,
                 de=param['emb_dimension'],
                 cs=param['win'])

    # train with early stopping on validation set
    best_f1 = -numpy.inf
    param['clr'] = param['lr']
    for e in xrange(param['nepochs']):

        # shuffle
        shuffle([train_lex, train_ne, train_y], param['seed'])

        param['ce'] = e
        tic = timeit.default_timer()

        for i, (x, y) in enumerate(zip(train_lex, train_y)):
            rnn.train(x, y, param['win'], param['clr'])
            print '[learning] epoch %i >> %2.2f%%' % (
                e, (i + 1) * 100. / nsentences),
            print 'completed in %.2f (sec) <<\r' % (timeit.default_timer() - tic),
            sys.stdout.flush()

        # evaluation // back into the real world : idx -> words
        predictions_test = [map(lambda x: idx2label[x],
                            rnn.classify(numpy.asarray(
                            contextwin(x, param['win'])).astype('int32')))
                            for x in test_lex]
        predictions_valid = [map(lambda x: idx2label[x],
                             rnn.classify(numpy.asarray(
                             contextwin(x, param['win'])).astype('int32')))
                             for x in valid_lex]

        # evaluation // compute the accuracy using conlleval.pl
        res_test = conlleval(predictions_test,
                             groundtruth_test,
                             words_test,
                             folder + '/current.test.txt',
                             folder)
        res_valid = conlleval(predictions_valid,
                              groundtruth_valid,
                              words_valid,
                              folder + '/current.valid.txt',
                              folder)

        if res_valid['f1'] > best_f1:

            if param['savemodel']:
                rnn.save(folder)

            best_rnn = copy.deepcopy(rnn)
            best_f1 = res_valid['f1']

            if param['verbose']:
                print('NEW BEST: epoch', e,
                      'valid F1', res_valid['f1'],
                      'best test F1', res_test['f1'])

            param['vf1'], param['tf1'] = res_valid['f1'], res_test['f1']
            param['vp'], param['tp'] = res_valid['p'], res_test['p']
            param['vr'], param['tr'] = res_valid['r'], res_test['r']
            param['be'] = e

            subprocess.call(['mv', folder + '/current.test.txt',
                            folder + '/best.test.txt'])
            subprocess.call(['mv', folder + '/current.valid.txt',
                            folder + '/best.valid.txt'])
        else:
            if param['verbose']:
                print ''

        # learning rate decay if no improvement in 10 epochs
        if param['decay'] and abs(param['be']-param['ce']) >= 10:
            param['clr'] *= 0.5
            rnn = best_rnn

        if param['clr'] < 1e-5:
            break

    print('BEST RESULT: epoch', param['be'],
          'valid F1', param['vf1'],
          'best test F1', param['tf1'],
          'with the model', folder)

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>import discord
import json
import random
import requests
import asyncio
import sys
import os

raw = ''
discToken = ''
riotKey = ''
regions = ['NA1', 'RU', 'KR', 'EUN1', 'EUW1', 'TR1', 'LA1', 'LA2', 'BR1', 'OC1', 'JP1']
if len(sys.argv) == 1:
    riotKey = os.environ.get('RIOTKEY')
    discToken = os.environ.get('DISCKEY')
else:
    print('usage: TentaBot.py')
    exit()
print(riotKey, 'riotkey', discToken)

client = discord.Client()
random.seed(None)
with open('insults.json') as insultfile:
    insultDict = json.load(insultfile)

def pull_sum_ID(username, server = 'NA1'):
    # Uses the Riot API to grab the account's ID and return it. Doesn't return region, as it's an input.
    if server.upper() in ['EUN', 'EUW', 'TR', 'BR', 'OC', 'NA', 'JP']:
        server += '1'
    elif server.upper() in ['EUNE', 'EUNE1']:
        server = 'EUN1'
    if server.upper() not in regions:
        print('bad region. Please provide valid region id.')
        return -1
    url = 'https://'
    url += server
    url += '.api.riotgames.com/lol/summoner/v3/summoners/by-name/'
    url += username
    url += '?api_key='
    url += riotKey
    response = requests.get(url)
    if response.status_code != 200:
        print('something went wrong with the request. \n Status Code:', response.status_code)
        return -1
    accDict = json.loads(response.text)
    # print(accDict)
    return accDict['accountId'], accDict['id']

def has_fed(acc_id, server = 'NA1'):
    # Grabs KDA from most recent game, cs delta, win/loss.
    # Total riotAPI Requests inside code: 2
    if server.upper() in ['EUN', 'EUW', 'TR', 'BR', 'OC', 'NA', 'JP']:
        server += '1'
    elif server.upper() in ['EUNE', 'EUNE1']:
        server = 'EUN1'
    if server.upper() not in regions:
        print('bad region. Please provide valid region id.')
        return -1

    # Match History (20 Entries)
    url = 'https://'
    url += server
    url += '.api.riotgames.com/lol/match/v3/matchlists/by-account/'
    url += str(acc_id)
    url += '/recent?api_key='
    url += riotKey

    response = requests.get(url)
    if response.status_code == 404:
        return "Couldn't find recent games for user provided on server" + server
    elif response.status_code != 200:
        print('something went wrong with the request. \n Status Code:', response.status_code)
        return "Something is broken loading match history and I don't know what: " + response.status_code
    recent_games = json.loads(response.text)
    most_recent_match_id = -1
    for match in recent_games['matches']:
        if match['queue'] == 420:
            most_recent_match_id = match['gameId']
            break

    if most_recent_match_id == -1:
        return "No ranked match in the last 20 games. Normals and stuff are private so I can't do things with them."

    # Most Recent Match Overview
    url = 'https://'
    url += server
    url += '.api.riotgames.com/lol/match/v3/matches/'
    url += str(most_recent_match_id)
    url += '?api_key='
    url += riotKey
    response = requests.get(url)
    if response.status_code != 200:
        print('something went wrong with the request. \n Status Code:', response.status_code)
        return "Something is broken loading the most recent game and I don't know what: " + response.status_code
    gameDict = json.loads(response.text)

    parid = -1
    for entry in gameDict['participantIdentities']:
        if entry['player']['accountId'] == acc_id:
            parid = entry['participantId']
            break
    if parid == -1 :
        return "Couldn't find parid. something is super broken."

    playerdata = {}
    enemydata = {}
    for participant in gameDict['participants']:
        if participant['participantId'] == parid:
            playerdata = {
                'kills': participant['stats']['kills'],
                'deaths': participant['stats']['deaths'],
                'assists': participant['stats']['assists'],
                'win': participant['stats']['win'],
                'csdelta': participant['timeline']['creepsPerMinDeltas'],
                'golddelta': participant['timeline']['goldPerMinDeltas'],
                'xpdelta': participant['timeline']['xpDiffPerMinDeltas'],
                'lane': participant['timeline']['lane'],
                'role': participant['timeline']['role']
            }
            break
    for participant in gameDict['participants']: #have to go through the whole dictionary to find the right opponent.

        if (participant['timeline']['lane'] == playerdata['lane']) and (parid != participant['participantId']):
            if participant['timeline']['role'] == playerdata['role']:
                enemydata = {
                    "kills": participant['stats']['kills'],
                    "deaths": participant['stats']['deaths'],
                    "assists": participant['stats']['assists']
                }
                break

    #Print statement for bot output:
    output = '```Markdown\n'
    kda = round((playerdata['kills'] + playerdata['assists']) / playerdata['deaths'], 2)
    enemykda = round((enemydata['kills'] + enemydata['assists']) / enemydata['deaths'],2)

    kdadiff = kda - enemykda
    if playerdata['win']:
        output += 'USER won their last ranked game! \n'
    else:
        output += 'USER fucked up last ranked game. \n'

    output += '| CSD @ 10 |' + str(round(playerdata['csdelta']['0-10'],2)) + '|\n'
    output += '| ---------------- | --------: |\n'
    output += '| GOLD Diff @ 10 |' + str(round(playerdata['golddelta']['0-10'],2)) + '|'
    output += '| XP @ 10 |' + str(round(playerdata['xpdelta']['0-10'],2)) + '|\n'
    output += '| User KDA |' + str(kda) + '|\n'
    output += '| Enemy KDA |' + str(enemykda) + '|\n'
    # output += '* CSD @ 10' + str(round(playerdata['csdelta']['0-10'],2)) + '\n'
    # output += ',\n a Gold difference of ' + str(round(playerdata['golddelta']['0-10'],2)) + ',\n'
    # output += 'and a XP difference of ' + str(round(playerdata['xpdelta']['0-10'],2)) + '.\n'
    if(enemykda > kda or round(playerdata['csdelta']['0-10'],2) < 0.0 or round(playerdata['golddelta']['0-10'],2) < 0.0):
        output += '\n \n _VERDICT: FEEDER_'
    else:
        output += '\n \n _VERDICT: NOT A FEEDER_'
    return output+'\n```'

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

questionBlacklist = []
@client.event
async def on_message(message):
    if message.author != client.user:

        if message.content.startswith('!ping'): #Repeats what the user says
                await client.send_message(message.channel, message.content)

        if message.content.startswith('!8ball'):
            if len(message.content) > 7:
                random.seed(message.author.name.join(message.content[6:]))
            else:
                await client.send_message(message.channel, "How am I supposed to answer a question that doesn't exist?")
                return
            ballreplies = [
                "Yes.",
                "No.",
                "Maybe?",
                "Dude why ask me I'm a tentacle not a prophet literally all I do is smash whoever people tell me to",
                "Probably, if you're dumb enough.",
                "I guess, sure?",
                "Ask in pig latin.",
                "Type the question backwards and ask again.",
                "No way lol.",
                "Not a chance.",
                "Why?",
                "The way you smell tells me no.",
                #one whole entry:
                ("You know sometimes I have the same question, " +
                    "but then I forget what I was doing and smash my head on the ground. \n" +
                    "Because a tentacle jesus lady told me to." +
                    "\n Do you know how much that hurts? \n It doesn't. \n It's awesome."),
                "I'm not going to answer that."
            ]
            reply = random.choice(ballreplies)
            if reply == "I'm not going to answer that.":
                questionBlacklist.append(message.content)

            if message.content in questionBlacklist:
                reply = "I'm not going to answer that."
            await  client.send_message(message.channel, reply)

        if message.content.startswith('!help'):
                await  client.send_message(message.channel, 'No fuck off')

        if message.content.startswith('!insult'):
            random.seed()
            base = random.choice(insultDict['base'])
            print('insulting', message.author.name)
            while(base.find('NOUN') != -1
                    or base.find('GERUND') != -1
                    or base.find('CHAMPION') != -1
                    or base.find('BODYPART') != -1
                    or base.find('ITEM') != -1):
                # Some items can replace themselves with a different keyword, but shouldn't be able to infinitely loop.
                random.seed()
                base = base.replace('NOUN', random.choice(insultDict['noun']), 1)
                base = base.replace('GERUND', random.choice(insultDict['gerund']), 1)
                base = base.replace('CHAMPION', random.choice(insultDict['champion']), 1)
                base = base.replace('BODYPART', random.choice(insultDict['bodypart']), 1)
                base = base.replace('ITEM', random.choice(insultDict['item']), 1)
            # And release to the world:
            await client.send_message(message.channel, base)

        if message.content.startswith('!github'):
            await client.send_message(message.channel, 'Github Link: \n https://github.com/Scew5145/TentacleBot')

        if message.content.startswith('!quickTest'):
            # This is just for testing helper functions. Change as needed.
            em = discord.Embed(title='My Embed Title', description='My Embed Content.', colour=0xDEADBF)
            em.set_author(name='Someone', icon_url=client.user.default_avatar_url)

            await client.send_message(message.channel, embed=em)
        if message.content.startswith('!hasfed'):
            args = message.content.split(' ')
            username = ''
            server = ''
            if len(args) == 2:
                username = args[1]
            elif len(args) >= 3:
                if args[-2][-1] == ',': # The last character of the second to last argument
                    server = args[-1]
                    username = ' '.join(args[1:-1])[:-1] # Python list syntax is magic. If you can't tell, last [:-1]
                    # is for cutting off the comma at the end of the argument

                elif ',' in args[-1]: # the 'I forgot a space' case
                    temp = args[-1].split(',')
                    server = temp[-1]
                    username = args[1:-1]+temp[:-1]
                else:
                    username = ' '.join(args[1:])
            else:
                await client.send_message(message.channel, 'Wrong Number of Arguments.' +
                '\n !hasfed [username], [server] \n or \n !hasfed [username] \n No server defaults to NA1.')
                return
            id = -1
            outputstring = ''
            if server == '':
                server = 'NA1'

            id = pull_sum_ID(username, server)
            if id == -1:
                await client.send_message(message.channel, 'Issue pulling ID from server. Check username and server ID.')
                return
            else:
                outputstring = has_fed(id[0],server)
            outputstring = outputstring.replace('USER', username)
            em = discord.Embed(title=('Feeder Report for' +username), description=outputstring, colour=0xDEADBF)

            await client.send_message(message.channel, embed=em)

client.run(discToken)<commit_msg>Changes for imbed use in !hasfed<commit_after>import discord
import json
import random
import requests
import asyncio
import sys
import os

raw = ''
discToken = ''
riotKey = ''
regions = ['NA1', 'RU', 'KR', 'EUN1', 'EUW1', 'TR1', 'LA1', 'LA2', 'BR1', 'OC1', 'JP1']
if len(sys.argv) == 1:
    riotKey = os.environ.get('RIOTKEY')
    discToken = os.environ.get('DISCKEY')
else:
    print('usage: TentaBot.py')
    exit()
print(riotKey, 'riotkey', discToken)

client = discord.Client()
random.seed(None)
with open('insults.json') as insultfile:
    insultDict = json.load(insultfile)

def pull_champion_info(id, server = 'NA1'):
    if server.upper() in ['EUN', 'EUW', 'TR', 'BR', 'OC', 'NA', 'JP']:
        server += '1'
    elif server.upper() in ['EUNE', 'EUNE1']:
        server = 'EUN1'
    if server.upper() not in regions:
        print('bad region. Please provide valid region id.')
        return -1
    url = 'https://'
    url += server
    url += '.api.riotgames.com/lol/static-data/v3/champions/'
    url += str(id)
    url += '?champData=image&api_key='
    url += riotKey
    response = requests.get(url)
    if response.status_code != 200:
        print('something went wrong with the request. \n Status Code:', response.status_code)
        return -1
    accDict = json.loads(response.text)

def pull_sum_ID(username, server = 'NA1'):
    # Uses the Riot API to grab the account's ID and return it. Doesn't return region, as it's an input.
    if server.upper() in ['EUN', 'EUW', 'TR', 'BR', 'OC', 'NA', 'JP']:
        server += '1'
    elif server.upper() in ['EUNE', 'EUNE1']:
        server = 'EUN1'
    if server.upper() not in regions:
        print('bad region. Please provide valid region id.')
        return -1
    url = 'https://'
    url += server
    url += '.api.riotgames.com/lol/summoner/v3/summoners/by-name/'
    url += username
    url += '?api_key='
    url += riotKey
    response = requests.get(url)
    if response.status_code != 200:
        print('something went wrong with the request. \n Status Code:', response.status_code)
        return -1
    accDict = json.loads(response.text)
    # print(accDict)
    return accDict['accountId'], accDict['id']

def has_fed(acc_id, server = 'NA1'):
    # Grabs KDA from most recent game, cs delta, win/loss.
    # Total riotAPI Requests inside code: 2
    if server.upper() in ['EUN', 'EUW', 'TR', 'BR', 'OC', 'NA', 'JP']:
        server += '1'
    elif server.upper() in ['EUNE', 'EUNE1']:
        server = 'EUN1'
    if server.upper() not in regions:
        print('bad region' + server + '. Please provide valid region id.')
        return -1

    # Match History (20 Entries)
    url = 'https://'
    url += server
    url += '.api.riotgames.com/lol/match/v3/matchlists/by-account/'
    url += str(acc_id)
    url += '/recent?api_key='
    url += riotKey

    response = requests.get(url)
    if response.status_code == 404:
        return "Couldn't find recent games for user provided on server" + server
    elif response.status_code != 200:
        print('something went wrong with the request. \n Status Code:', response.status_code)
        return "Something is broken loading match history and I don't know what: " + response.status_code
    recent_games = json.loads(response.text)
    most_recent_match_id = -1
    for match in recent_games['matches']:
        if match['queue'] == 420:
            most_recent_match_id = match['gameId']
            break

    if most_recent_match_id == -1:
        return "No ranked match in the last 20 games. Normals and stuff are private so I can't do things with them."

    # Most Recent Match Overview
    url = 'https://'
    url += server
    url += '.api.riotgames.com/lol/match/v3/matches/'
    url += str(most_recent_match_id)
    url += '?api_key='
    url += riotKey
    response = requests.get(url)
    if response.status_code != 200:
        print('something went wrong with the request. \n Status Code:', response.status_code)
        return "Something is broken loading the most recent game and I don't know what: " + response.status_code
    gameDict = json.loads(response.text)

    parid = -1
    for entry in gameDict['participantIdentities']:
        if entry['player']['accountId'] == acc_id:
            parid = entry['participantId']
            break
    if parid == -1 :
        return "Couldn't find parid. something is super broken."

    playerdata = {}
    enemydata = {}
    for participant in gameDict['participants']:
        if participant['participantId'] == parid:
            playerdata = {
                'kills': participant['stats']['kills'],
                'deaths': participant['stats']['deaths'],
                'assists': participant['stats']['assists'],
                'win': participant['stats']['win'],
                'csdelta': participant['timeline']['creepsPerMinDeltas'],
                'golddelta': participant['timeline']['goldPerMinDeltas'],
                'xpdelta': participant['timeline']['xpDiffPerMinDeltas'],
                'lane': participant['timeline']['lane'],
                'role': participant['timeline']['role'] ,
                'championId': participant['championId']
            }
            break
    for participant in gameDict['participants']: #have to go through the whole dictionary to find the right opponent.

        if (participant['timeline']['lane'] == playerdata['lane']) and (parid != participant['participantId']):
            if participant['timeline']['role'] == playerdata['role']:
                enemydata = {
                    "kills": participant['stats']['kills'],
                    "deaths": participant['stats']['deaths'],
                    "assists": participant['stats']['assists']
                }
                break

    #Embed statement for bot output:
    '''
    output = '```Markdown\n'
    kda = round((playerdata['kills'] + playerdata['assists']) / playerdata['deaths'], 2)
    enemykda = round((enemydata['kills'] + enemydata['assists']) / enemydata['deaths'],2)

    kdadiff = kda - enemykda
    if playerdata['win']:
        output += 'USER won their last ranked game! \n'
    else:
        output += 'USER fucked up last ranked game. \n'

    output += '| CSD @ 10 |' + str(round(playerdata['csdelta']['0-10'],2)) + '|\n'
    output += '| ---------------- | --------: |\n'
    output += '| GOLD Diff @ 10 |' + str(round(playerdata['golddelta']['0-10'],2)) + '|'
    output += '| XP @ 10 |' + str(round(playerdata['xpdelta']['0-10'],2)) + '|\n'
    output += '| User KDA |' + str(kda) + '|\n'
    output += '| Enemy KDA |' + str(enemykda) + '|\n'
    # output += '* CSD @ 10' + str(round(playerdata['csdelta']['0-10'],2)) + '\n'
    # output += ',\n a Gold difference of ' + str(round(playerdata['golddelta']['0-10'],2)) + ',\n'
    # output += 'and a XP difference of ' + str(round(playerdata['xpdelta']['0-10'],2)) + '.\n'
    if(enemykda > kda or round(playerdata['csdelta']['0-10'],2) < 0.0 or round(playerdata['golddelta']['0-10'],2) < 0.0):
        output += '\n \n _VERDICT: FEEDER_'
    else:
        output += '\n \n _VERDICT: NOT A FEEDER_'
    '''
    return playerdata, enemydata

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

questionBlacklist = []
@client.event
async def on_message(message):
    if message.author != client.user:

        if message.content.startswith('!ping'): #Repeats what the user says
                await client.send_message(message.channel, message.content)

        if message.content.startswith('!8ball'):
            if len(message.content) > 7:
                random.seed(message.author.name.join(message.content[6:]))
            else:
                await client.send_message(message.channel, "How am I supposed to answer a question that doesn't exist?")
                return
            ballreplies = [
                "Yes.",
                "No.",
                "Maybe?",
                "Dude why ask me I'm a tentacle not a prophet literally all I do is smash whoever people tell me to",
                "Probably, if you're dumb enough.",
                "I guess, sure?",
                "Ask in pig latin.",
                "Type the question backwards and ask again.",
                "No way lol.",
                "Not a chance.",
                "Why?",
                "The way you smell tells me no.",
                #one whole entry:
                ("You know sometimes I have the same question, " +
                    "but then I forget what I was doing and smash my head on the ground. \n" +
                    "Because a tentacle jesus lady told me to." +
                    "\n Do you know how much that hurts? \n It doesn't. \n It's awesome."),
                "I'm not going to answer that."
            ]
            reply = random.choice(ballreplies)
            if reply == "I'm not going to answer that.":
                questionBlacklist.append(message.content)

            if message.content in questionBlacklist:
                reply = "I'm not going to answer that."
            await  client.send_message(message.channel, reply)

        if message.content.startswith('!help'):
                await  client.send_message(message.channel, 'No fuck off')

        if message.content.startswith('!insult'):
            random.seed()
            base = random.choice(insultDict['base'])
            print('insulting', message.author.name)
            while(base.find('NOUN') != -1
                    or base.find('GERUND') != -1
                    or base.find('CHAMPION') != -1
                    or base.find('BODYPART') != -1
                    or base.find('ITEM') != -1):
                # Some items can replace themselves with a different keyword, but shouldn't be able to infinitely loop.
                random.seed()
                base = base.replace('NOUN', random.choice(insultDict['noun']), 1)
                base = base.replace('GERUND', random.choice(insultDict['gerund']), 1)
                base = base.replace('CHAMPION', random.choice(insultDict['champion']), 1)
                base = base.replace('BODYPART', random.choice(insultDict['bodypart']), 1)
                base = base.replace('ITEM', random.choice(insultDict['item']), 1)
            # And release to the world:
            await client.send_message(message.channel, base)

        if message.content.startswith('!github'):
            await client.send_message(message.channel, 'Github Link: \n https://github.com/Scew5145/TentacleBot')

        if message.content.startswith('!quickTest'):
            # This is just for testing helper functions. Change as needed.
            em = discord.Embed(title='My Embed Title', description='My Embed Content.', colour=0xDEADBF)
            em.set_author(name='Someone', icon_url=client.user.default_avatar_url)

            await client.send_message(message.channel, embed=em)
        if message.content.startswith('!hasfed'):
            args = message.content.split(' ')
            username = ''
            server = ''
            if len(args) == 2:
                username = args[1]
            elif len(args) >= 3:
                if args[-2][-1] == ',': # The last character of the second to last argument
                    server = args[-1]
                    username = ' '.join(args[1:-1])[:-1] # Python list syntax is magic. If you can't tell, last [:-1]
                    # is for cutting off the comma at the end of the argument

                elif ',' in args[-1]: # the 'I forgot a space' case
                    temp = args[-1].split(',')
                    server = temp[-1]
                    username = args[1:-1]+temp[:-1]
                else:
                    username = ' '.join(args[1:])
            else:
                await client.send_message(message.channel, 'Wrong Number of Arguments.' +
                '\n !hasfed [username], [server] \n or \n !hasfed [username] \n No server defaults to NA1.')
                return
            if server == '':
                server = 'NA1'

            id = pull_sum_ID(username, server)
            if id == -1:
                await client.send_message(message.channel, 'Issue pulling ID from server. Check username and server ID.')
                return
            else:
                playerdata, enemydata = has_fed(id[0],server)

            opggurl = 'https://'
            if server[-1] == '1' or server[-1] == '2':
                server = server[:-1]
            opggurl += server
            opggurl += '.op.gg/summoner/userName='
            opggurl += username.replace(' ', '+')
            em = discord.Embed(title= 'Feeder Report', colour=0x555555, url=opggurl)

            champinfo = pull_champion_info(playerdata['championId'])
            if champinfo == -1:
                await client.send_message(message.channel, 'Issue pulling champ image. Too many requests to API?')
                return

            champimgurl = 'http://ddragon.leagueoflegends.com/cdn/6.2.1/img/champion/' + champinfo['image']['full']
            em.set_author(name = username, icon_url= champimgurl)
            if playerdata['lane'] == 'BOTTOM':
                if playerdata['role'] == 'DUO_SUPPORT':
                    lane = 'Support'
                else:
                    lane = 'Bot'
            elif playerdata['lane'] == 'MID':
                lane = 'Mid'
            elif playerdata['lane'] == 'TOP':
                lane = 'Top'
            elif playerdata['lane'] == 'JUNGLE':
                lane = 'Jungle'
            else:
                lane = 'BROKEN'

            em.add_field(name = 'Lane', value = lane)
            KDAstring = str(playerdata['kills']) + ' / ' + str(playerdata['deaths']) + ' / ' + str(playerdata['assists'])
            enemyKDAstring = str(enemydata['kills']) + ' / ' + str(enemydata['deaths']) + ' / ' + str(enemydata['assists'])
            kda = round((playerdata['kills'] + playerdata['assists']) / playerdata['deaths'], 2)
            enemykda = round((enemydata['kills'] + enemydata['assists']) / enemydata['deaths'], 2)
            em.add_field(name = 'KDA', value = (str(kda) + ' | *' + KDAstring + '*'))
            em.add_field(name = 'CSD @ 10', value = str(round(playerdata['csdelta']['0-10'],2)))
            em.add_field(name = 'Gold Difference @ 10', value = str(round(playerdata['golddelta']['0-10'],2)))
            em.add_field(name = 'XP Difference @ 10', value = str(round(playerdata['xpdelta']['0-10'],2)))
            em.add_field(name = "Enemy Laner's KDA", value = str(enemykda) + ' | *' + enemyKDAstring + '*')

            if enemykda > kda or round(playerdata['csdelta']['0-10'], 2) < 0.0 or round(playerdata['golddelta']['0-10'], 2) < 0.0:
                em.add_field(name = 'Feeder Status', value = 'True')
            else:
                em.add_field(name = 'Feeder Status', value = 'False')

            await client.send_message(message.channel, embed=em)

client.run(discToken)<|endoftext|>


<commit_before>import ply.yacc as yacc
import AST
from lex import tokens

operations = {
    'plus': lambda x, y: x+y,
    'moins': lambda x, y: x-y,
    'fois': lambda x, y: x*y,
    'divise par': lambda x, y: x/y,
    'plus petit que': lambda x, y: x<y,
    'plus petit ou egal que': lambda x, y: x<=y,
    'plus grand que': lambda x, y: x>y,
    'plus grand ou egal que': lambda x, y: x>=y,
    'est egal a': lambda x, y: x==y,
}

default_values = {
    'entier': '0',
    'reel': '0.0',
    'texte': '',
    'booleen': 'faux',
}

precedence = (
    ('left', 'PLUS_OP'),
    ('left', 'MINUS_OP'),
    ('left', 'TIME_OP'),
    ('left', 'DIVIDE_OP'),
    ('right', 'UMINUS'),
)

def p_programme_statement(p):
    """programme : statement"""
    p[0] = AST.ProgramNode(p[1])

def p_programme_recursive(p):
    """programme : statement programme"""
    p[0] = AST.ProgramNode([p[1]]+p[2].children)

def p_statement(p):
    """statement : assignation ';'
                | structure ';'"""
    p[0] = p[1]

def p_statement_afficher(p):
    """statement : afficher expression ';'"""
    p[0] = AST.PrintNode(p[2])

def p_if(p):
    """structure : SI '(' expression ')' '{' programme '}'"""
    p[0] = AST.IfNode([p[3], p[6]])

def p_if_else(p):
    """structure : SI '(' expression ')' '{' programme '}' SINON '{' programme '}'"""
    p[0] = AST.IfNode([p[3], p[6], p[10]])

def p_declaration(p):
    """assignation : IDENTIFIER TYPE"""
    p[0] = AST.AssignNode([AST.TokenNode(p[1])] + [AST.TokenNode(p[2]), AST.TokenNode(default_values[p[2]])])

def p_declaration_assignation(p):
    """assignation : IDENTIFIER TYPE ASSIGN expression"""
    p[0] = AST.AssignNode([AST.TokenNode(p[1])] + [AST.TokenNode(p[2]), p[4]])

def p_assignation(p):
    """assignation : IDENTIFIER ASSIGN expression"""
    p[0] = AST.AssignNode([AST.TokenNode(p[1])] + [p[3]])

def p_expression_op(p):
    """expression : expression PLUS_OP expression
                | expression MINUS_OP expression
                | expression TIME_OP expression
                | expression DIVIDE_OP expression"""
    p[0] = AST.OpNode(p[2], [p[1], p[3]])

def p_expression_bool(p):
    """expression : expression SMALLER_THAN expression
            | expression SMALLER_EQUAL_THAN expression
            | expression GREATER_THAN expression
            | expression GREATER_EQUAL_THAN expression
            | expression EQUAL expression"""
    p[0] = AST.OpNode(p[2], [p[1], p[3]])

def p_expression_num(p):
    """expression : NUMBER
                | BOOL
                | STRING
                | IDENTIFIER"""
    p[0] = AST.TokenNode(p[1])

def p_expression_paren(p):
    """expression : '(' expression ')' """
    p[0] = p[2]

def p_for(p):
    """structure : POUR '(' IDENTIFIER de NUMBER a NUMBER BY_STEP NUMBER ')' '{' programme '}'"""
    p[0] = AST.ForNode([
        AST.AssignNode([AST.TokenNode('entier')] + [AST.TokenNode(p[3]), AST.TokenNode(p[5])]),  # Initialization
        AST.IfNode([AST.OpNode('SMALLER_EQUAL_THAN', [AST.TokenNode(p[3]), AST.TokenNode(p[7])]), p[12]]),  # Condition
        AST.AssignNode([AST.TokenNode(p[3])] + [AST.OpNode('plus', [AST.TokenNode(p[3]), AST.TokenNode(p[9])])])  # Inc
    ])

def p_while(p):
    """structure : WHILE '(' expression ')' '{' programme '}' """
    p[0] = AST.WhileNode([p[3]] + [p[6]])

def p_minus(p):
    """expression : PLUS_OP expression %prec UMINUS
                | MINUS_OP expression %prec UMINUS"""
    p[0] = AST.OpNode(p[1], [p[2]])

def p_error(p):
    print("Syntax error in line %d" % p.lineno)
    yacc.errok()

yacc.yacc(outputdir='generated')

def parse(program):
    return yacc.parse(program)#, debug=1)

if __name__ == "__main__":
    import os
    test_dir = "./tests/parser/"

    for file in os.listdir(test_dir):
        prog = open(test_dir+file).read()
        print(file)
        print("----------------------")
        result = parse(prog)
        print(result)
        graph = result.makegraphicaltree()
        name = 'pdf/' + file.split('.')[0] + '−ast.pdf'
        graph.write_pdf(name)<commit_msg>Fix bug<commit_after>import ply.yacc as yacc
import AST
from lex import tokens

operations = {
    'plus': lambda x, y: x+y,
    'moins': lambda x, y: x-y,
    'fois': lambda x, y: x*y,
    'divise par': lambda x, y: x/y,
    'plus petit que': lambda x, y: x<y,
    'plus petit ou egal que': lambda x, y: x<=y,
    'plus grand que': lambda x, y: x>y,
    'plus grand ou egal que': lambda x, y: x>=y,
    'est egal a': lambda x, y: x==y,
}

default_values = {
    'entier': '0',
    'reel': '0.0',
    'texte': '',
    'booleen': 'faux',
}

precedence = (
    ('left', 'PLUS_OP'),
    ('left', 'MINUS_OP'),
    ('left', 'TIME_OP'),
    ('left', 'DIVIDE_OP'),
    ('right', 'UMINUS'),
)

def p_programme_statement(p):
    """programme : statement"""
    p[0] = AST.ProgramNode(p[1])

def p_programme_recursive(p):
    """programme : statement programme"""
    p[0] = AST.ProgramNode([p[1]]+p[2].children)

def p_statement(p):
    """statement : assignation ';'
                | structure ';'"""
    p[0] = p[1]

def p_statement_afficher(p):
    """statement : afficher expression ';'"""
    p[0] = AST.PrintNode(p[2])

def p_if(p):
    """structure : SI '(' expression ')' '{' programme '}'"""
    p[0] = AST.IfNode([p[3], p[6]])

def p_if_else(p):
    """structure : SI '(' expression ')' '{' programme '}' SINON '{' programme '}'"""
    p[0] = AST.IfNode([p[3], p[6], p[10]])

def p_declaration(p):
    """assignation : IDENTIFIER TYPE"""
    p[0] = AST.AssignNode([AST.TokenNode(p[1])] + [AST.TokenNode(p[2]), AST.TokenNode(default_values[p[2]])])

def p_declaration_assignation(p):
    """assignation : IDENTIFIER TYPE ASSIGN expression"""
    p[0] = AST.AssignNode([AST.TokenNode(p[1])] + [AST.TokenNode(p[2]), p[4]])

def p_assignation(p):
    """assignation : IDENTIFIER ASSIGN expression"""
    p[0] = AST.AssignNode([AST.TokenNode(p[1])] + [p[3]])

def p_expression_op(p):
    """expression : expression PLUS_OP expression
                | expression MINUS_OP expression
                | expression TIME_OP expression
                | expression DIVIDE_OP expression"""
    p[0] = AST.OpNode(p[2], [p[1], p[3]])

def p_expression_bool(p):
    """expression : expression SMALLER_THAN expression
            | expression SMALLER_EQUAL_THAN expression
            | expression GREATER_THAN expression
            | expression GREATER_EQUAL_THAN expression
            | expression EQUAL expression"""
    p[0] = AST.OpNode(p[2], [p[1], p[3]])

def p_expression_num(p):
    """expression : NUMBER
                | BOOL
                | STRING
                | IDENTIFIER"""
    p[0] = AST.TokenNode(p[1])

def p_expression_paren(p):
    """expression : '(' expression ')' """
    p[0] = p[2]

def p_for(p):
    """structure : POUR '(' IDENTIFIER de NUMBER a NUMBER BY_STEP NUMBER ')' '{' programme '}'"""
    p[0] = AST.ForNode([
        AST.AssignNode([AST.TokenNode('entier')] + [AST.TokenNode(p[3]), AST.TokenNode(p[5])]),  # Initialization
        AST.IfNode([AST.OpNode('plus petit ou egal que', [AST.TokenNode(p[3]), AST.TokenNode(p[7])]), p[12]]),  # Condition
        AST.AssignNode([AST.TokenNode(p[3])] + [AST.OpNode('plus', [AST.TokenNode(p[3]), AST.TokenNode(p[9])])])  # Inc
    ])

def p_while(p):
    """structure : WHILE '(' expression ')' '{' programme '}' """
    p[0] = AST.WhileNode([p[3]] + [p[6]])

def p_minus(p):
    """expression : PLUS_OP expression %prec UMINUS
                | MINUS_OP expression %prec UMINUS"""
    p[0] = AST.OpNode(p[1], [p[2]])

def p_error(p):
    print("Syntax error in line %d" % p.lineno)
    yacc.errok()

yacc.yacc(outputdir='generated')

def parse(program):
    return yacc.parse(program)#, debug=1)

if __name__ == "__main__":
    import os
    test_dir = "./tests/parser/"

    for file in os.listdir(test_dir):
        prog = open(test_dir+file).read()
        print(file)
        print("----------------------")
        result = parse(prog)
        print(result)
        graph = result.makegraphicaltree()
        name = 'pdf/' + file.split('.')[0] + '−ast.pdf'
        graph.write_pdf(name)<|endoftext|>


<commit_before># coding=utf-8
from datetime import timedelta

import discord
from discord.ext import commands
import asyncio

import config
from TextChecker import TextChecker
from data.rp_texts import cheat_texts
import random
from data.links import inventory_manipulation_link as iml
import database

from web import Web

class Fun(commands.Cog):

    cheats = {
        "▒▒▓▓▓▓▒▓▓▓▓▓▓▓▓▓▒▓▓": ('Fuchsia', None, 0, 0, 0xFF00FF),
        "░░░░░░░░░░░░░░░░░░░": ('Olive', None, 0, 0, 0x808000),
        "░░▒░░▒▒▒░░░░▒▒░░░▒░": ('Green', 'diamonds', 100, 500, 0x66FF00),
        "░▓▓░░▓▓▒▓▒▒▒░░▒▒▓░▒": ('Navy', 'diamonds', -500, -100, 0x000080),
        "▒░░░░▒░░▒▒▒░░░▒▓▒▓░": ('Turquoise', 'diamonds', 1000, 2000, 0x40E0D0),
        "▒▓░░▒▓▓▒░▒▒░░▒░▒▓░░": ('Violet', 'diamonds', -2000, -1000, 0x8F00FF),
        "▓░░░▓░▓▓▒░▓░░▓▓▓▒░░": ('Maroon', 'diamonds', 2000, 5000, 0xB03060),
        "▒▒░░▒▒▓░▒▒▓░░▒▓▓▒░▒": ('Yellow', 'diamonds', -5000, -2000, 0xFFE135),
        "▒░░▒▒░▒▓▒░▒▒▓░░▒▓▓▒": ('Gold', 'diamonds', 1, 10000, 0xFFD700),
        "▓░░▓▓▓▒░░░░░▒▒▓▓░░▒": ('Silver', 'diamonds', -10000, -1, 0xC0C0C0),
        "░▒▒░▒▒░▒▓▓▒▒▓▒▒░▒░░": ('Aqua', 'diamonds', 0, 0, 0x00FFFF),
        "▒▒░▒▒░▒░▒▓░▒▒▓░░░▒▒": ('Lime', 349, 1, 1, 0x00FF00),
        "▒▒░░▒▒▒▒▓▒░░░▒▒▒░▒▓": ('Blue', 412, 5, 5, 0x0000FF),
        "▓▒▒▓▓▒▓▒▒░░▒░▒░▒▒░░": ('Teal', 439, 5, 5, 0x008080),
        "▒░▒▒░░░▒▒▒▒░░▒▒░▒▓▒": ('Emerald', 410, 5, 5, 0x50C878),
        "░░░▒▒▓▓░░▒▒░▓░░▒▓░░": ('Red', 411, 5, 5, 0xFF0038),
        "░░░▒▒▒░▒▓▒▒▓▓▓▓▒▓▓▓": ('Orange', 407, 5, 5, 0xFFA500),
        "░░▓▓▒░░▓▓▒░░▓░▓░▓░▒": ('White', 409, 5, 5, 0xF8F8FF),
        "░░▒▓░▒▓▓▒▓▒░░▒▒░░▒░": ('Bronze', 386, 1, 1, 0xCD7F32),
        "▒░░░▒░▓▒▓░░░▒▒░░▒░░": ('Copper', 302, 1, 1, 0xB87333),
        "▒▒▓░▒▓▒▓░▒▓░▒▓▓░▒▒▒": ('Brass', 271, 1, 1, 0xB5A642),
        "░░▒▒░░░▒░▒░▒▒░░░▒░░": ('Grey', 270, 1, 1, 0x848482),
        "▓▓▓▒░░▒░░▓░▓░░░░░░░": ('Black', 421, 1, 1, 0x292421),
        "░░▓▓░▓░▓▓░▓░░▓░░▓▓▒": ('Pink', 87, 1, 1, 0xFFB7C5),
        "▓░▓▓░▓░▓▓░▓░░▓░░▓▓▓": ('Brown', 261, 1, 1, 0x964B00),
    }

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command(aliases=tuple(cheats), hidden=True)
    async def _use_cheat(self, ctx):
        if not isinstance(ctx.channel, discord.DMChannel):
            await ctx.message.delete()
        else:
            await ctx.send("This needs to be used in RP channel.")
            return
        if '💎' not in ctx.channel.name:
            to_delete = await ctx.send("This needs to be used in RP channel.")
            await asyncio.sleep(7)
            await to_delete.delete()
            return
        await self.inventory_manipulation(ctx)

    async def inventory_manipulation(self, ctx):
        db = await database.Database.get_connection(self.bot.loop)
        cooldown_check = "SELECT * FROM cheat_history WHERE user_id = $1 and code = $2 and use > $3"
        cooldown_data = (
            str(ctx.author.id),
            ctx.invoked_with,
            ctx.message.created_at - timedelta(days=1)
        )
        async with db.transaction():
            async for (user_id, code, last_use) in db.cursor(cooldown_check, *cooldown_data):
                cd_end = last_use + timedelta(days=1)
                difference = cd_end - ctx.message.created_at
                if difference > timedelta(hours=12):
                    remaining = "almost a day"
                elif difference > timedelta(hours=6):
                    remaining = "less than 12 hours"
                elif difference > timedelta(hours=3):
                    remaining = "less than 6 hours"
                elif difference > timedelta(hours=1):
                    remaining = "less than 3 hours"
                else:
                    remaining = "less than 1 hour"
                await ctx.send("You have to wait for " + remaining + " in order to use this")
                return
        name, item, min_bound, max_bound, colour = self.cheats[ctx.invoked_with]
        text = TextChecker.replace_emotes(cheat_texts[name], self.bot)
        text = text.replace('[CMDR]', ctx.author.mention)
        amount = random.randint(min_bound, max_bound)

        embed = discord.Embed(description=text, colour=colour)
        embed.set_author(name=ctx.author.nick or ctx.author.display_name,
                         icon_url=ctx.author.avatar_url)

        await ctx.send(embed=embed)

        if item is not None:
            values = {
                'item'      : item,
                'quantity'  : amount,
                'hack'      : True,
                'discord_id': ctx.author.id,
                # 'discord_id': 294171600478142466,
                'key'       : config.TRANSACTION_KEY
            }
            response = await Web.get_response(iml, values)
        cheat_history_data = (
            str(ctx.author.id),
            ctx.invoked_with,
            ctx.message.created_at
        )
        await db.execute("INSERT INTO cheat_history VALUES($1, $2, $3)", *cheat_history_data)

def setup(bot: commands.Bot):
    bot.add_cog(Fun(bot))
<commit_msg>cheating system<commit_after># coding=utf-8
from datetime import timedelta

import discord
from discord.ext import commands
import asyncio

import config
from TextChecker import TextChecker
from data.rp_texts import cheat_texts
import random
from data.links import inventory_manipulation_link as iml
import database

from web import Web

class Fun(commands.Cog):

    cheats = {
        "▒▒▓▓▓▓▒▓▓▓▓▓▓▓▓▓▒▓▓": ('Fuchsia', None, 0, 0, 0xFF00FF),
        "░░░░░░░░░░░░░░░░░░░": ('Olive', None, 0, 0, 0x808000),
        "░░▒░░▒▒▒░░░░▒▒░░░▒░": ('Green', 'diamonds', 100, 500, 0x66FF00),
        "░▓▓░░▓▓▒▓▒▒▒░░▒▒▓░▒": ('Navy', 'diamonds', -500, -100, 0x000080),
        "▒░░░░▒░░▒▒▒░░░▒▓▒▓░": ('Turquoise', 'diamonds', 1000, 2000, 0x40E0D0),
        "▒▓░░▒▓▓▒░▒▒░░▒░▒▓░░": ('Violet', 'diamonds', -2000, -1000, 0x8F00FF),
        "▓░░░▓░▓▓▒░▓░░▓▓▓▒░░": ('Maroon', 'diamonds', 2000, 5000, 0xB03060),
        "▒▒░░▒▒▓░▒▒▓░░▒▓▓▒░▒": ('Yellow', 'diamonds', -5000, -2000, 0xFFE135),
        "▒░░▒▒░▒▓▒░▒▒▓░░▒▓▓▒": ('Gold', 'diamonds', 1, 10000, 0xFFD700),
        "▓░░▓▓▓▒░░░░░▒▒▓▓░░▒": ('Silver', 'diamonds', -10000, -1, 0xC0C0C0),
        "░▒▒░▒▒░▒▓▓▒▒▓▒▒░▒░░": ('Aqua', 'diamonds', 0, 0, 0x00FFFF),
        "▒▒░▒▒░▒░▒▓░▒▒▓░░░▒▒": ('Lime', 349, 1, 1, 0x00FF00),
        "▒▒░░▒▒▒▒▓▒░░░▒▒▒░▒▓": ('Blue', 412, 5, 5, 0x0000FF),
        "▓▒▒▓▓▒▓▒▒░░▒░▒░▒▒░░": ('Teal', 439, 5, 5, 0x008080),
        "▒░▒▒░░░▒▒▒▒░░▒▒░▒▓▒": ('Emerald', 410, 5, 5, 0x50C878),
        "░░░▒▒▓▓░░▒▒░▓░░▒▓░░": ('Red', 411, 5, 5, 0xFF0038),
        "░░░▒▒▒░▒▓▒▒▓▓▓▓▒▓▓▓": ('Orange', 407, 5, 5, 0xFFA500),
        "░░▓▓▒░░▓▓▒░░▓░▓░▓░▒": ('White', 409, 5, 5, 0xF8F8FF),
        "░░▒▓░▒▓▓▒▓▒░░▒▒░░▒░": ('Bronze', 386, 1, 1, 0xCD7F32),
        "▒░░░▒░▓▒▓░░░▒▒░░▒░░": ('Copper', 302, 1, 1, 0xB87333),
        "▒▒▓░▒▓▒▓░▒▓░▒▓▓░▒▒▒": ('Brass', 271, 1, 1, 0xB5A642),
        "░░▒▒░░░▒░▒░▒▒░░░▒░░": ('Grey', 270, 1, 1, 0x848482),
        "▓▓▓▒░░▒░░▓░▓░░░░░░░": ('Black', 421, 1, 1, 0x292421),
        "░░▓▓░▓░▓▓░▓░░▓░░▓▓▒": ('Pink', 87, 1, 1, 0xFFB7C5),
        "▓░▓▓░▓░▓▓░▓░░▓░░▓▓▓": ('Brown', 261, 1, 1, 0x964B00),
    }

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command(aliases=tuple(cheats), hidden=True)
    async def _use_cheat(self, ctx):
        if not isinstance(ctx.channel, discord.DMChannel):
            await ctx.message.delete()
        else:
            await ctx.send("This needs to be used in RP channel.")
            return
        if '💎' not in ctx.channel.name:
            to_delete = await ctx.send("This needs to be used in RP channel.")
            await asyncio.sleep(7)
            await to_delete.delete()
            return
        await self.inventory_manipulation(ctx)

    async def inventory_manipulation(self, ctx):
        db = await database.Database.get_connection(self.bot.loop)
        cooldown_check = "SELECT * FROM cheat_history WHERE user_id = $1 and code = $2 and use > $3"
        cooldown_data = (
            str(ctx.author.id),
            ctx.invoked_with,
            ctx.message.created_at - timedelta(days=1)
        )
        async with db.transaction():
            async for (user_id, code, last_use) in db.cursor(cooldown_check, *cooldown_data):
                cd_end = last_use + timedelta(days=1)
                difference = cd_end - ctx.message.created_at
                if difference > timedelta(hours=12):
                    remaining = "almost a day"
                elif difference > timedelta(hours=6):
                    remaining = "less than 12 hours"
                elif difference > timedelta(hours=3):
                    remaining = "less than 6 hours"
                elif difference > timedelta(hours=1):
                    remaining = "less than 3 hours"
                else:
                    remaining = "less than 1 hour"
                to_delete = await ctx.send("You must wait for " + remaining + " to use this command again.")
                await asyncio.sleep(7)
                await to_delete.delete()
                return
        name, item, min_bound, max_bound, colour = self.cheats[ctx.invoked_with]
        text = TextChecker.replace_emotes(cheat_texts[name], self.bot)
        text = text.replace('[CMDR]', ctx.author.mention)
        amount = random.randint(min_bound, max_bound)

        embed = discord.Embed(description=text, colour=colour)
        embed.set_author(name=ctx.author.nick or ctx.author.display_name,
                         icon_url=ctx.author.avatar_url)

        await ctx.send(embed=embed)

        if item is not None:
            values = {
                'item'      : item,
                'quantity'  : amount,
                'hack'      : True,
                'discord_id': ctx.author.id,
                # 'discord_id': 294171600478142466,
                'key'       : config.TRANSACTION_KEY
            }
            response = await Web.get_response(iml, values)
        cheat_history_data = (
            str(ctx.author.id),
            ctx.invoked_with,
            ctx.message.created_at
        )
        await db.execute("INSERT INTO cheat_history VALUES($1, $2, $3)", *cheat_history_data)

def setup(bot: commands.Bot):
    bot.add_cog(Fun(bot))
<|endoftext|>


<commit_before>import discord
from discord.ext import commands
from tabulate import tabulate

from models.character import Character
from utils import *

class Delete:
    """Delete commands."""

    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True)
    async def delete(self, ctx, fam_name=''):
        """Deletes users's main character from list. **officers can add an optional family name at the
        end to delete a certain user"""

        try:
            author = ctx.message.author
            if not fam_name:
                member = Character.primary_chars(member = author.id).first()
            else:
                member = Character.primary_chars(fam_name__icontains = fam_name, server = ctx.message.server.id).first()
                roles = [u.name for u in author.roles]
                if ADMIN_USER not in roles:
                    await self.bot.say("Only officers may perform this action")
                    return
            member.delete()
            info = [["Success Deleting User"], ["Character", member.char_name], ["Family", member.fam_name]]
            logActivity('Character {} has been deleted'.format(member.char_name), author.name)
            await self.bot.say(codify(tabulate(info)))
        except Exception as e:
            print_error(e)
            await self.bot.say(codify("Error deleting user"))

def setup(bot):
    bot.add_cog(Delete(bot))
<commit_msg>Adds delete_all function for officers<commit_after>import discord
from discord.ext import commands
from tabulate import tabulate

from models.character import Character
from utils import *

class Delete:
    """Delete commands."""

    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True)
    async def delete(self, ctx, fam_name=''):
        """Deletes users's main character from list. **officers can add an optional family name at the
        end to delete a certain user"""

        try:
            author = ctx.message.author
            if not fam_name:
                member = Character.primary_chars(member = author.id).first()
            else:
                member = Character.primary_chars(fam_name__icontains = fam_name, server = ctx.message.server.id).first()
                roles = [u.name for u in author.roles]
                if ADMIN_USER not in roles:
                    await self.bot.say("Only officers may perform this action")
                    return
            member.delete()
            info = [["Success Deleting User"], ["Character", member.char_name], ["Family", member.fam_name]]
            logActivity('Character {} has been deleted'.format(member.char_name), author.name)
            await self.bot.say(codify(tabulate(info)))
        except Exception as e:
            print_error(e)
            await self.bot.say(codify("Error deleting user"))

    @commands.command(pass_context=True)
    async def delete_all(self, ctx):
        """****Officers only***** Deletes All Characters from the server"""

        try:
            author = ctx.message.author
            roles = [u.name for u in author.roles]
            if ADMIN_USER not in roles:
                await self.bot.say("Only officers may perform this action")
                return
            await self.bot.say(codify("Are you sure you want to delete all characters?(times out in 10 secs)\n Reply Yes to confirm"))
            msg = await self.bot.wait_for_message(author=ctx.message.author, content="Yes", timeout=10)
            if msg and msg.content == "Yes":
                Character.objects(server = ctx.message.server.id).delete()
                await self.bot.say(codify("Success Clearing All Characters on Server"))
                return
            await self.bot.say(codify("Operation Cancelled"))
        except Exception as e:
            print(e)
            await self.bot.say(codify("Error deleting all characters"))

def setup(bot):
    bot.add_cog(Delete(bot))
<|endoftext|>


<commit_before>import unittest

import numpy

import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import testing
from chainer import utils
from chainer.testing import attr

def _sigmoid(x):
    half = x.dtype.type(0.5)
    return numpy.tanh(x * half) * half + half

@testing.parameterize(*testing.product({
    'shape': [(3, 2), ()],
    'dtype': [numpy.float16, numpy.float32, numpy.float64],
    'contiguous': [None, 'C'],
}))
@testing.fix_random()
@testing.inject_backend_tests(
    None,
    # CPU tests
    [
        {},
        {'use_ideep': True},
    ]
    # GPU tests
    + testing.product({
        'use_cuda': [True],
        'use_cudnn': ['never', 'always'],
        'cuda_device': [0, 1],
    })
    # ChainerX tests
    + testing.product({
        'use_chainerx': [True],
        'chainerx_device': ['native:0', 'cuda:0', 'cuda:1'],
    })
)
class TestSigmoid(testing.FunctionTestCase):

    def setUp(self):
        if self.dtype == numpy.float16:
            self.check_forward_options = {'atol': 1e-4, 'rtol': 1e-3}
            self.check_backward_options = {'atol': 1e-2, 'rtol': 5e-2}
            self.check_double_backward_options = {'atol': 1e-2, 'rtol': 5e-2}

    def generate_inputs(self):
        x = numpy.random.uniform(-.5, .5, self.shape).astype(self.dtype)
        return x,

    def forward_expected(self, inputs):
        x, = inputs
        y = _sigmoid(x)
        y = utils.force_array(y)
        return y,

    def forward(self, inputs, device):
        x,  = inputs
        return functions.sigmoid(x),

@testing.parameterize(*testing.product({
    'use_cudnn': ['always', 'auto', 'never'],
    'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
@attr.cudnn
class TestSigmoidCudnnCall(unittest.TestCase):

    def setUp(self):
        self.x = cuda.cupy.random.uniform(-1, 1, (2, 3)).astype(self.dtype)
        self.gy = cuda.cupy.random.uniform(-1, 1, (2, 3)).astype(self.dtype)
        with chainer.using_config('use_cudnn', self.use_cudnn):
            self.expect = chainer.should_use_cudnn('==always')

    def forward(self):
        x = chainer.Variable(self.x)
        return functions.sigmoid(x)

    def test_call_cudnn_forward(self):
        default_func = cuda.cupy.cudnn.activation_forward
        with chainer.using_config('use_cudnn', self.use_cudnn):
            with testing.patch('cupy.cudnn.activation_forward') as func:
                func.side_effect = default_func
                self.forward()
                self.assertEqual(func.called, self.expect)

    def test_call_cudnn_backward(self):
        with chainer.using_config('use_cudnn', self.use_cudnn):
            y = self.forward()
            y.grad = self.gy
            default_func = cuda.cupy.cudnn.activation_backward
            with testing.patch('cupy.cudnn.activation_backward') as func:
                func.side_effect = default_func
                y.backward()
                self.assertEqual(func.called, self.expect)

testing.run_module(__name__, __file__)
<commit_msg>fix import order<commit_after>import unittest

import numpy

import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
from chainer import utils

def _sigmoid(x):
    half = x.dtype.type(0.5)
    return numpy.tanh(x * half) * half + half

@testing.parameterize(*testing.product({
    'shape': [(3, 2), ()],
    'dtype': [numpy.float16, numpy.float32, numpy.float64],
    'contiguous': [None, 'C'],
}))
@testing.fix_random()
@testing.inject_backend_tests(
    None,
    # CPU tests
    [
        {},
        {'use_ideep': True},
    ]
    # GPU tests
    + testing.product({
        'use_cuda': [True],
        'use_cudnn': ['never', 'always'],
        'cuda_device': [0, 1],
    })
    # ChainerX tests
    + testing.product({
        'use_chainerx': [True],
        'chainerx_device': ['native:0', 'cuda:0', 'cuda:1'],
    })
)
class TestSigmoid(testing.FunctionTestCase):

    def setUp(self):
        if self.dtype == numpy.float16:
            self.check_forward_options = {'atol': 1e-4, 'rtol': 1e-3}
            self.check_backward_options = {'atol': 1e-2, 'rtol': 5e-2}
            self.check_double_backward_options = {'atol': 1e-2, 'rtol': 5e-2}

    def generate_inputs(self):
        x = numpy.random.uniform(-.5, .5, self.shape).astype(self.dtype)
        return x,

    def forward_expected(self, inputs):
        x, = inputs
        y = _sigmoid(x)
        y = utils.force_array(y)
        return y,

    def forward(self, inputs, device):
        x,  = inputs
        return functions.sigmoid(x),

@testing.parameterize(*testing.product({
    'use_cudnn': ['always', 'auto', 'never'],
    'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
@attr.cudnn
class TestSigmoidCudnnCall(unittest.TestCase):

    def setUp(self):
        self.x = cuda.cupy.random.uniform(-1, 1, (2, 3)).astype(self.dtype)
        self.gy = cuda.cupy.random.uniform(-1, 1, (2, 3)).astype(self.dtype)
        with chainer.using_config('use_cudnn', self.use_cudnn):
            self.expect = chainer.should_use_cudnn('==always')

    def forward(self):
        x = chainer.Variable(self.x)
        return functions.sigmoid(x)

    def test_call_cudnn_forward(self):
        default_func = cuda.cupy.cudnn.activation_forward
        with chainer.using_config('use_cudnn', self.use_cudnn):
            with testing.patch('cupy.cudnn.activation_forward') as func:
                func.side_effect = default_func
                self.forward()
                self.assertEqual(func.called, self.expect)

    def test_call_cudnn_backward(self):
        with chainer.using_config('use_cudnn', self.use_cudnn):
            y = self.forward()
            y.grad = self.gy
            default_func = cuda.cupy.cudnn.activation_backward
            with testing.patch('cupy.cudnn.activation_backward') as func:
                func.side_effect = default_func
                y.backward()
                self.assertEqual(func.called, self.expect)

testing.run_module(__name__, __file__)
<|endoftext|>


<commit_before>#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

__author__ = 'lycheng'
__email__ = "lycheng997@gmail.com"

from public import TreeNode
from public import list_to_linked
from public import is_palindrome

import unittest

class Solution(unittest.TestCase):

    def sortedListToBST(self, head):
        def get_n_item(head, n):
            i = head
            while n:
                i = i.next
                n -= 1
            return i

        def helper(head, start, end):
            if start > end or not head:
                return None

            mid = (start + end) / 2
            mid_item = get_n_item(head, mid)
            if not mid_item:
                return None
            root = TreeNode(mid_item.val)
            if start != end:
                root.left = helper(head, 0, mid-1)
                root.right = helper(mid_item.next, 0, end-mid-1)
            return root

        if not head:
            return None

        cur = head
        l = 0
        while cur:
            cur = cur.next
            l += 1

        return helper(head, 0, l)

    def test_sortedListToBST(self):
        head = list_to_linked([1, 2, 3])
        root = self.sortedListToBST(head)
        self.assertEqual(2, root.val)
        self.assertEqual(1, root.left.val)
        self.assertEqual(3, root.right.val)

    def majorityElement(self, num):
        count_map = {}
        majority = None
        majority_times = 0

        for n in num:
            if n not in count_map:
                count_map[n] = 0
            count_map[n] += 1

            if count_map[n] > majority_times:
                majority_times = count_map[n]
                majority = n

        return majority

    def test_majorityElement(self):
        num = [1, 2, 3, 4, 1, 1, 1]
        self.assertEqual(self.majorityElement(num), 1)

    def convertToTitle(self, num):
        ascii_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        result = []
        while num:
            r = num % 26
            num /= 26
            result.append(ascii_table[r-1])
            if not r:
                num -= 1
        return "".join(result[::-1])

    def test_convertToTitle(self):
        self.assertEqual(self.convertToTitle(26), 'Z')
        self.assertEqual(self.convertToTitle(27), 'AA')

    def compareVersion(self, version1, version2):
        longer = version1.split('.')
        shorter = version2.split('.')
        flag = 1

        if len(longer) < len(shorter):
            longer, shorter = shorter, longer
            flag = -1

        for idx in range(len(longer)):
            longer_item = int(longer[idx])
            if idx >= len(shorter):
                if not longer_item:
                    shorter.append(0)
                    continue
                return flag
            elif longer_item > int(shorter[idx]):
                return flag
            elif longer_item < int(shorter[idx]):
                return -flag

        if len(longer) == len(shorter):
            return 0

    def test_compareVersion(self):
        self.assertEqual(self.compareVersion('2.1', '1.1'), 1)
        self.assertEqual(self.compareVersion('1.1', '1.1'), 0)
        self.assertEqual(self.compareVersion('1.1', '2.1'), -1)
        self.assertEqual(self.compareVersion('1', '1.1'), -1)
        self.assertEqual(self.compareVersion('1.0', '1'), 0)

    def partition(self, s):
        ''' https://oj.leetcode.com/problems/palindrome-partitioning/
        '''
        result = []

        def dfs(cur_idx, cur_result):
            if cur_idx == len(s):
                result.append(cur_result[:])
                return

            for i in range(cur_idx, len(s)):
                cur_str = s[cur_idx:i+1]
                if is_palindrome(cur_str):
                    cur_result.append(cur_str)
                    dfs(i+1, cur_result)
                    cur_result.pop()

        dfs(0, [])
        return result

    def test_partition(self):
        s = 'aab'
        rv = self.partition(s)
        self.assertIn(['a', 'a', 'b'], rv)
        self.assertIn(['aa', 'b'], rv)
        self.assertEqual(2, len(rv))

if __name__ == "__main__":
    unittest.main()
<commit_msg>update<commit_after>#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

__author__ = 'lycheng'
__email__ = "lycheng997@gmail.com"

from public import TreeNode
from public import list_to_linked
from public import is_palindrome

import unittest

class Solution(unittest.TestCase):

    def sortedListToBST(self, head):
        def get_n_item(head, n):
            i = head
            while n:
                i = i.next
                n -= 1
            return i

        def helper(head, start, end):
            if start > end or not head:
                return None

            mid = (start + end) / 2
            mid_item = get_n_item(head, mid)
            if not mid_item:
                return None
            root = TreeNode(mid_item.val)
            if start != end:
                root.left = helper(head, 0, mid-1)
                root.right = helper(mid_item.next, 0, end-mid-1)
            return root

        if not head:
            return None

        cur = head
        l = 0
        while cur:
            cur = cur.next
            l += 1

        return helper(head, 0, l)

    def test_sortedListToBST(self):
        head = list_to_linked([1, 2, 3])
        root = self.sortedListToBST(head)
        self.assertEqual(2, root.val)
        self.assertEqual(1, root.left.val)
        self.assertEqual(3, root.right.val)

    def majorityElement(self, num):
        count_map = {}
        majority = None
        majority_times = 0

        for n in num:
            if n not in count_map:
                count_map[n] = 0
            count_map[n] += 1

            if count_map[n] > majority_times:
                majority_times = count_map[n]
                majority = n

        return majority

    def test_majorityElement(self):
        num = [1, 2, 3, 4, 1, 1, 1]
        self.assertEqual(self.majorityElement(num), 1)

    def convertToTitle(self, num):
        '''https://oj.leetcode.com/problems/excel-sheet-column-title/
        '''
        ascii_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        result = []
        while num:
            r = num % 26
            num /= 26
            result.append(ascii_table[r-1])
            if not r:
                num -= 1
        return "".join(result[::-1])

    def test_convertToTitle(self):
        self.assertEqual(self.convertToTitle(26), 'Z')
        self.assertEqual(self.convertToTitle(27), 'AA')

    def compareVersion(self, version1, version2):
        longer = version1.split('.')
        shorter = version2.split('.')
        flag = 1

        if len(longer) < len(shorter):
            longer, shorter = shorter, longer
            flag = -1

        for idx in range(len(longer)):
            longer_item = int(longer[idx])
            if idx >= len(shorter):
                if not longer_item:
                    shorter.append(0)
                    continue
                return flag
            elif longer_item > int(shorter[idx]):
                return flag
            elif longer_item < int(shorter[idx]):
                return -flag

        if len(longer) == len(shorter):
            return 0

    def test_compareVersion(self):
        self.assertEqual(self.compareVersion('2.1', '1.1'), 1)
        self.assertEqual(self.compareVersion('1.1', '1.1'), 0)
        self.assertEqual(self.compareVersion('1.1', '2.1'), -1)
        self.assertEqual(self.compareVersion('1', '1.1'), -1)
        self.assertEqual(self.compareVersion('1.0', '1'), 0)

    def partition(self, s):
        ''' https://oj.leetcode.com/problems/palindrome-partitioning/
        '''
        result = []

        def dfs(cur_idx, cur_result):
            if cur_idx == len(s):
                result.append(cur_result[:])
                return

            for i in range(cur_idx, len(s)):
                cur_str = s[cur_idx:i+1]
                if is_palindrome(cur_str):
                    cur_result.append(cur_str)
                    dfs(i+1, cur_result)
                    cur_result.pop()

        dfs(0, [])
        return result

    def test_partition(self):
        s = 'aab'
        rv = self.partition(s)
        self.assertIn(['a', 'a', 'b'], rv)
        self.assertIn(['aa', 'b'], rv)
        self.assertEqual(2, len(rv))

    def titleToNumber(self, s):
        '''https://oj.leetcode.com/problems/excel-sheet-column-number/
        '''
        ascii_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        result = 0
        p = 0
        for l in s[::-1]:
            idx = ascii_table.index(l) + 1
            result += idx * (26 ** p)
            p += 1
        return result

    def test_titleToNumber(self):
        self.assertEqual(self.titleToNumber('Z'), 26)
        self.assertEqual(self.titleToNumber('AA'), 27)

if __name__ == "__main__":
    unittest.main()
<|endoftext|>


<commit_before>emojis = {
    "lenny": "( ͡° ͜ʖ ͡°)",
    "fight": "(ง º  ͜ʖ º )ง",
    "fight2": "(ง⚆ᗜ⚆)ง",
    "fight3": "(ง⚆ᨎ⚆)ง",
    "approve": "ಠ_ಠ",
    "cool": "(⌐■_■)",
    "happy": "^‿^",
    "mouse": "ʢ◉ᴥ◉ʡ",
    "arrow": "⤜(ʘ_ʘ)⤏",
    "hug": "(づ◔ ͜ʖ◔)づ",
    "hug2": "(づ｡◕‿‿◕｡)づ",
    "dog": "(⚆ᴥ⚆)",
    "fireworks": "(∩*ヮ*)⊃━☆ﾟ.*",
    "smile": "◕ ◡ ◕",
    "embarrassed": "⊙﹏⊙",
    "surprised": "( ﾟoﾟ)",
    "ballin": "ヘ(◕。◕ヘ)",
    "stare": "◉_◉",
    "stare2": "๏_๏",
    "stop": "╚(•⌂•)╝",
    "oo": "•ﺑ•",
    "oo2": "‹•.•›",
    "fyou": "ಠ︵ಠ凸",
    "potter": "ϟ",
    "needle": "┣▇▇▇═───────────",
    "injured": "(///_ಥ)",
    "pucker": "(ﾟ＊ﾟ)",
    "blush": "(｡･_･｡)",
    "happy2": "(ﾟヮﾟ)",
    "ha": "(´▽`)",
    "silly": ":^Þ",
    "bigsmile": """⎛　　　　●　　　　●　 ⎞

⎝　　　　　　╰╯　　  ⎠""",
    "ok": "👌",
    "fight4": "(ง ͠° ͟ل͜ ͡°)ง",
    "money5": "[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
    "moneylenny": "[̲̅$̲̅(̲̅ ͡° ͜ʖ ͡°̲̅)̲̅$̲̅]",
    "magic": "(ﾉ◕ヮ◕)ﾉ*:･ﾟ✧",
    "doublemagic": "(ﾉ◕ヮ◕)ﾉ*:･ﾟ✧ ✧ﾟ･: *ヽ(◕ヮ◕ヽ)",
    "cry": "(ಥ﹏ಥ)",
    "kiss": "(づ￣ ³￣)づ",
    "point": "(☞ﾟヮﾟ)☞",
    "uzi": "⌐╦╦═─",
    "sword": "o()xxxx[{::::::::::::::::::::::::::::::::::>",
    "machete": "O:::|_________________/",
    "bender": "¦̵̱ ̵̱ ̵̱ ̵̱ ̵̱(̢ ̡͇̅└͇̅┘͇̅ (▤8כ−◦",
    "shoot": "( ͡° ͜ʖ ͡°) ▄︻̷̿┻̿═━一 (ʘᗩʘ')",
    "salt": "ヽ｀、ヽヽ｀ヽ｀、ヽヽ｀ヽ｀、ヽヽ༼ຈ ل͜ຈ༽ﾉ ɪᴛs ʀᴀɪɴɪɴɢ sᴀʟᴛ! ヽ༼ຈل͜ຈ༽ﾉ ヽ｀ヽ｀、ヽヽ｀ヽ｀、｀ヽ｀",
    "robber": "̿ ̿ ̿'̿'\̵͇̿̿\з:(•_•):ε/̵͇̿̿/'̿'̿ ̿",
    "dead": "(✖╭╮✖)",
    "dead2": "╭( ✖_✖ )╮",
    "evil": "ψ(｀∇´)ψ",
    "evil2": "Ψ(｀◇´)Ψ",
    "evil3": "ψ(｀∇´)ψ",
    "excited": "(★^O^★)",
    "fish": "(◐ o ◑ )",
    "fish2": ">゜))))彡",
    "coffee": "( -_-)旦~",
    "kiss2": "( ˘ ³˘)❤",
    "kiss3": "(ΘεΘ)",
    "happy3": "(◎ヮ◎)",
    "shrug2": "┐(￣ー￣)┌",
    "mustache": "( ￣┏＿┓￣)",
    "shrug": "¯\_(ツ)_/¯",
    "infinity": "∞",
    "why": "щ(ಠ益ಠщ)",
    "facepalm": "(－‸ლ)"
}

# dir = dir()
#
# emojis = []
# for emoji in dir:
#     if not emoji.startswith("__"):
#         emojis.append(emoji)
# emojis = "`{}`".format("`, `".join(emojis))
#
# rEmojis = []
# for emoji in dir:
#     if not emoji.startswith("__"):
#         rEmojis.append(emoji)
<commit_msg>added emoj<commit_after>emojis = {
    "lenny": "( ͡° ͜ʖ ͡°)",
    "fight": "(ง º  ͜ʖ º )ง",
    "fight2": "(ง⚆ᗜ⚆)ง",
    "fight3": "(ง⚆ᨎ⚆)ง",
    "approve": "ಠ_ಠ",
    "cool": "(⌐■_■)",
    "happy": "^‿^",
    "mouse": "ʢ◉ᴥ◉ʡ",
    "arrow": "⤜(ʘ_ʘ)⤏",
    "hug": "(づ◔ ͜ʖ◔)づ",
    "hug2": "(づ｡◕‿‿◕｡)づ",
    "dog": "(⚆ᴥ⚆)",
    "fireworks": "(∩*ヮ*)⊃━☆ﾟ.*",
    "smile": "◕ ◡ ◕",
    "embarrassed": "⊙﹏⊙",
    "surprised": "( ﾟoﾟ)",
    "ballin": "ヘ(◕。◕ヘ)",
    "stare": "◉_◉",
    "stare2": "๏_๏",
    "stop": "╚(•⌂•)╝",
    "oo":"【☉.☉】",
    "oo2": "•ﺑ•",
    "oo3": "‹•.•›",
    "fyou": "ಠ︵ಠ凸",
    "potter": "ϟ",
    "needle": "┣▇▇▇═───────────",
    "injured": "(///_ಥ)",
    "pucker": "(ﾟ＊ﾟ)",
    "blush": "(｡･_･｡)",
    "happy2": "(ﾟヮﾟ)",
    "ha": "(´▽`)",
    "silly": ":^Þ",
    "bigsmile": """⎛　　　　●　　　　●　 ⎞

⎝　　　　　　╰╯　　  ⎠""",
    "ok": "👌",
    "fight4": "(ง ͠° ͟ل͜ ͡°)ง",
    "money5": "[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
    "moneylenny": "[̲̅$̲̅(̲̅ ͡° ͜ʖ ͡°̲̅)̲̅$̲̅]",
    "magic": "(ﾉ◕ヮ◕)ﾉ*:･ﾟ✧",
    "doublemagic": "(ﾉ◕ヮ◕)ﾉ*:･ﾟ✧ ✧ﾟ･: *ヽ(◕ヮ◕ヽ)",
    "cry": "(ಥ﹏ಥ)",
    "kiss": "(づ￣ ³￣)づ",
    "point": "(☞ﾟヮﾟ)☞",
    "uzi": "⌐╦╦═─",
    "sword": "o()xxxx[{::::::::::::::::::::::::::::::::::>",
    "machete": "O:::|_________________/",
    "bender": "¦̵̱ ̵̱ ̵̱ ̵̱ ̵̱(̢ ̡͇̅└͇̅┘͇̅ (▤8כ−◦",
    "shoot": "( ͡° ͜ʖ ͡°) ▄︻̷̿┻̿═━一 (ʘᗩʘ')",
    "salt": "ヽ｀、ヽヽ｀ヽ｀、ヽヽ｀ヽ｀、ヽヽ༼ຈ ل͜ຈ༽ﾉ ɪᴛs ʀᴀɪɴɪɴɢ sᴀʟᴛ! ヽ༼ຈل͜ຈ༽ﾉ ヽ｀ヽ｀、ヽヽ｀ヽ｀、｀ヽ｀",
    "robber": "̿ ̿ ̿'̿'\̵͇̿̿\з:(•_•):ε/̵͇̿̿/'̿'̿ ̿",
    "dead": "(✖╭╮✖)",
    "dead2": "╭( ✖_✖ )╮",
    "evil": "ψ(｀∇´)ψ",
    "evil2": "Ψ(｀◇´)Ψ",
    "evil3": "ψ(｀∇´)ψ",
    "excited": "(★^O^★)",
    "fish": "(◐ o ◑ )",
    "fish2": ">゜))))彡",
    "coffee": "( -_-)旦~",
    "kiss2": "( ˘ ³˘)❤",
    "kiss3": "(ΘεΘ)",
    "happy3": "(◎ヮ◎)",
    "shrug2": "┐(￣ー￣)┌",
    "mustache": "( ￣┏＿┓￣)",
    "shrug": "¯\_(ツ)_/¯",
    "infinity": "∞",
    "why": "щ(ಠ益ಠщ)",
    "facepalm": "(－‸ლ)"
}

# dir = dir()
#
# emojis = []
# for emoji in dir:
#     if not emoji.startswith("__"):
#         emojis.append(emoji)
# emojis = "`{}`".format("`, `".join(emojis))
#
# rEmojis = []
# for emoji in dir:
#     if not emoji.startswith("__"):
#         rEmojis.append(emoji)
<|endoftext|>