#Create Sidebar

from Tkinter import *

class SideBar(Frame):
    """The sidebar contains the Library and Component Attribute frames."""
    def __init__(self, master):
        Frame.__init__(self, master)

        self._master = master

        #set default width
        self._width = 300

        # sidebar has a handle on the right which allows the user to resize it
        self._handle = Frame(self, bd = 2, relief = RAISED,
                             cursor = 'sb_h_double_arrow', bg = 'white',
                             width = 4)
        self._handle.pack(side = RIGHT, anchor = E, fill = Y)
        self._handle.bind('<B1-Motion>', self._resize)

        self._libraryFrame = LibraryFrame(self, width = self._width,
                          text = "Project Library")
        self._compAttrFrame = CompAttrFrame(self, width = self._width,
                          text = "foobar")

    def _resize(self, e):
        self._width = (e.x_root - self.winfo_rootx())
        self._libraryFrame.resize(self._width)
        self._compAttrFrame.resize(self._width)

class LibraryFrame(LabelFrame):
    """ A place to put loaded library information """
    def __init__(self, master, **options):
        LabelFrame.__init__(self, master, **options)
        self.pack(fill = Y, expand = 1)

        self._body = Canvas(self, bg = 'green', width = self['width'])
        self._body.pack()

    def resize(self, newWidth):
        self['width'] = newWidth
        self._body['width'] = newWidth

class CompAttrFrame(LabelFrame):
    """ A place to put selected component attribute information. """
    def __init__(self, master, **options):
        LabelFrame.__init__(self, master, **options)
        self.pack(fill = Y, expand = 1)

        self._body = Canvas(self, bg = 'red', width = self['width'])
        self._body.pack()

    def resize(self, newWidth):
        self['width'] = newWidth
        self._body['width'] = newWidth

def test(master):
    master.minsize(700,480)
    master.geometry("800x600")
    SideBar(master).pack(side = LEFT, fill = Y)

if __name__ == '__main__':
    root = Tk()
    test(root)
    root.mainloop()


"""Convert CSV string to Python dict using ../../tapshex/template.py."""

# pylint: disable=unused-import,unused-argument,import-error
import pytest
from tapshex.classes import Shape, StatementTemplate
from tapshex.config import tapshex_config
from tapshex.csvreader import dctap_csvreader

NONDEFAULT_CONFIGYAML_STR = """
prefixes:
    "my:":      "http://my.example/#"
    "ex:":      "http://ex.example/#"
"""

@pytest.mark.skip(reason="TODO: 42 Negative Triple Constraints")
def test_csv_to_dict(capsys):
    """From CSV to Python dict (actual_dict)."""
    config_dict = tapshex_config(nondefault_configyaml_str=NONDEFAULT_CONFIGYAML_STR)
    # fmt: off
    #
    csvfile_str = """\
    shapeID               , propertyID   , valueConstraint           , valueConstraintType , minoccurs , maxoccurs
    my:SolitaryIssueShape , ex:state     , ex:unassigned ex:assigned , picklist            ,           ,
                          , ex:component ,                           ,                     , 0         , 0
    """
    #
    # fmt: on
    expected_dict = {
        "namespaces": {
            "my:": "http://my.example/#",
            "ex:": "http://ex.example/#",
        },
        "shapes": [
            {
                "shapeID": "my:SolitaryIssueShape",
                "statement_templates": [
                    {
                        "propertyID": "ex:state",
                        "valueConstraint": ["ex:unassigned", "ex:assigned"],
                        "valueConstraintType": "picklist",
                        "_dot": False,
                    },
                    {
                        "propertyID": "ex:component",
                        "minoccurs": "0",
                        "maxoccurs": "0",
                        "_dot": True,
                    }
                ],
            }
        ],
        "warnings": {
            "my:SolitaryIssueShape": {}
        },
    }
    # pylint: disable=invalid-name
    actual_dict = dctap_csvreader(
        csvfile_str=csvfile_str,
        config_dict=config_dict,
        shape_class=Shape,
        state_class=StatementTemplate,
    )
    assert isinstance(actual_dict, dict)
    assert isinstance(actual_dict["namespaces"], dict)
    assert actual_dict["namespaces"] == expected_dict["namespaces"]
    assert actual_dict["warnings"] == expected_dict["warnings"]
    assert actual_dict["shapes"][0]["statement_templates"][0].keys() == expected_dict["shapes"][0]["statement_templates"][0].keys()
    assert actual_dict["shapes"][0]["statement_templates"][1] == expected_dict["shapes"][0]["statement_templates"][1]
    # assert actual_dict == expected_dict

    # with capsys.disabled():
    #     from pprint import pprint
    #     # pprint(config_dict)
    #     # pprint(csvfile_str)
    #     # pprint(config_dict["prefixes"])
    #     print()
    #     pprint(expected_dict)
    #     print()
    #     pprint(actual_dict)


from telegram import Update, error
from telegram.ext import (
    CallbackContext,
    ConversationHandler,
    JobQueue,
    DispatcherHandlerStop,
)
from constants import Messages, ConversationsStates
from db import getUsers
from utils import chunk

def _sendMessages(context: CallbackContext):
    job = context.job
    for user in job.context["users"]:
        try:
            context.bot.send_message(user["telegram_id"], job.context["message"])
        except:
            pass

def start(update: Update, context: CallbackContext):
    if context.user_data["mode"] != "admin":
        return
    context.bot.send_message(update.effective_chat.id, Messages.enter_message)
    raise DispatcherHandlerStop(ConversationsStates.RECEIVED_MESSAGE)

def receivedMessage(update: Update, context: CallbackContext):
    if context.user_data["mode"] != "admin":
        return
    message = update.message.text
    chat_id = update.effective_message.chat_id
    context.bot.send_message(update.effective_chat.id, Messages.will_send_messages)
    all_users = getUsers()
    all_users = list(chunk(all_users, 20))
    for index in range(len(all_users)):
        some_users = all_users[index]
        context.job_queue.run_once(
            _sendMessages,
            index,
            context={"users": some_users, "message": message},
        )
    raise DispatcherHandlerStop(ConversationHandler.END)


from libs.connection import MySQLConnection
import datetime

