import sys
from typing import List
import cv2
import base64
import argparse
import insightface
import numpy as np
from pathlib import Path
path_root = Path(__file__).parents[1]
sys.path.append(str(path_root))
from videoAnalytics.encoder import OutputData, encoderExtractor
from videoAnalytics.analyzer import faceAnalyzer
from videoAnalytics.logger import Logger

class processor:
    def __init__(self, detector_load_device=0, recognizer_load_device=0,face_detection_model='retinaface_r50_v1', face_recognition_model='arcface_r100_v1') -> None:
        #loading the face detection model. detector_load_device 0 means to work with GPU. -1 is for CPU.
        detector = insightface.model_zoo.get_model(face_detection_model)
        detector.prepare(ctx_id = detector_load_device, nms=0.4)

        #loading the face recognition model. recognizer_load_device 0 means to work with GPU. -1 is for CPU.
        recognizer = insightface.model_zoo.get_model(face_recognition_model)
        recognizer.prepare(ctx_id = recognizer_load_device)

        self.encoder = encoderExtractor(None, detector, recognizer)
        self.analyzer = faceAnalyzer(detector, recognizer, None)

    def b642cv2(self, in_img_b64):
        try:
            img_b64 = in_img_b64.split(',')[1]
        except:
            img_b64 = in_img_b64
        nparr = np.fromstring(base64.b64decode(img_b64), np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        return img

    def encode_images(self, input_data):
        self.encoder.set_input_data( input_data )
        result = self.encoder.process_data()
        return result

    def encode_narray_image(self, img: np.ndarray) -> List[float]:
        result = self.encoder.process_image( img )
        return result

    def encode_narray_images(self, imgs: List[np.ndarray], key: str) -> OutputData:
        result = self.encoder.process_images( imgs, key )
        return result

    def set_analyzer_dataset(self, dataset_path):
        self.analyzer.set_dataset(dataset_path)

    def analyze_image(self, dataset_path, image, return_img=False, return_landmarks=False, return_img_json=False):
        self.set_analyzer_dataset(dataset_path)
        if return_img:
            result,img = self.analyzer.analyze_img(image, return_img, return_landmarks, return_img_json)
            return result, img
        else:
            result = self.analyzer.analyze_img(image, return_img, return_landmarks, return_img_json)
            return result

    def analyze_image_2(self, image, return_img=False, return_landmarks=False, return_img_json=False):
        if return_img:
            result,img = self.analyzer.analyze_img(image, return_img, return_landmarks, return_img_json)
            return result, img
        else:
            result = self.analyzer.analyze_img(image, return_img, return_landmarks, return_img_json)
            return result

    def detect_image(self, image, return_img=False, return_landmarks=False, return_img_json=False):
        if return_img:
            result,img = self.analyzer.detect_img(image, return_img, return_landmarks, return_img_json)
            return result, img
        else:
            result = self.analyzer.detect_img(image, return_img, return_landmarks, return_img_json)
            return result

    # TODO: Work on video feed to frontend
    def analyze_video(self, dataset_path, video_source, return_img=False, return_landmarks=False, return_img_json=False, show_video=False, print_output=False, logger=None):
        self.set_analyzer_dataset(dataset_path)
        cap = cv2.VideoCapture(video_source)

        img_id = 0
        while cap.isOpened():
            ret, img_read = cap.read()
            result,img = self.analyzer.analyze_img(img_read, True, return_landmarks, return_img_json)
            if print_output and logger:
                logger.info(f'frame_{img_id}: {result}')
            img_id += 1

            if show_video:
                cv2.namedWindow('Frame')
                cv2.imshow('Frame', img)

                fin = cv2.waitKey(1) & 0xFF
                if(fin == ord('q')):
                    break

    # TODO: Work on video feed to frontend
    def detect_video(self, video_source, return_img=False, return_landmarks=False, return_img_json=False, show_video=False, print_output=False, logger=None):
        cap = cv2.VideoCapture(video_source)

        img_id = 0
        while cap.isOpened():
            ret, img_read = cap.read()
            result,img = self.analyzer.detect_img(img_read, True, return_landmarks, return_img_json)
            if print_output and logger:
                logger.info(f'frame_{img_id}: {result}')
            img_id += 1

            if show_video:
                cv2.namedWindow('Frame')
                cv2.imshow('Frame', img)

                fin = cv2.waitKey(1) & 0xFF
                if(fin == ord('q')):
                    break

def main() -> None:
    # Importing these two libs only if this modules is called as a standalone script
    import pyfiglet
    import iridi

    ap = argparse.ArgumentParser()
    ap.add_argument("type", choices=["detection", "recognition"], help="Select detection for Plain FaceDet and Recognition for FaceDetection and Recognition.")
    ap.add_argument("-i", "--image", required=False, help="Reads an image from path. If not given, opens camera")
    ap.add_argument("-d", "--dataset", required=False, help="path to the dataset json file containing refference info")
    ap.add_argument("-t", "--video_test", action="store_true", help="If selected, opens camera to live test")
    ap.add_argument("-v", "--verbose", action="store_true", help="Debug level for logger output")
    ap.add_argument("-s", "--show_img", action="store_true", help="Shows image output")
    ap.add_argument("-p", "--print_output", action="store_true", help="Prints output to console")
    ap.add_argument("-dd", "--det-dev", required=False, help="Detection device to use. Default is CPU. -1 for CPU, 0-N for GPU id")
    ap.add_argument("-rd", "--rek-dev", required=False, help="Recognition device to use. Default is CPU. -1 for CPU, 0-N for GPU id")
    args = vars(ap.parse_args())

    # Cool title
    moduleTitle = pyfiglet.figlet_format("Face Processor", font="isometric2", width=200)
    iridi.print(moduleTitle, ["#8A2387", "#E94057", "#F27121"], bold=True)
    iridi.print("Loading face processor module as a standalone program", ["#8A2387", "#E94057", "#F27121"], bold=True)
    iridi.print("Prepare your mind to be blown!!!!", ["#8A2387", "#E94057", "#F27121"], bold=True)

    # Logger Configuration
    MODULE_NAME = "FACE ANALITICS PROCESSOR"
    if args["verbose"]:
        logger = Logger("DEBUG", COLORED=True, TAG_MODULE= MODULE_NAME)
    else:
        logger = Logger("INFO", COLORED=True, TAG_MODULE= MODULE_NAME)

    def print_output(label: str, result: any):
        if args['image']: logger.info(f'{args["image"]}: {result}')

    # Check if the user provided a valid device id
    try:
        detection_using_cpu = int(args["det_dev"]) if args["det_dev"] else -1
        rekognition_using_cpu = int(args["rek_dev"]) if args["rek_dev"] else -1
    except ValueError:
        logger.error("Invalid device id. Must be an integer")
        sys.exit()

    logger.info("Using CPU for detection") if detection_using_cpu == -1 else logger.info(f"Using GPU {detection_using_cpu} for detection")
    logger.info("Using CPU for recognition") if rekognition_using_cpu == -1 else logger.info(f"Using GPU {rekognition_using_cpu} for recognition")

    if not args["dataset"]:
       if args["type"] == "recognition":
           logger.error("For recognition you must provide a dataset. Use the flag: -d /path/to/dataset")
           sys.exit()

    logger.info("Preparing the models")
    face_detection_model = 'retinaface_r50_v1'
    face_recognition_model = 'arcface_r100_v1'
    logger.debug(f'Face detection model: {face_detection_model}')
    logger.debug(f'Face recognition model: {face_recognition_model}')
    mProcessor = processor(
        detection_using_cpu,
        rekognition_using_cpu,
        face_detection_model,
        face_recognition_model
    )

    # Getting input image. -i to get it from path. else get it from camera
    if args["image"]:
        logger.info("Reading image from path")
        input_img = cv2.imread(args['image'])
    else:
        logger.info("Image not provided. reading camera instead")
        cap = cv2.VideoCapture(0)
        ret, input_img = cap.read()
        cap.release()
        pass

    logger.info(f'Reading dataset from path {args["dataset"]}')
    dataset_path = args["dataset"]

    # Video Recognition Example
    # python videoAnalytics/processor.py recognition -d 'embeddings.json' -t
    # Image Recognition Example
    # python videoAnalytics/processor.py recognition -i 'img.jpg' -d 'embeddings.json' -s

    if args["type"] == "recognition":
        logger.debug("Performing face recognition on image")
        result,img = mProcessor.analyze_image(dataset_path, input_img, return_img=True)
    else:
        logger.debug("Performing face detection on image")
        result,img = mProcessor.detect_image(input_img, return_img=True)

    if args["print_output"]:
        logger.info("Printing output to console")
        if args['image']: print_output(args['image'], result)

    if args["show_img"]:
        logger.info("Image processed will be shown")
        cv2.imshow('image', img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    # Video Testing if option selected. stop it pressing q
    if args["video_test"]:
        logger.info("Starting video test")
        print_video_output = True if args["print_output"] else False
        if args["type"] == "recognition":
            mProcessor.analyze_video(dataset_path, 0, show_video=True, print_output=print_video_output, logger=logger)
        else:
            mProcessor.detect_video(0, show_video=True, print_output=print_video_output, logger=logger)

if __name__=="__main__":
    main()


from __future__ import annotations

from typing import TYPE_CHECKING, Union, Optional

import discord
from discord.ext import commands
from utils import Context, Embed

if TYPE_CHECKING:
    from utils import Bot

class Info(commands.Cog):
    def __init__(self, bot: Bot):
        self.bot = bot

    @commands.command()
    async def whois(
        self,
        ctx: Context,
        *,
        user: Optional[Union[discord.Member, discord.User]] = None,
    ):
        user = user or ctx.author

        description = (
            f"ID: {user.id} \n"
            f"Bot: {'Yes' if user.bot else 'No'} \n"
            f"Created at: {discord.utils.format_dt(user.created_at)}"
        )

        embed = Embed(
            title=f"Info about {user}!",
            description=description,
            color=getattr(user, "color", None),
        ).set_thumbnail(url=user.avatar)

        await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(Info(bot))


import func as f
from const import _Const

CONST = _Const()
class Agriculture:
    def __init__(self, start_year):
        self = self
        self.start_year = start_year

        self.AL     = CONST.INITIAL.ALI
        self.PAL    = CONST.INITIAL.PALI
        self.UIL    = CONST.INITIAL.UILI
        self.LFERT  = CONST.INITIAL.LFERTI
        self.AI     = CONST.INITIAL.AII
        self.PFR    = CONST.INITIAL.PFRI

    def initial_result(self):
        ret = {}
        ret[CONST.RETURNS.AI]       = CONST.INITIAL.AII
        ret[CONST.RETURNS.F]        = CONST.INITIAL.FI
        ret[CONST.RETURNS.FALM]     = CONST.INITIAL.FALMI
        ret[CONST.RETURNS.FIOAA]    = CONST.INITIAL.FIOAAI
        return ret

    def model(self,
                 current_year,
                 io, pop, ppolx,
                 year_step = CONST.YEAR_STEP_SIZE):
        IFPC = f.f90(io/pop)
        DCPH = f.f97(self.PAL/3.2*10**9)
        LFDR = f.f122(ppolx)
        FALM = f.f126(self.PFR)
        LFRT = f.f125(FALM)
        LRUI = max(0, (pop*f.f117(io/pop) - self.UIL)/10)

        AIPH = self.AI * (1 - FALM) / self.AL
        LY = self.LFERT * f.f102(AIPH) * f.f106(io)
        F = LY * self.AL * 0.63
        FPC = F / pop
        FIOAA = f.f94(FPC/IFPC)
        TAI = FIOAA * io
        MPAI = 2 * LY * f.f111(AIPH) / f.f102(AIPH)
        MPLD = LY / (DCPH * 0.7)
        FIALD = f.f108(MPLD / MPAI)

        CAI = TAI * (1 - FIALD)
        FR = FPC / 230
        LER = self.AL / (6000*f.f114(LY/600))
        LDR = FIALD * TAI / DCPH

        dAL = LDR - LRUI - LER
        dPAL = -1 * LDR
        dUIL = LRUI
        dLFERT = (600 - self.LFERT)/LFRT - self.LFERT*LFDR
        dAI = (CAI - self.AI)/2
        dPFR = (FR - self.PFR)/2

        self.AL += (dAL * year_step)
        self.PAL += (dPAL * year_step)
        self.UIL += (dUIL * year_step)
        self.LFERT += (dLFERT * year_step)
        self.AI += (dAI * year_step)
        self.PFR += (dPFR * year_step)

        ret = {}
        ret[CONST.RETURNS.AI] = self.AI
        ret[CONST.RETURNS.F] = F
        ret[CONST.RETURNS.FALM] = FALM
        ret[CONST.RETURNS.FIOAA] = FIOAA
        return ret


import argparse
import datetime
import logging
import platform
import time

from api import from_google_spreadsheets, get_daycode, send_email, ADMIN_EMAIL, ALIAS_TO_MAIL, \
    LOG_PATH, \
    gen_subject, gen_message, split_daycode, gen_weekly_report, is_class, TESTING, TESTING_LOG_PATH

if not TESTING:
    logging.basicConfig(handlers=[logging.FileHandler(LOG_PATH, 'a', 'utf-8')],
                        level=logging.DEBUG,
                        format='[%(asctime)s] %(levelname)s - %(name)s:%(lineno)s - %(message)s')
else:
    logging.basicConfig(handlers=[logging.FileHandler(TESTING_LOG_PATH, 'a', 'utf-8')],
                        level=logging.DEBUG,
                        format='[%(asctime)s] %(levelname)s - %(name)s:%(lineno)s - %(message)s')

logger = logging.getLogger(__name__)

oauth2client_logger = logging.getLogger('oauth2client')
oauth2client_logger.setLevel(logging.CRITICAL)

urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)

def main(tomorrow=False, weekly_report=False):
    if not TESTING and platform.system() == 'Windows':
        raise RuntimeError('Only linux')

    logger.debug('Starting app, tomorrow=%r, weekly_report=%r', tomorrow, weekly_report)
    data = from_google_spreadsheets()

    logger.debug('Data=%r', data)

    if weekly_report:
        try:
            report = gen_weekly_report(data)
        except RuntimeError:
            return False
        destinations = list(ALIAS_TO_MAIL.values())
        return send_email(destinations, 'Informe Semanal', report)

    daycode = get_daycode(tomorrow=tomorrow)

    logger.debug('Daycode=%r', daycode)

    if daycode not in data:
        logger.critical('Daycode (%r) not in data', daycode)

        month, day = split_daycode(daycode)

        datetime_ = datetime.datetime(2019, month, day)
        logger.debug('Day=%r, month=%r, weekday=%r', day, month, datetime_.weekday())

        if not is_class(datetime_):
            logger.debug('Identified as weekend')
            return True

        return send_email(ADMIN_EMAIL, 'ERROR', f'{daycode!r} is not defined in the database')

    if data[daycode] not in ALIAS_TO_MAIL:
        logger.debug('Data is not a known alias, broadcasting')
        destinations = list(ALIAS_TO_MAIL.values())
        motive = data[daycode]
    else:
        destinations = ALIAS_TO_MAIL[data[daycode]]
        logger.debug('Found alias: %r', destinations)
        motive = 'C'

    logger.debug('Motive=%r', motive)

    return send_email(destinations, gen_subject(motive, tomorrow), gen_message(motive, tomorrow))

if __name__ == '__main__':
    logger.debug('-' * 50)
    t0 = time.time()
    parser = argparse.ArgumentParser()
    parser.add_argument('-tomorrow', action='store_true')
    parser.add_argument('-weekly-report', action='store_true')

    opt = vars(parser.parse_args())

    main(tomorrow=opt['tomorrow'], weekly_report=opt['weekly_report'])

    logger.debug(f'EcoMun Shifts executed in {time.time() - t0:.2f} s')


import argparse
import os
from pathlib import Path
from typing import Optional

import matplotlib.pyplot as plt
import numpy as np
import torch
from tqdm import tqdm, trange

from tinydfa import DFA, DFALayer, FeedbackPointsHandling
import tinydfa.light_dfa as light_dfa

from nerf import cumprod_exclusive, get_minibatches, get_ray_bundle, positional_encoding

def compute_query_points_from_rays(
    ray_origins: torch.Tensor,
    ray_directions: torch.Tensor,
    near_thresh: float,
    far_thresh: float,
    num_samples: int,
    randomize: Optional[bool] = True,
) -> (torch.Tensor, torch.Tensor):
    r"""Compute query 3D points given the "bundle" of rays. The near_thresh and far_thresh
    variables indicate the bounds within which 3D points are to be sampled.

    Args:
        ray_origins (torch.Tensor): Origin of each ray in the "bundle" as returned by the
          `get_ray_bundle()` method (shape: :math:`(width, height, 3)`).
        ray_directions (torch.Tensor): Direction of each ray in the "bundle" as returned by the
          `get_ray_bundle()` method (shape: :math:`(width, height, 3)`).
        near_thresh (float): The 'near' extent of the bounding volume (i.e., the nearest depth
          coordinate that is of interest/relevance).
        far_thresh (float): The 'far' extent of the bounding volume (i.e., the farthest depth
          coordinate that is of interest/relevance).
        num_samples (int): Number of samples to be drawn along each ray. Samples are drawn
          randomly, whilst trying to ensure "some form of" uniform spacing among them.
        randomize (optional, bool): Whether or not to randomize the sampling of query points.
          By default, this is set to `True`. If disabled (by setting to `False`), we sample
          uniformly spaced points along each ray in the "bundle".

    Returns:
        query_points (torch.Tensor): Query points along each ray
          (shape: :math:`(width, height, num_samples, 3)`).
        depth_values (torch.Tensor): Sampled depth values along each ray
          (shape: :math:`(num_samples)`).
    """
    # TESTED
    # shape: (num_samples)
    depth_values = torch.linspace(near_thresh, far_thresh, num_samples).to(ray_origins)
    if randomize is True:
        # ray_origins: (width, height, 3)
        # noise_shape = (width, height, num_samples)
        noise_shape = list(ray_origins.shape[:-1]) + [num_samples]
        # depth_values: (num_samples)
        depth_values = (
            depth_values
            + torch.rand(noise_shape).to(ray_origins)
            * (far_thresh - near_thresh)
            / num_samples
        )
    # (width, height, num_samples, 3) = (width, height, 1, 3) + (width, height, 1, 3) * (num_samples, 1)
    # query_points:  (width, height, num_samples, 3)
    query_points = (
        ray_origins[..., None, :]
        + ray_directions[..., None, :] * depth_values[..., :, None]
    )
    # TODO: Double-check that `depth_values` returned is of shape `(num_samples)`.
    return query_points, depth_values

def render_volume_density(
    radiance_field: torch.Tensor, ray_origins: torch.Tensor, depth_values: torch.Tensor
) -> (torch.Tensor, torch.Tensor, torch.Tensor):
    r"""Differentiably renders a radiance field, given the origin of each ray in the
    "bundle", and the sampled depth values along them.

    Args:
    radiance_field (torch.Tensor): A "field" where, at each query location (X, Y, Z),
      we have an emitted (RGB) color and a volume density (denoted :math:`\sigma` in
      the paper) (shape: :math:`(width, height, num_samples, 4)`).
    ray_origins (torch.Tensor): Origin of each ray in the "bundle" as returned by the
      `get_ray_bundle()` method (shape: :math:`(width, height, 3)`).
    depth_values (torch.Tensor): Sampled depth values along each ray
      (shape: :math:`(num_samples)`).

    Returns:
    rgb_map (torch.Tensor): Rendered RGB image (shape: :math:`(width, height, 3)`).
    depth_map (torch.Tensor): Rendered depth image (shape: :math:`(width, height)`).
    acc_map (torch.Tensor): # TODO: Double-check (I think this is the accumulated
      transmittance map).
    """
    # TESTED
    sigma_a = torch.nn.functional.relu(radiance_field[..., 3])
    rgb = torch.sigmoid(radiance_field[..., :3])
    one_e_10 = torch.tensor([1e10], dtype=ray_origins.dtype, device=ray_origins.device)
    dists = torch.cat(
        (
            depth_values[..., 1:] - depth_values[..., :-1],
            one_e_10.expand(depth_values[..., :1].shape),
        ),
        dim=-1,
    )
    alpha = 1.0 - torch.exp(-sigma_a * dists)
    weights = alpha * cumprod_exclusive(1.0 - alpha + 1e-10)

    rgb_map = (weights[..., None] * rgb).sum(dim=-2)
    depth_map = (weights * depth_values).sum(dim=-1)
    acc_map = weights.sum(-1)

    return rgb_map, depth_map, acc_map

# One iteration of TinyNeRF (forward pass).
def run_one_iter_of_tinynerf(
    height,
    width,
    focal_length,
    tform_cam2world,
    near_thresh,
    far_thresh,
    depth_samples_per_ray,
    encoding_function,
    get_minibatches_function,
    chunksize,
    model,
    encoding_function_args,
):

    # Get the "bundle" of rays through all image pixels.
    ray_origins, ray_directions = get_ray_bundle(
        height, width, focal_length, tform_cam2world
    )

    # Sample query points along each ray
    query_points, depth_values = compute_query_points_from_rays(
        ray_origins, ray_directions, near_thresh, far_thresh, depth_samples_per_ray
    )

    # "Flatten" the query points.
    flattened_query_points = query_points.reshape((-1, 3))

    # Encode the query points (default: positional encoding).
    encoded_points = encoding_function(flattened_query_points, encoding_function_args)

    # Split the encoded points into "chunks", run the model on all chunks, and
    # concatenate the results (to avoid out-of-memory issues).
    batches = get_minibatches_function(encoded_points, chunksize=chunksize)
    predictions = []
    for batch in batches:
        predictions.append(model(batch))
    radiance_field_flattened = torch.cat(predictions, dim=0)

    # "Unflatten" to obtain the radiance field.
    unflattened_shape = list(query_points.shape[:-1]) + [4]
    radiance_field = torch.reshape(radiance_field_flattened, unflattened_shape)

    # Perform differentiable volume rendering to re-synthesize the RGB image.
    rgb_predicted, _, _ = render_volume_density(
        radiance_field, ray_origins, depth_values
    )

    return rgb_predicted

class VeryTinyNerfModel(torch.nn.Module):
    r"""Define a "very tiny" NeRF model comprising three fully connected layers.
    """

    def __init__(self, filter_size=128, num_encoding_functions=6, training_method='BP', feedback_mode=None):
        super(VeryTinyNerfModel, self).__init__()
        self.feedback_mode = feedback_mode
        if self.feedback_mode == 'HOOK':
            dfa_layer = light_dfa.DFALayer
            dfa = light_dfa.DFA
        else:
            dfa_layer = DFALayer
            dfa = DFA
        # Input layer (default: 39 -> 128)
        self.layer1 = torch.nn.Linear(3 + 3 * 2 * num_encoding_functions, filter_size)
        # Layer 2 (default: 128 -> 128)
        self.layer2 = torch.nn.Linear(filter_size, filter_size)
        # Layer 3 (default: 128 -> 4)
        self.layer3 = torch.nn.Linear(filter_size, 4)
        # Short hand for torch.nn.functional.relu
        self.relu = torch.nn.functional.relu

        self.training_method = training_method

        if self.training_method in ['DFA', 'SHALLOW']:
            self.dfa_1 = dfa_layer(name='dfa1')
            self.dfa_2 = dfa_layer(name='dfa2')
            if self.feedback_mode == 'HOOK':
                self.dfa = dfa([self.dfa_1, self.dfa_2], no_training= self.training_method=='SHALLOW')
            else:
                self.dfa = dfa([self.dfa_1, self.dfa_2], no_training= self.training_method == 'SHALLOW',
                               feedback_points_handling=FeedbackPointsHandling.MINIBATCH)

    def forward(self, x):
        if self.training_method in ['DFA', 'SHALLOW']:
            x = self.dfa_1(self.relu(self.layer1(x)))
            x = self.dfa_2(self.relu(self.layer2(x)))
            x = self.dfa(self.layer3(x))
        else:
            x = self.relu(self.layer1(x))
            x = self.relu(self.layer2(x))
            x = self.layer3(x)
        return x

def main(args):
    # Setup general stuff:
    device = torch.device(f"cuda:{args.gpu_id}")  # Setup CUDA GPU

    seed = 9458
    torch.manual_seed(seed)
    np.random.seed(seed)

    save_path = os.path.join(args.save_path, f'tiny-{args.training_method}-{args.feedback_mode}/')
    Path(save_path).mkdir(parents=True, exist_ok=True)

    # Prepare data from scene:
    data = np.load(os.path.join(args.dataset_path, "tiny_nerf_data.npz"))

    tform_cam2world = data["poses"]  # Camera poses
    tform_cam2world = torch.from_numpy(tform_cam2world).to(device)

    focal_length = data["focal"]  # Focal lengths
    focal_length = torch.from_numpy(focal_length).to(device)

    images = data["images"]  # Actual images
    height, width = images.shape[1:3]

    testimg, testpose = images[101], tform_cam2world[101]  # Test view
    testimg = torch.from_numpy(testimg).to(device)

    images = torch.from_numpy(images[:100, ..., :3]).to(device)

    # Training parameters:
    near_thresh = 2.0  # Near clipping treshold for depth
    far_thresh = 6.0  # Far clipping treshold for depth
    encode = positional_encoding  # Position and angle encoding function
    num_encoding_functions = 10  # Encoding depth
    depth_samples_per_ray = 32  # Samples along ray

    chunksize = 8192  # Numbers of rays queried at once (4096 ~ 1.4GB of GPU/ray/8 samples

    lr = 5e-3  # Learning rate
    num_iters = 5000  # Number of iterations

    display_every = 100  # Display stats every

    # Model:
    model = VeryTinyNerfModel(num_encoding_functions=num_encoding_functions, training_method=args.training_method,
                              feedback_mode=args.feedback_mode)
    model.to(device)

    # Optimizer:
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)

    # Training loop:
    psnrs = []  # Log PSNR values
    iternums = []  # Log number of iterations

    for i in trange(num_iters):
        # Randomly pick an image as the target.
        target_img_idx = np.random.randint(images.shape[0])
        target_img = images[target_img_idx].to(device)
        target_tform_cam2world = tform_cam2world[target_img_idx].to(device)

        # Run one iteration of TinyNeRF and get the rendered RGB image.
        rgb_predicted = run_one_iter_of_tinynerf(height, width, focal_length, target_tform_cam2world, near_thresh,
                                                 far_thresh, depth_samples_per_ray, encode, get_minibatches,
                                                 chunksize, model, num_encoding_functions,)

        # Compute mean-squared error between the predicted and target images, and backprop.
        loss = torch.nn.functional.mse_loss(rgb_predicted, target_img)
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        # Validate every so often:
        if i % display_every == 0 or i == num_iters - 1:
            # Render the held-out view and compute metrics on it:
            rgb_predicted = run_one_iter_of_tinynerf(height, width, focal_length, testpose, near_thresh, far_thresh,
                                                     depth_samples_per_ray, encode, get_minibatches, chunksize,
                                                     model, num_encoding_functions,)
            loss = torch.nn.functional.mse_loss(rgb_predicted, target_img)
            tqdm.write("Loss: " + str(loss.item()))
            psnr = -10.0 * torch.log10(loss)

            psnrs.append(psnr.item())  # Log the metrics
            iternums.append(i)

            plt.imshow(rgb_predicted.detach().cpu().numpy())
            plt.savefig(os.path.join(save_path, str(i).zfill(6) + ".png"))
            plt.close("all")

            if i == num_iters - 1:
                plt.plot(iternums, psnrs)
                plt.savefig(os.path.join(save_path, "psnr.png"))
                plt.close("all")
    print("Done!")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Tiny-NeRF DFA example')
    parser.add_argument('-t', '--training-method', type=str, choices=['BP', 'DFA', 'SHALLOW'], default='SHALLOW',
                        metavar='T', help='training method to use, choose from backpropagation (BP), direct feedback '
                                          'alignment (DFA), or only topmost layer (SHALLOW) (default: BP)')
    parser.add_argument('-f', '--feedback-mode', type=str, choices=['MINIBATCH', 'HOOK'],
                        default='MINIBATCH', metavar='F', help='feedback handling mode to use when training with DFA.')

    parser.add_argument('-g', '--gpu-id', type=int, default='0', metavar='i',
                        help='id of the CUDA GPU to use (default: 0)')

    parser.add_argument('-p', '--dataset-path', type=str, default='/data', metavar='DP',
                        help='path to dataset (default: /data)')
    parser.add_argument('-s', '--save-path', type=str, default='/logs', metavar='SP',
                        help='path to saving folder (logs and outputs) (default: /logs)')
    args = parser.parse_args()
    main(args)


