from django.db import models
from django.urls import reverse
from django.conf import settings

class Analysis(models.Model):
    CONCENTRATION_UNIT_CHOICES = [
        ("mg/l", "mg/l"),
        ("g/l", "g/l"),
        ("mg/ml", "mg/ml"),
        ("mol/l", "mol/l"),
    ]

    analysis_name = models.CharField(
        "Nome da Análise",
        max_length=255,
        help_text="Digite um nome para identificar sua análise.",
    )
    substance_name = models.CharField(
        "Nome da Substância",
        max_length=255,
        help_text="Digite o nome da substância que você está analisando.",
    )
    absorbance = models.CharField(
        "Absorbâncias",
        max_length=255,
        help_text="Valores das absorbâncias lidas separados por vírgula.",
    )
    concentration = models.CharField(
        "Concentrações",
        max_length=255,
        help_text="Valores das concentrações para cada absorbância fornecida separados por vírgulas.",
    )

    concentration_units = models.CharField(
        "Unidades das Concentrações",
        max_length=255,
        help_text="Valores das unidades das concentrações.",
        choices=CONCENTRATION_UNIT_CHOICES,
        default="mg/l",
    )

    analyst = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        default=1,
        verbose_name="Analista",
    )

    created = models.DateTimeField("Data de Criação", auto_now_add=True, blank=True)

    updated = models.DateTimeField("Data de Atualização", auto_now=True, blank=True)

    class Meta:
        verbose_name_plural = "Analyses"

    def get_absolute_url(self):
        return reverse("analysis-detail", args=[str(self.id)])

    def __str__(self):
        return f"{self.analysis_name} -> {self.substance_name} -> {self.id}"


def question24():
    inf = input().split()
    caseNum = int(inf[0])
    keyNum = int(inf[1])
    cases = list(map(int, input().split()))
    keys = list(map(int, input().split()))
    evenCase = 0
    evenKey = 0
    for i in cases:
        if i % 2 == 0:
            evenCase += 1
    for i in keys:
        if i % 2 == 0:
            evenKey += 1
    oddCase = caseNum - evenCase
    oddKey = keyNum - evenKey
    return min(oddCase,evenKey)+min(evenCase,oddKey)

if __name__ == '__main__':
    print(question24())


import tensorflow as tf

from encoder_layer import EncoderLayer
from pos_embedding import PositionalEmbedding

class Encoder(tf.keras.layers.Layer):
    def __init__(self, num_layers, model_dim, num_heads, ff_dim, vocab_size, dropout_rate=0.1):
        super().__init__()

        self.model_dim = model_dim
        self.num_layers = num_layers

        self.pos_embedding = PositionalEmbedding(vocab_size=vocab_size, model_dim=model_dim, sentence_size=128)

        self.enc_layers = [
            EncoderLayer(model_dim=model_dim, num_heads=num_heads, ff_dim=ff_dim, dropout_rate=dropout_rate)
            for _ in range(num_layers)]

        self.dropout = tf.keras.layers.Dropout(dropout_rate)

    def call(self, x):
        x = self.pos_embedding(x)

        x = self.dropout(x)

        for i in range(self.num_layers):
            x = self.enc_layers[i](x)

        return x


def makeIntList(list):
    count = 0;
    while (count < len(list)):
        list[count] = int(list[count]);
        count += 1;
    return list;
def leftLeastNum(list):
    i=0;
    ans=[];
    while(i<len(list)):
        j=i-1;
        while(j>=0):
            if(list[j]<list[i]):
                ans.append(list[j]);
                break;
            j-=1;
        else:
            ans.append(-1);
        i+=1;
    i=0;
    while(i<len(ans)):
        print(ans[i],end=" ");
        i+=1;
    print();
Total=int(input());
i=0;
while(i<Total):
    size=int(input());
    list=makeIntList(input().split(" "));
    leftLeastNum(list);
    i+=1;


import pymongo

__author__ = 'Manos'

import csv
from optparse import OptionParser

from pymongo import MongoClient
from datetime import datetime
import time

mongo_client=MongoClient('mongodb://localhost:27017/')
db=mongo_client.mydb
db_col=db.things

result3a = db.things.find({},{"timestamp": 1} ).sort("timestamp",pymongo.DESCENDING).limit(1)

print("query 3")
for row in result3a:
    print("The last message published on:", end=" ")
    print(row["timestamp"])

result3b = db.things.find({"timestamp":{'$ne':None}},{"timestamp": 1} ).sort("timestamp",pymongo.ASCENDING).limit(1)

for rb in result3b:
    print("The earliest message published on:", end=" ")
    print(rb["timestamp"])

print("query 4")

tmax = row["timestamp"]
dmax = datetime.strptime(tmax, "%Y-%m-%d %H:%M:%S")
secondmax=time.mktime(dmax.timetuple())

tmin = rb["timestamp"]
dmin = datetime.strptime(tmin, "%Y-%m-%d %H:%M:%S")
secondmin=time.mktime(dmin.timetuple())

# print(secondmax)
all_plithos_msg=db.things.find().count()
deltatimemean = ((secondmax - secondmin) / (all_plithos_msg -1))
print("The mean time delta between all messages is :", end=" ")
print(deltatimemean)


import random
print("Rock Paper Scissors \n"
"choose R for rock \n"
"choose P for paper \n"
"choose S for scissors \n")
while True:
    options=["R", "S", "P"]
    cpu = random.choice(options)
    player = None

    while player not in options:

        player=input("what do you pick: ")
        if player not in options:
            print("Error 404, try again")
        else:
            print("You:",player)
            print("CPU:",cpu)
        if player == cpu:
            print("Ït's a tie")
            continue
        elif player == "R":
            if cpu == "S":
                print("Rock beats scissors,You win!")
            if cpu == "P":
                print("Paper beats rock, You lost to computer.")
        elif player == "S":
            if cpu == "P":
                print("Scissors beats Paper, You win!")
            if cpu == "R":
                print("Rock beats scissors, You lost to computer.")
        elif player == "P":
            if cpu == "R":
                print("Paper beats Rock, You win!")
            if cpu == "S":
                print("Scissors beats Paper, You lost to computer.")

        exit = input("\nWould you like to play again? Y/N")
        if exit=="N":
            break


from elasticsearch_dsl import (
    Document,
    Object,
    InnerDoc,
    Double,
    Text,
    Keyword,
    Boolean,
    RankFeature
)  # the data types needed
from elasticsearch_dsl.connections import connections

from config.settings import ELASTICSEARCH_DSL

# create a default connection to the host

es_client = connections.create_connection(hosts=ELASTICSEARCH_DSL['default']['hosts'])

class ChannelInnerDoc(InnerDoc):
    id = Keyword(required=True)
    subs = RankFeature()  # you won't really need this.
    lang_code = Keyword()

class VideoInnerDoc(InnerDoc):
    id = Keyword(required=True)
    views = RankFeature()
    # likes = RankFeature()
    # dislikes = RankFeature()
    # like_ratio = RankFeature()
    publish_date_int = RankFeature()
    category = Keyword()  # should be a keyword
    title = Text()  # might come in handy for context2def later
    channel = Object(ChannelInnerDoc)

class CaptionInnerDoc(InnerDoc):
    id = Keyword(required=True)
    is_auto = Boolean()
    lang_code = Keyword()
    video = Object(VideoInnerDoc)

class GeneralDoc(Document):
    # define the fields here
    start = Double()
    duration = Double()
    content = Text()
    prev_id = Keyword()
    next_id = Keyword()
    context = Text()
    caption = Object(CaptionInnerDoc)

    class Index:
        name = "general_idx"
        # using the default settings for now.

    def save(self, **kwargs):
        # do something before save here, if you wish
        return super().save(**kwargs)

class OpenSubDoc(Document):
    # define the fields here
    response = Text()
    # contexts. array of strings. might want to make it searchable..?
    # in elastic search, there is no dedicated "array" data type.
    # every datatype can have one or more values.
    # https://www.elastic.co/guide/en/elasticsearch/reference/current/array.html
    contexts = Text()

    class Index:
        name = "opensub_idx"

    def save(self, **kwargs):
        # do something before saving here, if you wish.
        return super().save(**kwargs)


import requests
from unittest import TestCase
from GameDesignerAI import GameDesignerAI

base_url='http://localhost:8003'

class GameDesignerAIAPITests(TestCase):

    def test_extract(self):
        pass

    def test_get_conversation(self):
        print('---test_get_conversation---')
        response = requests.get(f"{base_url}/get_conversation", json={'world_name':'test_world_name'})
        if response.status_code == 200:
            print(response.json())
            print('Conversation:\n', response.json()['conversation'])
        else:
            print(f"Request failed with status {response.status_code}")

    def test_message_game_designer_ai_and_get_response(self):
        print('---test_message_game_designer_ai_and_get_response---')
        request_payload={
            'world_name':'test_world_name',
            'user_message':'are there any characters already made?'
        }
        response = requests.post(f"{base_url}/message_game_designer_ai_and_get_response", json=request_payload)
        if response.status_code == 200:
            print(response.json())
            print('Response:\n', response.json()['response'])
        else:
            print(f"Request failed with status {response.status_code}")

tc = GameDesignerAIAPITests()
# tc.test_get_conversation()
tc.test_message_game_designer_ai_and_get_response()


import numpy as np
import os
import faiss
import time

dataset_list = [
    '/home/y/yujianfu/similarity_search/datasets/ANN_SIFT10K/SIFT10K_base.npy',
]

entropy_list = [
    '/home/y/yujianfu/similarity_search/datasets/ANN_SIFT10K/entropy.npy'
]

save_path = '/home/y/yujianfu/similarity_search/datasets/'
k_list = [3, 5, 10, 50]

for dataset_index in range(len(dataset_list)):
    dataset_path = dataset_list[dataset_index]
    dataset_name = 'ANN_SIFT10K'
    #dataset_path.split('/')[-1].split('_')[0]
    entropy_path = entropy_list[dataset_index]

    dataset = np.ascontiguousarray(np.load(dataset_path).astype('float32'))
    instances = dataset.shape[0]
    dimension = dataset.shape[1]
    dataset = np.ascontiguousarray(np.transpose(dataset))

    entropy = np.load(entropy_path)
    performance = np.zeros((dimension, 9))
    index_brute = faiss.IndexFlatL2(instances)
    index_brute.add(dataset)
    quantilizer = faiss.IndexFlatL2(instances)
    index = faiss.IndexHNSWFlat(instances, 12)
    index.hnsw.efConstruction = 100
    index.hnsw.efSearch = 40
    index.add(dataset)

    for i in range(dimension):
        performance[i, 0] = entropy[i, 0]
        dis_truth, id_truth = index_brute.search(dataset[i, :].reshape(1, -1), k_list[-1])
        for j in range(len(k_list)):
            k = k_list[j]
            time_start = time.time()
            dis_search, ID_search = index.search(dataset[i, :].reshape(1, -1), k)
            time_end = time.time()
            qps = 1 / (time_end - time_start)
            dis_truth, id_truth = index_brute.search(dataset[i, :].reshape(1, -1), k)
            recall = len(set(id_truth[0,:]) & set(ID_search[0,:]))/len(set(id_truth[0, :]))
            #print(id_truth, ID_search)
            performance[i, 2*j+1] = recall
            performance[i, 2*j+2] = qps
            print('the result now is: ', i, k, recall, qps)

    np.save(os.path.join(save_path, dataset_name, 'entropy_performance.npy'),performance)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep  2 16:02:38 2022