class Estadisticas:
    def __init__(self):
        self.conexion = MySQLConnection()

    def getBestSellingProducts(self):
        query = """
            SELECT producto.nombre, SUM(DetallesCompra.Cantidad) AS TotalVendido FROM DetallesCompra
            INNER JOIN producto ON DetallesCompra.IdProducto = producto.Id GROUP BY DetallesCompra.IdProducto
            ORDER BY TotalVendido DESC LIMIT 5
        """

        res = self.conexion.obtener_registros(query)
        return res

    def getFechasCompras(self):
        query = """
            SELECT MONTH(FechaCompra) AS Mes FROM Compra GROUP BY MONTH(FechaCompra) ORDER BY Mes ASC
        """

        res = self.conexion.obtener_registros(query)
        return res

    def getBestSellingProductsByMes(self, mes):
        query = """
            SELECT p.nombre, SUM(dc.Cantidad) AS CantidadVendida
            FROM DetallesCompra dc
            JOIN producto p ON dc.IdProducto = p.id
            JOIN Compra c ON dc.IdCompra = c.IdCompra
            WHERE MONTH(c.FechaCompra) = %s
            GROUP BY dc.IdProducto
            ORDER BY CantidadVendida DESC
            LIMIT 5;
        """
        parametros = (mes,)

        res = self.conexion.obtener_registros(query, parametros)
        return res

    def obtener_compras_total_ventas(self, mes=None):
        query = """
            SELECT
                C.IdCompra,
                C.FechaCompra,
                C.TotalCompra
            FROM
                Compra C
            WHERE
                MONTH(C.FechaCompra) = %s OR %s IS NULL;
        """

        parametros = (mes, mes) if mes else (None, None)

        registros = self.conexion.obtener_registros(query, parametros)

        return registros

    def obtener_productos_vendidos(self, mes=None):
        sql = """
            SELECT c.IdCompra,
                   c.FechaCompra,
                   c.TotalCompra,
                   c.Pago,
                   c.Cambio,
                   dc.IdProducto,
                   dc.IdCompra AS IdCompraDetalles,
                   dc.IdProducto AS IdProductoDetalles,
                   dc.PrecioProducto,
                   dc.Cantidad,
                   dc.Descuento,
                   p.nombre AS Nombre
            FROM Compra c
            INNER JOIN DetallesCompra dc ON c.IdCompra = dc.IdCompra
            INNER JOIN producto p ON dc.IdProducto = p.id
            WHERE MONTH(c.FechaCompra) = %s OR %s IS NULL;
            """

        parametros = (mes, mes) if mes else (None, None)

        results = self.conexion.obtener_registros(sql, parametros)

        formatted_results = [{
            "IdCompra"           : int(row[0]),
            "FechaCompra"        : (
                datetime.datetime.strptime(str(row[1]), "%a, %d %b %Y %H:%M:%S %Z").strftime("%Y-%m-%d")
                if isinstance(row[1], str)
                else row[1].strftime("%Y-%m-%d")
            ),
            "TotalCompra"        : "{:.2f}".format(float(row[2])),
            "Pago"               : "{:.2f}".format(float(row[3])),
            "Cambio"             : "{:.2f}".format(float(row[4])),
            "IdProducto"         : int(row[5]),
            "IdCompraDetalles"   : int(row[6]),
            "IdProductoDetalles" : int(row[7]),
            "PrecioProducto"     : "{:.2f}".format(float(row[8])),
            "Cantidad"           : "{:.2f}".format(float(row[9])),
            "Descuento"          : "{:.2f}".format(float(row[10])),
            "Nombre"             : row[11]
        } for row in results]

        return formatted_results

    def getGanaciasByMonth(self, mes):
        sql = """
            SELECT SUM(TotalCompra) AS TotalMes FROM Compra WHERE MONTH(FechaCompra) = %s;
            """

        parametros = (mes,)

        results = self.conexion.obtener_registros(sql, parametros)

        ganancias = [{
            "ganancias": "{:.2f}".format(float(row[0])),
        } for row in results]

        return ganancias

    def getPurchaseDetails(self, idCompra):
        sql = """
                SELECT c.IdCompra, c.FechaCompra, p.nombre AS NombreProducto, dc.Cantidad, dc.PrecioProducto, dc.Descuento
                    FROM Compra c
                    JOIN DetallesCompra dc ON c.IdCompra = dc.IdCompra
                    JOIN producto p ON dc.IdProducto = p.id
                WHERE c.IdCompra = %s;
              """
        parametros = (idCompra,)

        results = self.conexion.obtener_registros(sql, parametros)

        formatted_results = [{
            "IdCompra"       : int(row[0]),
            "Fecha"          : (datetime.datetime.strptime(str(row[1]), "%a, %d %b %Y %H:%M:%S %Z").strftime("%Y-%m-%d")
                                if isinstance(row[1], str)
                                else row[1].strftime("%Y-%m-%d")),
            "Nombre"         : row[2],
            "Cantidad"       : int(row[3]),
            "PrecioProducto" : "{:.2f}".format(float(row[4])),
            "Descuento"      : "{:.2f}".format(float(row[5]))
        } for row in results]

        return formatted_results

    def verifyingStock(self):
        conexion = MySQLConnection()

        sql = """
              SELECT proveedor.nombre_empresa, proveedor.nombre_contacto, proveedor.telefono, proveedor.email, producto.totalProducto, producto.nombre
                  FROM producto
                  JOIN proveedor ON producto.proveedor_id = proveedor.id
              WHERE producto.totalProducto <= 5;
              """

        results = conexion.obtener_registros(sql)

        conexion.cerrar_conexion()

        if not results:
            return 'False'
        else:
            formatted_results = [{
                "NombreEmpresa"    : row[0],
                "NombreContacto"   : row[1],
                "Telefono"         : row[2],
                "Email"            : row[3],
                "TotalProducto"    : int(row[4]),
                "NombreProducto"   : row[5]
            } for row in results]

            return formatted_results

    def searchDetails(self, search, mes=None):
        search_str = f'%{search}%'

        query = """
                SELECT DISTINCT
                    C.IdCompra,
                    C.FechaCompra,
                    C.TotalCompra
                FROM
                    Compra C
                    JOIN DetallesCompra DC ON C.IdCompra = DC.IdCompra
                    JOIN producto P ON DC.IdProducto = P.id
                WHERE
                    (P.nombre LIKE %s OR C.IdCompra LIKE %s)
                    AND (MONTH(C.FechaCompra) = %s OR %s IS NULL)
                """
        parameters = [search_str, search_str, mes, mes,]

        results = self.conexion.obtener_registros(query, parameters)

        return results


from selene import by, be, have
from selene.support.shared import browser

def test_search():
    browser.open('https://google.com/ncr')

    browser.element(by.name('q')).should(be.blank)\
        .type('python selene').press_enter()

    results = browser.all('#search .g')
    results.should(have.size_greater_than_or_equal(6))
    results.first.should(have.text('User-oriented Web UI browser tests'))
    results.first.element('.r>a').click()

    browser.should(have.title_containing('yashaka/selene'))


import argparse
import glob
import json
import msgpack
import numpy as np
import torch

from transformers import OpenAIGPTTokenizer, OpenAIGPTLMHeadModel
from transformers import GPT2Tokenizer, GPT2LMHeadModel
from transformers import XLNetTokenizer, XLNetLMHeadModel
from transformers import TransfoXLTokenizer, TransfoXLLMHeadModel

parser = argparse.ArgumentParser(description='Collect per positions losses.')
parser.add_argument('--save', type=str, default='../results/results_books.npy',
                    help='Name of save file')
parser.add_argument('--data', type=str, default='../data/wiki40b/',
                    help='Path to data')
parser.add_argument('--batch', type=int, default=8,
                    help='Batch size for SRL parser.')
parser.add_argument('--dataset', type=str, default='books',
                    choices=['books', 'wiki', 'litbank', 'research'], help='Dataset type')
args = parser.parse_args()

def get_gpt():
    tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt')
    model = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt')
    model.eval()
    return tokenizer, model

def get_gpt2():
    tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
    model = GPT2LMHeadModel.from_pretrained('gpt2')
    model.eval()
    return tokenizer, model

def get_tranxl():
    tokenizer = TransfoXLTokenizer.from_pretrained('transfo-xl-wt103')
    model = TransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103')
    model.eval()
    return tokenizer, model

def get_xlnet(): # Doesn't work
    tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased')
    model = XLNetLMHeadModel.from_pretrained('xlnet-large-cased')
    model.eval()
    return tokenizer, model

def get_wiki_data(path):
    files = glob.glob(path+"/*")
    for fname in files:
        with open(fname, "rb") as buf:
            unpacker = msgpack.Unpacker(buf, raw=False)
            for unpacked in unpacker:
                yield unpacked

def get_books_data(path):
    data = []
    collect = True
    with open(path, "r") as f:
        one_book = []
        for i, line in enumerate(f):
            if collect:
                one_book.append(line)
                if len(one_book) == 50:
                    data.append(one_book)
                    one_book = []
                    collect = False
            if i % 10000 == 0:
                collect = True
    all_data = []
    for book in data:
        lines = " ".join([l.strip() for l in book])
        all_data.append(lines)
    for d in all_data[1:]:
        yield d

def get_litbank_data(path):
    litbank_file = glob.glob(path + "*")
    data = []
    for fname in litbank_file:
        book = []
        section = []
        with open(fname, "r") as f:
            spaces = 0
            for line in f:
                if line.isspace():
                    spaces += 1
                else:
                    if spaces < 2:
                        section.append(line.strip())
                    else:
                        book.append(section)
                        section = []
                        section.append(line.strip())
                    spaces = 0
            if section:
                book.append(section)
        data.append(book)

    all_data = []
    for book in data:
        new_book = [" ".join(sec) for sec in book if len(sec) > 50]
        all_data.append(new_book)

    all_data = [sec for book in all_data for sec in book]
    for d in all_data:
        yield d

def get_research_data(path):
    filenames = glob.glob(path+"/*.json")
    all_intros = []
    for path in filenames:
        with open(path, "r") as f:
            doc = json.load(f)
            intro = []
            for ent in doc['body_text']:
                if "Introduction" == ent['title']:
                    intro.append((ent['startOffset'], ent['sentence']))
            intro = sorted(intro)
            intro = [b for a, b in intro]
            intro = " ".join(intro)
            all_intros.append(intro)
    for d in all_intros:
        yield d

def  main(args):
    # TODO: check uninitialized weights
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    if args.dataset == "books":
        get_data = get_books_data
    elif args.dataset == "litbank":
        get_data = get_litbank_data
    elif args.dataset == "research":
        get_data = get_research_data
    else:
        get_data = get_wiki_data

    configs = {"gpt": get_gpt,
               "gpt2": get_gpt2,
               "tranxl": get_tranxl} #,
               # "xlnet": get_xlnet}
    for name, get_config in configs.items():
        print("Running", name)
        paragraphs = get_data(args.data)

        tokenizer, model = get_config()
        model = model.to(device)
        loss_fct = torch.nn.CrossEntropyLoss(reduction="none")

        done = False
        count = 0
        while not done:
            tokenized_paras = []
            for para in paragraphs:
                toked = tokenizer.encode(para, return_tensors="pt", truncation=True, max_length=512)
                if toked.shape[1] >= 512:
                    tokenized_paras.append(toked[:, :512])
                    if len(tokenized_paras) == args.batch:
                        break
            if len(tokenized_paras) < args.batch:
                done = True
            if not tokenized_paras:
                continue
            tokenized_paras = torch.cat(tokenized_paras, axis=0)
            tokenized_paras = tokenized_paras.to(device)

            with torch.no_grad():
                out = model(tokenized_paras, labels=tokenized_paras, return_dict=True)
                if name == "tranxl":
                    loss = out.losses.cpu()
                else:
                    shift_logits = out.logits[..., :-1, :].contiguous()
                    shift_labels = tokenized_paras[..., 1:].contiguous()
                    # Flatten the tokens
                    loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
                save_results(loss.cpu().numpy(), args.save, name)
                count += 1
                if count > 3000:
                    break
    return

def save_results(loss, savefile, key_name):
    filename = savefile.replace(".npy", "-" + key_name + ".npy")
    print("saving to filename...", filename)
    with open(filename, "ab") as f:
        np.save(f, loss)

if __name__ == "__main__":
    main(args)


import random
import math
import time

