from collections import defaultdict

from django.db import models

from wagtail.core import blocks
from wagtail.core.fields import RichTextField, StreamField
from wagtail.core.rich_text import RichText
from wagtail.images.blocks import ImageChooserBlock
from wagtail.snippets.blocks import SnippetChooserBlock

from wagtail_localize.models import TranslatableMixin
from wagtail_localize.segments import TemplateValue

from .html import restore_html_segments

def organise_template_segments(segments):
    template = None
    segments_by_position = {}

    for segment in segments:
        if isinstance(segment, TemplateValue):
            template = segment
        else:
            segments_by_position[int(segment.path)] = segment

    texts = []
    for position in range(template.segment_count):
        texts.append(segments_by_position[position].text)

    return template.format, template.template, texts

def handle_related_object(related_object, src_locale, tgt_locale, segments):
    if related_object is None or not isinstance(related_object, TranslatableMixin):
        return related_object

    # Note: when called from streamfield, we may be given the translated object
    related_original = related_object.get_translation(src_locale)
    related_translated = related_object.get_translation_or_none(tgt_locale)

    if related_translated is None:
        # Create translated version by copying the original version
        related_translated = related_original.copy_for_translation(tgt_locale)

    ingest_segments(related_original, related_translated, src_locale, tgt_locale, segments)
    related_translated.save()
    return related_translated

class StreamFieldSegmentsWriter:
    def __init__(self, field, src_locale, tgt_locale):
        self.field = field
        self.src_locale = src_locale
        self.tgt_locale = tgt_locale

    def handle_block(self, block_type, block_value, segments):
        if hasattr(block_type, 'restore_translated_segments'):
            return block_type.restore_translated_segments(block_value, segments)

        elif isinstance(block_type, blocks.CharBlock):
            return segments[0].text

        elif isinstance(block_type, blocks.RichTextBlock):
            format, template, texts = organise_template_segments(segments)
            assert format == 'html'
            return RichText(restore_html_segments(template, texts))

        elif isinstance(block_type, (ImageChooserBlock, SnippetChooserBlock)):
            return self.handle_related_object_block(block_value, segments)

        elif isinstance(block_type, blocks.StructBlock):
            return self.handle_struct_block(block_value, segments)

        elif isinstance(block_type, blocks.ListBlock):
            return self.handle_list_block(block_value, segments)

        else:
            raise Exception("Unrecognised StreamField block type '{}'. Have you implemented restore_translated_segments() on this class?".format(block_type.__class__.__name__))

    def handle_related_object_block(self, related_object, segments):
        return handle_related_object(related_object, self.src_locale, self.tgt_locale, segments)

    def handle_struct_block(self, struct_block, segments):
        segments_by_field = defaultdict(list)

        for segment in segments:
            field_name, segment = segment.unwrap()
            segments_by_field[field_name].append(segment)

        for field_name in getattr(struct_block.block.meta, 'translated_fields', []):
            segments = segments_by_field[field_name]

            if segments:
                block_type = struct_block.block.child_blocks[field_name]
                block_value = struct_block[field_name]
                struct_block[field_name] = self.handle_block(block_type, block_value, segments)

        return struct_block

    def handle_list_block(self, list_block, segments):
        # TODO
        pass

    def get_stream_block_child_data(self, data, block_uuid):
        for stream_child in data:
            if stream_child.id == block_uuid:
                return stream_child

    def handle_stream_block(self, data, segments):
        segments_by_block = defaultdict(list)

        for segment in segments:
            block_uuid, segment = segment.unwrap()
            segments_by_block[block_uuid].append(segment)

        for block_uuid, segments in segments_by_block.items():
            block = self.get_stream_block_child_data(data, block_uuid)
            block.value = self.handle_block(block.block, block.value, segments)

def ingest_segments(original_obj, translated_obj, src_locale, tgt_locale, segments):
    # Get segments by field name
    segments_by_field_name = defaultdict(list)
    for segment in segments:
        field_name, segment = segment.unwrap()
        segments_by_field_name[field_name].append(segment)

    for field_name, field_segments in segments_by_field_name.items():
        field = translated_obj.__class__._meta.get_field(field_name)

        if hasattr(field, 'restore_translated_segments'):
            value = field.value_from_object(original_obj)
            new_value = field.restore_translated_segments(value, field_segments)
            setattr(translated_obj, field_name, new_value)

        elif isinstance(field, StreamField):
            data = field.value_from_object(original_obj)
            StreamFieldSegmentsWriter(field, src_locale, tgt_locale).handle_stream_block(data, field_segments)
            setattr(translated_obj, field_name, data)

        elif isinstance(field, RichTextField):
            format, template, texts = organise_template_segments(field_segments)
            assert format == 'html'
            html = restore_html_segments(template, texts)
            setattr(translated_obj, field_name, RichText(html))

        elif isinstance(field, (models.TextField, models.CharField)):
            setattr(translated_obj, field_name, field_segments[0].text)

        elif isinstance(field, models.ForeignKey):
            related_original = getattr(original_obj, field_name)
            related_translated = handle_related_object(related_original, src_locale, tgt_locale, field_segments)
            setattr(translated_obj, field_name, related_translated)

        elif isinstance(field, (models.ManyToOneRel)):
            original_manager = getattr(original_obj, field_name)
            translated_manager = getattr(translated_obj, field_name)

            segments_by_child = defaultdict(list)

            for segment in field_segments:
                child_translation_key, segment = segment.unwrap()
                segments_by_child[child_translation_key].append(segment)

            for child_translation_key, child_segments in segments_by_child.items():
                original_child_object = original_manager.filter(translation_key=child_translation_key).first()
                translated_child_object = translated_manager.filter(translation_key=child_translation_key).first()

                if not translated_child_object:
                    # TODO: Here, we expect that the inline child to already exist as Wagtail copies it
                    # when creating the translated page. When we add editing, we will need to support
                    # adding new inline objects manually.
                    continue

                ingest_segments(original_child_object, translated_child_object, src_locale, tgt_locale, child_segments)
                translated_child_object.save()


import numpy as np
from keras.models import Model, Sequential
from keras.layers import GRU, Input, Dense, TimeDistributed, Activation, RepeatVector, Bidirectional, Dropout, LSTM
from keras.layers.embeddings import Embedding
from keras.optimizers import Adam
from keras.losses import sparse_categorical_crossentropy

latent_dim = 256  # latent dimensionality of the encoding space
learning_rate = 0.003

encoder_inputs = Input(shape=(None, encode_tokens))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]

decoder_inputs = Input(shape=(None, decoder_tokens))
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
                                     initial_state=encoder_states)
