from rest_framework import serializers

from src.constants import CREDIT_TRANSFER_TYPE, DEBIT_TRANSFER_TYPE, TRANSACTION_TYPES_CHOICES, TRANSFER_TRANSFER_TYPE
from .models import BankAccount, Transaction
from .utils import AccountValidator, update_transactions

class BankAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = BankAccount
        exclude = ('id', 'user')

class CreateAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = BankAccount
        fields = ('balance', 'first_name', 'last_name',)

    def create(self, validated_data):
        account_object = BankAccount(**validated_data)
        account_object.save()
        return account_object

class TransactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Transaction
        exclude = ('id',)

class CreateTransactionSerializer(serializers.Serializer):
    debit_account_number = serializers.CharField(allow_blank=True, required=False, max_length=100,
                                                 validators=[AccountValidator()])
    credit_account_number = serializers.CharField(allow_blank=True, required=False, max_length=100,
                                                  validators=[AccountValidator()])
    amount = serializers.DecimalField(max_digits=12, decimal_places=2, required=True)
    transaction_type = serializers.ChoiceField(choices=TRANSACTION_TYPES_CHOICES)

    def validate(self, attrs):
        if not attrs.get('debit_account_number') and not attrs('credit_account_number'):
            raise serializers.ValidationError('Provide either debit_account_number or credit_account_number')

        if attrs.get('transaction_type') == DEBIT_TRANSFER_TYPE and not attrs.get('debit_account_number'):
            raise serializers.ValidationError({"debit_account_number": ["Provide debit_account_number for debit"]})
        elif attrs.get('transaction_type') == CREDIT_TRANSFER_TYPE and not attrs.get('credit_account_number'):
            raise serializers.ValidationError({"credit_account_number": ["Provide credit_account_number for credit"]})
        elif attrs.get('transaction_type') == TRANSFER_TRANSFER_TYPE and (
                    not attrs.get('debit_account_number') or not attrs.get('credit_account_number')):
            raise serializers.ValidationError('Provide both debit_account_number or credit_account_number for transfer')

        return attrs

    def create(self, validated_data):
        is_successful = False
        message = ''
        if validated_data.get('transaction_type') == DEBIT_TRANSFER_TYPE:
            account_object = BankAccount.objects.get(account_number=validated_data.get('debit_account_number'))
            if account_object.balance >= validated_data.get('amount', 0):
                account_object.balance = account_object.balance - validated_data.get('amount', 0)
                account_object.save()
                is_successful = True

            if not is_successful:
                message = 'Not enough balance in the account'
            return update_transactions(debit_account=validated_data.get('debit_account_number'),
                                       amount=validated_data.get('amount'), is_successful=is_successful), message
        elif validated_data.get('transaction_type') == CREDIT_TRANSFER_TYPE:
            account_object = BankAccount.objects.get(account_number=validated_data.get('credit_account_number'))
            account_object.balance = account_object.balance + validated_data.get('amount', 0)
            account_object.save()
            return update_transactions(credit_account=validated_data.get('credit_account_number'),
                                       amount=validated_data.get('amount'), is_successful=True), message
        else:
            debit_account_object = BankAccount.objects.get(account_number=validated_data.get('debit_account_number'))
            credit_account_object = BankAccount.objects.get(account_number=validated_data.get('credit_account_number'))
            if debit_account_object.balance >= validated_data.get('amount', 0):
                debit_account_object.balance -= validated_data.get('amount', 0)
                credit_account_object.balance += validated_data.get('amount', 0)
                debit_account_object.save()
                credit_account_object.save()
                is_successful = True
            if not is_successful:
                message = 'Not enough balance in the account'
            return update_transactions(debit_account=validated_data.get('debit_account_number'),
                                       credit_account=validated_data.get('credit_account_number'),
                                       amount=validated_data.get('amount'), is_successful=is_successful), message


import collections
import logging
import os
import redis
from .client import Redis, StrictRedis

logger = logging.getLogger(__name__)  # pylint: disable=C0103

original_classes = collections.defaultdict(lambda: None)  # pragma: no cover
Redis_Patched = False
StrictRedis_Patched = False

def patch_redis_Redis(dbfile=None):
    """
    This class patches the redis module to replace the :class:`redis.Redis()`
    class with the redislite enhanced :class:`redislite.Redis()` class that uses
    the embedded redis server.

    Example:
        patch_redis_Redis('/tmp/redis.db')

    Notes:
        If the dbfile parameter is not passed, each instance of the
        redis.Redis() class with no arguments will get a separate redis
        server.  If the dbfile parameter is provided, all instances of
        the redis.Redis() class without a host or path argument will
        share/reference the same redis server.

    Args:
        dbfile(str):
            The name of the Redis db file to be used.  If this argument is
            passed all instances of the :class:`redis.Redis` class will share a
            single embedded redis server.

    Returns:
        This function does not return any values.
    """
    global original_classes
    global Redis_Patched

    if Redis_Patched:
        logger.info('redis.Redis class has already been patched.')
        return

    if dbfile:
        if dbfile == os.path.basename(dbfile):
            dbfile = os.path.join(os.getcwd(), dbfile)
        Redis.dbdir = os.path.dirname(dbfile)
        Redis.dbfilename = os.path.basename(dbfile)
        Redis.settingregistryfile = os.path.join(
            Redis.dbdir, Redis.dbfilename + '.settings'
        )

    original_classes['Redis'] = redis.Redis
    redis.Redis = Redis
    Redis_Patched = True

def unpatch_redis_Redis():
    """
    This class unpatches the :class:`redis.Redis()` class of the redis module
    and restores the original :class:`redis.Redis()`  class.

    Example:
        unpatch_redis_Redis()

    Returns:
        This function does not return any values.
    """
    global original_classes
    global Redis_Patched

    if original_classes['Redis']:    # pragma: no cover
        redis.Redis = original_classes['Redis']
        original_classes['Redis'] = None
    Redis_Patched = False

def patch_redis_StrictRedis(dbfile=None):
    """
    This class patches the redis module to replace the
    :param dbfile:
    :class:`redis.StrictRedis()` class with the redislite enhanced
    :class:`redislite.StrictRedis()` class that uses the embedded redis server.

    Example:
        patch_redis_StrictRedis('/tmp/redis.db')

    Notes:
        If the dbfile parameter is not passed, all :class:`redis.StrictRedis()`
        class with no arguments will get a separate redis server.  If the
        dbfile parameter is provided, all instances of the
        :class:`redis.Redis()` class passed with the same dbfile value
        will share/reference the same redis server.

    Args:
        dbfile(str):
            The name of the Redis db file to be used.  If this argument is
            passed all instances of the :class:`redis.Redis` class will share
            a single instance of the embedded redis server.

    Returns:
        This function does not return any values.
    """
    global original_classes
    global StrictRedis_Patched

    if StrictRedis_Patched:
        logger.info('redis.StrictRedis class has already been patched')
        return

    if dbfile:
        if dbfile == os.path.basename(dbfile):
            dbfile = os.path.join(os.getcwd(), dbfile)
        StrictRedis.dbdir = os.path.dirname(dbfile)
        StrictRedis.dbfilename = os.path.basename(dbfile)
        StrictRedis.settingregistryfile = os.path.join(
            StrictRedis.dbdir, StrictRedis.dbfilename + '.settings'
        )

    original_classes['StrictRedis'] = redis.StrictRedis
    redis.StrictRedis = StrictRedis
    StrictRedis_Patched = True

def unpatch_redis_StrictRedis():
    """
    This class unpatches the :class:`redis.StrictRedis()` class of the redis
    module and restores the original :class:`redis.StrictRedis()`  class.

    Example:
        unpatch_redis_StrictRedis()

    Returns:
        This function does not return any values.
    """
    global original_classes
    global StrictRedis_Patched

    if original_classes['StrictRedis']:   # pragma: no cover
        redis.StrictRedis = original_classes['StrictRedis']
        original_classes['StrictRedis'] = None
    StrictRedis_Patched = False

def patch_redis(dbfile=None):
    """
    Patch all the redis classes provided by redislite that have been patched.

    Example:
        patch_redis('/tmp/redis.db')

    Notes:
        If the dbfile parameter is not passed, each any instances of
        :class:`redis.StrictRedis()` class with no arguments will get a unique
        instance of the redis server.  If the dbfile parameter is provided, all
        instances of :class:`redis.Redis()` will share/reference the same
        instance of the redis server.

    Args:
        dbfile(str):
            The name of the Redis db file to be used.  If this argument is
            passed all instances of the :class:`redis.Redis()` class will
            share a single instance of the embedded redis server.

    Returns:
        This function does not return any values.
    """
    for patch in [patch_redis_Redis, patch_redis_StrictRedis]:
        patch(dbfile)

def unpatch_redis():
    """
    Unpatch all the redis classes provided by :mod:`redislite` that have been
    patched.

    Example:
        unpatch_redis()
    """
    for unpatch in [unpatch_redis_Redis, unpatch_redis_StrictRedis]:
        unpatch()


import sys
import os
import pytest
import io

from os.path import abspath
from os.path import dirname

sys.path.append(dirname(dirname(dirname(abspath(__file__)))))

import ctools.cspark as cspark

CSPARK_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)),"cspark.py")
assert os.path.exists(CSPARK_PATH)

fh_config = """
[spark]
name1.key1=value1
name2.key2: value2
"""

def test_spark_submit_cmd():
    from configparser import ConfigParser
    config = ConfigParser()
    config.read_string(fh_config)
    cmd = cspark.spark_submit_cmd(configdict=config['spark'])
    assert "name1.key1=value1" in cmd
    assert "name2.key2=value2" in cmd

TEST_RUN_SPARK_FILENAME='TEST_RUN_SPARK_FILENAME'
def test_spark_submit():
    # Run a Spark job and then check to make sure we got the result.
    # To get the result back, we have to save it in a file. But we only want to call
    # NamedTemporaryFile once, so we store the temporary file name in an environment variable.
    # For the same reason, we can't open the file in truncate mode.

    return

    raise RuntimeWarning("""WARNING: this test can make all test suite exit, likely because of the use of os.execvp in cspark.py. See comments inline in the test""")

    if not cspark.spark_available():
        return                  # don't test if no Spark is available

    # spark-submit will run in a subprocess

    if TEST_RUN_SPARK_FILENAME not in os.environ:
        import tempfile
        f = tempfile.NamedTemporaryFile(delete=False, mode='w+')
        os.environ[TEST_RUN_SPARK_FILENAME] = f.name
        f.close()

    """
    redo this so that it creates a file and submits it with spark-submit.

    with open(os.environ[TEST_RUN_SPARK_FILENAME], "w+") as f:
        if cspark.spark_submit(logLevel='error',pyfiles=[CSPARK_PATH], argv=[__file__]):
            from pyspark.sql import SparkSession
            spark = SparkSession.builder.appName("cspark_test:test_run_spark").getOrCreate()
            import operator
            mysum = spark.sparkContext.parallelize(range(1000000)).reduce(operator.add)
            f.truncate(0)
            f.write("{}\n".format(mysum))

            # Not sure what Simson tried to do here, but the file should not be closed,
            # because it is read from later. Neither there should be any exit from the program,
            # otherwise the test just exits (and the whole suite of unit tests ends to)
            #
            # It used to work before, but now doesn't, apparently, after changing
            # of the subprocess call in cspark.spark_submit to os.execvp

            # Commenting them out fixes the run in standalone run with python,
            # but when run from pytest it still exits.
            #
            # My guess is that it is because os.exec* commands replace the processes and do not return.
            #
            # --- P.Z.

            # f.close()
            # exit(0)             # spark job is finished

            data = f.read()
            assert data=='499999500000\n'
            print("spark ran successfully")
            f.close()
    os.unlink(os.environ[TEST_RUN_SPARK_FILENAME])
    """

