from tkinter import Frame, Label, Button, TOP, RIGHT, LEFT, CENTER, BOTTOM
from PIL import Image, ImageTk
import PIL
from Screens.shopButton import ShopButton
class StarShopEngine:
    def __init__(self, window):
        self.window = window
        self.normalShop = True
        self.f = Frame(self.window.root, bg="blue", width=self.window.width, height =self.window.height)
        self.f.pack_propagate(0)

        self.backgroundImage= ImageTk.PhotoImage(file="Backgrounds/starShop.png")
        self.backgroundLabel = Label(self.f, image=self.backgroundImage)

        self.shopScale = self.window.width / 1280
        self.save = self.window.save
        barScale = self.shopScale / 5
        buttonScale = self.shopScale / 2

        self.barImageList = []
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar1.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar2.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar3.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar4.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar5.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar6.png", barScale))

        self.buttonList = []

        self.sideBar = Label(self.window.root, bg="#%02x%02x%02x" % (121, 202, 249), width=self.window.width // 5, height=self.window.height)
        self.sideBar.pack(in_=self.f, side=LEFT, pady=25, padx = 25)

        self.buttonGrid = Label(self.window.root, bg="#%02x%02x%02x" % (121, 202, 249), width=self.window.width // 5 * 3, height =self.window.height)
        self.buttonGrid.pack(in_=self.f, side=TOP)

        self.moneyL = Label(self.window.root, text="Stars: " + str(self.save.stars), bg="#%02x%02x%02x" % (121, 202, 249), font="Helvetica 15 bold", width=self.window.width // 5)
        self.moneyL.pack(side=TOP, in_=self.sideBar, pady=25)

        self.achievementB = Button(self.window.root, text="Shop", command=self.shop, bg="#%02x%02x%02x" % (255, 165, 0), width=self.window.width // 5, font="Helvetica 15 bold")
        self.achievementB.pack(side=BOTTOM, in_=self.sideBar, pady=25)

        self.accept = Button(self.window.root, text="Accept", command=self.accept, bg="#%02x%02x%02x" % (255, 0, 0), width=self.window.width // 5, font="Helvetica 15 bold")
        self.accept.pack(side=BOTTOM, in_=self.sideBar)

        self.shieldButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/maxFuelButton.png"), buttonScale))
        ShopButton(self.window, self.window.save.starFuelCanLevel, self.buttonGrid, self.sideBar, self.save, self.buttonList, self.barImageList, self.backgroundImage, 0, 0,
                   """Fuel Cans:
Doubles the amount of fuel than fuel cans give you""",
                   self.window.root, image=self.shieldButtonImage)
        self.airResistButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/propulsionButton.png"), buttonScale))
        ShopButton(self.window, self.window.save.starSpeedGateLevel, self.buttonGrid, self.sideBar, self.save, self.buttonList, self.barImageList, self.backgroundImage, 1, 0,
                   """Speed Gates:
Doubles the acceleration from speed gates""",
                   self.window.root, image=self.airResistButtonImage)
        self.antiGravButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/shieldButton.png"), buttonScale))
        ShopButton(self.window, self.window.save.starShieldLevel, self.buttonGrid, self.sideBar, self.save, self.buttonList, self.barImageList, self.backgroundImage, 2, 0,
                   """Shields:
Reduces the amount of pull from black holes based on your number of shields""",
                   self.window.root, image=self.antiGravButtonImage)
        self.frictionButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/magnetButton.png"), buttonScale))
        ShopButton(self.window, self.window.save.starMagnetLevel, self.buttonGrid, self.sideBar, self.save, self.buttonList, self.barImageList, self.backgroundImage, 0, 1,
                   """Magnet:
Gives you a magnet that sucks in blobs""",
                   self.window.root, image=self.frictionButtonImage)
        self.launchSpeedButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/predictionButton.png"), buttonScale))
        ShopButton(self.window, self.window.save.starPredictionLevel, self.buttonGrid, self.sideBar, self.save, self.buttonList, self.barImageList, self.backgroundImage, 1, 1,
                   """Predictions:
Displays a line that shows the path you will travel along""",
                   self.window.root, image=self.launchSpeedButtonImage)
        self.maxMassButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/blackHoleButton.png"), buttonScale))
        ShopButton(self.window, self.window.save.starBlackHoleLevel, self.buttonGrid, self.sideBar, self.save, self.buttonList, self.barImageList, self.backgroundImage, 2, 1,
                   """Black hole warnings:
Displays arrows that point towards black holes""",
                   self.window.root, image=self.maxMassButtonImage)

    def update(self):
        self.f.config(width=self.window.width, height=self.window.width)

        self.shopScale = self.window.width / 1280
        self.save = self.window.save
        barScale = self.shopScale / 5
        buttonScale = self.shopScale / 2

        self.sideBar.config(width=self.window.width // 5, heigh=self.window.height)
        self.buttonGrid.config(width=self.window.width // 5 * 3, height=self.window.height)

        self.barImageList.clear()
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar1.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar2.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar3.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar4.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar5.png", barScale))
        self.barImageList.append(self.openTkImage("Images/Shop/levelBar6.png", barScale))

        self.buttonGrid.config(width=self.window.width // 5 * 3, height=self.window.height)
        try:
            self.shieldButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/maxFuelButton.png"), buttonScale))
            self.buttonList[0].config(image=self.shieldButtonImage)
            self.airResistButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/propulsionButton.png"), buttonScale))
            self.buttonList[1].config(image=self.airResistButtonImage)
            self.antiGravButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/shieldButton.png"), buttonScale))
            self.buttonList[2].config(image=self.antiGravButtonImage)
            self.frictionButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/magnetButton.png"), buttonScale))
            self.buttonList[3].config(image=self.frictionButtonImage)
            self.launchSpeedButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/predictionButton.png"), buttonScale))
            self.buttonList[4].config(image=self.launchSpeedButtonImage)
            self.maxMassButtonImage = ImageTk.PhotoImage(self.scale(Image.open("Images/Shop/blackHoleButton.png"), buttonScale))
            self.buttonList[5].config(image=self.maxMassButtonImage)
        except:
            pass

    def accept(self):
        #must add in saving here, buttons dont currently do anything
        self.window.rMenu = "charScreen"

    def shop(self):
        self.window.rMenu = "shop"

    def run(self):
        #must save levels here
        for button in self.buttonList:
            button.run()
        self.save = self.window.save
        self.moneyL.config(text="Stars: " + str(int(self.save.stars)))
        for button in self.buttonList:
            button.save = self.window.save

        self.window.save.starFuelCanLevel = self.buttonList[0].level
        self.window.save.starSpeedGateLevel =self.buttonList[1].level
        self.window.save.starShieldLevel = self.buttonList[2].level
        self.window.save.starMagnetLevel = self.buttonList[3].level
        self.window.save.starPredictionLevel = self.buttonList[4].level
        self.window.save.starBlackHoleLevel = self.buttonList[5].level

    def scale(self, image, scale):
        newWidth = image.size[0] * scale
        wPercent = (newWidth/float(image.size[0]))
        hSize = int((float(image.size[1])*float(wPercent)))
        scaledImage = image.resize((int(newWidth), int(hSize)), PIL.Image.ANTIALIAS)
        return scaledImage

    def hide(self):
        self.backgroundLabel.place(x=10000, y=10000, relwidth=1, relheight=1)
        self.sideBar.place(x=10000, y=10000, relwidth=.15, relheight=1)
        self.f.pack_forget()

    def setUp(self):
        self.backgroundLabel.place(x=0, y=0, relwidth=1, relheight=1)
        self.sideBar.place(x=0, y=0, relwidth=.15, relheight=1)
        self.buttonList[0].level = self.window.save.starFuelCanLevel
        self.buttonList[1].level = self.window.save.starSpeedGateLevel
        self.buttonList[2].level = self.window.save.starShieldLevel
        self.buttonList[3].level = self.window.save.starMagnetLevel
        self.buttonList[4].level = self.window.save.starPredictionLevel
        self.buttonList[5].level = self.window.save.starBlackHoleLevel

        self.f.pack()

    def openTkImage(self, path, scale):
        return ImageTk.PhotoImage(self.scale(Image.open(path), scale).convert("RGB"))


import random
class Electrodomestico:
    def __init__(self):
        self.color="blanco"
        self.consumo="A"
        self.prebase="10 €"
        self.consumo=None
    def tabla(self):
        self.consumo= "A"
        self.consumo2= "B"
        self.consumo3= "C"

def precio_if():
    if refrigeradora.consumo=="A":
        print(" Precio: 100")
    elif refrigeradora.consumo=="B":
        print(" Precio: 80")
    elif refrigeradora.consumo=="C":
        print(" Precio: 60")

class lavadora():
    def __init__(self):
        self.color="blanco"
        self.consumo="A"
        self.prebase="10 €"
        self.consumo=None

    def tabla2(self):
        self.consumo= "Entre 0 y 19 kg"
        self.consumo2= "Entre 20 y 49 kg"
        self.consumo3= "Entre 50 y 79 kg"
        self.consumo4= "Mayor que 80 kg"

def precio_lavadora():
    if lavadora.consumo=="Entre 0 y 19 kg":
        print(" Precio: 10%")
    elif lavadora.consumo=="Entre 20 y 49 kg":
        print(" Precio: 20%")
    elif lavadora.consumo=="Entre 50 y 79 kg":
        print(" Precio: 30%")
    elif lavadora.consumo=="Mayor que 80 kg":
        print(" Precio: 40%")

obj_c= Electrodomestico()
obj_l= lavadora()
obj_c.tabla()
obj_l.tabla2()

print(" ")
print(" ------------Valores Predeterminados de la tienda------------")
peso=int(input(" Ingrese el peso del objeto: "))
refrigeradora=Electrodomestico()

print(" Precio Base:",refrigeradora.prebase,"\n","Color:",refrigeradora.color,"\n",
      "Consumo energetico:",obj_c.consumo,"\n","Peso:",peso)

lista=["azul","rojo"]
refrigeradora.color=random.choice(lista)
listaconsumo=[obj_c.consumo,obj_c.consumo2,obj_c.consumo3]
refrigeradora.consumo=random.choice(listaconsumo)
print(" ")
print(" //////////////////////////////////////////////////////")
print(" ")
for i in range(1):
    print(" ------------Refrigeradora------------")
    print(" Color refrigeradora: ",refrigeradora.color,"\n","Consumo energetico:",refrigeradora.consumo,
          "\n","Peso:",peso,"\n",precio_if())

lavadora.color=random.choice(lista)
listaconsumo=[obj_l.consumo,obj_l.consumo2,obj_l.consumo3,obj_l.consumo4]
lavadora.consumo=random.choice(listaconsumo)
print(" ")
for i in range(1):
    print(" ------------Lavadora------------")
    print(" Color lavadora: ",lavadora.color,"\n","Carga:",lavadora.consumo,
          "\n","Peso:",peso,"\n",precio_lavadora())


def main():
    file_path = input("Enter path containing puzzle input: ")
    algorithm_selection = input("Use checksum 1 or 2? ")
    puzzle_input = open(file_path, "r")
    input_lines = puzzle_input.readlines()
    lines_no_whitespace = []
    for line in input_lines:
        lines_no_whitespace.append(line.split())

    if algorithm_selection == 1:
        solution = calculate_checksum(lines_no_whitespace)
    else:
        solution = calculate_checksum_2(lines_no_whitespace)

    print("Solution: {}".format(solution))

def calculate_checksum(input_lines):
    checksum = 0
    for line in input_lines:
        sorted_line = sorted([int(x) for x in line])
        last = sorted_line[-1]
        first = sorted_line[0]
        difference = last - first
        checksum += difference if difference > 0 else 0
    return checksum

def calculate_checksum_2(input_lines):
    checksum = 0
    for line in input_lines:
        sorted_line = sorted([int(x) for x in line])

        for x in range(0, len(sorted_line) - 1):
            found_remainder_zero = False
            for y in range(x + 1, len(sorted_line)):
                divisor = sorted_line[x]
                dividend = sorted_line[y]
                if dividend % divisor == 0:
                    checksum += dividend // divisor
                    found_remainder_zero = True
                    break
            if found_remainder_zero:
                break

    return checksum

if __name__ == "__main__": main()


from random import randint

million = 10**5

with open('/usr/share/dict/words') as word_file:
    words = word_file.readlines()

for i in range(million):
    offset = randint(0, million / 2)
    diff = randint(0, million / 4)
    print(randint(offset, offset + diff),
          randint(offset + diff, offset + offset + diff*2),
          words[randint(0, len(words) - 1)], end='')


import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, recall_score, f1_score, classification_report
import matplotlib.pyplot as plt
import seaborn as sns
import os
from PIL import Image

# Define the CNN model
class CNNModel(nn.Module):
    def __init__(self):
        super(CNNModel, self).__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)
        self.pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Linear(32, 1)

    def forward(self, x):
        x = nn.functional.relu(self.conv1(x))
        x = nn.functional.relu(self.conv2(x))
        x = self.pool(x)
        x = x.view(x.size(0), -1)
        x = torch.sigmoid(self.fc(x))
        return x

# Custom dataset class
class CustomDataset(Dataset):
    def __init__(self, image_folder, labels_data, transform=None):
        self.image_folder = image_folder
        self.labels_data = labels_data
        self.transform = transform

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

    def __getitem__(self, idx):
        # img_name = os.path.join(self.image_folder, f'e{str(idx+1).zfill(5)}.png')
        img_name = os.path.join(self.image_folder, self.labels_data.iloc[idx, 0])

        image = Image.open(img_name).convert('RGB')
        label = self.labels_data.iloc[idx, 1]
        if self.transform:
            image = self.transform(image)
        return image, label

# Define transformations
transform = transforms.Compose([
    transforms.Resize((32, 32)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

# raw data
# image_folder = 'image_cwt_raw/overall'
# labels_file = 'image_cwt_raw/overall_labels.csv'

image_folder = 'CWT_data_resampled/overall'
labels_file = 'CWT_data_resampled/overall_labels.csv'

# balanced data
# image_folder = 'CWT_data_resampled/training-e1'
# labels_file = 'CWT_data_resampled/training-e/e_labels.csv'

# Load and split the data
labels_data = pd.read_csv(labels_file)
train_data, test_data = train_test_split(labels_data, test_size=0.3, random_state=42)

train_dataset = CustomDataset(image_folder, train_data, transform=transform)
test_dataset = CustomDataset(image_folder, test_data, transform=transform)

train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)

# Initialize the CNN model and optimizer
model = CNNModel()
criterion = nn.BCELoss()  # Binary Cross-Entropy loss
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Train the model
num_epochs = 10
for epoch in range(num_epochs):
    for batch_X, batch_y in train_loader:
        optimizer.zero_grad()
        outputs = model(batch_X)
        loss = criterion(outputs, batch_y.unsqueeze(1).float())
        loss.backward()
        optimizer.step()

# Evaluate the model
model.eval()
with torch.no_grad():
    y_pred_probs = []
    y_true = []

    for batch_X, batch_y in train_loader:
        outputs = model(batch_X)
        y_pred_probs.extend(outputs)
        y_true.extend(batch_y)

y_pred_probs = torch.cat(y_pred_probs)
y_pred = (y_pred_probs >= 0.5).float()
y_true = torch.tensor(y_true)

# Calculate metrics
accuracy = accuracy_score(y_true, y_pred)
conf_matrix = confusion_matrix(y_true, y_pred)
tn, fp, fn, tp = conf_matrix.ravel()
sensitivity = tp / (tp + fn)
specificity = tn / (tn + fp)
uf1 = (2 * tp) / (2 * tp + fp + fn)
uar = (sensitivity + specificity) / 2

# Calculate the normalized confusion matrix
normalized_conf_matrix = conf_matrix.astype('float') / conf_matrix.sum(axis=1)[:, np.newaxis]

# Print metrics
classification_rep = classification_report(y_true, y_pred, target_names=['Class 0', 'Class 1'])
normalized_conf_matrix = conf_matrix.astype('float') / conf_matrix.sum(axis=1)[:, np.newaxis]

print("Accuracy:", accuracy)
print("Sensitivity:", sensitivity)
print("Specificity:", specificity)
print("Unweighted F1-Score (UF1):", uf1)
print("Unweighted Average Recall (UAR):", uar)

plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['font.size'] = '46'
sns.set(font_scale=1.2)
sns.heatmap(normalized_conf_matrix, annot=True, cmap="Blues", fmt=".2f", xticklabels=['Normal', 'Abnormal'], yticklabels=['Normal', 'Abnormal'])

plt.xlabel('Predicted label')
plt.ylabel('True label')
plt.title('Normalised Confusion Matrix')
print("Classification Report:\n", classification_rep)

plt.show()


# -*- coding: utf-8 -*-
"""
Created on Fri April 7 17:13:22 2023
@author: PhoenixWANG
"""

import time
import serial
import pandas as pd
import numpy as np

#根据Arduino代码设置串口（Serial）信息
ser = serial.Serial(
    port = 'COM3',
    baudrate = 9600,
    parity = serial.PARITY_ODD,
    stopbits = serial.STOPBITS_TWO,
    bytesize = serial.SEVENBITS,

    )

#设置生成数据集文件位置
outputpath = 'D:/PolyU/year3 sem02/ME31002/Lab MiniProject/Lab3/2DOF_TWOOverdamped.csv'

#定义数据收集函数
def datacollection(ser,list1,time1,t_initial,length,outputpath = False):

    for i in range(length):#length: 需要的数据集大小

        data = ser.readline()#读取串口信息
        time1.append(time.time()-t_initial)#计算当前时间差
        list1.append(data)#添加数据

    for i in range(length):

        list1[i] = float(list1[i].decode('utf-8'))#对串口读取数据根据utf-8解码表解码为字符串

    if outputpath != False:#如果制定了输出路径，则为要分析的运动数据集，而非检查初末位置

        diction = {
            'Time':time1,
            'Distance':list1,
            }

        result = pd.DataFrame(diction)#生成DataFrame为输出数据集做准备

        return result

    else:#检查初末位置

        position =  (1+np.std(list1)/np.mean(list1))*np.mean(list1)#减少噪音的影响，近似估计位置

        return position

data = ''#提前占上内存

list1,time1 = [],[]#初始化收集距离与时间数据的容器

count = 0#是否开始正式测量，而非检查初末位置的标志

t_initial = time.time()#获得实验开始时间

length = 300

#计算初位置
print("Check your initial position\n")

pos_initial = datacollection(ser,list1,time1,t_initial,length)

#计算整个运动过程中数据
count = input("Please input 1 for start\n")

if int(count) == 1:#开始记录实验

    list1,time1 = [],[]

    print("Release!!!!\n")

    time.sleep(1.5)#延时1.5s给人反应的时间

    t_initial = time.time()#获得实际实验开始的初始时间

    result = datacollection(ser, list1, time1, t_initial, length,outputpath)#获得整体数据集

#计算末位置
list1,time1 = [],[]
t_initial = time.time()

print("Check your Final position\n")

pos_final = datacollection(ser, list1, time1, t_initial, length,outputpath = False)

#进行平移，使得数据整体与坐标轴尽可能对齐

idx = 0;#初始化起点index

for i in range(len(result)):
    if abs(result['Distance'][i] - pos_initial) >=30:#如果和估算初位置差别过大，则index前一个数据可以视为起点
        idx = i-1
        break

result = result.iloc[idx:,:]#切除前面不必要的冗余数据

result['Distance'] = result['Distance'] - pos_final#将数据向下平移到坐标轴上，获得delta_x

result.to_csv(outputpath,sep = ',',index = False, header = True)#输出最终的数据集文件，用于MATLAB仿真

#关闭同Arduino的串口
ser.close()


import numpy as np
import torch as t
import torch.nn as nn
import torch.nn.functional as F

from ..attention import MultiHeadAttention
from ..utils import PositionWise

class Decoder(nn.Module):
    def __init__(self, embeddings, n_layers, n_heads, h_s, p_s, vocab_s, dropout=0.1):
        """
        :param embeddings: An instance of embeddings layer
        :param n_heads: Number of attention heads
        :param h_s: hidden size of input
        :param p_s: size of projected queries, keys and values
        :param vocab_s: vocab size
        :param dropout: drop prob
        """
        super(Decoder, self).__init__()

        self.embeddings = embeddings
        self.vocab_s = vocab_s
        self.layers = nn.ModuleList([
            DecoderLayer(n_heads, h_s, p_s, dropout)
            for _ in range(n_layers)
        ])

        self.out_to_vocab = nn.Sequential(
            nn.Linear(h_s, 1000),
            nn.SELU(),
            nn.Linear(1000, vocab_s)
        )

    def forward(self, input):
        """
        :param input: An long tensor with shape of [b_s, input_len]
        :return: An float tensor with shape of [b_s, input_len, h_s]
        """

        b_s, input_len = input.size()

        input, _ = self.embeddings(input)
        mask = self.autoregressive_mask(b_s, input_len, input.device)

        out = input
        for layer in self.layers:
            out = layer(out, mask)

        return self.out_to_vocab(out)

    def generate(self, seed, device):

        # 1 is go token idx
        seed_len = len(seed)
        input_idx = t.tensor([seed], dtype=t.long, device=device)

        input, _ = self.embeddings(input_idx)

        history = []
        for i, layer in enumerate(self.layers):
            history += [input]
            input = layer(input, mask=self.autoregressive_mask(1, len(seed), device))

        out = F.softmax(1.5 * self.out_to_vocab(input[:, -1]).squeeze(), dim=-1)

        result = []

        for step in range(self.embeddings.max_len - 2):

            out = out.cpu().numpy()
            input_idx = int(np.random.choice(self.vocab_s, 1, p=out)[0])
            if input_idx == 2:
                break

            result += [input_idx]

            input_idx = t.tensor([[input_idx]], dtype=t.long, device=device)
            pos = t.tensor([[step + 1 + seed_len]], dtype=t.long, device=device)
            input, _ = self.embeddings(input_idx, pos)

            for i, layer in enumerate(self.layers):
                history[i] = t.cat([history[i], input], 1)
                input = layer.inference_mode(input, history[i])

            out = F.softmax(1.5 * self.out_to_vocab(input).squeeze(), dim=-1)

        return result

    @staticmethod
    def autoregressive_mask(batch_size, length, device):
        mask = t.ones(length, length, dtype=t.uint8, device=device).tril_(-1)
        return mask.transpose(0, 1).repeat(batch_size, 1).view(batch_size, length, length)

class DecoderLayer(nn.Module):
    def __init__(self, n_heads, h_s, p_s, dropout=0.1):
        """
        :param n_heads: Number of attention heads
        :param h_s: hidden size of input
        :param p_s: size of projected queries and keys
        :param dropout: drop prob
        """
        super(DecoderLayer, self).__init__()

        self.attention = MultiHeadAttention(n_heads, h_s, p_s, dropout)
        self.position_wise = PositionWise(h_s, h_s * 4, dropout)

    def forward(self, input, mask):
        """
        :param input: An float tensor with shape of [b_s, input_len, h_s]
        :param mask: An byte tensor with shape of [b_s, input_len, input_len]
        :return: An float tensor with shape of [b_s, input_len, h_s]
        """

        result = self.attention(q=input, k=input, v=input, mask=mask)
        return self.position_wise(result)

    def inference_mode(self, q, input):
        """
        :param q: An float tensor with shape of [b_s, 1, h_s]
        :param input: An float tensor with shape of [b_s, input_len, h_s]
        :return: An float tensor with shape of [b_s, 1, h_s]
        """

        '''
        I believe that there is the way this module could be written in more efficient and beautiful way,
        in order to prevent having two different functions
        for training and inference modes with quite similar semantics,
        but I'm not sure if I want to find it.
        '''

        result = self.attention(q=q, k=input, v=input)
        return self.position_wise(result)


import sensor, image, lcd
import KPU as kpu
from Maix import GPIO
from fpioa_manager import *
from machine import UART
import time

fm.register(20, fm.fpioa.UART2_TX) # Declare the pin for TX uart
fm.register(21, fm.fpioa.UART2_RX) # Declare the pin for RX uart

uart = UART(UART.UART2, 9600, 8, None, 1, timeout = 1000, read_buf_len = 4096)

# Commands for DFplayer
cmd_init = bytearray([0x7E, 0xFF, 0x06, 0x0C, 0x01, 0x00, 0x00, 0xFE, 0xEE, 0xEF])
cmd_vol =  bytearray([0x7E, 0xFF, 0x06, 0x06, 0x01, 0x00, 0x14, 0xFE, 0xE0, 0xEF]) # 14 in HEX is 20 in DEC
cmd_1st_song = bytearray([0x7E, 0xFF, 0x06, 0x03, 0x01, 0x00, 0x01, 0xFE, 0xF6, 0xEF])
cmd_2nd_song = bytearray([0x7E, 0xFF, 0x06, 0x03, 0x01, 0x00, 0x02, 0xFE, 0xF5, 0xEF])
cmd_3rd_song = bytearray([0x7E, 0xFF, 0x06, 0x03, 0x01, 0x00, 0x03, 0xFE, 0xF4, 0xEF])
cmd_4th_song = bytearray([0x7E, 0xFF, 0x06, 0x03, 0x01, 0x00, 0x04, 0xFE, 0xF3, 0xEF])
cmd_5th_song = bytearray([0x7E, 0xFF, 0x06, 0x03, 0x01, 0x00, 0x05, 0xFE, 0xF2, 0xEF])

cmd_dict = {'Angry' : cmd_1st_song, 'Happy' : cmd_2nd_song, 'Sad' : cmd_3rd_song, 'Surprise' : cmd_4th_song}

uart.write(cmd_init)
uart.read()
uart.write(cmd_vol)
uart.read()

lcd.init(freq=15000000)
sensor.reset()                      # Reset and initialize the sensor. It will
                                    # run automatically, call sensor.run(0) to stop
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA)   # Set frame size to QVGA (320x240)
#sensor.set_windowing((320, 240))
sensor.skip_frames(time = 2000)     # Wait for settings take effect.
sensor.set_vflip(1)
sensor.set_hmirror(1)
clock = time.clock()                # Create a clock object to track the FPS.

print('loading face detect model')
task_detect_face = kpu.load(0x300000) # Charge face detect model into KPU
print('loading face expresion classify model')
task_classify_face = kpu.load(0x500000) # Charge face classification model into KPU

a=kpu.set_outputs(task_classify_face, 0, 1, 1, 5)

anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)
a = kpu.init_yolo2(task_detect_face, 0.5, 0.3, 5, anchor)

labels = ['Angry', 'Happy', 'Neutral', 'Sad', 'Surprise'] # Facial expression labels

print('configuration complete')

while(True):
    clock.tick()                    # Update the FPS clock.
    img = sensor.snapshot()         # Take a picture and return the image.
    detected_face = kpu.run_yolo2(task_detect_face, img)

    if detected_face:
        for i in detected_face:
            face = img.cut(i.x(), i.y(), i.w(), i.h())
            face_128 = face.resize(128, 128)
            a = face_128.pix_to_ai()
            fmap = kpu.forward(task_classify_face, face_128)
            plist = fmap[:]
            pmax = max(plist)
            #print("%s: %s" % (labels[plist.index(pmax)], pmax))
            print(plist)
            label = labels[plist.index(pmax)]

            if label != 'Neutral':
                uart.write(cmd_dict[label])
                uart.read()
                time.sleep(2)


from flask import Flask, request
from flask import Flask, render_template
from flask_cors import CORS, cross_origin
import logging
import json
import sys
import pandas as pd
from pretty_html_table import build_table

#Import own functions
# from historical_bets import update_betting_timeseries

from config import CONTRACT_CHAIN_DICT, DATA_FILE_NAME
#Set up Flask app
app = Flask(__name__,template_folder='templates')
CORS(app)
print('ready')

# app.logger.addHandler(logging.StreamHandler(sys.stdout))
# app.logger.setLevel(logging.ERROR)

#Set up routes
@app.route('/', methods=['GET'])
@cross_origin(headers=['Content- Type','Authorization'])
def landing_page():
    return "Welcome to Cognoscenti"

# @app.route('/timeseries', methods=['GET'])
# @cross_origin(headers=['Content- Type','Authorization'])
# def get_timeseries():
#     #Get chain name
#     chain_name = request.args.get('chain_name', type=str)

#     #Chain contract matching
#     if chain_name not in CONTRACT_CHAIN_DICT.keys():
#         return {'error': f"No contract instance for {chain_name}"}

#     contract_address = CONTRACT_CHAIN_DICT[chain_name]

#     res = update_betting_timeseries(chain_name=chain_name,contract_address=contract_address)

#     return res

@app.route('/okx_dashboard', methods=['GET'])
@cross_origin(headers=['Content- Type','Authorization'])
def get_dashboard_data():
    #Load data set
    with open(DATA_FILE_NAME) as user_file:
        file_contents = user_file.read()

    return file_contents

@app.route('/okx', methods=['GET'])
@cross_origin(headers=['Content- Type','Authorization'])
def get_dashboard():
    #Load data set
    # with open(DATA_FILE_NAME) as user_file:
    #     file_contents = user_file.read()

    # # # users = User.query
    # file_contents = json.loads(file_contents)
    # addr = list(file_contents.keys())
    # data = pd.DataFrame(file_contents)
    # data = data.T
    # data['address'] = addr

    data = pd.read_pickle('all_data.pkl')
    addr = list(data.keys())
    data = pd.DataFrame(data)
    data = data.T
    data['address'] = data.index
    # data = data.to_json(orient='records')
    # print(data)

    html_table_blue_light = build_table(data,'blue_light')
    return html_table_blue_light
    # print(type(data)
    # return_data = data.to_html()
    # return render_template('base.html')
    # return render_template('bootstrap_table.html', title='Bootstrap Table',users=file_contents)

if __name__ == '__main__':
#Run Flask app
    #Server settings
    app.run()


import requests
from bs4 import BeautifulSoup
import pandas as pd

def scrape_product_listing(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')

    products = soup.find_all('div', {'data-component-type': 's-search-result'})

    data = []
    for product in products:
        product_url = 'https://www.amazon.in' + product.find('a', {'class': 'a-link-normal s-no-outline'})['href']
        product_name = product.find('span', {'class': 'a-size-medium a-color-base a-text-normal'}).text.strip()
        product_price = product.find('span', {'class': 'a-price-whole'}).text.strip()

        rating_element = product.find('span', {'class': 'a-icon-alt'})
        rating = rating_element.text.strip() if rating_element else ''

        reviews_element = product.find('span', {'class': 'a-size-base'})
        reviews = reviews_element.text.strip() if reviews_element else ''

        data.append([product_url, product_name, product_price, rating, reviews])

    return data

# Scrape product listing pages
base_url = 'https://www.amazon.in/s?k=bags&crid=2M096C61O4MLT&qid=1653308124&sprefix=ba%2Caps%2C283&ref=sr_pg_'
num_pages = 20

all_data = []
for page in range(1, num_pages + 1):
    url = base_url + str(page)
    page_data = scrape_product_listing(url)
    all_data.extend(page_data)

# Export data to CSV
df = pd.DataFrame(all_data, columns=['Product URL', 'Product Name', 'Product Price', 'Rating', 'Number of Reviews'])
df.to_csv('amazon_product_listing.csv', index=False)


import sys

from PyQt5.QtWidgets import *

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setWindowTitle("Font Dialog")
        self.setGeometry(50, 50, 500, 300)
        layout = QGridLayout()
        self.setLayout(layout)
        button = QPushButton("Choose Font")
        button.clicked.connect(self.open)
        layout.addWidget(button, 0, 0)
        self.font = QFontDialog()

    def open(self):
        self.font.open()

app = QApplication(sys.argv)

def main():
    window = Window()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


from __future__ import annotations

import numpy as np
from sanic.log import logger

from . import category as ImageDimensionCategory
from ...node_base import NodeBase
from ...node_factory import NodeFactory
from ...properties.inputs import ImageInput, NumberInput, InterpolationInput
from ...properties.outputs import ImageOutput
from ...properties import expression
from ...impl.pil_utils import resize, InterpolationMethod
from ...utils.utils import get_h_w_c, round_half_up

@NodeFactory.register("chainner:image:resize_factor")
class ImResizeByFactorNode(NodeBase):
    def __init__(self):
        super().__init__()
        self.description = (
            "Resize an image by a percent scale factor. "
            "Auto uses box for downsampling and lanczos for upsampling."
        )
        self.inputs = [
            ImageInput(),
            NumberInput(
                "Scale Factor",
                precision=4,
                controls_step=25.0,
                default=100.0,
                unit="%",
            ),
            InterpolationInput(),
        ]
        self.category = ImageDimensionCategory
        self.name = "Resize (Factor)"
        self.outputs = [
            ImageOutput(
                image_type=expression.Image(
                    width="max(1, int & round(Input0.width * Input1 / 100))",
                    height="max(1, int & round(Input0.height * Input1 / 100))",
                    channels_as="Input0",
                )
            )
        ]
        self.icon = "MdOutlinePhotoSizeSelectLarge"
        self.sub = "Resize"

    def run(
        self, img: np.ndarray, scale: float, interpolation: InterpolationMethod
    ) -> np.ndarray:
        """Takes an image and resizes it"""

        logger.debug(f"Resizing image by {scale} via {interpolation}")

        h, w, _ = get_h_w_c(img)
        out_dims = (
            max(round_half_up(w * (scale / 100)), 1),
            max(round_half_up(h * (scale / 100)), 1),
        )

        return resize(img, out_dims, interpolation)


nums = [8,9,99,18,13,25,144,44,201,904]
largestNum = -1
average = 0
smallestNum = 904
for num in nums:
    if largestNum < num:
        largestNum = num
    #print(largestNum,num)
    average = (average + num)
    if smallestNum > num:
        smallestNum = num
    #print(smallestNum,num)

average = average/10
print(nums)
print("The smallest number is",smallestNum)
print("The average is",average)
print("The Largest number is",largestNum)
print("Done")


from typing import Dict, List, Optional
from constructs import Construct

from aws_cdk import (
    Stack,
    aws_route53 as route53,
    aws_certificatemanager as certificatemanager,
    CfnOutput,
)

class DomainStack(Stack):
    def __init__(
        self,
        scope: Construct,
        domain_of_hosted_zone: str,                     # Example: 'example.com'
        sub_domain_list: List[str] = [],                # Example: ['sub.example.com', 'foo.example.com']
        existing_hosted_zone_id: Optional[str] = None,  # Fill this field if you don't want to create an new Hosted Zone. Read warning below.
    ) -> None:
        # Replace 'example.com' for 'example-dot-com'
        id = domain_of_hosted_zone.replace('.', '-dot-')

        # Join all domains
        all_domains = [domain_of_hosted_zone, ] + sub_domain_list

        # Call super constructor
        super().__init__(
            scope=scope,
            id=id,
            description=f'Hosted zone and certificates of {", ".join(all_domains)}.'
        )

        # Warning: Each time a Hosted Zone is created, it costs like 0.5 USD. So, take care.
        # Also, very important, each time you create a Hosted Zone with CDK, the deploy will stops until you
        # attach the namespaces to your domain. Do do it, first deploy, and then, go to your route53
        # open the hosted zone created, and copy the four namespaces.
        # Then, go to your domain provider and paste the namespaces in the configuration of the domain.

        # Assert that every sub domain ends correctly
        for sub_domain in sub_domain_list:
            assert sub_domain.endswith(domain_of_hosted_zone)

        if existing_hosted_zone_id:
            hosted_zone = route53.HostedZone.from_hosted_zone_id(
                self,
                id=id,
                hosted_zone_id=existing_hosted_zone_id
            )
        else:
            # Do not forget to set up the namespaces correctly once the zone name is created.

            hosted_zone = route53.HostedZone(
                self,
                id=id,
                zone_name=domain_of_hosted_zone
            )

        # Store some properties in the instance
        self.hosted_zone = hosted_zone
        self._certificates = self.generate_certificates(all_domains, hosted_zone)

    def generate_certificates(self, all_domains, hosted_zone) -> Dict[str, certificatemanager.Certificate]:
        # Add a certificate for the domain and each sub domain
        certificates: Dict[str, certificatemanager.Certificate] = dict()
        for sub_domain in all_domains:
            certificate = certificatemanager.Certificate(self,
                id=sub_domain,
                domain_name=sub_domain,
                validation=certificatemanager.CertificateValidation.from_dns(hosted_zone),
            )

            CfnOutput(self, id=f'certificate_arn_of_{sub_domain}', value= certificate.certificate_arn)

        return certificates

    def get_certificate_of(self, domain_or_sub_domain: str) -> certificatemanager.Certificate:
        if domain_or_sub_domain not in self._certificates:
            raise Exception('You are using get_certificate_of over an non declared domain neighter subdomain.')

        return self._certificates[domain_or_sub_domain]

# Interface.
class IDomainAttachable:
    def attach_to_domain(
        self,
        domain_stack: DomainStack,
        domain: str # Example: 'foo.example.com'
        ):
        raise NotImplementedError()


#!/usr/bin/env python3

from collections import OrderedDict
import logging
import os
from pathlib import Path
import shlex
import subprocess
import sys

from util import KernelVersion
from vmtest.config import (
    ARCHITECTURES,
    HOST_ARCHITECTURE,
    KERNEL_FLAVORS,
    SUPPORTED_KERNEL_VERSIONS,
    Kernel,
)
from vmtest.download import DownloadCompiler, DownloadKernel, download_in_thread
from vmtest.kmod import build_kmod
from vmtest.rootfsbuild import build_drgn_in_rootfs
from vmtest.vm import LostVMError, run_in_vm

logger = logging.getLogger(__name__)

class _ProgressPrinter:
    def __init__(self, file):
        self._file = file
        if hasattr(file, "fileno"):
            try:
                columns = os.get_terminal_size(file.fileno())[0]
                self._color = True
            except OSError:
                columns = 80
                self._color = False
        self._header = "#" * columns
        self._passed = {}
        self._failed = {}

    def _green(self, s: str) -> str:
        if self._color:
            return "\033[32m" + s + "\033[0m"
        else:
            return s

    def _red(self, s: str) -> str:
        if self._color:
            return "\033[31m" + s + "\033[0m"
        else:
            return s

    def update(self, category: str, name: str, passed: bool):
        d = self._passed if passed else self._failed
        d.setdefault(category, []).append(name)

        if self._failed:
            header = self._red(self._header)
        else:
            header = self._green(self._header)

        print(header, file=self._file)
        print(file=self._file)

        if self._passed:
            first = True
            for category, names in self._passed.items():
                if first:
                    first = False
                    print(self._green("Passed:"), end=" ")
                else:
                    print("       ", end=" ")
                print(f"{category}: {', '.join(names)}")
        if self._failed:
            first = True
            for category, names in self._failed.items():
                if first:
                    first = False
                    print(self._red("Failed:"), end=" ")
                else:
                    print("       ", end=" ")
                print(f"{category}: {', '.join(names)}")

        print(file=self._file)
        print(header, file=self._file, flush=True)

def _kdump_works(kernel: Kernel) -> bool:
    if kernel.arch.name == "aarch64":
        # kexec fails with "kexec: setup_2nd_dtb failed." on older versions.
        # See
        # http://lists.infradead.org/pipermail/kexec/2020-November/021740.html.
        return KernelVersion(kernel.release) >= KernelVersion("5.10")
    elif kernel.arch.name == "arm":
        # Without virtual address translation, we can't debug vmcores. Besides,
        # kexec fails with "Could not find a free area of memory of 0xXXX
        # bytes...".
        return False
    elif kernel.arch.name == "ppc64":
        # Before 6.1, sysrq-c hangs.
        return KernelVersion(kernel.release) >= KernelVersion("6.1")
    elif kernel.arch.name == "s390x":
        # Before 5.15, sysrq-c hangs.
        return KernelVersion(kernel.release) >= KernelVersion("5.15")
    elif kernel.arch.name == "x86_64":
        return True
    else:
        assert False, kernel.arch.name

if __name__ == "__main__":
    import argparse

    logging.basicConfig(
        format="%(asctime)s:%(levelname)s:%(name)s:%(message)s", level=logging.INFO
    )
    parser = argparse.ArgumentParser(
        description="test drgn in a virtual machine",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        "-d",
        "--directory",
        metavar="DIR",
        type=Path,
        default="build/vmtest",
        help="directory for vmtest artifacts",
    )
    parser.add_argument(
        "-a",
        "--architecture",
        dest="architectures",
        action="append",
        choices=["all", "foreign", *sorted(ARCHITECTURES)],
        default=argparse.SUPPRESS,
        required=HOST_ARCHITECTURE is None,
        help="architecture to test, "
        '"all" to test all supported architectures, '
        'or "foreign" to test all supported architectures other than the host architecture; '
        "may be given multiple times"
        + (
            "" if HOST_ARCHITECTURE is None else f" (default: {HOST_ARCHITECTURE.name})"
        ),
    )
    parser.add_argument(
        "-k",
        "--kernel",
        metavar="PATTERN|{all," + ",".join(KERNEL_FLAVORS) + "}",
        dest="kernels",
        action="append",
        default=argparse.SUPPRESS,
        help="kernel to test, "
        '"all" to test all supported kernels, '
        "or flavor name to test all supported kernels of a specific flavor; "
        "may be given multiple times (default: none)",
    )
    parser.add_argument(
        "-l",
        "--local",
        action="store_true",
        help="run local tests",
    )
    args = parser.parse_args()

    architecture_names = []
    if hasattr(args, "architectures"):
        for name in args.architectures:
            if name == "all":
                architecture_names.extend(ARCHITECTURES)
            elif name == "foreign":
                architecture_names.extend(
                    [
                        arch.name
                        for arch in ARCHITECTURES.values()
                        if arch is not HOST_ARCHITECTURE
                    ]
                )
            else:
                architecture_names.append(name)
        architectures = [
            ARCHITECTURES[name] for name in OrderedDict.fromkeys(architecture_names)
        ]
    else:
        architectures = [HOST_ARCHITECTURE]

    if hasattr(args, "kernels"):
        kernels = []
        for pattern in args.kernels:
            if pattern == "all":
                kernels.extend(
                    [
                        version + ".*" + flavor
                        for version in SUPPORTED_KERNEL_VERSIONS
                        for flavor in KERNEL_FLAVORS
                    ]
                )
            elif pattern in KERNEL_FLAVORS:
                kernels.extend(
                    [version + ".*" + pattern for version in SUPPORTED_KERNEL_VERSIONS]
                )
            else:
                kernels.append(pattern)
        args.kernels = OrderedDict.fromkeys(kernels)
    else:
        args.kernels = []

    if not args.kernels and not args.local:
        parser.error("at least one of -k/--kernel or -l/--local is required")

    if args.kernels:
        to_download = [DownloadCompiler(arch) for arch in architectures]
        for pattern in args.kernels:
            for arch in architectures:
                to_download.append(DownloadKernel(arch, pattern))
    else:
        to_download = []

    progress = _ProgressPrinter(sys.stderr)

    with download_in_thread(args.directory, to_download) as downloads:
        for arch in architectures:
            if arch is HOST_ARCHITECTURE:
                subprocess.check_call(
                    [sys.executable, "setup.py", "build_ext", "-i"],
                    env={
                        **os.environ,
                        "CONFIGURE_FLAGS": "--enable-compiler-warnings=error",
                    },
                )
                if args.local:
                    logger.info("running local tests on %s", arch.name)
                    status = subprocess.call(
                        [
                            sys.executable,
                            "-m",
                            "pytest",
                            "-v",
                            "--ignore=tests/linux_kernel",
                        ]
                    )
                    progress.update(arch.name, "local", status == 0)
            else:
                rootfs = args.directory / arch.name / "rootfs"
                build_drgn_in_rootfs(rootfs)
                if args.local:
                    logger.info("running local tests on %s", arch.name)
                    status = subprocess.call(
                        [
                            "unshare",
                            "--map-root-user",
                            "--map-users=auto",
                            "--map-groups=auto",
                            "--fork",
                            "--pid",
                            "--mount-proc=" + str(rootfs / "proc"),
                            "sh",
                            "-c",
                            r"""
set -e

mount --bind . "$1/mnt"
chroot "$1" sh -c 'cd /mnt && pytest -v --ignore=tests/linux_kernel'
""",
                            "sh",
                            rootfs,
                        ]
                    )
                    progress.update(arch.name, "local", status == 0)
        for kernel in downloads:
            if not isinstance(kernel, Kernel):
                continue
            kmod = build_kmod(args.directory, kernel)
            if _kdump_works(kernel):
                kdump_command = """\
    "$PYTHON" -Bm vmtest.enter_kdump
    # We should crash and not reach this.
    exit 1
"""
            else:
                kdump_command = ""
            test_command = rf"""
set -e

export PYTHON={shlex.quote(sys.executable)}
export DRGN_TEST_KMOD={shlex.quote(str(kmod))}
export DRGN_RUN_LINUX_KERNEL_TESTS=1
if [ -e /proc/vmcore ]; then
    "$PYTHON" -Bm pytest -v tests/linux_kernel/vmcore
else
    insmod "$DRGN_TEST_KMOD"
    "$PYTHON" -Bm pytest -v tests/linux_kernel --ignore=tests/linux_kernel/vmcore
{kdump_command}
fi
"""
            try:
                status = run_in_vm(
                    test_command,
                    kernel,
                    args.directory / kernel.arch.name / "rootfs",
                    args.directory,
                )
            except LostVMError as e:
                print("error:", e, file=sys.stderr)
                status = -1
            progress.update(kernel.arch.name, kernel.release, status == 0)


#importar libreria de datos
from sklearn import datasets
#importar libreria de ML regresion lineal
from sklearn.linear_model import LinearRegression
#importar libreria para graficos de visualizacion
import matplotlib.pyplot as plt

import numpy as np

#asignar los datos a una variable
boston = datasets.load_boston()

#crear un objeto de regresion lineal
lr = LinearRegression(normalize=True)
#entrenar el objeto de regresion lineal con los datos obtenidos
#el primer argumento será toda las variables y la segunda el resultado
lr.fit(boston.data, boston.target)

#observar el coeficiente con respectos al valor de los precios
for (feature, coef) in zip(boston.feature_names, lr.coef_):
    print('{:>7}: {: 9.5f}'.format(feature, coef))

#funcion para observar mediante graficos las relaciones
def plot_feature(feature):
    f = (boston.feature_names == feature)
    plt.scatter(boston.data[:,f], boston.target, c='b', alpha=0.3)
    plt.plot(boston.data[:,f], boston.data[:,f]*lr.coef_[f] + lr.intercept_, 'k')
    plt.legend(['Predicted value', 'Actual value'])
    plt.xlabel(feature)
    plt.ylabel("Median value in $1000's")
    plt.show()
#llamada de la funcion
plot_feature('AGE')

#predecir el precio de una vivienda tras entrenarlo
predictions = lr.predict(boston.data)
f, ax = plt.subplots(1)
ax.hist(boston.target - predictions, bins=50, alpha=0.7)
ax.set_title('Histograma de residuales')
ax.text(0.95, 0.90, 'Media de residuales: {:.3e}'.format(np.mean(boston.target - predictions)),
        transform=ax.transAxes, verticalalignment='top', horizontalalignment='right')
plt.show()


import os
import time
import warnings
import argparse

from IPython import embed

import numpy

from matplotlib import pyplot, ticker, colors

from ..etc import source, efficiency, telescopes, spectrum, extract, aperture, detector
from ..etc.observe import Observation
from . import scriptbase
from .. import data_file

def get_wavelength_vector(start, end, logstep):
    """
    Get the wavelength vector
    """
    nwave = int((numpy.log10(end)-numpy.log10(start))/logstep + 1)
    return numpy.power(10., numpy.arange(nwave)*logstep + numpy.log10(start))

def get_spectrum(wave, mag, emline_db=None, redshift=0.0, resolution=3500):
    """
    """
    spec = spectrum.ABReferenceSpectrum(wave, resolution=resolution, log=True)
    g = efficiency.FilterResponse()
    spec.rescale_magnitude(mag, band=g)
    if emline_db is None:
        return spec
    spec = spectrum.EmissionLineSpectrum(wave, emline_db['flux'], emline_db['restwave'],
                                         emline_db['fwhm'], units=emline_db['fwhmu'],
                                         redshift=redshift, resolution=resolution, log=True,
                                         continuum=spec.flux)
    warnings.warn('Including emission lines, spectrum g-band magnitude changed '
                  'from {0} to {1}.'.format(mag, spec.magnitude(band=g)))
    return spec

class FOBOSETCGrid(scriptbase.ScriptBase):

    @classmethod
    def get_parser(cls, width=None):
        import argparse

        parser = super().get_parser(description='Grid sampling of FOBOS ETC', width=width)

        parser.add_argument('-w', '--wavelengths', default=[3100,10000,4e-5], nargs=3, type=float,
                            help='Wavelength grid: start wave, approx end wave, logarithmic step.')
        parser.add_argument('-m', '--mag', default=[21.,25.,0.5], nargs=3, type=float,
                            help='Object apparent AB magnitude; assumed spectrum has a constant AB '
                                'otherwise, it is assumed to be the total magnitude of the source.')
        parser.add_argument('-t', '--time', default=[300.,3600.,300.], nargs=3, type=float,
                            help='Exposure time (s)')
        parser.add_argument('-f', '--fwhm', default=0.65, type=float,
                            help='On-sky PSF FWHM (arcsec)')
        parser.add_argument('-a', '--airmass', default=1.0, type=float, help='Airmass')
        parser.add_argument('--snr_units', type=str, default='pixel',
                            help='The units for the S/N.  Options are pixel, angstrom, resolution.')

        return parser

    @staticmethod
    def main(args):

        t = time.perf_counter()

        # Constants:
        resolution = 3500.      # lambda/dlambda
        fiber_diameter = 0.8    # Arcsec
        rn = 2.                             # Detector readnoise (e-)
        dark = 0.0                          # Detector dark-current (e-/s)

        # Temporary numbers that assume a given spectrograph PSF and LSF.
        # Assume 3 pixels per spectral and spatial FWHM.
        spatial_fwhm = 3.0
        spectral_fwhm = 3.0

        mags = numpy.arange(args.mag[0], args.mag[1]+args.mag[2], args.mag[2])
        times = numpy.arange(args.time[0], args.time[1]+args.time[2], args.time[2])

        # Get source spectrum in 1e-17 erg/s/cm^2/angstrom. Currently, the
        # source spectrum is assumed to be
        #   - normalized by the total integral of the source flux
        #   - independent of position within the source
        wave = get_wavelength_vector(args.wavelengths[0], args.wavelengths[1], args.wavelengths[2])
        spec = get_spectrum(wave, mags[0], resolution=resolution)

        # Get the source distribution.  If the source is uniform, onsky is None.
        onsky = None

        # Get the sky spectrum
        sky_spectrum = spectrum.MaunakeaSkySpectrum()

        # Overplot the source and sky spectrum
    #    ax = spec.plot()
    #    ax = sky_spectrum.plot(ax=ax, show=True)

        # Get the atmospheric throughput
        atmospheric_throughput = efficiency.AtmosphericThroughput(airmass=args.airmass)

        # Set the telescope. Defines the aperture area and throughput
        # (nominally 3 aluminum reflections for Keck)
        telescope = telescopes.KeckTelescope()

        # Define the observing aperture; fiber diameter is in arcseconds,
        # center is 0,0 to put the fiber on the target center. "resolution"
        # sets the resolution of the fiber rendering; it has nothing to do
        # with spatial or spectral resolution of the instrument
        fiber = aperture.FiberAperture(0, 0, fiber_diameter, resolution=100)

        # Get the spectrograph throughput (circa June 2018; TODO: needs to
        # be updated). Includes fibers + foreoptics + FRD + spectrograph +
        # detector QE (not sure about ADC). Because this is the total
        # throughput, define a generic efficiency object.
        thru_file = str(data_file(filename='efficiency') / 'fobos_throughput.db')
        thru_db = numpy.genfromtxt(thru_file)
        spectrograph_throughput = efficiency.Efficiency(thru_db[:,1], wave=thru_db[:,0])

        # System efficiency combines the spectrograph and the telescope
        system_throughput = efficiency.SystemThroughput(wave=spec.wave,
                                                        spectrograph=spectrograph_throughput,
                                                        telescope=telescope.throughput)

        # Instantiate the detector; really just a container for the rn and
        # dark current for now. QE is included in fobos_throughput.db file,
        # so I set it to 1 here.
        det = detector.Detector(rn=rn, dark=dark, qe=1.0)

        # Extraction: makes simple assumptions about the detector PSF for
        # each fiber spectrum and mimics a "perfect" extraction, including
        # an assumption of no cross-talk between fibers. Ignore the
        # "spectral extraction".
        extraction = extract.Extraction(det, spatial_fwhm=spatial_fwhm,
                                        spatial_width=1.5*spatial_fwhm,
                                        spectral_fwhm=spectral_fwhm, spectral_width=spectral_fwhm)

        snr_label = 'S/N per {0}'.format('R element' if args.snr_units == 'resolution'
                                        else args.snr_units)

        # SNR
        g = efficiency.FilterResponse()
        r = efficiency.FilterResponse(band='r')
        snr_g = numpy.empty((mags.size, times.size), dtype=float)
        snr_r = numpy.empty((mags.size, times.size), dtype=float)
        for i in range(mags.size):
            spec.rescale_magnitude(mags[i], band=g)
            for j in range(times.size):
                print('{0}/{1} ; {2}/{3}'.format(i+1,mags.size,j+1,times.size), end='\r')
                # Perform the observation
                obs = Observation(telescope, sky_spectrum, fiber, times[j], det,
                                system_throughput=system_throughput,
                                atmospheric_throughput=atmospheric_throughput,
                                airmass=args.airmass, onsky_source_distribution=onsky,
                                source_spectrum=spec, extraction=extraction,
                                snr_units=args.snr_units)

                # Construct the S/N spectrum
                snr_spec = obs.snr(sky_sub=True)
                snr_g[i,j] = numpy.sum(g(snr_spec.wave)*snr_spec.flux)/numpy.sum(g(snr_spec.wave))
                snr_r[i,j] = numpy.sum(r(snr_spec.wave)*snr_spec.flux)/numpy.sum(r(snr_spec.wave))
        print('{0}/{1} ; {2}/{3}'.format(i+1,mags.size,j+1,times.size))

        extent = [args.time[0] - args.time[2]/2, args.time[1] + args.time[2]/2,
                args.mag[0] - args.mag[2]/2, args.mag[1] + args.mag[2]/2]

        w,h = pyplot.figaspect(1)
        fig = pyplot.figure(figsize=(1.5*w,1.5*h))
        ax = fig.add_axes([0.15, 0.2, 0.7, 0.7])
        img = ax.imshow(snr_g, origin='lower', interpolation='nearest', extent=extent,
                        aspect='auto', norm=colors.LogNorm(vmin=snr_g.min(), vmax=snr_g.max()))
        cax = fig.add_axes([0.86, 0.2, 0.02, 0.7])
        pyplot.colorbar(img, cax=cax)
        cax.text(4, 0.5, snr_label, ha='center', va='center', transform=cax.transAxes,
                rotation='vertical')
        ax.text(0.5, -0.08, 'Exposure Time [s]', ha='center', va='center', transform=ax.transAxes)
        ax.text(-0.12, 0.5, r'Surface Brightness [AB mag/arcsec$^2$]', ha='center', va='center',
                transform=ax.transAxes, rotation='vertical')
        ax.text(0.5, 1.03, r'$g$-band S/N', ha='center', va='center', transform=ax.transAxes,
                fontsize=12)
        pyplot.show()


# 출처 : https://www.acmicpc.net/problem/16853
a, b = map(int, input().split())

answer = 0
while(b > a):
    # 짝수이면 나누기 2
    if(b % 2 == 0):
        b = b//2
        answer += 1
    # 홀수인 경우 맨 끝이 1일때와 1이 아닐 때로 분기
    else:
        # 맨 끝이 1이 아니면 어떤 방법으로도 만들 수 없으므로 -1
        if(str(b)[-1] != '1'):
            answer = -1
            break
        # 맨 끝이 1이라면 1을 제거한다.
        else:
            b = int(str(b)[0:len(str(b))-1])
            answer += 1

# 연산을 다 마치고 나서 값이 다르면 만들 수 없는 것이다.
if(b != a):
    print(-1)
else:
    print(answer+1)


from django.urls import path
from . import views

urlpatterns = [
	path('', views.index, name = 'index'),
	path('scrape/', views.scrape, name = 'scrape_url'),
	path('temp/', views.scraper2, name=  'temp'),
	path('temp_detail', views.scraper2_detail, name = 'temp_detail')
]


general = dict(
    disableLogging = False,
    actionDataSource = 'actionData.csv',
    mediaRendererModelName = 'gmediarender',
    deviceSearchTimeout = 20,
    rfidLockIntervall = 6,
    logging_formatter = '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
)

app = dict(
    host = '0.0.0.0',
    port = 80,
    debug = False,
)

wifi = dict(
    wpa_conf_file = '/etc/wpa_supplicant/wpa_supplicant.conf',
    interface_file = '/etc/network/interfaces',
)

rfid = dict(
    sleepTime = 1,
)


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

import collections
import re

from . import _common as common
from ..base.candidate import CandidateFactory
from ..base.sentence import SentenceFactory
from ..base.mweoccur import MWEOccurrence
from ..base.word import Word
from .. import util

class TPCInfo(common.FiletypeInfo):
    r"""FiletypeInfo subclass for TaggedPlainCorpus format."""
    description = "One sentence per line with <mwepart>tags</mwepart>"
    filetype_ext = "TaggedPlainCorpus"

    comment_prefix = "#"
    escape_pairs = [("$", "${dollar}"), ("#", "${hash}"),
                    ("<", "${lt}"), (">", "${gt}"), (" ", "${space}"),
                    ("\n", "${newline}")]

    def operations(self):
        return common.FiletypeOperations(TPCChecker, TPCParser, TPCPrinter)

class TPCChecker(common.AbstractChecker):
    r"""Checks whether input is in TaggedPlainCorpus format."""
    def matches_header(self, strict):
        return not strict or "<mwepart" in self.fileobj.peek(1024)

class TPCParser(common.AbstractTxtParser):
    r"""Instances of this class parse the TaggedPlainCorpus format,
    calling the `handler` for each object that is parsed.
    """
    valid_categories = ["corpus"]
    RE_ENTRY = re.compile(
            "(?P<word>[^<> ]+)" \
            "|(?P<complex><mwepart +id=\"(?P<ids>[0-9,]*)\">" \
                    "(?P<c_word>[^<> ]+)</ *mwepart *>)")

    def __init__(self, encoding='utf-8'):
        super(TPCParser, self).__init__(encoding)
        self.candidate_factory = CandidateFactory()
        self.sentence_factory = SentenceFactory()
        self.category = "corpus"

    def _parse_line(self, line, info={}):
        sentence = self.sentence_factory.make()
        num2cand = collections.defaultdict(list)
        num2indexes = collections.defaultdict(list)

        for match in self.RE_ENTRY.finditer(line):
            word, complex, ids, c_word = match.groups()
            if word:
                sentence.append(Word(word))
            else:
                sentence.append(Word(c_word))
                for id in ids.split(","):
                    num2cand[int(id)].append(sentence[-1])
                    num2indexes[int(id)].append(len(sentence)-1)

        for num in sorted(num2cand.keys()):
            words = num2cand[ num ]
            c = self.candidate_factory.make(words, id_number=num)
            mweo = MWEOccurrence(sentence, c, num2indexes[num])
            sentence.mweoccurs.append(mweo)

        self.handler.handle_sentence(sentence, info)

class TPCPrinter(common.AbstractPrinter):
    """Instances can be used to print HTML format."""
    valid_categories = ["corpus"]

    def handle_sentence(self, sentence, info={}):
        """Print a simple readable string where the surface forms of the
        current sentence are concatenated and separated by a single space.

        @return A string with the surface form of the sentence,
        space-separated.
        """
        surface_list = [self.escape(w.surface) for w in sentence.word_list]
        mwetags_list = [[] for i in range(len(surface_list))]
        for mweoccur in sentence.mweoccurs:
            for i in mweoccur.indexes:
                mwetags_list[i].append( mweoccur.candidate.id_number)
        for (mwetag_i, mwetag) in enumerate(mwetags_list):
            if mwetag:
                mwetag = (unicode(index) for index in mwetag)
                surface_list[mwetag_i] = "<mwepart id=\"" + ",".join(mwetag) \
                              + "\">" + surface_list[mwetag_i] + "</mwepart>"
        line = " ".join(surface_list)
        self.add_string(line, "\n")


"""
Implement StrStr
Implement strStr().
 strstr - locate a substring ( needle ) in a string ( haystack ).
Try not to use standard library string functions for this question.
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack."""

#Using KMP Algorithm
def strStrKMP(A, B):
    def lpsTable(A):
        i, j, n = 1, 0, len(A)
        lps = [None]*n
        lps[0] = 0
        while i < n:
            if A[i] == A[j]:
                lps[i] = j+1
                i, j = i+1, j+1
            else:
                if j != 0:
                    j = lps[j-1]
                else:
                    lps[i] = 0
                    i += 1
        return lps

    i = 0
    target = 0
    lps = lpsTable(B)

    n, m = len(A), len(B)
    while i < n:
        if A[i] == B[target]:
            i, target = i+1, target+1

        if target == m:
            return i-m

        elif i < n and A[i]!=B[target]:
            if target != 0:
                target = lps[target-1]
            else:
                i += 1

    return -1

#Using Rolling Hash algorithm
def strStrRolling(A, B):
    if len(A) == 0 or len(B) == 0 or len(A) < len(B):
        return -1
    n, m = len(A), len(B)
    target = 0
    index = 0
    for i in B:
        temp = (37**index)
        target += ord(i)*temp
        target = target
        index += 1

    roll_hash = 0
    index = 0
    for i in range(m):
        temp = (37**index)
        roll_hash += ord(A[i])*temp
        roll_hash = roll_hash
        index += 1

    if roll_hash == target:
        return 0

    for i in range(1,n-m+1):
        roll_hash -= ord(A[i-1])
        roll_hash = roll_hash//37
        roll_hash += ord(A[m+i-1])*(37**(m-1))
        if roll_hash == target:
            return i

    return -1


from ansible.vars import VariableManager
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader

import copy
import functools
import importlib
import os
import paramiko
import pkgutil
import subprocess

class Group:

    def __init__(self, group_name, inventory):

        self._name = group_name

        self._inventory = inventory

        self._hosts = dict()

    def __getitem__(self, name):

        return self.get(name)

    def get(self, name):

        result = None

        host = self.get_host(name)

        if host != None:

            result = host

        else:

            var = self._inventory.get_group_vars(self._name)[name]

            if var != None:

                result = var

        return result

    def get_host(self, name):

        result = None

        if self._hosts.has_key(name):

            result = self._hosts[name]

        else:

            group_dict = self._inventory._inventory.get_group_dict()

            group = group_dict[self._name]

            if group != None:

                if name in group:

                    self._hosts[name] = self._inventory.get_host(name)

                    result = self._hosts[name]

        return result

class Host(object):

    _modules = None

    def __init__(self, host_name, inventory):

        self._name = host_name

        self._inventory = inventory

        self._ssh = None

        self._cd = None

        self._sudo = None

        self.load_modules()

    def load_modules(self):

        if Host._modules == None:

            Host._modules = dict()

            for module_name in [name for _, name, _ in pkgutil.iter_modules(['%s/modules' % os.path.dirname(__file__)])]:

                module = importlib.import_module('ntx.systest.modules.%s' % module_name)

                Host._modules[module_name] = module.hook

    def __getattr__(self, name):

        # TODO: look for module

        if Host._modules.has_key(name):

            p = functools.partial(Host._modules[name], self)

            return p

        else:

            return object.__getattribute__(self, name)

    def __getitem__(self, name):

        return self.get(name)

    def cd(self, path = '~/'):

        result = copy.copy(self)

        result.set_cd(path)

        return result

    def get(self, name):

        result = None

        if self._inventory.get_host_vars(self._name).has_key(name):

            result = self._inventory.get_host_vars(self._name)[name]

        return result

    def _get_connection(self):

        if self._ssh == None:

            ssh = paramiko.SSHClient()

            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            pkey = paramiko.RSAKey.from_private_key(open(self['ansible_ssh_private_key_file'], 'r'))

            ssh.connect(self['ansible_host'], username = self['ansible_user'], pkey = pkey)

            self._ssh = ssh

        return self._ssh

    def do(self, command):

        result = None

        if self._sudo != None:

            command = 'sudo -u %s %s' % (self._sudo, command)

        if self._cd != None:

            command = 'cd %s; %s' % (self._cd, command)

        if self['ansible_connection'] == 'local':

            result = self.do_local(command)

        else:

            result = self.do_remote(command)

        return result

    def do_local(self, command):

        p = subprocess.Popen(command, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)

        out, err = p.communicate()

        return out.strip().split('\n')

    def do_remote(self, command):

        ssh = paramiko.SSHClient()

        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        pkey = paramiko.RSAKey.from_private_key(open(self['ansible_ssh_private_key_file'], 'r'))

        ssh.connect(self['ansible_host'], username = self['ansible_user'], pkey = pkey)

        ins, out, err = ssh.exec_command(command, get_pty = True)

        result = out.readlines()[:]

        ssh.close()

        return [line.strip() for line in result]

    def set_cd(self, path = '~/'):

        self._cd = path

    def set_sudo(self, username = 'root'):

        self._sudo = username

    def sudo(self, username = 'root'):

        result = copy.copy(self)

        result.set_sudo(username)

        return result

class Inventory:

    def __init__(self, source):

        self._source = source

        self._loader = DataLoader()

        self._variables = VariableManager()

        self._inventory = AnsibleInventory(loader = self._loader, variable_manager = self._variables, host_list = self._source)

        self._groups = dict()

        self._hosts = dict()

    def __getitem__(self, name):

        return self.get(name)

    def get(self, name):

        result = None

        host = self.get_host(name)

        if host != None:

            result = host

        else:

            group = self.get_group(name)

            if group != None:

                result = group

            else:

                group_all = self._inventory.get_group('all')

                if group_all != None:

                    var = group_all.get_vars()[name]

                    if var != None:

                        result = var

        return result

    def get_group(self, group_name):

        result = None

        if self._groups.has_key(group_name):

            result = self._groups[group_name]

        elif self._inventory.get_group(group_name) != None:

            result = Group(group_name, self)

            self._groups[group_name] = result

        return result

    def get_group_vars(self, group_name):

        result = None

        group = self._inventory.get_group(group_name)

        if group != None:

            result = group.get_vars()

        return result

    def get_host(self, host_name):

        result = None

        if self._hosts.has_key(host_name):

            result = self._hosts[host_name]

        elif self._inventory.get_host(host_name) != None:

            result = Host(host_name, self)

            self._hosts[host_name] = result

        return result

    def get_host_vars(self, host_name):

        result = None

        host = self._inventory.get_host(host_name)

        if host != None:

            result = self._variables.get_vars(self._loader, host = host)

        return result

#------------------------------------------------------------------------------
# UNIT TESTING
#------------------------------------------------------------------------------

import unittest

class InvetoryTestCase(unittest.TestCase):

    def setUp(self):

        inventory_description = '''
localhost ansible_connection=local ansible_user=isilla ansible_host=localhost ansible_ssh_private_key_file=/home/isilla/.ssh/id_rsa

[testing_group]
localhost

[testing_group:vars]
foo=bar

[all:vars]
foo_all=bar_all
        '''

        f = open('/tmp/unit_test.inv', 'w')

        f.write(inventory_description)

        f.close()

        self.inventory = Inventory('/tmp/unit_test.inv')

    def test_01_loading(self):
        '''Loading the inventory
        '''

        self.assertNotEqual(None, self.inventory, 'Loading inventory')

    def test_02_inventory_hosts(self):
        '''Reading the hosts'''

        self.assertEqual('localhost', self.inventory.get('localhost')._name, 'Reading host: localhost')

        self.assertEqual('localhost', self.inventory['localhost']._name, 'Reading host: localhost [getitem]')

    def test_03_inventory_groups(self):
        '''Reading the groups'''

        self.assertEqual('testing_group', self.inventory.get('testing_group')._name, 'Reading group: testing_group')

        self.assertEqual('testing_group', self.inventory['testing_group']._name, 'Reading group: testing_group [getitem]')

    def test_04_inventory_variables(self):
        '''Reading the inventory variables'''

        self.assertEqual('bar_all', self.inventory.get('foo_all'), 'Reading an inventory-wide variable')

        self.assertEqual('bar_all', self.inventory['foo_all'], 'Reading an inventory-wide variable [getitem]')

    def test_05_group_hosts(self):
        '''Reading hosts from groups'''

        group = self.inventory.get_group('testing_group')

        host = group.get('localhost')

        self.assertEqual('localhost', host._name, 'Reading host from group')

        self.assertEqual('localhost', group['localhost']._name, 'Reading host from group [getitem]')

    def test_06_group_variables(self):
        '''Reading group variables'''

        group = self.inventory.get_group('testing_group')

        self.assertEqual('bar', group.get('foo'), 'Reading a group var')

        self.assertEqual('bar', group['foo'], 'Reading a group var [getitem]')

    def test_07_host_variables(self):
        '''Reading host variables'''

        host = self.inventory.get_host('localhost')

        self.assertEqual('bar_all', host.get('foo_all'), 'Reading a host variable')

        self.assertEqual('bar_all', host['foo_all'], 'Reading a host variable [getitem]')

    def test_08_host_modules_hook(self):
        '''Hooking modules'''

        host = self.inventory.get_host('localhost')

        file = host.file('/tmp/foo.txt')

        self.assertEqual('File [/tmp/foo.txt]', file.__repr__(), 'Hooking modules from Host')

    def test_09_host_remote_do(self):
        '''Running remote commands'''

        host = self.inventory.get_host('localhost')

        out = host.do('whoami')

        self.assertEqual('%s' % host['ansible_user'], out[0], 'Remotely running a command')

    def test_10_reading_remote_file(self):
        '''Reading remote files'''

        host = self.inventory.get_host('localhost')

        host.do('echo "One ring to rule them all" > /tmp/remote_file.txt')

        file_content = host.file('/tmp/remote_file.txt').tail()

        self.assertEqual('One ring to rule them all', file_content[0], 'Reading a remote file')

if __name__ == '__main__':

    unittest.main(verbosity=2)


from dados import produtos, pessoas, lista

nova_lista = filter(lambda x: x > 5, lista)
print(list(nova_lista))

lista_nova = [x for x in lista if x > 5]
print(list(lista_nova))

# produtos
nova_lista = filter(lambda p: p['preco'] > 35, produtos)

for produto in nova_lista:
    print(produto)

# ou

def filtrar(produto):
    if produto['preco'] >= 55:
        produto['e_caro'] = True
        return True
    else:
        return False

nova_lista = filter(filtrar, produtos)

for produto in nova_lista:
    print(produto)

# pessoas
def filtra(pessoa):
    if pessoa['idade'] < 18:
        return True
    else:
        return False

nova_lista = filter(filtra, pessoas)

for pessoa in nova_lista:
    print(pessoa)


import sys
from collections import deque
from itertools import combinations
sys.setrecursionlimit(10**5)

input = sys.stdin.readline
n = input().strip()
arr = [0 for i in range(10)]
for i in range(len(n)):
    if int(n[i]) == 6 or int(n[i]) == 9:
        if arr[6] >= arr[9]:
            arr[9]+=1
        else:
            arr[6]+=1
    else:
        arr[int(n[i])]+=1
print(max(arr))


#!/usr/bin/python

import rospkg
import glob
import sys
import yaml
from tf.transformations import *
import collections

from multi_robot_fusion.src.load_csv_data import *
from multi_robot_fusion.src.construct_poses import *

def pose_average(poses):
  positions = [H[:3,3] for H in poses]
  orientations = [quaternion_from_matrix(H) for H in poses]
  mean_ori = numpy.array(orientations[0])
  ori_count = 1.0
  for ori in orientations[1:]:
    ori = numpy.array(ori)
    if mean_ori.dot(ori) < 0.0:
      ori = -ori
    mean_ori = quaternion_slerp(mean_ori, ori, ori_count/(ori_count+1.0))
    ori_count += 1.0
  H = quaternion_matrix(mean_ori)
  H[:3,3] = numpy.array(positions).mean(0)
  return H

def fuse_poses(poses, parent, child, time_thresh=0.01):

  times = [p['time'] for p in poses]
  in_poses = numpy.array([p['pose'] for p in poses])

  fused_pose = []
  fused_time = []
  idxs = numpy.array([0] * len(times))
  lens = numpy.array([len(t) for t in times])

  while any(idxs < lens):
    curr_times = numpy.array([t[i] if i<l else numpy.nan for t,i,l in zip(times, idxs, lens)])
    min_time = numpy.nanmin(curr_times)

    fuse_idxs = (curr_times - min_time) < time_thresh

    f_ps = in_poses[fuse_idxs]
    p_is = idxs[fuse_idxs]
    fused_pose.append(pose_average([f_p[p_i] for f_p,p_i in zip(f_ps,p_is)]))
    fused_time.append(min_time)
    idxs[fuse_idxs] += 1

  return {
    'parent': parent,
    'child': child,
    'time': numpy.array(fused_time),
    'pose': fused_pose
  }

if __name__ == '__main__':
  p1_obs = load_poses(filter_str = 'tf-observer_exp-picket_1_obs_*',static_tf=None)
  p2_obs = load_poses(filter_str = 'tf-observer_exp-picket_2_obs_*',static_tf=None)

  p1_avg = fuse_poses(p1_obs, 'observer_exp', 'picket_1_obs_avg')
  p2_avg = fuse_poses(p2_obs, 'observer_exp', 'picket_2_obs_avg')

  poses_to_csv(**p1_avg)
  poses_to_csv(**p2_avg)


"""
File name: cache.py
Description: Home page API route

Change Log:
Release Date    Revision Date   Changes By      Description
------------    -------------   ----------      -----------
                July 2020       Sabarish AC     Initial
                August 2020     Ganapathy R     Code Updation & Refraction
"""
# Built in Modules
from flask import render_template, abort, session, flash, redirect, url_for

# Customized Modules
from . import home
import sys
sys.path.append('C:\\ctpt\\ctpt-backup\\resource_integrate')
from util import util

conf = util.get_conf()
const = util.excelConstants()

"""
Render to Home Page on / route
"""
@home.route('/home')
@home.route('/')
def homePage():
    if 'email' in session:
        email = session['email']
        return render_template(conf['templates']['home'], logged_in=session, is_home=True, title='Welcome to CTPT Shift Plan App')
    else:
        flash('You muste be logged in to use this app, please login!!', category='warning')
        return redirect(url_for('auth.user_login'))


from services.MeshNode import MeshNode
from services.NonAgent import NonAgent, Request

def test_NonAgent():
    na = NonAgent()
    na.bind()
    na.start()
    nb = NonAgent()
    nb.bind()
    nb.start()
    nc = NonAgent()
    nc.bind()
    nc.start()
    print("pn: ", nc.portNumber)
    p = nc.portNumber

    ssidReq = Request(function='ssid', args=[])
    fncsReq = Request(function='list_functions', args=[])

    ssidResponse = MeshNode.call(p, ssidReq)
    fncsResponse = MeshNode.call(p, fncsReq)
    dumbResponse = MeshNode.call(p, Request(function='is_coopai', args=[]))

    print("SSID query response: ", ssidResponse.response)
    print("fucntions query response: ", fncsResponse.response)
    print("dumbass query response: ", dumbResponse.response)

    del na
    del nb
    del nc

test_NonAgent()


import sys
read=sys.stdin.readline

N=int(read())
dp=[0]*(N+1)

for i in range(1,N+1):
    dp[i]=i         #dp=[0,1,2,3,4....N] 초기화
    for j in range(1, i):
        # 제곱수가 i보다 커지면 멈춤
        if j*j > i:
            break
        if dp[i] > dp[i-j*j] + 1:
            dp[i] = dp[i-j*j] + 1  #dp[4-2*2]+1 =1
print(dp[N])

동적 프로그래밍/1699_제곱수의 합.py


print("            APK TERBILANG           ")
print("====================================")
number=input("Masukkan Angka :")
number_mapping={
    "1": " satu ",
    "2": " dua ",
    "3": " tiga ",
    "4": " empat ",
    "5": " lima ",
    "6": " enam ",
    "7": " tujuh ",
    "8": " delapan ",
    "9": " sembilan ",
}

output=  ""

for n in number:
    terbilang =  number_mapping.get ( n , "invalid")
    output= output + terbilang + ""
print(output)


def print_formatted(number):
    width = len(format(number, 'b'))
    types = ['d', 'o', 'X', 'b']

    for i in range(1, number+1):
        values = ['{:>{width}{type}}'.format(i, width=width, type=type) for type in types]
        print(' '.join(values))

if __name__ == '__main__':
    n = int(input())
    print_formatted(n)


#https://leetcode.com/problems/max-area-of-island/
#time O(M * N * α(M * N)) space  O(M * N)
#union find
class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        uf = {}
        size = {}
        def find(x):
            uf.setdefault(x,x)
            size.setdefault(x,1)
            if x!=uf[x]:
                uf[x]=find(uf[x])
            return uf[x]
        def union(x,y):
            rootx = find(x)
            rooty = find(y)
            if rootx == rooty:
                return
            if size[rootx]<size[rooty]:
                size[rooty]+=size[rootx]
                uf[rootx]=uf[rooty]
            else:
                size[rootx]+=size[rooty]
                uf[rooty]=uf[rootx]
        ans = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]==1:
                    ans = max(ans,1)
                    if i>0 and grid[i-1][j]==1:
                        union((i-1,j),(i,j))
                    if j>0 and grid[i][j-1]==1:
                        union((i,j-1),(i,j))
        if size:
            ans = max(ans,max(size.values()))
        return ans

#time O(M * N) space  O(M * N)
#dfs
class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        self.ans = 0
        self.max = 0
        m = len(grid)
        n = len(grid[0])
        visited = set()
        def dfs(i,j):
            if i<0 or i>=m or j<0 or j>=n or (i,j) in visited or grid[i][j]==0:
                return
            visited.add((i,j))
            self.ans += 1
            dfs(i+1,j)
            dfs(i-1,j)
            dfs(i,j+1)
            dfs(i,j-1)

        for i in range(m):
            for j in range(n):
                if grid[i][j]==1 and (i,j) not in visited:
                    self.ans =0
                    dfs(i,j)
                    self.max=max(self.max,self.ans)

        return self.max


#!/Users/dmitrychernyshev/Projects/stepik_python/venv/bin/python3
import json
import sys
import requests

params = {
	'default': 'boring',
	'fragment': ''
	}

for line in sys.stdin:
	line = line.strip()
	url = "http://numbersapi.com/" + line + "/math"

	res = requests.get(url, params=params)
	print('Interesting' if res.text != 'boring' else 'Boring')


import os
from flask import Flask, jsonify, g
from flask_cors import CORS
from flask_login import LoginManager

import models
#import resources
from resources.dates import date
from resources.users import user
from resources.creates import create

DEBUG = True
PORT = 8000

# Initialize an instance of the Flask class.
app = Flask(__name__)

app.secret_key = "ladedaladeda" #secret key encodes session
login_manager = LoginManager()
login_manager.init_app(app) #sets up sessions

@login_manager.user_loader #loads user object when we access the session
#grab user by importing current_user from flask_login
def load_user(userid):
    try:
        return models.User.get(models.User.id == userid)
    except: models.DoesNotExist
    return None

@app.before_request
def before_request():
    """Connect to the database before each request."""
    g.db = models.DATABASE
    g.db.connect()

@app.after_request
def after_request(response):
    """Close the database connection after each request."""
    g.db.close()
    return response

# CORS(app, origins=['http://localhost:3000'], supports_credentials=True)
#supports_credentials = true means we allow cookies to be sent to the server
CORS(date, origins=['http://localhost:3000', 'https://react-find-a-date-idea.herokuapp.com'], supports_credentials=True)
app.register_blueprint(date,  url_prefix='/api/v1/dates')
CORS(user, origins=['http://localhost:3000', 'https://react-find-a-date-idea.herokuapp.com'], supports_credentials=True)
app.register_blueprint(user,  url_prefix='/api/v1/users')
CORS(create, origins=['http://localhost:3000', 'https://react-find-a-date-idea.herokuapp.com'], supports_credentials=True)
app.register_blueprint(create,  url_prefix='/api/v1/creates')

# Run the app
if 'ON_HEROKU' in os.environ:
    print('hitting')
    models.initialize()

if __name__ == '__main__':
    models.initialize()
    app.run(debug=DEBUG, port=PORT)


#
# @lc app=leetcode.cn id=1605 lang=python
#
# [1605] 给定行和列的和求可行矩阵
#

# @lc code=start
class Solution(object):
    def restoreMatrix(self, rowSum, colSum):
        """
        :type rowSum: List[int]
        :type colSum: List[int]
        :rtype: List[List[int]]
        """
        n,m = len(rowSum),len(colSum)
        matrix = [[0]*m for _ in range(n)]

# @lc code=end

rowSum = [5,7,10]
colSum = [8,6,8]

1605.给定行和列的和求可行矩阵.py


# def fibonacci(n):
#     if n <= 1:
#         return n
#     else:
#         return fibonacci(n-1) + fibonacci(n-2)

# print(fibonacci(10))

def fibo_linear(n):
    if n <= 1:
        return n, 0
    else:
        a, b = fibo_linear(n-1)
        return a + b, a

print(fibo_linear(10))


import os
import setuptools
import sys

from swiftclient.openstack.common import setup

name = 'python-swiftclient'

requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setuptools.setup(
    name=name,
    version=setup.get_post_version('swiftclient'),
    description='Client Library for OpenStack Object Storage API',
    long_description=read('README.rst'),
    url='https://github.com/openstack/python-swiftclient',
    license='Apache License (2.0)',
    author='OpenStack, LLC.',
    author_email='openstack-admins@lists.launchpad.net',
    packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
    cmdclass=setup.get_cmdclass(),
    install_requires=requires,
    dependency_links=depend_links,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Environment :: No Input/Output (Daemon)',
    ],
    test_suite='nose.collector',
    scripts=[
        'bin/swift',
    ],
)


from flask import Flask, render_template, redirect, url_for, session
from flask.ext.bootstrap import Bootstrap
from flask.ext.wtf import Form
from wtforms import StringField, \
    SelectField, RadioField, TextAreaField, SubmitField
from wtforms.validators import Required, Email
import logging
import sys

app = Flask(__name__)
app.config.from_pyfile('maprequests.cfg')
bootstrap = Bootstrap(app)
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.ERROR)

class MapForm(Form):
    name = StringField('Name:', validators=[Required()])
    email = StringField('Email:', validators=[Required(), Email()])
    pageSize = SelectField(
        'Page Size:',
        choices=[('std', '8.5x11'), ('lg', '11x17')],
        validators=[Required()])
    orientation = RadioField(
        'Page Orientation:',
        choices=[('portrait', 'Portrait'), ('landscape', 'Landscape')],
        validators=[Required()])
    submit = SubmitField('Next')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MapForm()
    if form.validate_on_submit():
        session['name'] = form.name.data
        session['email'] = form.email.data
        session['pageSize'] = form.pageSize.data
        session['orientation'] = form.orientation.data
        return redirect(url_for('index'))
    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run()


"""
Build DPT depth model
 - modified from https://github.com/isl-org/DPT
"""

import os
import torch
import cv2
import argparse
import util.io

from torchvision.transforms import Compose

from dpt.models import DPTDepthModel
from dpt.transforms import Resize, NormalizeImage, PrepareForNet

class DepthModel(object):
    """
    Build DPT network and compute depth maps
    """

    def __init__(self, model_type="dpt_hybrid", optimize=True):
        """
        Build MonoDepthNN to compute depth maps.

        Arguments:
            model_path (str): path to saved model
        """
        default_models = {
            "dpt_large": "weights/dpt_large-midas-2f21e586.pt",
            "dpt_hybrid": "weights/dpt_hybrid-midas-501f0c75.pt",
            "dpt_hybrid_kitti": "weights/dpt_hybrid_kitti-cb926ef4.pt",
        }
        model_path = default_models[model_type]
        self.model_type = model_type
        self.optimize = optimize

        # select device
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        print("device: ", self.device)

        # load network
        if model_type == "dpt_large":  # DPT-Large
            net_w = net_h = 384
            model = DPTDepthModel(
                path=model_path,
                backbone="vitl16_384",
                non_negative=True,
                enable_attention_hooks=False,
            )
            normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])

        elif model_type == "dpt_hybrid":  # DPT-Hybrid
            net_w = net_h = 384
            model = DPTDepthModel(
                path=model_path,
                backbone="vitb_rn50_384",
                non_negative=True,
                enable_attention_hooks=False,
            )
            normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])

        elif model_type == "dpt_hybrid_kitti":
            net_w = 1216
            net_h = 352

            model = DPTDepthModel(
                path=model_path,
                scale=0.00006016,
                shift=0.00579,
                invert=True,
                backbone="vitb_rn50_384",
                non_negative=True,
                enable_attention_hooks=False,
            )

            normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])

        else:
            assert (
                False
            ), f"model_type '{model_type}' not implemented, use: --model_type [dpt_large|dpt_hybrid|dpt_hybrid_kitti|dpt_hybrid_nyu|midas_v21]"

        self.transform = Compose(
            [
                Resize(
                    net_w,
                    net_h,
                    resize_target=None,
                    keep_aspect_ratio=True,
                    ensure_multiple_of=32,
                    resize_method="minimal",
                    image_interpolation_method=cv2.INTER_CUBIC,
                ),
                normalization,
                PrepareForNet(),
            ]
        )

        model.eval()

        if optimize and self.device == torch.device("cuda"):
            model = model.to(memory_format=torch.channels_last)
            model = model.half()

        self.model = model.to(self.device)

    @torch.no_grad()
    def compute_depth(self, img, kitti_crop=False):
        """
        Computes depth map

        Arguments:
            img (array): image (0-255)
        """

        if img.ndim == 2:
            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0

        if kitti_crop is True:
            height, width, _ = img.shape
            top = height - 352
            left = (width - 1216) // 2
            img = img[top : top + 352, left : left + 1216, :]

        img_input = self.transform({"image": img})["image"]

        # with torch.no_grad():
        sample = torch.from_numpy(img_input).to(self.device).unsqueeze(0)

        if self.optimize and self.device == torch.device("cuda"):
            sample = sample.to(memory_format=torch.channels_last)
            sample = sample.half()

        prediction = self.model.forward(sample)
        prediction = (
            torch.nn.functional.interpolate(
                prediction.unsqueeze(1),
                size=img.shape[:2],
                mode="bicubic",
                align_corners=False,
            )
            .squeeze()
            .cpu()
            .numpy()
        )

        # if self.model_type == "dpt_hybrid_kitti":
        #     prediction *= 256

        return prediction

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-m", "--model_weights", default=None, help="path to model weights"
    )

    parser.add_argument(
        "-t",
        "--model_type",
        default="dpt_hybrid",
        help="model type [dpt_large|dpt_hybrid|midas_v21]",
    )

    parser.add_argument("--optimize", dest="optimize", action="store_true")
    parser.set_defaults(optimize=True)

    args = parser.parse_args()

    # default_models = {
    #     "midas_v21": "weights/midas_v21-f6b98070.pt",
    #     "dpt_large": "weights/dpt_large-midas-2f21e586.pt",
    #     "dpt_hybrid": "weights/dpt_hybrid-midas-501f0c75.pt",
    #     "dpt_hybrid_kitti": "weights/dpt_hybrid_kitti-cb926ef4.pt",
    #     "dpt_hybrid_nyu": "weights/dpt_hybrid_nyu-2ce69ec7.pt",
    # }
    #
    # if args.model_weights is None:
    #     args.model_weights = default_models[args.model_type]

    # set torch options
    torch.backends.cudnn.enabled = True
    torch.backends.cudnn.benchmark = True

    # build model
    model = DepthModel(
        args.model_type,
        args.optimize,
    )
    # print(model)

    # read img
    img_path = r"dataset\sequences_jpg\00\image_0\000000.jpg"
    img = cv2.imread(img_path)

    # compute depth
    depth = model.compute_depth(img, kitti_crop=False)

    filename = os.path.join(
        "temp", os.path.splitext(os.path.basename(img_path))[0]
    )
    util.io.write_depth(filename.replace(".jpg", "_depth.jpg"), depth, bits=2, absolute_depth=True)