decoder_dense = Dense(decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
model = Model(inputs=[encoder_inputs, decoder_inputs],
              outputs=decoder_outputs)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')


import requests
import bs4

def url_in_list(url, listobj):
    """Determine whether a URL is in a list of URLs.
    This function checks whether the URL is contained in the list with either
    an http:// or https:// prefix. It is used to avoid crawling the same
    page separately as http and https.
    """
    http_version = url.replace('https://', 'http://')
    https_version = url.replace('http://', 'https://')
    return (http_version in listobj) or (https_version in listobj)

def find_title_and_artist(soup, base_title, base_url='https://www.lyrics.com', base_artist=None):
    temp = soup.body.find_all('div', attrs={'class':'sec-lyric clearfix'})
    #print(temp)
    for t in temp:
        base = t.find_all('div', attrs={'class':'lyric-meta within-lyrics'})[0]
        title = base.find('p', attrs={'class':'lyric-meta-title'}).text
        artist = base.find('p', attrs={'class':'lyric-meta-artists'}).text
        link = base.find('p', attrs={'class':'lyric-meta-title'}).a.get('href')
        link = base_url + link
        #print(title, " -- " ,base_title)
        if base_artist is not None:
            if base_artist.lower() != artist.lower():
                print(base_artist)
                continue
        if title.lower() == base_title.lower():
            print(title," ", artist, " ", link )
            return [title, artist, link]

def find_lyrics_title_artist(keyword, base_artist=None):
    url = 'https://www.lyrics.com/lyrics/'+keyword.replace(" ", "%20")
    #print(url)
    # read the page
    try:
        response = requests.get(url)
    except (requests.exceptions.MissingSchema,
            requests.exceptions.InvalidSchema):
        print("*FAILED*:", url)
        return
    if not response.headers['content-type'].startswith('text/html'):
        print("not html. skipping..")
        return
    soup = bs4.BeautifulSoup(response.text, "html.parser")
    try:
        title, artist, link = find_title_and_artist(soup, base_title=keyword, base_artist=base_artist)
    except:
        return
    lyrics = find_lyric(link)
    return [title, artist, link, lyrics]

def find_lyric(link):
    response = requests.get(link)
    if not response.headers['content-type'].startswith('text/html'):
        print("not html. skipping..")
        #return
    soup = bs4.BeautifulSoup(response.text, "html.parser")
    lyrics = soup.body.pre.text.replace("\r\n",' \n')
    #print(lyrics)
    return lyrics


from conans import ConanFile, CMake

class TaoCppAlgorithm(ConanFile):
    name = "algorithm"
    license = "MIT"
    url = "https://github.com/tao-cpp/algorithm"
    description = "C++ general purpose algorithms library"

    settings = "os", "compiler", "arch", "build_type"

    exports_sources = "CMakeLists.txt", "include/*", "test/*", "benchmark/*", "src/*"
    no_copy_source = True
    # build_policy = "missing"

    options = {
        "tests": [True, False],
    }

    default_options = {
        "tests": False,
    }

    def configure(self):
        # self.output.info("****** configure ******* self.options.tests: %s" % (self.options.tests,))

        # If header only, the compiler, etc, does not affect the package!
        if not self.options.tests:
            # self.output.info("****** CLEARING THE SETTINGS *******")
            self.settings.clear()

    def build(self):
        if self.options.tests:
            # self.output.info("****** build ******* self.options.tests: %s" % (self.options.tests,))
            cmake = CMake(self)
            cmake.configure()
            cmake.build()
            # cmake.install()
            cmake.test()

    def package(self):
        self.copy("*.h", dst="include", src="include")
        self.copy("*.hpp", dst="include", src="include")
        self.copy("*.ipp", dst="include", src="include")

    def package_id(self):
        self.info.header_only()
        self.info.options.tests = "ANY"


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

def osoba(imie, nazwisko, wiek):
    return {'imie': imie, 'nazwisko': nazwisko, 'wiek': wiek}

def pobierzDane(lista, n):
    for i in range(0, n):
        imie = input('Podaj imię: ')
        nazwisko = input('Podaj nazwisko: ')
        wiek = int(input('Podaj wiek: '))
        lista.append(osoba(imie, nazwisko, wiek))
    return lista

def wyswietlDane(lista):
    for o in lista:
        print("Imię: {:>20}".format(o['imie']))
        print("Nazwisko: {:>20}".format(o['nazwisko']))
        print("Wiek: {:>20}".format(o['wiek']))
    print()

def zapiszDane(lista):
    with open('osobyp.txt', 'w') as plik:
        for o in lista:
            plik.write(
                o['imie'] + "," + o['nazwisko'] + "," + str(o['wiek']) + "\n")

def zapiszDaneCsv(lista):
    import csv
    with open('osobyp.csv', 'w', newline='') as plik:
        tresc = csv.writer(plik, delimiter=';')
        for o in lista:
            tresc.writerow(o.values())

def czytajDane(nazwa):
    import csv
    with open(nazwa, newline='') as plik:
        tresc = csv.reader(plik, delimiter=';')
        for o in tresc:
            print(o)

def main(args):
    # osoba1 = osoba('Jan', 'Kowalski', 23)
    # print(osoba1['imie'], osoba1['nazwisko'])
    # lista = []  # pusta lista
    # ile = int(input('Ile osób wprowadzisz? '))
    # lista = pobierzDane(lista, ile)
    # wyswietlDane(lista)
    # zapiszDaneCsv(lista)
    czytajDane('osobyp.csv')
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import seaborn as sb

df = pd.read_csv('sgti15.csv')

df = pd.concat([df, pd.get_dummies(df['TIPO'])], axis=1)

df = df.drop(columns='TIPO')

for col in  df.columns:
    df[col] = df[col].astype(float)

X = df

kmeans = KMeans(n_clusters=3, random_state=0).fit(X)
X_clustered = kmeans.fit_predict(X)

X['clusterNumber'] = X_clustered

print(df.dtypes)

LABEL_COLOR_MAP = {0 : 'red', 1 : 'blue', 2: 'green'}
label_color = [LABEL_COLOR_MAP[l] for l in X_clustered]

feature1 = 2 # valor do índice da coluna
feature2 = 1
labels = ['TEMPO', 'ANO', 'BENNER','COMPUTADOR']
c1label = labels[feature1]
c2label = labels[feature2]

plt.figure(figsize = (12,12))
plt.scatter(X.iloc[:, feature1],X.iloc[:, feature2], c=label_color, alpha=0.3)
plt.xlabel(c1label, fontsize=18)
plt.ylabel(c2label, fontsize=18)

plt.show()


#!/usr/bin/env python

from pathlib import Path
from setuptools import setup

root = Path(__file__).parent or "."

with (root / "README.rst").open(encoding="utf-8") as f:
    long_description = f.read()

with (root / "requirements.txt").open(encoding="utf-8") as f:
    requirements = list(filter(None, (row.strip() for row in f)))

info = {
    "name":                "piweather",
    "version":             "0.1",
    "author":              "Christoph Weinsheimer",
    "author_email":        "ch.weinsheimer@googlemail.com",
    "url":                 "https://github.com/weinshec/piweather",
    "packages":            ["piweather"],
    "provides":            ["piweather"],
    "description":         "Automatic weather station based on a Raspberry Pi",
    "long_description":    long_description,
    "keywords":            ["raspberrypi", "python", "aws", "weather"],
    "install_requires":    requirements,
    "setup_requires":      ["nose", "flake8", "coverage"],
}

if __name__ == "__main__":
    setup(**info)


import pygame
import random
from player import Player
from enemies import Enemies
from tiro import Tiro
from killzone import Zone
from missil import Misseis
from bosses import Boss
from laser import Laser

#Iciando o pygame
pygame.init()

#Criando a janela
janela = pygame.display.set_mode([600, 480])

#Grupos
objectGroup = pygame.sprite.Group()
enemyGroup = pygame.sprite.Group()
shotGroup = pygame.sprite.Group()
menuGroup = pygame.sprite.Group()
zoneGroup = pygame.sprite.Group()
overGroup = pygame.sprite.Group()

#BG GAME
bg1 = pygame.sprite.Sprite(objectGroup)
bg1.image = pygame.image.load("Sprites/Cenario.png")
bg1.rect = pygame.Rect(10, 20, 100, 100)

bg2 = pygame.sprite.Sprite(objectGroup)
bg2.image = pygame.image.load("Sprites/Cenario.png")
bg2.rect = pygame.Rect(10, 250, 100, 100)

bg3 = pygame.sprite.Sprite(objectGroup)
bg3.image = pygame.image.load("Sprites/Cenario.png")
bg3.rect = pygame.Rect(490, 20, 100, 100)

bg4 = pygame.sprite.Sprite(objectGroup)
bg4.image = pygame.image.load("Sprites/Cenario.png")
bg4.rect = pygame.Rect(490, 250, 100, 100)

#BG MENU
bgm = pygame.sprite.Sprite(menuGroup)
bgm.image = pygame.image.load("Sprites/Menu.png")
bgm.rect = bgm.image.get_rect()

#BG GAME OVER
bgo = pygame.sprite.Sprite(overGroup)
bgo.image = pygame.image.load("Sprites/Gameover.png")
bgo.rect = bgm.image.get_rect()

#Musica
pygame.mixer.music.load("Musica/Musica.wav")
pygame.mixer.music.play(-1)
pygame.mixer.music.set_volume(0.2)

#Variaveis de controle
clock = pygame.time.Clock() #Definiro "fps" do jogo
click = False
pontos = 0
gameMode = 1
vidaBoss = 0

#Função para apresentar a pontuação
def Pontos():
    pygame.font.init()
    font = pygame.font.Font('freesansbold.ttf', 32)
    score = font.render("Score : " + str(pontos), True, (255, 255, 255))
    janela.blit(score, (250, 20))

#Logica do game
def Game():

    pygame.display.set_caption("ATIRA MULESTA! - GAME - ") #Tela

    #Efeitos sonoros
    tiro = pygame.mixer.Sound("Musica/Tiro.wav")
    pygame.mixer.Sound.set_volume(tiro, 0.1)

    player = Player(objectGroup) #Criar o player

    #Loop principal
    global pontos
    global restart    # Variaveis globais
    global gameMode
    global vidaBoss

    #Variaveis de controle em geral
    shot = True # controle do tiro
    pode = True # controle para spawnar o boss
    timer1 = 0
    timer2 = 0 #Timers para controlar tempo
    timer3 = 0
    timer4 = 0
    restart = 0
    gameMode = 3
    gameLoop = True

    if __name__ == "__main__":
        while gameLoop:
            clock.tick(60)

            for event in pygame.event.get():  # Essa linha captura os inputs
                if event.type == pygame.QUIT: #Input de fechar o game
                    gameMode = 1
                    gameLoop = False

                elif event.type == pygame.KEYDOWN and shot: #Input SPACE
                    if event.key == pygame.K_SPACE:
                        tiro.play()
                        newShot = Tiro(objectGroup, shotGroup) #Cria o tiro se apertar SPACE
                        newShot.rect.center = player.rect.center
                        shot = False

            objectGroup.update()
            timer1 += 1
            timer2 += 1     #Atualizadores
            timer3 += 1
            timer4 += 1
            restart += 1

            if restart == 1: # Restart
                zona = Zone(objectGroup, zoneGroup)
                zona.rect.center = player.rect.center

            #Spawn de inimigos simples
            if timer1 > 30:
                timer1 = 0
                shot = True
                if random.randint(1, 10) <= 3:
                    newEnemy = Enemies(objectGroup, enemyGroup)

            #Spawn de inimgos complexos
            if timer2 > 60:
                timer2 = 0
                if random.randint(1, 10) <= 1:
                    newMissil = Misseis(objectGroup, enemyGroup)

            #Boss
            if timer3 >= 1800 and vidaBoss == 0 and pode:
                pode = False
                vidaBoss = 10
                if vidaBoss == 10:
                    newBoss = Boss(objectGroup, zoneGroup)

            #Laser do boss
            if timer4 > 60 and not pode:
                timer4 = 0
                print("opa")
                laser = Laser(objectGroup, enemyGroup)
                #laser.rect.center =

            #Verifica colisão de sprites (sprite do palyer com sprites do enemyGroup)
            collisions = pygame.sprite.spritecollide(player, enemyGroup, True, pygame.sprite.collide_mask)

            if collisions: # Se colidir, morre, game over e tal
                print("Game over")
                player.kill()
                if not pode:
                    newBoss.kill()
                gameover()
                gameLoop = False

            #Colisões de gupo, as variaveis boleanas nas colisões servem pra dizer se o objeto vai ser ou não destruido
            hits = pygame.sprite.groupcollide(shotGroup, enemyGroup, True, True, pygame.sprite.collide_mask)
            zoo = pygame.sprite.groupcollide(zoneGroup, enemyGroup, False, True, pygame.sprite.collide_mask)

            if hits: #Se acertar algum inimigo, conta ponto
                pontos += 1

            # Acertar o boss
            bossHit = pygame.sprite.groupcollide(shotGroup, zoneGroup, True, False)
            if bossHit:
                if bossHit and vidaBoss > 0:
                    vidaBoss -= 1

                elif vidaBoss == 0:
                    newBoss.kill()
                    vidaBoss = 1

            #Atualizadores da tela e de pontos
            janela.fill([0, 0, 0])
            objectGroup.draw(janela)
            Pontos()
            pygame.display.update()

#Função de menu
#Tudo nessa função serve para apresentar a tela de menu
def Menu():
    global restart
    global pontos

    while True:

        pygame.display.set_caption("ATIRA MULESTA! - MENU - ")
        janela.fill([0, 0, 0])

        mx, my = pygame.mouse.get_pos()# Posição do mouse

        button = pygame.Rect(200, 310, 190, 95)

        if button.collidepoint((mx, my)): #Se o mouse esta encima do botão
            if click: # se click, inicia o jogo
                Game()

        pygame.draw.rect(janela, (255, 0, 0), button)

        click = False
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:  #Verificando e acianando o click
                print("Antes")
                if event.button == 1:
                    print("Funcionou")
                    restart = 0
                    pontos = 0
                    click = True

        menuGroup.draw(janela)
        clock.tick(60)              #Atualizadores
        pygame.display.update()

def gameover(): #A tela de game over

    global restart
    global pontos
    gameLoop = True
    while gameLoop:

        janela.fill([0, 0, 0])
        overGroup.draw(janela)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameLoop = False

        clock.tick(60)
        pygame.display.update()

#Chamando a função de menu, serve pra iniciar o game em si
Menu()


from django import forms

from .models import Voter

class VoterForm(forms.ModelForm):
    class Meta:
        model = Voter
        fields = [
            "first_name",
            "last_name",
            "house_number",
            "street_name",
            "unit_num",
            "zip_code",
            "email",
            "phone",
            "date_of_birth",
            "support_level",
            "notes",
        ]

class VoterSearchForm(forms.ModelForm):
    class Meta:
        model = Voter

        fields = [
            "first_name",
            "last_name",
        ]

    def __init__(self, *args, **kwargs):
            super(VoterSearchForm, self).__init__(*args, **kwargs)
            for key in self.fields:
                self.fields[key].required = False


import paramiko
import os

privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
username = 'vinod'
transport = paramiko.Transport(('192.168.9.50', '22'))
transport.connect(username=username, pkey=mykey)

sftp = paramiko.SFTPClient.from_transport(transport)

remotepath = '/U1000/t1/images/file.png'
localpath = '/test/test.gz'
sftp.put(remotepath, localpath)

sftp.close()
transport.close()


#
# tags/utilitylib.py
#
# SVN/CVS Keywords
#----------------------------------
# $Author: cnobile $
# $Date: 2010-10-05 12:28:39 -0400 (Tue, 05 Oct 2010) $
# $Revision: 26 $
#----------------------------------

from django import template
from inventory.setupenv import getLogger

log = getLogger()

register = template.Library()

@register.tag
def hideNoValueField(parser, token):
    """
    This tag hides fields that have no data.

    Arguments:

     1. field = The field to be worked on.
     2. fieldList = A list or tuple of valid field names. Can be a literal
        string on the page or from the context.
     3. tag = The tag type. ie. li, td, etc.

    Examples:

     * {% hideNoValueField field "('Distributor', 'Manufacturer')" li %}
     * {% hideNoValueField field fieldList li %}
     """
    tokens = token.split_contents()
    size = len(tokens)

    if size < 4:
        msg = "Invalid number of arguments, found %s should be three."
        raise template.TemplateSyntaxError(msg % (size-1))

    tagName = tokens[0]
    field = tokens[1]
    cmpLabels = tokens[2].strip('"')
    tagType = tokens[3]
    #log.debug("tagName: %s, field: %s, cmpLabels: %s, tageType: %s",
    #          tagName, field, cmpLabels, tagType)
    return NoValueFieldNode(tagName, field, cmpLabels, tagType)

class NoValueFieldNode(template.Node):
    def __init__(self, tagName, field, cmpLabels, tagType):
        self._tagName = tagName
        self._fieldVar = template.Variable(field)
        self._cmpLabelsVar = template.Variable(cmpLabels)
        self._tagTypeVar = template.Variable(tagType)

    def render(self, context):
        field = self._fieldVar.resolve(context)
        label = field.label
        labelTag = field.label_tag()
        tagType = self._tagTypeVar.var

        try:
            cmpLabels = self._cmpLabelsVar.resolve(context)
        except:
            cmpLabels = eval(self._cmpLabelsVar.var)

        #log.debug("%s: label: %s, field: %s, labelTag: %s, cmpLabels: %s",
        #          self._tagName, label, field, labelTag, cmpLabels)

        result = ""

        if 'value' in str(field) or 'None' not in str(field):
            result = "<%s>%s%s</%s>" % (tagType, labelTag, field, tagType)

        return result

@register.tag
def assign(parser, token):
    """
    Assign an expression to a variable in the current context.

    Arguments:

     1. name = The variable name.
     2. value = The value to assign to the name.

    Examples:

     * {% assign [name] [value] %}
     * {% assign list entry.get_related %}
    """
    bits = token.contents.split()

    if len(bits) != 3:
        msg = "%s: tag takes two arguments"
        raise template.TemplateSyntaxError(msg % bits[0])

    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def render(self, context):
        context[self.name] = self.value.resolve(context, True)
        return ''


#!/usr/bin/python3

import sys

blast = open(sys.argv[1],"r")
for l in blast:
	if l.startswith("#"): continue
	f = l.split("\t")
	if abs(int(f[9]) - int(f[8])) < 800: continue
	print(l,end="")
blast.close()


import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
import urllib
from google.appengine.api import urlfetch
import logging
from django.utils import simplejson

logger = logging.getLogger("EcoSystemInputsBatchOutput")

ubertool_config_service_base_url = os.environ['UBERTOOL_MONGO_SERVER']

def batchLoadEcosystemInputsConfigs(params_matrix,config_index,ubertool_configuration_properties):
    config_params = {}
    config_name = None
    if "ecosystem_inputs_config_name" in params_matrix:
        config_name = params_matrix.get("ecosystem_inputs_config_name")[config_index]
    if "concentration_of_particulate_organic_carbon" in params_matrix:
        config_params['concentration_of_particulate_organic_carbon'] = params_matrix.get("concentration_of_particulate_organic_carbon")[config_index]
    if "concentration_of_dissolved_organic_carbon" in params_matrix:
        config_params['concentration_of_dissolved_organic_carbon'] = params_matrix.get("concentration_of_dissolved_organic_carbon")[config_index]
    if "concentration_of_dissolved_oxygen" in params_matrix:
        config_params['concentration_of_dissolved_oxygen'] = params_matrix.get("concentration_of_dissolved_oxygen")[config_index]
    if "water_temperature" in params_matrix:
        config_params['water_temperature'] = params_matrix.get("water_temperature")[config_index]
    if "concentration_of_suspended_solids" in params_matrix:
        config_params['concentration_of_suspended_solids'] = params_matrix.get("concentration_of_suspended_solids")[config_index]
    if "sediment_organic_carbon" in params_matrix:
        config_params['sediment_organic_carbon'] = params_matrix.get("sediment_organic_carbon")[config_index]
    config_params['ecosystems_configuration'] = config_name
    ubertool_configuration_properties.update(config_params)
    config_params['config_name'] = config_name
    form_data = simplejson.dumps(config_params)
    url = ubertool_config_service_base_url+"/ubertool/eco/"+config_name
    result = urlfetch.fetch(url=url,
                        payload=form_data,
                        method=urlfetch.POST,
                        headers={'Content-Type': 'application/json'})
    return ubertool_configuration_properties


import cv2
import numpy as np
import requests
import webbrowser

#--------------------------------------NFC MODULE=====================================

def nfc_read():
    f = open('C:/Users/정근영/Desktop/nfc.txt','r')

    print(f)
    for i in range(1,6) :
        line = f.readline()
    print(line)
    f.read(15)
    nfcid=""
    for j in range(1,5) :
        nfcid=nfcid+f.read(2)
        f.read(1)
    print(nfcid)
    nfcurl = "http://113.198.84.251:80/process/selnfc"
    data = {'nfc_id' :  nfcid}
    d = requests.post(nfcurl, data=data)
    open('photo.jpg','wb').write(d.content)

#---------------------insert passport picture and recognized that----------------

def facematcher():
    recognizer_LBP = cv2.face.LBPHFaceRecognizer_create()
    #분류기 모델을 LBPH(local binary pattern histogram)으로 만들어줌
    #recognizer_PCA = cv2.face.EigenFaceRecognizer_create()
    #recognizer_FFR = cv2.face.FisherFaceRecognizer_create()
    #LBPH검출기에 트레이닝한 yml파일을 읽혀줌
    recognizer_LBP.read('trainner/trainner_LBP.yml')
    #recognizer_PCA.read('trainner/trainner_PCA.yml')
    #recognizer_FFR.read('trainner/trainner_FFR.yml')
    #cascade검출기를 이용하여 얼굴을 검색
    cascadePath = "src/haarcascade_frontalface_alt.xml"
    #imgPath = "user8.jpg"
    #imgPath = "passport1.jpg"
    imgPath = "user6.jpg"
    #imgPath = "123.jpg"
    #여권에서 뽑은 사진
    faceCascade = cv2.CascadeClassifier(cascadePath)
    x=0
    y=0
    w=0
    h=0
    Id = 0
    result = ''
    names = ['User','Keunyoung','Hanbin','jayhwan','changwoo','dongmin']
    number = [0,1,2,3,4,5]
    #회원의 Id가 1로 설정되어있기 때문에 검출기에서 1을 반환하면 Success
    #cam = cv2.VideoCapture(0)
    #font = cv2.InitFont(cv2.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1)
    font = cv2.FONT_HERSHEY_SIMPLEX
    fontscale = 1
    fontcolor = (255, 0, 0)
    #while True:
    img =cv2.imread(imgPath)
    img_resize = img#cv2.resize(img,(260,350),cv2.INTER_AREA)
    #이미지의 크기를 일정한 크기로 변환
    gray=cv2.cvtColor(img_resize,cv2.COLOR_BGR2GRAY)
    gray_tmp = gray.copy()
    faces=faceCascade.detectMultiScale(gray, 1.2,5)
    #gray스케일로 변환한 이미지를 cascade분류기를 통해 얼굴을 검출
    #print(faces)
    faces_k = faces[0]
    #print(faces_k)
    x = faces_k[0]
    y = faces_k[1]
    w = faces_k[2]
    h = faces_k[3]
    #print(x,y,w,h)
    ex,ey,ew,eh = int(x + 0.15*w), int(y + 0.25 * h), int(0.70 * w), int(0.70 * h)
    gray_tmp=gray_tmp[ey:ey+eh,ex:ex+ew]
    cv2.rectangle(img_resize,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
    #gray_tmp=gray_tmp[y+50:y+h-30,x+30:x+w-30]
    #Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
    Id_LBP, conf_LBP = recognizer_LBP.predict(faces)
    #Id_PCA, conf_PCA = recognizer_PCA.predict(gray_tmp_rs)
    #Id_FFR, conf_FFR = recognizer_FFR.predict(gray_tmp)
    #뽑아낸 얼굴에서 검출기로 훈련된 ID와 confidence값을 구함
    print('LBPH recognizer : ',Id_LBP,conf_LBP)
    #print('EigenFace recognizer : ',Id_PCA,conf_PCA)
    #print('Fisher recognizer : ',Id_FFR,conf_FFR)
    if(conf_LBP < 50):
        if(Id_LBP == 0) :
            Id_LBP = names[Id_LBP]
            result = 'Success'
            conf_LBP = "  {0}%".format(round(150-(conf_LBP)))
            #만약 conf값이 70이하이면 Id는 success로 바꿔줌 (일치율 :)
        else :
            Id_LBP = names[Id_LBP]
            result = 'Fail'
            conf_LBP = "  {0}%".format(round(150-(conf_LBP)))
            fontcolor=(0,0,255)
    else:
        Id_LBP= "Fail"
        conf_LBP = "  {0}%".format(round(100 - (conf_LBP)))
        fontcolor=(0,0,255)

    #if resive_data == Id_LBP :
    #    result = 'Success'
    #    fontcolor=(0,0,255)

    cv2.putText(img_resize,str(Id_LBP), (ex,ey+5),font, 1.5,fontcolor)
    cv2.putText(img_resize,result, (ex,ey-30),font, 1.5,fontcolor)
    cv2.putText(img_resize,str(conf_LBP),(x+5,y+h-5),font,1,(255,0,0))
    #화면에 이름과 퍼센트를 표현
    cv2.imshow('im',img_resize)
    cv2.imwrite('result.jpg',img_resize)
    k = cv2.waitKey(0) & 0xFF
    if k == 27 :cv2.destroyAllWindows()
    '''
    res = "true"
    url = "http://113.198.84.251:80/process/faceauth"
    data = {'faceauth': res}
    d = requests.post(url, data=data)
    print('Complete result sended!! \n result = ' + str(d.content))
    print(d.content)
    ff = open("test.html","w")
    ff.write(str(d.content.decode('utf-8')))
    ff.close()
    webbrowser.open_new("test.html")
    '''
#nfc_read()
facematcher()

#0번이 실시간 훈련데이터 1~5는 미리 훈련한 사용자 데이터이고 0번이 안나오면 실패


import setuptools

with open("README.txt", "r") as fh:
    long_desription = fh.read()

setuptools.setup(
        name='project',
        version='0.1',
        scripts=['project'] ,
        author="Shreyas Shandilya",
        author_email="Shreyas Shandilya",
        description="ED6001 project",
        long_description = long_desription,
        long_description_content_type="text/markdown",
        url="https://github.com/shandilya1998/ED6001-project",
        packages=setuptools.find_packages(),
        classifiers=[
         "Programming Language :: Python :: 2",
        ],
    )


import os
import pandas as pd

train = pd.read_csv(os.path.join('../practice/kaggle/titanic/data', 'train.csv'))
df = train

# window width option
pd.set_option('display.width', 1500)

# explore
df.info()
df.describe()
df.head()
df.tail()
df.nlargest(5, ['Pclass', 'Age'])
df.nsmallest(5, ['Pclass', 'Age'])

# counts
train.Survived.value_counts(normalize=True)

# group by
train['Survived'].groupby(train['Pclass']).mean()

# aggregate ml_tools
df.Survived.groupby(df.Pclass).agg(['mean','count'])

# apply
train['Name_Len'] = train['Name'].apply(lambda x: len(x))
# value_counts by all columns
df.apply(pd.Series.value_counts)

# cut
pd.cut(train['Age'],3)

# fillna
train['Cabin'].fillna(0, inplace=True)

# recode
df.loc[(df['Age'] > 16) & (df['Age'] <= 32), 'Age'].mean()
train.loc[(df['Cabin'] != 0), 'Cabin'] = 1

# one hot
pd.get_dummies(pd.cut(train['Pclass'],5), prefix="Pclass")

# sorting
df.sort_values(by=('Age'))

# change columns name
df.columns = [x.lower() for x in df.columns]

# factorize with labels as indexes - pd.factorize
df_numeric = df.select_dtypes(exclude=['object'])  # get numeric types
df_obj = df.select_dtypes(include=['object']).copy()  # get non-numeric types
for c in df_obj:
    df_obj[c] = pd.factorize(df_obj[c])[0]  # [0] mean save only values, if index not necessary
df_values = pd.concat([df_numeric, df_obj], axis=1)


# essential
import _thread as thread
from queue import *

# other imports
from lxml import html
import requests
import time
import re
import tempfile

class xkcd:
    def __init__(self, bot):
        # Initialize update timer and threshold.
        self.last_update = 0
        self.threshold = 300

        self.bot = bot.bot
        self.description = """*/xkcd* _<id|r[andom]>_ - outputs current, specific id or random xkcd comic"""
        self.queue_in = Queue()
        thread.start_new_thread(self.run, ())

    def run(self):
        while True:
            message = self.queue_in.get() # get() is blocking
            message_text = message.get_text().lower()
            url = ""
            if re.search(r'^/xkcd$', message_text): # current comic
                url = "http://xkcd.com/"
            elif re.search(r'^/xkcd r[andom]{0,5}$', message_text): # current comic
                url = "http://c.xkcd.com/random/comic/"
            elif re.search(r'^/xkcd (\d)', message_text): # message with numeric value
                comic_id = re.search(r'^/xkcd (\d*)$', message_text)
                print(comic_id.groups())
                if comic_id:
                    url = "http://xkcd.com/{}/".format(comic_id.group(1))
                else:
                    continue
            if url:
                comic=self.get_xpath(url,'//*[@id="comic"]/img')[0]
                img_src   = "http://{}".format(comic.get("src").strip('/'))
                img_title = comic.get("title")
                print(img_src,img_title)

                with tempfile.NamedTemporaryFile(suffix='.jpg') as temporaryfile:
                    temporaryfile.write(requests.get(img_src).content)
                    temporaryfile.seek(0)
                    if len(img_title)>200:
                        self.bot.sendPhoto(message.get_chat_id(),temporaryfile,caption="")
                        self.bot.sendMessage(message.get_chat_id(),img_title)
                    else:
                        self.bot.sendPhoto(message.get_chat_id(),temporaryfile,caption=img_title)

    def fetch_lectures(self):
        lectures = []

        for tr in self.get_xpath("http://display.informatik.uni-goettingen.de/events.html",
             '//*[@id="comic"]/img')[0]:
            if len(tr) == 4:
                lectures.append(self.process_lecture(tr))

        return lectures

    def process_lecture(self, tr):
        return [ ' '.join(td.text_content().split()) for td in tr ]

    def get_xpath(self, url, xpath):
        page = requests.get(url)
        tree = html.fromstring(page.content)
        return tree.xpath(xpath)

    def enqueue(self, msg):
        self.queue_in.put(msg)


import logging
import argparse
from src.utils.all_utils import read_yaml, create_directory
from src.utils.models import load_model, get_unique_path_to_save_model
from src.utils.callbacks import get_callbacks
from src.utils.data_management import train_valid_generator
import os

stage = "stage_04"

logs_dir = "logs"
os.makedirs(logs_dir, exist_ok=True)
logging_str = "[%(asctime)s: %(levelname)s: %(module)s: %(message)s]"
logging.basicConfig(filename=os.path.join(logs_dir, "running_logs.log"), level=logging.INFO, format=logging_str, filemode="a")

def train(config_path, params_path):
    config = read_yaml(config_path)
    params = read_yaml(params_path)

    artifacts = config["artifacts"]
    artifacts_dir = artifacts["ARTIFACTS_DIR"]
    base_model_dir = artifacts["BASE_MODEL_DIR"]
    #base_model = os.path.join(artifacts_dir, base_model_dir, artifacts["BASE_MODEL_NAME"])

    updated_base_model = os.path.join(artifacts_dir, base_model_dir, artifacts["UPDATED_BASE_MODEL_NAME"])
    model = load_model(updated_base_model)

    callback_dir_path = os.path.join(artifacts_dir, artifacts["CALLBACKS_DIR"])
    callbacks = get_callbacks(callback_dir_path)

    train_generator, valid_generator = train_valid_generator(
        data_dir = artifacts["DATA_DIR"],
        IMAGE_SIZE = tuple(params["IMAGE_SIZE"][:-1]),
        BATCH_SIZE = params["BATCH_SIZE"],
        do_data_augmentation = params["AUGMENTATION"]
    )

    steps_per_epochs = train_generator.samples // train_generator.batch_size
    validation_steps = valid_generator.samples // valid_generator.batch_size

    model.fit(
        train_generator,
        validation_data = valid_generator,
        epochs = params["EPOCHS"],
        steps_per_epoch = steps_per_epochs,
        validation_steps = validation_steps,
        callbacks = callbacks
    )
    logging.info("training completed")

    trained_model_dir_path = os.path.join(artifacts, artifacts["TRAINED_MODEL_DIR"])
    create_directory([trained_model_dir_path])

    model_file_path = get_unique_path_to_save_model(trained_model_dir_path)
    model.save(model_file_path)
    logging.info(f"trained model is saved at {model_file_path}")

if __name__ == "__main__":
    args = argparse.ArgumentParser()
    args.add_argument("--config", "-c", default="config/config.yaml")
    args.add_argument("--params", "-p", default="params.yaml")
    parsed_args = args.parse_args()

    try:
        logging.info(f"<<<<< Stage {stage} started")
        train(config_path=parsed_args.config, params_path=parsed_args.params)
        logging.info(f"Stage {stage} completed, model trained and saved")
    except Exception as e:
        logging.exception(e)
        raise e


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

#!pip install sidrapy --upgrade

import sidrapy
import pandas as pd

def get_estimated_population(cod_ibge):
    # Get Table
    df = sidrapy.get_table(
        table_code='6579',
        territorial_level='6',
        ibge_territorial_code=cod_ibge,
        period='all',
        header='n',
    )

    # Dict
    dict_col = {
        'D1C': 'id_municipio',
        'D1N': 'municipio_nome',
        'V': 'n_habitantes',
        'D2N': 'ano'
    }

    # Remane Columns
    df.rename(
        dict_col,
        axis=1,
        inplace=True
    )

    # Select Columns
    df = df[[v for k,v in dict_col.items()]]

    # Adjust Columns
    df.sort_values(by=['ano'], inplace=True)
    df['id_municipio'] = pd.to_numeric(df['id_municipio'], errors='coerce')
    df['n_habitantes'] = pd.to_numeric(df['n_habitantes'], errors='coerce')
    df['ano'] = pd.to_numeric(df['ano'], errors='coerce')

    # Results
    return df


import numpy as np
from gazir import linear_layer, relu_layer, network, softmax_nll_layer, dropout_layer
from data_iterator import data_iterator
from learn_rate import learn_rate_schedule
import pickle
input_len = 784
output_len =10
train_x_file = 'train_x.npy'
train_y_file = 'train_y'
expected_train_size= 55000
validation_sample_ratio = 55
train_batch_size = 64
validation_batch_size = 128

def load_data():
    data_x = np.load(train_x_file)
    data_y = np.loadtxt(train_y_file,dtype=int)
    if data_x.shape[0] != expected_train_size:
        raise ValueError("expected {} rows in train data, found {}".format(expected_train_size, data_x.shape[0]))
    if data_y.shape[0] != expected_train_size:
        raise ValueError("number of labels, {}, does not match number of train data {}".format(data_y.shape[0], expected_train_size))

    validation_x = data_x[::validation_sample_ratio]
    validation_y = data_y[::validation_sample_ratio]
    train_x = np.delete(data_x, list(range(0, data_x.shape[0], validation_sample_ratio)), axis=0)
    train_y = np.delete(data_y, list(range(0, data_y.shape[0], validation_sample_ratio)), axis=0)
    # del data_x
    di_train = data_iterator(train_x, train_y, train_batch_size)
    di_valid = data_iterator(validation_x, validation_y, validation_batch_size, False)
    return di_train, di_valid

def create_network():
    return network([linear_layer(input_len,100), relu_layer(),
        linear_layer(100,50), relu_layer(),
        linear_layer(50,10), relu_layer(),
    softmax_nll_layer()])
    #return network([linear_layer(input_len, output_len),  softmax_nll_layer()])

def ex3_main(pretrained_net=None):
    if pretrained_net is not None:
        net = pretrained_net
    else:
        net = create_network()
    net.to_pickle('save_model_before.pkl')
    di_train, di_valid = load_data()
    lr = learn_rate_schedule('constant',momentum=True, eta=0.001, alpha=10, gamma=0.2)
    net.set_train_options(epochs=120, report_interval=250)
    net.train(di_train, lr, di_valid)
    net.to_pickle('save_model_after.pkl')

if __name__ == "__main__":
    fname = 'retrain_100_100.pkl'
    with open(fname,'rb') as f:
        prev_net = pickle.load(f)

    ex3_main(prev_net)


import discord
import random
import asyncio
import os
import datetime
from discord.ext import commands
from keep_alive import keep_alive
bot = commands.Bot(command_prefix='++')
bot.remove_command('help')

@bot.event
async def on_ready():
  print("Entered in Poke World as {0.user}".format(bot))
async def ch_presence():
  await bot.wait_until_ready()

  statuses = ["Gaining Knowledge",f"on {len(bot.guilds)} servers | ++help", "Invite using ++invite","Gotta Know ’Em All!","bit.ly/pokesupport"]
  while not bot.is_closed():
    status = random.choice(statuses)
    await bot.change_presence(activity=discord.Game(name=status))
    await asyncio.sleep(10)
bot.loop.create_task(ch_presence())

#HELP Commands
@commands.command(aliases=['help','h'])
async def halp(ctx):
  embed=discord.Embed(
    title='\nPokepedia Help',
    timestamp=datetime.datetime.utcnow(),
    color=0xff00ff
  )
  embed.add_field(name='Prefix',
  value='++',inline=False)
  embed.add_field(name='Commands',
  value='`bug` , `dark` , `dragon` , `electric` , `fairy` , `fighting` , `fire` , `flying` , `ghost` , `grass` , `ground` , `ice` , `normal` , `poison` , `psychic` , `rock` , `steel` , `water` \n')
  embed.add_field(name='++all',value='`Invokes all 18 commands listed above`\n',inline=False)
  embed.add_field(name='++search / ++s',value='`Search Pokemon by number eg : ++s 1`\n',inline=False)
  embed.add_field(name='++name',value='`Search Pokemon images by name try : ++name pikachu`\n',inline=False)
  embed.add_field(name='For giff lovers',value='`Try ++giff`\n',inline=False)
  embed.add_field(name='Know a random Pokemon Fact',value='`Use ++f or ++fact`',inline=False)
  embed.add_field(name='Play TicTacToe(++ttt)',value='`Play tictactoe by using command `\n`++ttt @mentionPlayer1 @mentionPlayer2`\n',inline=False)
  embed.add_field(name='Play Rock Paper Scissor(++rps)',value='`Try ++rps rock`\n',inline=False)
  embed.add_field(name='Play Magic 8 ball',value='`Try ++8ball <question>`\n',inline=False)
  embed.add_field(name='Useful Links',value='[Support Server](https://discord.gg/pbRtbJX5Sf) | [GitHub](https://github.com/lucifer00911/Pokepedia) | [Invite](https://discord.com/oauth2/authorize?client_id=804665852221325342&permissions=379968&scope=bot) | [Vote !](https://top.gg/bot/804665852221325342/vote)',inline=False)
  embed.set_thumbnail(url="https://i.pinimg.com/originals/ce/cc/91/cecc913aee77c99b18d2043dbbd8bd72.gif")
  await ctx.send(embed=embed)

bot.add_command(halp)
#INVITE commands
@commands.command()
async def invite(ctx):
  embed=discord.Embed(title='Pokepedia',description='\n**Invite Link :** [Invite](https://discord.com/api/oauth2/authorize?client_id=804665852221325342&permissions=379968&scope=bot)\n**Support Server :** [Support](https://discord.gg/pbRtbJX5Sf)',
  color=0x00ffff)
  embed.set_thumbnail(url='https://media.tenor.com/images/27215c1c6dbaca5d396184e5f8f7a73f/tenor.gif')
  await ctx.send(embed=embed)
bot.add_command(invite)

#-------------------------------------------------------------------------------PING COMMAND-------------------------------------------------------------------------------------
@commands.command()
async def ping(ctx):
  embed=discord.Embed(title='Pokepedia',timestamp=datetime.datetime.utcnow(),description=f'Ping : `{round(bot.latency * 1000)}ms`\nPlaying on `{len(bot.guilds)}` servers',color=0xF00091 )
  embed.set_footer(text='\u200b')
  await ctx.send(embed=embed)
bot.add_command(ping)
#------------------------------------------------------------------------------NORMAL TYPE---------------------------------------------------------------------------------------
@commands.command()
async def normal(ctx):
    embed=discord.Embed(
      description='[Normal Type](https://bulbapedia.bulbagarden.net/wiki/Normal_type)\n\n**Weak Against** : Rock, Ghost, Steel \n**Resistant To**: Ghost \n**Vulnerable To**: Fighting',
      color=0x85886F
    )
    embed.set_thumbnail(url="https://i.imgur.com/PdDUKBT.gif")
    await ctx.send(embed=embed)
bot.add_command(normal)
#-----------------------------------------------------------------------------FIGHTING TYPE--------------------------------------------------------------------------------------
@commands.command(aliases=['fight'])
async def fighting(ctx):
    embed=discord.Embed(
      description='[Fighting Type](https://bulbapedia.bulbagarden.net/wiki/Fighting_type)\n\n**Strong Against**: Normal, Rock, Steel, Ice, Dark\n**Weak Against** : Flying, Poison, Psychic, Bug, Ghost, Fairy \n**Resistant To**: Rock, Bug, Dark\n**Vulnerable To**:Flying, Psychic, Fairy',
      color=0xB30000
    )
    embed.set_thumbnail(url="https://i.imgur.com/d7yQufV.gif")
    await ctx.send(embed=embed)
bot.add_command(fighting)
#------------------------------------------------------------------------------FLYING TYPE---------------------------------------------------------------------------------------
@commands.command()
async def flying(ctx):
  embed=discord.Embed(
      description='[Flying Type](https://bulbapedia.bulbagarden.net/wiki/Flying_type)\n\n**Strong Against**: Fighting, Bug, Grass\n**Weak Against** : Rock, Steel, Electric \n**Resistant To**: Fighting, Ground, Bug, Grass\n**Vulnerable To**:Rock, Electric, Ice',
      color=0x30EED5
    )
  embed.set_thumbnail(url="https://i.imgur.com/MWjhVyj.gif")
  await ctx.send(embed=embed)
bot.add_command(flying)
#------------------------------------------------------------------------------POISON TYPE---------------------------------------------------------------------------------------
@commands.command()
async def poison(ctx):
    embed=discord.Embed(
      description='[Poison Type](https://bulbapedia.bulbagarden.net/wiki/Poison_type)\n\n**Strong Against**: Grass, Fairy\n**Weak Against** : Poison, Ground, Rock, Ghost, Steel\n**Resistant To**:Fighting, Poison, Grass, Fairy\n**Vulnerable To**:Ground, Psychic',
      color=0xE0AC25
    )
    embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/805113889418510346/805749181485678632/848488.gif")
    await ctx.send(embed=embed)
bot.add_command(poison)
#-----------------------------------------------------------------------------GROUND TYPE---------------------------------------------------------------------------------------
@commands.command()
async def ground(ctx):
    embed=discord.Embed(
      description='[Ground Type](https://bulbapedia.bulbagarden.net/wiki/Ground_type)\n\n**Strong Against**:Poison, Rock, Steel, Fire, Electric\n**Weak Against** : Flying, Bug, Grass \n**Resistant To**: Poison, Rock, Electric\n**Vulnerable To**:Water, Grass, Ice',
      color=0x724805
    )
    embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/805113889418510346/805116049430675486/1111.gif")
    await ctx.send(embed=embed)
bot.add_command(ground)
#-------------------------------------------------------------------------------ROCK TYPE---------------------------------------------------------------------------------------
@commands.command()
async def rock(ctx):
    embed=discord.Embed(
      description='[Rock Type](https://bulbapedia.bulbagarden.net/wiki/Rock_type)\n\n**Strong Against**: Flying, Bug, Fire, Ice\n**Weak Against** : Fighting, Ground, Steel\n**Resistant To**: Normal, Flying, Poison, Fire\n**Vulnerable To**:Fighting, Ground, Steel, Water, Grass',
      color=0x7B7262
    )
    embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/805113889418510346/805116673707081759/11112.gif")
    await ctx.send(embed=embed)
bot.add_command(rock)
#--------------------------------------------------------------------------------BUG TYPE---------------------------------------------------------------------------------------
@commands.command()
async def bug(ctx):
    embed=discord.Embed(
      description='[Bug Type](https://bulbapedia.bulbagarden.net/wiki/Bug_type)\n\n**Strong Against**: Grass, Psychic, Dark\n**Weak Against** : Fighting, Flying, Poison, Ghost, Steel, Fire, Fairy\n**Resistant To**: Fighting, Ground, Grass\n**Vulnerable To**:Fighting, Ground, Grass',
      color=0x89D306
    )
    embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/805113889418510346/805748308839891004/984889.gif")
    await ctx.send(embed=embed)
bot.add_command(bug)
#-------------------------------------------------------------------------------GHOST TYPE---------------------------------------------------------------------------------------
@commands.command()
async def ghost(ctx):
    embed=discord.Embed(
      description='[Ghost Type](https://bulbapedia.bulbagarden.net/wiki/Ghost_type)\n\n**Strong Against**: Ghost, Psychic\n**Weak Against** : Normal, Dark\n**Resistant To**:Normal, Fighting, Poison, Bug\n**Vulnerable To**:Ghost, Dark',
      color=0x050621
    )
    embed.set_thumbnail(url="https://i.imgur.com/PcFJp4L.gif")
    await ctx.send(embed=embed)
bot.add_command(ghost)
#-------------------------------------------------------------------------------STEEL TYPE---------------------------------------------------------------------------------------
@commands.command()
async def steel(ctx):
    embed=discord.Embed(
      description='[Steel Type](https://bulbapedia.bulbagarden.net/wiki/Steel_type)\n\n**Strong Against**:Rock, Ice, Fairy\n**Weak Against** : Steel, Fire, Water, Electric\n**Resistant To**: Normal, Flying, Poison, Rock, Bug, Steel, Grass, Psychic, Ice, Dragon, Fairy\n**Vulnerable To**:Fighting, Ground, Fire',
      color=0xCCBFA2
    )
    embed.set_thumbnail(url="https://media.giphy.com/media/ZBexIRI4raU0YIruAW/giphy.gif")
    await ctx.send(embed=embed)
bot.add_command(steel)
#--------------------------------------------------------------------------------FIRE TYPE---------------------------------------------------------------------------------------
@commands.command()
async def fire(ctx):
    embed=discord.Embed(
      description='[Fire Type](https://bulbapedia.bulbagarden.net/wiki/Fire_type)\n\n**Strong Against**:Bug, Steel, Grass, Ice\n**Weak Against** : Rock, Fire, Water, Dragon\n**Resistant To**: Bug, Steel, Fire, Grass, Ice\n**Vulnerable To**:Ground, Rock, Water',
      color=0xFBF600
    )
    embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/805113889418510346/805126023417954324/154848.gif")
    await ctx.send(embed=embed)
bot.add_command(fire)
#-------------------------------------------------------------------------------WATER TYPE---------------------------------------------------------------------------------------
@commands.command()
async def water(ctx):
    embed=discord.Embed(
      description='[Water Type](https://bulbapedia.bulbagarden.net/wiki/Water_type)\n\n**Strong Against**: Ground, Rock, Fire\n**Weak Against** : Water, Grass, Dragon\n**Resistant To**:Steel, Fire, Water, Ice\n**Vulnerable To**:Grass, Electric',
      color=0x02AFF3
    )
    embed.set_thumbnail(url="https://i.imgur.com/us6XOaF.gif")
    await ctx.send(embed=embed)
bot.add_command(water)
#-------------------------------------------------------------------------------GRASS TYPE---------------------------------------------------------------------------------------
@commands.command()
async def grass(ctx):
    embed=discord.Embed(
      description='[Grass Type](https://bulbapedia.bulbagarden.net/wiki/Grass_type)\n\n**Strong Against**: Ground, Rock, Water\n**Weak Against** : Flying, Poison, Bug, Steel, Fire, Grass, Dragon\n**Resistant To**: Ground, Water, Grass, Electric\n**Vulnerable To**:Flying, Poison, Bug, Fire, Ice',
      color=0x13DE05
    )
    embed.set_thumbnail(url="https://i.gifer.com/4o45.gif")
    await ctx.send(embed=embed)
bot.add_command(grass)
#----------------------------------------------------------------------------ELECTRIC TYPE---------------------------------------------------------------------------------------
@commands.command()
async def electric(ctx):
    embed=discord.Embed(
      description='[Electric Type](https://bulbapedia.bulbagarden.net/wiki/Electric_type)\n\n**Strong Against**: Flying, Water\n**Weak Against** : Ground, Grass, Electric, Dragon\n**Resistant To**:Flying, Steel, Electric\n**Vulnerable To**:Ground',
      color=0xEBE302
    )
    embed.set_thumbnail(url="https://img1.picmix.com/output/stamp/normal/4/8/0/4/1604084_93e2e.gif")
    await ctx.send(embed=embed)
bot.add_command(electric)
#---------------------------------------------------------------------------PSYCHIC TYPE-----------------------------------------------------------------------------------------
@commands.command()
async def psychic(ctx):
    embed=discord.Embed(
      description='[Psychic Type](https://bulbapedia.bulbagarden.net/wiki/Psychic_type)\n\n**Strong Against**: Fighting, Poison\n**Weak Against** : Steel, Psychic, Dark\n**Resistant To**: Fighting, Psychic\n**Vulnerable To**:Bug, Ghost, Dark',
      color=0xF80AF0
    )
    embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/805113889418510346/805119836689530893/65564.gif")
    await ctx.send(embed=embed)
bot.add_command(psychic)
#-----------------------------------------------------------------------------ICE TYPE------------------------------------------------------------------------------------------
@commands.command()
async def ice(ctx):
    embed=discord.Embed(
      description='[Ice Type](https://bulbapedia.bulbagarden.net/wiki/Ice_type)\n\n**Strong Against**: Flying, Ground, Grass, Dragon\n**Weak Against** : Steel, Fire, Water, Ice\n**Resistant To**:Ice\n**Vulnerable To**:Fighting, Rock, Steel, Fire',
      color=0x3FADE2
    )
    embed.set_thumbnail(url="https://i.imgur.com/PrXXz6e.gif")
    await ctx.send(embed=embed)
bot.add_command(ice)
#-----------------------------------------------------------------------------DRAGON TYPE----------------------------------------------------------------------------------------
@commands.command()
async def dragon(ctx):
    embed=discord.Embed(
      description='[Dragon Type](https://bulbapedia.bulbagarden.net/wiki/Dragon_type)\n\n**Strong Against**:Dragon\n**Weak Against** : Steel, Fairy\n**Resistant To**: Fire, Water, Grass, Electric\n**Vulnerable To**:Ice, Dragon, Fairy',
      color=0xDD350C
    )
    embed.set_thumbnail(url="https://i.imgur.com/NK1VH5b.gif")
    await ctx.send(embed=embed)
bot.add_command(dragon)
#------------------------------------------------------------------------------FAIRY TYPE----------------------------------------------------------------------------------------
@commands.command()
async def fairy(ctx):
    embed=discord.Embed(
      description='[Fairy Type](https://bulbapedia.bulbagarden.net/wiki/Fairy_type)\n\n**Strong Against**: Fighting, Dragon, Dark\n**Weak Against** : Poison, Steel, Fire\n**Resistant To**: Fighting, Bug, Dragon, Dark\n**Vulnerable To**:Poison, Steel',
      color=0xF02A72
    )
    embed.set_thumbnail(url="https://thumbs.gfycat.com/OddBiodegradableAmphiuma-max-1mb.gif")
    await ctx.send(embed=embed)
bot.add_command(fairy)
#-----------------------------------------------------------------------------DARK TYPE------------------------------------------------------------------------------------------
@commands.command()
async def dark(ctx):
    embed=discord.Embed(
      description='[Dark Type](https://bulbapedia.bulbagarden.net/wiki/Dark_type)\n\n**Strong Against**: Ghost, Psychic\n**Weak Against** :Fighting, Dark, Fairy\n**Resistant To**:Ghost, Psychic, Dark\n**Vulnerable To**:Fighting, Bug, Fairy',
      color=0x3C3335
    )
    embed.set_thumbnail(url="https://i.imgur.com/FtfrpoZ.gif")
    await ctx.send(embed=embed)
bot.add_command(dark)
#----------------------------------------------------------------------SEARCH POKEMON BY NUMBER----------------------------------------------------------------------------------
@commands.command(aliases=['s'])
async def search(ctx,i=1):

  try:
    req = 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/' + '{:03d}'.format(i) + '.png'
    embed=discord.Embed(title='{:03d}'.format(i),timestamp=datetime.datetime.utcnow(),color=0xff00ff)
    embed.set_image(url=req)
    embed.set_footer(text='\u200b')
    await ctx.send(embed=embed)
  except Exception as e:

    await ctx.send("Error Occured for Pokemon " + '{:04d}'.format(i))
    print(str(e))

bot.add_command(search)
#-------------------------------------------------------------------SEARCH POKEMON BY NAME---------------------------------------------------------------------------------------
@commands.command(aliases=['name'])
async def sName(ctx,*,name='Missing argument name of the Pokemon'):

  try:
    n=name.lower()
    req='https://img.pokemondb.net/artwork/large/'+n+'.jpg'
    embed=discord.Embed(title=n,timestamp=datetime.datetime.utcnow(),color=0xff00ff)
    embed.set_image(url=req)
    embed.set_footer(text='No Image ? Spell check and try again!')
    await ctx.send(embed=embed)
  except Exception as e:

    await ctx.send("```Missing argument name of the Pokemon```")
    print(str(e))

bot.add_command(sName)
#-------------------------------------------------------------------------CALL ALL AT ONCE---------------------------------------------------------------------------------------
@commands.command(aliases=['IO','all'])
async def call_all(ctx):
  await bug(ctx)
  await asyncio.sleep(3)
  await dark(ctx)
  await asyncio.sleep(3)
  await dragon(ctx)
  await asyncio.sleep(3)
  await electric(ctx)
  await asyncio.sleep(3)
  await fairy(ctx)
  await asyncio.sleep(3)
  await fighting(ctx)
  await asyncio.sleep(3)
  await fire(ctx)
  await asyncio.sleep(3)
  await flying(ctx)
  await asyncio.sleep(3)
  await ghost(ctx)
  await asyncio.sleep(3)
  await grass(ctx)
  await asyncio.sleep(3)
  await ground(ctx)
  await asyncio.sleep(3)
  await ice(ctx)
  await asyncio.sleep(3)
  await normal(ctx)
  await asyncio.sleep(3)
  await poison(ctx)
  await asyncio.sleep(3)
  await psychic(ctx)
  await asyncio.sleep(3)
  await rock(ctx)
  await asyncio.sleep(3)
  await steel(ctx)
  await asyncio.sleep(3)
  await water(ctx)
  await ctx.send("```That's All !```")
bot.add_command(call_all)

#-------------------------------------------------------------------------------------GIFF COMMAND------------------------------------------------------------------------------
@commands.command()
async def giff(ctx):
  embed=discord.Embed(
    title='Gif Commands',
    description='Try these commands on your server for some cool gifs eg : ++g my',
    color=0xff00ff
  )
  embed.add_field(name='Giffs [use ++g then name of gifs listed below]',value='1.Hypnosis Pika(++g hp)\n2.Mystic Logo(++g my)\n3.Valor Logo(++g va)\n4.Instinct Logo(++g in)\n5.Dancing Dragonite(++g dance)',inline=False)
  embed.set_thumbnail(url='https://i.imgur.com/OqMXWbD.jpg')
  embed.set_footer(text='Join our support server for adding custom gifs')
  await ctx.author.send(embed=embed)
  await ctx.send("``Check DM``")
bot.add_command(giff)
#---------------------------------------------------------------------------------GIFFS COMMAND---------------------------------------------------------------------------------
@commands.command(aliases=['g'])
async def giffs(ctx,*,name='empty'):
    if name=='empty':
        await ctx.send('```Give following parameters : hp , my , va , in , dance | Try ++g hp```')
    if name=='hp':
        await ctx.send("https://emojis.slackmojis.com/emojis/images/1450458394/182/pikachu.gif?1450458394")
        await ctx.message.delete()
    if name=='my':
        await ctx.send("https://emojis.slackmojis.com/emojis/images/1469201975/673/mystic.gif?1469201975")
        await ctx.message.delete()
    if name=='dance':
        await ctx.send("https://emojis.slackmojis.com/emojis/images/1469223471/679/charmander_dancing.gif?1469223471")
        await ctx.message.delete()
    if name=='va':
        await ctx.send("https://emojis.slackmojis.com/emojis/images/1469202036/674/valor.gif?1469202036")
        await ctx.message.delete()
    if name=='in':
        await ctx.send("https://emojis.slackmojis.com/emojis/images/1469201940/672/instinct.gif?1469201940")
        await ctx.message.delete()
bot.add_command(giffs)

#---------------------------------------------------------------------------RANDOM FACT------------------------------------------------------------------------------------------
@commands.command(aliases=['f','fact'])
async def pokeFacts(ctx):
    responses = ['Bulbasaur is the first Pokemon in the Pokedex.',
                'Rhydon is the first Pokemon ever to be created.',
                'Pikachu is a Japanese onomatopoeia for squeaking and shimmering.',
                'There are over 800 Pokemon species today and the number continues to grow.',
                'Slowbro is the only Pokemon that can devolve.',
                'Pikachu is not the original mascot for the franchise. The original mascot prior to Pikachu was Clefairy.',
                'According to a legend, Ditto was the result of an experiment in an attempt to create a copy of Mew.',
                'You could originally battle Professor Oak in Pokemon Red/Blue.',
                'Many of Nintendo’s game consoles are featured in certain versions of the mainline Pokemon games.',
                'Ninetails is based on the Japanese mythological fox that breathes fire and shapeshifts.',
                'The Kanto region is based on a real region in Japan with the same name.',
                'Victini is the only Pokemon with a dex number of 000.',
                'Wailord is lighter than the average full-grown adult.',
                'Cosmoem is based on a protostar which explains why it is so heavy for its small size.',
                'The original 151 Pokemon only made 37 types of noises.',
                'Bulbasaur is the only unevolved dual-type starter Pokemon before Gen VIII.',
                'The Sword of Justice legendary trio is based on the three musketeers.',
                'Rotom’s forms are designed by several artists. ',
                'Blastoise has the highest base Special Defense among all fully evolved starters. ',
                'Ekans is snake spelled backward.',
                'https://i.imgur.com/QQbZoU7.jpg',
                'https://i.imgur.com/I8OEfwf.jpg',
                'https://i.imgur.com/ApGoshR.jpg',
                'https://i.imgur.com/PbbC4dI.jpg']
    await ctx.send(random.choice(responses))
bot.add_command(pokeFacts)

#-------------------------------------------------------------------------------TIC TAC TOE--------------------------------------------------------------------------------------
player1 = ""
player2 = ""
turn = ""
gameOver = True

board = []

winningConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
]

@commands.command(aliases=['ttt'])
async def tictactoe(ctx, p1: discord.Member, p2: discord.Member):
    global count
    global player1
    global player2
    global turn
    global gameOver

    if gameOver:

      global board
      board = [":white_large_square:", ":white_large_square:", ":white_large_square:",
                 ":white_large_square:", ":white_large_square:", ":white_large_square:",
                 ":white_large_square:", ":white_large_square:", ":white_large_square:"]
      turn = ""
      gameOver = False
      count = 0

      player1 = p1
      player2 = p2

        # print the board
      line = ""
      for x in range(len(board)):
        if x == 2 or x == 5 or x == 8:
          line += " " + board[x]
          await ctx.send(line)
          line = ""
        else:

          line += " " + board[x]

        # determine who goes first
      num = random.randint(1, 2)
      if num == 1:
        turn = player1
        await ctx.send("It is <@" + str(player1.id) + ">'s turn.\n```Use ++place to mark | To quit type ++quit```")
      elif num == 2:
        turn = player2
        await ctx.send("It is <@" + str(player2.id) + ">'s turn.\n```Use ++place to mark | To quit type ++quit```")
    else:
      await ctx.send("```A game is already in progress! Quit this one by typing ++quit```")
bot.add_command(tictactoe)
@commands.command()
async def place(ctx, pos: int):
  global turn
  global player1
  global player2
  global board
  global count
  global gameOver

  if not gameOver:

    mark = ""
    if turn == ctx.author:

      if turn == player1:

        mark = ":regional_indicator_x:"
      elif turn == player2:
        mark = ":o2:"
      if 0 < pos < 10 and board[pos - 1] == ":white_large_square:" :
        board[pos - 1] = mark
        count += 1

                # print the board
        line = ""
        for x in range(len(board)):
          if x == 2 or x == 5 or x == 8:

            line += " " + board[x]
            await ctx.send(line)
            line = ""
          else:
            line += " " + board[x]

        checkWinner(winningConditions, mark)
        print(count)

        if gameOver == True:
          await ctx.send(mark + " wins!")
        elif count >= 9:
          gameOver = True
          await ctx.send("```It's a tie!```")

                # switch turns
        if turn == player1:
            turn = player2
        elif turn == player2:
            turn = player1
      else:
                await ctx.send("```Be sure to choose an integer between 1 and 9 (inclusive) and an unmarked tile.```")
    else:
      await ctx.send("`It is not your turn.`")
  else:
    await ctx.send("```Please start a new game using the ,tictactoe command.```")

def checkWinner(winningConditions, mark):

  global gameOver
  for condition in winningConditions:
    if board[condition[0]] == mark and board[condition[1]] == mark and board[condition[2]] == mark:
      gameOver = True
bot.add_command(place)
@tictactoe.error
async def tictactoe_error(ctx, error):
  print(error)
  if isinstance(error, commands.MissingRequiredArgument):
    await ctx.send("```Please mention 2 players for this command.```")
  elif isinstance(error, commands.BadArgument):
    await ctx.send("```Please make sure to mention/ping players (ie. <@Player>).```")

@place.error
async def place_error(ctx, error):
  if isinstance(error, commands.MissingRequiredArgument):
    await ctx.send("```Please enter a position you would like to mark. | Eg : ++place 5```")
  elif isinstance(error, commands.BadArgument):
    await ctx.send("```Please make sure to enter an integer between 1 to 9.```")

@commands.command()
async def quit(ctx):
  global gameOver
  gameOver = True
  await ctx.send("```Game Over . Thanks for playing ! ```")
bot.add_command(quit)

#--------------------------------------------------------------------------------8 BALL------------------------------------------------------------------------------------------

@commands.command(aliases=['8ball'])
async def _8ball(ctx,question='empty'):
  if question == 'empty':
    await ctx.send("```Ask a question please | ++8ball <question>```")
    return

  coloor=[0xff00ff,0xFC6700,0xF9FC00,0x74FC00,0x00FC16,
            0x08E1B1,0x08BEE1,0x086CE1,0x0811E1,0xB609CD ,
            0xCD09A0,0xCD097D ,0xCD0936,0xF70000]
  responses = ['As I see it, yes.',
                 'Ask again later.',
                 'Better not tell you now.',
                 'Cannot predict now.',
                 'Concentrate and ask again.',
                 'Don’t count on it.',
                 'It is certain.',
                 'It is decidedly so.',
                 'Most likely.',
                 'My reply is no.',
                 'My sources say no.',
                 'Outlook not so good.',
                 'Outlook good.',
                 'Reply hazy, try again.',
                 'Signs point to yes.',
                 'Very doubtful.',
                 'Without a doubt.',
                 'Yes.',
                 'Yes – definitely.',
                 'You may rely on it.',
                 'Are you kidding',
                 'Hell No']
  embed=discord.Embed(
  timestamp=datetime.datetime.utcnow(),
  description=random.choice(responses),
  color=random.choice(coloor)
    )
  embed.set_footer(text='\u200b')
  await ctx.send(embed=embed)
bot.add_command(_8ball)

#--------------------------------------------------------------------------ROCK PAPER SCISSOR-----------------------------------------------------------------------------------
@commands.command(aliases=['rps'])
async def RockPaperScissor(ctx,userChoice='Nothing'):
    userWeapon=userChoice.lower()
    if userWeapon!='rock' and userWeapon!='paper' and userWeapon!='scissor' and userWeapon!='nothing':
      await ctx.send("Either choose `rock` or `paper` or `scissor`")
      return
    weapons=['rock','paper','scissor']
    randomWeapon=random.choice(weapons)
    if userWeapon=='nothing':
      await ctx.send('Required argument `rock`,`paper`,or,`scissor` is missing.\nFor example try:`++rps rock`')
    elif userWeapon=='rock' and randomWeapon=='paper':
      embed=discord.Embed(
        timestamp=datetime.datetime.utcnow(),
        description='paper beats rock . I win !',
        color=0xff00ff
      )
      embed.set_footer(text='\u200b')
      await ctx.send(embed=embed)
    elif userWeapon=='paper' and randomWeapon=='scissor':
      embed=discord.Embed(
        timestamp=datetime.datetime.utcnow(),
        description='scissor beats paper . I win !',
        color=0xff00ff
      )
      embed.set_footer(text='\u200b')
      await ctx.send(embed=embed)
    elif userWeapon=='scissor' and randomWeapon=='rock':
      embed=discord.Embed(
        timestamp=datetime.datetime.utcnow(),
        description='rock beats scissor . I win !',
        color=0xff00ff
      )
      embed.set_footer(text='\u200b')
      await ctx.send(embed=embed)
    elif userWeapon==randomWeapon:
      embed=discord.Embed(
        timestamp=datetime.datetime.utcnow(),
        description='Its a tie since I choose '+userChoice+' too :)',
        color=0xff00ff
      )
      embed.set_footer(text='\u200b')
      await ctx.send(embed=embed)
    else:
      embed=discord.Embed(
        timestamp=datetime.datetime.utcnow(),
        description='You win !',
        color=0xff00ff,
      )
      embed.set_footer(text='\u200b')
      await ctx.send(embed=embed)
bot.add_command(RockPaperScissor)
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
keep_alive()
bot.run(os.getenv('TOKEN'))


import requests, json
import matplotlib.pyplot as plt

#added token = 'your token'

doc = requests.get('https://api.github.com/repos/opencode18/OpenCode-Collaborative/stats/contributors?access_token=' + token)
docDict = json.loads(doc.content)

name = []
commits = []
deletions = []
additions = []

for i in range(100):
    name.append(docDict[i]['author']['login'])
    commits.append(docDict[i]['total'])
    add = 0
    deletion = 0
    for j in range(5):
        x = docDict[i]['weeks'][j]['a']
        y = docDict[i]['weeks'][j]['d']
        add += x
        deletion += y
    deletions.append(deletion)
    additions.append(add)

name = name[80:100]
commits = commits[80:100]

plt.style.use('ggplot')

fig, ax = plt.subplots()

ax.set_xlabel('Participants')
plt.xticks(rotation=30)
ax.set_ylabel('No. Of Commits')
ax.set_title('No. of Commits by Participants in OpenCode-Collaborative')

rects = ax.bar(name, commits, width=0.35)

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1*height,
                '%d' % int(height),
                ha='center', va='bottom')