if __name__=="__main__":
    # This is solely so that we can run under pytest
    # Don't remove it! You can also just run this program to see what happens
    # It should print "spark ran successfully."
    test_spark_submit_cmd()


# -*- coding: UTF-8 -*-
"""
title: 数组中数字出现的次数 II
在一个数组 nums 中除一个数字只出现一次之外，其他数字都出现了三次。请找出那个只出现一次的数字。

示例 1：
输入：nums = [3,4,3,3]
输出：4

示例 2：
输入：nums = [9,1,7,9,7,9,7]
输出：1

限制：
1 <= nums.length <= 10000
1 <= nums[i] < 2^31
"""
from collections import Counter
from typing import List

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        """哈希表"""
        for num, cnt in Counter(nums).items():
            if cnt == 1:
                return num

    def singleNumber_2(self, nums: List[int]) -> int:
        """
        分别统计每一位上1的个数，然后对3取余。该方法适用于所有的 一个数字出现一次，其余数字出现n次（对n取余）类问题
        Python不区分 有符号整数类型 和 无符号整数类型，所以Python需要对负数额外处理，而Java、C++不需要
        """
        res = 0
        # 用32位来表示一个int整数，分别统计每一位上1的个数
        for i in range(32):
            total = sum((num >> i) & 1 for num in nums)
            if total % 3:
                res |= 1 << i
        return ~(res ^ 0xffffffff) if res >> 31 else res

    def singleNumber_3(self, nums: List[int]) -> int:
        """
        有限状态自动机(数字电路设计)。负数也适用
        # 遍历数组，统计每个bit位上1的出现次数时，对于任一bit位，其统计结果都是 0 ——> 1 ——> 2 ——> 0（%3），转换为二进制便是 00 ——> 01 ——> 10 ——> 00
        # 因此可用两个int整数（twos、ones）来表示每个bit位上1的统计结果。以 最右位的统计结果为01 为例，则可表示成twos的最右位为0、ones的最右位为1
        # 统计过程可描述如下：
        #    1、遍历数组中的数字，统计结果以最右位为例。twos、ones的初始值均为0
        #    2、若第一个数字的最右位为1，则此时twos的最右位为0、ones的最右位为1
        #    3、若第二个数字的最右位也为1，则此时twos的最右位为1、ones的最右位为0
        #    4、若第三个数字的最右位也为1，则此时twos的最右位为0、ones的最右位为0
        #    5、……
        # 异或可以实现不进位的相加，0+0=0;0+1=1;1+0=1;1+1=0。即 ones = ones ^ num; twos = twos ^ num
        # twos、ones不会同时为1，当ones为1时，twos必为0；当ones为0时，twos可以为1。即 ones = ones & ~twos; twos = twos & ~ones
        # 最终统计结果一定是01，即 twos的所有位均为0、ones等于要查找的那个出现一次的数字
        """
        ones, twos = 0, 0
        for num in nums:
            # 下面这两句的顺序不能换，先计算低位，再计算高位。先把num不进位加到ones上
            ones = (ones ^ num) & ~twos
            twos = (twos ^ num) & ~ones
        return ones

if __name__ == '__main__':
    print(Solution().singleNumber_2([9, -1, -7, 9, -7, -7, 9]))


#!/usr/bin/python

import tweepy, sys

#Récupération des arguments de la commande
arguments = sys.argv
texte = arguments[1]
mediaAUpluoad = arguments[2]

#Identifiants API
API_KEY = ''
API_secret = ''
BAERER_TOKEN = ''
access_token = ''
access_token_secret = ''

#Connexion API
auth = tweepy.OAuthHandler(API_KEY, API_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

#Fonctions de Tweet
def post_tweet(text):
    response = api.update_status(text)
    return response

def upload_media(text, filename):
    media = api.media_upload(filename)
    response = api.update_status(text, media_ids=[media.media_id_string])
    return response

print(upload_media(texte, mediaAUpluoad))


from question_model import Question
from data import question_data
from quiz_brain import QuizBrain

question_bank = []

#Creando una lista de objetos
for elemento_lista in question_data:
    question_bank.append(Question(elemento_lista["question"], elemento_lista["correct_answer"]))

#Imprimiendo el objeto dentro de la lista con atributo text
# print(question_bank[1].text)

quiz = QuizBrain(question_bank)
while quiz.still_has_questions():
    quiz.next_question()

print("Terminaste el quiz")
print(f"Tu puntaje final es: {quiz.puntaje}/{quiz.question_number}")


#!/usr/bin/python
#
# Utility script to copy the pictures to the correct directory in the correct format
#
# Usage:
#    ./copy-pictures.py -s /tmp/pictures/ -t site/static/static/pictures/
import os
import sys
import re
import argparse
from shutil import copyfile

def _parse_args(argv):
    parser = argparse.ArgumentParser(description='Copy pictures and normalize file names')
    parser.add_argument('-s', '--source', required=True,
                        help='Source directory')
    parser.add_argument('-t', '--target', required=True,
                        help='Source directory')

    args = parser.parse_args()
    source_dir = args.source
    target_dir = args.target
    return source_dir, target_dir

def main(argv):
    # p = re.compile('A\. Confinamiento(\d*)\.png')
    p = re.compile('A\. Confinamiento movil(\d*)\.png')
    source_dir, target_dir = _parse_args(argv)
    for file in os.listdir(source_dir):
        match = p.match(file)
        if match:
            count = int(match.group(1) or 1)
            source_path = os.path.join(source_dir, file)
            target_file = 'picture-%s.png' % count
            target_path = os.path.join(target_dir, target_file)
            print("Copying '%s' to '%s'" % (source_path, target_path))
            copyfile(source_path, target_path)

if __name__ == "__main__":
    main(sys.argv[1:])


from os.path import join, exists, basename
from sqlite3.dbapi2 import Cursor
from six.moves import cPickle as pickle #for performance
from shutil import move
from os import makedirs, listdir, rmdir
import sys, re
from typing import List
import cv2
import sqlite3
import warnings
from numpy.core.numeric import Inf
from tqdm import tqdm
import numpy as np
import argparse
from face_recognition import face_encodings

PREFIX_RETINA = 'models/retinaface-R50/R50'
RETINA_FOLDER = './insightface/detection/RetinaFace/'
sys.path.insert(1, RETINA_FOLDER)
import random
verbose = False
# HCVM stand for "Human centric video matting challenge" (https://maadaa.ai/cvpr2021-human-centric-video-matting-challenge/)

from face_detect import (RetinaFace, get_videos_infos, save_face,
                         save_log, get_annotations, clean_annotations,
                         save_face_tmp, parse_string, clusterFaces)

def detect_crop_and_identify(dataset, method, compression, label, nb_frames_processed,
                             random_sample, db_folder, db_file, output_folder, face_size_threshold = None):

    detector = RetinaFace(PREFIX_RETINA, 0, 0, network='net3', vote=True)

    makedirs(db_folder, exist_ok=True)
    print("Saved in database : ", join(db_folder, db_file))
    conn = sqlite3.connect(db_folder + db_file)
    db = conn.cursor()

    video_files = get_videos_infos(db, dataset, method, compression, label)
    video_files = list(filter(lambda e: not (re.match(r"^laptop_a\d{4}_(in|out)door\.mp4$", e[3]) is None),
                              video_files)) # Only keep HCVM files (cf. face_detect_hcvm.py)
    print("Processed {} videos".format(len(video_files)))

    annotations_all = []
    for (videoid, dataset_folder, video_folder, video_file, nb_frames,
         frames) in tqdm(video_files):

        # Select random frames
        if frames == None:
            available_frames = range(nb_frames)
        else:
            available_frames = list(
                set(range(nb_frames)) -
                set(map(lambda x: int(x), frames.split(','))))
        nb_frames_processed = min(nb_frames_processed, len(available_frames))
        if random_sample:
            subset_frame = random.sample(available_frames, nb_frames_processed)
        else:
            subset_frame = available_frames[:nb_frames_processed]

        # Load video
        video_path = db_folder + dataset_folder + '/' + video_folder + '/' + video_file
        video = cv2.VideoCapture(video_path)

        # Create output folder
        video_name = re.sub(r"\.[^\.]*$", "", video_file)
        # images_folder = join(dataset_folder, re.sub("/videos$", "",  video_folder), 'images', video_name)
        images_folder = join(dataset_folder, re.sub("/videos$", "",  video_folder), "hcvm")
        tmp_folder = output_folder + images_folder + "/tmp/"
        # if the folder already exist, we concidere the job has already be done
        # before and we skip to next iteration
        # if exists(join(output_folder, images_folder)) : continue

        makedirs(join(output_folder, images_folder), exist_ok=True)

        # Save frames
        for frame_nb in tqdm(subset_frame):
            video.set(cv2.CAP_PROP_POS_FRAMES, frame_nb)
            ret, frame = video.read()
            if not ret:
                log_message = 'file ' + video_file + ' stopped at frame ' + str(
                    frame_nb) + ' (max ' + str(nb_frames) + ')'
                save_log('log', [log_message], prefix='Error: ')
                break

            annotations = get_annotations(frame, detector)
            annotations, bad_detection = clean_annotations(annotations, face_size_threshold)

            db.execute("INSERT INTO frames(videoid,frame_nb) VALUES (?,?)",
                       (videoid, frame_nb))
            frameid = db.execute("SELECT last_insert_rowid()").fetchone()[0]
            if bad_detection:
                infos = [dataset_folder, video_path, str(annotations), '']
                save_log(output_folder + 'error_detect.txt',
                         infos,
                         prefix='Error: ')

            i = 0
            for annotation in annotations:
                image_path_tmp = tmp_folder + "{}_{:0>5}_{:0>3}.jpg".format(video_name, frame_nb, i)

                face, x, y, w, h, p = save_face_tmp(frame, image_path_tmp, annotation)
                i += 1

                face_boxes = [(0,face.shape[1],face.shape[0],0)]

                annotations_all.append({"image_path_tmp": image_path_tmp,
                                        "annotation" : annotation,
                                        "crop_result": (x, y, w, h, p),
                                        "frame_nb"   : frame_nb,
                                        "frameid"    : frameid,
                                        "video_name" : video_name,
                                        "embedding"  : face_encodings(face, face_boxes)[0]})
        conn.commit()

    makedirs(join(output_folder, images_folder), exist_ok=True)

    # Cluster Identities
    with open(join(output_folder, images_folder, "annotations_all.pkl"), 'wb') as f: pickle.dump(annotations_all, f)
    # with open(join(output_folder, images_folder, "annotations_all.pkl"), 'rb') as f: annotations_all = pickle.load(f)
    if len(annotations_all) > 0:
        annotations_all = clusterFaces(annotations_all)
    else:
        warnings.warn("No faces were detected")

    image_names = []
    for i in range(len(annotations_all)):
        annotation  = annotations_all[i]["annotation"]
        frame_nb    = annotations_all[i]["frame_nb"]
        frameid     = annotations_all[i]["frameid"]
        identity    = annotations_all[i]["identity"]
        video_name  = annotations_all[i]["video_name"]
        crop_result    = annotations_all[i]["crop_result"]
        image_path_tmp = annotations_all[i]["image_path_tmp"]

        identity_folder = join(images_folder, "{:03}".format(identity))

        image_name = "{}_{:0>5}_{:0>3}.jpg".format(video_name, frame_nb, identity)

        # Manage de possibility that multiple face of the same frame
        # are concidered as having the same identity
        # (while the name already exist : create new name)
        j = 0
        while image_name in image_names:
            image_name = "{}_{:0>5}_{:0>3}_{:0>3}.jpg".format(video_name, frame_nb, identity,j)
            j += 1
        image_names.append(image_name)

        annotations_all[i]["image_path"] = join(output_folder, identity_folder, image_name)

        save_face(db, crop_result, identity_folder, image_name, identity,
                  frameid, image_path_tmp, output_folder)

        conn.commit()
        if len(listdir(tmp_folder)) < 1:
            rmdir(tmp_folder)
    with open(join(output_folder, images_folder, "annotations_all.pkl"), 'wb') as f: pickle.dump(annotations_all, f)
    conn.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--db",
                        default='./data/',
                        help="Path to the database")
    parser.add_argument("--dbFile",
                        default="Deepfake.db",
                        help="Path to the database (.db file)")
    parser.add_argument("-O",
                        "--output",
                        default="None",
                        type=str,
                        help="Where should the output be stored")
    parser.add_argument("-d",
                        "--dataset",
                        default="None",
                        type=str,
                        help="Which dataset to be considered")
    parser.add_argument("-m",
                        "--method",
                        default="None",
                        type=str,
                        help="Which method to be considered")
    parser.add_argument("-l",
                        "--label",
                        default="REAL",
                        type=str,
                        help="Which label to be considered")
    parser.add_argument("-c",
                        "--compression",
                        default="None",
                        type=str,
                        help="Which compression to be considered")
    parser.add_argument("-n",
                        "--nbFrames",
                        default=Inf,
                        type=int,
                        help="Number of frames per video to be considered")
    parser.add_argument("-r",
                        "--random",
                        default=False,
                        type=bool,
                        help="Select random frames or in natural order")
    parser.add_argument("-s",
                        "--face_size_threshold",
                        default=0.5,
                        type=float,
                        help="Faces are ignored : \
                            if (s >  1 and 'face width' < s) or \
                               (s <= 1 and 'face area'  < 'area of the biggest face' * s),\
                            recommended values s=0.5 or s=40")
    parser.add_argument("-v", "--verbose",
                        action='store_true',
                        help="Print more info")
    args = parser.parse_args()
    DB_FOLDER = parse_string(args.db, isFolder=True)
    DB_FILE = parse_string(args.dbFile)
    OUTPUT_FOLDER = DB_FOLDER if args.output == "None" else parse_string(
        args.output, isFolder=True)
    DATASET = parse_string(args.dataset)
    METHOD = parse_string(args.method)
    LABEL = parse_string(args.label)
    COMPRESSION = parse_string(args.compression)
    NB_FRAMES = args.nbFrames
    RANDOM = args.random
    FACE_SIZE_THRESHOLD = args.face_size_threshold

    verbose = args.verbose

    detect_crop_and_identify(DATASET, METHOD, COMPRESSION, LABEL, NB_FRAMES, RANDOM,
                             DB_FOLDER, DB_FILE, OUTPUT_FOLDER, FACE_SIZE_THRESHOLD)

    # The script is assumed to be run with docker :
    # docker run --gpus all -v "path/to/datasets/:/app/data"


