import os
from pytube import Playlist, YouTube

def download_video(url, folder, number_videos, skip_existing):
    try:
        if 'playlist' in url:
            playlist = Playlist(url)
            videos = playlist.video_urls
        else:
            videos = [url]

        download_path = os.path.join(os.getcwd(), folder)
        os.makedirs(download_path, exist_ok=True)

        for i, video in enumerate(videos, start=1):
            youtube = YouTube(video)
            stream = youtube.streams.get_highest_resolution()

            if number_videos:
                title = f'{i:02d} - {youtube.title}'
            else:
                title = youtube.title

            filename = f'{title}.{stream.subtype}'.replace(':', '_')

            file_path = os.path.join(download_path, filename)
            if skip_existing and os.path.exists(file_path):
                print(f'Skipping existing file: {filename}')
                continue

            stream.download(output_path=download_path, filename=filename)

            print(f'Downloaded video {i}/{len(videos)}: {filename}')

        print('Beeep boop! Download complete!')
    except Exception as e:
        print('Error:', str(e))

def main():
    print('Beeep boop! Welcome to the YouTube video/playlist downloader app!')

    url = input('Enter the YouTube video or playlist link: ')
    folder = input('Enter the download folder name: ')
    number_videos = input('Should the videos be numbered in the playlist order? (Y/N): ')
    number_videos = number_videos.lower() == 'y'
    skip_existing = input('Should existing files be skipped? (Y/N): ')
    skip_existing = skip_existing.lower() == 'y'

    download_video(url, folder, number_videos, skip_existing)

if __name__ == '__main__':
    main()


from behave import given, then, when, step
import requests
import subprocess
import json
import os

@step('Using "{server}" as endpoint')
def set_endpoint(context, server):
    context.endpoint = server

@step('Working with "{mode}" mode')
def set_server_mode(context, mode):
    context.mode = mode
    context.endpoint = context.endpoint + '/' + mode

@step('Load "{template}" body as template request')
def load_default_json(context, template):
    base_path = os.path.dirname(__file__)
    template_path = os.path.join(base_path, 'utils/bodyTest.json')
    with open(template_path, 'r') as fd:
        context.template = json.loads(fd.read())

@step('Using {method} method to ask {code} as mocked code')
@step('Using {method} method')
def set_request(context, method, code=None):
    context.req_method = method
    if code is not None:
        set_code_to_request(context, code)

@step('Ask {code} as mocked code')
def set_code_to_request(context, code):
    context.req_code = code
    if context.mode == 'mockurl':
        request_mockurl(context)
    else:
        request_mockserver(context)

@step('I get the requested code')
def check_requested_code(context):
    assert int(context.req_code) == int(context.response.status_code),\
        f'Differences between requests [{context.req_code}] and response code [{context.response.status_code}]'

def request_mockurl(context):
    if context.req_method == 'GET':
        context.response = requests.get(f'{context.endpoint}/{context.req_code}')
    elif context.req_method == 'POST':
        context.response = requests.post(f'{context.endpoint}/{context.req_code}')

def content_length(body_to_send):
    str = json.dumps(body_to_send)
    return (len(str.encode('utf-8')))

def request_mockserver(context):
    context.req_body = dict(context.template['content'])
    context.req_body['message']['messages'][0]['text']['body'] = context.req_code
    context.req_headers = context.template['header']
    context.req_headers['Content-Length'] = str(content_length(context.req_body))
    if context.req_method == 'POST':
        context.response = requests.post(context.endpoint, headers=context.req_headers, json=context.req_body)
    else:
        pass


import numpy as np   # check out how to install numpy
from utils import load, plot_sample
from PIL import Image
import matplotlib.pyplot as plt
from collections import Counter

def KNN_classify(k,X,training_data):
    Xtrain = training_data[0]
    Ytrain = training_data[1]
    #open a dict to store the label of eachdatapoint (by distance)
    d = {}
    # Iterate for each training datapoint:
    # ------

    for i, digit in enumerate(Xtrain):
        # calc auclidien distanse:
        # -then save in a HashTable
        distance = np.linalg.norm(X - digit)
        d[i] = distance

    # get K minimum distance neighbors
    k_nearst_neighbors = sorted(d, key=d.get)[:k]

    arr = []
    # run over each of nearest n's, and count them.
    for index in k_nearst_neighbors:
        neighbor = Ytrain[index]
        arr.append(neighbor[0])

    # return the most common digit among k neighbors
    return Counter(arr).most_common()[0][0]


from aocutils import get_raw

from collections import defaultdict, Counter
from math import ceil

def problem1():
    return simulate(10)

def problem2():
    return simulate(40)

def simulate(steps):
    mapping, counts = parse_input()
    for _ in range(steps):
        counts = Counter({pair: sum(counts[starter] for starter in starters) for pair, starters in mapping.items()})
    return calc_answer(counts)

def parse_input():
    template, rules = get_raw(14).split('\n\n')
    mapping = defaultdict(list)
    for rule in rules.splitlines():
        pair, insert = rule.split(' -> ')
        mapping[pair[0] + insert].append(pair)
        mapping[insert + pair[1]].append(pair)
    counts = Counter()
    for i in range(len(template) - 1):
        counts[template[i:i + 2]] += 1
    return mapping, counts

def calc_answer(counts):
    elements = Counter()
    for pair, count in counts.items():
        elements[pair[0]] += count
        elements[pair[1]] += count
    return ceil((max(elements.values()) - min(elements.values())) / 2)


import torch
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
from torchvision.transforms.functional import to_tensor
from pathlib import Path

def NormalizeData(data):
    return (data - np.min(data)) / (np.max(data) - np.min(data))

def img_loader(path):
    return Image.open(path).convert('RGB')

def CropPatches(image, patch_size=32, stride=32):
    w, h = image.size
    #image.show()
    patches = ()
    for i in range(0, h-patch_size, stride):
        for j in range(0, w-patch_size, stride):
            patch = to_tensor(image.crop((j, i, j+patch_size, i+patch_size)))
            patches = patches + (patch,)
    return patches

def Split_left_right(image):
    w, h = image.size
    imL = image.crop((0, 0, w/2, h))
    imR = image.crop((w/2, 0, w, h))
    return imL, imR

class SIQADataset(Dataset):
    def __init__(self, dataset, config, index, status):
        self.img_loader = img_loader
        im_dirR = config[dataset]['im_dirR']
        im_dirL = config[dataset]['im_dirL']
        self.patch_size = config['patch_size']
        self.stride = config['stride']

        test_ratio = config['test_ratio']
        train_ratio = config['train_ratio']
        trainindex = index[:int(train_ratio * len(index))]
        testindex = index[int((1 - test_ratio) * len(index)):]
        train_index, test_index = [], []

        im_names = []
        ref_names = []
        for line1 in open("./data/" + dataset + "/im_names_S.txt", "r"):
            line1 = line1.strip()
            im_names.append(line1)
        im_names = np.array(im_names)
        #print("im_names {}".format (im_names))
        typpe = []
        for line10  in open("./data/" + dataset + "/im_names_S.txt", "r"):
            line10 = line10.strip()
            line10 = line10.split("/")

            typpe.append(line10)
        typpe =[item[0] for item in typpe]
        typpe = np.array(typpe)
        #print("type {}".format (typpe))

        for line2 in open("./data/" + dataset + "/refnames_S.txt", "r"):
            line2 = line2.strip()
            ref_names.append(line2)
        ref_names = np.array(ref_names)
        ref_ids = []
        for line0 in open("./data/" + dataset + "/ref_ids_S.txt", "r"):
            line0 = float(line0[:-1])
            ref_ids.append(line0)
        ref_ids = np.array(ref_ids)

        for i in range(len(ref_ids)):
            if(ref_ids[i] in trainindex):
                train_index.append(i)
            elif(ref_ids[i] in testindex):
                test_index.append(i)

        if status == 'train':
            self.index = train_index
            print("#==> Train Images len: {}".format(len(self.index)))
            print('#==> Training Indexes: ', trainindex)
        if status == 'test':
            self.index = test_index
            print("#==> Test Images len: {}".format(len(self.index)))
            print('#==> Test Indexes: ', testindex)
            print('#==> Test Image names: ', im_names[test_index])

        self.mos_s = []
        self.mos_l = []
        self.mos_r = []

        for line_s in open("./data/" + dataset + "/MOS_S.txt", "r"):
            line_s = float(line_s.strip())
            self.mos_s.append(line_s)
        self.mos_s = np.array(self.mos_s)

        for line_l in open("./data/" + dataset + "/MOS_L.txt", "r"):
            line_l = float(line_l.strip())
            self.mos_l.append(line_l)
        self.mos_l = np.array(self.mos_l)

        for line_r in open("./data/" + dataset + "/MOS_R.txt", "r"):
            line_r = float(line_r.strip())
            self.mos_r.append(line_r)
        self.mos_r = np.array(self.mos_r)

        self.patchesR = ()
        self.patchesL = ()

        self.label = []
        self.label_L = []
        self.label_R = []

        self.im_names = [im_names[i] for i in self.index]
        self.ref_names = [ref_names[i] for i in self.index]
        self.mos_s = [self.mos_s[i] for i in self.index]
        self.mos_l = [self.mos_l[i] for i in self.index]
        self.mos_r = [self.mos_r[i] for i in self.index]

        typpe = [typpe[i] for i in self.index]

        for idx in range(len(self.index)):

            img = self.img_loader(Path(str(im_dirL)+ str(self.im_names[idx]) ))
            imL, imR = Split_left_right(img)

            patchesR = CropPatches(imR, self.patch_size, self.stride)
            patchesL = CropPatches(imL, self.patch_size, self.stride)

            if status == 'train':
                self.patchesL = self.patchesL + patchesL
                self.patchesR = self.patchesR + patchesR

                for i in range(len(patchesL)):
                    self.label.append(self.mos_s[idx])
                    self.label_L.append(self.mos_l[idx])
                    self.label_R.append(self.mos_r[idx])

            elif status == 'test':
                self.patchesL = self.patchesL + (torch.stack(patchesL), )
                self.patchesR = self.patchesR + (torch.stack(patchesR), )
                self.label.append(self.mos_s[idx])
                self.label_L.append(self.mos_l[idx])
                self.label_R.append(self.mos_r[idx])

    def __len__(self):
        return len(self.patchesL)

    def __getitem__(self, idx):
        return self.patchesL[idx], self.patchesR[idx], (torch.Tensor([self.label[idx]]), torch.Tensor([self.label_L[idx]]), torch.Tensor([self.label_R[idx]]))


# -*- coding: utf-8 -*-
"""
@authors: david candela & andreu giménez
"""

import os
import json
import duckdb

trusted_path = 'trusted/'
explotation_path = 'exploitation/'

def load_queries():
    if not os.path.exists(explotation_path + "tables.json"):
        print("No exploitation tables defined")
        return {}
    with open(explotation_path + "tables.json", mode='r', encoding='utf-8') as handler:
        queries = json.load(handler)
        return queries

def merge_tables(queries):
    with duckdb.connect(database=trusted_path + 'database.db', read_only=False) as con:
        # Attach tables and extract information
        con.execute(f"ATTACH DATABASE '{explotation_path + 'database.db'}' AS destination")
        for table, query in queries.items():
            try:
                con.execute(f"CREATE OR REPLACE TABLE destination.{table} AS {query}")
            except (duckdb.CatalogException, duckdb.ParserException) as err:
                print(f"Unable to generate table {table} from the query:")
                print("CREATE OR REPLACE TABLE destination.{table} AS")
                print(f"{query}")
                print("Causes:")
                for arg in err.args:
                    print(arg)

def to_exploitation():
    queries = load_queries()
    merge_tables(queries)


import logging
import os
import pathlib
import time

import httpx
import regex
import yarl
from tqdm import tqdm

from ...config import FFMPEG_EXECUTABLE, FFMPEG_HLS, FFMPEG_SUBMERGE
from .content_mt import mimetypes
from .ffmpeg import FFMPEG_EXTENSIONS, ffmpeg_download, has_ffmpeg, merge_subtitles
from .hls import HLS_STREAM_EXTENSIONS, hls_yield

if FFMPEG_EXECUTABLE:
    ffmpeg_executable = FFMPEG_EXECUTABLE

EXEMPT_EXTENSIONS = ["mpd"]
CONTENT_DISP_RE = regex.compile(r'filename=(?:"(.+?)"|([^;]+))')

