import random
import numpy as np
import torch
from PIL import Image

import torchvision.transforms as tf
import torchvision.transforms.functional as F

class Compose:
    # Composes segtransforms: segtransform.Compose([segtransform.RandScale([0.5, 2.0]), segtransform.ToTensor()])
    def __init__(self, segtransform):
        self.segtransform = segtransform

    def __call__(self, args, *more_args):

        # allow for intermediate representations
        for t in self.segtransform:
            result = t(args, *more_args)
            args = result[0]
            more_args = result[1:]

        return result

class ToTensorMask:

    def __toByteTensor(self, pic):
        return torch.from_numpy(np.array(pic, np.int32, copy=False))

    def __call__(self, images, masks):

        new_masks = []
        for i, (image, mask) in enumerate(zip(images, masks)):
            images[i] = F.to_tensor(image)
            new_masks.append(self.__toByteTensor(mask))

        return images, new_masks

class CreateMask:
    """Create mask to hold invalid pixels
    (e.g. from rotations or downscaling)
    """

    def __call__(self, images):

        masks = []
        for i, image in enumerate(images):
            masks.append(Image.new("L", image.size))

        return images, masks

class Normalize:

    # Normalize tensor with mean and standard deviation along channel: channel = (channel - mean) / std
    def __init__(self, mean, std=None):

        if std is None:
            assert len(mean) > 0
        else:
            assert len(mean) == len(std)

        self.mean = mean
        self.std = std

    def __call__(self, images, masks):

        for i, (image, mask) in enumerate(zip(images, masks)):

            if self.std is None:
                for t, m in zip(image, self.mean):
                    t.sub_(m)
            else:
                for t, m, s in zip(image, self.mean, self.std):
                    t.sub_(m).div_(s)

        return images, masks

class ApplyMask:

    def __init__(self, ignore_label):
        self.ignore_label = ignore_label

    def __call__(self, images, masks):

        for i, (image, mask) in enumerate(zip(images, masks)):
            mask = mask > 0.
            images[i] *= (1. - mask.type_as(image))

        return images

class GuidedRandHFlip:

    def __call__(self, images, mask, affine=None):

        if affine is None:
            affine = [[0.,0.,0.,1.,1.] for _ in images]

        if random.random() > 0.5:
            for i, image in enumerate(images):
                affine[i][4] *= -1
                images[i] = F.hflip(image)

        return images, mask, affine

class AffineIdentity(object):

    def __call__(self, images, masks, affine=None):

        if affine is None:
            affine = [[0.,0.,0.,1.,1.] for _ in images]

        return images, masks, affine

class MaskRandScaleCrop(object):

    def __init__(self, scale_from, scale_to):
        self.scale_from = scale_from
        self.scale_to = scale_to
        #assert scale_from >= 1., "Zooming in is not supported yet"

    def get_scale(self):
        return random.uniform(self.scale_from, self.scale_to)

    def get_params(self, h, w, new_scale):
        # generating random crop
        # preserves aspect ratio
        new_h = int(new_scale * h)
        new_w = int(new_scale * w)

        # generating
        if new_scale <= 1.:
            assert w >= new_w and h >= new_h, "{} vs. {} | {} / {}".format(w, new_w, h, new_h)
            i = random.randint(0, h - new_h)
            j = random.randint(0, w - new_w)
        else:
            assert w <= new_w and h <= new_h, "{} vs. {} | {} / {}".format(w, new_w, h, new_h)
            i = random.randint(h - new_h, 0)
            j = random.randint(w - new_w, 0)

        return i, j, new_h, new_w

    def __call__(self, images, masks, affine=None):

        if affine is None:
            affine = [[0.,0.,0.,1.,1.] for _ in images]

        W, H = images[0].size

        i2 = H / 2
        j2 = W / 2

        masks_new = []

        # one crop for all
        s = self.get_scale()

        ii, jj, h, w = self.get_params(H, W, s)

        # displacement of the centre
        dy = ii + h / 2 - i2
        dx = jj + w / 2 - j2

        for k, image in enumerate(images):

            affine[k][0] = dy
            affine[k][1] = dx
            affine[k][3] = 1 / s # scale

            if s <= 1.:
                assert ii >= 0 and jj >= 0
                # zooming in
                image_crop = F.crop(image, ii, jj, h, w)
                images[k] = image_crop.resize((W, H), Image.BILINEAR)

                mask_crop = F.crop(masks[k], ii, jj, h, w)
                masks_new.append(mask_crop.resize((W, H), Image.NEAREST))
            else:
                assert ii <= 0 and jj <= 0
                # zooming out
                pad_l = abs(jj)
                pad_r = w - W - pad_l
                pad_t = abs(ii)
                pad_b = h - H - pad_t

                image_pad = F.pad(image, (pad_l, pad_t, pad_r, pad_b))
                images[k] = image_pad.resize((W, H), Image.BILINEAR)

                mask_pad = F.pad(masks[k], (pad_l, pad_t, pad_r, pad_b), 1)
                masks_new.append(mask_pad.resize((W, H), Image.NEAREST))

        return images, masks, affine

class MaskScaleSmallest(object):

    def __init__(self, smallest_range):
        self.size = smallest_range

    def __call__(self, images, masks):
        assert len(images) > 0, "Non-empty array expected"

        new_size = self.size[0] + int((self.size[1] - self.size[0]) * random.random())

        w, h = images[0].size
        aspect = w / h

        if aspect > 1:
            new_h = new_size
            new_w = int(new_size * aspect)
        else:
            new_w = new_size
            new_h = int(new_size / aspect)

        new_size = (new_w, new_h)

        for i, (image, mask) in enumerate(zip(images, masks)):
            assert image.size == mask.size
            assert image.size == (w, h)

            images[i] = image.resize(new_size, Image.BILINEAR)
            masks[i] = mask.resize(new_size, Image.NEAREST)

        return images, masks

class MaskRandCrop:

    def __init__(self, size, pad_if_needed=False):
        self.size = size # (h, w)
        self.pad_if_needed = pad_if_needed

    def __pad(self, img, padding_mode='constant', fill=0):

        # pad the width if needed
        pad_width = self.size[1] - img.size[0]
        pad_height = self.size[0] - img.size[1]
        if self.pad_if_needed and (pad_width > 0 or pad_height > 0):
            pad_l = max(0, pad_width // 2)
            pad_r = max(0, pad_width - pad_l)
            pad_t = max(0, pad_height // 2)
            pad_b = max(0, pad_height - pad_t)
            img = F.pad(img, (pad_l, pad_t, pad_r, pad_b), fill, padding_mode)

        return img

    def __call__(self, images, masks):

        for i, (image, mask) in enumerate(zip(images, masks)):
            images[i] = self.__pad(image)
            masks[i] = self.__pad(mask, fill=1)

        i, j, h, w = tf.RandomCrop.get_params(images[0], self.size)

        for k, (image, mask) in enumerate(zip(images, masks)):
            images[k] = F.crop(image, i, j, h, w)
            masks[k] = F.crop(mask, i, j, h, w)

        return images, masks

class MaskCenterCrop:

    def __init__(self, size):
        self.size = size # (h, w)

    def __call__(self, images, masks):

        for i, (image, mask) in enumerate(zip(images, masks)):
            images[i] = F.center_crop(image, self.size)
            masks[i] = F.center_crop(mask, self.size)

        return images, masks

class MaskRandHFlip:

    def __call__(self, images, masks):

        if random.random() > 0.5:

            for i, (image, mask) in enumerate(zip(images, masks)):
                images[i] = F.hflip(image)
                masks[i] = F.hflip(mask)

        return images, masks


in_file = open('voca.txt','r', encoding='utf-8')
for line in in_file:
    # 데이터 한줄을 읽어서 공란이나 \n를 제거하고 :을 기준으로 list를 생성
    data = line.strip().split(':')
    kor = data[1];     eng = data[0]
    print(f"{kor}에 대한 영어는 ?")
    answer = input()
    if eng == answer:    print("정답 대박")
    else:    print(f"에효 ! 정당은 {eng}야")
print("종료")
in_file.close()


import sys

def input():
    return sys.stdin.readline().rstrip()

MAX_VALUE = 100000
C, N = map(int, input().split())

# idx = 인원, value = 해당 인원을 모집하기 위한 최소비용
# dp배열의 크기를 C+100으로 해야하는 이유 :
# - C명보다 많은 고객의 수에서 최소비용이 나올 수 있다.
# - 한 도시에서 최대로 홍보할 수 있는 고객 수는 100명이다.
# - 따라서 C+1명, C+2명,.. C+100명 까지의 경우만 고려해도 된다.
dp = [MAX_VALUE] * (C+100)
dp[0] = 0
info = list(map(int, input().split()) for _ in range(N))

for cost, customer in info:
    # 주어진 인원의 수에서, 최대 고려해볼 인원 수 까지
    for i in range(customer, C + 100):
        # i명을 모집할 때, 과거의 i명까지 확보하는데 최소 비용과 비교하겠다.
        dp[i] = min(dp[i], dp[i-customer]+cost)

print(min(dp[C:]))
# for i in range(100):
#     for idx, val in zip(range(i*10, (i+1)*10), dp[i*10:(i+1)*10]):
#         print(f"{idx}명 : {val}원", end="\t")
#     print()


# coding:utf-8

from . import api
from ihome.utils.commons import login_required
from flask import g, current_app, jsonify, request, session
from ihome.utils.response_code import RET
from ihome.utils.image_storage import storage
from ihome.models import User
from ihome import db, constants
import os
import uuid

@api.route("/users/avatar", methods=["POST"])
@login_required
def set_user_avatar():
    """user_id
    """
    # The user_id is already stored in the G object in the decorator code
    # so it can be read directly from the view
    user_id = g.user_id

    # get picture
    image_file = request.files.get("avatar")

    if image_file is None:
        return jsonify(errno=RET.PARAMERR, errmsg="Image not uploaded")

    # Call Qiniu upload pictures, return the file name TODO to local storage
    try:
        # Get the UUID from the timestamp
        file_name = str(uuid.uuid1())+'.png'
        basedir = os.getcwd()
        image_path = os.path.join(basedir,'ihome','static','images',file_name)
        image_file.save(image_path)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="Image upload failed")

    # Save the file name to the database
    try:
        User.query.filter_by(id=user_id).update({"avatar_url": file_name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="Failed to save image information")

    avatar_url = constants.QINIU_URL_DOMAIN + file_name
    # save successfully
    return jsonify(errno=RET.OK, errmsg="save successfully ", data={"avatar_url": avatar_url})

@api.route("/users/name", methods=["PUT"])
@login_required
def change_user_name():
    """change username"""
    # With the login_required decorator, you can get the user user_id from the g object
    user_id = g.user_id

    # Gets the user name that the user wants to set
    req_data = request.get_json()
    if not req_data:
        return jsonify(errno=RET.PARAMERR, errmsg="Parameter Incomplete")

    name = req_data.get("name")  # set name
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg="Names cannot be empty")

    # Save the user nickname name and determine if the name is duplicated (using the unique index of the database)
    try:
        User.query.filter_by(id=user_id).update({"name": name})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="Set user error")

    # Modify the name field in the session data
    session["name"] = name
    return jsonify(errno=RET.OK, errmsg="OK", data={"name": name})

@api.route("/user", methods=["GET"])
@login_required
def get_user_profile():
    """get user information"""
    user_id = g.user_id
    # query database to get user information
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="Failed to obtain user information")

    if user is None:
        return jsonify(errno=RET.NODATA, errmsg="invalid operation")

    return jsonify(errno=RET.OK, errmsg="OK", data=user.to_dict())