import boto3

# List WorkspaceIds not to be in the script rule
WORKSPACES_EXCEPTION = []

def execute_workspaces(command):
	"""
	This function execute start and stop workspaces where not in WORKSPACES_EXCEPTION
	"""
	client = boto3.client('workspaces')
	response = client.describe_workspaces()['Workspaces']

	# get WorkspacesIds
	workspaceIds = [ {'WorkspaceId': workspace['WorkspaceId']} for workspace in response if workspace['WorkspaceId'] not in WORKSPACES_EXCEPTION ]

	if command == 'start':
		response = client.start_workspaces(StartWorkspaceRequests=workspaceIds)

	elif command == 'stop':
		response = client.stop_workspaces(StopWorkspaceRequests=workspaceIds)

def lambda_handler(event, context):
	"""
	execute function execute_workspaces
	@command (start, stop)
	"""
	execute_workspaces(command='stop')


from django.urls import path
from django.urls.resolvers import URLPattern
from django.views.generic.base import RedirectView
from . import views
app_name='posts'
urlpatterns=[
    path('create/',views.CreatePostView.as_view(),name='createPost'),
    path('<slug:username>/post/<int:pk>/',views.postDetailView.as_view(),name='PostDetail'),
    path('',views.FriendsPostsListView.as_view(),name='FriendsPost'),
    path('<slug:username>/post/<int:pk>/delete',views.DeletePostView.as_view(),name='PostDelete'),
    path('<slug:username>/post/<int:pk>/update',views.UpdatePostView.as_view(),name='PostUpdate'),
    path('<slug:username>/post/<int:pk>/addcomment/',views.CreateCommentView.as_view(),name="addComment"),
    path('post/<int:post_id>/removecomment/<int:pk>',views.DeleteCommentView.as_view(),name="deleteComment"),
    path('post/<int:post_id>/editcomment/<int:pk>',views.UpdateCommentView.as_view(),name="UpdateComment"),

]


