import argparse
from logging import Logger, getLogger
from pathlib import Path
import tempfile
from typing import List

from cp_problem_maker.problem import Problem
from cp_problem_maker.config import Config
from cp_problem_maker.compile import compile_solution, compile_checker
from cp_problem_maker.testcase import TestCase
from cp_problem_maker.judge import assert_judge_status,  JudgeStatus, judge

logger: Logger = getLogger(__name__)

def add_parser(subparsers):
    parser_check: argparse.ArgumentParser = subparsers.add_parser(
        "check", description="check solutions")
    parser_check.add_argument(
        "-p", "--path",
        type=str,
        default="."
    )
    parser_check.add_argument(
        "-s", "--solutions",
        type=str,
        nargs="*"
    )

def run(path: Path, solutions: List[str]):
    problem = Problem(path)
    config = Config(problem.config_file)

    compile_checker(problem.checker_file)

    if not solutions:
        solutions = list(
            solution_config.name for solution_config in config.solution_config.values())

    for solution in solutions:
        if solution not in config.solution_config:
            logger.error(
                f'Configuration about the solution "{solution}" is missing. skipped.'
            )
            continue
        logger.info(f'started checking the solution "{solution}"')

        solution_config = config.solution_config[solution]

        name = solution_config.name
        solution_file = problem.solutions_folder / name
        compile_solution(solution_file)

        detect_tle = False
        detect_wa = False

        for testcase_config in config.testcase_config.values():
            name = testcase_config.name
            number = testcase_config.number
            for case_no in range(number):
                generator_file = problem.gen_folder / Path(name)
                testcase = TestCase(generator_file, case_no)
                input_file = problem.in_folder / testcase.input_file_name
                output_file_expected = problem.out_folder / testcase.output_file_name

                with tempfile.NamedTemporaryFile(mode='w') as output_file_actual_wrapper:
                    output_file_actual = Path(output_file_actual_wrapper.name)
                    logger.info("checking solution...")
                    result = judge(
                        input_file=input_file,
                        output_file=output_file_actual,
                        solution_file=solution_file,
                        checker_file=problem.checker_file,
                        output_file_expected=output_file_expected,
                        config=config,
                        parents=True,
                        exist_ok=True
                    )
                    logger.info(f"  result  : {result.status}")
                    logger.info(f"  time    : {result.elapsed_ms} ms")
                    assert_judge_status(result.status, solution_config)

                    detect_tle |= result.status == JudgeStatus.TLE
                    detect_wa |= result.status == JudgeStatus.WA

        if solution_config.allow_tle and not detect_tle:
            logger.warning(
                f'"allow_tle" flag is set to the solution "{solution_config.name}", but there is no TLE cases.'
            )
        if solution_config.wrong and not detect_wa:
            logger.error(
                f'"wrong" flag is set to the solution "{solution_config.name}", but there is no WA cases.'
            )


import sys

last = 0

def randomNumber(max):
    global last
    last = (25214903917 * last + 11) % 281474976710656
    if last >= 0:
        tmp = last
    else:
        tmp = -last
    return tmp % max

def createArray(len, maxValue):
    return [randomNumber(maxValue) for x in range(len)]

def main():
    tabSize = 10000000
    maxValue = 5000000
    noOutput = False
    debug = False

    for arg in sys.argv:
        if arg == "--nooutput":
            noOutput = True
        elif arg.startswith("--nbop="):
            n = int(arg[7:])
            if n > 0:
                tabSize = n
        elif arg == "--debug":
            debug = True

    if debug:
        print("lang=python;tabSize=%d;maxValue=%d;noOutput=%d;debug=%d" %
              (tabSize, maxValue, noOutput, debug))

    tab = createArray(tabSize, maxValue)

    tab.sort()

    if not noOutput:
        print("array:"+str(tab[:10]))

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('problempost', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='problempost',
            name='councilMem',
            field=models.CharField(max_length=30, default=''),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='problempost',
            name='status',
            field=models.CharField(max_length=10, default=''),
            preserve_default=True,
        ),
    ]