@author: andy
"""

import re

def fasta_to_dict(fasta):
    """
    Parameters
    ----------
    fasta : String
        Fasta file read in from Rosalind, each genome is labelled in the form
        of Rosalind_xxxx

    Returns
    -------
    fasta_dict : Dictionary
        Returns a dictionary where the key is the name of the genome and
        the value is the genome
    """
    fasta_list_no_ws = fasta.replace("\n","")
    genome_list = list(filter(None,re.split(">Rosalind_[0-9]{0,4}",fasta_list_no_ws)))
    genome_names = re.findall("Rosalind_[0-9]{0,4}",fasta_list_no_ws)

    fasta_dict = {k:v for k,v in zip(genome_names,genome_list)}
    return fasta_dict

with open("finding_a_shared_motif.txt") as f:
    fasta_in = f.read()
genome_dict = fasta_to_dict(fasta_in)

genome_ref_key = list(genome_dict.keys())[0]
genome_ref_value = genome_dict[genome_ref_key]
genome_no_ref = {k:v for k,v in genome_dict.items() if k != genome_ref_key}

common_string_bool = True
i = 0
j = 1
largest_common_string = ""
while (i + j) < len(genome_ref_value):
    common_string_bool = True
    while common_string_bool:
        genome_string = genome_ref_value[i:i+j]
        common_string_bool = all([genome_string in genome_no_ref[gen] for gen in genome_no_ref])
        if common_string_bool:
            largest_common_string = genome_string
            j += 1
            #print(largest_common_string)
    i += 1


import sqlite3
import sys

DB_NAME = "db/responses.db"

def add_to_db(table, response):
    '''
    Adds a response to the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Add the response to the database
    c.execute(f"INSERT INTO {table} VALUES (?)", (response,))

    # Commit the changes
    conn.commit()

    # Close the connection
    conn.close()

    print("Response added to database")

def delete_from_db(table, response):
    '''
    Deletes a response from the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Delete the response from the database
    c.execute(f"DELETE FROM {table} WHERE response = ?", (response,))

    # Commit the changes
    conn.commit()

    # Close the connection
    conn.close()

    print("Response deleted from database")

def list_responses(table):
    '''
    Lists all the responses in the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Get all the responses
    c.execute(f"SELECT * FROM {table}")
    responses = c.fetchall()

    # Close the connection
    conn.close()

    # Print the responses
    for response in responses:
        print(response[0])

def clear(table):
    '''
    Clears all the responses from the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Delete all the responses from the database
    c.execute(f"DELETE FROM {table}")

    # Commit the changes
    conn.commit()

    # Close the connection
    conn.close()

    print("Responses cleared from database")

def list_tables():
    '''
    Lists all the tables in the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Get all the tables
    c.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = c.fetchall()

    # Close the connection
    conn.close()

    # Print the tables
    for table in tables:
        print(table[0])

def create_table(table):
    '''
    Creates a table in the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Create the table
    c.execute(f"CREATE TABLE {table} (response TEXT)")

    # Commit the changes
    conn.commit()

    # Close the connection
    conn.close()

    print(f"Created table {table}")

def delete_table(table):
    '''
    Deletes a table from the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Delete the table
    c.execute(f"DROP TABLE {table}")

    # Commit the changes
    conn.commit()

    # Close the connection
    conn.close()

    print(f"Deleted table {table}")

def get_random_response(table):
    '''
    Gets a random response from the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Get a random response
    c.execute(f"SELECT response FROM {table} ORDER BY RANDOM() LIMIT 1")
    response = c.fetchone()[0]

    # Close the connection
    conn.close()

    return response

def run_query(query):
    '''
    Runs a query on the database
    '''
    # Connect to the database
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()

    # Run the query
    c.execute(query)
    result = c.fetchall()

    # Close the connection
    conn.close()

    return result

def help():
    print("add <table> <response> - Adds a response to the database")
    print("delete <table> <response> - Deletes a response from the database")
    print("list <table> - Lists all the responses in the database")
    print("clear <table> - Clears all the responses from the database")
    print("list_tables - Lists all the tables in the database")
    print("create_table <table> - Creates a table in the database")
    print("delete_table <table> - Deletes a table from the database")
    print("get_random_response <table> - Gets a random response from the database")
    print("run_query <query> - Runs a query on the database")
    print("help - Shows this help message")

# Run the script from the command line
if __name__ == "__main__":
    # Get the arguments
    args = sys.argv[1:]

    if len(args) == 0:
        help()
        sys.exit()

    # Check if the arguments are valid
    if len(args) < 2 and args[0] != "help" and args[0] != "list_tables":
        print("Invalid arguments")
        sys.exit()

    # Get the command and the response
    command = args[0]
    table = args[1] if len(args) > 1 else None
    response = " ".join(args[2:])

    # Check the command
    if command == "add":
        add_to_db(table, response)
    elif command == "delete":
        delete_from_db(table, response)
    elif command == "list":
        list_responses(table)
    elif command == "clear":
        clear(table)
    elif command == "list_tables":
        list_tables()
    elif command == "create_table":
        create_table(response)
    elif command == "delete_table":
        delete_table(table)
    elif command == "get_random_response":
        print(get_random_response(table))
    elif command == "run_query":
        print(run_query(response))
    elif command == "help":
        help()
    else:
        print("Invalid command")


import os
import errno
from time import sleep
import shutil
import psutil

from PIL import Image

def main() -> None:
    # in_path = "images/initial_images_copied/"
    in_path = "images/"
    merge(in_path)

def merge(in_path: str) -> None:
    out_path = "../../images/moveLevels/"
    delete_directory(out_path)
    create_directory(out_path)
    img_list = []
    for img_path in sorted(os.listdir(in_path)):
        rgb_img = open_img_path(in_path + img_path)
        gray_img = fadeAlpha(rgb_img)
        img_list.append(gray_img)
    merged_img = merge_images(img_list)
    merged_img.save(out_path + 'a0.png')
    for i, img_path in enumerate(sorted(os.listdir(in_path))):
        rgb_img = open_img_path(in_path + img_path)
        new_list = img_list.copy()
        new_list[i] = rgb_img
        merged_img = merge_images(new_list)
        merged_img.save(out_path + 'a' + str(i+1) + ".png")

def merge_images(img_list: list) -> Image:
    image1 = img_list[0]
    i = 1
    while i < len(img_list):
        image2 = img_list[i]
        image1 = merge2images(image1, image2)
        i += 1
    return image1

def merge2images(image1: Image, image2: Image) -> Image:
    # resize, first image
    # image1 = image1.resize((426, 240))
    image1_size = image1.size
    image2_size = image2.size
    new_image = Image.new(
        'RGBA', (image1_size[0]+image2_size[0], image1_size[1]))
    new_image.paste(image1, (0, 0))
    new_image.paste(image2, (image1_size[0], 0))
    return new_image

def fadeAlpha(im2: Image):
    im = im2.copy()
    im.putalpha(255)
    width, height = im.size
    pixels = im.load()
    fade255 = 50
    # for y in range(int(height*.55), int(height*.75)):
    for y in range(height):
        # alpha = 255-int((y - height*.55)/height/.20 * 255)
        for x in range(width):
            pixels[x, y] = pixels[x, y][:3] + (fade255,)
    for y in range(y, height):
        for x in range(width):
            pixels[x, y] = pixels[x, y][:3] + (fade255,)
    return im

def open_img_path(img_path: str) -> Image:
    return Image.open(img_path)

def test_image_by_showing(rgb_img: Image) -> None:
    rgb_img.show()
    sleep(2)
    # hide image
    for proc in psutil.process_iter():
        if proc.name() == "display":
            proc.kill()

def delete_directory(out_path: str) -> None:
    try:
        shutil.rmtree(out_path)
    except OSError as e:
        print("Error: %s : %s" % (out_path, e.strerror))

def create_directory(out_path: str) -> None:
    try:
        os.makedirs(out_path)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

if __name__ == "__main__":
    main()


import collections

import cv2
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

class ImageAnalyzer:
    """
    Esta clase efectúa un recorrido exhaustivo de todas las imágenes que
    conforman el conjunto de datos ISIC 2019, cargándolas una a una y
    examinando sus propiedades.
    """
    def __init__(self, configuration):
        # Establecemos la semilla aleatoria a utilizar.
        self.random_seed = 1000

        # Establecemos el directorio de imágenes a utilizar.
        self.dir_images = configuration["IMAGES_DIR"]

        # Lectura del fichero que describe la clase a la que pertenece cada
        # imagen.
        self.df_images = pd.read_csv(configuration["CLASSES_FILE"])

    def images_report(self):
        """
        Esta función explora y ofrece un informe de las imágenes que se
        encuentran por debajo de un directorio raíz especificado. El informe
        contiene los siguientes elementos:

        - Rango dinámico (valores máximo y mínimo encontrados en sus matrices de
        canales). Cada imagen se obtiene como un array de Numpy con lo que
        podemos utilizar las funciones min() y max() para obtener la respuesta.
        - Tamaño de la imagen: altura x anchura.
        - Número de canales.
        """

        # Recorremos el listado de imágenes obtenido y vamos obteniendo
        # distintas métricas de cada una de ellas.
        range_min = 9999
        range_max = -1
        dimensions = {}
        channels = []
        for i in self.df_images.index:
            # Lectura de la imagen
            image = cv2.imread(
                self.dir_images + '/' + self.df_images["image"][i] + '.jpg')

            # Actualización del valor mínimo encontrado para el rango dinámico
            # global.
            if image.min() < range_min:
                range_min = image.min()

            # Actualización del valor máximo encontrado para el rango dinámico
            # global.
            if image.max() > range_max:
                range_max = image.max()

            # Actualización de la lista de dimensiones de imagen encontradas
            size_pair = (image.shape[0], image.shape[1])
            if size_pair in dimensions:
                classes_dict = dimensions.get(size_pair)
                class_key = self.df_images.columns[
                    np.argmax(self.df_images.loc[i][2:]) + 2]
                if class_key in classes_dict:
                    classes_dict.update(
                        {class_key: classes_dict.get(class_key) + 1})
                else:
                    classes_dict[class_key] = 1
                dimensions.update({size_pair: classes_dict})
            else:
                dimensions[size_pair] = {
                    self.df_images.columns[
                        np.argmax(self.df_images.loc[i][2:]) + 2]: 1
                }

            # Actualización del número de canales encontrado
            channels.append(image.shape[2])

        # Agrupamos y contamos las imágenes que tenemos por número de canales.
        count_channels = collections.Counter(channels)

        # Mostramos el rango dinámico encontrado para el dataset completo.
        print("Rango dinámico: {}-{}".format(range_min, range_max))

        # Mostramos cuántas imágenes tenemos por número de canales.
        print("Número de canales:")
        for j in count_channels.keys():
            print("  - {} -> {} imágenes ({})".format(
                str(j).rjust(7),
                count_channels.get(j),
                str("{:.2f}%".format(
                    count_channels.get(j) / len(self.df_images) * 100))
            ).rjust(6))

        # Mostramos cuántas imágenes tenemos por cada tamaño encontrado.
        print("Dimensiones:")
        for j in dimensions.keys():
            total_images = sum(dimensions.get(j).values())
            for k in dimensions.get(j):
                dimensions.get(j)[k] = "{:.2f}%".format(
                    dimensions.get(j)[k] * 100 / total_images)

            print("  - {}x{} -> {} imágenes ({}) (clases: {})".format(
                str(j[0]).rjust(4),
                str(j[1]).rjust(4),
                str(total_images).rjust(5),
                str("{:.2f}%".format(
                    total_images / len(self.df_images) * 100)).rjust(7),
                dimensions.get(j)
            ))

        # Finalmente mostramos el total de imágenes del conjunto de datos.
        print("Total imágenes del conjunto de entrenamiento:",
              len(self.df_images),
              "(100.00%)")

    def show_sample_images(self, n_images: int) -> None:
        """
        Cargamos y mostramos las primeras imágenes de cada clase usando OpenCV

        :param n_images: número de imágenes de muestra a mostrar.
        """

        for the_class in self.df_images.loc[:, "MEL":"SCC"].columns:
            print("Muestra de la clase " + the_class + ":")
            df_sample_class = \
                self.df_images.loc[self.df_images[the_class] == 1.0].sample(
                    n=n_images, random_state=self.random_seed)

            sample_images = []
            for i in df_sample_class.index:
                sample_images.append(cv2.imread(self.dir_images + "/" +
                                                df_sample_class["image"][i] +
                                                '.jpg'))

            plt.figure(figsize=(16, 10))
            for i in range(1, n_images + 1):
                plt.subplot(1, 5, i)
                plt.grid(False)
                plt.imshow(sample_images[i - 1])
            plt.show()

    def classes_graph(self) -> None:
        """
        Esta función produce un gráfico donde se puede ver la representación de
        cada clase en el conjunto de datos.
        """

        # Mostrar un extracto del contenido del fichero leído
        print(self.df_images)

        # Mostramos un gráfico con la distribución de clases del conjunto de
        # datos,
        # para ello definimos un eje Y con el número de imágenes por clase.
        y = self.df_images.loc[:, "MEL":"UNK"].sum()

        # El eje X con cada una de las clases de imágenes.
        x = self.df_images.columns[1:]

        # Ordenar los datos para apreciar mejor los posibles desequilibrios.
        y, x = zip(*sorted(zip(y, x)))

        # Gráfico que muestra los dos ejes definidos.
        fig = plt.figure()
        ax = fig.add_axes([0, 0, 1, 1])
        ax.bar(x, y)
        ax.set_ylabel("Número de imágenes")
        ax.set_xlabel("Clase")
        patches = ax.patches
        labels = [f"{i}" for i in y]
        for rect, label in zip(patches, labels):
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width() / 2, height, label,
                    ha="center",
                    va="bottom")
        plt.show()


###Q4 final
# sc.stop()
from pyspark import SparkContext
sc = SparkContext(appName="exercise")
def max_temperature(a,b):
    if a>=b:
        return a
    else:
        return b

precipitation_file=sc.textFile("precipitation-readings-tiny.csv")
linesp = precipitation_file.map(lambda line:line.split(";"))

temperature_file=sc.textFile("temperature-readings-tiny.csv")
linest = temperature_file.map(lambda line:line.split(";"))

temperatures = linest.map(lambda x:((x[0],x[1][0:4]),float(x[3])))
precipitations = linesp.map(lambda x:((x[0],x[1][0:4]),float(x[3])))

max_temperatures = temperatures.reduceByKey(max_temperature)  # for each year
max_precipitations = precipitations.reduceByKey(max_temperature)
# print(*max_precipitations.take(10), sep="\n")

station = max_temperatures.join(max_precipitations)
# print(*station.take(10), sep="\n")

station = station.filter(lambda x: x[1][0]>=25 and x[1][0]<=30 and x[1][1]>=100 and x[1][1]<=200)
station = station.map(lambda x:(x[0],x[1][0],x[1][1]))
# print(*station.take(10), sep="\n")

station.saveAsTextFile("station")


#!/usr/bin/env python
from mpi4py import MPI
import numpy as np

# Example of implementing a custom reduction operation
# that identifies array indexes with odd numbers
# in any of the processors

def unpack_array(array_mem, dt):
    a = array_mem.tobytes()
    itemsize = dt.Get_size()
    array_len = int(array_mem.shape[0])
    unpack_array = []
    for i in range(int(array_len/itemsize)):
        unpack_array.append(int(np.frombuffer(a[itemsize*i:itemsize*(i+1)],
                            dtype=np.int64)))
    return np.array(unpack_array)

def myprod(xmem, ymem, dt):
    a = unpack_array(xmem, dt)
    b = unpack_array(ymem, dt)

    c = np.array([0] * len(a))
    for i in range(len(a)):
        c[i] = a[i] % 2 | b[i] % 2

    ymem[:] = memoryview(bytearray(c))[:]

comm = size = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

a = np.array([rank * (i + 1) for i in range(3)])
b = np.array([0] * 3)
print("Rank %d: Data %s" %(rank, a))

myop = MPI.Op.Create(myprod, True) # commute is True
comm.Reduce([a, MPI.DOUBLE], [b, MPI.DOUBLE], op=myop, root=0)

if rank==0:
    print("Contains odd numbers: %s" %(b))


from sqlalchemy import create_engine, MetaData, select, and_, join, text
from sqlalchemy.orm import sessionmaker
from datetime import timedelta, datetime
from pytz import utc
from dotenv import load_dotenv, find_dotenv
from operator import itemgetter
from itertools import groupby
from sqlalchemy.dialects import postgresql
import os

# Load environment variables
load_dotenv(find_dotenv())

# Initialize connection and Session
database_url = os.getenv('POSTGRES_DB_URL')
engine = create_engine(database_url)
Session = sessionmaker(bind=engine)
session = Session()

meta = MetaData()
meta.reflect(bind=engine)

# Map tables
stays = meta.tables['stays']
hotels = meta.tables['hotels']

def fetch_stays(start_date, end_date, hotels_name_text = [], hotel_cities=[], hotel_countries=[], hotel_regions=[], award_categories=[], rate_filter=None):

    filter_conditions = [
        stays.c.check_in_date >= start_date,
        stays.c.check_out_date <= end_date,
        stays.c.duration == 1,
        stays.c.last_checked_time > datetime.now().astimezone(utc) - timedelta(hours=48),
        hotels.c.hotel_brand == 'hyatt'
    ]

    if [name for name in hotels_name_text if name]:
        filter_conditions.append(hotels.c.hotel_name.in_(hotels_name_text))
    if [name for name in hotel_cities if name]:
        filter_conditions.append(hotels.c.hotel_city.in_(hotel_cities))
    if [name for name in hotel_countries if name]:
        filter_conditions.append(hotels.c.hotel_country.in_(hotel_countries))
    if [name for name in hotel_regions if name]:
        filter_conditions.append(hotels.c.hotel_region.in_(hotel_regions))
    if [name for name in award_categories if name]:
        filter_conditions.append(hotels.c.award_category.in_(award_categories))
    if rate_filter == 'Standard':
        filter_conditions.append(stays.c.standard_rate > 0)
    if rate_filter == 'Premium':
        filter_conditions.append(stays.c.premium_rate > 0)

    j = join(stays, hotels, stays.c.hotel_id == hotels.c.hotel_id)

    stay_records = session.execute(
        select(*stays.c, *hotels.c).select_from(j).where(
            and_(*filter_conditions)
        ).group_by(*stays.c, *hotels.c)
        .order_by(hotels.c.hotel_name, stays.c.check_in_date)
    ).fetchall()

    return [record._mapping for record in stay_records]

def get_consecutive_stays(hotel_data, num_consecutive_days, rate_filter=None, max_points_budget=0):
    # Sort data by hotel code and check in date
    hotel_data.sort(key=lambda x: (x['hotel_code'], x['check_in_date']))

    # Group data by hotel code
    grouped_data = groupby(hotel_data, key=itemgetter('hotel_code'))

    result = []

    # Iterate over each group
    for hotel_code, group in grouped_data:
        stays = list(group)

        for i in range(len(stays) - num_consecutive_days + 1):
            result_stay = {}
            # Check if the dates are consecutive
            if all((stays[i + j + 1]['check_in_date'] - stays[i + j]['check_in_date'] == timedelta(days=1) for j in range(num_consecutive_days - 1))):

                standard_rate = 0
                premium_rate = 0

                if all(stay['premium_rate'] > 0 for stay in stays[i:i + num_consecutive_days]):
                    premium_rate = sum(stay['premium_rate'] for stay in stays[i:i + num_consecutive_days]) / num_consecutive_days
                if all(stay['standard_rate'] > 0 for stay in stays[i:i + num_consecutive_days]):
                    standard_rate = sum(stay['standard_rate'] for stay in stays[i:i + num_consecutive_days]) / num_consecutive_days

                if standard_rate == 0 and premium_rate == 0:
                    continue

                response_url, booking_url = build_url('Hyatt', hotel_code, stays[i]['check_in_date'].strftime('%Y-%m-%d'), (stays[i]['check_in_date'] + timedelta(days=num_consecutive_days)).strftime('%Y-%m-%d'), room_qty = 1, adults = 2, kids = 0)

                result_stay = {
                    'hotel_name': stays[i]['hotel_name'],
                    'hotel_code': stays[i]['hotel_code'],
                    'date_range_start': stays[i]['check_in_date'],
                    'date_range_end': stays[i]['check_in_date'] + timedelta(days=num_consecutive_days),
                    'last_checked': stays[i]["last_checked_time"],
                    'standard_rate': standard_rate,
                    'premium_rate': premium_rate,
                    'hotel_city': stays[i]["hotel_city"],
                    'hotel_province': stays[i]["hotel_province"],
                    'hotel_country': stays[i]["hotel_country"],
                    'hotel_region': stays[i]["hotel_region"],
                    'award_category': stays[i]["award_category"],
                    'booking_url': booking_url
                }

                if rate_filter == 'Standard':
                    if max_points_budget == 0 or (standard_rate <= max_points_budget and standard_rate != 0):
                        result.append(result_stay)
                elif rate_filter == 'Premium':
                    if max_points_budget == 0 or (premium_rate <= max_points_budget and premium_rate != 0):
                        result.append(result_stay)
                else:
                    if max_points_budget == 0 or (standard_rate <= max_points_budget and standard_rate != 0) or (premium_rate <= max_points_budget and premium_rate != 0):
                        result.append(result_stay)
    return result

def build_url(hotel_brand, hotel_code, checkin_date, checkout_date, room_qty = 1, adults = 2, kids = 0):
    base_url_dict = {
        'Hyatt': 'https://www.hyatt.com/shop/service/rooms/roomrates/'
    }
    search_base_url_dict = {
        'Hyatt': 'https://www.hyatt.com/shop/rooms/'
    }
    base_url = base_url_dict[hotel_brand] + hotel_code
    search_base_url = search_base_url_dict[hotel_brand] + hotel_code
    response_url = base_url + f'?spiritCode={hotel_code}&rooms={room_qty}&adults={adults}&checkinDate={checkin_date}&checkoutDate={checkout_date}&kids={kids}'
    search_url = search_base_url + f'?checkinDate={checkin_date}&checkoutDate={checkout_date}&rateFilter=woh'
    return response_url, search_url

def search_by_consecutive_nights(start_date, end_date, length_of_stay, hotel_name_text=[], hotel_city=[], hotel_country=[], hotel_region=[], award_category=[], rate_filter=None, max_points_budget=0):
    try:
        records = fetch_stays(start_date=start_date, end_date=end_date, hotels_name_text=hotel_name_text, hotel_cities=hotel_city, hotel_countries=hotel_country, hotel_regions=hotel_region, award_categories=award_category, rate_filter=rate_filter)
        # print(len(records))
        consecutive_stays = get_consecutive_stays(records, length_of_stay, rate_filter, max_points_budget)
        session.close()
        return consecutive_stays
    except Exception as e:
        session.close()
        return "Error in search_stays.py: %s", str(e)

# result = get_consecutive_stays_2(
#     start_date='2023-08-31',
#     end_date='2023-08-31',
#     hotel_cities=['New York', 'Paris'],
#     hotel_countries=['United States', 'France'],
#     award_categories=[],
#     length_of_stay='3',
#     rate_filter=[],
#     max_points_budget='0',
# )


for _ in range(int(input())):
    L=[]
    a=int(input())
    if a <10:
        print(1)
        continue
    cnt=0
    for i in range(9,1,-1):
        while a%i ==0:
            a//=i
            cnt+=1
    if a!=1:
        print(-1)
    else:
        print(cnt)


# 排序算法

from random import shuffle

def quick_sort(nums: tuple, l, r):
    if l<r:
        aim = nums[l]
        i, j = l, r
        while i<j:
            while i<j and nums[j]>aim:
                j -= 1
            while i<j and nums[i]<aim:
                i += 1
            if i<j:
                nums[i], nums[j] = nums[j], nums[i]
        quick_sort(nums, l, i-1)
        quick_sort(nums, i+1, r)

res = [i for i in range(20)]
shuffle(res)
quick_sort(res, 0, len(res)-1)
print(res)


from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import urllib.request
from .scrapper import text_from_html
from .models import Literature

def html_view(request):
    if request.method == 'POST':
        url = request.POST.get('url')
        literature = Literature.objects.filter(url=url).first()
        if literature:
            return JsonResponse({"html": literature.data})
        else:
            html = urllib.request.urlopen(url).read()
            html = text_from_html(html)
            literature = Literature(url=url, data=html)
            literature.save()
            return JsonResponse({"html": html})
    return render(request, 'home/index.html')


class PeFile:
    def __init__(self, data):
        assert data[:2] == b'MZ'
        pe_offset = int.from_bytes(data[60:64], 'little')
        assert data[pe_offset:pe_offset+2] == b'PE'
        self.dos_stub = bytearray(data[:pe_offset])
        self.pe_header = bytearray(data[pe_offset:pe_offset+120])
        noffsets = int.from_bytes(self.pe_header[116:120], 'little')
        nsections = int.from_bytes(self.pe_header[6:8], 'little')
        self.base_addr = base_addr = int.from_bytes(self.pe_header[52:56], 'little')
        self.mem_align = int.from_bytes(self.pe_header[56:60], 'little')
        self.offset_table = []
        for i in range(noffsets):
            t = data[pe_offset+120+i*8:pe_offset+128+i*8]
            rva = int.from_bytes(t[:4], 'little')
            l = int.from_bytes(t[4:], 'little')
            if l == 0:
                self.offset_table.append(None)
            elif i == 4:
                self.offset_table.append(data[rva:rva+l])
            else:
                self.offset_table.append((rva + base_addr, l))
        self.sections = []
        for i in range(nsections):
            t = data[pe_offset+120+noffsets*8+i*40:pe_offset+160+noffsets*8+i*40]
            name = t[:8].decode('latin-1')
            while name[-1:] == '\0': name = name[:-1]
            memsz = int.from_bytes(t[8:12], 'little')
            rva = int.from_bytes(t[12:16], 'little')
            filesz = int.from_bytes(t[16:20], 'little')
            offset = int.from_bytes(t[20:24], 'little')
            flags = int.from_bytes(t[36:40], 'little')
            self.sections.append((name, base_addr+rva, memsz, flags, bytearray(data[offset:offset+filesz])))
    @classmethod
    def from_bytes(self, data):
        return self(data)
    def to_bytes(self):
        self.dos_stub[60:64] = len(self.dos_stub).to_bytes(4, 'little')
        ans = bytearray(self.dos_stub)
        self.base_addr = base_addr = int.from_bytes(self.pe_header[52:56], 'little')
        self.mem_align = int.from_bytes(self.pe_header[56:60], 'little')
        file_align = int.from_bytes(self.pe_header[60:64], 'little')
        self.pe_header[88:92] = bytes(4) # checksum
        self.pe_header[6:8] = len(self.sections).to_bytes(2, 'little')
        self.pe_header[116:120] = len(self.offset_table).to_bytes(4, 'little')
        self.pe_header[80:84] = (max(i[1] + i[2] for i in self.sections) - base_addr).to_bytes(4, 'little')
        ans += self.pe_header
        o_o = []
        for i in self.offset_table:
            if i == None:
                ans += bytes(8)
            elif isinstance(i, bytes):
                o_o.append(len(ans))
                ans += bytes(4) + len(i).to_bytes(4, 'little')
            else:
                va, l = i
                ans += (va - base_addr).to_bytes(4, 'little') + l.to_bytes(4, 'little')
        sz = len(ans) + 40 * len(self.sections)
        for name, va, memsz, flags, data in self.sections:
            rva = va - base_addr
            filesz = len(data)
            sz += (-sz) % file_align
            sz += (-sz) % 4096
            offset = sz
            sz += filesz + (-filesz) % 4096
            ans += name.encode('latin-1') + bytes(8 - len(name))
            ans += memsz.to_bytes(4, 'little')
            ans += rva.to_bytes(4, 'little')
            ans += filesz.to_bytes(4, 'little')
            ans += offset.to_bytes(4, 'little')
            ans += bytes(12)
            ans += flags.to_bytes(4, 'little')
        for name, va, memsz, flags, data in self.sections:
            ans += bytes((-len(ans)) % file_align)
            ans += bytes((-len(ans)) % 4096)
            ans += data
            ans += bytes((-len(ans)) % 4096)
        o_o = iter(o_o)
        for i in self.offset_table:
            if isinstance(i, bytes):
                o = next(o_o)
                ans += bytes((-len(ans)) % 16)
                ans[o:o+4] = len(ans).to_bytes(4, 'little')
                ans += i
        return bytes(ans)


# -*- coding: utf-8 -*-
'''
@createTool    : PyCharm-2020.3.2
@projectName   : pythonProjectPy3.9
@originalAuthor: Made in win10.Sys design by deHao.Zou
@createTime    : 2021/01/27 20:36
'''
# ============================================================================================
'''
目标：实现Excel全部功能
一、单元格样式简介
openpyxl处理Excel文件中单元格样式，总共有六个属性类。
font(字体类----可设置字号、字体颜色、下划线等)
fill(填充类----可设置单元格填充颜色等)
border（边框类----可以设置单元格各种类型的边框）
alignment(位置类----可以设置单元格内数据各种对齐方式)
number_format(格式类----可以设置单元格内各种类型的数据格式)
protection(保护类----可以设置单元格写保护等)
'''
# ============================================================================================
from openpyxl.comments import Comment
from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font, NamedStyle, GradientFill, Color
from openpyxl.cell.cell import WriteOnlyCell
from openpyxl.chart import BarChart, Reference, Series
from openpyxl.utils.dataframe import dataframe_to_rows

'''表格创建'''
workbook = Workbook()  # write_only=True仅写模式,guess_types=True当读取单元格时,guess_types将启用或禁用（默认）类型推断(比如0.34 -> 34%)
worksheet = workbook.active

# 添加评论
# comment = worksheet["A1"].comment
# comment = Comment('This is the comment text', 'Comment Author')
# comment.text  # 'This is the comment text'
# comment.author  # 'Comment Author'

# 创建子页及子页名称
worksheet.title = 'Sheet.NO1'  # 子页名称（默认第一个）
worksheet = workbook.create_sheet('Create.Sheet2', 1)  # # 创建名为Sheet2的子页放在第2
worksheet = workbook.create_sheet('Create.Sheet1', 0)  # 创建名为Sheet1的子页放在第1

# worksheetcopy = workbook["New Title"]  # 给工作表命名后,即可将其作为工作簿的键
# print(workbook.sheetnames) # 打印全部子页名称

# 遍历工作表
# for sheet in workbook:
#     print(sheet.title)

# 在单个工作簿中创建工作表的副本
# 仅复制单元格（包括值,样式,超链接和注释）和某些工作表属性（包括尺寸,格式和属性）.不复制所有其他工作簿/工作表属性-例如图像,图表.
# 您不能在工作簿之间复制工作表.如果工作簿以只读或仅写模式打开,则您也无法复制工作表.
# source = workbook.active
# target = workbook.copy_worksheet(source)

# 工作簿保护
# workbook.security.workbookPassword = ''  # 防止其他用户查看隐藏的工作表,添加,移动,删除或隐藏工作表以及重命名工作表
# worksheet.security.revisionsPassword = ''  # 防止从共享工作簿中删除更改跟踪和更改历史记录
# workbook.security.set_workbook_password(hashed_password = '', already_hashed=True) # 如果需要在不使用默认哈希算法的情况下设置原始密码值，则提供特定的设置器功能

# 工作表保护
# 如果未指定密码,则用户无需指定密码即可禁用配置的工作表保护。否则,他们必须提供密码才能更改已配置的保护。
# workbook.protection.sheet = True # 设置属性来锁定工作表的各个方面
# workbook.protection.password = ''  # 属性设置密码

'''全局设置样式'''
# 子页全局背景颜色
worksheet.sheet_properties.tabColor = "1072BA"  # 默认白色

# 编辑页面设置
worksheet.page_setup.orientation = worksheet.ORIENTATION_LANDSCAPE
worksheet.page_setup.paperSize = worksheet.PAPERSIZE_TABLOID
worksheet.page_setup.fitToHeight = 0
worksheet.page_setup.fitToWidth = 1

highlight = NamedStyle(name="highlight")
number_format = 'General'

font = Font(name='Calibri',
            size=11,
            bold=True,
            italic=False,
            vertAlign=None,
            underline='none',
            strike=False,
            color='FF000000')
align = Alignment(horizontal='center', vertical='center')
# general bottom top left right center
alignment = Alignment(horizontal='general',
                      vertical='bottom',
                      text_rotation=0,
                      wrap_text=False,
                      shrink_to_fit=False,
                      indent=0)

protection = Protection(locked=True, hidden=False)
# thin 单线; double 双线
bottom_thin = Side(border_style="double", color="000000")  # 下
left_thin = Side(border_style="thin", color="000000")  # 左
top_double = Side(border_style="double", color="000000")  # 上
right_double = Side(border_style="thin", color="000000")  # 右
# border = Border(bottom=left_thin, left=left_thin, top=left_thin, right=left_thin)  # 边框样式
# thin double thick
border = Border(left=Side(border_style='thin', color='FF000000'),
                right=Side(border_style='thin', color='FF000000'),
                top=Side(border_style='thin', color='FF000000'),
                bottom=Side(border_style='thin', color='FF000000'),
                diagonal=Side(border_style='thin', color='FF000000'),
                diagonal_direction=0,
                outline=Side(border_style='thin', color='FF000000'),
                vertical=Side(border_style='thin', color='FF000000'),
                horizontal=Side(border_style='thin', color='FF000000')
                )
# title_font = Font(name='黑体', size=16, bold=True, color="000000")
title_font = Font(name='Calibri',  # 字体名称
                  size=11,  # 字体大小
                  bold=False,  # 加粗-True/False
                  italic=False,  # 斜体-True/False
                  vertAlign=None,  # 对其方向-
                  underline='none',  # 下划线-single/double
                  strike=False,
                  color='FF000000')

title_fill = PatternFill(fill_type='solid', fgColor="F8F8FF")
# fill = PatternFill(fill_type=None, start_color='FFFFFFFF', end_color='FF000000')
interval_fill = GradientFill(stop=("000000", "FFFFFF"))  # 连续区间底色填充
content_font = Font(name='宋体', size=14, bold=False, color="000000")
content_fill = PatternFill(fill_type='solid', fgColor="F8F8FF")

worksheet.merge_cells('A1:I2')  # 合并单元格,保留左上角值,其他删除
# worksheet.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)  # 合并单元格第二种方法
# worksheet.unmerge_cells('A1:I2')  # 拆分合并的单元格,值值保留在左上角
# worksheet.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4) #拆分合并的单元格第二种方法
worksheet.cell(row=1, column=1).value = '合并的单元格内容'

'''内容填充及字段属性设置'''
# 注意：表格cell的最低行列值都是从1开始,不是0
for rowi in range(3, 8):
    for colj in range(1, 10):
        # _ = ws.cell(row=4, column=2, value=10)
        worksheet.cell(row=rowi, column=colj).value = rowi + colj

# 使用数学公式
# worksheet["A1"] = "=SUM(10, 10)"
# 插入图片
# image = Image('C:/Users/Zeus/Desktop/新logo.png')
# worksheet.add_image(imgage, 'A1')  # A1为插入图片起始单元格
# 折叠行列
# worksheet.row_dimensions.group(1, 3, outline_level=1, hidden=True) # outline_level显示折叠轮廓线(默认1),hidden直接隐藏掉折叠的行列(默认True)
# worksheet.column_dimensions.group('A', 'D', outline_level=1, hidden=False)

# ============================================================================================
'''数据可视化
1. 面积图
     ---2D区域图
     ---3D区域图
2. 条形图和柱形图---BarChart()
     ---垂直、水平和堆叠条形图
     ---3D条形图
3. 气泡图
4. 折线图
     ---折线图
     ---3D折线图
5. 散点图
6. 饼状图
     ---饼状图
     ---投影饼图
     ---3D饼图
7. 甜甜圈图
8. 雷达图
9. 股票图
10.表面图
'''

# ---条形图
# from openpyxl import Workbook
# from openpyxl.chart import BarChart, Reference, Series
#
# wb = Workbook()
# ws = wb.active
# for i in range(15):
#     ws.append([i])
#
# values = Reference(ws, min_row=1, max_row=10, min_col=1, max_col=1)  # 选取区域内容
# chart = BarChart()
# chart.add_data(values)
# ws.add_chart(chart, "E15")  # 大小为15 x 7.5厘米(约5列乘14行),可以通过设置图表的anchor,width和height属性来更改
# wb.save("C:/Users/Zeus/Desktop/SampleChart.xlsx")

# ---散点图
# 坐标-最小最大范围设置
# from openpyxl import Workbook
# from openpyxl.chart import ScatterChart, Reference, Series
#
# wb = Workbook()
# ws = wb.active
#
# ws.append(['X', '1/X'])
# for x in range(-10, 11):
#     if x:
#         ws.append([x, 1.0 / x])
#
# chart1 = ScatterChart()
# chart1.title = "Full Axes"
# chart1.x_axis.title = 'x'
# chart1.y_axis.title = '1/x'
# chart1.legend = None
#
# chart1.x_axis.scaling.min = -10
# chart1.x_axis.scaling.max = 10
# chart1.y_axis.scaling.min = -1.5
# chart1.y_axis.scaling.max = 1.5
#
# chart2 = ScatterChart()
# chart2.title = "Clipped Axes"
# chart2.x_axis.title = 'x'
# chart2.y_axis.title = '1/x'
# chart2.legend = None
#
# chart2.x_axis.scaling.min = 0
# chart2.x_axis.scaling.max = 11
# chart2.y_axis.scaling.min = 0
# chart2.y_axis.scaling.max = 1.5
#
# x = Reference(ws, min_col=1, min_row=2, max_row=22)
# y = Reference(ws, min_col=2, min_row=2, max_row=22)
# s = Series(y, xvalues=x)
# chart1.append(s)
# chart2.append(s)
#
# ws.add_chart(chart1, anchor="C1")
# ws.add_chart(chart2, anchor="C15")
#
# wb.save("C:/Users/Zeus/Desktop/minmax.xlsx")

# 坐标-对数缩放
# from openpyxl import Workbook
# from openpyxl.chart import ScatterChart, Reference, Series
# import math
#
# wb = Workbook()
# ws = wb.active
#
# ws.append(['X', 'Gaussian'])
# for i, x in enumerate(range(-10, 11)):
#     ws.append([x, "=EXP(-(($A${row}/6)^2))".format(row=i + 2)])
#
# chart1 = ScatterChart()
# chart1.title = "No Scaling"
# chart1.x_axis.title = 'x'
# chart1.y_axis.title = 'y'
# chart1.legend = None
#
# chart2 = ScatterChart()
# chart2.title = "X Log Scale"
# chart2.x_axis.title = 'x (log10)'
# chart2.y_axis.title = 'y'
# chart2.legend = None
# chart2.x_axis.scaling.logBase = 10
#
# chart3 = ScatterChart()
# chart3.title = "Y Log Scale"
# chart3.x_axis.title = 'x'
# chart3.y_axis.title = 'y (log10)'
# chart3.legend = None
# chart3.y_axis.scaling.logBase = 10
#
# chart4 = ScatterChart()
# chart4.title = "Both Log Scale"
# chart4.x_axis.title = 'x (log10)'
# chart4.y_axis.title = 'y (log10)'
# chart4.legend = None
# chart4.x_axis.scaling.logBase = 10
# chart4.y_axis.scaling.logBase = 10
#
# chart5 = ScatterChart()
# chart5.title = "Log Scale Base e"
# chart5.x_axis.title = 'x (ln)'
# chart5.y_axis.title = 'y (ln)'
# chart5.legend = None
# chart5.x_axis.scaling.logBase = math.e
# chart5.y_axis.scaling.logBase = math.e
#
# x = Reference(ws, min_col=1, min_row=2, max_row=22)
# y = Reference(ws, min_col=2, min_row=2, max_row=22)
# s = Series(y, xvalues=x)
# chart1.append(s)
# chart2.append(s)
# chart3.append(s)
# chart4.append(s)
# chart5.append(s)
#
# ws.add_chart(chart1, "C1")
# ws.add_chart(chart2, "I1")
# ws.add_chart(chart3, "C15")
# ws.add_chart(chart4, "I15")
# ws.add_chart(chart5, "F30")
#
# wb.save("C:/Users/Zeus/Desktop/log.xlsx")

# 坐标-方向设置
# from openpyxl import Workbook
# from openpyxl.chart import ScatterChart, Reference, Series
#
# wb = Workbook()
# ws = wb.active
#
# ws["A1"] = "Archimedean Spiral"
# ws.append(["T", "X", "Y"])
# for i, t in enumerate(range(100)):
#     ws.append([t / 16.0, "=$A${row}*COS($A${row})".format(row=i + 3),
#                "=$A${row}*SIN($A${row})".format(row=i + 3)])
#
# chart1 = ScatterChart()
# chart1.title = "Default Orientation"
# chart1.x_axis.title = 'x'
# chart1.y_axis.title = 'y'
# chart1.legend = None
#
# chart2 = ScatterChart()
# chart2.title = "Flip X"
# chart2.x_axis.title = 'x'
# chart2.y_axis.title = 'y'
# chart2.legend = None
# chart2.x_axis.scaling.orientation = "maxMin"
# chart2.y_axis.scaling.orientation = "minMax"
#
# chart3 = ScatterChart()
# chart3.title = "Flip Y"
# chart3.x_axis.title = 'x'
# chart3.y_axis.title = 'y'
# chart3.legend = None
# chart3.x_axis.scaling.orientation = "minMax"
# chart3.y_axis.scaling.orientation = "maxMin"
#
# chart4 = ScatterChart()
# chart4.title = "Flip Both"
# chart4.x_axis.title = 'x'
# chart4.y_axis.title = 'y'
# chart4.legend = None
# chart4.x_axis.scaling.orientation = "maxMin"
# chart4.y_axis.scaling.orientation = "maxMin"
#
# x = Reference(ws, min_col=2, min_row=2, max_row=102)
# y = Reference(ws, min_col=3, min_row=2, max_row=102)
# s = Series(y, xvalues=x)
# chart1.append(s)
# chart2.append(s)
# chart3.append(s)
# chart4.append(s)
#
# ws.add_chart(chart1, "D1")
# ws.add_chart(chart2, "J1")
# ws.add_chart(chart3, "D15")
# ws.add_chart(chart4, "J15")
#
# wb.save("C:/Users/Zeus/Desktop/orientation.xlsx")

# 坐标-添加第二坐标
# from openpyxl import Workbook
# from openpyxl.chart import LineChart, BarChart, Reference, Series
#
# wb = Workbook()
# ws = wb.active
#
# rows = [
#     ['Aliens', 2, 3, 4, 5, 6, 7],
#     ['Humans', 10, 40, 50, 20, 10, 50],
# ]
#
# for row in rows:
#     ws.append(row)
#
# c1 = BarChart()
# v1 = Reference(ws, min_col=1, min_row=1, max_col=7)
# c1.add_data(v1, titles_from_data=True, from_rows=True)
#
# c1.x_axis.title = 'Days'
# c1.y_axis.title = 'Aliens'
# c1.y_axis.majorGridlines = None
# c1.title = 'Survey results'
#
# # Create a second chart
# c2 = LineChart()
# v2 = Reference(ws, min_col=1, min_row=2, max_col=7)
# c2.add_data(v2, titles_from_data=True, from_rows=True)
# c2.y_axis.axId = 200
# c2.y_axis.title = "Humans"
#
# # Display y-axis of the second chart on the right by setting it to cross the x-axis at its maximum
# c1.y_axis.crosses = "max"
# c1 += c2
#
# ws.add_chart(c1, "D4")
#
# wb.save("C:/Users/Zeus/Desktop/secondary.xlsx")

# ============================================================================================
'''局部设置样式'''
for row in worksheet.rows:
    for cell in row:
        cell.alignment = align
        if cell.row == 1 or cell.row == 2:
            cell.border = border
            cell.font = title_font
            cell.fill = title_fill
        else:
            cell.border = border
            cell.font = content_font
            cell.fill = content_fill

# col = worksheet.column_dimensions['A']
# col.font = Font(bold=True)
# row = worksheet.row_dimensions[1]
# row.font = Font(underline="single")
# c = Color(indexed=32)  # 按索引选颜色
# c = Color(theme=6, tint=0.5)  # 使用主题
# workbook.add_named_style(highlight)

'''储存表格'''
workbook.save(filename='C:/Users/Zeus/Desktop/openpyxl.xlsx')  # 储存格式：xlsx、xlsm或zip

# # 读取与储存文件
# # workbook = load_workbook(filename='large_file.xlsx', read_only=True) # 仅读模式
# workbook = load_workbook('document.xlsx')
# # 当读取单元格时,guess_types将启用或禁用（默认）类型推断.
# # read_only仅读取模式,不可改动
# # data_only控制具有公式的单元格是否具有公式(默认值)或Excel上次读取工作表时存储的值.
# # keep_vba控制是否保留任何Visual Basic元素(默认).如果保留它们,则它们仍不可编辑.
# print(workbook.get_sheet_names())
# workbook.template = True  # template = True,以将工作簿另存为模板;
# workbook.save('document_template.xltx')  # 注意为xltx格式
# workbook = load_workbook('document_template.xltx')
# workbook.template = False  # 将此属性设置为 template =False(默认)以另存为文档
# workbook.save('document.xlsx', as_template=False)


from helper.warper import ImageMap
import cv2, numpy
from data_sources.csvsequence import CsvSequence
from helper import homography_func as hf
from data_sources.videofile import VideoFile
import time

surf = hf.SURF()

homographynet = hf.HomographyNet("../checkpoints/realdata2-vgg13.pth.tar")
video = CsvSequence("../datasets/example6.csv", base_path="../")

map_size = (1024,1000)
patch_location = (128,128)

imagemap = ImageMap(map_size)

stream1 = imagemap.create_stream(position=(0,200), func=homographynet, data=video, memory=1, distance=100, borders=False, indicate_centers=True) # homography func
stream2 = imagemap.create_stream(position=(0,600), func=surf, data=video, memory=1, distance=100) # sift

while not imagemap.finished():

    image = imagemap.warp()

    cv2.imshow("map", image)
    cv2.waitKey(1)

    last_matches = surf.draw_keypoints()
    if last_matches is not None:
        cv2.imshow("matches", last_matches)
        cv2.waitKey(1)

cv2.waitKey(0)


import RPi.GPIO as GPIO
import time

N = [10, 9, 11, 5, 6, 13, 19, 26]

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(N, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.setup(4, GPIO.IN)

def num2dac(val):
    binary = bin(val)[2:].zfill(8)
    for i in range(8):
        GPIO.output(N[i], int(binary[7 - i]))

def DarkALL():
    for i in range(8):
        GPIO.output(N[i], 0)
DarkALL()

GPIO.setup(4, GPIO.IN)
GPIO.output(17, 1)

try:

    voltage = 0
    newVoltage = 0

    while True:

        for i in range (0, 255):
            num2dac (i)
            time.sleep (0.0001)

            if GPIO.input (4) != 1:
                newVoltage = 3.3*float(i)/255
                break

        if abs(newVoltage - voltage) > 1.0/255.0:
            print (round(newVoltage, 2),' - ' , int(newVoltage*255/3.3))
            voltage = newVoltage

except ZeroDivisionError:
    print('Число от 0 до 255!!!')
except ValueError:
    print('Число от 0 до 255!!!')

finally:
    DarkALL()
    GPIO.cleanup()


"""
Small modules for the structure of PointNet.
Author: Carlos Leo
Time:   2020/10/15 - 15:12
Version: 1.0
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

