import platform

from async_service.trio import background_trio_service
import pytest
import trio

from eth2.beacon.constants import GENESIS_SLOT
from eth2.validator_client.beacon_node import BeaconNode as BeaconNodeClient
from eth2.validator_client.client import Client as ValidatorClient
from eth2.validator_client.key_store import KeyStore

# NOTE: seeing differences in ability to connect depending on platform.
# This could be specific to our trio HTTP server (somehow...) so try removing after deprecation...
local_host_name = "127.0.0.1"  # linux default
if platform.system() == "Darwin":
    local_host_name = "localhost"  # macOS variant

@pytest.mark.trio
async def test_beacon_node_and_validator_client_can_talk(
    autojump_clock,
    clock,
    beacon_node,
    eth2_config,
    chain_config,
    seconds_per_epoch,
    sample_bls_key_pairs,
    client_id,
    # NOTE: temporarily disable BLS while it standardizes
    no_op_bls,
):
    starting_head_slot = beacon_node._chain.get_canonical_head().slot
    assert starting_head_slot == GENESIS_SLOT

    async with trio.open_nursery() as nursery:
        await nursery.start(beacon_node.run)

        api_client = BeaconNodeClient(
            chain_config.genesis_time,
            f"http://{local_host_name}:{beacon_node.validator_api_port}",
            eth2_config.SECONDS_PER_SLOT,
        )
        async with api_client:
            # sanity check
            assert api_client.client_version == client_id

            key_store = KeyStore(sample_bls_key_pairs)
            validator = ValidatorClient(key_store, clock, api_client)

            with trio.move_on_after(seconds_per_epoch):
                async with background_trio_service(validator):
                    await trio.sleep(seconds_per_epoch * 2)
            nursery.cancel_scope.cancel()
    sent_operations_for_broadcast = api_client._broadcast_operations
    received_operations_for_broadcast = (
        beacon_node._validator_api_server.context._broadcast_operations
    )

    # temporary until we update to the new API
    # NOTE: with new API, remove assertion and deletion
    assert validator._duty_store._store[((1 << 64) - 1, 0)]
    del validator._duty_store._store[((1 << 64) - 1, 0)]

    # NOTE: this is the easiest condition to pass while suggesting this is working
    # As the other parts of the project shore up, we should do stricter testing to ensure
    # the operations we expect (and that they exist...) get across the gap from
    # validator to beacon node
    assert received_operations_for_broadcast.issubset(sent_operations_for_broadcast)
    assert beacon_node._chain.get_canonical_head().slot > starting_head_slot


__author__ = 'Nina Stawski'
__version__ = '1.1'

import bottle
from bottle import *
import os
from prparser import *
from tempfile import TemporaryFile
import glob
import importlib

global robotTips
global maxAm
robotTips = 8
maxAm = 150

@route('/')
def prpr():
    human = __import__('prpr_human')
    languages = list(human.PRPR.dictionary)
    return template('pages' + os.sep + 'page.html', file='', btn='', text='', alerterror=[], alertsuccess=[], tables=GetDefaultTables(), selected='tecan', version=__version__, languages = languages)

@post('/preview')
def preview():
    a = {'response' : 'error', 'config' : ['1', '2'], 'somethingelse' : {'somethign' : 'else'}}
    return json_dumps(a)

@route('/dev')
def dev():
    return template('pages' + os.sep + 'page_dev.html', version=__version__)

@route('/mf')
def mf():
    return template('pages' + os.sep + 'dev-mf.html', version=__version__)

@route('/disclaimer')
def disclaimer():
    return template('pages' + os.sep + 'disclaimer.html', version=__version__)

@route('/copyright')
def copyright_():
    return template('pages' + os.sep + 'copyright.html', version=__version__)

@post('/table')
def table():
    plateIndexes = {}
    plateNicknames = {}
    experiment = False
    tablename = request.body.read().decode()
    tabledirname = 'default_tables' + os.sep
    plateFile = open(tabledirname + tablename, "r")
    PlateFileParse(plateFile, experiment, plateNicknames, plateIndexes)
    plates = []
    for key in plateIndexes.keys():
        plates.append([key, [plateIndexes[key][0], plateIndexes[key][1]], plateNicknames[key]])
        tojs = json_dumps(plates)
    return tojs

@post('/plates')
def plates():
    a = request.body.read().decode().split('\n')[2:-2]
    plateFile = TemporaryFile(mode='r+')
    plateFile.writelines(a)
    plateFile.seek(0)
    plateIndexes = {}
    plateNicknames = {}
    experiment = False
    PlateFileParse(plateFile, experiment, plateNicknames, plateIndexes)
    plates = []
    for key in plateIndexes.keys():
        plates.append([key, [plateIndexes[key][0], plateIndexes[key][1]], plateNicknames[key]])
        tojs = json_dumps(plates)
    return tojs

@post('/mfplates')
def mfplates():
    position = request.forms.get('position', '')
    wells = request.forms.get('wells', '')
    mywells = '\n'.join(json_loads(wells))
    tablename = createMFPlate(mywells, position)
    return tablename

def createMFPlate(wells, position):
    directory = 'tables'
    mydata = position + '\n' + wells
    fileCounter = len(glob.glob1(directory, "tables_mf_*"))
    tablename = 'tables_mf_' + str(fileCounter) + '.mfp'
    tablefile = open(directory + os.sep + tablename, "wb")
    tablefile.write(bytes(mydata, 'UTF-8'))
    tablefile.close()
    return tablename

@post('/mfparse')
def mfparse():
    info = request.body.read().decode()
    if info[-3:] == 'mfp':
        tabledirname = 'default_tables' + os.sep
        with open(tabledirname + info, "r") as plateFile:
            a = plateFile.readlines()
    else:
        a = request.body.read().decode().split('\n')[4:-2]
        a[-1] = a[-1].strip()
    tojs = json_dumps(a)
    return tojs

@post('/sample')
def sample():
    platform = request.body.read().decode()
    configFile = 'prpr_sample_' + platform + '.par'
    config = open('samples/' + configFile, 'r')
    return config.readlines()

@post('/getMethods')
def getMethods():
    db = DBHandler()
    methods = db.getMethods()
    return json_dumps(methods)

@post('/getPlates')
def getPlates():
    db = DBHandler()
    plates = db.getPlates()
    return json_dumps(plates)

@post('/getconfig')
def config():
    human = __import__('prpr_human')
    languages = list(human.PRPR.dictionary)
    errorList = []
    successList = []
    platform = request.forms.get('deviceselect', '').strip()
    getconfig = request.forms.get('text', '').strip()
    language = request.forms.get('language', '').strip()
    customMethods = request.forms.get('methods', '').strip().split(',')
    if getconfig != '':
        db = DBHandler()
        global experiment
        if customMethods != ['']:
            experiment = Experiment(maxVolume=150, tips=8, db=db, platform=platform, userMethods=customMethods, language=language)
        else:
            experiment = Experiment(maxVolume=150, tips=8, platform=platform, db=db, language=language)
        expID = experiment.ID

        print('platform:', platform)

        if platform == 'tecan':
            preselected = request.forms.get('tableselect')
            data = request.files.data
            if data != '':
                fileExtension = data.filename[-3:]
                raw = data.file.read()
                tablename = 'tables' + os.sep + 'tables_' + expID + '.' + fileExtension
                tablefile = open(tablename, "wb")
                tablefile.write(raw)
                tablefile.close()
            else:
                if preselected != 'select':
                    tablename = 'default_tables' + os.sep + preselected
                else:
                    errorList.append("Please select or upload the table file for your configuration script.")
                    return template('pages' + os.sep + 'page.html', file='', btn='', text=getconfig, alerterror=errorList, alertsuccess=successList,tables=GetDefaultTables(), selected=platform, version=__version__)
        elif platform == 'microfluidics':
            preselected = request.forms.get('mftableselect')
            #note: if the platform is microfluidics
            if preselected != 'select':
                tablename = 'default_tables' + os.sep + preselected
            else:
                position = request.forms.get('position', '')
                wells = '\n'.join(request.forms.get('wells', '').strip().split(';'))
                tablename = 'tables' + os.sep + createMFPlate(wells, position)

        dirname = 'incoming' + os.sep
        filename = 'config_' + expID + '.par'
        writefile = open(dirname + filename, "w", encoding="utf-8")

        if getconfig.startswith('TABLE'):
            getconfig = '\n'.join(getconfig.split('\n')[1:]) #removing the extra 'TABLE' from the config file
        if (platform != 'human') and (platform != 'microscope'):
            list_ = ['TABLE ', tablename, '\n', '\n', getconfig] #adding the chosen/uploaded table to the config file.
        else:
            list_ = getconfig
        writefile.writelines(''.join(list_))
        writefile.close()
        readfile = open(dirname + filename, "r", encoding="utf-8")
        platform = __import__('prpr_'+ experiment.platform)

        ParseFile(readfile, experiment)

        if len(experiment.errorLogger):
            for item in experiment.errorLogger:
                errorList.append(item)
            return template('pages' + os.sep + 'page.html', file='', btn='btn-success', text=getconfig, alerterror=errorList, alertsuccess=successList, tables=GetDefaultTables(), selected=platform, version=__version__, languages=languages)

        elif experiment.testindex:
            if experiment.platform == 'human':
                platformFileExtension = 'txt'
            elif experiment.platform == 'microscope':
                platformFileExtension = 'py'
            else:
                platformFileExtension = platform.defaults.fileExtensions[tablename[-3:]]
            file = 'config' + str(expID) + '.' + platformFileExtension
            prpr = platform.PRPR(experiment.ID)
            log = 'experiment' + str(expID) + '.log'
            successList.append("Your configuration file has been successfully processed.")

            return template('pages' + os.sep + 'page.html', file=file, btn='btn-success', text=getconfig, alerterror=errorList, alertsuccess=successList, tables=GetDefaultTables(), selected=platform, version=__version__, languages=languages)

        else:
            errorList.append("Your configuration file doesn't contain any actions. Please refer to PR-PR howto guide.")
            return template('pages' + os.sep + 'page.html', file='', btn='btn-success', text=getconfig, alerterror=errorList, alertsuccess=successList, tables=GetDefaultTables(), selected=platform, version=__version__, languages=languages)

    else:
        errorList.append("Your configuration file doesn't contain any actions. Please refer to PR-PR howto guide.")
        return template('pages' + os.sep + 'page.html', file='', btn='btn-success', text=getconfig, alerterror=errorList, alertsuccess=successList, tables=GetDefaultTables(), selected=platform, version=__version__, languages=languages)

@route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')

@route('/download/<filename>')
def download(filename):
    if filename.startswith('config'):
        root = 'esc'
    elif filename.startswith('tables_mf_'):
        root = 'tables'
    else:
        root = 'logs'
    return static_file(filename, root, download=filename)

@route('/get/<filename>')
def download(filename):
    return static_file(filename, root='tables', download=filename)

def GetDefaultTables():
    """
    Getting a list of default tables from folder 'tables'
    """
    tablesDir = os.listdir('default_tables')
    tables = []
    for name in tablesDir:
        if not name.startswith('.') and (name.endswith('.ewt') or name.endswith('.gem') or name.endswith('.mfp')):
            tables.append(name)
    tables.sort()
    jsonTables = json_dumps(tables)
    return jsonTables

if __name__ == '__main__':
    bottle.debug(True)
    run(host='localhost', port=8080, reloader=True)


import os
import cv2 as cv
import sys
import numpy as np

# PATHS

# get current dir so it can work on any os
# asuming that frames dir is present in the same dir as this code
path = os.getcwd()
print("Current Directory:", path, "\n")

# no need to get parent dir
parent = os.path.dirname(path)
print("Parent directory:", parent, "\n")

'''
zero-in on the correct file(s)
'''
# for part 1
path_to_frames = os.path.join(path, "frames")
part1_path = os.path.join(path_to_frames, "000000.jpg")

# for part 2
path_to_frames = os.path.join(path, "frames")
part2_path = os.path.join(path_to_frames, "%06d.jpg")

# check if the final paths are correct
print(os.path.isfile(part1_path))
print(os.path.isfile(part2_path))

