from step_functions.state_machine_resource import execute_state_machine
import click

# as per available non english ids https://docs.aws.amazon.com/polly/latest/dg/ntts-voices-main.html
NEURAL_VOICE_LIST = [
    "Vicki",
    "Bianca",
    "Takumi",
    "Seoyeon",
    "Camila",
    "Vitoria",
    "Ines",
    "Lucia",
    "Mia",
    "Lupe",
    "Lea",
    "Gabrielle",
    "Hannah",
    "Arlet",
]

# note some of comprehend services like sentiment are less restrictive but detect syntax only allows these
COMPREHEND_LANG_CODES = [
    "de",
    "pt",
    "en",
    "it",
    "fr",
    "es",
]

@click.command()
@click.option("--sf_name", help="Name of step function to execute")
@click.option("--target_lang_code", help="Lang to translate video into")
@click.option(
    "--voice_id",
    help="Polly voice id for synthesising text to speech. Must be available with neural engine option in AWS Polly",
)
@click.option(
    "--deploy/--no-deploy",
    default=False,
    help="Flag to determine whether to deploy new step function or not before execution",
)
@click.option(
    "--bucket",
    default="awstestnlp",
    help="s3 bucket containing the source and output files",
)
@click.option(
    "--source_filename", default="transcribe-sample.mp3", help="filename of source mp3",
)
@click.option(
    "--source_lang_code", default="en-US", help="language code for source video"
)
@click.option(
    "--job_name",
    default="Test",
    help="Name of transcription job to execute in step function",
)
@click.option(
    "--sf_role",
    default="StepFunctionAWSNLPServices",
    help="Name of IAM role assumed by step function",
)
def execute_nlp_state_machine(
    sf_name,
    target_lang_code,
    bucket,
    source_filename,
    source_lang_code,
    job_name,
    voice_id,
    deploy,
    sf_role,
):

    if voice_id in NEURAL_VOICE_LIST:
        engine = "neural"
    else:
        engine = "standard"

    if target_lang_code in COMPREHEND_LANG_CODES:
        skip_comprehend = False
    else:
        skip_comprehend = True

    sf_input = {
        "BucketName": bucket,
        "Source": f"s3://{bucket}/source/{source_lang_code}/{source_filename}",
        "TranscribeOutputKey": f"transcribe/{target_lang_code}/transcribed.json",
        "PollyVideoOutputKey": f"polly/{target_lang_code}/{voice_id}/",
        "PollyResponseOutputKey": f"polly/{target_lang_code}/response.json",
        "ComprehendOutputKey": f"comprehend/{target_lang_code}/response.json",
        "TranslateOutputKey": f"translate/{target_lang_code}/response.json",
        "SourceLanguageCode": source_lang_code,
        "TargetLanguageCode": target_lang_code,
        "JobName": job_name,
        "VoiceId": voice_id,
        "EngineType": engine,
        "SkipComprehend": skip_comprehend,
    }

    if deploy:
        return execute_state_machine(sf_input, sf_name, True, sf_role)
    else:
        return execute_state_machine(sf_input, sf_name)

if __name__ == "__main__":
    execute_nlp_state_machine()


# 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12909

def solution(s):
    stack = []
    for char in s:
        if char == "(":
            stack.append("(")
        elif char == ")":
            if not stack:
                return False
            else:
                stack.pop()
    if len(stack) == 0:
        return True
    else:
        return False


from abc import abstractmethod
from io import BytesIO
from json import JSONEncoder
import numpy as np
import imageio
from PIL import Image
from pydicom import Sequence
from pydicom import read_file
from pydicom.dataelem import PersonName
from pydicom.multival import MultiValue
from pydicom.valuerep import DA, DT, TM, DSfloat, DSdecimal, IS

from apps.core.models import *

class DicomSaver:

    @classmethod
    def save(cls, img):
        print("save")
        if isinstance(img, Dataset):
            ds: Dataset = img
            img = BytesIO()
            img.seek(0)
            ds.save_as(img)
        else:
            ds: Dataset = read_file(img)
        if isinstance(img, str):
            img = open(img, 'rb')
        if Instance.objects.filter(sop_instance_uid=ds.SOPInstanceUID).exists():
            instance = Instance.objects.get(sop_instance_uid=ds.SOPInstanceUID)
            instance.image.delete()
            instance.image.save('', img)
            return instance
        elif Series.objects.filter(series_instance_uid=ds.SeriesInstanceUID).exists():
            series = Series.objects.get(series_instance_uid=ds.SeriesInstanceUID)
            instance = Instance.from_dataset(ds=ds)
            instance.series = series
            instance.image.save('', img)
            instance.save()
            img.close()
            return instance
        elif Study.objects.filter(study_instance_uid=ds.StudyInstanceUID).exists():
            study = Study.objects.get(study_instance_uid=ds.StudyInstanceUID)
            series = Series.from_dataset(ds=ds)
            series.study = study
            series.save()
            instance = Instance.from_dataset(ds=ds)
            instance.series = series
            instance.image.save('', img)
            instance.save()
            img.close()
            return instance

        if ds.PatientID is None or ds.PatientID == '':
            patient = Patient.from_dataset(ds=ds)
            patient.save()
            study = Study.from_dataset(ds=ds)
            study.patient = patient
            study.save()
            series = Series.from_dataset(ds=ds)
            series.study = study
            series.save()
            instance = Instance.from_dataset(ds=ds)
            instance.series = series
            instance.image.save('', img)
            instance.save()
            img.close()
            return instance
        elif Patient.objects.filter(patient_id=ds.PatientID):
            patient = Patient.objects.get(patient_id=ds.PatientID)
            study = Study.from_dataset(ds=ds)
            study.patient = patient
            study.save()
            series = Series.from_dataset(ds=ds)
            series.study = study
            series.save()
            instance = Instance.from_dataset(ds=ds)
            instance.series = series
            instance.image.save('', img)
            instance.save()
            img.close()
            return instance
        else:
            patient = Patient.from_dataset(ds=ds)
            patient.save()
            study = Study.from_dataset(ds=ds)
            study.patient = patient
            study.save()
            series = Series.from_dataset(ds=ds)
            series.study = study
            series.save()
            instance = Instance.from_dataset(ds=ds)
            instance.series = series
            instance.image.save('', img)
            instance.save()
            img.close()
            return instance

class BaseProcessor:

    @abstractmethod
    def process(self, img, **params):
        pass

class ImageProcessor(BaseProcessor):

    def __init__(self, plugin: Plugin):
        self.processor = __import__(plugin.name).Plugin()

    def __enter__(self):
        if hasattr(self.processor, "__enter__"):
            self.processor.__enter__()
        return self

    def process(self, instance: Instance, **params):
        ds = read_file(instance.image).pixel_array
        result = self.processor.process(ds, **params)
        return result

    def __exit__(self, exc_type, exc_val, exc_tb):
        if hasattr(self.processor, "__exit__"):
            self.processor.__exit__(exc_type, exc_val, exc_tb)
        return self

class DicomJsonEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, PersonName):
            return obj.original_string
        if isinstance(obj, MultiValue) or isinstance(obj, Sequence):
            return_list = []
            for value in obj:
                return_list.append(self.default(value))
            return return_list
        if isinstance(obj, DA):
            return '%d-%02d-%02d' % (obj.year, obj.month, obj.day)
        if isinstance(obj, DT):
            return '%d-%02d-%02d %02d:%02d:%02d' % (obj.year, obj.month, obj.day, obj.hour, obj.minute, obj.second)
        if isinstance(obj, TM):
            return '%02d:%02d:%02d' % (obj.hour, obj.minute, obj.second)
        if isinstance(obj, DSfloat):
            return str(obj)
        if isinstance(obj, DSdecimal):
            return str(obj)
        if isinstance(obj, IS):
            return obj.original_string or str(obj)
        if isinstance(obj, Dataset):
            child_tags = obj.dir()
            return_dict = {}
            for tag in child_tags:
                return_dict[tag] = self.default(obj.data_element(tag).value)
            return return_dict
        return str(obj)

def convert_dicom_to_img(ds: Dataset, img_format='jpeg'):
    pixel_array = ds.pixel_array
    file = BytesIO()
    imageio.imwrite(file, pixel_array, format='jpeg')
    file.seek(0)
    return file.read()

def convert_array_to_img(pixel_array: np.ndarray, fname, instance):
    file = BytesIO()
    imageio.imwrite(file, pixel_array, format='jpeg')
    file.seek(0)
    resave = ProcessingResult.objects.create(instance=instance, filename=fname)
    resave.result.save('', file)
    file.seek(0)
    return file.read()

def convert_img(ds: Dataset, img_max, img_min):
    pixel_array = ds.pixel_array
    pixel_array[pixel_array >= img_max] = img_max
    pixel_array[pixel_array <= img_min] = img_min
    file = BytesIO()
    imageio.imwrite(file, pixel_array, format='jpeg')
    file.seek(0)
    return file.read()


import re

decode = {
    "1": "1",
    "-": "-",
    "A": "2",
    "B": "2",
    "C": "2",
    "D": "3",
    "E": "3",
    "F": "3",
    "G": "4",
    "H": "4",
    "I": "4",
    "J": "5",
    "K": "5",
    "L": "5",
    "M": "6",
    "N": "6",
    "O": "6",
    "P": "7",
    "Q": "7",
    "R": "7",
    "S": "7",
    "T": "8",
    "U": "8",
    "V": "8",
    "W": "9",
    "X": "9",
    "Y": "9",
    "Z": "9",
    "characters": "ABCDEFGHIJKLMNOPQRSTUVWXYZ1-",
}

def change_to_number(name):
    if type(name) != type("str"):
        raise TypeError(f"name {name} must be an string")
    letters = [*name]
    sentence = ""
    for letter in letters:
        if letter not in decode["characters"]:
            raise ValueError(f"Character {letter} not valid")
        sentence += decode[letter.upper()]

    return sentence


fname = input('Enter the file name: ')
try:
    fhand = open(fname)
except:
    print('File cannot be opened: ', fname)
    exit()
domaincount = dict()
for line in fhand:
    lines = line.rstrip()
    words = lines.split()
    if len(words) == 0 or words[0] != 'From' :
        continue
    else:
        atspot = words[1].find('@')
        domain = words[1][atspot+1:]
        if domain not in domaincount:
            domaincount[domain] = 1
        else:
            domaincount[domain] += 1
print(domaincount)


import time
start = time.time()

class Queue1Stack(object):

    def __init__(self):
        self.stack = []
    def enqueue(self,item):
        self.stack.append(item)

    def dequeue(self):
        return self.stack.pop(0)
q = Queue1Stack()

for i in range(5000):
    q.enqueue(i)

for i in range(5000):
    print(q.dequeue())

print(time.time()-start)


import numpy as np
import argparse
import cv2

cap = cv2.VideoCapture(0)

while(1):
  ret, frame = cap.read()
  gray_vid = cv2.cvtColor(frame, cv2.IMREAD_GRAYSCALE)
  cv2.imshow('Original',frame)
  edged_frame = cv2.Canny(frame,100,200)
  cv2.imshow('Edges',edged_frame)
  if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


import os
import shrimpy
from datetime import datetime
from arbitrage import *