class TNet(nn.Module):
    """
    T-Net which produce a transformation matrix to align input or feature space.

    k: the channel of the input
    """
    def __init__(self, k=3):
        super().__init__()
        self.k = k

        # shared mlp(64, 128, 1024)
        self.conv1 = nn.Conv1d(k, 64, 1)
        self.bn1 = nn.BatchNorm1d(64)
        self.conv2 = nn.Conv1d(64, 128, 1)
        self.bn2 = nn.BatchNorm1d(128)
        self.conv3 = nn.Conv1d(128, 1024, 1)
        self.bn3 = nn.BatchNorm1d(1024)

        # fully connected layer(512, 256, k*k)
        self.fc1 = nn.Linear(1024, 512)
        self.bn4 = nn.BatchNorm1d(512)
        self.fc2 = nn.Linear(512, 256)
        self.bn5 = nn.BatchNorm1d(256)
        self.fc3 = nn.Linear(256, k * k)

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        x = F.relu(self.bn3(self.conv3(x)))

        # max symmetric function which change dims (B, C, N)
        # into dims (B, C)
        x = torch.max(x, dim=-1)[0]

        x = F.relu(self.bn4(self.fc1(x)))
        x = F.relu(self.bn5(self.fc2(x)))
        x = self.fc3(x)

        x = x.view(-1, self.k, self.k)

        eye = torch.eye(self.k)
        if x.is_cuda:
            eye = eye.cuda()
        eyes = eye.repeat(x.size()[0], 1, 1)
        x += eyes

        return x