import math
import random

class LeaderElection:
    def __init__(
            self,
            validator_list,
            window_size,
            exclude_size,
            ledger_module,
            pacemaker_module):
        self.ledger_module = ledger_module
        self.pacemaker_module = pacemaker_module
        self.validators = validator_list  # The list of current validators
        self.window_size = window_size  # A parameter for the leader reputation algorithm
        # Between f and 2f, number of excluded authors of last committed blocks
        # reputation leaders; // Map from round numbers to leaders elected due
        # to the reputation scheme
        self.exclude_size = exclude_size
        # Map from round numbers to leaders elected due to the reputation
        # scheme
        self.reputation_leaders = {}

    """
    validators; // The list of current validators
    window size; // A parameter for the leader reputation algorithm
    exclude size; // Between f and 2f, number of excluded authors of last committed blocks
    reputation leaders; // Map from round numbers to leaders elected due to the reputation scheme

    """

    def elect_reputation_leader(self, qc):
        # validators that signed the last window size committed blocks
        active_validators = self.validators
        last_authors = []  # ordered set of authors of last exclude size committed blocks
        current_qc = qc
        i = 0
        while i < self.window_size or len(last_authors) < self.exclude_size:
            current_block = self.ledger_module.committed_block(
                current_qc.vote_info.parent_id)
            block_author = current_block.author
            if i < self.window_size:
                active_validators = self.validators
                # active_validators.append(current_qc.signatures.signers())
            if len(last_authors) < self.exclude_size:
                last_authors.append(block_author)
            current_qc = current_block.qc
        for x in last_authors:
            active_validators.remove(x)
        return active_validators[int(random.seed(
            current_qc.vote_info.round) * len(active_validators))]

    """
    Function elect reputation leader(qc)
        active validators ← ∅ // validators that signed the last window size committed blocks
        last authors ← ∅ // ordered set of authors of last exclude size committed blocks
        current qc ← qc
        for i = 0; i < window size ∨ |last authors| < exclude size; i ← i + 1 do
        current block ← Ledger.committed block(current qc.vote info.parent id)
        block author ← current block.author
        if i < window size then
        active validators ← active validators ∪ current qc.signatures.signers()
        // |current qc.signatures.signers()| ≥ 2f + 1
        if |last authors| < exclude size then
        last authors ← last authors ∪ {block author}
        current qc ← current block.qc
        active validators ← active validators \\ last authors // contains at least 1 validator
        return active validators.pick one(seed ← qc.voteinfo.round)

    """

    def update_leaders(self, qc):
        extended_round = qc.vote_info.parent_round
        qc_round = qc.vote_info.round
        current_round = self.pacemaker_module.current_round
        if extended_round + 1 == qc_round and qc_round + 1 == current_round:
            self.reputation_leaders[current_round +
                                    1] = self.elect_reputation_leader(qc)

    """
    Procedure update leaders(qc)
        extended round ← qc.vote info.parent round
        qc round ← qc.vote info.round
        current round ← PaceMaker.current round
        if extended round + 1 = qc round ∧ qc round + 1 = current round then
        reputation leaders[current round + 1] ← elect reputation leader(qc)

    """

    def get_leader(self, round):
        if self.reputation_leaders[round]:
            lst = list(self.validators)
            return lst.index(self.reputation_leaders[round])
        index = math.floor(round / 2) % len(self.validators)
        return index

    """
    Function get leader(round)
        if ⟨round, leader⟩ ∈ reputation leaders then
        return leader // Reputation-based leader
        return validators[⌊round/2⌋ mod |validators|] // Round-robin leader (two rounds per leader)
    """


