import asyncio
import concurrent.futures
import glob
import json
import logging
import os
import shutil
import sys
import tempfile
import uuid
from asyncio.exceptions import CancelledError
from datetime import datetime
from functools import partial
from pprint import pprint
from typing import Callable, Dict, List, Optional, Union

import ansible_runner
import dpath.util
import janus
import yaml

if os.environ.get("RULES_ENGINE", "durable_rules") == "drools":
    from drools.vendor import lang
else:
    from durable import lang

from .collection import find_playbook, has_playbook, split_collection_name
from .conf import settings
from .exception import ShutdownException
from .util import get_horizontal_rule

logger = logging.getLogger()

async def none(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
):
    await event_log.put(
        dict(
            type="Action",
            action="noop",
            activation_id=settings.identifier,
            run_at=str(datetime.utcnow()),
        )
    )

async def debug(event_log, **kwargs):
    print(get_horizontal_rule("="))
    print("context:")
    pprint(lang.c.__dict__)
    print(get_horizontal_rule("="))
    print("facts:")
    pprint(lang.get_facts(kwargs["ruleset"]))
    print(get_horizontal_rule("="))
    print("kwargs:")
    pprint(kwargs)
    print(get_horizontal_rule("="))
    sys.stdout.flush()
    await event_log.put(
        dict(
            type="Action",
            action="debug",
            playbook_name=kwargs.get("name"),
            activation_id=settings.identifier,
            run_at=str(datetime.utcnow()),
        )
    )

async def print_event(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
    name: Optional[str] = None,
    var_root: Union[str, Dict, None] = None,
    pretty: Optional[str] = None,
):
    print_fn: Callable = print
    if pretty:
        print_fn = pprint

    if var_root:
        update_variables(variables, var_root)

    var_name = "event"
    if "events" in variables:
        var_name = "events"

    print_fn(variables[var_name])
    sys.stdout.flush()
    await event_log.put(
        dict(
            type="Action",
            action="print_event",
            activation_id=settings.identifier,
            playbook_name=name,
            run_at=str(datetime.utcnow()),
        )
    )

async def assert_fact(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
    fact: Dict,
    name: Optional[str] = None,
):
    logger.debug(f"assert_fact {ruleset} {fact}")
    lang.assert_fact(ruleset, fact)
    await event_log.put(
        dict(
            type="Action",
            action="assert_fact",
            activation_id=settings.identifier,
            playbook_name=name,
            run_at=str(datetime.utcnow()),
        )
    )

async def retract_fact(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
    fact: Dict,
    name: Optional[str] = None,
):
    lang.retract_fact(ruleset, fact)
    await event_log.put(
        dict(
            type="Action",
            action="retract_fact",
            activation_id=settings.identifier,
            playbook_name=name,
            run_at=str(datetime.utcnow()),
        )
    )

async def post_event(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
    event: Dict,
):
    lang.post(ruleset, event)

    await event_log.put(
        dict(
            type="Action",
            action="post_event",
            activation_id=settings.identifier,
            run_at=str(datetime.utcnow()),
        )
    )

async def run_playbook(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
    name: str,
    assert_facts: Optional[bool] = None,
    post_events: Optional[bool] = None,
    verbosity: int = 0,
    var_root: Union[str, Dict, None] = None,
    copy_files: Optional[bool] = False,
    json_mode: Optional[bool] = False,
    retries: Optional[int] = 0,
    retry: Optional[bool] = False,
    delay: Optional[int] = 0,
    **kwargs,
):

    logger.info(f"running Ansible playbook: {name}")
    temp, playbook_name, job_id = await pre_process_runner(
        event_log,
        inventory,
        variables,
        facts,
        ruleset,
        name,
        "run_playbook",
        var_root,
        copy_files,
        True,
        **kwargs,
    )
    logger.info("Calling Ansible runner")

    if retry:
        retries = max(retries, 1)
    for i in range(retries + 1):
        if i > 0 and delay > 0:
            await asyncio.sleep(delay)

        run_at = str(datetime.utcnow())
        await call_runner(
            event_log,
            job_id,
            temp,
            dict(playbook=playbook_name),
            hosts,
            verbosity,
            json_mode,
        )
        if get_status(temp) != "failed":
            break

    return await post_process_runner(
        event_log,
        temp,
        ruleset,
        settings.identifier,
        name,
        "run_playbook",
        job_id,
        run_at,
        assert_facts,
        post_events,
    )

async def run_module(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
    name: str,
    assert_facts: Optional[bool] = None,
    post_events: Optional[bool] = None,
    verbosity: int = 0,
    var_root: Union[str, Dict, None] = None,
    copy_files: Optional[bool] = False,
    json_mode: Optional[bool] = False,
    module_args: Union[Dict, None] = None,
    retries: Optional[int] = 0,
    retry: Optional[bool] = False,
    delay: Optional[int] = 0,
    **kwargs,
):

    temp, module_name, job_id = await pre_process_runner(
        event_log,
        inventory,
        variables,
        facts,
        ruleset,
        name,
        "run_module",
        var_root,
        copy_files,
        False,
        **kwargs,
    )
    logger.info("Calling Ansible runner")
    module_args_str = ""
    if module_args:
        for k, v in module_args.items():
            if len(module_args_str) > 0:
                module_args_str += " "
            module_args_str += f'{k}="{v}"'

    if retry:
        retries = max(retries, 1)
    for i in range(retries + 1):
        if i > 0 and delay > 0:
            await asyncio.sleep(delay)

        run_at = str(datetime.utcnow())
        await call_runner(
            event_log,
            job_id,
            temp,
            dict(
                module=module_name,
                host_pattern=",".join(hosts),
                module_args=module_args_str,
            ),
            hosts,
            verbosity,
            json_mode,
        )
        if get_status(temp) != "failed":
            break

    return await post_process_runner(
        event_log,
        temp,
        ruleset,
        settings.identifier,
        name,
        "run_module",
        job_id,
        run_at,
        assert_facts,
        post_events,
    )

async def call_runner(
    event_log,
    job_id: str,
    private_data_dir: str,
    runner_args: Dict,
    hosts: List,
    verbosity: int = 0,
    json_mode: Optional[bool] = False,
):

    host_limit = ",".join(hosts)

    loop = asyncio.get_running_loop()

    queue = janus.Queue()

    # The event_callback is called from the ansible-runner thread
    # It needs a thread-safe synchronous queue.
    # Janus provides a sync queue connected to an async queue
    # Here we push the event into the sync side of janus
    def event_callback(event, *args, **kwargs):
        event["job_id"] = job_id
        event["ansible_events_id"] = settings.identifier
        logger.debug("event_callback")
        queue.sync_q.put(dict(type="AnsibleEvent", event=event))

    # Here we read the async side and push it into the event queue
    # which is also async.
    # We do this until cancelled at the end of the ansible runner call.
    # We might need to drain the queue here before ending.
    async def read_queue():
        try:
            while True:
                val = await queue.async_q.get()
                event_data = val.get("event", {})
                val["run_at"] = event_data.get("created")
                await event_log.put(val)
        except CancelledError:
            pass

    tasks = []

    tasks.append(asyncio.create_task(read_queue()))

    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as task_pool:
        await loop.run_in_executor(
            task_pool,
            partial(
                ansible_runner.run,
                private_data_dir=private_data_dir,
                limit=host_limit,
                verbosity=verbosity,
                event_handler=event_callback,
                json_mode=json_mode,
                **runner_args,
            ),
        )

    # Cancel the queue reading task
    for task in tasks:
        task.cancel()
    await asyncio.gather(*tasks)

async def pre_process_runner(
    event_log,
    inventory: Dict,
    variables: Dict,
    facts: Dict,
    ruleset: str,
    name: str,
    action: str,
    var_root: Union[str, Dict, None] = None,
    copy_files: Optional[bool] = False,
    check_files: Optional[bool] = True,
    **kwargs,
):

    private_data_dir = tempfile.mkdtemp(prefix=action)
    logger.debug(f"private data dir {private_data_dir}")
    logger.debug(f"variables {variables}")
    logger.debug(f"facts {facts}")

    variables["facts"] = facts
    for k, v in kwargs.items():
        variables[k] = v

    if var_root:
        update_variables(variables, var_root)

    playbook_name = name
    if True:
        os.mkdir(os.path.join(private_data_dir, "env"))
        with open(
            os.path.join(private_data_dir, "env", "extravars"), "w"
        ) as f:
            f.write(yaml.dump(variables))
        os.mkdir(os.path.join(private_data_dir, "inventory"))
        with open(
            os.path.join(private_data_dir, "inventory", "hosts"), "w"
        ) as f:
            f.write(yaml.dump(inventory))
        os.mkdir(os.path.join(private_data_dir, "project"))

    if check_files:
        if os.path.exists(name):
            playbook_name = os.path.basename(name)
            shutil.copy(
                name, os.path.join(private_data_dir, "project", playbook_name)
            )
            if copy_files:
                shutil.copytree(
                    os.path.dirname(os.path.abspath(name)),
                    os.path.join(private_data_dir, "project"),
                    dirs_exist_ok=True,
                )
        elif has_playbook(*split_collection_name(name)):
            playbook_name = name
            shutil.copy(
                find_playbook(*split_collection_name(name)),
                os.path.join(private_data_dir, "project", name),
            )
        else:
            logger.error(
                f"Could not find a playbook for {name} from {os.getcwd()}"
            )

    job_id = str(uuid.uuid4())

    await event_log.put(
        dict(type="Job", job_id=job_id, ansible_events_id=settings.identifier)
    )
    return (private_data_dir, playbook_name, job_id)

async def post_process_runner(
    event_log,
    private_data_dir: str,
    ruleset: str,
    activation_id: str,
    name: str,
    action: str,
    job_id: str,
    run_at: str,
    assert_facts: Optional[bool] = None,
    post_events: Optional[bool] = None,
):

    for rc_file in glob.glob(
        os.path.join(private_data_dir, "artifacts", "*", "rc")
    ):
        with open(rc_file, "r") as f:
            rc = int(f.read())

    status = get_status(private_data_dir)

    result = dict(
        type="Action",
        action=action,
        activation_id=activation_id,
        playbook_name=name,
        job_id=job_id,
        ruleset=ruleset,
        rc=rc,
        status=status,
        run_at=run_at,
    )
    await event_log.put(result)

    if assert_facts or post_events:
        logger.debug("assert_facts")
        for host_facts in glob.glob(
            os.path.join(private_data_dir, "artifacts", "*", "fact_cache", "*")
        ):
            with open(host_facts) as f:
                fact = json.loads(f.read())
            logger.debug(f"fact {fact}")
            if assert_facts:
                lang.assert_fact(ruleset, fact)
            if post_events:
                lang.post(ruleset, fact)

    return result