autolabel(rects)
fig.tight_layout()
plt.show()


import fire
import json
from rs_utils.abstract import RSObject

from rs_utils import logger
import traceback

class Validator(RSObject):

	ARGS = {}
	ARG_ERRORS = {}
	_ERROR = False

	"""
	The validator can be used by using it's public methods, or it can all
	be used in the constructor. If ARG_CONFIG is passed to the constructor,
	self.validate() will use that ARG_CONFGI. If EXCEPTION_FUNCTION is passed
	to the constructor, EXCEPTION_FUNCTION will be called if self.validate()
	sets a non-False self.ERROR(). If EXCEPTION_FUNCTION does not raise an
	exception when called, self.raise_generic_exception() will be called using
	the message produced from EXCEPTION_FUNCTION.
	"""
	def __init__(self,
		ARG_CONFIG=None,
		EXCEPTION_FUNCTION=None,
		json=False,
		**kwargs
	):
		# Make sure to set these values on __init__ otherwise the module
		# function VALIDATE will use old values if the object has already
		# been initialized in the same script.
		self._ERROR = False
		self.ARG_ERRORS = {}
		if ARG_CONFIG is not None:
			self.validate(ARG_CONFIG=ARG_CONFIG, **kwargs)
			if self.ERROR():
				ERROR_DATA = str(self.ERROR(return_json=json))
				if EXCEPTION_FUNCTION is None:
					EXCEPTION_FUNCTION = self.raise_generic_exception
				"""
				EXCEPTION_FUNCTION can either raise an exception or return an
				exception message. If it doesn't raise an exception, use
				self.raise_generic_exception() with the return of the custom
				EXCEPTION_FUNCTION as the ERROR_DATA.
				"""
				ERROR_DATA = EXCEPTION_FUNCTION(ERROR_DATA)
				self.raise_generic_exception(ERROR_DATA)

	def add_error(self, param_name, error_msg):
		self.ARG_ERRORS[param_name] = error_msg

	def ERROR(self, return_json=False):
		if self.ARG_ERRORS == {}:
			return False
		self._ERROR = True
		if return_json == True:
			return json.dumps(
				self.ARG_ERRORS,
				indent=4
			)
		return " ".join([
			self.ARG_ERRORS[param_name]
				for param_name, err_msg
				in self.ARG_ERRORS.items()
			])

	def raise_generic_exception(self, ERROR_DATA="No error message availible."):
		raise Exception(
			"Invalid arguments: %s" % str(ERROR_DATA)
		)

	def _validate_condition(self, param_name, condition, **kwargs):
		try:
			"""
			The param value might be passed a function, but
			it doesn't necessarily mean it's required. If we
			declare it as None now, condition functions will
			have to check for NoneType. Instead, we can just
			call condition() without any parameters if the
			param_name is not in kwargs, that way condition
			functions can just check:

				if param is None:
			"""
			param_value = None
			if param_name in kwargs:
				param_value = kwargs[param_name]

				response = condition(param_value)
			else:
				response = condition()
			if type(response).__name__ == "Response":
				if response.ERROR == True:
					raise Exception(
						response.STDERR
					)
		except Exception as ex:
			self.add_error(
				param_name,
				"Invalid param '%s': %s" % (
					param_name,
					str(ex)
				)
			)

	def _validate_active_group(self,
			active_groups,
			param_name,
			condition,
			**kwargs
		):
		if "group" not in condition:
			raise Exception("Recieved group condition, but no " +
				"'group' name provided. Must pass 'group' to " +
				"condition dict.")
		if "condition" not in condition:
			raise Exception("Recieved group condition, but no " +
				"'condition' function provided. Must pass " +
				"'condition' to condition dict.")
		if active_groups is None:
			raise Exception("active_groups is None for some reason.")
		group = condition["group"]
		if group in active_groups:
			if active_groups[group] == True:
				if param_name not in kwargs:
					raise Exception(("""Active group is '%s', """ +
					"""but param '%s' in that group was not passed """ +
					"""as a parameter.""") % (
						group,
						param_name
					))
				else:
					self._validate_condition(
						param_name,
						condition["condition"],
						**kwargs
					)

	"""
	First, go through ARG_CONFIG and find the distict groups.

	Next, Go through the ARG_CONFIG and **kwargs and see which **kwargs are not
	None. If they're not none, find the group that param_name is part of and
	mark the gropu as active.
	"""
	def _parse_active_groups(self, ARG_CONFIG, **kwargs):
		"""
		Find distinct groups.
		"""
		grouped_params = []
		grouped_params = list(
			filter(
				lambda key:
				type(ARG_CONFIG[key]).__name__ == "dict",
				[
					key for key, val in ARG_CONFIG.items()
				]
			)
		)
		"""
		Find groups that are active, indicated by params being passed
		in kwargs.
		"""
		active_groups = {}
		for grouped_param in grouped_params:
			if grouped_param in kwargs:
				active_groups[ARG_CONFIG[grouped_param]["group"]] = True
		return active_groups

	"""
	kwargs for validation params:
		True 	 => required.
		function => raise exception means invalid, capture str(ex).
	"""
	def validate(self, ARG_CONFIG={}, **kwargs):
		"""
		Track the active group condition if it exists.
		"""
		active_groups = self._parse_active_groups(
			ARG_CONFIG=ARG_CONFIG,
			**kwargs,
		)
		for param_name, condition in ARG_CONFIG.items():
			"""
			Check if condition passed is a method of function.
			"""
			if (
				(type(condition).__name__ == "method") or
				(type(condition).__name__ == "function")
			):
				self._validate_condition(
					param_name,
					condition,
					**kwargs,
				)
			"""
			Check if condition is part of a group. If any members of
			the group are present, they're all required per their
			conditions.
			"""
			if type(condition).__name__ == "dict":
				self._validate_active_group(
					active_groups,
					param_name,
					condition,
					**kwargs
				)
			"""
			Check if condition passed is 'True', this means it's
			required.
			"""
			if condition == True:
				if param_name not in kwargs:
					self.add_error(
						param_name,
						"'%s' is required." % param_name
					)

	#-----------------------------------------------------------------------
	# UNIT TESTS (PUBLIC)
	#-----------------------------------------------------------------------

	def test(self,
			test_groups=None,
			test_file_path="../tests/validator.py",
		):
		self._test(
			test_file_path=test_file_path,
			test_groups=test_groups,
		)