"""
    Ordena um vetor usando Merge Sort.
    :param vet: Vetor a ser ordenado.
    :param inv: Booleano para indicar ordenação decrescente.
    :return: Retorna o vetor ordenado.
"""
def mergeSort(vet, inv):
    if len(vet) <= 1:
        return vet
    meio = math.ceil(len(vet)/2)
    a = mergeSort(vet[:meio], inv)
    b = mergeSort(vet[meio:], inv)

    vet = merge(a, b, inv)
    return vet

"""
    Mescla dois vetores.
    :param a: Primeiro vetor.
    :param b: Segundo vetor
    :param inv: Booleano para indicar ordenação decrescente.
    :return: Retorna o vetor ordenado.
"""
def merge(a, b, inv):
    vet = []
    indexA = 0 # Inicio da primeira metade
    indexB = 0 # Inicio da segunda metade
    while indexA < len(a) and indexB < len(b):
        if not inv: #Ordena em ordem crescente
            if a[indexA] < b[indexB]:
                vet.append(a[indexA])
                indexA += 1
            elif a[indexA] > b[indexB]:
                vet.append(b[indexB])
                indexB += 1
            else:
                vet.append(a[indexA])
                vet.append(b[indexB])
                indexA += 1
                indexB += 1
        else: #Ordena em ordem decrescente
            if a[indexA] > b[indexB]:
                vet.append(a[indexA])
                indexA += 1
            elif a[indexA] < b[indexB]:
                vet.append(b[indexB])
                indexB += 1
            else:
                vet.append(a[indexA])
                vet.append(b[indexB])
                indexA += 1
                indexB += 1

    while indexA < len(a):
        vet.append(a[indexA])
        indexA += 1
    while indexB < len(b):
        vet.append(b[indexB])
        indexB += 1
    return vet
"""
    Contabiliza o tempo de execução para as seguintes entradas:
    Vetor de inteiros:
    - Desordenado.
    - Ordenado crescente.
    - Ordenado decrescente.
    - Ordenado metade crescente, metade decrescente.
    - Ordenado metade decrescente, metade crescente.
"""
testes = [] # Vetor que guarda os casos de teste
tempos = [] # Vetor que guarda os tempos de execução para cada caso de teste
tamanho = 100000 # Tamanho dos casos de teste
nOp= 5 # número de casos de teste
meio = math.ceil(tamanho/2)

# Vetor desordenado
vet = []
for i in range(tamanho):
    vet.append(random.randint(0,tamanho))
print("Entrada 1 - Desordenado: \n", vet)

# Cria 5 copias do vetor deordenado
for i in range(nOp):
    testes.append(vet)

#Vetor Crescente
testes[1] = mergeSort(testes[1], False)
print("\nEntrada 2 - Ordem Crescente: \n", testes[1])

#Vetor Decrescente
testes[2] = mergeSort(testes[2], True)
print("\nEntrada 3 - Ordem Decrescente: \n", testes[2])

#Vetor Crescente/Decrescente
metade1 = mergeSort(testes[3][:meio], False)
metade2 = mergeSort(testes[3][meio:], True)
testes[3] = metade1 + metade2
print("\nEntrada 4 - Ordem Crescente/Decrescente: \n", testes[3])

#Vetor Decrescente/Crescente
metade1 = mergeSort(testes[4][:meio], True)
metade2 = mergeSort(testes[4][meio:], False)
testes[4] = metade1 + metade2
print("\nEntrada 5 - Ordem Decrescente/Crescente: \n", testes[4], "\n")

# Medição de tempo para cada entrada
for i in range(nOp):
    inicio = time.time()
    mergeSort(testes[i], False)
    fim = time.time()
    tempos.append(fim - inicio)

print("Tempos de execução(segundos):")
for i in range(len(tempos)):
    print("Entrada", i+1, ":", tempos[i])


"""
Fill-in the squares problem (Brainjammer) in cpmpy.

This problem is from the ZDC system, available from
http://www.bracil.net/CSP/cacp/cacpdemo.html , in the
file
    Brainjammer.txt
from 2003-01-26, which states:
'''
Only Solution is:
    1     2       3       4       5
====================================================
A    7      11      2       17      1
B   13      19      23      22      3
C   9       20      24      14      12
D   16      21      25      18      10
E   4       8       15      6       5

  22mins55secs of CPU time to find first solution
  50mins42secs of CPU time with duplicate induced variables removed?
  Maybe this has something to do with the variable ordering...as this might change
  as a result of removing duplicate induced variables.
  1hr:34 mins of CPU time to find a single solution and determine no other solutions
  exist.

  Statistics for finding the first solution:
  (with duplicate induced nodes removed)
  CPU seconds:                4880.63 (On a Pentium Pro 200Mhz, VC++)
  Node count:                 4036162
  Induced node count: 1849214
  Backtracks:                 5885311

'''

Notes:
- On my dual core 3.2 Mhz (Linux) it takes about 0.3 seconds (runtime) to solve
  this problem (0.058s solution time), but the comparison is really not fair
  considering the  difference in machines.
- The only references to this problem I've found are the following pages:
   http://discuss.fogcreek.com/techInterview/default.asp?cmd=show&ixPost=2787
   http://notdarkandstormy.blogspot.com/2005/05/funky-logic-problem.html
   and especially
   http://perplexus.info/show.php?pid=2683
   which has a lot of comments about manually solving the problem.

I've yet to know the original source.

Model created by Hakan Kjellerstrand, hakank@hakank.com
See also my CPMpy page: http://www.hakank.org/cpmpy/
"""
from cpmpy import *
import numpy as np
from cpmpy_hakank import *

def fill_in_the_squares():

    model = Model()

    n = 5
    nn = n*n

    Primes = [2,3,5,7,11,13,17,19,23]
    Primes2 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
    Squares = [1,4,9,16,25]

    a = intvar(1,nn,shape=n,name="a")
    b = intvar(1,nn,shape=n,name="b")
    c = intvar(1,nn,shape=n,name="c")
    d = intvar(1,nn,shape=n,name="d")
    e = intvar(1,nn,shape=n,name="e")

    ALL = intvar(1,nn,shape=nn,name="ALL") # all numbers

    min_sum = 21
    max_sum = 25
    min_max_sum = sum([i for i in range(min_sum,max_sum+1)])
    a_sum = intvar(1,min_max_sum,name="a_sum")
    b_sum = intvar(1,min_max_sum,name="b_sum")
    c_sum = intvar(1,min_max_sum,name="c_sum")
    d_sum = intvar(1,min_max_sum,name="d_sum")
    e_sum = intvar(1,min_max_sum,name="e_sum")

    model += (a_sum == sum(a))
    model += (b_sum == sum(b))
    model += (c_sum == sum(c))
    model += (d_sum == sum(d))
    model += (e_sum == sum(e))

    #
    # Note: The constraint comments are 1-based, but Python is not.
    #

    # Each number from 1-25, used only once
    for i in range(n):
        model += ([
        ALL[i]     == a[i],
        ALL[i+n]   == b[i],
        ALL[i+2*n] == c[i],
        ALL[i+3*n] == d[i],
        ALL[i+4*n] == e[i],
        ])

    model+= (AllDifferent(ALL))

    # 1.Sum of each column is odd
    for i in range(n):
        model += ((a[i] + b[i] + c[i] + d[i] + e[i]) % 2 == 1)

    # 2.Sum of each row, except C is even
    model += ([
      a_sum % 2 == 0,
      b_sum % 2 == 0,
      c_sum % 2 == 1,
      d_sum % 2 == 0,
      e_sum % 2 == 0
      ])

    # 3.Sum of row A is not greater than the sum of any other row
    model += ([
      a_sum <= b_sum,
      a_sum <= c_sum,
      a_sum <= d_sum,
      a_sum <= e_sum,
      ])

    # 4.The sum of diagonal A1 to E5 is greater than the sum of
    #   diagonal E1 to A5
    model += (a[0] + b[1] + c[2] + d[3] + e[4]  > e[0] + d[1] + c[2] + b[3] + a[4])

    # 5.(A4 + B4) is greater than (C4+D4+E4)
    model += (a[3] + b[3] > c[3] + d[3] + e[3])

    # 6. A1 + B1 = D1 + E1
    model += (a[0] + b[0] == d[0] + e[0])

    # 7. A1 > E1
    model += (a[0] > e[0])

    # 8. A1, A3 and B1 are primes
    model += ([
             member_of(Primes,a[0]),
             member_of(Primes,a[2]),
             member_of(Primes,b[0])
             ])
    # 9.(A3 + E3) is a prime number
    model += (member_of(Primes,a[2]+e[2]))

    # 10. A5,D1,D3 and E1 are squares
    model += ([
      member_of(Squares,a[4]),
      member_of(Squares,d[0]),
      member_of(Squares,d[2]),
      member_of(Squares,e[0]),
      ])

    # 11. B2, C2, and D2 are ascending consecutive numbers
    model += ([
      b[1] + 1 == c[1],
      c[1] + 1 == d[1],
      ])

    # 12. B3, C3, and D3 are ascending consecutive numbers
    model += ([
        b[2] + 1 == c[2],
        c[2] + 1 == d[2]
        ])

    # 13. B5 + D5 = A5 + C5
    model += (b[4] + d[4] == a[4] + c[4])

    # 14. (c1)^2 + (c5)^2 = (e3)^2
    model += (c[0]*c[0] + c[4]*c[4] == e[2]*e[2])

    # 15. C5 is a two-digit number
    model += (c[4] > 9)

    # 16. D5 is a multiple of E5
    model += (d[4] % e[4] == 0)

    # 17. E1 + E3 = E2 + E4 + E5
    model += (e[0] + e[2] == e[1] + e[3] + e[4])

    def print_sol():
        print("a:",a.value())
        print("b:",b.value())
        print("c:",c.value())
        print("d:",d.value())
        print("e:",e.value())
        print()

    ss = CPM_ortools(model)
    num_solutions = ss.solveAll(display=print_sol)
    print("num_solutions:", num_solutions)
    print(ss.status())