async def shutdown(
    event_log,
    inventory: Dict,
    hosts: List,
    variables: Dict,
    facts: Dict,
    ruleset: str,
):
    await event_log.put(
        dict(
            type="Action",
            action="shutdown",
            activation_id=settings.identifier,
            run_at=str(datetime.utcnow()),
        )
    )
    raise ShutdownException()

actions: Dict[str, Callable] = dict(
    none=none,
    debug=debug,
    print_event=print_event,
    assert_fact=assert_fact,
    retract_fact=retract_fact,
    post_event=post_event,
    run_playbook=run_playbook,
    run_module=run_module,
    shutdown=shutdown,
)

def update_variables(variables: Dict, var_root: Union[str, Dict]):
    var_roots = {var_root: var_root} if isinstance(var_root, str) else var_root
    if "event" in variables:
        for key, _new_key in var_roots.items():
            new_value = dpath.util.get(
                variables["event"], key, separator=".", default=None
            )
            if new_value:
                variables["event"] = new_value
                break
    elif "events" in variables:
        for _k, v in variables["events"].items():
            for old_key, new_key in var_roots.items():
                new_value = dpath.util.get(
                    v, old_key, separator=".", default=None
                )
                if new_value:
                    variables["events"][new_key] = new_value
                    break

def get_status(private_data_dir: str):
    status_files = glob.glob(
        os.path.join(private_data_dir, "artifacts", "*", "status")
    )
    status_files.sort(key=os.path.getmtime, reverse=True)
    with open(status_files[0], "r") as f:
        status = f.read()
    return status


#   Libaries
import face_recognition
import os
import cv2

#   This is well suited for a rasberry pi surveillance camera project, for example.
#   Examine saved images and detects familiar faces and keep images of strangers.

#   Path to the folder where the images are located for identification
path_unknown = "path to folder"

#   Path to the folder where identified faces are
path_known = "path to folder"

#   Using cv2.imread() method
identified_1 = cv2.imread(path_known+"Joe Biden.jpg")
identified_2 = cv2.imread(path_known+"Elon Musk.jpg")
identified_3 = cv2.imread(path_known+"Kamala harris.jpg")

#   convert the input frame from BGR to RGB
#   face 1
identified_1 = cv2.cvtColor(identified_1,cv2.COLOR_BGR2RGB)
img_encoding_1 = face_recognition.face_encodings(identified_1)[0]
#   face2
identified_2 = cv2.cvtColor(identified_2,cv2.COLOR_BGR2RGB)
img_encoding_2 = face_recognition.face_encodings(identified_2)[0]
#   face 3
identified_3 = cv2.cvtColor(identified_3,cv2.COLOR_BGR2RGB)
img_encoding_3 = face_recognition.face_encodings(identified_3)[0]
#       ... And so on..

#   Create arrays of known face encodings.
img_encoding = [img_encoding_1, img_encoding_2, img_encoding_3]

#   Retrieves all images from the folder
for image in os.listdir(path_unknown):
#   Must use "try" if faces cannot be identified from the image
    try:
#       Using cv2.imread() method
        img2 = cv2.imread(path_unknown+image)
#       convert the input frame from BGR to RGB
#       If the face is recognized then delete the image from the file
        img2 = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)

        img_encoding2 = face_recognition.face_encodings(img2)[0]
        #   Compare faces
        result = face_recognition.compare_faces(img_encoding, img_encoding2)
        print("Result: ", result,"-",image)

        if result[0] == True:
#       if result[0] == False:
#       Delete the image if the faces are idenetified.
            print("Joe Biden identified")
            os.remove(path_unknown+image)
        elif result[1] == True:
            print("Elon Musk identified")
#       elif result[1] == False:
            os.remove(path_unknown+image)
        elif result[2] == True:
            print("Kamala Harris identified")
#       elif result[2] == False:
            os.remove(path_unknown+image)
#       ... And so on..

    except IndexError as e:
#       If the face cannot be detected then delete the image from the file.
        print("Could not recognize any faces in image")

#       Delete the image if the face cannot be detected.
#       If you want keep image just remove (os.remove(path_unknown+image)) but keep except IndexError
        os.remove(path_unknown+image)


T = int(input())

for _ in range(T):
    a,b=map(int,input().split(" "))
    numsA=[int(x) for x in input().split(" ")]
    numsB=[int(x) for x in input().split(" ")]
    numsA.sort()
    numsB.sort()
    ap=0
    bp=0
    ans=0
    while(ap<a):
        while(bp<b and numsA[ap]>numsB[bp]):
            bp+=1
        ans+=bp
        ap+=1
    print(ans)


import os
import pickle
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder

DATASET = 'czech_bank'
MAPFILE = 'mapping.pickle'
LE_MAP_PATH = os.path.join(Path(__file__).parent, 'resources/label_encode_map', DATASET, MAPFILE)
CAT_COL = ['account_id', 'type', 'operation', 'k_symbol', 'bank', 'account']
DATE_COLUMN = 'date'

def label_encode(df, cat_col, mapping_path):
    le_name_mapping = dict()
    le = preprocessing.LabelEncoder()
    for col in cat_col:
        df[col] = le.fit_transform(df[col])
        le_name_mapping[col] = dict(zip(le.classes_, le.transform(le.classes_)))
    with open(mapping_path, 'wb') as fp:
        pickle.dump(le_name_mapping, fp)

def one_hot(df, column):
    return pd.get_dummies(df[column])

def cyclical_encode(df, date_column):
    date_col = pd.DatetimeIndex(df[date_column])
    df[date_column] = date_col
    df['year'] = date_col.year
    df['month'] = date_col.month
    df['day'] = date_col.day
    df['dayofweek'] = date_col.dayofweek

def time_diff(df, date_column):
    df[date_column] = pd.to_datetime(df[date_column])
    diff = df.loc[:, [date_column]].sub(df.loc[0, [date_column]], axis='columns')/np.timedelta64(1, "D").astype("int64")
    df[date_column] = diff[date_column].dt.days
    return df

def preprocess(filename, date_column, le_map_path, dataset):
    csv_path = os.path.join(Path(__file__).parents[0], 'resources/real_datasets', dataset, filename)
    raw = pd.read_csv(csv_path)
    raw[['amount', 'balance']] = raw[['amount', 'balance']].astype(int)
    # cyclical_encode(raw, date_column)
    df = raw.drop(columns=['trans_id'])
    df[date_column]= pd.to_datetime(df[date_column])
    # label_encode(df, cat_col, le_map_path)
    # raw_one_hot = one_hot(raw, one_hot_col)
    return df

# processed = preprocess('clean_trans.csv', DATE_COLUMN, LE_MAP_PATH, DATASET)
#
# splited_df = np.array_split(processed, 20)
# splited_df[0].to_csv(os.path.join(Path(__file__).parents[0], 'resources/real_datasets', dataset, 'trans_3.csv'), index=False)

def process(filename, cat_col, date_column, dataset, real):
    if real:
        csv_path = os.path.join(Path(__file__).parents[0], 'resources/real_datasets', dataset, filename)
    else:
        csv_path = os.path.join(Path(__file__).parents[0], 'resources/fake_datasets', dataset, filename)
    df = pd.read_csv(csv_path)
    df['first_day'] = '1993-01-01'
    df['first_day'] = pd.to_datetime(df['first_day'])
    df[date_column] = pd.to_datetime(df[date_column])
    df[date_column] -= df['first_day']
    df[date_column] = df[date_column].dt.days
    df[cat_col] = df[cat_col].apply(LabelEncoder().fit_transform)
    df_out = df.drop(columns=['first_day'])
    if real:
        df_out.to_csv(os.path.join(Path(__file__).parents[0], 'resources/real_datasets', dataset, 'labelencode_' + filename),
                  index=False)
    else:
        df_out.to_csv(
            os.path.join(Path(__file__).parents[0], 'resources/fake_datasets', dataset, 'labelencode_' + filename),
            index=False)

def min_acc():
    csv_path = os.path.join(Path(__file__).parents[0], 'resources/real_datasets', 'czech_bank', 'clean_trans.csv')
    df = pd.read_csv(csv_path)
    df = df.set_index('date')
    accs = df.account_id.unique()
    min_acc = 100000
    grp = df.groupby(['account_id'])
    min_len = grp.size().min()
    return min_len

def tablegan_data(filename, dataset):
    csv_path = os.path.join(Path(__file__).parents[0], 'resources/real_datasets', dataset, f"{filename}.csv")
    raw = pd.read_csv(csv_path)

    def ctpy_check(row):
        if row['bank'] == 13 and row['account'] == 1715:
            return 0
        else:
            return 1
    label_df = pd.DataFrame()
    label_df['label'] = raw.apply(lambda row: ctpy_check(row), axis=1)
    label_df.to_csv(os.path.join(Path(__file__).parents[0],
                                 'resources/real_datasets',
                                 dataset, f"{filename}_labels.csv"),
                    index=False, header=False)

process('ctgan_fake_3_2022-04-10.csv', CAT_COL, 'date', DATASET, real=True)


import json
from django.shortcuts import  render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
from django.contrib import messages
import pandas as pd
import numpy as np

# Create your views here.

def home(request):
    return render(request,'home.html')

def upload_file(request):
    if request.method=='POST':
        uploaded_file=request.FILES['doc']
        f=FileSystemStorage()
        name=f.save(uploaded_file.name,uploaded_file)
        url=settings.MEDIA_ROOT.replace("/","\\")
        #print(url+"\\"+name)
        p=url+"\\"+name
        if 'csv' in p:
            df=pd.read_csv(p)
        elif 'json' in p:
            df=pd.read_json(p)
        elif 'xlsx' in p:
            df=pd.read_excel(p)
        else:
            context={"msg":"not valid"}
            return render(request,'home.html',context)
        l=[]

        #print(df)
        for i in df.index:
            s=str(i+1)
            l.append(s)
        df.insert(loc=0, column='SNO', value=l)
        df['PortCode']=df['PortCode'].apply(portcodecheck,d=df)
        df.dropna(subset=['ID','Name','PortCode','UnctadPortCode','Country','Latitude','Longitude'],inplace=True)
        #print(df)
        name=df['Name'].to_list()
        PortCode=df['PortCode'].to_list()
        df['MainPortName']=df['MainPortCode'].apply(mainport,y=name,z=PortCode)
        df["Longitude"]=df["Longitude"].apply(rep)
        df["Latitude"]=df["Latitude"].apply(rep)
        df['ID']=df['ID'].apply(str)
        df['Map'] = df.apply(lambda row: "https://www.google.com/maps/search/?api=1&query="+row.Latitude+"%2C"+row.Longitude, axis = 1)
        df_copy=df.drop(['SNO'], axis=1)
        head=df_copy.columns
        df_copy=df_copy.to_json(orient="index")
        json_df_copy=json.loads(df_copy)
        #columns=json_df['columns']
        #indexes=json_df['index']
        #data=json_df['data']
        context={"all":json_df_copy,"head":head}
        df.to_json('E:\\Private\\New folder\\port.json', orient='index')
        return render(request,'file.html',context)
    elif request.method == 'GET':
        return HttpResponse("Success!")