def main():
    shrimpy_public_key = os.environ.get("PUBLIC_KEY")
    shrimpy_secret_key = os.environ.get("PRIVATE_KEY")
    shrimpy_client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)

    # Works well on binance but have bugs on some other exchanges
    exchange = "binance"

    sentence = "\n----------------------- \n-----------------------\n {} on {}\n----------------------- \n-----------------------"
    date = str(datetime.now())
    sentence = sentence.format(date, exchange)

    with open("infos.csv", "a") as file:
        file.write(sentence)

    triangle_creation = Triangle()
    triangles = triangle_creation.form_triangles(exchange,
                                                 shrimpy_public_key,
                                                 shrimpy_secret_key,
                                                 shrimpy_client)

    array_of_symbols1 = triangles[0]["symbol"]
    array_of_symbols1_base = triangles[0]["base"]
    array_of_symbols1_quote = triangles[0]["quote"]

    array_of_symbols2 = triangles[1]["symbol"]
    array_of_symbols2_base = triangles[1]["base"]
    array_of_symbols2_quote = triangles[1]["quote"]

    array_of_symbols3 = triangles[2]["symbol"]
    array_of_symbols3_base = triangles[2]["base"]
    array_of_symbols3_quote = triangles[2]["quote"]

    # Release memory
    del sentence
    del date
    del triangle_creation
    del triangles

    def Arbitrage():
        if (len(array_of_symbols1) == len(array_of_symbols1_base) == len(array_of_symbols1_quote) ==
                len(array_of_symbols2) == len(array_of_symbols2_base) == len(array_of_symbols2_quote) ==
                len(array_of_symbols3) == len(array_of_symbols3_base) == len(array_of_symbols3_quote)):

            while True:

                for i in range(len(array_of_symbols1) - 1):
                    triangle = Triangle()

                    try:
                        triangle.set_fees(shrimpy_public_key, shrimpy_secret_key, shrimpy_client, exchange)

                    except:
                        print("Can't access the fees")
                        continue

                    triangle.symbol1 = Symbol(array_of_symbols1[i], array_of_symbols1_base[i],
                                              array_of_symbols1_quote[i])
                    triangle.symbol2 = Symbol(array_of_symbols2[i], array_of_symbols2_base[i],
                                              array_of_symbols2_quote[i])
                    triangle.symbol3 = Symbol(array_of_symbols3[i], array_of_symbols3_base[i],
                                              array_of_symbols3_quote[i])

                    try:
                        triangle.order_triangle()

                        triangle.symbol1.calc_bid_and_ask(shrimpy_public_key, shrimpy_secret_key, shrimpy_client,
                                                          exchange)
                        triangle.symbol2.calc_bid_and_ask(shrimpy_public_key, shrimpy_secret_key, shrimpy_client,
                                                          exchange)
                        triangle.symbol3.calc_bid_and_ask(shrimpy_public_key, shrimpy_secret_key, shrimpy_client,
                                                          exchange)

                    except:
                        continue

                    triangle.calculate_delta_long()
                    triangle.calculate_delta_short()

                    if triangle.PLBuy > triangle.fees:
                        try:
                            gain_net = str(round(triangle.PLBuy - triangle.fees, 2))
                            triangle.save_triangle("infos.csv", gain_net, "long")

                        except:
                            print("Error")

                        print(
                            f"Long arbitrage opportunity in triangle: {triangle.symbol1.name} = {triangle.symbol2.name} * {triangle.symbol3.name}")
                        print(f"Gain net : {gain_net} percent")

                    elif triangle.PLSell > triangle.fees:
                        try:
                            gain_net = str(round(triangle.PLSell - triangle.fees, 2))
                            triangle.save_triangle("infos.csv", gain_net, "short")

                        except:
                            print("Error")

                        print(
                            f"Short arbitrage opportunity in triangle: {triangle.symbol1.name} = {triangle.symbol2.name} * {triangle.symbol3.name}")
                        print(f"Gain net : {gain_net} percent")
                    else:
                        print(
                            f"No arbitrage opportunity in triangle: {triangle.symbol1.name} {triangle.symbol2.name} {triangle.symbol3.name}")

    Arbitrage()

if __name__ == '__main__':
    main()


from flask import Flask, request
from covid import CovidAssist
import pycountry
import requests_cache
import datetime
import json
import requests
import os
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)
agent = CovidAssist()
requests_cache.install_cache(cache_name='covid_cache', backend='sqlite', expire_after=86400)

@app.route('/bot', methods=['POST'])
def bot():
    # add webhook logic here and return a response
    # keys = authenticate()
    incoming_msg = request.values.get('Body')
    response = message_parser(incoming_msg)
    return response

def authenticate():
    ACCOUNT_SID = ""
    AUTH_TOKEN = ""
    with open("auth.txt","r") as f:
        return  [str(el).strip("\n") for el in f.readlines()]

def message_parser(incoming_msg):
    resp = MessagingResponse()
    msg = resp.message()
    if "information" in incoming_msg or "Information" in incoming_msg:
        agent.country=country_parser(incoming_msg)
        date = agent.get_latest_date()
        date = date.text
        data = agent.get_latest_country_data()
        data = json.loads(data)
        msg.body(" COVID-19 Cases in : "+ str(agent.country)+
                " \n Date Updated : " + str(date)+
                " \n\n \U0001F449 confirmed = " + str(data["result"][date]["confirmed"]) +
                " \n \U0001F449 deaths = " + str(data["result"][date]["deaths"]) +
                " \n \U0001F449 recoverd = " + str(data["result"][date]["recovered"]))
    elif "charts" in incoming_msg or "chart" in incoming_msg:
        pass
    else:
        msg.body("I didnot understand, could you mention 'information' or 'chart' please!")

    return str(resp)

def country_parser(incoming_msg):
    x = incoming_msg.split()
    country = pycountry.countries.search_fuzzy(x[-1])[0].alpha_3
    return country

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


import torch
from torch import nn

from torch import Tensor

class RanEncoder(nn.Module):
    def __init__(self, per_dim, in_channel, out_channel):
        super().__init__()
        self.per_dim = per_dim
        self.in_channel = in_channel
        self.out_channel = out_channel
        self.conv1 = nn.Conv2d(self.in_channel, self.out_channel, kernel_size=(1, 1))
        self.bn = nn.BatchNorm2d(self.out_channel)
        self.drop_out = nn.Dropout(p=0.2)
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x: Tensor):
        """

        :param x: shape(bs,features_dim)
        :return:
        """

        x_nums = x.shape[0]
        x = torch.reshape(x, (-1, self.in_channel, self.per_dim, self.per_dim))
        out = self.conv1(x)
        out = self.bn(out)
        out = self.drop_out(out)
        out = self.relu(out)

        out = torch.reshape(out, (x_nums, self.out_channel, -1))

        return out


from time import sleep
from threading import Thread, Lock
from os import mkfifo, access, R_OK

from canary_api import settings

from canary_utils.lib import logger
from canary_utils.lib.log import Log, Nginx, SMB, DNS

class serverState(object):
    """Maintains server state, stops the server when disabled."""

    def __init__(self):
        """Initialize lock."""

        self.lock = Lock()
        self.active = False

    def is_active(self):
        """Maintains the current state of the server."""

        with self.lock:
            if self.active:
                return True

            else:
                return False

class cmdServer():
    """Runs the cmdServer as a daemon."""

    def __init__(self):
        """Initialize server state and start logger and parsers.."""

        self.state = serverState()

        with self.state.lock:
            self.state.active = True

        self.logger = logger.Logger()

        if not access(settings.PIPE, R_OK):
            mkfifo(settings.PIPE)

        self.start_parsers()

    def start_parsers(self):
        """Starts the log parsers based on the list in the configuration."""

        try:
            for parser in settings.parsers:
                index = settings.parsers.index(parser)

                settings.parsers[index].append(Thread(target=self.start_log,
                                             args=(parser[0],)))
                settings.parsers[index][1].setDaemon(True)
                settings.parsers[index][1].start()

            watch = Thread(target=self.watch_threads, args=())
            watch.setDaemon(True)
            watch.start()

            self.logger.log_info('daemons started successfully')

            while self.state.is_active():
                sleep(1)

            self.logger.log_info('shutting down!')

        except Exception as msg:

            if isinstance(msg, FileNotFoundError):

                with self.state.lock:
                    self.state.active = False

            self.logger.log_exception(msg)

    def watch_threads(self):
        """Watchdog to restart potentially crashed threads."""

        while self.state.is_active:
            self.check_alive()
            sleep(3)

    def check_alive(self):
        """Check to see whether the thread is still alive."""

        for thread in settings.parsers:
            if not thread[1].is_alive():

                self.restart_thread(thread)
                self.logger.log_info(f"Restarted thread {str(thread[0])}")

    def restart_thread(self, thread):
        """Reinitialize threads, as restarting is not possible."""

        thread[1] = Thread(target=self.start_log,
                           args=(thread[0],))
        thread[1].setDaemon(True)
        thread[1].start()

    def start_log(self, log_type):
        """Start log parsers for detecting canaries."""

        try:
            self.logd = Log()

            if log_type == 'smb':
                self.parser = SMB()

            elif log_type == 'nginx':
                self.parser = Nginx()

            elif log_type == 'dns':
                self.parser = DNS()

            self.logd.monitor_log(self.parser.parse,
                                  settings.log[log_type],
                                  self.state)

        except Exception as msg:
            self.logger.log_exception(msg)

    def stop_parsers(self):

        self.logger.log_info('stopping parsers...')

        with self.state.lock:
            self.state.active = False

            for thread in settings.parsers:

                if len(thread) > 1:

                    if thread[1].is_alive():
                        thread[1].join(5)

        self.logger.log_info('parsers stopped!')


from PyQt5 import Qt, QtCore, QtGui, QtWidgets
from ui.mainw import Ui_MainWindow
import os, json
import subprocess