def VALIDATE(
		ARG_CONFIG=None,
		EXCEPTION_FUNCTION=None,
		json=False,
		**kwargs
	):
	validator = Validator(
		ARG_CONFIG=ARG_CONFIG,
		EXCEPTION_FUNCTION=EXCEPTION_FUNCTION,
		json=json,
		**kwargs
	)

def main():
	fire.Fire(Validator())

if __name__ == '__main__':
	main()


#!/usr/bin/env python3

import time

import numpy as np

import gym
import gym_duckietown
from gym_duckietown.envs import SimpleSimEnv

st = time.time()
env = SimpleSimEnv(max_steps = 20000)
env.seed(0)
env.reset()
load_time = 1000 * (time.time() - st)

num_frames = 0
st = time.time()

while True:
    dt = time.time() - st

    if dt > 5:
        break

    # Slow speed to minimize resets
    action = np.array([0.05, 0.05])
    obs, reward, done, info = env.step(action)

    if done:
        env.reset()

    num_frames += 1

fps = num_frames / dt
frame_time = 1000 * dt / num_frames

print()
print('load time: %d ms' % int(load_time))
print('frame time: %.1f ms' % frame_time)
print('frame rate: %.1f fps' % fps)

env.close()


import os
from nipype.interfaces.base import BaseInterface, \
    BaseInterfaceInputSpec, traits, File, TraitedSpec