def portcodecheck(x,d):
    temp = d['PortCode'].str.contains(x, case=False)
    df=d[temp]
    w=df['UnctadPortCode'].loc[df.index[0]]
    if len(x)==5:
        if x[2:]==w:
            return x
    else:
        return np.nan

def mainport(x,y,z):
    if x in z:
        p=z.index(x)
        x=y[p]
    return x

def rep(x):
    return str(x).replace(',','.')

def search(request):
    word=request.POST.get('keyword')
    d=pd.read_json('E:\\Private\\New folder\\port.json', orient='index')
    #print(d)
    d['ID']=d['ID'].apply(str)
    mask1 = d['PortCode'].str.contains(word, case=False)
    mask2 = d['Name'].str.contains(word, case=False)
    mask3 = d['ID'].str.contains(word, case=False)
    df=d[mask1 | mask2 | mask3]
    df_copy=df.drop(['SNO'], axis=1)
    head=df_copy.columns
    df_copy=df_copy.to_json(orient="index")
    json_df=json.loads(df_copy)
    if len(json_df)>0:
        context={"all":json_df,"head":head}
    else:
        context={"nodata":"No data available"}
    return render(request,'file.html',context)

def to_edit(request):
    portcode=request.POST.get('portcode')
    d=pd.read_json('E:\\Private\\New folder\\port.json', orient='index')
    mask3 = d['PortCode'].str.contains(portcode, case=False)
    df=d[mask3].drop(['Map','MainPortName'], axis=1)
    head=df.columns
    df_copy=df.to_json(orient="index")
    json_df=json.loads(df_copy)
    context={"all":json_df,"head":head}
    return render(request,'edit.html',context)

def edit(request):
    if request.method=='POST':
        sno=str(request.POST.get('SNO'))
        id=request.POST.get('ID')
        Name=request.POST.get('Name')
        PortCode=request.POST.get('PortCode')
        UnctadPortCode=request.POST.get('UnctadPortCode')
        Country=request.POST.get('Country')
        Latitude=request.POST.get('Latitude')
        Longitude=request.POST.get('Longitude')
        Url=request.POST.get('Url')
        MainPortCode=request.POST.get('MainPortCode')
        df=pd.read_json('E:\\Private\\New folder\\port.json', orient='index')
        df['SNO']=df['SNO'].apply(str)
        mask3 = df['SNO'].str.contains(sno, case=False)
        d=df[mask3]
        if id=='' or Name=='' or PortCode=='' or UnctadPortCode=='' or Country=='' or Latitude=='' or Longitude=='' or MainPortCode=='':
            if PortCode[2:]==UnctadPortCode and len(PortCode)==5:
                df=d[mask3].drop(['Map','MainPortName'], axis=1)
                print(df)
                head=df.columns
                df_copy=df.to_json(orient="index")
                json_df=json.loads(df_copy)
                messages.error(request,"Hi buddy")
                context={"all":json_df,"head":head}
                return render(request,'edit.html',context)
        w=d.index[0]
        df.at[w,'ID']=id
        df.at[w,'Name']=Name
        df.at[w,'PortCode']=PortCode
        df.at[w,'UnctadPortCode']=UnctadPortCode
        df.at[w,'Country']=Country
        df.at[w,'Latitude']=Latitude
        df.at[w,'Longitude']=Longitude
        df.at[w,'Url']=Url
        df.at[w,'MainPortCode']=MainPortCode
        df.at[w,'Map']="https://www.google.com/maps/search/?api=1&query="+Latitude+"%2C"+Longitude
        df_copy=df.drop(['SNO'], axis=1)
        head=df_copy.columns
        df_copy=df_copy.to_json(orient="index")
        json_df_copy=json.loads(df_copy)
        #columns=json_df['columns']
        #indexes=json_df['index']
        #data=json_df['data']
        context={"all":json_df_copy,"head":head}
        df.to_json('E:\\Private\\New folder\\port.json', orient='index')
        return render(request,'file.html',context)
    elif request.method == 'GET':
        return HttpResponse("Success!")

def delete(request):
    portcode=request.POST.get('portcode')
    d=pd.read_json('E:\\Private\\New folder\\port.json', orient='index')
    mask3 = d['PortCode'].str.contains(portcode, case=False)
    df=d[mask3]
    w=df.index[0]
    d=d.drop(w)
    d=d.drop(['SNO'],axis=1)
    l=[]
    for i in d.index:
        s=str(i)
        l.append(s)
    d.insert(loc=0, column='SNO', value=l)
    df_copy=d.drop(['SNO'], axis=1)
    head=df_copy.columns
    df_copy=df_copy.to_json(orient="index")
    json_df_copy=json.loads(df_copy)
    context={"all":json_df_copy,"head":head}
    d.to_json('E:\\Private\\New folder\\port.json', orient='index')
    return render(request,'file.html',context)


#  Copyright (c) 2022-present - Predeactor - Licensed under the MIT License.
#  See the LICENSE file included with the file for more information about this project's
#   license.

import unittest

from discapty import (
    AlreadyCompletedError,
    AlreadyRunningError,
    Challenge,
    ChallengeCompletionError,
    States,
    TooManyRetriesError,
    WheezyGenerator,
)

class TestChallenge(unittest.TestCase):
    """
    Test the discapty.Challenge object.
    """

    def test_create_challenge(self):
        """
        Attempt to create a Challenge object.
        """
        challenge = Challenge(WheezyGenerator())
        self.assertIsInstance(challenge.generator, WheezyGenerator)

    def test_can_begin(self):
        """
        Attempt to begin the challenge.
        """
        challenge = Challenge(WheezyGenerator())
        challenge.begin()

        self.assertIs(challenge.state, States.WAITING)

    def test_can_not_begin(self):
        """
        Check that the challenge cannot begin.
        """
        challenge = Challenge(WheezyGenerator())
        challenge.state = States.FAILED
        self.assertRaises(TooManyRetriesError, challenge.begin)

        challenge.state = States.FAILURE
        self.assertRaises(ChallengeCompletionError, challenge.begin)

        challenge.state = States.COMPLETED
        self.assertRaises(AlreadyCompletedError, challenge.begin)

        challenge.state = States.WAITING
        self.assertRaises(AlreadyRunningError, challenge.begin)

    def test_can_be_reloaded(self):
        """
        Try to reload the Challenge's code.
        """
        challenge = Challenge(WheezyGenerator(width=500, height=300), code="wheezy")

        with self.assertRaisesRegex(TypeError, "Challenge is not running"):
            challenge.reload()

        challenge.begin()
        challenge.reload()
        self.assertEqual(challenge.attempted_tries, 1)
        self.assertNotEqual(challenge.code, "wheezy")

        challenge.reload(increase_attempted_tries=False)
        self.assertEqual(challenge.attempted_tries, 1)

    def test_ensure_captcha_is_same(self):
        """
        Ensure that the same captcha is generated each time.
        """
        challenge = Challenge(WheezyGenerator(width=500, height=300))
        first = challenge.captcha_object
        second = challenge.captcha_object
        self.assertEqual(id(first), id(second))

        challenge.code = "Anything goes!"
        third = challenge.captcha_object
        self.assertNotEqual(id(first), id(third))

    def test_challenge_validation(self):
        """
        Ensure that the Challenge returns the correct boolean when checking codes.
        """
        challenge = Challenge(WheezyGenerator(width=500, height=300), code="wheezy")

        # Testing an incorrect code
        self.assertFalse(challenge.check("whezzy"))
        self.assertIs(challenge.failures, 1)
        self.assertIs(challenge.attempted_tries, 1)

        # Testing correct code
        self.assertTrue(challenge.check("wheezy"))
        self.assertIs(challenge.failures, 1)
        self.assertIs(challenge.state, States.COMPLETED)

    def test_ensure_failures(self):  # sourcery skip: class-extract-method
        """
        Ensure that the challenge raises an error if too many fails.
        """
        challenge = Challenge(WheezyGenerator())
        challenge.begin()

        # Testing an incorrect code
        for _ in range(challenge.allowed_retries - 1):
            challenge.check("random")

        with self.assertRaises(TooManyRetriesError):
            challenge.check("random")

    def test_ensure_last_failure(self):
        """
        Ensure that the challenge can handle a last success before failure.
        """
        challenge = Challenge(WheezyGenerator())
        challenge.begin()

        # Testing an incorrect code
        for _ in range(challenge.allowed_retries - 1):
            challenge.check("random")

        self.assertTrue(challenge.check(challenge.code))

    def test_increase_attempted_tries_on_reload(self):
        """
        Ensure the challenge increases the failure by one if specified.
        """
        challenge = Challenge(WheezyGenerator())
        challenge.begin()
        actual_tries = challenge.attempted_tries
        challenge.reload(increase_attempted_tries=True)

        self.assertGreater(challenge.attempted_tries, actual_tries)

    def test_increase_failure_on_reload(self):
        """
        Ensure the challenge increases the failure by one if specified.
        """
        challenge = Challenge(WheezyGenerator())
        challenge.begin()
        actual_failures = challenge.failures
        challenge.reload(increase_failures=True)

        self.assertGreater(challenge.failures, actual_failures)

    def test_cant_reload_on_failed(self):
        """
        Ensure the challenge can't be modified on reload.
        """
        challenge = Challenge(WheezyGenerator())
        challenge.state = States.FAILED

        self.assertRaises(TypeError, challenge.reload)

    def test_cant_check(self):
        """
        Ensure the challenge cannot be checked if not modifiable
        """
        challenge = Challenge(WheezyGenerator())
        challenge.state = States.FAILED

        self.assertRaises(TypeError, challenge.check)

    def test_cant_cancel(self):
        """
        Ensure the challenge cannot be cancelled if not modifiable
        """
        challenge = Challenge(WheezyGenerator())
        challenge.state = States.FAILED

        self.assertRaises(TypeError, challenge.cancel)

    def test_casing_enforcement(self):
        """
        Ensure that the casing is respected.
        """
        challenge = Challenge(WheezyGenerator(), code="TEST")
        challenge.begin()

        self.assertFalse(challenge.check("test", force_casing=True))
        self.assertTrue(challenge.check("test", force_casing=False))

    def test_spaces_removal(self):
        """
        Ensure that spaces are removed if needed.
        """
        challenge = Challenge(WheezyGenerator(), code="TEST")
        challenge.begin()

        self.assertFalse(challenge.check("TE ST", remove_spaces=False))
        self.assertTrue(challenge.check("TE ST", remove_spaces=True))

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


from tkinter import *

pi = 3.14159