def feature_transform_regularization(trans):
    """
    $L_{reg}=||I-AA^{T}||^2_F$, references the original implement

    :param trans: transformation matrix by T-Net in features
    :return:
    """
    d = trans.size()[1]
    I = torch.eye(d)[None, :, :]
    if trans.is_cuda:
        I = I.cuda()
    loss = torch.mean(torch.norm(torch.bmm(trans, trans.transpose(2, 1)) - I, dim=(1, 2)))
    return loss

def to_one_hots(y, categories):
    """
    Encode the labels into one-hot coding.

    :param y: labels for a batch data with size (B,)
    :param categories: total number of kinds for the label in the dataset
    :return: (B, categories)
    """
    y_ = torch.eye(categories)[y.data.cpu().numpy()]
    if y.is_cuda:
        y_ = y_.cuda()
    return y_

if __name__ == '__main__':

    def setup_seed(seed):
        """
        Set a random seed to generate same random numbers
        :param seed: random seed number
        :return:
        """
        torch.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
        np.random.seed(seed)
        torch.backends.cudnn.deterministic = True

    setup_seed(20)

    # 随机生成数据测试T-Net
    x = torch.rand((10, 3, 1024))

    t_net = TNet()
    print(t_net(x).size())

    x2 = torch.rand((10, 64, 1024))
    t_net64 = TNet(k=64)
    print(t_net64(x2).size())