from nipype.utils.filemanip import split_filename

import numpy as np
import nibabel as nb
from variables import workingdir, lhvertices, rhvertices
import os

class MaskInputSpec(BaseInterfaceInputSpec):
    sxfmout = File(exists=True, desc='original surface', mandatory=True)
    hemi = traits.String(exists=True, desc='hemisphere', mandatory=True)

class MaskOutputSpec(TraitedSpec):
    mask_volume = File(exists=True, desc="mask volume")

class Mask(BaseInterface):
    input_spec = MaskInputSpec
    output_spec = MaskOutputSpec

    def _run_interface(self, runtime):
        sxfmout = self.inputs.sxfmout
        hemi = self.inputs.hemi
        _, base, _ = split_filename(sxfmout)

        data = nb.load(sxfmout).get_data()
        origdata = data.shape
        affine = nb.spatialimages.SpatialImage.get_affine(nb.load(sxfmout))
        data.resize(data.shape[0]*data.shape[2],1,1,data.shape[3])
        mask = np.zeros_like(data)
        if hemi == 'lh': chosenvertices = lhvertices
        if hemi == 'rh': chosenvertices = rhvertices
        for i,vertex in enumerate(chosenvertices):
            mask[vertex][:] = 1
        mask.resize(origdata)
        maskImg = nb.Nifti1Image(mask, affine)

        nb.save(maskImg, os.path.abspath(base + '_mask.nii'))
        return runtime

    def _list_outputs(self):
        outputs = self._outputs().get()
        fname = self.inputs.sxfmout
        _, base, _ = split_filename(fname)
        outputs["mask_volume"] = os.path.abspath(base+'_mask.nii')
        return outputs