def sanitize_filename(f):
    return "".join(" - " if _ in '<>:"/\\|?*' else _ for _ in f).strip()

def ext_from_filename(filename):
    position = filename.rfind(".")
    if position == -1:
        return ""
    return filename[position + 1 :]

def get_extension(url):
    url = yarl.URL(url)
    return ext_from_filename(url.name)

def guess_extension(content_type):
    if not content_type:
        return ""

    for _, cd, extension in mimetypes:
        if cd == content_type:
            return (extension or "").lstrip(".")

def ext_from_content_disposition(content_disposition):
    match = CONTENT_DISP_RE.search(content_disposition)

    if not match:
        return ""

    return ext_from_filename(match.group(1) or match.group(2))

def process_url(session, url, headers={}):
    """
    Get the extension, content size and range downloadability forehand.

    Returns:

    `str`, `int`, `bool`
    """
    response = session.head(url, headers=headers)
    response_headers = response.headers

    extension = (
        ext_from_content_disposition(
            response_headers.get("content-disposition", "") or ""
        )
        or guess_extension(response_headers.get("content-type", ""))
        or get_extension(url)
        or get_extension(str(response.url))
    ).lower()

    return (
        extension,
        int(response_headers.get("content-length") or 0),
        "bytes" in response_headers.get("accept-ranges", ""),
    )

def standard_download(
    session: httpx.Client,
    url: str,
    content_dir: pathlib.Path,
    outfile_name: str,
    extension: str,
    content_size: int,
    headers: dict = {},
    ranges=True,
    **opts
):
    file = "{}.{}".format(outfile_name, extension)

    logger = logging.getLogger("downloader/standard[{}]".format(file))
    out_path = content_dir / pathlib.Path(sanitize_filename(file))

    if not ranges:
        logger.critical(
            "Stream does not support ranged downloading; failed downloads cannot be continued."
        )

    with open(out_path, "ab") as outstream:
        downloaded = outstream.tell() if ranges else 0
        progress_bar = tqdm(
            desc="GET / {}".format(file),
            total=content_size,
            disable=opts.get("log_level", 20) > 20,
            initial=downloaded,
            unit="B",
            unit_scale=True,
            unit_divisor=1024,
        )
        while content_size > downloaded:
            temporary_headers = headers.copy()
            if ranges:
                temporary_headers.update({"Ranges": "bytes={}-".format(downloaded)})
            try:
                with session.stream("GET", url, headers=headers) as http_stream:
                    http_stream.raise_for_status()

                    for chunks in http_stream.iter_bytes():
                        size = len(chunks)
                        outstream.write(chunks)
                        progress_bar.update(size)
                        downloaded += size
            except httpx.RequestError as e:
                if not ranges:
                    downloaded = 0
                    outstream.seek(0)
                    progress_bar.clear()
                else:
                    outstream.flush()
                logger.error("Downloading error due to {!r}, retrying.".format(e))
                time.sleep(opts.get("retry_timeout") or 5.0)

    progress_bar.close()

def hls_download(
    session: httpx.Client,
    url: str,
    content_dir: pathlib.Path,
    outfile_name: str,
    headers: dict = {},
    **opts
):

    sanitized = sanitize_filename(outfile_name)
    content_path = content_dir / "{}.ts".format(sanitized)
    index_holder = content_dir / "{}.partialts".format(sanitized)
    index = 1

    if index_holder.exists():
        with open(index_holder, "r") as ih:
            index = int(ih.read() or 1)

    sizes = []
    with open(content_path, "ab") as tsstream, open(index_holder, "w+") as istream:
        downloaded = tsstream.tell()
        if downloaded:
            sizes.extend([downloaded / index] * index)
        progress_bar = tqdm(
            desc="HLS GET / {}.ts".format(outfile_name),
            unit="B",
            unit_scale=True,
            unit_divisor=1024,
            initial=downloaded,
            disable=opts.get("log_level", 20) > 20,
        )

        for content in hls_yield(
            session,
            [{"stream_url": url, "headers": headers}],
            opts.get("preferred_quality") or 1080,
            opts.get("retry_timeout") or 5,
            continuation_index=index,
        ):
            stream = content.get("bytes")
            total = content.get("total")
            current = content.get("current")

            size = len(stream)
            sizes.append(size)

            mean = sum(sizes) / len(sizes)
            stddev = (sum(abs(mean - s) ** 2 for s in sizes) / len(sizes)) ** 0.5

            progress_bar.total = mean * total
            progress_bar.desc = "HLS GET / {}.ts [± {:.3f} MB]".format(
                outfile_name, stddev / (1024**2)
            )
            progress_bar.update(size)

            istream.write(str(current or 0 + 1))
            istream.seek(0)
            istream.flush()

            tsstream.write(stream)

    progress_bar.close()
    os.remove(index_holder)

def idm_download(url, headers, content_dir, outfile_name, extension, **opts):
    file = "{}.{}".format(outfile_name, extension)
    from .idmanlib import wait_until_download as idmdl

    idmdl(url, headers=headers or {}, download_folder=content_dir, filename=file)

def subautomatic(f):
    def __inner__(session, url, headers, content_dir, outfile_name, *args, **kwargs):
        logger = logging.getLogger("ffmpeg/submerge")

        subtitles = kwargs.pop("subtitles", [])

        callback = f(session, url, headers, content_dir, outfile_name, *args, **kwargs)

        if not subtitles:
            return

        if (not has_ffmpeg()) or not FFMPEG_SUBMERGE:
            logger.debug("{!r} will not be merged.".format(subtitles))
            for count, subtitle in enumerate(subtitles, 1):
                handle_download(
                    session,
                    subtitle,
                    headers=headers,
                    content_dir=content_dir,
                    outfile_name="{}_SUB_{}".format(outfile_name, count),
                )
            return callback

        extension, _, _ = process_url(session, url, headers)
        resolved_path = (
            content_dir / "{}.{}".format(outfile_name, extension)
        ).resolve()
        subout_path = (
            content_dir / "{} [CC].{}".format(outfile_name, extension)
        ).resolve()

        ffmpeg_returncode = merge_subtitles(
            resolved_path, subout_path, subtitles, log_level=kwargs.get("log_level", 20)
        )

        if ffmpeg_returncode:
            return (
                logger.warning(
                    "Got a non-zero return code {} from ffmpeg, the original file will not be erased in case of merge failure.".format(
                        ffmpeg_returncode
                    )
                )
                or callback
            )

        try:
            os.remove(resolved_path)
        except FileNotFoundError:
            pass

        try:
            os.rename(subout_path, resolved_path)
        except FileNotFoundError:
            pass

        return callback

    return __inner__

@subautomatic
def handle_download(
    session, url, headers, content_dir, outfile_name, idm=False, **opts
):

    extension, content_size, ranges = process_url(session, url, headers)

    if FFMPEG_HLS and (extension in FFMPEG_EXTENSIONS and has_ffmpeg()):
        return ffmpeg_download(url, headers, outfile_name, content_dir, **opts)

    if extension in EXEMPT_EXTENSIONS:
        raise Exception(
            "Download extension {!r} requires custom downloading which is not supported yet.".format(
                extension
            )
        )

    if extension in HLS_STREAM_EXTENSIONS:
        return hls_download(
            session, url, content_dir, outfile_name, headers or {}, **opts
        )

    if idm:
        return idm_download(
            url, headers or {}, content_dir.resolve(), outfile_name, extension, **opts
        )

    return standard_download(
        session,
        url,
        content_dir,
        outfile_name,
        extension,
        content_size,
        headers or {},
        ranges,
        **opts
    )


import json
import logging

from apiflask import abort, input

from ibm.auth import authenticate
from ibm.middleware import log_restore_activity
from ibm.models import (DisasterRecoveryBackup, IBMCloud, IBMImage, IBMKubernetesCluster, IBMSshKey, WorkflowRoot,
                        WorkflowsWorkspace, IBMSatelliteCluster)
from ibm.tasks.draas_tasks.utils import update_payload_with_new_ids
from ibm.web import db as ibmdb
from ibm.web.common.utils import authorize_and_get_ibm_cloud, verify_and_get_region, create_kubernetes_restore_workflow
from ibm.web.ibm.draas import ibm_draas
from .schemas import ClusterRestoreInSchema, DisasterRecoveryRestoreInSchema, AgentClusterRestoreInSchema
from .utils import create_ibm_draas_restore_workflow, region_to_zones

LOGGER = logging.getLogger(__name__)

@ibm_draas.post('/draas_backups/<backup_id>/restore')
@authenticate
@log_restore_activity
@input(DisasterRecoveryRestoreInSchema)
def restore_backup(backup_id, data, user):
    """
    Restore Disaster Recovery Backup
    This request restores Disaster Recovery Backup for a given backup_id
    """
    backup = ibmdb.session.query(DisasterRecoveryBackup).filter_by(id=backup_id).first()
    if not backup:
        message = f"No Disaster recovery Backup found with ID {backup_id}"
        LOGGER.debug(message)
        abort(404, message)

    if backup.status != DisasterRecoveryBackup.SUCCESS:
        message = f"Disaster recovery Backup with ID {backup_id} not ready"
        LOGGER.debug(message)
        abort(400, message)

    blueprint = backup.disaster_recovery_resource_blueprint

    if data["resource_type"] == "IKS":
        restore_type_existing_iks = data.get("restore_type_existing_iks")
        kubernetes_cluster_target = ibmdb.session.query(IBMKubernetesCluster).filter_by(
            id=restore_type_existing_iks["ibm_cluster_target"]["id"]
        ).first()

        if not kubernetes_cluster_target:
            message = f'IBM Kubernetes Cluster {restore_type_existing_iks["ibm_cluster_target"]["id"]} does not exist'
            LOGGER.debug(message)
            abort(404, message)

        cos_bucket_id = blueprint.resource_metadata["cos_bucket_id"]
        cos_access_keys_id = blueprint.resource_metadata["cos_access_keys_id"]
        namespaces = blueprint.resource_metadata["namespaces"]
        task_metadata = {
            "ibm_cloud": {
                "id": restore_type_existing_iks["ibm_cloud"]["id"]
            },
            "cos_bucket_id": cos_bucket_id,
            "cos_access_keys_id": cos_access_keys_id,
            "backup_name": backup.name,
            "namespaces": namespaces,
            "backup_id": backup_id,
            "workflow_name": f"{DisasterRecoveryBackup.__name__} {kubernetes_cluster_target.name}",
            "email": user.get("email"),
            "resource_type": data["resource_type"],
            "user": user
        }
        backup_provider = backup.backup_metadata['resource_json'].get('provider')
        task_metadata["backup_provider"] = backup_provider
        if backup_provider and backup_provider != "vpc-gen2":  # Classic cluster backup
            kubernetes_cluster = ibmdb.session.query(IBMKubernetesCluster).filter_by(
                id=restore_type_existing_iks["ibm_cluster_source"]["id"]
            ).first()
            if not kubernetes_cluster:
                message = f'IBM Kubernetes Cluster {restore_type_existing_iks["ibm_cluster_source"]["id"]} does not ' \
                          f'exist'
                LOGGER.debug(message)
                abort(404, message)

            resource_json = {
                "name": kubernetes_cluster_target.name,
                "target_resource_id": kubernetes_cluster_target.resource_id,
                "resource_id": kubernetes_cluster.resource_id,
                "target_cluster_hostname": kubernetes_cluster_target.ingress.get("hostname"),
                "classic_cluster_name": kubernetes_cluster.name,
                "classic_cluster_ingress_hostname": kubernetes_cluster.ingress.get("hostname")
            }

        else:
            resource_json = {
                "name": kubernetes_cluster_target.name,
                "resource_id": kubernetes_cluster_target.resource_id
            }

        task_metadata["resource_json"] = resource_json
        workflow_root = create_ibm_draas_restore_workflow(data=task_metadata, user=user)
        return workflow_root.to_json(metadata=True)
    else:
        from ibm.web.ibm.workspaces.utils import create_workspace_workflow
        cloud_id = data["ibm_cloud"]["id"]
        region_id = data["region"]["id"]

        ibm_cloud = authorize_and_get_ibm_cloud(cloud_id=cloud_id, user=user)
        verify_and_get_region(ibm_cloud=ibm_cloud, region_id=region_id)

        workspace_payload = backup.backup_metadata["workspace_payload"]
        updated_workspace_payload = update_payload_with_new_ids(workspace_payload)
        if workspace_payload.get("address_prefixes"):
            old_region_id = updated_workspace_payload["address_prefixes"][0]["region"]["id"]

            zones_old_ids = region_to_zones(old_region_id)
            zones_new_ids = region_to_zones(region_id)

            json_dict_str = json.dumps(updated_workspace_payload)
            json_dict_str = json_dict_str.replace(old_region_id, region_id)

            for old_id, new_id in zip(zones_old_ids, zones_new_ids):
                json_dict_str = json_dict_str.replace(old_id[0], new_id[0])

            updated_workspace_payload = json.loads(json_dict_str)

        for ibm_ssh_key in updated_workspace_payload['ssh_keys']:
            ssh_key = ibmdb.session.query(IBMSshKey).filter_by(name=ibm_ssh_key["resource_json"]['name'],
                                                               public_key=ibm_ssh_key["resource_json"]['public_key'],
                                                               region_id=ibm_ssh_key["region"]["id"]).first()
            if ssh_key:
                for instance in updated_workspace_payload.get("instances"):
                    for key in instance.get("resource_json").get("keys"):
                        if key.get("name") == ssh_key.name:
                            key["id"] = ssh_key.id
                updated_workspace_payload["ssh_keys"].remove(ibm_ssh_key)

        for instance_images in updated_workspace_payload["instances"]:
            image = instance_images["resource_json"].get("image")
            if not image:
                continue
            if image.get("name"):
                instance_images["resource_json"]["image"].pop("id", None)
                continue
            old_image = ibmdb.session.query(IBMImage).filter_by(
                region_id=old_region_id, cloud_id=cloud_id, id=instance_images["resource_json"]["image"]["id"]
            ).first()
            if old_image:
                new_image = ibmdb.session.query(IBMImage).filter_by(region_id=region_id, cloud_id=cloud_id,
                                                                    name=old_image.name).first()
                if new_image:
                    updated_workspace_payload["instances"][0]["resource_json"]["image"]["id"] = new_image.id

        updated_workspace_payload["cloud_id"] = blueprint.cloud_id
        updated_workspace_payload["backup_name"] = backup.name
        updated_workspace_payload['resource_type'] = blueprint.resource_type
        updated_workspace_payload['project_id'] = user.get("project_id")
        updated_workspace_payload["user_id"] = user.get("id")

        workspace_tree = create_workspace_workflow(user, data=updated_workspace_payload, backup_id=backup_id,
                                                   source_cloud=WorkflowsWorkspace.IBM,
                                                   workspace_type=WorkflowsWorkspace.TYPE_RESTORE)
        for workflow_root in workspace_tree.associated_roots.all():
            workflow_root.status = WorkflowRoot.STATUS_READY
            ibmdb.session.commit()

        workspace_tree.status = WorkflowsWorkspace.STATUS_PENDING
        ibmdb.session.commit()

        return workspace_tree.to_json()