####################################################################################################
## A program producing pencil drawing from natural images (https://github.com/LarsPh/Pencil-Sketch).
## Copyright (c) 2019 Zhaorong Wang.
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, version 3.
##
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
####################################################################################################

import numpy as np
import cv2
from scipy.ndimage.interpolation import rotate
from scipy.interpolate import UnivariateSpline
from scipy.signal import fftconvolve
from scipy.sparse import spdiags
from scipy.sparse.linalg import cg
from PIL import Image
import matplotlib.pyplot as plt
import sys
import os

#np.set_printoptions(threshold=sys.maxsize)
#np.set_printoptions(**opt)

#normalize the pixel valute to the range 0-255
def to255Int(A, c=255):
    return np.uint8((A - np.amin(A))/(np.amax(A)-np.amin(A))*c)

#edge detection
def gradEdges(S, method):
    #gradient edge detection, works poorly even after denoising
    #S = cv2.GaussianBlur(S, (7,7), 0)
    #S = cv2.bilateralFilter(S, 30, 30, 3)
    #Dx = np.column_stack((S[ : ,1: ], S[ : , -1]))-S
    #Dy = np.row_stack((S[1: , : ], S[-1, : ]))-S
    #G = np.sqrt(Dx**2+Dy**2)
    if(method == 1):
        #Laplacian edge detection, works better after bilateral filter
        #S = cv2.GaussianBlur(S, (7,7), 0)
        S = cv2.bilateralFilter(S, 30, 30, 3)
        G = cv2.Laplacian(S, cv2.CV_8U, ksize=5)
    else:
        #Canny edge detection, good performance on denoising, but more and thinner strokes
        #works better with ligher strokes, i.e. smaller value for darkerStroke
        (r, c) = np.shape(S)
        mean = np.sum(S)/(r*c)
        lower = mean*0.75
        upper = mean*1.25
        G = cv2.Canny(S, lower, upper)
    return G