import os

import speech_utilities as spf

# get sentence- and word-level sentence_features of the speech data
# requires 2 directories:
#   - directory with intensity contours, one file per sample
#   - directory with pitch contours, one file per sample

def get_speech_features(speech_data, annotations, dataset):

    sentence_features = {}
    current = os.getcwd()

    for d in speech_data:
        sentence_features[d[0]] = spf.SentenceFeatures(d, dataset)

    for line in annotations:
        name = line[0]
        del line[0]

        for word in line:
            if word == '[length]':
                sentence_features[name].words.append('#')
            elif word == '':
                pass
            else:
                sentence_features[name].words.append(word)

    # get pitch and intensity contours, calculate syllables per sec
    for (name, u) in sentence_features.items():
        os.chdir('pitchContours/' + dataset)
        u.parsePitch(name)

        os.chdir('../../intensityContours/' + dataset)
        u.parseIntensity(name)
        os.chdir(current)

        u.calc_syllables()

    print('normalizing based on speakers mean')

    # normalization of contours
    if dataset == 'set2':
        u.read_means()
    else:
        u.calcMeans()  # find means for each speaker

    for name, u in sentence_features.items():
        u.normalize()

    u.output_means()

    print('outputting features')

    os.chdir(current) # making sure working directory is as expected
    spf.write_sentence(sentence_features, dataset)

    #spf.to_binary(sentence_features.values(), dataset)

    data = []
    predict = []

    if dataset == 'daria':
        to_predict = 2
    elif dataset == 'set1':
        to_predict = 99
    else:
        to_predict = 0

    for name, u in sentence_features.items():
        utterance = u.features()
        if u.sarcasm != to_predict:
            utterance.append(name)
            data.append(utterance)
        else:
            predict.append(utterance)

    return list([data, predict])