from django.urls import path
from api import views

from rest_framework_simplejwt import views as jwt_views

app_name = "api"

urlpatterns = (
    path('sslcert', views.SslCertDataView.as_view()),
    path('target_test', views.TargetHealth.as_view()),
    path('prom_targets', views.PromTargetView.as_view()),
    path('prom_data', views.PromQlView.as_view()),
    path('csrf_cookie', views.GetCSRF.as_view()),
    path('app_version', views.get_backend_version),

    path('services_status/<int:server_id>', views.ServicesStatus.as_view()),
    path('ping', views.Ping.as_view()),
)


import unittest

from mock import *

from manager.decorator import *
from manager.event_manager import EventManager
from tests.handlers import *
from tests.utils import count

class TestEventManager(unittest.TestCase):
    def setUp(self):
        self.event_manager = EventManager()

    def test_em_register_handler(self):
        test_handler = count(print_10nd_event)
        self._register_decorated_func(self.event_manager, test_handler)

        for i in xrange(4):
            self.event_manager.notify(object)
        self.assertEqual(test_handler.counter, 0)

        for i in xrange(8):
            self.event_manager.notify(object)
        self.assertEqual(test_handler.counter, 1)

    def test_em_unregister_existing_handler(self):
        test_handler = count(print_10nd_event)
        self._register_decorated_func(self.event_manager, test_handler)
        for i in xrange(4):
            self.event_manager.notify(object)

        self.event_manager.unregister_handler(test_handler)
        for i in xrange(8):
            self.event_manager.notify(object)

        self.assertEqual(test_handler.counter, 0)

    def test_em_unregister_not_existing_handler(self):
        def test_handler():
            pass
        self.event_manager.unregister_handler(test_handler)

    def test_em_unregister_and_register(self):
        test_handler = count(print_10nd_event)
        self._register_decorated_func(self.event_manager, test_handler)
        for i in xrange(4):
            self.event_manager.notify(object)

        self.event_manager.unregister_handler(test_handler)
        self._register_decorated_func(self.event_manager, test_handler)

        for i in xrange(8):
            self.event_manager.notify(object)

        self.assertEqual(test_handler.counter, 1)

    def test_em_delayed_once_register(self):
        mock = Mock()
        mock.test_handler_mock = Mock()

        for i in xrange(4):
            self.event_manager.notify(object)

        self.event_manager.register_handler(mock.test_handler_mock,
                                            TriggerInfo(once(), Priority.STANDARD, False, True))

        for i in xrange(4):
            self.event_manager.notify(object)

        expected_result = [call.test_handler_mock(IndexedEvent(object, 4))]

        self.assertEqual(mock.mock_calls, expected_result)

    def test_em_register_priority_handlers(self):
        mock = Mock()
        mock.low = Mock()
        mock.standard = Mock()
        mock.high = Mock()

        self.event_manager.register_handler(mock.standard,
                                            TriggerInfo(once(), Priority.STANDARD, False))
        self.event_manager.register_handler(mock.low,
                                            TriggerInfo(once(), Priority.LOW, False))
        self.event_manager.register_handler(mock.high,
                                            TriggerInfo(once(), Priority.HIGH, False))

        self.event_manager.notify(object)

        event = IndexedEvent(object, 0)
        expected_result = [call.high(event), call.standard(event), call.low(event)]
        self.assertEqual(mock.mock_calls, expected_result)

    def test_em_register_repeat_handlers(self):
        mock = Mock()
        mock.repeat_handler_mock = Mock()

        self.event_manager.register_handler(mock.repeat_handler_mock,
                                            TriggerInfo(repeat_index(3)(), Priority.STANDARD, False))

        for i in xrange(9):
            self.event_manager.notify(object)

        expected_result = []
        for i in xrange(2, 9, 3):
            event = IndexedEvent(object, i)
            expected_result.append(call.repeat_handler_mock(event))

        self.assertEqual(mock.mock_calls, expected_result)

    def test_em_register_repeat_with_max_retry_count_handlers(self):
        mock = Mock()
        mock.repeat_handler_mock = Mock()

        self.event_manager.register_handler(mock.repeat_handler_mock,
                                            TriggerInfo(repeat_index(3, repeat_count=3)(), Priority.STANDARD, False))

        for i in xrange(100):
            self.event_manager.notify(object)

        expected_result = []
        for i in xrange(2, 9, 3):
            event = IndexedEvent(object, i)
            expected_result.append(call.repeat_handler_mock(event))

        self.assertEqual(mock.mock_calls, expected_result)

    def test_em_register_non_critical_handler(self):
        self._register_decorated_func(self.event_manager, swallow_exception_on_1st_event)
        self.event_manager.notify(object)

    def test_em_register_critical_handler(self):
        self._register_decorated_func(self.event_manager, throw_exception_on_4th)

        def trigger_exception_routine():
            for i in xrange(10):
                self.event_manager.notify(object)

        self.assertRaises(Exception, trigger_exception_routine)

    def _register_decorated_func(self, event_manager, func):
        event_manager.register_handler(func,
                                       EventHandlerDecorator.extract_trigger_info_from_function(func))

if __name__ == "__main__":
    unittest.main()


from bots.base import Bot
from simpleeval import simple_eval

class CalcBot(Bot):
    def _q(self):
        s = "Input some expression"
        if self.runtype == 'loop':
            s += " (type x, q, exit or quit to quit)"
        return s

    def _think(self, s):
        try:
            result = f"Done. Result = {simple_eval(s)}"
        except:
            result = "Sorry I can't understand"

        return result

if __name__ == '__main__':
    c = CalcBot()
    c.run()

    c = CalcBot('loop')
    c.run()


import json

from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIClient

from artsouterrain.apps.artwork.models import Place
from artsouterrain.apps.event.models import EventType, Event

class EventTexts(APITestCase):

    def setUp(self) -> None:
        self.client = APIClient()

        self.event_type = EventType.objects.create(
            key='TYPE_1',
            name='Type 1'
        )

        self.event_type_2 = EventType.objects.create(
            key='TYPE_2',
            name='Type 2'
        )

        self.place_1 = Place.objects.create(
            name='Place 1'
        )

        self.place_2 = Place.objects.create(
            name='Place 2'
        )

        self.event = Event.objects.create(
            name='Event 1',
            description='event 1 description',
            event_type=self.event_type,
            place=self.place_1,
            link='http://event2.com',
        )
        self.event_2 = Event.objects.create(
            name='Event 2',
            description='event 2 description',
            event_type=self.event_type,
            place=self.place_1,
            link='http://event2.com',
        )
        self.event_3 = Event.objects.create(
            name='Event 3',
            description='event 3 description',
            event_type=self.event_type_2,
            place=self.place_2,
            link='http://event3.com',
        )

    def test_list_event(self):

        response = self.client.get(
            reverse('event-list')
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            response.content,
        )

        response_data = json.loads(response.content)

        self.assertEqual(response_data['count'], 3)

    def test_get_event(self):
        response = self.client.get(
            reverse('event-detail', kwargs={'pk': self.event.id})
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            response.content,
        )

        response_data = json.loads(response.content)

        self.assertEqual(response_data['name'], self.event.name)
        self.assertEqual(response_data['link'], self.event.link)
        self.assertEqual(response_data['description'],
                         self.event.description)
        self.assertEqual(response_data['event_type']['key'],
                         self.event.event_type.key)

    def test_list_filter_by_type_key(self):
        response = self.client.get(
            reverse('event-list'),
            {'event_type__key': self.event_type.key}
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            response.content,
        )

        response_data = json.loads(response.content)

        self.assertEqual(response_data['count'], 2)

    def test_list_filter_by_type_id(self):
        response = self.client.get(
            reverse('event-list'),
            {'event_type': self.event_type.id}
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            response.content,
        )

        response_data = json.loads(response.content)

        self.assertEqual(response_data['count'], 2)

    def test_update_event(self):
        response = self.client.patch(
            reverse('event-detail', kwargs={'pk': self.event.id}),
            {
                'event_type': 'fake',
                'name': 'fake'
            }
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_501_NOT_IMPLEMENTED,
            response.content,
        )

    def test_delete_event(self):
        response = self.client.delete(
            reverse('event-detail', kwargs={'pk': self.event.id})
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_501_NOT_IMPLEMENTED,
            response.content,
        )

    def test_update_event_type(self):

        response = self.client.patch(
            reverse('eventtype-detail', kwargs={'pk': self.event_type.id}),
            {
                'key': 'fake',
                'name': 'fake'
            }
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_501_NOT_IMPLEMENTED,
            response.content,
        )

    def test_delete_event_type(self):
        response = self.client.delete(
            reverse('eventtype-detail', kwargs={'pk': self.event_type.id})
        )

        self.assertEqual(
            response.status_code,
            status.HTTP_501_NOT_IMPLEMENTED,
            response.content,
        )


import tkinter as tk