"""ag.Space sanitizer for certain hyperparameters."""
import warnings

import numpy as np
from autogluon.core import Categorical, Int

def sanitize_batch_size(batch_size, min_value=1, max_value=np.inf):
    if isinstance(batch_size, Categorical):
        valid_bs = []
        bs_values = batch_size.data
        for bs_value in bs_values:
            if isinstance(bs_value, int) and min_value < bs_value < max_value:
                valid_bs.append(bs_value)
        if valid_bs != bs_values:
            warnings.warn(
                f'Pruning batch size from {batch_size} to {valid_bs} due to memory limit.'
            )
        if len(valid_bs) == 1:
            new_bs = valid_bs[0]
        else:
            new_bs = Categorical(*valid_bs)
    elif isinstance(batch_size, Int):
        lower = batch_size.lower
        upper = batch_size.upper
        if not isinstance(lower, int) or not isinstance(upper, int):
            raise TypeError(
                f'Invalid lower {lower} or upper {upper} bound for Int space')
        lower = max(lower, min_value)
        upper = min(upper, max_value)
        new_bs = Int(lower=lower, upper=upper)
        if lower != batch_size.lower or upper != batch_size.higher:
            warnings.warn(
                f'Adjusting batch size range from {batch_size} to {new_bs} due to memory limit.'
            )
    elif isinstance(batch_size, int):
        new_bs = max(min(batch_size, max_value), min_value)
        if new_bs != batch_size:
            warnings.warn(
                f'Adjusting batch size from {batch_size} to {new_bs} due to memory limit.'
            )
    else:
        raise TypeError(
            f'Expecting batch size to be (Categorical/Int/int), given {type(batch_size)}.'
        )
    return new_bs