# -*- coding: utf-8 -*-
from pathlib import Path
import argparse
import yaml
from preprocessing.database import clean_database, download_database
from preprocessing.preprocessing import preprocess_data
from preprocessing.split import split_data
from cnn.training import train_model
from utils.accuracy import multi_label
from utils.misc import list_to_date, triplet_to_str, read_csv_with_genres, create_logger
from tensorflow.keras.models import load_model
import numpy as np

def main(args):
    config = yaml.safe_load(open(args.config, encoding='utf-8'))
    # Naming files
    nb_genres = len(config['genres'])
    start = list_to_date(config['first_date'])
    end = list_to_date(config['last_date'])
    selection_name = triplet_to_str(config['first_date'])+'_'+triplet_to_str(config['last_date'])+'_'+str(nb_genres)
    appendix_data = triplet_to_str(config['image_size']) + '_' + selection_name
    appendix_split = config['split_method']+'_tr{}t{}_'.format(config['training_size'], config['testing_size'])+appendix_data
    model_name = config['model_name']+'_e{}b{}v{}_'.format(config['nb_epochs'], config['batch_size'], config['validation_split'])
    model_name += appendix_split
    logger = None #create_logger(name=model_name, log_dir=Path(args.log_dir))
    selection_name = args.csv+selection_name+'.csv'
    appendix_data += '.npy'
    model_name = args.models_dir + model_name + '.h5'

    if Path(selection_name).exists():
        if args.verbose:
            print('Database already cleaned')
        selected_movies = read_csv_with_genres(Path(selection_name))
    else:
        selected_movies = clean_database(Path(args.database), config['genres'],
                                         start=start, end=end,
                                         verbose=args.verbose, logger=logger)
        if args.save:
            selected_movies.to_csv(Path(selection_name))
    not_found = download_database(Path(args.posters), selected_movies,
                                  verbose=args.verbose, logger=logger)

    data_name = [Path(prefix+appendix_data) for prefix in [args.preproc+'x_', args.preproc+'y_', args.preproc+'id_']]
    if data_name[0].exists() and data_name[1].exists() and data_name[2].exists():
        if args.verbose:
            print('Data already preprocessed')
        posters, genres, ids = np.load(data_name[0]), np.load(data_name[1]), np.load(data_name[2])
    else:
        posters, genres, ids = preprocess_data(Path(args.posters), selected_movies, config['genres'],
                                               config['image_size'], verbose=args.verbose, logger=logger)
        if args.save:
            np.save(data_name[0], posters)
            np.save(data_name[1], genres)
            np.save(data_name[2], ids)

    data_name = [Path(prefix+appendix_split) for prefix in [args.split+'xtr_', args.split+'ytr_', args.split+'idtr_', args.split+'xtest_', args.split+'ytest_', args.split+'idtest_']]
    if data_name[0].exists() and data_name[1].exists() and data_name[2].exists() and data_name[3].exists() and data_name[4].exists() and data_name[5].exists():
        if args.verbose:
            print('Data already splitted')
        train_posters, train_genres, train_ids, test_posters, test_genres, test_ids = np.load(data_name[0]), np.load(data_name[1]), np.load(data_name[2]), np.load(data_name[3]), np.load(data_name[4]), np.load(data_name[5])
    else:
        train_posters, train_genres, train_ids, test_posters, test_genres, test_ids = split_data(
            selected_movies, posters, genres, ids, config['genres'], config['training_size'], config['testing_size'],
            config['split_method'], verbose=args.verbose, logger=logger)
        if args.save:
            np.save(data_name[0], train_posters)
            np.save(data_name[1], train_genres)
            np.save(data_name[2], train_ids)
            np.save(data_name[3], test_posters)
            np.save(data_name[4], test_genres)
            np.save(data_name[5], test_ids)

    if Path(model_name).exists():
        if args.verbose:
            print('Model already trained')
        model = load_model(str(Path(model_name)))
        training_history = None
    else:
        model, training_history = train_model(
            train_posters, train_genres, nb_genres, config['image_size'],
            nb_epochs=config['nb_epochs'], batch_size=config['batch_size'],
            validation_split=config['validation_split'],
            verbose=args.verbose, logger=logger
        )
        if args.save:
            model.save(str(Path(model_name)))

    predicted_genres = model.predict(test_posters)
    print(multi_label(test_genres, predicted_genres, logger=logger))
    return model, test_posters, test_genres, test_ids, selected_movies, predicted_genres, training_history

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='Path to the config file', default='./default_config.yml')
    parser.add_argument('--log-dir', help='Path to the log directory', default='../log/')
    parser.add_argument('--posters', help='Path to the posters', default='../data/posters/')
    parser.add_argument('--models-dir', help='Path to the saved models', default='../data/models/')
    parser.add_argument('--preproc', help='Path to the preprocessed data', default='../data/preprocessed/')
    parser.add_argument('--split', help='Path to the splitted data', default='../data/splitted/')
    parser.add_argument('--database', help='Path to the databse csv', default='../data/poster_data.csv')
    parser.add_argument('--csv', help='Path to the clean csv', default='../data/')
    parser.add_argument('-s', '--save', help='Save model', action='store_true')
    parser.add_argument('-v', '--verbose', help='Verbose', action='store_true')
    args, _ = parser.parse_known_args()
    main(args)