def show_color_popup(color):
    root = tk.Tk()
    root.geometry("400x100")
    # Set window attributes to make it appear at the top and not minimize
    root.wm_attributes("-topmost", 1)
    root.overrideredirect(True)
    root.attributes("-alpha", 0.8)

    # Calculate the position to center the window on the screen
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    window_width = 400
    window_height = 100
    x = (screen_width-window_width//2) // 2
    y = (screen_height - window_height) // 4
    root.geometry(f"+{x}+{y}")
    # customize title bar
    title_bar = tk.Frame(root, bg='#2e2e2e', relief='raised', bd=2,highlightthickness=0)

    # put a close button on the title bar
    close_button = tk.Button(title_bar, text='X', command=root.destroy,bg="#2e2e2e",padx=2,pady=2,activebackground='red',bd=0,font="bold",fg='white',highlightthickness=0)

    # pack the widgets
    title_bar.pack(expand=1, fill=tk.X)
    close_button.pack(side=tk.RIGHT)

    # Create a frame to hold the color block and text
    frame = tk.Frame(root)
    frame.pack(padx=10, pady=10)
    # Create a canvas to display the color block
    color_canvas = tk.Canvas(frame, width=50, height=50, bg=color, highlightthickness=0)
    color_canvas.pack(side=tk.LEFT)

    # Create a label to display the color in hex
    color_hex_label = tk.Label(frame, text=f"Color: {color}", font=("Arial", 12))
    color_hex_label.pack(side=tk.LEFT, padx=(10, 20))
    root.after(3000, root.destroy)

    # # Show and focus the window
    # root.deiconify()
    # root.lift()

    root.mainloop()


from oslo.config import cfg

from ceilometer.compute import instance
from ceilometer import counter
from ceilometer import plugin
from ceilometer import utils

OPTS = [
    cfg.StrOpt('nova_control_exchange',
               default='nova',
               help="Exchange name for Nova notifications"),
]

cfg.CONF.register_opts(OPTS)

class ComputeNotificationBase(plugin.NotificationBase):

    @staticmethod
    def get_exchange_topics(conf):
        """Return a sequence of ExchangeTopics defining the exchange and
        topics to be connected for this plugin.
        """
        return [
            plugin.ExchangeTopics(
                exchange=conf.nova_control_exchange,
                topics=set(topic + ".info"
                           for topic in conf.notification_topics)),
        ]

class InstanceScheduled(ComputeNotificationBase):

    metadata_keys = ['request_spec']

    @staticmethod
    def get_event_types():
        return ['scheduler.run_instance.scheduled']

    def notification_to_metadata(self, event):
        metadata = super(InstanceScheduled,
                         self).notification_to_metadata(event)
        metadata['weighted_host'] = event['payload']['weighted_host']['host']
        metadata['weight'] = event['payload']['weighted_host']['weight']
        return metadata

    def process_notification(self, message):
        return [
            counter.Counter(
                name='instance.scheduled',
                type=counter.TYPE_DELTA,
                volume=1,
                unit='instance',
                user_id=None,
                project_id=
                message['payload']['request_spec']
                ['instance_properties']['project_id'],
                resource_id=message['payload']['instance_id'],
                timestamp=message['timestamp'],
                resource_metadata=dict(
                    utils.recursive_keypairs(message['payload'])),
            )
        ]

class ComputeInstanceNotificationBase(ComputeNotificationBase):
    """Convert compute.instance.* notifications into Counters
    """
    metadata_keys = instance.INSTANCE_PROPERTIES

    def notification_to_metadata(self, event):
        metadata = super(ComputeInstanceNotificationBase,
                         self).notification_to_metadata(event)
        metadata['instance_type'] = event['payload']['instance_type_id']
        return metadata

    @staticmethod
    def get_event_types():
        return ['compute.instance.create.end',
                'compute.instance.exists',
                'compute.instance.delete.start',
                'compute.instance.finish_resize.end',
                'compute.instance.resize.revert.end']

class Instance(ComputeInstanceNotificationBase):

    def process_notification(self, message):
        return [
            counter.Counter(name='instance',
                            type=counter.TYPE_GAUGE,
                            unit='instance',
                            volume=1,
                            user_id=message['payload']['user_id'],
                            project_id=message['payload']['tenant_id'],
                            resource_id=message['payload']['instance_id'],
                            timestamp=message['timestamp'],
                            resource_metadata=self.notification_to_metadata(
                                message),
                            ),
        ]

class Memory(ComputeInstanceNotificationBase):

    def process_notification(self, message):
        return [
            counter.Counter(name='memory',
                            type=counter.TYPE_GAUGE,
                            unit='MB',
                            volume=message['payload']['memory_mb'],
                            user_id=message['payload']['user_id'],
                            project_id=message['payload']['tenant_id'],
                            resource_id=message['payload']['instance_id'],
                            timestamp=message['timestamp'],
                            resource_metadata=self.notification_to_metadata(
                                message)),
        ]

class VCpus(ComputeInstanceNotificationBase):

    def process_notification(self, message):
        return [
            counter.Counter(name='vcpus',
                            type=counter.TYPE_GAUGE,
                            unit='vcpu',
                            volume=message['payload']['vcpus'],
                            user_id=message['payload']['user_id'],
                            project_id=message['payload']['tenant_id'],
                            resource_id=message['payload']['instance_id'],
                            timestamp=message['timestamp'],
                            resource_metadata=self.notification_to_metadata(
                                message)),
        ]

class RootDiskSize(ComputeInstanceNotificationBase):

    def process_notification(self, message):
        return [
            counter.Counter(name='disk.root.size',
                            type=counter.TYPE_GAUGE,
                            unit='GB',
                            volume=message['payload']['root_gb'],
                            user_id=message['payload']['user_id'],
                            project_id=message['payload']['tenant_id'],
                            resource_id=message['payload']['instance_id'],
                            timestamp=message['timestamp'],
                            resource_metadata=self.notification_to_metadata(
                                message)),
        ]

class EphemeralDiskSize(ComputeInstanceNotificationBase):

    def process_notification(self, message):
        return [
            counter.Counter(name='disk.ephemeral.size',
                            type=counter.TYPE_GAUGE,
                            unit='GB',
                            volume=message['payload']['ephemeral_gb'],
                            user_id=message['payload']['user_id'],
                            project_id=message['payload']['tenant_id'],
                            resource_id=message['payload']['instance_id'],
                            timestamp=message['timestamp'],
                            resource_metadata=self.notification_to_metadata(
                                message)),
        ]

class InstanceFlavor(ComputeInstanceNotificationBase):

    def process_notification(self, message):
        counters = []
        instance_type = message.get('payload', {}).get('instance_type')
        if instance_type:
            counters.append(
                counter.Counter(
                    name='instance:%s' % instance_type,
                    type=counter.TYPE_GAUGE,
                    unit='instance',
                    volume=1,
                    user_id=message['payload']['user_id'],
                    project_id=message['payload']['tenant_id'],
                    resource_id=message['payload']['instance_id'],
                    timestamp=message['timestamp'],
                    resource_metadata=self.notification_to_metadata(
                        message),
                )
            )
        return counters

class InstanceDelete(ComputeInstanceNotificationBase):
    """Handle the messages sent by the nova notifier plugin
    when an instance is being deleted.
    """

    @staticmethod
    def get_event_types():
        return ['compute.instance.delete.samples']

    def process_notification(self, message):
        return [
            counter.Counter(name=sample['name'],
                            type=sample['type'],
                            unit=sample['unit'],
                            volume=sample['volume'],
                            user_id=message['payload']['user_id'],
                            project_id=message['payload']['tenant_id'],
                            resource_id=message['payload']['instance_id'],
                            timestamp=message['timestamp'],
                            resource_metadata=self.notification_to_metadata(
                                message),
                            )
            for sample in message['payload'].get('samples', [])
        ]


from decimal import Decimal, InvalidOperation
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect, render
from .models import Produto, Grupo

def consulta_produtos(request):
    produtos = Produto.objects.filter(user=request.user)
    return render(request, 'consulta-produtos.html', {'produtos': produtos})

def consulta_grupos(request):
    grupos = Grupo.objects.filter(user=request.user)
    return render(request, 'consulta-grupos.html', {'grupos': grupos})

def cadastrar_produto(request):
    if request.method == "POST":
        nome = request.POST.get('nome')
        descricao = request.POST.get('descricao')
        grupo_id = request.POST.get('grupo')
        preco_original = request.POST.get('preco_original')
        preco_promocional = request.POST.get('preco_promocional')
        imagem = request.FILES.get('imagem')
        pausado = request.POST.get('pausado')

        try:
            if preco_original:
                preco_original = Decimal(preco_original)
            if preco_promocional:
                preco_promocional = Decimal(preco_promocional)
        except InvalidOperation:
            # Tratar erro aqui
            pass

        grupo = None
        if grupo_id:
           grupo = Grupo.objects.get(id_grupo=grupo_id)

        loja = request.user.loja

        produto = Produto(
            nome=nome,
            descricao=descricao,
            grupo=grupo,
            preco_original=preco_original,
            preco_promocional=preco_promocional,
            imagem=imagem,
            pausado=pausado,
            user=loja
        )
        produto.save()

        return redirect('lojas:cadastros:consulta_produtos')
    else:
        grupos = Grupo.objects.filter(user=request.user)
        context = {'grupos': grupos}
        return render(request, 'cadastro-produto.html', context)

def atualizar_status_produto(request, produto_id):
    produto = get_object_or_404(Produto, id_produto=produto_id)

    if request.method == "GET":
        novo_status = 'S' if produto.pausado == 'N' else 'N'
        produto.pausado = novo_status
        produto.save()
        return redirect('lojas:cadastros:consulta_produtos')
    else:
        return redirect('lojas:cadastros:consulta_produtos')

def alterar_produto(request, produto_id):
    produto = get_object_or_404(Produto, id_produto=produto_id)

    if request.method == "POST":
        produto.nome = request.POST.get('nome', produto.nome)
        produto.descricao = request.POST.get('descricao', produto.descricao)
        grupo_id = request.POST.get('grupo')

        if grupo_id:
            produto.grupo = Grupo.objects.get(id_grupo=grupo_id)
        try:
            produto.preco_original = Decimal(request.POST.get('preco_original', produto.preco_original))
            produto.preco_promocional = Decimal(request.POST.get('preco_promocional', produto.preco_promocional))
        except InvalidOperation:
            # Tratar erro aqui
            pass

        nova_imagem = request.FILES.get('imagem')
        if nova_imagem:
            produto.imagem = nova_imagem

        produto.pausado = request.POST.get('pausado', produto.pausado)

        produto.save()

        return redirect('lojas:cadastros:consulta_produtos')

    else:
        grupos = Grupo.objects.filter(user=request.user)
        context = {'grupos': grupos, 'produto': produto}
        return render(request, 'alterar-produto.html', context)

def deletar_produto(request, produto_id):
    produto = get_object_or_404(Produto, id_produto=produto_id)
    produto.delete()
    messages.success(request, 'Produto deletado com sucesso.')
    return redirect('lojas:cadastros:consulta_produtos')

def cadastrar_grupo(request):
    if request.method == "POST":
        nome = request.POST.get('nome')
        pausado = request.POST.get('pausado')

        loja = request.user.loja
        grupo = Grupo(
            nome=nome,
            pausado=pausado,
            user=loja
        )
        grupo.save()

        return redirect('lojas:cadastros:consulta_grupos')
    else:
        return render(request, 'cadastro-grupo.html')

def deletar_grupo(request, id_grupo):
    grupo = get_object_or_404(Grupo, id_grupo=id_grupo)

    Produto.objects.filter(grupo_id=id_grupo).delete()

    grupo.delete()
    messages.success(request, 'Grupo deletado com sucesso.')
    return redirect('lojas:cadastros:consulta_grupos')

def atualizar_status_grupo(request, id_grupo):
    grupo = get_object_or_404(Grupo, id_grupo=id_grupo)

    if request.method == "GET":
        novo_status = 'S' if grupo.pausado == 'N' else 'N'
        grupo.pausado = novo_status
        grupo.save()
        return redirect('lojas:cadastros:consulta_grupos')
    else:
        return redirect('lojas:cadastros:consulta_grupos')

def alterar_grupo(request, id_grupo):
    grupo = get_object_or_404(Grupo, id_grupo=id_grupo)

    if request.method == "POST":
        grupo.nome = request.POST.get('nome', grupo.nome)
        grupo.pausado = request.POST.get('pausado', grupo.pausado)
        grupo.save()

        return redirect('lojas:cadastros:consulta_grupos')

    else:
        context = {'grupo': grupo}
        return render(request, 'alterar-grupo.html', context)


import datetime

from django.test import TestCase
from django.urls import reverse

from .models import Inscription

class InscriptionListTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        # Crear 13 Inscripciones para probar la pagination
        number_of_inscriptions = 13
        for inscription_num in range(number_of_inscriptions):
            Inscription.objects.create(name='Nombre %s' % inscription_num, last_name='Apellidos %s' % inscription_num,
                                       address='Dirección %s' % inscription_num, country='Ciudad %s' % inscription_num,
                                       gender=0, postal_code=12345,
                                       dni=12345678901, birth_date=datetime.datetime.now(), phone=12345678,
                                       email='email@email%s.com' % inscription_num, average_time=1,
                                       email_confirm='email@email%s.com' % inscription_num, race_rules=True, )

    def test_view_url_exists_at_desired_location(self):
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, 200)

    def test_view_url_accessible_by_name(self):
        resp = self.client.get(reverse('inscription-list'))
        self.assertEqual(resp.status_code, 200)

    def test_view_uses_correct_template(self):
        resp = self.client.get(reverse('inscription-list'))
        self.assertEqual(resp.status_code, 200)

        self.assertTemplateUsed(resp, 'inscription/list.html')

    # Ponerle el atributo paginate_by a la clase InscriptionList para que pasen las pruebas
    def test_pagination_is_ten(self):
        resp = self.client.get(reverse('inscription-list'))
        self.assertEqual(resp.status_code, 200)
        self.assertTrue('is_paginated' in resp.context)
        self.assertTrue(resp.context['is_paginated'] == True)
        self.assertTrue(len(resp.context['object_list']) == 10)

    def test_lists_all_inscriptions(self):
        # Obtener 2da página y confirmar que tiene exactamente 3 elementos
        resp = self.client.get(reverse('inscription-list') + '?page=2')
        self.assertEqual(resp.status_code, 200)
        self.assertTrue('is_paginated' in resp.context)
        self.assertTrue(resp.context['is_paginated'] == True)
        self.assertTrue(len(resp.context['object_list']) == 3)