#Draw strokes. Generate cross-like effect at junctions of strokes
def drawLines(G, nDirec, kernR, darkerStroke):
    (r, c) = np.shape(G)
    kernScale = int(min(r, c)/kernR)
    #generate line segments
    L = np.zeros((kernScale*2+1, kernScale*2+1, nDirec))
    L[ : , kernScale+1, 0] = 1
    for i in range(nDirec):
        L[ : , : ,i] = np.round(rotate(L[ : , : ,0], i/nDirec*180, reshape=False))
    #classification, fftconvolve save mem compared with convolve when N is large
    Gc = np.zeros((r, c, nDirec))
    for i in range(nDirec):
        Gc[ : , : ,i] = fftconvolve(G, L[ : , : ,i], mode="same")
    Index = np.argmax(Gc, axis=2)
    C = np.zeros((r, c, nDirec))
    for i in range(nDirec):
        C[ : , : ,i] = G*(Index == i)

    Sp = np.zeros((r, c))
    for i in range(nDirec):
        Sp += fftconvolve(C[ : , : ,i], L[ : , : ,i], mode="same")

    Sp = 1-(Sp - np.amin(Sp))/(np.amax(Sp)-np.amin(Sp))
    Sp = Sp ** darkerStroke
    return Sp

#Tone transformation
def transferTone(A, w1, w2, w3):
    A = to255Int(A)
    (r, c) = np.shape(A)
    p = np.zeros(256)
    inten = np.arange(0, 256)
    p1 = (1/9)*np.exp(-(255-inten)/9)
    p2 = np.zeros(256)
    p2[105:225] = 1/(225-105)
    p3 = (1/np.sqrt(2*np.pi*11))*np.exp(-(inten-90)**2/(11*11*2))
    p = w1*p1+w2*p2+w3*p3
    p /= np.sum(p)
    #plt.plot(inten, p, 'ro')
    #smoothen the curve
    fp = UnivariateSpline(inten, p)
    fp.set_smoothing_factor(0.000035)
    p = fp(inten)
    plt.plot(inten, p, 'go')
    p /= np.sum(p)
    cp = np.zeros(256)
    #calculate cunmulative density function
    for i in range(256):
        cp[i] = np.sum(p[0:i])
    cp /= cp[255]
    s = np.zeros(256)
    for i in range(r):
        for j in range(c):
            s[A[i, j]] += 1
    s /= r*c
    cs = np.zeros(256)
    for i in range(256):
        cs[i] = np.sum(s[0:i])
    #plt.plot(inten, s, 'o')

    Diff = np.zeros((256, 256))
    for i in range(256):
        for j in range(256):
            Diff[i, j] = np.abs(cs[i]-cp[j])
    #tonal mapping
    matching = np.zeros(256)
    for i in range(256):
        minIdx = 0
        minVal = Diff[i, 0]
        for j in range(256):
            if (Diff[i, j] < minVal):
                minVal = Diff[i, j]
                minIdx = j
        matching[i] = minIdx
    J = np.zeros((r,c))
    for i in range(r):
        for j in range(c):
            J[i, j] = matching[A[i, j]]

    t = np.zeros(256)
    for i in range(r):
        for j in range(c):
            t[np.uint8(J[i, j])] += 1
    t /= r*c
    plt.plot(inten, t, 'bo')
    #uncommnet to see the comparison on target(p) and mapped(t) histogram
    #plt.show()
    return to255Int(J)

#Transfer the texture so that it matches the tone image by sovling linear equation
def renderTexture(J, H1, lam):
    (r, c) = np.shape(J)
    (n, m) = np.shape(H1)
    #adjust the resolution of texture
    x = int(np.ceil(r/n))
    y = int(np.ceil(c/m))
    H2 = H1
    for i in range(y):
        H2 = np.hstack((H2, H1))
    H = H2
    for i in range(x):
        H = np.vstack((H, H2))
    H = H[ :r, :c]
    Image.fromarray(to255Int(H), "L").save("temp/texture_test1.jpg")

    epsilon = 0.0001
    H = np.float64(H)/255
    #prevent log(0)
    J = np.float64(J+epsilon)/255
    #transform to vector
    h = np.reshape(H, r*c)
    j = np.reshape(J, r*c)
    logh = np.log(h)
    logj = np.log(j)
    i = np.ones(r*c)
    #use methods for sparse matrix to prevent mem problems
    Dx = spdiags(np.array([-i,i]), np.array([0,1]), r*c, r*c)
    Dy = spdiags(np.array([-i,i]), np.array([0,c]), r*c, r*c)
    A = spdiags(logh*logh, 0, r*c, r*c)+lam*(Dx.transpose().dot(Dx)+Dy.transpose().dot(Dy))
    b = logh*logj
    #conjugate gradient
    beta, _ = cg(A, b)
    Beta = beta.reshape(r, c)
    T = H**Beta
    #elements of T have values between 0 to 1
    return T

#Combine the pencil strokes and tonal texture
def combineST(S, T):
    return to255Int(S) * T

#edgeDetctMthd: choose method for edge detection. 1 for bilateral filter + Laplacian, 2 for Canny
#kerndirN: value for line segments (kernal) with different directions
#kernScale: the scale for kernal would be min(w, h)/kerScale. w and h are the height and width of input image
#darkerStroke: larger value would make the stroke darker
#w1, w2, w3: weight of three distribution
#lam: lambda multiplied by the gradient of beta in formula (8) in final step (check the paper for details)
def pencilSketch(srcDir="source_images", txPath="textures/texture1.jpg", edgeDetctMthd=1, kerdireN=8, kernScale=200, darkerStroke=2, w1=0.52, w2=0.37, w3=0.11, lam=0.2):
    print("Generating images...")

    for fname in os.listdir(srcDir):
        im = Image.open(srcDir+"/"+fname)
        ImRGB = np.array(im)
        ImLUV = cv2.cvtColor(ImRGB, cv2.COLOR_RGB2Luv)
        #transform on L channal
        ImGs = ImLUV[ : , : ,0]
        if not os.path.exists("temp"):
            os.mkdir("temp")
        if not os.path.exists("output"):
            os.mkdir("output")
        Image.fromarray(ImGs, "L").save("temp/grayscale_"+fname)
        #print(np.shape(ImGs))

        G = gradEdges(ImGs, 1)
        Image.fromarray(to255Int(G), "L").save("temp/gradient_"+fname)
        Sp = drawLines(G, kerdireN, kernScale, darkerStroke)
        Image.fromarray(to255Int(Sp), "L").save("temp/lines_"+fname)
        J = transferTone(ImGs, w1, w2, w3)
        Image.fromarray(to255Int(J), "L").save("temp/tone_map_"+fname)
        texIm = Image.open(txPath).convert("L")
        H = np.array(texIm)
        T = renderTexture(J, H, lam)
        Image.fromarray(to255Int(T), "L").save("temp/pencil_texture_"+fname)
        R = combineST(Sp, T)
        Image.fromarray(to255Int(R), "L").save("output/pencil_sketch_"+fname)
        ImLUV[ : , : ,0] = to255Int(R)
        ImRGB = cv2.cvtColor(ImLUV, cv2.COLOR_Luv2RGB)
        Image.fromarray(ImRGB, "RGB").save("output/colored_pencil_sketch_"+fname)

    print("Finished generation")