@api.route("/users/auth", methods=["GET"])
@login_required
def get_user_auth():
    """Get the user's real-name authentication information"""
    user_id = g.user_id

    # query informaiton in the database
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="Failed to obtain user real name information")

    if user is None:
        return jsonify(errno=RET.NODATA, errmsg="invalid operation")

    return jsonify(errno=RET.OK, errmsg="OK", data=user.auth_to_dict())

@api.route("/users/auth", methods=["POST"])
@login_required
def set_user_auth():
    """Save real-name authentication information"""
    user_id = g.user_id

    # get parameters
    req_data = request.get_json()
    if not req_data:
        return jsonify(errno=RET.PARAMERR, errmsg="wrong parameters ")

    real_name = req_data.get("real_name")  # real name
    id_card = req_data.get("id_card")  # id number

    # Parameter calibration
    if not all([real_name, id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # Save the user's name and ID number
    try:
        User.query.filter_by(id=user_id, real_name=None, id_card=None)\
            .update({"real_name": real_name, "id_card": id_card})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="Failed to save user real name information")

    return jsonify(errno=RET.OK, errmsg="OK")


from enum import Enum

class Role(Enum):
    ADMIN = "ADMIN"
    USER = "USER"
    VIEWER = 'VIEWER'

class ESPType(str, Enum):
    SENSOR = "SENSOR"
    CO2_CONTROLLER = "CO2_CONTROLLER"
    LIGHT_CONTROLLER = "LIGHT_CONTROLLER"
    AC_CONTROLLER = "AC_CONTROLLER"
    DEHUMIDIFIER_CONTROLLER = "DEHUMIDIFIER_CONTROLLER"
    WATERING_SYSTEM = "WATERING_SYSTEM"

class HardwareType(str, Enum):
    LIGHT = "LIGHT"
    AC = "AC"
    CO2_SENSOR = "CO2_SENSOR"
    CO2_CONTROLLER = "CO2_CONTROLLER"
    DEHUMIDIFIER = "DEHUMIDIFIER"
    HUMIDITY_SENSOR = "HUMIDITY_SENSOR"
    TEMPERATURE_SENSOR = "TEMPERATURE_SENSOR"
    WATERING = "WATERING"

class System(str, Enum):
    USERNAME = "mqtt2db"


import serial  # install "pyserial" instead of "serial"
import time
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams['font.size'] = 12

class TacSensor():
    def __init__(self):
        self.data_initial = self.initialize_sensor()

    def read_sensor(self,N=3, timeout=0.5):
        '''
        Read raw data of N Hall sensor array ()
        :param N: the number of the whole sensor array
        :return: 3-axis magnetic flux densities of Nx9 Hall sensors (dim = 3 x N x 9)
        '''

        t_wait = 0
        res_x = 0.25;
        res_y = 0.25;
        res_z = 0.403
        bx, by, bz = np.zeros((N, 9)), np.zeros((N, 9)), np.zeros((N, 9))

        data = self.s_my.readline().split()
        while len(data) != N * 3 * 9 or data[0] == 0:
            t1 = time.time()
            #         print(data)
            data = self.s_my.readline().split()
            t2 = time.time()
            t_wait = t_wait + (t2 - t1)
            if t_wait > timeout:
                #             print('Timeout!')
                return np.array([bx, by, bz])

        for n in range(N):
            for i in range(9):
                bx[n][i] = res_x * int(data[0 + i * 3 + n * 27])
                by[n][i] = res_y * int(data[1 + i * 3 + n * 27])
                bz[n][i] = res_z * int(data[2 + i * 3 + n * 27])

        data_assembly = np.array([bx, by, bz])

        return data_assembly  # dim = 3 x N x 9 (3-axial magnetic flux densities of N sensor array, each with 9 Hall sensors)

    def initialize_sensor(self,serial_port='/dev/ttyACM0'):
        '''
        Connect the sensor to the PC and initialize the sensor
        :param serial_port: for Windows --> enter port number 'COM#'
                            for Linux --> enter port number '/dev/ttyS#' and enable the serial port in command line
                            with command "sudo chmod 666 /dev/ttyS#" befor opening the port
                            （Tips: you can check serial devices on you PC with command "dmesg | grep ttyS*"）
        :return: the initial sensor readings (dim = 3 x N x 9)
        '''

        t = 0
        self.s_my = serial.Serial(serial_port, 115200, timeout=0.1)
        time.sleep(2)
        self.s_my.reset_input_buffer()

        while True:
            t1 = time.time()
            data_initial = self.read_sensor()  # the initial readings of the sensor (when not loaded)
            t2 = time.time()
            t = t + (t2 - t1)
            if data_initial[0][0][0] == 0:
                if t < 3:
                    continue
                elif t >= 3:
                    print("Timeout! Resetting the serial port...")
                    self.s_my.close()
                    time.sleep(1)
                    self.s_my = serial.Serial(serial_port, 115200, timeout=0.1)
                    time.sleep(1)
                    if self.read_sensor()[0][0][0] != 0:
                        t = 0
                        continue
                    else:
                        print("Failed to reset, please reconnect the arduino and the PC (replug the USB cable)!")
                        break

            elif data_initial[0][0][0] != 0 and t >= 3:
                break

        return data_initial

    def bar_plot(self,ax1, data):
        x = [1, 2, 3, 1, 2, 3, 1, 2, 3]
        y = [1, 1, 1, 2, 2, 2, 3, 3, 3]
        z = [0, 0, 0, 0, 0, 0, 0, 0, 0]
        dx = [0.7 for i in range(9)]
        dy = [0.7 for i in range(9)]

        dz = data
        ax1.cla()
        ax1.bar3d(x, y, z, dx, dy, dz, color='C0', shade=True)
        ax1.set_zlim(-100, 2000)  # change this bound when necessary (according to the plot requirement)
        ax1.set_title('Magnetic flux density B (uT)')
        ax1.invert_yaxis()
        fig.canvas.draw()

if __name__ == '__main__':
    try:
        sensors = TacSensor()

        t = 0
        fig = plt.figure()
        ax1 = Axes3D(fig, auto_add_to_figure=False)
        fig.add_axes(ax1)

        while t < 15:  # modify the plot time t when necessary
            t_start = time.time()
            d = sensors.read_sensor() - sensors.data_initial  # remove the initial sensor readings from the original ones
            #     d = read_sensor()         # directly use the original sensor readings

            bx_s1 = d[0][0];
            bx_s2 = d[0][1];
            bx_s3 = d[0][2]
            by_s1 = d[1][0];
            by_s2 = d[1][1];
            by_s3 = d[1][2]
            bz_s1 = d[2][0];
            bz_s2 = d[2][1];
            bz_s3 = d[2][2]

            # overall magnetic flux density B
            B1 = [np.sqrt(bx_s1[i] ** 2 + by_s1[i] ** 2 + bz_s1[i] ** 2) for i in range(9)]
            B2 = [np.sqrt(bx_s2[i] ** 2 + by_s2[i] ** 2 + bz_s2[i] ** 2) for i in range(9)]
            B3 = [np.sqrt(bx_s3[i] ** 2 + by_s3[i] ** 2 + bz_s3[i] ** 2) for i in range(9)]

            #     bar_plot(ax1,bz_s1)    # plot magnetic flux density along z-axis
            #     bar_plot(ax1,bx_s1)    # plot magnetic flux density along x-axis
            #     bar_plot(ax1,by_s1)    # plot magnetic flux density along y-axis
            # sensors.bar_plot(ax1, B1)  # plot overall magnetic flux density
            print(B3)
            t_end = time.time()
            t = t + (t_end - t_start)

        sensors.s_my.close()

    except:
        pass


n,m = int(input()),int(input())
graph = [[float('inf')]*n for _ in range(n)]
for _ in range(m):
    s,e,w = map(int, input().split())
    s,e = s-1,e-1
    graph[s][e] = min(graph[s][e], w)

for i in range(n):
    graph[i][i] = 0

for p in range(n):
    for i in range(n):
        if p != i:
            for j in range(n):
                if i != j and p != j:
                    graph[i][j] = min(graph[i][j], graph[i][p]+graph[p][j])

for gra in graph:
    for g in gra:
        if g != float('inf'):
            print(g,end=' ')
        else: print(0,end=' ')
    print()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

def add_new_image_type_and_format(apps, schema_editor):
    formats = [
        'tar.gz',
        'tar.xz'
    ]
    ImageFormat = apps.get_model('package', 'ImageFormat')
    for format in formats:
        ImageFormat.objects.get_or_create(name=format)

    ImageType = apps.get_model('package', 'ImageType')
    ImageType.objects.get_or_create(name='docker')

class Migration(migrations.Migration):

    dependencies = [
        ('package', '0010_auto_20160218_1339'),
    ]

    operations = [
        migrations.RunPython(add_new_image_type_and_format)
    ]


def request():
    max = 3
    time = 5
    timeStamps = [1, 2, 2, 5, 7]
    n1 = timeStamps[0]
    n2 = timeStamps[1]
    n3 = n1+n2
    bul = []

    for i in range(0, 7, 5):
        if n3 < max:
            bool = True
            bul.append(bool)
        else:
            bool = False
            bul.append(bool)

    print(bul)

request()


from warbler.database import db, datetime

class Message(db.Model):
    """An individual message ("warble")."""

    __tablename__ = 'messages'

    id = db.Column(
        db.Integer,
        primary_key=True,
    )

    text = db.Column(
        db.String(140),
        nullable=False,
    )

    timestamp = db.Column(
        db.DateTime,
        nullable=False,
        default=datetime.utcnow,
    )

    user_id = db.Column(
        db.Integer,
        db.ForeignKey('users.id', ondelete='CASCADE'),
        nullable=False,
    )

    users_liked = db.relationship(
        "User",
        secondary="likes",
        backref="messages_liked"
    )


# import dependencies
import os
import numpy as np
from numpy.typing import NDArray
import matplotlib.pyplot as plt
import cv2
from IPython.display import display, Javascript
from base64 import b64decode, b64encode
import PIL
import io

def pointDetector(path_to_img):
    img = cv2.imread(path_to_img)
    kernel = np.float32([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]])
    img_out = cv2.filter2D(img,-1,kernel)
    plt.figure(figsize=(20,10))
    plt.subplot(121),plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),plt.title('Input',color='c')
    plt.subplot(122),plt.imshow(cv2.cvtColor(img_out,cv2.COLOR_BGR2RGB)),plt.title('Transformed',color='c')
    plt.show()
    return

def load_images_from_folder(folder : str):
    images = []
    for filename in os.listdir(folder):
        img = cv2.imread(os.path.join(folder,filename))
        if img is not None:
            images.append(img)
    return images

def rotate_img(angle_val : float):
    path_to_img = 'noidea.jpg'
    scaleFactor = 1
    img = cv2.imread(path_to_img,cv2.IMREAD_UNCHANGED)
    rows,cols,_ = img.shape
    imgCenter = (cols-1)/2.0,(rows-1)/2.0
    #Calculate an affine matrix of 2D rotation.
    rotateMat = cv2.getRotationMatrix2D(imgCenter,angle_val,scaleFactor)
    # Apply an affine transformation to an image.
    out_img = cv2.warpAffine(img,rotateMat,(cols,rows))
    plt.figure(figsize=(10,10))
    plt.subplot(1,2,1), plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) ,plt.title('Original Image',color='c')
    plt.subplot(1,2,2), plt.imshow(cv2.cvtColor(out_img,cv2.COLOR_BGR2RGB)), plt.title('Rotated Image',color='c')
    plt.show()

hori_line_mat = np.float32([[-1,-1,-1],
                            [2,2,2],
                            [-1,-1,-1]])

verti_line_mat = np.float32([[-1,2,-1],
                            [-1,2,-1],
                            [-1,2,-1]])