fill_in_the_squares()


def solution(user_id, banned_id):
    answer = set()

    def 아이디찾기(아이디리스트, 밴아이디):
        리스트 = []
        for idx in range(len(아이디리스트)):
            if len(아이디리스트[idx]) == len(밴아이디):
                flag=1
                for i in range(len(밴아이디)):
                    if 밴아이디[i]=='*': continue # *일경우엔 문자비교 생략
                    if 밴아이디[i] != 아이디리스트[idx][i]: flag=0 #문자 하나라도 틀리면 flag=0 갱신
                if flag: 리스트.append(idx)
        return 리스트

    def 백트래킹(현재밴아이디, 선택된아이디):
        if 현재밴아이디 == len(banned_id):
            answer.add(tuple(sorted(선택된아이디)))
            return

        가능한아이디 = 아이디찾기(user_id, banned_id[현재밴아이디])

        for 아이디 in 가능한아이디:
            if 아이디 not in 선택된아이디:
                선택된아이디.add(아이디)
                백트래킹(현재밴아이디 + 1, 선택된아이디)
                선택된아이디.remove(아이디)

    백트래킹(0, set())
    return len(answer)

230418_불량사용자.py


import re

def get_name_convert_func():
    """
    Get the function to convert Caffe2 layer names to PyTorch layer names.
    Returns:
        (func): function to convert parameter name from Caffe2 format to PyTorch
        format.
    """
    pairs = [
        # ------------------------------------------------------------
        # 'nonlocal_conv3_1_theta_w' -> 's3.pathway0_nonlocal3.conv_g.weight'
        [
            r"^nonlocal_conv([0-9]+)_([0-9]+)_(.*)",
            r"s\1.pathway0_nonlocal\2_\3",
        ],
        # 'theta' -> 'conv_theta'
        [r"^(.*)_nonlocal([0-9]+)_(theta)(.*)", r"\1_nonlocal\2.conv_\3\4"],
        # 'g' -> 'conv_g'
        [r"^(.*)_nonlocal([0-9]+)_(g)(.*)", r"\1_nonlocal\2.conv_\3\4"],
        # 'phi' -> 'conv_phi'
        [r"^(.*)_nonlocal([0-9]+)_(phi)(.*)", r"\1_nonlocal\2.conv_\3\4"],
        # 'out' -> 'conv_out'
        [r"^(.*)_nonlocal([0-9]+)_(out)(.*)", r"\1_nonlocal\2.conv_\3\4"],
        # 'nonlocal_conv4_5_bn_s' -> 's4.pathway0_nonlocal3.bn.weight'
        [r"^(.*)_nonlocal([0-9]+)_(bn)_(.*)", r"\1_nonlocal\2.\3.\4"],
        # ------------------------------------------------------------
        # 't_pool1_subsample_bn' -> 's1_fuse.conv_f2s.bn.running_mean'
        [r"^t_pool1_subsample_bn_(.*)", r"s1_fuse.bn.\1"],
        # 't_pool1_subsample' -> 's1_fuse.conv_f2s'
        [r"^t_pool1_subsample_(.*)", r"s1_fuse.conv_f2s.\1"],
        # 't_res4_5_branch2c_bn_subsample_bn_rm' -> 's4_fuse.conv_f2s.bias'
        [
            r"^t_res([0-9]+)_([0-9]+)_branch2c_bn_subsample_bn_(.*)",
            r"s\1_fuse.bn.\3",
        ],
        # 't_pool1_subsample' -> 's1_fuse.conv_f2s'
        [
            r"^t_res([0-9]+)_([0-9]+)_branch2c_bn_subsample_(.*)",
            r"s\1_fuse.conv_f2s.\3",
        ],
        # ------------------------------------------------------------
        # 'res4_4_branch_2c_bn_b' -> 's4.pathway0_res4.branch2.c_bn_b'
        [
            r"^res([0-9]+)_([0-9]+)_branch([0-9]+)([a-z])_(.*)",
            r"s\1.pathway0_res\2.branch\3.\4_\5",
        ],
        # 'res_conv1_bn_' -> 's1.pathway0_stem.bn.'
        [r"^res_conv1_bn_(.*)", r"s1.pathway0_stem.bn.\1"],
        # 'conv1_xy_w_momentum' -> 's1.pathway0_stem.conv_xy.'
        [r"^conv1_xy(.*)", r"s1.pathway0_stem.conv_xy\1"],
        # 'conv1_w_momentum' -> 's1.pathway0_stem.conv.'
        [r"^conv1_(.*)", r"s1.pathway0_stem.conv.\1"],
        # 'res4_0_branch1_w' -> 'S4.pathway0_res0.branch1.weight'
        [
            r"^res([0-9]+)_([0-9]+)_branch([0-9]+)_(.*)",
            r"s\1.pathway0_res\2.branch\3_\4",
        ],
        # 'res_conv1_' -> 's1.pathway0_stem.conv.'
        [r"^res_conv1_(.*)", r"s1.pathway0_stem.conv.\1"],
        # ------------------------------------------------------------
        # 'res4_4_branch_2c_bn_b' -> 's4.pathway0_res4.branch2.c_bn_b'
        [
            r"^t_res([0-9]+)_([0-9]+)_branch([0-9]+)([a-z])_(.*)",
            r"s\1.pathway1_res\2.branch\3.\4_\5",
        ],
        # 'res_conv1_bn_' -> 's1.pathway0_stem.bn.'
        [r"^t_res_conv1_bn_(.*)", r"s1.pathway1_stem.bn.\1"],
        # 'conv1_w_momentum' -> 's1.pathway0_stem.conv.'
        [r"^t_conv1_(.*)", r"s1.pathway1_stem.conv.\1"],
        # 'res4_0_branch1_w' -> 'S4.pathway0_res0.branch1.weight'
        [
            r"^t_res([0-9]+)_([0-9]+)_branch([0-9]+)_(.*)",
            r"s\1.pathway1_res\2.branch\3_\4",
        ],
        # 'res_conv1_' -> 's1.pathway0_stem.conv.'
        [r"^t_res_conv1_(.*)", r"s1.pathway1_stem.conv.\1"],
        # ------------------------------------------------------------
        # pred_ -> head.projection.
        [r"pred_(.*)", r"head.projection.\1"],
        # '.b_bn_fc' -> '.se.fc'
        [r"(.*)b_bn_fc(.*)", r"\1se.fc\2"],
        # conv_5 -> head.conv_5.
        [r"conv_5(.*)", r"head.conv_5\1"],
        # conv_5 -> head.conv_5.
        [r"lin_5(.*)", r"head.lin_5\1"],
        # '.bn_b' -> '.weight'
        [r"(.*)bn.b\Z", r"\1bn.bias"],
        # '.bn_s' -> '.weight'
        [r"(.*)bn.s\Z", r"\1bn.weight"],
        # '_bn_rm' -> '.running_mean'
        [r"(.*)bn.rm\Z", r"\1bn.running_mean"],
        # '_bn_riv' -> '.running_var'
        [r"(.*)bn.riv\Z", r"\1bn.running_var"],
        # '_b' -> '.bias'
        [r"(.*)[\._]b\Z", r"\1.bias"],
        # '_w' -> '.weight'
        [r"(.*)[\._]w\Z", r"\1.weight"],
    ]

    def convert_caffe2_name_to_pytorch(caffe2_layer_name):
        """
        Convert the caffe2_layer_name to pytorch format by apply the list of
        regular expressions.
        Args:
            caffe2_layer_name (str): caffe2 layer name.
        Returns:
            (str): pytorch layer name.
        """
        for source, dest in pairs:
            caffe2_layer_name = re.sub(source, dest, caffe2_layer_name)
        return caffe2_layer_name

    return convert_caffe2_name_to_pytorch


#? Melhore o desafio 061, perguntando para o usuário se ele quer mostrar
#? mais alguns termos. O programa encerra quando ele disser que mostrar 0 termos.

termo = int(input('Digite o primeiro termo da PA: '))
razao = int(input('Digite a razão da PA: '))
contador = 0

print(f'{termo} -> ', end= '')
while contador < 10:
    termo += razao
    contador += 1
    print(f'{termo} -> ' if contador != 10 else f'{termo}', end='')

contador = int(input('\nQuantos termos você quer a mais?'))
while contador > 0:
    termo += razao
    contador -= 1
    print(f'{termo} -> ' if contador > 0 else f'{termo}', end='')
    if contador == 0:
        contador = int(input('\nQuantos termos você quer a mais?'))

print('FINALIZADO')


import datetime, os, pandas as pd, numpy as np, requests, time, urllib3
from bs4 import BeautifulSoup