pencilSketch()


from django.conf.urls import url
from . import views

app_name = 'hostel'

urlpatterns = [

    url(r'^hostels', views.hostels, name="hostels"),
    url(r'^contact', views.contact, name="contact"),
    url(r'^about', views.about, name="about"),
    url(r'^boys_hostel', views.boys_hostel, name="boys_hostel"),
    url(r'^girls_hostel', views.girls_hostel, name="girls_hostel"),
    url(r'^signup', views.signup, name="signup"),
    # url(r'^login', views.loginUser, name="login"),
    # url(r'^logout', views.logoutUser, name="logout"),
    url(r'^user', views.userPage, name="userPage"),
]


import math

DATA = [i for i in range(0, 100)]
PAGE_SIZE = 5

def api_call(page):
    print("API_CALL", page)
    index = page * PAGE_SIZE
    return DATA[index:index + PAGE_SIZE]

class ApiConsumer:
    def __init__(self, page_size=PAGE_SIZE, api_call=api_call) -> None:
        self.index = 0
        self.page = -1
        self.store = []
        self.page_size = page_size
        self.api_call = api_call

    def fetch(self, retreive_count):
        self.index += retreive_count
        next_page = math.floor(self.index / self.page_size)

        if next_page > self.page:
            self.page = next_page
            self.store += self.api_call(page=next_page)

        response = self.store[:retreive_count]
        self.store = self.store[retreive_count:]
        return response

# Current usage
# print(api_call(0))  # >>> [0, 1, 2, 3, 4]
# print(api_call(100))  # >>> []
# print(api_call(17))  # >>> [85, 86, 87, 88, 89]

consumer = ApiConsumer()

# assert(consumer.fetch(2) == [0, 1])
# assert(consumer.fetch(4) == [2, 3, 4, 5])
# assert(consumer.fetch(1) == [6])

print(consumer.fetch(2))
print(consumer.fetch(4))
print(consumer.fetch(1))


from time import time, sleep
import random
import sys
import math

import Adafruit_GPIO.SPI as SPI
import Adafruit_GPIO.GPIO as GPIO
import Adafruit_MAX31855.MAX31855 as MAX31855

# Define a function to convert celsius to fahrenheit.
def c_to_f(c):
        return c * 9.0 / 5.0 + 32.0

SPI_PORT = 0
SPI_DEVICE = 1
MUXING = False

if(len(sys.argv) > 2):
    SPI_PORT = int(sys.argv[1])
    SPI_DEVICE = int(sys.argv[2])

if(len(sys.argv) > 9):
    MUXING = True
    MUXING_SELECTORS = [int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]), int(sys.argv[6])]
    MUXING_ENABLER = int(sys.argv[7])
    MUXING_LATCH = int(sys.argv[8])
    MUXING_COUNT = int(sys.argv[9])

    if (MUXING_COUNT > 16):
        print("Max number of muxings is 16.")
        exit()

SAMPLING_RATE = 1.000
REPORTING_RATE = 1.000
if(len(sys.argv) > 11):
    SAMPLING_RATE = float(sys.argv[10]) / 1000
    REPORTING_RATE = float(sys.argv[11]) / 1000

if(len(sys.argv) > 14):
    SPI_CLK = int(sys.argv[12])
    SPI_DO = int(sys.argv[13])
    SPI_CS = int(sys.argv[14])
    sensor = MAX31855.MAX31855(clk=SPI_CLK, do=SPI_DO, cs=SPI_CS)
else:
    sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

# Raspberry Pi hardware SPI configuration.

if (MUXING):
    gpio = GPIO.get_platform_gpio()
    for selector in MUXING_SELECTORS:
        gpio.setup(selector, GPIO.OUT)
    gpio.setup(MUXING_ENABLER, GPIO.OUT)
    gpio.setup(MUXING_LATCH, GPIO.OUT)

def disableMuxing():
    gpio.output(MUXING_ENABLER, True)

def enableMuxing():
    gpio.output(MUXING_ENABLER, False)

def enableSelecting():
    gpio.output(MUXING_LATCH, True)

def disableSelecting():
    gpio.output(MUXING_LATCH, False)

def setMuxing(chipSelect):
    enableSelecting()
    chipSelectArray = [int(x) for x in bin(chipSelect)[2:]]
    while (len(chipSelectArray) < 4):
        chipSelectArray.insert(0, 0)
    for index, value in enumerate(chipSelectArray):
        gpio.output(MUXING_SELECTORS[index], (value == 1))
    disableSelecting()

channels = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
maxInternal = 0
last_report = 0

def sampledData(channel, temp):
    global channels
    if not math.isnan(temp):
        channels[channel].append(temp)

def report():
    global channels, maxInternal, last_report
    if (time() - last_report > REPORTING_RATE):
        last_report = time()
        for i in range(0,MUXING_COUNT):
            if len(channels[i]) > 0:
                print('{0:0.3F},{1},{2:0.3F}'.format(time(),i, sum(channels[i])/len(channels[i]) ))

        print ('{0:0.3F},maxInternal,{1:0.3F}'.format(time(), maxInternal ))
        maxInternal = 0
        channels = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]

# Loop printing measurements every second.
print('Press Ctrl-C to quit.')
while True:
    if MUXING:
        enableMuxing()
        maxInternal = 0
        for i in range(0,MUXING_COUNT):
            setMuxing(i)
            channelTemp = sensor.readTempC()
            sampledData(i, channelTemp)
            maxInternal = max(maxInternal, sensor.readInternalC())
        disableMuxing()
        report()

    else:
        temp = sensor.readTempC()
        internal = sensor.readInternalC()
        print('{0:0.3F},0,{1:0.3F}'.format(time(), temp ))
        print ('{0:0.3F},internal,{1:0.3F}'.format(time(), internal ))

    # TODO: Check for errors. Removed because 0x7 is too broad.
    #v = sensor._read32()
    #if v & 0x7:
    #    print "{0:0.3F},error,{1:0.1F}".format(time(), float( v & 0x7))

    sleep(SAMPLING_RATE)


def Main():
    print('Conversor de temperaturas: ')
    print('Opções: \n[1] celsius > farenheit \n[2] farenheit > celsius')
    resposta = Controle()
    print(resposta)
    Conversor(resposta)
    Continuar()

def Controle():
    r = input("Digite a opção de conversão: ")
    while r not in '12':
            print("Opção inválida.")
            r = input("Digite a opção de conversão: ")
    if r == '1':
        return 1
    elif r == '2':
        return 2

def Conversor(Controle):
    if Controle == 1:
        print("Opção escolhida: [1] celsius > farenheit")
        Tc = float(input("Digite a temperatura em Celsius: "))
        Tf = (Tc*1.8)+32
        print(f"A temperatura {Tc:.1f}ºC equivale {Tf:.1f}ºF")
    elif Controle == 2:
        print("Opção escolhida: [2] farenheit > celsius ")
        Tf = float(input("Digite a temperatura em farenheit: "))
        Tc = (Tf-32)/1.8
        print(f"A temperatura {Tf:.1f}ºF equivale {Tc:.1f}ºC")

def Continuar():
    resposta = input("Deseja Continuar?: [s/n]").strip().upper()
    while resposta not in 'SN':
            print("Opção inválida")
            resposta = input("Deseja Continuar?: [s/n]").strip().upper()
    if resposta == 'S':
        Main()
    elif resposta == 'N':
        return

Main()


#!/usr/bin/python3

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import re
import nltk
from math import log

COUNT_KEY = '_count' # for dictionaries
PAD_FRONT_CHAR = '@' # we use this character to pad the start of each string
PAD_END_CHAR = '^'
OTHER_STRING = 'other' # classify as other
OTHER_THRESHOLD = 0.5 # threshold for classifying as other
EPSILON = 0.00001 # avoid division by 0

DEFAULT_PAD = True
DEFAULT_HOMOGENIZE_DIGITS = True
DEFAULT_NO_PUNC = False
DEFAULT_LOWERCASE = True
DEFAULT_SMOOTH_UNSEEN = False

def build_LM(in_file, pad=DEFAULT_PAD, homogenize_digits=DEFAULT_HOMOGENIZE_DIGITS, no_punc=DEFAULT_NO_PUNC, lowercase=DEFAULT_LOWERCASE):
    """
    build language models for each label
    each line in in_file contains a label and a string separated by a space
    """
    print("building language models...")
    lines = read_lines(in_file)
    train_set = input_lines_to_train_set(lines, pad, homogenize_digits, no_punc, lowercase)
    model = build_model(train_set)
    return model

def build_model(train_set):
    """
    builds the model from a training set
    """
    model = dict()
    vocab = set()

    # this loop will build the initial table and smooth the observed entries
    for datum in train_set:
        label, features = datum
        four_grams = line_to_4grams(features)
        for four_gram in four_grams:
            vocab.add(four_gram)
            model[label] = model.get(label, dict())
            model[label][four_gram] = model[label].get(four_gram, 1) + 1 # default value of 1 due to add-1 smoothing.

    # this loop does smoothing for 4grams in the vocabulary that were not observed in each language
    for four_gram in vocab:
        for label in model.keys():
            if not (four_gram in model[label].keys()):
                model[label][four_gram] = 1 # default value of 1 due to add-1 smoothing

    # this loop counts the number of occurrences for each language in total
    for label in model.keys():
        total = 0
        for four_gram in model[label].keys():
            total += model[label][four_gram]
        model[label][COUNT_KEY] = total
    return model

def line_to_4grams(line):
    """
    converts a string to a list of 4-grams
    """
    four_grams = []
    for i in range(len(line)-3):
        four_grams.append(line[i:i+4])
    return four_grams

def input_lines_to_train_set(lines, pad, homogenize_digits, no_punc, lowercase):
    """
    converts the lines from the input training corpus into a training set with (label, features) pairs.
    """
    train_set = []
    for line in lines:
        label = line.split()[0]
        features = line[len(label)+1:]
        features = process_line(features, pad, homogenize_digits, no_punc, lowercase)
        train_set.append((label,features))
    return train_set

def process_line(line, pad, homogenize_digits, no_punc, lowercase):
    """
    performs preprocessing for a single line, based on the provided options
    """
    if no_punc:
        line = re.sub(r'[^\s\w]', '', line)
    if lowercase:
        line = line.lower()
    if homogenize_digits:
        line = re.sub(r'[\d]+', '1', line)
    line = line.strip()
    if pad:
         line = f'{PAD_FRONT_CHAR}{PAD_FRONT_CHAR}{PAD_FRONT_CHAR}{line}{PAD_END_CHAR}{PAD_END_CHAR}{PAD_END_CHAR}'

    return line

def read_lines(in_file):
    """
    reads the lines from a file, removing all whitespace (including newline)
    """
    with open(in_file, "r") as f:
        lines = f.readlines()
    print(f'{len(lines)} lines')
    for i in range(len(lines)):
        lines[i] = lines[i].strip()
    return lines