def lineDetector(path_to_img : str, kernel : NDArray[np.floating]):
    img = cv2.imread(path_to_img)
    img_out = cv2.filter2D(img,-1,kernel)
    plt.figure(figsize=(20,10))
    plt.subplot(121),plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),plt.title('Input',color='c')
    plt.subplot(122),plt.imshow(cv2.cvtColor(img_out,cv2.COLOR_BGR2RGB)),plt.title('Transformed',color='c')
    plt.show()
    return

def edgeDetector(path_to_img : str, algo_edgedetect : str=None):
    img = cv2.imread(path_to_img)
    if algo_edgedetect == 'canny':
        img_edge = cv2.Canny(img,100,200)
    if algo_edgedetect == 'sobel':
        img_edge = cv2.Sobel(img,-1,1,0,ksize=-1)
    if algo_edgedetect == 'prewitt':
        prewitt_kernel_h = np.array([[1,1,1],
                                    [0,0,0],
                                    [-1,-1,-1]])
        prewitt_kernel_v = np.array([[-1,0,1],
                                    [-1,0,1],
                                    [-1,0,1]])
        prewitt_h = cv2.filter2D(img,-1,prewitt_kernel_h)
        prewitt_v = cv2.filter2D(img,-1,prewitt_kernel_v)
        img_edge = prewitt_h + prewitt_v
    if algo_edgedetect == 'roberts':
        roberts_kernel_h = np.array([[-1,0],[0,1]])
        roberts_kernel_v = np.array([[0,-1],[1,0]])
        roberts_h_ele = cv2.filter2D(img,-1,roberts_kernel_h)
        roberts_v_ele = cv2.filter2D(img,-1,roberts_kernel_v)
        img_edge = roberts_h_ele + roberts_v_ele
    if algo_edgedetect == 'scharr':
        # img_gaussian = cv2.GaussianBlur(img,(3,3),5)
        # img_edge = cv2.Laplacian(img_gaussian,-1)
        img_edge = cv2.Scharr(img,-1,1,0)
    # print(img_edge.dtype0
    plt.figure(figsize=(20,10))
    plt.subplot(121),plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),plt.title('Input',color='c')
    plt.subplot(122),plt.imshow(cv2.cvtColor(img_edge,cv2.COLOR_BGR2RGB)),plt.title('Output',color='c')
    plt.show()
    return img_edge

def houghLineDetector(path_to_img : str):
    img = cv2.imread(path_to_img)
    img_edge = cv2.Canny(img,80,200)
    lines = cv2.HoughLinesP(img_edge,5,np.pi/180,20,minLineLength=50,maxLineGap=10)
    for line in lines:
        x1,y1,x2,y2 = line[0]
        cv2.line(img,(x1,y1),(x2,y2),(255,0,0),2)
    plt.figure(figsize=(20,10))
    plt.subplot(121),plt.imshow(cv2.cvtColor(img_edge,cv2.COLOR_BGR2RGB)),plt.title('Input',color='c')
    plt.subplot(122),plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),plt.title('Output',color='c')
    plt.show()
    return

def houghCircleDetector(path_to_img : str):
    img = cv2.imread(path_to_img)
    img_edge = cv2.medianBlur(img,3)
    #img_edge = cv2.Canny(img,100,200)

    circles = cv2.HoughCircles(img_edge,cv2.HOUGH_GRADIENT,1,minDist=50,param1=200,param2=31, maxRadius=100, minRadius=50)
    print(circles)
    circles = np.uint16(np.around(circles))
    for val in circles[0,:]:
        cv2.circle(img_edge,(val[0],val[1]),val[2],(255,0,0),2)

    plt.figure(figsize=(20,10))
    plt.subplot(121),plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),plt.title('Input',color='c')
    plt.subplot(122),plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),plt.title('Result',color='c')
    plt.show()
    return

def detectColorObjects(path_to_img : str, find_color : str=None):
    img =cv2.imread(path_to_img)
    img_hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    if find_color == 'red':
        Red1Lower = np.array([0,90,100])
        Red1Upper = np.array([10,255,255])
        #(170-180)
        Red2Lower = np.array([170,90,100])
        Red2Upper = np.array([180,255,255])
        img_mask1 = cv2.inRange(img_hsv,Red1Lower,Red1Upper)
        img_mask2 = cv2.inRange(img_hsv,Red2Lower,Red2Upper)
        img_mask = img_mask1+img_mask2
        masked_out = cv2.bitwise_and(img,img,mask=img_mask)
    if find_color == 'green':
        GreenLower = np.array([40,100,100])
        GreenUpper = np.array([80,255,255])
        img_mask = cv2.inRange(img_hsv,GreenLower,GreenUpper)
        masked_out = cv2.bitwise_and(img,img,mask=img_mask)
    return img,img_mask

def markDetectdObjects(og_img,masked_img):
    # Find Blue Contours
    (contours,_)=cv2.findContours(masked_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    FinImg = og_img.copy()
    for pic, contour in enumerate(contours):
        area = cv2.contourArea(contour)
        if(area):
            x,y,w,h = cv2.boundingRect(contour)
            # FinImg = cv2.rectangle(og_img,(x,y),(x+w,y+h),(0,0,255),2)
            cv2.putText(FinImg,"*",(int(x+w/2),int(y+h/2)),cv2.FONT_HERSHEY_SIMPLEX,0.7,(255,0,0))
            # BaseCord = np.array([x+h+round(w/2), y+h+round(w/2)])
    plt.figure(figsize=(20,10))
    plt.subplot(131),plt.imshow(cv2.cvtColor(og_img,cv2.COLOR_BGR2RGB)),plt.title('Input',color='c')
    plt.subplot(132),plt.imshow(cv2.cvtColor(masked_img,cv2.COLOR_BGR2RGB)),plt.title('Result',color='c')
    plt.subplot(133),plt.imshow(cv2.cvtColor(FinImg,cv2.COLOR_BGR2RGB)),plt.title('Result',color='c')
    plt.show()
    return

def detectShapes(img_path):
    img = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE)
    _,img_Otsubin = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    contours,_ = cv2.findContours(img_Otsubin.copy(),1,2)
    for num,cnt in enumerate(contours):
        x,y,w,h = cv2.boundingRect(cnt)
        approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
        # print(num, approx)
        if len(approx) == 3:
            cv2.putText(img,"Triangle",(int(x+w/2),int(y+h/2)),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)
            cv2.drawContours(img,[cnt],-1,(0,255,0),2)
        if len(approx) == 4:
            cv2.putText(img,"Rect",(int(x+w/2),int(y+h/2)),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)
            cv2.drawContours(img,[cnt],-1,(0,255,0),2)
        if len(approx) > 10:
            cv2.putText(img,"Circle",(int(x+w/2),int(y+h/2)),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),2)
            cv2.drawContours(img,[cnt],-1,(0,255,0),2)

    plt.figure(figsize=(20,10))
    plt.subplot(131),plt.imshow(cv2.cvtColor(img_Otsubin,cv2.COLOR_BGR2RGB)),plt.title('Input',color='c')
    plt.subplot(132),plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),plt.title('Result')
    plt.subplot(133),plt.imshow(cv2.cvtColor(cv2.imread(img_path),cv2.COLOR_BGR2RGB)),plt.title('Original')
    plt.show()
    return

def js_to_image(js_reply):
  """
  Params:
          js_reply: JavaScript object containing image from webcam
  Returns:
          img: OpenCV BGR image
  """
  # decode base64 image
  image_bytes = b64decode(js_reply.split(',')[1])
  # convert bytes to numpy array
  jpg_as_np = np.frombuffer(image_bytes, dtype=np.uint8)
  # decode numpy array into OpenCV BGR image
  img = cv2.imdecode(jpg_as_np, flags=1)

def bbox_to_bytes(bbox_array):
  """
  Params:
          bbox_array: Numpy array (pixels) containing rectangle to overlay on video stream.
  Returns:
        bytes: Base64 image byte string
  """
  # convert array into PIL image
  bbox_PIL = PIL.Image.fromarray(bbox_array, 'RGBA')
  iobuf = io.BytesIO()
  # format bbox into png for return
  bbox_PIL.save(iobuf, format='png')
  # format return string
  bbox_bytes = 'data:image/png;base64,{}'.format((str(b64encode(iobuf.getvalue()), 'utf-8')))

  return bbox_bytes

def take_photo(filename='photo.jpg', quality=0.8):
  js = Javascript('''
    async function takePhoto(quality) {
      const div = document.createElement('div');
      const capture = document.createElement('button');
      capture.textContent = 'Capture';
      div.appendChild(capture);

      const video = document.createElement('video');
      video.style.display = 'block';
      const stream = await navigator.mediaDevices.getUserMedia({video: true});

      document.body.appendChild(div);
      div.appendChild(video);
      video.srcObject = stream;
      await video.play();

      // Resize the output to fit the video element.
      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);

      // Wait for Capture to be clicked.
      await new Promise((resolve) => capture.onclick = resolve);

      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0);
      stream.getVideoTracks()[0].stop();
      div.remove();
      return canvas.toDataURL('image/jpeg', quality);
    }
    ''')
  display(js)

  # get photo data
  data = eval_js('takePhoto({})'.format(quality))
  # get OpenCV format image
  img = js_to_image(data)
  # grayscale img
  #gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  #print(gray.shape)
  # get face bounding box coordinates using Haar Cascade
  #faces = face_cascade.detectMultiScale(gray)
  # draw face bounding box on image
  #for (x,y,w,h) in faces:
  #    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
  # save image
  cv2.imwrite(filename, img)

  return filename

from IPython.display import display, Javascript
from base64 import b64decode

def re_encode_video(video_path):
    print(f"Re-encoding video, this might take some time, please be patient.")
    #added -r 30, otherwise, for some reason it records 1000FPS as metadata for the Astra
    os.system(f"ffmpeg -y -i {video_path} -vcodec libx264 -r 30 temp.mp4")
    os.system(f"rm {video_path}")
    os.system(f"mv temp.mp4 {video_path}")
    print(f"Done encoding!")

def record_video(filename='video.mp4'):
  js = Javascript("""
    async function recordVideo() {
      // mashes together the advanced_outputs.ipynb function provided by Colab,
      // a bunch of stuff from Stack overflow, and some sample code from:
      // https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API

      // Optional frames per second argument.
      const options = { mimeType: "video/webm; codecs=vp9" };
      const div = document.createElement('div');
      const capture = document.createElement('button');
      const stopCapture = document.createElement("button");
      capture.textContent = "Start Recording";
      capture.style.background = "green";
      capture.style.color = "white";

      stopCapture.textContent = "Stop Recording";
      stopCapture.style.background = "red";
      stopCapture.style.color = "white";
      div.appendChild(capture);

      const video = document.createElement('video');
      const recordingVid = document.createElement("video");
      video.style.display = 'block';

      const stream = await navigator.mediaDevices.getUserMedia({video: true});
      // create a media recorder instance, which is an object
      // that will let you record what you stream.
      let recorder = new MediaRecorder(stream, options);
      document.body.appendChild(div);
      div.appendChild(video);
      // Video is a media element.  This line here sets the object which serves
      // as the source of the media associated with the HTMLMediaElement
      // Here, we'll set it equal to the stream.
      video.srcObject = stream;
      // We're inside an async function, so this await will fire off the playing
      // of a video. It returns a Promise which is resolved when playback has
      // been successfully started. Since this is async, the function will be
      // paused until this has started playing.
      await video.play();

      // Resize the output to fit the video element.
      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
      // and now, just wait for the capture button to get clicked in order to
      // start recording
      await new Promise((resolve) => {
        capture.onclick = resolve;
      });
      recorder.start();
      capture.replaceWith(stopCapture);
      // use a promise to tell it to stop recording
      await new Promise((resolve) => stopCapture.onclick = resolve);
      recorder.stop();

      let recData = await new Promise((resolve) => recorder.ondataavailable = resolve);
      let arrBuff = await recData.data.arrayBuffer();

      // stop the stream and remove the video element
      stream.getVideoTracks()[0].stop();
      div.remove();

      let binaryString = "";
      let bytes = new Uint8Array(arrBuff);
      bytes.forEach((byte) => {
        binaryString += String.fromCharCode(byte);
      })
      return btoa(binaryString);
    }
    """)
  try:
    display(js)
    data = eval_js('recordVideo({})')
    binary = b64decode(data)
    with open(filename, "wb") as video_file:
      video_file.write(binary)
    print(
        f"Finished recording video. Saved binary under filename in current working directory: {filename}"
    )
    '''
    unfortunately, webcam capture is not that clean in Colab and the videos need to
    be re-encoded to play properly. This takes some time.
    '''
    re_encode_video(filename)
  except Exception as err:
      # In case any exceptions arise
      print(str(err))
  return filename

