# work with python 3.6
import discord, time, nltk, numpy, requests
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
from discord.ext import commands
from discord.ext.commands import bot
import random

TOKEN = 65468126548721

client = discord.Client()

bot = commands.Bot(command_prefix='-')

@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return
    if message.content.startswith('-hi'):
        msg = 'Hello {0.author.mention}'.format(message)
        await message.channel.send(msg)
    elif message.content.startswith('-8'):
        await message.channel.send(random.choice(['That is a resounding no:8ball:',
                                                  'Negative:8ball:',
                                                  'Abort!:8ball:',
                                                  'It is not looking likely:8ball:',
                                                  'Too hard to tell:8ball:',
                                                  'It is quite possible:8ball:',
                                                  'Definitely:8ball:',
                                                  'Hell yea boi!:8ball:',
                                                  'Yes:8ball:']))
        """Selects a random operator to ban on the attacking side"""
    elif message.content.startswith('-banA'):
        await message.channel.send(random.choice(['Ash:octagonal_sign:',
                                                  'Thermite:octagonal_sign:',
                                                  'Thatcher:octagonal_sign:',
                                                  'Blackbeard:octagonal_sign:',
                                                  'Capitao:octagonal_sign:',
                                                  'Maverick:octagonal_sign:',
                                                  'Hibana:octagonal_sign:',
                                                  'Montagne:octagonal_sign:',
                                                  'Twitch:octagonal_sign:',
                                                  'Lion:octagonal_sign:',
                                                  'Dokkaebi:octagonal_sign:',
                                                  'Sledge:octagonal_sign:',
                                                  'Buck:octagonal_sign:',
                                                  'IQ:octagonal_sign:',
                                                  'Nomad:octagonal_sign:',
                                                  'Gridlock:octagonal_sign:',
                                                  'Jackal:octagonal_sign:',
                                                  'Zofia:octagonal_sign:',
                                                  'Fuze:octagonal_sign:',
                                                  'Finka:octagonal_sign:',
                                                  'Glaz:octagonal_sign:',
                                                  'Blitz:octagonal_sign:',
                                                  'Ying:octagonal_sign:',
                                                  'Nøkk:octagonal_sign:',
                                                  'Amaru:octagonal_sign:']))
        """Selects a random operator to ban on defending side"""
    elif message.content.startswith('-banD'):
        await message.channel.send(random.choice(['Rook:octagonal_sign:',
                                                  'Doc:octagonal_sign:',
                                                  'Smoke:octagonal_sign:',
                                                  'Jager:octagonal_sign:',
                                                  'Mute:octagonal_sign:',
                                                  'Mozzie:octagonal_sign:',
                                                  'Mira:octagonal_sign:',
                                                  'Kaid:octagonal_sign:',
                                                  'Tachanka:octagonal_sign:',
                                                  'Kapkan:octagonal_sign:',
                                                  'Goyo:octagonal_sign:',
                                                  'Ela:octagonal_sign:',
                                                  'Warden:octagonal_sign:',
                                                  'Pulse:octagonal_sign:',
                                                  'Castle:octagonal_sign:',
                                                  'Caveira:octagonal_sign:',
                                                  'Valkyrie:octagonal_sign:',
                                                  'Clash:octagonal_sign:',
                                                  'Maestro:octagonal_sign:',
                                                  'Vigil:octagonal_sign:',
                                                  'Alibi:octagonal_sign:',
                                                  'Echo:octagonal_sign:',
                                                  'Lesion:octagonal_sign:',
                                                  'Frost:octagonal_sign:',
                                                  'Bandit:octagonal_sign:']))
    elif message.content.startswith('-stats'):
        print()
    print(message)
    print(message.author)
    await bot.process_commands(message)

@bot.command()
async def siege(content='repeating...'):
    def convUser(username):
        """Takes raw input from runSearch"""
        names = nltk.word_tokenize(username)
        global fnamelist
        fnamelist = names
        return names

    def getRank(x):
        tokpanel = str(x.find('div', id='season-10'))
        tokpanel = nltk.word_tokenize(tokpanel)
        del tokpanel[0:63]
        del tokpanel[1: len(tokpanel)]
        tokpanel[0] = tokpanel[0][-22:-16]
        tokpanel[0] = tokpanel[0].replace("-", "")
        tokpanel[0] = tokpanel[0].replace("rank", "")
        ranklist = ["Copper IV", "Copper III", "Copper II", "Copper I",
                    "Bronze IV", "Bronze III", "Bronze II", "Bronze I",
                    "Silver IV", "Silver III", "Silver II", "Silver I",
                    "Gold III", "Gold II", "Gold I",
                    "Plat III", "Plat II", "Plat I",
                    "Diamond",
                    "Master"]
        rank = ranklist[int(tokpanel[0]) - 1]
        return rank

    def getWinLoss(x):
        infopanel = x.find('div', id='season-10')
        infopanelsmall = infopanel.find_all('div', class_='value')
        infopanelsmall = str(infopanelsmall)
        infopanel = nltk.word_tokenize(infopanelsmall)
        infopanelsmall = infopanelsmall.split('\n')
        winloss = infopanelsmall
        return winloss

    def getMMR(x):
        infopanel = x.find('div', id='season-10')
        infopanelsmall = infopanel.find_all('div', class_="value")
        infopanelsmall = str(infopanelsmall)
        infopanel = nltk.word_tokenize(infopanelsmall)
        infopanelsmall = infopanelsmall.split('\n')
        mmr = infopanelsmall[9]
        return mmr

    def getHMMR(x):
        infopanel = x.find('div', id='season-10')
        infopanelsmall = infopanel.find_all('div', class_="value")
        infopanelsmall = str(infopanelsmall)
        infopanel = nltk.word_tokenize(infopanelsmall)
        infopanelsmall = infopanelsmall.split("\n")
        hmmr = infopanelsmall[11]
        return hmmr

    def getCasualKD(x):
        mainpanel = str(x.find('div', class_='trn-stats'))
        mainpanel = nltk.word_tokenize(mainpanel)
        del mainpanel[0:375]
        del mainpanel[1:len(mainpanel)]
        KD = mainpanel[0]
        return KD

    def Search(x):
        site = "https://r6.tracker.network/profile/pc/" + x
        # set header to allow script to access site
        hdr = {'User-Agent': 'Mozilla/5.0'}
        req = Request(site, headers=hdr)
        page = urlopen(req)
        # parse the site saved in site variable
        soup = BeautifulSoup(page, "html.parser")
        return soup

    def runSearch(x):
        names = convUser(x)
        for i in range(0, len(names)):
            global fKD, fhmmr, fmmr, fwinloss, frank, fname, labels
            # calls each function to get player stats from single save
            fKD = getCasualKD(Search(names[i]))
            fhmmr = getHMMR(Search(names[i]))
            fmmr = getMMR(Search(names[i]))
            fwinloss = getWinLoss(Search(names[i]))
            frank = getRank(Search(names[i]))
            fname = names[i]
            # print the data out in a formatted way
            output = "Siege Stats: \n " + "Ubisoft ID: " + fname + "\n Rank: " + frank + "\n Casual KD: " + fKD + "\n Highest MMR: " + fhmmr + "\n Current MMR: " + fmmr + "\n Ranked Win/Loss: " + fwinloss
            return output

    await bot.say(runSearch(content))

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

client.run('Nah fam')


from config import settings as st
from typing import Tuple, Generator, List, Union
from rasterio.windows import Window
from shapely.geometry import Polygon

import affine
import rasterio
from tqdm import tqdm
import numpy as np
from skimage import exposure, img_as_ubyte
import itertools
import shapely
import warnings
from PIL import Image as pilimg
import os

def get_chip_windows(raster_width,raster_height,raster_transform,chip_width,chip_height,skip_partial_chips = False) -> Generator[Tuple[Window, affine.Affine, Polygon], any, None]:
    """
    Generate windows of defined width and height for vectors
    :param raster_width: width of raster image
    :param raster_height: height of raster image
    :param raster_transform: transformation of raster image
    :param chip_width: output width of each chips
    :param chip_height: output height of each chips
    :param skip_partial_chips: Ignore the edge chips that are not in full size
    :return: Yields the tuple of chip window, transform and polygon
    """

    col_row_offsets = itertools.product(range(0, raster_width, chip_width), range(0, raster_height, chip_height))
    raster_window = Window(col_off=0, row_off=0, width=raster_width, height=raster_height)

    for col_off, row_off in col_row_offsets:
        chip_window = Window(col_off=col_off, row_off=row_off, width=chip_width, height=chip_height)

        if skip_partial_chips:
            if row_off + chip_height > raster_height or col_off + chip_width > raster_width:
                continue

        chip_window = chip_window.intersection(raster_window)
        chip_transform = rasterio.windows.transform(chip_window, raster_transform)
        chip_bounds = rasterio.windows.bounds(chip_window, raster_transform)  # Uses transform of full raster.
        chip_poly = shapely.geometry.box(*chip_bounds, ccw=False)

        yield (chip_window, chip_transform, chip_poly)

def cut_chip_images(inpath_raster,
                    outpath_chipfolder,
                    chip_names,
                    chip_windows,
                    raster_image_range,
                    bands=[3, 2, 1]):
    """Cuts image raster to chips via the given windows and exports them to jpg."""

    src = rasterio.open(inpath_raster)

    all_chip_stats = {}
    for chip_name, chip_window in tqdm(zip(chip_names, chip_windows)):
        img_array = np.dstack(list(src.read(window=chip_window)))
        #img_array = exposure.rescale_intensity(img_array, in_range=(0, raster_image_range))  # Sentinel2 range.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            img_array = img_as_ubyte(img_array)
        img_pil = pilimg.fromarray(img_array)

        # Export chip images
        dst = os.path.join(outpath_chipfolder,str(chip_name) + '.jpg')
        img_pil.save(dst, format='JPEG', subsampling=0, quality=100)

        all_chip_stats[chip_name] = {'mean': img_array.mean(axis=(0, 1)),
                                     'std': img_array.std(axis=(0, 1))}
    src.close()

    return all_chip_stats


from IPython.display import display
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def show_prices(cereals, per_100g=False):
    """Creates and displays a bar chart over cereal prices

    Parameters:
    cereals: List of Cereal objects
    per_100g: Boolean. True, if the bar chart should be per 100 grams for easier comparison. Default False
    """
    # names = [cereal.get_brand_name() for cereal in cereals]
    # stores = __get_stores(cereals)
    # prices_in_stores = __get_prices_with_cereal_name(stores, cereals)
    # title = 'Cereal Prices'
    # __plot_prices(names, stores, prices_in_stores, title)
    stores = list(__get_stores(cereals))
    for store in stores:
        title = __create_title(store, per_100g)
        cereals_prices = {
            cereal.get_brand_name(): __get_price(value, cereal.grams, per_100g)
            for cereal in cereals
            for key, value in cereal.price.items()
            if key == store
        }
        __plot_prices_in_store(cereals_prices, title)

def show_nutrition(cereals):
    """Creates and displays a dataframe over the nutritional content
    (protein, carbohydrates, fiber, fat, salt)
    per 100 grams in cereals

    Parameters:
    cereals: List of Cereal objects
    """
    data = __get_nutrition_data(cereals)
    df = pd.DataFrame(data)
    print("Nutritional Content per 100 grams in Cereals")
    # df = df.style.set_caption('Nutritional Content per 100 grams in Cereals')
    display(df)