from docxtpl import DocxTemplate

def work_job_document(number, context, name_file):
    doc = DocxTemplate(f'shablons/shablon{number}.docx')
    doc.render(context)
    path = f'donedocs/Договор №{name_file}.docx'
    doc.save(path)
    return path

def document(number, names, money):
    name_file = f'{number}_{names}'
    context = {
        'full_name': names,
        'money': money
    }
    path = work_job_document(number, context, name_file)
    return path


# 4871 - 그래프 경로
import sys
sys.stdin = open('input.txt')

def DFS(S, G):  # 인접 노드 순회 stack 사용
    stack = [S]     # 시작 노드 지정
    visited = [False] * (V + 1) # 방문자 확인

    while stack:    # 스택이 비어있지 않을 때
        start = stack.pop() # 시작 노드
        if visited[start] == False: # 방문을 하지 않았을 때
            visited[start] = True   # 방문하였다고 표시
            for next in range(1, V + 1):    # next  V 순회
                if graph[start][next] == 1 and visited[next] == 0:
                    # 현재 노드의 next의 graph 값이 1이면서 방문을 안 했을 때
                    if next == G:   # next가 G일 때 시작노드 S에서 G까지 탐색 완료
                        return 1
                    stack.append(next)  # 아닐 때 next 값을 stack에 넣어준다.
    return 0

T = int(input())
for t in range(1, T+1):
    V, E = map(int, input().split())    # V = 노드 수, E = 간선 수
    visited = [0 for _ in range(V + 1)]     # 방문 표시
    graph = [[0 for _ in range(V + 1)] for _ in range(V + 1)]   # 그래프 간선 입력 리스트

    for _ in range(E):  # 간선 수 만큼
        i, j = map(int, input().split())    # 노드와 연결된 노드 입력 받기
        graph[i][j] = 1     # 간선 표시해주기

    S, G = map(int, input().split())    # 시작과 끝 값 입력 받기

    print(f'#{t} {DFS(S, G)}')  # S에서 G로 가는 경로가 존재하는지 확인하기


from .devices import Devices
from .alerts import Alerts
from .traffic import Traffic
from .cti import Cti
from .configuration import Configuration

class EdgeDefenseManager(object):
    """
    Define the fido device
    """

    def __init__(self, *args, **kwargs):
        """
        Positional Arguments:
            host: Hostname or FQDN of the device
            apitoken: API token

        Keyword Arguments:
            api_version: API version (Default: v1)
            raise_on_error: Raise exception on failed Rest calls
                            (Default: False)
        """
        if not args or len(args) < 2:
            raise AttributeError('Missing required positional arguments '
                                 '`host` and/or `apitoken`')
        if not kwargs or 'api_version' not in kwargs.keys():
            raise AttributeError('Missing required keyword argument '
                                 '`api_version`')
        self.host = args[0]
        self.apitoken = args[1]
        self.apiversion = kwargs['api_version']
        self.raise_on_error = kwargs.get('raise_on_error', False)
        self.devices = Devices(*args, **kwargs)
        self.alerts = Alerts(*args, **kwargs)
        self.traffic = Traffic(*args, **kwargs)
        self.cti = Cti(*args, **kwargs)
        self.configuration = Configuration(*args, **kwargs)