class Control_panel:
	def __init__(self):
		self.root = Tk()

		# sliders
		self.s_rx = Scale(self.root, orient=HORIZONTAL, from_=-pi, to=pi, resolution=0.1, length=200)
		self.s_ry = Scale(self.root, orient=HORIZONTAL, from_=-pi, to=pi, resolution=0.1, length=200)
		self.s_rz = Scale(self.root, orient=HORIZONTAL, from_=-pi, to=pi, resolution=0.1, length=200)
		self.s_px = Scale(self.root, orient=HORIZONTAL, from_=-10, to=10, resolution=0.1, length=200)
		self.s_py = Scale(self.root, orient=HORIZONTAL, from_=-10, to=10, resolution=0.1, length=200)
		self.s_pz = Scale(self.root, orient=HORIZONTAL, from_=-10, to=10, resolution=0.1, length=200)
		self.create_text(text='rotation x', col=0, row=0)
		self.create_text(text='rotation y', col=0, row=2)
		self.create_text(text='rotation z', col=0, row=4)
		self.create_text(text='position x', col=0, row=6)
		self.create_text(text='position y', col=0, row=8)
		self.create_text(text='position z', col=0, row=10)
		self.s_rx.grid(column=0, row=1, sticky=W)
		self.s_ry.grid(column=0, row=3, sticky=W)
		self.s_rz.grid(column=0, row=5, sticky=W)
		self.s_px.grid(column=0, row=7, sticky=W)
		self.s_py.grid(column=0, row=9, sticky=W)
		self.s_pz.grid(column=0, row=11, sticky=W)

		# checkboxes
		self.v_stroke = False
		self.v_fill = False
		self.b_stroke = Button(self.root, text="stroke", command=self.stroke_changed)
		self.b_fill = Button(self.root, text="fill", command=self.fill_changed)
		self.b_stroke.grid(column=0, row=12, sticky=W)
		self.b_fill.grid(column=0, row=12, sticky=E)

	def create_text(self, text='###', row=0, col=0):
		Label(self.root, text=text, font=("Consolas", 14, "normal")).grid(row=row, column=col)

	def stroke_changed(self):
		self.v_stroke = not self.v_stroke

	def fill_changed(self):
		self.v_fill = not self.v_fill

	def get_vars(self):
		return [self.s_px.get(),
				self.s_py.get(),
				self.s_pz.get(),
				self.s_rx.get(),
				self.s_ry.get(),
				self.s_rz.get(),
				self.v_stroke,
				self.v_fill]

	def get_root(self):
		return self.root


import json
import numpy as np
import math
import torch
import torch.nn as nn

def read_dict(path):
    with open(path, encoding='utf-8') as type_dict:
        idx = json.load(type_dict)

    return idx

# sinusoidal embeddings for argument-aware position embeddings
def get_embedding(max_seq_len, embedding_dim, padding_idx=None, rel_pos_init=0):
    """Build sinusoidal embeddings.
    This matches the implementation in tensor2tensor, but differs slightly
    from the description in Section 3.5 of "Attention Is All You Need".
    rel pos init:
    """
    # num_embeddings = 2*max_seq_len+1
    num_embeddings = max_seq_len
    half_dim = embedding_dim // 2
    emb = math.log(10000) / (half_dim - 1)
    emb = torch.exp(torch.arange(half_dim, dtype=torch.float, requires_grad=False) * -emb)
    if rel_pos_init == 0:
        emb = torch.arange(num_embeddings, dtype=torch.float, requires_grad=False).unsqueeze(1) * emb.unsqueeze(0)
    else:
        emb = torch.arange(-max_seq_len,max_seq_len+1, dtype=torch.float, requires_grad=False).unsqueeze(1)*emb.unsqueeze(0)
    emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
    if embedding_dim % 2 == 1:
        # zero pad
        emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
    if padding_idx is not None:
        emb[padding_idx, :] = 0

    return nn.Embedding.from_pretrained(emb, freeze=True)

class TypeEmbeddings(nn.Module):

    def __init__(self, type_dict_path, embeddinsg_size, is_freeze=False):
        super().__init__()
        self.type2id = read_dict(type_dict_path)
        self.id2type = {v: k for k, v in self.type2id.items()}

        embeddings = [np.random.uniform(-0.25, 0.25, embeddinsg_size) for i in range(len(self.type2id) - 1)]

        embeddings = np.vstack([np.zeros(embeddinsg_size), embeddings])

        self.type_embeddings = nn.Embedding.from_pretrained(torch.FloatTensor(embeddings), freeze=is_freeze)

    def get_type2id(self):
        return self.type2id

    def get_id2type(self):
        return self.id2type

    def forward(self, input_idx):
        return self.type_embeddings(input_idx)

class UtterenceAwarePosEmbedding(nn.Module):

    def __init__(self, max_utter_nums, max_seq_lens, hidden_size, dropout=0.2):
        super().__init__()
        self.hidden_size = hidden_size
        self.max_utter_nums = max_utter_nums
        self.max_seq_lens = max_seq_lens

        self.utter_embedding = get_embedding(self.max_utter_nums, hidden_size)
        self.linear = nn.Sequential(nn.Linear(self.hidden_size, self.hidden_size),
                                    nn.Dropout(dropout),
                                    nn.ReLU(inplace=True)
                                    )

    def forward(self, utter_pos, mask):
        utter_pos = self.utter_embedding(utter_pos)

        return self.linear(utter_pos)


from collections import namedtuple
from enigma_machine.conf.defaults import ALPHABET

Wire = namedtuple("Wire", "l_contact r_contact")

class Rotor:

    def __init__(self, wheel_id, contact_mapping, notch, window="A", ring_setting="A", alphabet=ALPHABET):
        """ Initialize Rotor

        Args:
            wheel_id (str):  Identifier for the Rotor
            contact_mapping (str):   Index ordered mapping from alphabet onto
                                    inbound contacts
            notch (str):    Letter associated with position of notch on Rotor ring
            window (str):   Initial window position of Rotor
            ring_setting (str): Rotor ring setting
            alphabet (str): Alphabet used for Rotor

        """
        self.alphabet = alphabet
        self.wheel_id = wheel_id
        self.wiring = contact_mapping
        self.notch = notch
        self.configure(window, ring_setting)

    @property
    def alphabet(self):
        return self._alphabet

    @alphabet.setter
    def alphabet(self, alphabet):
        assert isinstance(alphabet, str), "Alphabet must be string"
        assert len(alphabet) > 0, "Alphabet must be non-zero length"

        self._alphabet = alphabet

    @property
    def notch(self):
        return self._notch

    @notch.setter
    def notch(self, notch_pos):
        """ Set the position of the notch on the ring

        Sets the letter position of the notch on the ring for the rotor. Also
        updates and records the turnover position (Letter visible in window)
        when notch is active and triggers the next rotor to step.

        Args:
            notch_pos (str): Letter position of the notch on the ring

        """
        assert (len(notch_pos) == 1), 'Notch position must be single digit'
        assert isinstance(notch_pos, str), 'Notch postion must be of type string'
        assert notch_pos in self.alphabet, 'Notch position must be member of alphabet'

        self._notch = notch_pos.upper()
        # Notch position is 8 letter positions advanced from turnover in window
        self.turnover = self.alphabet[(self.alphabet.index(self._notch) - 8) % len(self.alphabet)]

    @property
    def ring_setting(self):
        return self._ring_setting

    @ring_setting.setter
    def ring_setting(self, setting):
        assert (len(setting) == 1), 'Ring setting must be a single letter'
        assert isinstance(setting, str), 'Ring setting must be of type string'
        assert setting in self.alphabet, 'Ring setting must be member of alphabet'

        self._ring_setting = setting.upper()

    @property
    def window(self):
        return self._window

    @window.setter
    def window(self, window):
        assert (len(window) == 1), 'Window setting must be a single letter'
        assert isinstance(window, str), 'Window setting must be of type string'
        assert window in self.alphabet, 'Window setting must be member of alphabet'

        self._window = window.upper()
        # Offset the core wiring based on selected window position
        self.core_offset = (self.alphabet.index(self.window) - self.alphabet.index(self.ring_setting)) % len(self.alphabet)

    @property
    def wiring(self):
        # Return forward pass mapping by default
        return sorted(self._wiring, key=lambda x: x.r_contact)

    @wiring.setter
    def wiring(self, contact_mapping):
        """ Set the wiring from a string mapping of alphabet onto inbound contacts

        Iterates over the provided mapping of alphabet from the right contacts through
        the scrambled wiring onto the left contacts. Populates a wiring array with
        all Wire mappings such that they can be used to encode letters during
        forward or reverse passes on the rotor.

        All wires are established disregarding the ring setting (equivalent to
        assuming a default ring setting of A).

        Args:
            contact_mapping (string): String containing ordered mapping of contacts

        """
        assert (len(contact_mapping) == len(self.alphabet)), f"Argument must contain {len(self.alphabet)} letters"
        assert isinstance(contact_mapping, str), 'Argument must be of type string'

        self._wiring = []
        for idx in range(len(self.alphabet)):
            self._wiring.append(Wire(contact_mapping[idx], self.alphabet[idx]))

    def configure(self, window="A", ring_setting="A"):
        """ Configure the rotor ring or window setting

        Args:
            window (str): Window setting for the rotor
            ring_setting (str): Ring setting for the ring relative to wiring core

        """
        # Configure ring setting first
        self.ring_setting = ring_setting
        # Then set window position
        self.window = window

    def step(self):
        """ Step the rotor position

        Returns:
            (bool) True if window is on a the turnover letter position

        """
        # Increment the core_offset and wrap around to 0 after after final letter
        turned = self.window == self.turnover
        self.core_offset = (self.core_offset + 1) % len(self.alphabet)
        self.window = self.alphabet[self.core_offset]
        return turned

    def encode(self, letter, forward=True):
        """ Encode a letter passing through the rotor

        Args:
            letter (str): Letter to encode
            forward (bool): Encoding forward pass or reverse through the rotor

        Returns:
            (string) Letter associated with the output index encoded by the
                     rotor

        """
        assert len(letter) == 1, 'Letter must be a single letter'
        assert isinstance(letter, str), 'Letter must be of type str'
        assert isinstance(forward, bool), 'forward must be of type boolean'

        # Target wire for input letter shifted by positon of wiring core and
        # inverse wiring mapping if backward pass through rotor
        wiring_map = self.wiring if forward else sorted(self.wiring, key=lambda x: x.l_contact)
        wire = wiring_map[self.core_offset]
        # Get output letter from encoding on wiring core
        encoded_letter = self.alphabet.index(wire.l_contact if forward else wire.r_contact)
        # Get index of the output letter shifted by the position of the wiring core
        output_index = encoded_letter - self.core_offset % len(self.alphabet)
        # Return letter associated with the output index
        return self.alphabet[output_index]


'''
Find Repeat
    We can find a duplicate integer in O(n) time while keeping our space cost at O(1).
'''