import logging
from typing import Mapping, Any, List, Optional, Dict

from robocorp_ls_core.basic import implements
from robocorp_ls_core.client_base import LanguageServerClientBase
from robocorp_ls_core.protocols import (
    ILanguageServerClient,
    IIdMessageMatcher,
)
from robocorp_ls_core.lsp import (
    CodeLensTypedDict,
    CompletionsResponseTypedDict,
    CompletionItemTypedDict,
    CompletionResolveResponseTypedDict,
    PositionTypedDict,
    TextEditTypedDict,
)

log = logging.getLogger(__name__)

class LanguageServerClient(LanguageServerClientBase):
    pid: Optional[int] = None

    DEFAULT_TIMEOUT: Optional[int] = None

    def __init__(self, *args, **kwargs):
        from robocorp_ls_core.unittest_tools.fixtures import TIMEOUT

        LanguageServerClientBase.__init__(self, *args, **kwargs)

        self.DEFAULT_TIMEOUT = TIMEOUT

    @implements(ILanguageServerClient.settings)
    def settings(self, settings: Dict):
        self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "workspace/didChangeConfiguration",
                "params": settings,
            }
        )

    @implements(ILanguageServerClient.initialize)
    def initialize(
        self, root_path: str, msg_id=None, process_id=None, initialization_options=None
    ):
        from robocorp_ls_core.uris import from_fs_path

        root_uri = from_fs_path(root_path)

        msg_id = msg_id if msg_id is not None else self.next_id()
        msg = self.request(
            {
                "jsonrpc": "2.0",
                "id": msg_id,
                "method": "initialize",
                "params": {
                    "processId": process_id,
                    "rootPath": root_path,
                    "rootUri": root_uri,
                    "initializationOptions": initialization_options,
                    "capabilities": {
                        "workspace": {
                            "applyEdit": True,
                            "didChangeConfiguration": {"dynamicRegistration": True},
                            "didChangeWatchedFiles": {"dynamicRegistration": True},
                            "symbol": {"dynamicRegistration": True},
                            "executeCommand": {"dynamicRegistration": True},
                        },
                        "textDocument": {
                            "synchronization": {
                                "dynamicRegistration": True,
                                "willSave": True,
                                "willSaveWaitUntil": True,
                                "didSave": True,
                            },
                            "completion": {
                                "dynamicRegistration": True,
                                "completionItem": {
                                    "snippetSupport": True,
                                    "commitCharactersSupport": True,
                                },
                            },
                            "hover": {"dynamicRegistration": True},
                            "signatureHelp": {"dynamicRegistration": True},
                            "definition": {"dynamicRegistration": True},
                            "references": {"dynamicRegistration": True},
                            "documentHighlight": {"dynamicRegistration": True},
                            "documentSymbol": {"dynamicRegistration": True},
                            "codeAction": {"dynamicRegistration": True},
                            "codeLens": {"dynamicRegistration": True},
                            "formatting": {"dynamicRegistration": True},
                            "rangeFormatting": {"dynamicRegistration": True},
                            "onTypeFormatting": {"dynamicRegistration": True},
                            "rename": {"dynamicRegistration": True},
                            "documentLink": {"dynamicRegistration": True},
                        },
                    },
                    "trace": "off",
                },
            }
        )

        assert "capabilities" in msg["result"]
        return msg

    @implements(ILanguageServerClient.change_workspace_folders)
    def change_workspace_folders(
        self, added_folders: List[str], removed_folders: List[str]
    ) -> None:
        from robocorp_ls_core import uris
        import os.path

        added_folders_uri_name = [
            {"uri": uris.from_fs_path(s), "name": os.path.basename(s)}
            for s in added_folders
        ]
        removed_folders_uri_name = [
            {"uri": uris.from_fs_path(s), "name": os.path.basename(s)}
            for s in removed_folders
        ]
        self.request(
            {
                "jsonrpc": "2.0",
                "method": "workspace/didChangeWorkspaceFolders",
                "id": self.next_id(),
                "params": {
                    "event": {
                        "added": added_folders_uri_name,
                        "removed": removed_folders_uri_name,
                    }
                },
            }
        )

    @implements(ILanguageServerClient.open_doc)
    def open_doc(self, uri: str, version: int = 1, text: Optional[str] = None):
        self.request(
            {
                "jsonrpc": "2.0",
                "method": "textDocument/didOpen",
                "id": self.next_id(),
                "params": {
                    "textDocument": {
                        "uri": uri,
                        "languageId": "robotframework",
                        "version": version,
                        "text": text,
                    }
                },
            }
        )

    @implements(ILanguageServerClient.close_doc)
    def close_doc(self, uri: str):
        self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/didClose",
                "params": {"textDocument": {"uri": uri}},
            }
        )

    @implements(ILanguageServerClient.hover)
    def hover(self, uri: str, line: int, col: int):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/hover",
                "params": {
                    "textDocument": {"uri": uri},
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.change_doc)
    def change_doc(self, uri: str, version: int, text: str):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/didChange",
                "params": {
                    "textDocument": {"uri": uri, "version": version},
                    "contentChanges": [{"range": None, "rangeLength": 0, "text": text}],
                },
            }
        )

    def _build_completions_request(self, uri: str, line: int, col: int):
        return {
            "jsonrpc": "2.0",
            "id": self.next_id(),
            "method": "textDocument/completion",
            "params": {
                "textDocument": {"uri": uri},
                "position": {"line": line, "character": col},
            },
        }

    @implements(ILanguageServerClient.get_completions)
    def get_completions(
        self, uri: str, line: int, col: int
    ) -> CompletionsResponseTypedDict:
        return self.request(self._build_completions_request(uri, line, col))

    @implements(ILanguageServerClient.get_completions_async)
    def get_completions_async(
        self, uri: str, line: int, col: int
    ) -> Optional[IIdMessageMatcher[CompletionsResponseTypedDict]]:
        return self.request_async(self._build_completions_request(uri, line, col))

    @implements(ILanguageServerClient.request_resolve_completion)
    def request_resolve_completion(
        self, completion_item: CompletionItemTypedDict
    ) -> CompletionResolveResponseTypedDict:
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "completionItem/resolve",
                "params": completion_item,
            }
        )

    @implements(ILanguageServerClient.request_source_format)
    def request_source_format(self, uri: str):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/formatting",
                "params": {"textDocument": {"uri": uri}},
            }
        )

    @implements(ILanguageServerClient.request_code_action)
    def request_code_action(
        self, uri: str, line: int, col: int, endline: int, endcol: int
    ):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/codeAction",
                "params": {
                    "textDocument": {"uri": uri},
                    "range": {
                        "start": {"line": line, "character": col},
                        "end": {"line": endline, "character": endcol},
                    },
                    "context": {},
                },
            }
        )

    @implements(ILanguageServerClient.request_signature_help)
    def request_signature_help(self, uri, line, col):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/signatureHelp",
                "params": {
                    "textDocument": {"uri": uri},
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.request_hover)
    def request_hover(self, uri, line, col):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/hover",
                "params": {
                    "textDocument": {"uri": uri},
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.request_text_document_highlight)
    def request_text_document_highlight(self, uri, line, col):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/documentHighlight",
                "params": {
                    "textDocument": {"uri": uri},
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.request_references)
    def request_references(self, uri, line, col, include_declaration):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/references",
                "params": {
                    "textDocument": {"uri": uri},
                    "position": {"line": line, "character": col},
                    "context": {
                        "includeDeclaration": include_declaration,
                    },
                },
            }
        )

    @implements(ILanguageServerClient.request_folding_range)
    def request_folding_range(self, uri):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/foldingRange",
                "params": {"textDocument": {"uri": uri}},
            }
        )

    @implements(ILanguageServerClient.request_on_type_formatting)
    def request_on_type_formatting(
        self, uri: str, ch: str, line: int, col: int
    ) -> Optional[List[TextEditTypedDict]]:
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/onTypeFormatting",
                "params": {
                    "textDocument": {"uri": uri},
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.request_selection_range)
    def request_selection_range(self, doc_uri: str, positions: List[PositionTypedDict]):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/selectionRange",
                "params": {"textDocument": {"uri": doc_uri}, "positions": positions},
            }
        )

    @implements(ILanguageServerClient.request_code_lens)
    def request_code_lens(self, uri):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/codeLens",
                "params": {"textDocument": {"uri": uri}},
            }
        )

    @implements(ILanguageServerClient.request_resolve_code_lens)
    def request_resolve_code_lens(self, code_lens: CodeLensTypedDict):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "codeLens/resolve",
                "params": code_lens,
            }
        )

    @implements(ILanguageServerClient.request_document_symbol)
    def request_document_symbol(self, uri):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/document_symbol",
                "params": {"textDocument": {"uri": uri}},
            }
        )

    @implements(ILanguageServerClient.request_rename)
    def request_rename(self, uri: str, line: int, col: int, new_name: str):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/rename",
                "params": {
                    "textDocument": {
                        "uri": uri,
                    },
                    "position": {"line": line, "character": col},
                    "newName": new_name,
                },
            }
        )

    @implements(ILanguageServerClient.request_prepare_rename)
    def request_prepare_rename(self, uri: str, line: int, col: int):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/prepareRename",
                "params": {
                    "textDocument": {
                        "uri": uri,
                    },
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.request_provide_evaluatable_expression)
    def request_provide_evaluatable_expression(
        self, uri: str, line: int, col: int
    ) -> Optional[IIdMessageMatcher]:
        """
        :Note: This is a custom message (not part of the language server spec).

        :Note: async complete.
        """
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "robot/provideEvaluatableExpression",
                "params": {
                    "uri": uri,
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.request_workspace_symbols)
    def request_workspace_symbols(self, query: Optional[str] = None):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "workspace/symbol",
                "params": {"query": query},
            }
        )

    def request_cancel(self, message_id) -> None:
        """
        Requests that some processing is cancelled.
        """
        self.write(
            {
                "jsonrpc": "2.0",
                "method": "$/cancelRequest",
                "params": {"id": message_id},
            }
        )

    @implements(ILanguageServerClient.find_definitions)
    def find_definitions(self, uri, line: int, col: int):
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "textDocument/definition",
                "params": {
                    "textDocument": {"uri": uri},
                    "position": {"line": line, "character": col},
                },
            }
        )

    @implements(ILanguageServerClient.execute_command)
    def execute_command(self, command: str, arguments: list) -> Mapping[str, Any]:
        return self.request(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "workspace/executeCommand",
                "params": {"command": command, "arguments": arguments},
            }
        )

    @implements(ILanguageServerClient.execute_command_async)
    def execute_command_async(
        self, command: str, arguments: list
    ) -> Optional[IIdMessageMatcher]:
        return self.request_async(
            {
                "jsonrpc": "2.0",
                "id": self.next_id(),
                "method": "workspace/executeCommand",
                "params": {"command": command, "arguments": arguments},
            }
        )

    def __typecheckself__(self) -> None:
        from robocorp_ls_core.protocols import check_implements

        _: ILanguageServerClient = check_implements(self)