def part1():
    # read the image as a cv::Mat object and show it
    img = cv.imread(part1_path)
    if img is None:
        sys.exit("Could not read the image.")
    cv.imshow("part1 first frame color", img)

    # wait forever until user presses any key; return value is the key pressed
    k = cv.waitKey(0)

    # print the shape of the cv::Mat object (a numpy array) containing the image
    print(img.shape)
    print("rows: " + str(img.shape[0]))
    print("cols: " + str(img.shape[1]))
    print("channels: " + str(img.shape[2]))

    # double check rows:
    print("rows: ")
    print(len(img[:,0,0]))
    print(len(img[0,:,0]))
    print(len(img[0,0,:]))

    # printing the image itself
    print(img)

    # convert the image to grayscale, show it and wait
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    cv.imshow('part1 first frame gray', gray)
    k = cv.waitKey(0)

    # save gray to a png
    cv.imwrite("part1_gray.png", gray)

def part2():
    # list of grayscale frames to be averaged
    gray_list = []

    # set up video capture from frames dir
    cap = cv.VideoCapture(part2_path)

    while cap.isOpened():
        ret, frame = cap.read()

        # if frame is read correctly ret is True
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break

        # operations on the frame
        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        gray_list.append(gray)

        # display the original frame
        cv.imshow('part2 original video', frame)
        # apparently cv.waitkey(1) = 25 milliseconds
        if cv.waitKey(100) == ord('q'):
            break

    cap.release()
    cv.destroyAllWindows()

    # perform moving-object subtraction
    avg_img = np.mean(gray_list, axis=0)
    avg_img = avg_img.astype('uint8')

    cv.imshow('part2 averaged image', avg_img)
    k = cv.waitKey(0)

    cv.imwrite("part2_gray.png", avg_img)

def part3():
    im1 = cv.imread("part1_gray.png", cv.IMREAD_GRAYSCALE)
    if im1 is None:
        sys.exit("Could not read the image.")

    im2 = cv.imread("part2_gray.png", cv.IMREAD_GRAYSCALE)
    if im2 is None:
        sys.exit("Could not read the image.")

    # the absolute difference between the grayscale background image and the grayscale first frame
    abs_diff = cv.absdiff(im2, im1)
    cv.imshow('part3 absolute difference', abs_diff)
    k = cv.waitKey(0)

    # apply binary thresholding to the previous absolute difference image
    # this simple thresholding returns two outputs: the threshold that was used and the thresholded image
    ret1, thresh1 = cv.threshold(abs_diff, 40, 255, cv.THRESH_BINARY)
    cv.imshow('part3 simple thresh', thresh1)
    k = cv.waitKey(0)

    # apply Otsu's thresholding to the absolute difference image
    # Otsu's thresholding returns two outputs: the optimal threshold value and the thresholded image
    ret2, thresh2 = cv.threshold(abs_diff, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)
    cv.imshow('part3 Otsu\'s thresh', thresh2)
    k = cv.waitKey(0)

def bonus():
    # get the background image for doing absolute difference with each frame
    im2 = cv.imread("part2_gray.png", cv.IMREAD_GRAYSCALE)
    if im2 is None:
        sys.exit("Could not read the image.")

    # set up video capture from frames dir
    cap = cv.VideoCapture(part2_path)

    while cap.isOpened():
        ret, frame = cap.read()

        # if frame is read correctly ret is True
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break

        # turn the frame into grayscale
        im1 = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

        # absolute difference
        abs_diff = cv.absdiff(im2, im1)

        # thresholding
        ret, thresh = cv.threshold(abs_diff, 0, 255, cv.THRESH_BINARY+cv.THRESH_OTSU)
        #ret, thresh = cv.threshold(abs_diff, 40, 255, cv.THRESH_BINARY)
        #ret, thresh = cv.threshold(abs_diff, 40, 255, 0)

        # find the contours in the thresholded frame
        #contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
        contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

        # apparently, we don't have to draw the contours back onto the thresholded frame
        #ct_frame = cv.drawContours(thresh, contours, -1, (255,255,255), 3)

        # but instead we are supposed to draw the bounding boxes onto the thresholded frame
        for cnt in contours:
            x,y,w,h = cv.boundingRect(cnt)
            ct_frame = cv.rectangle(thresh,(x,y),(x+w,y+h),(255,255,255),1)

        # display the bounding-boxed, thresholded frame
        cv.imshow('bonus boxed thresh frame', ct_frame)
        if cv.waitKey(100) == ord('q'):
            break

    cap.release()
    cv.destroyAllWindows()

part1()
part2()
part3()
bonus()


# -*- coding: utf-8 -*-
"""
Created on Mon May  7 22:08:47 2018

@author: XIN
"""
from functools import reduce
import math
import cmath
import random
import time

def poly_eval(vec, x):
    return reduce((lambda a, b: a*x + b), vec[::-1])

#print(poly_eval([1,2,3,4],2))

def poly_add(vec1, vec2):
    while len(vec1) != len(vec2):
        if len(vec1) < len(vec2):
            vec1.append(0)
        else:
            vec2.append(0)
    return [vec1[i]+vec2[i] for i in range(len(vec1))]

#print(poly_add([1,2,3,4,11],[2,3,4,5]))

def nth_roots_of_unity(n):
    return [cmath.exp(1j*2*math.pi*i/n) for i in range(n)]

def even_odd_divide(vec):
    return vec[0::2], vec[1::2]

#print(even_odd_divide([1,2,3,4,5,6,7,8,9]))

def FFT(v):
    vec = v.copy()
    l = len(vec)
    if l == 1:
        return [(1, poly_eval(vec, 1))]
    n = 0
    while True:
        if l > 2**n:
            n += 1
        else:
            break
    vec += [0 for _ in range(2**n-l)]
#    print(vec)
    even_vec, odd_vec = even_odd_divide(vec)

    roots = nth_roots_of_unity(2**n)
#    print(len(roots))
    return [(roots[i], FFT(even_vec)[i % 2**(n-1)][1] + roots[i] * FFT(odd_vec)[i % 2**(n-1)][1]) for i in range(2**n)]
#
#def FFT2(vec):
#    return [x[1] for x in FFT(vec)[:len(vec)]]
#
#vec = [i for i in range(8)]
#ans1 = FFT(vec)
#r = nth_roots_of_unity(8)
#ans2 = [(r[i], poly_eval(vec, r[i])) for i in range(8)]
#print(ans1)
#print("=====================================================")
#print(ans2)
#print("=====================================================")
#ans3 = [round(abs(ans1[i][1] - ans2[i][1]),6) for i in range(len(ans1))]
#print(ans3)

def _IFFT(v):
    vec = v.copy()
    l = len(vec)
    if l == 1:
        return [(1, poly_eval(vec, 1))]
    n = 0
    while True:
        if l > 2**n:
            n += 1
        else:
            break
    vec += [0 for _ in range(2**n-l)]

    even_vec, odd_vec = even_odd_divide(vec)

    roots = [num.conjugate() for num in nth_roots_of_unity(2**n)]

    return [(roots[i], _IFFT(even_vec)[i % 2**(n-1)][1] + roots[i] * _IFFT(odd_vec)[i % 2**(n-1)][1]) for i in range(2**n)]

def IFFT(v):
    vec = v.copy()
    l = len(vec)
    if l == 1:
        return [(1, poly_eval(vec, 1))]
    n = 0
    while True:
        if l > 2**n:
            n += 1
        else:
            break
    return [(x[0], x[1]/2**n) for x in _IFFT(v)]

#def IFFT2(vec):
#    return [x[1] for x in IFFT(vec)[:len(vec)]]
#
#v = [1,2,3,4,5,6]
#f = FFT(v)
#print(FFT2(v))
#print(FFT(v))
#f_vec = [x[1] for x in f]
#print(f_vec)
#print(IFFT2(FFT2(v)))
#print(IFFT(f_vec))
#print([num.conjugate() for num in nth_roots_of_unity(2**4)])

def fast_poly_mul(v1, v2):
    vec1 = v1.copy()
    vec2 = v2.copy()
    l1 = len(vec1)
    l2 = len(vec2)
    l_max = l1 + l2 - 1
    n = 0
    while True:
        if l_max > 2**n:
            n += 1
        else:
            break
    vec1 += [0 for _ in range(2**n-l1)]
    vec2 += [0 for _ in range(2**n-l2)]

    f_vec1 = [x[1] for x in FFT(vec1)]
    f_vec2 = [x[1] for x in FFT(vec2)]
    f_mul = [f_vec1[i] * f_vec2[i] for i in range(len(f_vec1))]
    return [x[1] for x in IFFT(f_mul)]

degree = 17
v1 = [random.uniform(-5,5) for _ in range(degree)]
v2 = [random.uniform(-5,5) for _ in range(degree)]
t1 = time.time()
v3 = fast_poly_mul(v1, v2)
t2 = time.time()
print(t2-t1)


import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class Ventana(Gtk.Window):

    def __init__(self, imagenJ, imagenM, result):
        super().__init__(title="Resultado")
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        box2= Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        box2.pack_start(imagenJ, False, False, 0)
        box2.pack_start(imagenM, False, False, 0)
        box.pack_start(box2, False, False, 0)
        box.pack_start(Gtk.Label(label=result), False, False, 0)
        self.add(box)
        self.connect("destroy", Gtk.main_quit)


from django.shortcuts import render
from course.models import Catalog, Prerequisites

def list(request):
    data = Catalog.objects.all().values_list('code', 'name', 'credits', 'id')
    output = []
    for item in data:
        output.append([item, Prerequisites.objects.filter(cid=item[3]).values_list('prereq')])

    try:
        request.session["mode"]
        loggedin = True
    except:
        loggedin = False
    return render(request, 'list.html', {'data': output, 'nbar': 'courselist', 'loggedin': loggedin})


from ...ethercat.tests.test_data_types import (
    TestEtherCATDataType as _TestEtherCATDataType,
)
from ...hal.tests.test_data_types import TestHALDataType as _TestHALDataType
from .base_test_class import BaseLCECTestClass

class TestLCECDataType(
    BaseLCECTestClass, _TestEtherCATDataType, _TestHALDataType
):

    defined_shared_types = {
        "bit",
        "int8",
        "int16",
        "int32",
        "int64",
        "uint8",
        "uint16",
        "uint32",
        "uint64",
        "float",
        "double",
    }

    def test_igh_type_attr(self):
        for shared_name in self.defined_shared_types:
            cls = self.data_type_class.by_shared_name(shared_name)
            print("cls:", cls)
            assert hasattr(cls, "igh_type")


import sqlite3

class Test:
    con = sqlite3. connect("TestDB.db3")

    Cur = con.cursor()

    def Insert_Data(self, data1, data2, data3):
        try:
            sp1 = "INSERT INTO TsetTABLE VALUES(?, ?, ?)"
            data = (data1, data2, data3)
            self.Cur.execute(sp1, data)
        except Exception as e:
            print('error', e)
        finally:
            self.con.commit()

if __name__ == '__main__':
    SQL = Test()
    SQL.Insert_Data("1", "You", "010-1111-0000")


from django.urls import path

from .apis import (
    CommunityListCreateAPIView,
    CommunityRetrieveUpdateDestroyAPIView,
    JoinedCommunityListCreateAPIView,
)

urlpatterns = [
    # communities
    path(
        'community/',
        CommunityListCreateAPIView.as_view(),
        name='community-list-create'

    ),
    path(
        'community/<slug:slug>/',
        CommunityRetrieveUpdateDestroyAPIView.as_view(),
        name='community-retrieve-update-destroy'
    ),

    # for joining and leaving communities
    path(
        'my-communities/',
        JoinedCommunityListCreateAPIView.as_view(),
        name='joined-community-list-create'
    ),
]


import sys, pygame, math
from pygame.locals import *
import time

pygame.init()

size = width, height = 960, 540
speed = [2,2]

#store color value as a tuple
black = 0, 0, 0

#create graphical window, a new surface object
#to represent actual displayed graphics
screen = pygame.display.set_mode(size)

tiepre = pygame.image.load("finalTIE.png")
tie = pygame.transform.rotate(tiepre, 270 * math.pi / 180)

#set up utility object type named Rect, representing
#a rectangular area
tierect = tie.get_rect()

#function to load images and prepare for main()
def load_image(file):
        surface = pygame.image.load(file)
        return surface.convert()

#change icon from default pygame
loadicon = load_image('tieicon.gif')
icon = pygame.transform.scale(loadicon, (32,32))
pygame.display.set_icon(icon)
pygame.display.set_caption("Bouncy TIE")
pygame.mouse.set_visible(0)

#-------------------------load screen-----------------------
time.sleep(1)