# MicroPython SH1106 OLED driver
#
# Pin Map I2C for ESP8266
#   - 3v - xxxxxx   - Vcc
#   - G  - xxxxxx   - Gnd
#   - D2 - GPIO 5   - SCK / SCL
#   - D1 - GPIO 4   - DIN / SDA
#   - D0 - GPIO 16  - Res (required, unless a Hardware reset circuit is connected)
#   - G  - xxxxxx     CS
#   - G  - xxxxxx     D/C
#
# Pin's for I2C can be set almost arbitrary
#
from machine import Pin, I2C
import sh1106  # 用于oled屏幕的显示

# 创建I2C对象，指定了SCL引脚和SDA引脚的GPIO编号以及通信频率
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)
# 创建sh1106.SH1106_I2C对象
# 执行显示屏的尺寸为128*64
# 使用前面创建的i2c对象进行通信
# GPIO引脚16作为复位引脚
# i2c的地址为0x3C
display = sh1106.SH1106_I2C(128, 64, i2c, Pin(16), 0x3C)
display.sleep(False)  # 这行代码调用sleep()方法，将显示屏从睡眠模式中唤醒。

# 这行代码使用fill()方法清空显示屏上的内容。参数0表示黑色，将显示屏填充为黑色，相当于清空屏幕。
display.fill(0)

# 这行代码使用text()方法在坐标（0,0）的位置显示文本内容为"Testing 1"。最后一个参数1表示颜色为白色。
display.hline(0, 0, 1, 1)
display.text("Testing 1", 0, 0, 1)
display.text("hello ", 6, 0, 1)

# 之前进行的显示操作刷新到屏幕上，使得内容可见。
display.show()


import math
from tokenize import group
import torch
import torch.nn as nn
import torch.nn.functional as F

class PUNet(nn.Module):

    def __init__(self, depth = [1, 1, 1, 1, 2]):
        super(PUNet, self).__init__()

        base_channel = 32

        # encoder
        self.Encoder = nn.ModuleList([
            BasicConv(base_channel, base_channel, 3, 1),
            nn.Sequential(*[LKB(base_channel) for _ in range(depth[0])]),
            Down_scale(base_channel),
            BasicConv(base_channel*2, base_channel*2, 3, 1),
            nn.Sequential(*[LKB(base_channel*2) for _ in range(depth[1])]),
            Down_scale(base_channel*2),
            BasicConv(base_channel*4, base_channel*4, 3, 1),
            nn.Sequential(*[LKB(base_channel*4) for _ in range(depth[2])]),
            Down_scale(base_channel*4),
        ])

        # Middle
        self.middle = nn.Sequential(*[LKB(base_channel*8) for _ in range(depth[3])])

        # decoder
        self.Decoder = nn.ModuleList([
            Up_scale(base_channel*8),
            BasicConv(base_channel*8, base_channel*4, 3, 1),
            nn.Sequential(*[LKB(base_channel*4) for _ in range(depth[2])]),
            Up_scale(base_channel*4),
            BasicConv(base_channel*4, base_channel*2, 3, 1),
            nn.Sequential(*[LKB(base_channel*2) for _ in range(depth[1])]),
            Up_scale(base_channel*2),
            BasicConv(base_channel*2, base_channel, 3, 1),
            nn.Sequential(*[LKB(base_channel) for _ in range(depth[0])]),
        ])

        # conv
        self.conv_first = BasicConv(3, base_channel, 3, 1)
        self.conv_last = nn.Conv2d(base_channel, 3, 3, 1, 1)
        self.refine = nn.Sequential(*[LKB(base_channel) for i in range(depth[4])])

    def skip_con(self, shortcuts_l, shortcuts_r):
        refine_l, refine_r = [], []
        for i in range(len(shortcuts_l)):
            shortcut_l, shortcut_r = shortcuts_l[i], shortcuts_r[i]
            # stereo fusion

            refine_l.append(shortcut_l)
            refine_r.append(shortcut_r)
        return refine_l, refine_r

    def encoder(self, x):
        shortcuts = []
        for i in range(len(self.Encoder)):
            x = self.Encoder[i](x)
            if (i + 2) % 3 == 0 :
                shortcuts.append(x)

        return shortcuts, x

    def decoder(self, x, shortcuts):
        index = len(shortcuts)
        for i in range(len(self.Decoder)):
            if (i + 2) % 3 ==0:
                index = index - 1
                x = torch.cat([x, shortcuts[index]], 1)
            x = self.Decoder[i](x)

        return x

    def to_one(self, x):
        return (torch.tanh(x) + 1) / 2

    def forward(self, x):
        x_l, x_r = x[:,:3,:,:], x[:,3:,:,:]
        x_l, x_r = self.conv_first(x_l), self.conv_first(x_r)
        shortcuts_l, x_l = self.encoder(x_l)
        shortcuts_r, x_r = self.encoder(x_r)
        x_l, x_r =  self.middle(x_l), self.middle(x_r)
        shortcuts_l, shortcuts_r = self.skip_con(shortcuts_l, shortcuts_r)
        x_l, x_r = self.decoder(x_l, shortcuts_l), self.decoder(x_r, shortcuts_r)
        x_l, x_r = self.refine(x_l), self.refine(x_r)
        x_l, x_r = self.conv_last(x_l), self.conv_last(x_r)
        x_l, x_r = self.to_one(x_l), self.to_one(x_r)
        return x_l, x_r

class BasicConv(nn.Module):
    def __init__(self, in_channel, out_channel, kernel_size, stride, bias=True, norm=False, activation=True, transpose=False, groups=True):
        super(BasicConv, self).__init__()
        if bias and norm:
            bias = False

        padding = kernel_size // 2
        layers = list()
        if transpose:
            padding = kernel_size // 2 -1
            layers.append(nn.ConvTranspose2d(in_channel, out_channel, kernel_size, padding=padding, stride=stride, bias=bias))
        else:
            layers.append(nn.Conv2d(in_channel, out_channel, kernel_size, padding=padding, stride=stride, bias=bias))
        if norm:
            # layers.append(nn.LayerNorm(out_channel))
            layers.append(nn.InstanceNorm2d(out_channel))
        if activation:
            layers.append(nn.GELU())
        self.main = nn.Sequential(*layers)

    def forward(self, x):
        return self.main(x)

class GroupConv(nn.Module):
    def __init__(self, dim, kernel_size, stride=1):
        super(GroupConv, self).__init__()
        padding = kernel_size // 2
        self.main = nn.Conv2d(dim, dim, kernel_size, padding=padding, stride=stride, bias=True, groups=dim)

    def forward(self, x):
        return self.main(x)

class MLP(nn.Module):
    def __init__(self, dim_in, din_out):
        super(MLP, self).__init__()
        self.main = nn.Conv2d(dim_in, din_out, 1, 1)

    def forward(self, x):
        return self.main(x)

class LKB(nn.Module):
    def __init__(self, dim):
        super(LKB, self).__init__()
        self.layer_1 = nn.Sequential(*[
            LayerNorm2d(dim),
            MLP(dim, dim*2),
            GroupConv(dim*2, 7),
            MLP(dim*2, dim)
        ])
        self.layer_2 = nn.Sequential(*[
            LayerNorm2d(dim),
            MLP(dim, dim*2),
            nn.GELU(),
            MLP(dim*2, dim)
        ])

    def forward(self, x):
        x = self.layer_1(x) + x
        x = self.layer_2(x) + x
        return x

class RB(nn.Module):
    def __init__(self, channels):
        super(RB, self).__init__()
        self.layer_1 = BasicConv(channels, channels, 3, 1)
        self.layer_2 = BasicConv(channels, channels, 3, 1)

    def forward(self, x):
        y = self.layer_1(x)
        y = self.layer_2(y)
        return y + x

class RDB(nn.Module):
    def __init__(self, dim, gd=32):
        super(RDB, self).__init__()
        # gc: growth channel, i.e. intermediate channels
        self.conv1 = BasicConv(dim, gd, 3, 1)
        self.conv2 = BasicConv(dim + gd, gd, 3, 1)
        self.conv3 = BasicConv(dim + gd * 2, gd, 3, 1)
        self.conv4 = BasicConv(dim + gd * 3, gd, 3, 1)
        self.conv5 = BasicConv(dim + gd * 4, dim, 3, 1)

    def forward(self, x):
        x1 = self.conv1(x)
        x2 = self.conv2(torch.cat((x, x1), 1))
        x3 = self.conv3(torch.cat((x, x1, x2), 1))
        x4 = self.conv4(torch.cat((x, x1, x2, x3), 1))
        x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
        return x5 * 0.2 + x

class RRDB(nn.Module):
    '''Residual in Residual Dense Block'''

    def __init__(self, dim, gc=32):
        super(RRDB, self).__init__()
        self.RDB1 = RDB(dim, gc)
        self.RDB2 = RDB(dim, gc)
        self.RDB3 = RDB(dim, gc)

    def forward(self, x):
        out = self.RDB1(x)
        out = self.RDB2(out)
        out = self.RDB3(out)
        return out * 0.2 + x