class Metadata(object):
    '''
    '''

    identifiers = None
    metadata_filepath = None

    def request_bulk_metadata(self, date_of_last_request):
        '''
        Requests bulk metadata from OAI2.
        Returns (rows, requestDate) where
        '''

        rows = []
        resumptionToken = 'placeholder'
        url = 'http://export.arxiv.org/oai2?verb=ListRecords&set=physics:astro-ph&metadataPrefix=arXiv'
        results = None

        # If we have specified the date of the last request, add it to the URL
        if date_of_last_request:
            url += '&from=' + date_of_last_request.strftime('%Y-%m-%d')

        # Continue requesting until we are not given any more resumption tokens
        while resumptionToken is not None:
            # Send request and receive results, waiting specified time if necessary
            while results == None:
                try:
                    print('Requesting: ' + url)
                    results = requests.get(url).text
                except urllib3.exceptions.HTTPError as e:
                    wait = int(e.headers.get('Retry-After'))
                    print('HTTPError: Waiting ' + str(wait) + 's to retry requesting metadata...')
                    time.sleep(wait)

            # Parse with Beautiful Soup
            soup = BeautifulSoup(results, 'xml')
            records = soup.find_all('record')
            for record in records:
                # Get header data
                identifier = record.find('identifier')
                datestamp = record.find('datestamp')
                spec = record.find('setSpec')

                # Get metadata
                filename = record.find('id')
                created = record.find('created')
                updated = record.find('updated')
                authors = []
                for author in record.find_all('author'):
                    forenames = author.forenames
                    keyname = author.keyname
                    if forenames and keyname:
                        authors.append(author.forenames.text.strip() + ' ' + author.keyname.text.strip())
                author_str = ', '.join(authors)
                title = record.find('title')
                categories = record.find('categories')
                journal = record.find('journal-ref')
                doi = record.find('doi')
                abstract = record.find('abstract')
                comments = record.find('comment')

                # Save current record as a row in the table
                row = {
                    'identifier': getattr(identifier, 'text', None),
                    'filename': getattr(filename, 'text', None),
                    'spec': getattr(spec, 'text', None),
                    'title': getattr(title, 'text', None),
                    'datestamp': getattr(datestamp, 'text', None),
                    'created': getattr(created, 'text', None),
                    'updated': getattr(updated, 'text', None), # may have more than one instance that we're missing
                    'authors': author_str,
                    'categories': getattr(categories, 'text', None),
                    'journal': getattr(journal, 'text', None),
                    'doi': getattr(doi, 'text', None),
                    'abstract': getattr(abstract, 'text', None),
                    'comments': getattr(comments, 'text', None)
                }
                rows.append(row)

            # Get resumption token if provided
            resumptionToken = soup.find('resumptionToken')

            # Continue if we have resumption token
            if resumptionToken is not None:
                print('Status: ' + str(int(resumptionToken['cursor']) + 1) + '—' + str(len(rows)) + '/' + str(resumptionToken['completeListSize']) + '...')
                resumptionToken = resumptionToken.text
                url = 'http://export.arxiv.org/oai2?verb=ListRecords&resumptionToken=' + resumptionToken
                time.sleep(20) # avoid 503 status

        return rows

    def update(self):
        '''
        Checks if an update is needed. If it is needed, gathers
        '''
        metadata_filepath = 'arxiv_metadata_astroph.csv'

        if os.path.exists(metadata_filepath):
            # If the metadata file exists, load it into a data frame
            existing_metadata_df = pd.read_csv(metadata_filepath,
                                               dtype={'filename': str,
                                                      'filename_parsed': str,
                                                      'identifier': str,
                                                      'updated': str,
                                                      'doi': str},
                                               parse_dates=['date_retrieved'])
            # Get the date of the last request
            existing_metadata_df['date_retrieved'] = existing_metadata_df['date_retrieved'].apply(lambda x:x.replace(tzinfo=datetime.timezone.utc))
            date_of_last_request = existing_metadata_df['date_retrieved'].max()
            print(metadata_filepath + ' last updated on ' + date_of_last_request.strftime('%Y-%m-%d'))
            print('Updating...')
            # Send a request to access metadata since that date
            records = self.request_bulk_metadata(date_of_last_request + datetime.timedelta(days=1))
            # Create data frame for records to specify additional info
            if len(records) > 0:
                print('Number of new records found: ' + str(len(records)))
                records_df = pd.DataFrame(records)
                records_df['date_retrieved'] = np.full(len(records_df), datetime.datetime.now())
                records_df['filename_parsed'] = existing_metadata_df['filename'].str.replace('/', '')
                # Update metadata file
                metadata_df = pd.concat([existing_metadata_df, records_df], axis=0, sort=True, ignore_index=True)
                metadata_df.to_csv(metadata_filepath, index=False)
                print('Metadata has been updated.')
            else:
                print('No additional records found. Metadata is up to date.')
        else:
            # If the metadata file doesn't exist, request all metadata
            print(metadata_filepath + ' is being created...')
            records = request_bulk_metadata(None)
            # Load records into data frame
            metadata_df = pd.DataFrame(records)
            # Add a column to specify additional info
            metadata_df['date_retrieved'] = np.full(len(metadata_df), datetime.datetime.now())
            metadata_df['filename_parsed'] = metadata_df['filename'].str.replace('/', '')
            # Save it to CSV
            metadata_df.to_csv(metadata_filepath, index=False)
            print('Metadata has been saved.')

    def get_identifiers(self):
        # Grab identifiers from metadata
        metadata_df = pd.read_csv(self.metadata_filepath,
                                   dtype={'filename': str,
                                          'filename_parsed': str,
                                          'identifier': str,
                                          'updated': str,
                                          'doi': str},
                                   parse_dates=['date_retrieved'])
        self.identifiers = metadata_df['filename_parsed']

    def __init__(self, update=False):
        self.metadata_filepath = 'arxiv_metadata_astroph.csv'
        # Automatically check for any updates
        if update:
            self.update()
        self.get_identifiers()


import copy
from typing import List

import torch

from torchsim.core.graph.unit import Unit
from torchsim.core.memory.tensor_creator import TensorCreator
from torchsim.core.graph.worker_node_base import WorkerNodeBase
from torchsim.core.graph.slot_container import Inputs, MemoryBlocks
from torchsim.core.nodes.disentangled_world_node import DisentangledWorldNodeParams
from torchsim.core.physics_model.pymunk_physics import PymunkParams

class DisentangledWorldRendererUnit(Unit):
    bitmap: torch.Tensor
    _params: DisentangledWorldNodeParams

    def __init__(self, creator: TensorCreator, params: DisentangledWorldNodeParams):
        super().__init__(creator.device)

        self._params = copy.copy(params)

        self._render_world = params.render_world_class((params.sx, params.sy), **params.render_world_params)

        width = self._render_world.world_size[0]
        height = self._render_world.world_size[1]
        self.bitmap = creator.zeros((width, height, 3),
                                     dtype=self._float_dtype,
                                     device=self._device)

    def step(self, instances: torch.Tensor):
        params = PymunkParams()
        self._params.sx = params.sx
        self._params.sy = params.sy
        self._params.shape_max = params.shape_max
        self._params.color_max = params.color_max
        self._params.world_dims = params.world_dims
        self._params.max_velocity = params.max_velocity
        self.bitmap.copy_(self._render_world.to_tensor(instances, params))

class DisentangledWorldRendererInputs(Inputs):
    def __init__(self, owner):
        super().__init__(owner)
        self.latent = self.create("Latent vars")

class DisentangledWorldRendererOutputs(MemoryBlocks):
    def __init__(self, owner):
        super().__init__(owner)
        self.bitmap = self.create("Bitmap")

    def prepare_slots(self, unit: DisentangledWorldRendererUnit):
        self.bitmap.tensor = unit.bitmap

class DisentangledWorldRendererNode(WorkerNodeBase[DisentangledWorldRendererInputs, DisentangledWorldRendererOutputs]):

    def __init__(self, params: DisentangledWorldNodeParams, name="DisentangledWorldRenderer"):
        super().__init__(name=name,
                         inputs=DisentangledWorldRendererInputs(self),
                         outputs=DisentangledWorldRendererOutputs(self))

        self._params = params.clone()

    def _create_unit(self, creator: TensorCreator) -> Unit:
        self._creator = creator

        return DisentangledWorldRendererUnit(creator, self._params)

    def _step(self):
        self._unit.step(self.inputs.latent.tensor)


from django.shortcuts import render, get_object_or_404, redirect

from django.http import HttpResponse
from django.http import Http404

from .models import Articles
from random import randint

# Create your views here.

# def articles_home(request):
#     obj_query_set = Articles.objects.all()
#     string1 = '<h1> I am from articles articles_home view</h1>'
#     return HttpResponse(string1)

def articles_home(request):
    # get set of all objects of Articles class
    obj_query_set = Articles.objects.all()

    # get all objects id queryset
    all_ids = Articles.objects.values_list('id', flat = True)  # it is an iterable set
    all_ids_list = list(all_ids) # it's a list of ids

    # let's create random id
    random_id = randint(1, len(all_ids))
    random_obj = Articles.objects.get(id=random_id)

    # creating context
    context = {
        'all_obj' : Articles.objects.all(),
        'rand_obj' : random_obj
    }
    return render(request, 'articles/articles_home.html', context)