#get image first
loadscrn = load_image('TIEloadscrn1.jpg')
screen = pygame.display.set_mode(loadscrn.get_rect().size)
loadback = pygame.Surface(loadscrn.get_rect().size)
loadback.blit(loadscrn, (0,0))
loadback.set_alpha(0)
pygame.display.flip()

#gradual fade in
for n in range(256):
        screen.fill(black)
        loadback.set_alpha(0 + n)
        screen.blit(loadback, (0,0))
        pygame.display.flip()

time.sleep(3) #hold image
pygame.mixer.music.load('tieshot1.wav')
pygame.mixer.music.play(0)

"""
#flickering fade
for n in range(256):
        screen.fill(black)
        pygame.display.flip()
        loadback.set_alpha(256-n)
        screen.blit(loadback, (0,0))
        pygame.display.flip()
"""

#gradual fade out
for n in range(256):
        screen.fill(black)
        loadback.set_alpha(256-n)
        screen.blit(loadback, (0,0))
        pygame.display.flip()

time.sleep(1)

#---------------------------------------------------------------------------

#initialize counting variable for rotations
count = 1

#create background image
pygame.mixer.music.load('Tie Fighter Attack.mp3')
pygame.mixer.music.play(-1)
while 1:

        for event in pygame.event.get():
        #if event.type in (pygame.QUIT, pygame.KEYDOWN) : sys.exit()
                if not hasattr(event, 'key'): continue
                down = event.type == KEYDOWN
                if event.key == K_ESCAPE:
                        pygame.display.quit()
                        pygame.quit()
                        sys.exit(0)

        #move method determines location on screen
        tierect = tierect.move(speed)

        #reverse velocity direction when the image hits the borders
        if tierect.left < 0 or tierect.right > width:
                speed[0] = -speed[0]
        if tierect.top < 0 or tierect.bottom > height:
                speed[1] = -speed[1]

	#fill screen with black to erase image
        screen.fill(black)

	#draw image using *surface*.blit() method
	#blit is the main method for changing onscreen pixels
        screen.blit(tie, tierect)

	#update display, since pygame manages display with double buffer
        pygame.display.flip()

	#update
        tie = pygame.transform.rotate(tiepre, count * math.pi / 180)
        tierect = tie.get_rect()
        count += 1


from machine import Pin, SPI
from gdtls import HLoader
from gd import *
from math import sin, cos #sqrt
import time

BLACK = rgb(0,0,0)
WHITE = rgb(255,255,255)

def replicate(color): # Byte
	return (color << 6) | (color << 4) | (color << 2) | color

# === PlotterClass =============================================================

class PlotterClass():
	def __init__( self, gameduino ):
		self.gd = gameduino # Gameduino instance
		self.flip = 0 # byte
		self.plotting = 0 # byte

		# Loading Eraser_code MicroCode from eraser.h
		hl = HLoader( 'eraser.h' )
		self.eraser_code = [ int(value) for value in hl.get('eraser_code') ] # Extract from: static flash_uint8_t eraser_code[] = [
		del( hl )
		# Loading Wireframe_code MicroCode from wireframe.h
		hl = HLoader( 'wireframe.h' )
		self.wireframe_code = [ int(value) for value in hl.get('wireframe_code') ]
		del( hl )

	def _erase( self ):
		color = 1 if self.flip>0 else 2
		self.plotting = 0
		self.gd.wr(J1_RESET, 1)
		self.gd.wr(COMM+7, 1)
		self.gd.wr(COMM+8, replicate(color ^ 3))
		self.gd.microcode(self.eraser_code)

	def _waitready( self ):
		while( self.gd.rd(COMM+7) ):
			time.sleep( 0.001 ) # Wait 1 ms

	def begin( self ):
		# Draw 256 sprites left to right, top to bottom, all in 4-color
		# palette mode.  By doing them in column-wise order, the address
		# calculation in setpixel is made simpler.
		# First 64 use bits 0-1, next 64 use bits 2-4, etc.
		# This gives a 256 x 256 4-color bitmap.

		#unsigned int i;
		for i in range( 256 ):
			x =     72 + 16 * ((i >> 4) & 15)  #    int x =     72 + 16 * ((i >> 4) & 15);
			y =     22 + 16 * (i & 15)         #    int y =     22 + 16 * (i & 15);
			image = i & 63         #  image 0-63
			pal   =   3 - (i >> 6) #  palettes bits in columns 3,2,1,0
			self.gd.sprite(i, x, y, image, 0x8 | (pal << 1), 0)
		self.flip = 0
		self.plotting = 0
		self._erase()
		self.show()

	def show( self ):
		self._waitready()
		if (self.flip == 1):
			self.gd.wr16(PALETTE4A, BLACK)
			self.gd.wr16(PALETTE4A + 2, WHITE)
			self.gd.wr16(PALETTE4A + 4, BLACK)
			self.gd.wr16(PALETTE4A + 6, WHITE)
		else:
			self.gd.wr16(PALETTE4A, BLACK)
			self.gd.wr16(PALETTE4A + 2, BLACK)
			self.gd.wr16(PALETTE4A + 4, WHITE)
			self.gd.wr16(PALETTE4A + 6, WHITE)
		self.flip = 1 if self.flip==0 else 0
		self._erase()

	def line( self, x0, y0, x1, y1): # Byte
		swap = 0 # Byte
		steep = abs(y1 - y0) > abs(x1 - x0)
		if steep :
			x0, y0 = y0, x0
			x1, y1 = y1, x1
			steep = 1
		else:
			steep = 0
		if x0 > x1:
			x0, x1 = x1, x0
			y0, y1 = y1, y0
		deltax = x1 - x0
		deltay = abs(y1 - y0)
		error = int( deltax / 2 )
		if y0 < y1:
			ystep = 1
		else:
			# ystep est un byte (0..255). Il faut donc utiliser un complément à deux
			# ystep = -1
			# >>> bin( -1 & 0b11111111 )
			# '0b11111111'
			ystep = 255

		x = 0
		y = y0

		self._waitready()
		if self.plotting==0 : # if( !plotting )
			self.gd.microcode( self.wireframe_code )
			self.plotting = 1
			color = 1 if self.flip == 1 else 2
			self.gd.wr(COMM+8, color << 6)

		self.gd.__wstart( COMM+0 )
		self.gd.spi.write( bytes( [x0,y0,x1,y1,steep,deltax,deltay,ystep] ) )
		self.gd.__end()

# === 3D Projection ============================================================
hl = HLoader( 'eliteships.h' )
# List of ships Pythonized from eliteships.h, static struct ship eliteships[]
# which list the available ships
eliteships = hl.get('eliteships')
NSHIP = len( eliteships )
# Name, VerticeCount, vertices_res_name, EdgesCount, edges_res_name
# eliteships = [
#	[ "ADDER", 18, "ADDER_vertices", 29, "ADDER_edges" ],
#	[ "ANACONDA", 15, "ANACONDA_vertices", 25, "ANACONDA_edges" ],

class ShipDataFacade():
	""" Small facade to gain easy access to a ship data """
	def __init__( self, eliteships, hl, ship_index ):
		self.eliteships = eliteships
		self.hl = hl # HLoader - header loader
		self.ship_index = ship_index

	@property
	def name( self ):
		return self.eliteships[self.ship_index][0]

	@property
	def vertice_count( self ):
		return int(self.eliteships[self.ship_index][1])

	@property
	def edge_count( self ):
		return int(self.eliteships[self.ship_index][3])

	@property
	def vertices( self ):
		""" Vertices data as a list """
		return self.hl.get( self.eliteships[self.ship_index][2] )

	@property
	def edges( self ):
		""" Edges data as a list """
		return self.hl.get( self.eliteships[self.ship_index][4] )

def ship_data( ship_index ):
	""" return the eliteships[x] entry but with the array of data instead of the
	 	zzz_vertices and zzz_edges name.  Returns a tuple ( Name, Vertices_count, Vertices_list, Edges_count, Edges_list )"""
	global eliteships
	global hl

	return ShipDataFacade( eliteships, hl, ship_index  )

# Transformation matrice for the vertex projection
mat = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ] # static float mat[9]

def rotation( phi ): # float
	""" Calculate the transformation matrice.

		Taken from glRotate()"""
	x = 0.57735026918962573
	y = 0.57735026918962573
	z = 0.57735026918962573

	s = sin(phi)
	c = cos(phi)

	mat = []
	mat.append( x*x*(1-c)+c   ) # mat[0]
	mat.append( x*y*(1-c)-z*s ) # mat[1]
	mat.append( x*z*(1-c)+y*s ) # mat[2]

	mat.append( y*x*(1-c)+z*s  ) # mat[3]
	mat.append( y*y*(1-c)+c    ) # mat[4]
	mat.append( y*z*(1-c)-x*s  ) # mat[5]

	mat.append( x*z*(1-c)-y*s ) # mat[6]
	mat.append( y*z*(1-c)+x*s ) # mat[7]
	mat.append( z*z*(1-c)+c   ) # mat[8]
	return mat

projected = list( (0,) * 40 * 2 ) # static byte projected[40 * 2];

def project( ship, distance ): # eliteships[x], float
	""" Make a Projection of a given ship with the projection matrix

		ship is a ShipDataFacade """
	vx = 0 # byte
	pm = ship.vertices
	pm_e = ship.edges #pm_e = pm + (s->nvertices * 3);
  	#byte *dst = projected;
	global projected
	projected_idx = 0
	x, y, z = 0, 0, 0 # Byte

	global mat
	for i in range( 0, ship.vertice_count*3,  3 ): # count from 0 to vertice_count by step of 3
		x = int( pm[i] )
		y = int( pm[i+1] )
		z = int( pm[i+2] )
		xx = x * mat[0] + y * mat[3] + z * mat[6] # float
		yy = x * mat[1] + y * mat[4] + z * mat[7]
		zz = x * mat[2] + y * mat[5] + z * mat[8] + distance
		q = 140 / (140 + zz) # float
		projected[projected_idx] = int(128 + xx * q) # *dst++ = byte(128 + xx * q);
		projected_idx += 1
		projected[projected_idx] = int(128 + yy * q)
		projected_idx += 1

def draw( ship, plotter, distance ): # distance as float
	""" draw a given ship on the screen

	ship is a ShipDataFacade """

	# project the ship to a flat screen (will update projected)
	project( ship, distance )

	pe = ship.edges
	# flash_uint8_t *pe_e = pe + (s->nedges * 2);
	# while (pe < pe_e) {
	global projected
	for i in range( 0, (ship.edge_count)*2, 2 ):
		v0 =  int(pe[i]) << 1
		v1 =  int(pe[i+1]) << 1
		#Plotter.line(v0[0], v0[1], v1[0], v1[1]);
		plotter.line( projected[v0], projected[v0+1], projected[v1], projected[v1+1] )

# === Setup ====================================================================
print( 'Setup...' )

# Initialize the SPI Bus (on ESP8266-EVB)
# Software SPI
#    spi = SPI(-1, baudrate=4000000, polarity=1, phase=0, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
# Hardware SPI
spi = SPI(2) # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init( baudrate=20000000, phase=0, polarity=0 ) # raise @ 20 Mhz
# We must manage the SS signal ourself
ss = Pin( Pin.board.Y5, Pin.OUT )

# Gameduino Lib
gd = Gameduino( spi, ss )
gd.begin()
gd.ascii()
gd.putstr(0, 0, "Accelerated wireframe");

plotter = PlotterClass( gd )
plotter.begin()

# === Loop =====================================================================
print( 'Loop...')

sn = 0    # Ship number, 0-NSHIPS
phi = 0.0 # Current rotation angle
every = 0 # byte
tprev = time.ticks_ms() # time

def cycle( ship, distance ):
	""" Draw one frame of ship """
	global gd
	global plotter
	global mat
	global phi
	global tprev
	mat = rotation( phi ) # Transformation matrice
	phi += 0.02

	draw( ship, plotter, distance);

	# GD.waitvblank(); // uncomment this to sync to 72Hz frame rate
	plotter.show()

	# Update the FPS statistic (every 4 iteration)
	global every
	every += 1
	if every == 4:
		t = time.ticks_ms()
		every = 0

		fps = 4 * 1000/(t-tprev)
		gd.putstr(36, 0, "%.3f fps  " % fps )
		tprev = t