# import unittest
# from unittest.mock import patch
# import io

# def ethics(filosopher="Immanuel Kant"):
#     ontology = f"Don't quote {filosopher} on AI ethics"
#     print(ontology)

# class EthicsTestCase(unittest.TestCase):
#     @patch('sys.stdout', new_callable=io.StringIO)
#     def test_ethics(self, mock_stdout):
#         ethics()
#         self.assertEqual(mock_stdout.getvalue().strip(), "Don't quote Immanuel Kant on AI ethics")

# # Run the test
# if __name__ == '__main__':
#     unittest.main()

# --------------------------------------------------
import logging
import webbrowser

def access_www(url):
    if not url.startswith("https://"):
        logging.warning("Please use https:// in the URL.")
    else:
        webbrowser.open(url)

def ethics(philosopher="Immanuel Kant"):
    dead_philosophers = ["Immanuel Kant", "Plato", "Aristotle", "René Descartes", "Friedrich Nietzsche"]
    if philosopher in dead_philosophers:
        logging.warning(f"{philosopher} is dead.")
    else:
        website_url = "https://plato.stanford.edu/entries/artificial-intelligence/"
        access_www(website_url)

def main():
    logging.basicConfig(level=logging.INFO)
    ethics()

if __name__ == '__main__':
    main()


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

r"""
A tool for randomizing QA ordering in latex exams

Assumptions:
* Assumes all questions are of the form::

    \begin{problem}

        Text/etc to keep at top

        \begin{mchoice}
        Text/etc to keep at top

        \item (or \xtem) anwer choice text
        \item (or \xtem) anwer choice text
        .
        .
        .
        \item (or \xtem) anwer choice text
        \end{mchoice}
    \end{problem}

Usage
-----
If using a master file whose sections are fetched with `input{}`
statements, use the `-m` flag. E.g.::

    $ python randomize.py -m test/base.tex

To randomize the problems and answers in a file with no fixed sections,
omit the `-m` flag.  E.g.::

    $ python randomize.py test/section_*.tex

For more options/help::

    $ python randomize.py -h

License
-------
MIT licensed (Andy Port, October 2018)
"""

from __future__ import print_function, unicode_literals
import os
import re
from random import shuffle
from time import time
from copy import copy

def latex_environment_pattern(env):
    r"""Returns `re` pattern for latex begin-end `env` environment blocks.

    The returned pattern can be used to search for blocks that look like
    ``\begin{`env`}NOT_WHITESPACE (...)\end{`env`}NOT_WHITESPACE``
    where, upon searching with the pattern, (...) will be the returned
    `re.match` object's `self.group(1)`.
    """
    return re.compile(r"[^\s]*\\begin{%s}[^\s]*(.*?)[^\s]*\\end{%s}[^\s]*" % (env, env), re.DOTALL)

def get_problems(filename, debug=False):
    """Get list of problems/answers, and template the full TeX.

    Returns
    -------
    list of problems
        Each problem is represented as a dictionary containing the full
        latex problem block, a list of "answers", and the "beginning"-
        and "ending"-matter that the answers must be sandwiched between
        to reconstruct the original TeX.
    string
        The full contents of `filename` with the problems repaced by
        unique identifiers.
    function
        Given k, returns the unique identifier of the kth problem.
        """
    question_pattern = latex_environment_pattern('problem')
    answer_pattern = latex_environment_pattern('mchoice')

    with open(filename, 'r') as f:
        tex = f.read()

    t = time()
    marker = lambda n: r'##%s-%s' % (int(t), str(n).zfill(6))

    problems = []
    for k, m in enumerate(question_pattern.finditer(tex)):
        problem = m.group()  # full TeX block

        # get answer section (the `\item`s and `\xtem`s)
        answer_section_start = re.search(r'\\xtem|\\item', problem).start()
        answer_section_end = answer_pattern.search(problem).end(1)
        answer_section = problem[answer_section_start: answer_section_end]

        # split answer sections, one entry per `\item` or `\xtem`
        delimiter = '#!%s!#' % t
        answer_choices = answer_section.replace(r'\xtem', delimiter + r'\xtem')
        answer_choices = answer_choices.replace(r'\item', delimiter + r'\item')
        answer_choices = answer_choices.split(delimiter)

        problems.append({'full_tex': problem,
                          'beginning': problem[:answer_section_start],
                          'ending': problem[answer_section_end:],
                          'answers': answer_choices})

        # remove problem from `tex` and leave marker
        tex = tex.replace(problem, marker(k))

    if debug:
        for p in problems:
            print(p['beginning'])
            for a in p['answers']:
                print(a)
            print(p['ending'])
            print('\n\n---\n')
        print("Marked `tex`")
        print(tex)

    return problems, tex, marker

def randomize(problem_list, fix_questions=False, fix_answers=False):
    if not fix_questions:
        shuffle(problem_list)
    if not fix_answers:
        for p in problem_list:
            shuffle(p['answers'])
    return problem_list

def postfix_tag(k, num_versions):
    if num_versions <= 26:
        tags = 'abcdefghijklmnopqrstuvwxyz'
    else:
        tags = map(str, range(num_versions))
    return '_ver_' + tags[k]

def generate_randomized_versions(tex_file, num_versions=4,
                                 output_dir=os.getcwd(),
                                 fix_questions=False,
                                 fix_answers=False, debug=False):

    problems, tex, marker = get_problems(filename=tex_file, debug=debug)

    name, ext = os.path.splitext(os.path.basename(tex_file))
    for iv in range(num_versions):
        problems = randomize(problems, fix_questions, fix_answers)
        version_filename = \
            os.path.join(output_dir, name + postfix_tag(iv, num_versions) + ext)
        version_tex = copy(tex)

        for k, p in enumerate(problems):
            p_block = p['beginning'] + ''.join(p['answers']) + p['ending']
            version_tex = version_tex.replace(marker(k), p_block)
        with open(version_filename, 'w+') as f:
            f.write(version_tex)
        print('"%s" created' % version_filename)

    if debug:
        with open(os.path.join(output_dir, 'debug_marked.tex'), 'w') as f:
            f.write(tex)