def article_detail(request, id):
    all_ids = Articles.objects.values_list('id', flat = True)  # it is an iterable set
    object = Articles.objects.get(id = id) if id in all_ids else None
    return render(request, 'articles/detail.html', {'obj' : object})

# Raising a 404 error
def article_random_detail(request, id):
    try:
        object = Articles.objects.get(pk=id)  # this is same as Articles.objects.get(id = id)
    except Articles.DoesNotExist:
        raise Http404('Article does not exist')

    # A shortcut: get_object_or_404()
    # we can use it instead of try except statement
    # from django.shortcuts import render, get_object_or_404
    # object = get_object_or_404(Articles, pk=id)

    return render(request, 'articles/detail.html', {'obj' : object})

# view for search id
def article_search_detail(request):
    # print(dir(request))
    print(request.GET) # look at terminal to see the output of print function

    # extracting data from the request using get method
    query_dict = request.GET
    # query_dict is a dictionary
    # but it is not possible to get data writing like request.GET ['q] or query_dict['q]
    # we sould grab data using 'get' function

    query = query_dict.get('q')   # <input type="text"  name="q">
    # or, query = rquest.GET.get('q)

    # get data fffrom database
    object = get_object_or_404(Articles, pk=query)
    return render(request, 'articles/search.html', {'obj' : object})
    # we could use detail page instead of search page like below
    # return render(request, 'articles/detail.html', {'obj' : object})
    # it would be good for us as we don't need to create extra search.html page

def article_create(request):

    # sometimes GET and POST methods are called simultaneously
    # on that time, GET request will show 'None, None' value in terminal
    # so to avoid this we should use the following code

    context = {}
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        print(title, content)
        object = Articles.objects.create(title = title, content = content)
        context['obj'] = object
        context['created'] = True

    """
    title = request.POST.get('title')
    content = request.POST.get('content')
    print(title, content)
    object = Articles.objects.create(title = title, content = content)
    context = {
        'obj' : object,
        'created' : True     # this value indicates that for is created
    }
    """
    return render(request, 'articles/create.html', context = context)