# -- effective loop --
# print( hl.indexes )
while True:
	_ship = ship_data( sn ) # sn: Ship Number
	name = "%s - ship %s of %s" % (_ship.name, sn+1, NSHIP )

	print( name )

	gd.putstr(0, 36, "                                                  ")
	gd.putstr(25 - int(len(name)/2), 36, name)

	# Zoom in + rotate
	for d in range( 100 ):
		cycle( _ship, 1000 - 10*d ) # Variation of distance
	# Stay in front + rotate
	for d in range( 76*2 ):
		cycle( _ship, 0.0 )
	# Zoom out + rotate
	for d in range( 100 ):
		cycle( _ship, 10 * d )

	# Next SHIP
	sn = (sn + 1) % NSHIP

# Finally
print( "That's all folks" )


T = int(input())

for tc in range(1, T+1):
    case = list(input())
    stack = []

    for item in case:
        # 스택이 비어있으면 append
        if len(stack) == 0:
            stack.append(item)
            continue

        # 스택 마지막문자가 새로 들어올 문자랑 같으면 pop 아니면 append
        if stack[-1] == item:
            stack.pop()
        else:
            stack.append(item)

    print(f'#{tc} {len(stack)}')


from flask import Flask, render_template
import math
app = Flask(__name__)

@app.route('/static/<content>')
def static_content(content):
    return render_template(content)

@app.route('/<figurageometrica>/<volumenosurfacearea>/<parametro1>', methods=['GET'])
#esto es para figuras que necesitan 1 parametro
def CalculoCon1Parametro(figurageometrica,volumenosurfacearea,parametro1):
  # Su código va aquí
  parametro1 = int(parametro1)
  if parametro1 <= 0:
    return 'El parámetro ingresado es incorrecto.'
  else:
    if figurageometrica=='cube': #esto es si es un cubo
      if volumenosurfacearea=='volumen':
        volumen= (int(parametro1))**3
        return f'El volumen del cubo es: {volumen}'
      elif volumenosurfacearea=='surfacearea':
        surfacearea=6*(int(parametro1))**2
        surfacearea=round(surfacearea,2)
        return f'El area de la supercificie del cubo es: {surfacearea}'
      else:
        return "Ingrese área o volumen, por favor"

    if figurageometrica=='sphere':#esto es si es una esfera
      if volumenosurfacearea=='volumen':
        volumen= (4/3)*math.pi*(parametro1)**3
        return f'El volumen de la esfera es:  {volumen}'
      elif volumenosurfacearea=='surfacearea':
        surfacearea=4*math.pi*(parametro1)**2
        surfacearea=round(surfacearea,2)
        return f'El area de la superficie de la esfera es:  {surfacearea}'
      else:
        return "Opción invalida"

    if figurageometrica=='regular tetrahedron':#esto es si es tetrahedro
      if volumenosurfacearea=='volumen':
        volumen= (1/12)*math.sqrt(2)*(parametro1)**3
        return f'El volumen del tetrahedro regular es: {volumen}'
      elif volumenosurfacearea=='surfacearea':
        surfacearea=math.sqrt(3)*(parametro1)**2
        surfacearea=round(surfacearea,2)
        return f'El area de la superficie del tetrahedro regular es :  {surfacearea}'
      else:
        return "Opción invalida"

@app.route('/<figurageometrica>/<volumenosurfacearea>/<parametro1>/<parametro2>', methods=['GET'])
#esto es para figuras que necesitan 2 parametros
def CalculoCon2parametros(figurageometrica,volumenosurfacearea,parametro1,parametro2):
    # Su código va aquí
    parametro1=int(parametro1)
    parametro2=int(parametro2)
    if parametro1 <=0 or parametro2 <=0:
      return 'Uno o todos los parámetros ingresados son incorrectos.'
    else:
      if figurageometrica=='general cone' or figurageometrica=='general pyramid':
        if volumenosurfacearea=='volumen':
          volumen = (1/3)*parametro1*parametro2
          volumen=round(volumen,2)
          return f'El volumen del general cone es: {volumen}'

      if figurageometrica=='right cicular cone':
        if volumenosurfacearea=='volumen':
          volumen = (1/3)*math.pi*((parametro1)**2)*parametro2
          volumen=round(volumen,2)
          return f'El volumen del right circular cone es: {volumen}'
        elif volumenosurfacearea=='surfacearea':
          surfacearea = math.pi*(parametro1)*(math.sqrt(((parametro1)**2)+((parametro2)**2))) + (math.pi*((parametro1)**2))
          surfacearea=round(surfacearea,2)
          return f'El área de la superficie del rigth circular cone es: {surfacearea}'
        else:
          return("opción invalida")

      if figurageometrica=='right cicular cylinder':
        if volumenosurfacearea=='volumen':
          volumen = math.pi*((parametro1)**2)*parametro2
          volumen=round(volumen,2)
          return f'El volumen del right circular cylinder es: {volumen}'
        elif volumenosurfacearea=='surfacearea':
          surfacearea = (2*math.pi*parametro1*parametro2) + (2*math.pi*((parametro1)**2))
          surfacearea=round(surfacearea,2)
          return f'El área de superficie del right circular cylinder es: {surfacearea}'
        else:
          return("Opción invalida")

      if figurageometrica=='square pyramid':
        if volumenosurfacearea=='volumen':
          volumen = (1/3)*((parametro1)**2)*parametro2
          volumen=round(volumen,2)
          return f'El volumen del {figurageometrica} es: {volumen}'
        elif volumenosurfacearea=='surfacearea':
          surfacearea = parametro1*(parametro1+ (math.sqrt((parametro1**2)+(4*(parametro2**2)))))
          surfacearea=round(surfacearea,2)
          return f'El area de superficie del {figurageometrica} es:  {surfacearea}'
        else:
          return("Opción invalida")

      if figurageometrica=='torus':
        if volumenosurfacearea=='volumen':
          volumen = 2*(math.pi**2)*(parametro1**2)*parametro2
          volumen=round(volumen,2)
          return f'El volumen del {figurageometrica} es:{volumen}'
        elif volumenosurfacearea=='surfacearea':
          surfacearea = 4*(math.pi**2)*parametro1*parametro2
          surfacearea=round(surfacearea,2)
          return f'El área de superficie del {figurageometrica} es: {surfacearea}'
        else:
          return("Opción invalida")

@app.route('/<figurageometrica>/<volumenosurfacearea>/<parametro1>/<parametro2>/<parametro3>', methods=['GET'])
#esto es para figuras que necesitan 3 parametros
def CalculoCon3Parametros(figurageometrica,volumenosurfacearea,parametro1,parametro2,parametro3):
  parametro1=int(parametro1)
  parametro2=int(parametro2)
  parametro3=int(parametro3)
  if parametro1 <=0 or parametro2 <=0 or parametro3 <=0:
      return 'Uno o todos los parámetros ingresados son incorrectos.'
  else:
    if figurageometrica =="rectangulo solido":
      if volumenosurfacearea=="volumen":
        volumen=(parametro1*parametro2*parametro3)
        volumen=round(volumen,2)
        return f'El volumen del rectangulo sólido es: {volumen}'
      elif volumenosurfacearea=="surfacearea":
        surfacearea= 2*(parametro1*parametro2)+2*(parametro1*parametro3)+2*(parametro2*parametro3)
        surfacearea=round(surfacearea,2)
        return f'El área del rectangulo sólido es: {surfacearea}'
      else:
        return "opción invalida"

@app.route('/<figurageometrica>/<volumenosurfacearea>/<parametro1>/<parametro2>/<parametro3>/<parametro4>', methods=['GET'])
#esto es para figuras que necesitan 4 parametros
def calculoCon4Parametros(figurageometrica,volumenosurfacearea,parametro1,parametro2,parametro3, parametro4):
  parametro1=int(parametro1)
  parametro2=int(parametro2)
  parametro3=int(parametro3)
  parametro4=int(parametro4)
  if parametro1 <=0 or parametro2 <=0 or parametro3 <=0 or parametro4 <=0:
      return 'Uno o todos los parámetros ingresados son incorrectos.'
  else:
    if figurageometrica == "frustum of a cone":
      if volumenosurfacearea=="volumen":
        volumen = ((math.pi/3)*((parametro1**2)+(parametro1*parametro2)+(parametro2**2)))*parametro3
        volumen=round(volumen,2)
        return f'El volumen de tronco de un cono es: {volumen}'

      elif volumenosurfacearea== "surfacearea":
        area = (math.pi*parametro4)*(parametro2+parametro1)+(math.pi*parametro1**2)+(math.pi*parametro2**2)
        area= round(area,2)
        return f'El área del tronco de un cono es: {area}'

if __name__ == '__main__':
    app.secret_key = ".."
    app.run(port=8080, threaded=True, host=('127.0.0.1'))


# pylint: skip-file
import numpy as np
import pandas as pd
import umap
from sklearn.preprocessing import StandardScaler

from ferry import config, database

courses = pd.read_sql_table("courses", con=database.Engine)  # type: ignore
courses = courses.set_index("course_id")

context_vectors = pd.read_hdf(  # type: ignore
    config.DATA_DIR / "description_embeddings/context_vectors.h5",
    key="context_vectors",
)

# sort newest-first and drop title+description duplicates
courses = courses.sort_values(by="season_code", ascending=False)
courses = courses.drop_duplicates(subset=["description"], keep="first")
courses = courses.drop_duplicates(subset=["title"], keep="first")

valid_courses = set(courses.index)

# subset nonduplicate courses
context_vectors = context_vectors[context_vectors.index.isin(valid_courses)]

context_embeddings = StandardScaler().fit_transform(context_vectors.to_numpy())

# cast to float64 before UMAP
context_embeddings = context_embeddings.astype(np.float64)

# apply umap
reducer = umap.UMAP()
umap_embeddings = reducer.fit_transform(context_embeddings)

# convert embeddings to DataFrame
umap_embeddings = pd.DataFrame(
    umap_embeddings, index=context_vectors.index, columns=["umap1", "umap2"]
)

# join embeddings with courses
courses = courses.join(umap_embeddings, how="inner")

courses.to_csv(
    config.DATA_DIR / "description_embeddings/courses_context_embedded_umap.csv"
)


import random
AnaDizi = []
SiralanmisDizi = []
#dizielemansayisi = int (random.uniform(1,50))
dizielemansayisi = 5
for i in range(0,dizielemansayisi,1):
    AnaDizi.append(int(random.uniform(1,250)))
SiralanmisDizi = AnaDizi
print(AnaDizi)
def InsertionSort(SiralanmisDizi):
    Adim = 1
    for i in range(1, len(SiralanmisDizi)):
        key = SiralanmisDizi[i]
        j = i-1
        girisadim = Adim
        while j >=0 and key < SiralanmisDizi[j] :
            print("Adım:",Adim,"(giriş) | ",SiralanmisDizi[j]," vs ",key," | i = ",i," | j = ",j," | ",SiralanmisDizi)
            SiralanmisDizi[j+1] = SiralanmisDizi[j]
            j -= 1
            SiralanmisDizi[j+1] = key
            print("Adım:",Adim,"(çıkış) | i = ",i," | j = ",j," | ",SiralanmisDizi)
            Adim = Adim +1
        if girisadim == Adim:
            print("Adım:",Adim,"(çıkış) | i = ",i," | j = ",j," | ",SiralanmisDizi)
            Adim = Adim+1
    print("\n Sıralanmış dizi = ",end = "")
    for i in range(len(SiralanmisDizi)):
        if i+1 ==len(SiralanmisDizi):
            print(SiralanmisDizi[i],end = "")
        else:
            print(SiralanmisDizi[i],end = ",")

InsertionSort(SiralanmisDizi)


import scrapy

# image http://lacor.es/images/productos/53828p.jpg
#                      /images/productos/53828p.jpg
class ProductSpider(scrapy.Spider):
    name = 'product'
    allowed_domains = ['lacor.es']
    start_urls = ['http://lacor.es/eng/catalogo/chef-sets/4335/%s/' % index for index in range(1, 75)]

    def parse(self, response):
        all_books = response.xpath('//article[@class="product_pod"]')  # /html/body/div/div[2]/section

        for book in all_books:
            title = book.xpath('.//h3/a/@title').extract_first()
            price = book.xpath('.//div/p[@class="price_color"]/text()').extract_first()
            image_url = self.start_urls[0] + book.xpath('.//img[@class="thumbnail"]/@src').extract_first()
            book_url = self.start_urls[0] + book.xpath('.//h3/a/@href').extract_first()

            yield {
                'title': title,
                'price': price,
                'Image URL': image_url,
                'Book URL': book_url,
            }