from IPython.display import HTML
from base64 import b64encode

def show_video(video_path, video_width = 640, reencode = False):
  video_file = open(video_path, "r+b").read()
  video_url = f"data:video/mp4;base64,{b64encode(video_file).decode()}"
  return HTML(f"""<video width={video_width} controls><source src="{video_url}"></video>""")


from typing import Any

from sqlalchemy import event  # noqa: F401
from sqlalchemy.engine import Engine  # noqa: F401
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

from back.settings import DatabaseTypeEnum, setting  # noqa: F401

DATABASE_TYPE = setting.database_type
DATABASE_URL = setting.database_url
ECHO = setting.database_echo

class DatabaseSession:
    def __init__(
        self,
        database_url: str,
        echo: bool = ECHO,
        expire_on_commit: bool = False,
        class_: AsyncSession = AsyncSession,
    ):
        self.async_engine = create_async_engine(database_url, echo=echo)
        self.expire_on_commit = expire_on_commit
        self.class_ = class_

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        return sessionmaker(
            self.async_engine,
            *args,
            expire_on_commit=self.expire_on_commit,
            class_=self.class_,
            **kwargs
        )()

    def load(
        self,
        database_url: str,
        echo: bool = ECHO,
        expire_on_commit: bool = False,
        class_: AsyncSession = AsyncSession,
    ):
        self.async_engine = create_async_engine(database_url, echo=echo)
        self.expire_on_commit = expire_on_commit
        self.class_ = class_

async_session = DatabaseSession(
    DATABASE_URL, echo=ECHO, expire_on_commit=False, class_=AsyncSession
)

# if DATABASE_TYPE == DatabaseTypeEnum.SQLITE:

#     @event.listens_for(Engine, "connect")
#     def set_sqlite_pragma(dbapi_connection, _):
#         cursor = dbapi_connection.cursor()
#         cursor.execute("PRAGMA foreign_keys=ON")
#         cursor.close()


from openpyxl import load_workbook
import pandas as pd

codigo_empresa = '5533'

def dar_formato(txt, total, tipo):
    if len(txt) + 1 <= total:
        resto = total - len(txt)
        if tipo == 'A':
            txt = txt + ' ' * resto
        elif tipo == 'N':
            txt = '0' * resto + txt

    if len(txt) > total:
        txt = txt[:total]

    return txt

wb = load_workbook("formato.xlsx")
ws_formato = wb.active
index = 1
columnas = []

for row in ws_formato:
    try:
        if int(row[2].value) > 0:
            tupla_columnas = (index, row[1].value, int(row[2].value), row[0].value)
            columnas.append(tupla_columnas)
            index = index + 1
    except:
        pass

col_list = ['MONTO', 'localidad', 'COD_SUCURSAL', 'NOMBRE_SUCURSAL', 'NOMBRES', 'APELLIDOS', 'CUIT', 'FECHA_DESDE', 'FECHA_HASTA', 'NRO_DOCUMENTO', 'DATOS BANCO']
df_cuotas = pd.read_excel(codigo_empresa+'.xlsx', usecols=col_list)

print(list(df_cuotas.columns))

try:
    df_cuotas['COD_SUCURSAL'] = df_cuotas['COD_SUCURSAL'].astype(str).str.slice(0, -2, 1)
    df_cuotas['CUIT'] = df_cuotas['CUIT'].astype(str).astype(str).str.slice(0, -2, 1)
except:
    pass
print(df_cuotas['FECHA_HASTA'])

print(df_cuotas)
df_cuotas.to_excel(codigo_empresa+" formateado.xlsx", index=False)

print(df_cuotas)

calc_monto_gral = df_cuotas['MONTO'].sum()
monto_gral = dar_formato(str(calc_monto_gral), 10, 'N')
monto_gral = monto_gral + '00'
cantidad_registros = dar_formato(str(df_cuotas.shape[0]), 8, 'N')
txt = "00032021"+cantidad_registros+monto_gral+"000000000000000000002203202105042021020"+ codigo_empresa + dar_formato("", 953, 'A')
for index, row in df_cuotas.iterrows():
    txt += "\n"
    txt += "00"
    #GRUPO DE PAGO	FECHA DESDE	FECHA HASTA
    txt += dar_formato(str(row['FECHA_DESDE']), 8, 'N') + dar_formato(str(row['FECHA_HASTA']), 8, 'N')
    cuit = str(row['CUIT'])
    txt += dar_formato(cuit, 11, 'N')
    #EXCAJA	 TIPO BENEFICIARIO
    txt += "000"
    txt += dar_formato(str(row['NRO_DOCUMENTO']), 8, 'N')
    #BCO: FIJO= 020	SUCURSAL
    txt += "0020" + dar_formato(str(row['COD_SUCURSAL']), 3, 'N')
    apellido_nombre = str(row['APELLIDOS']) + " " + str(row['NOMBRES'])
    apellido_nombre = apellido_nombre.title().upper()
    txt += dar_formato(apellido_nombre, 27, 'A')
    #TIPO DE DOC: DNI=1
    txt += "1"
    txt += dar_formato(str(row['NRO_DOCUMENTO']), 8, 'N')
    #PCIA EMISIÓN: CBA=04	CUIL APODERADO
    txt += "0400000000000"
    #APELLIDO Y NOMBRE DE APODERADO
    txt += dar_formato("", 27, 'A')
    #TIPO DOC. APODERADO NRO DOC APODERADO PCIA EMISIÓN: CBA=04	CÓDIGO CONCEPTO 1: FIJO 001	SUBCÓDIGO DEL CONCEPTO 1: FIJO 000	IMPORTE DEL CONCEPTO 1
    txt += "00000000004001000000" + str(row['MONTO']) + '00'
    #columna desde la 23 a la 97
    sum = 0
    for i in range(23,98):
        sum  += columnas[i][2]
    sum += 2
    txt += dar_formato("", sum, 'N')
    #IMPORTE MAYOR A $ 9.999,00.-: 0=NO ; 1=SI	PERIODO LIQUIDACIÓN: MMAA	TIPO DE PAGO: VER ANEXO	FORMA DE PAGO: VENTANILLA= 0	TIPO DE CUENTA: VALOR FIJO 0
    txt += "101210000"
    #NRO CUENTA VALOR FIJO 0	FECHA DESDE PROX PAGO: DDMMAAA	FECHA HASTA PROX PAGO: DDMMAAAA
    txt += dar_formato("", 36, 'N')
    #LEYENDA 1	LEYENDA 2	LEYENDA 3	LEYENDA 4
    if codigo_empresa == '5533':
        ministerio = 'MINISTERIO DE PROMOCION DEL EMPLEO Y E'
    elif codigo_empresa == '5541':
        ministerio = 'MINISTERIO DE DESARROLLO SOCIAL       '

    programa = 'PROGRAMA VIDA DIGNA                   '
    txt += "GOBIERNO DE LA PROVINCIA DE CORDOBA   "+ministerio+programa+"APODERADO DE                          "
    #LEYENDA 5
    txt += dar_formato(apellido_nombre, 38, 'A')
    #LEYENDA 6	LEYENDA 7	LEYENDA 8
    txt += dar_formato("", 114, 'A')
    #CÓDIGO PAGO-IMPAGO: LA EMPRESA DEBE PONER SIEMPRE 1= IMPAGO. ELBANCO EN LA RENDICIÓN DEVUELVE 0=PAGO O 1=IMPAGO	FECHA PAGO:COMPLETA EL BANCO LA EMPRESA DEBE PONER 0	PAGO CON TARJETA VALOR FIJO = 0	MOTIVO IMPAGO VALOR FIJO PARA LA EMPRESA=0- LUEGO COMPLETA EL BANCO - VER ANEXOS	NÚMERO DE COMPROBANTE: COMPLETA EL BANCO	ÚLTIMO MOV CUENTA: COMPLETA EL BANCO	RETENCIÓN DE TARJETA: 0=PAGO NORMAL; 1=TARJ.RETENIDA CAJERO	COMISIÓN: VALOR FIJO= ESPACIO	UR ASIGNADA: VALOR FIJO=000	IMPORTE  MORATORIA AFIP: VALOR FIJO=0000000000	IMP. RETROACTIVO MOR. AFIP: VALOR FIJO=0000000000	IMPORTE NETO A COBRAR 	CÓDIGO DE EMPRESA
    txt += "100000000000000000000000000 0000000000000000000000000000" + str(row['MONTO']) + '00' + codigo_empresa
    #USO FUTURO: VALOR FIJO= ESPACIOS
    txt += dar_formato("", 38, 'A')

f = open(codigo_empresa+".txt", "w")
f.write(txt)
f.close()


from odoo import models, fields, api

class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    @api.model
    def _get_product_domain(self):
        domain = [('sale_ok', '=', True)]
        if not self.advertising:
            ads = self.env.ref('sale_advertising_order.advertising_category').id
            title_pricelist = self.env.ref('sale_advertising_order.title_pricelist_category').id
            domain +=['!', ('categ_id', 'child_of', [ads, title_pricelist])]
        return domain

    product_id = fields.Many2one('product.product', string='Product', domain=_get_product_domain, change_default=True, ondelete='restrict', required=True)


import os
import sys
from lab0 import getLine

def main():

    while True:
        if('PS1' in os.environ):
            os.write(1, (os.environ['PS1']).encode())
        else:
            os.write(1, ("$ ").encode()) #writes the prompt
            userInput = getLine()

            if(userInput == 'exit'): #quit if exit is typed
                sys.exit(1)

            #splitUserInput = userInput.split(" ")

            #if(splitUserInput[0] == 'cd' and len(splitUserInput) == 2): #makes sure only two things were entered for cd

                #try:
                    #os.chdir(splitUserInput[1])

                #except:  #directory does not exist
                    #os.write(1, ("%s was not found\n" % splitUserInput[1]).encode())

if __name__ == '__main__':
    main()


#practical 10
#loop to input integer
#if input positive - while exhaustive enumeration loop based on lecture notes to find square root
#sub option for numbers that are not perfect squares
#exception for negative numbers with message

while True:
     try:
          a = int(input('Enter a positive integer: '))
          if a > -1:
               counter= 0
               while counter**2 <=a:
                    if a != counter**2:
                         counter +=1
                    else:
                         print(a, ' = ', counter,'^2')
                         break
               else:
                    print(a, ' isnt a perfect square')
          else:
               print("Error this is a negative integer")
               break
     finally:
          print('')


# Local Imports
from cogharm.woolhouse09 import event_attraction

# Consants
ALLPC = [[pc] for pc in range(0,12)]