# redirect problem
def article_create_redirect(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        print(title, content)
        obj = Articles.objects.create(title=title, content=content)
        return redirect('articles:articles_home')
        # redirect('app_name:url_name')
        # here redirected to article detail page

        # if i want to redirect to article_detail page, i have to insert an extra argument for 'id'
        # redirect('app_name:url_name', 'argument_needed_for_url')
        # for instance, redirect('articles:article_detail', obj.id)

    return render(request, 'articles/create.html')

"""
I apologize for the misunderstanding.
The `autocomplete="off"` attribute is used to prevent browsers from autofilling form fields,
but it does not prevent form resubmission when navigating back and forward.

To prevent duplicate form submissions when navigating back and forward,
you can implement a technique called Post/Redirect/Get (PRG).
The PRG pattern involves redirecting the user to another URL after successfully submitting the form.
This way, when the user navigates back,
they will be taken to the redirected URL instead of resubmitting the form.

Here's an example of how you can modify your `article_create` function to implement the PRG pattern:

```python
from django.shortcuts import redirect

def article_create(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        print(title, content)
        article = Articles.objects.create(title=title, content=content)
        return redirect('article_detail', id=article.id)  # Redirect to article detail page

    return render(request, 'articles/create.html')
```

In this example, after creating the `Articles` object,
the user is redirected to the `article_detail` page for the newly created article.
This redirection helps avoid form resubmission when the user navigates back to the form page.

Make sure to replace `'article_detail'` with the actual URL name or path for
your article detail page in the `redirect()` function.

By implementing the PRG pattern,
you should prevent duplicate form submissions when navigating back and forward in the browser.

"""


while True:

    height=input('身長(cm)?:')

    #入力は文字列なので、少数に変換します
    try:
        height=float(height)
    except:
        print('Error! 半角数字で入力してね！')
        break

    height=height / 100
    height=float(height)

    try:
        weight=float(input('体重(kg)?:'))
    except:
        print('Error! 半角数字で入力してね！')
        break

    #組み込み関数powで累乗を計算できます
    bmi=weight/pow(height,2)

    #小数点以下第一位までの出力にフォーマットしています
    print('BMI値は{:.1f}です。'.format(bmi))
    if bmi<18.5:
        print('すこしやせすぎです。')
    elif 18.5<=bmi<25.0:
        print('標準的な体型です。')
    elif 25.0<=bmi<30.0:
        print('少し太っています。')
    else:
        print('高度の肥満です。')


import os
import time
from multiprocessing import Semaphore, Process

def f1():
    print("%d 想要执行事件" % os.getpid())
    sem.acquire()  # 拿到信号量的执行 信号量-1  只有3个拿到（因为信号量只有3） 其他7个没有拿到的阻塞 等着其中一个执行完+1 剩下7个进程抢
    # 直到其他7个都抢到 并执行完 程序结束
    print("%d 拿到信号量开始执行" % os.getpid())
    time.sleep(1)
    # 1个进程执行完成 信号量+1 变为1 这样剩余的7个进程 就有一个解除阻塞 执行任务
    sem.release()

if __name__ == "__main__":
    # 创建信号量
    sem = Semaphore(3)
    # 定义空列表，存放所有进程对象
    pList = []

    for i in range(10):
        p = Process(target=f1)
        pList.append(p)
        p.start()

    for p in pList:
        p.join()


"""
out=[]
visited=[False]*N
def visit(depth,N,M):
    if depth==M:
        print(' '.join(map(str,out)))
        return
    for i in range(N):
        if not visited[i]:
            visited[i]=True
            out.append(i+1)
            visit(depth+1,N,M)
            visited[i]=False
            out.pop()
visit(0,N,M)
"""

N,M=map(int,input().split())
number=[]
visited=[False]*N
def printN(depth):
    global N,M
    if depth==M:
        print(' '.join(map(str,number)))
        return
    for i in range(N):
        if visited[i]==False:
            visited[i]=True
            number.append(i+1)
            printN(depth+1)
            visited[i]=False
            number.pop()
printN(0)


from flask import Response, request
from database.models import Movie, User
from flask_restplus import Resource,fields
from flask_jwt_extended import jwt_required, get_jwt_identity
from mongoengine.errors import FieldDoesNotExist, NotUniqueError, \
                                DoesNotExist,ValidationError
import resources.errors as errors
from app import api

class MoviesApi(Resource):
    @api.response(200, 'Success')
    @api.response(400, 'Validation Error')
    def get(self):
        movies = Movie.objects().to_json()
        return Response(movies, mimetype="application/json", status = 200)

    @jwt_required()
    def post(self):
        try:
            user_id = get_jwt_identity()
            body = request.get_json()
            user = User.objects.get(id=user_id)
            movie = Movie(**body, added_by= user)
            movie.save()
            user.update(push__movies=movie)
            user.save()
            id = movie.id
            return {"id": str(id)}, 200
        except(FieldDoesNotExist, ValidationError):
            raise errors.SchemaValidationError
        except(NotUniqueError):
            raise errors.MovieAlreadyExistsError
        except Exception as e:
            raise errors.InternalServerError

class MoviesApiId(Resource):
    @api.response(200, 'Success')
    @api.response(400, 'Validation Error')
    def get(self, id):
        movie = Movie.objects(id=id).to_json()
        return Response(movie, mimetype="application/json", status = 200)

    @jwt_required()
    def put(self,id):
        try:
            user_id = get_jwt_identity()
            Movie.objects.get(id=id, added_by=user_id)
            body = request.get_json()
            Movie.objects.get(id = id).update(**body)
            return '', 200
        except errors.InvalidQueryError:
           raise errors.SchemaValidationError
        except DoesNotExist:
           raise errors.UpdatingMovieError
        except Exception:
           raise errors.InternalServerError

    @jwt_required()
    def delete(self, id):
        try:
            user_id = Movie.objects.get(id=id).delete()
            movie = Movie.objects.get(id=id, added_by=user_id)
            movie.delete()
            return '', 200
        except DoesNotExist:
            raise errors.MovieNotExistsError
        except Exception:
            raise errors.InternalServerError


import tensorflow as tf
import dataflow as D
import time
import numpy as np
import datetime
from multiprocessing import cpu_count
from augmentation.augment.utils import compose_augmentations

def benchmark(dataflow, num_epochs=2, sleep=0.):
    start_time = time.perf_counter()
    for epoch_num in range(num_epochs):
        s = time.time()
        counter = 0
        for _ in dataflow:
            # Performing a training step
            time.sleep(sleep)
            counter += 1
            pass
        tf.print(f"Samples counted: {counter}")
        e = time.time()
        tf.print(f'{e - s}s elapsed.')
    tf.print("Total execution time:", time.perf_counter() - start_time)

def dataflow_len(dataflow):
    """
    Compute the length of a dataflow.
    """
    tot = 0
    for data in dataflow:
        tot += data[0].shape[0]
        print(tot)
    return tot

def create_direct_dataflow(tf_dataset,
                           batch_size,
                           augmentations=(),
                           gpu_augmentations=(),
                           label_augmentations=(),
                           num_proc=cpu_count(),
                           test_flow=True,
                           ):

    # Create a dataflow
    dataflow = D.DataFromGenerator(tf_dataset)
    # Map the tensors to numpy arrays
    dataflow = D.MapData(dataflow, func=lambda x: (x[0].numpy(), x[1].numpy()))
    # Batch the data
    dataflow = D.BatchData(dataflow, batch_size=batch_size)
    # Repeat the data only once, we use a custom loop over epochs
    dataflow = D.RepeatedData(dataflow, 1)
    # Create a function for data augmentations
    daug = lambda x: compose_augmentations((compose_augmentations(x[0], augmentations), x[1]), label_augmentations)
    # Map the function onto the data
    dataflow = D.MapData(dataflow, func=daug)
    # Create a function for gpu data augmentations
    gpu_daug = lambda x: (compose_augmentations(x, gpu_augmentations))
    # Map the function onto the data
    dataflow = D.MapDataComponent(dataflow, func=gpu_daug, index=0)

    if test_flow:
        # A quick runthrough of all the data
        D.TestDataSpeed(dataflow, size=128).start()
    else:
        # Reset state manually
        dataflow.reset_state()

    return dataflow

def create_paired_direct_dataflow(tf_dataset_1,
                                  tf_dataset_2,
                                  batch_size,
                                  augmentations,
                                  x_only=False,
                                  num_proc=cpu_count(),
                                  test_flow=True,
                                  cache_dir1='',
                                  cache_dir2='',
                                  shuffle=True,
                                  shuffle_buffer=1000):
    # Cache the dataset first
    tf_dataset_1 = tf_dataset_1.cache(cache_dir1).prefetch(tf.data.experimental.AUTOTUNE)
    tf_dataset_2 = tf_dataset_2.cache(cache_dir2).prefetch(tf.data.experimental.AUTOTUNE)

    try:
        # Unbatch them
        tf_dataset_1 = tf_dataset_1.unbatch()
        tf_dataset_2 = tf_dataset_2.unbatch()
    except ValueError:
        pass

    if shuffle:
        # Shuffle the data
        tf_dataset_1 = tf_dataset_1.shuffle(shuffle_buffer, seed=1)
        tf_dataset_2 = tf_dataset_2.shuffle(shuffle_buffer, seed=2)

    # Run through to cache the datasets: this is necessary to do, otherwise it won't work
    for _ in tf_dataset_1.batch(batch_size):
        print('.', end='')
        pass

    for _ in tf_dataset_2.batch(batch_size):
        print('.', end='')
        pass

    # Create a dataflow
    dataflow_1 = D.DataFromGenerator(tf_dataset_1)
    dataflow_2 = D.DataFromGenerator(tf_dataset_2)
    # Map the tensors to numpy arrays
    dataflow_1 = D.MapData(dataflow_1, func=lambda x: (x[0].numpy(), x[1].numpy()))
    dataflow_2 = D.MapData(dataflow_2, func=lambda x: (x[0].numpy(), x[1].numpy()))
    # Select some indices in the data
    if x_only:
        dataflow_1 = D.SelectComponent(dataflow_1, [0])
        dataflow_2 = D.SelectComponent(dataflow_2, [0])
    # Zip them
    dataflow = D.JoinData([dataflow_1, dataflow_2])
    # Batch data
    dataflow = D.BatchData(dataflow, batch_size=batch_size, remainder=True)
    # Repeat data only once, we use a custom loop over epochs
    dataflow = D.RepeatedData(dataflow, 1)
    # Create a function for data augmentations
    if not x_only:
        daug = lambda x: (compose_augmentations(x[0], augmentations), x[1],
                          compose_augmentations(x[2], augmentations), x[3])
    else:
        daug = lambda x: (compose_augmentations(x[0], augmentations),
                          compose_augmentations(x[1], augmentations))
    # Map the function onto the data
    dataflow = D.MapData(dataflow, func=daug)
    if test_flow:
        # A quick runthrough of all the data
        D.TestDataSpeed(dataflow).start()
    else:
        # Reset state manually
        dataflow.reset_state()
    return dataflow

def create_parallel_dataflow_via_numpy(tf_dataset,
                                       batch_size,
                                       augmentations=(),
                                       gpu_augmentations=(),
                                       x_only=False,
                                       num_proc=cpu_count(),
                                       test_flow=True):
    X, y = [], []
    # Materialize the dataset as a numpy array: this is memory intensive for large datasets!
    for data in tf_dataset:
        X.append(data[0].numpy())
        y.append(data[1].numpy())
    numpy_dataset = list(zip(np.array(X), np.array(y)))
    # Create a dataflow
    dataflow = D.DataFromList(numpy_dataset)
    # Select some indices in the data
    if x_only:
        dataflow = D.SelectComponent(dataflow, [0])
    # Batch data
    dataflow = D.BatchData(dataflow, batch_size=batch_size)
    # Repeat data only once, we use a custom loop over epochs
    dataflow = D.RepeatedData(dataflow, 1)
    # Create a function for data augmentations
    if not x_only:
        daug = lambda x: (compose_augmentations(x[0], augmentations), x[1])
    else:
        daug = lambda x: (compose_augmentations(x[0], augmentations))
    # Map the function onto the data with parallelism
    dataflow = D.MultiProcessMapData(dataflow, num_proc=num_proc, map_func=daug, strict=True)
    # Create a function for gpu data augmentations
    gpu_daug = lambda x: (compose_augmentations(x, gpu_augmentations))
    # Map the function onto the data
    dataflow = D.MapDataComponent(dataflow, func=gpu_daug, index=0)
    if test_flow:
        # A quick runthrough of all the data
        D.TestDataSpeed(dataflow).start()
    return dataflow

def create_paired_parallel_dataflow_via_numpy(tf_dataset_1,
                                              tf_dataset_2,
                                              batch_size,
                                              augmentations,
                                              x_only=False,
                                              num_proc=cpu_count(),
                                              test_flow=True):
    X_1, y_1 = [], []
    X_2, y_2 = [], []
    # Materialize the dataset as a numpy array: this is memory intensive for large datasets!
    for data in tf_dataset_1:
        X_1.append(data[0].numpy())
        y_1.append(data[1].numpy())

    for data in tf_dataset_2:
        X_2.append(data[0].numpy())
        y_2.append(data[1].numpy())

    numpy_dataset_1 = list(zip(np.array(X_1), np.array(y_1)))
    numpy_dataset_2 = list(zip(np.array(X_2), np.array(y_2)))
    # Create a dataflow
    dataflow_1 = D.DataFromList(numpy_dataset_1)
    dataflow_2 = D.DataFromList(numpy_dataset_2)
    # Select some indices in the data
    if x_only:
        dataflow_1 = D.SelectComponent(dataflow_1, [0])
        dataflow_2 = D.SelectComponent(dataflow_2, [0])
    # Zip them
    dataflow = D.JoinData([dataflow_1, dataflow_2])
    # Batch data
    dataflow = D.BatchData(dataflow, batch_size=batch_size)
    # Repeat data only once, we use a custom loop over epochs
    dataflow = D.RepeatedData(dataflow, 1)
    # Create a function for data augmentations
    if not x_only:
        daug = lambda x: (compose_augmentations(x[0], augmentations), x[1],
                          compose_augmentations(x[2], augmentations), x[3])
    else:
        daug = lambda x: (compose_augmentations(x[0], augmentations),
                          compose_augmentations(x[1], augmentations))
    # Map the function onto the data with parallelism
    dataflow = D.MultiProcessMapData(dataflow, num_proc=num_proc, map_func=daug, strict=True)
    if test_flow:
        # A quick runthrough of all the data
        D.TestDataSpeed(dataflow).start()
    return dataflow

def build_basic_data_pipeline(datasets, n_examples, batch_size, map_fn, map_fn_args):
    """
    Builds a basic data pipeline for multiple datasets by,
    - Restricting the dataset to a few examples with take (use n_examples = -1 as default to fetch whole dataset)
    - Batching data with batch
    - Prefetching batches of data, keeping CPU busy for speedup
    - Applying multiple augmentations to the data in sequence using a map_fn and map_fn_args. map_fn_args
    is a list of list of arguments. Each list of arguments corresponds to an augmentation we would like to map on
    the dataset.

    Example:
    map_fn = data_map
    map_fn_args = [[BasicImagePreprocessingPipeline], [NoAugmentationPipeline]]
    applies the two augmentations to the dataset in sequence.

    :param datasets: list of datasets
    :param n_examples: number of examples to take
    :param batch_size: batch size
    :param map_fn: function to map over the data for augmentation
    :param map_fn_args: list of lists. Each inner list contains arguments to pass to map_fn.
    :return: the list of augmented datasets
    """

    augmented_datasets = []
    for dataset in datasets:
        # Take some examples, batch the dataset and enable prefetching
        dataset = dataset.take(n_examples).batch(batch_size).prefetch(tf.data.experimental.AUTOTUNE)
        # Map some transformation over the dataset
        for args in map_fn_args:
            dataset = dataset.map(lambda image, label: map_fn(image, label, *args))
        # Append the augmented dataset
        augmented_datasets.append(dataset)

    return augmented_datasets


########################################################################################################
# The RWKV Language Model - https://github.com/BlinkDL/RWKV-LM
########################################################################################################

import json, math, random, os, sys
import numpy as np
import torch
from torch.utils.data import Dataset
from pytorch_lightning.utilities import rank_zero_info
from .binidx import MMapIndexedDataset
from .utils import MaybeIsPrime
from .utils import TOKENIZER

class DatasetJA(Dataset):
    def __init__(self, args):
        self.args = args
        self.ctx_len = args.ctx_len
        self.data = open(args.data_file, "r", encoding=args.data_type).read()
        self.data_size = len(self.data)

        self.t = TOKENIZER([
                "20B_tokenizer.json",
                "20B_tokenizer.json",
        ])
        self.data = open(args.data_file, "r", encoding=args.data_type).read()
        self.vocab_size = self.t.vocab_size

    def __len__(self):
        return self.args.epoch_steps * self.args.micro_bsz

    def _encode(self, d):
       return self.t.tokenizer.encode(
            d,
            padding="max_length",
            max_length=self.ctx_len,
            return_tensors="pt",
            add_special_tokens=False,
            dtype=torch.long
       )
    def __getitem__(self, idx):
        data = self.data[idx: self.ctx_len]
        x = self._encode(data[1])
        y = self._encode(data[:-1])
        return x, y


import sys
input = sys.stdin.readline

#레이저 방향 변환 함수
def find_direction(x_, y_):
    x, y = x_, y_

    if x == 0:
        return 2
    elif x == n + 1:
        return 0
    elif y == 0:
        return 1
    elif y == n + 1:
        return 3

#레이저 이동 재귀함수
def move_laser(start, direction):
    global out_x, out_y
    x, y = start
    x, y = x + dx[direction], y + dy[direction]

    #밖으로
    if x in (0, n + 1) or y in (0, n + 1):
        out_x, out_y = str(x), str(y)
        return

    #거울이면
    if board[x][y] != 0:
        new_direction = (direction + 1) % 4
        #오른쪽 90도 회전

        #보드 값이 새 방향과 같은 경우(무한반복)
        if board[x][y] == new_direction:
            out_x, out_y = '0', '0'
            return

        #보드 값을 새 방향 값으로 갱신
        board[x][y] = new_direction
        direction = new_direction

    #다음 칸으로 이동
    move_laser((x, y), direction)

T = int(map(int, input.split()))

for _ in range(T):

    n, r = map(int, input.split())
    board = [[0] * (n + 2) for _ in range(n + 2)]

    #거울 위치
    for _ in range(r):
        x, y = map(int, input.split())
        board[x][y] = -1

    #레이저 시작, 방향
    laser = tuple(map(int, input.split()))
    laser_direction = find_direction(laser[0], laser[1])

    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]

    #레이저 빔의 마지막 좌표
    out_x, out_y = -1, -1

    #레이저 이동
    move_laser(laser, laser_direction)
    print(out_x + ' ' + out_y)