import os
from os.path import join
import argparse
import sys
import numpy as np
from tqdm import tqdm
sys.path.append('.')

import json
from lib.utils.data_utils import transform2opencv
from lib.utils.vis_utils import vis_point_cloud, pcd_array2o3d
import open3d as o3d

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', type=str)
    parser.add_argument('--transform_name', type=str)
    args = parser.parse_args()
    return args

def transform_points_opengl_to_opencv(points):
    # 创建一个新的数组，因为我们不想修改原始数据
    new_points = points.copy()

    # 在OpenGL中，Z轴是向摄像机的反方向，所以我们需要翻转Z轴
    new_points[:, 2] *= -1
    new_points[:, :2] = new_points[:, [1, 0]]

    return new_points

def main(args):
    # datapaser_tranforms = json.load(open(join(args.input, 'dataparser_transforms.json')))
    # scale = datapaser_tranforms['scale']
    # global_trans = np.eye(4)
    # global_trans[:3, :4] = np.asarray(datapaser_tranforms['transform'])

    # transform2opencv = lambda x: x

    input_transforms = json.load(open(join(args.input, 'transforms.json')))
    input_poses = [transform2opencv(np.asarray(transform['transform_matrix'])) for transform in input_transforms['frames']]
    input_xyz = np.asarray([pose[:3, 3] for pose in input_poses])
    input_pcd = pcd_array2o3d(input_xyz)
    input_scene_pcd = o3d.io.read_point_cloud(join(args.input, 'exports/pcd/point_cloud.ply'))
    points = np.asarray(input_scene_pcd.points)
    points = transform_points_opengl_to_opencv(points)
    input_scene_pcd.points = o3d.utility.Vector3dVector(points)
    # o3d.visualization.draw_geometries([input_pcd, input_scene_pcd])
    # vis_point_cloud(input_xyz)

    tranforms = json.load(open(join(args.input, 'camera_paths', args.transform_name)))
    vis_poses = [transform2opencv(np.asarray(transform['camera_to_world']).reshape(4, 4)) for transform in tranforms['camera_path']]
    # vis_poses = [np.linalg.inv(np.linalg.inv(pose) @ np.linalg.inv(global_trans * scale)) for pose in vis_poses]
    # vis_scene_pcd = o3d.io.read_point_cloud(join(args.input, 'point_cloud.ply'))
    vis_xyz = np.asarray([pose[:3, 3] for pose in vis_poses])
    vis_pcd = pcd_array2o3d(vis_xyz)

    o3d.visualization.draw_geometries([vis_pcd, input_pcd, input_scene_pcd])

if __name__ == '__main__':
    args = parse_args()
    main(args)


import sys

def getLastNumAndOp(array):
    nonNumbers = set(['-', '+'])
    lastNum = 0
    lastOp = None
    for element in array:
        if element in nonNumbers:
            lastNum = 0
            lastOp = element
        elif element == ' ':
            continue
        else:
            lastNum = lastNum * 10 + element
    return lastNum, lastOp

def solve(array, Sum, count):
    if count == N:
        if Sum == 0:
            answers.append(array[:])
        return

    count += 1

    lastNum, lastOp = getLastNumAndOp(array)

    array.append('+')
    array.append(count)
    solve(array, Sum + count, count)
    array.pop()
    array.pop()

    array.append('-')
    array.append(count)
    solve(array, Sum - count, count)
    array.pop()
    array.pop()

    array.append(' ')
    array.append(count)
    newSum = 0
    if lastOp == '+':
        newSum = Sum - lastNum + lastNum * 10 + count
    elif lastOp == '-':
        newSum = Sum + lastNum - lastNum * 10 - count
    else:
        newSum = lastNum * 10 + count
    solve(array, newSum, count)
    array.pop()
    array.pop()
    return

input = sys.stdin.readline
T = int(input())
for i in range(T):
    N = int(input())
    answers = []
    solve([1], 1, 1)
    answers.sort()
    for answer in answers:
        print(''.join(map(str, answer)))
    print()


#!./venv/bin/python3
import argparse
import math
import os
import re
import tkinter
import xerox
import sys

try:
    import tkinter as tk
    from tkinter import ttk
    gui_possible = True
except ModuleNotFoundError:
    gui_possible = False

def send_to_clipboard(formatted_msg):
    print(formatted_msg)
    try:
        xerox.copy(formatted_msg)
    except xerox.XclipNotFound:
        print('Unable to copy to clipboard. You must install xclip on your Linux system.')
    except Exception as e:
        print(f'Unhandled exception: {e}')

VALID_TAGS = {
    "Hy Newn": "hy",
    "Character 2": "c2",
}

parser = argparse.ArgumentParser()
parser.add_argument('--tag', type=str, choices=VALID_TAGS.values(), default=None)
parser.add_argument('--msg', type=str, nargs="*", default=None)
parser.add_argument('--file', type=str, default=None)
parser.add_argument('--clipboard', action='store_true')
parser.add_argument('--gui', action='store_true')

arg = parser.parse_args()

if arg.gui:

    if not gui_possible:
        print("GUI is not available. Please install the tkinter package for your operating system.")
        sys.exit()

    def convert_action(*_):
        try:
            tag = VALID_TAGS[tag_input_box.get()]
        except KeyError:
            tag = tag_input_box.get()
        except NameError:
            tag = ""
        try:
            action_text = input_box.get("1.0", tk.END)
            pattern1 = '\s"'
            pattern2 = '"\s'
            pattern3 = '"\n'
            action_text = re.sub(pattern1, ' "**', action_text)
            action_text = re.sub(pattern2, '**" ', action_text)
            action_text = re.sub(pattern3, '**"', action_text)
        except:
            pass
        try:
            output_box.delete("1.0", tk.END)
        except tkinter.TclError as e:
            print(f"Captured Exception: {e}")
        output_box.insert("1.0", f"{tag}:{action_text}")

    def clear_input_box():
        input_box.delete("1.0", tk.END)
        convert_action()

    # Set up main window
    root = tk.Tk()
    root.title("SWLW Action Formatter")
    tag = tk.StringVar()
    tag.trace('w', convert_action)
    input_text = tk.StringVar()
    input_text.trace('w', convert_action)

    # Configure widgets

    ## Text box for action entry, and vertical scrollbar
    ### Input Box and Vertical Scroll Bar
    input_box = tk.Text(root, wrap=tk.WORD, height=3)
    input_vsb = ttk.Scrollbar(root, command=input_box.yview, orient="vertical")
    input_box.configure(yscrollcommand=input_vsb.set)
    input_box.grid(column=2, row=1, rowspan=3, padx=1, pady=1, sticky=tk.NS)
    input_vsb.grid(column=3, row=1, rowspan=3, padx=0, pady=0, sticky=tk.NS)

    ### Text box for action output and horizontal scrollbar
    output_box = tk.Text(root, wrap=tk.NONE, height=1)
    output_hsb = ttk.Scrollbar(root, command=output_box.xview, orient="horizontal")
    output_box.configure(xscrollcommand=output_hsb.set)
    output_box.grid(column=2, row=4, padx=1, pady=1, sticky=tk.NSEW)
    output_hsb.grid(column=2, row=5, padx=1, pady=0, sticky=tk.NSEW)

    ## Input boxes
    ### List of Character Tags
    tag_input_box = ttk.Combobox(values=list(VALID_TAGS.keys()), textvariable=tag, width=8)
    tag_input_box.current(0)
    tag_input_box.grid(column=1, row=1, columnspan=2, sticky=tk.NW, padx=1, pady=1)

    ## Buttons
    clr_button = ttk.Button(root, text='Clear', command=clear_input_box)
    clr_button.grid(column=1, row=2, sticky=tk.W, padx=1, pady=1)
    conv_button = ttk.Button(root, text='Convert', command=convert_action)
    conv_button.grid(column=1, row=3, sticky=tk.W, padx=1, pady=1)
    copy_button = ttk.Button(root, text='Copy', command=lambda:send_to_clipboard(output_box.get("1.0", tk.END)[:-1]))
    copy_button.grid(column=1, row=4, sticky=tk.W, padx=1, pady=1)

    # Binds
    input_box.bind('<Return>', convert_action)
    input_box.bind('<Button-1>', convert_action)
    input_box.bind('<Escape>', lambda e: clear_input_box())
    input_box.bind('<Double-3>', lambda e: clear_input_box())
    root.mainloop()
    sys.exit()

if arg.file:
    print("Files aren't yet supported. Exiting.")
    sys.exit()

if arg.msg:
    # Pull msg into single string from list
    formatted_msg = f'{arg.tag}:'
    for word in arg.msg:
        formatted_msg += f'"**{word}**" ' if ' ' in word else f'{word} '
else:
    print("No message found.")
    sys.exit()

if arg.clipboard:
    send_to_clipboard(formatted_msg)
else:
    print(formatted_msg)


from typing import Optional, List

from src.model.frontend_model import Driver
from src.model.internal_model import Driver as InternalDriver
from src.repositories.driver_repository import AbstractDriverRepository

def add_driver_usecase(driver_repository: AbstractDriverRepository, name: str, surname: str, pesel: str,
                       phone: str) -> Driver:
    driver = driver_repository.add(first_name=name, last_name=surname, pesel=pesel, phone=phone)
    return Driver.form_internal(driver)

def get_driver_usecase(driver_repository: AbstractDriverRepository, driver_id) -> Driver:
    return Driver.form_internal(driver_repository.get(driver_id))

def get_all_drivers_usecase(driver_repository: AbstractDriverRepository) -> List[Driver]:
    return [Driver.form_internal(driver) for driver in driver_repository.get_all()]

def update_driver_use_case(driver_repository: AbstractDriverRepository, name: Optional[str], surname: Optional[str],
                           pesel: Optional[str], driver_id: str,
                           phone: Optional[str]
                           ) -> Driver:
    old_driver = driver_repository.get(driver_id)
    new_driver = InternalDriver(
        first_name=name or old_driver.first_name,
        last_name=surname or old_driver.last_name,
        phone=phone or old_driver.phone,
        PESEL=pesel or old_driver.PESEL,
        id=driver_id
    )
    driver_repository.update(driver_id, new_driver)
    return Driver.form_internal(new_driver)


def height(element):
    if element not in tree:
        return 0
    else:
        return 1 + height(tree[element])

tree = {}

if __name__ == '__main__':
	n = int(input())
	for i in range(n - 1):
	    child, parent = input().split()
	    tree[child] = parent

	heights = {}
	for element in set(tree.keys()).union(set(tree.values())):
	    heights[element] = height(element)

	for key, value in sorted(heights.items()):
	    print(key, value)


import statistics

n = int(input())
xs, ys = [], []
for i in range(n):
    x, y = map(int, input().split())
    xs.append(x)
    ys.append(y)

def m_d(x1, y1, x2, y2):
    return abs(x1 - x2) + abs(y1 - y2)

xc, yc = statistics.median(xs), statistics.median(ys)
print(int(sum(m_d(x, y, xc, yc) for x, y in zip(xs, ys))))


"""
Czytamy z JSON
http://api.nbp.pl/api/exchangerates/rates/a/usd/2022-09-01/2022-12-01/?format=json
Wykorzystamy:
https://requests.readthedocs.io/en/latest/
"""

import requests
import matplotlib.pyplot as plt

wal = ("usd", "chf", "gbp")
od = "2021-12-01"
do = "2022-12-01"

#print(dane)
wartosci2 = []

def get_curr(waluta, data_od, data_do):
    wartosci = []
    api_link = f"http://api.nbp.pl/api/exchangerates/rates/a/{waluta}/{data_od}/{data_do}/?format=json"
    r_api = requests.get(api_link)
    print(r_api)
    dane = r_api.json()
    for day in dane["rates"]:
        wartosci.append(day["mid"])
    return wartosci

title = f""" KURS {(wal)}
        od {od}  do {do}"""
for waluta in wal:
    get_curr(wal, od, do)

print(wartosci2)
plt.title(title)

x_points = [x for x in range(len(wartosci2))]
plt.plot(x_points, wartosci2)
plt.grid()
plt.show()


"""The one and only module for the sake of documentation."""
from pandas import DataFrame