SCALES = {
    'ka0ma': [0,2,4,5,7,9,11],
    'ka1ma': [1,3,5,6,8,10,0],
    'ka2ma': [2,4,6,7,9,11,1],
    'ka3ma': [3,5,7,8,10,0,2],
    'ka4ma': [4,6,8,9,11,1,3],
    'ka5ma': [5,7,9,10,0,2,4],
    'ka6ma': [6,8,10,11,1,3,5],
    'ka7ma': [7,9,11,0,2,4,6],
    'ka8ma': [8,10,0,1,3,5,7],
    'ka9ma': [9,11,1,2,4,6,8],
    'ka10ma': [10,0,2,3,5,7,9],
    'ka11ma': [11,1,3,4,6,8,10]}

def chroma_attraction(chord, alpha = 9999999, beta = 4):
    """"""
    ca = [(round(event_attraction(chord, pc, alpha = alpha, beta = beta, Gamma = 1, delta = 0),3)) for pc in ALLPC]
    return ca

def key_attraction(chord):
    """"""
    ca = chroma_attraction(chord)
    ka = {}
    for name, scale in SCALES.items():
        ka_list = []
        for pc in SCALES[name]:
            ka_list.append(ca[pc])
            ka[name] = sum(ka_list)/len(ka_list)
    return ka


import time
from dataclasses import dataclass
from typing import Dict

def _convert_timestamp(timestamp: str or int) -> str or None:
    """ Converts epoch timestamp into human-readable time

    Args:
        timestamp: epoch timestamp in seconds
    Returns:
        String time in the format YYYY-mm-dd hh:mm:ss
    """

    if timestamp:
        if isinstance(timestamp, str):
            timestamp = timestamp.split('.', 1)[0]

        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(timestamp)))
    else:
        return None

@dataclass(slots=True)
class User(object):
    """ Class that defines User objects for Slack users"""

    id: str
    name: str
    email: str
    deleted: bool
    real_name: str
    first_name: str
    last_name: str
    phone: str
    skype: str
    display_name: str
    tz: str
    tz_label: str
    tz_offset: str
    title: str
    is_admin: bool
    is_owner: bool
    is_primary_owner: bool
    is_restricted: bool
    is_ultra_restricted: bool
    is_bot: bool
    updated: int or float or str
    has_2fa: bool

@dataclass(slots=True)
class UserSuccinct(object):
    """ Class that defines User objects for Slack users"""

    id: str
    name: str
    email: str
    display_name: str
    has_2fa: str
    is_admin: str

def create_from_dict(user_dict: Dict,
                     verbose: bool) -> User or UserSuccinct:
    """ Create a User object from a dict response from the Slack API

    Args:
        verbose: Whether to output a full User object, or use
            less verbose succinct class
        user_dict: dict/JSON format data from Slack API
    Returns:
        A new User object
    """

    if verbose:
        return User(
            id=user_dict.get('id'),
            name=user_dict.get('name'),
            deleted=user_dict.get('deleted'),
            real_name=user_dict.get('real_name'),
            tz=user_dict.get('tz'),
            tz_label=user_dict.get('tz_label'),
            tz_offset=user_dict.get('tz_offset'),
            title=user_dict.get('profile').get('title'),
            phone=user_dict.get('profile').get('phone'),
            skype=user_dict.get('profile').get('skype'),
            display_name=user_dict.get('profile').get('display_name'),
            email=user_dict.get('profile').get('email'),
            first_name=user_dict.get('profile').get('first_name'),
            last_name=user_dict.get('profile').get('last_name'),
            is_admin=user_dict.get('is_admin'),
            is_owner=user_dict.get('is_owner'),
            is_primary_owner=user_dict.get('is_primary_owner'),
            is_restricted=user_dict.get('is_restricted'),
            is_ultra_restricted=user_dict.get('is_ultra_restricted'),
            is_bot=user_dict.get('is_bot'),
            updated=_convert_timestamp(user_dict.get('updated')),
            has_2fa=user_dict.get('has_2fa')
        )
    else:
        return UserSuccinct(
            id=user_dict.get('id'),
            name=user_dict.get('name'),
            display_name=user_dict.get('profile').get('display_name'),
            has_2fa=user_dict.get('has_2fa'),
            is_admin=user_dict.get('is_admin'),
            email=user_dict.get('profile').get('email')
        )


# this is what I want
import my_module as m
import nn