class VirtualCD_Window(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(VirtualCD_Window, self).__init__()
        self.setupUi(self)
        self.setWindowOpacity(0.5)
        self.setWindowFlags(Qt.Qt.WindowCloseButtonHint | Qt.Qt.WindowMinimizeButtonHint | Qt.Qt.WindowStaysOnTopHint)
        self.wHeight = self.height()
        _result = subprocess.getstatusoutput('losetup -J')
        # print(_result)
        _loaded = False
        self._vcd_list = {}
        if _result[0] == 0:
            if _result[1] != '':
                self._vcd_list = json.loads(_result[1])
                # print(self._vcd_list)
                _loaded = True
                # print(_result[1].split('\n')[1])
        # print(_result)
        # print(type(_result))
        # print(_loaded)
        self.btnEject.setEnabled(_loaded)
        self.btnOpen.clicked.connect(self.loadISO)
        self.btnEject.clicked.connect(self.unloadISO)

    def loadISO(self):
        iso_file, file_type = QtWidgets.QFileDialog.getOpenFileName(self, caption='选择ISO文件', filter='光盘镜像文件(*.iso)')
        # print(iso_file, file_type)
        if iso_file != '':
            # print(f'选择文件为{iso_file}')
            result = subprocess.getstatusoutput(f'losetup -r /dev/loop0 {iso_file}')
            if result[0] != 0:
                result = subprocess.getstatusoutput(f'gksudo -m 加载虚拟光驱需要输入当前用户的密码才能继续 "losetup -r /dev/loop0 {iso_file}"')
            # print(result[0])
            if result[0] == 0:
                self.btnEject.setEnabled(True)
                _result = subprocess.getstatusoutput('losetup -J')
                self._vcd_list = json.loads(_result[1])
                # print(self._vcd_list)
            else:
                QtWidgets.QMessageBox.warning(self, '警告', f'文件"{iso_file}"加载失败！')
        # else:
            # print('没有选择任何文件')

    def unloadISO(self):
        iso_filename = os.path.basename(self._vcd_list['loopdevices'][0]['back-file'])
        iso_mnt_path = '/media/' + os.environ['USER'] + '/' +iso_filename[:iso_filename.rfind('.')]
        # print('iso filename', iso_filename, iso_mnt_path)
        if os.path.exists(iso_mnt_path):
            result = subprocess.getstatusoutput(f'umount {iso_mnt_path}')
            # print(result)
        result = subprocess.getstatusoutput('losetup -d /dev/loop0')
        # print(result)
        if result[0] != 0:
            result = subprocess.getstatusoutput('gksudo -m 弹出虚拟光驱需要输入当前用户的密码才能继续 "losetup -d /dev/loop0"')
            # print(result)
        if result[0]==0:
            self.btnEject.setEnabled(False)
        else:
            QtWidgets.QMessageBox.warning(self, '警告', '虚拟光驱弹出失败！')

if __name__=="__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    mainw = VirtualCD_Window()
    x = (app.desktop().width() - mainw.width()) / 2
    y = (app.desktop().height() - mainw.height()) / 2
    mainw.move(x, y)
    mainw.show()
    sys.exit(app.exec_())


#B = (X'X)^-1 X' y
from plotfit import plotLineReg
from derive import approxD2iter, testf

def linereg(xlist: list, ylist: list):
    if len(xlist)!=len(ylist):
        print("xlist and ylist are not of matching size")
        return None

    # 'a' represents entries of A, which is a label for the matrix (X'X)
    a00 = len(xlist)
    a10 = 0
    for i in range(len(xlist)):
        a10 += xlist[i]
    a11 = 0
    for i in range(len(xlist)):
        a11 += xlist[i]*xlist[i]

    # 'c_n' represents the nth component of c which is a label for the vector(X'y)
    c0 = 0
    for i in range(len(ylist)):
        c0 += ylist[i]
    c1 = 0
    for i in range(len(ylist)):
        c1 += ylist[i]*xlist[i]

    detA = (a00*a11)-(a10*a10)

    # entries of A^-1
    ai00 = a11/detA
    ai10 = -1*a10/detA
    ai11 = a00/detA

    #entries of beta
    b0 = (c0*ai00)+(c1*ai10) # intercept
    b1 = (c0*ai10)+(c1*ai11) # slope

    return b0, b1

if (__name__=='__main__'):
    # Test method
    #xlist = [1,2,3,4,5,6,7,8,9]
    #ylist = [1,2,3,4,5,6,7,8,9]

    pointslist = approxD2iter(testf, 1.0, .125, .000001, 200)
    xlist = []
    ylist = []
    for i in range(len(pointslist)):
        xlist.append(pointslist[i][0])
        ylist.append(pointslist[i][1])
    b, a = linereg(xlist, ylist)
    print("a: ",a,"b: ",b)
    plotLineReg(xlist, ylist, a, b)


import os
import random
import cv2
from torchvision import transforms
import matplotlib.pyplot as plt

torch_image_transform = transforms.ToTensor()

def get_data(dir, labels):
    data = []
    for label in labels:
        path = os.path.join(dir, label)
        class_num = labels.index(label)
        for img in os.listdir(path):
          try:
            img = cv2.imread(os.path.join(path, img))
            torch_img = torch_image_transform(img)
            torch_img_numpy = torch_img.cpu().numpy().transpose([1, 2, 0])
            data.append([torch_img_numpy, class_num])
          except Exception as e:
            print(e)
    return data, len(data)

def get_random_data(dir, labels, num_samples_per_label):
    data = []
    for label in labels:
        path = os.path.join(dir, label)
        class_num = labels.index(label)
        images = os.listdir(path)

        # Shuffle the images to get random samples
        random.shuffle(images)

        # Take a specified number of random samples from each label
        selected_images = random.sample(images, num_samples_per_label)

        for img_filename in selected_images:
            try:
                img = cv2.imread(os.path.join(path, img_filename))
                torch_img = torch_image_transform(img)
                torch_img_numpy = torch_img.cpu().numpy().transpose([1, 2, 0])
                data.append([torch_img_numpy, class_num])
            except Exception as e:
                print(e)
    return data, len(data)
def get_random_file(directory_path):
    # Get the list of files in the directory
    files = os.listdir(directory_path)

    # Optional: Filter out directories from the list (if needed)
    files = [file for file in files if os.path.isfile(os.path.join(directory_path, file))]

    # Check if there are any files in the directory
    if not files:
        print("No files found in the directory.")
        return None

    # Generate a random index within the range of the files list
    random_index = random.randint(0, len(files) - 1)

    # Get the randomly chosen file from the list
    random_file = files[random_index]

    # Return the full path to the randomly chosen file
    return os.path.join(directory_path, random_file)

def get_labels(data_path):
  #get children folders of root data directory
  labels = os.listdir(data_path)
  return labels

def count_files_in_folder(folder_path):
    file_count = 0
    for item in os.listdir(folder_path):
        if os.path.isfile(os.path.join(folder_path, item)):
            file_count += 1
    return file_count


from manimlib.imports import *

class Operaciones_continuidad(ThreeDScene):
    def acomodar_textos(self,objeto):
        self.add_fixed_in_frame_mobjects(objeto)
        self.play(Write(objeto))
    def acomodar_puntos(self,objeto):
        self.add_fixed_in_frame_mobjects(objeto)
        self.add(objeto)

    # Definimos las funciones a utilizar (las que vamos a graficar)
    # Puedes cambiar estas funciones con las que se te ocurra
    # Son funciones de R  a R2, y estamos obteniendo sus gráficas
    # por lo que la primer entrada siempre debe ser lo que parametriza
    # la función, es decir, la variable independiente
    def helicoide(self,t):
        return [t,np.cos(5*t),np.sin(5*t)] #f(t)=(cos(5t),sin(5t))

    def identidad(self,t):
        return [t,t,t] #g(t)=(t,t)

    def func_suma(self,t):
        return [t,t+np.cos(5*t),t+np.sin(5*t)] #(f+g)(t)=(t+cos(5t),t+sin(5t))

    def func_por_escalar(self,t):
        k = 3 #Cambiar esta constante hará que se cambie la gráfica de k*f, también debes cambiarla en construct
        return [t,k*np.cos(5*t),k*np.sin(5*t)] #(k*f)(t)=(kcos(5t),ksin(5t))

    def func_prod_int(self,t):
        return[t,2*t**2+t*np.cos(5*t)+t*np.sin(5*t),0] #(f\cdot g)(t)=2t^2+tcos(5t)+tsin(5t)
    # Aquí se realiza la animación
    def construct(self):
        k = 3 #Cambia también esta constante al mismo valor que la de la función
        title = TextMobject('''Continuidad: Teoremas de Operaciones''').scale(1.5)
        t_1 = TextMobject('''Sean $f,g:D\\subseteq\\mathbb{R}^n\\longrightarrow\\mathbb{R}^m$, ''','''$x_0$''','''$\\in D$ \n
                            $f$ y $g$ ''','''continuas''',''' en ''','''$x_0$''',''' entonces:''').shift(2*UP)
        t_1.set_color_by_tex_to_color_map({
            '''continuas''': BLUE,
            '''$x_0$''': PURPLE_B
        })
        t_2 = TextMobject('''1) $f+g$ es ''','''continua''',''' en ''','''$x_0$''').next_to(t_1,DOWN,buff=1.2)
        t_2.set_color_by_tex_to_color_map({
            '''continua''': BLUE,
            '''$x_0$''': PURPLE_B
        })
        t_3 = TextMobject('''2) Sea $k\\in\\mathbb{R}$, $kf$ es ''','''continua''',''' en ''','''$x_0$''').next_to(t_2,DOWN)
        t_3.set_color_by_tex_to_color_map({
            '''continua''': BLUE,
            '''$x_0$''': PURPLE_B
        })
        t_4 = TextMobject('''3) $f\\cdot g$ es ''','''continua''',''' en ''','''$x_0$''').next_to(t_3,DOWN)
        t_4.set_color_by_tex_to_color_map({
            '''continua''': BLUE,
            '''$x_0$''': PURPLE_B
        })
        Nota = TextMobject('''Nota: la tercera operación es un producto interior \\\\
                            Si $m=1$ se trata de producto de reales''').scale(0.75).to_edge(DOWN)
        t_5 = TextMobject('''Veamos algunos ejemplos...''')
        reglaf = TextMobject('''$f(t)$''','''$=(\cos(5t),\sin(5t))$''').scale(0.85).to_corner(LEFT+UP).shift(1*RIGHT)
        reglaf.set_color_by_tex_to_color_map({
            '''$f(t)$''': RED
        })
        reglaf.bg = SurroundingRectangle(reglaf,color=WHITE,fill_color=BLACK,fill_opacity=1)
        reglag = TextMobject('''$g(t)$''','''$=(t,t)$''').scale(0.85).to_corner(LEFT+UP).shift(2*RIGHT)
        reglag.set_color_by_tex_to_color_map({
            '''$g(t)$''': TEAL_D
        })
        reglag.bg = SurroundingRectangle(reglag,color=WHITE,fill_color=BLACK,fill_opacity=1)
        t_6 = TextMobject('''$f$''',''' y ''','''$g$''',''' son funciones ''','''continuas''',''' \n
                            en ''','''$t_0=0$''',''', ¿puedes demostrarlo?''').scale(0.85).to_corner(LEFT+UP)
        t_6.set_color_by_tex_to_color_map({
            '''continuas''': BLUE,
            '''$f$''': RED,
            '''$g$''': TEAL_D,
            '''$t_0=0$''': YELLOW
        })
        t_6.bg = SurroundingRectangle(t_6,color=WHITE,fill_color=BLACK,fill_opacity=1)
        t_7 = TextMobject('''Entonces $f+g$ también es \n
                            ''','''continua''',''' en ''','''$t_0$''').scale(0.85).to_corner(LEFT+UP)
        t_7.set_color_by_tex_to_color_map({
            '''continua''': BLUE,
            '''$t_0$''': YELLOW
        })
        t_7.bg = SurroundingRectangle(t_7,color=WHITE,fill_color=BLACK,fill_opacity=1)
        reglafmasg = TextMobject('''$(f+g)(t)$''','''$=(t+\cos(5t),t+\sin(5t))$''').scale(0.85).to_corner(LEFT+UP)
        reglafmasg.set_color_by_tex_to_color_map({
            '''$(f+g)(t)$''': PINK
        })
        reglafmasg.bg = SurroundingRectangle(reglafmasg,color=WHITE,fill_color=BLACK,fill_opacity=1)
        t_8 = TextMobject('''Si tomamos $k=$'''+str(k)+''', \n
                            $kf$ también es ''','''continua''',''' en ''','''$t_0$''').scale(0.85).to_corner(LEFT+UP).shift(0.4*RIGHT)
        t_8.set_color_by_tex_to_color_map({
            '''continua''': BLUE,
            '''$t_0$''': YELLOW
        })
        t_8.bg = SurroundingRectangle(t_8,color=WHITE,fill_color=BLACK,fill_opacity=1)
        reglakf = TexMobject(r"("+str(k)+r"f)(t)=("+str(k)+r"\cos(5t),"+str(k)+r"\sin(5t))").scale(0.85).to_corner(LEFT+UP).shift(0.4*RIGHT)
        reglakf.bg = SurroundingRectangle(reglakf,color=WHITE,fill_color=BLACK,fill_opacity=1)
        for i in range(0,7):
            reglakf[0][i].set_color(ORANGE)
        t_9 = TextMobject('''Por último, al tomar el producto punto de ''','''$f$''',''' y ''','''$g$''',''', la función \n
                            resultante es también ''','''continua''',''' en ''','''$t_0$''')
        t_9.set_color_by_tex_to_color_map({
            '''$f$''': RED,
            '''$g$''': TEAL_D,
            '''continua''': BLUE,
            '''$t_0$''': YELLOW
        })
        reglafpuntog = TextMobject('''$(f\cdot g)(t)$''','''$=2t^2+t\cos(5t)+t\sin(5t)$''').scale(0.85).to_corner(LEFT+UP)
        reglafpuntog.set_color_by_tex_to_color_map({
            '''$(f\cdot g)(t)$''': GREEN_D
        })
        reglafpuntog.bg = SurroundingRectangle(reglafpuntog,color=WHITE,fill_color=BLACK,fill_opacity=1)

        # Ejes en 3D
        axis_config = {
            "x_min" : -6,
            "x_max" : 6,
            "y_min" : -6,
            "y_max" : 6,
            "z_min" : -6,
            "z_max" : 6,
        }
        ejes = ThreeDAxes(**axis_config)
        # Ejes en 2D
        ejes2 = Axes(
            x_min=-6,
            x_max=6,
            y_min=-3.5,
            y_max=3.5
        )
        # Funciones que se van a utilizar
        tmin = -6
        tmax = 6
        f = ParametricFunction(self.helicoide,t_min=tmin,t_max=tmax,color=RED).set_shade_in_3d(True)
        g = ParametricFunction(self.identidad,t_min=tmin,t_max=tmax,color=TEAL_D).set_shade_in_3d(True)
        fmasg = ParametricFunction(self.func_suma,t_min=tmin,t_max=tmax,color=PINK).set_shade_in_3d(True)
        kf = ParametricFunction(self.func_por_escalar,t_min=tmin,t_max=tmax,color=ORANGE).set_shade_in_3d(True)
        fpuntog = ParametricFunction(self.func_prod_int,t_min=-1.3,t_max=1.3,color=GREEN_D).set_shade_in_3d(True)
        dot1 = Dot(point=(0,1,0),color=YELLOW,radius=0.1)
        dot2 = Dot(point=(0,0,0),color=YELLOW,radius=0.1)
        dot3 = Dot(point=(0,1,0),color=YELLOW,radius=0.1)
        dot4 = Dot(point=(0,k,0),color=YELLOW,radius=0.1)
        dot5 = Dot(point=(0,0,0),color=YELLOW,radius=0.1)
        ### Grupos ###
        Group1 = VGroup(t_1,t_2,t_3,t_4,Nota)
        ### Animación ###
        self.play(Write(title))
        self.wait()
        self.play(FadeOutAndShiftDown(title))
        self.play(Write(t_1))
        self.wait(8)
        self.play(Write(t_2))
        self.wait(3)
        self.play(Write(t_3))
        self.wait(3.25)
        self.play(Write(t_4))
        self.wait(3.25)
        self.play(Write(Nota))
        self.wait(2.75)
        self.play(FadeOut(Group1))
        self.play(Write(t_5))
        self.wait(2)
        self.play(FadeOut(t_5))

        self.set_camera_orientation(phi=115*DEGREES,theta=-65*DEGREES)
        self.play(ShowCreation(ejes))
        self.begin_ambient_camera_rotation(rate=0.07)
        self.acomodar_textos(reglaf.bg)
        self.acomodar_textos(reglaf)
        self.add_foreground_mobjects(reglaf.bg)
        self.add_foreground_mobjects(reglaf)
        self.play(ShowCreation(f),run_time=2)
        self.wait(2.5)
        self.play(FadeOut(reglaf),FadeOut(reglaf.bg))
        self.remove_foreground_mobjects(reglaf.bg)
        self.remove_foreground_mobjects(reglaf)
        self.acomodar_textos(reglag.bg)
        self.acomodar_textos(reglag)
        self.add_foreground_mobjects(reglag.bg)
        self.add_foreground_mobjects(reglag)
        self.play(ShowCreation(g),run_time=2)
        self.wait(2.5)
        self.play(FadeOut(reglag),FadeOut(reglag.bg))
        self.remove_foreground_mobjects(reglag.bg)
        self.remove_foreground_mobjects(reglag)
        self.acomodar_textos(t_6.bg)
        self.acomodar_textos(t_6)
        self.add_foreground_mobjects(t_6.bg)
        self.add_foreground_mobjects(t_6)
        self.add(dot1,dot2)
        self.wait(4.5)
        self.remove(dot1,dot2)
        self.play(FadeOut(f),FadeOut(g),FadeOut(t_6),FadeOut(t_6.bg))
        self.remove_foreground_mobjects(t_6.bg)
        self.remove_foreground_mobjects(t_6)
        self.acomodar_textos(t_7.bg)
        self.acomodar_textos(t_7)
        self.add_foreground_mobjects(t_7.bg)
        self.add_foreground_mobjects(t_7)
        self.wait(4.5)
        self.play(FadeOut(t_7),FadeOut(t_7.bg))
        self.remove_foreground_mobjects(t_7.bg)
        self.remove_foreground_mobjects(t_7)
        self.acomodar_textos(reglafmasg.bg)
        self.acomodar_textos(reglafmasg)
        self.add_foreground_mobjects(reglafmasg.bg)
        self.add_foreground_mobjects(reglafmasg)
        self.play(ShowCreation(fmasg),run_time=2)
        self.add(dot3)
        self.wait(6)
        self.remove(dot3)
        self.play(FadeOut(fmasg),FadeOut(reglafmasg),FadeOut(reglafmasg.bg))
        self.remove_foreground_mobjects(reglafmasg.bg)
        self.remove_foreground_mobjects(reglafmasg)
        self.acomodar_textos(t_8.bg)
        self.acomodar_textos(t_8)
        self.add_foreground_mobjects(t_8.bg)
        self.add_foreground_mobjects(t_8)
        self.wait(4.5)
        self.play(FadeOut(t_8),FadeOut(t_8.bg))
        self.remove_foreground_mobjects(t_8.bg)
        self.remove_foreground_mobjects(t_8)
        self.acomodar_textos(reglakf.bg)
        self.acomodar_textos(reglakf)
        self.add_foreground_mobjects(reglakf.bg)
        self.add_foreground_mobjects(reglakf)
        self.play(ShowCreation(kf),run_time=2)
        self.add(dot4)
        self.wait(2)
        self.remove(dot4)
        self.play(FadeOut(reglakf.bg),FadeOut(reglakf),FadeOut(kf),FadeOut(ejes))
        self.remove_foreground_mobjects(reglakf.bg)
        self.remove_foreground_mobjects(reglakf)
        self.stop_ambient_camera_rotation()
        self.set_camera_orientation(phi=0,theta=-90*DEGREES)
        self.play(Write(t_9))
        self.wait(8)
        self.play(FadeOutAndShiftDown(t_9))
        self.play(ShowCreation(ejes2))
        self.play(FadeIn(reglafpuntog.bg))
        self.play(Write(reglafpuntog))
        self.add_foreground_mobjects(reglafpuntog.bg)
        self.add_foreground_mobjects(reglafpuntog)
        self.play(ShowCreation(fpuntog))
        self.add(dot5)
        self.wait(4)
        self.play(FadeOut(ejes2),FadeOut(reglafpuntog),FadeOut(fpuntog),FadeOut(dot5))
        self.remove_foreground_mobjects(reglafpuntog.bg)
        self.remove_foreground_mobjects(reglafpuntog)

Límite y continuidad en funciones multivariable/operaciones_continuas.py


import math
from model.enums import SearchType
from helpers.utils import load_json, get_elements, get_center_coordinates
from setup.setup_app import LOCATOR_KEY_NAME, ELEMENT_NAME_PLACEHOLDER, FINDERS_KEY_NAME, DATA_FILE_PATH
from model.element_dto import Element
from setup.setup_logger import logger

def find_element(element_name):
    """Find element that match with element_name.
    :param element_name: name of the element to find
    :type element_name: str
    :return an Element object or a None value if not found
    """
    # Load dictionary from File1.json
    dictionary = load_json('{}/File1.json'.format(DATA_FILE_PATH))

    locators = []
    if dictionary is not None:
        # Look for specific definition that match with the element_name. Add locator to the list
        if element_name in dictionary.keys():
            locators.append(dictionary[element_name][LOCATOR_KEY_NAME])
        else:
            # Look for each locator in finders, replace the placeholder and add to the list
            for finder in dictionary.get(FINDERS_KEY_NAME):
                loc = finder[LOCATOR_KEY_NAME].replace(ELEMENT_NAME_PLACEHOLDER, element_name)
                locators.append(loc)

    # Look for existing elements for each locator in list
    for locator in locators:
        element_list = get_elements(locator)
        return element_list[0] if element_list else None
    return None

def find_element_near_to(element, locator, search_type=SearchType.ALL):
    """Find a element object of the elements with locator X that is nearest to element A
    :param element: element A
    :type element: Element

    :param locator: locator X
    :type locator: str

    :param search_type: Type of search. Default = SearchType.ALL
    :type search_type: SearchType

    :return an Element object or a None value if not found.
    """
    if None not in (element, locator):
        # Get list of elements that match with the locator
        element_list = get_elements(locator)
        if element_list:
            # Get the center of the element
            x1, y1 = get_center_coordinates(element)

            found_elements = []
            min_distance = None
            # calculate distance for each element
            for e in element_list:
                element_distance = None
                x2, y2 = get_center_coordinates(e)
                if search_type in (SearchType.X_AXIS, SearchType.LEFT, SearchType.RIGHT):
                    # Search in X axis
                    if search_type == SearchType.LEFT and x1 >= x1:
                        continue
                    elif search_type == SearchType.RIGHT and x2 <= x1:
                        continue
                    else:
                        element_distance = abs(x2 - x1)
                elif search_type in (SearchType.Y_AXIS, SearchType.UP, SearchType.DOWN):
                    # Search in Y axis
                    if search_type == SearchType.UP and y2 <= y1:
                        continue
                    elif search_type == SearchType.DOWN and y2 >= y1:
                        continue
                    else:
                        element_distance = abs(y2 - y1)
                elif search_type == SearchType.ALL:
                    # Search in both axis. Calculate the distance using the Pythagorean Theorem and find the minimum
                    element_distance = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))

                # save the minimal distance
                if min_distance is None or element_distance < min_distance:
                    min_distance = element_distance
                    found_elements = [e]
                elif element_distance == min_distance:
                    found_elements.append(e)

            # print a message if there are more than one element found with the same distance
            if len(found_elements) > 1:
                print("There are more than one element with the same distance. First element was returned. See log "
                      "for more information.")
                logger.info('Element founds: \n' + '\n'.join([str(e) for e in found_elements]))

            # return the first element of the list
            return found_elements[0] if found_elements else None
    return None