class OneManyModel:
    """Uses an experiment from 1 VM and another with different amounts."""

    def __init__(self, one_vm_model, many_vms_model):
        self._one = one_vm_model
        self._many = many_vms_model
        self._many_intercept_bak = many_vms_model.get_linreg().intercept_
        self._size_per_worker = None

    def predict(self, df):
        """Prediction based on number of workers and input size.

        :param df: DataFrame with workers and input cols or list of such pairs.
        """
        if isinstance(df, list):
            pairs = df
        else:
            pairs = df[['workers', 'input']].values
        return [self._predict(row) for row in pairs]

    def _predict(self, features):
        workers, size = features
        size_per_worker = size  # / workers
        self._set_intercept(size_per_worker)
        return self._many.predict([[workers]])[0]

    def _set_intercept(self, size_per_worker):
        if self._size_per_worker != size_per_worker:
            self._update_intercept(size_per_worker)
            self._size_per_worker = size_per_worker

    def _update_intercept(self, size_per_worker):
        df = DataFrame({'workers': [1], 'input': [size_per_worker]})
        df['ms'] = self._one.predict(df.drop('workers', axis=1))
        self._many.set_intercept(df.drop('input', axis=1))


from ml3.parser.parser import Rules
from ml3.compiler.enums import RawType

class SymbolTable():

    def __init__(self):
        self._functions_ = {Rules.variable_assignment: self._variable_assignment,
                }
        self._BSS_ = BSS()

    def symbolize(self, grammar_node):
        assert grammar_node.type == Rules.grammar
        for node in grammar_node.children:
            try:
                func = self._functions_[node.type]
                func(node)
                #print(self._BSS_)
            except:
                pass

    def _variable_assignment(self, node):
        # Need a flag for local scopes if it becomes an issue.
        assert node.type == Rules.variable_assignment
        type = node.children[0].type
        name = node.children[1].content

        if(type == Rules.type_int):
            size = 4 # 4 bytes 32 bit only for now
            self._BSS_.set_variable(name, size, RawType.INT)
            return
        raise NotImplementedError

    def get_variable(self, name):
        # Once I have multiple segments need to check them all but don't right now.
        return self._BSS_.get_variable(name=name)

    def __repr__(self):
        response = "Symbol Table\n"
        response += self._BSS_.__repr__()
        return response

    def set_offsets(self, bss_offset):
        self._BSS_.set_offset(bss_offset)

class BSS():
    "Uninitialized Global Segment"

    def __init__(self):
        self.__stack__ = []
        self._lookup_position_dict_ = {}
        self.raw_size = 0
        self.position = 0

    def set_variable(self, name: str, size: str, type: RawType):
        self.__stack__.append([name, size, type, self.raw_size])
        self._lookup_position_dict_[name] = len(self.__stack__) -1
        self.raw_size += size
        self.position += 1
        return self.position - 1

    def update_variable(self, position, value):
        self.__stack__[position][4] = value

    def get_variable(self, position_in_arr: int = None, name: str = None):
        if(position_in_arr == None and name == None):
            raise Exception("One or the other argument must have a value")
        if(name != None):
            position_in_arr = self._lookup_position_dict_[name]
        return self.__stack__[position_in_arr]

    def __repr__(self):
        response = f"    BSS, Total Size in Bytes = {self.raw_size}\n"
        for i in self.__stack__:
            response += "        " + str(i) + "\n"
        return response

    def set_offset(self, offset: int):
        """Modifies the offset position by the offset. This is necessary because
        it's not possible to know the memory location until you know the desired entrypoint.
        Which would depend on the size of the total file. """
        for item in self.__stack__:
            item[3] = item[3] + offset


#!/usr/bin/env python
import ctypes
import math
import os
import socket
import struct
import sys

import cv2
import numpy
import rospkg
import rospy
import sensor_msgs.point_cloud2 as pc2
from cork_classifier.srv import ClassifyCork
from cv_bridge import CvBridge
from sensor_msgs.msg import Image, PointCloud2

from Classifier import classify, loadCNN

name = 'belly_right'
img_id = 100

MODEL_FILE = "produtech_model.h5"
rp = rospkg.RosPack()
BASE_PATH = rp.get_path('cork_classifier')
MODEL_PATH = BASE_PATH + "/models/" + MODEL_FILE
print(MODEL_PATH)

# model = loadCNN(MODEL_PATH)
# print(model)

def getCorkBoundingRect(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(gray,250,255,0)

    kernel = numpy.ones((2,2), numpy.uint8)
    thresh = cv2.erode(thresh, kernel, iterations=2)
    # thresh = cv2.dilate(thresh, kernel, iterations=5)

    contour_len = -1

    while(contour_len != 2):
        thresh = cv2.erode(thresh, kernel, iterations=1)
        contours, hierarchy = cv2.findContours(thresh, 1,  cv2.CHAIN_APPROX_SIMPLE)
        contour_len = len(contours)

    max_cont = None
    max_area = 0

    cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

    conts = []
    for c in contours:
        if(cv2.contourArea(c) > 100 and cv2.contourArea(c) < 30000):
            if cv2.contourArea(c) > max_area:
                max_cont = c
                max_area = cv2.contourArea(c)
            conts.append(c)

    cnt = cv2.minAreaRect(max_cont)
    box = cv2.boxPoints(cnt)
    box = numpy.intp(box)

    return box

def unskewImage(img, rect):

    tl = rect[0]
    tr = rect[1]
    br = rect[2]
    bl = rect[3]

    widthA = math.sqrt(math.pow(br[0] - bl[0], 2) + (math.pow(br[1] - bl[1], 2)))
    widthB = math.sqrt(math.pow(tr[0] - tl[0], 2) + (math.pow(tr[1] - tl[1], 2)))
    maxWidth = max(int(widthA), int(widthB))

    heightA = math.sqrt(math.pow(tr[0] - br[0], 2) + (math.pow(tr[1] - br[1], 2)))
    heightB = math.sqrt(math.pow(tl[0] - bl[0], 2) + (math.pow(tl[1] - bl[1], 2)))
    maxHeight = max(int(heightA), int(heightB))

    pts1 = numpy.float32([tl, tr, br, bl])
    pts2 = numpy.float32([[0,0], [maxWidth-1,0], [maxWidth-1, maxHeight-1], [0,maxHeight-1]])
    M = cv2.getPerspectiveTransform(pts1,pts2)
    dst = cv2.warpPerspective(img,M,(maxWidth-1,maxHeight-1))

    return dst

''' Apply contours etc. Get a bounding rectangle of the cork and unskew it. Finally get the desired pixels from the
    image_raw image.'''
def getClassifiableCorkImage(raw_image, cork_img):

    box = getCorkBoundingRect(cork_img) # Get the 2d bounding box of the cork piece

    unskewed = unskewImage(raw_image, box) # unskew if necessary

    global img_id

    if unskewed.shape[0] < unskewed.shape[1]:
        unskewed = cv2.rotate(unskewed, cv2.cv2.ROTATE_90_CLOCKWISE)

    return unskewed

def classify_cork_piece(data):

    # data = data.cork_cloud
    br = CvBridge()
    # cork_img contains the cropped rgb part of the rgb-d group
    cork_img = br.imgmsg_to_cv2(data.cork_cloud, 'bgr8')
    cork_img[numpy.where((cork_img==[0,0,0]).all(axis=2))] = [255, 255, 255] # replace black bg with white
    # raw image is the pure rgb image
    raw_image = br.imgmsg_to_cv2(data.raw_image, 'bgr8')

    # cv2.imshow("image", raw_image)
    # cv2.waitKey()
    img = getClassifiableCorkImage(raw_image, cork_img)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    (classification_category, classification_accuracy) = classify(gray, MODEL_PATH)

    return [classification_category, classification_accuracy]
    # return ['', 0.0]

if __name__ == '__main__':

    try:
        rospy.init_node('cork_classification', anonymous=False)

        s = rospy.Service("classify_cork", ClassifyCork, classify_cork_piece)

        rospy.spin()
    except rospy.ROSInterruptException:
        pass

    # print("ok")

    # for i in range(0, 179):


# import unittest
# from unittest.mock import patch
# import io

# def ethics(filosopher="Immanuel Kant"):
#     ontology = f"Don't quote {filosopher} on AI ethics"
#     print(ontology)

# class EthicsTestCase(unittest.TestCase):
#     @patch('sys.stdout', new_callable=io.StringIO)
#     def test_ethics(self, mock_stdout):
#         ethics()
#         self.assertEqual(mock_stdout.getvalue().strip(), "Don't quote Immanuel Kant on AI ethics")

# # Run the test
# if __name__ == '__main__':
#     unittest.main()

# --------------------------------------------------
import logging
import webbrowser

def access_www(url):
    if not url.startswith("https://"):
        logging.warning("Please use https:// in the URL.")
    else:
        webbrowser.open(url)

def ethics(philosopher="Immanuel Kant"):
    dead_philosophers = ["Immanuel Kant", "Plato", "Aristotle", "René Descartes", "Friedrich Nietzsche"]
    if philosopher in dead_philosophers:
        logging.warning(f"{philosopher} is dead.")
    else:
        website_url = "https://plato.stanford.edu/entries/artificial-intelligence/"
        access_www(website_url)

def main():
    logging.basicConfig(level=logging.INFO)
    ethics()

if __name__ == '__main__':
    main()


"""View definitions for the surfaces router."""
import logging

import fastapi
from fastapi import status

from src.core import settings, utils
from src.routers.surfaces import controller, schemas

config = settings.get_settings()
LOGGER_NAME = config.LOGGER_NAME

logger = logging.getLogger(LOGGER_NAME)

router = fastapi.APIRouter(prefix="/surfaces", tags=["surfaces"])

@router.get("/hemispheres", responses={status.HTTP_200_OK: {"model": schemas.Surface}})
def get_hemispheres(
    response: fastapi.Response,
    species: str = fastapi.Query(
        ..., example="human", description="The species to fetch the hemispheres for."
    ),
    side: str = fastapi.Query(
        ..., example="left", description="The hemisphere to fetch the surfaces for."
    ),
) -> schemas.Surface:
    """Fetches the human and macaque hemisphere surfaces.

    Args:
        species: The species to fetch the hemispheres for, valid values are
            'human' and 'macaque'.
        side: The hemisphere to fetch the surfaces for, valid values are 'left' and
            'right'.

    Returns:
        A Pydantic BaseClass containing the surface.
    """
    logger.info("Calling GET /surfaces/hemispheres endpoint.")
    response = utils.add_cache_control(response)
    return controller.get_hemispheres(species, side)


services = data.get("services")  # type: list
image_url = data.get("image_url")
title = data.get("title")
message = data.get("message")

if services and message:
    for service in services:
        service_data = {"message": message}
        if image_url:
            service_data["data"] = {"image": {"url": image_url}}
        if title:
            service_data["title"] = title
        hass.services.call("notify", service, service_data)
else:
    logger.error(f"Not all required parameters were provided. message: {message}, title: {title}, image_url: {image_url}, services: {services}")


import logging
import configparser
class userlogging:
    def loggingOut(self,S_Level,G_Level,formatter=None):
        my_logger=logging.Logger("DSDK")#创建收集器
        my_logger.setLevel(S_Level)#设置收集器的收集级别`
        sh=logging.StreamHandler()#指定日志输出到控制台
        sh.setLevel(G_Level)
        #fh=logging.FileHandler("log.txt",encoding="utf-8")#指定日志输出到文件
        #fh.setLevel(G_Level)
        #设置格式
        formatter_1=logging.Formatter(formatter)#格式化输出
        sh.setFormatter(formatter_1) #控制台日志添加格式化输出
        #fh.setFormatter(formatter_1)#文件日志增加控制台输出
        #对接收集器
        my_logger.addHandler(sh)
        #my_logger.addHandler(fh)
        return my_logger

def read_conf():
    cf=configparser.RawConfigParser()
    cf.read(r"G:\pythonxiangmu1\interface_auto_cases\config\registerconf.conf",encoding="utf-8")
    S_Level=eval(cf.get("LEVEL","S_Level"))
    G_Level=eval(cf.get("LEVEL","S_Level"))
    formatter_1=cf.get("FORMATTER","formatter_1")
    my=userlogging().loggingOut(S_Level[0],G_Level[0],formatter_1)
    return my


import json

from fmlaas.request_processor import IDProcessor
from fmlaas.request_processor import AuthContextProcessor
from fmlaas import get_job_table_name_from_env
from fmlaas import get_project_table_name_from_env
from fmlaas.database import DynamoDBInterface
from fmlaas.exception import RequestForbiddenException
from fmlaas.controller.submit_model_update import SubmitModelUpdateController

def lambda_handler(event, context):
    req_json = json.loads(event.get('body'))
    auth_json = event["requestContext"]["authorizer"]

    try:
        id_processor = IDProcessor(req_json)
        project_id = id_processor.get_project_id()
        job_id = id_processor.get_job_id()

        auth_context = AuthContextProcessor(auth_json)

        project_db = DynamoDBInterface(get_project_table_name_from_env())
        job_db = DynamoDBInterface(get_job_table_name_from_env())

        can_submit_model_to_job, presigned_url = SubmitModelUpdateController(project_db,
                                                                             job_db,
                                                                             project_id,
                                                                             job_id,
                                                                             auth_context).execute()

        if not can_submit_model_to_job:
            return {
                "statusCode": 400,
                "body": json.dumps({"error_msg": "Cannot submit model to this job. Either device is not active, or job is complete"})
            }
        else:
            return {
                "statusCode": 200,
                "body": json.dumps({"model_url": presigned_url})
            }
    except ValueError as error:
        return {
            "statusCode": 400,
            "body": json.dumps({"error_msg": str(error)})
        }
    except RequestForbiddenException as error:
        return {
            "statusCode": 403,
            "body": json.dumps({"error_msg": str(error)})
        }


import random, tweepy
import goodreads_scraper, hp_scraper1

# variables.

consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
fileName = "my_quotes.txt"
last_mention_file = "lastMention.txt"
mentions = []

#1151753922069114880            first mention ID
#1152263154006712322            NEXT TEST ID
#-            next id     ~~~

# setup connection to twitter.
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
# create oject for twiiter.
twitter = tweepy.API(auth)

#function that opens a file containing the last mention id that was responded to.
# it will return this ID as an int.
def getLastMention(file_name) :
    f = open(file_name, 'r')
    last_mention_id = int(f.read())
    f.close()
    return last_mention_id

#funtion that will write that last seen mention id to the mentionID file.
# returns no value.
def setLastMention(file_name, last_mention_id) :
    f = open(file_name, 'w')
    f.write(last_mention_id)
    f.close()
    return

#function that will return a set of mentions from twtter.
# return a python like list.
def getMentions(input_id) :
    print("... gathering mentions\n...\n...")
    mentions = twitter.mentions_timeline(input_id)
    print("... mentions gathered")
    if len(mentions) == 0 :
        print("... No new Mentions to gather since tweet ID :" + str(getLastMention(last_mention_file)))
    return mentions

#function that will respond to the mentions since the last documented mentions.
# needs to access the lastMentions.txt file.
# returns to the calling funciton.
def respondToMentions() :
    #get the last mentions id from the file.
    last_ment_id = getLastMention(last_mention_file)
    newMentions = getMentions(last_ment_id)
    #loop most recent mentions from the twitter timeline.
    for mention in reversed(newMentions) :
        #store tweet ID.
        last_ment_id = mention.id_str
        setLastMention(last_mention_file, last_ment_id)
        #store tweet text.
        last_ment_text = mention.text
        print(last_ment_id + "\t\t"+ last_ment_text)
        #store tweet sender
        at_name = "@" + mention.user.screen_name
        if "#quote" in (last_ment_text).lower() :
            search_tag = ""
            split_list = last_ment_text.split(" ")
            for word in split_list :
                if "@" in word or word.lower() == "#quote" :
                    continue
                if "#" in word :
                    word = word.strip("#")
                search_tag = search_tag + word + "+"
            print('... responding')
            print(search_tag)
            quote = goodreads_scraper.getRandomQuote(str(search_tag))
            if quote == "NONE" :
                status = at_name + " No tweets found on goodreads.com//quotes with tag of : " + search_tag
                twitter.update_status(status, int(last_ment_id))
                print(status)
            else :
                quote = at_name +" "+ quote
                twitter.update_status(quote, int(last_ment_id))
                #print(quote)
            #print(quote)
    print("\n... done")
    return

#call function to get the random quote.
# function will get a random quote from one of the two scrapers randomly.
# then it will post the quote to twitter.
# function will need an input from the user to search good reads for.
def sendQuote(input_tag) :
    # try except to catch any errors then retry to post.
    try :
        # call function and tweet.
        #   function needs an input from the user regarding a quote topic/tag
        #   for testing its Harry Potter.
        randomGR_quote = goodreads_scraper.getRandomQuote(str(input_tag))
        twitter.update_status(randomGR_quote+"\n#QuickQuote#Bot")
        print("... Random Quote Sent.")
        #print("Just posted a tweet, GR!")
        #print(randomGR_quote)
    except tweepy.TweepError :
        sendQuote(input_tag)

#def sendHPQuote() :
    #randomHP_quote = hp_scraper1.getRandomQuote()
    #twitter.update_status(randomHP_quote+"\n#QuickQuote#Bot")
    #print("Just posted a tweet! HP")
    #print(randomHP_quote)

# send a HP quote tweet out!
sendQuote("Inspiration")

# gather most recent menions.
respondToMentions()


from django.contrib import admin
from django.urls import path

from quizapp.views import IndexView, QuizView, QuizDataView, QuizSaveView
from natijaapp.views import ResultView, SignupView, LoginView, logoutView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', IndexView.as_view(), name='index'),
    path('index/<int:pk>', QuizView.as_view(), name='quiz'),
    path('result/', ResultView.as_view(), name='result'),
    path('', SignupView.as_view(), name='signup'),
    path('logout/', logoutView, name='logout'),
    path('login/', LoginView.as_view(), name='login'),
    path('<int:pk>/data/', QuizDataView.as_view(), name='quiz-data'),
    path('<int:pk>/save/', QuizSaveView.as_view(), name='quiz-save'),
]