@ibm_draas.post('/draas-eks-restores')
@authenticate
@input(ClusterRestoreInSchema)
def restore_eks_backup(data, user):
    """
    Restore Disaster Recovery EKS Backup in IKS cluster
    This request restores Disaster Recovery Backup for a eks backup
    """
    cloud = data["ibm_cloud"]
    cloud["user_id"] = user["id"]
    cloud["project_id"] = user["project_id"]
    ibm_cloud = ibmdb.session.query(IBMCloud).filter_by(
        **cloud
    ).first()
    if not ibm_cloud:
        message = f"IBM Cloud {cloud['id'] if cloud.get('id') else cloud.get('name')} not found"
        LOGGER.debug(message)
        abort(404, message)

    if ibm_cloud.status != IBMCloud.STATUS_VALID:
        message = f"IBM Cloud {ibm_cloud.name} is not in {IBMCloud.STATUS_VALID} status"
        LOGGER.debug(message)
        abort(404, message)

    cluster = data["cluster"]
    cluster["cloud_id"] = ibm_cloud.id
    kubernetes_cluster = ibmdb.session.query(IBMKubernetesCluster).filter_by(
        **cluster
    ).first()
    if not kubernetes_cluster:
        message = f'IBM Kubernetes Cluster {cluster["id"] if data["cluster"].get["id"] else cluster["name"]} does ' \
                  f'not exist'
        LOGGER.debug(message)
        abort(404, message)

    workflow_root = create_kubernetes_restore_workflow(user, IBMKubernetesCluster, data)
    return workflow_root.to_json()

@ibm_draas.post('/draas-satellite-restores')
@authenticate
@input(AgentClusterRestoreInSchema)
def restore_eks_backup_satellite_cluster(data, user):
    """
    Restore Disaster Recovery EKS Backup in Satellite cluster
    This request restores Disaster Recovery Backup for a eks backup
    """
    cloud = data["ibm_cloud"]
    cloud["user_id"] = user["id"]
    cloud["project_id"] = user["project_id"]
    ibm_cloud = ibmdb.session.query(IBMCloud).filter_by(
        **cloud
    ).first()
    if not ibm_cloud:
        message = f"IBM Cloud {cloud['id'] if cloud.get('id') else cloud.get('name')} not found"
        LOGGER.debug(message)
        abort(404, message)

    if ibm_cloud.status != IBMCloud.STATUS_VALID:
        message = f"IBM Cloud {ibm_cloud.name} is not in {IBMCloud.STATUS_VALID} status"
        LOGGER.debug(message)
        abort(404, message)

    cluster = data["cluster"]
    agent_id = data['agent_id']
    cluster["cloud_id"] = ibm_cloud.id
    satellite_cluster = ibmdb.session.query(IBMSatelliteCluster).filter_by(
        **cluster
    ).first()
    if not satellite_cluster:
        message = f'IBM Satellite Cluster {cluster["id"] if data["cluster"].get["id"] else cluster["name"]} does ' \
                  f'not exist'
        LOGGER.debug(message)
        abort(404, message)

    satellite_cluster.agent_id = agent_id
    ibmdb.session.commit()

    workflow_root = create_kubernetes_restore_workflow(user, IBMSatelliteCluster, data)
    return workflow_root.to_json()


import boto3
import sys
s3 = boto3.resource('s3')
for bucket_name in sys.argv[1:]:
    bucket = s3.Bucket(bucket_name)
    try:
        resp = bucket.delete()
        print(resp)
    except Exception as e:
        print(e)


import requests
from bs4 import BeautifulSoup

url = "https://yandex.ru/news/"
first_news_class = "news-card__annotation"

def parse():
    response = str(requests.get(url=url).content.decode())
    soup = BeautifulSoup(response[1 : len(response)-2], "html.parser")
    tmp = soup.find('div', class_=first_news_class)
    tmp = str(tmp)

    begin_text_index = tmp.find('>') + 1
    tmp_cut_left = tmp[begin_text_index:]
    end_text_index = tmp_cut_left.find('<')
    cut = tmp_cut_left[:end_text_index]
    return cut

if __name__ == '__main__':
    print(parse())


import duckdb
import os

# get all tables' row number of a database
def get_row_count(dir):
    # connect to database with dir
    con = duckdb.connect(dir)
    cur = con.cursor()

    # get all tables' name
    cur.execute("SELECT name FROM sqlite_master WHERE type='table';")

    tables = cur.fetchall()
    with open("answers/row_count.txt", "w") as f:
        for table in tables:
            # get row number of each table
            cur.execute("SELECT COUNT(*) FROM %s;" % table)
            row_count = cur.fetchone()[0]
            f.write("%s: %s\n" % (table[0], row_count))

    con.close()

if __name__ == "__main__":
    dir = 'NYC-transit.db'
    get_row_count(dir)


import hashlib
import json
import os

_ENV_DIR = '/var/db/factory/umpire'
_CONFIG_PATH = os.path.join(_ENV_DIR, 'active_umpire.json')

def SaveNewActiveConfig(config):
  """Serialize and saves the configuration as new active config file."""
  json_config = json.dumps(
      config, indent=2, separators=(',', ': '), sort_keys=True) + '\n'

  encoded_json_config = json_config.encode('utf-8')
  json_name = 'umpire.%s.json' % hashlib.md5(encoded_json_config).hexdigest()
  json_path = os.path.join('resources', json_name)
  with open(os.path.join(_ENV_DIR, json_path), 'w') as f:
    f.write(json_config)

  os.unlink(_CONFIG_PATH)
  os.symlink(json_path, _CONFIG_PATH)

def Migrate():
  with open(_CONFIG_PATH) as f:
    config = json.load(f)

  if 'services' in config and 'http' in config['services']:
    config['services']['umpire_http'] = config['services'].pop('http')
    SaveNewActiveConfig(config)


from datetime import datetime, timedelta
import numpy as np
import pytz, tzlocal

sind = lambda degrees: np.sin(np.deg2rad(degrees))
cosd = lambda degrees: np.cos(np.deg2rad(degrees))
arcsind = lambda ratio: np.rad2deg(np.arcsin(ratio))
arccosd = lambda ratio: np.rad2deg(np.arccos(ratio))

class SunAtLatLon():

    def __init__(self, lat: float, lon: float):
        self.lat = lat
        self.lon = lon

    @staticmethod
    def __localize_tz(when):
        if when.tzinfo is None or when.tzinfo.utcoffset(when) is None:
            local_tz = tzlocal.get_localzone()
            tz = pytz.timezone(local_tz._zone.key)
            when = tz.localize(when)
        return when, when.tzinfo.zone

    def at_datetime(self, when: datetime):
        # code implement from
        # https://www.pveducation.org/pvcdrom/properties-of-sunlight/elevation-angle

        when, tzinfo = self.__localize_tz(when)
        tz = pytz.timezone(tzinfo)
        tz_offset_hours = when.utcoffset().seconds/60/60
        LSTM = 15*tz_offset_hours
        start_of_year = tz.localize(datetime(when.year,1,1,0,0))
        N_dt = (when-start_of_year)
        Nd = N_dt.days + 1
        B = (360/365)*(Nd-81)
        EoT = 9.87*sind(2*B)-7.53*cosd(B)-1.5*sind(B)
        TC = 4*(self.lon - LSTM) + EoT # minutes
        LST = when + timedelta(0,TC*60)
        HRA = 15*(LST.hour + LST.minute/60 + LST.second/60/60 - 12)
        delta = 23.45*sind((360/365)*(Nd-81)) # declanation
        theta = self.lat
        alpha = arcsind(sind(delta)*sind(theta) + cosd(delta)*cosd(theta)*cosd(HRA)) # elevation
        az = arccosd((sind(delta)*cosd(theta) - cosd(delta)*sind(theta)*cosd(HRA))/cosd(alpha)) # azimuth uncorrected
        azimuth = az if HRA <0 else 360 - az
        elevation = alpha

        return {'azimuth':azimuth, 'elevation':elevation}


import torch
import numpy as np
from matplotlib import pyplot as plt

path = "two-spiral traing data(update).txt"

def plot_data(data, ax, lw=0.5, clr0='b', clr1='r'):
    ax.set_facecolor('darkgray')
    idx1 = np.where(data[:, 2] == 1)[0]
    ax.scatter(data[idx1, 0], data[idx1, 1], c=clr1, linewidths=lw)
    idx0 = np.where(data[:, 2] == 0)[0]
    ax.scatter(data[idx0, 0], data[idx0, 1], c=clr0, linewidths=lw)

def plot_decision_boundary(net, ax, lw=0.1):
    ax.set_facecolor('darkgray')
    indexs = np.linspace(-6.5, 6.5, num=100).astype(float)
    X, Y = np.meshgrid(indexs, indexs)
    input_ = np.dstack((X, Y)).reshape(-1, 2)
    input_ = torch.tensor(input_, dtype=torch.float, requires_grad=False)
    out_ = net(input_).detach().numpy()

    x, y = X.flatten(), Y.flatten()
    idx0 = np.where(out_ > 0)[0]
    ax.scatter(x[idx0], y[idx0], c='w', linewidths=lw)
    idx1 = np.where(out_ < 0)[0]
    ax.scatter(x[idx1], y[idx1], c='k', linewidths=lw)