def get_daria_features(speech_data, annotations):
    sentence_features = {}
    current = os.getcwd()

    for d in speech_data:
        sentence_features[d[0]] = spf.SentenceFeatures(d, 'daria')

    for line in annotations:
        name = line[0]
        del line[0]

        for word in line:
            if word == '[length]':
                sentence_features[name].words.append('#')
            elif word == '':
                pass
            else:
                sentence_features[name].words.append(word)

    # get pitch and intensity contours, calculate syllables per sec
    for (name, u) in sentence_features.items():
        os.chdir('pitchContours/Daria')
        u.parsePitch(name)

        os.chdir('../../intensityContours/daria')
        u.parseIntensity(name)
        os.chdir(current)

        u.calc_syllables()

    print('normalizing based on speakers mean')

    # normalization of contours

    u.calcMeans()  # find means for each speaker

    for name, u in sentence_features.items():
        u.normalize()

    print('splitting contours')

    for (name, u) in sentence_features.items():
        if (u.words == []):
            print(name)
        pitches = u.pitch
        intensities = u.intensity
        # parse pitch and intensity contours
        u.splitContours(pitches, 'p')
        u.splitContours(intensities, 'i')

    word_features = {}
    print('fitting to legendre polynomials')

    # get legendre polynomials
    for (name, u) in sentence_features.items():

        utterance = spf.WordFeatures(list([u.name, u.sarcasm, u.words]))

        errorp = errori = 0

        errorp = utterance.legendre(u.pitch, utterance.pcoefficients, 'p')
        errori = utterance.legendre(u.intensity, utterance.icoefficients, 'i')

        if errorp == -1 or errori == -1:
            print(name + ' is whack yo')

        utterance.updateTotals()

        word_features[name] = utterance

    word_features[name].ngrams(word_features)

    print('outputting features')

    os.chdir(current)  # making sure working directory is as expected

    # spf.to_binary(sentence_features.values(), dataset)

    data = []
    predict = []

    to_predict = 2

    for name, u in sentence_features.items():
        utterance = u.features()
        if u.sarcasm != to_predict:
            utterance.append(name)
            data.append(utterance)
        else:
            predict.append(utterance)

    return list([data, predict])


