from PySide6 import QtWidgets, QtCore
import pyqtgraph as pg
import numpy as np
import time

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, radar):
        super().__init__()
        self.setWindowTitle('SignalFromNoise')

        # Виджеты
        centralWidget = QtWidgets.QWidget()
        startBtn = QtWidgets.QRadioButton('Start')
        stopBtn = QtWidgets.QRadioButton('Stop')

        self.fovRadar = QtWidgets.QSpinBox()
        self.fovRadar.setRange(0, 360)
        self.fovRadar.setValue(120)
        self.fovRadar.setSingleStep(2)

        self.rovRadar = QtWidgets.QSpinBox()
        self.rovRadar.setRange(0, 20)
        self.rovRadar.setValue(10)

        self.plotRadar = pg.PlotWidget(background='#04005f')
        grp = QtWidgets.QGroupBox('Manage')

        self.plotRadar.setAspectLocked()

        # Макеты
        layout = QtWidgets.QGridLayout()
        layoutGrpRadar = QtWidgets.QVBoxLayout()
        layoutGrpRadarView = QtWidgets.QGridLayout()

        # Настройка отображения
        self.setCentralWidget(centralWidget)

        centralWidget.setLayout(layout)

        layoutGrpRadar.addWidget(startBtn)
        layoutGrpRadar.addWidget(stopBtn)
        layoutGrpRadarView.addWidget(QtWidgets.QLabel('Fov'), 0, 0)
        layoutGrpRadarView.addWidget(QtWidgets.QLabel('Range'), 0, 1)
        layoutGrpRadarView.addWidget(self.fovRadar, 1, 0)
        layoutGrpRadarView.addWidget(self.rovRadar, 1, 1)

        layoutGrpRadar.addLayout(layoutGrpRadarView)

        grp.setLayout(layoutGrpRadar)

        grp.setSizePolicy(QtWidgets.QSizePolicy.Fixed,
                          QtWidgets.QSizePolicy.Fixed)

        stopBtn.setChecked(True)
        stopBtn.setCheckable(True)

        layout.addWidget(grp, 0, 0)
        layout.addWidget(self.plotRadar, 0, 1)

        self.plotRadar.setXRange(-5, 5)
        self.plotRadar.setYRange(0, 10)

        self.plotRadar.setLabel('left', text='Y position (m)')
        self.plotRadar.setLabel('bottom', text='X position (m)')
        self.plotRadar.showGrid(x=True, y=True)

        # Указатель на новый график с точками
        self.updateGridPlot()

        # Таймер
        self.timer = QtCore.QTimer()
        self.timer.setInterval(200)
        self.timer.timeout.connect(self.updatePlot)

        # Сигналы на продолжение и приостановку генерации
        startBtn.clicked.connect(self.start)
        stopBtn.clicked.connect(self.stop)

        self.fovRadar.valueChanged.connect(self.updateGridPlot)
        self.rovRadar.valueChanged.connect(self.updateGridPlot)

        #Радар
        self.radar = radar if radar else None

    def start(self):
        if self.radar:
            self.radar.startRadar()
        self.timer.start()

    def stop(self):
        if self.radar:
            self.radar.stopRadar()
        self.timer.stop()

    def updateGridPlot(self):
        fov = self.fovRadar.value()
        rov = self.rovRadar.value()
        self.plotRadar.clear()
        for r in range(1, rov + 1, 1):
            circle = QtWidgets.QGraphicsEllipseItem(-r, -r, r * 2, r * 2)
            circle.setPen(pg.mkPen(0.2))
            if fov < 360:
                emp = (180-fov)/2
                circle.setStartAngle(-emp * 16)
                circle.setSpanAngle((-180 + emp*2) * 16)
                self.plotRadar.addItem(circle)
            else:
                self.plotRadar.addItem(circle)
        self.new_points = self.plotRadar.plot([], [], pen=None, symbol='o')

    # Обновление графика
    def updatePlot(self):

        if self.radar:
            self.radar.updateData()

            if self.radar.dataOk:
                detObj = self.radar.detObj
                x = -detObj["x"]
                y = detObj["y"]
                self.new_points.setData(x, y)
        else:
            fov = self.fovRadar.value()
            rov = self.rovRadar.value()
            if fov < 360:
                mean = (180-fov)/2
                theta = np.linspace(np.deg2rad(mean), np.deg2rad(180-mean), 20)
                radius = np.random.uniform(0, rov, size=20)
            else:
                theta = np.linspace(0, 2*np.pi, 100)
                radius = np.random.uniform(0, rov, size=100)
            x = radius * np.cos(theta)
            y = radius * np.sin(theta)
            self.new_points.setData(x, y)


import os
import settings
import subprocess
import traceback
import common_functions

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (QPushButton, QLabel, QLineEdit,
                             QWidget, QGridLayout, QMessageBox,
                             QRadioButton)

# Widgets and functions for the wallet tab
class Wallet(QWidget):
    def __init__(self):
        super().__init__()

        # Creating local variables
        self.vkey_name = ""
        self.address_name = ""
        self.pkh_name = ""

        # Header text
        self.label_0_0 = QLabel("Manage wallet address and its keys.")

        # Cardano picture
        picture_0_2 = QLabel("")
        picture_0_2.setPixmap(QPixmap("./images/cardano.png"))
        picture_0_2.setFixedSize(80,80)
        picture_0_2.setScaledContents(True)

        # Widgets for verification key section
        self.label_1_0 = QLabel("Input verification key name:")
        self.input_2_0 = QLineEdit()
        self.button_2_1 = QPushButton("Set")

        # Widgets for signing key section
        self.label_3_0 = QLabel("Signing key name:")
        self.input_4_0 = QLineEdit()
        self.button_5_0 = QPushButton("Generate both keys")

        # Widget actions for signing and verifaction key section
        self.button_2_1.clicked.connect(self.set_verification_key)
        self.button_5_0.clicked.connect(self.generate_skey_and_vkey)

        # Widgets for payment address section
        self.label_7_0 = QLabel("Input payment address name:")
        self.input_8_0 = QLineEdit()
        self.button_8_1 = QPushButton("Set")
        self.button_8_2 = QPushButton("Generate")
        self.label_9_0 = QLabel("Payment address:")
        self.radioButton_9_1 = QRadioButton("Mainnet")
        self.radioButton_9_2 = QRadioButton("Testnet")
        self.input_10_0 = QLineEdit()
        self.button_10_1 = QPushButton("Show")

        # Widget actions for payment address section
        self.button_8_1.clicked.connect(self.set_address)
        self.button_8_2.clicked.connect(self.generate_address)
        self.button_10_1.clicked.connect(self.show_address)

        # Widgets for payment address key hash section
        self.label_12_0 = QLabel("Payment public key hash name:")
        self.input_13_0 = QLineEdit()
        self.button_13_1 = QPushButton("Set")
        self.button_13_2 = QPushButton("Generate")
        self.label_14_0 = QLabel("Key hash:")
        self.input_15_0 = QLineEdit()
        self.button_15_1 = QPushButton("Show")

        # Widget actions for payment public key hash section
        self.button_13_1.clicked.connect(self.set_pkh)
        self.button_13_2.clicked.connect(self.generate_pkh)
        self.button_15_1.clicked.connect(self.show_pkh)

        # Set label fonts
        labels = [self.label_0_0,
                  self.label_1_0, self.label_3_0,
                  self.label_7_0, self.label_9_0,
                  self.label_12_0, self.label_14_0]
        for label in labels:
            font = label.font()
            font.setPointSize(12)
            label.setFont(font)

        # Set lineEdit sizes
        inputs = [self.input_2_0, self.input_4_0,
                  self.input_8_0, self.input_10_0,
                  self.input_13_0, self.input_15_0]
        for input in inputs:
            input.setFixedSize(500,30)

        # Set button sizes
        buttons = [self.button_2_1,
                   self.button_8_1, self.button_8_2,
                   self.button_10_1, self.button_13_1,
                   self.button_13_2, self.button_15_1]
        for button in buttons:
            button.setFixedSize(80,30)

        self.button_5_0.setFixedSize(160,30)

        # Space between the sections
        self.emptyLabel = QLabel()

        # Layouts
        layout = QGridLayout()
        layout.addWidget(self.label_0_0, 0, 0)
        layout.addWidget(picture_0_2, 0, 2)
        # Adding widgets for verification key section
        layout.addWidget(self.label_1_0, 1, 0)
        layout.addWidget(self.input_2_0, 2, 0)
        layout.addWidget(self.button_2_1, 2, 1)
        layout.addWidget(self.emptyLabel, 3, 0)
        # Adding widgets for signing key section
        layout.addWidget(self.label_3_0, 3, 0)
        layout.addWidget(self.input_4_0, 4, 0)
        layout.addWidget(self.button_5_0, 5, 0)
        layout.addWidget(self.emptyLabel, 6, 0)
        # Adding widgets for payment address section
        layout.addWidget(self.label_7_0, 7, 0)
        layout.addWidget(self.input_8_0, 8, 0)
        layout.addWidget(self.button_8_1, 8, 1)
        layout.addWidget(self.button_8_2, 8, 2)
        layout.addWidget(self.label_9_0, 9, 0)
        layout.addWidget(self.radioButton_9_1, 9, 1)
        layout.addWidget(self.radioButton_9_2, 9, 2)
        layout.addWidget(self.input_10_0, 10, 0)
        layout.addWidget(self.button_10_1, 10, 1)
        layout.addWidget(self.emptyLabel, 11, 0)
        # Adding widgets for payment public key hash section
        layout.addWidget(self.label_12_0, 12, 0)
        layout.addWidget(self.input_13_0, 13, 0)
        layout.addWidget(self.button_13_1, 13, 1)
        layout.addWidget(self.button_13_2, 13, 2)
        layout.addWidget(self.label_14_0, 14, 0)
        layout.addWidget(self.input_15_0, 15, 0)
        layout.addWidget(self.button_15_1, 15, 1)
        layout.addWidget(self.emptyLabel, 16, 0)

        self.setLayout(layout)

    def set_verification_key(self):
        vkey_name = self.input_2_0.text()
        vkey_path = settings.folder_path + "/" + vkey_name
        vkey_exists = os.path.isfile(vkey_path)

        skey_name = vkey_name.split(".")[0] + ".skey"
        skey_path = settings.folder_path + "/" + skey_name
        skey_exists = os.path.isfile(skey_path)

        if not vkey_exists:
            msg = "Verification key does not exists.\n" + \
                  "Please enter a valid file name."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        if not (".vkey" in vkey_name):
            msg = "Verification key has to have a .vkey file extension name.\n" + \
                  "Please type in a file name with a .vkey extension."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        self.vkey_name = vkey_name
        msg = "Verification key file successfully set."
        QMessageBox.information(self, "Notification:", msg)
        if skey_exists:
            self.input_4_0.setText(skey_name)

    def generate_skey_and_vkey(self):
        file_number_counter = 1
        while(True):
            if len(str(file_number_counter)) == 1:
                vkey_name = "0" + str(file_number_counter) + ".vkey"
                skey_name = "0" + str(file_number_counter) + ".skey"
            else:
                vkey_name = str(file_number_counter) + ".vkey"
                skey_name = str(file_number_counter) + ".skey"

            vkey_file_path = settings.folder_path + "/" + vkey_name
            vkey_file_exists = os.path.isfile(vkey_file_path)

            skey_file_path = settings.folder_path + "/" + skey_name
            skey_file_exists = os.path.isfile(skey_file_path)

            if (not vkey_file_exists) and (not skey_file_exists):
                command = "cardano-cli address key-gen " + \
                          "--verification-key-file " + vkey_name + " " + \
                          "--signing-key-file " + skey_name

                if settings.debug_mode:
                    print("Command below is defined in py-files/wallet.py line 190:")
                    print(common_functions.format_command(command) + "\n")
                else:
                    try:
                        subprocess.Popen(command.split(), cwd=settings.folder_path)
                        self.vkey_name = vkey_name
                        self.input_2_0.setText(self.vkey_name)
                        self.input_4_0.setText(skey_name)
                    except Exception:
                        output = traceback.format_exc()
                        common_functions.log_error_msg(output)

                        msg = "Verification and signing key could not be generated.\n" + \
                              "Look at the error.log file for error output."
                        QMessageBox.warning(self, "Notification:", msg,
                                            QMessageBox.Close)
                break

            file_number_counter += 1

    def set_address(self):
        address_name = self.input_8_0.text()
        address_path = settings.folder_path + "/" + address_name
        address_exists = os.path.isfile(address_path)

        if not (".addr" in address_name):
            msg = "Address file has to have a .addr file extension name.\n" + \
                  "Please type in a file name with a .addr extension."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        if not address_exists:
            msg = "Address does not exists.\n" + \
                  "Please enter a valid file name."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        self.address_name = address_name
        msg = "Public address file successfully set."
        QMessageBox.information(self, "Notification:", msg)

    def generate_address(self):
        is_mainnet = self.radioButton_9_1.isChecked()
        is_testnet = self.radioButton_9_2.isChecked()

        if (not is_mainnet) and (not is_testnet):
            msg = "Select option mainnet or testnet."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        if self.vkey_name == "":
            msg = "Please set or generate first a verification key."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        address_name = self.vkey_name.split(".")[0] + ".addr"
        address_path = settings.folder_path + "/" + address_name
        address_exists = os.path.isfile(address_path)

        if address_exists:
            file_number_counter = 1
            while(True):
                if len(str(file_number_counter)) == 1:
                    tmp_address_name = "0" + str(file_number_counter) + ".addr"
                else:
                    tmp_address_name = str(file_number_counter) + ".addr"

                tmp_address_path = settings.folder_path + "/" + tmp_address_name
                tmp_address_exists = os.path.isfile(tmp_address_path)

                if (not tmp_address_exists):
                    address_name = tmp_address_name
                    break

                file_number_counter += 1

            msg = "Address file with same name as verification key already exists.\n" + \
                  "The address file name " + address_name + " will be used."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)

        if is_testnet:
            net_part = "--testnet-magic " + settings.testnet_magic + " "
        elif is_mainnet:
            net_part = "--mainnet "

        command = "cardano-cli address build " + \
                  "--payment-verification-key-file " + self.vkey_name + " " + \
                  net_part + \
                  "--out-file " + address_name

        if settings.debug_mode:
            print("Command below is defined in py-files/wallet.py line 285:")
            print(common_functions.format_command(command) + "\n")
        else:
            try:
                subprocess.Popen(command.split(), cwd=settings.folder_path)
                self.input_8_0.setText(address_name)
                self.address_name = address_name
            except Exception:
                output = traceback.format_exc()
                common_functions.log_error_msg(output)

                msg = "Address could not be generated.\n" + \
                      "Look at the error.log file for error output."
                QMessageBox.warning(self, "Notification:", msg,
                                    QMessageBox.Close)

    def show_address(self):
        address_path = settings.folder_path + "/" + self.address_name
        address_exists = os.path.isfile(address_path)

        if address_exists:
            with open(address_path, "r") as file:
                address = file.read()
            self.input_10_0.setText(address)
        else:
            msg = "Please set or generate first an address file."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)

    def set_pkh(self):
        pkh_name = self.input_13_0.text()
        pkh_path = settings.folder_path + "/" + pkh_name
        pkh_exists = os.path.isfile(pkh_path)

        if not pkh_exists:
            msg = "Public key hash does not exists.\n" + \
                  "Please specify a valid file name."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        if not (".pkh" in pkh_name):
            msg = "Public key hash has to have a .pkh file extension name.\n" + \
                  "Please type in a file name with a .pkh extension."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        self.pkh_name = pkh_name
        msg = "Public key hash file successfully set."
        QMessageBox.information(self, "Notification:", msg)

    def generate_pkh(self):
        if self.vkey_name == "":
            msg = "Please set or generate first a verification key."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)
            return None

        pkh_name = self.vkey_name.split(".")[0] + ".pkh"
        pkh_path = settings.folder_path + "/" + pkh_name
        pkh_exists = os.path.isfile(pkh_path)

        if pkh_exists:
            file_number_counter = 1
            while(True):
                if len(str(file_number_counter)) == 1:
                    tmp_pkh_name = "0" + str(file_number_counter) + ".pkh"
                else:
                    tmp_pkh_name = str(file_number_counter) + ".pkh"

                tmp_pkh_path = settings.folder_path + "/" + tmp_pkh_name
                tmp_pkh_exists = os.path.isfile(tmp_pkh_path)

                if (not tmp_pkh_exists):
                    pkh_name = tmp_pkh_name
                    break

                file_number_counter += 1

            msg = "Public key hash file with same name as verification key already exists." + \
                  "The public key hash file name " + pkh_name + " will be used."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)

        command = "cardano-cli address key-hash " + \
                  "--payment-verification-key-file " + self.vkey_name + " " + \
                  "--out-file " + pkh_name

        if settings.debug_mode:
            print("Command below is defined in py-files/wallet.py line 376:")
            print(common_functions.format_command(command) + "\n")
        else:
            try:
                subprocess.Popen(command.split(), cwd=settings.folder_path)
                self.input_13_0.setText(pkh_name)
                self.pkh_name = pkh_name
            except Exception:
                output = traceback.format_exc()
                common_functions.log_error_msg(output)

                msg = "Public key hash could not be generated.\n" + \
                      "Look at the error.log file for error output."
                QMessageBox.warning(self, "Notification:", msg,
                                    QMessageBox.Close)

    def show_pkh(self):
        pkh_path = settings.folder_path + "/" + self.pkh_name
        pkh_exists = os.path.isfile(pkh_path)

        if pkh_exists:
            with open(pkh_path, "r") as file:
                pkh = file.read()
            self.input_15_0.setText(pkh)
        else:
            msg = "Public key hash file does not exists.\n" + \
                  "If you have generated it, wait a couple of\n" + \
                  "seconds and try again to view the file."
            QMessageBox.warning(self, "Notification:", msg,
                                QMessageBox.Close)