#%% packages
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import seaborn as sns

#%% data import
cars_file = 'https://gist.githubusercontent.com/noamross/e5d3e859aa0c794be10b/raw/b999fb4425b54c63cab088c0ce2c0d6ce961a563/cars.csv'
cars = pd.read_csv(cars_file)
cars.head()

#%% visualise the model
sns.scatterplot(x='wt', y='mpg', data=cars)
sns.regplot(x='wt', y='mpg', data=cars)

#%% convert data to tensor
X_list = cars.wt.values
X_np = np.array(X_list, dtype=np.float32).reshape(-1,1)
y_list = cars.mpg.values
y_np = np.array(y_list, dtype=np.float32).reshape(-1,1)
X = torch.from_numpy(X_np)
y_true = torch.from_numpy(y_np)

#%% model class
class LinearRegressionTorch(nn.Module):
    def __init__(self, input_size, output_size):
        super(LinearRegressionTorch, self).__init__()
        self.linear = nn.Linear(input_size, output_size)

    def forward(self, x):
        out = self.linear(x)
        return out

input_dim = 1
output_dim = 1
model = LinearRegressionTorch(input_dim, output_dim)

#%% loss Function
loss_fun = nn.MSELoss()

#
# %% Optimizer
LR = 0.02
optimizer = torch.optim.SGD(model.parameters(), lr=LR)

# %% training
losses, slope, bias = [], [], []

NUM_EPOCHS = 1000
for epoch in range(NUM_EPOCHS):
    # set gradients to zero
    optimizer.zero_grad()

    # fowrad pass
    y_pred = model(X)

    # compute loss
    loss = loss_fun(y_pred, y_true)

    # compute gradients
    loss.backward()

    # update weights
    optimizer.step()

    # get parameter
    for name, param in model.named_parameters():
        if param.requires_grad:
            if name == 'linear.weight':
                slope.append(param.data.numpy()[0][0])
            if name == 'linear.bias':
                bias.append(param.data.numpy()[0])

    losses.append(float(loss.data))

    # print loss
    if epoch % 100 == 0:
        print('Epoch: {}, Loss: {:.4f}'.format(epoch, loss.data))

# %% visualize model training
sns.scatterplot(x=range(NUM_EPOCHS), y=losses)

# %% visualize the bias development
sns.scatterplot(x=range(NUM_EPOCHS), y=bias)

# %%
sns.scatterplot(x=range(NUM_EPOCHS), y=slope)
# %% check the result
y_pred = model(X).data.numpy().reshape(-1)
sns.scatterplot(x=X_list, y=y_list)
sns.lineplot(x=X_list, y=y_pred, color='red')

# %%


import time
import random
from typing import List, Tuple, Generator

class Life:
    state: List[List[bool]]
    m: int
    n: int

    def __init__(self, m: int, n: int):
        self.m = m
        self.n = n
        self.state = [[False for _ in range(n)] for _ in range(m)]

    def __repr__(self) -> str:
        return str(self.state)

    def random_select(self, rate):
        for x_grid in range(self.m):
            for y_grid in range(self.n):
                if random.randint(0, rate) == 0:
                    self.state[x_grid][y_grid] = True

    def neighbours(self, i: int, j: int) -> Generator[Tuple[int, int], None, None]:
        for x_grid in range(-1, 2):
            for y_grid in range(-1, 2):
                if self.m > i + x_grid >= 0 and self.n > j + y_grid >= 0 \
                        and not (x_grid == y_grid == 0):
                       yield i + x_grid, j + y_grid

    def nextstate(self) -> None:
        next_ = self.state.copy()

        for x_grid in range(self.m):
            for y_grid in range(self.n):
                num_of_on = 0
                for cell in self.neighbours(x_grid, y_grid):

                    try:
                        if self.state[cell[0]][cell[1]]:
                            num_of_on += 1
                    except:
                        print(x_grid, y_grid)
                        print(cell[0], cell[1])
                        return

                if self.state[x_grid][y_grid]:
                    if num_of_on not in (2, 3):
                        next_[x_grid][y_grid] = False
                elif num_of_on == 3:
                    next_[x_grid][y_grid] = True

        self.state = next_

    def addfigure(self, i: int, j: int, figure: List[str]) -> None:
        if i + len(figure) > self.m:
            raise ValueError

        for x_grid in range(len(figure)):
            if len(figure[x_grid]) > self.n - j:
                raise ValueError

            for y_grid in range(len(figure[x_grid])):
                self.state[x_grid + i][y_grid + j] = figure[x_grid][y_grid] not in ". "

    def __str__(self) -> str:
        grid = ""
        for x_grid in range(self.m):
            for y_grid in range(self.n):
                if self.state[x_grid][y_grid]:
                    grid += '# '
                else:
                    grid += '. '

            grid += '\n'
        return grid


# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from pandas import DataFrame

from util import spider_util

#获取学校学区信息
xx_url='http://map.28dat.net/s_ft/school.aspx?no=101'
cz_url='http://map.28dat.net/s_ft/school.aspx?no=225'#初中
url_arr=[]
url_arr.append(xx_url)
url_arr.append(cz_url)
schoolarea = []
for url in url_arr:
	html = spider_util.open_url(url, self_rotation=5, timeout=20)  # 20秒超时
	bsObj = BeautifulSoup(html, "html.parser", from_encoding="utf-8")
	a_tags=bsObj.find('span',{'id':'s_school'}).find_all('a')
	for a_tag in a_tags:
			schoolname=a_tag.get_text()
			url='http://map.28dat.net/s_ft/school.aspx'+a_tag.get('href')
			html = spider_util.open_url(url, self_rotation=5, timeout=20)  # 20秒超时
			bsObj = BeautifulSoup(html, "html.parser", from_encoding="utf-8")
			span=bsObj.find('span',{'id':'s_list'})
			area_text=span.get_text()
			area_text_arr=area_text.split('，')
			for text in area_text_arr:
				area = {}
				area['学校名称'] = schoolname
				area['区域范围']=text
				schoolarea.append(area)

DataFrame(schoolarea).to_csv("D:\\011111111111111111111111\\软件\\school_area.csv", index=False, sep=',')


import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
root.title("cakahal johnson")
root.geometry("600x200")

photo = tk.PhotoImage(file="bg.jpg")

label = tk.Label(root, image=photo, bg="black", fg="yellow", width=600, height=200)

label.pack()

root.mainloop()


"""Defines helpers related to the system database."""

import logging
import time

from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import text

from .project_settings_service import ProjectSettingsService

# Keep a Project → Engine mapping to serve
# the same engine for the same Project
_engines = dict()

def project_engine(project, default=False) -> ("Engine", sessionmaker):
    """Creates and register a SQLAlchemy engine for a Meltano project instance."""

    existing_engine = _engines.get(project)
    if existing_engine:
        return existing_engine

    settings = ProjectSettingsService(project)

    engine_uri = settings.get("database_uri")
    logging.debug(f"Creating engine {project}@{engine_uri}")
    engine = create_engine(engine_uri, pool_pre_ping=True)

    check_db_connection(
        engine,
        max_retries=settings.get("database_max_retries"),
        retry_timeout=settings.get("database_retry_timeout"),
    )

    init_hook(engine)

    engine_session = (engine, sessionmaker(bind=engine))

    if default:
        # register the default engine
        _engines[project] = engine_session

    return engine_session

def check_db_connection(engine, max_retries, retry_timeout):  # noqa: WPS231
    """Check if the database is available the first time a project's engine is created."""
    attempt = 0
    while True:
        try:
            engine.connect()
        except OperationalError:
            if attempt == max_retries:
                logging.error(
                    "Could not connect to the Database. Max retries exceeded."
                )
                raise
            attempt += 1
            logging.info(
                f"DB connection failed. Will retry after {retry_timeout}s. Attempt {attempt}/{max_retries}"
            )
            time.sleep(retry_timeout)
        else:
            break

def init_hook(engine):
    function_map = {"sqlite": init_sqlite_hook}

    try:
        function_map[engine.dialect.name](engine)
    except KeyError:
        pass
    except Exception as e:
        raise Exception(f"Can't initialize database: {str(e)}") from e

def init_sqlite_hook(engine):
    # enable the WAL
    engine.execute("PRAGMA journal_mode=WAL")

class DB:
    @classmethod
    def ensure_schema_exists(cls, engine, schema_name, grant_roles=()):
        """
        Make sure that the given schema_name exists in the database
        If not, create it

        :param db_conn: psycopg2 database connection
        :param schema_name: database schema
        """
        schema_identifier = schema_name
        group_identifiers = ",".join(grant_roles)

        create_schema = text(f"CREATE SCHEMA IF NOT EXISTS {schema_identifier}")
        grant_select_schema = text(
            f"ALTER DEFAULT PRIVILEGES IN SCHEMA {schema_identifier} GRANT SELECT ON TABLES TO {group_identifiers}"
        )
        grant_usage_schema = text(
            f"GRANT USAGE ON SCHEMA {schema_identifier} TO {group_identifiers}"
        )

        with engine.connect() as conn, conn.begin():
            conn.execute(create_schema)
            if grant_roles:
                conn.execute(grant_select_schema)
                conn.execute(grant_usage_schema)

        logging.info(f"Schema {schema_name} has been created successfully.")
        for role in grant_roles:
            logging.info(f"Usage has been granted for role: {role}.")


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('workArounds', '0002_remove_monthlyreport_cycle'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='workday',
            name='offDay',
        ),
    ]


'''
本节文章
https://learnscript.net/zh-hant/obs-python-scripting/junior/data/create-data/ 如何建立资料
'''

# 汇入模组 obspython
import obspython as obs

def script_properties():
    props = obs.obs_properties_create()

    # 添加一个选择背景图片的档案对话方块
    prop = obs.obs_properties_add_path(props, 'path', '图片路径：', obs.OBS_PATH_FILE, '图片档案(*.jpg *.png)', None)
    obs.obs_property_set_modified_callback(prop, path_modified)

    return props

def path_modified(props, prop, settings):
    # 读取档案对话方块确定的档案
    path = obs.obs_data_get_string(settings, 'path')

    # 如果使用者还没有选择任何图片，则不设定图片来源
    if path:
        # 取得场景中的图片来源
        source = obs.obs_get_source_by_name('bg')

        # 将图片档案路径设定到图片来源
        data = obs.obs_data_create()
        obs.obs_data_set_string(data, 'file', path)
        obs.obs_source_update(source, data)

        # 释放资料物件和来源物件
        obs.obs_data_release(data)
        obs.obs_source_release(source)


# Program to swap numbers *WITH* a temporary 3rd variable

class SwapNos:
    def __init__(self, x: int = 0, y: int = 1) -> None:
        self.x = x
        self.y = y

    def swap_third_temp(self) -> None:
        print(f"before: x={self.x}, y={self.y}")
        tmp = self.x
        self.x = self.y
        self.y = tmp
        print(f"after: x={self.x}, y={self.y}")
        self.reset()

    def reset(self) -> None:
        print("[x] resetting...")
        self.x = 0
        self.y = 1

    def swap_no_third_variable(self) -> None:
        print(f"before: x={self.x}, y={self.y}")
        self.x = self.x + self.y
        self.y = self.x - self.y
        self.x = self.x - self.y
        print(f"after: x={self.x}, y={self.y}")
        self.reset()


#18405. 경쟁적 전염
"""
heapq를 쓰는법도 있을것만 같지만 일단 이렇게 구현했다.
"""
#STEP 1. INPUT SETTING
import sys
from collections import deque
input=sys.stdin.readline
N,K=map(int,input().rstrip().split())
board=[]
dist=[[-1]* N for _ in range(N)]
start_deq=deque([])
for row in range(N):
    arr=list(map(int,input().rstrip().split()))
    board.append(arr)
    for col in range(N):
        if arr[col]:
            dist[row][col]=0 #바이러스가 들어있는건 거리 0으로 설정.
            start_deq.append((row,col))

#STEP 2. OPERATION START(BFS, ON)

def bfs(deq, board, dist):
    dx=[1,-1,0,0]
    dy=[0,0,1,-1]
    #이미 시작점은 넣어놨으니 start부분 작업할 필요 없음
    while deq:
        x,y=deq.popleft()

        for i in range(4):
            nx=x+dx[i]; ny=y+dy[i]
            if nx<0 or ny<0 or nx>=N or ny>=N: continue
            if dist[nx][ny]>=0: #이미 방문한 적이 있는데, 하필 나랑 같은 우선순위라면
                if dist[nx][ny]==dist[x][y]+1:
                    board[nx][ny]=min(board[nx][ny],board[x][y]) #더 빠른놈이 먹겠지
                continue
            board[nx][ny]=board[x][y]
            dist[nx][ny]=dist[x][y]+1
            deq.append((nx,ny))
bfs(start_deq,board,dist)

# #바이러스 확인용
# print("-------board--------")
# for row in board:
#     print(row)

# print("-------dist---------")
# for row in dist:
#     print(row)

#결과 출력용
S,X,Y=map(int,input().rstrip().split())
result= int(dist[X-1][Y-1]<=S) * board[X-1][Y-1]
print(result)


import numpy as np
import hydra

from tools.profiler import timeit
from waymo_dataset.registry import PIPELINES
from utils.sampler import preprocess as prep
from utils.bbox import box_np_ops

def _dict_select(dict_, inds):
    for k, v in dict_.items():
        if isinstance(v, dict):
            _dict_select(v, inds)
        else:
            dict_[k] = v[inds]

def drop_arrays_by_name(gt_names, used_classes):
    inds = [i for i, x in enumerate(gt_names) if x not in used_classes]
    inds = np.array(inds, dtype=np.int64)
    return inds