def find_duplicate(listi):
    n = len(listi) - 1

    # STEP 1: GET INSIDE A CYCLE
    # Start at position n+1 and walk n steps to
    # find a position guaranteed to be in a cycle
    pos = n + 1
    for _ in range(n):
        pos = listi[pos - 1]
        # we subtract 1 from the current position to step ahead:
        # the 2nd *position* in a listi is *index* 1

    # STEP 2: FIND THE LENGTH OF THE CYCLE
    # Find the length of the cycle by remembering a position in the cycle
    # and counting the steps it takes to get back to that position
    pos_cycle = pos
    curr_pos = listi[pos - 1]  # 1 step ahead
    cycle_size = 1

    while curr_pos != pos_cycle:
        curr_pos = listi[curr_pos - 1]
        cycle_size += 1

    # STEP 3: FIND THE FIRST NODE OF THE CYCLE
    # Start two pointers
    #   (1) at position n+1
    #   (2) ahead of position n+1 as many steps as the cycle's length
    slow = n + 1
    fast = n + 1
    for _ in range(cycle_size):
        fast = listi[fast - 1]

    # Advance until the pointers are in the same position
    # which is the first node in the cycle
    while slow != fast:
        slow = listi[slow - 1]
        fast = listi[fast - 1]

    # Since there are multiple values pointing to the first node
    # in the cycle, its position is a duplicate in our listi
    return slow


import string
import os
import random
import discord
import asyncio
import time
from utilities.vechainEnergyClient import vechainEnergyClient
from utilities.discordUtil import DiscordUtil

venergy = vechainEnergyClient()
disutil = DiscordUtil()

TIMEOUT = 90

class VechainConnect:
    async def connect(self, interaction: discord.Interaction):
        baseuri = os.getenv('VECHAIN_ENERGY_BASE_URL')
        sessionid = ''.join(random.choice(string.ascii_letters) for i in range(36)[2:])
        state = ''.join(random.choice(string.ascii_letters) for i in range(36)[2:])
        await venergy.start_session(session_id=sessionid, state=state)
        redirect = f"https://{baseuri}/session/{sessionid}"
        authurl = f"https://{baseuri}/oauth2/authorize?state={state}&scope=identity%20profile&redirect_uri={redirect}"
        embed = discord.Embed()
        embed.description = f"please click [here]({authurl}) to identify yourself."
        await disutil.interactionResponse(interaction=interaction, embed=embed, ephemeral=True)

        return sessionid

    async def waitforuserauth(self, sessionid: str):
        timeout = TIMEOUT
        while True:
            await asyncio.sleep(1)
            status = await venergy.get_session(sessionid=sessionid)
            if 'access_token' in status or 'error' in status:
                return status

            if --timeout == 0:
                break
        return

    async def getuserdata(self, token_type, access_token):
        return await venergy.get_user_info(token_type=token_type, access_token=access_token)

    async def editresponse(selfs, interaction: discord.Interaction, description: str):
        embed = discord.Embed()
        embed.description = description
        await interaction.edit_original_response(content=None, embed=embed)


import torch
import torch.nn.functional as F
import logging
logger = logging.getLogger(__name__)

def softmax_accuracy(y_pred,labels,weights):
   logger.debug('y_pred.shape=%s labels.shape=%s weights.shape=%s',y_pred.shape,labels.shape,weights.shape)
   # y_pred = y_pred.permute(0,2,1)
   # number of non-zero points in this batch
   nonzero = torch.sum(weights)
   logger.debug('nonzero=%s',nonzero)
   # convert logits to predictions
   y_pred = F.softmax(y_pred, dim=-1)
   # count how many predictions were correct, weighted for balance
   correct = torch.eq(y_pred.argmax(dim=1),labels).int()
   correct = torch.sum(weights * correct)

   return correct / nonzero


#!/home/maria/quack/venv/bin/python

class DoubleLinkedListCell(object):        #класс ячейки двусвязного списка
    def __init__(self, elem = None, prev__item= None, next__item = None):   #data - содержимое ячейки , prevc - предыдущая ячейка , nextc - следующая ячейка
        self.elem = elem
        self.prev__item = prev__item
        self.next__item = next__item

class DoubleLinkedList(object):                                    #класс двусвязного списка
    def __init__(self, first__item = None, last__item = None, length = 0):     #first - начало списка, last - конец списка, length -  длина списка
        self.first__item = first__item
        self.last__item = last__item
        self.length = length

    def len(self):                                              #вывод длины списка
       return self.length

    def unshift(self, x):                                   #добавление ячейки в начало списка
        self.length = self.length + 1;
        if self.first__item == None:
            self.first__item = DoubleLinkedListCell(x, None, None);
            self.last__item = self.first__item;
        else:
            self.first__item = DoubleLinkedListCell(x, None, self.first__item);
            self.first__item.next__item.prev__item = self.first__item

    def push(self, x):                                         #добавление ячейки в конец списка
        self.length = self.length + 1;
        if self.first__item == None:
            self.first__item = DoubleLinkedListCell(x, None, None)
            self.last__item = self.first__item
        elif self.first__item == self.last__item:
            self.last__item = DoubleLinkedListCell(x, self.first__item, None)
            self.first__item.next__item = self.last__item

        else:
            current = DoubleLinkedListCell(x, self.last__item, None)
            self.last__item.next__item = current;
            self.last__item = current;

    def addTo(self, x, i):            #добавление на определенное место i
        self.length = self.length + 1;
        if self.first__item  == None:
            self.first__item = DoubleLinkedListCell(x, None, None);
            self.last__item = self.first__item
        elif i == 0:
            self.first__item = DoubleLinkedListCell(x, None, self.first__item)
            self.first__item.next__item.prev__item = self.first__item
        else:
            current = self.first__item;
            count = 0;
            while current != None:
                #print('c:',count)
                if count == i - 1:
                    #print('found')
                    if current.next__item == None:
                        current.next__item = DoubleLinkedListCell(x, current, current.next__item)
                        #print(1,current.next__item.elem)
                        self.last__item = current.next__item
                    else:
                        #print(2,current.next__item.elem)
                        current.next__item = DoubleLinkedListCell(x, current, current.next__item)
                        current.next__item.next__item.prev__item = current.next__item
                    break;
                count = count + 1
                current = current.next__item

    def shift(self):                    #удаление первой ячейки
        if self.first__item.next__item == None:
            self.length = 0
            self.first__item =  None
            self.last__item = None
        else:
            self.length = self.length - 1
            self.first__item = self.first__item.next__item
            self.first__item.prev__item = None;

    def deleteFrom(self, i):                             #удаление ячейки с номером i
        if (self.first__item == None):
            print("DoubleLinkedList is empty")
        elif ((self.first__item == self.last__item) and (i == 0)):
            self.length = 0
            self.first__item = None
            self.last__item = None
        else:
            current = self.first__item;
            count = 0;
            if self.length > i:
                self.length = self.length - 1;
                while current != None:
                    if count == i - 1:
                        if current.next__item.next__item == None:
                            self.last__item = current.last__item
                        else:
                            current.next__item = current.next__item.next__item
                            current.next__item.prev__item = current
                        break;
                    current = current.next__item

    def give(self, i):                          #вывод ячейки с номером i
        if self.length < i:
            return None
        else:
            current = self.first__item
            count = 0;
            while current != None:
                if count == i:
                    return current.elem
                    break
                current = current.next__item
                count = count + 1

    def find(self,i):                           #поиск всех элементов с заданным значением и возвращение множества индексов
        count = 0
        current = self. first__item
        res = set()
        while count < self.length:
            if current.elem == i:
                res.add(count)
            count = count + 1
            current = current.next__item
        return res

    def delete(self,i):                             #удаление ячеек со значением i
        if ((self.length == 1) and (self.first__item.elem == i)):
            self.length = 0
            self.first__item = None
            self.last__item = None
        elif (self.length > 1):
            count = 0
            deleted = 0
            current = self.first__item
            while count < self.length:
                if current.elem == i:
                    if count == 0:
                        self.first__item = self.first__item.next__item
                        self.first__item.prev__item = None

                    elif current == self.last__item:
                        self.last__item.prev__item.next__item = None
                        self.last__item = self.last__item.prev__item

                    else:
                        current.prev__item.next__item = current.next__item
                        current.next__item.prev__item = current.prev__item
                    deleted = deleted + 1

                count = count + 1
                current = current.next__item

            self.length = self.length - deleted

    def contains(self,i):                         #проверяет, есть ли ячейки со значением i
        count = 0
        res = False
        current = self. first__item
        while count < self.length:
            if current.elem == i:
                res = True
                break
            count = count + 1
            current = current.next__item
        return res

    def first(self):                              #возвращает  первый элемент
        return self.first__item

    def last(self):                               #возвращает последний элемента
        return self.last__item

    def pop(self):
        if self.length == 0:
            return None
        elif self.last__item == self.first__item:
            self.length = 0
            self.first__item = None
            self.first__item = None
        else:
            self.length = self.length - 1
            self.last__item = self.last__item.prev__item
            self.last__item.next__item = None


# Create a function called `odd_average` that takes a list of numbers as parameter
# and returns the average value of the odd numbers in the list
# Create basic unit tests for it with at least 3 different test cases

def odd_average(list):
    average = []
    for n in range(len(list)):
        if list[n] % 2 !=0:
            average.append(list[n])

list_of_num = [2,4,6,8,10,12,14,16,18,20]

odd_average(list_of_num)


'''

How much did the item cost : 65.64
How much did the person give you: 100.00
The person ’s change is $34 .36
The bills or the change should be:
1 twenties
1 tens
0 fives
4 ones
1 quarters
1 dimes
0 nickels
1 pennies

'''
cost=float(input("How much did the item cost : "))
money=float(input("How much did the person give you :"))
change = money - cost
print("The persons' change is %1.2f" % change)

remain = change
twenties = 0
tens = 0
fives = 0
ones = 0
quarters = 0
dimes = 0
nickels = 0
pennies = 0

def print_change_bills():
    print("%d twenties" % twenties)
    print("%d tens" % tens)
    print("%d fives" % fives)
    print("%d ones" % ones)
    print("%d quarters" % quarters)

if remain >= 20 :
    twenties = int(remain) // 20
else:
    twenties = 0

remain = remain - 20 * twenties
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 10:
    tens = int(remain) // 10
else:
    tens = 0

remain = remain - 10 * tens
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 5:
    fives = int(remain) // 5
else:
    fives = 0

remain = remain - 5 * fives
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 1:
    ones = int(remain)
else:
    ones = 0

remain = (float)(remain - ones)
if remain == 0:
    print_change_bills()
    exit(0)

if remain >= 0.25:
    quarters = (int)(remain / 0.25)
else:
    quarters = 0

remain = remain - quarters * 0.25

print_change_bills()

if remain > 0.00:
    print("Bill is %1.2f" % remain)