def load_data_with_partition(partition=False):
    """
    devide the origin problem into n*n sub-problems
    """
    lines = open(path).readlines()
    n = len(lines)
    data = np.zeros((n, 3), dtype=np.float)
    for i in range(n):
        data[i] = np.array([float(j) for j in lines[i].split()])

    if not partition:
        return torch.tensor(data, dtype=torch.float)

    idx0 = np.where(data[:, 2] == 0)[0]
    idx1 = np.where(data[:, 2] == 1)[0]

    np.random.shuffle(idx0)
    np.random.shuffle(idx1)

    # step0, step1 = len(idx0) // npart, len(idx1) // npart
    #
    # data_part = []
    # for i in range(0, len(idx0)-step0, step0):
    #     for j in range(0, len(idx1)-step1, step1):
    #         idx = np.append(idx0[i: i + step0], idx1[j: j + step1])
    #         sub_data = data[idx]
    #         np.random.shuffle(sub_data)
    #         data_part.append(sub_data)
    mid0, mid1 = len(idx0) // 2, len(idx1) // 2

    data_part0 = data[idx0[0: mid0]]
    data_part1 = data[idx0[mid0 + 1:]]
    data_part2 = data[idx1[0: mid1]]
    data_part3 = data[idx1[mid1 + 1:]]
    data_part = [data_part0, data_part1, data_part2, data_part3]

    sub_data0 = np.append(data_part0, data_part2, axis=0)
    sub_data1 = np.append(data_part0, data_part3, axis=0)
    sub_data2 = np.append(data_part1, data_part2, axis=0)
    sub_data3 = np.append(data_part1, data_part3, axis=0)
    sub_data = [sub_data0, sub_data1, sub_data2, sub_data3]

    return data_part, sub_data

if __name__ == "__main__":
    # data_part, sub_data = load_data_with_partition(True, 2)
    # fig1 = plt.figure()
    # fig2 = plt.figure()
    # for i in range(len(data_part)):
    #     ax = fig1.add_subplot(2, 2, i + 1)
    #     plot_data(data_part[i], ax)
    #
    # for i in range(len(sub_data)):
    #     ax = fig2.add_subplot(2, 2, i + 1)
    #     plot_data(sub_data[i], ax)

    plt.show()


from typing import Any, Callable, Mapping, Optional, Union

import re

from speech.norm.num import (
    digits_to_text,
    float_to_text,
    floats_to_text,
    number_to_text,
    numbers_to_text,
    number_to_ordinal,
    numbers_to_ordinal,
    year_to_text,
    years_to_text,
)

# Each voice module in the directory speech/voices can define a
# 'Normalization' class as a subclass of 'DefaultNormalization' in
# order to override normalization functions/methods for a particular voice
NORMALIZATION_CLASS = "Normalization"

def strip_markup(text: str) -> str:
    """Remove HTML/SSML tags from a string."""
    return re.sub(r"<.*?>", "", text)

def gssml(data: Any = None, *, type: str, **kwargs: Union[str, int, float]) -> str:
    """
    Utility function, surrounds data with Greynir-specific
    voice normalizing tags.
    E.g. '<greynir ...>{data}</greynir>'
      or '<greynir ... />' if data is None.

    Type specifies the type of handling needed when the tags are parsed.
    The kwargs are then passed to the handler functions as appropriate.

    The greynir tags can be handled/normalized
    in different ways depending on the voice engine used.

    Example:
        gssml(43, type="number", gender="kk") -> '<greynir type="number" gender="kk">43</greynir>'
    """
    assert type and isinstance(
        type, str
    ), f"type keyword arg must be non-empty string in function gssml; data: {data}"
    return (
        f'<greynir type="{type}"'
        + "".join(f' {k}="{v}"' for k, v in kwargs.items())
        + (f">{data}</greynir>" if data is not None else f" />")
    )

# Spell out how character names are pronounced in Icelandic
_CHAR_PRONUNCIATION: Mapping[str, str] = {
    "a": "a",
    "á": "á",
    "b": "bé",
    "c": "sé",
    "d": "dé",
    "ð": "eð",
    "e": "e",
    "é": "é",
    "f": "eff",
    "g": "gé",
    "h": "há",
    "i": "i",
    "í": "í",
    "j": "joð",
    "k": "ká",
    "l": "ell",
    "m": "emm",
    "n": "enn",
    "o": "o",
    "ó": "ó",
    "p": "pé",
    "q": "kú",
    "r": "err",
    "s": "ess",
    "t": "té",
    "u": "u",
    "ú": "ú",
    "v": "vaff",
    "w": "tvöfalt vaff",
    "x": "ex",
    "y": "ufsilon",
    "ý": "ufsilon í",
    "þ": "þoddn",
    "æ": "æ",
    "ö": "ö",
    "z": "seta",
}

def spell_out(s: str) -> str:
    """Spell out a sequence of characters, e.g. "LTB" -> "ell té bé".
    Useful for controlling speech synthesis of serial numbers, etc."""
    if not s:
        return ""
    t = [_CHAR_PRONUNCIATION.get(c.lower(), c) if not c.isspace() else "" for c in s]
    return " ".join(t).replace("  ", " ").strip()

_MONTH_ABBREVS = (
    "jan",
    "feb",
    "mar",
    "apr",
    "maí",
    "jún",
    "júl",
    "ágú",
    "sep",
    "okt",
    "nóv",
    "des",
)
_MONTH_NAMES = (
    "janúar",
    "febrúar",
    "mars",
    "apríl",
    "maí",
    "júní",
    "júlí",
    "ágúst",
    "september",
    "október",
    "nóvember",
    "desember",
)
_DATE_REGEXES = (
    # Matches e.g. "1986-03-07"
    re.compile(r"(?P<year>\d{1,4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"),
    # Matches e.g. "1/4/2001"
    re.compile(r"(?P<day>\d{1,2})/(?P<month>\d{1,2})/(?P<year>\d{1,4})"),
    # Matches e.g. "25. janúar 1999" or "25 des."
    re.compile(
        r"(?P<day>\d{1,2})\.? ?"
        r"(?P<month>(jan(úar|\.)?|feb(rúar|\.)?|mar(s|\.)?|"
        r"apr(íl|\.)?|maí\.?|jún(í|\.)?|"
        r"júl(í|\.)?|ágú(st|\.)?|sep(tember|\.)?|"
        r"okt(óber|\.)?|nóv(ember|\.)?|des(ember|\.)?))"  # 'month' capture group ends
        r"( (?P<year>\d{1,4}))?",  # Optional
        flags=re.IGNORECASE,
    ),
)

# Break strength values:
# none: No pause should be outputted. This can be used to remove a pause that would normally occur (such as after a period).
# x-weak: No pause should be outputted (same as none).
# weak: Treat adjacent words as if separated by a single comma (equivalent to medium).
# medium: Treat adjacent words as if separated by a single comma.
# strong: Make a sentence break (equivalent to using the s tag).
# x-strong: Make a paragraph break (equivalent to using the p tag).
_STRENGTHS = frozenset(("none", "x-weak", "weak", "medium", "strong", "x-strong"))

NormMethod = Callable[..., str]

class DefaultNormalization:
    """
    Class containing default text normalization functions
    for Icelandic speech synthesis.
    """

    # TODO
    # amount/s
    # currency/ies
    # distance/s

    @classmethod
    def number(cls, txt: str, **kwargs: str) -> str:
        """Voicify a number."""
        return number_to_text(txt, **kwargs)

    @classmethod
    def numbers(cls, txt: str, **kwargs: str) -> str:
        """Voicify text containing multiple numbers."""
        return numbers_to_text(txt, **kwargs)

    @classmethod
    def float(cls, txt: str, **kwargs: str) -> str:
        """Voicify a float."""
        return float_to_text(txt, **kwargs)

    @classmethod
    def floats(cls, txt: str, **kwargs: str) -> str:
        """Voicify text containing multiple floats."""
        return floats_to_text(txt, **kwargs)

    @classmethod
    def ordinal(cls, txt: str, **kwargs: str) -> str:
        """Voicify an ordinal."""
        return number_to_ordinal(txt, **kwargs)

    @classmethod
    def ordinals(cls, txt: str, **kwargs: str) -> str:
        """Voicify text containing multiple ordinals."""
        return numbers_to_ordinal(txt, **kwargs)

    @classmethod
    def digits(cls, txt: str) -> str:
        """Spell out digits."""
        return digits_to_text(txt)

    @classmethod
    def phone(cls, txt: str) -> str:
        """Spell out digits."""
        return cls.digits(txt)

    @classmethod
    def time(cls, txt: str) -> str:
        """
        Voicifies time of day, specified as 'HH:MM'.
        E.g.
            "11:34" -> "ellefu þrjátíu og fjögur",
            "00:30" -> "tólf þrjátíu um nótt"
        Note: doesn't check for incorrect data, caller should handle.
        """
        h, m = [int(i) for i in txt.split(":")]
        suffix: Optional[str] = None
        # Some times
        if h == 0:
            # Call 00:00 "tólf á miðnætti"
            # and 00:xx "tólf ... um nótt"
            h = 12
            suffix = "á miðnætti" if m == 0 else "um nótt"
        elif 0 < h <= 5:
            suffix = "um nótt"
        elif h == 12 and m == 0:
            suffix = "á hádegi"
        t = [
            number_to_text(h, case="nf", gender="hk"),
        ]
        if m > 0:
            if m < 10:
                # e.g. "þrettán núll fjögur"
                t.append("núll")
            t.append(number_to_text(m, case="nf", gender="hk"))
        if suffix:
            t.append(suffix)
        return " ".join(t)

    @classmethod
    def date(cls, txt: str, case: str = "nf") -> str:
        """
        Voicifies dates specified in either
            'YYYY-MM-DD' (ISO 8601 format),
            'DD/MM/YYYY' or
            'DD. month[ YYYY]'
        Note: doesn't check for incorrect numbers,
            as that should be handled by caller.
        """
        # Get first fullmatch from date regexes
        m = next(
            filter(
                lambda x: x is not None,
                (r.fullmatch(txt) for r in _DATE_REGEXES),
            ),
            None,  # Default if no matches are found
        )
        assert m is not None, f"Incorrect date format specified for date handler: {txt}"

        # Handle 'DD/MM/YYYY' or 'MM. jan/feb/... [year]' match
        gd = m.groupdict()
        day = number_to_ordinal(gd["day"], gender="kk", case=case, number="et")
        mon: str = gd["month"]
        # Month names don't change in different declensions
        month = (
            _MONTH_NAMES[int(mon) - 1]  # DD/MM/YYYY specification
            if mon.isdecimal()
            else _MONTH_NAMES[_MONTH_ABBREVS.index(mon[:3])]  # Non-decimal
        )
        return (
            f"{day} {month} {year_to_text(gd['year'])}"
            if gd["year"]
            else f"{day} {month}"
        )

    @classmethod
    def timespan(cls, seconds: str) -> str:
        """Voicify a span of time, specified in seconds."""
        # TODO: Replace time_period_desc in queries/util/__init__.py
        raise NotImplementedError()

    @classmethod
    def year(cls, txt: str, *, after_christ: Optional[str] = None) -> str:
        """Voicify a year."""
        ac = after_christ is not None and after_christ == "True"
        return year_to_text(txt, after_christ=ac)

    @classmethod
    def years(cls, txt: str, *, after_christ: Optional[str] = None) -> str:
        """Voicify text containing multiple years."""
        ac = after_christ is not None and after_christ == "True"
        return years_to_text(txt, after_christ=ac)

    # Pronunciation of character names in Icelandic
    _CHAR_PRONUNCIATION: Mapping[str, str] = {
        "a": "a",
        "á": "á",
        "b": "bé",
        "c": "sé",
        "d": "dé",
        "ð": "eð",
        "e": "e",
        "é": "é",
        "f": "eff",
        "g": "gé",
        "h": "há",
        "i": "i",
        "í": "í",
        "j": "joð",
        "k": "ká",
        "l": "ell",
        "m": "emm",
        "n": "enn",
        "o": "o",
        "ó": "ó",
        "p": "pé",
        "q": "kú",
        "r": "err",
        "s": "ess",
        "t": "té",
        "u": "u",
        "ú": "ú",
        "v": "vaff",
        "w": "tvöfaltvaff",
        "x": "ex",
        "y": "ufsilon",
        "ý": "ufsilon í",
        "þ": "þoddn",
        "æ": "æ",
        "ö": "ö",
        "z": "seta",
    }

    @classmethod
    def spell(cls, txt: str) -> str:
        """Spell out a sequence of characters."""
        if not txt:
            return ""
        t = [
            cls._CHAR_PRONUNCIATION.get(c.lower(), c) if not c.isspace() else ""
            for c in txt
        ]
        return ", ".join(t)

    @classmethod
    def abbrev(cls, txt: str) -> str:
        """Spell out a sequence of characters."""
        return cls.spell(txt)

    _DOMAIN_PRONUNCIATIONS: Mapping[str, str] = {
        "is": "is",
        "org": "org",
        "net": "net",
        "com": "komm",
        "gmail": "gjé meil",
        "hotmail": "hott meil",
        "yahoo": "ja húú",
        "outlook": "átlúkk",
    }

    @classmethod
    def email(cls, txt: str) -> str:
        """Voicify emails."""
        user, domain = txt.split("@")
        user_parts = user.split(".")
        domain_parts = domain.split(".")
        for i, p in enumerate(user_parts):
            if len(p) < 3:
                # Short parts of username get spelled out
                user_parts[i] = cls.spell(p)
        for i, p in enumerate(domain_parts):
            if p in cls._DOMAIN_PRONUNCIATIONS:
                domain_parts[i] = cls._DOMAIN_PRONUNCIATIONS[p]
            elif len(p) <= 3:
                # Spell out short, unknown domains
                domain_parts[i] = cls.spell(p)
        return f"{' punktur '.join(user_parts)} hjá {' punktur '.join(domain_parts)}"

    @classmethod
    def vbreak(cls, time: Optional[str] = None, strength: Optional[str] = None) -> str:
        """Create a break in the voice/speech synthesis."""
        if time:
            return f'<break time="{time}" />'
        if strength:
            assert strength in _STRENGTHS, f"Break strength {strength} is invalid."
            return f'<break strength="{strength}" />'
        return f"<break />"

    @classmethod
    def paragraph(cls, txt: str) -> str:
        return f"<p>{txt}</p>"

    @classmethod
    def sentence(cls, txt: str) -> str:
        return f"<s>{txt}</s>"