from typing import List

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        dp = [grid[0][0] for i in range(n)]

        for i in range(1, n):
            dp[i] = dp[i-1] + grid[0][i]
        for i in range(1, m):
            dp[0] += grid[i][0]
            for j in range(1, n):
                dp[j] = min(dp[j-1], dp[j]) + grid[i][j]
        return dp[n-1]

def test(test_name, grid, expected):
    res = Solution().minPathSum(grid)
    if res == expected:
        print(test_name + ' success.')
    else:
        print(test_name + ' failed.')

if __name__ == "__main__":
    grid1 = [
        [1,3,1],
        [1,5,1],
        [4,2,1]
    ]
    expected1 = 7
    test('test1', grid1, expected1)


from employee import Employee, SalaryEmployee, HourlyEmployee, ComissionEmployee

class Company:
    def __init__(self):
        self.employees = []

    def add_employee(self, new_employee):
        self.employees.append(new_employee)

    def display_employees(self):
        print('Current Employees:')
        for i in self.employees:
            print(i.fname, i.lname)
        print('------------')

    def pay_employees(self):
        print('Paychecks:')
        for i in self.employees:
            print('Paycheck for:', i.fname, i.lname)
            print(f'Paycheck amount: ${i.calculate_paycheck():,.2f}')
        print('------------')

def main():
    my_company = Company()
    employee1 = SalaryEmployee("Sara", "Hess", 50000)
    my_company.add_employee(employee1)
    employee2 = HourlyEmployee("John", "Hess", 25, 50)
    my_company.add_employee(employee2)
    employee3 = ComissionEmployee("Roberto", "Perez", 40000, 5, 150)
    my_company.add_employee(employee3)

    my_company.display_employees()
    my_company.pay_employees()
main()


from django.shortcuts import render
from django.views import generic
import random

# Create your views here.

from .models import Delfin, Pregunta, Ubicador, Atributo
from .forms.forms import ResponderPreguntaForm
from django.shortcuts import redirect

def index(request):
    num_delfines = len(Delfin.objects.all())
    num_preguntas = len(Pregunta.objects.all())

    context = {"num_delfines": num_delfines, "num_preguntas": num_preguntas}

    return render(request, 'tests/index.html', context)

class DelfinDetailView(generic.DetailView):
    model = Delfin

def test(request):

    atributos = list(Atributo.objects.all())

    preguntas_por_atributo = 3
    cant_atributos = len(atributos)
    num_actual_preguntas = preguntas_por_atributo * cant_atributos

    pregunta_list = Pregunta.objects.all()
    pregunta_list_real = []
    num_preguntas = len(pregunta_list)

    for atributo in atributos:
        pregunta_list_real.extend(random.sample(list(Pregunta.objects.filter(atributo=atributo)), preguntas_por_atributo))

    context = {}
    context["num_preguntas"] = num_preguntas
    context["pregunta_list"] = pregunta_list_real
    context["num_actual_preguntas"] = num_actual_preguntas
    context["form"] = ResponderPreguntaForm(pregunta_list_real)

    return render(request, 'tests/test.html', context)

def responder(request):
    if request.method=='POST':

        respuesta_procesada = dict(request.POST)
        respuesta_procesada.pop("csrfmiddlewaretoken",None)

        for item,val in respuesta_procesada.items():
            respuesta_procesada[item] = int(val[0])

        if(len(respuesta_procesada)>0): ##es valido
            id_delfin = Ubicador.ubicar_respuestas(respuesta_procesada).pk
            return redirect('delfin-detail', pk=id_delfin)


from utils import *
from model import *
from config import *
import os

def predict():
    train_filename = os.path.join('data', 'train.txt')
    train_text, train_label = read_data(train_filename)

    test_filename = os.path.join('data', 'test.txt')
    test_text, _ = read_data(test_filename)
    text = test_text[1]

    print(text)

    inputs = tokenizer.encode(text,
                              return_tensors='pt')
    inputs = inputs.to(DEVICE)
    model = torch.load(MODEL_DIR + 'model_1.pth')
    y_pre = model(inputs).reshape(-1)  # 或者是y_pre[0]也行,因为y_pre是一个batch，需要进行reshape

    _, id2label = build_label_2_index(train_label)

    label = [id2label[l] for l in y_pre[1:-1]]
    print(text)
    print(label)

if __name__ == '__main__':
    predict()


from flask import Flask, render_template
from bokeh.embed import server_document
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.server.server import Server
from bokeh.themes import Theme
from tornado.ioloop import IOLoop
from bokeh.plotting import figure, output_file, show
from bokeh.plotting import ColumnDataSource
from redistimeseries.client import Client
from bokeh.layouts import column
from bokeh.models import HoverTool
from datetime import datetime
import pandas as pd