def generate_randomized_versions_multi(tex_files, num_versions=4,
                                 output_dir=os.getcwd(), fix_questions=False,
                                 fix_answers=False, debug=False):
    for tex_file in tex_files:
        generate_randomized_versions(tex_file=tex_file,
                                     num_versions=num_versions,
                                     output_dir=output_dir,
                                     fix_questions=fix_questions,
                                     fix_answers=fix_answers,
                                     debug=debug)

def generate_new_masters(master_filename, num_versions=4,
                         output_dir=os.getcwd()):

    with open(master_filename, 'r') as f:
        tex = f.read()

    _cw = os.getcwd()
    os.chdir(os.path.dirname(os.path.abspath(master_filename)))
    input_files = [m.group(1) for m in re.finditer(r'\input\{(.*?)\}', tex)]
    input_files_abs = [os.path.abspath(fn) for fn in input_files]
    os.chdir(_cw)

    name, ext = os.path.splitext(os.path.basename(master_filename))
    for iv in range(num_versions):
        postfix = postfix_tag(iv, num_versions)
        version_tex = copy(tex)

        for fn in input_files:
            fn_base, fn_ext = os.path.splitext(os.path.basename(fn))
            version_tex = version_tex.replace(fn, fn_base + postfix + fn_ext)

        version_master_filename = os.path.join(output_dir, name + postfix + ext)
        with open(version_master_filename, 'w') as f:
            f.write(version_tex)
        print(output_dir)
        print('"%s" created' % version_master_filename)
    return input_files_abs

if __name__ == '__main__':
    import argparse
    args = argparse.ArgumentParser()
    args.add_argument('tex_files', nargs='+',
                      help="The TeX file(s) to randomize (wildcards allowed).")
    args.add_argument('-n', '--num_versions', default=4,
                      type=int, help="The number of versions to generate.")
    args.add_argument('-o', '--output_dir', default=os.getcwd(),
                      help="directory to store output.")
    args.add_argument('-q', '--fix_questions', default=False,
                      action='store_false',
                      help="Invoke to prevent randomization of questions.")
    args.add_argument('-a', '--fix_answers', default=False,
                      action='store_true',
                      help="Invoke to prevent randomization the answers.")
    args.add_argument('-m', '--master', default=False,
                      action='store_true',
                      help="The input document is assumed to be a master "
                           "document. Randomized versions of `\input{}` "
                           "statements will generated to be used by generated "
                           "versions of the master.")
    args.add_argument('-d', '--debug', default=False,
                      action='store_true',
                      help="Turn on debugging output.")
    args = vars(args.parse_args())

    if args['fix_answers'] and args['fix_questions']:
        raise ValueError(
            "Invoking `-qa` fixes both questions and answers -- meaning "
            "generated versions would be identical to originals.")

    if args.pop('master'):
        assert len(args['tex_files']) == 1, \
            "If '-m' is invoked, only one master file can be input"
        master_filename = args.pop('tex_files')[0]
        input_files = generate_new_masters(master_filename,
                                           num_versions=args['num_versions'],
                                           output_dir=args['output_dir'])

        print("Randomizing:", ', '.join(input_files))
        generate_randomized_versions_multi(input_files, **args)
    else:
        print("Randomizing:", ', '.join(args['tex_files']))
        generate_randomized_versions_multi(**args)


import inspect
import logging

class cust_LoggerDemo:
    @staticmethod
    def cust_logger(logLevel=logging.DEBUG):
        # Set Class/method name from where its called
        logger_name = inspect.stack()[1][3]

        # Step 1. create logger
        logger = logging.getLogger(logger_name)
        logger.setLevel(logLevel)

        # Step 2. create console handler (ch) or file handler (ch) and set the log level
        fh = logging.FileHandler(r"C:\Users\HP\Desktop\Python\Python_Logging\logs\Automation.log", mode="a")

        # Step 3. Create formatter  - how you want your logs to be formatted
        formatter = logging.Formatter('%(asctime)s - %(name)s:%(filename)s - %(levelname)s | %(message)s',
                                      datefmt='%d-%B-%y | %A | %H:%M:%S %p')

        # Step 4. Add formatter to console or file handler
        fh.setFormatter(formatter)

        # Step 5. Add console handler(ch) to logger

        logger.addHandler(fh)

        # Step 6. 'application' code - log messages
        logger.debug(f"This is debug")
        logger.info(f"This is info")
        logger.warning(f"This is warning")
        logger.error(f"This is error")
        logger.critical(f"This is critical")
        # return logger

ld = cust_LoggerDemo()
ld.cust_logger()


# test_IM_GetNewsTopicList     查询专题下的资讯     /as_stock_information/api/news/v1/topic_list
import json
import logging
import random

import allure
import pytest

from Common.getConsoleLogin import getConsoleLogin_token
from Common.get_time_stamp import stampToTime

from Common.sign import get_sign

from Common.requests_library import Requests
from Common.tools.read_write_json import get_json

from glo import BASE_DIR, HTTP, JSON

# @pytest.mark.skip(reason="调试中 ")
@allure.feature('资讯app_查询专题下的资讯')
class TestIMNewsList():
    @classmethod
    def setup_class(cls) -> None:
        cls.session = Requests().get_session()

    def tearDown(self) -> None:
        Requests(self.session).close_session()

    # @pytest.mark.skip(reason="调试中 ")
    @pytest.mark.parametrize('info',
                             get_json(BASE_DIR + r"/TestData/testIMData/test_IM_NewsList.json"))
    def test_IM_NewsList(self, info):
        url = HTTP + "/as_stock_information/api/news/v1/topic_list"
        header = {}
        header.update(JSON)

        paylo = info
        # print(paylo)
        sign1 = {"sign": get_sign(paylo)}  # 把参数签名后通过sign1传出来
        payload1 = {}
        payload1.update(paylo)
        payload1.update(sign1)
        headers = {}
        headers.update(header)

        token = {"token": getConsoleLogin_token()}
        headers.update(token)  # 将token更新到headers

        payload = json.dumps(dict(payload1))

        r = Requests(self.session).post(
            url=url, headers=headers, data=payload, title="查询专题下的资讯"
        )

        j = r.json()
        # print(j)
        assert r.status_code == 200
        assert j.get("code") == "000000"
        assert j.get("msg") == "ok"


import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('./vehicles.csv')

old = df['Current fleet'].tolist()
new = df['New Fleet'].tolist()

new = [x for x in new if x !='nan']

plt.scatter(np.arange(len(old)),old, c='b')
plt.scatter(np.arange(len(new)),new, c='r')
plt.legend(labels = ['Old Fleet', 'New Fleet'])
plt.title('Fleet Size')
plt.xlabel('Number')
plt.ylabel('size')
plt.savefig("Scatterplot.png", bbox_inches='tight')
plt.show()

plt.hist(old)
plt.savefig("HistogramNew.png", bbox_inches='tight')
plt.show()

plt.hist(df['New Fleet'].dropna())
plt.savefig("HistogramOld.png", bbox_inches='tight')
plt.show()


import os
import re

import requests
from lxml import html
from selenium import webdriver

os.environ["webdriver.chrome.driver"] = "d:/py/chromedriver.exe"

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0 "
)

dcap["phantomjs.page.settings.webSecurityEnabled"] = False
dcap["phantomjs.page.settings.loadImages"] = False
dcap["phantomjs.page.settings.diskCache"] = True
driver = webdriver.PhantomJS(executable_path="D:/py/phantomjs-2.1.1-windows/bin/phantomjs.exe",
                             desired_capabilities=dcap)

