import numpy as np
import cv2
from scipy.misc import imresize
from imageio import imread
from tensorflow.keras.preprocessing import image
from keras.applications import imagenet_utils
import os
def get_bounding_box_coordinates(projection):
    combined_channels = np.sum(projection[0], axis=2)

    arg_positions = np.argwhere(combined_channels)
    (xstart, ystart), (xstop, ystop) = arg_positions.min(0), arg_positions.max(0)

    return (ystart, ystop, xstart, xstop)

def draw_bounding_box_cv2(image, bounding_boxes):
    count = 0
    for xstart,xstop,ystart,ystop in bounding_boxes:
        count += 1
        cv2.rectangle(image, (xstart,ystart), (xstop,ystop), (255, 0, 0), 1 )
        cv2.putText(image, "b%d"%(count), (xstart+10,ystart+10), 1, 1, (255, 0, 0), 1)
    return image

def get_strongest_filter(activation_img):

    # Make sure that dimensions 2 and 3 are spacial (Image is square)
    assert activation_img.shape[1] == activation_img.shape[2], "Index ordering incorrect"

    # Find maximum activation for each filter for a given image
    activation_img = np.nanmax(activation_img, axis=2)
    activation_img = np.nanmax(activation_img, axis=1)

    # Remove batch size dimension
    assert activation_img.shape[0] == 1
    activation_img = activation_img.sum(0)

    # Make activations 1-based indexing
    activation_img = np.insert(activation_img, 0, 0.0)

    #  activation_image is now a vector of length equal to number of filters (plus one for one-based indexing)
    #  each entry corresponds to the maximum/summed activation of each filter for a given image

    return activation_img.argmax()

def get_strongest_filters(activation_img, N=2):

    # Make sure that dimensions 2 and 3 are spacial (Image is square)
    assert activation_img.shape[1] == activation_img.shape[2], "Index ordering incorrect"

    # Find maximum activation for each filter for a given image
    # Find maximum activation for each filter for a given image
    activation_img = np.nanmax(activation_img, axis=2)
    activation_img = np.nanmax(activation_img, axis=1)

    # Remove batch size dimension
    assert activation_img.shape[0] == 1
    activation_img = activation_img.sum(0)

    # Make activations 1-based indexing
    activation_img = np.insert(activation_img, 0, 0.0)

    #  activation_image is now a vector of length equal to number of filters (plus one for one-based indexing)
    #  each entry corresponds to the maximum/summed activation of each filter for a given image

    return activation_img.argsort()[-N:][::-1]