from typing import Tuple, cast, List
from web3 import Web3
from src.common.logger import logger
from src.common.clients import (
    makeSwimmerCraClient,
    makeSwimmerNetworkClient,
)
from src.common.dotenv import getenv
from src.common.config import donatePercentage, donateFrequency
from web3.types import TxReceipt, Wei, Nonce
from src.common.constants import eoas
from src.helpers.instantMessage import sendIM
from src.helpers.price import tusToWei, craToWei, weiToCra, weiToTus
import os
from src.libs.CrabadaWeb2Client.types.idleGameTypes import Game

def getClaimsLogFilepath() -> str:
    """
    Return the path of the log file containing the user's
    recent claims

    Each line of the file contains the TUS and CRA rewards
    claimed by the user during the most recent closeGame
    and settleGame transactions.

    The file will be deleted after each donation.
    """
    return os.path.join(getenv("STORAGE_FOLDER", "storage"), "logs/app", "claims.log")

def userWantsToDonate() -> bool:
    """
    Return True if the user agreed to donate to
    the project
    """
    return donatePercentage is not None and donatePercentage > 0.01

def shouldDonate(claims: List[List[float]], donateFrequency: int) -> bool:
    """
    Return True if it is time to donate.

    The principle is simple: we donate only if the user
    claimed X times since his/her last donation, where
    X is given by the 'donateFrequency' parameter.
    """
    return (
        userWantsToDonate() and len(claims) > 0 and len(claims) % donateFrequency == 0
    )

def maybeDonate(game: Game, isMining: bool = True) -> Tuple[TxReceipt, TxReceipt]:
    """
    If the user expressed the desire to donate to the
    project, do so.

    In order to save gas, we donate only once every X times,
    where X is given by the parameter 'donateFrequency'.

    Returns the TUS and CRA transactions as a tuple, or
    (None, None) if donation has not taken place.

    """
    if not userWantsToDonate():
        logger.warning(getDonateMessage())
        sendIM(getDonateMessage())
        return (None, None)

    # Make sure the folder with the claim logs exists
    path = getClaimsLogFilepath()
    os.makedirs(os.path.dirname(path), exist_ok=True)

    # Log the rewards that the user just claimed
    tusRewardInWei = (
        game.get("miner_tus_reward", Wei(0))
        if isMining
        else game.get("looter_tus_reward", Wei(0))
    )
    craRewardInWei = (
        game.get("miner_cra_reward", Wei(0))
        if isMining
        else game.get("looter_cra_reward", Wei(0))
    )
    logClaim((weiToTus(tusRewardInWei), weiToCra(craRewardInWei)))

    # Determine whether it is time to donate
    claims = getClaimsFromLog()
    if not shouldDonate(claims, donateFrequency):
        return (None, None)

    # The donation shall consider only the most recent claims
    recentClaims = claims[-donateFrequency:]

    # Reset the counter, for good measure
    deleteClaimsLog()

    # Donate
    return donate(recentClaims, donatePercentage)