def solution(A):
    sum_a = 0
    for number in A:
        sum_a += number

    max_num = len(A) + 1
    sum_expected = max_num * (max_num + 1) // 2
    return sum_expected - sum_a

arr = [5, 3, 2, 6, 1]
arr = [5, 3, 4, 2, 6, 1, 7]
arr = []
print(solution(arr))


from django import db

from adminpanel.models import Orders, Product, Users_shop, Managers_shop
from services.jobjson.getapijson import Wretline_json

import datetime

class Json_joob:
    """Работа с json данными"""

    def save_orders_db() -> None:
        """Получаем, сохраняем и проверяем данные по заказу"""
        # TODO уменьшить количество обращений к БД
        orders = Wretline_json.orders_json()

        #Orders.objects.all().delete()
        #Product.objects.all().delete()

        for order in orders:
            orders_db = Orders()

            try:
                instance = Orders.objects.get(
                    number=order['number'])
                print('1')
                Json_joob.save_midel_order(instance, order)
            except Orders.DoesNotExist:
                print('2')
                Json_joob.save_midel_order(orders_db, order)

            for product in order['positions']:
                products_db = Product()

                #print(product['id'])
                try:
                    instance = Product.objects.get(
                        number_order=order['number'],
                        number_product=product['id']
                    )
                    instance.status = product['status']
                    instance.comment = product['comment']
                    instance.save()
                except Product.DoesNotExist:
                    order_nubmer =order['number']
                    Json_joob.save_model_product(
                        products_db,
                        order_nubmer,
                        order['date'],
                        product)
            db.connections.close_all()

    def save_users_db() -> None:
        """Получаем и сохраняем список покупателей"""

        users = Wretline_json.users_json()

        for user in users:
            user_db = Users_shop()

            try:
                instance = Users_shop.objects.get(id_user=user['userId'])

                if instance.name != user['name']:
                    instance.name = user['name']
                if instance.mobile != user['mobile']:
                    instance.mobile = user['mobile']
                instance.save()
            except Users_shop.DoesNotExist:
                user_db.id_user = user['userId']
                user_db.name = user['name']
                user_db.mobile = user['mobile']
                user_db.save()
            db.connections.close_all()

    def save_manager_db() -> None:
        """Получаем, сохраняем и проверяем на изменение список менеджеров"""

        managers = Wretline_json.managers_json()

        for manager in managers:
            flname = f"{manager['firstName']} {manager['lastName']}"
            manager_db = Managers_shop()

            try:
                instance = Managers_shop.objects.get(
                    id_manager=manager['contractorId'])
                if instance.name != flname:
                    instance.name = flname
                if instance.mobile != manager['mobile']:
                    if manager['mobile'] == None:
                        instance.mobile = ' '
                    else:
                        instance.mobile = manager['mobile']
                instance.save()
            except Managers_shop.DoesNotExist:
                manager_db.id_manager = manager['contractorId']
                manager_db.name = flname
                if manager['mobile'] == None:
                    manager_db.mobile = ' '
                else:
                    manager_db.mobile = manager['mobile']
                manager_db.save()
            db.connections.close_all()

    def save_midel_order(orders_db, order) -> None:
        """Сохраняем данные заказов"""

        paid = order['sum'] - int(float(order['debt']))

        orders_db.number = order['number']
        orders_db.id_manager = Json_joob.managernumber(Json_joob.manager_name(order['userId']))
        orders_db.data_orders = order['date']
        orders_db.price = Json_joob.split_position(order['sum'])
        orders_db.debt = Json_joob.split_position(int(float(order['debt'])))
        orders_db.paid = Json_joob.split_position(paid)
        orders_db.name_client = order['userName']
        orders_db.phone = Json_joob.mobile_user(order['userId'])
        orders_db.update_date = order['dateUpdated']
        orders_db.manager = Json_joob.manager_name(order['userId'])
        orders_db.save()

    def mobile_user(userid) -> str:
        """Получаем номер телефона"""

        mobile = ''
        try:
            instance = Users_shop.objects.get(id_user=userid)
            if instance.mobile == '':
                mobile = '----------'
            else:
                mobile = instance.mobile
        except:
            instance = Managers_shop.objects.get(id_manager=userid)
            if instance.mobile == '':
                mobile = '----------'
            else:
                mobile = instance.mobile
        return mobile

    def manager_name(userid) -> str:
        """Получаем имя сотрудника"""

        name = ''
        try:
            instance = Managers_shop.objects.get(id_manager=userid)
            name = instance.name
        except:
            name = '----------'
        return name

    def save_model_product(products_db, number, data_order, product) -> None:
        """Сохраняем проверенные данные товаров"""

        products_db.number_order = number
        products_db.number_product = product['id']
        products_db.status = product['status']
        products_db.descriptions = product['description']
        products_db.brand = product['brand']
        products_db.article = product['numberFix']
        products_db.quantity = product['quantity']
        products_db.price_product = Json_joob.split_position(int(float(product['priceInSiteCurrency'])))
        products_db.date_deadline = Json_joob.time_add(
            data_order,
            product['deadline'])
        products_db.distributor = product['distributorName']
        if product['distributorOrderId'] == None:
            products_db.order_distributer = ' '
        else:
            products_db.order_distributer = product['distributorOrderId']
        products_db.comment = product['comment']
        products_db.save()

    def time_add(date_order, add_hour) -> str:
        """Дата поставки"""

        date_object = datetime.datetime.strptime(
            date_order, '%Y-%m-%d %H:%M:%S')
        duration_minutes = datetime.timedelta(hours=int(add_hour))
        result = date_object + duration_minutes
        return result

    def split_position(price) -> int:
        """Сплит цены по разрядам"""

        z = '{0:,}'.format(int(float(price))).replace(',', ' ')
        return z

    def dashinsert(str) -> str:
        """Сплит номера заказа"""

        midPoint = len(str)//2
        return str[:midPoint] + '-' + str[midPoint:]

    def managernumber(manager) -> str:
        number_id = 0
        if manager == 'Валентин Панаетидис':
            number_id = 1
        if manager == 'Василий Панаетидис':
            number_id = 2
        if manager == 'Максим Паненко':
            number_id = 3
        if manager == 'Роман Оробейко':
            number_id = 4
        if manager == 'Дмитрий Маслов':
            number_id = 5
        if manager == 'Сергей Параскевопуло':
            number_id = 6
        if manager == 'Станислав Ефремов':
            number_id = 7

        return number_id


#Лабораторная 3
Print('Это функция,которая получает список nums  длины n в котором находятся числа nums[I] в диапазоне [1, n], и возвращает список чисел в диапазоне [1, n], которых нет в списке nums.')
def find_missing_nums(nums):
    r = len(nums)
    s = []
    y = False
    for i in range (1,r+1):
        for j in range (0,r):
            if i == nums[j]:
                y = True
                continue
        if not y:
            s.append(i)
        y = False
    return s
#Вывод функции


import random

def gen_numbers():
    answer = []
    while len(answer) <3:
        b = random.randint(1,10)
        if b not in answer:
            yield b
            answer.append(b)

for i in gen_numbers():
    print(i)


from rest_framework.serializers import ModelSerializer, SlugRelatedField

from api.models.model_year import ModelYear
from api.models.organization_ldv_sales import OrganizationLDVSales

class OrganizationLDVSalesSerializer(ModelSerializer):
    """
    Serializer for saving/editing the Supplier
    Loads most of the fields and the balance for the Supplier
    """
    model_year = SlugRelatedField(
        slug_field='name',
        queryset=ModelYear.objects.all()
    )

    def save(self):
        request = self.context.get('request')
        organization = self.context.get('organization')
        model_year = self.validated_data.get('model_year')
        ldv_sales = self.validated_data.get('ldv_sales')

        organization_ldv_sale = OrganizationLDVSales.objects.update_or_create(
            model_year_id=model_year.id,
            organization_id=organization.id,
            defaults={
                'ldv_sales': ldv_sales,
                'create_user': request.user.username,
                'update_user': request.user.username
            }
        )

        return organization_ldv_sale

    class Meta:
        model = OrganizationLDVSales
        fields = (
            'id', 'ldv_sales', 'model_year'
        )


def get_shape_with_label(pres, label, slide_num=None):
    """Select the shape with a particular label from a presentation object.

    Keyword Arguments:
      pres -- pptx Pres object containing the target shape
      slide_num -- (Optional) Slide number containing the target shape (if known)
      label -- The unique label of the target shape
    """
    if slide_num is None:
        target_shape = [
            shape
            for slide in pres.slides
            for shape in slide.shapes
            if shape.name == label
        ]
    else:
        slide_num = int(slide_num)
        slide = pres.slides[slide_num - 1]
        target_shape = [shape for shape in slide.shapes if shape.name == label]

    if len(target_shape) == 0:
        raise Exception("No object with the specified label was found.")
    elif len(target_shape) > 1:
        raise Exception("More than one shape with that label was found.")

    return target_shape[0]


#!/usr/bin/env python3
def main():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    m = 3005
    mod = 998244353

    dp = [[0]*m for _ in range(n)]

    for j in range(A[0], B[0]+1):
        dp[0][j] += 1

    for i in range(n):
        for j in range(A[i], B[i]+1):
            if i > 0:
                dp[i][j] = dp[i-1][j]

        for j in range(m-1):
            dp[i][j+1] += dp[i][j]
            dp[i][j+1] %= mod

    return dp[n-1][B[n-1]]

print(main())


#Convert an integer to its english representation
#Link: http://www.codewars.com/kata/53c94a82689f84c2dd00007d

import re
units =["one","two","three","four","five","six","seven","eight","nine"]
teens = ["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen",
         "seventeen", "eighteen","nineteen"]
tens = ["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety","hundred"]
threes=["","thousand","million","billion","trillion","quadrillion","quintillion",
        "sextillion","septillion"]

#convert a power of three into its word representation by looking up in the threes list
def threePowerToString(power):
    index = power/3
    threePowerString=threes[index]
    return threePowerString

#convert a unit into its word representation by looking up in the units list
def unitToString(unit):
    string = ""
    if unit!=0:
        string=units[unit-1]
    return  " "+string

#convert a ten into its word representation, by looking in the teens list, tens list and units list depending
#upon input
def tenToString(ten,unit):
    string=""
    if ten==0:
        string=unitToString(unit)
    elif ten==1:
        string=teens[unit]
    else:
        string=tens[ten-2]
        unitString=unitToString(unit)
        string+=unitString
    return " "+string

#convert a hundred into its word representation by looking in the appropriate list
def hundredToString(hundred, ten, unit):
    string =""
    if hundred!=0:
        string =unitToString(hundred)+" hundred"
    tenString=tenToString(ten,unit)
    string+=tenString
    return " " + string