def test_LM(in_file, out_file, LM, pad=DEFAULT_PAD, homogenize_digits=DEFAULT_HOMOGENIZE_DIGITS, no_punc=DEFAULT_NO_PUNC, lowercase=DEFAULT_LOWERCASE, smooth_unseen=DEFAULT_SMOOTH_UNSEEN):
    """
    test the language models on new strings
    each line of in_file contains a string
    you should print the most probable label for each string into out_file
    """
    print("testing language models...")
    lines = read_lines(in_file)
    output_str = ''
    for i in range(len(lines)):
        line = process_line(lines[i], pad, homogenize_digits, no_punc, lowercase)
        if smooth_unseen:
            lang = classify_smooth_unseen(line, LM)
        else:
            lang = classify_ignore_unseen(line, LM)
        output_str += f'{lang} {lines[i]}\n'
    with open(out_file, "w") as f:
        f.write(output_str)

def classify_ignore_unseen(line, model):

    """
    classifies a given string according to a language model. ignore unseen 4grams.
    """
    four_grams = line_to_4grams(line)
    log_prob = dict() # multiplying probabilities can lead to very small numbers, which are often not handled well by computers. so we sum up log probabilities instead.
    unseen_4grams = set()
    for lang in model.keys():
        for four_gram in four_grams:
            if not (four_gram in model[lang].keys()):
                unseen_4grams.add(four_gram)

    # we assume it's some alien language if there are many 4grams that we haven't seen before
    if len(unseen_4grams) / (len(set(four_grams))+EPSILON) > OTHER_THRESHOLD:
        return OTHER_STRING

    for lang in model.keys():
        log_prob[lang] = 0
        count = model[lang][COUNT_KEY]
        for four_gram in four_grams:
            if four_gram in unseen_4grams:
                continue
            four_gram_count = model[lang][four_gram]
            log_prob[lang] += log(four_gram_count/(EPSILON+count))
    return max(log_prob, key=log_prob.get) # logarithm functions are increasing so we can still take the max

def classify_smooth_unseen(line, model):
    """
    classifies a given string according to a language model. applies add-1 smoothing even to 4grams that have not been seen before in the corpus.
    """
    four_grams = line_to_4grams(line)
    log_prob = dict() # multiplying probabilities can lead to very small numbers, which are often not handled well by computers. so we sum up log probabilities instead.
    unseen_4grams = dict()
    unseen_4grams_set = set()
    for lang in model.keys():
        unseen_4grams[lang] = set()
        for four_gram in four_grams:
            if not (four_gram in model[lang].keys()):
                unseen_4grams[lang].add(four_gram)
                unseen_4grams_set.add(four_gram)

    # we assume it's some alien language if there are many 4grams that we haven't seen before
    if len(unseen_4grams_set) / (len(set(four_grams))+EPSILON) > OTHER_THRESHOLD:
        return OTHER_STRING

    for lang in model.keys():
        log_prob[lang] = 0
        count = model[lang][COUNT_KEY]
        for four_gram in four_grams:
            four_gram_count = model[lang].get(four_gram, 1) # default value of 1 due to add-1 smoothing
            log_prob[lang] += log(four_gram_count/(EPSILON+count+len(unseen_4grams[lang])))
    return max(log_prob, key=log_prob.get) # logarithm functions are increasing so we can still take the max


n, k = map(int, input().split())
s = input()
d, i = {}, 0
while(i < len(s)):
    j = i;
    while(j < len(s) and s[j] == s[i]):
        j += 1
    ans = (j - i) // k
    if(s[i] in d):
        d[s[i]] += ans
    else:
        d[s[i]] = ans
    i = j
print(max(d.values()))


import logging

import numpy
try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser

from .Rcvr68_92 import Rcvr68_92
from gbtcal.decode import getFitsForScan, getDcrDataDescriptors
from gbtcal.dcrtable import DcrTable

logger = logging.getLogger(__name__)

class Backend:

    def __init__(self, data, dcrHdu):
        self.dcrHdu = dcrHdu
        self.data = data
        self.descriptors = getDcrDataDescriptors(data)

        feedPolCombos = list(set([(f, p) for f, p, _, _ in self.descriptors]))
        self.channels = ["%s%s" % (f, p) for f, p in feedPolCombos]

        self.name = "DCR"

    def GetRawPower(self, feed, pol, phase):

        sigref, cal = phase

        mask = ((self.data['FEED'] == feed) &
                (numpy.char.rstrip(self.data['POLARIZE']) == pol) &
                (self.data['SIGREF'] == sigref) &
                (self.data['CAL'] == cal))

        return self.data[mask]['DATA'][0]

    def GetIntegrationTime(self):

        h = self.dcrHdu[0].header
        return h['DURATION']

    def GetIntegrationStartTimes(self):

        dataTab = self.dcrHdu[3].data
        return dataTab.field('TIMETAG')

    def GetPhases(self):
        phases = numpy.unique(self.data[['SIGREF', 'CAL']])
        return phases

    def GetNumPhases(self):

        return len(self.GetPhases())

class CalSeqScan:

    def __init__(self, projectPath, scanNum):
        # self.project = project
        # self.scan    = scan
        self.projectPath = projectPath
        self.scanNum = scanNum

        self.fitsMap = getFitsForScan(projectPath, scanNum)

        logger.debug("fits files %s", list(self.fitsMap.keys()))
        self.channels = []
        self.ports = []  # need ordered list to correspond with data columns
        self.SetBackend()
        self.SetReceiver()
        self.InitData()

    def SetBackend(self):

        dcrHdu = self.fitsMap['DCR']
        ifHdu = self.fitsMap['IF']
        data = DcrTable.read(dcrHdu, ifHdu)

        self.backend = Backend(data, dcrHdu)

    def getBackendName(self):
        return self.backend.name

    # def GetDataConnection(self):
        # return self.scan.getDataConnection()

    def GetReceiverCal(self):
        rcvrName = self.scan.getRcvrName()
        try:
            return self.project.getRcvrCalibration(rcvrName)
        except Exception:
            return None

    def SetReceiver(self):
        hdu = self.fitsMap['Rcvr68_92']
        self.receiver = Rcvr68_92(hdu, debug=True)

    def InitData(self):
        self.scanData = {}

    def getTwarm(self):
        """ Uses receiver class to get TWARM from receiver FITS file """
        if self.receiver:
            # TBF: for auto scan returns header value of twarm unless have dmjd arg
            return self.receiver.getTwarm()
        return 0

    def getTcold(self):
        """ Reads TCOLD from CalSeq.conf config file """
        ygorTelescope = "/home/sim"  # getConfigValue("/home/sim", "YGOR_TELESCOPE")
        filename = ygorTelescope + "/etc/config/CalSeq.conf"
        cp = ConfigParser()
        cp.read(filename)
        try:
            return float(cp.get("all_modes", "tcold"))
        except Exception as e:
            default = 50.0
            logger.warning("Caught exception %s", e)
            logger.warning("Returning default value %s", default)
            return default

    def getCalPos(self):
        return self.receiver.getCalpos()

    def isAuto(self):
        return self.receiver.isAuto()

    def getScanData(self):
        """ self.scanData is a dict of format {channel: (type, Raw Power data)}
            where:
            channel = 1X, 1Y, 2X, or 2Y
            type    = Vwarm, Vcold, Observing, Position2, or Position5
        """
        return self.scanData

    def getChannels(self):
        return self.channels

    def processCalseqScan(self):
        """ Read channel data and put in scanData dictionary
            with calibration wheel position metadata """

        if self.getBackendName() == "DCR":
            logger.debug("processCalseqScan for DCR")
            # Get DCR FITS DATA 'TIMETAG' column
            # (we only need this for auto mode,
            # but don't want to repeat this in loop)
            dmjds = self.backend.GetIntegrationStartTimes()

            for channel in self.backend.channels:
                for phase in self.backend.GetPhases():
                    logger.debug("channel, phase: %s, %s", channel, phase)
                    self.channels.append(channel)
                    feed = int(channel[0])
                    pol = channel[1]
                    # get the data for that channel
                    channelData = self.backend.GetRawPower(feed, pol, phase)

                    if self.isAuto():  # auto CalSeq
                        # This is the more complicated case;
                        # Have to parse channelData according to calpos
                        autoData = {}
                        tint = self.backend.GetIntegrationTime()
                        for idx, dmjd in enumerate(dmjds):
                            calPosition = self.receiver.getPosition(dmjd, tint)
                            if calPosition != "Unknown":
                                dataType = self.getDataType(calPosition, feed)
                                try:
                                    autoData[dataType].append(channelData[idx])
                                except KeyError:
                                    # start a list for this dataType
                                    autoData[dataType] = [channelData[idx]]
                        for datatype in list(autoData.keys()):
                            try:
                                self.scanData[channel].append(
                                    (datatype, numpy.array(autoData[datatype]))
                                )
                            except KeyError:
                                self.scanData[channel] = [
                                    (datatype, numpy.array(autoData[datatype]))
                                ]
                    else:  # manual CalSeq
                        # This is the simple case, all data is the same type
                        calPosition = self.getCalPos()
                        dataType = self.getDataType(calPosition, feed)
                        # Now put data in dict
                        self.scanData[channel] = (dataType, channelData)
        elif self.getBackendName() in ["Spectrometer", "Vegas"]:
            phase = 0

            for beam in self.backend.getBeams():
                for pol in self.backend.getPolarizations():
                    channel = str(beam) + pol[0]
                    self.channels.append(channel)
                    channelData = None
                    if self.isAuto():  # auto CalSeq
                        autoData = {}
                        for ifnum in self.backend.getIFNumbers():
                            # retrieve the needed Spectrometer class
                            bankIdx = self.backend.getBankIndex(
                                beam, pol, ifnum
                            )
                            bank = self.backend.getBank(bankIdx)

                            # Data for stationary wheel positions during scan
                            tint = bank.GetIntegrationTime()
                            dmjds = bank.GetIntegrationStartTimes()
                            for idx, dmjd in enumerate(dmjds):
                                calPosition = self.receiver.getPosition(
                                    dmjd, tint
                                )
                                if calPosition != "Unknown":
                                    dataType = self.getDataType(
                                        calPosition, beam
                                    )
                                    newData = self.backend.getRawPowerByValues(
                                        beam, pol, ifnum, idx, phase
                                    )
                                    if numpy.isnan(newData).any():
                                        continue
                                    try:
                                        autoData[dataType] = numpy.concatenate(
                                            (autoData[dataType], newData)
                                        )
                                    except KeyError:
                                        autoData[dataType] = newData
                        for datatype in list(autoData.keys()):
                            try:
                                self.scanData[channel].append(
                                    (datatype, autoData[datatype])
                                )
                            except KeyError:
                                self.scanData[channel] = [
                                    (datatype, autoData[datatype])
                                ]
                    else:  # manual CalSeq
                        for ifnum in self.backend.getIFNumbers():
                            for i in range(self.backend.getNumIntegrations()):
                                newData = self.backend.getRawPowerByValues(
                                    beam, pol, ifnum, i, phase
                                )
                                try:
                                    channelData = numpy.concatenate(
                                        (channelData, newData)
                                    )
                                except ValueError:
                                    channelData = newData

                        calPosition = self.getCalPos()
                        dataType = self.getDataType(calPosition, beam)
                        self.scanData[channel] = (dataType, channelData)

    def getDataType(self, calPos, feed):
        """Converts cal position Cold1/2 to Vwarm or Vcold depending on feed"""
        if "Cold" in calPos:
            # Convert calPos to key 'Vwarm' or 'Vcold'
            beamLoad = {"Cold1": ("Vcold", "Vwarm"),
                        "Cold2": ("Vwarm", "Vcold")}
            dataType = beamLoad[calPos][feed - 1]
        else:
            dataType = calPos
        return dataType

if __name__ == "__main__":
    projPath = "/home/gbtdata/AGBT16B_288_03"
    scanNum = 1
    scan = CalSeqScan(projPath, scanNum)
    logger.debug("scan: %s", scan)
    scan.processCalseqScan()