class Solution:
	def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
		import collections
		dict1 = collections.defaultdict(int)
		if not root:
			return []

		def dfs(root):
			if not root:
				return 0
			num = root.val + dfs(root.left) + dfs(root.right)
			dict1[num] += 1
			return num

		dfs(root)
		maxnum = None
		result = []
		for i,v in sorted(dict1.items(),key = lambda x:x[1],reverse = True):
			if maxnum is None:
				maxnum = v
			if v == maxnum:
				result.append(i)
			else:
				break
		return result

	#Record the sum of the elements of each subtree,
	#and then sort from largest to smallest


import os
from datetime import datetime

from pytorch_lightning.callbacks.progress import TQDMProgressBar
from pytorch_lightning.callbacks import ModelCheckpoint
from torchinfo import summary

import data
from models.ssgan import SSGAN
from models.cgan import CGAN

import pytorch_lightning as pl

def set_env():
    # The slurm job id is used to set the run name on tensorboard.
    os.environ["SLURM_JOB_ID"] = datetime.now().strftime("%Y%m%d%H%M%S")

def main():
    set_env()

    img_size = (128, 128)
    latent_size = 256

    datamodule = data.BreastCancerDataModule(batch_size=64, num_workers=0, preload=True)
    model = CGAN(latent_size=latent_size, lr=3e-4)

    summary(model.generator, input_size=(1, latent_size,))
    summary(model.discriminator, input_size=[(1, 1, *img_size), (1,)])

    checkpoint_callback = ModelCheckpoint(
        save_top_k=2, monitor="accuracy/real/val", save_last=True
    )
    trainer = pl.Trainer(
        accelerator='gpu',
        devices=1,
        max_epochs=100,
        callbacks=[checkpoint_callback, TQDMProgressBar()],
    )
    trainer.fit(model, datamodule)

if __name__ == "__main__":
    main()


import pyttsx3 as pt
import PyPDF2 as pdf

book = open('Notice.pdf', 'rb')

reader = pdf.PdfFileReader(book)
pages = reader.numPages
print(pages)
speaker = pt.init()

speed = speaker.getProperty("rate")
speaker.setProperty("rate", 150)
page = reader.getPage(0)
text = page.extractText()

speaker.say(text)
speaker.runAndWait()


import sys, os
from termcolor import colored, cprint
from wordfreq import word_frequency
import matplotlib.pyplot as plt

from utils import *

os.system("color")

CHANCES = 5
WORD_LENGTH = 5
#ANSWER_WORD = "steal"
GRAY, YELLOW, GREEN = 0, 1, 3
# FORMAT BITMAPY: 5 x 2 bity
# ZIELONY 3 - ŻÓŁTY 1 - SZARY 0
# np GreenYellowGrayGreenGreen = 11 01 00 11 11

#NIEUŻYWANE | mamy termcolor
def map_colors(color_int):
    if color_int == 0: return "GRAY"
    elif color_int == 1: return "YELLOW"
    elif color_int == 3: return "GREEN"

def print_colored_input(input_word, colors):
    input_word_letters = list(input_word)
    for i in range(WORD_LENGTH):
        if colors[i] == GRAY:
            cprint(input_word_letters[i], "white", "on_red", end="")
        elif colors[i] == GREEN:
            cprint(input_word_letters[i], "white", "on_green", end="")
        else:
            cprint(input_word_letters[i], "white", "on_yellow", end="")
    #print()

#mode["entropy"]
def run(answer):
    global words, first_guess
    if not first_guess:
        first_guess = find_best_guess(words)[0]

    score = 0
    new_words = words.copy()

    while score < 6:
        guess = find_best_guess(new_words)[0] if score > 0 else first_guess
        colors = check_conditions(answer, guess)
        score += 1
        print_colored_input(guess, colors2table(colors))
        if check_win_condition(colors):
            print()
            return score
        if guess in new_words:
            new_words.remove(guess)
        new_words = reduce(guess, colors, new_words)
        print(f" [{len(new_words)}] words left")

#mode["random"]
def run_random(answer):
    global words, first_guess

    score = 0
    new_words = words.copy()

    while score < 6:
        guess = random.choice(new_words)
        colors = check_conditions(answer, guess)
        score += 1
        print_colored_input(guess, colors2table(colors))
        if check_win_condition(colors):
            print()
            return score
        new_words.remove(guess)
        new_words = reduce(guess, colors, new_words)
        print(f" [{len(new_words)}] words left")

#mode["common"]
def run_most_common_word(answer):
    global words, first_guess
    new_words = assign_frequencies(words)

    score = 0

    while score < 6:
        guess = new_words[-1]
        colors = check_conditions(answer, guess)
        score += 1
        print_colored_input(guess, colors2table(colors))
        if check_win_condition(colors):
            print()
            return score
        new_words.remove(guess)
        new_words = reduce(guess, colors, new_words)
        print(f" [{len(new_words)}] words left")

#mode["letters"]
def run_best_letter(answer):
    global words
    new_words = order_by_letters(words)
    score = 0

    while score < 6:
        guess = new_words[0]
        colors = check_conditions(answer, guess)
        score += 1
        print_colored_input(guess, colors2table(colors))
        if check_win_condition(colors):
            print()
            return score
        new_words.remove(guess)
        new_words = reduce(guess, colors, new_words)
        print(f" [{len(new_words)}] words left")

#entropia v2
#nie działa bez load_LUT(True) w utils.py
def run_large(answer):
    global words, first_guess
    first_guess = "tares"
    return run(answer)

#entropia v3
def run_2_layer(answer):
    global words, first_guess
    first_guess = "crony" #TO NIE JEST NAJLEPSZE SŁOWO
    return run(answer)

#Wersja gry z user input
def play(answer_word):
    print("Dawaj 5 literowe slowo")

    for _ in range(CHANCES):
        input_word = ""
        while True:
            input_word = input()
            if (len(input_word) == WORD_LENGTH):
                break
            else:
                print("Zla dlugosc")

        # sprawdzamy wszystkie warunki
        colors = check_conditions(answer_word, input_word)
        print_colored_input(input_word, colors2table(colors))
        if check_win_condition(colors):
            print("Win")
            return

#częstotliwość słow w języku angielskim
def assign_frequencies(words):
    words_assigned = {}
    for word in words:
        probability = word_frequency(word, 'en')
        words_assigned[word] = probability
    # define dict

    # open file for writing
    sorted_words = dict(sorted(words_assigned.items(), key=lambda item: item[1]))

    return list(sorted_words.keys())

#coś tam do tej sigmy
def interpolate():
    increment = 7/  len(sorted_words) # tą 7 mozna mzieniac
    i = 0
    interpolated_words = {}
    for word in sorted_words:
        x = -8 + increment * i*2 #  Tu -8 i i*2 tez mozna zmieniac zeby modyfikowac predkosc wzrostu grafu / przesunięcie wartości lewo prawo
        interpolated_words[word] = x
        i+=1
    for word in interpolated_words:
        x=1/(1+math.e**-interpolated_words[word])
        interpolated_words[word]=x
    #DEBUG
    #values = interpolated_words.values()
    # open file for writing
    #f = open("interpolated_twice.txt", "w")

    # write file
    #f.write(str(interpolated_words))

    # close file
    #f.close()
    #plt.plot(values)
    #plt.show()
    return interpolated_words

if __name__ == '__main__':
    first_guess = 'raise'
    words = load_words()

    #Wybór strategii za pomocą argv[1]
    modes = {
    "entropy":(run, "Wybór maksymalizujący entropię", "entropy.png"),
    "common":(run_most_common_word, "Wybór najczęstszego słowa", "common.png"),
    "random": (run_random, "Losowane słowa", "random.png"),
    "letters": (run_best_letter, "Wybór według najczęstszych liter", "letters.png"),
    "entropy_large": (run_large, "Wybór maksymalizujący entropię w pełnym zestawie\n", "entropy_large.png"),
    "2_layer": (run_2_layer, "Wybór maksymalizujący entropię 2 razy wgłąb\n", "entropy_2_layer.png")
    }

    algorithm,plot_title,plot_name = modes[sys.argv[1]]

    #Tabela wyników
    distribution = [0,0,0,0,0,0,0]

    #Symulacja gry
    for i,answer in enumerate(words):
        print(f"Game {i}")
        score = algorithm(answer)
        if score:
            distribution[score-1] += 1
            print(f"Score: {score} | {distribution}")
        else:
            print("Failed")
            distribution[-1] += 1

    #Dane końcowe
    acceptable_results = [1,2,3,4,5,6,7]
    avg_score = weighted_average(acceptable_results, distribution, 2)
    print(f"Average score: {avg_score} Failures: {distribution[-1]}")

    plt.bar(acceptable_results, distribution)
    plt.title(f"{plot_title} - Średnia: {avg_score} - Porażki: {distribution[-1]}")
    plt.xlabel("Liczba prób")
    plt.ylabel("Liczba wystąpień")
    plt.savefig(f"./graphs/{plot_name}")
    plt.show()


from setuptools import setup, find_packages
import sys, os

here = os.path.abspath(os.path.dirname(__file__))
try:
    README = open(os.path.join(here, 'README.rst')).read()
except IOError:
    README = ''

version = "0.3.0"

test_requirements = [
  'nose',
  'webtest<=2.0.24',
]

setup(name='tgext.mailer',
      version=version,
      description="TurboGears extension for sending emails with transaction manager integration",
      long_description=README,
      classifiers=[
        "Environment :: Web Environment",
        "Framework :: TurboGears"
      ],
      keywords='turbogears2.extension',
      author='Alessandro Molina',
      author_email='amol@turbogears.org',
      url='https://github.com/amol-/tgext.mailer',
      license='MIT',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tgext.mailer.tests']),
      namespace_packages = ['tgext'],
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          "TurboGears2 >= 2.3.2",
          "repoze.sendmail == 4.3",
      ],
      extras_require={
           # Used by Travis and Coverage due to setup.py nosetests
           # causing a coredump when used with coverage
           'testing': test_requirements,
      },
      test_suite='nose.collector',
      tests_require=test_requirements,
      entry_points="""
      # -*- Entry points: -*-
      """,
      )


import matplotlib.pyplot as plt

# Given list of words and counts
word_frequencies = {
    'video evidence': 69,
    'scientific evidence': 37,
    'photo evidence': 34,
    'statistical evidence': 17,
    'source verification': 16,
    'event date': 13,
    'source credibility': 12,
    'verification source': 11,
    'source reliability': 9,
    'voting record': 9,
    'news source': 9,
    'speech verification': 8,
    'official confirmation': 8,
    'data source': 7,
    'policy specifics': 7
}
# Sort the words by count for better visualization
sorted_words = dict(sorted(word_frequencies.items(), key=lambda item: item[1], reverse=True))