def donate(
    recentClaims: List[List[float]], percentage: float
) -> Tuple[TxReceipt, TxReceipt]:
    """
    Donate a percentage of the TUS and CRA rewards from the
    given claims.

    Return a tuple with the transaction receipts.
    """

    # Make sure the % is within bounds
    percentage = max(0, min(100, percentage))
    if not percentage:
        return (None, None)

    # How much should we donate?
    (tusDonation, craDonation) = getDonationAmounts(recentClaims, percentage)

    # Initialize nonce and receipts
    client = makeSwimmerNetworkClient()
    nonce = client.getNonce()
    tusReceipt, craReceipt = None, None

    # Donate TUS
    if tusDonation:
        try:
            txTus = client.sendEthInWei(eoas["project"], tusDonation, nonce)
            tusReceipt = client.getTransactionReceipt(txTus)
            if tusReceipt["status"] != 1:
                logger.error(
                    f"Error from TUS donation [tx={txTus}, status={tusReceipt['status']}"
                )
            nonce = cast(Nonce, nonce + 1)
        except Exception as e:
            logger.error(f"Could not send TUS donation > {e}")

    # Donate CRA
    if craDonation:
        try:
            craClient = makeSwimmerCraClient()
            txCra = craClient.transfer(eoas["project"], craDonation, nonce)
            craReceipt = craClient.getTransactionReceipt(txCra)
            if craReceipt["status"] != 1:
                logger.error(
                    f"Error from CRA donation [tx={txCra}, status={craReceipt['status']}"
                )
        except Exception as e:
            logger.error(f"Could not send CRA donation > {e}")

    return (tusReceipt, craReceipt)

def getDonationAmounts(claims: List[List[float]], percentage: float) -> Tuple[Wei, Wei]:
    """
    Given the list of reward claims by the user, return the amount
    to be donated in Wei, based on the donation percentage chosen
    by the user
    """
    if percentage > 100:
        raise Exception(f"Donation is higher than rewards [percentage={percentage}]")

    tusTotalRewards = sum([line[0] for line in claims])
    craTotalRewards = sum([line[1] for line in claims])

    tusDonation = percentage * tusTotalRewards / 100
    craDonation = percentage * craTotalRewards / 100

    return (tusToWei(tusDonation), craToWei(craDonation))

def logClaim(rewards: Tuple[float, float]) -> None:
    """
    Append a line to the claims file
    """
    with open(getClaimsLogFilepath(), mode="a+", encoding="utf-8") as file:
        file.write("%10.5f %10.5f\n" % rewards)

def getClaimsFromLog() -> List[List[float]]:
    """
    Fetch all the reward claims in the file log
    """
    try:
        with open(getClaimsLogFilepath(), mode="r", encoding="utf-8") as file:
            return [[float(x) for x in line.split()] for line in file]
    except FileNotFoundError:
        return []

def deleteClaimsLog() -> None:
    """
    Delete the claims file
    """
    try:
        os.remove(getClaimsLogFilepath())
    except FileNotFoundError:
        pass

def getDonateMessage() -> str:
    return """
🦀  🦀  🦀

Building Crabada.py requires time and passion.
Please consider expressing your gratitude
by donating a small % of your rewards :-)

To donate, write DONATE_PERCENTAGE=5%
in your .env file; this message will
disappear regardless of the amount that
you donate 🙂

Thank you!

🙏  ❤  🙏
"""


import common.day as day
from common.hash_knot import knot, knot_bytes
from common.string import cat, hex_byte

def main():
    data = day.read_input(10)

    day.solve_day(
        data,
        (solve1, 1935),
        (solve2, 'dc7e7dee710d4c7201ce42713e6b8359'),
    )

def solve1(incoming):
    data = day.process_list(
        incoming.split(','),
        modify=int,
    )

    [first, second, *_] = knot(data)

    return first * second

def solve2(incoming):
    hexed = map(hex_byte, knot_bytes(list(incoming)))

    return cat(hexed)

if __name__ == "__main__":
    main()


import errno
from pathlib import Path

import requests

ENCODING = "UTF-8"

def sanitize_ident(ident: str):
    """Naive ident sanitizer"""

    for illegal in r'/\|!?[]<>.,:;"*':
        ident = ident.replace(illegal, "_")

    return ident

def download(url: str, path: Path):
    """Downloads a file over http(s), returns (err, path)."""

    path = Path(path).resolve()
    if path.is_dir():
        path = path / url.split("/")[-1]
    if not (path.parent.is_dir() and path.parent.exists()):
        return errno.EINVAL, path

    with requests.get(url, stream=True) as request:
        request.raise_for_status()
        with path.open("wb") as local:
            for chunk in request.iter_content(chunk_size=8192):
                local.write(chunk)

    return 0, path


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 18:05:45 2018