def preprocess_image_batch(image_paths, img_size=(256, 256), crop_size=(224, 224), color_mode="rgb", out=None):
    """
    Resize, crop and normalize colors of images
    to make them suitable for alexnet_model (if default parameter values are chosen)

    This function is also from
    https://github.com/heuritech/convnets-keras/blob/master/convnetskeras/convnets.py
    with only some minor changes
    """

    # Make function callable with single image instead of list
    if type(image_paths) is str:
        image_paths = [image_paths]

    img_list = []
    for im_path in image_paths:
        img = imread(im_path, mode='RGB')
        img = imresize(img, img_size)

        img = img.astype('float32')
        # Normalize the colors (in RGB space) with the empirical means on the training set
        img[:, :, 0] -= 123.68
        img[:, :, 1] -= 116.779
        img[:, :, 2] -= 103.939
        # We permute the colors to get them in the BGR order
        if color_mode == "bgr":
            img[:, :, [0, 1, 2]] = img[:, :, [2, 1, 0]]
        img = img.transpose((2, 0, 1))

        if crop_size:
            img = img[:, (img_size[0] - crop_size[0]) // 2:(img_size[0] + crop_size[0]) // 2
            , (img_size[1] - crop_size[1]) // 2:(img_size[1] + crop_size[1]) // 2]

        img_list.append(img)

    try:
        img_batch = np.stack(img_list, axis=0)
    except:
        raise ValueError('when img_size and crop_size are None, images'
                         ' in image_paths must have the same shapes.')

    if out is not None and hasattr(out, 'append'):
        out.append(img_batch)
    else:
        return img_batch

def grey_square(img, x, y, radius = 10):

    h = img.shape[1]
    w = img.shape[2]
    assert radius <= x < h - radius
    assert radius <= y < w - radius
    #square size = 2*radius + 1
    img[:, x-radius:x+radius, y-radius:y+radius, :] = 0
    return img

def set_zero_except_maximum(filter, x):
    assert filter >= 1
    # Set other layers to zero
    new_array = np.zeros_like(x)
    new_array[0, :, :, filter - 1] = x[0, :, :, filter - 1]
    # Set other activations in same layer to zero
    max_index_flat = np.nanargmax(new_array)
    max_index = np.unravel_index(max_index_flat, new_array.shape)
    out = np.zeros_like(new_array)
    out[max_index] = new_array[max_index]
    return out

def get_path_from_id(img_id):
    '''
    used for imagenet data
    :param img_id:
    :return:
    '''
    img_id_str = str(img_id)
    while len(img_id_str) < 5:
        img_id_str = '0' + img_id_str
    folder = 'D:\data\imagenet-data\ILSVRC2012_img_val\\'
    file = 'ILSVRC2012_val_000' + img_id_str + '.JPEG'
    path = folder + file
    return path

def load_image(img_path):
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = imagenet_utils.preprocess_input(x)
    return x

def deprocess_image(x, format = 'cl'):
    '''
    Same normalization as in:
    https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py
    '''
    if np.ndim(x) > 3:
        x = np.squeeze(x)
    # normalize tensor: center on 0., ensure std is 0.1
    x -= x.mean()
    x /= (x.std() + 1e-5)
    x *= 0.1

    # clip to [0, 1]
    x += 0.5
    x = np.clip(x, 0, 1)

    # convert to RGB array
    x *= 255
    if format == 'cf':
        x = x.transpose((1, 2, 0))
    x = np.clip(x, 0, 255).astype('uint8')
    return x

def to_small_pitch(path, pitch_size=(50,50), input_shape=(224,224,3)):
    img = image.load_img(path, target_size = pitch_size)
    x = image.img_to_array(img)
    out = np.zeros(input_shape)
    out[50:50+pitch_size[0],50:50+pitch_size[1],:] = x
    fname = os.path.basename(path)
    image.save_img("small_pitch_{}".format(fname), out)

if __name__ == '__main__':
    to_small_pitch('D:\data\imagenet-data\ILSVRC2012_img_val\ILSVRC2012_val_00000003.JPEG',pitch_size=(100,100))


"""

1) Imprimir a quantidade de números pares entre dois números solicitados para o usuário.

"""

comeco = int(input("Digite o valor do inicio do intervalo: "))
final = int(input("Digite o valor do final do intervalo: "))

quantidadePares = 0;
while comeco <= final:
    if comeco % 2 == 0:
        quantidadePares+=1
    comeco+=1

print("A quantidade de números pares neste intervalo é", quantidadePares)

Gizelle/Modulo3/Modulo3dia3/Exercicio 1 - M3 - A3.py


# needed to see solution

import sys

def re_spaced(document, dictionary):
    memo = [None] * len(document)
    result = re_space(document, dictionary, 0, memo)
    return result.parsed

def re_space(document, dictionary, start, memo):
    if start == len(document):
        return ResultParse("", 0)
    elif memo[start] is not None:
        return memo[start]

    best_invalid = sys.float_info.max
    best_parse = None
    current_parse = ""
    for i in range(start, len(document)):
        current_parse += document[i]
        invalid = 0 if current_parse in dictionary else i + 1 - start
        if invalid < best_invalid:
            remain_re_spaced = re_space(document, dictionary, i + 1, memo)
            new_invalid = invalid + remain_re_spaced.invalid
            if new_invalid < best_invalid:
                best_parse = current_parse + " " + remain_re_spaced.parsed
                best_invalid = new_invalid

    memo[start] = ResultParse(best_parse, best_invalid)
    return memo[start]

class ResultParse:
    def __init__(self, parsed, invalid):
        self.parsed = parsed
        self.invalid = invalid

dictionary = {"looked", "just", "like", "her", "brother", "i", "in", "an", "island", "is", "land"}
document = "jesslookedjustliketimherbrotherinanisland"

result = re_spaced(document, dictionary)
print(result)


#******************************************************************************
#Interfaz gráfica para gestionar las películas guardadas por Trailers.py
#Un doble click en la película abre el link asociado
#El botón > permite asociar una fecha al nombre de una película
#@angalaagl
#https://github.com/aglpy
#https://anaconda.org/angala
#******************************************************************************
import glob
import webbrowser
import shutil
import os

from PySide2 import *
from PySide2.QtWidgets import *

from mod.func import *

class TrailersReader(QMainWindow):
	def __init__(self):
		QMainWindow.__init__(self)
		#-----------------------------------------------------------------------------------------------------------
		self.setWindowTitle("Trailers Reader")
		self.setFixedSize(873, 370)
		self.setWindowIcon(QtGui.QIcon("./mod/icon.ico"))
		#********************************************************************************************
		self.list_dias = QListWidget(self)
		self.list_pelis = QListWidget(self)
		self.borrar_dia = QPushButton(self, text="Borrar!")
		self.dia_visto = QPushButton(self, text="Vista")
		self.peli_arriba = QPushButton(self, text="▲")
		self.peli_abajo = QPushButton(self, text="▼")
		self.borrar_peli = QPushButton(self, text="Borrar!")
		self.peli_pendiente = QPushButton(self, text="Pendiente")
		self.calendario = QCalendarWidget(self)
		self.poner_fecha = QPushButton(self, text=">")
		#********************************************************************************************
		self.list_dias.resize(418,290)
		self.list_dias.move(12,42)
		self.list_pelis.resize(418,290)
		self.list_pelis.move(436,42)
		self.borrar_dia.resize(87, 21)
		self.borrar_dia.move(171, 338)
		self.dia_visto.resize(87, 21)
		self.dia_visto.move(343, 338)
		self.peli_arriba.resize(87, 21)
		self.peli_arriba.move(495, 338)
		self.peli_abajo.resize(87, 21)
		self.peli_abajo.move(588, 338)
		self.borrar_peli.resize(87, 21)
		self.borrar_peli.move(681, 338)
		self.peli_pendiente.resize(87, 21)
		self.peli_pendiente.move(774, 338)
		self.calendario.resize(250, 200)
		self.calendario.move(600, 29)
		self.poner_fecha.resize(25, 21)
		self.poner_fecha.move(825, 8)
		#-----------------------------------------------------------------------------------------------------------
		self.list_dias.itemSelectionChanged.connect(self.ev_list_dias_select)
		self.list_pelis.itemDoubleClicked.connect(self.ev_list_pelis_dclick)
		self.borrar_dia.clicked.connect(self.ev_borrar_dia)
		self.dia_visto.clicked.connect(self.ev_dia_visto)
		self.peli_arriba.clicked.connect(self.ev_peli_arriba)
		self.peli_abajo.clicked.connect(self.ev_peli_abajo)
		self.borrar_peli.clicked.connect(self.ev_borrar_peli)
		self.peli_pendiente.clicked.connect(self.ev_peli_pendiente)
		self.calendario.selectionChanged.connect(self.ev_calendario)
		self.poner_fecha.clicked.connect(self.ev_poner_fecha)
		#-----------------------------------------------------------------------------------------------------------
		self.links = []
		self.nombres = []
		self.dia_actual = []
		self.calendario.hide()
		self.iscalendarioshow = False
		for arch in glob.glob("./Trailers/*.txt"):
			self.list_dias.addItem(arch.split("\\")[-1][:-4])
		#-----------------------------------------------------------------------------------------------------------
	def ev_list_dias_select(self):
		self.list_pelis.clear()
		pelis = open(f"./Trailers/{self.list_dias.currentItem().text()}.txt", encoding="utf-8").readlines()
		pelis = [pelis[i].strip() for i in range(len(pelis))]
		self.list_pelis.addItems(pelis[::3])
		self.links = pelis[1::3]
		self.nombres = pelis[::3]
		self.dia_actual = self.list_dias.currentItem().text()

	def ev_list_pelis_dclick(self):
		webbrowser.open(self.links[self.list_pelis.currentRow()])

	def ev_borrar_dia(self):
		os.remove(f"./Trailers/{self.list_dias.currentItem().text()}.txt")
		self.list_dias.takeItem(self.list_dias.currentRow())

	def ev_dia_visto(self):
		shutil.move(f"./Trailers/{self.list_dias.currentItem().text()}.txt",
					f"./Trailers/vistas/{self.list_dias.currentItem().text()}.txt")
		self.list_dias.takeItem(self.list_dias.currentRow())

	def ev_peli_arriba(self):
		i = self.list_pelis.currentRow()
		self.nombres[i], self.nombres[i-1] = self.nombres[i-1], self.nombres[i]
		self.links[i], self.links[i-1] = self.links[i-1], self.links[i]
		self.list_pelis.insertItem(i-1, self.list_pelis.item(i).text())
		self.list_pelis.setCurrentRow(i-1)
		self.list_pelis.takeItem(i+1)
		escribir_archivo(self.nombres, self.links, self.dia_actual)

	def ev_peli_abajo(self):
		i = self.list_pelis.currentRow()
		self.nombres[i], self.nombres[i+1] = self.nombres[i+1], self.nombres[i]
		self.links[i], self.links[i+1] = self.links[i+1], self.links[i]
		self.list_pelis.insertItem(i+2, self.list_pelis.item(i).text())
		self.list_pelis.setCurrentRow(i+2)
		self.list_pelis.takeItem(i)
		escribir_archivo(self.nombres, self.links, self.dia_actual)

	def ev_borrar_peli(self):
		self.nombres.pop(self.list_pelis.currentRow())
		self.links.pop(self.list_pelis.currentRow())
		escribir_archivo(self.nombres, self.links, self.dia_actual)
		self.list_pelis.takeItem(self.list_pelis.currentRow())

	def ev_peli_pendiente(self):
		with open("./Trailers/000-00-0.txt", "a", encoding="utf-8") as arch:
			arch.write("\n"+self.list_pelis.currentItem().text()+"\n")
			arch.write("\t"+self.links[self.list_pelis.currentRow()]+"\n")

	def ev_calendario(self):
		fecha = self.calendario.selectedDate().toString("dd-MM-yyyy")
		i = self.list_pelis.currentRow()
		self.nombres[i] = self.nombres[i].strip() + "-" + fecha
		escribir_archivo(self.nombres, self.links, self.dia_actual)
		self.list_pelis.insertItem(i+1, self.nombres[i])
		self.list_pelis.takeItem(i)
		self.calendario.hide()
		self.iscalendarioshow = False

	def ev_poner_fecha(self):
		if self.iscalendarioshow:
			self.calendario.hide()
		else:
			self.calendario.show()
		self.iscalendarioshow = not self.iscalendarioshow

if __name__ == "__main__":
	app = QtWidgets.QApplication()

	widget = TrailersReader()
	widget.show()

	app.exec_()


#!/usr/bin/env python3

import json

def sum_numbers(data, ignore_red=False):
    if isinstance(data, list):
        total = 0
        for e in data:
            total += sum_numbers(e, ignore_red)
        return total
    elif isinstance(data, str):
        return 0
    elif isinstance(data, int):
        return data
    elif isinstance(data, dict):
        total = 0
        for key in data:
            if ignore_red and data[key] == 'red':
                return 0
            total += sum_numbers(key, ignore_red)
            total += sum_numbers(data[key], ignore_red)
        return total
    else:
        print("Unknown type", type(data))
    return 0

with open('input.txt', 'r') as f:
    data = json.load(f)

print(sum_numbers(data))
print(sum_numbers(data, True))


from re import M
from pyrailbaron.map.svg import MapSvg, transform_lcc, transform_dxf
from pyrailbaron.map.datamodel import Map, Coordinate
from pyrailbaron.map.states import get_border_data

from pathlib import Path
from typing import List

ROOT_DIR = (Path(__file__) / '../../..').resolve()
border_data = get_border_data(ROOT_DIR / 'data')

BORDERS_TO_DRAW = [
    [["MINNESOTA",0,[175,0]],
     ["M",[49,-98]],
     ["M",[49,-99]],
     ["M",[49,-100]],
     ["M",[49,-101]],
     ["M",[49,-102]],
     ["M",[40.5,-102]],
     ["M",[40.5,-108]],
     ["M",[37,-108]],
     ["COLORADO",0,[65,45]],
     ["OKLAHOMA",0,[200,33]],
     ["ARKANSAS",0,[0,8]],
     ["M",[36.5,-92.5]],
     ["M",[40.6,-92.5]],
     ["IOWA",0,[124,25]],
     ["WISCONSIN",0,[265,-1]]],
    [["M",[40.5,-108]],
    ["M",[40.5,-109]],
    ["M",[40.5,-110]],
    ["M",[40.5,-111]],
    ["M",[40.5,-112]],
     ["M",[40.5,-113]],
     ["M",[40.5,-114]],
    ["NEVADA",0,[12,0]],
    ["NEVADA",0,[-1,173]],
    ["CALIFORNIA",0,[15,0]],
    ["CALIFORNIA",0,[-1,158]],
    ["ARIZONA",0,[154,113]],
    ["NEW MEXICO",0,[65,52]],
    ["TEXAS",0,[700,606]],
    ["OKLAHOMA",0,[196,200]],
    ["COLORADO",0,[45,65]],
    ["M",[37,-108]]],
   [["TEXAS",0,[606,172]],
    ["LOUISIANA",0,[470,100]],
    ["MISSISSIPPI",0,[70,40]],
            ["M", [32.97, -88.47]],
        ["M", [32.97, -85.50]],
        ["KENTUCKY", 0, [263,150]],
        ["MISSOURI",0,[105,173]],
        ["OKLAHOMA",0,[33,196]]]
]

with (ROOT_DIR/'output/map.json').open('rt') as map_json:
    map: Map = Map.from_json(map_json.read())
(ROOT_DIR / 'output/border_test.svg').unlink(missing_ok=True)
svg = MapSvg(ROOT_DIR / 'output/border_test.svg')
svg.transforms = [transform_lcc, map.map_transform, transform_dxf]

colors = ['black', 'red', 'blue']
l = svg.layer('main')
for row_idx, rows in enumerate(BORDERS_TO_DRAW):
    pts: List[Coordinate] = []
    for i, row in enumerate(rows):
        if row[0] == 'M':
            pts.append(row[1])
            print(f'  Added point {pts[-1]}')
        else:
            state, border_idx, range = row
            border = border_data[state][border_idx]
            print(f'BORDER {state} #{border_idx} = {len(border)} points')
            segment = None
            if range == 'all':
                segment = border
            elif isinstance(range, list):
                start, end = range
                do_reverse = False
                if (end >= 0 and start > end) or start < 0:
                    start, end = end, start
                    do_reverse = True
                if end == -1:
                    segment = border[start:]
                else:
                    segment = border[start:(end + 1)]
            if segment:
                if do_reverse:
                    segment = segment.copy()
                    segment.reverse()
                if len(pts) == 0:
                    l.circle(segment[0], 2, fill='black')
                    l.text('start', segment[0])
                pts += segment
                l.circle(pts[-1], 2, fill='black')
                l.text(str(i), pts[-1])
                print(f'  Added segment from {segment[0]} to {segment[-1]}')
    pts.append(pts[0])
    l.path(pts, stroke=colors[row_idx % 3], stroke_width=0.5, fill='none')

svg.save()


#a1,b1,c1 = str(input("Please enter 3 words separated by a comma and the programm will print the first letter of each word: "))

# for i in a1,b1,c1:
#    print(course[0])

#word1=input("Enter first word")
#word2=input("Enter second word")
#word3=input("Enter third word")

# print(word1[0])
# print(word2[0])
# print(word3[0])

words = input("Enter three words: ")

for word in words.split():
    print(word[0])


from fastai.vision.widgets import *
from fastai.vision.all import *
from pathlib import Path
import PIL
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import color

file_name='style.pkl'
learn_inference = load_learner(Path()/file_name)

#defining wallpaper class for testing
class Wallpaper():
    def __init__(self, id, color, style):
        #path to wallpaper
        self.id = id
        #color of wallpaper
        self.color = color
        #style of wallpaper
        self.style = style

categories = ['texture', 'geometric', 'stripe', 'nature']

#sample list of wallpapers
wallpapers = [Wallpaper("26", "green", "texture"), Wallpaper("24", "darkblue", "stripe"), Wallpaper("30", "gray", "texture"), Wallpaper("7", "darkblue", "geometric"), Wallpaper("31", "darkblue", "nature"), Wallpaper("22", "gray", "nature")]

def give_recommendation(image_path):
    #loading image
    location = image_path
    image = open(location, 'rb')

    #classifying style of image
    pred, pred_idx, probs = learn_inference.predict(PILImage.create(image))
    style = pred

    #classifying color of image
    image_color = color.compare(image_path)

    matches = []

    #checking if there are wallpapers with the same color and style
    for wallpaper in wallpapers:
        if wallpaper.color == image_color and wallpaper.style == style:
            matches.append(wallpaper)
        if len(matches) == 6:
            return matches

    #if there are not enough wallpapers with the same color and style, return wallpapers with the same style
    if len(matches) < 6:
        for wallpaper in wallpapers:
            if wallpaper.style == style:
                matches.append(wallpaper)
            if len(matches) == 6:
                return matches

    return matches

#test
print(give_recommendation("/Users/Leah/boho/images/test/1.jpg"))


from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, render

from .models import News, Tag

def page_list(set, request):
    paginator = Paginator(set, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return page_obj

# Главная страница
def index(request):
    post_list = News.objects.all()
    page_obj = page_list(post_list, request)
    template = 'news/index.html'
    context = {
        'page_obj': page_obj,
    }
    return render(request, template, context)

# Страница со списком новостей по тегу
def news_tag(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    news = News.objects.filter(tag=tag)
    page_obj = page_list(news, request)
    template = 'news/news_tag.html'
    context = {
        'page_obj': page_obj,
        'tag': tag,
    }
    return render(request, template, context)

def news_detail(request, pk):
    new = get_object_or_404(News, pk=pk)
    context = {
        'new': new,
    }
    return render(request, 'news/news_detail.html', context)


import os

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, pathpatch_2d_to_3d
import seaborn as sns
from scipy import spatial

from utils import update_matplotlib_rc_parameters
from utils import sph2cart
from utils import sph_normals

def main():
	# averaging surface configuration
	edge_length = 0.02  # in m
	target_area_origin = (-edge_length/2, -edge_length/2)
	N = 11  # number of grid points

	# control evaluation plane coordinates
	x = np.linspace(-edge_length/2, edge_length/2, N)
	y = 0
	z = np.linspace(-edge_length/2, edge_length/2, N)
	Xt, Zt = np.meshgrid(x, z)
	x_pln = Xt.ravel()
	z_pln = Zt.ravel()

	# spherical averaging surface coordinates
	r = 0.05  # in m
	alpha = 2 * np.arcsin(edge_length/2/r)  # angle from secant
	theta = np.linspace(np.pi/2-alpha/2, np.pi/2+alpha/2, N)
	phi = np.linspace(np.pi-alpha/2, np.pi+alpha/2, N)
	Theta, Phi = np.meshgrid(theta, phi)
	y_sph, x_sph, z_sph = sph2cart(r, Theta.ravel(), Phi.ravel())
	y_sph -= y_sph.min() + y_sph.ptp() / 2
	ny_sph, nx_sph, nz_sph = sph_normals(r, Theta.ravel(), Phi.ravel())

	# visualize
	update_matplotlib_rc_parameters(is_3d=True)
	cs = sns.color_palette('rocket', 2)
	fig = plt.figure()
	ax = plt.axes(projection ='3d')
	plane = Rectangle(target_area_origin,
					  width=edge_length, height=edge_length,
					  ec=cs[0], fc=cs[1], alpha=0.25,
					  label='control evaluation plane')
	ax.add_patch(plane)
	pathpatch_2d_to_3d(plane, z=y, zdir='y')
	ax.scatter(x_sph, y_sph, z_sph, color=cs[0], depthshade=True,
		       label='integration grid')
	ax.quiver(x_sph, y_sph, z_sph,
		      nx_sph, ny_sph, nz_sph,
			  normalize=True, arrow_length_ratio=0.33, length=0.75/1000,
			  lw=1.25, color=cs[0], label='unit normal vector')
	ax.set_box_aspect([1, 1, 1])
	ax.set(xlabel='$x$ [mm]', ylabel='$y$ [mm]', zlabel='$z$ [mm]',
		   xticks=[x_pln.min(), 0.0, x_pln.max()],
		   yticks=[y_sph.min(), 0.0, y_sph.max()],
		   zticks=[z_pln.min(), 0.0, z_pln.max()],
		   xticklabels=[round(x_pln.min()*1000), 0, round(x_pln.max()*1000)],
		   yticklabels=[round(y_sph.min()*1000, 2), 0, round(y_sph.max()*1000, 2)],
		   zticklabels=[round(z_pln.min()*1000), 0, round(z_pln.max()*1000)],
		   xlim=[x_pln.min()*1.5, x_pln.max()*1.5],
		   ylim=[y_sph.min()-abs(y_sph.max()*0.5),
				 y_sph.max()+abs(y_sph.max()*0.5)],
		   zlim=[z_pln.min()*1.5, z_pln.max()*1.5]
		   )
	ax.xaxis.pane.fill = False
	ax.yaxis.pane.fill = False
	ax.zaxis.pane.fill = False
	ax.view_init(20, -70)
	fig.legend()
	fig.tight_layout()
	# fig.savefig(os.path.join(
	#     os.pardir, 'artwork', 'spherical_surface.pdf'
	#     ))
	plt.show()

if __name__ == '__main__':
	main()


class Animal:
    def __init__(self, kind, name, next = None):
        """
            Initializes an instance of the Animal class.

            Args:
                kind (str): The type or kind of the animal.
                name (str): The name of the animal.
                next (Animal, optional): The reference to the next animal in the queue. Defaults to None.
        """
        self.kind = kind
        self.name = name
        self.next = next

class AnimalShelter:
    def __init__(self, back = None, front = None):
        """
        Initializes an instance of the AnimalShelter class.

        Args:
            back (Animal, optional): The reference to the back of the queue. Defaults to None.
            front (Animal, optional): The reference to the front of the queue. Defaults to None.
        """
        self.back = back
        self.front = front

    def __str__(self):
        """
        Returns a string representation of the animal queue.

        Returns:
            str: A string representation of the animal queue.
        """
        current = self.front
        queue = ""
        while current:
            queue = f" <- {current.name}" + queue
            current = current.next
        return "None" + queue

    def enqueue(self, animal):
        """
        Enqueues an animal into the shelter queue.

        Args:
            animal (Animal): The animal object to be enqueued.
        """
        if not self.back :
            self.back = animal
            self.front = animal
        else:
            self.back.next = animal
            self.back = animal

    def dequeue(self, pref):
        """
        Dequeues an animal from the shelter queue based on the preference.

        Args:
            pref (str): The preference for the type of animal to dequeue ("cat", "dog", or any other value).

        Returns:
            str: The name of the dequeued animal.

        Raises:
            Exception: If the queue is empty.
        """
        if not self.front:
            raise Exception("The queue is empty !")
        temp = self.front
        if (self.front.kind == pref) or (pref != "cat" and pref != "dog"):
            self.front = temp.next
            temp.next = None
            return temp.name

        else:
            counter = 0
            found = False
            dequeued_value = None
            while temp:
                counter += 1
                temp = temp.next
            temp = self.front

            for _ in range(counter - 1):
                if self.front.kind == pref and not found:
                    dequeued_value = self.front.name
                    self.front = temp.next
                    temp.next = None
                    temp = self.front
                    found = True

                self.front = temp.next
                temp.next = None
                self.enqueue(temp)
                temp = self.front
            counter += 1
            return dequeued_value

animal1 = Animal("cat", "locy")
animal2 = Animal("dog", "joy")
animal3 = Animal("cat", "locyy")
animal4 = Animal("dog", "joyy")
animal5 = Animal("cat", "locyyy")
animal6 = Animal("deg", "joyyy")
shelter = AnimalShelter()
shelter.enqueue(animal1)
shelter.enqueue(animal2)
shelter.enqueue(animal3)
shelter.enqueue(animal4)
shelter.enqueue(animal5)
shelter.enqueue(animal6)
print(shelter)                  # Output =>  None <- joyyy <- locyyy <- joyy <- locyy <- joy <- locy
print(shelter.dequeue("lion"))  # Output => joy
print(shelter)                  # Output =>  None <- joyyy <- locyyy <- joyy <- locyy <- locy


from __future__ import annotations
import json
import os
import requests
from typing import Tuple
from .common import *
from .jws import sign, rsa, x509

INTERACTIVE_PAYMENT = "interactive_payment"
AUTOMATED_PAYMENT = "automated_payment"
EXPECTED_PAYMENT = "expected_payment"

class PayinDebtor:
    """The debtor (origin) of a payin with the following fields:

    - name: The name of the debtor (optional)
    - identification: The ID of the debtor (optional)
    - financial_institution: The financial institution of the debtor (optional)
    - account: The account of the debtor (optional)
    - account_type: The type of account of the debtor (optional)
    - email: The email of the debtor (optional)
    """

    def __init__(
        self,
        name: str = None,
        identification: PersonId = None,
        financial_institution: FinancialInstitution = None,
        account: str = None,
        account_type: str = None,
        email: str = None,
    ) -> None:
        self.name = name
        self.identification = identification
        self.financial_institution = financial_institution
        self.account = account
        self.account_type = account_type
        self.email = email

class PayinCreditor:
    """The creditor (destination) of a payin with:

    - name: The name of the creditor
    - identification: The ID of the creditor
    - financial_institution: The financial institution of the creditor
    - account: The account of the creditor
    - account_type: The type of account of the creditor
    - email: The email of the creditor
    """

    def __init__(
        self,
        name: str,
        identification: PersonId,
        financial_institution: FinancialInstitution,
        account: str,
        account_type: str,
        email: str,
    ) -> None:
        self.name = name
        self.identification = identification
        self.financial_institution = financial_institution
        self.account = account
        self.account_type = account_type
        self.email = email

class PayinTransaction:
    """A payin transaction with:

    - payin_type: Either "interactive_payment" or "automated_payment" or "expected_payment"
    - interactive_payment_provider: The provider of the interactive payment (optional)
    - interactive_payment_success_redirect_url: The URL to redirect to after a successful interactive payment (only required for interactive payments)
    - interactive_payment_failure_redirect_url: The URL to redirect to after a failed interactive payment (only required for interactive payments)
    - transaction_id: The ID of the transaction (UUID string)
    - currency: The currency of the transaction
    - amount: The amount of the transaction (string) (optional)
    - description: The description of the transaction
    - expiration_date: The last date the transaction can be executed, after which the payment will be considered as failed (optional)
    - debtor: The debtor of the transaction
    - creditor: The creditor of the transaction
    """

    def __init__(
        self,
        payin_type: str,
        currency: str,
        creditor: PayinCreditor,
        interactive_payment_provider: str = None,
        interactive_payment_success_redirect_url: str = None,
        interactive_payment_failure_redirect_url: str = None,
        transaction_id: str = None,
        amount: str = None,
        description: str = None,
        expiration_date: str = None,
        debtor: PayinDebtor = None,
    ) -> None:
        self.transaction_type = "payin"
        self.payin_type = payin_type
        self.interactive_payment_provider = interactive_payment_provider
        self.interactive_payment_success_redirect_url = (
            interactive_payment_success_redirect_url
        )
        self.interactive_payment_failure_redirect_url = (
            interactive_payment_failure_redirect_url
        )
        self.transaction_id = transaction_id or random_uuid()
        self.currency = currency
        self.amount = amount
        self.description = description
        self.expiration_date = expiration_date
        self.debtor = debtor
        self.creditor = creditor

class PayinHttpResponseError:
    """An error in the payin sync response with:

    - error_code: The error code
    - error_message: Human-readable error message
    """

    def __init__(self, error_code: str, error_message: str) -> None:
        self.error_code = error_code
        self.error_message = error_message

    def __str__(self) -> str:
        return f"{self.error_code} ({self.error_message})"

    def __repr__(self) -> str:
        return f"PayinHttpResponseError({self.error_code}, {self.error_message})"

class PayinHttpResponse:
    """The http response received right after posting a payin message, with:
    - http_status_code: The HTTP code of the response
    - transaction ids: A dict mapping transaction ids to Shinkansen's transaction id
    - interactive_payment_urls: A dict mapping transaction ids to interactive payment URLs
    - errors: A list of `PayinHttpResponseError`s
    """

    def __init__(
        self,
        http_status_code: int,
        transaction_ids: dict[str, str],
        interactive_payment_urls: dict[str, str],
        errors: list[PayinHttpResponseError],
    ) -> None:
        self.http_status_code = http_status_code
        self.transaction_ids = transaction_ids
        self.interactive_payment_urls = interactive_payment_urls
        self.errors = errors

    def __str__(self) -> str:
        return f"{self.http_status_code} transaction_ids={self.transaction_ids} interactive_payment_urls={self.interactive_payment_urls} errors={self.errors}"

    def __repr__(self) -> str:
        return f"PayinHttpResponse({self.http_status_code}, {self.transaction_ids}, {self.interactive_payment_urls} {self.errors})"

    @classmethod
    def from_http_response(cls, response: requests.Response) -> PayinHttpResponse:
        """Return a PayinHttpResponse from a HTTP response"""
        if response.status_code in (200, 409):
            return PayinHttpResponse(
                http_status_code=response.status_code,
                errors=[],
                transaction_ids={
                    t["transaction_id"]: t["shinkansen_transaction_id"]
                    for t in response.json()["transactions"]
                },
                interactive_payment_urls={
                    t["transaction_id"]: t["interactive_payment_url"]
                    for t in response.json()["transactions"]
                    if "interactive_payment_url" in t
                },
            )
        elif response.status_code == 400:
            try:
                return PayinHttpResponse(
                    http_status_code=response.status_code,
                    transaction_ids={},
                    interactive_payment_urls={},
                    errors=[
                        PayinHttpResponseError(e["error_code"], e["error_message"])
                        for e in response.json()["errors"]
                    ],
                )
            except requests.exceptions.JSONDecodeError:
                pass  # go to the catch-all at the end
        # Catch all:
        return PayinHttpResponse(
            http_status_code=response.status_code,
            transaction_ids={},
            interactive_payment_urls={},
            errors=[],
        )

class PayinMessage:
    """A payin message with:

    - header: The header of the message
    - transactions: A list of transactions contained in the message
    """

    def __init__(
        self, header: MessageHeader, transactions: list[PayinTransaction]
    ) -> None:
        self.header = header
        self.transactions = transactions

    def as_json(self) -> str:
        """Returns the message as a JSON object"""
        return json.dumps(
            {"document": self},
            default=lambda o: {k: v for (k, v) in o.__dict__.items() if v is not None},
        )

    @classmethod
    def from_json(cls, json_string: str) -> "PayinMessage":
        """Return a message from a JSON string"""
        json_dict = json.loads(json_string)
        return cls(
            header=MessageHeader.from_json_dict(json_dict["document"]["header"]),
            transactions=[
                PayinTransaction(
                    payin_type=t["payin_type"],
                    interactive_payment_provider=t.get("interactive_payment_provider"),
                    interactive_payment_success_redirect_url=t.get(
                        "interactive_payment_success_redirect_url"
                    ),
                    interactive_payment_failure_redirect_url=t.get(
                        "interactive_payment_failure_redirect_url"
                    ),
                    transaction_id=t["transaction_id"],
                    currency=t["currency"],
                    amount=t.get("amount"),
                    description=t.get("description"),
                    expiration_date=t.get("expiration_date"),
                    debtor=t.get("debtor")
                    and PayinDebtor(
                        name=t["debtor"].get("name"),
                        identification=t["debtor"].get("identification")
                        and PersonId(
                            id_schema=t["debtor"]["identification"]["id_schema"],
                            id=t["debtor"]["identification"]["id"],
                        ),
                        financial_institution=t["debtor"].get("financial_institution")
                        and FinancialInstitution(
                            fin_id_schema=t["debtor"]["financial_institution"][
                                "fin_id_schema"
                            ],
                            fin_id=t["debtor"]["financial_institution"]["fin_id"],
                        ),
                        account=t["debtor"].get("account"),
                        account_type=t["debtor"].get("account_type"),
                        email=t["debtor"].get("email"),
                    ),
                    creditor=PayinCreditor(
                        name=t["creditor"]["name"],
                        identification=PersonId(
                            id_schema=t["creditor"]["identification"]["id_schema"],
                            id=t["creditor"]["identification"]["id"],
                        ),
                        financial_institution=FinancialInstitution(
                            fin_id_schema=t["creditor"]["financial_institution"][
                                "fin_id_schema"
                            ],
                            fin_id=t["creditor"]["financial_institution"]["fin_id"],
                        ),
                        account=t["creditor"]["account"],
                        account_type=t["creditor"]["account_type"],
                        email=t["creditor"]["email"],
                    ),
                )
                for t in json_dict["document"]["transactions"]
            ],
        )

    @property
    def id(self) -> str:
        """Returns the ID of the message"""
        return self.header.message_id

    def signature(
        self,
        certificate_private_key: rsa.RSAPrivateKey,
        certificate: x509.Certificate,
    ) -> str:
        return sign(self.as_json(), certificate_private_key, certificate)

    def sign_and_send(
        self,
        certificate_private_key: rsa.RSAPrivateKey,
        certificate: x509.Certificate,
        api_key: str = None,
        base_url: str = None,
    ) -> Tuple[str, PayinHttpResponse]:
        """Signs the message and sends it to the Shinkansen API"""
        signature = self.signature(certificate_private_key, certificate)
        return (signature, self.send(signature, api_key, base_url))

    def send(
        self, signature: str, api_key: str = None, base_url: str = None
    ) -> PayinHttpResponse:
        """Sends the message to the Shinkansen API"""
        base_url = base_url or SHINKANSEN_API_V1_BASE_URL
        api_key = api_key or os.environ.get("SHINKANSEN_API_KEY")
        if not api_key:
            raise ShinkansenException(
                "No api_key argument and SHINKANSEN_API_KEY not found in env"
            )
        response = requests.post(
            url=f"{base_url}/messages/payins",
            data=self.as_json(),
            headers={
                "Content-Type": "application/json",
                "Shinkansen-Api-Key": api_key,
                "Shinkansen-JWS-Signature": signature,
            },
        )
        return PayinHttpResponse.from_http_response(response)


from flask import Flask, request, render_template
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from utils import scroll_to_page_end, extract_videos_data

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/result", methods=["POST"])
def result():
    url = request.form["url"]
    if "/videos" not in url:
        url = url.rstrip("/") + "/videos"
    driver = webdriver.Chrome()
    driver.get(url)
    scroll_to_page_end(driver)
    html = driver.page_source
    soup = BeautifulSoup(html, "html.parser")
    data = extract_videos_data(soup)
    channel_name = url.split("/")[-2].replace("@", "")
    df = pd.DataFrame(data)
    videos = df.to_dict("records")
    return render_template("result.html", videos=videos)

if __name__ == "__main__":
    app.run(debug=True)


import os
import sys
import difflib
import unittest
import subprocess
import distutils.file_util

import getnose
import nose.plugins
import nose.plugins.builtin
import makeloadertests

class JsTest(nose.plugins.Plugin):
    def options(self, parser, env=os.environ):
        nose.plugins.Plugin.options(self, parser, env)
        parser.add_option("--revalidate-logs", action="store_true",
                          dest="revalidate_logs",
                          default=False,
                          help="For all tests run, makes their logs "
                          "the expected, or canonical, log file to "
                          "which all future runs of the tests are "
                          "compared to.")

    def configure(self, options, config):
        nose.plugins.Plugin.configure(self, options, config)
        self.revalidate_logs = options.revalidate_logs

    def wantFile(self, file):
        basename = os.path.basename(file)
        ext = os.path.splitext(file)[1]
        if (basename.startswith("test_") and ext == ".js"):
            return True
        # Oddly enough, if we return 'False' here instead of 'None',
        # none of the other plugins get a chance to test the file.
        return None

    def loadTestsFromFile(self, filename):
        return [JsTestCase(filename, self.revalidate_logs)]

class JsTestCase(unittest.TestCase):
    def __init__(self, test, revalidate_logs):
        self.__test = test
        self.__revalidate_logs = revalidate_logs
        unittest.TestCase.__init__(self)

    def shortDescription(self):
        return os.path.basename(os.path.splitext(self.__test)[0])

    def runTest(self):
        test = self.__test
        dirname = os.path.dirname(test)
        testname = os.path.splitext(os.path.basename(test))[0]
        result = subprocess.call(
            ["make",
             "-C", dirname,
             "-f", "../harness/Makefile",
             testname],
            stdout = subprocess.PIPE,
            stderr = subprocess.STDOUT
            )
        logfile_name = os.path.join(dirname, testname + ".log")
        if result != 0:
            self.fail(open(logfile_name, "r").read())
        else:
            expected_logfile_name = logfile_name + ".expected"
            if self.__revalidate_logs:
                distutils.file_util.copy_file(logfile_name,
                                              expected_logfile_name)
            if os.path.exists(expected_logfile_name):
                expected = open(expected_logfile_name, "r").read()
                actual = open(logfile_name, "r").read()
                if expected != actual:
                    diff = "Expected results differ from actual results.\n\n"
                    diff += "\n".join(difflib.unified_diff(
                        expected.splitlines(), actual.splitlines(),
                        "expected results", "actual results"
                        ))
                    diff += ("\n\nIf you believe that these changes are valid "
                             "(i.e., that they don't represent malfunctioning "
                             "code), you may want to re-validate the expected "
                             "results by running the following command:\n\n")
                    diff += "python %s %s --revalidate-logs\n" % (
                        sys.argv[0],
                        self.__test
                        )
                    self.fail(diff)

if __name__ == "__main__":
    makeloadertests.remove_old_loader_tests()
    makeloadertests.make_loader_tests()

    sys.argv.append("--with-jstest")
    nose.main(defaultTest=["scripts",
                           "tests/unit",
                           "tests/system"],
              plugins=[JsTest()])


from size_based_ecosystem import *
import matplotlib.animation as animation
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
             (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
             (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
             (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
             (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]

# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for i in range(len(tableau20)):
    r, g, b = tableau20[i]
    tableau20[i] = (r / 255., g / 255., b / 255.)

from size_based_ecosystem import *
import copy as copy
import scipy.stats as stats
import pickle as pkl

depth = 20
layers = 100
size_classes = 1
lam = 1
simulate = True
verbose = False
daily_cycle = 365*2*np.pi

obj = spectral_method(depth, layers-1) #This is the old off-by-one error... Now we have added another fucked up error!
#norm_dist = stats.norm.pdf(obj.x, loc = 3, scale = 3)
#print(norm_dist)
norm_dist = stats.norm.pdf(obj.x, loc = 3)
res_start = 3*norm_dist #0.1*(1-obj.x/depth)
res_max = 10*norm_dist

water_start = water_column(obj, res_start, layers = layers, resource_max = res_max, replacement = lam, advection = 0, diffusion = 0)
list_of_sizes = np.array([20, 8000]) #, 1, 400, 1600, 40000])

l2 = False
size_classes = 2
m_v_t = list_of_sizes #list_of_sizes[0:size_classes]
params = ecosystem_parameters(m_v_t, obj)
eco = ecosystem_optimization(m_v_t, layers, params, obj, water_start, l2 = l2, output_level = 5, movement_cost = 1)
#OG_layered_attack = np.copy(eco.parameters.layered_attack)
eco.population_setter(np.array([20, 0.1]) )#, 1, 1, 1, 0.1]))
eco.parameters.handling_times = 0 * eco.parameters.handling_times
OG_layered_attack = np.copy(params.layered_attack)
frozen_ecos = []

stability = False
time_step = 10**(-4)
#max_err = time_step*1/10
x_res = sequential_nash(eco, verbose=True, l2=l2, max_its_seq = 20)
eco.strategy_setter(x_res)

for i in range(2):
    plt.plot(obj.x, x_res[i]@eco.heat_kernels[i])
plt.show()

for i in range(100):
    eco.population_setter(np.array([20, 0.1+0.01*(i+1)]) )#, 1, 1, 1, 0.1]))
    x_res = sequential_nash(eco, verbose=True, l2=l2, max_its_seq=20)
    eco.strategy_setter(x_res)
    print("Current iteration", i)


from PIL import Image
import numpy as np
import pandas as pd
from shutil import copyfile
import os

# Add instructions to copy .csv to test/train directory
if not os.path.isdir("./data/"):
    print('Creating Data Directory')
    os.mkdir("./data/")
if os.path.isdir("./data/smiles_valset/"):
    print("You already have raw test images, so I'm using those\n")
else:
    print("Downloading Raw Test Images\n")
    os.system('gsutil -m cp -r gs://cs229-gap-data/RawData/smiles_valset ./data/')
    print("Raw Training Test Downloaded\n")
print("Processing Test Images")
source_csv_path = "./"
source_img_path = "./data/smiles_valset/"
file_name = "gender_fex_valset.csv"
dest_csv_path = "data/test_face/"
if not os.path.isdir("./data/test_face"):
    os.mkdir("./data/test_face")
train_data = pd.read_csv(source_csv_path+file_name,header=0)
img_names = np.array(train_data.ix[:,0:1])
copyfile(source_csv_path+file_name, dest_csv_path+file_name)

for img_name in img_names:
    img = Image.open(source_img_path+img_name[0])
    img = img.resize((256,256), Image.ANTIALIAS)
    img.save(dest_csv_path+img_name[0])

for img_name in img_names:
    img = np.array(Image.open(dest_csv_path+img_name[0]))
    if(img.shape!=(256,256,3)):
        img = np.stack((img,)*3,axis=2)
        img = Image.fromarray(img)
        img.save(dest_csv_path+img_name[0])

if os.path.isdir("./data/smiles_trset/"):
    print("You already have raw training images, so I'm using those\n")
else:
    print("Downloading Raw Training Images\n")
    os.system('gsutil -m cp -r gs://cs229-gap-data/RawData/smiles_trset ./data/')
    print("Raw Training Training Downloaded\n")
print("Processing Training Images")
source_csv_path = "./"
source_img_path = "./data/smiles_trset/"
file_name = "gender_fex_trset.csv"
dest_csv_path = "data/train_face/"
if not os.path.isdir("./data/train_face"):
    os.mkdir("./data/train_face")
train_data = pd.read_csv(source_csv_path+file_name,header=0)
img_names = np.array(train_data.ix[:,0:1])
copyfile(source_csv_path+file_name, dest_csv_path+file_name)

for img_name in img_names:
    img = Image.open(source_img_path+img_name[0])
    img = img.resize((256,256), Image.ANTIALIAS)
    img.save(dest_csv_path+img_name[0])

for img_name in img_names:
    img = np.array(Image.open(dest_csv_path+img_name[0]))
    if(img.shape!=(256,256,3)):
        img = np.stack((img,)*3,axis=2)
        img = Image.fromarray(img)
        img.save(dest_csv_path+img_name[0])


# do some analysis of variance
import sys
import csv
from tabulate import tabulate
from scipy import stats

ANOVA_HEADERS = ['src', 'DF', 'SS', 'MS', 'F', 'p']

def sum_x(data):
    total = 0
    for row in data:
        total += sum(row)
    return total

def sum_xsq(data):
    total = 0
    for row in data:
        for item in row:
            total += item**2
    return total

def prep_data(file, reps):
    reader = csv.reader(file)
    init_data = []
    for line in reader:
        init_data.append([float(item) for item in line])

    n_rows = len(init_data)
    n_cols = len(init_data[0])
    n = n_cols * n_rows

    gridsum_data = []
    for i in range(0, n_rows, reps):
        summed_line = []
        for j in range(n_cols):
            block_sum = 0
            for k in range(i, i+reps, 1):
                block_sum += init_data[k][j]
            summed_line.append(block_sum)
        gridsum_data.append(summed_line)

    col_sums = [0 for _ in range(n_cols)]
    row_sums = []
    for row in gridsum_data:
        row_sums.append(sum(row))
        for i in range(len(row)):
            col_sums[i] += row[i]

    grand_total = sum(col_sums)

    return init_data, gridsum_data, col_sums, row_sums, grand_total, n, n_cols, n_rows

def pretty_anova_tbl(anova, sources):
    anova_tbl = []
    for src in sources:
        line = [src, ]
        for attr in ANOVA_HEADERS[1:]:
            if attr in anova[src]:
                line.append(anova[src][attr])
            else:
                line.append(None)
        anova_tbl.append(line)

    print(tabulate(anova_tbl, headers=ANOVA_HEADERS))

def simple_anova(file, reps):

    data, _, treat_sums, _, grand_total, n, treat_n, obs_per_treat = prep_data(file, reps)

    anova = {}; sources = ['treats', 'err', 'total']
    for item in sources:
        anova[item] = {}

    # DF's
    anova['treats']['DF'] = treat_n-1
    anova['total']['DF'] = n-1
    anova['err']['DF'] = anova['total']['DF'] - anova['treats']['DF']

    # SS's
    anova['total']['SS'] = sum_xsq(data) - ((sum_x(data)**2)/n)
    ssTreats = 0
    for i in range(treat_n):
        ssTreats += (treat_sums[i]**2)/obs_per_treat
    ssTreats -= (grand_total**2)/n
    anova['treats']['SS'] = ssTreats
    anova['err']['SS'] = anova['total']['SS'] - anova['treats']['SS']

    # MS's
    anova['treats']['MS'] = anova['treats']['SS']/anova['treats']['DF']
    anova['err']['MS'] = anova['err']['SS']/anova['err']['DF']

    # F
    anova['treats']['F'] = anova['treats']['MS']/anova['err']['MS']

    # p
    anova['treats']['p'] = stats.f(anova['treats']['DF'], anova['err']['DF']).sf(anova['treats']['F'])

    pretty_anova_tbl(anova, sources)

def blocked_anova(file, reps):

    data, _, treat_sums, block_sums, grand_total, n, n_treats, obs_per_treat = prep_data(file, reps)
    n_blocks = obs_per_treat//reps
    obs_per_block = n // n_blocks

    anova = {}; sources = ['treats', 'blocks', 'err', 'total']
    for item in sources:
        anova[item] = {}

    # DF's
    anova['total']['DF'] = n-1
    anova['treats']['DF'] = n_treats-1
    anova['blocks']['DF'] = n_blocks-1
    anova['err']['DF'] = anova['total']['DF'] - anova['treats']['DF'] - anova['blocks']['DF']

    # SS's
    anova['total']['SS'] = sum_xsq(data) - ((sum_x(data) ** 2) / n)
    ssTreats = 0
    for i in range(n_treats):
        ssTreats += (treat_sums[i] ** 2) / obs_per_treat
    ssTreats -= (grand_total ** 2) / n
    anova['treats']['SS'] = ssTreats
    ssBlocks = 0
    for i in range(n_blocks):
        ssBlocks += (block_sums[i]**2) / obs_per_block
    ssBlocks -= (grand_total**2) / n
    anova['blocks']['SS'] = ssBlocks
    anova['err']['SS'] = anova['total']['SS'] - anova['treats']['SS'] - anova['blocks']['SS']

    # MS's
    anova['treats']['MS'] = anova['treats']['SS'] / anova['treats']['DF']
    anova['blocks']['MS'] = anova['blocks']['SS'] / anova['blocks']['DF']
    anova['err']['MS'] = anova['err']['SS'] / anova['err']['DF']

    # F
    anova['treats']['F'] = anova['treats']['MS'] / anova['err']['MS']
    anova['blocks']['F'] = anova['blocks']['MS'] / anova['err']['MS']

    # p
    anova['treats']['p'] = stats.f(anova['treats']['DF'], anova['err']['DF']).sf(anova['treats']['F'])
    anova['blocks']['p'] = stats.f(anova['blocks']['DF'], anova['err']['DF']).sf(anova['blocks']['F'])

    pretty_anova_tbl(anova, sources)

def twoway_anova(file, reps):
    data, gridsum_data, fac1_sums, fac2_sums, grand_total, n, n_fac1s, obs_per_fac1 = prep_data(file, reps)
    n_fac2s = obs_per_fac1 // reps
    obs_per_fac2 = n // n_fac2s
    obs_per_square = obs_per_fac1 // n_fac2s

    anova = {}; sources = ['faccol', 'facrow', 'inter', 'err', 'total']
    for item in sources:
        anova[item] = {}

    # DF's
    anova['total']['DF'] = n - 1
    anova['faccol']['DF'] = n_fac1s-1
    anova['facrow']['DF'] = n_fac2s-1
    anova['inter']['DF'] = anova['faccol']['DF'] * anova['facrow']['DF']
    anova['err']['DF'] = anova['total']['DF'] - anova['faccol']['DF'] - anova['facrow']['DF'] - anova['inter']['DF']

    # SS's
    anova['total']['SS'] = sum_xsq(data) - ((sum_x(data) ** 2) / n)
    SSFac1 = 0
    for sum in fac1_sums:
        SSFac1 += (sum**2)/obs_per_fac1
    SSFac1 -= grand_total**2 / n
    anova['faccol']['SS'] = SSFac1
    SSFac2 = 0
    for sum in fac2_sums:
        SSFac2 += (sum**2)/obs_per_fac2
    SSFac2 -= grand_total**2 / n
    anova['facrow']['SS'] = SSFac2
    SSInter = 0
    for i in range(n_fac2s):  # rows
        for j in range(n_fac1s):  # cols
            SSInter += gridsum_data[i][j]**2 / obs_per_square
    SSInter -= grand_total**2 / n
    SSInter -= SSFac1 + SSFac2
    anova['inter']['SS'] = SSInter
    anova['err']['SS'] = anova['total']['SS'] - anova['faccol']['SS'] - anova['facrow']['SS'] - anova['inter']['SS']

    # MS's
    anova['faccol']['MS'] = anova['faccol']['SS'] / anova['faccol']['DF']
    anova['facrow']['MS'] = anova['facrow']['SS'] / anova['facrow']['DF']
    anova['inter']['MS'] = anova['inter']['SS'] / anova['inter']['DF']
    anova['err']['MS'] = anova['err']['SS'] / anova['err']['DF']

    # F
    anova['faccol']['F'] = anova['faccol']['MS'] / anova['err']['MS']
    anova['facrow']['F'] = anova['facrow']['MS'] / anova['err']['MS']
    anova['inter']['F'] = anova['inter']['MS'] / anova['err']['MS']

    # p
    anova['faccol']['p'] = stats.f(anova['faccol']['DF'], anova['err']['DF']).sf(anova['faccol']['F'])
    anova['facrow']['p'] = stats.f(anova['facrow']['DF'], anova['err']['DF']).sf(anova['facrow']['F'])
    anova['inter']['p'] = stats.f(anova['inter']['DF'], anova['err']['DF']).sf(anova['inter']['F'])

    pretty_anova_tbl(anova, sources)

if __name__ == '__main__':
    if len(sys.argv) < 4:
        print('Usage: python3', sys.argv[0], '[simple|blocked|twoway]', '[csv_file]', '[reps]')
        exit()

    method = sys.argv[1]
    reps = int(sys.argv[3])
    with open(sys.argv[2]) as file:
        if method == 'simple':
            simple_anova(file, reps)
        elif method == 'blocked':
            blocked_anova(file, reps)
        elif method == 'twoway':
            twoway_anova(file, reps)
        else:
            print('Unknown method:', method)
            print('Allowed methods: simple, blocked, twoway')


import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
import csv
import numpy as np
import matplotlib.mlab

def plotDecisionRegionQDA(sampleMean, CV_, training, data):
    all_res = []
    minX, maxX, minY, maxY = 0., 8., 0., 8.

    # create one-dimensional arrays for x and y
    x = np.linspace(minX, maxX, 100, endpoint=True)
    y = np.linspace(minY, maxY, 100, endpoint=True)
    cnt = 0
    for i in range(len(x) - 1):
        for k in range(len(y) - 1):
            classIndex = 0
            logLikelihood = float("inf")
            for j in range(len(data.species.unique())):
                Nk = training.groupby('species').size()[data.species.unique()[j]]
                newLikelihood = logLikelihoodCalc([x[i],y[k]], sampleMean[j], CV_[j], Nk)
                if (newLikelihood < logLikelihood):
                    logLikelihood = newLikelihood
                    classIndex = j
            test = [x[i],y[k], data.species.unique()[classIndex]]
            test = pd.DataFrame([test], columns=['pet_length', 'pet_width', 'species'])
            cnt  =cnt + 1
            all_res.append(test)
    plotPairwiseScatterPlot(pd.concat(all_res))

def plotDecisionRegionLDA(sampleMean, CV_, training, data):
    all_res = []
    minX, maxX, minY, maxY = 0., 8., 0., 8.

    # create one-dimensional arrays for x and y
    x = np.linspace(minX, maxX, 100, endpoint=True)
    y = np.linspace(minY, maxY, 100, endpoint=True)
    cnt = 0
    for i in range(len(x) - 1):
        for k in range(len(y) - 1):
            classIndex = 0
            logLikelihood = float("inf")
            for j in range(len(data.species.unique())):
                Nk = training.groupby('species').size()[data.species.unique()[j]]
                newLikelihood = logLikelihoodCalc([x[i],y[k]], sampleMean[j], CV_, Nk)
                if (newLikelihood < logLikelihood):
                    logLikelihood = newLikelihood
                    classIndex = j
            test = [x[i],y[k], data.species.unique()[classIndex]]
            test = pd.DataFrame([test], columns=['pet_length', 'pet_width', 'species'])
            cnt  =cnt + 1
            all_res.append(test)
    plotPairwiseScatterPlot(pd.concat(all_res))

def plotPairwiseScatterPlot(dataframe):
    sns.scatterplot(x="pet_length", y="pet_width", hue="species",
                      data=dataframe)

def plotDecisionRegion(C, mu ):
    x = np.arange(-5, 10.0, 0.005)
    y = np.arange(-5, 10.0, 0.005)
    X, Y = np.meshgrid(x, y)
    Z = matplotlib.mlab.bivariate_normal(X, Y, C[0, 0], C[1, 1], mu[0], mu[1], (C[0,1]*C[1,0]))
    plt.contour(X, Y, Z, levels = 10)

def Mahalonobis(x,C):
    return x.dot(np.linalg.inv(C)).dot(np.transpose(x))

#-log likelihood
def logLikelihoodCalc(data,mu, C, Nk):
    return (1/2 * np.log(np.linalg.det(C)) + np.log(Mahalonobis(data-mu,C)) - np.log(Nk))

def generateSampleMean(data):
    mean = [ data["pet_length"].mean(),data["pet_width"].mean()]
    return mean
def generateClassSampleMeans(data):
    classMeans = []
    classes = data.species.unique()
    for species in classes:
        classFrame = data.loc[data['species'] == species]
        classMeans.append(generateSampleMean(classFrame))
    return np.asarray(classMeans)

def generateClassCovarianceMatrix(data, mu):
    classCVs = []
    classes = data.species.unique()
    j=0
    mu = np.asarray(mu)
    for species in classes:
        classFrame = data.loc[data['species'] == species]
        classCVs.append(generatePooledCovariance(classFrame,mu[j]))
        j = j+1

    return np.asarray(classCVs)

def generatePooledCovariance(data, mean):
    data = pd.DataFrame(data)
    C  = np.ndarray(shape=(2,2), dtype=float, order='F')
    mean = np.asarray(mean)
    data.reset_index(inplace=True, drop = True)
    for i in range(len(data.index)):
        x_ = [data["pet_length"][i],data["pet_width"][i]]
        for j in  range(len(data.species.unique())):
            if data.species.unique()[j] == data["species"][i]:
                C = C + 1/len(data.index)*np.outer((x_-mean[j]),np.transpose(x_-mean[j]))
    return C

def LOOCVQDA(data, mode):
    LOOCV_Error = 0.0;
    data = data.reset_index()
    for i in range(len(data.index)):
        training = data.copy(deep=True)
        training.drop(training.index[i], inplace=True)
        test = data.iloc[i]
        classIndex = 0
        logLikelihood = float("inf")
        sampleMean = generateClassSampleMeans(training)
        CV_ = generateClassCovarianceMatrix(training, sampleMean)
        for j in range(CV_.shape[0]):
            if mode > 0:
                CV_[j]= np.diag(np.diag(CV_[j]))
                if mode > 1:
                    CV_[j] = (np.trace(CV_[j]) / CV_[j].shape[1]) * \
                          np.identity(CV_[j].shape[1])
        for j in range(len(data.species.unique())):
            Nk = training.groupby('species').size()[data.species.unique()[j]]
            newLikelihood = logLikelihoodCalc([test['pet_length'], test['pet_width']], sampleMean[j], CV_[j], Nk)
            if (newLikelihood < logLikelihood):
                logLikelihood = newLikelihood
                classIndex = j
        if (i == len(data.index) - 1):
            #plotPairwiseScatterPlot(training)
            plotDecisionRegionQDA(sampleMean, CV_, training, data)
        if data.species.unique()[classIndex] != test["species"]:
            LOOCV_Error = LOOCV_Error + 1 / len(data.index);

    return LOOCV_Error

def LOOCVLDA(data, mode):
    LOOCV_Error = 0.0;
    data = data.reset_index()
    for i in range(len(data.index)):
        training = data.copy(deep=True)
        training.drop(training.index[i], inplace=True)
        test = data.iloc[i]
        classIndex = 0
        logLikelihood = float("inf")
        sampleMean = generateClassSampleMeans(training)
        CV_ = generatePooledCovariance(training,sampleMean)

        if mode > 0:
            CV_ = np.diag(np.diag(CV_))
            if mode > 1:
                CV_ =( np.trace(CV_) / CV_.shape[0]) * \
                     np.identity(CV_.shape[0])
        for j in range(len(data.species.unique())):
            #if(i == len(data.index) - 1):
                #plotDecisionRegion(CV_, sampleMean[j])
            Nk =training.groupby('species').size()[data.species.unique()[j]]
            newLikelihood = logLikelihoodCalc([test['pet_length'],test['pet_width']],sampleMean[j], CV_, Nk)
            if( newLikelihood < logLikelihood):
                logLikelihood = newLikelihood
                classIndex = j
        if (i == len(data.index) - 1):
            plotPairwiseScatterPlot(training)
            plotDecisionRegionLDA(sampleMean, CV_, training, data)
        if data.species.unique()[classIndex] != test["species"]:
            LOOCV_Error = LOOCV_Error + 1/len(data.index);

    return LOOCV_Error

with open("iris.data.txt", 'rt') as csvfile:
     iris = csv.reader(csvfile, delimiter=',', quotechar='|')
     IrisReduced = pd.DataFrame(list(iris))
IrisReduced.columns = ['sep_length','sep_width','pet_length','pet_width','species']
IrisReduced.drop(['sep_length'], axis = 1, inplace = True)
IrisReduced.drop(['sep_width'], axis = 1, inplace = True)
IrisReduced[['pet_length','pet_width']] = IrisReduced[['pet_length','pet_width']].astype(float)

#LDA mode: 0-general, 1-independent, 2- isotropic
print("Error for LDA: general case")
print(LOOCVLDA(IrisReduced, 1))
#print("Error for LDA: independent case")
#print(LOOCVLDA(IrisReduced, 1))
#print("Error for LDA: isotropic case")
#print(LOOCVLDA(IrisReduced, 2))

#QDA mode: 0-general, 1-independent, 2- isotropic
#print("Error for QDA: general case")
#print(LOOCVQDA(IrisReduced, 0))
#print("Error for QDA: in independent case")
#print(LOOCVQDA(IrisReduced, 1))
#print("Error for QDA: isotropic case")
#print(LOOCVQDA(IrisReduced, 2))
plt.show()


import questionTools as qTools
import dataTools as dTools
import aiTools

def main():
	# define the question # and question column set
	problem = 2

	csv = 'project510Data.csv'

	dataTotal = dTools.dataTotal(csv)

	q = qTools.Question(problem)
	q.getInputDataAndLabels(dataTotal._dataList)

	trainToTestRatio = 0.9

	dataQ = dTools.dataQuestion(q, trainToTestRatio)

	classifier = aiTools.classifier(q, dataQ, aiTools.featureExtractor, maxIter)

	classifier.prepDataTrain()
	classifier.train()
	tests.append(classifier.test())

if __name__=="__main__":
	main()


import sys
import os
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parent_dir)

import unittest

from ngsi_ld_models.models.sensor import Sensor

class Sensors(unittest.TestCase):
    def test_interface(self):
        self.assertIsInstance(
            Sensor.parse_file(
                "example/example-normalized.json"),
            Sensor)

if __name__ == '__main__':
    unittest.main()


import problem1
import problem2
import problem3
import sys

def print_help():
	print('Uso: python3 main.py problema[ 1 | 2 | 3 ] m L delta1 delta2 alpha beta')
	print(' - Ejemplo: python3 main.py problema1 100 0.51302 0.008 0.004 2 5.45')

def main():

	if (len(sys.argv) != 8):
		print_help()
		return

	m = int(sys.argv[2])
	L = float(sys.argv[3])
	delta1 = float(sys.argv[4])
	delta2 = float(sys.argv[5])
	alpha = float(sys.argv[6])
	beta = float(sys.argv[7])

	option = sys.argv[1]

	if option == 'problema1':
		print('Ejecutando problema 1.')
		A = problem1.calculate_matrix_A(m, L, delta1, delta2, alpha, beta)
		print('Matriz A: (formato MatrixMarket .mtx)')
		A.print_as_list()

	elif option == 'problema2':
		print('Ejecutando problema 2.')
		egs = problem2.calculate_eigenvalues_A(m, L, delta1, delta2, alpha, beta)
		print('Autovalores de A:')
		for val in egs:
			print(val)

	elif option == 'problema3':
		print('Ejecutando problema 3.')
		egs = problem3.calculate_eigenvalues_A(m, L, delta1, delta2, alpha, beta)
		print('Autovalores de A:')
		for val in egs:
			print(val)

	else:
		raise Error()

if __name__ == '__main__':
	main()


import os
import re
import shutil
import tempfile
import unittest

from cupy import testing

from example_tests import example_test

os.environ['MPLBACKEND'] = 'Agg'

@testing.with_requires('matplotlib')
class TestKmeans(unittest.TestCase):

    def test_default(self):
        output = example_test.run_example(
            'kmeans/kmeans.py', '-m', '1', '--num', '10')
        assert re.search(
            r' CPU :  [0-9\.]+ sec\s+GPU :  [0-9\.]+ sec',
            output.decode('utf-8'),
        )

    def test_custom_kernel(self):
        output = example_test.run_example(
            'kmeans/kmeans.py', '-m', '1', '--num', '10',
            '--use-custom-kernel')
        assert re.search(
            r' CPU :  [0-9\.]+ sec\s+GPU :  [0-9\.]+ sec',
            output.decode('utf-8'),
        )

    def test_result_image(self):
        dir_path = tempfile.mkdtemp()
        try:
            image_path = os.path.join(dir_path, 'kmeans.png')
            example_test.run_example(
                'kmeans/kmeans.py', '-m', '1', '--num', '10', '-o', image_path)
            assert os.path.exists(image_path)
        finally:
            shutil.rmtree(dir_path, ignore_errors=True)


# -*- coding: UTF-8 -*-
from flask import Flask, jsonify, current_app, render_template, request

import os
import sys
import json             # http query responses handled as json
                        # (in python requests/grequests and ajax calls)
import requests         # for http get/post calls
from time import time   # to measure elapsed time for debugging purpose

''' 'yelp2' module is my contribution for extracting photos (biz-photos) '''
from yelp2.url_params import Url_Params     # set up parameters to use Yelp search API
from yelp2.config import DEFAULT_TERM       # term/category for yelp search query in case term input field is empty
from yelp2.config import DEFAULT_LOCATION   # default location for yelp search query
from yelp2.visual_yelp import Visual_Yelp # wrapper for yelp client object
import logging
from logging.handlers import RotatingFileHandler

app = Flask(__name__)

IS_PRODUCTION = (os.getenv('PYTHON_ENV', False) == "production")
if not IS_PRODUCTION:
    app.debug = True

''' landing page '''
@app.route('/')
def index():
    return render_template('kd.html')

''' "visual" presentation of yelp search results '''
@app.route('/yelp')
def yelp():
    # business photos (biz-photos) are extracted from yelp search results,
    # and displayed one business per row.

    # biz-photos are found on each business' photo-box page. Formatted results
    # are appended to "search-results" div tag in body.

    # Yelp query string is '/yelp/?term=category&location=region'
    # business term or category and location are taken from input fields

    # visitor first sees yelp results with default term/category and
    # ip-obtained geolocation displayed on page

    # browser ip used to obtain geolocation
    client_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)

    # util functions to generate search query parameters
    # in case of error default term/category & location values used
    util = Url_Params()

    location = util.get_location(client_ip)

    # pass location info to yelp page
    return render_template('yelp.html', term=DEFAULT_TERM, loc=location)

@app.route('/kd')
def kd():
     return render_template('kd.html')

# @app.route('/home')
# def home():
#      link_id_1 = 'YelpPhotos'
#      link_url_1 = '/yelp/'
#      link_id_2 = 'LinkedIn'
#      link_url_2 = 'https://www.linkedin.com/in/gilkwak'
#      return render_template('indexhtml.html',
#                              link_id_1=link_id_1,
#                              link_url_1=link_url_1,
#                              link_id_2=link_id_2,
#                              link_url_2=link_url_2)

""" Displays results of Yelp http get request """
@app.route("/search/", methods=["GET"])
def main():
    # decorator for Yelp client for search query & process response for
    # visual display of results (biz-photos for each businesses)
    yelp = Visual_Yelp()

    biz_photos = yelp.biz_photos()

    # json containing status, html for biz-photos,
    # longitudes and latitudes of businesses for google map
    return biz_photos

''' for google map '''
@app.route('/googlemap/')
def googlemap():
    return render_template('googlemap.html')

if __name__ == "__main__":
    # handler = RotatingFileHandler('foo.log', maxBytes=10000, backupCount=1)
    # handler.setLevel(logging.INFO)
    # app.logger.addHandler(handler)
    if app.debug:
        app.run(
            host=os.getenv('IP', '0.0.0.0'),
            port=int(os.getenv('PORT', '8080'))
        )
    else:
        app.run()


class Hero:
    def __init__(self, name, health):
        self.name: str = name
        self.health: int = health
        self.max_health: int = 20
        self.attack: int = 0
        self.money: int = 0

        self.lvl: int = 1
        self.kills: int = 0
        self.limit_kills = 10

    def __str__(self):
        if self.attack:
            return f"{self.name} {self.health}+{self.attack}"
        return f"{self.name} {self.health}"

    def lvl_up(self):
        self.lvl += 1
        self.max_health += 5
        self.limit_kills *= 2

    # __________CHECKER__________
    def have_weapon(self):
        return bool(self.attack)

    def is_alive(self):
        if self.health > 0:
            return True
        return False

    # __________ACTION__________
    def attack_enemy(self, enemy):
        if self.have_weapon():
            if enemy.health >= self.attack:
                enemy.health -= self.attack
                self.attack -= self.attack
            else:
                self.attack -= enemy.health
                enemy.health -= enemy.health

        self.health -= enemy.health

        enemy.health -= enemy.health
        self.kills += 1

    def take_potion(self, potion):
        self.health += potion.health
        if self.health > self.max_health:
            self.health = self.max_health

    def take_weapon(self, weapon):
        self.attack = weapon.attack


import math
import time
from collections import OrderedDict

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

import utils
from agent.sarsa import Sarsa

class GeneratorB(nn.Module):
    def __init__(self, tau_dim, skill_dim, hidden_dim):
        super().__init__()
        self.skill_pred_net = nn.Sequential(nn.Linear(tau_dim, hidden_dim),
                                            nn.ReLU(),
                                            nn.Linear(hidden_dim, hidden_dim),
                                            nn.ReLU(),
                                            nn.Linear(hidden_dim, skill_dim))

        self.apply(utils.weight_init)

    def forward(self, tau):
        skill_pred = self.skill_pred_net(tau)
        return skill_pred

class Discriminator(nn.Module):
    def __init__(self, tau_dim, feature_dim, hidden_dim):
        super().__init__()
        # def SimClR :
        self.embed = nn.Sequential(nn.Linear(tau_dim, hidden_dim),
                                   nn.ReLU(),
                                   nn.Linear(hidden_dim, hidden_dim),
                                   nn.ReLU(),
                                   nn.Linear(hidden_dim, feature_dim))

        self.project_head = nn.Sequential(nn.Linear(feature_dim, hidden_dim),
                                          nn.ReLU(),
                                          nn.Linear(hidden_dim, feature_dim))
        self.apply(utils.weight_init)

    def forward(self, tau):
        features = self.embed(tau)
        features = self.project_head(features)
        return features

class OURCAgent(Sarsa):
    def __init__(self, contrastive_scale,
                 update_encoder, contrastive_update_rate,skill_dim, temperature, update_skill_every_step,
                 **kwargs):
        self.skill_dim = skill_dim
        kwargs["meta_dim"] = self.skill_dim
        super().__init__(**kwargs)
        self.contrastive_scale = contrastive_scale
        self.update_encoder = update_encoder
        self.batch_size = kwargs['batch_size']
        self.contrastive_update_rate = contrastive_update_rate
        self.temperature = temperature

        self.update_skill_every_step = update_skill_every_step
        self.tau_len = update_skill_every_step

        # create ourc
        self.gb = GeneratorB(self.obs_dim - self.skill_dim, self.skill_dim,
                             kwargs['hidden_dim']).to(kwargs['device'])

        self.discriminator = Discriminator(self.obs_dim - self.skill_dim,
                                           self.skill_dim,
                                           kwargs['hidden_dim']).to(kwargs['device'])

        # loss criterion
        self.gb_criterion = nn.CrossEntropyLoss()
        self.discriminator_criterion = nn.CrossEntropyLoss()

        # optimizers
        self.gb_opt = torch.optim.Adam(self.gb.parameters(), lr=self.lr)
        self.dis_opt = torch.optim.Adam(self.discriminator.parameters(), lr=self.lr)

        self.gb.train()
        self.discriminator.train()

        self.skill_ptr = 0

    def init_meta(self):
        skill = np.zeros(self.skill_dim, dtype=np.float32)
        skill[self.skill_ptr] = 1
        meta = OrderedDict()
        meta['skill'] = skill
        return meta

    def update_meta(self, meta, global_step, time_step, finetune=False):
        if global_step % self.update_skill_every_step == 0:
            self.skill_ptr = (self.skill_ptr + 1) % self.skill_dim
            return self.init_meta()
        return meta

    def update_gb(self, skill, gb_batch, step):
        metrics = dict()
        labels = torch.argmax(skill, dim=1)
        loss, df_accuracy = self.compute_gb_loss(gb_batch, labels)

        self.gb_opt.zero_grad()
        loss.backward()
        self.gb_opt.step()

        return metrics

    def update_contrastive(self, taus, skills):
        metrics = dict()
        features = self.discriminator(taus)
        loss = self.compute_info_nce_loss(features, skills)
        loss = torch.mean(loss)
        metrics['loss'] = loss.item()
        self.dis_opt.zero_grad()
        loss.backward()
        self.dis_opt.step()

        return metrics

    def compute_intr_reward(self, skills, tau_batch, metrics):

        # compute q(z | tau) reward
        d_pred = self.gb(tau_batch)
        d_pred_log_softmax = F.log_softmax(d_pred, dim=1)
        _, pred_z = torch.max(d_pred_log_softmax, dim=1, keepdim=True)
        gb_reward = d_pred_log_softmax[torch.arange(d_pred.shape[0]), torch.argmax(skills, dim=1)] - math.log(
            1 / self.skill_dim)
        gb_reward = gb_reward.reshape(-1, 1)

        # compute contrastive reward
        features = self.discriminator(tau_batch)

        # maximize softmax item
        contrastive_reward = torch.exp(-self.compute_info_nce_loss(features, skills))
        intri_reward = gb_reward + contrastive_reward * self.contrastive_scale
        return intri_reward

    def compute_info_nce_loss(self, features, skills):

        size = features.shape[0] // self.skill_dim

        labels = torch.argmax(skills, dim=1)
        labels = (labels.unsqueeze(0) == labels.unsqueeze(1)).long()
        labels = labels.to(self.device)

        features = F.normalize(features, dim=1)

        similarity_matrix = torch.matmul(features, features.T)

        # discard the main diagonal from both: labels and similarities matrix
        mask = torch.eye(labels.shape[0], dtype=torch.bool).to(self.device)
        labels = labels[~mask].view(labels.shape[0], -1)
        similarity_matrix = similarity_matrix[~mask].view(similarity_matrix.shape[0], -1)
        similarity_matrix = torch.exp(similarity_matrix / self.temperature)

        # don't limit update for all negative
        pick_one_positive_sample_idx = torch.argmax(labels, dim=-1, keepdim=True)
        pick_one_positive_sample_idx = torch.zeros_like(labels).scatter_(-1, pick_one_positive_sample_idx, 1)
        neg = (~labels.bool()).long()
        # select one and combine multiple positives
        positives = torch.sum(similarity_matrix * pick_one_positive_sample_idx, dim=-1, keepdim=True)
        negatives = torch.sum(similarity_matrix * neg, dim=-1, keepdim=True)

        loss = -torch.log(positives / negatives)

        return loss

    def compute_gb_loss(self, taus, skill):
        """
        DF Loss
        """
        d_pred = self.gb(taus)
        d_pred_log_softmax = F.log_softmax(d_pred, dim=1)
        _, pred_z = torch.max(d_pred_log_softmax, dim=1, keepdim=True)
        d_loss = self.gb_criterion(d_pred, skill)
        df_accuracy = torch.sum(
            torch.eq(skill,
                     pred_z.reshape(1,
                                    list(
                                        pred_z.size())[0])[0])).float() / list(
            pred_z.size())[0]
        return d_loss, df_accuracy

    def update(self, buffer, step):
        metrics = dict()
        start = time.time()
        if step % self.update_every_steps != 0:
            return metrics

        batch = buffer.sample_batch(1024)
        obs, next_obs, action, rew, done, skill, next_skill = utils.to_torch(batch.values(), self.device)
        metrics.update(self.update_contrastive(next_obs, skill))
        for i in range(self.contrastive_update_rate - 1):
            batch = buffer.sample_batch(1024)
            obs, next_obs, action, rew, done, skill, next_skill = utils.to_torch(batch.values(), self.device)
            metrics.update(self.update_contrastive(next_obs, skill))

        # update q(z | tau)
        # bucket count for less time spending
        metrics.update(self.update_gb(skill, next_obs, step))

        # compute intrinsic reward
        with torch.no_grad():
            intr_reward = self.compute_intr_reward(skill, next_obs, metrics)
        metrics["reward"] = intr_reward.mean().item()
        if not self.update_encoder:
            obs = obs.detach()
            next_obs = next_obs.detach()

        action = action.cpu().numpy().astype('int').flatten()
        obs = obs.cpu().numpy().astype('int').flatten()
        next_obs = next_obs.cpu().numpy().astype('int').flatten()
        next_action = self.act(next_obs, skill).flatten()
        skill = torch.argmax(skill, dim=1).cpu().numpy()
        intr_reward = intr_reward.cpu().numpy().flatten()
        td_error = intr_reward + self.gamma * self.Q_table[next_obs, skill, next_action] - \
                   self.Q_table[obs, skill, action]
        self.Q_table[obs, skill, action] += self.alpha * td_error
        end = time.time()
        if step % 10000 == 0:
            print("on step : ",step, metrics, "update_time:", end-start)
        return metrics


###

### starting damage 40
### starting commander damage 21
### starting infect damage 15

import time

starting_health = 40
starting_commander_health = 21
starting_infect = 15

def commander_menu():
    print("""
    1. Life Damage
    2. Commander Damage
    3. Infect Damage
    4. Exit
    """)
    choice = int(input("What would you like to do? "))
    if choice == 1:
        life_damage(int(input("How much damage? ")))
    elif choice == 2:
        commander_damage(int(input("How much Commander damage? ")))
    elif choice == 3:
        infect_damage(int(input("How much infect damage? ")))
    elif choice == 4:
        print("Goodbye.")
    else:
        print("Invalid choice.")
        commander_menu()

def commander_intro():
    print("""
    Magic The Gathering Life Counter
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Your starting health is 40.
    Your starting commander health is 21.
    Your starting infect is 15.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    """)
    commander_menu()

def health_status():
    print("\n")
    print("Your health is " + str(starting_health))
    print("Your commander health is " + str(starting_commander_health))
    print("Your infect is " + str(starting_infect))
    time.sleep(1)
    print("\n")

def life_damage(x):
    global starting_health
    starting_health -= x
    if starting_health <= 0:
        print("You died!")
        exit()
    else:
        health_status()
        commander_menu()

def commander_damage(x):
    global starting_commander_health
    starting_commander_health -= x
    if starting_commander_health <= 0:
        print("You died!")
        exit()
    else:
        health_status()
        commander_menu()

def infect_damage(x):
    global starting_infect
    starting_infect -= x
    if starting_infect <= 0:
            print("You died!")
            exit()
    else:
        health_status()
        commander_menu()

commander_intro()


class Tictactoe:
    def __init__(self):
        self.ttt = '012345678'
        self.line = ''

    def add_X(self, position):
        i = 0
        while i < 9:
            if self.ttt[i] == position and self.ttt[i]:
                self.ttt = self.ttt[:i] + 'X' + self.ttt[i+1:]

            i += 1

    def add_O(self, position):
        i = 0
        while i < 9:
            if self.ttt[i] == position and self.ttt[i]:
                self.ttt = self.ttt[:i] + 'O' + self.ttt[i+1:]

            i += 1

    def draw_ttt_no_numbers(self):
        print('+-+-+-+')
        i = 0
        j = 3
        while j <= 9:
            self.line = '|'
            while i < j:
                if self.ttt[i] in ['0','1','2','3','4','5','6','7','8']:
                    self.line += ' |'

                if self.ttt[i] == 'O':
                    self.line += 'O|'

                if self.ttt[i] == 'X':
                    self.line += 'X|'

                i += 1

            print(self.line)
            print('+-+-+-+')

            j += 3

    def draw_ttt(self):
        print('+-+-+-+')
        for i in range(0,9,3):
            print('|' + self.ttt[i] + '|' + self.ttt[i+1] + '|' + self.ttt[i+2] + '|')
            print('+-+-+-+')

    def check_lines(self):
        for i in range(0,9,3):
            if self.ttt[i] == self.ttt[i+1] == self.ttt[i+2]:
                return self.ttt[i] + ' won'
        return 'nobody won'

    def check_columns(self):
        i = 0
        while i < 3:
            if self.ttt[i] == self.ttt[i+3] == self.ttt[i+6]:
                return self.ttt[i] + ' won'

            i += 1
        return 'nobody won'

    def check_dia(self):
        if self.ttt[0] == self.ttt[4] == self.ttt[8]:
            return self.ttt[0] + ' won'
        if self.ttt[2] == self.ttt[4] == self.ttt[6]:
            return self.ttt[0] + ' won'
        return 'nobody won'

    def result_ttt(self):
        l = self.check_lines()
        c = self.check_columns()
        d = self.check_dia()

        if l == c == d == 'nobody won':
            for i in range(0,8):
                if self.ttt[i] in ['0','1','2','3','4','5','6','7','8']:
                    return 'Game not finished'
            return 'O and X tie'

        if l == 'O won' or l == 'X won':
            return l

        if c == 'O won' or c == 'X won':
            return c

        if d == 'O won' or d == 'X won':
            return d

my_ttt = Tictactoe()
#my_ttt.draw_ttt()
my_ttt.draw_ttt_no_numbers()

my_ttt.add_X('1')
my_ttt.add_X('3')
my_ttt.add_X('4')
my_ttt.add_X('6')
my_ttt.add_X('8')

my_ttt.add_O('0')
my_ttt.add_O('2')
my_ttt.add_O('5')
my_ttt.add_O('7')
my_ttt.add_X('7')

my_ttt.draw_ttt()
my_ttt.draw_ttt_no_numbers()

my_tt2 = Tictactoe()
my_tt2.add_O('0')
my_tt2.add_O('3')
my_tt2.add_O('6')
my_tt2.draw_ttt_no_numbers()
print(my_tt2.result_ttt())

#print(my_ttt.check_lines())
#print(my_ttt.check_columns())
#print(my_ttt.check_dia())
#print(my_ttt.result_ttt())


import config
import telebot
import requests
from telebot import types

bot = telebot.TeleBot(config.token)

# Декодую json
response = requests.get(config.url).json()

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
    itembtn1 = types.KeyboardButton('USD')
    itembtn2 = types.KeyboardButton('EUR')

    markup.add(itembtn1, itembtn2,)
    msg = bot.send_message(message.chat.id,
                    "Дізнатися курс ПриватБанка ", reply_markup=markup)
    bot.register_next_step_handler(msg, process_coin_step)

def process_coin_step(message):
    try:
       markup = types.ReplyKeyboardRemove(selective=False)

       for coin in response:
           if (message.text == coin['ccy']):
              bot.send_message(message.chat.id, printCoin(coin['buy'], coin['sale']),
                               reply_markup=markup, parse_mode="Markdown")

    except Exception as e:
       bot.reply_to(message, 'ooops!')

def printCoin(buy, sale):
    '''Вивід курсу користувачу'''
    return "💰 *Курс купівлі:* " + str(buy) + "\n💰 *Курс продажу:* " + str(sale)

# Enable saving next step handlers to file "./.handlers-saves/step.save".
# Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())
# saving will hapen after delay 2 seconds.
bot.enable_save_next_step_handlers(delay=2)

# Load next_step_handlers from save file (default "./.handlers-saves/step.save")
# WARNING It will work only if enable_save_next_step_handlers was called!
bot.load_next_step_handlers()

if __name__ == '__main__':
    bot.polling(none_stop=True)

Telegram bot (курс П.Б.)/telegram bot P_B_.py


import logging.handlers
import re
import sys
import tqdm

class Utilities(object):
	"""
	Utility functions.
	"""
	HEADERS = {
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
		'Accept-Language': 'en-US,en;q=0.5',
		'Accept-Encoding': 'gzip, deflate',
		'Connection': 'close'
	}

	URL_REGEX = re.compile(r'(https?:\/\/[\d\w.:-]+)', re.I)
	FORM_REGEX = re.compile(r'method[\'\"= ]{1,4}post[\'\"]?', re.I)
	OPEN_REGEX = re.compile(r'name[\'\"= ]{1,4}notesview[\'\"]?', re.I)
	ACCOUNT_REGEX = re.compile(r'/([a-f0-9]{32}/[a-f0-9]{32})', re.I)
	USER_FIELD_REGEX = re.compile(r'user.+', re.I)
	REDIRECT_FIELD_REGEX = re.compile(r'redirect.+', re.I)
	NAMES_REGEX = re.compile(r'name[\'\"= ]{1,4}notesview[\'\"]?', re.I)
	WEBADMIN_REGEX = re.compile(r'<title>.*administration</title>', re.I)
	RESTRICTED_REGEX = re.compile(r'(notes exception|not authorized)', re.I)
	VERSION_REGEX = re.compile(r'(?:version|domino administrator|domino|release)[=":\s]{0,4}([\d.]+)(?:\s|\")?', re.I)
	LINUX_USER_REGEX = re.compile(r'([a-z0-9-_].+):(.+)', re.I)
	WINDOWS_USER_REGEX = re.compile(r'(.+)\\(.+)', re.I)
	PATH_REGEX = re.compile(r'DataDirectory\s*=\s*\'(.+)\';', re.I)

	def set_logging(self):
		"""
		Configure the basic logging environment for the application.
		"""
		logger = logging.getLogger('DomiOwned')
		logger.setLevel(logging.DEBUG)
		custom_format = CustomLoggingFormatter()
		handler = logging.StreamHandler()
		handler.setFormatter(custom_format)
		logger.addHandler(handler)

		return logger

	def parse_credentials(self, value):
		"""
		Handle credentials if value is None.
		"""
		return '' if value is None else value

	def check_url(self, url):
		"""
		Check for valid base URL.
		"""
		if self.URL_REGEX.search(url):
			return self.URL_REGEX.search(url).group(1)
		else:
			self.logger.error('Invalid URL provided')
			sys.exit()

	def setup_progress(self, total):
		"""
		Setup progress bar.
		"""
		progress_bar = tqdm.tqdm(
			total=total,
			desc="Progress",
			smoothing=0.5,
			bar_format='{desc}{percentage:3.0f}%|{bar}|({n_fmt}/{total_fmt})|{elapsed} '
		)

		return progress_bar

class CustomLoggingFormatter(logging.Formatter):
	"""
	Custom logging formatter.
	"""
	DEBUG_FORMAT = "\033[1m\033[34m[*]\033[0m %(msg)s"
	INFO_FORMAT = "\033[1m\033[32m[+]\033[0m %(msg)s"
	WARN_FORMAT = "\033[1m\033[33m[!]\033[0m %(msg)s"
	ERROR_FORMAT = "\033[1m\033[31m[-]\033[0m %(msg)s"

	def __init__(self):
		super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=None, style='%')

	def format(self, record):
		orig_format = self._style._fmt

		if record.levelno == logging.DEBUG:
			self._style._fmt = CustomLoggingFormatter.DEBUG_FORMAT
		elif record.levelno == logging.INFO:
			self._style._fmt = CustomLoggingFormatter.INFO_FORMAT
		elif record.levelno == logging.WARN:
			self._style._fmt = CustomLoggingFormatter.WARN_FORMAT
		elif record.levelno == logging.ERROR:
			self._style._fmt = CustomLoggingFormatter.ERROR_FORMAT

		result = logging.Formatter.format(self, record)
		self._style._fmt = orig_format

		return result

class Banner(object):
	"""
	Domi-Owned visual banner.
	"""
	SHOW = """
         __________   __________ __________
        |          |\|          |          |\\
        |  *    *  |||  *  *  * |        * ||
        |  *    *  |||          |     *    ||
        |  *    *  |||  *  *  * |  *       ||
        |__________|||__________|__________||
        |          || `---------------------`
        |  *    *  ||
        |          ||
        |  *    *  ||
        |__________||
         `----------`

             IBM/Lotus Domino OWNage
"""