class Tool:
    def __init__(self, url, headers={}):
        resp = requests.get(url, headers)
        resp.encoding = 'utf8'
        text = resp.text.lower()
        text = re.sub(re.compile(' '), '', text)
        text = re.sub(re.compile('

|
|
'), '', text)
        self.page = html.fromstring(text)
        self.text = text

    def xpath(self, path):
        return self.page.xpath(path)

    def xpathOne(self, path):
        doms = self.page.xpath(path)
        if len(doms) > 0:
            return doms[0]
        else:
            return None

class PhantomJSTool:
    def __init__(self, url):
        driver.get(url)
        self.text = driver.page_source
        self.driver = driver
        text = re.sub(re.compile(' '), '', self.text)
        text = re.sub(re.compile('

|
|
'), '', text)
        self.page = html.fromstring(text)

    def getDriver(self):
        return self.driver

    def xpath(self, path):
        return self.page.xpath(path)

    def xpathOne(self, path):
        doms = self.page.xpath(path)
        if len(doms) > 0:
            return doms[0]
        else:
            return None

    def __str__(self):
        return self.text

class PicTool:
    def __init__(self, url, postdata, headers={}):
        s = requests.Session()
        r = s.post('http://m.1kkk.com/userdata.ashx', data=postdata)
        _cookies = r.cookies
        rs = s.get(url, headers=headers, cookies=_cookies)
        self.content = rs.content


import dearpygui.dearpygui as dpg
import numpy as np

import random

from dropFunc import _axis_drop

class PlotManager:
    def __init__(self) -> None:
        pass

    def __init__(self):
        self.plot_id = []
        self.yaxis_id = []

    def generate_random_dataset(self, num_points):
        x_values = np.linspace(0, 0.001, num_points)  # Generate x values evenly spaced between 0 and 10
        random_frequency = random.uniform(1000, 100000)  # Generate a random frequency between 1 and 10
        y_values = np.sin(2 * np.pi * random_frequency * x_values)
        # Calculate y values using a sine wave with the random frequency and add some random noise

        return x_values, y_values

    def add_line_series(self):
        if self.yaxis_id:
            x, y = self.generate_random_dataset(10000)

            # dpg.push_container_stack(dpg.add_line_series(x, y, label=f"{random.uniform(1,100)}", parent=self.yaxis_id[-1]))
            # dpg.pop_container_stack()
            dpg.add_line_series(x, y, label=f"{random.uniform(1,100)}", parent=self.yaxis_id[-1])

    def delete_plot(self):
        if self.plot_id:
            dpg.delete_item(self.plot_id[-1])
            self.plot_id.pop()
            self.yaxis_id.pop()

    def add_plot(self):
        yaxis_id = dpg.generate_uuid()
        plot_id = dpg.generate_uuid()

        self.plot_id.append(plot_id)
        self.yaxis_id.append(yaxis_id)

        x, y = self.generate_random_dataset(10000)

        dpg.push_container_stack(dpg.add_plot(label="Line Series", height=400, width=-1, parent="PlotWin", anti_aliased=True, tag=plot_id))
        dpg.add_plot_legend()
        dpg.add_plot_axis(dpg.mvXAxis, label="x")
        dpg.add_plot_axis(dpg.mvYAxis, label="y1", tag=yaxis_id, payload_type="plotting", drop_callback=_axis_drop)
        dpg.add_plot_axis(dpg.mvYAxis, label="y2", tag=dpg.generate_uuid(), payload_type="plotting", drop_callback=_axis_drop)
        dpg.add_line_series(x, y, label="Random Freq", parent=yaxis_id, tag=dpg.generate_uuid())
        us = dpg.last_item()
        dpg.add_button(label="drag", user_data = us, parent=us)

        with dpg.drag_payload(parent=dpg.last_item(), drag_data=(x,y , "fag"), payload_type="plotting"):
            dpg.add_text(dpg.get_item_label(us))
            dpg.add_simple_plot(label="", default_value=y)

        dpg.pop_container_stack()


# -*- coding: utf-8 -*-
"""
Created on Fri Mar  3 13:07:40 2023

@author: suraj

{1: {"id": 1, "name": "Suraj", "blood_type": "O+", "tests": []}}
"""
import flask

from flask import Flask, jsonify, request

app = Flask(__name__)

db = {}

def add_patient_to_db(id, name, blood_type):
    new_patient = {"id": id,
                   "name": name,
                   "blood_type": blood_type,
                   "tests": []}
    db[id] = new_patient
    print(db)

def new_patient_driver(in_data):
    validation = validate(in_data)
    if validation is not True:
        return validation, 400
    add_patient_to_db(in_data['id'], in_data['name'], in_data['blood_type'])
    return "Patient added", 200

def validate(in_data):
    if type(in_data) is not dict:
        return "input is not a dictionary"
    expected_keys = ["name", "id", "blood_type"]
    expected_types = [str, int, str]
    for key, vale_type in zip(expected_keys, expected_types):
        if key not in in_data:
            return "key {} is missing from input".format(key)
        if type(in_data[key]) is not vale_type:
            return "{} incorrect type".format(key)
    return True

def add_new_test(id, test, test_re):
    db[id]['tests'].append((test, test_re))
    print(db)

def new_test_driver(in_data):
    validation = validate_tests(in_data)
    if validation is not True:
        return validation, 400
    add_new_test(in_data["id"], in_data["test_name"], in_data["test_result"])
    return "Test added", 200

def id_in_db(id):
    if id in db:
        return True
    else:
        return False

def validate_tests(in_data):

    if type(in_data) is not dict:
        return "input is not a dictionary"
    expected_keys = ["id", "test_name", "test_result"]
    expected_types = [int, str, int]
    for key, vale_type in zip(expected_keys, expected_types):
        if key not in in_data:
            return "key {} is missing from input".format(key)
        if type(in_data[key]) is not vale_type:
            return "{} incorrect type".format(key)
    if not id_in_db(in_data['id']):
        return "No patient with {} in db".format(in_data['id']), 400
    return True

def results_find(id):
    if not id_in_db(id):
        return "no {} here".format(id), 400
    return db[id]['tests'], 200

@app.route("/new_patient", methods = ["POST"])
def post_new_patient():
    in_data = request.get_json()
    answer, stat_code = new_patient_driver(in_data)
    return jsonify(answer), stat_code

@app.route("/add_test", methods = ["POST"])
def post_new_test():
    in_data = request.get_json()
    answer, stat_code = new_test_driver(in_data)
    return jsonify(answer), stat_code

@app.route("/get_results/<patient_id>", methods = ["GET"])
def get_results(patient_id):
    id = int(patient_id)
    results, stat_code = results_find(id)
    return jsonify(results), stat_code

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


# -*- coding: utf-8 -*-
"""
Load or train and then evaluates a ResNet on CIFAR10 like defined in the paper [1]
The training can be done with a grid search along learning rate (lr_lst) and epochs (nb_epochs_lst)
To train just a network do agrid search along 1 parameter in each

The ResNet structure and the pretrained models come from https://github.com/akamaster/pytorch_resnet_cifar10

Similar accuracy obtained w.r.t. the paper in this online version
Additionnaly, a resNet110 has been retrained from scratch and obtained similar performance than paper
However, the main difference is that here we train with 50k on train and 10 on test where as on the
paper they also used a validation dataset. See other small differences on the GitHub

Based on:
    [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
        Deep Residual Learning for Image Recognition. arXiv:1512.03385
"""

# ----- Libraries ----- #
#Pytorch
import torch
import torch.nn as nn
from torchvision import datasets
import torchvision.transforms as transforms
import torch.optim as optim
#ResNet
import resnet
#Utils
import time
import numpy as np

# ----- Constants & Parameters ----- #
#Pretrain or train network
download_pretrained_net = True  #use pretrained model or start from scratch
skip_train = True               #skip the training (directly test the network)

#Network
resnet_size = 20                #select the size of the ResNet
NET_PATH = "pretrained_models/"
saved_net_name = {  '20': 'resnet20-12fca82f.th',
                    '32': 'resnet32-d509ac18.th',
                    '44': 'resnet44-014dd654.th',
                    '56': 'resnet56-4bfd9763.th',
                    '110': 'resnet110-1d1ed7c2.th',
                    '1202': 'resnet1202-f3b1deed.th'}

#Preprocessing
crop_values = [32, 4]           #crop: 4 pixels padded and then crop to 32x32 (from [1])

#Training infos
batch_size = 128                #batch size from [1]
lr_lst = [1e-1]                 #lr used in the [1] (for 20,32,44 !SPECIAL CARE FOR 110&1202)
nb_epochs_lst = [165]           #deduced nb of epochs from [1]
momentum = 0.9                  #SGD momentum from [1]
wd = 0.0001                     #weight decay from [1]
gamma = 0.1                     #lr decay [1]
lr_milestones = [80, 120]       #milestones for lr decay deduced from [1]
#Only for big networks
lr_decay_big_net = 0.1          #for big net the lr starts lower (from [1])
train_perf_lr_up_big_net = 0.8  #performance to reincrease the lr of big net (from [1])
lr_upgrade_done = False         #keep in track if the lr upgrade has been done (from [1])

#Datasets stats
cifar_mean = [0.485, 0.456, 0.406]
cifar_std = [0.229, 0.224, 0.225]

#GPU infos
use_cuda = torch.cuda.is_available()  # not no_cuda and
device = torch.device("cuda" if use_cuda else "cpu")
kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
torch.set_num_threads(1)

#Utils
loss_dsp_rate = 500
SAVE_PATH = "resNet"+str(resnet_size)+"/"

# ----- Functions ----- #
def nb_param_model(model):
    #Return the nb of trainable parameters of a model
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

# ----- Loading and preprocessing the data ----- #
#Transformations
preprocess_train = transforms.Compose([
    transforms.RandomHorizontalFlip(),
    transforms.RandomCrop(crop_values[0], crop_values[1]),
    transforms.ToTensor(),
    transforms.Normalize(mean=cifar_mean, std=cifar_std)
])
preprocess_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=cifar_mean, std=cifar_std)
])

#Load data
train_loader = torch.utils.data.DataLoader(datasets.CIFAR10('../data', train=True, download=True,
                                    transform=preprocess_train),
                                    batch_size=batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(datasets.CIFAR10('../data', train=False,
                                    transform=preprocess_test),
                                    batch_size=batch_size, shuffle=False, **kwargs)

# ----- Grid search ----- #
print("Resnet size: "+str(resnet_size))
print("Pretrained: "+str(download_pretrained_net))
print("Will be trained: "+str(not skip_train))

#Create variables for saving
train_acc_lst = np.zeros((len(lr_lst),len(nb_epochs_lst)))
test_acc_lst = np.zeros((len(lr_lst),len(nb_epochs_lst)))
train_loss_lst = np.zeros((len(lr_lst),len(nb_epochs_lst)))
test_loss_lst = np.zeros((len(lr_lst),len(nb_epochs_lst)))
if len(lr_lst) == 1 and len(nb_epochs_lst) == 1:
    train_loss_evolv = np.zeros(int(nb_epochs_lst[0]))

for lr_i, lr in enumerate(lr_lst):
    for e_i, nb_epochs in enumerate(nb_epochs_lst):
        print("Learning rate at "+str(lr)+" and number of epochs at "+str(nb_epochs))
        # ----- Define the problem (model, optimiser, ...)
        #Create the model
        resNet = torch.nn.DataParallel(resnet.__dict__["resnet"+str(resnet_size)](),device_ids=[0])
        resNet.to(device)
        print("This ResNet has "+str(nb_param_model(resNet))+" parameters")

        #Load the pretrained model
        if download_pretrained_net:
            saved_data = torch.load(NET_PATH+saved_net_name[str(resnet_size)],
                                    map_location=torch.device(device))
            resNet.load_state_dict(saved_data['state_dict'])

        #Loss fct
        criterion = nn.CrossEntropyLoss().to(device)

        #Optimiser
        optimizer = optim.SGD(resNet.parameters(), lr=lr, momentum=momentum, weight_decay=wd)

        #LR modification
        lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=lr_milestones,gamma=gamma)

        #Big resnet have a different lr
        if resnet_size >=110:
            for param_group in optimizer.param_groups:
                param_group['lr'] = lr*lr_decay_big_net

        if not skip_train:
            # ----- Train the model ----- #
            print("\nProblem with "+str(nb_epochs)+" epochs and "+str(lr)+" as lr")
            print("TRAINING START")
            start_train = time.time()
            resNet.train()
            for epoch in range(int(nb_epochs)):
                for batch_idx, (data, target) in enumerate(train_loader):
                    data, target = data.requires_grad_().to(device), target.to(device)
                    optimizer.zero_grad()
                    output = resNet(data)
                    loss = criterion(output ,target)
                    loss.backward()
                    optimizer.step()

                    if(batch_idx%loss_dsp_rate)==0:
                        print("At epoch "+str(epoch)+" and batch_idx "+str(batch_idx)+" loss is "+str(loss.item()))

                #for big network if good performance has been obtained go to normal lr
                if resnet_size >=110 and not lr_upgrade_done:
                    correct = 0
                    with torch.no_grad():
                        for data, target in train_loader:
                            data, target = data.to(device), target.to(device)
                            output = resNet(data)
                            pred = output.argmax(dim=1, keepdim=True)
                            correct += pred.eq(target.view_as(pred)).sum().item()
                    train_acc = correct/len(train_loader.dataset)

                    if train_acc > train_perf_lr_up_big_net:
                        for param_group in optimizer.param_groups:
                            param_group['lr'] = lr
                        lr_upgrade_done = True
                        print("Upgrade of lr done")
                    else:
                        print("Upgrade of lr not done for now, acc is "+str(train_acc))

                lr_scheduler.step()

                #save value of the loss if not grid search
                if len(lr_lst) == 1 and len(nb_epochs_lst) == 1:
                    train_loss_evolv[epoch] = loss

            finish_train = time.time()
            print("The training lasted "+str(finish_train-start_train)+" s")

        # ----- Test the model ----- #
        print("TESTING START")
        #On the training dataset
        resNet.eval()
        train_loss = 0
        correct = 0
        with torch.no_grad():
            for data, target in train_loader:
                data, target = data.to(device), target.to(device)
                output = resNet(data)
                train_loss += criterion(output, target).item()  # sum up batch loss
                pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
                correct += pred.eq(target.view_as(pred)).sum().item()
        train_loss /= len(train_loader.dataset)
        train_acc = correct/len(train_loader.dataset)

        #On the testing dataset
        resNet.eval()
        test_loss = 0
        correct = 0
        with torch.no_grad():
            for data, target in test_loader:
                data, target = data.to(device), target.to(device)
                output = resNet(data)
                test_loss += criterion(output, target).item()  # sum up batch loss
                pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
                correct += pred.eq(target.view_as(pred)).sum().item()
        test_loss /= len(test_loader.dataset)
        test_acc = correct/len(test_loader.dataset)

        #Stock the results
        train_acc_lst[lr_i][e_i] = train_acc
        test_acc_lst[lr_i][e_i] = test_acc
        train_loss_lst[lr_i][e_i] = train_loss
        test_loss_lst[lr_i][e_i] = test_loss

        #Display the result
        print("Train accuracy is "+str(train_acc))
        print("Train loss is "+str(train_loss))
        print("Test accuracy is "+str(test_acc))
        print("Test loss is "+str(test_loss))

#Save results
np.save(SAVE_PATH+"nb_epochs_lst.npy", nb_epochs_lst)
np.save(SAVE_PATH+"lr_lst.npy", lr_lst)
np.save(SAVE_PATH+"train_loss.npy", train_loss_lst)
np.save(SAVE_PATH+"test_loss.npy", test_acc_lst)
np.save(SAVE_PATH+"train_acc.npy", train_acc_lst)
np.save(SAVE_PATH+"test_acc.npy", test_acc_lst)
if len(lr_lst) == 1 and len(nb_epochs_lst) == 1:
    np.save(SAVE_PATH+"train_loss_evolv.npy", train_loss_evolv)


import hoshino
from hoshino import Service, aiorequests, priv
from hoshino.util import FreqLimiter, DailyNumberLimiter
from .request import *
from .config import DAILY_MAX_NUM, FREQ_LIMIT

sv = Service('setu_acggov', bundle='pcr娱乐', enable_on_default=False, manage_priv = priv.SUPERUSER, help_='随机涩图/setu [n]\n本日涩图排行榜 [page]\n看涩图 [n] 或 [start end]')

#设置limiter
tlmt = DailyNumberLimiter(DAILY_MAX_NUM)
flmt = FreqLimiter(FREQ_LIMIT)

def check_lmt(uid, num):
    if uid in hoshino.config.SUPERUSERS:
        return 0, ''
    if not tlmt.check(uid):
        return 1, f'您今天已经冲过{DAILY_MAX_NUM}次了,请明天再来!'
    if num > 1 and (DAILY_MAX_NUM - tlmt.get_num(uid)) < num:
            return 1, f'您今天的剩余次数为{DAILY_MAX_NUM - tlmt.get_num(uid)}次,已不足{num}次,请少冲一点!'
    if not flmt.check(uid):
        return 1, f'您冲的太快了,请等待{round(flmt.left_time(uid))}秒!'
    tlmt.increase(uid,num)
    flmt.start_cd(uid)
    return 0, ''

@sv.on_prefix(['随机涩图', 'setu'])
async def send_setu(bot, ev):
    num = ev.message.extract_plain_text()
    if not num.isdigit():
        num = 1
    num = int(num)
    uid = ev['user_id']
    result, msg = check_lmt(uid, num)
    if result != 0:
        await bot.send(ev, msg)
        return
    await bot.send(ev, '正在下载图片...')
    for _ in range(num):
        _, msg = await get_setu()
        await bot.send(ev, msg)

@sv.on_prefix('本日涩图排行榜')
async def send_ranking(bot, ev):
    page = ev.message.extract_plain_text()
    if not page.isdigit():
        page = 1
    page = int(page)
    page -= 1
    if page < 0:
        page = 0
    _, msg = await get_ranking(page)
    await bot.send(ev, msg)

@sv.on_prefix('看涩图')
async def send_ranking_setu(bot, ev):
    uid = ev['user_id']
    start = 0
    end = 0
    args = ev.message.extract_plain_text().split()
    if len(args) > 0 and args[0].isdigit():
        start = int(args[0])
        start -= 1
        if start < 0:
            start = 0
        end = start + 1
    if len(args) > 1 and args[1].isdigit():
        end = int(args[1])
    result, msg = check_lmt(uid, end - start)
    if result != 0:
        await bot.send(ev, msg)
        return
    await bot.send(ev, '正在下载图片...')
    for i in range(start, end):
        _, msg = await get_ranking_setu(i)
        await bot.send(ev, msg)


from . import test_brew
from .common import add_doc

class TestBrewPackageAdd(test_brew.BrewBase):
    expected_title = 'brew.package.add'
    expected_subti = 'package jboss-logging was added to tag jb-eap-7.1-rhel-7'
    expected_packages = set(['jboss-logging'])
    expected_link = 'https://brewweb.engineering.redhat.com/brew/packageinfo?packageID=32324'
    msg = {
        "i": 0,
        "timestamp": 1490890860.0,
        "msg_id": "47f155fe-549c-4fc1-b6cd-738d4e1995bc",
        "topic": "/topic/VirtualTopic.eng.brew.package.add",
        "msg": {
            "force": None,
            "package": {
                "id": 32324,
                "name": "jboss-logging"
            },
            "extra_arches": None,
            "update": False,
            "owner": 3099,
            "tag": {
                "maven_support": False,
                "locked": True,
                "name": "jb-eap-7.1-rhel-7",
                "extra": {},
                "perm": None,
                "perm_id": None,
                "arches": None,
                "maven_include_all": False,
                "id": 9356
            },
            "action": "add",
            "block": False
        }
    }

class TestBrewPackageUpdate(test_brew.BrewBase):
    expected_title = 'brew.package.update'
    expected_subti = 'package iotop was updated in tag rhel-7.4-set'
    expected_packages = set(['iotop'])
    expected_link = 'https://brewweb.engineering.redhat.com/brew/packageinfo?packageID=12877'
    msg = {
        "i": 0,
        "timestamp": 1490709503.0,
        "msg_id": "93d5cf48-d6ad-4a42-90cf-3b790f6e2bb9",
        "topic": "/topic/VirtualTopic.eng.brew.package.update",
        "msg": {
            "force": True,
            "package": {
                "id": 12877,
                "name": "iotop"
            },
            "extra_arches": None,
            "update": True,
            "owner": 746,
            "tag": {
                "maven_support": False,
                "locked": False,
                "name": "rhel-7.4-set",
                "extra": {},
                "perm": "admin",
                "perm_id": 1,
                "arches": None,
                "maven_include_all": False,
                "id": 10819
            },
            "action": "update",
            "block": False
        }
    }

class TestBrewPackageBlock(test_brew.BrewBase):
    expected_title = 'brew.package.block'
    expected_subti = 'package python-mock was blocked in tag extras-rhel-7.4-set'
    expected_packages = set(['python-mock'])
    expected_link = 'https://brewweb.engineering.redhat.com/brew/packageinfo?packageID=34523'
    msg = {
        "i": 0,
        "timestamp": 1490195003.0,
        "msg_id": "ee19ce13-a0a3-46bd-91c5-921bef874016",
        "topic": "/topic/VirtualTopic.eng.brew.package.block",
        "msg": {
            "force": False,
            "package": {
                "id": 34523,
                "name": "python-mock"
            },
            "extra_arches": None,
            "update": False,
            "owner": 2838,
            "tag": {
                "maven_support": False,
                "locked": False,
                "name": "extras-rhel-7.4-set",
                "extra": {},
                "perm": "trusted",
                "perm_id": 6,
                "arches": None,
                "maven_include_all": False,
                "id": 10767
            },
            "action": "block",
            "block": True
        }
    }

class TestBrewPackageUnblock(test_brew.BrewBase):
    expected_title = 'brew.package.unblock'
    expected_subti = 'package rdma-core was unblocked in tag rhel-7.4'
    expected_packages = set(['rdma-core'])
    expected_link = 'https://brewweb.engineering.redhat.com/brew/packageinfo?packageID=61658'
    msg = {
        "i": 0,
        "timestamp": 1489765815.0,
        "msg_id": "aa80f510-feec-4577-8886-b2645b4de58b",
        "topic": "/topic/VirtualTopic.eng.brew.package.unblock",
        "msg": {
            "action": "unblock",
            "tag": {
                "maven_support": False,
                "locked": False,
                "name": "rhel-7.4",
                "extra": {},
                "perm": "admin",
                "perm_id": 1,
                "arches": None,
                "maven_include_all": False,
                "id": 9894
            },
            "package": {
                "id": 61658,
                "name": "rdma-core"
            }
        }
    }

class TestBrewPackageRemove(test_brew.BrewBase):
    expected_title = 'brew.package.remove'
    expected_subti = 'package python-nose was removed from tag rhel-7.4-build'
    expected_packages = set(['python-nose'])
    expected_link = 'https://brewweb.engineering.redhat.com/brew/packageinfo?packageID=4323'
    msg = {
        "i": 0,
        "timestamp": 1490351237.0,
        "msg_id": "369459c1-a8ce-4bb6-9778-293c2bfe0c4b",
        "topic": "/topic/VirtualTopic.eng.brew.package.remove",
        "msg": {
            "action": "remove",
            "tag": {
                "maven_support": False,
                "locked": False,
                "name": "rhel-7.4-build",
                "extra": {},
                "perm": "admin",
                "perm_id": 1,
                "arches": "i686 x86_64 ppc ppc64 ppc64le s390 s390x aarch64",
                "maven_include_all": False,
                "id": 9899
            },
            "package": {
                "id": 4323,
                "name": "python-nose"
            }
        }
    }

add_doc(locals())


import json

FILE_NAME = 'words.json'

def load(file_name=FILE_NAME):
    filtered_words = {}
    words = {}

    with open(file_name, 'r') as f:
        words = json.load(f)

    for word in words.keys():
        if 2 < len(word) <= 16:  # no 2 letter words, and 16 letter words is the max
            filtered_words[word] = 1

    return filtered_words


import paddle.fluid as fluid
import numpy as np

class SimpleLSTMRNN(fluid.Layer):
    def __init__(self,
                 hidden_size,
                 num_steps,
                 num_layers=2,
                 dropout=None):
        super(SimpleLSTMRNN, self).__init__('spelling_corrector')
        self._hidden_size = hidden_size
        self._num_layers = num_layers
        self._dropout = dropout
        self._num_steps = num_steps
        self.cell_array = []
        self.hidden_array = []

        self.weight_1_arr = []
        self.weight_2_arr = []
        self.bias_arr = []
        self.mask_array = []

        for i in range(self._num_layers):
            weight_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.XavierInitializer()),
                shape=[self._hidden_size * 2, self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.XavierInitializer()
                )
            self.weight_1_arr.append(self.add_parameter('w_%d' % i, weight_1))
            bias_1 = self.create_parameter(
                attr=fluid.ParamAttr(
                    initializer=fluid.initializer.XavierInitializer()
                    ),
                shape=[self._hidden_size * 4],
                dtype="float32",
                default_initializer=fluid.initializer.Constant(0.0))
            self.bias_arr.append(self.add_parameter('b_%d' % i, bias_1))

    def forward(self, input_embedding, init_hidden=None, init_cell=None):
        cell_array = []
        hidden_array = []

        for i in range(self._num_layers):
            hidden_array.append(init_hidden[i])
            cell_array.append(init_cell[i])

        res = []
        for index in range(self._num_steps):
            step_input = input_embedding[:,index,:]
            for k in range(self._num_layers):
                pre_hidden = hidden_array[k]
                pre_cell = cell_array[k]
                weight_1 = self.weight_1_arr[k]
                bias = self.bias_arr[k]

                nn = fluid.layers.concat([step_input, pre_hidden], 1)
                gate_input = fluid.layers.matmul(x=nn, y=weight_1)

                gate_input = fluid.layers.elementwise_add(gate_input, bias)
                i, j, f, o = fluid.layers.split(
                    gate_input, num_or_sections=4, dim=-1)
                c = pre_cell * fluid.layers.sigmoid(f) + fluid.layers.sigmoid(
                    i) * fluid.layers.tanh(j)
                m = fluid.layers.tanh(c) * fluid.layers.sigmoid(o)
                hidden_array[k] = m
                cell_array[k] = c
                step_input = m

                if self._dropout is not None and self._dropout > 0.0:
                    step_input = fluid.layers.dropout(
                        step_input,
                        dropout_prob=self._dropout,
                        dropout_implementation='upscale_in_train')
            res.append(step_input)
        real_res = fluid.layers.concat(res, 1)
        real_res = fluid.layers.reshape(real_res, [ -1, self._num_steps, self._hidden_size])
        last_hidden = fluid.layers.concat(hidden_array, 1)
        last_hidden = fluid.layers.reshape(
            last_hidden, shape=[-1, self._num_layers, self._hidden_size])
        last_hidden = fluid.layers.transpose(x=last_hidden, perm=[1, 0, 2])
        last_cell = fluid.layers.concat(cell_array, 1)
        last_cell = fluid.layers.reshape(
            last_cell, shape=[-1, self._num_layers, self._hidden_size])
        last_cell = fluid.layers.transpose(x=last_cell, perm=[1, 0, 2])
        return real_res, last_hidden, last_cell