import os

import click
import pandas
import tabulate

from clapper.click import verbosity_option
from clapper.logging import setup
from tqdm import tqdm

logger = setup(__name__.split(".")[0], format="%(levelname)s: %(message)s")

@click.command(
    epilog="""Examples:

\b
  1. Compares system A and B, with their own pre-computed measure files:

     .. code:: sh

        $ deepdraw compare -vv A path/to/A/train.csv B path/to/B/test.csv
""",
)
@click.argument(
    "label_path",
    nargs=-1,
)
@click.option(
    "--output-figure",
    "-f",
    help="Path where write the output figure (any extension supported by "
    "matplotlib is possible).  If not provided, does not produce a figure.",
    required=False,
    default=None,
    type=click.Path(dir_okay=False, file_okay=True),
)
@click.option(
    "--table-format",
    "-T",
    help="The format to use for the comparison table",
    show_default=True,
    required=True,
    default="rst",
    type=click.Choice(tabulate.tabulate_formats),
)
@click.option(
    "--output-table",
    "-u",
    help="Path where write the output table. If not provided, does not write "
    "write a table to file, only to stdout.",
    required=False,
    default=None,
    type=click.Path(dir_okay=False, file_okay=True),
)
@click.option(
    "--threshold",
    "-t",
    help="This number is used to select which F1-score to use for "
    "representing a system performance.  If not set, we report the maximum "
    "F1-score in the set, which is equivalent to threshold selection a "
    "posteriori (biased estimator), unless the performance file being "
    "considered already was pre-tunned, and contains a 'threshold_a_priori' "
    "column which we then use to pick a threshold for the dataset. "
    "You can override this behaviour by either setting this value to a "
    "floating-point number in the range [0.0, 1.0], or to a string, naming "
    "one of the systems which will be used to calculate the threshold "
    "leading to the maximum F1-score and then applied to all other sets.",
    default=None,
    show_default=False,
    required=False,
)
@click.option(
    "--plot-limits",
    "-L",
    help="""If set, must be a 4-tuple containing the bounds of the plot for
    the x and y axis respectively (format: x_low, x_high, y_low,
    y_high]).  If not set, use normal bounds ([0, 1, 0, 1]) for the
    performance curve.""",
    default=[0.0, 1.0, 0.0, 1.0],
    show_default=True,
    nargs=4,
    type=float,
)
@verbosity_option(
    logger=logger,
)
@click.pass_context
def compare(
    ctx,
    label_path,
    output_figure,
    table_format,
    output_table,
    threshold,
    plot_limits,
    verbose,
    **kwargs,
):
    def _validate_threshold(t, dataset):
        """Validate the user threshold selection.

        Returns parsed threshold.
        """
        if t is None:
            return t

        try:
            # we try to convert it to float first
            t = float(t)
            if t < 0.0 or t > 1.0:
                raise ValueError(
                    "Float thresholds must be within range [0.0, 1.0]"
                )
        except ValueError:
            # it is a bit of text - assert dataset with name is available
            if not isinstance(dataset, dict):
                raise ValueError(
                    "Threshold should be a floating-point number "
                    "if your provide only a single dataset for evaluation"
                )
            if t not in dataset:
                raise ValueError(
                    f"Text thresholds should match dataset names, "
                    f"but {t} is not available among the datasets provided ("
                    f"({', '.join(dataset.keys())})"
                )

        return t

    def _load(data, threshold=None):
        """Plot comparison chart of all evaluated models.

        Parameters
        ----------

        data : dict
            A dict in which keys are the names of the systems and the values are
            paths to ``measures.csv`` style files.

        threshold : :py:class:`float`, :py:class:`str`, Optional
            A value indicating which threshold to choose for selecting a score.
            If set to ``None``, then use the maximum F1-score on that measures file.
            If set to a floating-point value, then use the score that is
            obtained on that particular threshold.  If set to a string, it should
            match one of the keys in ``data``.  It then first calculate the
            threshold reaching the maximum score on that particular dataset and
            then applies that threshold to all other sets. Obs: If the task
            is segmentation, the score used is the F1-Score.

        Returns
        -------

        data : dict
            A dict in which keys are the names of the systems and the values are
            dictionaries that contain two keys:

            * ``df``: A :py:class:`pandas.DataFrame` with the measures data loaded
              to
            * ``threshold``: A threshold to be used for summarization, depending on
              the ``threshold`` parameter set on the input
        """

        col_name = "mean_f1_score"
        score_name = "F1-score"

        if isinstance(threshold, str):
            logger.info(
                f"Calculating threshold from maximum {score_name} at "
                f"'{threshold}' dataset..."
            )
            measures_path = data[threshold]
            df = pandas.read_csv(measures_path)
            use_threshold = df.threshold[df[col_name].idxmax()]
            logger.info(f"Dataset '*': threshold = {use_threshold:.3f}'")

        elif isinstance(threshold, float):
            use_threshold = threshold
            logger.info(f"Dataset '*': threshold = {use_threshold:.3f}'")

        # loads all data
        retval = {}
        for name, measures_path in tqdm(data.items(), desc="sample"):
            logger.info(f"Loading measures from {measures_path}...")
            df = pandas.read_csv(measures_path)

            if threshold is None:
                if "threshold_a_priori" in df:
                    use_threshold = df.threshold[df.threshold_a_priori.idxmax()]
                    logger.info(
                        f"Dataset '{name}': threshold (a priori) = "
                        f"{use_threshold:.3f}'"
                    )
                else:
                    use_threshold = df.threshold[df[col_name].idxmax()]
                    logger.info(
                        f"Dataset '{name}': threshold (a posteriori) = "
                        f"{use_threshold:.3f}'"
                    )

            retval[name] = dict(df=df, threshold=use_threshold)

        return retval

    # hack to get a dictionary from arguments passed to input
    if len(label_path) % 2 != 0:
        raise click.ClickException(
            "Input label-paths should be doubles"
            " composed of name-path entries"
        )
    data = dict(zip(label_path[::2], label_path[1::2]))

    threshold = _validate_threshold(threshold, data)

    # load all data measures
    data = _load(data, threshold=threshold)

    from ..utils.plot import precision_recall_f1iso
    from ..utils.table import performance_table

    if output_figure is not None:
        output_figure = os.path.realpath(output_figure)
        logger.info(f"Creating and saving plot at {output_figure}...")
        os.makedirs(os.path.dirname(output_figure), exist_ok=True)
        fig = precision_recall_f1iso(data, limits=plot_limits)
        fig.savefig(output_figure)
        fig.clear()

    logger.info("Tabulating performance summary...")
    table = performance_table(data, table_format)
    click.echo(table)
    if output_table is not None:
        output_table = os.path.realpath(output_table)
        logger.info(f"Saving table at {output_table}...")
        os.makedirs(os.path.dirname(output_table), exist_ok=True)
        with open(output_table, "w") as f:
            f.write(table)