#called recursively decrementing the power to the next factor of 3 on each pass
def int_to_english_helper(returnString, numberString, power):
    unit=""
    ten=""
    hundred=""
    threePow=""
    decrement=0
    if power%3==0:
        decrement=1
        returnString+=unitToString(int(numberString[:1]))
    elif power%3==1:
        decrement=2
        returnString+=tenToString(int(numberString[:1]),int(numberString[1:2]))
    else:
        returnString+=hundredToString(int(numberString[:1]),int(numberString[1:2]),int(numberString[2:3]))
        decrement=3

    if power<3:
        return returnString
    else:
        returnString+=" "+threePowerToString(power)
        return int_to_english_helper(returnString, numberString[decrement:],power-decrement)

#entry point to the program if the number is zero simpy return it else proceed to int_to_english_helper
#providing the current power of ten of the number the returnString to append to and the string representation
#of the input number
def int_to_english(n):
    if n==0:
        return "zero"
    else:
        returnString=""
        numberString=str(n)
        numberLength = len(str(n))
        power=numberLength-1
        returnString = int_to_english_helper(returnString, numberString, power)
        return re.sub(' +',' ', returnString.strip())

#Test Cases:
Test.expect(int_to_english(15) == 'fifteen', "'fifteen' expected")
Test.expect(int_to_english(47) == 'forty seven' or int_to_english(47) == 'forty-seven', "'forty seven' or 'forty-seven' expected")
Test.expect(int_to_english(536) == 'five hundred thirty six' or int_to_english(536) == 'five hundred and thirty-six', "'five hundred thirty six' or 'five hundred and thirty-six' expected")
Test.expect(int_to_english(12356) == 'twelve thousand three hundred fifty six' or int_to_english(12356) == 'twelve thousand three hundred and fifty-six', "'twelve thousand three hundred fifty six' or 'twelve thousand three hundred and fifty-six' expected")