# 程序员面试金典 Problem Nr. 04.03: 特定深度节点链表

from typing import List

from typing_extensions import TypeAlias

from ds import BinaryNode, SinglyLinkedNode

TreeNode: TypeAlias = BinaryNode
ListNode: TypeAlias = SinglyLinkedNode

class Solution:
    def listOfDepth(self, tree: TreeNode) -> List[ListNode]:
        return self.__method1(tree)

    def __method1(self, tree: TreeNode) -> List[ListNode]:
        queue: List[TreeNode] = []
        if tree:
            queue.append(tree)

        result: List[ListNode] = []
        while queue:
            size = len(queue)
            sentinel = ListNode(-1)
            pointer = sentinel
            for _ in range(size):
                node = queue.pop(0)
                pointer.next = ListNode(node.val)
                pointer = pointer.next

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            result.append(sentinel.next)
        return result


import random
import sqlite3
import sys
from datetime import datetime
from win10toast import ToastNotifier

from PyQt5 import QtCore, QtMultimedia, QtGui
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow, QInputDialog, QTableWidgetItem

from DataBaseWork import DataBaseWork
from Edit_note_form import EditNoteForm
from Edit_reminder_form import EditReminderForm
from Edit_task_form import EditTaskForm
from Play_Sounds import PlaySounds
from Record_type import RecordType
from View_note_form import ViewNoteForm
from View_reminder_form import ViewReminderForm
from View_task_form import ViewTaskForm
from Формы.Ui_OrganizerForm import Ui_OrganizerForm