@PIPELINES.register_module
class Preprocess(object):
    def __init__(self, **kwargs):
        self.shuffle_points = kwargs.get("shuffle_points", False) # cfg.shuffle_points
        self.min_points_in_gt = kwargs.get("min_points_in_gt", -1)

        self.mode = kwargs.get('mode')
        if self.mode == "train":
            self.global_rotation_noise = list(kwargs.get("global_rot_noise", None)) if kwargs.get("global_rot_noise", None) is not None else None
            self.global_scaling_noise = list(kwargs.get("global_scale_noise", None)) if kwargs.get("global_rot_noise", None) is not None else None
            self.class_names = kwargs.get("class_names")
            assert len(self.class_names) != 0
            self.db_sampler = kwargs.get('db_sampler', None)
            if self.db_sampler != None:
                # print(cfg.db_sampler)
                # raise NotImplementedError # TODO: implement the builder !
                # self.db_sampler = build_dbsampler(cfg.db_sampler)
                from utils.sampler.sample_ops import DataBaseSamplerV2
                import pickle, logging
                logger = logging.getLogger("build_dbsampler")
                info_path = hydra.utils.to_absolute_path(self.db_sampler['db_info_path']) # skip hydra current output folder
                with open(info_path, "rb") as f:
                    db_infos = pickle.load(f)
                # build preprocessors
                from utils.sampler.preprocess import DBFilterByDifficulty, DBFilterByMinNumPoint, DataBasePreprocessor
                preprocessors = []
                if "filter_by_difficulty" in self.db_sampler['db_prep_steps']:
                    v = list(self.db_sampler['db_prep_steps']["filter_by_difficulty"])
                    preprocessors.append(DBFilterByDifficulty(v, logger=logger))
                elif "filter_by_min_num_points" in self.db_sampler['db_prep_steps']:
                    v = self.db_sampler['db_prep_steps']["filter_by_min_num_points"]
                    preprocessors.append(DBFilterByMinNumPoint(v, logger=logger))
                db_prepor = DataBasePreprocessor(preprocessors)
                self.db_sampler = DataBaseSamplerV2(
                    db_infos,
                    groups = self.db_sampler['sample_groups'],
                    db_prepor = db_prepor,
                    rate = self.db_sampler['rate'],
                    global_rot_range = list(self.db_sampler['global_random_rotation_range_per_object']),
                    logger=logger
                )
            else:
                self.db_sampler = None

            self.npoints = kwargs.get("npoints", -1)

        self.no_augmentation = kwargs.get('no_augmentation', False)

    # @timeit
    def __call__(self, res, info):

        res["mode"] = self.mode

        if res["type"] in ["WaymoDataset"]:
            if "combined" in res["lidar"]:
                points = res["lidar"]["combined"]
            else:
                points = res["lidar"]["points"]
        else:
            raise NotImplementedError

        if self.mode == "train":
            anno_dict = res["lidar"]["annotations"]

            gt_dict = {
                "gt_boxes": anno_dict["boxes"],
                "gt_names": np.array(anno_dict["names"]).reshape(-1),
            }

        if self.mode == "train" and not self.no_augmentation:
            selected = drop_arrays_by_name(
                gt_dict["gt_names"], ["DontCare", "ignore", "UNKNOWN"]
            )

            _dict_select(gt_dict, selected)

            if self.min_points_in_gt > 0:
                point_counts = box_np_ops.points_count_rbbox(
                    points, gt_dict["gt_boxes"]
                )
                mask = point_counts >= self.min_points_in_gt
                _dict_select(gt_dict, mask)

            gt_boxes_mask = np.array(
                [n in self.class_names for n in gt_dict["gt_names"]], dtype=np.bool_
            )

            if self.db_sampler:
                sampled_dict = self.db_sampler.sample_all(
                    res["metadata"]["image_prefix"],
                    gt_dict["gt_boxes"],
                    gt_dict["gt_names"],
                    res["metadata"]["num_point_features"],
                    False,
                    gt_group_ids=None,
                    calib=None,
                    road_planes=None
                )

                if sampled_dict is not None:
                    sampled_gt_names = sampled_dict["gt_names"]
                    sampled_gt_boxes = sampled_dict["gt_boxes"]
                    sampled_points = sampled_dict["points"]
                    sampled_gt_masks = sampled_dict["gt_masks"]
                    gt_dict["gt_names"] = np.concatenate(
                        [gt_dict["gt_names"], sampled_gt_names], axis=0
                    )
                    gt_dict["gt_boxes"] = np.concatenate(
                        [gt_dict["gt_boxes"], sampled_gt_boxes]
                    )
                    gt_boxes_mask = np.concatenate(
                        [gt_boxes_mask, sampled_gt_masks], axis=0
                    )

                    points = np.concatenate([sampled_points, points], axis=0)

            _dict_select(gt_dict, gt_boxes_mask)

            gt_classes = np.array(
                [self.class_names.index(n) + 1 for n in gt_dict["gt_names"]],
                dtype=np.int32,
            )
            gt_dict["gt_classes"] = gt_classes

            gt_dict["gt_boxes"], points = prep.random_flip_both(gt_dict["gt_boxes"], points)

            gt_dict["gt_boxes"], points = prep.global_rotation(
                gt_dict["gt_boxes"], points, rotation=self.global_rotation_noise
            )
            gt_dict["gt_boxes"], points = prep.global_scaling_v2(
                gt_dict["gt_boxes"], points, *self.global_scaling_noise
            )
        elif self.no_augmentation:
            gt_boxes_mask = np.array(
                [n in self.class_names for n in gt_dict["gt_names"]], dtype=np.bool_
            )
            _dict_select(gt_dict, gt_boxes_mask)

            gt_classes = np.array(
                [self.class_names.index(n) + 1 for n in gt_dict["gt_names"]],
                dtype=np.int32,
            )
            gt_dict["gt_classes"] = gt_classes

        if self.shuffle_points:
            np.random.shuffle(points)

        res["lidar"]["points"] = points

        if self.mode == "train":
            res["lidar"]["annotations"] = gt_dict

        return res, info


#!/usr/bin/env python
# -*- coding:utf-8 -*-

#@ brief introduction
"""
本段程序描述了移动机器人底盘的一些控制方法，包括使能、前进、设置底盘速度等
底盘电机的控制可以通过多种方式，例如：can modbus等
"""

from ZL_motor_control import ZL_motor_control
# class ZL_motor_control
import can
from math import *
import time
# 外部设置bus，然后传递给car
class car(object):
    def __init__(self,wheel_diameter,wheel_distance,bus,id_list):
        self.bus = bus
        self.diameter = wheel_diameter
        self.distance = wheel_distance
        self.id_list = id_list
        self.odom = {'x':0,'y':0,'theta':0,'v':0,'w':0}
        self.isRunMode = False
        self.isSending = False

    def enable(self):
        return self.bus.enable(self.id_list)

    def disable(self):
        return self.bus.disable(self.id_list)

    #根据车的速度，计算轮子的速度
    def set_car_vel(self,v,w):
        data_dict = self.cal_wheel_vel(v,w)
        return self.bus.only_set_vel(self.id_list,data_dict)

    # 计算轮子速度
    def cal_wheel_vel(self,v,w):
        w1 = 2*v/self.diameter - w*self.distance/self.diameter
        w2 = -(2*v/self.diameter + w*self.distance/self.diameter)
        return {self.id_list[0]:w1,self.id_list[1]:w2}

    # 获取车的速度和转速
    def get_car_status(self):
        #print(self.bus.status)
        w1 = self.bus.status[self.id_list[0]]["Vel"]
        w2 = self.bus.status[self.id_list[1]]["Vel"]
        w = (w1+w2)*self.diameter/2/self.diameter
        v = (w1-w2)*self.diameter/2
        return [v,w]

    #设置车辆odom信息
    def set_odom(self):
        dt = 0.05
        #print("set odom")
        v,w = self.get_car_status()
        self.odom['x']= self.odom['x'] + v*dt*cos(self.odom['theta'])
        self.odom['y']= self.odom['y'] + v*dt*sin(self.odom['theta'])
        self.odom['theta'] = self.odom['theta'] + w*dt
        self.odom['v'] = v
        self.odom['w'] = w

    # 进入config mode,关闭bus
    def config_mode(self):
        self.bus.bus.ser.setDTR(False)
        self.bus.set_vel_stop(self.id_list)
        self.bus.disable(self.id_list)
        self.isRunMode = False
        self.bus.close_bus()

    # 进入run_mode，就可以进行速度控制了
    def run_mode(self):
        self.bus.open_bus()
        self.bus.bus.ser.setDTR(False)
        # 设置运动模式--速度模式
        mode = {}
        for member in self.id_list:
            mode[member] = 0x2F
        self.bus.set_mode(self.id_list,mode)
        self.bus.enable(self.id_list)
        self.isRunMode = True
        print("diff_car go into the run mode")

    # 跟新轮子信息以及车子信息
    def update_status(self):
        recv_msg = None
        try:
            recv_msg = self.bus.recv(timeout=self.bus.timeout)
        except can.CanError as e:
            print(e)
            return False
        finally:
            if recv_msg != None:
                #print("update car status")
                self.bus.read_status(recv_msg)
                self.set_odom()

def test_set_car_vel(v,w):
    bus_channel = "/dev/wheels_ZL"
    bus_bitrate = bus_baudrate = 115200
    bus_id_list = [1,2]
    bus_type='serial'
    wheel_diameter = 100
    wheel_distance = 100
    bus = ZL_motor_control(bus_channel,bus_bitrate,bus_baudrate,bus_id_list,bus_type)
    diff_car = car(wheel_diameter,wheel_distance,bus,bus_id_list)
    diff_car.run_mode()
    start = time.time()
    while True:
        diff_car.set_car_vel(v,w)
        if (start-time.time()>2):
            break

def test_car_run_mode():
    bus_channel = "/dev/wheels_ZL"
    bus_bitrate = bus_baudrate = 115200
    bus_id_list = [1,2]
    bus_type='serial'
    wheel_diameter = 100
    wheel_distance = 100
    bus = ZL_motor_control(bus_channel,bus_bitrate,bus_baudrate,bus_id_list,bus_type)
    diff_car = car(wheel_diameter,wheel_distance,bus,bus_id_list)
    diff_car.run_mode()

def test_car_config_mode():
    bus_channel = "/dev/wheels_ZL"
    bus_bitrate = bus_baudrate = 115200
    bus_id_list = [1,2]
    bus_type='serial'
    wheel_diameter = 100
    wheel_distance = 100
    bus = ZL_motor_control(bus_channel,bus_bitrate,bus_baudrate,bus_id_list,bus_type)
    bus.open_bus()
    diff_car = car(wheel_diameter,wheel_distance,bus,bus_id_list)
    diff_car.config_mode()

if __name__ == '__main__':
    #test_car_config_mode()
    #test_car_run_mode()
    test_set_car_vel(5,5)


import sys

from PyQt5 import Qt, QtGui
from PyQt5.QtWidgets import QDialog, QWidget, QVBoxLayout, QScrollArea, QApplication, QMainWindow
from PyQt5.uic import loadUi

from Screens import db_objects as dbo
import gnrl_database_con

class InspectionPlannerPage(QDialog):
    def __init__(self, mainWindowRef: QMainWindow):
        super(InspectionPlannerPage, self).__init__()
        self.previously_selected_constructionItem = None
        loadUi(r'inspectionPlannerPage_UI.ui', self)
        self.mainWindow = mainWindowRef

        # self.rightSidedMenu.setFixedWidth(0)

        self.setObjectName('InspectionPlannerPage')
        self.db: gnrl_database_con.Database = QApplication.instance().database
        self.scrollAreaContent: QWidget
        self.scrollLayout = QVBoxLayout()
        self.scrollArea: QScrollArea
        self.scrollArea.setLayout(self.scrollLayout)

        self.constructions_objects = self.loadConstructionList()
        self.rightSidedMenu.setCurrentIndex(0)

        # -------------------------------------------------- Buttons script

        import inspectionPlannerWindow_SCRIPT
        self.openModuleBtn.clicked.connect(
            lambda: (self.openNewModule(inspectionPlannerWindow_SCRIPT.InspectionPlannerWindow(
                self.constructions_objects))))

    def loadConstructionList(self):
        construction_objects = []
        for construct_id in range(len(self.db.table_into_DF('Deki_mainConstructions'))):
            construction = dbo.MainConstruction()
            construction.load_info(construct_id + 1)
            construction_objects.append(construction)
            constructionListItem = ConstructionListItemPageVersion(self, construction)
            constructionListItem.clicked.connect(self.updateRightMenu)
            self.scrollLayout.addWidget(constructionListItem, alignment=Qt.Qt.AlignTop)
        self.scrollLayout.setAlignment(Qt.Qt.AlignTop)
        return construction_objects

    def updateRightMenu(self):
        if self.previously_selected_constructionItem is None:
            for constructionItem in self.scrollArea.findChildren(ConstructionListItemPageVersion):
                if constructionItem.selected:
                    self.previously_selected_constructionItem = constructionItem
                    self.load_selectedItemInfo(constructionItem.constructionObj)
                    break
        else:
            for constructionItem in self.scrollArea.findChildren(ConstructionListItemPageVersion):
                if constructionItem.selected and constructionItem != self.previously_selected_constructionItem:
                    self.previously_selected_constructionItem.deselect()
                    self.load_selectedItemInfo(constructionItem.constructionObj)
                    self.previously_selected_constructionItem = constructionItem

    def load_selectedItemInfo(self, constructionObj):
        if not constructionObj.released:
            self.rightSidedMenu.setCurrentIndex(1)
            welds_df = self.db.table_into_DF(f"{constructionObj.info['serial_number']}_modelWelds")
            unique_welds = welds_df[welds_df['same_as_weldID'].isna()]
            if len(unique_welds) != 0:
                self.uniqueWeldsBtn.setText(f"{len(unique_welds)}")
            else:
                self.uniqueWeldsBtn.setText(f"0")
            test_assigned = self.db.df_from_filteredTable(
                f"{constructionObj.info['serial_number']}_modelWelds", 'testing_methods',
                "''", False)
            if len(test_assigned) != 0:
                self.testAssignedBtn.setText(f"{len(test_assigned)}")
            else:
                self.testAssignedBtn.setText(f"0")
        else:
            self.rightSidedMenu.setCurrentIndex(2)

    def openNewModule(self, newModuleWindow: QWidget):
        newModuleWindow.show()
        # self.close()
        # in lambda definition an "event" has to be passed for proper functionality!
        newModuleWindow.closeEvent = lambda event: self.show()