def extractNeoTranslations(item):
	"""
	# Neo Translations

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or 'preview' in item['title'].lower():
		return None
	if 'The Man Picked up by the Gods'.lower() in item['title'].lower():
		return buildReleaseMessageWithType(item, 'The Man Picked up by the Gods', vol, chp, frag=frag, postfix=postfix)
	if 'I came back but the world is still a fantasy' in item['tags']:
		return buildReleaseMessageWithType(item, 'Kaettekite mo Fantasy!?', vol, chp, frag=frag, postfix=postfix)
	if 'I came back but the world is still a fantasy' in item['title']:
		return buildReleaseMessageWithType(item, 'Kaettekite mo Fantasy!?', vol, chp, frag=frag, postfix=postfix)
	if 'Ashes and Kingdoms' in item['tags']:
		return buildReleaseMessageWithType(item, 'Ashes and Kingdoms', vol, chp, frag=frag, postfix=postfix)
	if 'Goblin Kingdom' in item['tags']:
		return buildReleaseMessageWithType(item, 'Goblin no Oukoku', vol, chp, frag=frag, postfix=postfix)
	return False


    # The program sums three given integers.
    # However, if two values are equals, the sum will be zero.

def sum(x, y, z):
    if x == y or y == z or x == z:
        sum = 0
    else:
        sum = x + y + z

    return sum

print("The sum of 2, 1 and 2 is:", sum(2, 1, 2))
print("The sum of 1, 2 and 6 is", sum(1, 2, 6))


class Solution(object):
    def updateMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        import sys
        if not matrix or not matrix[0]:
            return matrix
        m, n = len(matrix), len(matrix[0])
        dp = [[sys.maxint for _ in range(n)] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 1:
                    dp[i][j] = min(dp[i-1][j] if i >= 1 else sys.maxint, dp[i][j-1] if j >= 1 else sys.maxint) + 1
                else:
                    dp[i][j] = 0
        for i in range(m-1, -1, -1):
            for j in range(n-1, -1, -1):
                if matrix[i][j] == 1:
                    tmp = min(dp[i+1][j] if i < m-1 else sys.maxint, dp[i][j+1] if j < n-1 else sys.maxint) + 1
                    dp[i][j] = min(tmp, dp[i][j])
                else:
                    dp[i][j] = 0
        return dp


# Używanie funkcji partial() do przekazywania dodatkowych argumentów do wywołania zwrotnego

def output_result(result, log=None):
    if log is not None:
        log.debug('Pobrano: %r', result)

# Przykładowa funkcja
def add(x, y):
    return x + y

if __name__ == '__main__':
    import logging
    from multiprocessing import Pool
    from functools import partial

    logging.basicConfig(level=logging.DEBUG)
    log = logging.getLogger('test')

    p = Pool()
    p.apply_async(add, (3, 4), callback=partial(output_result, log=log))
    p.close()
    p.join()


from tkinter import *
from PIL import Image, ImageTk

from GUI.ScrollableFrame import ScrollableFrame

class FrameListCell(Frame):
    def click_slot(self, e):
        self.object.click_action()

    def __init__(self, parent, obj, width=200, height=200):
        Frame.__init__(self, parent, bg="white", width=width, height=height)
        self.object = obj

        img = obj.image.resize((int(height*0.75), int(height*0.75)), Image.ANTIALIAS)
        self.image = ImageTk.PhotoImage(img)
        self.img_label = Label(self, image=self.image, bg='white', borderwidth=5)
        self.img_label.grid(row=0, column=0)
        col_number = 1

        for col in obj.text_columns:
            text_column = Label(self, width=30,  text=col, fg='black', bg='white', font=('Microsoft YaHei UI Light', 12, 'bold'))
            text_column.grid(row=0, column=col_number, sticky="w")
            col_number = col_number + 1
            text_column.bind("<Button-1>", self.click_slot)

        self.bind("<Button-1>", self.click_slot)
        self.img_label.bind("<Button-1>", self.click_slot)

class ListManager(Frame):
    def __init__(self, parent, row_width, height, width, objects):
        Frame.__init__(self, parent, bg="white", width=width, height=height)
        self.scrollable_frame = ScrollableFrame(self, height=height)
        for obj in objects:
            FrameListCell(
                self.scrollable_frame.scrollable_frame, height=row_width, width=width, obj=obj
            ).pack()
        self.scrollable_frame.pack(fill=BOTH)


"""This file contains tests for functions in stacking.utils"""
import os
import unittest

from stacking.errors import StackingError
from stacking.readers.dr16_reader import defaults as defaults_dr16_reader
from stacking.readers.dr16_reader import accepted_options as accepted_options_dr16_reader
from stacking.readers.dr16_reader import required_options as required_options_dr16_reader
from stacking.rebin import defaults as defaults_rebin
from stacking.rebin import accepted_options as accepted_options_rebin
from stacking.rebin import required_options as required_options_rebin
from stacking.tests.abstract_test import AbstractTest
from stacking.utils import (attribute_from_string, class_from_string,
                            update_accepted_options, update_default_options,
                            update_required_options)

THIS_DIR = os.path.dirname(os.path.abspath(__file__))

class UtilsTest(AbstractTest):
    """Test the functions in stacking.utils

    Methods
    -------
    (see AbstractTest in stacking/tests/abstract_test.py)
    test_attribute_from_string
    test_class_from_string
    test_update_accepted_options
    test_update_default_options
    test_update_required_options
    """

    def test_attribute_from_string(self):
        """Test function attribute_from_string"""
        # case: missing module
        expected_message = "No module named 'invalid_module'"
        with self.assertRaises(ImportError) as context_manager:
            attribute_from_string("invalid_atribute", "invalid_module")
        self.compare_error_message(context_manager, expected_message)

        # case: missing attribute
        expected_message = (
            "module 'stacking.tests.utils' has no attribute 'invalid_atribute'")
        with self.assertRaises(AttributeError) as context_manager:
            attribute_from_string("invalid_atribute", "stacking.tests.utils")
        self.compare_error_message(context_manager, expected_message)

        # case: correct execution
        this_dir = attribute_from_string("THIS_DIR", "stacking.tests.utils")
        self.assertEqual(this_dir, THIS_DIR)

    def test_class_from_string(self):
        """Test function class_from_string"""
        # case: missing module
        expected_message = "No module named 'stacking.invalid_module'"
        with self.assertRaises(ImportError) as context_manager:
            class_from_string("InvalidClass", "invalid_module")
        self.compare_error_message(context_manager, expected_message)

        # case: missing class
        expected_message = (
            "module 'stacking.tests.utils' has no attribute 'Utils'")
        with self.assertRaises(AttributeError) as context_manager:
            class_from_string("Utils", "tests")
        self.compare_error_message(context_manager, expected_message)

        # case: correct execution - load AbstractTest
        class_object, default_args, accepted_options, required_options = class_from_string(
            "AbstractTest", "tests")
        self.assertTrue(isinstance(class_object, type))
        self.assertTrue(default_args == {})
        self.assertTrue(accepted_options == [])
        self.assertTrue(required_options == [])

        # case: correct execution - load Dr16Reader
        class_object, default_args, accepted_options, required_options = class_from_string(
            "Dr16Reader", "readers")
        self.assertTrue(isinstance(class_object, type))
        self.assertTrue(default_args == defaults_dr16_reader)
        self.assertTrue(accepted_options == accepted_options_dr16_reader)
        self.assertTrue(required_options == required_options_dr16_reader)

        # case: correct execution - load Rebin
        class_object, default_args, accepted_options, required_options = class_from_string(
            "Rebin", ".")
        self.assertTrue(isinstance(class_object, type))
        self.assertTrue(default_args == defaults_rebin)
        self.assertTrue(accepted_options == accepted_options_rebin)
        self.assertTrue(required_options == required_options_rebin)

    def test_update_accepted_options(self):
        """Test function update_accepted_options"""

        accepted_options = ["1", "2", "3"]

        cases = [
            # (new_options, expected_result, remove?)
            (["1"], ["2", "3"], True),
            (["3"], ["1", "2"], True),
            (["2"], ["1", "3"], True),
            (["1", "2"], ["3"], True),
            (["2"], ["1", "2", "3"], False),
            (["0"], ["0", "1", "2", "3"], False),
        ]

        for new_options, expected_result, remove in cases:
            new_accepted_options = update_accepted_options(accepted_options,
                                                           new_options,
                                                           remove=remove)
            self.assertTrue(len(new_accepted_options) == len(expected_result))
            self.assertTrue(new_accepted_options == expected_result)

    def test_update_default_options(self):
        """Test function update_default_options"""

        default_options = {"1": 1, "2": 2, "3": 3}

        cases = [
            # (new_options, expected_result, force_overwrite?, expected_message)
            ({
                "1": "0"
            }, {}, False, "Incompatible defaults are being added. Key 1 "
             "found to have values with different type: <class 'int'> and "
             "<class 'str'>. Revise your recent changes or contact stacking "
             "developpers."),
            ({
                "1": 0
            }, {}, False, "Incompatible defaults are being added. Key 1 "
             "found to have two default values: '0' and '1' "
             "Please revise your recent changes. If you really want to "
             "overwrite the default values of a parent class, then pass "
             "`force_overload=True`. If you are unsure what this message "
             "means contact stacking developpers."),
            ({
                "1": 0
            }, {
                "1": 0,
                "2": 2,
                "3": 3
            }, True, None),
            ({
                "0": 0
            }, {
                "0": 0,
                "1": 1,
                "2": 2,
                "3": 3
            }, False, None),
        ]

        for new_options, expected_result, force_overwrite, expected_message in cases:
            if expected_message is None:
                new_default_options = update_default_options(
                    default_options,
                    new_options,
                    force_overwrite=force_overwrite)
                self.assertTrue(
                    len(new_default_options) == len(expected_result))
                for key, value in expected_result.items():
                    self.assertTrue(key in new_default_options)
                    self.assertTrue(new_default_options[key] == value)
            else:
                with self.assertRaises(StackingError) as context_manager:
                    update_default_options(default_options,
                                           new_options,
                                           force_overwrite=force_overwrite)
                self.compare_error_message(context_manager, expected_message)

    def test_update_required_options(self):
        """Test function updaterequired_options"""

        required_options = ["1", "2", "3"]

        cases = [
            # (new_options, expected_result)
            (["2"], ["1", "2", "3"]),
            (["0"], ["0", "1", "2", "3"]),
        ]

        for new_options, expected_result in cases:
            new_accepted_options = update_required_options(
                required_options, new_options)
            self.assertTrue(len(new_accepted_options) == len(expected_result))
            self.assertTrue(new_accepted_options == expected_result)

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


from crud import *

def menu():
    print("="*20)
    print("""    SISTEMA CRUD
    [1] - CREATE
    [2] - READ
    [3] - UPDATE
    [4] - DELETE
    [5] - QUIT """)
    print("="*20)

def main():
    while True:
        menu()
        choice = str(input("Type menu option: "))

        if choice not in '12345':
            print("\nInvalid Option. See Menu\n")
            continue

        if choice == '1':
            create()
        elif choice == '2':
            read()
        elif choice == '3':
            update()
        elif choice == '4':
            delete()
        elif choice == '5':
            break

main()


from __future__ import absolute_import
import functools
import operator

import gast

from tangent import annotations as anno
from tangent import ast as ast_
from tangent import grammar
from tangent import utils

class Node(object):
  """A node in the CFG."""
  __slots__ = ['next', 'value', 'prev']

  def __init__(self, value):
    self.next = set()
    self.prev = set()
    self.value = value

class CFG(gast.NodeVisitor):
  """Construct a control flow graph.

  Each statement is represented as a node. For control flow statements such
  as conditionals and loops the conditional itself is a node which either
  branches or cycles, respectively.

  Attributes:
    entry: The entry node, which contains the `gast.arguments` node of the
        function definition.
    exit: The exit node. This node is special because it has no value (i.e. no
        corresponding AST node). This is because Python functions can have
        multiple return statements.
  """

  def __init__(self):
    # The current leaves of the CFG
    self.head = []
    # A stack of continue statements
    self.continue_ = []
    # A stack of break nodes
    self.break_ = []

  @staticmethod
  def backlink(node):
    """Given a CFG with outgoing links, create incoming links."""
    seen = set()
    to_see = [node]
    while to_see:
      node = to_see.pop()
      seen.add(node)
      for succ in node.next:
        succ.prev.add(node)
        if succ not in seen:
          to_see.append(succ)

  def set_head(self, node):
    """Link this node to the current leaves."""
    for head in self.head:
      head.next.add(node)
    self.head[:] = []
    self.head.append(node)

  @classmethod
  def build_cfg(cls, node):
    """Build a CFG for a function.

    Args:
      node: A function definition the body of which to analyze.

    Returns:
      A CFG object.

    Raises:
      TypeError: If the input is not a function definition.
    """
    if not isinstance(node, gast.FunctionDef):
      raise TypeError('input must be a function definition')
    cfg = cls()
    cfg.entry = Node(node.args)
    cfg.head = [cfg.entry]
    cfg.visit_statements(node.body)
    cfg.exit = Node(None)
    cfg.set_head(cfg.exit)
    cfg.backlink(cfg.entry)
    return cfg

  def visit_statements(self, nodes):
    for node in nodes:
      if isinstance(node, grammar.CONTROL_FLOW):
        self.visit(node)
      else:
        expr = Node(node)
        self.set_head(expr)

  def generic_visit(self, node):
    raise ValueError('unknown control flow')

  def visit_If(self, node):
    # The current head will hold the conditional
    test = Node(node.test)
    self.set_head(test)
    # Handle the body
    self.visit_statements(node.body)
    body_exit = self.head[:]
    self.head[:] = []
    self.head.append(test)
    # Handle the orelse
    self.visit_statements(node.orelse)
    self.head.extend(body_exit)

  def visit_While(self, node):
    test = Node(node.test)
    self.set_head(test)
    # Start a new level of nesting
    self.break_.append([])
    self.continue_.append([])
    # Handle the body
    self.visit_statements(node.body)
    self.head.extend(self.continue_.pop())
    self.set_head(test)
    # Handle the orelse
    self.visit_statements(node.orelse)
    # The break statements and the test go to the next node
    self.head.extend(self.break_.pop())

  def visit_For(self, node):
    iter_ = Node(node)
    self.set_head(iter_)
    self.break_.append([])
    self.continue_.append([])
    self.visit_statements(node.body)
    self.head.extend(self.continue_.pop())
    self.set_head(iter_)
    self.head.extend(self.break_.pop())

  def visit_Break(self, node):
    self.break_[-1].extend(self.head)
    self.head[:] = []

  def visit_Continue(self, node):
    self.continue_[-1].extend(self.head)
    self.head[:] = []

  def visit_Try(self, node):
    self.visit_statements(node.body)
    body = self.head
    handlers = []
    for handler in node.handlers:
      self.head = body[:]
      self.visit_statements(handler.body)
      handlers.extend(self.head)
    self.head = body
    self.visit_statements(node.orelse)
    self.head = handlers + self.head
    self.visit_statements(node.finalbody)

class Forward(object):
  """Forward analysis on CFG.

  Args:
    label: A name for this analysis e.g. 'active' for activity analysis. The
        AST nodes in the CFG will be given annotations 'name_in', 'name_out',
        'name_gen' and 'name_kill' which contain the incoming values, outgoing
        values, values generated by the statement, and values deleted by the
        statement respectively.
    gen: A function which takes the CFG node as well as a set of incoming
        values. It must return a set of newly generated values by the statement
        as well as a set of deleted (killed) values.
    op: Either the AND or OR operator. If the AND operator is used it turns
        into forward must analysis (i.e. a value will only be carried forward
        if it appears on all incoming paths). The OR operator means that
        forward may analysis is done (i.e. the union of incoming values will be
        taken).
  """

  def __init__(self, label, gen, op=operator.or_):
    self.gen = gen
    self.op = op
    self.out_label = label + '_out'
    self.in_label = label + '_in'
    self.gen_label = label + '_gen'
    self.kill_label = label + '_kill'

  def visit(self, node):
    if node.value:
      if anno.hasanno(node.value, self.out_label):
        before = hash(anno.getanno(node.value, self.out_label))
      else:
        before = None
      preds = [anno.getanno(pred.value, self.out_label)
               for pred in node.prev
               if anno.hasanno(pred.value, self.out_label)]
      if preds:
        incoming = functools.reduce(self.op, preds[1:], preds[0])
      else:
        incoming = frozenset()
      anno.setanno(node.value, self.in_label, incoming, safe=False)
      gen, kill = self.gen(node, incoming)
      anno.setanno(node.value, self.gen_label, gen, safe=False)
      anno.setanno(node.value, self.kill_label, kill, safe=False)
      anno.setanno(node.value, self.out_label, (incoming - kill) | gen,
                   safe=False)
      if hash(anno.getanno(node.value, self.out_label)) != before:
        for succ in node.next:
          self.visit(succ)
    else:
      preds = [anno.getanno(pred.value, self.out_label)
               for pred in node.prev]
      self.exit = functools.reduce(self.op, preds[1:], preds[0])

def forward(node, analysis):
  """Perform a given analysis on all functions within an AST."""
  if not isinstance(analysis, Forward):
    raise TypeError('not a valid forward analysis object')
  for succ in gast.walk(node):
    if isinstance(succ, gast.FunctionDef):
      cfg_obj = CFG.build_cfg(succ)
      analysis.visit(cfg_obj.entry)
  return node

class ReachingDefinitions(Forward):
  """Perform reaching definition analysis.

  Each statement is annotated with a set of (variable, definition) pairs.

  """

  def __init__(self):
    def definition(node, incoming):
      definitions = ast_.get_updated(node.value)
      gen = frozenset((id_, node.value) for id_ in definitions)
      kill = frozenset(def_ for def_ in incoming
                       if def_[0] in definitions)
      return gen, kill
    super(ReachingDefinitions, self).__init__('definitions', definition)

class Defined(Forward):
  """Perform defined variable analysis.

  Each statement is annotated with a set of variables which are guaranteed to
  be defined at that point.
  """

  def __init__(self):
    def defined(node, incoming):
      gen = ast_.get_updated(node.value)
      return gen, frozenset()
    super(Defined, self).__init__('defined', defined, operator.and_)

class Active(Forward):
  """Active variable analysis.

  Given a set of active arguments, find all variables that are active i.e.
  variables whose values possibly depend on the given set of arguments.

  Args:
    wrt: A tuple of indices of arguments that are active.
  """

  def __init__(self, wrt):
    def active(node, incoming):
      gen = set()
      kill = set()
      if isinstance(node.value, gast.arguments):
        gen.update(node.value.args[i].id for i in wrt)
      if isinstance(node.value, gast.Assign):
        # Special-case e.g. x = tangent.pop(_stack)
        # such that all values popped off the stack are live.
        if anno.getanno(node.value.value, 'func', False) == utils.pop:
          gen.update(ast_.get_updated(node.value))
        else:
          for succ in gast.walk(node.value.value):
            if isinstance(succ, gast.Name) and succ.id in incoming:
              gen.update(ast_.get_updated(node.value))
              break
          else:
            kill.update(ast_.get_updated(node.value))
      return gen, kill
    super(Active, self).__init__('active', active)


import logging

class Logger:
    __LOGGING_FORMAT = '%(asctime)s %(levelname)-8s %(message)s'
    __DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
    __ENCODING = 'utf-8'

    def __init__(self, log_filename: str):
        logging.basicConfig(
            filename=log_filename,
            encoding=self.__ENCODING,
            level=logging.INFO,
            format=self.__LOGGING_FORMAT,
            datefmt=self.__DATE_FORMAT
        )
        logging.getLogger('deepl').disabled = True

    @staticmethod
    def warn(message: str):
        logging.warning(message)

    @staticmethod
    def info(message: str):
        logging.info(message)