# Create a bar graph
plt.figure(figsize=(10,8))
plt.barh(list(sorted_words.keys()), list(sorted_words.values()), color='skyblue')
plt.xlabel('Count')
plt.ylabel('ngram')
plt.title('2-Gram Graph Prompt 2')
plt.yticks(fontsize=12)
plt.gca().invert_yaxis()  # Invert y-axis to have the word with the highest count at the top
plt.show()


from dataloader.dataset import *
from utils.utility import *
from utils.resume import *
from models.model import *
from loss.seg_loss import *
from torch.autograd import Variable
from scipy import ndimage
import copy
import cv2

from argparse import *
import yaml

class StreamSegMetrics():
    """
    Stream Metrics for Semantic Segmentation Task
    """
    def __init__(self, n_classes):
        self.n_classes = n_classes
        self.confusion_matrix = np.zeros((n_classes, n_classes))

    def update(self, label_trues, label_preds):
        for lt, lp in zip(label_trues, label_preds):
            self.confusion_matrix += self._fast_hist( lt.flatten(), lp.flatten() )

    @staticmethod
    def to_str(results):
        string = "\n"
        for k, v in results.items():
            if k!="Class IoU":
                string += "%s: %f\n"%(k, v)

        return string

    def _fast_hist(self, label_true, label_pred):
        mask = (label_true >= 0) & (label_true < self.n_classes)
        hist = np.bincount(
            self.n_classes * label_true[mask].astype(int) + label_pred[mask],
            minlength=self.n_classes ** 2,
        ).reshape(self.n_classes, self.n_classes)
        return hist

    def get_results(self):
        """Returns accuracy score evaluation result.
            - overall accuracy
            - mean accuracy
            - mean IU
            - fwav IOU
        """
        hist = self.confusion_matrix
        acc = np.diag(hist).sum() / hist.sum()
        acc_cls = np.diag(hist) / hist.sum(axis=1)
        acc_cls = np.nanmean(acc_cls)
        iu = np.diag(hist) / (hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist))
        mean_iu = np.nanmean(iu)
        freq = hist.sum(axis=1) / hist.sum()
        fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()
        cls_iu = dict(zip(range(self.n_classes), iu))

        return {
                "Overall Acc": acc,
                "Mean Acc": acc_cls,
                "FreqW IoU": fwavacc,
                "Mean IoU": mean_iu,
                "Class IoU": cls_iu
            }

    def reset(self):
        self.confusion_matrix = np.zeros((self.n_classes, self.n_classes))

def write_seq_images(opt, input_imgs, input_mask, predicted, idx,key,metrics):
    def _func(x):
        return (x.numpy()*255).astype(np.uint8).transpose(1,2,0).squeeze()

    base_num = idx * input_imgs.shape[0]

    mask_refine = opt.writer.refiner.bin(predicted)

    input_imgs = scale_img_back(input_imgs, device=opt.gpu)
    input_imgs, input_mask, predicted = input_imgs.cpu(), input_mask.cpu(), predicted.cpu()
    mask_refine = mask_refine.cpu()

    mask_raw = copy.deepcopy(predicted)
    mask_raw[mask_raw >= 0.5] = 1
    mask_raw[mask_raw < 0.5] = 0

    mask_out = input_imgs * mask_refine

    for i, (img, mask, out, maskout,raw,refine) in enumerate(zip(input_imgs, input_mask, predicted,mask_out,mask_raw,mask_refine)):

        metrics.update(mask.numpy().transpose(1,2,0).squeeze(),refine.numpy().transpose(1,2,0).squeeze())

        img = cv2.cvtColor(_func(img), cv2.COLOR_RGB2BGR)
        maskout = cv2.cvtColor(_func(maskout), cv2.COLOR_RGB2BGR)
        mask = _func(mask)
        out = _func(out)
        raw = _func(raw)
        refine = _func(refine)

        dump_folder = os.path.join(opt.dump_folder,str(base_num+i))

        if not os.path.exists(dump_folder):
            os.mkdir(dump_folder)

        cv2.imwrite(join(dump_folder, key+"_img_%04d"%(base_num+i)+ ".png"), img)
        cv2.imwrite(join(dump_folder, key+"_gt_%04d"%(base_num+i)+ ".png"), mask)
        cv2.imwrite(join(dump_folder, key+"_refine_%04d"%(base_num+i)+ ".png"), refine)
        cv2.imwrite(join(dump_folder, key+"_maskout_%04d"%(base_num+i)+ ".png"), maskout)

def validate(opt,key):
    metrics = StreamSegMetrics(2)
    metrics.reset()
    opt.G.eval()
    opt.writer.reset()
    with torch.no_grad():
        for idx, (input_imgs, input_mask) in enumerate(opt.val_loader):

            input_imgs = input_imgs.cuda(opt.gpu)
            predicted = opt.G(input_imgs)
            write_seq_images(opt, input_imgs, input_mask, predicted, idx,key,metrics)

            predicted_ = predicted.cpu().numpy().repeat(3,axis=1)
            input_imgs = input_imgs.cpu().numpy()

        score = metrics.get_results()
        print(metrics.to_str(score))

def folder_init(opt):
    ''' tensorboard initialize: create tensorboard filename based on time tick and hyper-parameters

        Args:
            opt: parsed options from cmd or .yml(in config/ folder)

        Returns:
            opt: add opt.dump_folder and return opt

    '''

    return opt

def init_settings(opt, data_path):
    torch.backends.cudnn.benchmark = True
    torch.cuda.manual_seed(1124)
    opt.gpu = torch.device(opt.device_id)
    opt.dice_criterion = DiceLoss().cuda(opt.gpu)
    opt.bce_criterion = nn.BCEWithLogitsLoss().cuda(opt.gpu)
    opt.self_op = SelfOperation(opt)

    opt = init_models(opt)
    opt = init_dataset(opt, data_path)
    opt = folder_init(opt)
    opt.writer = TensorWriter(opt)

    opt.ones = torch.ones(opt.batch_size).cuda(opt.gpu)
    opt.zeros = torch.zeros(opt.batch_size).cuda(opt.gpu)

    return opt

def init_models(opt):
    # model init
    generator = ModelFactory(opt)
    generator.register_hook_model(get_generator_model)
    generator.register_hook_optimizer(get_ralamb_optimizer)

    opt.G, opt.optim_G, opt.sche_G = generator()

    return opt

def init_dataset(opt, data_path):

    opt.portrait_val = SegmentationDataset(opt, split="test", folder=data_path)
    opt.val_loader =  DataLoader(opt.portrait_val, collate_fn=segmentation_collate_fn, batch_size=opt.batch_size, shuffle=False, pin_memory=True,num_workers=4)
    return opt

## option args
def parse_opts():
    parser = ArgumentParser(description="segmentation")
    parser.add_argument('--hyper_setting', default='config/dynamic_config.yml',type=str,help="hyper-parameters of experiments")
    parser.add_argument('--device_id', default=2, type=int,help="CUDA device.")
    parser.add_argument('--comments', default="mask_together", type=str)

    opt =  parser.parse_args()

    hyper_opt = yaml.safe_load(open(opt.hyper_setting,"r"))
    opt = Namespace(**hyper_opt,**vars(opt))
    return opt

def main():
    current_folder = os.getcwd()
    pretrain_model_dir = os.path.join(current_folder,'pretrain')
    dump_dir = os.path.join(current_folder,'result')
    key_list = ["pa"]

    opt = parse_opts()

    data_folder = os.path.join(current_folder,'datasets')

    experiment_mapp = {
        'test': {'name':'test',
                 'data':data_folder},
    }
    opt = parse_opts()

    for k, item in experiment_mapp.items():

        experiment_name = item['name']
        data_path = item['data']

        experiment_name = experiment_name
        opt.experiment_name = experiment_name

        print("method-->",k)

        for key in key_list:

            opt.dump_folder = join(dump_dir,k, key)

            if not os.path.exists(opt.dump_folder):
                os.makedirs(opt.dump_folder)

            opt = init_settings(opt,data_path)

            opt.G = Resume(pretrain_model_dir,experiment_name).resume_model(opt.G, model_path=None, key=key, state=False)
            opt.G.cuda(opt.gpu)
            validate(opt,key)

    opt.writer.close()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("ctrl + c ")


from keras.models import load_model
import cv2
import numpy as np
import sys

input = sys.argv[1]
output = sys.argv[2]

model = './u2netp_keras.h5'

# load model
u2netp_keras = load_model(model, compile=False)

# load image
image = cv2.imread(input)

# convert to array
blob = cv2.dnn.blobFromImage(image, 1.0/255, (320, 320), (0, 0, 0), swapRB=True, crop=False)

# predict
d1,d2,d3,d4,d5,d6,d7 = u2netp_keras.predict(blob)
pred = np.array(d1[:,0,:,:])[0]

# normalize
ma = np.max(pred)
mi = np.min(pred)
pred = (pred-mi)/(ma-mi)

pred = pred.squeeze()

pred = (pred*255).astype(np.uint8)

mask = cv2.resize(pred, image.shape[1::-1], interpolation=cv2.INTER_CUBIC)

# create alpha channel
b, g, r = cv2.split(image)
out = cv2.merge((b, g, r, mask))

# crop image
y, x = out[:,:,3].nonzero()
minx = np.min(x)
miny = np.min(y)
maxx = np.max(x)
maxy = np.max(y)
out = out[miny:maxy, minx:maxx]

# save image
cv2.imwrite(output, out)


import pygame
import random
import os

from pygame.constants import K_k, K_w , K_s , K_a , K_d , K_u , K_h , K_j , K_k