def show_recommended_nutrition():
    """Creates and displays a dataframe over the daily recommended maximum nutritional intake
    (protein, carbohydrates, fiber, fat, salt)
    """
    df = __get_recommended_nutrition()
    print("Daily Recommended Maximum Nutritional Intake")
    # df = df.style.set_caption('Daily Recommended Nutritional Intake')
    display(df)

def show_pct_of_recommended_nutrition(cereal, sex):
    """Creates and displays a bar chart over the percentage of a cereal's
    nutritional content compared to the recommended daily intake
    (protein, carbohydrates, fiber, fat, salt)

    Parameters:
    cereal: Cereal object
    sex: String - either 'Male' or 'Female'. Sex needed for recommended daily nutritional intake
    """
    data = __get_recommended_nutrition()
    df = data[data[:]["Sex"] == sex.capitalize()]
    recommended = __get_recommended_nutrition_from_dataframe(df)
    actual = cereal.nutrition.get_nutrition_as_list()
    pcts = [(ac / rec) * 100 for ac, rec in zip(actual, recommended)]
    labels = "Calories", "Protein", "  Carbohydrates", "Fiber", "Fat", "Salt"
    title = (
        "Percentage of %s %s's Nutrional Content compared to Daily Recommended Intake"
        % (cereal.brand.capitalize(), cereal.name.capitalize())
    )
    __plot_percentage(pcts, labels, title)

def __plot_prices_in_store(cereals_prices, title):
    names = cereals_prices.keys()
    prices = cereals_prices.values()
    plt.bar(names, prices, width=0.5, align="center")
    plt.xticks(rotation=15, horizontalalignment="right", fontweight="light")
    plt.ylabel("Price in DKK", fontsize=10)
    plt.grid(axis="y", color="grey")
    plt.title(title)
    plt.show()

def __plot_percentage(pcts, labels, title):
    plt.bar(labels, pcts, width=0.5, align="center")
    plt.ylabel("Percentage (%)", fontsize=10)
    plt.grid(axis="y", color="grey")
    plt.title(title)
    plt.show()

def __get_stores(cereals):
    return list(set([key for cereal in cereals for key in cereal.price.keys()]))

def __get_price(price, grams, per_100g):
    if per_100g:
        return price / 10
    return (price / 1000) * grams

def __get_nutrition_data(cereals):
    names = [cereal.get_brand_name() for cereal in cereals]
    calories = [str(cereal.nutrition.calories) + " kcal" for cereal in cereals]
    proteins = [str(cereal.nutrition.protein) + " g" for cereal in cereals]
    carbs = [str(cereal.nutrition.carbohydrates) + " g" for cereal in cereals]
    fibers = [str(cereal.nutrition.fiber) + " g" for cereal in cereals]
    fats = [str(cereal.nutrition.fat) + " g" for cereal in cereals]
    salts = [str(cereal.nutrition.salt) + " g" for cereal in cereals]
    return {
        "Cereal Name": names,
        "Calories": calories,
        "Protein": proteins,
        "Carbohydrates": carbs,
        "Fiber": fibers,
        "Fat": fats,
        "Salt": salts,
    }

def __get_recommended_nutrition():
    return pd.read_csv("files/daily_nutrition.csv")

def __get_recommended_nutrition_from_dataframe(df):
    calories = int(df.loc[:, "Calories"].str.replace(" kcal", ""))
    protein = float(df.loc[:, "Protein"].str.replace(" g", ""))
    carbs = float(df.loc[:, "Carbohydrates"].str.replace(" g", ""))
    fiber = float(df.loc[:, "Fiber"].str.replace(" g", ""))
    fat = float(df.loc[:, "Fat"].str.replace(" g", ""))
    salt = float(df.loc[:, "Salt"].str.replace(" g", ""))
    return [calories, protein, carbs, fiber, fat, salt]

def __create_title(store, per_100g):
    if per_100g:
        return "Cereal Prices per 100 grams at " + store.capitalize()
    return "Cereal Prices per at " + store.capitalize()


"""goals

Revision ID: 2db51ca0949b
Revises: 2ba80b8acdf9
Create Date: 2018-08-16 22:16:43.684402

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '2db51ca0949b'
down_revision = '2ba80b8acdf9'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('goal',
    sa.Column('id', sa.INTEGER(), nullable=False),
    sa.Column('user_id', sa.INTEGER(), nullable=True),
    sa.Column('distance', sa.TEXT(), nullable=True),
    sa.Column('date', sa.DATE(), nullable=True),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_goal_id'), 'goal', ['id'], unique=False)
    op.create_index(op.f('ix_goal_user_id'), 'goal', ['user_id'], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_goal_user_id'), table_name='goal')
    op.drop_index(op.f('ix_goal_id'), table_name='goal')
    op.drop_table('goal')
    # ### end Alembic commands ###


class Single_Linked_List:
    class _Nodo:
        def __init__(self,valor):
               self.valor = valor
               self.nodo_siguiente = None

    def _init_ (self):
        self.cabeza = None
        self.cola = None
        self.tamanio = 0
    def __str__(self):
        #Muestra los elementos de la linkedlist
        array = []
        nodo_actual = self.cabeza
        while nodo_actual != None :
               array.append(nodo_actual.valor)
               nodo_actual = nodo_actual.nodo_siguiente
        return str(array) + "Tamano : " + str(self.tamanio)

    def append (self, value):
        nuevo_nodo = self._Nodo(value)
        if self.cabeza == None and self.cola == None :
               self.cabeza = nuevo_nodo
               self.cola = nuevo_nodo
        else:
               self.cola.nodo_siguiente = nuevo_nodo
               self.cola = nuevo_nodo

        self.tamanio += 1

    def prepend (self, valor):
        #Agrega un nuevo elemento al principio de la linkedlist
        nuevo_nodo = self._Nodo(valor)
        if self.cabeza == None and self.cola == None:
               self.cabeza = nuevo_nodo
               self.cola = nuevo_nodo
        else :
               nuevo_nodo.nodo_siguiente = self.cabeza
               self.cabeza = nuevo_nodo

        self.tamanio += 1

    def shift (self):
        if self.tamanio == 0 :
               self.cabeza == None
               self.cola == None
        else:
               nodo_eliminado = self.cabeza
               self.cabeza = nodo_eliminado.nodo_siguiente
               nodo_eliminado.nodo_siguiente = None
               self.tamanio -= 1

               return print (f"El nodo eliminado tiene el valor {nodo_eliminado.valor}")

    def pop (self):
        #Saca el elemento de la linkedlist
        if self.tamanio == 0:
            self.cabeza = None
            self.cola = None
        else:
            nodo_actual = self.cabeza
            nueva_cola = nodo_actual
            while nodo_actual.nodo_siguiente != None :
                nueva_cola = nodo_actual
                nodo_actual = nodo_actual.nodo_siguiente
            self.cola = nueva_cola
            self.cola.nodo_siguiente = None
            self.tamanio -= 1
            return print (f"El valor eliminado es {nodo_actual.valor}")

    def get (self, indice):
        if indice == self.tamanio -1 :
            print (self.cola.valor)
            return self.cola
        elif indice == 0 :
            print (self.cabeza.valor)
            return self.cabeza
        elif not (indice >= self.tamanio or indice < 0 ):
            nodo_actual = self.cabeza
            contador = 0
            while contador != indice :
                nodo_actual = nodo_actual.nodo_siguiente
                contador += 1
            print (nodo_actual.valor)
            return nodo_actual
        else:
             return None

    def update (self,indice,valor):
        nodo_objetivo = self.get(indice)
        if nodo_objetivo != None :
            nodo_objetivo.valor = valor
        else :
            return None

    def insert (self,indice,valor):
        #Agrega un elemento en donde sea en la linkedlist dado el inidice
        if indice == self.tamanio -1 :
            return self.append (valor)
        elif not (indice >= self.tamanio or indice < 0 ):
            nuevo_nodo = self._Nodo(valor)
            nodos_anteriores = self.get(indice)
            nodos_siguientes = nodos_anteriores.nodo_siguiente
            nodos_anteriores.nodo_siguiente = nuevo_nodo
            nuevo_nodo.nodo_siguiente = nodos_siguientes
            self.tamanio += 1
        else:
             return None
    def remove (self,indice):
        #Saca un elemento de donde sea de la linkedlist dado el indice
        if indice == 0 :
            return self.shift()
        elif indice == self.tamanio- -1 :
            return self.pop()
        elif not (indice >= self.tamanio or indice < 0 ):
            nodos_anteriores = self.get(indice - 1)
            nodo_removido = nodos_anteriores.nodo_siguiente
            nodos_anteriores.nodo_siguiente = nodo_removido.nodo_siguiente
            nodo_removido.nodo_siguiente = None
            self.tamanio -= 1
            return nodo_removido
        else :
            return None

    def reverse (self):
        #Revierte la linked list
        nodos_revertidos = None
        nodo_actual = self.cabeza
        self.cola = nodo_actual
        while nodo_actual != None :
            nodo_siguiente = nodo_actual.nodo_siguiente
            nodo_actual.nodo_siguiente = nodos_revertidos
            nodos_revertidos = nodo_actual
            nodo_actual = nodo_siguiente
        self.cabeza = nodos_revertidos
        return self.cabeza

sll = Single_Linked_List()
sll.append(26)
sll.append(15)
sll.append(80)
sll.prepend(10)
print (sll)
sll.shift()
sll.insert(1,28)
print (sll)
sll.remove(1)
print (sll)


"""
Значения из переменных tkinter могут извлекаться и после удаления виджета

Поскольку объекты переменных tkinter продолжают существовать после уничтожения
виджетов Entry, к которым они привязаны, сохраняется возможность извлекать
из них значения, когда модального диалога уже нет, как показано в этом примере/

Этот пример такой же, как example_08_20, но теперь функция show уничтожает
всплывающее окно до извлечения введенных данных из переменных StringVar в списке,
созданном функцией makeform.

Переменные оказываются более надежными в некоторых контекстах, потому что они
не являются частью дерева виджетов.