import glob
import shutil
import subprocess
from threading import Thread
from typing import List
from google.cloud import storage
import requests
import os
import logging
import sys
from PIL import Image

from settings import BUKECT_NAME, DEFAULT_IMAGE_URL, JSON_IMAGE_KEY
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

logging.info(f'Evironment: {os.environ}')
# 環境変数の設定
# os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/app/credentials.json"

# 環境変数が正しく設定されたか確認
# if not os.path.exists(os.environ["GOOGLE_APPLICATION_CREDENTIALS"]):
#     print("Fucking hell, credentials.json is not found!")
# else:
#     print("Good, credentials.json is found.")

# Google Cloud Storageクライアントの初期化
# try:
#     storage_client = storage.Client()
#     print("Successfully initialized storage client.")
# except Exception as e:
#     print(f"Initialization failed with error: {e}")

def upload_blob(source_file_name: str, gcs_file_path: str):
    storage_client = storage.Client()
    bucket = storage_client.bucket(BUKECT_NAME)
    blob = bucket.blob(gcs_file_path)
    blob.upload_from_filename(source_file_name)

class MovieConfig:
    def __init__(self, encode_speed: str, output_movie_path: str, image_type='png', frame_rate=6, width=720):
        self.frame_rate = frame_rate
        self.width = width
        self.encode_speed = encode_speed
        self.output_movie_path = output_movie_path
        self.image_type = image_type

def to_image_urls(data: dict) -> list:
    images = []
    for i, item in enumerate(data):
        poster_url = item.get(JSON_IMAGE_KEY, '')
        if poster_url == '':
            images.append(DEFAULT_IMAGE_URL)
        else:
            images.append(poster_url)
    return images

def download_images(image_urls: list[str]) -> list:
    # imgフォルダがない場合、作成する
    if not os.path.exists("img"):
        os.makedirs("img")
    else:
        # すでにimgフォルダがある場合、中身を削除する
        for f in glob.glob("img/*"):
            os.remove(f)
    file_names = []
    for i, image_url in enumerate(image_urls):
        image_file_name = f"img/{i:03d}.png"
        # requestsを使用して画像をダウンロード
        try:
            response = requests.get(image_url, timeout=3)
            response.raise_for_status()  # エラーレスポンスを確認し、エラーの場合は例外を発生させる
            with open(image_file_name, 'wb') as f:
                f.write(response.content)
            file_names.append(image_file_name)
        except requests.RequestException as e:
            print(f"画像のダウンロードに失敗しました: {e}")
    return file_names

def process_images(image_paths: List[str]) -> List[str]:
    for i, path in enumerate(image_paths):
        # 画像をロード
        image = Image.open(path)

        # 画像を左に90度回転
        rotated_image = image.rotate(90, expand=1)

        # アスペクト比を維持しながらリサイズ
        target_size = (1280, 720)
        rotated_image.thumbnail(target_size)

        # 背景を黒で作成
        background = Image.new('RGBA', target_size, (0, 0, 0, 255))

        # リサイズした画像を背景の中央に配置
        bg_w, bg_h = background.size
        img_w, img_h = rotated_image.size
        offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)

        # アルファチャンネルの有無を確認
        if rotated_image.mode == 'RGBA':
            mask = rotated_image.split()[3]
        else:
            mask = None

        # ペースト
        background.paste(rotated_image, offset, mask=mask)

        # 最終的な画像で上書き保存
        background.save(path)
    return image_paths

def copy_images_for_frame_rate(image_paths: List[str], frame_rate) -> None:
    """
    Copy files to create images for frame rate.
    :param image_paths:
    :param frame_rate:
    :return:
    """
    # copy images framerate times -1
    threads = []
    for i in range(1, frame_rate):
        for image_path in image_paths:
            # copy image. ex) image.png -> image_01.png
            new_image_path = image_path.replace(
                f'.{image_path.split(".")[-1]}',
                f'_{i:02d}.{image_path.split(".")[-1]}')

            t = Thread(target=shutil.copy,
                       args=(
                           image_path,
                           new_image_path))
            t.start()
            threads.append(t)
    [thread.join() for thread in threads]

def image_to_movie(movie_config: MovieConfig, image_paths: List[str]) -> None:
    """
    Create image_dir files to movie.
    :param movie_config:
    :return None:
    """
    # create movie dir
    if not os.path.exists("movie"):
        os.makedirs("movie")
    if len(image_paths) == 0:
        raise Exception("No image files.")
    img_dir = 'img/*.' + movie_config.image_type
    logging.info(f'img_dir: {img_dir}')
    copy_images_for_frame_rate(image_paths, movie_config.frame_rate)
    commands = ['ffmpeg',
                '-framerate', f'{movie_config.frame_rate}',
                # Select image_dir/*.file_type
                '-pattern_type', 'glob', '-i', img_dir,
                # iw is input width, -2 is auto height
                '-vf', f"scale='min({movie_config.width},iw)':-2",
                '-c:v', 'h264',  # codec
                '-pix_fmt', 'yuv420p',
                '-profile:v', 'baseline',  # Baseline Profile を使う
                '-bf', '0',  # Bidirectional Predictive Frame を使わない
                '-preset', movie_config.encode_speed,
                '-tune', 'stillimage',  # tune for still image
                '-y',  # overwrite output file
                f'{movie_config.output_movie_path}']
    logging.info(f'commands: {commands}')
    try:
        subprocess.run(commands, check=True, stderr=subprocess.PIPE, text=True)
    except subprocess.CalledProcessError as e:
        error_message = e.stderr
        logging.error(f'Error: {error_message}')


# Pomodoro Technique is a technique that should help with doing tasks efficiently. You work for 25 minutes, then take a 5 minute break. Repeat this step, and after 4 times, you take a 30 minute break.
# Minutes = Total. MinutesDisplay = Displayed Count. MinutesDisplay2 = Dummy count

import time