class CustomBlock(m.Compute):
    def __init__(self, input_shape, out_channel, hidden_channel):
        batch, in_channel, H, W = input_shape
        self.hidden_channel = hidden_channel
        self.out_channel = out_channel
        self.__compute__ = self.define_compute

        self.weight1 = m.placeholder(shape=[in_channel, hidden_channel // in_channel, 3, 3], dtype="float32")
        self.weight2 = m.placeholder(shape=[out_channel, hidden_channel], dtype="float32")

    def define_compute(self, inputs):
        input_shape = inputs.shape
        batch, in_channel, H, W = input_shape
        hidden_channel = self.hidden_channel
        out_channel = self.out_channel

        ri, rj = m.reduce_axis((0, 3)), m.reduce_axis((0, 3))
        factor = hidden_channel // in_channel
        out1 = m.compute(
            (batch, hidden_channel, H, W),
            lambda b, c, i, j:
                m.sum(
                    inputs[b, c // factor, i + ri, j + rj] *
                    self.weight1[c // factor, c % factor, ri, rj],
                    axis=[ri, rj]
                    )
        )
        rc = m.reduce_axis((0, hidden_channel))
        out2 = m.compute(
            (batch, out_channel, H, W),
            lambda b, c, i, j:
                m.sum(out1[b, rc, i, j] * self.weight2[c, rc], axis=[rc])
        )
        return out2

    def forward(self, inputs):
        return self.__compute__(inputs)

inputs = m.placeholder(shape=[1, 3, 224, 224], dtype="float32")

# this should use the library such as cuDNN
conv = nn.Conv2d(inputs, out_channel=32, kernel=[3, 3], stride=2, padding=1)

# this is a user-defined function block
block = CustomBlock(conv.shape, 32, 64)

result = block.forward(conv)

# create the computation graph with optimization
compute_graph = m.create_graph(result)

# link to library and generate code for user-defined functions
runnable = m.deploy(compute_graph, target="cuda")

# run the graph
runnable.run()


"""
@Author:    chenghua.Wang
@file:      src/GUI/CurrentTableStatus.py
@brief:     Load and store current TableView is showing witch table in sql.
"""
class CurrentTableStatus:
    def __init__(self, TableName):
        self.TableName = TableName

    def Update(self, TableName, data, describe):
        self.TableName = TableName
        self.data = data
        self.describe = describe
        self.Row = len(self.describe)
        if self.Row == 0:
            self.Col = 0
        else:
            self.Col = len(self.describe[0])


import re

# stack solution pretty straight forward
# this solution is good for coding
class Solution:
    def calculate(self, s: str) -> int:
        if not s:
            return 0
        s = s.replace(" ", "")  # remove all spaces
        L = re.findall('[0-9.]+|.', s)  # separate digits and operators 42/3 -- 【'42'，'/'，'3'】

        i = 0
        stack = []  # holds the values and + - operators (get rid of *,/)
        while i <= len(L) - 1:
            if L[i] != '*' and L[i] != '/':
                stack.append(L[i])
                i += 1
            else:
                val = stack.pop()
                if L[i] == '*':
                    stack.append(int(val) * int(L[i + 1]))
                else:
                    stack.append(int(val) / int(L[i + 1]))
                i += 2

        i = 0
        stack2 = []  # holds the values (get rid of +,-)
        while i <= len(stack) - 1:
            if stack[i] != '+' and stack[i] != '-':
                stack2.append(stack[i])
                i += 1
            else:

                val = stack2.pop()
                if stack[i] == '+':
                    stack2.append(int(val) + int(stack[i + 1]))
                else:
                    stack2.append(int(val) - int(stack[i + 1]))
                i += 2
        return int(stack2[0])

# 以下为标准答案， 写着容易但是理解难一点。
class Solution:
    def calculate(self, s: str) -> int:
        # 3-2*8+7/6
        # [3, -2, ]
        # [3,-16,]
        # [3, -16,7]
        # [3,-16,1]
        if not s:
            return 0
        temp = s.split(' ')
        s = ''.join(temp)
        s = '+' + s
        i = 0
        stack = []
        while i <= len(s) - 1:
            if s[i] == '+':
                digits = self.getInt(s, i)
                stack.append(int(digits))
                i += len(digits) + 1
            elif s[i] == '-':
                digits = self.getInt(s, i)
                stack.append(-int(digits))
                i += len(digits) + 1
            elif s[i] == "*":
                digits = self.getInt(s, i)
                val = stack.pop()
                stack.append(val * int(digits))
                i += len(digits) + 1
            elif s[i] == '/':
                digits = self.getInt(s, i)
                val = stack.pop()
                stack.append(int(val / int(digits)))
                i += len(digits) + 1
            else:
                print('error')

        return sum(stack)

    def getInt(self, s, i):
        ind = i + 1
        while ind <= len(s) - 1 and s[ind].isdigit():
            ind += 1
        return s[i + 1:ind]


import typing
import os
import dataclasses

class Role(typing.Protocol):
    def get_arn(self) -> str:
        ...

@dataclasses.dataclass
class BucketAccessConfiguration:
    bucket_arn: str
    bucket_paths: typing.Optional[typing.Sequence[os.PathLike]] = None


#!/usr/bin/env python
# coding: utf-8
#SBATCH --time=100:00:00

### #SBATCH -p small --exclusive
#SBATCH -p gpu --gres=gpu:1 --mem=8GB

from argparse import ArgumentParser
import torch
import numpy as np

import pytorch_lightning as pl
from pytorch_lightning.loggers import TensorBoardLogger

from bgforces.ala2 import Ala2Data, Ala2Generator

def main():

    parser = ArgumentParser()
    parser = pl.Trainer.add_argparse_args(parser)#, gpus=0, min_epochs=5, max_epochs=20)
    parser = Ala2Generator.add_model_specific_args(parser)
    parser = Ala2Data.add_model_specific_args(parser)
    parser.add_argument("--n-samples", type=int, default=10000)
    args = parser.parse_args()

    # Data
    data = Ala2Data(**vars(args))
    data.prepare_data()
    data.setup()

    # Model
    gen = Ala2Generator(**vars(args))

    # Trainer
    logger = TensorBoardLogger("logs", name=f"a2_{data.slice}")
    #checkpoint_callback = ModelCheckpoint(monitor='val_loss')
    trainer = pl.Trainer.from_argparse_args(args, logger=logger)#, callbacks=[checkpoint_callback])

    # Training
    trainer.fit(gen, data)

    # Sampling
    print("Sample best model...")
    loaded = Ala2Generator.load_from_checkpoint(
        trainer.checkpoint_callback.best_model_path
    )
    with torch.no_grad():
        samples = []
        target_energies = []
        model_energies = []
        while len(samples) < args.n_samples:
            xyz = loaded.model.sample(min(256, args.n_samples-len(samples)))
            samples.extend(list(xyz.cpu().numpy()))
            tar = loaded.model._target.energy(xyz)
            target_energies.extend(list(tar.cpu().numpy()))
            mod = loaded.model.energy(xyz)
            model_energies.extend(list(mod.cpu().numpy()))
    np.savez(
        trainer.checkpoint_callback.best_model_path+".npz",
        samples=samples,
        u_target=target_energies,
        u_model=model_energies
    )
    print("Best model:", trainer.checkpoint_callback.best_model_path)
    import sys; sys.exit(0)

if __name__ == "__main__":
    main()


import os

class Logger(object):

    def __init__(self, name, save_path, type, num_labels=-1):

        self.type_list = ['patches', 'features', 'predicts', 'train']

        assert isinstance(name, str), \
            ">>   [LOGGER] Name is not a string"

        assert os.path.isdir(save_path), \
            ">>   [LOGGER] Save path is not a directory"

        assert type in self.type_list, \
            ">>   [LOGGER] Wrong logger type"

        self.name = name
        self.save_path = save_path
        self.type = type

        print(">>   [LOGGER] Creating log on: " + self.save_path)

        if((self.type != 'predicts') and (self.type != 'train')):

            assert num_labels > 0, \
                ">>   [LOGGER] Number of labels must be positive"

            self.num_labels = num_labels

            self.num_dir = 0
            self.num_files = 0

            self.count_label = {}
            for i in range(self.num_labels):
                self.count_label[i] = 0

            self.count_split = {
                'test': 0,
                'train': 0,
                'eval': 0
            }

        if(self.type == 'patches'):
            self.count_patch = {
                'body': 0,
                'face': 0,
                'relation': 0,
                'context': 0,
                'object': 0
            }

        if(self.type == 'features'):
            self.count_feature = {
                'objects_attention': 0,
                'context_emotion': 0,
                'context_activity': 0,
                'body_activity': 0,
                'body_gender': 0,
                'body_age': 0,
                'body_clothing': 0
            }

        if(self.type == 'predicts'):
            self.predicts = {}

        if(self.type == 'train'):

            self.metrics = ['loss', 'accuracy', 'precision']
            self.modes = ['max', 'mean', 'vote']

            self.configs = []
            self.total_epochs = "Not logged yet"
            self.total_time = "Not logged yet"
            self.best_loss_max = "    - Not logged yet"
            self.best_loss_mean = "    - Not logged yet"
            self.best_loss_vote = "    - Not logged yet"
            self.best_accuracy_max = "    - Not logged yet"
            self.best_accuracy_mean = "    - Not logged yet"
            self.best_accuracy_vote = "    - Not logged yet"
            self.best_precision_max = "    - Not logged yet"
            self.best_precision_mean = "    - Not logged yet"
            self.best_precision_vote = "    - Not logged yet"

    def log_dir(self):

        assert (self.type != 'predicts') and (self.type != 'train'), \
            ">>   [LOGGER] This logger doesn't have this function"

        self.num_dir += 1

    def log_patch(self, split, label, patch):

        assert self.type == 'patches', \
            ">>   [LOGGER] This logger is not a patcher"

        assert split in self.count_split, \
            ">>   [LOGGER] Split type doesn't exists"

        assert label in self.count_label, \
            ">>   [LOGGER] Label number doesn't exists"

        assert patch in self.count_patch, \
            ">>   [LOGGER] Patch type doesn't exists"

        self.num_files += 1
        self.count_split[split] += 1
        self.count_label[label] += 1
        self.count_patch[patch] += 1

    def log_feature(self, split, label, feature):

        assert self.type == 'features', \
            ">>   [LOGGER] This logger is not a featurer"

        assert split in self.count_split, \
            ">>   [LOGGER] Split type doesn't exists"

        assert label in self.count_label, \
            ">>   [LOGGER] Label number doesn't exists"

        assert feature in self.count_feature, \
            ">>   [LOGGER] Feature type doesn't exists"

        self.num_files += 1
        self.count_split[split] += 1
        self.count_label[label] += 1
        self.count_feature[feature] += 1

    def log_predict(self, relation, predict):

        assert self.type == 'predicts', \
            ">>   [LOGGER] This logger is not a predictor"

        self.predicts[relation] = predict

    def log_configs(self, configurations):

        assert self.type == 'train', \
            ">>   [LOGGER] This logger is not a trainer"

        self.configs = configurations

    def log_metric(self, metric, mode, value):

        assert self.type == 'train', \
            ">>   [LOGGER] This logger is not a trainer"

        assert metric in self.metrics, \
            ">>   [LOGGER] Invalid metric"

        assert mode in self.modes, \
            ">>   [LOGGER] Invalid mode"

        if(metric == 'loss'):
            if(mode == 'max'):
                self.best_loss_max = value

            elif(mode == 'mean'):
                self.best_loss_mean = value

            else:
                self.best_loss_vote = value

        elif(metric == 'accuracy'):
            if(mode == 'max'):
                self.best_accuracy_max = value

            elif(mode == 'mean'):
                self.best_accuracy_mean = value

            else:
                self.best_accuracy_vote = value

        else:
            if(mode == 'max'):
                self.best_precision_max = value

            elif(mode == 'mean'):
                self.best_precision_mean = value

            else:
                self.best_precision_vote = value

    def log_epochs(self, epochs):

        assert self.type == 'train', \
            ">>   [LOGGER] This logger is not a trainer"

        self.total_epochs = epochs

    def log_time(self, time):

        assert self.type == 'train', \
            ">>   [LOGGER] This logger is not a trainer"

        self.total_time = time

    def save(self):

        print(">>   [LOGGER] Logging... ")

        if(self.type == 'train'):

            path = os.path.join(
                self.save_path, "configs_" + self.name + ".yaml")

            with open(path, "w") as file:
                file.write("#[CONFIGURATIONS]\n")
                for conf in self.configs:
                    file.write(conf + "\n")

            path = os.path.join(
                self.save_path, "scores_" + self.name + ".yaml")

            with open(path, "w") as file:
                file.write("#[TRAINING]\n")
                file.write("Epochs: " + self.total_epochs + "\n")
                file.write("Time: " + self.total_time + "\n")

                file.write("#[BEST SCORES]\n")
                file.write("Loss:\n")
                file.write("  - Max:\n")
                file.write(self.best_loss_max + "\n")

                file.write("  - Mean:\n")
                file.write(self.best_loss_mean + "\n")

                file.write("  - Vote:\n")
                file.write(self.best_loss_vote + "\n")

                file.write("Accuracy:\n")
                file.write("  - Max:\n")
                file.write(self.best_accuracy_max + "\n")

                file.write("  - Mean:\n")
                file.write(self.best_accuracy_mean + "\n")

                file.write("  - Vote:\n")
                file.write(self.best_accuracy_vote + "\n")

                file.write("Precision:\n")
                file.write("  - Max:\n")
                file.write(self.best_precision_max + "\n")

                file.write("  - Mean:\n")
                file.write(self.best_precision_mean + "\n")

                file.write("  - Vote:\n")
                file.write(self.best_precision_vote + "\n")

        else:

            path = os.path.join(self.save_path, "logs_" + self.name + ".yaml")

            with open(path, "w") as file:
                if(self.type != 'predicts'):
                    file.write("#[TOTAL]\n")
                    file.write("dir: %d\n" % self.num_dir)
                    file.write("files: %d\n" % self.num_files)

                    file.write("#[SPLITS]\n")
                    for key in self.count_split:
                        file.write("%s: %d\n" % (key, self.count_split[key]))

                    file.write("#[LABELS]\n")
                    for i in range(self.num_labels):
                        file.write("%d: %d\n" % (i, self.count_label[i]))

                if(self.type == 'patches'):
                    file.write("#[PATCHES]\n")
                    for key in self.count_patch:
                        file.write(str(key) + ": %d\n" % self.count_patch[key])

                if(self.type == 'features'):
                    file.write("#[FEATURES]\n")
                    for key in self.count_feature:
                        file.write(str(key) + ": %d\n" %
                                   self.count_feature[key])

                if(self.type == 'predicts'):
                    file.write("#[PREDITCS]\n")
                    for key in self.predicts:
                        file.write(str(key) + ": %d\n" % self.predicts[key])

        print(">>   [LOGGER] ... done!")


import numpy as np
from prettytable import PrettyTable
from _pydecimal import Decimal
from scipy.stats import f
from scipy.stats import t
from random import randrange
from math import sqrt
from math import fabs as fab

def a(first, second):
    need_a = 0
    for j in range(N):
        need_a += matrix_x[j][first - 1] * matrix_x[j][second - 1] / N
    return need_a

def find(number):
    a = 0
    for j in range(N):
        a += average_y[j] * matrix_x[j][number - 1] / 15
    return a

def check(b_lst, k):
    y_i = b_lst[0] + b_lst[1] * matrix[k][0] + b_lst[2] * matrix[k][1] + b_lst[3] * matrix[k][2] + \
          b_lst[4] * matrix[k][3] + b_lst[5] * matrix[k][4] + b_lst[6] * matrix[k][5] + b_lst[7] * matrix[k][6] + \
          b_lst[8] * matrix[k][7] + b_lst[9] * matrix[k][8] + b_lst[10] * matrix[k][9]
    return y_i

counter1 = 0
counter2 = 0

# Variant №208
for i in range(100):
    m, d = 3, 0
    p = 0.95
    N = 15

    x1_min, x1_max = -30, 0
    x2_min, x2_max = 10, 60
    x3_min, x3_max = 10, 35
    x01 = (x1_max + x1_min) / 2
    x02 = (x2_max + x2_min) / 2
    x03 = (x3_max + x3_min) / 2
    delta_x1 = x1_max - x01
    delta_x2 = x2_max - x02
    delta_x3 = x3_max - x03

    matrix_pfe = [
        [-1, -1, -1, +1, +1, +1, -1, +1, +1, +1],
        [-1, -1, +1, +1, -1, -1, +1, +1, +1, +1],
        [-1, +1, -1, -1, +1, -1, +1, +1, +1, +1],
        [-1, +1, +1, -1, -1, +1, -1, +1, +1, +1],
        [+1, -1, -1, -1, -1, +1, +1, +1, +1, +1],
        [+1, -1, +1, -1, +1, -1, -1, +1, +1, +1],
        [+1, +1, -1, +1, -1, -1, -1, +1, +1, +1],
        [+1, +1, +1, +1, +1, +1, +1, +1, +1, +1],
        [-1.73, 0, 0, 0, 0, 0, 0, 2.9929, 0, 0],
        [+1.73, 0, 0, 0, 0, 0, 0, 2.9929, 0, 0],
        [0, -1.73, 0, 0, 0, 0, 0, 0, 2.9929, 0],
        [0, +1.73, 0, 0, 0, 0, 0, 0, 2.9929, 0],
        [0, 0, -1.73, 0, 0, 0, 0, 0, 0, 2.9929],
        [0, 0, +1.73, 0, 0, 0, 0, 0, 0, 2.9929],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

    matrix_x = [[] for x in range(N)]
    for i in range(len(matrix_x)):
        if i < 8:
            x_1 = x1_min if matrix_pfe[i][0] == -1 else x1_max
            x_2 = x2_min if matrix_pfe[i][1] == -1 else x2_max
            x_3 = x3_min if matrix_pfe[i][2] == -1 else x3_max

        else:
            x_lst = (
            matrix_pfe[i][0] * delta_x1 + x01, matrix_pfe[i][1] * delta_x2 + x02, matrix_pfe[i][2] * delta_x3 + x03)
            x_1, x_2, x_3 = x_lst
        matrix_x[i] = [x_1, x_2, x_3, x_1 * x_2, x_1 * x_3, x_2 * x_3, x_1 * x_2 * x_3, x_1 ** 2, x_2 ** 2, x_3 ** 2]

    adequacy, homogeneity = False, False
    while not adequacy:
        matrix_y = [[(8.0 + 5.3 * matrix_x[j][0] + 0.5 * matrix_x[j][1] + 5.6 * matrix_x[j][2] + 3.2 * matrix_x[j][0] *
                      matrix_x[j][0] + 0.7 * matrix_x[j][1] * matrix_x[j][1] + 4.1 * matrix_x[j][2] * matrix_x[j][2] + 8.9 *
                      matrix_x[j][0] * matrix_x[j][1] + 0.5 * matrix_x[j][0] * matrix_x[j][2] + 1.5 * matrix_x[j][1] *
                      matrix_x[j][2] + 1.2 * matrix_x[j][0] * matrix_x[j][1] * matrix_x[j][2] + randrange(0, 10) - 5) for i
                     in range(m)] for j in range(N)]
        average_x = []
        for column in range(len(matrix_x[0])):
            number_lst = []
            for rows in range(len(matrix_x)):
                number_lst.append(matrix_x[rows][column])
            average_x.append(sum(number_lst) / len(number_lst))

        average_y = []
        for rows in range(len(matrix_y)):
            average_y.append(sum(matrix_y[rows]) / len(matrix_y[rows]))

        matrix = [(matrix_x[i] + matrix_y[i]) for i in range(N)]
        mx_i = average_x
        my = sum(average_y) / 15

        unk = [
            [1, mx_i[0], mx_i[1], mx_i[2], mx_i[3], mx_i[4], mx_i[5], mx_i[6], mx_i[7], mx_i[8], mx_i[9]],
            [mx_i[0], a(1, 1), a(1, 2), a(1, 3), a(1, 4), a(1, 5), a(1, 6), a(1, 7), a(1, 8), a(1, 9), a(1, 10)],
            [mx_i[1], a(2, 1), a(2, 2), a(2, 3), a(2, 4), a(2, 5), a(2, 6), a(2, 7), a(2, 8), a(2, 9), a(2, 10)],
            [mx_i[2], a(3, 1), a(3, 2), a(3, 3), a(3, 4), a(3, 5), a(3, 6), a(3, 7), a(3, 8), a(3, 9), a(3, 10)],
            [mx_i[3], a(4, 1), a(4, 2), a(4, 3), a(4, 4), a(4, 5), a(4, 6), a(4, 7), a(4, 8), a(4, 9), a(4, 10)],
            [mx_i[4], a(5, 1), a(5, 2), a(5, 3), a(5, 4), a(5, 5), a(5, 6), a(5, 7), a(5, 8), a(5, 9), a(5, 10)],
            [mx_i[5], a(6, 1), a(6, 2), a(6, 3), a(6, 4), a(6, 5), a(6, 6), a(6, 7), a(6, 8), a(6, 9), a(6, 10)],
            [mx_i[6], a(7, 1), a(7, 2), a(7, 3), a(7, 4), a(7, 5), a(7, 6), a(7, 7), a(7, 8), a(7, 9), a(7, 10)],
            [mx_i[7], a(8, 1), a(8, 2), a(8, 3), a(8, 4), a(8, 5), a(8, 6), a(8, 7), a(8, 8), a(8, 9), a(8, 10)],
            [mx_i[8], a(9, 1), a(9, 2), a(9, 3), a(9, 4), a(9, 5), a(9, 6), a(9, 7), a(9, 8), a(9, 9), a(9, 10)],
            [mx_i[9], a(10, 1), a(10, 2), a(10, 3), a(10, 4), a(10, 5), a(10, 6), a(10, 7), a(10, 8), a(10, 9), a(10, 10)]]

        k = [my, find(1), find(2), find(3), find(4), find(5), find(6),
             find(7), find(8), find(9), find(10)]

        beta = np.linalg.solve(unk, k)
        print("Рівняння регресії")
        print("y = {:.3f} + {:.3f} * x1 + {:.3f} * x2 + {:.3f} * x3 + {:.3f} * x1x2 + {:.3f} * x1x3 + {:.3f} * x2x3"
              "+ {:.3f} * x1x2x3 + {:.3f} * x11^2 + {:.3f} * x22^2 + {:.3f} * x33^2 \n\nПеревірка"
              .format(beta[0], beta[1], beta[2], beta[3], beta[4], beta[5], beta[6], beta[7], beta[8], beta[9], beta[10]))
        for i in range(N):
            print("y{} = {:.3f} ≈ {:.3f}".format((i + 1), check(beta, i), average_y[i]))

        while not homogeneity:
            dispersion_y = [0.0 for x in range(N)]
            print("\n\n\n")
            for i in range(N):
                dispersion_i = 0
                for j in range(m):
                    dispersion_i += (matrix_y[i][j] - average_y[i]) ** 2
                dispersion_y.append(dispersion_i / (m - 1))
            f1 = m - 1
            f2 = N
            f3 = f1 * f2
            q = 1 - p
            Gp = max(dispersion_y) / sum(dispersion_y)

            print("Матриця планування:")

            x_norm = np.array(matrix_x)
            matrix_plan = np.array(matrix_y)
            my_table = np.hstack((x_norm, matrix_plan))
            table = PrettyTable()
            table.field_names = ["X1", "X2", "X3", "X1X2", "X1X3", "X2X3", "X1X2X3", "X1^2", "X2^2", "X3^2", "Y1", "Y2", "Y3"]
            for i in range(len(my_table)):
                table.add_row(my_table[i])

            print(table)

            print("Критерій Кохрена")

            f2 += 1
            partResult1 = q / (f2 - 1)
            params = [partResult1, f1, (f2 - 1 - 1) * f1]
            fisher = f.isf(*params)
            result = fisher / (fisher + (f2 - 1 - 1))
            Gt = Decimal(result).quantize(Decimal('.0001')).__float__()
            if Gt > Gp:
                print("Дисперсія однорідна при q = {:.2f}\n".format(q))
                homogeneity = True
            else:
                print("Дисперсія не однорідна при q = {:.2f}\n".format(q))
                m += 1

        dispersion_b2 = sum(dispersion_y) / (N * N * m)

        dispersion_b = sqrt(dispersion_b2)
        number_x = 10
        for column in range(number_x + 1):
            t_practice = 0
            t_theoretical = Decimal(abs(t.ppf(q / 2, f3))).quantize(Decimal('.0001')).__float__()
            for row in range(N):
                if column == 0:
                    t_practice += average_y[row] / N
                else:
                    t_practice += average_y[row] * matrix_pfe[row][column - 1]
            if fab(t_practice / dispersion_b) < t_theoretical:
                beta[column] = 0

        student_lst = list(beta)
        print("Отримане рівняння регресії з урахуванням критерія Стьюдента")
        print("y = {:.3f} + {:.3f} * x1 + {:.3f} * x2 + {:.3f} * 3 + {:.3f} * x1x2 + {:.3f} * x1x3 + {:.3f} * x2x3"
              "+ {:.3f} * x1x2x3 + {:.3f} * x11^2 + {:.3f} * x22^2 + {:.3f} * x33^2 \n\nПеревірка"
              .format(student_lst[0], student_lst[1], student_lst[2], student_lst[3], student_lst[4], student_lst[5],
                      student_lst[6], student_lst[7], student_lst[8], student_lst[9], student_lst[10]))
        for i in range(N):
            print("y{} = {:.3f} ≈ {:.3f}".format((i + 1), check(student_lst, i), average_y[i]))

        print("\nКритерій Фішера")
        d = 11 - student_lst.count(0)
        dispersion_ad = 0
        f4 = N - d
        for row in range(len(average_y)):
            dispersion_ad += (m * (average_y[row] - check(student_lst, row))) / (N - d)
        F_practice = dispersion_ad / dispersion_b2
        F_theoretical = Decimal(abs(f.isf(q, f4, f3))).quantize(Decimal('.0001')).__float__()
        if F_practice < F_theoretical:
            print("Рівняння регресії адекватне стосовно оригіналу")
            counter2 += 1
            adequacy = True
        else:
            counter1 += 1
            print("Рівняння регресії неадекватне стосовно оригіналу. Потрібно  провести експеремент повторно!")

print("З ефектом взаємодії {0}\nЗ квадратичними членами {1}".format(counter1, counter2))


# darcy merilan database... please note this is a work in progress and does not illustrate my full understanding of python and sql
import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()

cur.execute('''CREATE Table style (
              ID INT PRIMARY KEY     NOT NULL,
              style_name text NOT NULL
              )''')

cur.execute('''CREATE TABLE recipie (
             ID INT PRIMARY KEY     NOT NULL,
             r_name   text NOT NULL,
             calories real
             )''')

cur.execute("""CREATE TABLE Ingrediants (
              ID INT PRIMARY KEY     NOT NULL,
 	          Name     text NOT NULL,
 	          Price    real,
 	          Amount   real,
 	         Measurement   text
 	        )""")

con.commit

class recipebook:
    def __init__(self):
        self.menu_option = int(input("what is your selection?"))

    def menu():
        print(" ")
        print("Welcome to Your Cheif Recipie Table, Please Select the following:")
        print(" ")
        print ("0. Exit Program")
        print("1. Show all Recipes")
        print("2. Show all Base")
        print("3. Insert Base")
        print("4. Delete Base")
        print("5. Insert Recipe")
        print("6. Delete Recipe")
        print("7. Insert Ingrediant")
        print("8. Delete Ingrediant")
        print("9. Modify Ingrediant")

    def option_0():
        print(" ")
        print("Thank you for trying out my program")
        print(" ")
        con.close

    def option_1():
        try:
            cur.execute("SELECT * FROM recipie")
            print(cur.fetchall())
            con.commit
        except:
            print (" Oh, we cannot seem to find your recipie please insert a recipie into the list!")

    def option_2():
        try:
            cur.execute("SELECT * FROM style")
            con.commit()
            print(cur.fetchall())
        except:
            print (" Oh, we cannot seem to find your Base please insert the name of the Base for your recipie into the list!")

    def option_3():
        try:
            id_num = int(input("Whats the ID #:"))
            s_name = input("What is the Style name: ")
            cur.execute("INSERT INTO style (ID, style_name) values ('{}');").format(id_num,s_name)
            con.commit
            print(cur.fetchall())
        except:
            print (" Oh, we cannot seem to find your recipie please insert the name of the recipie below to list it!")

    def option_4():
        # This is the delete option, i am trying to solve how to delete trough a user input
        #cur.execute("Delete From style where ('{}');")
        pass

    def option_5():
        try:
            id_num = int(input("Whats the ID #:"))
            re_name = input("What is the recipe's name: ")
            calo = int(input("What is the recipe's calories: "))
            cur.execute("INSERT INTO recipie (ID , r_name, calories) values ('{}','{}');").format(id_num,re_name, calo)
            con.commit
            print(cur.fetchall())
        except:
            print (" Oh, we cannot seem to find your recipie please insert the name of the recipie below to list it!")

    def option_6():
        # This is the delete option, i am trying to solve how to delete trough a user input
        #cur.execute("Delete From recipie where ('{}');")
        pass

    def option_7():
        try:
            id_num = int(input("Whats the ID #:"))
            in_name = input("What is the ingrediants's name: ")
            pri = float(input("What is the ingrediants's prince: "))
            amo = float(input("How much do you need: "))
            meas = input("What is the measurment: ")
            cur.execute("INSERT INTO Ingrediants (ID ,Name, Price,Amount,Measurement)values ('{}','{}','{}','{}','{}');").format(id_num,in_name, pri, amo, meas)
            con.commit
            print(cur.fetchall())
        except:
            print (" Oh, we cannot seem to find your ingrediants, please try again!")

    def option_8():
        # This is the delete option, i am trying to solve how to delete trough a user input
        #try:
        #    del_ing = input("Please delete an ingrediant from the recipebook: ")
        #    cur.execute("Delete From Ingrediants where ('{}');")
        #except:
        #    print ("Can Not Compute, Please try again")
        pass

    def option_9():
        # This is the modify option, to be updated later
        pass

recipebook.menu()
menu_option = int(input(""))

while recipebook.menu() != 0:
    if menu_option == 1:
        recipebook.option_1()
    elif menu_option == 2:
        recipebook.option_2()
    elif menu_option == 3:
        recipebook.option_3()
    elif menu_option == 4:
        recipebook.option_4()
    elif menu_option == 5:
        recipebook.option_5()
    elif menu_option == 6:
        recipebook.option_6()
    elif menu_option == 7:
        recipebook.option_7()
    elif menu_option == 8:
        recipebook.option_8()
    elif menu_option == 9:
        recipebook.option_9()
    else:
        recipebook.option_0()
        break

    recipebook.menu()
    menu_option = int(input(""))

#  print (recipebook)
# print(cur.fetchall())


from typing import Dict

from fastapi import APIRouter

from back.dependency.security import api_security
from back.init.check import check_host_port
from back.init.statics import get_static_file
from back.model.scope import ScopeEnum

from .ping import router as ping

PORTS = [5430, 5431, 5555, 6379, 6380, 8080, 9000, 9001, 9200]

router = APIRouter(prefix="/init")

router.include_router(ping)

@router.get(
    "/check-host-ports",
    response_model=Dict[int, bool],
    dependencies=[api_security([ScopeEnum.init_check_host_ports_get.value])],
)
def check_host_ports() -> Dict[int, bool]:
    host_ports = {}
    for port in PORTS:
        is_port = not check_host_port(port)
        host_ports[port] = is_port

    return host_ports

@router.get(
    "/download-redoc",
    dependencies=[api_security([ScopeEnum.init_download_redoc_get.value])],
)
async def download_redoc():
    redoc_url = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"
    redoc_map_url = (
        "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js.map"
    )

    await get_static_file(redoc_url)
    await get_static_file(redoc_map_url)

@router.get(
    "/download-swagger",
    dependencies=[api_security([ScopeEnum.init_download_swagger_get.value])],
)
async def download_swagger():
    swagger_url = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui-bundle.js"
    swagger_map_url = (
        "https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui-bundle.js.map"
    )

    swagger_css_url = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui.css"
    swagger_css_map_url = (
        "https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui.css.map"
    )

    await get_static_file(swagger_url)
    await get_static_file(swagger_map_url)
    await get_static_file(swagger_css_url)
    await get_static_file(swagger_css_map_url)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        output = 0

        def dfs(root , maxVal ):
            nonlocal output
            if not root:
                return

            if root.val >= maxVal:
                output += 1
            maxVal = max(maxVal , root.val)

            dfs(root.left , maxVal )
            dfs(root.right , maxVal )

            return output

        return dfs(root , root.val)

Daily Questions ( Sept 2022)/1448. Count Good Nodes in Binary Tree.py


import datetime
import decimal
import logging
from decimal import ROUND_HALF_UP, Decimal

from structlog import wrap_logger

from transform.transformers.common_software.cs_formatter import CSFormatter
from transform.transformers.survey import Survey
from transform.transformers.survey_transformer import SurveyTransformer

logger = wrap_logger(logging.getLogger(__name__))

class MBSTransformer(SurveyTransformer):
    """Perform the transforms and formatting for the MBS survey."""

    @staticmethod
    def round_mbs(value):
        """MBS rounding is done on a ROUND_HALF_UP basis and values are divided by 1000 for the pck"""
        try:
            # Set the rounding context for Decimal objects to ROUND_HALF_UP
            decimal.getcontext().rounding = ROUND_HALF_UP
            return Decimal(round(Decimal(float(value))) / 1000).quantize(1)

        except TypeError:
            logger.info("Tried to quantize a NoneType object. Returning None")
            return None

    @staticmethod
    def convert_str_to_int(value):
        """Convert submitted data to int in the transform"""
        try:
            return int(value)
        except TypeError:
            logger.info("Tried to transform None to int. Returning None.")
            return None

    @staticmethod
    def parse_timestamp(text):
        """Parse a text field for a date or timestamp.

        Date and time formats vary across surveys.
        This method reads those formats.

        :param str text: The date or timestamp value.
        :rtype: Python date or datetime.

        """

        cls = datetime.datetime

        if text:
            if text.endswith("Z"):
                return cls.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(
                    tzinfo=datetime.timezone.utc
                )

            try:
                return cls.strptime(text, "%Y-%m-%dT%H:%M:%S.%f%z")

            except ValueError:
                pass

            try:
                return cls.strptime(text.partition(".")[0], "%Y-%m-%dT%H:%M:%S")

            except ValueError:
                pass

            try:
                return cls.strptime(text, "%Y-%m-%d").date()

            except ValueError:
                pass

            try:
                return cls.strptime(text, "%d/%m/%Y").date()

            except ValueError:
                pass

            if len(text) != 6:
                return None

            try:
                return cls.strptime(text + "01", "%Y%m%d").date()

            except ValueError:
                return None

    def __init__(self, response, seq_nr=0):

        super().__init__(response, seq_nr)

        self.employment_questions = ("51", "52", "53", "54")
        self.turnover_questions = ("49",)

        self.idbr_ref = {
            "0106": "T106G",
            "0111": "T111G",
            "0161": "T161G",
            "0117": "T117G",
            "0123": "T123G",
            "0158": "T158G",
            "0167": "T167G",
            "0173": "T173G",
            "0201": "MB01B",
            "0202": "MB01B",
            "0203": "MB03B",
            "0204": "MB03B",
            "0205": "MB15B",
            "0216": "MB15B",
            "0251": "MB51B",
            "0253": "MB53B",
            "0255": "MB65B",
            "0817": "T817G",
            "0823": "T823G",
            "0867": "T867G",
            "0873": "T873G",
        }

    def get_identifiers(self, batch_nr=0, seq_nr=0):
        """Parse common metadata from the survey.

        Return a named tuple which code can use to access the various ids and discriminators.

        :param int batch_nr: A batch number for the reply.
        :param int seq_nr: An image sequence number for the reply.

        """

        logger.info("Parsing data from submission")

        ru_ref = self.response.get("metadata", {}).get("ru_ref", "")
        ts = datetime.datetime.now(datetime.timezone.utc)
        ids = {
            "batch_nr": batch_nr,
            "seq_nr": seq_nr,
            "ts": ts,
            "tx_id": self.response.get("tx_id"),
            "survey_id": self.response.get("survey_id"),
            "instrument_id": self.response.get("collection", {}).get("instrument_id"),
            "submitted_at": Survey.parse_timestamp(
                self.response.get("submitted_at", ts.isoformat())
            ),
            "user_id": self.response.get("metadata", {}).get("user_id"),
            "ru_ref": "".join(i for i in ru_ref if i.isdigit()),
            "ru_check": ru_ref[-1] if ru_ref and ru_ref[-1].isalpha() else "",
            "period": self.response.get("collection", {}).get("period"),
        }

        for key, value in ids.items():
            if value is None:
                logger.error(f"Missing value for: {key}")
                return None

        return ids

    def check_employee_totals(self):
        """Populate qcode 51:54 based on d50"""
        if self.response["data"].get("d50") == "Yes":
            logger.info("Setting default values to 0 for question codes 51:54")
            return {q_id: 0 for q_id in self.employment_questions}

        else:
            logger.info("d50 not yes. No default values set for question codes 51:54.")
            employee_totals = {}

            for q_id in self.employment_questions:
                # QIDSs 51 - 54 aren't compulsory. If a value isn't present,
                # then it doesn't need to go in the PCK file.
                try:
                    employee_totals[q_id] = self.convert_str_to_int(
                        self.response["data"].get(q_id)
                    )
                except TypeError:
                    logger.info(f"No answer supplied for {q_id}. Skipping.")

            return employee_totals

    def check_turnover_totals(self):
        """Populate qcode 49 based on d49"""
        if self.response["data"].get("d49") == "Yes":
            logger.info("Setting default value to 0 for question code 49")
            return {q_id: 0 for q_id in self.turnover_questions}

        else:
            logger.info("d49 not yes. No default values set for question code 49.")
            turnover_totals = {}

            for q_id in self.turnover_questions:
                try:
                    turnover_totals[q_id] = self.round_mbs(
                        self.response["data"].get(q_id)
                    )
                except TypeError:
                    logger.info(f"No answer supplied for {q_id}. Skipping.")

            return turnover_totals

    def survey_dates(self):
        """If questions 11 or 12 don't appear in the survey data, then populate
        them with the period start and end date found in the metadata
        """
        try:
            start_date = MBSTransformer.parse_timestamp(self.response["data"]["11"])
        except KeyError:
            logger.info("Populating start date using metadata")
            start_date = MBSTransformer.parse_timestamp(
                self.response.get("metadata", {})["ref_period_start_date"]
            )

        try:
            end_date = MBSTransformer.parse_timestamp(self.response["data"]["12"])
        except KeyError:
            logger.info("Populating end date using metadata")
            end_date = MBSTransformer.parse_timestamp(
                self.response.get("metadata", {})["ref_period_end_date"]
            )

        return {"11": start_date, "12": end_date}

    def _transform(self):
        """Perform a transform on survey data."""
        employee_totals = self.check_employee_totals()
        turnover_totals = self.check_turnover_totals()
        dates = self.survey_dates()

        logger.info(
            "Transforming data for {}".format(self.ids.ru_ref),
            tx_id=self.ids.tx_id
        )

        transformed_data = {
            "146": 1 if self.response["data"].get("146") is not None else 2,
            "40": self.round_mbs(self.response["data"].get("40")),
            "42": self.round_mbs(self.response["data"].get("42")),
            "43": self.round_mbs(self.response["data"].get("43")),
            "46": self.round_mbs(self.response["data"].get("46")),
            "47": self.round_mbs(self.response["data"].get("47")),
            "90": self.round_mbs(self.response["data"].get("90")),
            "50": MBSTransformer.convert_str_to_int(self.response["data"].get("50")),
            "110": MBSTransformer.convert_str_to_int(self.response["data"].get("110")),
        }

        return {
            k: v
            for k, v in {**transformed_data, **employee_totals, **turnover_totals, **dates}.items()
            if v is not None
        }

    def create_pck(self, img_seq=None):
        logger.info("Creating PCK", ru_ref=self.ids.ru_ref)
        pck_name = CSFormatter.pck_name(self.ids.survey_id, self.ids.tx_id)
        transformed_data = self._transform()
        pck = CSFormatter.get_pck(
            transformed_data,
            self.idbr_ref[self.ids.inst_id],
            self.ids.ru_ref,
            self.ids.ru_check,
            self.ids.period,
        )

        return pck_name, pck


import sys
import os

def main():
    #Display Title and Usage Texts
    print("Pharma-Code: BMI Calculator")
    print("Input the Weight (kg) and the Height (m) to calculate the BMI")

    #Receive Inputs
    weight = input("Input the Weight (kg): ")
    height = input("Input the Height (m): ")

    #Convert Inputs to Numerical Formats
    weight = convert_to_float(weight)
    height = convert_to_float(height)

    #Calculate BMI
    bmi = calculate_bmi(weight, height)
    bmi_category = get_bmi_category(bmi)

    #Display Result
    print("BMI: " + str(bmi))
    print("BMI Category: " + bmi_category)
    os.system("PAUSE")

def convert_to_float(value: str) -> float:
    try:
        return float(value)
    except:
        print("Invalid Input. Please, input numbers only.")
        sys.exit()

def calculate_bmi(weight: float, height: float) -> float:
    bmi = weight / height ** 2
    bmi = round(bmi, 1)
    return bmi

def get_bmi_category(bmi: float) -> str:
    if bmi < 18.5:
        return "Underweight"
    elif bmi >= 18.5 and bmi < 25:
        return "Normal"
    elif bmi >= 25 and bmi < 30:
        return "Overweight"
    else:
        return "Obese"

if __name__ == "__main__":
    main()