Например, они часто используются с флажками, группами переключателей и ползунками,
обеспечивая доступ к текущим значениям и связывая вместе несколько виджетов.
"""
from tkinter import *
from examples.entry3 import makeform, fetch, fields

def show(variables, popup):
    popup.destroy()             # здесь порядок не имеет значения
    fetch(variables)            # переменные сохраняются после уничтожения окна

def ask():
    popup = Toplevel()          # отображение формы в модальном диалоге
    vars = makeform(popup, fields)
    Button(popup, text='OK', command=(lambda: show(vars, popup))).pack()
    popup.grab_set()
    popup.focus_set()
    popup.wait_window()         # ждать уничтожения окна

root = Tk()
Button(root, text='Dialog', command=ask).pack()
root.mainloop()


import unittest
from collections import defaultdict, deque
import sys

def minimumBribes(q):
    moves = 0
    for pos, val in enumerate(q):

        d = (val - 1) - pos
        if d > 2:
            return "Too chaotic"
        start = max(0, val - 2)
        end = pos + 1
        for j in range(start, end):
            if q[j] > val:
                moves += 1
    return moves

def minimumBribesa(final):
    n = len(final)
    queue = [i for i in range(1, n + 1)]

    state = defaultdict(int)
    n = len(final)
    for index in range(n):
        state[final[index]] = index

    movements = 0
    ite = deque(queue[:])
    while ite:
        target = ite.popleft()
        pos = state[target]
        index = queue.index(target)
        dist = abs(pos - index)
        if dist > 2:
            return "Too chaotic"
        while queue[pos] != target:
            movements += 1
            temp = queue[index + 1]
            queue[index + 1] = target
            queue[index] = temp
            index = index + 1

    return movements

class Test(unittest.TestCase):

    def test_case(self):
        peaple = 5
        target = [2, 1, 5, 3, 4]
        result = minimumBribes(target)
        self.assertEqual(3, result)

    def test_case_caotic(self):
        peaple = 5
        target = [2, 5, 1, 3, 4]
        result = minimumBribes(target)
        self.assertEqual("Too chaotic", result)

    def test_case_caotic_b(self):
        target = [5, 1, 2, 3, 7, 8, 6, 4]
        result = minimumBribes(target)
        self.assertEqual("Too chaotic", result)

    def test_case_caotic(self):
        #arget = [1, 2, 3, 4, 5, 6, 7, 8]
        target = [1, 2, 5, 3, 7, 8, 6, 4]
        result = minimumBribes(target)
        self.assertEqual(7, result)


from django import forms
from django.forms import ModelForm
from .models import ToDoModel

class ToDoForm(ModelForm):
    class Meta:
        model = ToDoModel
        fields = ['title', 'description', 'high_priority']

        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control'}),
            # 'high_priority': forms.CheckboxInput(attrs={'class': 'form-control'}),
        }

        def clean_title(self):
            new_title = self.cleaned_data['title'].lower()

            # if new_title == 'create':
            #     from django.core.exceptions import ValidationError
            #     raise ValidationError('title may not be "Create"')
            return new_title


from pydbus import SystemBus
from gi.repository import GLib
from modules.logger import log

BLUEZ_SERVICE = 'org.bluez'
INTERFACE = {
    'ADAPTER': BLUEZ_SERVICE+'.Adapter1',
    'DEVICE': BLUEZ_SERVICE+'.Device1',
    'MEDIA_CONTROL': BLUEZ_SERVICE+'.MediaControl1',
    'MEDIA_PLAYER': BLUEZ_SERVICE+'.MediaPlayer1'
}

class Bluetooth:
    def __init__(self, name):
        self.__bus = SystemBus()
        self.__adapter = self.__bus.get(BLUEZ_SERVICE, 'hci0')[INTERFACE['ADAPTER']]
        self.__set_alias(name)
        self.__player = None
        self.__change_callback = None

        self.__bus.subscribe(sender=BLUEZ_SERVICE, signal='PropertiesChanged', arg0=INTERFACE['ADAPTER'], signal_fired=self.__adapter_handler)
        self.__bus.subscribe(sender=BLUEZ_SERVICE, signal='PropertiesChanged', arg0=INTERFACE['MEDIA_CONTROL'], signal_fired=self.__mediacontrol_handler)
        self.__bus.subscribe(sender=BLUEZ_SERVICE, signal='PropertiesChanged', arg0=INTERFACE['MEDIA_PLAYER'], signal_fired=self.__mediaplayer_handler)

    def start_discovery(self):
        self.__powered()
        self.__pairable()
        self.__discoverable()
        return self.__adapter.StartDiscovery()

    def set_on_change(self, callback):
        self.__change_callback = callback

    @property
    def device_name(self):
        device_object = self.__bus.get(BLUEZ_SERVICE, self.__player[INTERFACE['MEDIA_PLAYER']].Device)
        device = device_object[INTERFACE['DEVICE']]
        return device.Alias

    @property
    def current_track(self):
        player = self.__player[INTERFACE['MEDIA_PLAYER']]
        return {
            'title': player.Track.get('Title', ''),
            'album': player.Track.get('Album', ''),
            'artist': player.Track.get('Artist', ''),
            'genre': player.Track.get('Genre', ''),
            'track_number': player.Track.get('TrackNumber', 0),
            'number_of_tracks': player.Track.get('NumberOfTracks', 0),
            'duration_ms': player.Track.get('Duration', 0),
            'position_ms': player.Position,
            'status': player.Status.lower()
        }

    def play(self):
        try:
            self.__player[INTERFACE['MEDIA_PLAYER']].Play()
        except GLib.Error:
            log.warning('Can\'t play track, player not ready.')

    def pause(self):
        try:
            self.__player[INTERFACE['MEDIA_PLAYER']].Pause()
        except GLib.Error:
            log.warning('Can\'t pause track, player not ready.')

    def next(self):
        try:
            self.__player[INTERFACE['MEDIA_PLAYER']].Next()
        except GLib.Error:
            log.warning('Can\'t go to next track, player not ready.')

    def previous(self):
        try:
            self.__player[INTERFACE['MEDIA_PLAYER']].Previous()
        except GLib.Error:
            log.warning('Can\'t go to previous track, player not ready.')

    def shuffle(self, setting):
        shuffle_settings = ['off', 'alltracks', 'group']
        if setting not in shuffle_settings:
            return
        try:
            self.__player[INTERFACE['MEDIA_PLAYER']].Shuffle = setting
        except GLib.Error:
            log.warning('Can\'t set shuffle mode to %s, player not ready.', setting)

    def repeat(self, setting):
        repeat_settings = ['off', 'singletrack', 'alltracks', 'group']
        if setting not in repeat_settings:
            return
        try:
            self.__player[INTERFACE['MEDIA_PLAYER']].Repeat = setting
        except GLib.Error:
            log.warning('Can\'t set repeat mode to %s, player not ready.', setting)

    def __get_managed_objects(self):
        object_manager = self.__bus.get(BLUEZ_SERVICE, '/')['org.freedesktop.DBus.ObjectManager']
        return object_manager.GetManagedObjects()

    def __set_alias(self, alias):
        self.__adapter.Alias = alias

    def __powered(self):
        self.__adapter.Powered = True

    def __discoverable(self, timeout=90):
        self.__adapter.Discoverable = True
        self.__adapter.DiscoverableTimeout = timeout

    def __pairable(self, timeout=90):
        self.__adapter.Pairable = True
        self.__adapter.PairableTimeout = timeout

    def __get_devices(self):
        objects = self.__get_managed_objects()
        devices_filter = lambda item: INTERFACE['DEVICE'] in item[1]
        return dict(filter(devices_filter, objects.items()))

    def __get_paired_media_devices(self):
        devices = self.__get_devices()
        paired_media_filter = lambda item: item[1][INTERFACE['DEVICE']]['Paired'] and INTERFACE['MEDIA_CONTROL'] in item[1]
        return dict(filter(paired_media_filter, devices.items()))

    def __connect_to_paired_media_device(self):
        devices = self.__get_paired_media_devices()
        device_path = list(devices.keys())[0]
        device_object = self.__bus.get(BLUEZ_SERVICE, device_path)
        device = device_object[INTERFACE['DEVICE']]
        if device.Connected:
            log.info('Connected to device %s.', device.Name)
            player_path = device_object[INTERFACE['MEDIA_CONTROL']].Player
            self.__init_player(player_path)
        else:
            try:
                device.Connect()
            except GLib.GError as err:
                log.warning('Can\'t connect to device %s.', device.Alias)

    def __init_player(self, player_path):
        self.__player = self.__bus.get(BLUEZ_SERVICE, player_path)

    def __adapter_handler(self, sender, path, interface, signal, parameters):
        interface, properties, optional = parameters
        if 'Discovering' in properties:
            log.info('Discovering active. Looking for devices.')
        try:
            self.__connect_to_paired_media_device()
        except:
            log.info('No paired devices found.')

    def __mediacontrol_handler(self, sender, path, interface, signal, parameters):
        interface, properties, optional = parameters
        if properties['Connected']:
            if 'Player' in properties:
                self.__init_player(properties['Player'])

    def __mediaplayer_handler(self, sender, path, interface, signal, parameters):
        self.__change_callback()


import unittest

from app.users import User
from app.categories import Categories
from app.recipes import Recipes

class UserTest(unittest.TestCase):
    def setUp(self):
        self.user = User()
        self.user_data = {
            "user@email":"passwordofuser"
        }

    def testusercreation(self):
        self.user.addUser(self.user_data)
        self.assertEqual(1, len(self.user.getUsers()))

    def testdublicateuseraddition(self):
        self.user.addUser(self.user_data)
        self.assertEqual(1, len(self.user.getUsers()))

        self.assertEqual("Dublicate user", self.user.addUser(self.user_data))
    def testmultipleusercreation(self):
        self.user.addUser(self.user_data)
        self.assertEqual(1, len(self.user.getUsers()))

        self.user.addUser({"new@email.com": "newpassword"})
        self.assertEqual(2, len(self.user.getUsers()))
    def testgetsingleuser(self):
        self.user.addUser(self.user_data)
        self.assertEqual(1, len(self.user.getUsers()))

        self.assertIn("user@email", self.user.getUser("user@email"))

    def testdeleteuser(self):
        self.user.addUser(self.user_data)
        self.assertEqual(1, len(self.user.getUsers()))

        self.user.addUser({"new@email.com": "newpassword"})
        self.assertEqual(2, len(self.user.getUsers()))

        self.user.deleteUser("new@email.com")
        self.assertEqual(1, len(self.user.getUsers()))
    def testupdateuser(self):
        self.user.addUser(self.user_data)
        self.assertEqual(1, len(self.user.getUsers()))

        new_data = {
            "another@email.com":"123456"
        }
        self.user.updateUser("user@email", new_data)
        self.assertIn("another@email.com", self.user.getUser("another@email.com"))

class CategoriesTest(unittest.TestCase):
    def setUp(self):
        self.categories = Categories()
        self.cat_data = {
            "pic":"/cat1.png",
            "description":"my pavi recipies"
        }
    def testcartegoryadd(self):
        self.categories.addCategories("testcart", self.cat_data)
        self.assertEqual(1, len(self.categories.getCategories()))
    def testcategorydublicate(self):
        self.categories.addCategories("testcart", self.cat_data)
        self.assertEqual(1, len(self.categories.getCategories()))

        self.assertEqual("Dublicate category",
                         self.categories.addCategories("testcart", self.cat_data))
    def testmultiplecategoriescreation(self):
        self.categories.addCategories("testcart", self.cat_data)
        self.assertEqual(1, len(self.categories.getCategories()))

        self.categories.addCategories("new cart", self.cat_data)
        self.assertEqual(2, len(self.categories.getCategories()))
    def testdeletecategories(self):
        self.categories.addCategories("testcart", self.cat_data)
        self.assertEqual(1, len(self.categories.getCategories()))

        self.categories.addCategories("new cart", self.cat_data)
        self.assertEqual(2, len(self.categories.getCategories()))

        self.categories.deleteCategory("testcart")
        self.assertEqual(1, len(self.categories.getCategories()))
    def testgetsinglecategory(self):
        self.categories.addCategories("testcart", self.cat_data)
        self.assertEqual(1, len(self.categories.getCategories()))

        self.assertIn("testcart", self.categories.getCategory("testcart"))
    def testupdatecategory(self):
        self.categories.addCategories("testcart", self.cat_data)
        self.assertEqual(1, len(self.categories.getCategories()))

        new_data = {
            "pic":"/cat33.png",
            "description":"my home recipies"
        }
        self.categories.updateCategory("testcart", new_data)
        self.assertIn("/cat33.png", self.categories.getCategory("testcart").get("testcart").get("pic"))

class RecipeTest(unittest.TestCase):
    def setUp(self):
        self.recipe = Recipes()
        self.recipe_data = {
            "ingredients":["one", "two", "three"],
            "procedure":["one", "two", "three"],
            "pic":"/recipe1.png"
        }
    def testrecipeadd(self):
        self.recipe.addRecipes("testrecipe", self.recipe_data)
        self.assertEqual(1, len(self.recipe.getRecipes()))
    def testrecipedublicate(self):
        self.recipe.addRecipes("testrecipe", self.recipe_data)
        self.assertEqual(1, len(self.recipe.getRecipes()))

        self.assertEqual("Dublicate recipe",
                         self.recipe.addRecipes("testrecipe", self.recipe_data))
    def testmultiplerecipecreation(self):
        self.recipe.addRecipes("testrecipe", self.recipe_data)
        self.assertEqual(1, len(self.recipe.getRecipes()))

        self.recipe.addRecipes("new testrecipe", self.recipe_data)
        self.assertEqual(2, len(self.recipe.getRecipes()))
    def testdeleterecipe(self):
        self.recipe.addRecipes("testrecipe", self.recipe_data)
        self.assertEqual(1, len(self.recipe.getRecipes()))

        self.recipe.addRecipes("new testrecipe", self.recipe_data)
        self.assertEqual(2, len(self.recipe.getRecipes()))

        self.recipe.deleteRecipe("testrecipe")
        self.assertEqual(1, len(self.recipe.getRecipes()))
    def testgetsinglerecipe(self):
        self.recipe.addRecipes("testrecipe", self.recipe)
        self.assertEqual(1, len(self.recipe.getRecipes()))

        self.assertIn("testrecipe", self.recipe.getRecipy("testrecipe"))
    def testupdatecategory(self):
        self.recipe.addRecipes("testrecipe", self.recipe)
        self.assertEqual(1, len(self.recipe.getRecipes()))

        new_data = {
            "ingredients":["one1", "two1", "three1"],
            "procedure":["one1", "two1", "three1"],
            "pic":"/recipe12.png"
        }

        self.recipe.updateRecipe("testrecipe", new_data)
        self.assertIn("/recipe12.png", self.recipe.getRecipy("testrecipe").get("testrecipe").get("pic"))


from pprint import pprint
from typing import List

from utils import SIGame, SIPlayer

new_si_stages = ["1/16 финала", "1/8 финала", "1/4 финала", "1/2 финала", "Финал"]

class Numbers:
    def __init__(self):
        self.numbers = list(range(1, 100))
        self.pos = -1

    def __iter__(self):
        return self

    def __next__(self):
        self.pos += 1
        return f"Бой {self.numbers[self.pos]}"

def read_single_game(stage: str, name: str, lines: List[str], place_col) -> SIGame:
    game = SIGame(stage, name, [])

    for line in lines:
        line_split = line.strip("\n").split("\t")

        place = float(line_split[place_col])

        if place_col == 3:
            first_name, last_name = line_split[1].split(" ")
            points_str = line_split[2]
            if "(" in points_str:
                points = int(points_str.split("(")[0])
                shootout = int(points_str.split("(")[1][:-1])
            else:
                points = int(points_str)
                shootout = None

        elif place_col == 1:
            first_name, last_name = line_split[2].split(" ")
            points = int(line_split[3])
            shootout = None
        else:
            raise ValueError

        game.players.append(
            SIPlayer(
                team=None,
                city=None,
                first_name=first_name,
                last_name=last_name,
                place=place,
                points=points,
                shootout=shootout,
            )
        )

    return game

def read_2017() -> List[SIGame]:
    numbers = Numbers()

    with open(f"./txt/2017/si.txt") as year_file:
        lines = year_file.readlines()

    sixteenth_games = [
        read_single_game(
            new_si_stages[0], next(numbers), lines[6 * k + 3 : 6 * k + 7], place_col=3,
        )
        for k in range(16)
    ]

    eighth_games = [
        read_single_game(
            new_si_stages[1], next(numbers), lines[6 * k + 101 : 6 * k + 105], place_col=3,
        )
        for k in range(8)
    ]

    quarters = [
        read_single_game(
            new_si_stages[2], next(numbers), lines[6 * k + 151 : 6 * k + 155], place_col=3
        )
        for k in range(4)
    ]

    semis = [
        read_single_game(
            new_si_stages[3], next(numbers), lines[6 * k + 177 : 6 * k + 181], place_col=3
        )
        for k in range(2)
    ]

    finals = [
        read_single_game(new_si_stages[4], next(numbers), lines[189:193], place_col=3)
    ]

    return sixteenth_games + eighth_games + quarters + semis + finals

def read_year(year: int) -> List[SIGame]:
    numbers = Numbers()

    with open(f"./txt/{year}/si.txt") as year_file:
        lines = year_file.readlines()

    sixteenth_games = [
        read_single_game(
            new_si_stages[0], next(numbers), lines[9 * k + 4: 9 * k + 8], place_col=1,
        )
        for k in range(16)
    ]

    eighth_games = [
        read_single_game(
            new_si_stages[1], next(numbers), lines[9 * k + 149: 9 * k + 153], place_col=1,
        )
        for k in range(8)
    ]

    quarters = [
        read_single_game(
            new_si_stages[2], next(numbers), lines[9 * k + 222: 9 * k + 226], place_col=1
        )
        for k in range(4)
    ]

    semis = [
        read_single_game(
            new_si_stages[3], next(numbers), lines[9 * k + 259: 9 * k + 263], place_col=1
        )
        for k in range(2)
    ]

    finals = [
        read_single_game(new_si_stages[4], next(numbers), lines[275:279], place_col=1)
    ]

    return sixteenth_games + eighth_games + quarters + semis + finals

def load_new_si_results():
    new_years = [2018, 2019]
    newer = {year: read_year(year) for year in new_years}
    return {2017: read_2017(), **newer}

if __name__ == "__main__":
    results = load_new_si_results()
    pprint(results)


import tempfile

import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as fn
from torch.nn.init import normal_
from torchvision import models

import fastestimator as fe
from fastestimator.backend import reduce_mean
from fastestimator.dataset.data import mscoco
from fastestimator.layers.pytorch import Cropping2D
from fastestimator.op.numpyop import LambdaOp
from fastestimator.op.numpyop.multivariate import Resize
from fastestimator.op.numpyop.univariate import ChannelTranspose, Normalize, ReadImage
from fastestimator.op.tensorop import TensorOp
from fastestimator.op.tensorop.model import ModelOp, UpdateOp
from fastestimator.trace.io import ModelSaver

class ExtractVGGFeatures(TensorOp):
    def __init__(self, inputs, outputs, device, mode=None):
        super().__init__(inputs, outputs, mode)
        self.vgg = LossNet()
        self.vgg.to(device)

    def forward(self, data, state):
        return self.vgg(data)

class StyleContentLoss(TensorOp):
    def __init__(self, style_weight, content_weight, tv_weight, inputs, outputs=None, mode=None, average_loss=True):
        super().__init__(inputs=inputs, outputs=outputs, mode=mode)
        self.style_weight = style_weight
        self.content_weight = content_weight
        self.tv_weight = tv_weight
        self.average_loss = average_loss

    def calculate_style_recon_loss(self, y_true, y_pred):
        y_true_gram = self.calculate_gram_matrix(y_true)
        y_pred_gram = self.calculate_gram_matrix(y_pred)
        y_diff_gram = y_pred_gram - y_true_gram
        y_norm = torch.sqrt(torch.sum(y_diff_gram * y_diff_gram, dim=(1, 2)))
        return y_norm

    def calculate_feature_recon_loss(self, y_true, y_pred):
        y_diff = y_pred - y_true
        num_elts = torch.tensor(y_diff.shape[1] * y_diff.shape[2] * y_diff.shape[3], dtype=torch.float32)
        y_diff_norm = torch.sum(y_diff * y_diff, dim=(1, 2, 3)) / num_elts
        return y_diff_norm

    def calculate_gram_matrix(self, x):
        num_elts = torch.tensor(x.shape[1] * x.shape[2] * x.shape[3], dtype=torch.float32)
        gram_matrix = torch.einsum('bcij,bdij->bcd', x, x)
        gram_matrix /= num_elts
        return gram_matrix

    def calculate_total_variation(self, y_pred):
        return (torch.sum(torch.abs(y_pred[:, :, :, :-1] - y_pred[:, :, :, 1:]), dim=[1, 2, 3]) +
                torch.sum(torch.abs(y_pred[:, :, :-1, :] - y_pred[:, :, 1:, :]), dim=[1, 2, 3]))

    def forward(self, data, state):
        y_pred, y_style, y_content, image_out = data

        style_loss = [self.calculate_style_recon_loss(a, b) for a, b in zip(y_style['style'], y_pred['style'])]
        style_loss = torch.stack(style_loss, dim=0).sum(dim=0)
        style_loss *= self.style_weight

        content_loss = [
            self.calculate_feature_recon_loss(a, b) for a, b in zip(y_content['content'], y_pred['content'])
        ]
        content_loss = torch.stack(content_loss, dim=0).sum(dim=0)
        content_loss *= self.content_weight

        total_variation_reg = self.calculate_total_variation(image_out)
        total_variation_reg *= self.tv_weight
        loss = style_loss + content_loss + total_variation_reg

        if self.average_loss:
            loss = reduce_mean(loss)

        return loss

class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=3):
        super().__init__()
        self.cropping2d = Cropping2D(cropping=2)
        self.layers = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size),
                                    nn.InstanceNorm2d(out_channels),
                                    nn.Conv2d(out_channels, out_channels, kernel_size=kernel_size),
                                    nn.InstanceNorm2d(out_channels))

        for layer in self.layers:
            if isinstance(layer, nn.Conv2d):
                normal_(layer.weight.data, mean=0, std=0.02)

    def forward(self, x):
        x0 = self.cropping2d(x)
        x = self.layers(x)
        x = x + x0
        return x

class ConvBlock(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=9, padding=4, apply_relu=True):
        super().__init__()
        self.conv_layer = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding)
        self.instance_norm = nn.InstanceNorm2d(out_channels)
        self.apply_relu = apply_relu

        normal_(self.conv_layer.weight.data, mean=0, std=0.02)

    def forward(self, x):
        x = self.conv_layer(x)
        x = self.instance_norm(x)

        if self.apply_relu:
            x = fn.relu(x)

        return x

class Upsample(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=3, stride=2, output_size=(128, 128), padding=1):
        super().__init__()
        self.conv_layer = nn.ConvTranspose2d(in_channels,
                                             out_channels,
                                             kernel_size=kernel_size,
                                             stride=stride,
                                             padding=padding)
        self.instance_norm = nn.InstanceNorm2d(out_channels)
        self.output_size = output_size

        normal_(self.conv_layer.weight.data, mean=0, std=0.02)

    def forward(self, x):
        x = self.conv_layer(x, output_size=self.output_size)
        x = self.instance_norm(x)
        x = fn.relu(x)
        return x

class Downsample(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=3, stride=2, padding=1):
        super().__init__()
        self.conv_layer = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding)
        self.instance_norm = nn.InstanceNorm2d(out_channels)

        normal_(self.conv_layer.weight.data, mean=0, std=0.02)

    def forward(self, x):
        x = self.conv_layer(x)
        x = self.instance_norm(x)
        x = fn.relu(x)
        return x

class StyleTransferNet(nn.Module):
    """Style Transfer Network Architecture
    """
    def __init__(self) -> None:
        super().__init__()
        self.reflection_padding = nn.ReflectionPad2d(40)
        self.network_block = nn.Sequential(ConvBlock(3, 32),
                                           Downsample(32, 64),
                                           Downsample(64, 128),
                                           ResidualBlock(128, 128),
                                           ResidualBlock(128, 128),
                                           ResidualBlock(128, 128),
                                           ResidualBlock(128, 128),
                                           ResidualBlock(128, 128),
                                           Upsample(128, 64, output_size=(128, 128)),
                                           Upsample(64, 32, output_size=(256, 256)),
                                           ConvBlock(32, 3, apply_relu=False))

    def forward(self, x):
        x = self.reflection_padding(x)
        x = self.network_block(x)
        x = torch.tanh(x)
        return x

class LossNet(nn.Module):
    """Creates the network to compute the style loss.
    This network outputs a dictionary with outputs values for style and content.
    """
    def __init__(self) -> None:
        super().__init__()
        vgg16 = models.vgg16(pretrained=True)

        self.layer1 = nn.Sequential(*list(vgg16.features.children())[:4])
        self.layer2 = nn.Sequential(*list(vgg16.features.children())[4:9])
        self.layer3 = nn.Sequential(*list(vgg16.features.children())[9:16])
        self.layer4 = nn.Sequential(*list(vgg16.features.children())[16:23])

    def forward(self, x):
        x_relu1 = self.layer1(x)
        x_relu2 = self.layer2(x_relu1)
        x_relu3 = self.layer3(x_relu2)
        x_relu4 = self.layer4(x_relu3)

        return {"style": [x_relu1, x_relu2, x_relu3, x_relu4], "content": [x_relu3]}

def get_estimator(batch_size=4,
                  epochs=2,
                  train_steps_per_epoch=None,
                  log_steps=100,
                  style_weight=5.0,
                  content_weight=1.0,
                  tv_weight=1e-4,
                  save_dir=tempfile.mkdtemp(),
                  style_img_path='Vassily_Kandinsky,_1913_-_Composition_7.jpg',
                  data_dir=None):
    train_data, _ = mscoco.load_data(root_dir=data_dir, load_bboxes=False, load_masks=False, load_captions=False)

    device = "cuda:0" if torch.cuda.is_available() else "cpu"
    style_img = cv2.imread(style_img_path)
    assert style_img is not None, "cannot load the style image, please go to the folder with style image"
    style_img = cv2.resize(style_img, (256, 256))
    style_img = (style_img.astype(np.float32) - 127.5) / 127.5

    pipeline = fe.Pipeline(
        train_data=train_data,
        batch_size=batch_size,
        ops=[
            ReadImage(inputs="image", outputs="image"),
            Normalize(inputs="image", outputs="image", mean=1.0, std=1.0, max_pixel_value=127.5),
            Resize(height=256, width=256, image_in="image", image_out="image"),
            LambdaOp(fn=lambda: style_img, outputs="style_image"),
            ChannelTranspose(inputs=["image", "style_image"], outputs=["image", "style_image"])
        ])

    model = fe.build(model_fn=StyleTransferNet,
                     model_name="style_transfer_net",
                     optimizer_fn=lambda x: torch.optim.Adam(x, lr=1e-3))

    network = fe.Network(ops=[
        ModelOp(inputs="image", model=model, outputs="image_out"),
        ExtractVGGFeatures(inputs="style_image", outputs="y_style", device=device),
        ExtractVGGFeatures(inputs="image", outputs="y_content", device=device),
        ExtractVGGFeatures(inputs="image_out", outputs="y_pred", device=device),
        StyleContentLoss(style_weight=style_weight,
                         content_weight=content_weight,
                         tv_weight=tv_weight,
                         inputs=('y_pred', 'y_style', 'y_content', 'image_out'),
                         outputs='loss'),
        UpdateOp(model=model, loss_name="loss")
    ])

    estimator = fe.Estimator(network=network,
                             pipeline=pipeline,
                             traces=ModelSaver(model=model, save_dir=save_dir, frequency=1),
                             epochs=epochs,
                             train_steps_per_epoch=train_steps_per_epoch,
                             log_steps=log_steps)

    return estimator

if __name__ == "__main__":
    est = get_estimator()
    est.fit()


# -*- coding: utf-8 -*-

import pickle
import numpy as np
import torch
import os
from torch.utils.data import Dataset

class NHPDataset(Dataset):
    '''
    Create Dataset for Neural Hawkey Process
    using financial data from original paper
    '''

    def __init__(self, file_path):
        self.event_type = []
        self.event_time = []

        with open(file_path, 'rb') as f:

            if 'dev' in file_path:
                seqs = pickle.load(f, encoding='latin1')['dev']
            elif 'train' in file_path:
                seqs = pickle.load(f, encoding='latin1')['train']
            elif 'test' in file_path:
                seqs = pickle.load(f, encoding='latin1')['test']

            for idx, seq in enumerate(seqs):
                self.event_type.append(torch.Tensor([int(event['type_event']) for event in seq]))
                self.event_time.append(torch.Tensor([float(event['time_since_start']) for event in seq]))

    def __len__(self):
        return len(self.event_type)

    def __getitem__(self, index):

        event_type = torch.LongTensor(self.event_type[index].long())[1:]
        event_time = torch.Tensor(self.event_time[index])
        #delta_time = torch.zeros_like(event_time)
        delta_time = event_time[1:] - event_time[:-1]

        return delta_time, event_type

def prepare_datasets(data_directory, train_size=0.6, val_size=0.2):
    """
    Prepare train, val and test datasets from several files
    with given proportions.
    Input:
        data_directory (str) - path to directory with data in .npy format
        train_size (float) - proportion of the dataset to include in the train split
        val_size (float) - proportion of the dataset to include in the val split
    Output:
        train_dsets (dict) - dictionary with train datasets and correspondig file names
        val_dsets (dict) - dictionary with val datasets and correspondig file names
        test_dsets (dict) - dictionary with test datasets and correspondig file names
    """

    datasets = {}
    for file in os.listdir(data_directory):
      if file.endswith(".npy"):
        datasets[file[:3]] = np.load(data_directory + file)

    train_dsets, val_dsets, test_dsets = {}, {}, {}
    for (name, dset) in datasets.items():

        train_part, val_part = int(train_size * len(dset)), int(val_size * len(dset))
        train_dsets[name] = LOBDataset(dset[:train_part])
        val_dsets[name]   = LOBDataset(dset[train_part:train_part + val_part])
        test_dsets[name]  = LOBDataset(dset[train_part + val_part:])

    return train_dsets, val_dsets, test_dsets

class LOBDataset(Dataset):
    """
    Wrapper for LOB dataset.
    """

    def __init__(self, data):
        """
        Input:
            data (B, S, 3) - batch of sequences
        """

        self.event_type = []
        self.event_time = []

        for seq in data:
            self.event_type.append(torch.Tensor(seq[:,2]))
            self.event_time.append(torch.Tensor(seq[:,0])/1000)

    def __len__(self):
        return len(self.event_type)

    def __getitem__(self, index):

        event_type = torch.LongTensor(self.event_type[index].long())
        event_time = torch.Tensor(self.event_time[index])

        return event_time, event_type

def collate_fn(batch, n_events=2):

      """
      While initializing LSTM we have it read a special beginning-of-stream (BOS) event (k0, t0),
      where k0 is a special event type and t0 is set to be 0
      (expanding the LSTM’s input dimensionality by one) see Appendix A.2
      Input:
          batch tuple((batch_size, seq_len)x2) - batch with event types sequence and corresponding inter-arrival times
      Output:
          pad_event_seq (batch_size, seq_len) - padded event types sequence
          pad_time_seq (batch_size, seq_len) - padded event times sequence
      """
      seq_time = torch.stack([sample[0] for sample in batch])
      seq_events = torch.stack([sample[1] for sample in batch])

      pad_event = torch.zeros_like(seq_events[:,0]) + n_events
      pad_time = torch.zeros_like(seq_time[:,0])
      pad_event_seq = torch.cat((pad_event.reshape(-1,1), seq_events), dim=1)
      pad_time_seq = torch.cat((pad_time.reshape(-1,1), seq_time), dim=1)

      return pad_event_seq.long(), pad_time_seq


from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
from sklearn.neighbors import KDTree
from scipy.spatial import Delaunay
from sklearn.model_selection import train_test_split
from vtk import vtkPolyDataReader, vtkXMLUnstructuredGridReader
from pandas import read_csv
from os.path import join
import pyvista as pv
import numpy as np

def get_xyz4apex(path, patient):
    reader = vtkXMLUnstructuredGridReader()
    reader.SetFileName(join(path, f"heart.colored.{patient:03}.vtu"))
    reader.Update()
    data = reader.GetOutput()
    apex_base = vtk_to_numpy(data.GetPointData().GetArray('Apex_base'))
    lv_colors = vtk_to_numpy(data.GetPointData().GetArray('LV colors'))

    apex0 = vtk_to_numpy(data.GetPoints().GetData())[np.where(apex_base == np.min(apex_base[np.where(lv_colors == 3)]))]
    apex1 = vtk_to_numpy(data.GetPoints().GetData())[np.where(apex_base == np.max(apex_base[np.where(lv_colors == 3)]))]

    xyz_apex0 = np.array([[np.average(apex0[:, 0]), np.average(apex0[:, 1]), np.average(apex0[:, 2])]])
    xyz_apex1 = np.array([[np.average(apex1[:, 0]), np.average(apex1[:, 1]), np.average(apex1[:, 2])]])

    return xyz_apex0, xyz_apex1

def get_bbox_bounds(path, patient):
    if "vtu" in path:
        path = join(path, f"heart.colored.{patient:03}.vtu")
    elif "vtk" in path:
        path = join(path, f"{patient}.vtk")
    model = pv.read(path)

    xmin, xmax, ymin, ymax, zmin, zmax = model.bounds

    min_xyz = np.array([[xmin, ymin, zmin]])
    max_xyz = np.array([[xmax, ymax, zmax]])

    return min_xyz, max_xyz

def extract_vtk_file(path, patient):
    reader = vtkPolyDataReader()
    reader.SetFileName(join(path, f"{patient}.vtk"))
    reader.Update()
    data = reader.GetOutput()
    heart_points = vtk_to_numpy(data.GetPoints().GetData())
    scalars = vtk_to_numpy(data.GetPointData().GetScalars())

    return data, heart_points, scalars

def kdtree_maker(points):
    if len(points) == 1:
        return KDTree(points[0], leaf_size=2)
    kdtrees = []
    for point_cloud in points:
        current_tree = None
        if point_cloud is not None and point_cloud.shape[0] != 0:
            current_tree = KDTree(point_cloud, leaf_size=2)
        kdtrees.append(current_tree)
    return kdtrees

def get_infarct_points(path, patient):
    infarct_data = read_csv(join(path, f"{patient}.csv"))[["x", "y", "z"]]
    infarct_points = np.array(infarct_data).astype("float32")
    return infarct_points

def get_infarct_mask(heart_points, infarct_points):
    heart_tree = kdtree_maker([heart_points])
    dist, ind = heart_tree.query(infarct_points)
    infarct_inds = [i for d, i in zip(dist, ind) if d < 1]
    infarct_mask = np.array([1 if i in infarct_inds else 0 for i in range(heart_points.shape[0])])

    return infarct_mask

def split_infarct_mask(infarct_mask, scalars, infarct=True):
    # return binary mask for [infarct / non-infarct] areas of the heart
    # 3 - left ventricular endocardium
    # 4 - epicardium
    # 6 - right ventricular endocardium
    if infarct:
        lv_mask = np.array(scalars == 3) & np.array(infarct_mask == 1)
        epi_mask = np.array(scalars == 4) & np.array(infarct_mask == 1)
        rv_mask = np.array(scalars == 6) & np.array(infarct_mask == 1)
    else:
        lv_mask = np.array(scalars == 3) & np.array(infarct_mask == 0)
        epi_mask = np.array(scalars == 4) & np.array(infarct_mask == 0)
        rv_mask = np.array(scalars == 6) & np.array(infarct_mask == 0)
    return lv_mask, epi_mask, rv_mask

def dists_inds_getting(points_cloud, tree_1, tree_2):
    # there are [infarct / non-infarct] points in [right / left] ven endo area -->
    # 1. find distances between ([right / left] ven endo points) and ([left / right] ven endo points)
    # 2. find distances between ([right / left] ven endo points) and (epi points)
    # 3. get minimal distances between 1st and 2nd steps
    # distances from 3rd step are distances [infarct / non-infarct] points for ven endo
    pc_dists_1, pc_inds_1 = np.array([]), np.array([])
    pc_dists_2, pc_inds_2 = np.array([]), np.array([])
    actual_dists = np.array([])
    if points_cloud.shape[0] != 0:
        if tree_1 is not None:
            pc_dists_1, pc_inds_1 = tree_1.query(points_cloud)
        if tree_2 is not None:
            pc_dists_2, pc_inds_2 = tree_2.query(points_cloud)
        actual_dists = np.minimum(pc_dists_1, pc_dists_2)

    # for left_ven points and right_ven kdtree returns indices of right_ven_points
    pc_only_inds_1 = np.array([i for d, i in zip(pc_dists_1, pc_inds_1) if d in actual_dists])
    pc_only_dists_1 = np.array([d for d, i in zip(pc_dists_1, pc_inds_1) if d in actual_dists])
    pc_only_inds_2 = np.array([i for d, i in zip(pc_dists_2, pc_inds_2) if d in actual_dists])
    pc_only_dists_2 = np.array([d for d, i in zip(pc_dists_2, pc_inds_2) if d in actual_dists])
    return pc_only_dists_1, pc_only_inds_1, pc_only_dists_2, pc_only_inds_2

def actual_distances(points_cloud, tree_1, tree_2):
    # there are [infarct / non-infarct] points in [right / left] ven endo area -->
    # 1. find distances between ([right / left] ven endo points) and ([left / right] ven endo points)
    # 2. find distances between ([right / left] ven endo points) and (epi points)
    # 3. get minimal distances between 1st and 2nd steps
    # distances from 3rd step are distances [infarct / non-infarct] points for ven endo
    pc_dists_1, _ = np.array([]), np.array([])
    pc_dists_2, _ = np.array([]), np.array([])
    actual_dists = np.array([])
    if points_cloud.shape[0] != 0:
        if tree_1 is not None:
            pc_dists_1, _ = tree_1.query(points_cloud)
        if tree_2 is not None:
            pc_dists_2, _ = tree_2.query(points_cloud)
        actual_dists = np.minimum(pc_dists_1, pc_dists_2)

    return actual_dists


import os
import pybullet as p
import numpy as np
from scipy.spatial.transform import Rotation as R
import xml.etree.ElementTree as ET

urdf = 'models/hook/Hook_60/base.urdf'
assert os.path.exists(urdf), f'{urdf} not exists'

physics_client_id = p.connect(p.GUI)
p.resetDebugVisualizerCamera(
    cameraDistance=0.3,
    cameraYaw=120,
    cameraPitch=0,
    cameraTargetPosition=[0.0, 0.0, 0.0]
)

tree = ET.parse(urdf)
root = tree.getroot()
center = np.array(
    [
        float(i) for i in root[0].find(
            "inertial"
        ).find(
            "origin"
        ).attrib['xyz'].split(' ')
    ]
)

rot = [0, np.pi / 2, 0]
matrix = R.from_rotvec(rot).as_matrix()
quat = R.from_rotvec(rot).as_quat()
quat = list(quat)

offset = matrix @ center

obj_id = p.loadURDF(urdf, [0, 0, 0], quat)
pos, rot = p.getBasePositionAndOrientation(obj_id)
pose = list(pos) + list(rot)
print(pose)

obj_id = p.loadURDF(urdf, [0, 0, 0], quat)
p.resetBasePositionAndOrientation(obj_id, [0, 0, 0], quat)
pos, rot = p.getBasePositionAndOrientation(obj_id)
pose = list(pos) + list(rot)
print(pose)

pose = np.asarray(pose)
pose[:3] = pose[:3] + offset
print(list(pose))

while True:
    # key callback
    keys = p.getKeyboardEvents()
    if ord('q') in keys and keys[ord('q')] & (p.KEY_WAS_TRIGGERED | p.KEY_IS_DOWN):
        break


from setuptools import setup
import os

with open(
        os.path.join(os.path.dirname(__file__), 'eagleSqlTools', 'VERSION')
) as version_file:
    version = version_file.read().strip()

setup(
    name='eagleSqlTools',
    version=version,
    description='Utilities for accessing EAGLE public database.',
    url='',
    author='Kyle Oman',
    author_email='koman@astro.rug.nl',
    license='GNU GPL v3',
    packages=['eagleSqlTools'],
    install_requires=['numpy'],
    include_package_data=True,
    zip_safe=False
)


import pygame
from pygame.math import Vector2

pygame.init()
pygame.display.set_caption("statue shooter")
screen = pygame.display.set_mode((800, 800))
screen.fill((0,0,0))
clock = pygame.time.Clock()
gameover = False

#CONSTANTS
LEFT=0
RIGHT=1
UP = 2
DOWN = 3

#player variables
xpos = 500 #xpos of player
ypos = 200 #ypos of player
vx = 0 #x velocity of player
vy = 0 #y velocity of player
keys = [False, False, False, False] #this list holds whether each key has been pressed

#timer for launching projectile:
timer = 0

#---------projectile class---------------------------------------------------------
class projectile():
    def __init__(self):

        self.pos = Vector2(200,500)
        self.isAlive = False
        self.speed = 10

    def draw(self):
        pygame.draw.circle(screen, (200, 200, 0), (self.pos[0], self.pos[1]), 10)

    def move(self):
        self.isAlive = True

    def update(self, start, end):

        #bounds check: reset if you cross the edge of the game screen
        if self.pos[0] < 0 or self.pos[0] > 800 or self.pos[1] < 0 or self.pos[1] > 800:
            self.isAlive = False
            self.pos = (200, 500)

        self.direction = Vector2(end) - Vector2(start) #i want to write this out to show the math

        #to normalize a vector means to strip the magnitude and only look at the length
        if self.isAlive:
            self.pos += self.direction.normalize() * self.speed #This too- let's show the math

#---------end projectile class---------------------------------------------------------

p1 = projectile()

while not gameover:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameover = True

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                keys[LEFT]=True
            elif event.key == pygame.K_RIGHT:
                keys[RIGHT]=True
            elif event.key == pygame.K_UP:
                keys[UP]=True
            elif event.key == pygame.K_DOWN:
                keys[DOWN]=True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                keys[LEFT]=False
            elif event.key == pygame.K_RIGHT:
                keys[RIGHT]=False
            elif event.key == pygame.K_UP:
                keys[UP]=False
            elif event.key == pygame.K_DOWN:
                keys[DOWN]=False

    if keys[LEFT]==True:
        vx=-5
    elif keys[RIGHT] == True:
        vx = 5
    else:
        vx = 0

    if keys[UP]==True:
        vy=-5
    elif keys[DOWN] == True:
        vy = 5
    else:
        vy = 0

    timer+=1
    if timer > 100:
        p1.move()
        timer = 0
        print("shoot")

    xpos+=vx
    ypos+=vy
    p1.update((200, 500), (xpos, ypos))

    # RENDER--------------------------------------------------------------------------------

    screen.fill((0,0,0))

    pygame.draw.rect(screen, (100, 200, 100), (xpos, ypos, 30, 30)) #player

    pygame.draw.rect(screen, (100,100,100), (200, 500, 50,50)) #statue

    p1.draw()

    pygame.display.flip()


import os
import argparse
import joblib

import numpy as np
import scipy.spatial.distance as spd
from sklearn.metrics import f1_score, accuracy_score

from utils.openmax import fit_weibull, openmax

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--distance_type', default='eucos')
    parser.add_argument('--euc_scale', type=float, default=5e-3)
    parser.add_argument('--alpha', type=int, default=5)
    parser.add_argument('--tailsize', type=int, default=20)
    parser.add_argument('--threshold', type=float, default=0.2)
    parser.add_argument('--save', default='None', help='Directory to save the results')
    parser.add_argument('--score_path', default='None')
    opt = parser.parse_args()

    categories = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]

    means = joblib.load(os.path.join(opt.save, "mavs.joblib"))
    dists = joblib.load(os.path.join(opt.save, "dists.joblib"))
    scores, labels = joblib.load(opt.score_path)

    weibull_model = fit_weibull(means, dists, categories, opt.tailsize, opt.distance_type)
    pred_y, pred_y_o = [], []
    for score in scores:
        so, ss = openmax(weibull_model, categories, score,
                         opt.euc_scale, opt.alpha, opt.distance_type)
        pred_y.append(np.argmax(ss) if np.max(ss) >= opt.threshold else 10)
        pred_y_o.append(np.argmax(so) if np.max(so) >= opt.threshold else 10)

    print("Open Set evaluation:")
    print("Both:")
    print("Accuracy: softmax={}, openmax={}".format(
        accuracy_score(labels, pred_y), accuracy_score(labels, pred_y_o)))
    print("F1 score: softmax={}, openmax={}".format(
        f1_score(labels, pred_y, average="macro"), f1_score(labels, pred_y_o, average="macro")))

    print("CIFAR-10 only:")
    print("Accuracy: softmax={}, openmax={}".format(
        accuracy_score(labels[:10000], pred_y[:10000]), accuracy_score(labels[:10000], pred_y_o[:10000])))
    print("F1 score: softmax={}, openmax={}".format(
        f1_score(labels[:10000], pred_y[:10000], average="macro"),
        f1_score(labels[:10000], pred_y_o[:10000], average="macro")))

    print("Closed Set evaluation:")
    pred_y = np.argmax(scores, axis=2)[:, 0]
    print("Accuracy: softmax={}".format(accuracy_score(labels[:10000], pred_y[:10000])))
    print("F1 score: softmax={}".format(f1_score(labels[:10000], pred_y[:10000], average="macro")))

if __name__ == "__main__":
    main()


from flask import Flask, request, jsonify
from bson import json_util
from pymongo import MongoClient
from mongo import read_data, delete_data, update_general
from bson import ObjectId
from endpoints import delete, insert, complete_list, update, complete_auth

app = Flask("quoteapi")

@app.route('/') #Homepage
def home():
    return "Welcome! This site is a prototype API for famous quotes :)"

@app.route("/Data") #to obtain all the information about authors, categories and phrases from our entire database
def data():
    read = complete_list()
    return jsonify(read)

@app.route("/AuthorId") #to obtain all the authors of the API
def data_aut():
    read = complete_auth()
    return json_util.dumps(read)

@app.route("/Authors/<Collection>") #to get all the authors contained in a given collection
def all_names(Collection):
    aut = read_data({}, {"Author":1, "_id": 0}, f"{Collection}")
    return json_util.dumps(aut)

@app.route("/Quotes/<Collection>") #to get all the phrases contained in a given collection
def all_quotes(Collection):
    aut = read_data({}, {"Quote":1, "_id": 0}, f"{Collection}")
    return json_util.dumps(aut)

##DELETE objeos en una colleccion
@app.route("/<collection>/delete") #Delete a certain author and his / her quote from the biology collection
def delete_prueba(collection):
    args = dict(request.args)
    x = json_util.dumps(delete(args, collection))
    update_general()
    return x

@app.route("/<collection>/new") # Insert a new author and his citation from the biology collection
def insert_new(collection):
    args = dict(request.args)
    x = json_util.dumps(insert(args, collection))
    update_general()
    return x

@app.route("/<collection>/update")
def update_lit(collection):
   args = dict(request.args)
   x = json_util.dumps(update(args, collection))
   update_general()
   return x

app.run(debug=True)


# -*- coding: utf-8 -*-

from .key import Key, PrimaryKey
from .item import Item, ItemSize
from .storage import Store
from collections import defaultdict, namedtuple
from threading import Timer, Lock
from ddbmock import config
from ddbmock.errors import ValidationException, LimitExceededException, ResourceInUseException
import time, copy, datetime

# All validations are performed on *incomming* data => already done :)

# items: array
# size: ItemSize
Results = namedtuple('Results', ['items', 'size', 'last_key', 'scanned'])

class Table(object):
    def __init__(self, name, rt, wt, hash_key, range_key, status='CREATING'):
        self.name = name
        self.rt = rt
        self.wt = wt
        self.hash_key = hash_key
        self.range_key = range_key
        self.status = status

        self.store = Store(name)
        self.write_lock = Lock()

        self.creation_time = time.time()
        self.last_increase_time = 0
        self.last_decrease_time = 0
        self.count = 0

        Timer(config.DELAY_CREATING, self.activate).start()

    def delete(self, callback):
        """
        Delete is really done when the timeout is exhausted, so we need a callback
        for this
        In Python, this table is not actually destroyed until all references are
        dead. So, we shut down the links with the databases but not the table itself
        until all requests are done. This is the reason why the lock is not acquired
        here. Indeed, this would probably dead-lock the server !

        :ivar callback: real delete function
        """
        if self.status != "ACTIVE":
            raise ResourceInUseException("Table {} is in {} state. Can not UPDATE.".format(self.name, self.status))

        self.status = "DELETING"

        Timer(config.DELAY_DELETING, callback, [self.name]).start()

    def activate(self):
        self.status = "ACTIVE"

    def update_throughput(self, rt, wt):
        if self.status != "ACTIVE":
            raise ResourceInUseException("Table {} is in {} state. Can not UPDATE.".format(self.name, self.status))

        # is decrease ?
        if self.rt > rt or self.wt > wt:
            current_time = time.time()
            current_date = datetime.date.fromtimestamp(current_time)
            last_decrease = datetime.date.fromtimestamp(self.last_decrease_time)
            if (current_date - last_decrease).days < config.MIN_TP_DEC_INTERVAL:
                last = datetime.datetime.fromtimestamp(self.last_decrease_time)
                current = datetime.datetime.fromtimestamp(current_time)
                raise LimitExceededException("Subscriber limit exceeded: Provisioned throughput can be decreased only once within the {} day. Last decrease time: Tuesday, {}. Request time: {}".format(config.MIN_TP_DEC_INTERVAL, last, current))
            self.last_decrease_time = current_time

        # is increase ?
        if self.rt < rt or self.wt < wt:
            if (rt - self.rt)/float(self.rt)*100 > config.MAX_TP_INC_CHANGE:
                raise LimitExceededException('Requested provisioned throughput change is not allowed. The ReadCapacityUnits change must be at most {} percent of current value. Current ReadCapacityUnits provisioned for the table: {}. Requested ReadCapacityUnits: {}.'.format(config.MAX_TP_INC_CHANGE, self.rt, rt))
            if (wt - self.wt)/float(self.wt)*100 > config.MAX_TP_INC_CHANGE:
                raise LimitExceededException('Requested provisioned throughput change is not allowed. The WriteCapacityUnits change must be at most {} percent of current value. Current WriteCapacityUnits provisioned for the table: {}. Requested WriteCapacityUnits: {}.'.format(config.MAX_TP_INC_CHANGE, self.wt, wt))
            self.last_increase_time = time.time()

        # real work
        self.status = "UPDATING"

        self.rt = rt
        self.wt = wt

        Timer(config.DELAY_UPDATING, self.activate).start()

    def delete_item(self, key, expected):
        key = Item(key)
        hash_key = key.read_key(self.hash_key, u'HashKeyElement')
        range_key = key.read_key(self.range_key, u'RangeKeyElement')

        with self.write_lock:
            try:
                old = self.store[hash_key, range_key]
            except KeyError:
                return Item()

            old.assert_match_expected(expected)
            del self.store[hash_key, range_key]

        self.count -= 1
        return old

    def update_item(self, key, actions, expected):
        key = Item(key)
        hash_key = key.read_key(self.hash_key, u'HashKeyElement', max_size=config.MAX_HK_SIZE)
        range_key = key.read_key(self.range_key, u'RangeKeyElement', max_size=config.MAX_RK_SIZE)

        with self.write_lock:
            # Need a deep copy as we will *modify* it
            try:
                old = self.store[hash_key, range_key]
                new = copy.deepcopy(old)
                old.assert_match_expected(expected)
            except KeyError:
                # Item was not in the DB yet
                old = Item()
                new = Item()
                self.count += 1
                # append the keys
                new[self.hash_key.name] = key['HashKeyElement']
                if self.range_key is not None:
                    new[self.range_key.name] = key['RangeKeyElement']

            # Make sure we are not altering a key
            if self.hash_key.name in actions:
                raise ValidationException("UpdateItem can not alter the hash_key.")
            if self.range_key is not None and self.range_key.name in actions:
                raise ValidationException("UpdateItem can not alter the range_key.")

            new.apply_actions(actions)
            self.store[hash_key, range_key] = new

            size = new.get_size()
            if size > config.MAX_ITEM_SIZE:
                self.store[hash_key, range_key] = old  # roll back
                raise ValidationException("Items must be smaller than {} bytes. Got {} after applying update".format(config.MAX_ITEM_SIZE, size))

        return old, new

    def put(self, item, expected):
        item = Item(item)

        if item.get_size() > config.MAX_ITEM_SIZE:
            raise ValidationException("Items must be smaller than {} bytes. Got {}".format(config.MAX_ITEM_SIZE, item.get_size()))

        hash_key = item.read_key(self.hash_key, max_size=config.MAX_HK_SIZE)
        range_key = item.read_key(self.range_key, max_size=config.MAX_RK_SIZE)

        with self.write_lock:
            try:
                old = self.store[hash_key, range_key]
                old.assert_match_expected(expected)
            except KeyError:
                # Item was not in the DB yet
                self.count += 1
                old = Item()

            self.store[hash_key, range_key] = item
            new = copy.deepcopy(item)

        return old, new

    def get(self, key, fields):
        key = Item(key)
        hash_key = key.read_key(self.hash_key, u'HashKeyElement')
        range_key = key.read_key(self.range_key, u'RangeKeyElement')

        if self.range_key is None and u'RangeKeyElement' in key:
            raise ValidationException("Table {} has no range_key".format(self.name))

        try:
            item = self.store[hash_key, range_key]
            return item.filter(fields)
        except KeyError:
            # Item was not in the DB yet
            return None

    def query(self, hash_key, rk_condition, fields, start, reverse, limit):
        """Scans all items at hash_key and return matches as well as last
        evaluated key if more than 1MB was scanned.

        :ivar hash_key: Element describing the hash_key, no type checkeing performed
        :ivar rk_condition: Condition which must be matched by the range_key. If None, all is returned.
        :ivar fields: return only these fields is applicable
        :ivar start: key structure. where to start iteration
        :ivar reverse: wether to scan the collection backward
        :ivar limit: max number of items to parse in this batch
        :return: Results(results, cumulated_size, last_key)
        """
        #FIXME: naive implementation
        #FIXME: what is an item disappears during the operation ?
        #TODO:
        # - size limit

        hash_value = self.hash_key.read(hash_key)
        rk_name = self.range_key.name
        size = ItemSize(0)
        good_item_count = 0
        results = []
        lek = None

        if start and start['HashKeyElement'] != hash_key:
            raise ValidationException("'HashKeyElement' element of 'ExclusiveStartKey' must be the same as the hash_key. Expected {}, got {}".format(hash_key, start['HashKeyElement']))

        data = self.store[hash_value, None]

        keys = sorted(data.keys())

        if reverse:
            keys.reverse()

        if start:
            first_key = self.range_key.read(start['RangeKeyElement'])
            index = keys.index(first_key) + 1  # May raise ValueError but that's OK
            keys = keys[index:]

        for key in keys:
            item = data[key]

            if item.field_match(rk_name, rk_condition):
                good_item_count += 1
                size += item.get_size()
                results.append(item.filter(fields))

            if good_item_count == limit:
                lek = {
                    u'HashKeyElement': hash_key,
                    u'RangeKeyElement': item[rk_name],
                }
                break

        return Results(results, size, lek, -1)

    def scan(self, scan_conditions, fields, start, limit):
        """Scans a whole table, no matter the structure, and return matches as
        well as the the last_evaluated key if applicable and the actually scanned
        item count.

        :ivar scan_conditions: Dict of key:conditions to match items against. If None, all is returned.
        :ivar fields: return only these fields is applicable
        :ivar start: key structure. where to start iteration
        :ivar limit: max number of items to parse in this batch
        :return: results, cumulated_scanned_size, last_key
        """
        #FIXME: naive implementation (too)
        #TODO:
        # - reverse
        # - esk
        # - limit
        # - size limit
        # - last evaluated key

        size = ItemSize(0)
        scanned = 0
        results = []

        for item in self.store:
            size += item.get_size()
            scanned += 1
            if item.match(scan_conditions):
                results.append(item.filter(fields))

        return Results(results, size, None, scanned)

    @classmethod
    def from_dict(cls, data):
        hash_key = PrimaryKey.from_dict(data[u'KeySchema'][u'HashKeyElement'])
        range_key = None
        if u'RangeKeyElement' in data[u'KeySchema']:
            range_key = PrimaryKey.from_dict(data[u'KeySchema'][u'RangeKeyElement'])

        return cls( data[u'TableName'],
                    data[u'ProvisionedThroughput'][u'ReadCapacityUnits'],
                    data[u'ProvisionedThroughput'][u'WriteCapacityUnits'],
                    hash_key,
                    range_key,
                  )

    def get_size(self):
        # TODO: update size only every 6 hours
        size = 0

        for item in self.store:
            size += item.get_size().with_indexing_overhead()

        return size

    def to_dict(self, verbose=True):
        """Serialize table metadata for the describe table method. ItemCount and
        TableSizeBytes are accurate but highly depends on CPython > 2.6. Do not
        rely on it to project the actual size on a real DynamoDB implementation.
        """

        ret = {
            "CreationDateTime": self.creation_time,
            "KeySchema": {
                "HashKeyElement": self.hash_key.to_dict(),
            },
            "ProvisionedThroughput": {
                "ReadCapacityUnits": self.rt,
                "WriteCapacityUnits": self.wt,
            },
            "TableName": self.name,
            "TableStatus": self.status
        }

        if verbose:
            ret[u'ItemCount'] = self.count
            ret[u'TableSizeBytes'] = self.get_size()

        if self.last_increase_time:
            ret[u'ProvisionedThroughput'][u'LastIncreaseDateTime'] = self.last_increase_time
        if self.last_decrease_time:
            ret[u'ProvisionedThroughput'][u'LastDecreaseDateTime'] = self.last_decrease_time

        if self.range_key is not None:
            ret[u'KeySchema'][u'RangeKeyElement'] = self.range_key.to_dict()

        return ret

    # these 2 functions helps to persist table schema (If store supports it)
    # please note that only the schema is persisted, not the state
    def __getstate__(self):
        return (
            self.name,
            self.rt,
            self.wt,
            self.hash_key,
            self.range_key,
            'ACTIVE',
        )

    def __setstate__(self, state):
        self.__init__(*state)  # quick and dirty (tm), but it does the job


import csv
import matplotlib.pyplot as plt

file = open("data.csv")
csvreader = csv.reader(file)
header = next(csvreader)
#print(header)
data = []
for row in csvreader:
    data.append(row)
#print(data)
file.close()
#step 1---------------------------------------------------------------
poll_names = []
names = []

for i in range(len(data)):#it looping to data
  names.append([data[i][0]])#its appending i in data
for i in range(len(names)):#its looping to names
  if names[i] not in poll_names:#the name i is not in poll name
    poll_names.append(names[i])#is appending i in poll name
print()#it prints it
print(poll_names)#it prints it

#step 2--------------------------------------------------------------------------

polls_dict = {}#printing dictionary
for i in range(len(poll_names)):#loop to poll name in i
  polls_dict.update({poll_names[i][0]:[]})#its adding [] at the end of the line
print(polls_dict)#its printing
#step 3----------------------------------------------------------------------------
for i in range(len(data)):#loops to poll dict
  for key in polls_dict:#looping to data
    if data[i][0] == key:#data
      values = data[i][1:]#its value in i
      polls_dict[key].append(values)#its appending value in dict

print(polls_dict)#its printing
#step4------------------------------------------------------------------------------
for key in polls_dict:
  polls_dict[key].sort()
  holder = []#empty list called holder
  for i in range(len(polls_dict[key])): #loop inse poll dict for key i
    if polls_dict[key][i][0][1].isnumeric(): #find if the key i inside polls dict numeric
      holder.append(polls_dict[key][i])#if is numeric add holder to polls dict
  for j in range(len(holder) ):#new for loop but inside the holder
    if holder[j] in polls_dict[key]:#check if the value inside holder is in polls dict
      polls_dict[key].remove(holder[j])#if is inside remove
  for h in range(len(holder) ):#new for loop for holder
    polls_dict[key].append(holder[h])#add polls dict to holder
print(polls_dict)
#---------------------------------------------------------------------------------
#step 6
for key in polls_dict:#for loop for key inside polls dict
  plt.subplot(2,1,1)
  plt.title('Favorability')#add title to the output
  for i in range(len(polls_dict[key])):#for loop inside polls dict
    plt.bar(polls_dict[key][i][0],polls_dict[key][i][1],color='blue')#define the color
  plt.xticks(rotation=90)#rotate the ticks in 90 degrees
  plt.grid()
  plt.ylabel('percentage of population')#tittle of y label
  plt.subplot(2,1,1)
  plt.title('unfavorability')#title of another output
  for i in range(len(polls_dict[key])):#for loop inside pol dict
    plt.bar(polls_dict[key][i][0],polls_dict[key][i][2],color='red')#difine the color
plt.xticks(rotation=90)#rotate the ticks in 90 degrees
plt.grid()
plt.ylabel('percentage of population')
plt.suptitle(key)
plt.show(block=False)
plt.pause(5)
plt.close()


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

import xlrd
import codecs
from lxml import etree

def read_xls(filename):
    data = xlrd.open_workbook(filename)
    table = data.sheets()[0]
    c = []
    for i in range(table.nrows):
        c.append([int(j) for j in table.row_values(i)[0:]])
    return c

def save_xml(data):
    output = codecs.open('numbers.xml', 'w', 'utf-8')
    root = etree.Element('root')
    numbers_xml = etree.ElementTree(root)
    numbers = etree.SubElement(root, 'numbers')
    numbers.append(etree.Comment(u'数字信息\n'))
    numbers.text = str(data)
    output.write(etree.tounicode(numbers_xml.getroot()))
    output.close()

if __name__ == '__main__':
    file = 'numbers.xls'
    a = read_xls(file)
    save_xml(a)


def lengthOfLongestSubstring(s):
    """
    :type s: str
    :rtype: int
    """
    maxlength = 0
    if len(s) == 0:
        return 0
    if len(s) == 1:
        return 1
    for initIndex in range(0,len(s)):
        length = 0
        for secondIndex in range(initIndex,len(s)):
            if s[secondIndex] not in s[initIndex:secondIndex]:
                length += 1
            else:
                break
        maxlength = max(maxlength,length)
    return (maxlength)

s =  "bbbb"
#output = 3

x = lengthOfLongestSubstring(s)
print(x)


#!/usr/bin/env python
'''
    license_usage.py - Caculate Deadline usage stats from license file

    Usage:
        python license_usage.py Thinkbox.log

    Note that this is untested for accuracy, and should be inaccurate for logs
    which ran over DST changes.
'''

import sys
import time
from datetime import datetime, timedelta, MINYEAR

class checkout_tracker():
    def __init__(self):
        self.duration = timedelta(0)
        self.checkout_time = []

    def check_in(self, time):
        start_time = self.checkout_time.pop()
        self.duration += time - start_time

    def check_in_remaining(self, time):
        ''' Calculate the duration for what's left '''
        while len(self.checkout_time) > 0:
            self.check_in(time)

    def check_out(self, time):
        self.checkout_time.append(time)

    def __unicode__(self):
        return str(self.duration)

    def __str__(self):
        return self.__unicode__()

def main():
    time_total = datetime.min
    time_current = datetime.min
    time_last = datetime.min
    time_start = datetime.min

    machines = {}

    try:
        file = open(sys.argv[1])
    except IOError:
        print("Unable to open file.")
        sys.exit(2)
    except IndexError:
        print("No log file given.")
        sys.exit(1)

    for line in process_file(file):
        (timestamp, vendor, state, feature, key) = line.split()

        time_current = datetime.strptime(timestamp, "%H:%M:%S")

        if time_total == datetime.min:
            time_total = time_current
            time_start = time_current
        else:
            # Dealing with the clock rolling over to a new day...
            time_total += account_time(time_last, time_current)

        time_last = time_current

        process_element(machines, time_total, vendor, state, feature, key)

    # Tabulate everything, check in whatever was still out, etc
    total_duration = timedelta(0)
    for machine, duration in machines.items():
        duration.check_in_remaining(time_total)
        total_duration += duration.duration

        print("{0:<40}{1}".format(machine, duration))

    total_runtime = time_total - time_start

    print("-" * 50)
    print("{0:<40}{1}".format("Total used hours", total_duration))
    print("{0:<40}{1}".format("Total server runtime", total_runtime))
    print()
    print("These values may not be accurate (especially across time changes).")

    file.close()

def account_time(old, new):
    ''' Do the math if the time rolled over '''
    if new < old:
        # Time rolled over
        duration = timedelta(days=1)
        duration -= old - new
    else:
        duration = new - old

    return duration

def process_file(file):
    ''' Weed out unwanted lines and pass them on to tracking '''
    for line in file:
        if "OUT:" in line or "IN:" in line:
            yield line.strip()

def process_element(machines, timestamp, vendor, state, feature, key):
    if feature != '"deadline"':
        return

    if vendor != '(thinkbox)':
        return

    if state == "OUT:":
        if key in machines:
            machines[key].check_out(timestamp)
        else:
            new_tracker = checkout_tracker()
            new_tracker.check_out(timestamp)
            machines[key] = new_tracker
    elif state == "IN:":
        if key in machines:
            machines[key].check_in(timestamp)
        else:
            print("Unexpected checkin!")
    else:
        print("Unexpected state!")

main()


import tensorflow as tf
from tensorflow import keras
import tensorflow_datasets as tfds

from tensorflow.keras import layers
import numpy as np
from tensorflow.keras.losses import Loss
from cal_error import ExpectedCalibrationError
import time
from datetime import datetime
from tensorflow.keras.applications import *
from tqdm import tqdm
# from train_ece_shifted import train_attempt
from train_loop import train_attempt

from helper import load_cifar_c

verbose = False

#Load imagenet
imagenet_path = "/home/thlarsen/tensorflow_datasets/imagenet/"
batch_size = 128

# Prepare the training dataset.
imagenet = tfds.image_classification.Imagenet2012(imagenet_path)
# Prepare the training dataset.
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.shuffle(buffer_size=1024).batch(batch_size)

# Prepare the validation dataset.
val_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))
val_dataset = val_dataset.batch(batch_size)

# data, labels, sev = load_cifar_c('contrast')
# train_dataset_shift = tf.data.Dataset.from_tensor_slices((data, labels))
# train_dataset_shift = train_dataset_shift.batch(batch_size)

def main():

    # weights = [10 **i for i in range(-3, 1)]
    # learning_rates = [10**i for i in range(-5, -2)]

    weights = [0, 10**-2, .1]
    # learning_rates = [10**-3, 10**-2]
    # weights = [.1]
    learning_rates = [10**-4]

    overall_results = [['l/w']+ weights]
    prefix = '/home/thlarsen/ood_detection/learn_uncertainty/'
    epochs = 60

    with tqdm(total=len(learning_rates) * len(weights)) as pbar:
        for lr in learning_rates:
            overall_results.append([lr])
            for w in weights:
                model = EfficientNetB2(weights=None, classes=10, input_shape=input_shape, classifier_activation=None)
                model_save_path = f'{prefix}saved_weights/imagenet/cal(lr={lr})(w={w})'
                graph_path = f'{prefix}training_plots/imagenet/cal(lr={lr})(w={w}).png'
                acc, ece = train_attempt(model, train_dataset, train_dataset_shift, val_dataset,
                                        lr=lr, w=w, epochs=epochs,
                                        graph_path=graph_path,
                                        model_save_path=model_save_path,
                                        verbose=True)
                overall_results[-1].append((acc, ece))
                pbar.update(1)

    #array nonsense to make it print the array in a readable format
    s = [[str(e) for e in row] for row in overall_results]
    lens = [max(map(len, col)) for col in zip(*s)]
    fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
    table = [fmt.format(*row) for row in s]
    print('\n'.join(table))
if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Wed Apr  6 12:38:20 2022

@author: guswl
"""

n = int(input())
for i in range(n):
    num, s = input().split()
    text = ''
    for i in s:
        text += int(num)*i
    print(text)