app = Flask(__name__)
redis_host='redis-cluster-ip-service'
redis_port='6379'
connection=Client(host=redis_host,port=redis_port)
def bkapp(doc):
    MSEC=1
    SEC=1*MSEC
    MIN=60*SEC
    rts=Client(host=redis_host,port=redis_port)
    def get_ts(name,_min=0,_max=-1):
        y=rts.range('Temperature', _min,_max, aggregation_type='avg', bucket_size_msec=5*MIN)
        y_time,y_value=zip(*y)
        y_time=[datetime.utcfromtimestamp(int(x)) for x in y_time]
        y_value=[v for v in y_value]
        dataset_y=dict(time=y_time,value=y_value)
        ds=ColumnDataSource(dataset_y)
        return ds
    def get_pred(name,_min=0,_max=-1):
        y=rts.range(name, _min,_max)

        y_time,y_value=zip(*y)
        y_time=[datetime.utcfromtimestamp(int(x)) for x in y_time]
        y_value=[v for v in y_value]
        dataset_y=dict(time=y_time,value=y_value)
        ds=ColumnDataSource(dataset_y)
        return ds
    def get_bounds(upper,lower,_min=0,_max=-1):
        y=rts.range(upper, _min,_max)
        y_time,y_upper=zip(*y)
        y=rts.range(lower, _min,_max)
        _,y_lower=zip(*y)
        y_time=[datetime.utcfromtimestamp(int(x)) for x in y_time]
        y_upper=[v for v in y_upper]
        y_lower=[v for v in y_lower]
        dataset_y=dict(time=y_time,y_upper=y_upper,y_lower=y_lower)
        ds=ColumnDataSource(dataset_y)
        return ds
    def draw_line(p,data,line_color=None,line_width=2,alpha=1):
        output_file("test.html")
        p.line(x='time',y='value',source=data,line_width=line_width,line_color=line_color,alpha=alpha)
        return p

    # we want to plot 3 axes and have a slider to manipulate the date range
    def make_plot(name,dim_x,dim_y,label_x,label_y,type_x="datetime",x_range=None,y_range=None,tools=None,hover=None):
        if x_range is None:
            p = figure(plot_width=dim_x,
            plot_height=dim_y,
            x_axis_label=label_x,
            y_axis_label=label_y,
            x_axis_type=type_x,
            tools=TOOLS)
            p.add_tools(hover)
            return  p
        else:
            p = figure(plot_width=dim_x,
            plot_height=dim_y,
            x_axis_label=label_x,
            y_axis_label=label_y,
            x_axis_type=type_x,
            x_range=x_range,
            tools=TOOLS)
            p.add_tools(hover)
            return  p
    dim_y=250
    dim_x=int(5*dim_y)
    TOOLS = "pan,wheel_zoom,help"
    hover=HoverTool(
        tooltips=[
            ( 'Date',   '@time{%F %H:%M}'            ),
            ( 'Value',  '@value' )
        ],

        formatters={
            'time'      : 'datetime', # use 'datetime' formatter for 'date' field
        },
    )
    p_temperature=make_plot(name="Temperature",
                            dim_x=dim_x,
                            dim_y=dim_y,
                            label_x="Time",
                            label_y="Temperature",
                            tools=TOOLS,
                            hover=hover)
    p_temperature.xaxis.visible = False

    p_trend=make_plot(name='Trend',
                        dim_x=dim_x,
                        dim_y=dim_y,
                        label_x="Time",
                        label_y="Trend",
                        x_range=p_temperature.x_range,
                        tools=TOOLS,
                        hover=hover)
    p_trend.xaxis.visible = False

    p_seasonality=make_plot(name="Daily Seasonality",
                            dim_x=dim_x,
                            dim_y=dim_y,
                            label_x="Time",
                            label_y="Daily Seasonality",
                            x_range=p_trend.x_range,
                            tools=TOOLS,
                            hover=hover)

    def draw_trend(p_trend):
        data=get_pred('trend')
        p_trend=draw_line(p_trend,data,line_color='#2171b5')

        data=get_pred('trend_upper')
        p_trend= draw_line(p_trend,data,line_color='#2171b5',alpha=0.5,line_width=1)

        data=get_pred('trend_lower')
        p_trend= draw_line(p_trend,data,line_color='#2171b5',alpha=0.5,line_width=1)

        bounds=get_bounds('trend_upper','trend_lower')
        patch=p_trend.varea(x='time',
            y1='y_upper',
            y2='y_lower',source=bounds,fill_alpha=0.2)
        patch.level = 'underlay'
        return p_trend
    def draw_seasonality(p_seasonality):
        data=get_pred('daily')
        return draw_line(p_seasonality,data,line_color='#2171b5')
    def draw_temperature(p_temperature):
        data=get_pred('yhat')
        p_temperature= draw_line(p_temperature,data,line_color='#2171b5')
        data=get_ts('Temperature')
        p_temperature.circle('time', 'value', size=2, color="black", alpha=0.25,source=data)

        data=get_pred('yhat_upper')
        p_temperature= draw_line(p_temperature,data,line_color='#2171b5',alpha=0.5,line_width=1)

        data=get_pred('yhat_lower')
        p_temperature= draw_line(p_temperature,data,line_color='#2171b5',alpha=0.5,line_width=1)

        bounds=get_bounds('yhat_upper','yhat_lower')
        patch=p_temperature.varea(x='time',
            y1='y_upper',
            y2='y_lower',source=bounds,fill_alpha=0.2)
        patch.level = 'underlay'
        return p_temperature

    p_trend=draw_trend(p_trend)
    p_seasonality=draw_seasonality(p_seasonality)
    p_temperature=draw_temperature(p_temperature)

    layout=column(p_temperature,p_trend,p_seasonality)

    doc.add_root(layout)

    # doc.theme = Theme(filename="theme.yaml")

@app.route('/', methods=['GET'])
def bkapp_page():
    script = server_document('http://localhost:5006/bkapp')
    return render_template("embed.html", script=script, template="Flask")

def bk_worker():
    # Can't pass num_procs > 1 in this configuration. If you need to run multiple
    # processes, see e.g. flask_gunicorn_embed.py
    server = Server({'/bkapp': bkapp}, io_loop=IOLoop(), allow_websocket_origin=["10.0.2.15:30037"])
    server.start()
    server.io_loop.start()

from threading import Thread
Thread(target=bk_worker).start()

if __name__ == '__main__':
    print('Opening single process Flask app with embedded Bokeh application on http://localhost:8001/')
    print()
    print('Multiple connections may block the Bokeh app in this configuration!')
    print('See "flask_gunicorn_embed.py" for one way to run multi-process')
    app.run(port=8001)


# ###################################################################
# create_expanded_list.py
#
# Created August 21st, 2023
# by Alex McColm
#
# Purpose: Take Dale's list of ~3000 easy words, and use the
# word_forms module to write a new list containing every single form
# of the words in the previous list.
# ###################################################################
import os
import sys
from word_forms.word_forms import get_word_forms

def main() -> int:
	# Open original list and new list files.
	original_file = open('dale3000', 'r')
	new_file = open('dale-expanded', 'w')

	line = original_file.readline()

	# For each line in the old file
	while line != '':
		# Get rid of newline
		word = line.strip()

		# Get dictionary of word forms, sorted by word type
		forms_dict = get_word_forms(word)

		# Put all other type of word forms into a list.
		form_list = []

		for i in list(forms_dict.values()):
			for j in i:
				form_list.append(j)

		# Filter out word forms longer than 10 letters
		form_list = list(filter(
			lambda word: (len(word) < 11), form_list))

		# Convert to a set to get rid of duplicates.
		form_set = set(form_list)

		# Add the original word to the set.
		form_set.add(word)

		# Write to expanded list file followed by newline.
		for form in form_set:
			new_file.write(form + '\n')

		# Go to the next line.
		line = original_file.readline()

	# Close original list and new list files.
	original_file.close()
	new_file.close()
	return 0

if __name__ == '__main__':
	sys.exit(main())


import tkinter as tk
from tkinter import ttk

#window
root = tk.Tk()
root.title("Buttons")
root.geometry('600x400')

# button
def button_func():
    print("A Basic Button")
    print(radio_var.get())

btn_string = tk.StringVar(value="A button with StringVar")

button = ttk.Button(master=root, text="A Button", command=button_func, textvariable=btn_string)
button.pack()

# CheckButton
checkVar = tk.IntVar(value=10)
check = ttk.Checkbutton(root,
                        text="Check Box 1",
                        command=lambda: print(checkVar.get()),
                        variable=checkVar,
                        onvalue=10,
                        offvalue=5)
check.pack()

# Radio Buttons
radio_var = tk.StringVar()
radio1 = ttk.Radiobutton(root,
                         text="Radio Button 1",
                         value="Radio 1",
                         variable=radio_var,
                         command=lambda: print(radio_var.get()))
radio1.pack()

radio2 = ttk.Radiobutton(root, text="Radio Button 2", value=2, variable=radio_var)
radio2.pack()

# exercise

# def exercise():
#     print(btn_var.get())
#     check2.set()

# variables
btn_var = tk.StringVar(value="I have been summoned")
check2 = tk.BooleanVar()

ex_check = ttk.Checkbutton(root,
                           text="Exercise Check Button",
                           variable=btn_var,
                           command=lambda: print(btn_var.get()))
ex_check.pack()

ex_radio1 = ttk.Radiobutton(root,
                            text="Exercise Radio Button 1",
                            value="A",
                            variable=btn_var,
                            command=lambda: print(check2.get()))
ex_radio1.pack()

ex_radio2 = ttk.Radiobutton(root,
                            text="Exercise Radio Button 2",
                            value="B",
                            variable=btn_var,
                            command=lambda: print(check2.get()))

ex_radio2.pack()

#exit
root.mainloop()


import paddle.fluid as fluid
import numpy as np

class SimpleLSTMRNN(fluid.Layer):
    def __init__(self,
                 hidden_size,
                 num_steps,
                 num_layers=2,
                 dropout=None):
        super(SimpleLSTMRNN, self).__init__('spelling_corrector')
        self._hidden_size = hidden_size
        self._num_layers = num_layers
        self._dropout = dropout
        self._num_steps = num_steps
        self.cell_array = []
        self.hidden_array = []

        self.weight_1_arr = []
        self.weight_2_arr = []
        self.bias_arr = []
        self.mask_array = []

        for i in range(self._num_layers):
            weight_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.XavierInitializer()),
                shape=[self._hidden_size * 2, self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.XavierInitializer()
                )
            self.weight_1_arr.append(self.add_parameter('w_%d' % i, weight_1))
            bias_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.XavierInitializer()
                    ),
                shape=[self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.Constant(0.0))
            self.bias_arr.append(self.add_parameter('b_%d' % i, bias_1))

    def forward(self, input_embedding, init_hidden=None, init_cell=None):
        cell_array = []
        hidden_array = []

        for i in range(self._num_layers):
            hidden_array.append(init_hidden[i])
            cell_array.append(init_cell[i])

        res = []
        for index in range(self._num_steps):
            step_input = input_embedding[:,index,:]
            for k in range(self._num_layers):
                pre_hidden = hidden_array[k]
                pre_cell = cell_array[k]
                weight_1 = self.weight_1_arr[k]
                bias = self.bias_arr[k]

                nn = fluid.layers.concat([step_input, pre_hidden], 1)
                gate_input = fluid.layers.matmul(x=nn, y=weight_1)

                gate_input = fluid.layers.elementwise_add(gate_input, bias)
                i, j, f, o = fluid.layers.split(
                    gate_input, num_or_sections=4, dim=-1)
                c = pre_cell * fluid.layers.sigmoid(f) + fluid.layers.sigmoid(
                    i) * fluid.layers.tanh(j)
                m = fluid.layers.tanh(c) * fluid.layers.sigmoid(o)
                hidden_array[k] = m
                cell_array[k] = c
                step_input = m

                if self._dropout is not None and self._dropout > 0.0:
                    step_input = fluid.layers.dropout(
                        step_input,
                        dropout_prob=self._dropout,
                        dropout_implementation='upscale_in_train')
            res.append(step_input)
        real_res = fluid.layers.concat(res, 1)
        real_res = fluid.layers.reshape(real_res, [ -1, self._num_steps, self._hidden_size])
        last_hidden = fluid.layers.concat(hidden_array, 1)
        last_hidden = fluid.layers.reshape(
            last_hidden, shape=[-1, self._num_layers, self._hidden_size])
        last_hidden = fluid.layers.transpose(x=last_hidden, perm=[1, 0, 2])
        last_cell = fluid.layers.concat(cell_array, 1)
        last_cell = fluid.layers.reshape(
            last_cell, shape=[-1, self._num_layers, self._hidden_size])
        last_cell = fluid.layers.transpose(x=last_cell, perm=[1, 0, 2])
        return real_res, last_hidden, last_cell


# json File Read test code

import json

with open('config.json') as json_file:
    json_data = json.load(json_file)

    dir = json_data["directory"]
    format = json_data["name_format"]

print(dir)
print(format)


#7. Realiza el promedio de 4 calificaciones de una misma materia.

# con esta funcion valido si un valor es un numero
def esNumero(num):
  try:
    # aqui intento convertirlo a numero, si no sale error, retorna true
    float(num)
    return True
  except:
    # si sale algun error convirtiendo el numero, significa que no es un numero y retorno false
    return False

# pido las calificaciones, las guardare en un arreglo
calificaciones=[]

# con range le digo cuantas vueltas quiero dar, en este casi 4, va a ir de 0 a 3
for i in range(4):
  # pido la calificacion, le sumo 1 para mostrar pq inicia en 0
  calificacion=input(f"Ingresa la calificacion {i+1}: ")

  # verifico que sea un numero
  if not esNumero(calificacion):
    print(f"'{calificacion}' no es un número")
    # si no es un numero, con break detengo el ciclo
    break
  else:
    # si es un numero, lo convierto a flotante y lo agrego al arreglo
    calificaciones.append(float(calificacion))

# verifico que las calificaciones sean 4, pq si son menos, significa que ingreso un valor que no es un numero
if len(calificaciones)<4:
  # con exit detengo la ejecucion del programa
  exit()

# obtengo la suma de los arreglos
suma=0
# recorro las calificaciones, el valor va a ser cada valor del arreglo en cada vuelta
for valor in calificaciones:
  suma+=valor # y como lo guarde convertido a flotante, puedo sumarlo

# obtengo el promedio, que es la suma de las calificaciones entre la cantidad de calificaciones
promedio=suma/len(calificaciones)

# muestro el resultado, lo redondeo ya que lo dividi y pueden salir varios decimales
print(f"El promedio de las calificaciones es {round(promedio,2)}")