@author: laureano
"""

name = 'Victor Laureano Macieira Ferreira'

#print(name)
#print(name[0])
def formal(name):
    name = name.split()
    last_name = name[len(name)-1]
#    print(last_name[0])
    result =str(last_name)+", "
    teste = result
    for l in name:
#        print(l[0]+".")
        if l.istitle():
            lista_tit = l[0]
            if lista_tit == last_name[0]:
                continue
            else:
                teste +=lista_tit+". "
    return teste

treino = formal(name)
print(treino)
#
#


from argparse import ArgumentParser

from typings import SubparserCommand

subparser_commands: dict[str, SubparserCommand] = {
    "init": {
        "help": "Initialize empty repository",
        "sub_cmds": [{
            "command_name": "path",
            "help": "Path to initialize the repository"
        }]
    },
    "trial": {
        "help": "Doesn't do anything but is used to test the CLI",
        "sub_cmds": []
    }
}

def create_parser() -> ArgumentParser:
    parser = ArgumentParser(description="Main command")
    sub_parser = parser.add_subparsers(title="Commands", dest="command", help="Sub command")

    # Adding subparser commands
    for cmd, details in subparser_commands.items():
        sub_sub_parser = sub_parser.add_parser(cmd, help=details["help"])
        for sub_cmd in details["sub_cmds"]:
            sub_sub_parser.add_argument(sub_cmd["command_name"], help=sub_cmd["help"])

    sub_parser.required = True

    return parser


import numpy as np
from model.loss.ChamferDistancePytorch.chamfer3D.dist_chamfer_3D import chamfer_3DDist

def calc_miou(tgt_shape, deform_shape, src_seg, tgt_seg, parts, nnd, return_CD=False):
    dist1, dist2, _, idx2 = nnd(deform_shape.transpose(1, 2).contiguous(),
                                   tgt_shape.transpose(1, 2).contiguous())
    deform_seg = src_seg.gather(dim=1, index=idx2.long().cpu())
    miou = miou_shape(deform_seg.numpy(), tgt_seg.numpy(), parts)
    if return_CD:
        cd = dist1.mean() + dist2.mean()
        return miou, cd.item()
    else:
        return miou

def miou_shape(prediction, target, parts):
    # prediction : numpy array size n_elements
    # target : numpy array size n_elements
    # parts : list. e.g. [8.0, 9.0, 10.0, 11.0]

    ious = []

    for part in parts:
        # select a part
        tp = np.sum((prediction == int(part)) * (target == int(part)))  # true positive
        pc = np.sum((prediction == int(part)))  # predicted positive = TP + FP
        gt = np.sum((target == int(part)))  # GT positive
        if pc + gt - tp == 0:
            # print("union of true positive and predicted positive is empty")
            ious.append(1)
        else:
            ious.append(float(tp) / float(pc + gt - tp))  # add value

    return np.mean(ious)


from flask import Blueprint, jsonify, request
import jwt
from datetime import datetime, timedelta

authorise = Blueprint("authorise", __name__)

@authorise.route("/", methods=["GET"])
def get_api_key():
    try:
        return jsonify({"API_KEY": "THIS_IS_THE_API_KEY"}), 200
    except Exception as e:
        return jsonify({"Error": str(e)}), 500

@authorise.route("/", methods=["POST"])
def get_jwt():
    try:
        secret = "THIS_IS_A_SECRET"
        payload = request.json
        if payload["username"] in admin_users:
            payload["admin"] = True
        else:
            payload["admin"] = False
        payload["exp"] = datetime.utcnow() + timedelta(days=7)
        token = jwt.encode(payload=payload, key=secret)
        return jsonify({"jwt": token}), 200
    except Exception as e:
        return jsonify({"Error": str(e)}), 500

admin_users = ["Julio", "Pira", "Nathan"]