class CSI(nn.Module):
    def __init__(self, dim):
        # cross-scale interaraction
        super(CSI, self).__init__()
        self.low_up1 = nn.Sequential(*[Up_scale(dim*4), RRDB(dim*2)])
        self.low_up2 = nn.Sequential(*[Up_scale(dim*2), RRDB(dim)])

        self.mid_up = nn.Sequential(*[Up_scale(dim*2), RRDB(dim)])
        self.mid_down = nn.Sequential(*[Down_scale(dim*2), RRDB(dim*4)])

        self.high_down1 = nn.Sequential(*[Down_scale(dim), RRDB(dim*2)])
        self.high_down2 = nn.Sequential(*[Down_scale(dim*2), RRDB(dim*4)])

        self.conv_l = BasicConv(dim*12, dim*4, 1, 1)
        self.conv_m = BasicConv(dim*6, dim*2, 1, 1)
        self.conv_h = BasicConv(dim*3, dim, 1, 1)

    def forward(self, shortcuts):
        high, mid, low = shortcuts[0], shortcuts[1], shortcuts[2]

        l2m = self.low_up1(low)
        l2h = self.low_up2(l2m)
        m2h = self.mid_up(mid)
        m2l = self.mid_down(mid)
        h2m = self.high_down1(high)
        h2l = self.high_down2(h2m)

        low = self.conv_l(torch.cat([low, m2l, h2l], 1))
        mid = self.conv_m (torch.cat([l2m, mid, h2m], 1))
        high = self.conv_h(torch.cat([l2h, m2h, high], 1))

        return [high, mid, low]

class LayerNormFunction(torch.autograd.Function):

    @staticmethod
    def forward(ctx, x, weight, bias, eps):
        ctx.eps = eps
        N, C, H, W = x.size()
        mu = x.mean(1, keepdim=True)
        var = (x - mu).pow(2).mean(1, keepdim=True)
        y = (x - mu) / (var + eps).sqrt()
        ctx.save_for_backward(y, var, weight)
        y = weight.view(1, C, 1, 1) * y + bias.view(1, C, 1, 1)
        return y

    @staticmethod
    def backward(ctx, grad_output):
        eps = ctx.eps

        N, C, H, W = grad_output.size()
        y, var, weight = ctx.saved_variables
        g = grad_output * weight.view(1, C, 1, 1)
        mean_g = g.mean(dim=1, keepdim=True)

        mean_gy = (g * y).mean(dim=1, keepdim=True)
        gx = 1. / torch.sqrt(var + eps) * (g - y * mean_gy - mean_g)
        return gx, (grad_output * y).sum(dim=3).sum(dim=2).sum(dim=0), grad_output.sum(dim=3).sum(dim=2).sum(
            dim=0), None

class LayerNorm2d(nn.Module):

    def __init__(self, channels, eps=1e-6):
        super(LayerNorm2d, self).__init__()
        self.register_parameter('weight', nn.Parameter(torch.ones(channels)))
        self.register_parameter('bias', nn.Parameter(torch.zeros(channels)))
        self.eps = eps

    def forward(self, x):
        return LayerNormFunction.apply(x, self.weight, self.bias, self.eps)

class Down_scale(nn.Module):
    def __init__(self, in_channel):
        super(Down_scale, self).__init__()
        self.main = BasicConv(in_channel, in_channel*2, 3, 2)

    def forward(self, x):
        return self.main(x)

class Up_scale(nn.Module):
    def __init__(self, in_channel):
        super(Up_scale, self).__init__()
        self.main = BasicConv(in_channel, in_channel//2, kernel_size=4, activation=True, stride=2, transpose=True)

    def forward(self, x):
        return self.main(x)


guess=1
while guess<=5:
    sum=int(input("Enter your guess\n"))
    if sum==16:
        print("Your guess is right,You won\n")
        break
    else:
        print("Your guess is wrong.Try Again\n")
    guess+=1
else:
    print("You lose")

#We have to make a guessing game in which we have to guess the
#particular number is right or wrong and we will be provided with 5 chances


import json
import pickle
import numpy as np

__locations = None
__property_types = None
__attachement_types = None
__data_columns = None
__model = None

def get_estimated_price(location,sqft,bed,bath,property_type,attachement):

    loc_index = __data_columns.index(location)
    p_type_index = __data_columns.index(property_type)
    attachement_index = __data_columns.index(attachement)

    x = np.zeros(len(__data_columns))
    x[0] = bed
    x[1] = bath
    x[2] = sqft
    if loc_index >= 0:
        x[loc_index] = 1
    if p_type_index >= 0:
        x[p_type_index] = 1
    if attachement_index >= 0:
        x[attachement_index] = 1

    return round(__model.predict([x])[0],0)

def get_location_names():
    return __locations

def get_property_types():
    return __property_types

def get_attachement_types():
    return __attachement_types

def load_saved_artifacts():
    print("loading saved artifacts...start")
    global __data_columns
    global __locations
    global __property_types
    global __attachement_types

    with open("/Users/omarosefau/PRPP/Server/artifacts/columns.json",'r') as f:
        __data_columns = json.load(f)['data_columns']
        __locations = __data_columns[3:6]
        __property_types = __data_columns[6:10]
        __attachement_types = __data_columns[10:]

    global __model
    with open("/Users/omarosefau/PRPP/Model/pei_re_prediction_rf.pickle",'rb') as f:
        __model = pickle.load(f)

    print("loading saved artifacts...done")

if __name__ == '__main__':
    load_saved_artifacts()
    print(get_location_names())
    print(get_property_types())
    print(get_attachement_types())


"""Tests for nextdns package."""
import json
import re
from http import HTTPStatus

import aiohttp
import pytest
from aioresponses import aioresponses

from nextdns import (
    ATTR_ANALYTICS,
    ATTR_CLEAR_LOGS,
    ATTR_GET_LOGS,
    ATTR_LOGS,
    ATTR_PARENTAL_CONTROL_CATEGORIES,
    ATTR_PARENTAL_CONTROL_SERVICES,
    ATTR_PROFILE,
    ATTR_PROFILES,
    ATTR_TEST,
    ENDPOINTS,
    MAP_SETTING,
    ApiError,
    InvalidApiKeyError,
    NextDns,
    ProfileIdNotFoundError,
    ProfileNameNotFoundError,
    SettingNotSupportedError,
)
from nextdns.const import ATTR_BLOCK_PAGE

PROFILE_ID = "fakepr"

@pytest.mark.asyncio
async def test_valid_data():  # pylint: disable=too-many-locals,too-many-statements
    """Test with valid data."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)
    with open("tests/fixtures/dnssec.json", encoding="utf-8") as file:
        dnssec_data = json.load(file)
    with open("tests/fixtures/encryption.json", encoding="utf-8") as file:
        encryption_data = json.load(file)
    with open("tests/fixtures/ip_versions.json", encoding="utf-8") as file:
        ip_versions_data = json.load(file)
    with open("tests/fixtures/protocols.json", encoding="utf-8") as file:
        protocols_data = json.load(file)
    with open("tests/fixtures/status.json", encoding="utf-8") as file:
        status_data = json.load(file)
    with open("tests/fixtures/test.json", encoding="utf-8") as file:
        test_data = json.load(file)
    with open("tests/fixtures/profile.json", encoding="utf-8") as file:
        profile_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.get(
            ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="dnssec"),
            payload=dnssec_data,
        )
        session_mock.get(
            ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="encryption"),
            payload=encryption_data,
        )
        session_mock.get(
            ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="ipVersions"),
            payload=ip_versions_data,
        )
        session_mock.get(
            ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="protocols"),
            payload=protocols_data,
        )
        session_mock.get(
            ENDPOINTS[ATTR_ANALYTICS].format(profile_id=PROFILE_ID, type="status"),
            payload=status_data,
        )
        session_mock.get(
            ENDPOINTS[ATTR_TEST].format(profile_id=PROFILE_ID), payload=test_data
        )
        session_mock.get(
            ENDPOINTS[ATTR_PROFILE].format(profile_id=PROFILE_ID), payload=profile_data
        )

        nextdns = await NextDns.create(session, "fakeapikey")

        analitycs = await nextdns.get_all_analytics(PROFILE_ID)
        dnssec = analitycs.dnssec
        encryption = analitycs.encryption
        ip_versions = analitycs.ip_versions
        protocols = analitycs.protocols
        status = analitycs.status
        connection_status = await nextdns.connection_status(PROFILE_ID)
        settings = await nextdns.get_settings(PROFILE_ID)

    await session.close()

    assert len(nextdns.profiles) == 1
    assert nextdns.profiles[0].id == PROFILE_ID
    assert nextdns.profiles[0].fingerprint == "fakeprofile12"
    assert nextdns.profiles[0].name == "Fake Profile"

    assert dnssec.not_validated_queries == 793765
    assert dnssec.validated_queries == 49451
    assert dnssec.validated_queries_ratio == 5.9

    assert encryption.encrypted_queries == 1380260
    assert encryption.unencrypted_queries == 40
    assert encryption.encrypted_queries_ratio == 100.0

    assert ip_versions.ipv6_queries == 42117
    assert ip_versions.ipv4_queries == 1338183
    assert ip_versions.ipv6_queries_ratio == 3.1

    assert protocols.doh_queries == 99999
    assert protocols.doh3_queries == 88888
    assert protocols.doq_queries == 55555
    assert protocols.dot_queries == 101010
    assert protocols.tcp_queries == 33333
    assert protocols.udp_queries == 44444
    assert protocols.doh_queries_ratio == 23.6
    assert protocols.doh3_queries_ratio == 21.0
    assert protocols.doq_queries_ratio == 13.1
    assert protocols.dot_queries_ratio == 23.9
    assert protocols.tcp_queries_ratio == 7.9
    assert protocols.udp_queries_ratio == 10.5

    assert status.all_queries == 1380300
    assert status.allowed_queries == 5452
    assert status.blocked_queries == 530805
    assert status.default_queries == 837764
    assert status.relayed_queries == 6279
    assert status.blocked_queries_ratio == 38.5

    assert connection_status.connected is True
    assert connection_status.profile_id == PROFILE_ID

    assert settings.block_page is False
    assert settings.cache_boost is True
    assert settings.cname_flattening is True
    assert settings.anonymized_ecs is True
    assert settings.logs is True
    assert settings.logs_location == "ch"
    assert settings.logs_retention == 720
    assert settings.web3 is True
    assert settings.allow_affiliate is True
    assert settings.block_disguised_trackers is True
    assert settings.ai_threat_detection is True
    assert settings.block_csam is True
    assert settings.block_ddns is True
    assert settings.block_nrd is True
    assert settings.block_parked_domains is True
    assert settings.cryptojacking_protection is True
    assert settings.dga_protection is True
    assert settings.dns_rebinding_protection is True
    assert settings.google_safe_browsing is True
    assert settings.idn_homograph_attacks_protection is True
    assert settings.threat_intelligence_feeds is True
    assert settings.typosquatting_protection is True
    assert settings.block_bypass_methods is True
    assert settings.safesearch is False
    assert settings.youtube_restricted_mode is False

    assert settings.block_9gag is False
    assert settings.block_amazon is False
    assert settings.block_bereal is False
    assert settings.block_blizzard is False
    assert settings.block_chatgpt is False
    assert settings.block_dailymotion is False
    assert settings.block_discord is False
    assert settings.block_disneyplus is False
    assert settings.block_ebay is False
    assert settings.block_facebook is False
    assert settings.block_fortnite is False
    assert settings.block_google_chat is False
    assert settings.block_hbomax is False
    assert settings.block_hulu is False
    assert settings.block_imgur is False
    assert settings.block_instagram is False
    assert settings.block_leagueoflegends is False
    assert settings.block_mastodon is False
    assert settings.block_messenger is False
    assert settings.block_minecraft is False
    assert settings.block_netflix is False
    assert settings.block_pinterest is False
    assert settings.block_playstation_network is False
    assert settings.block_primevideo is False
    assert settings.block_reddit is False
    assert settings.block_roblox is False
    assert settings.block_signal is False
    assert settings.block_skype is False
    assert settings.block_snapchat is False
    assert settings.block_spotify is False
    assert settings.block_steam is False
    assert settings.block_telegram is False
    assert settings.block_tiktok is False
    assert settings.block_tinder is False
    assert settings.block_tumblr is False
    assert settings.block_twitch is False
    assert settings.block_twitter is False
    assert settings.block_vimeo is False
    assert settings.block_vk is False
    assert settings.block_whatsapp is False
    assert settings.block_xboxlive is False
    assert settings.block_youtube is False
    assert settings.block_zoom is False

    assert settings.block_dating is True
    assert settings.block_gambling is True
    assert settings.block_piracy is True
    assert settings.block_porn is True
    assert settings.block_social_networks is False
    assert settings.block_online_gaming is False
    assert settings.block_video_streaming is False

    assert nextdns.get_profile_name(PROFILE_ID) == "Fake Profile"
    assert nextdns.get_profile_id("Fake Profile") == PROFILE_ID

@pytest.mark.asyncio
async def test_profile_id_not_found():
    """Test with wrong profile id."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)

        nextdns = await NextDns.create(session, "fakeapikey")

    await session.close()

    with pytest.raises(ProfileIdNotFoundError):
        nextdns.get_profile_name("xxyyxx")

@pytest.mark.asyncio
async def test_profile_name_not_found():
    """Test with wrong name id."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)

        nextdns = await NextDns.create(session, "fakeapikey")

    await session.close()

    with pytest.raises(ProfileNameNotFoundError):
        nextdns.get_profile_id("Profile Name")

@pytest.mark.asyncio
async def test_clear_logs():
    """Test clear_logs() method."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.delete(
            ENDPOINTS[ATTR_CLEAR_LOGS].format(profile_id=PROFILE_ID),
            status=HTTPStatus.NO_CONTENT.value,
        )

        nextdns = await NextDns.create(session, "fakeapikey")

        result = await nextdns.clear_logs(PROFILE_ID)

    await session.close()

    assert result is True