run = input('Start the Pomodoro cycle? (Y/N)').lower()
seconds = minutes = minutesdisplay = minutesdisplay2 = hours = pomodoros = 0
while run == 'y':
    time.sleep(1)
    seconds += 1

    if minutes == hours == 0:
        print(f'{seconds} seconds elapsed')

    if minutes > 0 and hours == 0:
        print(f'{minutesdisplay} minutes, and {seconds} seconds elapsed')
    if minutes > 0 and hours > 0:
        print(f'{hours} hours, {minutesdisplay} minutes, and {seconds} seconds elapsed')
    if seconds == 60:
        minutesdisplay += 1
        minutesdisplay2 += 1
        minutes += 5
        seconds = 0
    if minutes == 60:
        hours += 1
        minutesdisplay = 0

    if minutesdisplay2 == 25 or minutesdisplay2 == 55 or minutesdisplay2 == 85:
        print('TIME TO TAKE A BREAK FOR 5 MINUTES! (Remember, dont think about work)')

    if minutesdisplay2 == 30 or minutesdisplay2 == 60 or minutesdisplay2 == 90:
        pomodoros += 1
        print(f'Get back to work. You have completed {pomodoros} out of 4 pomodoros until your big break.')
    if minutesdisplay2 == 120:
        print('You have completed 4 out of 4 pomodoros. Take a 30 minute break!')
    if minutesdisplay2 == 150:
        print('Get back to work. You have completed 0 out of 4 pomodoros until your big break.')
        minutesdisplay = minutesdisplay2 = secondsdisplay = pomodoros = 0

Newest Projects/Pomodoro Technique Clock/main.py


from pynput.mouse import Button
from pynput.mouse import Controller as MouseController

from pynput.keyboard import Key
from pynput.keyboard import Controller as KeyboardController

import scipy as scipy
from scipy import interpolate
import time
import numpy as np

import random

mouse = MouseController()
keyboard = KeyboardController()

def add_noise_mouse(mouse_position, delta):
	[x_noise, y_noise] = np.random.uniform(-delta,delta,2)
	return (mouse_position[0]+x_noise, mouse_position[1]+y_noise)

def add_time_noise(time, noise=0.005):
	[noise] = np.random.uniform(0, noise,1)
	return time+noise

def move_mouse(position_1, position_2, num=400, duration=0.2):
	(x1,y1) = position_1
	(x2,y2) = position_2

	x = scipy.linspace(x1, x2, num=num, dtype='int')
	y = scipy.linspace(y1, y2, num=num, dtype='int')

	# Move mouse.
	timeout = duration / len(x)
	for (x_, y_) in zip(x,y):
		mouse.position = add_noise_mouse((x_,y_), 5.0)
		time.sleep(timeout)

def click():
	mouse.press(Button.left)
	time.sleep(add_time_noise(0.05))
	mouse.release(Button.left)


"""1. Implement policy iteration. The stopping tolerance (defined as
maxs |Vold(s) − Vnew(s)|) is tol = 10−3. Use γ = 0.9. Return the optimal value function and
the optimal policy.
2. Implement value iteration in vi_and_pi.py. The stopping tolerance is tol = 10−3.
Use γ = 0.9. Return the optimal value function and the optimal policy.
"""
import gym
import random
import numpy as np

actions = {
    'Left': 0,
    'Down': 1,
    'Right': 2,
    'Up': 3}
IS_STOCHASTC=False

def main():
    tol=1e-3
    random_acts(IS_STOCHASTC)
    #value_iter(IS_STOCHASTC,tol)
    #policy_iter(IS_STOCHASTC,tol)

def value_iter(IS_STOCHASTC,tol):
    env = make_env(IS_STOCHASTC)
    env.reset()
    env.render()
    for i in range(10):
        new_state, reward, done, info = env.step()
        env.render()
        print("Reward: {:.2f}".format(reward))
        print(info)
        if done:
            break

def policy_iter(IS_STOCHASTC,tol):
    env = make_env(IS_STOCHASTC)
    env.reset()
    env.render()
    for i in range(5):
        new_state, reward, done, info = env.step()
        env.render()
        print("Reward: {:.2f}".format(reward))
        print(info)
        if done:
            break

def random_acts(IS_STOCHASTC):
    # To make some random acts
    env = make_env(IS_STOCHASTC)
    env.reset()
    env.render()
    """point: The 'prob' element is showing with how much probability the agent
    would select another action, in order to make your world deterministic use
    env = gym.make("FrozenLake-v0", is_slippery=False) instead.
    In order to make your custom map or use other maps add
    map_name='8x8'(or the custom one you've made) inside the parentheses """
    for iter in range(10):
        random_act=random.choice(list(actions.values()))
        new_state, reward, done, info = env.step(random_act)
        env.render()
        print("Reward: {:.2f}".format(reward))
        print(info)

def make_env(IS_STOCHASTC):
    if IS_STOCHASTC:
        env=gym.make("FrozenLake-v0")
    else:
        env=gym.make("FrozenLake-v0",is_slippery=False)
    return env

def isover(V,V_new,tol):
	if np.all(np.abs(V - V_new) < tol) :    #np.sum(np.sqrt(np.square(V_new-V))) < tol
		return 1
	return 0

if __name__ == '__main__':
    main()


# This is a guess the number game.
import random
print('Hello. What is your name?')
name = input()
secretNumber = random.randint(1, 20)
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
    print('Take a guess.')
    guess = int(input())
    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break  # This condition is the correct guess!