def dasher(Two_Player,WIN,WIDHT,HEIGHT,FPS):

    max_time = 60
    timer = max_time
    dt = 0
    clock = pygame.time.Clock()

    class ball_:
        def __init__(self,size):
            self.rect = pygame.Rect(0, 0, 4*size,4*size)
            self.x_vel = 0
            self.y_vel = 0
            self.rect.y = HEIGHT - 200
            random_number = random.randint(1,2)
            if random_number == 1:
                self.rect.x = 200
            else:
                self.rect.x = WIDHT - 200

        def move(self,size):

            if self.rect.x < WIDHT / 2:
                if self.x_vel > 0 and self.rect.x + self.x_vel < WIDHT * 0.45 - size * 4:
                    self.rect.x += self.x_vel
                elif self.x_vel < 0 and self.rect.x + self.x_vel > 0:
                    self.rect.x += self.x_vel
            else:
                if self.x_vel > 0 and self.rect.x + self.x_vel < WIDHT- size * 4:
                    self.rect.x += self.x_vel
                elif self.x_vel < 0 and self.rect.x + self.x_vel > WIDHT * 0.55:
                    self.rect.x += self.x_vel

            self.rect.y += self.y_vel
            self.x_vel *= 0.8
            self.y_vel *= 0.8

        def ball_swap(self):
            if self.rect.x < WIDHT / 2:
                if self.rect.y < 5:
                    self.rect.x += WIDHT * 0.55
                    self.y_vel *= -1
            else:
                if self.rect.y < 5:
                    self.rect.x -= WIDHT * 0.55
                    self.y_vel *= -1

        def collider(self,red_player,blue_player):
            if self.rect.colliderect(red_player):
                m1, v1, m2, v2 = 100, red_player.x_vel, 0.02, ball.x_vel
                u1 = (m1 * v1 + m2 *(2*v2-v1))/(m1+m2)
                u2 = (m2 * v2 + m1 *(2*v1-v2))/(m1+m2)
                red_player.x_vel = u1
                ball.x_vel = u2
                m1, v1, m2, v2 = 100, red_player.y_vel, 0.02, ball.y_vel
                u1 = (m1 * v1 + m2 *(2*v2-v1))/(m1+m2)
                u2 = (m2 * v2 + m1 *(2*v1-v2))/(m1+m2)
                red_player.y_vel = u1
                ball.y_vel = u2
            if self.rect.colliderect(blue_player):
                m1, v1, m2, v2 = 100, blue_player.x_vel, 0.02, ball.x_vel
                u1 = (m1 * v1 + m2 *(2*v2-v1))/(m1+m2)
                u2 = (m2 * v2 + m1 *(2*v1-v2))/(m1+m2)
                blue_player.x_vel = u1
                ball.x_vel = u2
                m1, v1, m2, v2 = 100, blue_player.y_vel, 0.02, ball.y_vel
                u1 = (m1 * v1 + m2 *(2*v2-v1))/(m1+m2)
                u2 = (m2 * v2 + m1 *(2*v1-v2))/(m1+m2)
                blue_player.y_vel = u1
                ball.y_vel = u2

    class player:
        def __init__(self,team,size,x,y):
            self.rect = pygame.Rect(x,y,size* 4 , size * 8)
            self.team = team
            self.y_vel = 0
            self.x_vel = 0

        def move(self,size):

            if self.team == "blue":
                if self.x_vel > 0 and self.rect.x + self.x_vel < WIDHT * 0.45 - size * 8:
                    self.rect.x += self.x_vel
                elif self.x_vel < 0 and self.rect.x + self.x_vel > 0:
                    self.rect.x += self.x_vel
                if self.y_vel > 0 and self.rect.y + self.y_vel < HEIGHT - size * 4:
                    self.rect.y += self.y_vel
                elif self.y_vel < 0 and self.rect.y + self.y_vel > 0:
                    self.rect.y += self.y_vel

            if self.team == "red":
                if self.x_vel > 0 and self.rect.x + self.x_vel < WIDHT- size * 8:
                    self.rect.x += self.x_vel
                elif self.x_vel < 0 and self.rect.x + self.x_vel > WIDHT * 0.55:
                    self.rect.x += self.x_vel
                if self.y_vel > 0 and self.rect.y + self.y_vel < HEIGHT - size * 4:
                    self.rect.y += self.y_vel
                elif self.y_vel < 0 and self.rect.y + self.y_vel > 0:
                    self.rect.y += self.y_vel

            self.x_vel *= 0.6
            self.y_vel *= 0.6

    size = 10
    red_player = player("red", size, (((WIDHT * 0.45 ) // 2) + (WIDHT * 0.55)) - size * 4,HEIGHT - 100)
    blue_player = player("blue", size, ((WIDHT  * 0.45) // 2) - size * 2,HEIGHT - 100)
    ball = ball_(size)

    # image import
    RED_PLAYER_IMAGE = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(os.path.join('Assets_Dasher', 'Red_Team_Dasher.png')), (4*size,8*size)), 90)
    BLUE_PLAYER_IMAGE = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(os.path.join('Assets_Dasher', 'Blue_Team_Dasher.png')), (4*size,8*size)), 90)
    BACKGROUND_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join("Assets_Dasher" , "dasher_background.png")), (WIDHT,HEIGHT))
    BALL_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join("Assets_Dasher", "Ball_Dasher.png")), (4*size, 4 * size))
    CLOCK_ZERO_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_0.png')), (90,90))
    CLOCK_ONE_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_1.png')), (90,90))
    CLOCK_TWO_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_2.png')), (90,90))
    CLOCK_THREE_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_3.png')), (90,90))
    CLOCK_FOUR_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_4.png')), (90,90))
    CLOCK_FIVE_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_5.png')), (90,90))
    CLOCK_SIX_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_6.png')), (90,90))
    CLOCK_SEVEN_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_7.png')), (90,90))
    CLOCK_EIGHT_IMAGE = pygame.transform.scale(pygame.image.load(os.path.join('Assets_Global', 'clock_8.png')), (90,90))

    def draw(red_player,blue_player,ball,WIN,WIDHT,HEIGHT):
        WIN.blit(BACKGROUND_IMAGE,(0,0))
        WIN.blit(RED_PLAYER_IMAGE, (red_player.rect.x, red_player.rect.y))
        WIN.blit(BLUE_PLAYER_IMAGE, (blue_player.rect.x, blue_player.rect.y))
        WIN.blit(BALL_IMAGE, (ball.rect.x, ball.rect.y))

        timer_text = CLOCK_ZERO_IMAGE
        if timer / max_time <= (1/9)*8:
            timer_text = CLOCK_ONE_IMAGE
        if timer / max_time <= (1/9)*7:
            timer_text = CLOCK_TWO_IMAGE
        if timer / max_time <= (1/9)*6:
            timer_text = CLOCK_THREE_IMAGE
        if timer / max_time <= (1/9)*5:
            timer_text = CLOCK_FOUR_IMAGE
        if timer / max_time <= (1/9)*4:
            timer_text = CLOCK_FIVE_IMAGE
        if timer / max_time <= (1/9)*3:
            timer_text = CLOCK_SIX_IMAGE
        if timer / max_time <= (1/9)*2:
            timer_text = CLOCK_SEVEN_IMAGE
        if timer / max_time <= (1/9):
            timer_text = CLOCK_EIGHT_IMAGE

        WIN.blit(timer_text ,(WIDHT - 95, HEIGHT - 95))

        pygame.display.update()

    def movement_controller(red_player,blue_player,keys):
        Player_VEL = 5
        if keys[K_w]:
            blue_player.y_vel -= Player_VEL
        if keys[K_s]:
            blue_player.y_vel += Player_VEL
        if keys[K_a]:
            blue_player.x_vel -= Player_VEL
        if keys[K_d]:
            blue_player.x_vel += Player_VEL
        if keys[K_u]:
            red_player.y_vel -= Player_VEL
        if keys[K_j]:
            red_player.y_vel += Player_VEL
        if keys[K_h]:
            red_player.x_vel -= Player_VEL
        if keys[K_k]:
            red_player.x_vel += Player_VEL

    blue_points, red_points = 0,0

    while True:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()

        keys = pygame.key.get_pressed()
        movement_controller(red_player,blue_player,keys)

        red_player.move(size)
        blue_player.move(size)
        ball.collider(red_player,blue_player)
        ball.ball_swap()
        ball.move(size)

        timer -= dt
        if timer <= 0:
            if blue_points == red_points:
                return "None"
            elif red_points > blue_points:
                return "red"
            else:
                return "blue"
        dt = clock.tick(FPS) / 1000

        draw(red_player,blue_player,ball,WIN,WIDHT,HEIGHT)

WIDHT, HEIGHT = 800, 800
WIN = pygame.display.set_mode((WIDHT,HEIGHT))
dasher(False,WIN,WIDHT,HEIGHT,60)
pygame.quit()


from rdkit import Chem

import os.path as osp
from statistics import mode, StatisticsError
import numpy as np
import pandas as pd
import pickle

# location of unzipped GEOM dataset
true_confs_dir = '../data/DRUGS/drugs'

def clean_confs(smi, confs):
    good_ids = []
    smi = Chem.MolToSmiles(Chem.MolFromSmiles(smi), isomericSmiles=False)
    for i, c in enumerate(confs):
        conf_smi = Chem.MolToSmiles(Chem.RemoveHs(c), isomericSmiles=False)
        if conf_smi == smi:
            good_ids.append(i)
    return [confs[i] for i in good_ids]

def correct_smiles(true_confs):

    conf_smis = []
    for c in true_confs:
        conf_smi = Chem.MolToSmiles(Chem.RemoveHs(c))
        conf_smis.append(conf_smi)

    try:
        common_smi = mode(conf_smis)
    except StatisticsError:
        return None  # these should be cleaned by hand

    if np.sum([common_smi == smi for smi in conf_smis]) == len(conf_smis):
        return mode(conf_smis)
    else:
        print('consensus', common_smi)  # these should probably also be investigated manually
        return common_smi
        # return None

test_data = pd.read_csv('../data/DRUGS/test_smiles_raw.csv')
corrected_smiles_dict = {}
failed_smiles = []
for i, data in test_data.iterrows():

    smi = data.smiles

    try:
        with open(osp.join(true_confs_dir, smi.replace('/', '_') + '.pickle'), "rb") as f:
            mol_dic = pickle.load(f)
    except FileNotFoundError:
        print(f'cannot find ground truth conformer file: {smi}')
        continue

    true_confs = [conf['rd_mol'] for conf in mol_dic['conformers']]
    true_confs = clean_confs(smi, true_confs)
    if len(true_confs) == 0:
        corrected_smiles_dict[smi] = smi
        continue

    corrected_smi = correct_smiles(true_confs)
    corrected_smiles_dict[smi] = corrected_smi

    if corrected_smi is None:
        failed_smiles.append(smi)
        corrected_smiles_dict[smi] = smi
        print(f'failed: {smi}\n')

test_data['corrected_smiles'] = list(corrected_smiles_dict.values())
test_data.to_csv('../data/DRUGS/test_smiles_corrected.csv', index=False)