class ConstructionListItemPageVersion(QWidget):
    clicked = Qt.pyqtSignal(object)
    deselected = Qt.pyqtSignal(object)

    def __init__(self, parentScreenObj: InspectionPlannerPage, loadedConstructionObject: dbo.MainConstruction):
        super(ConstructionListItemPageVersion, self).__init__()
        # set attribute that deletes the instance of this class on closeEvent
        loadUi(r'MainConstructionListItem_UI.ui', self)

        self.constructionID = loadedConstructionObject.info['id']
        self.parentScreen = parentScreenObj
        self.constructionObj = loadedConstructionObject
        self.db = QApplication.instance().database
        self.subConstructions_db_table = f"{self.constructionObj.info['serial_number']}_SubConstructions"

        self.releaseConstructionBtn.hide()

        self.selected = False

        self.assignInfoToWidgets()

    def mousePressEvent(self, a0: QtGui.QMouseEvent) -> None:
        super(ConstructionListItemPageVersion, self).mousePressEvent(a0)
        if not self.selected and self.constructionObj.released:
            # If construction has been released mark it as clicked and released (Green)
            self.selected = True
            self.mainFrame.setStyleSheet("#mainFrame{border-width: 3px;"
                                         "border-style: solid;"
                                         "border-color: rgb(30, 210, 80);}")
        elif not self.selected and not self.constructionObj.released:
            # If construction hasn't been released mark it as clicked but not released (Orange)
            self.mainFrame.setStyleSheet("#mainFrame{border-width: 3px;"
                                         "border-style: solid;"
                                         "border-color: rgb(255, 150, 0);}")
            self.selected = True

        # Has to be at the end in order to call the connected function after run of above code
        self.clicked.emit(self.constructionObj)

    def assignInfoToWidgets(self):
        self.constructionTag.setText(self.constructionObj.info["tag"])
        self.constructionName.setText(self.constructionObj.info['name'])
        self.constructionPicture.setPixmap(
            self.constructionObj.picture.scaledToHeight(120, mode=Qt.Qt.SmoothTransformation))
        self.seriesSize.setText(self.constructionObj.info['serial_number'])
        self.clientLbl.setText(self.constructionObj.info['owner'])
        in_preparation_style = 'color: rgb(255, 255, 255);' \
                               'font: 75 bold 9pt "Arial";' \
                               'background-color: rgb(250,150,0);' \
                               'border-radius: 10px;'
        released_style = 'color: rgb(255,255,255);' \
                         'font: 75 bold 9pt "Arial";' \
                         'text-decoration: underline;' \
                         'background-color: rgb(30, 210, 80);' \
                         'border-radius: 10px;'
        (self.stateLbl.setText('In preparation'), self.stateLbl.setStyleSheet(in_preparation_style)) if not \
            self.db.is_table(f'{self.constructionObj.info["serial_number"]}_welds') else \
            (self.stateLbl.setText('Released at: 17 Dec 22'), self.stateLbl.setStyleSheet(released_style))
        counter = len(self.constructionObj.subConstructions_df)
        self.subsAmountLbl.setText(str(counter))
        counter = len(self.constructionObj.modelWelds_df)
        self.weldsAmountLbl.setText(str(counter))

    def deselect(self):
        print(f"{self} deselected")
        self.mainFrame.setStyleSheet("#mainFrame{border-width: 0px;")
        self.selected = False
        self.deselected.emit(self.constructionObj)

if __name__ == "__main__":
    from mainWindow import DekiDesktopApp, MainWindow

    qApp = DekiDesktopApp(sys.argv)

    mw = MainWindow()
    mw.show()

    try:
        sys.exit(qApp.exec_())
    except:
        print("Exiting the App")


#noteParser.py
'''
3.5.x
Description: This module splits a note up into its #tag and its text.
Author: Michael Mentele
'''
import re

def parseText(note):
	'''Parses a string into its hashtag and textstring.'''
	try:
		hashtag_idx = note.index('#')
	except ValueError:
		raise Exception('No hashtag in note!')

	hashtag = note[hashtag_idx:]
	text = note[:hashtag_idx]

	return [hashtag, text]


# -*- coding: utf-8 -*-
"""
Created on Sun Jul 16 14:39:03 2017

@author: tangwenhua
"""

import numpy as np

"""
1.首先min/max与np.argmin/np.argmax函数的功能不同
  前者返回值，后者返回最值所在的索引（下标）

2.处理的对象不同
  前者跟适合处理list等可迭代对象，而后者自然是numpy里的核心数据结构ndarray（多维数组）

3.min/max是Python内置的函数
  np.argmin/np.argmax是numpy库中的成员函数
"""

a = np.arange(6)  #[0,1,2,3,4,5]
b = np.argmax(a)
print(b)          #5

a1 = np.arange(6).reshape(2,3)  #[[0 1 2]
                                 #[3 4 5]]
b1 = np.argmax(a1)
print(b1)        #5

c1 = np.argmax(a1, axis=0) #按照列来求最大值的索引
print(c1)       #[1 1 1]

c2 = np.argmax(a1, axis=1) #按照行来求最大值的索引
print(c2)      #[2 2]


from PyMca5.PyMcaPhysics.xrf import FastXRFLinearFit
from XRDXRFutils.data import DataXRF, SyntheticDataXRF
import h5py
from os.path import basename, dirname, join, exists
from os import remove

class FastFit():
    def __init__(self, data = None, cfgfile = None, outputdir = None):
        self.data = data
        self.cfgfile = cfgfile
        self.outputdir = outputdir
        self.outputRoot = "IMAGES"
        if self.outputdir:
            self.filename = join(self.outputdir, f'{self.outputRoot}.h5')

    def fit(self):
        if type(self.data) != type(None) and self.cfgfile and self.outputdir:
            self.fastfit = FastXRFLinearFit.FastXRFLinearFit()
            self.fastfit.setFitConfigurationFile(self.cfgfile)

            outbuffer = self.fastfit.fitMultipleSpectra(
                y = self.data,
                weight = 1,
                refit = 1,
                concentrations = 0,
                outputDir = self.outputdir,
                outputRoot= self.outputRoot,
                h5  = True)

            zero = outbuffer['configuration']['detector']['zero']
            gain = outbuffer['configuration']['detector']['gain']
            self.parameters = (0, gain, zero)

            self._load_fit_results()

        return self

    def _load_fit_results(self):
        self.labels  = {}
        with h5py.File(self.filename, 'r') as f:
            keys = f['images']['xrf_fit']['results']['parameters'].keys()
            for k in keys:
                if 'errors' not in k:
                    label = f['images']['xrf_fit']['results']['parameters'][k][()]
                    self.labels[k.replace('_','-')] = label

    def get_labels(self):
        if hasattr(self, "labels"):
            return self.labels

    def get_calibration_pars(self):
        if hasattr(self, "parameters"):
            return self.parameters


# 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/12922

def solution(n):
    answer = '수'
    for i in range(1, n):
        if n == 1:
            return answer
        if answer[i-1] == '수':
            answer += '박'
        if answer[i-1] == '박':
            answer += '수'
    print(answer)
    return answer

# def water_melon(n):

#     answer = "수박" * n

#     return answer[:n]


import tempfile
from datetime import datetime, timedelta
from typing import Any, Generator

import openpyxl
import pandas as pd
import pytest
from dateutil.tz import tzutc
from pytest_mock import MockFixture

from toucan_connectors.s3.s3_connector import S3Connector, S3DataSource
from toucan_connectors.toucan_connector import ConnectorStatus

@pytest.fixture
def raw_connector() -> S3Connector:
    return S3Connector(
        name='my_sts_s3_connector',
        bucket_name='my-s3-bucket',
        role_arn='my-role-arn',
        prefix='some/path',
        workspace_id='workspace-id',
        sts_access_key_id='id',
        sts_secret_access_key='secret',
    )

@pytest.fixture
def connector(mocker: MockFixture, raw_connector: S3Connector) -> Generator[Any, Any, Any]:
    mocker.patch.object(
        raw_connector,
        '_get_assumed_sts_role',
        return_value={
            'Credentials': {
                'AccessKeyId': 'test',
                'SecretAccessKey': 'toto',
                'SessionToken': 'tata',
            }
        },
    )
    yield raw_connector

@pytest.fixture
def sts_data_source_csv() -> Generator[Any, Any, Any]:
    yield S3DataSource(
        domain='test',
        name='test',
        file='my-file.csv',
        reader_kwargs={'preview_nrows': 2},
        fetcher_kwargs={},
    )

@pytest.fixture
def sts_data_source_xlsx() -> Generator[Any, Any, Any]:
    yield S3DataSource(
        domain='test',
        name='test',
        file='my-file.xlsx',
        reader_kwargs={'engine': 'openpyxl'},
        fetcher_kwargs={},
    )

@pytest.fixture
def sts_data_source_regex() -> Generator[Any, Any, Any]:
    yield S3DataSource(
        domain='test',
        name='test',
        file='data[0-9]+\\.csv$',
        reader_kwargs={},
        fetcher_kwargs={},
    )

def test_get_status(mocker: MockFixture, connector: S3Connector) -> None:
    # Test case where get_sts_role returns without raising an exception
    expected_status = ConnectorStatus(status=True)
    actual_status = connector.get_status()
    assert actual_status == expected_status

    mocker.patch.object(connector, '_get_assumed_sts_role', side_effect=Exception('Error'))
    expected_status = ConnectorStatus(
        status=False,
        error='Cannot verify connection to S3 and/or AssumeRole failed : Error',
    )
    actual_status = connector.get_status()
    assert actual_status == expected_status

def test_forge_url(connector: S3Connector) -> None:
    assert (
        connector._forge_url('key', 'secret', 'token', 'file')
        == 's3://key:secret@my-s3-bucket/some/path/file'
    )
    # with special characters, those needed to be urlencoded
    assert (
        connector._forge_url('k/e@y', 'sec/re@special/t', 'token1', 'file')
        == 's3://k%2Fe%40y:sec%2Fre%40special%2Ft@my-s3-bucket/some/path/file'
    )
    # on prefix empty
    connector.prefix = ''
    assert (
        connector._forge_url('key', 'secret', 'token3', 'file')
        == 's3://key:secret@my-s3-bucket/file'
    )
    connector.prefix = 'tea/'
    assert (
        connector._forge_url('key', 'secret', 'token', 'fileC')
        == 's3://key:secret@my-s3-bucket/tea/fileC'
    )
    connector.prefix = '/tea/secondo'
    assert (
        connector._forge_url('key', 'secret', 'token', 'fileB')
        == 's3://key:secret@my-s3-bucket/tea/secondo/fileB'
    )
    connector.prefix = '///tea/secondo/tertio////'
    assert (
        connector._forge_url('key', 'secret', 'token', 'fileA')
        == 's3://key:secret@my-s3-bucket/tea/secondo/tertio/fileA'
    )
    connector.prefix = 'tea'
    assert (
        connector._forge_url('key', 'secret', 'token', '/fileZ')
        == 's3://key:secret@my-s3-bucket/tea/fileZ'
    )

def test_validate_external_id(mocker: MockFixture) -> None:
    # workspace_id should override external_id
    assert (
        S3Connector(
            name='my_sts_s3_connector',
            bucket_name='my-s3-bucket',
            role_arn='my-role-arn',
            prefix='some/path',
            workspace_id='a',
            external_id='b',
        ).external_id
        == 'a'
    )