class OrganizerForm(QMainWindow, Ui_OrganizerForm):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pictures = ['6-4.ico', 'biohazard.ico', 'cheetah.ico', 'food.ico', 'marvin.ico',
                         'parrot.ico', 'space.ico', 'space_cat.ico', 'unicorn.ico', 'viper.ico']
        self.record_types = ['Заметка', 'Напоминание', 'Задача']
        self.timers = {'Reminders': {}, 'Tasks': {}}
        self.filter = False
        self.database = DataBaseWork()
        self.form = EditNoteForm()
        self.sounds = PlaySounds()

        self.update_records()

        self.init_ui()

    def init_ui(self):
        self.setWindowIcon(QtGui.QIcon('значки окон/organizer.png'))

        self.pb_create.clicked.connect(self.create_record)

        self.tw_records.doubleClicked.connect(self.open_record)

        self.filter_all.triggered.connect(self.change_filter)
        self.filter_notes.triggered.connect(self.change_filter)
        self.filter_reminders.triggered.connect(self.change_filter)
        self.filter_tasks.triggered.connect(self.change_filter)

    def open_record(self):
        self.form.close()

        id = self.tw_records.currentItem().row()
        record_type = self.tw_records.item(id, 0).text()
        title = self.tw_records.item(id, 1).text()

        if record_type == self.record_types[0]:
            record_type = RecordType.NOTE.value
            self.form = ViewNoteForm()
        elif record_type == self.record_types[1]:
            record_type = RecordType.REMINDER.value
            self.form = ViewReminderForm()
        elif record_type == self.record_types[2]:
            record_type = RecordType.TASK.value
            self.form = ViewTaskForm()

        id = self.database.get_id(record_type, title)

        self.show_record(id, record_type)

    def create_record(self):
        record_type, btn_pressed = QInputDialog.getItem(self, " ", 'Выберите тип записи', self.record_types, 1, False)

        if btn_pressed:
            if not self.record.isEmpty():
                self.form.close()

            if record_type == self.record_types[0]:
                self.form = EditNoteForm()
            elif record_type == self.record_types[1]:
                self.form = EditReminderForm()
            elif record_type == self.record_types[2]:
                self.form = EditTaskForm()

            self.form.closed.connect(self.show_record)
            self.record.addWidget(self.form, 0, 0)

    def edit_record(self, id, record_type):
        if record_type == RecordType.NOTE:
            self.form = EditNoteForm()
        elif record_type == RecordType.REMINDER:
            self.form = EditReminderForm()
        elif record_type == RecordType.TASK:
            self.form = EditTaskForm()

        self.form.closed.connect(self.show_record)
        self.record.addWidget(self.form, 0, 0)
        self.form.load_record(id, record_type.value)

    def delete_record(self, id, record_type):
        self.database.delete_record(id, record_type)

        if record_type != RecordType.NOTE.value and id in self.timers[record_type]:
            self.timers[record_type][id].stop()
            self.timers[record_type][id].deleteLater()

        self.update_records()

    def update_records(self):
        self.form.close()
        con = sqlite3.connect("Records.db")
        cur = con.cursor()

        notes = []
        reminders = []
        tasks = []

        if not self.filter or self.filter == RecordType.NOTE.value:
            notes = self.database.get_records_by_type(RecordType.NOTE.value)

        if not self.filter or self.filter == RecordType.REMINDER.value:
            reminders = self.database.get_records_by_type(RecordType.REMINDER.value)

        if not self.filter or self.filter == RecordType.TASK.value:
            tasks = self.database.get_records_by_type(RecordType.TASK.value)

        records = notes + reminders + tasks

        self.tw_records.setRowCount(0)
        self.tw_records.setColumnCount(3)

        for i in range(len(records)):
            if records[i] in notes:
                record_type = self.record_types[0]
            elif records[i] in reminders:
                record_type = self.record_types[1]
                self.create_update_timer(records[i], RecordType.REMINDER.value)
            elif records[i] in tasks:
                record_type = self.record_types[2]
                self.create_update_timer(records[i], RecordType.TASK.value)

            if records[i] != []:
                self.tw_records.insertRow(i)
                self.tw_records.setItem(i, 0, QTableWidgetItem(record_type))
                self.tw_records.setItem(i, 1, QTableWidgetItem(str(records[i][1])))
                self.tw_records.setItem(i, 2, QTableWidgetItem(str(records[i][2])))

    def change_filter(self):
        if self.sender() == self.filter_all:
            self.filter = False
        elif self.sender() == self.filter_notes:
            self.filter = RecordType.NOTE.value
        elif self.sender() == self.filter_reminders:
            self.filter = RecordType.REMINDER.value
        elif self.sender() == self.filter_tasks:
            self.filter = RecordType.TASK.value

        self.update_records()

    def create_update_timer(self, record, record_type):
        set_date_time = datetime.strptime(record[5], '%Y-%m-%d %H:%M:%S')

        if int((set_date_time - datetime.now()).total_seconds()) >= 0:

            add_date_time = datetime.now()
            seconds = int(str(int((set_date_time - add_date_time).total_seconds())) + '000')

            if record[0] in self.timers[record_type]:
                timer = self.timers[record_type][record[0]]
                timer.stop()

            timer = QTimer()
            timer.timeout.connect(lambda: self.send_notification(record_type, record[1], record[2]))
            timer.setSingleShot(True)
            timer.start(seconds)
            self.timers[record_type].update({record[0]: timer})

    def show_record(self, id, record_type):
        self.update_records()

        if record_type == RecordType.NOTE.value:
            self.form = ViewNoteForm()
        elif record_type == RecordType.REMINDER.value:
            self.form = ViewReminderForm()
        elif record_type == RecordType.TASK.value:
            self.form = ViewTaskForm()

        self.record.addWidget(self.form, 0, 0)
        self.form.load_record(id, record_type)

        self.form.delete_record.connect(self.delete_record)
        self.form.edit_record.connect(self.edit_record)

    def send_notification(self, record_type, title, topic):
        toaster = ToastNotifier()

        icon = 'картинки ico/' + random.choice(self.pictures)

        if record_type == RecordType.REMINDER.value:
            self.sounds.remind.play()

            toaster.show_toast(topic, title, threaded=True,
                               icon_path=icon, duration=5)

        elif record_type == RecordType.TASK.value:
            self.sounds.fail.play()

            toaster.show_toast('Внимание', f'Время на выполнение задния {title} истекло', threaded=True,
                               icon_path=icon, duration=5)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    wnd = OrganizerForm()
    wnd.show()
    sys.exit(app.exec())


from cv2 import cv2
from cvzone.HandTrackingModule import HandDetector
cap=cv2.VideoCapture(0)
cap.set(3,1260)
cap.set(4,720)

detector=HandDetector(detectionCon=0.8)

while True:
    success, img = cap.read()
    hands, img = detector.findHands(img)
    img1 = cv2.imread("Resources/fish.jpg")
    img1 = cv2.resize(img1,[250,250])
    img[10:260,10:260]=img1

    if len(hands):
        print("Zoom Gesture")

    cv2.imshow("Image",img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break