"""005 enrollments

Revision ID: 9c54ab0a43c5
Revises: 6d8dac873e40
Create Date: 2020-03-17 17:37:40.801390

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '9c54ab0a43c5'
down_revision = '6d8dac873e40'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('enrollments',
    sa.Column('event_id', sa.Integer(), nullable=False),
    sa.Column('participant_id', sa.Integer(), nullable=False),
    sa.Column('timestamp', sa.DateTime(), nullable=False),
    sa.ForeignKeyConstraint(['event_id'], ['events.id'], ),
    sa.ForeignKeyConstraint(['participant_id'], ['participants.id'], ),
    sa.PrimaryKeyConstraint('event_id', 'participant_id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('enrollments')
    # ### end Alembic commands ###


import uuid, datetime
import logging

from orderapp.main.model.order_dto import OrderDto
from orderapp.main.model.order_model import Order
from orderapp.main.model.product_model import Product
from orderapp.main.model.product_catalog_model import ProductCatalog
from orderapp.main.model.offer_model import Offer

from orderapp.db import db

from sqlalchemy.exc import SQLAlchemyError

#Logging configurations
logging.basicConfig(level=logging.DEBUG)

product = OrderDto.product

def save_order(order_request):
    order = lambda: None
    try:
        if order_request != None:
            order_id = str(uuid.uuid4())
            products = []
            product_request = order_request['products']

            if  product_request == None:
                raise Exception
                logging.error("Products not included in request", exc_info=True)

            catalogs =  get_all_product_catalog()
            for product in product_request:
                product_type=product['producttype']
                for catalog in catalogs:
                    if catalog.producttype == product_type:
                        product = Product(
                            producttype=product_type,
                            units=product['units'],
                            discountedunits=calculate_total_product_units_offer(requested_product_unit=product['units'],catalog_id=catalog.catalog_id),
                            order_id=order_id,
                            catalog_id=catalog.catalog_id
                        )
                        products.append(product)

            order = Order(
                username=order_request['username'],
                orderid=order_id,
                orderdate=datetime.datetime.utcnow(),
                totalordercost=round(calculate_total_order_cost(products),2),
                products=products
            )
            save_changes(order)
        else:
            order = None
    except KeyError as exp:
        raise KeyError
        logging.error("Key missing", exc_info=True)
    except SQLAlchemyError as exp:
        raise SQLAlchemyError
        logging.error("DB Error", exc_info=True)
    except Exception as exp:
        logging.error("Error occured while saving the order", exc_info=True)
    return order

def calculate_total_order_cost(products):
    try:
        order_cost=0
        if products!=None:
            for product in products:
                catalog = get_product_catalog_for_id(product.catalog_id)
                order_cost = order_cost + catalog.cost*product.units
                logging.info(order_cost)
    except AttributeError as exp:
        raise AttributeError
        logging.error("Attribute missing", exc_info=True)
    except Exception as exp:
        logging.error("Error occured while calculating the total cost", exc_info=True)
    return order_cost

#Calculates the total units to be added in the basket after applying the offers
def calculate_total_product_units_offer(requested_product_unit, catalog_id):
    number_of_products=0
    try:
        logging.info(requested_product_unit)
        if requested_product_unit != None and catalog_id != None:
            offer = get_offer_for_catalog(catalog_id)
            number_of_products = requested_product_unit + (requested_product_unit*offer.discount_fractional_value_on_unit)
    except AttributeError as exp:
        raise AttributeError
        logging.error("Attribute missing", exc_info=True)
    except Exception as exp:
        logging.error("Error occured while calculating the total cost", exc_info=True)
    return number_of_products

def save_changes(data):
    db.session.add(data)
    db.session.commit()

def get_orders():
    return Order.query.all()

def get_a_order(order_id):
    return Order.query.filter_by(orderid=order_id).first()

def get_all_product_catalog():
    return ProductCatalog.query.all()

def get_product_catalog_for_id(catalog_id):
    return ProductCatalog.query.filter_by(catalog_id=catalog_id).first()

def get_offer_for_catalog(catalog_id):
    return Offer.query.filter_by(catalog_id=catalog_id).first()


# from pudb import set_trace; set_trace()
from typing import List
from collections import defaultdict
import math
import heapq

class Solution:
    def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int:
        """Can't solve this, because my dumbass didn't realize that finding
        the path with the min weight is Dijkstra. Below I will reproduce the
        popular solution of three Dijkstras (ref: https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1844130/Python-3-Dijkstras-explained.)

        However, this solution (https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1844479/Simultaneous-Dijkstra-beats-100-(only-1-dijkstra))
        uses only one Dijkstra.

        O(ElogV + N) as according to Wikipedia. 3249 ms, 71% ranking.
        """
        # first produce two graphs, one in the original order, and the other
        # reversed order
        G1, G2 = defaultdict(list), defaultdict(list)
        for f, t, w in edges:
            G1[f].append((t, w))
            G2[t].append((f, w))  # reverse

        def Dijkstra(graph, start) -> List[int]:
            queue, weights = [(0, start)], {}
            while queue:
                w, node = heapq.heappop(queue)
                if node not in weights:  # weights always record the min weight
                    weights[node] = w
                    for child, weight in graph.get(node, []):
                        heapq.heappush(queue, (w + weight, child))
            return [weights.get(i, math.inf) for i in range(n)]

        s1toall = Dijkstra(G1, src1)
        s2toall = Dijkstra(G1, src2)
        dstoall = Dijkstra(G2, dest)

        res = min(s1toall[i] + s2toall[i] + dstoall[i] for i in range(n))
        return res if res < math.inf else -1

sol = Solution()
tests = [
    (6, [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], 0, 1, 5, 9),
    (3, [[0,1,1],[2,1,1]], 0, 1, 2, -1),
]

for i, (n, edges, src1, src2, dest, ans) in enumerate(tests):
    res = sol.minimumWeight(n, edges, src1, src2, dest)
    if res == ans:
        print(f'Test {i}: PASS')
    else:
        print(f'Test {i}; Fail. Ans: {ans}, Res: {res}')


import joblib
from flask import Flask, request, jsonify
from flask_cors import CORS
import os
from MovieReviewClassifierHelpers import preprocessor, tokenizer

app = Flask(__name__)
CORS(app)

@app.route('/predict', methods=['POST'])
def predict():
    if request.method == 'POST':
        # get our review from the request
        review = request.form.get('review')
        if review is None:
            return jsonify({"error": "Please enter a review"}), 422

        # load our classifier with joblib
        lr_classifier = joblib.load(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lr_pipeline.pkl'))

        # set up our outcome labels
        label = {0: 'negative', 1: 'positive'}

        # get our results
        result = {
            "label": label[lr_classifier.predict([review])[0]],
            "probability": str(round(lr_classifier.predict_proba([review]).max() * 100, 2))
        }
        # return as json
        return jsonify(result), 200


"""
urls for carpathians
"""

from django.urls import path
from gpsfun.carpathians.views import (
    ridges, ridge, peak, route, routes, peaks)

urlpatterns = [
    path('ridges/', ridges, name="ridges"),
    path('ridge/<slug>/', ridge, name="ridge"),
    path('peak/<slug>/', peak, name="peak"),
    path('peaks/', peaks, name="peaks"),
    path('route/<int:route_id>/', route, name="route"),
    path('', routes, name="routes"),
]


import os
import yagmail

receiver = "preethikahari2004@gmail.com"  # receiver email address
body = "Attendence File"  # email body
filename = "Attendance"+os.sep+"Attendance_2019-08-29_13-09-07.csv"  # attach the file

# mail information
yag = yagmail.SMTP("preethehari2004@gmail.com", "hari@123")

# sent the mail
yag.send(
    to=receiver,
    subject="Attendance Report",  # email subject
    contents=body,  # email body
    attachments=filename,  # file attached
)


# -*- coding: utf-8 -*-
"""
Created on Wed Jul 19 23:38:39 2023

@author: Shashank.S.Tiwari
"""

import os
import glob
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Set the folder path where the CSV files are located
folder_path = 'C:/Users/Shashank.S.Tiwari/OneDrive - Shell/Simulations/SUF_PearlGTL/40per_800TPH/16ppm_900secs/'

# Get a list of all CSV files in the folder
csv_files = glob.glob(os.path.join(folder_path, '*.out'))

# Set the DPI value for the plot (adjust as needed)
dpi = 300

# Set font options
font_size = 14
font_family = 'Arial'

# Set color palette
color_palette = 'viridis'  # Choose a color palette of your preference

# Set seaborn style
sns.set(style='ticks')

# Loop through each CSV file
for file in csv_files:
    # Read the CSV file and skip the first three lines
    df = pd.read_csv(file, delimiter=' ', skiprows=3, header=None)

    # Check the number of columns in the DataFrame
    if df.shape[1] == 4:
        # If there are four columns, drop the fourth column
        df = df.drop(columns=[3])

    # Assign column names
    df.columns = ['Time Step', 'Concentration', 'Flow-Time']

    # Convert 1.6e-5 concentration to desired amount
    df['Concentration'] *= 5.4

    # Convert concentration to ppm
    df['Concentration'] *= 1e6

    # Convert flow-time to hours
    df['Flow-Time'] /= 3600

    # Find the index where concentration reaches 16 ppm
    exposure_start = df[df['Concentration'] >= 16].iloc[0]['Flow-Time']
    exposure_end = df[df['Concentration'] >= 16].iloc[-1]['Flow-Time']

    # Calculate exposure duration
    exposure_duration = exposure_end - exposure_start

    # Generate the plot
    plt.plot(df['Flow-Time'], df['Concentration'])

    # Add a horizontal line at concentration of 16 ppm
    plt.axhline(y=16, color='red', linestyle='--')

    plt.xlabel('Flow-Time (hours)', fontsize=font_size, fontfamily=font_family)
    plt.ylabel('Concentration (ppm)', fontsize=font_size, fontfamily=font_family)
    plt.title('Flow-Time vs Concentration', fontsize=font_size, fontfamily=font_family)

    # Set font options for tick labels
    plt.xticks(fontsize=font_size-2, fontfamily=font_family)
    plt.yticks(fontsize=font_size-2, fontfamily=font_family)

    # Set x-axis limits
    plt.xlim(0, 12)
    plt.ylim(0, 50)

    # Set color palette
    sns.set_palette(color_palette)

    # Set seaborn style
    sns.set_style('ticks')

    # Find the position for the text within the plot
    text_x = exposure_start + (exposure_duration / 2)
    text_y = 16 + (max(df['Concentration']) - 16) / 3

    # # Check if the text position is too close to the curve
    # if text_y < max(df['Concentration']):
    #     text_y += (max(df['Concentration']) - text_y) / 5

    # Add the exposure duration as text on the plot
    text_to_show = f"16 ppm Exposure for {exposure_duration:.2f} hours"
    plt.text(3.8, 20, text_to_show, fontsize=10,fontfamily=font_family,
             bbox=dict(boxstyle='round,pad=0.5', facecolor='white', alpha=0.9))

    # Save the plot as a PNG image
    file_name = os.path.splitext(os.path.basename(file))[0] + '.png'
    save_path = os.path.join(folder_path, file_name)
    plt.savefig(save_path, dpi=dpi)

    # Close the plot
    plt.close()


import numpy as np
import projectq
from projectq.ops import Rx, Rz, CNOT, Measure
import matplotlib.pyplot as plt
import copy

class Trainer(object):
    def __init__(self):
        self.theta = np.random.rand(2*3*3).reshape(3, 2, 3)
        self.data = [(0, 0), (1, 0), (0, 1), (1, 1)]
        self.label = [0, 1, 1, 0]
        self.loss = []

        self.eng = projectq.MainEngine()
        self.qureg = self.eng.allocate_qureg(2)
        self.eng.flush()

    def cal_loss(self, y_model):
        loss = 0
        for i in range(len(y_model)):
            loss -= self.label[i] * np.log(y_model[i]) + (1 - self.label[i]) * np.log(1 - y_model[i])
        return loss/4

    def run(self):
        for l_index in range(len(self.theta)):
            for q_index in range(len(self.theta[l_index])):
                Rz(self.theta[l_index, q_index, 0]) | self.qureg[q_index]
                Rx(self.theta[l_index, q_index, 1]) | self.qureg[q_index]
                Rz(self.theta[l_index, q_index, 2]) | self.qureg[q_index]
            if l_index != len(self.qureg):
                CNOT | (self.qureg[0], self.qureg[1])
                CNOT | (self.qureg[1], self.qureg[0])

        self.eng.flush()
        prob = self.eng.backend.get_probability('0', [self.qureg[1]])
        return prob

    def measure(self):
        Measure | self.qureg

    def train(self):
        y_model = []
        for d in self.data:
            (a, b) = d
            a_vec = a * np.array([0, 1]) + (1 - a) * np.array([1, 0])
            b_vec = b * np.array([0, 1]) + (1 - b) * np.array([1, 0])
            wave_fun = np.kron(a_vec, b_vec)
            self.eng.backend.set_wavefunction(wave_fun, self.qureg)
            y_model.append(self.run())
            self.measure()
        c = self.cal_loss(y_model)
        return c

if __name__ == '__main__':
    # cl = Trainer()
    # theta = cl.theta.reshape(18)
    # del_theta = 0.00001
    # for iter in range(200):
    #     for i in range(len(theta)):
    #         theta[i] += del_theta
    #         cl.theta = theta.reshape(3, 2, 3)
    #         loss_plus = cl.train()
    #
    #         theta[i] += -2 * del_theta
    #         cl.theta = theta.reshape(3, 2, 3)
    #         loss_min = cl.train()
    #
    #         theta[i] += del_theta - 0.1 * (loss_plus - loss_min) / (2 * del_theta)
    #     cl.loss.append((loss_plus + loss_min)/2)
    #     print(loss_plus)
    #
    # plt.plot(cl.loss)
    # plt.xlabel('iterations')
    # plt.ylabel('loss')
    # plt.yscale('log')
    # plt.show()
    # print(cl.theta)

    x = np.arange(-5, 5, 0.01)

    plt.subplot(2, 2, 1)
    y_linear = x
    plt.plot(x, y_linear, linewidth=0.8, c='black')
    h_1 = max(y_linear)*0.8
    h_2 = max(y_linear)*0.6
    plt.text(-5, h_1, '$linear: cost: f(x) = 1 × (x > 0) - 1 × (x < 0) $', fontsize=10)
    plt.text(-4.1, h_2, '$  grad: f^{,}(x) = 1 $', fontsize=10)

    plt.subplot(2, 2, 2)
    y_relu = copy.deepcopy(x)
    y_relu[0:len(x)//2] = 0
    h_1 = max(y_relu)*0.9
    h_2 = max(y_relu)*0.8
    plt.plot(x, y_relu, linewidth=0.8, c='black')
    plt.text(-5, h_1, '$relu: cost: f(x) =  max(0, x)$', fontsize=10)
    plt.text(-4.2, h_2, '$  grad: f^{,}(x) = 0 + 1 × (x > 0) $', fontsize=10)

    plt.subplot(2, 2, 3)
    y_sigmoid = 1/(1 + np.e**(-x))
    h_1 = max(y_sigmoid)*0.9
    h_2 = max(y_sigmoid)*0.8
    plt.plot(x, y_sigmoid, linewidth=0.8, c='black')
    plt.text(-5, h_1, '$sigmoid: cost: f(x) = \dfrac{1}{1 + e^{-x}}$', fontsize=10)
    plt.text(-3.7, h_2, '$  grad: f^{,}(x) = f(x)(1-f(x)) $', fontsize=10)

    plt.subplot(2, 2, 4)
    y_tanh  = 2/(1 + np.e**(-2*x)) - 1
    h_1 = max(y_tanh)*0.8
    h_2 = max(y_tanh)*0.6
    plt.plot(x, y_tanh, linewidth=0.8, c='black')
    plt.text(-5, h_1, '$sigmoid: cost: f(x) = \dfrac{2}{1 + e^{-x}} - 1$', fontsize=10)
    plt.text(-3.7, h_2, '$  grad: f^{,}(x) = 1 - f(x)^{2} $', fontsize=10)

    plt.show()