def test_retrieve_data_with_limit_offset(
    mocker: MockFixture,
    connector: S3Connector,
    sts_data_source_csv: S3DataSource,
    sts_data_source_xlsx: S3DataSource,
) -> None:
    # We mock s3_open()
    mock_s3_open = mocker.patch('peakina.io.s3.s3_utils.s3_open')
    mock_s3_open_retries = mocker.patch('peakina.io.s3.s3_utils._s3_open_file_with_retries')
    boto3_session = mocker.patch('toucan_connectors.s3.s3_connector.boto3.Session')
    boto3_session.return_value.client.return_value.get_paginator.return_value.paginate.return_value = [
        {'Contents': [{'Key': 'my-file.csv'}, {'Key': 'my-file.xlsx'}]}
    ]

    with tempfile.NamedTemporaryFile(suffix='.xlsx') as temp_excel_file:
        with tempfile.NamedTemporaryFile(suffix='.csv') as temp_csv_file:
            ### --- for excel --- ###
            excel_df = pd.DataFrame({'X': [1, 2, 3, 4], 'Y': [5, 6, 7, 8], 'Z': [9, 10, 11, 12]})
            excel_df.to_excel(temp_excel_file.name, engine='openpyxl', index=False)

            mocker.patch('tempfile.NamedTemporaryFile', return_value=temp_excel_file)
            expected_return = excel_df.to_string()
            mock_s3_open_retries.return_value.read.return_value = expected_return.encode('utf-8')
            # s3_open side_effect
            mock_s3_open.side_effect = [
                temp_excel_file.read(),
                openpyxl.load_workbook(temp_excel_file.name),
            ]

            result = connector._retrieve_data(sts_data_source_xlsx, offset=2, limit=1)

            # assert that result is a DataFrame and has the expected values
            assert isinstance(result, pd.DataFrame)
            expected_result = pd.DataFrame(
                {'X': [3], 'Y': [7], 'Z': [11], '__filename__': 'my-file.xlsx'}
            )
            assert result.equals(expected_result)

            ### --- for csv --- ###
            csv_df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 11, 12]})
            csv_df.to_csv(temp_csv_file.name, index=False)

            mocker.patch('tempfile.NamedTemporaryFile', return_value=temp_csv_file)
            expected_return = csv_df.to_csv(index=False, sep=',') or ''
            mock_s3_open_retries.return_value.read.return_value = expected_return.encode('utf-8')
            # s3_open side_effect
            mock_s3_open.side_effect = [
                temp_csv_file.read().decode('utf-8'),
                pd.read_csv(temp_csv_file.name),
            ]

            result = connector._retrieve_data(sts_data_source_csv, offset=1, limit=2)
            # assert that result is a DataFrame and has the expected values
            assert isinstance(result, pd.DataFrame)
            expected_result = pd.DataFrame(
                {'A': [2, 3], 'B': [6, 7], 'C': [10, 11], '__filename__': 'my-file.csv'}
            )
            assert result.equals(expected_result)

def test_retrieve_data_match_patterns(
    mocker: MockFixture, connector: S3Connector, sts_data_source_regex: S3DataSource
) -> None:
    connector._forge_url = mocker.Mock(return_value='s3://example.com/data.csv')

    boto3_session = mocker.patch('toucan_connectors.s3.s3_connector.boto3.Session')
    boto3_session.return_value.client.return_value.get_paginator.return_value.paginate.return_value = [
        {
            'Contents': [
                {'Key': 'data/file1.txt'},
                {'Key': 'data1.csv'},
                {'Key': 'data123.csv'},
                {'Key': 'data/subfolder/file3.txt'},
                {'Key': 'data/subfolder/data2.csv'},
            ]
        }
    ]
    peakina_datasource = mocker.patch('toucan_connectors.s3.s3_connector.DataSource')
    peakina_datasource.return_value.get_df.return_value = pd.DataFrame()

    # Invoke the _retrieve_data method
    _ = connector._retrieve_data(sts_data_source_regex)

    # Assertions
    connector._forge_url.assert_called()
    # the url forger was called 2 times
    assert connector._forge_url.call_count == 2
    # for data1.csv and data123.csv because they match the regex
    # 'data[0-9]+\.csv$'
    assert connector._forge_url.call_args_list[0][1]['file'] == 'data1.csv'
    assert connector._forge_url.call_args_list[1][1]['file'] == 'data123.csv'

def test_get_assumed_sts_role_cached(mocker: MockFixture, raw_connector: S3Connector) -> None:
    """should cache assume role"""
    boto3_client = mocker.patch('toucan_connectors.s3.s3_connector.boto3.client')
    sts_client = boto3_client()
    sts_client.assume_role.return_value = {
        'Credentials': {
            'Expiration': datetime.utcnow().replace(tzinfo=tzutc()) + timedelta(hours=1)
        }
    }
    raw_connector._get_assumed_sts_role()
    raw_connector._get_assumed_sts_role()
    assert sts_client.assume_role.call_count == 1

def test_get_assumed_sts_role_expired(mocker: MockFixture, raw_connector: S3Connector) -> None:
    """should invalidate cache and re-assume role when expired"""
    boto3_client = mocker.patch('toucan_connectors.s3.s3_connector.boto3.client')
    sts_client = boto3_client()
    sts_client.assume_role.return_value = {
        'Test': 'OK',
        'Credentials': {
            'Expiration': datetime.utcnow().replace(tzinfo=tzutc()) + timedelta(hours=-1)
        },
    }
    raw_connector._get_assumed_sts_role()
    assert sts_client.assume_role.call_count == 2


#import libs
import sys
import os
import socket
import pygame

pygame.init()

#define variables
PORT = int(sys.argv[1])
host = "localhost"

HOST = socket.gethostbyname(host)

#Connect to host at port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#try connecting to host
try:
    s.connect((HOST, PORT))
    print("Connected to server " + str(HOST))

except:
    print("ERROR: Could not connect to server")
    print("Quitting Program")
    quit()

    #store recived data in data_recived
decoded_data = s.recv(1024).decode()

player = int(decoded_data)
print("You are player " + str(decoded_data) )

running = True

while running:

    keys = pygame.key.get_pressed()
    print(keys)
    input()

    if (keys[pygame.K_a]):
        s.send(str.encode("a"))
        print("sendt")
        quit()

    if (keys[pygame.K_1]):
        quit()

print("Ended koop " + player)
data = input()
s.send(str.encode(data))

print(decoded_data)


"""
ins_del

@Author: linlin
@Date: 17.05.23
"""
import numpy as np

def _optimize_costs_ins_del(
		nb_cost_mat, dis_k_vec, sorted_label_pairs, tria_rule_mode, remove_zeros,
		reconstruct_costs=True
):
	from gcl_frame.models.optim_costs2 import _optimize_costs_solve
	from gcl_frame.models.optimizers.utils import _reconstruct_costs, \
		_remove_zero_cols, _rejoin_zero_cols
	from gcl_frame.models.optimizers.tri_rule import _construct_tri_rule_vecs

	# Construct the triangle inequality constraints:
	tri_rule_list = _construct_tri_rule_vecs(sorted_label_pairs, tria_rule_mode)

	# Compress columns that are substitutions:
	nb_cost_mat, tri_rule_list, idx_rel = _compress_substitution_cols(
		nb_cost_mat, tri_rule_list, sorted_label_pairs
	)

	# Remove zero columns:
	if remove_zeros:
		new_nb_cost_mat, new_tri_rule_list, idx_non_zero = _remove_zero_cols(
			nb_cost_mat, tri_rule_list
		)
	else:
		new_nb_cost_mat = nb_cost_mat
		new_tri_rule_list = tri_rule_list

	# Solve the optimization problem:
	edit_costs_new, residual = _optimize_costs_solve(
		new_nb_cost_mat, dis_k_vec, new_tri_rule_list
	)

	if remove_zeros:
		edit_costs_new = _rejoin_zero_cols(edit_costs_new, idx_non_zero, nb_cost_mat.shape[1])

	# Reconstruct the edit costs from the compressed edit costs:
	edit_costs_new = _rejoin_substitution_cols(
		edit_costs_new, sorted_label_pairs, idx_rel
	)

	if reconstruct_costs:
		edit_costs_new = _reconstruct_costs(edit_costs_new, sorted_label_pairs)

	# Notice that the returned residual is the distance instead of the squared
	# distance. You may want to revise the codes where this function is invoked.
	return edit_costs_new, residual

def _compress_substitution_cols(nb_cost_mat, tri_rule_list, sorted_label_pairs):
	def _compress(sorted_l_pairs, nb_mat, rule_list):
		# for unlabeled graphs:
		if sorted_l_pairs == [('', ' '), (' ', ''), (' ', ' ')]:
			return nb_mat, rule_list
		# for labeled graphs:
		else:
			# Get the number of labels by finding the pairs starting with '':
			n_labels = len([i for i in sorted_l_pairs if i[0] == ''])

			# Get the insertion and deletion columns of nb_mat, namely the
			# [0: 2 * n_labels] columns, and compress the substitution columns:
			nb_mat_new = np.array(
				[list(i[0:2 * n_labels]) + [np.sum(i[2 * n_labels:])] for i in nb_mat]
			)
			# Same for the rule list:
			rule_list_new = [
				i[0:2 * n_labels] + [i[2 * n_labels]] for i in rule_list
			]
			return nb_mat_new, rule_list_new

	# Get the index of the separation between nodes and edges:
	idx_sep = len(sorted_label_pairs[0])

	# for nodes:
	nb_cost_mat_nodes = nb_cost_mat[:, 0:idx_sep]
	tri_rule_list_nodes = [i[0:idx_sep] for i in tri_rule_list]
	nb_cost_mat_nodes, tri_rule_list_nodes = _compress(
		sorted_label_pairs[0], nb_cost_mat_nodes, tri_rule_list_nodes
	)
	idx_sep_new = nb_cost_mat_nodes.shape[1]

	# for edges:
	nb_cost_mat_edges = nb_cost_mat[:, idx_sep:]
	tri_rule_list_edges = [i[idx_sep:] for i in tri_rule_list]
	nb_cost_mat_edges, tri_rule_list_edges = _compress(
		sorted_label_pairs[1], nb_cost_mat_edges, tri_rule_list_edges
	)

	# Concatenate the two:
	nb_cost_mat_new = np.concatenate(
		[nb_cost_mat_nodes, nb_cost_mat_edges], axis=1
	)
	tri_rule_list_new = [
		i + j for i, j in zip(tri_rule_list_nodes, tri_rule_list_edges)
	]

	# Remove the same rows from the rule list:
	tri_rule_list_new = list(set(tuple(i) for i in tri_rule_list_new))

	return nb_cost_mat_new, tri_rule_list_new, idx_sep_new

def _rejoin_substitution_cols(edit_costs, sorted_label_pairs, idx_sep):
	def _rejoin(sorted_l_pairs, ed_costs):
		# for unlabeled graphs:
		if sorted_l_pairs == [('', ' '), (' ', ''), (' ', ' ')]:
			return ed_costs
		# for labeled graphs:
		else:
			# Get the total length of the edit costs:
			length = len(sorted_l_pairs)
			# Append the substitution costs to the end of the edit costs:
			cs = ed_costs[-1]
			len_to_append = length - len(ed_costs)
			ed_costs = np.append(ed_costs, [cs for i in range(len_to_append)])
			return ed_costs

	# Get node and edge costs.
	node_costs = edit_costs[:idx_sep]
	edge_costs = edit_costs[idx_sep:]

	# for nodes:
	node_costs = _rejoin(sorted_label_pairs[0], node_costs)

	# for edges:
	edge_costs = _rejoin(sorted_label_pairs[1], edge_costs)

	# Concatenate the two:
	edit_costs_new = np.concatenate([node_costs, edge_costs], axis=0)

	return edit_costs_new


from event_manager.models import Event
from datetime import datetime, timedelta
from celery import shared_task
from django.core.mail import send_mail
import pytz
from scheduler_APP.settings import EMAIL_HOST_USER

@shared_task()
def to_remind():
    events_set = Event.objects.filter(remind_option__isnull=False)
    for event in events_set:
        current_time = pytz.UTC.localize(datetime.now() + timedelta(hours=3))
        if event.time_to_remind <= current_time:
            subject = 'Upcoming event notification'
            message = f'Please be informed of upcoming event, details are below: \n' \
                      f'Event: {event.event} \n Event starts: {event.event_start} and ends ' \
                      f'{event.event_finish}'
            send_mail(
                subject=subject,
                message=message,
                from_email=EMAIL_HOST_USER,
                recipient_list=[event.user.email]
            )
            Event.objects.filter(id=event.id).update(remind_option=None)


## 시간 제한

N, K = map(int, input().split())
temp_lst = list(map(int, input().split()))

sum_tmp = sum(temp_lst[:K])
tmp_kdays =[sum_tmp]

# for문 내에서 복잡한 연산 최대한 없애기 (sum을 밖에서 한번만)
for i in range(N-K):
    # 맨앞 지우고 맨뒤 +1 index를 더하기
    sum_tmp = sum_tmp - temp_lst[i] + temp_lst[i+K]
    tmp_kdays.append(sum_tmp)

print(max(tmp_kdays))