import sqlite3

# Connect to database
conn = sqlite3.connect("customers.db")

# Create a cursor
c = conn.cursor()

# Ordering results
# By default the database order the results by the rowid in ascending order
c.execute("SELECT rowid, * FROM customers ORDER BY last_name")
# The keyword to ordering are:
# ASC == ascending
# DESC == descending
# and you can combine and mix them like: ex. ORDER BY last_name DESC

# Commit changes to db
conn.commit()

# Only to verify that changes have been done we will print it to screen
c.execute("SELECT * FROM customers")

print(c.fetchall())

# Close connection to db
conn.close()


#!/usr/bin/env python3

import configargparse
import mflog
import mfutil
import os
import paho.mqtt.client as mqtt
import xattrfile
import signal
import time

def on_connect(client, userdata, flags, rc):
    client.is_connecting = True
    client.get_logger().debug("the client is connecting to the broker.")
    client.subscribe(client.args.subscription_topic)

def on_disconnect(client, userdata, rc):
    client.get_logger().debug("the client disconnects from the broker.")
    client.stop_flag = True
    client.is_connecting = False

def on_message(client, userdata, message):
    client.get_logger().debug("message received: %s" ,str(message.payload.decode("utf-8")))
    client.get_logger().debug("message topic: %s",message.topic)
    client.get_logger().debug("message qos: %s",message.qos)
    client.get_logger().debug("message retain flag: %s",message.retain)
    client.get_logger().debug("message info: %s",message.info)
    client.get_logger().debug("userdata: %s",userdata)
    basename = mfutil.get_unique_hexa_identifier()
    client.get_logger().debug("basename: %s" % (basename))

    filepath = os.path.join(client.args.dest_dir, basename)
    tmp_filepath = '.'.join((filepath, client.args.tmp_suffix))
    client.get_logger().debug("Created tmp file name : %s" % (tmp_filepath))
    with open(tmp_filepath, "w") as fichier:
        fichier.write(str(message.payload.decode("utf-8")))
    xaf = xattrfile.XattrFile(tmp_filepath)
    xaf.tags['mqtt_listener_subscription_topic'] = client.args.subscription_topic
    xaf.tags['mqtt_listener_received_topic'] = message.topic
    xaf.tags['mqtt_listener_broker_hostname'] = client.args.broker_hostname
    xaf.tags['mqtt_listener_broker_port'] = str(client.args.broker_port)
    if userdata is not None:
        xaf.tags['mqtt_listener_user_data'] = userdata
    xaf.rename(filepath)
    client.get_logger().debug("Created file name : %s" % (filepath))

class ExtraDaemonMqttListener(mqtt.Client):

    plugin_name = "mqtt_listener"
    daemon_name = "extra_daemon_mqtt_listener"
    stop_flag = False
    is_connecting = False
    __logger = None

    def __init__(self):
        super(ExtraDaemonMqttListener, self).__init__()
        signal.signal(signal.SIGTERM, self.__sigterm_handler)

    def __sigterm_handler(self, *args):
        self.get_logger().debug("SIGTERM signal handled => schedulling shutdown")
        self.stop_flag = True

    def get_logger(self):
        if not self.__logger:
            logger_name = "mfdata.%s.%s" % (self.plugin_name, self.daemon_name)
            self.__logger = mflog.getLogger(logger_name)
        return self.__logger

    def get_argument_parser(self):
        """Make and return an ArgumentParser object.
        If you want to add some extra options, you have to override
        the add_extra_arguments() method.
        Returns:
            an ArgumentParser object with all options added.
        """
        parser = configargparse.ArgumentParser()

        parser.add_argument('--broker-hostname', action='store',
                            default='127.0.0.1',
                            help='the hostname or IP address of the remote broker. Defaults to localhost')
        parser.add_argument('--broker-port', action='store', default=1883, type=int,
                            help='the network port of the server host to connect to. Defaults to 1883.')
        parser.add_argument('--keep-alive', action='store', default=60, type=int,
                            help='maximum period in seconds allowed between communications with the broker')
        parser.add_argument('--user-data', action='store',
                            default=None,
                            help='user defined data of any type. Defaults None')
        parser.add_argument('--dest-dir', action='store',
                            help='destination directory of the file made from the MQTT message')
        parser.add_argument('--subscription-topic', action='store', default='#',
                            help='string specifying the subscription topic to subscribe to. Default everybody')
        parser.add_argument('--tmp-suffix', action='store', default='t',
                            help='temporary file suffix. Default t')
        return parser

    def run(self):
        self.get_logger().info("Start daemon %s" % self.daemon_name)
        parser = self.get_argument_parser()
        self.args = parser.parse_args()
        self.get_logger().debug("broker_hostname: %s" % self.args.broker_hostname)
        self.get_logger().debug("broker_port: %s" % self.args.broker_port)
        self.get_logger().debug("keep_alive: %s" % self.args.keep_alive)
        self.get_logger().debug("dest_dir: %s" % self.args.dest_dir)
        self.get_logger().debug("subscription-topic: %s" % self.args.subscription_topic)
        self.get_logger().debug("user_data: %s" % self.args.user_data)
        self.on_message = on_message
        self.on_connect = on_connect
        self.on_disconnect = on_disconnect
        try:
            self.connect(self.args.broker_hostname, port=self.args.broker_port)
            self.loop_start()
        except Exception:
            self.get_logger().warning("Can not connect to the broker %s on port %d" % (self.args.broker_hostname,
                                                                          self.args.broker_port))
        else:
            while not self.is_connecting:
                self.get_logger().debug("Waiting for connection ...")
                time.sleep(1)
            try:
                while not self.stop_flag:
                    self.loop_forever()
                self.get_logger().info("Stop daemon %s" % self.daemon_name)
                self.disconnect()
            except Exception:
                self.warning("Daemon stopped on mqtt error")

if __name__ == "__main__":
    x = ExtraDaemonMqttListener()
    x.run()


import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

# init list with pin numbers

pinList = [17, 27]

# loop through pins and set mode and state to 'low'

#GPIO.cleanup()

GPIO.setup(17, GPIO.OUT)
GPIO.output(17, GPIO.HIGH)
GPIO.setup(27, GPIO.OUT)
GPIO.output(27, GPIO.HIGH)

GPIO.output(17, GPIO.LOW)
GPIO.output(27, GPIO.LOW)