if guess == secretNumber:
    print('Good job, ' + name + '! You guessed my number in ' +
          str(guessesTaken) + ' guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))

# The break statement causes the execution to jump out of the loop without
# running the rest of the code in the loop. The continue statement causes the
# execution to jump back to the start of the loop, skipping the rest of the
# code inside the loop for the current iteration.
# The continue statement causes the program execution to immediately jump back
# to the start of the loop and reevaluate the loop’s condition. (This is also
# what happens when the execution reaches the end of the loop.) In essence, the
# continue statement says, “Go back to the start of the loop.”
# The break statement causes the program execution to immediately leave the
# loop, without reevaluating the loop’s condition. The program continues
# execution at the line after the loop’s end.
# The continue statement is useful when you want to skip over a loop iteration
# prematurely to go back to the start of the loop. The break statement is
# useful when you want to exit out of a loop prematurely if, for example, you
# have already found what you are looking for in a list.
# The continue statement and break statement are similar in a way, because
# they both disrupt the normal flow of execution by jumping to another part of
# your code. The difference between continue and break is that continue jumps


# programa que leia um ângulo e mostre o valor do seno, cosseno e tangente.
import math

angulo = float(input('Digite o valor de um ângulo: '))
print('O cosseno de {} é {:.2f}, o seno é {:.2f} e a tangente {:.2f}'.format(angulo,
                                                                             math.cos(math.radians(angulo)), math.sin(math.radians(angulo)),
                                                                             math.tan(math.radians(angulo))))

# não está dando certo... (antes da correção)
# deu certo no meio da correção, ao entender o math.radius() e onde ele deve ficar.

# correção do guanabara
# from math import sin, cos, tan, radians
# angulo = float('Digite o ângulo que você deseja: ')
# seno = sin(radians(angulo))
# cosseno = cos(radians(angulo))
# tangente = tan(radians(angulo))
# print('O ângulo de {} tem o seno de {:.2f}, cosseno de {:.2f} e
# tangente de {:.2f}'.format(angulo, seno, cosseno, tangente))


import os
import random
import string
import sqlite3
import signal
import sys

DB_FILE = "combinations.db"
conn = None  # Initialize the conn variable in the global scope

def create_database():
    global conn  # Use the global conn variable
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS combinations (combination TEXT PRIMARY KEY)''')
    conn.commit()

def get_existing_combinations():
    c = conn.cursor()
    c.execute('''SELECT combination FROM combinations''')
    existing_combinations = set([row[0] for row in c.fetchall()])
    return existing_combinations

def insert_combinations(combination_list):
    c = conn.cursor()
    c.executemany("INSERT INTO combinations (combination) VALUES (?)", [(c,) for c in combination_list])
    conn.commit()

def generate_combinations(chunk_size, existing_combinations):
    characters = "abcdef0123456789"
    dashes = [8, 13, 18, 23]

    while True:
        combinations = []
        while len(combinations) < chunk_size:
            combination = ''.join(random.choices(characters, k=32))
            for pos in dashes:
                combination = combination[:pos] + '-' + combination[pos:]

            if combination not in existing_combinations:
                combinations.append(combination)

        yield combinations

def signal_handler(sig, frame):
    print("\nStopping the script...")
    if conn is not None:
        conn.close()  # Close the database connection before exiting
    sys.exit(0)

def write_to_files(combinations_per_file, chunk_size, conn):  # Pass conn as an argument
    total_combinations_written = 0
    for combinations in generate_combinations(chunk_size, get_existing_combinations()):
        if not combinations:
            break

        filename = f"output_files/output_{total_combinations_written + 1}.txt"
        with open(filename, 'w') as file:
            for combination in combinations:
                file.write(combination + '\n')

        insert_combinations(combinations)
        total_combinations_written += len(combinations)

        print(f"Total combinations written: {total_combinations_written}")

    print("Script completed successfully.")

def append_to_log(combinations):
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.executemany("INSERT INTO combinations (combination) VALUES (?)", [(c,) for c in combinations])
    conn.commit()
    conn.close()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal_handler)  # Handle KeyboardInterrupt (Ctrl+C)

    create_database()
    existing_combinations = get_existing_combinations()

    combinations_per_file = 100000
    chunk_size = 100000

    total_combinations_written = 0
    file_number = 1

    for combinations_chunk in generate_combinations(chunk_size, existing_combinations):
        if not combinations_chunk:
            break

        combinations_written = 0
        filename = f"output_files/output_{file_number}.txt"
        with open(filename, 'w') as file:
            for combination in combinations_chunk:
                file.write(combination + '\n')
                combinations_written += 1

                if combinations_written >= combinations_per_file:
                    break

        total_combinations_written += combinations_written
        append_to_log(combinations_chunk[:combinations_written])

        print(f"Total combinations written: {total_combinations_written}")

        file_number += 1  # Increment the file_number for the next file

    print("Script completed successfully.")


import re
from datetime import datetime

def mapping_period(value, cat):

    if re.search(r"^(Fév\.|Mars |Avr\.|Mai |Juin |Jul\.|Août |Sep\.|Oct\.|Nov\.|Déc\.)@", value):
        if cat == "def":
            return "mois_an"
        else:
            if re.search(r"/", value):
                return "mois_an"
            else:
                return "mois_an_complet"

    elif re.search(r"^Jan\. à @", value) :
        if cat == "def":
            return 'cumul_an'
        else:
            if re.search(r"/", value):
                return "cumul_an"
            else:
                return "cumul_an_complet"

    elif re.search(r"à", value) :
        return "cumul_12_mois_an"

    elif re.search(r"Ann\.", value):
        return "an_moins_1"
    # Périodes trimestrielles
    elif re.search(r"^[1|2|3|4] Trim\.", value):
        return "trimX4_an"

    # Périodes semestrielles
    elif re.search(r"^[1|2] Sems\.", value):
        return "semX2_an"

    elif re.search(r"^Jan\.@", value):
        return "moisX12_an"

    else:
        return None

def are_consecutives_values(lst, val1="Jan.@", val2="Fév.@") :
    verif = False
    liste_index = []
    for i in range(len(lst) - 1):
        if val1 in lst[i] and val2 in lst[i+1]:
            verif = True
            liste_index.append(i)
    if verif:
        return True, liste_index
    else :
        return False, None

def fonction_date_arrete (date, periode_cat) :
    if periode_cat == "def" :
        date = datetime.strptime(date, '%Y-%m-%d')
        if date.month == 1 :
            return datetime(date.year - 1, 12, 1).strftime('%Y-%m-%d')
        else :
            return datetime(date.year, date.month - 1, 1).strftime('%Y-%m-%d')
    else :
        return date

def format_element(element):
    return element + ' ' * (5 - len(element))

def decompo_element(element) :
    if element.endswith("FR"):
        return ["FRANCE"]
    elif element.endswith("OM"):
        return ["DOM"]
    elif element.endswith("XXS"):
        return ["FRANCE", "DOM"]

def clean_string(s):
    # Remplace les sauts de ligne et les espaces consécutifs par un seul espace
    s = re.sub(r'\n+', ' ', s)
    return re.sub(r'\s+', ' ', s).strip()

def html_to_dict(soup):

    # The outer table contains rows that represent each variable.
    outer_table_rows = soup.select('table > tbody > tr')

    result = {}

    for row in outer_table_rows[1:]:

        is_colspan_here = False

        # Get all td elements in the current row
        tds = row.find_all('td')

        for td in tds:
            if td.has_attr('colspan') and td['colspan'] == "2":
                is_colspan_here = True
        # Extract the variable name, which is the content of the first <td> in each row.
        variable_name = row.td.text.strip()

        # The details for each variable are in a sub-table. We extract the rows of this sub-table.
        inner_table_rows = row.select('table > tbody > tr')

        details = []
        if is_colspan_here :
            for inner_row in inner_table_rows :
                libelle = inner_row.select_one('td:nth-of-type(1)').text.strip()
                valeur = inner_row.select_one('td:nth-of-type(2)').text.strip()

                # Split the "valeur" on "ET" to handle multiple conditions.
                # Clean up the string to remove unwanted characters like "\n" and then split them.
                conditions = [clean_string(cond) for cond in valeur.split(" ET ")]

                details.append({
                    'libelle': libelle,
                    'valeur': conditions
                })

            result[variable_name] = details

    return result

def consecutive_months_count(months_list):
    # Dictionnaire pour convertir le nom du mois en numéro
    month_to_num = {
        'Jan.': 1, 'Fév.': 2, 'Mars': 3, 'Avr.': 4,
        'Mai': 5, 'Juin': 6, 'Jul.': 7, 'Août': 8,
        'Sep.': 9, 'Oct.': 10, 'Nov.': 11, 'Déc.': 12
    }

    # Extraire les mois et les années
    months_and_years = []
    for item in months_list:
        match = re.search(r"(\w+\.?)\s?@\s?(\d{4})", item)
        if match:
            month = month_to_num.get(match.group(1), 0)
            year = int(match.group(2))
            months_and_years.append((month, year))

    # Compter les mois consécutifs pour la même année
    max_count = 0
    count = 1
    for i in range(1, len(months_and_years)):
        if months_and_years[i][1] == months_and_years[i-1][1] and months_and_years[i][0] == months_and_years[i-1][0] + 1:
            count += 1
            max_count = max(max_count, count)
        else:
            break

    return max_count

def consecutive_trim_count(trimesters_list):
        # Dictionnaire pour convertir le nom du mois en numéro
    trimester_to_num = {
        '1 Trim.': 1, '2 Trim.': 2, '3 Trim.': 3, '4 Trim.': 4
    }

    # Extraire les mois et les années
    trims_and_years = []
    for item in trimesters_list:
        match = re.search(r"(\d\s?Trim\.)\s?@\s?(\d{4})", item)
        if match:
            trim = trimester_to_num.get(match.group(1), 0)
            year = int(match.group(2))
            trims_and_years.append((trim, year))

    # Compter les mois consécutifs pour la même année
    max_count = 0
    count = 1
    for i in range(1, len(trims_and_years)):
        if trims_and_years[i][1] == trims_and_years[i-1][1] and trims_and_years[i][0] == trims_and_years[i-1][0] + 1:
            count += 1
            max_count = max(max_count, count)
        else:
            break

    return max_count

def consecutive_sems_count(trimesters_list):
        # Dictionnaire pour convertir le nom du mois en numéro
    semester_to_num = {
        '1 Sems.': 1, '2 Sems.': 2
    }

    # Extraire les mois et les années
    sems_and_years = []
    for item in trimesters_list:
        match = re.search(r"(\d\s?Sems\.)\s?@\s?(\d{4})", item)
        if match:
            sems = semester_to_num.get(match.group(1), 0)
            year = int(match.group(2))
            sems_and_years.append((sems, year))

    # Compter les mois consécutifs pour la même année
    max_count = 0
    count = 1
    for i in range(1, len(sems_and_years)):
        if sems_and_years[i][1] == sems_and_years[i-1][1] and sems_and_years[i][0] == sems_and_years[i-1][0] + 1:
            count += 1
            max_count = max(max_count, count)
        else:
            break

    return max_count

def transformation_filtre (filtre) :

    dict_operator={"<": "lt", ">": "gt", "<=": "le", ">=": "ge", "==": "eq", "!=": "ne"}
    result_filter = []

    for key, value in filtre.items() :
        operator = "in"
        if re.search(r"sauf", key) :
            operator = "not in"
            key = key.split('sauf')[0].strip()
        if len(value) == 1 :
            # Rechercher l'opérateur dans l'expression
            match = re.search(r"(<|>|<=|>=|==|!=)", value[0])
            if match:
                operator_init = match.group(0)  # Récupérer l'opérateur correspondant
                operator = dict_operator.get(operator_init, None)  # Traduire l'opérateur
                value = value[0].split(operator_init)[1].strip()  # Récupérer la clé
        filtre_operator = {"operator": operator, "value": value}
        result_filter.append({key: filtre_operator})
    return {"and": result_filter}

#Permet de convertir l'ancien type utilisé vers le nouveau format de regroupement (s'applique également aux renommages)
def format_regroupement(regroupement):
    formatted_regroup = {}
    for key, regroups in regroupement.items():

        formatted_data = []
        for group in regroups:

            new_group = {}
            # Vérifiez si l'une des valeurs contient "De"
            if any("De" in val for val in group["Valeurs"]):

                for val in group["Valeurs"]:
                    new_group = {}
                    # Récupération des limites de l'intervalle pour chaque valeur.
                    limits = [int(s) for s in val.split() if s.isdigit()]
                    new_group["nom"] = val
                    new_group["operator"] = "between"
                    new_group["valeur"] = limits
                    formatted_data.append(new_group)

            else:  # Sinon, c'est une liste de valeurs.
                new_group["nom"] = group["nom"]
                new_group["operator"] = "in"
                new_group["valeur"] = group["Valeurs"]
                formatted_data.append(new_group)
        formatted_regroup[key] = formatted_data
    return formatted_regroup

#Permet de faire correspondre le nom de la colonne dans le bordereau avec le nom de la colonne dans la table snowflake
mapping_bordereau_to_table_snowflake = {
    "DEPART": "CODE_DEPARTEMENT",
    "CARROSSERIE": "CARROSSERIE_SAS",
    "MARQUE_STT_VN": "ADMIN__MARQUE_STT_VN",
    "GENRE_MOT": "ADMIN__GENRE_MOT",
    "DEPARTEMENT": "NOM_DEPARTEMENT",
}


from animal import Animal

class Bird(Animal):

	# constructor
	def __init__(self, species, can_fly):
		super().__init__('bird', 'feathers')
		self._species = species
		self._can_fly = can_fly

	def __str__(self):
		if self._can_fly:
			not_str = ''
		else:
			not_str = 'not'
		return f'The {self._species} can{not_str} fly {super().__str__()}'


import math

import numpy as np

from tensorflow.python.debug.cli import command_parser
from tensorflow.python.debug.cli import debugger_cli_common
from tensorflow.python.debug.cli import tensor_format
from tensorflow.python.debug.lib import common
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor as tensor_lib
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile

RL = debugger_cli_common.RichLine

# Default threshold number of elements above which ellipses will be used
# when printing the value of the tensor.
DEFAULT_NDARRAY_DISPLAY_THRESHOLD = 2000

COLOR_BLACK = "black"
COLOR_BLUE = "blue"
COLOR_CYAN = "cyan"
COLOR_GRAY = "gray"
COLOR_GREEN = "green"
COLOR_MAGENTA = "magenta"
COLOR_RED = "red"
COLOR_WHITE = "white"
COLOR_YELLOW = "yellow"

TIME_UNIT_US = "us"
TIME_UNIT_MS = "ms"
TIME_UNIT_S = "s"
TIME_UNITS = [TIME_UNIT_US, TIME_UNIT_MS, TIME_UNIT_S]

def bytes_to_readable_str(num_bytes, include_b=False):
  """Generate a human-readable string representing number of bytes.

  The units B, kB, MB and GB are used.

  Args:
    num_bytes: (`int` or None) Number of bytes.
    include_b: (`bool`) Include the letter B at the end of the unit.

  Returns:
    (`str`) A string representing the number of bytes in a human-readable way,
      including a unit at the end.
  """

  if num_bytes is None:
    return str(num_bytes)
  if num_bytes < 1024:
    result = "%d" % num_bytes
  elif num_bytes < 1048576:
    result = "%.2fk" % (num_bytes / 1024.0)
  elif num_bytes < 1073741824:
    result = "%.2fM" % (num_bytes / 1048576.0)
  else:
    result = "%.2fG" % (num_bytes / 1073741824.0)

  if include_b:
    result += "B"
  return result

def time_to_readable_str(value_us, force_time_unit=None):
  """Convert time value to human-readable string.

  Args:
    value_us: time value in microseconds.
    force_time_unit: force the output to use the specified time unit. Must be
      in TIME_UNITS.

  Returns:
    Human-readable string representation of the time value.

  Raises:
    ValueError: if force_time_unit value is not in TIME_UNITS.
  """
  if not value_us:
    return "0"
  if force_time_unit:
    if force_time_unit not in TIME_UNITS:
      raise ValueError("Invalid time unit: %s" % force_time_unit)
    order = TIME_UNITS.index(force_time_unit)
    time_unit = force_time_unit
    return "{:.10g}{}".format(value_us / math.pow(10.0, 3*order), time_unit)
  else:
    order = min(len(TIME_UNITS) - 1, int(math.log(value_us, 10) / 3))
    time_unit = TIME_UNITS[order]
    return "{:.3g}{}".format(value_us / math.pow(10.0, 3*order), time_unit)

def parse_ranges_highlight(ranges_string):
  """Process ranges highlight string.

  Args:
    ranges_string: (str) A string representing a numerical range of a list of
      numerical ranges. See the help info of the -r flag of the print_tensor
      command for more details.

  Returns:
    An instance of tensor_format.HighlightOptions, if range_string is a valid
      representation of a range or a list of ranges.
  """

  ranges = None

  def ranges_filter(x):
    r = np.zeros(x.shape, dtype=bool)
    for range_start, range_end in ranges:
      r = np.logical_or(r, np.logical_and(x >= range_start, x <= range_end))

    return r

  if ranges_string:
    ranges = command_parser.parse_ranges(ranges_string)
    return tensor_format.HighlightOptions(
        ranges_filter, description=ranges_string)
  else:
    return None

def numpy_printoptions_from_screen_info(screen_info):
  if screen_info and "cols" in screen_info:
    return {"linewidth": screen_info["cols"]}
  else:
    return {}

def format_tensor(tensor,
                  tensor_name,
                  np_printoptions,
                  print_all=False,
                  tensor_slicing=None,
                  highlight_options=None,
                  include_numeric_summary=False,
                  write_path=None):
  """Generate formatted str to represent a tensor or its slices.

  Args:
    tensor: (numpy ndarray) The tensor value.
    tensor_name: (str) Name of the tensor, e.g., the tensor's debug watch key.
    np_printoptions: (dict) Numpy tensor formatting options.
    print_all: (bool) Whether the tensor is to be displayed in its entirety,
      instead of printing ellipses, even if its number of elements exceeds
      the default numpy display threshold.
      (Note: Even if this is set to true, the screen output can still be cut
       off by the UI frontend if it consist of more lines than the frontend
       can handle.)
    tensor_slicing: (str or None) Slicing of the tensor, e.g., "[:, 1]". If
      None, no slicing will be performed on the tensor.
    highlight_options: (tensor_format.HighlightOptions) options to highlight
      elements of the tensor. See the doc of tensor_format.format_tensor()
      for more details.
    include_numeric_summary: Whether a text summary of the numeric values (if
      applicable) will be included.
    write_path: A path to save the tensor value (after any slicing) to
      (optional). `numpy.save()` is used to save the value.

  Returns:
    An instance of `debugger_cli_common.RichTextLines` representing the
    (potentially sliced) tensor.
  """

  if tensor_slicing:
    # Validate the indexing.
    value = command_parser.evaluate_tensor_slice(tensor, tensor_slicing)
    sliced_name = tensor_name + tensor_slicing
  else:
    value = tensor
    sliced_name = tensor_name

  auxiliary_message = None
  if write_path:
    with gfile.Open(write_path, "wb") as output_file:
      np.save(output_file, value)
    line = debugger_cli_common.RichLine("Saved value to: ")
    line += debugger_cli_common.RichLine(write_path, font_attr="bold")
    line += " (%sB)" % bytes_to_readable_str(gfile.Stat(write_path).length)
    auxiliary_message = debugger_cli_common.rich_text_lines_from_rich_line_list(
        [line, debugger_cli_common.RichLine("")])

  if print_all:
    np_printoptions["threshold"] = value.size
  else:
    np_printoptions["threshold"] = DEFAULT_NDARRAY_DISPLAY_THRESHOLD

  return tensor_format.format_tensor(
      value,
      sliced_name,
      include_metadata=True,
      include_numeric_summary=include_numeric_summary,
      auxiliary_message=auxiliary_message,
      np_printoptions=np_printoptions,
      highlight_options=highlight_options)

def error(msg):
  """Generate a RichTextLines output for error.

  Args:
    msg: (str) The error message.

  Returns:
    (debugger_cli_common.RichTextLines) A representation of the error message
      for screen output.
  """

  return debugger_cli_common.rich_text_lines_from_rich_line_list([
      RL("ERROR: " + msg, COLOR_RED)])

def _recommend_command(command, description, indent=2, create_link=False):
  """Generate a RichTextLines object that describes a recommended command.

  Args:
    command: (str) The command to recommend.
    description: (str) A description of what the command does.
    indent: (int) How many spaces to indent in the beginning.
    create_link: (bool) Whether a command link is to be applied to the command
      string.

  Returns:
    (RichTextLines) Formatted text (with font attributes) for recommending the
      command.
  """

  indent_str = " " * indent

  if create_link:
    font_attr = [debugger_cli_common.MenuItem("", command), "bold"]
  else:
    font_attr = "bold"

  lines = [RL(indent_str) + RL(command, font_attr) + ":",
           indent_str + "  " + description]

  return debugger_cli_common.rich_text_lines_from_rich_line_list(lines)

def get_tfdbg_logo():
  """Make an ASCII representation of the tfdbg logo."""

  lines = [
      "",
      "TTTTTT FFFF DDD  BBBB   GGG ",
      "  TT   F    D  D B   B G    ",
      "  TT   FFF  D  D BBBB  G  GG",
      "  TT   F    D  D B   B G   G",
      "  TT   F    DDD  BBBB   GGG ",
      "",
  ]
  return debugger_cli_common.RichTextLines(lines)

_HORIZONTAL_BAR = "======================================"

def get_run_start_intro(run_call_count,
                        fetches,
                        feed_dict,
                        tensor_filters,
                        is_callable_runner=False):
  """Generate formatted intro for run-start UI.

  Args:
    run_call_count: (int) Run call counter.
    fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
      for more details.
    feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
      for more details.
    tensor_filters: (dict) A dict from tensor-filter name to tensor-filter
      callable.
    is_callable_runner: (bool) whether a runner returned by
        Session.make_callable is being run.

  Returns:
    (RichTextLines) Formatted intro message about the `Session.run()` call.
  """

  fetch_lines = common.get_flattened_names(fetches)

  if not feed_dict:
    feed_dict_lines = [debugger_cli_common.RichLine("  (Empty)")]
  else:
    feed_dict_lines = []
    for feed_key in feed_dict:
      feed_key_name = common.get_graph_element_name(feed_key)
      feed_dict_line = debugger_cli_common.RichLine("  ")
      feed_dict_line += debugger_cli_common.RichLine(
          feed_key_name,
          debugger_cli_common.MenuItem(None, "pf '%s'" % feed_key_name))
      # Surround the name string with quotes, because feed_key_name may contain
      # spaces in some cases, e.g., SparseTensors.
      feed_dict_lines.append(feed_dict_line)
  feed_dict_lines = debugger_cli_common.rich_text_lines_from_rich_line_list(
      feed_dict_lines)

  out = debugger_cli_common.RichTextLines(_HORIZONTAL_BAR)
  if is_callable_runner:
    out.append("Running a runner returned by Session.make_callable()")
  else:
    out.append("Session.run() call #%d:" % run_call_count)
    out.append("")
    out.append("Fetch(es):")
    out.extend(debugger_cli_common.RichTextLines(
        ["  " + line for line in fetch_lines]))
    out.append("")
    out.append("Feed dict:")
    out.extend(feed_dict_lines)
  out.append(_HORIZONTAL_BAR)
  out.append("")
  out.append("Select one of the following commands to proceed ---->")

  out.extend(
      _recommend_command(
          "run",
          "Execute the run() call with debug tensor-watching",
          create_link=True))
  out.extend(
      _recommend_command(
          "run -n",
          "Execute the run() call without debug tensor-watching",
          create_link=True))
  out.extend(
      _recommend_command(
          "run -t <T>",
          "Execute run() calls (T - 1) times without debugging, then "
          "execute run() once more with debugging and drop back to the CLI"))
  out.extend(
      _recommend_command(
          "run -f <filter_name>",
          "Keep executing run() calls until a dumped tensor passes a given, "
          "registered filter (conditional breakpoint mode)"))

  more_lines = ["    Registered filter(s):"]
  if tensor_filters:
    filter_names = []
    for filter_name in tensor_filters:
      filter_names.append(filter_name)
      command_menu_node = debugger_cli_common.MenuItem(
          "", "run -f %s" % filter_name)
      more_lines.append(RL("        * ") + RL(filter_name, command_menu_node))
  else:
    more_lines.append("        (None)")

  out.extend(
      debugger_cli_common.rich_text_lines_from_rich_line_list(more_lines))

  out.append("")

  out.append_rich_line(RL("For more details, see ") +
                       RL("help.", debugger_cli_common.MenuItem("", "help")) +
                       ".")
  out.append("")

  # Make main menu for the run-start intro.
  menu = debugger_cli_common.Menu()
  menu.append(debugger_cli_common.MenuItem("run", "run"))
  menu.append(debugger_cli_common.MenuItem("exit", "exit"))
  out.annotations[debugger_cli_common.MAIN_MENU_KEY] = menu

  return out

def get_run_short_description(run_call_count,
                              fetches,
                              feed_dict,
                              is_callable_runner=False):
  """Get a short description of the run() call.

  Args:
    run_call_count: (int) Run call counter.
    fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
      for more details.
    feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
      for more details.
    is_callable_runner: (bool) whether a runner returned by
        Session.make_callable is being run.

  Returns:
    (str) A short description of the run() call, including information about
      the fetche(s) and feed(s).
  """
  if is_callable_runner:
    return "runner from make_callable()"

  description = "run #%d: " % run_call_count

  if isinstance(
      fetches, (tensor_lib.Tensor, ops.Operation, variables.Variable)
  ):
    description += "1 fetch (%s); " % common.get_graph_element_name(fetches)
  else:
    # Could be (nested) list, tuple, dict or namedtuple.
    num_fetches = len(common.get_flattened_names(fetches))
    if num_fetches > 1:
      description += "%d fetches; " % num_fetches
    else:
      description += "%d fetch; " % num_fetches

  if not feed_dict:
    description += "0 feeds"
  else:
    if len(feed_dict) == 1:
      for key in feed_dict:
        description += "1 feed (%s)" % (
            key
            if isinstance(key, str) or not hasattr(key, "name") else key.name)
    else:
      description += "%d feeds" % len(feed_dict)

  return description

def get_error_intro(tf_error):
  """Generate formatted intro for TensorFlow run-time error.

  Args:
    tf_error: (errors.OpError) TensorFlow run-time error object.

  Returns:
    (RichTextLines) Formatted intro message about the run-time OpError, with
      sample commands for debugging.
  """

  if hasattr(tf_error, "op") and hasattr(tf_error.op, "name"):
    op_name = tf_error.op.name
  else:
    op_name = None

  intro_lines = [
      "--------------------------------------",
      RL("!!! An error occurred during the run !!!", "blink"),
      "",
  ]

  out = debugger_cli_common.rich_text_lines_from_rich_line_list(intro_lines)

  if op_name is not None:
    out.extend(debugger_cli_common.RichTextLines(
        ["You may use the following commands to debug:"]))
    out.extend(
        _recommend_command("ni -a -d -t %s" % op_name,
                           "Inspect information about the failing op.",
                           create_link=True))
    out.extend(
        _recommend_command("li -r %s" % op_name,
                           "List inputs to the failing op, recursively.",
                           create_link=True))

    out.extend(
        _recommend_command(
            "lt",
            "List all tensors dumped during the failing run() call.",
            create_link=True))
  else:
    out.extend(debugger_cli_common.RichTextLines([
        "WARNING: Cannot determine the name of the op that caused the error."]))

  more_lines = [
      "",
      "Op name:    %s" % op_name,
      "Error type: " + str(type(tf_error)),
      "",
      "Details:",
      str(tf_error),
      "",
      "--------------------------------------",
      "",
  ]

  out.extend(debugger_cli_common.RichTextLines(more_lines))

  return out


# Two forms of Scraping Twitter: Tweepy vs SNScrape
#
# # https://www.freecodecamp.org/news/python-web-scraping-tutorial/
# Jon Chun
# 21 Oct 2022

import time
import pandas as pd
import tweepy
import config_twitter

consumer_key = config_twitter.API_KEY #Your API/Consumer key
consumer_secret = config_twitter.API_KEY_SECRET #Your API/Consumer Secret Key
access_token = config_twitter.ACCESS_TOKEN    #Your Access token key
access_token_secret = config_twitter.ACCESS_TOKEN_SECRET #Your Access token Secret key

#Pass in our twitter API authentication key
auth = tweepy.OAuth1UserHandler(
    consumer_key, consumer_secret,
    access_token, access_token_secret
)

#Instantiate the tweepy API
api = tweepy.API(auth, wait_on_rate_limit=True)

username = "elonmusk"
no_of_tweets = 10

try:
    #The number of tweets we want to retrieved from the user
    tweets = api.user_timeline(screen_name=username, count=no_of_tweets)

    #Pulling Some attributes from the tweet
    attributes_container = [[tweet.created_at, tweet.favorite_count,tweet.source,  tweet.text] for tweet in tweets]

    #Creation of column list to rename the columns in the dataframe
    columns = ["Date Created", "Number of Likes", "Source of Tweet", "Tweet"]

    #Creation of Dataframe
    tweets_df = pd.DataFrame(attributes_container, columns=columns)
except BaseException as e:
    print('Status Failed On,',str(e))
    time.sleep(3)

    tweets_df.to_csv('tweets_10_elonmusk_20221021_1300.csv')


import cv2 as cv
import numpy as np
import time
import tensorflow as tf
import os
from tensorflow import keras
import tensorflow
from tensorflow.keras.preprocessing import image
from mtcnn import MTCNN
from sklearn.neighbors import KNeighborsClassifier

from keras.preprocessing import image
from keras_vggface.vggface import VGGFace
from keras_vggface import utils

physical_devices = tf.config.list_physical_devices("GPU")
tf.config.experimental.set_memory_growth(physical_devices[0], True)

lable = ['unmasked','masked']
names = ['Aon','Most','First']
def togray(frame):
    return cv.cvtColor(frame,cv.COLOR_BGR2GRAY)

def process_img(frame):
    result = cv.resize(frame,(224,224))
    result = result.astype('float64')
    result = np.expand_dims(result,axis=0)
    result = utils.preprocess_input(result,version=2)
    return result

class setupmodel:
    def __init__(self,path,facedetect,model):
        self.Fcount = 0
        self.data  = []
        self.label = []
        self.Fname = "Data"
        for base, dirs, files in os.walk(path):
            for Files in files:
                self.Fcount += 1
        Lcount = 0;
        Mlabel = 0;
        for i in range(1,self.Fcount+1):
            img_name = path+"/"+self.Fname+str(i)+".jpg"
            img = cv.imread(img_name)
            result = facedetect.detect_faces(img)
            for j in result:
                confi = j['confidence']
                if confi > 0.95:
                    box = j['box']
                    x, y, w, h = box[0], box[1], box[2], box[3]
                    face = img[y:y+h,x:x+w]
                    data = model.predict(process_img(face))
                    dshape = data.shape
                    data = np.reshape(data,(dshape[1]*dshape[2]*dshape[3]))
                    self.data.append(data)
            Lcount += 1
            self.label.append(Mlabel)
            if(Lcount % 3 == 0):
                Mlabel+=1

        self.model = KNeighborsClassifier(n_neighbors=1)
        self.model.fit(self.data,self.label)
    def __call__(self,frame,model):
        data = model.predict(process_img(frame=frame))
        dshape = data.shape
        data = np.reshape(data,(dshape[1]*dshape[2]*dshape[3]))
        data = np.expand_dims(data,axis=0)
        return self.model.predict(data)

class facedetect:
    def __init__(self):
        self.model = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_alt2.xml')
    def __call__(self,frame):
        gray = togray(frame = frame)
        return (self.model.detectMultiScale(
        gray,
        scaleFactor = 1.3,
        minNeighbors = 5,
        flags=cv.CASCADE_SCALE_IMAGE))

class maskrec:
    def __init__(self):
        self.model = tf.keras.models.load_model('saved_model/my_model')
    def __call__(self,frame):
        # G_frame = togray(frame=frame)
        G_frame = frame
        G_frame = cv.resize(G_frame, (128,128))
        G_frame = G_frame/255.0
        # G_frame = G_frame.reshape(G_frame.shape[0],G_frame.shape[1],1)
        G_frame = np.expand_dims(G_frame,axis=0)
        result = self.model.predict(G_frame)
        if result[0][0] >= 0.99 :
            return 1
        else:
            return 0

facedetect1 = facedetect()
facedetect2 = MTCNN()
maskrec1 = maskrec()
model = VGGFace(model='resnet50',include_top=False)
model1 = setupmodel(path="D:/ML/Facerect/Data1",facedetect=facedetect2,model=model)

cap = cv.VideoCapture(0)
pTime = 0
Fcount = 0
CFrame = 1
while True:
    sccess, frame = cap.read()
    result = facedetect1(frame)
    if (len(result) >0):
        for i in result:
            x,y,w,h = i
            face = frame[y:y+h,x:x+w]
            mask = maskrec1(face)
            if mask == 1:
                cv.rectangle(frame,(x,y),(x+w,y+h),(0,155,255),2)
                cv.putText(frame, f'{lable[mask]}',(x,y-40),cv.FONT_HERSHEY_PLAIN,3,(0,255,0),2)
            else:
                name = model1(frame=face,model = model)
                cv.rectangle(frame,(x,y),(x+w,y+h),(0,155,255),2)
                cv.putText(frame, f'{lable[mask]}',(x,y-40),cv.FONT_HERSHEY_PLAIN,3,(0,255,0),2)
                cv.putText(frame, f'{names[name[0]]}',(x,y-10),cv.FONT_HERSHEY_PLAIN,3,(0,255,0),2)

    cTime = time.time()
    fps = 1/(cTime - pTime)
    pTime = cTime
    cv.putText(frame, f'Fps: {int(fps)}',(20,70),cv.FONT_HERSHEY_PLAIN,
                3,(0,255,0),2)
    cv.imshow('Python Window', frame)
    Fcount+=1
    if cv.waitKey(10) & 0xFF == ord('q'):
        cv.destroyAllWindows()
        break


import collections
import gc
import os
from typing import List, Optional, Union, Tuple, Dict, Any

import albumentations
import numpy as np
import pandas as pd
import torch
from hydra.utils import instantiate
from pytorch_toolbelt.inference import (
    ApplySigmoidTo,
    ApplySoftmaxTo,
    Ensembler,
    GeneralizedTTA,
    MultiscaleTTA,
    d2_image_augment,
    d4_image_augment,
    d4_image_deaugment,
    d2_image_deaugment,
    flips_image_deaugment,
    flips_image_augment,
    fliplr_image_augment,
    fliplr_image_deaugment,
)
from pytorch_toolbelt.utils import to_numpy, fs
from torch import nn
from torch.utils.data import DistributedSampler
from tqdm import tqdm
from pytorch_toolbelt.utils.distributed import is_main_process, get_rank, get_world_size, all_gather

from xview3.centernet.bboxer import (
    MultilabelCircleNetDecodeResult,
    MultilabelCircleNetCoder,
)
from xview3.centernet.constants import (
    CENTERNET_OUTPUT_SIZE,
    CENTERNET_OUTPUT_OFFSET,
    CENTERNET_OUTPUT_OBJECTNESS_MAP,
    CENTERNET_OUTPUT_VESSEL_MAP,
    CENTERNET_OUTPUT_FISHING_MAP,
)
from xview3.centernet.models.inference import (
    multilabel_centernet_tiled_inference,
    get_box_coder_from_model,
)
from xview3.dataset import (
    XView3DataModule,
    read_multichannel_image,
    stack_multichannel_image,
)

__all__ = [
    "average_checkpoints",
    "ensemble_from_checkpoints",
    "model_from_checkpoint",
    "ensemble_from_config",
    "wrap_multilabel_model_with_tta",
    "maybe_run_inference",
]

def average_checkpoints(inputs):
    """Loads checkpoints from inputs and returns a model with averaged weights. Original implementation taken from:
    https://github.com/pytorch/fairseq/blob/a48f235636557b8d3bc4922a6fa90f3a0fa57955/scripts/average_checkpoints.py#L16
    Args:
      inputs (List[str]): An iterable of string paths of checkpoints to load from.
    Returns:
      A dict of string keys mapping to various values. The 'model' key
      from the returned dict should correspond to an OrderedDict mapping
      string parameter names to torch Tensors.
    """
    params_dict = collections.OrderedDict()
    params_keys = None
    new_state = None
    num_models = len(inputs)
    for fpath in inputs:
        with open(fpath, "rb") as f:
            state = torch.load(
                f,
                map_location="cpu",
            )
        # Copies over the settings from the first checkpoint
        if new_state is None:
            new_state = state
        model_params = state["model_state_dict"]
        model_params_keys = list(model_params.keys())
        if params_keys is None:
            params_keys = model_params_keys
        elif params_keys != model_params_keys:
            raise KeyError("For checkpoint {}, expected list of params: {}, " "but found: {}".format(f, params_keys, model_params_keys))
        for k in params_keys:
            p = model_params[k]
            if isinstance(p, torch.HalfTensor):
                p = p.float()
            if k not in params_dict:
                params_dict[k] = p.clone()
                # NOTE: clone() is needed in case of p is a shared parameter
            else:
                params_dict[k] += p
    averaged_params = collections.OrderedDict()
    for k, v in params_dict.items():
        averaged_params[k] = v
        if averaged_params[k].is_floating_point():
            averaged_params[k].div_(num_models)
        else:
            averaged_params[k] //= num_models
    new_state["model_state_dict"] = averaged_params
    return new_state

def model_from_checkpoint(checkpoint_config: Union[str, Dict], **kwargs) -> Tuple[nn.Module, Dict]:
    if isinstance(checkpoint_config, collections.Mapping):
        if "average_checkpoints" in checkpoint_config:
            checkpoint = average_checkpoints(checkpoint_config["average_checkpoints"])
        else:
            checkpoint_name = checkpoint_config["checkpoint"]
            if os.path.isfile(checkpoint_name):
                checkpoint = torch.load(checkpoint_name, map_location="cpu")
            else:
                checkpoint = torch.hub.load_state_dict_from_url(checkpoint_name)

        model_config = checkpoint["checkpoint_data"]["config"]["model"]
    else:
        checkpoint_name = checkpoint_config

        if os.path.isfile(checkpoint_name):
            checkpoint = torch.load(checkpoint_name, map_location="cpu")
        else:
            checkpoint = torch.hub.load_state_dict_from_url(checkpoint_name)

        model_config = checkpoint["checkpoint_data"]["config"]["model"]

    model_state_dict = checkpoint["model_state_dict"]

    model = instantiate(model_config, _recursive_=False)
    model.load_state_dict(model_state_dict, strict=False)

    return model.eval(), checkpoint

def wrap_multilabel_model_with_tta(model, tta_mode, with_offset=True, size_offsets=(0, -32, -64, +32, +64)):
    from xview3.centernet import (
        CENTERNET_OUTPUT_VESSEL_MAP,
        CENTERNET_OUTPUT_FISHING_MAP,
        CENTERNET_OUTPUT_OBJECTNESS_MAP,
        CENTERNET_OUTPUT_OFFSET,
        CENTERNET_OUTPUT_SIZE,
    )

    keys_to_deaug = [
        CENTERNET_OUTPUT_VESSEL_MAP,
        CENTERNET_OUTPUT_FISHING_MAP,
        CENTERNET_OUTPUT_OBJECTNESS_MAP,
        CENTERNET_OUTPUT_SIZE,
    ]
    if with_offset:
        keys_to_deaug.append(CENTERNET_OUTPUT_OFFSET)

    def _make_deaug_dict(keys, fn):
        return dict((key, fn) for key in keys)

    if tta_mode == "d4":
        return GeneralizedTTA(model, augment_fn=d4_image_augment, deaugment_fn=_make_deaug_dict(keys_to_deaug, d4_image_deaugment))
    elif tta_mode == "ms":
        return MultiscaleTTA(model, size_offsets)
    elif tta_mode == "d2-ms":
        return MultiscaleTTA(GeneralizedTTA(model, d2_image_augment, d2_image_deaugment), size_offsets)
    elif tta_mode == "d2":
        model = GeneralizedTTA(model, d2_image_augment, deaugment_fn=_make_deaug_dict(keys_to_deaug, d2_image_deaugment))
    elif tta_mode == "flips":
        model = GeneralizedTTA(model, flips_image_augment, deaugment_fn=_make_deaug_dict(keys_to_deaug, flips_image_deaugment))
    elif tta_mode == "fliplr":
        model = GeneralizedTTA(model, fliplr_image_augment, deaugment_fn=_make_deaug_dict(keys_to_deaug, fliplr_image_deaugment))
    elif tta_mode is None:
        return model
    else:
        raise KeyError("Unusupported TTA mode '" + tta_mode + "'")

    return model

def ensemble_from_checkpoints(
    checkpoint_fnames: List[str],
    strict=True,
    sigmoid_outputs=None,
    softmax_outputs=None,
    activation: str = "after_model",
    tta: Optional[str] = None,
    with_offset=True,
):
    if activation not in {None, "None", "after_model", "after_tta", "after_ensemble"}:
        raise KeyError(activation)

    models = []
    checkpoints = []

    for ck in checkpoint_fnames:
        model, checkpoint = model_from_checkpoint(ck, strict=strict)
        models.append(model)
        checkpoints.append(checkpoint)

    if activation == "after_model":
        if sigmoid_outputs is not None:
            models = [ApplySigmoidTo(m, output_key=sigmoid_outputs) for m in models]
            print("Applying sigmoid activation to", sigmoid_outputs, "after each model", len(models))

        if softmax_outputs is not None:
            models = [ApplySoftmaxTo(m, output_key=softmax_outputs) for m in models]
            print("Applying softmax activation to", softmax_outputs, "after each model", len(models))

    if len(models) > 1:
        model = Ensembler(models)
        if activation == "after_ensemble":
            if sigmoid_outputs is not None:
                model = ApplySigmoidTo(model, output_key=sigmoid_outputs)
                print("Applying sigmoid activation to", sigmoid_outputs, "after ensemble")

            if softmax_outputs is not None:
                model = ApplySoftmaxTo(model, output_key=softmax_outputs)
                print("Applying softmax activation to", softmax_outputs, "after ensemble")

    else:
        assert len(models) == 1
        model = models[0]

    if tta not in {None, "None"}:
        model = wrap_multilabel_model_with_tta(model, tta, with_offset=with_offset)
        print("Wrapping models with TTA", tta)

    if activation == "after_tta":
        if sigmoid_outputs is not None:
            model = ApplySigmoidTo(model, output_key=sigmoid_outputs)
            print("Applying sigmoid activation to ", sigmoid_outputs, " after TTA")
        if softmax_outputs is not None:
            model = ApplySoftmaxTo(model, output_key=softmax_outputs)
            print("Applying softmax activation to", softmax_outputs, "after TTA")

    return model.eval(), checkpoints

def ensemble_from_config(config: Dict[str, Any]):
    model, checkpoints = ensemble_from_checkpoints(
        checkpoint_fnames=config["ensemble"]["models"],
        strict=True,
        activation=config["ensemble"]["activation_after"],
        tta=config["ensemble"]["tta"],
        sigmoid_outputs=config["ensemble"]["sigmoid_outputs"],
        softmax_outputs=config["ensemble"]["softmax_outputs"],
        with_offset=config["ensemble"]["with_offset"],
    )
    box_coder = get_box_coder_from_model(model)
    model = model.eval().cuda()
    return model, checkpoints, box_coder

@torch.jit.optimized_execution(False)
def predict_multilabel_scenes(
    model,
    box_coder: MultilabelCircleNetCoder,
    scenes: List[str],
    channels: List[str],
    tile_step: int,
    tile_size: int,
    objectness_thresholds_lower_bound: float,
    normalization: Dict[str, albumentations.ImageOnlyTransform],
    accumulate_on_gpu: bool,
    fp16: bool,
    batch_size: int,
    apply_activation: bool,
    save_raw_predictions: bool,
    max_objects: int,
    channels_last: bool,
    output_predictions_dir=None,
) -> pd.DataFrame:
    if output_predictions_dir is not None:
        os.makedirs(output_predictions_dir, exist_ok=True)

    all_predictions = []

    scenes = np.array(scenes)
    world_size, local_rank = get_world_size(), get_rank()

    if world_size > 1:
        sampler = DistributedSampler(scenes, world_size, local_rank, shuffle=False)
        rank_local_indexes = np.array(list(iter(sampler)))
        scenes = scenes[rank_local_indexes]
        print("Node", local_rank, "got", len(scenes), "to process")
        torch.distributed.barrier()

    for scene in tqdm(scenes, desc=f"Inference at Node {local_rank}/{world_size}", position=local_rank):
        gc.collect()
        scene_id = fs.id_from_fname(scene)
        predictions = maybe_run_inference(
            model=model,
            box_coder=box_coder,
            scene=scene,
            output_predictions_dir=output_predictions_dir,
            accumulate_on_gpu=accumulate_on_gpu,
            tile_size=tile_size,
            tile_step=tile_step,
            fp16=fp16,
            batch_size=batch_size,
            save_raw_predictions=save_raw_predictions,
            apply_activation=apply_activation,
            max_objects=max_objects,
            channels_last=channels_last,
            normalization=normalization,
            channels=channels,
            objectness_thresholds_lower_bound=objectness_thresholds_lower_bound,
        )

        all_predictions.append(predictions)
        if output_predictions_dir is not None:
            predictions.to_csv(os.path.join(output_predictions_dir, scene_id + ".csv"), index=False)

    all_predictions = pd.concat(all_predictions).reset_index(drop=True)

    if world_size > 1:
        torch.distributed.barrier()
        all_predictions = pd.concat(all_gather(all_predictions)).reset_index(drop=True)

    return all_predictions

def maybe_run_inference(
    model,
    box_coder,
    scene,
    output_predictions_dir,
    channels,
    normalization,
    objectness_thresholds_lower_bound: float,
    tile_size,
    tile_step,
    accumulate_on_gpu,
    fp16,
    batch_size,
    save_raw_predictions,
    apply_activation,
    max_objects,
    channels_last,
):
    scene_id = fs.id_from_fname(scene)
    predictions_computed_offline = False

    if output_predictions_dir is not None:
        raw_predictions_file = os.path.join(output_predictions_dir, scene_id + ".npz")
        decoded_predictions_file = os.path.join(output_predictions_dir, scene_id + ".csv")

        if os.path.isfile(decoded_predictions_file):
            try:
                predictions = pd.read_csv(decoded_predictions_file)
                return predictions
            except Exception as e:
                print(e)
                predictions_computed_offline = False
        elif os.path.isfile(raw_predictions_file):
            try:
                saved_predictions = np.load(raw_predictions_file, allow_pickle=True)
                outputs = dict(
                    CENTERNET_OUTPUT_OBJECTNESS_MAP=torch.from_numpy(saved_predictions[CENTERNET_OUTPUT_OBJECTNESS_MAP]),
                    CENTERNET_OUTPUT_VESSEL_MAP=torch.from_numpy(saved_predictions[CENTERNET_OUTPUT_VESSEL_MAP]),
                    CENTERNET_OUTPUT_FISHING_MAP=torch.from_numpy(saved_predictions[CENTERNET_OUTPUT_FISHING_MAP]),
                    CENTERNET_OUTPUT_SIZE=torch.from_numpy(saved_predictions[CENTERNET_OUTPUT_SIZE]),
                    CENTERNET_OUTPUT_OFFSET=torch.from_numpy(saved_predictions[CENTERNET_OUTPUT_OFFSET])
                    if CENTERNET_OUTPUT_OFFSET in saved_predictions
                    else None,
                )
                predictions_computed_offline = True
            except Exception as e:
                print(e)
                predictions_computed_offline = False

    if not predictions_computed_offline:
        image = read_multichannel_image(scene, channels)
        for channel_name in set(channels):
            image[channel_name] = normalization[channel_name](image=image[channel_name])["image"]
        image = stack_multichannel_image(image, channels)

        outputs = multilabel_centernet_tiled_inference(
            model,
            image,
            box_coder=box_coder,
            tile_size=tile_size,
            tile_step=tile_step,
            accumulate_on_gpu=accumulate_on_gpu,
            fp16=fp16,
            batch_size=batch_size,
            channels_last=channels_last,
        )

        if save_raw_predictions and output_predictions_dir is not None:
            raw_predictions_file = os.path.join(output_predictions_dir, scene_id + ".npz")
            predictions_dict = dict(
                CENTERNET_OUTPUT_OBJECTNESS_MAP=to_numpy(outputs[CENTERNET_OUTPUT_OBJECTNESS_MAP]),
                CENTERNET_OUTPUT_VESSEL_MAP=to_numpy(outputs[CENTERNET_OUTPUT_VESSEL_MAP]),
                CENTERNET_OUTPUT_FISHING_MAP=to_numpy(outputs[CENTERNET_OUTPUT_FISHING_MAP]),
                CENTERNET_OUTPUT_SIZE=to_numpy(outputs[CENTERNET_OUTPUT_SIZE]),
            )
            if CENTERNET_OUTPUT_OFFSET in outputs:
                predictions_dict[CENTERNET_OUTPUT_OFFSET] = to_numpy(outputs[CENTERNET_OUTPUT_OFFSET])
            np.savez(raw_predictions_file, **predictions_dict)

    preds: MultilabelCircleNetDecodeResult = box_coder.decode(
        objectness_map=outputs[CENTERNET_OUTPUT_OBJECTNESS_MAP],
        is_vessel_map=outputs[CENTERNET_OUTPUT_VESSEL_MAP],
        is_fishing_map=outputs[CENTERNET_OUTPUT_FISHING_MAP],
        length_map=outputs[CENTERNET_OUTPUT_SIZE],
        offset_map=outputs.get(CENTERNET_OUTPUT_OFFSET, None),
        apply_activation=apply_activation,
        max_objects=max_objects,
    )

    pos_mask = preds.scores[0] >= objectness_thresholds_lower_bound

    centers = to_numpy(preds.centers[0][pos_mask]).astype(int)
    scores = to_numpy(preds.scores[0, pos_mask]).astype(np.float32)
    lengths = XView3DataModule.decode_lengths(preds.lengths[0, pos_mask])

    is_vessel_prob = to_numpy(preds.is_vessel[0, pos_mask]).astype(np.float32)
    is_fishing_prob = to_numpy(preds.is_fishing[0, pos_mask]).astype(np.float32)

    predictions = collections.defaultdict(list)
    for (
        (detect_scene_column, detect_scene_row),
        objectness_score,
        is_vessel_p,
        is_fishing_p,
        vessel_length_m,
    ) in zip(centers, scores, is_vessel_prob, is_fishing_prob, lengths):
        predictions["vessel_length_m"].append(vessel_length_m)
        predictions["detect_scene_row"].append(detect_scene_row)
        predictions["detect_scene_column"].append(detect_scene_column)
        predictions["scene_id"].append(scene_id)
        # Scores
        predictions["objectness_p"].append(objectness_score)
        predictions["is_vessel_p"].append(is_vessel_p)
        predictions["is_fishing_p"].append(is_fishing_p)
        # Thresholds
        predictions["objectness_threshold"].append(objectness_thresholds_lower_bound)

    predictions = pd.DataFrame.from_dict(predictions)
    return predictions


#!/usr/bin/python3

import sys
import sqlite3
import json
import random

input=sys.argv
file_name=input[1]
db_name=input[2]

conn = sqlite3.connect(db_name)
c=conn.cursor()

c.execute("DROP TABLE IF EXISTS Metadata")
c.execute("CREATE TABLE Metadata(metadata_id int,start_at text,end_at text,activities_count int)")

c.execute("DROP TABLE IF EXISTS Ticket")
c.execute("CREATE TABLE Ticket(ticket_id int,shipping_address text,shipment_date text,category text,contacted_customer text,issue_type text,source int,priority int,groups text,agent_id int,requester int,product text)")

c.execute("DROP TABLE IF EXISTS FactActivityData")
c.execute("CREATE TABLE FactActivitydata(ticket_id int,activity_id int,note_id int,metadata_id int)")

c.execute("DROP TABLE IF EXISTS Activity")
c.execute("CREATE TABLE Activity(activity_id int,performed_at text,peformer_type text,performer_id int,status text)")

c.execute("DROP TABLE IF EXISTS Note")
c.execute("CREATE TABLE Note(note_id int,note_type text)")

c.execute("DROP TABLE IF EXISTS TicketTracker")
c.execute("CREATE TABLE TicketTracker(ticket_id int, status text, act_performed_at text)")

with open(file_name,"r") as read_file:
    j = json.load(read_file)
jsonstr=json.loads(j)
count=jsonstr["metadata"]["activities_count"]

metadata_id=random.randrange(1111,9999)
activity_id=1
note_id=0

c.execute("INSERT INTO Metadata VALUES (?,?,?,?)",
          (metadata_id,jsonstr["metadata"]["start_at"],jsonstr["metadata"]["end_at"],count))

activities=jsonstr["activities_data"]
ticket_id=0
for act in activities :
    note_present=0
    act_present=0
    if "note" in act["activity"]:
        note_id=act["activity"]["note"]["id"]
        note_present=1
        c.execute("INSERT INTO Note VALUES(?,?)",(note_id,act["activity"]["note"]["type"]))
    if "status" in act["activity"]:
        act_present=1
        if(ticket_id!=act["ticket_id"]):
            c.execute("INSERT INTO Ticket VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
            (act["ticket_id"],act["activity"]["shipping_address"],act["activity"]["shipment_date"],act["activity"]["category"],
            act["activity"]["contacted_customer"],act["activity"]["issue_type"],
            act["activity"]["source"],act["activity"]["priority"],act["activity"]["group"],
            act["activity"]["agent_id"],act["activity"]["requester"],act["activity"]["product"]))
            ticket_id=act["ticket_id"]
        c.execute("INSERT INTO ACTIVITY VALUES (?,?,?,?,?)",
        (activity_id,act["performed_at"],act["performer_type"],act["performer_id"],act["activity"]["status"]))
        activity_id=activity_id+1
    c.execute("INSERT INTO FactActivityData VALUES (?,?,?,?)",
    (act["ticket_id"],activity_id*act_present,note_id*note_present,metadata_id))

conn.commit()
conn.close()


from typing import Callable, Dict, Any, Awaitable, Union

from aiogram import BaseMiddleware
from aiogram.types import Update, Message, CallbackQuery

from app.db.repo import Repo

class RegisterMiddleware(BaseMiddleware):
    async def __call__(
        self,
        handler: Callable[[Update, Dict[str, Any]], Awaitable[Any]],
        event: Union[Message, CallbackQuery],
        data: Dict[str, Any],
    ) -> Any:
        repo: Repo = data["repo"]
        user = await repo.get_user(event.from_user.id)
        if not user:
            await repo.create_user(event.from_user.id)
        return await handler(event, data)


import botogram
from datetime import datetime
import json
import re
import time
import threading
import requests
import sys
import subprocess
import socket
bot  = botogram.create('441586309:AAGfrlV7RniRRSrn9rUlSkriqvvEajXBVt4')
status={0: 'Alive',1 : 'Dead', 2:"No connection to internet"}
ports={22:'ssh',80:'http',443:'https',23:'telnet',21:'ftp',25:'smtp',110:'pop3',143:'impap'}
userLock=threading.Lock()

class Host:
    def __init__(self,ip,nickname,state=1):
        self.ip = ip
        self.state = state
        self.nickname=nickname
        self.old_state = state
        self.thread_active=True
        self.thread=threading.Thread(target=self.check,)

    def start_thread(self):
        self.thread.start()

    def stop_thread(self):
        self.thread_active = False

    def check(self):
        while self.thread_active:
            self.state = subprocess.call(['ping','-c 2','-i 0.2',self.ip],stdout=subprocess.PIPE)
            if self.old_state != self.state:
                toggle = self.nickname + ' ' + self.ip + ' ' + status[self.state]
                print (toggle)
                with lock_log:
                    with open('aliveHost.log','a') as f:
                        f.write(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+' host '+self.nickname+' '+self.ip+' is now '+status[self.state]+'\n')
                with userLock:
                    with open('.chatidlist.txt','r') as user_list:
                        for i in user_list.readlines():
                            requests.get("https://api.telegram.org/bot441586309:AAGfrlV7RniRRSrn9rUlSkriqvvEajXBVt4/sendmessage?chat_id={}&text={}".format(i,toggle))
            else:
                pass
            self.old_state=self.state

def checkport(port,ip,chat):
    global ports
    client = socket.socket()
    client.settimeout(50)
    try:
        client.connect((ip,int(port)))
        client.send(bytes('qwerty', 'utf-8'))
        response=client.recv(1024)
        chat.send('Port {}/{} is open'.format(str(port),ports[port]))
    except socket.timeout:
        pass
    except ConnectionRefusedError:
        pass

@bot.command('start')
def startbot_command(chat, message, args):
    users=list()
    with userLock:
        with open('.chatidlist.txt','r') as u:
            for i in u.readlines():
                user = i.strip('\n')
                users.append(user)
        with open('.chatidlist.txt','a') as u:
            for i in users:
                if i == str(chat.id):
                    chat.send('User already in list')
                    break
            else:
                u.write(str(chat.id)+'\n')
                chat.send('User added, chat id: '+str(chat.id))
                print (str(chat.id)+" added")

@bot.command('stop')
def stop_command(chat,message,args):
    tmp_list=list()
    with userLock:
        with open('.chatidlist.txt','r') as user_list:
            for i in user_list:
                if i.strip('\n') == str(chat.id):
                    chat.send('Id removed')
                    print (i.strip('\n')+' removed')
                else:
                    tmp_list.append(i.strip('\n'))
        with open('.chatidlist.txt','w') as user_list:
            for i in tmp_list:
                user_list.write(i+'\n')

@bot.command('scan')
def scanhost_command(chat, message, args):
    global ports
    port_checking=list()
    chat.send('Scanning...')
    for i in ports.keys():
        t=threading.Thread(target=checkport,args=(i,str(args[0]),chat))
        port_checking.append(t)
    for i in port_checking:
        i.start()
    for i in port_checking:
        i.join()
    chat.send('Other main ports are closed')

status={0: 'Alive',1 : 'Dead', 2:"No connection to internet"}

lock_log = threading.Lock()
with lock_log:
    with open('aliveHost.log','w') as f:
        f.write('Start log\n')
host_list=list()
with open('.chatidlist.txt','w') as f:
    f.write('')
with open('hosts.json','r') as j:   #Elaborate JSON file
    json_obj=json.load(j)

for i in json_obj["hosts"].keys():
    host_list.append(Host(json_obj["hosts"][i],i))  #Initialize the list of host

for h in host_list:
    h.start_thread()
    print ('Thread for host ' + h.nickname + ' start.')
bot.run()                                               #Bisogna per forza ctrl+c per arrestare bot e programma
#   while sys.stdin.read(1)=='':
#       pass
for h in host_list:
    h.stop_thread()
with lock_log:
    with open('aliveHost.log','a') as f:
        f.write('Log end\n')


import random
with open('case.txt', 'w') as file:
    nums = []
    i = 0
    while (i < 5000):
        randnum = random.randint(-5000, 5000)
        if (randnum not in nums):
            nums.append(randnum)
            i += 1
    file.write( str( sorted( nums ) ) )


hrs = input("Ingrese Horas:")
h = float(hrs)

tar = input("Ingrese tarifa:")
t = float(tar)

def computepay(a,b):
        if(a<=40):
            paga=a*b
            return paga
        elif(a>40):
           paga=((a-5)*b)+((a-40)*b*1.5)
           return paga

p =computepay(h,t)
print(p)


import asyncio
from aiogram import types
from aiogram.dispatcher import filters

from loader import dp

FORBIDDEN_PHRASE = [
    'пися',
    'попа',
    'кака',
    'писька',
    'попка',
    'какашка',
    'говняшка'
]
DCP_PHRASE = 'э'

@dp.message_handler(filters.Text(equals=FORBIDDEN_PHRASE, ignore_case=True))
async def forbidden_phrase(message: types.Message):
    await message.reply("ЭТО ТЫ!")

@dp.message_handler(filters.Text(contains=DCP_PHRASE, ignore_case=True))
async def forbidden_phrase(message: types.Message):
    await message.reply("НЕ ЭКАЙ МНЕ ТУТ!")

@dp.message_handler(filters.Text(contains='пака', ignore_case=True))
async def forbidden_phrase(message: types.Message):
    await message.reply("По жопе получишь!")


import arcpy,os,uuid
raster=arcpy.GetParameterAsText(0)
vector=arcpy.GetParameterAsText(1)
reclassmap=arcpy.sa.RemapRange([[0,13,1],[13,25,2],[25,36,3],[36,48,4],[48,74,5],[74,90,6]])#分类级别
tempPath=os.environ["TMP"]#获取windows的临时目录
outslope=arcpy.sa.Slope(raster)
#outslope.save(os.path.join(os.environ["TMP"],"f2"))
arcpy.AddMessage(tempPath)
outReclassRR = arcpy.sa.Reclassify(outslope, "VALUE", reclassmap)
#if arcpy.Exists(os.path.join(os.environ["TMP"],"slopelevel")):
#    arcpy.Delete_management(os.path.join(os.environ["TMP"],"slopelevel"))
#outReclassRR.save(os.path.join(os.environ["TMP"],"slopelevel"))
#arcpy.RasterToPolygon_conversion(os.path.join(os.environ["TMP"],"slopelevel"),os.path.join(os.environ["TMP"],"vectorpolygon"),"NO_SIMPLIFY","VALUE")

if arcpy.Exists(os.path.join(os.environ["TMP"],"vectorpolygon.shp")):
    arcpy.Delete_management(os.path.join(os.environ["TMP"],"vectorpolygon.shp"))
    arcpy.AddMessage(os.path.join(os.environ["TMP"],"vectorpolygon.shp"))
arcpy.RasterToPolygon_conversion(outReclassRR,os.path.join(os.environ["TMP"],"vectorpolygon.shp"),"NO_SIMPLIFY","VALUE")
arcpy.AddField_management(os.path.join(os.environ["TMP"],"vectorpolygon.shp"),"AREA","DOUBLE")
arcpy.CalculateField_management(os.path.join(os.environ["TMP"],"vectorpolygon.shp"),"AREA","!shape.area!","PYTHON_9.3")

#arcpy.MakeFeatureLayer_management(os.path.join(os.environ["TMP"],"vectorpolygon.shp"),"polygonLayer")
#arcpy.SelectLayerByAttribute_management("polygonLayer","NEW_SELECTION",'"Shape_Area"<=900')
#arcpy.Eliminate_management("polygonLayer",vector,"LENGTH","")
#arcpy.AddMessage(vector)


import json
from tqdm import tqdm
import math
from config import UNK_TOKEN

def load_vocabulary():
    vocab = {}
    print("load vocabulary...")
    with open("./data/vector.txt", "r") as fr:
        for ids, line in enumerate(fr):
            line = line.strip()
            word = line[: line.find(" ")]
            vector = line[line.find(" ")+1:].split()
            if len(vector) != 300:
                raise Exception("dim of vector not equal 300!")
            vector = list(map(lambda x: float(x), vector))
            vocab[word] = vector
            if ids % 10000 == 0:
                print("load vocabulary %d" % ids)
    print("load vocabulary finish!")
    return vocab

# def cal_idf():
#     trainset = []
#     vocab = load_vocabulary()
#     idfs = {}
#     print("load data...")
#     with open("./data/train.txt", "r") as fr:
#         for ids, line in enumerate(fr):
#             trainset.append(json.loads(line))
#             if ids % 100000 == 0:
#                 print("load data %d" % ids)
#     print("load data finish!")
#     num_trainset = len(trainset)
#     print("calculate idf...")
#     for word in tqdm(vocab.keys()):
#         count = 1
#         for train_data in trainset:
#             if word in train_data['post'] or word in train_data['response']:
#                 count += 1
#         idf = math.log10(1.0*num_trainset/count)
#         idfs[word] = idf
#     print("calculate idf finish!")
#     with open("./data/idf.txt", "w") as fw:
#         fw.write(json.dumps(idfs))

def cal_idf():
    trainset = []
    vocab = load_vocabulary()
    idfs = dict(zip(vocab.keys(), [0]*len(vocab.keys())))
    print("load data...")
    with open("./data/train.txt", "r") as fr:
        for ids, line in enumerate(fr):
            line = json.loads(line)
            trainset.append(set(line['post']+line['response']))
            if ids % 100000 == 0:
                print("load data %d" % ids)
    print("load data finish!")
    num_trainset = len(trainset)
    print("calculate idf...")
    for sample in tqdm(trainset):
        for word in sample:
            if word in idfs:
                idfs[word] += 1
            else:
                idfs[UNK_TOKEN] += 1
    for word, idf in tqdm(idfs.items()):
        idfs[word] = math.log10(1.0*num_trainset/(idf+1))
    print("calculate idf finish!")
    with open("./data/idf.txt", "w") as fw:
        fw.write(json.dumps(idfs))

if __name__ == '__main__':
    cal_idf()


import cv2

# Load the cascade classifier for face detection
face_cascade = cv2.CascadeClassifier('haar_face.xml')

# Initialize the video capture device
cap = cv2.VideoCapture(0)

while True:
    # Capture a frame from the video feed
    ret, frame = cap.read()

    # Convert the frame to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the grayscale image
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

    # Draw a bounding box around each detected face
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('Face Detection', frame)

    # Exit the program if the user presses the 'q' key
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture device and close all windows
cap.release()
cv2.destroyAllWindows()