@pytest.mark.asyncio
async def test_get_logs():
    """Test get_logs() method."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    with open("tests/fixtures/logs.csv", encoding="utf-8") as file:
        logs = file.read()

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.get(
            ENDPOINTS[ATTR_GET_LOGS].format(profile_id=PROFILE_ID),
            status=HTTPStatus.OK.value,
            payload=logs,
        )

        nextdns = await NextDns.create(session, "fakeapikey")

        result = await nextdns.get_logs(PROFILE_ID)

    await session.close()

    assert result == logs

@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("setting", "url"),
    [
        ("block_page", ENDPOINTS[ATTR_BLOCK_PAGE].format(profile_id=PROFILE_ID)),
        (
            "block_tinder",
            MAP_SETTING["block_tinder"].url.format(
                profile_id=PROFILE_ID, service=MAP_SETTING["block_tinder"].name
            ),
        ),
        (
            "block_piracy",
            MAP_SETTING["block_piracy"].url.format(
                profile_id=PROFILE_ID, category=MAP_SETTING["block_piracy"].name
            ),
        ),
    ],
)
async def test_set_setting(setting, url):
    """Test set_setting() method."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.patch(url, status=HTTPStatus.NO_CONTENT.value)

        nextdns = await NextDns.create(session, "fakeapikey")

        result = await nextdns.set_setting(PROFILE_ID, setting, True)

    await session.close()

    assert result is True

@pytest.mark.asyncio
async def test_set_parental_contrl_service():
    """Test set_setting() method for parental control service."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.patch(
            MAP_SETTING["block_tinder"].url.format(
                profile_id=PROFILE_ID, service=MAP_SETTING["block_tinder"].name
            ),
            status=HTTPStatus.NOT_FOUND.value,
            payload={"errors": [{"code": "notFound"}]},
        )
        session_mock.post(
            ENDPOINTS[ATTR_PARENTAL_CONTROL_SERVICES].format(profile_id=PROFILE_ID),
            status=HTTPStatus.NO_CONTENT.value,
        )

        nextdns = await NextDns.create(session, "fakeapikey")

        result = await nextdns.set_setting(PROFILE_ID, "block_tinder", True)

    await session.close()

    assert result is True

@pytest.mark.asyncio
async def test_set_parental_contrl_category():
    """Test set_setting() method for parental control category."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.patch(
            MAP_SETTING["block_piracy"].url.format(
                profile_id=PROFILE_ID, category=MAP_SETTING["block_piracy"].name
            ),
            status=HTTPStatus.NOT_FOUND.value,
            payload={"errors": [{"code": "notFound"}]},
        )
        session_mock.post(
            ENDPOINTS[ATTR_PARENTAL_CONTROL_CATEGORIES].format(profile_id=PROFILE_ID),
            status=HTTPStatus.NO_CONTENT.value,
        )

        nextdns = await NextDns.create(session, "fakeapikey")

        result = await nextdns.set_setting(PROFILE_ID, "block_piracy", True)

    await session.close()

    assert result is True

@pytest.mark.asyncio
async def test_set_not_supported_setting():
    """Test set_setting() method with not supported setting."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)

        nextdns = await NextDns.create(session, "fakeapikey")

        with pytest.raises(SettingNotSupportedError):
            await nextdns.set_setting(PROFILE_ID, "unsupported_setting", True)

    await session.close()

@pytest.mark.asyncio
async def test_invalid_api_key():
    """Test error when provided API key is invalid."""
    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], status=HTTPStatus.FORBIDDEN.value)

        with pytest.raises(InvalidApiKeyError):
            await NextDns.create(session, "fakeapikey")

    await session.close()

@pytest.mark.asyncio
async def test_api_error():
    """Test API error."""
    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(
            ENDPOINTS[ATTR_PROFILES],
            status=HTTPStatus.BAD_REQUEST.value,
            payload={"errors": [{"code": "badRequest"}]},
        )

        with pytest.raises(ApiError) as exc:
            await NextDns.create(session, "fakeapikey")

        assert "400, badRequest, None" in str(exc.value)

    await session.close()

@pytest.mark.asyncio
async def test_set_logs_retention():
    """Test set_logs_retention() method."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.patch(
            ENDPOINTS[ATTR_LOGS].format(profile_id=PROFILE_ID),
            status=HTTPStatus.NO_CONTENT.value,
        )

        nextdns = await NextDns.create(session, "fakeapikey")

        result = await nextdns.set_logs_retention(PROFILE_ID, 1)

    await session.close()

    assert result is True

@pytest.mark.asyncio
async def test_set_logs_retention_with_invalid_value():
    """Test set_logs_retention() method with invalid value."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)

        nextdns = await NextDns.create(session, "fakeapikey")

    await session.close()

    with pytest.raises(
        ValueError,
        match=re.escape(
            "Invalid logs retention value. "
            "Allowed values are: (1, 6, 24, 168, 720, 2160, 4320, 8760, 17520)"
        ),
    ):
        await nextdns.set_logs_retention(PROFILE_ID, 999)

@pytest.mark.asyncio
async def test_set_logs_location():
    """Test set_logs_location() method."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)
        session_mock.patch(
            ENDPOINTS[ATTR_LOGS].format(profile_id=PROFILE_ID),
            status=HTTPStatus.NO_CONTENT.value,
        )

        nextdns = await NextDns.create(session, "fakeapikey")

        result = await nextdns.set_logs_location(PROFILE_ID, "us")

    await session.close()

    assert result is True

@pytest.mark.asyncio
async def test_set_logs_location_with_invalid_value():
    """Test set_logs_location() method with invalid value."""
    with open("tests/fixtures/profiles.json", encoding="utf-8") as file:
        profiles_data = json.load(file)

    session = aiohttp.ClientSession()

    with aioresponses() as session_mock:
        session_mock.get(ENDPOINTS[ATTR_PROFILES], payload=profiles_data)

        nextdns = await NextDns.create(session, "fakeapikey")

    await session.close()

    with pytest.raises(
        ValueError,
        match=re.escape(
            "Invalid logs location value. Allowed values are: ('ch', 'eu', 'gb', 'us')"
        ),
    ):
        await nextdns.set_logs_location(PROFILE_ID, "pl")


def lcs(a,b,cache):
	for x in range(len(a)+1):
		for y in range(len(b)+1):
			if x==0 or y==0:
				cache[x][y]=0
			elif a[x-1]==b[y-1]:
				cache[x][y]=1+cache[x-1][y-1]
			else:
				cache[x][y]=max(cache[x-1][y],cache[x][y-1])
	return cache[-1][-1]

def main():
	a=input("Enter a\n")
	b=input("Enter b\n")
	cache = [[None for i in range(len(b)+1)] for j in range(len(a)+1)]

	# print(cache)
	print(lcs(a,b,cache))

if __name__ == '__main__':
	main()


from factory.cars.jeep import Jeep
from factory.cars.null_car import NullCar
from factory.cars.van import Van
from factory.loader import load_factory

class TestFactory:
    def test_jeep_created(self) -> None:
        factory = load_factory('jeep_factory')
        car = factory.create_car()
        assert isinstance(car, Jeep)

    def test_van_created(self) -> None:
        factory = load_factory('van_factory')
        car = factory.create_car()
        assert isinstance(car, Van)

    def test_null_car_created(self) -> None:
        factory = load_factory('unknown_car_factory')
        car = factory.create_car()
        assert isinstance(car, NullCar)


import tkinter as tk

counter = 0

def increment():
    global counter
    counter += 1
    label_1['text'] = f'Брояч: {counter}'

win = tk.Tk()
win.title('TkInter Labels demo')
win.geometry('600x300+500+200')

label_1 = tk.Label(win, text=f'Брояч: {counter}')
label_1.pack()

button_plus = tk.Button(win,
                        text='Increment counter',
                        background='blue',
                        activebackground='red',
                        foreground='yellow',
                        activeforeground='lime',
                        command=increment)
button_plus.pack()

win.mainloop()


"""OES Template Library"""

from oes.template.env import default_jinja2_env, get_jinja2_env, jinja2_env_context
from oes.template.expression import (
    Expression,
    structure_expression,
    unstructure_expression,
)
from oes.template.logic import (
    Condition,
    LogicAnd,
    LogicOr,
    evaluate,
    structure_condition,
    unstructure_and,
    unstructure_or,
)
from oes.template.template import Template, structure_template, unstructure_template
from oes.template.types import Context, Evaluable, LiteralValue, LiteralValueOrEvaluable

__all__ = [
    "LiteralValue",
    "Evaluable",
    "LiteralValueOrEvaluable",
    "Context",
    "default_jinja2_env",
    "jinja2_env_context",
    "get_jinja2_env",
    "Template",
    "structure_template",
    "unstructure_template",
    "Expression",
    "structure_expression",
    "unstructure_expression",
    "LogicAnd",
    "LogicOr",
    "Condition",
    "evaluate",
    "structure_condition",
    "unstructure_and",
    "unstructure_or",
]