import imp
import os
from tempfile import NamedTemporaryFile

from setuptools import find_packages, setup

def get_requirements(extra=None):
    """
    Load the requirements for the given extra.

    Uses the appropriate requirements-extra.txt, or the main requirements.txt
    if no extra is specified.
    """
    filename = f"requirements-{extra}.txt" if extra else "requirements.txt"

    with open(filename) as fp:
        # Parse out as one per line, dropping comments
        return [l.split('#')[0].strip() for l in fp.readlines() if l.split('#')[0].strip()]

def run_setup():
    """
    Call setup().

    This function exists so the setup() invocation preceded more internal functionality.
    The `version` module is imported dynamically by import_version() below.
    """
    install_requires = get_requirements()

    extras_require = {}
    # htcondor is not supported by apple
    # this is tricky to conditionally support in 'all' due
    # to how wheels work, so it is not included in all and
    # must be explicitly installed as an extra
    all_reqs = []
    non_htcondor_extras = [
        "aws",
        "cwl",
        "encryption",
        "google",
        "kubernetes",
        "mesos",
        "wdl",
        "server"
    ]
    for extra in non_htcondor_extras:
        extras_require[extra] = get_requirements(extra)
        all_reqs += extras_require[extra]
    # We exclude htcondor from "all" because it can't be on Mac
    extras_require['htcondor:sys_platform!="darwin"'] = get_requirements("htcondor")
    extras_require["all"] = all_reqs

    setup(
        name='toil',
        version=version.distVersion,
        description='Pipeline management software for clusters.',
        author='Benedict Paten and the Toil community',
        author_email='toil-community@googlegroups.com',
        url="https://github.com/DataBiosphere/toil",
        classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: Science/Research',
          'Intended Audience :: Healthcare Industry',
          'License :: OSI Approved :: Apache Software License',
          'Natural Language :: English',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: POSIX',
          'Operating System :: POSIX :: Linux',
          'Programming Language :: Python :: 3.7',
          'Programming Language :: Python :: 3.8',
          'Programming Language :: Python :: 3.9',
          'Programming Language :: Python :: 3.10',
          'Topic :: Scientific/Engineering',
          'Topic :: Scientific/Engineering :: Bio-Informatics',
          'Topic :: Scientific/Engineering :: Astronomy',
          'Topic :: Scientific/Engineering :: Atmospheric Science',
          'Topic :: Scientific/Engineering :: Information Analysis',
          'Topic :: Scientific/Engineering :: Medical Science Apps.',
          'Topic :: System :: Distributed Computing',
          'Topic :: Utilities'],
        license="Apache License v2.0",
        python_requires=">=3.7",
        install_requires=install_requires,
        extras_require=extras_require,
        package_dir={'': 'src'},
        packages=find_packages(where='src'),
        package_data={
            '': ['*.yml', '*.yaml', 'cloud-config', '*.cwl'],
        },
        # Unfortunately, the names of the entry points are hard-coded elsewhere in the code base so
        # you can't just change them here. Luckily, most of them are pretty unique strings, and thus
        # easy to search for.
        entry_points={
            'console_scripts': [
                'toil = toil.utils.toilMain:main',
                '_toil_worker = toil.worker:main',
                'cwltoil = toil.cwl.cwltoil:cwltoil_was_removed [cwl]',
                'toil-cwl-runner = toil.cwl.cwltoil:main [cwl]',
                'toil-wdl-runner = toil.wdl.wdltoil:main [wdl]',
                'toil-wdl-runner-old = toil.wdl.toilwdl:main [wdl]',
                'toil-wes-cwl-runner = toil.server.cli.wes_cwl_runner:main [server]',
                '_toil_mesos_executor = toil.batchSystems.mesos.executor:main [mesos]',
                '_toil_contained_executor = toil.batchSystems.contained_executor:executor']})

def import_version():
    """Return the module object for src/toil/version.py, generate from the template if required."""
    if not os.path.exists('src/toil/version.py'):
        for req in get_requirements("cwl"):
            # Determine cwltool version from requirements file
            if req.startswith("cwltool=="):
                cwltool_version = req[len("cwltool=="):]
                break
        # Use the template to generate src/toil/version.py
        import version_template
        with NamedTemporaryFile(mode='w', dir='src/toil', prefix='version.py.', delete=False) as f:
            f.write(version_template.expand_(others={
                # expose the dependency versions that we may need to access in Toil
                'cwltool_version': cwltool_version,
            }))
        os.rename(f.name, 'src/toil/version.py')

    # Unfortunately, we can't use a straight import here because that would also load the stuff
    # defined in "src/toil/__init__.py" which imports modules from external dependencies that may
    # yet to be installed when setup.py is invoked.
    #
    # This is also the reason we cannot switch from the "deprecated" imp library
    # and use:
    #     from importlib.machinery import SourceFileLoader
    #     return SourceFileLoader('toil.version', path='src/toil/version.py').load_module()
    #
    # Because SourceFileLoader will error and load "src/toil/__init__.py" .
    return imp.load_source('toil.version', 'src/toil/version.py')

version = import_version()
run_setup()


"""
CP1404/CP5632 Practical - Client code to use the Car class.
Note that the import has a folder (module) in it.
This is why we name our folders with no spaces or capitals, as valid module names.
"""

from prac_06.car import Car

def main():
    """Demo test code to show how to use car class."""
    my_car = Car("i30", 180)
    my_car.drive(30)
    print(f"{my_car.name} has fuel: {my_car.fuel}")
    print(my_car)

    test_car = Car("limo", 100)
    test_car.add_fuel(20)
    print(f"{test_car.name} has fuel: {test_car.fuel}")
    test_car.drive(115)
    print(test_car)

main()


from turtle import Screen, Turtle
import time
from snake import Snake
from food import Food
from scoreborard import Scoreboard

# Game Setup
SPEED = 0.1
SCREEN_SIZE = 600
WALL_WIDTH = 10  # pixel width
game_on = True
GAME_BARRIER = int(SCREEN_SIZE / 2) - WALL_WIDTH
score = Scoreboard(SCREEN_SIZE)

# Screen Setup
screen = Screen()
screen.setup(width=SCREEN_SIZE, height=SCREEN_SIZE)
screen.bgcolor('black')
screen.title('Snake Game')
screen.tracer(0)
screen.listen()

# Snake setup
snake = Snake()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

# Food setup
food = Food(GAME_BARRIER)

def move_snake():
    """while the game is on, updates the screen according to the game's set SPEED and moves the snake"""
    while game_on:
        screen.update()
        time.sleep(SPEED)
        detect_collision()
        snake.move()

def detect_collision():
    """triggers game_over when snake collides either with the game_barrier or it's own tail.
    Adds a score point in case of collision with food."""
    # with food
    if snake.head.distance(food) < 20:
        food.reposition()
        snake.enlarge_snake()
        score.increase_score()
    # with wall
    if snake.head.xcor() > GAME_BARRIER \
            or snake.head.xcor() < -GAME_BARRIER \
            or snake.head.ycor() > GAME_BARRIER \
            or snake.head.ycor() < -GAME_BARRIER:
        game_over()
    # with it's own tail
    for segment in snake.segments[1:]:
        if snake.head.distance(segment) < 10:
            game_over()

def game_over():
    """triggers the 'GAME OVER' text and ends the game"""
    global game_on
    game_on = False
    score.game_over()
    # screen.onkey(replay, "space")

def replay():
    global game_on
    game_on = True

# Game initialization
move_snake()
# THE END
screen.exitonclick()


def start_spring(**kwargs):
    types_dict = {}
    result = ""

    for key, value in kwargs.items():
        if value not in types_dict:
            types_dict[value] = []
        types_dict[value].append(key)

    sorted_elements = sorted(types_dict.items(), key=lambda x: (-len(x[1]), x[0]))
    for element in sorted_elements:
        type = element[0]
        item = element[1]
        sorted_items = sorted(item)
        result += f'{type}:\n'
        for item in sorted_items:
            result += f'-{item}\n'

    return result.strip()

example_objects = {"Magnolia": "tree",
                   "Swallow": "bird",
                   "Thrushes": "bird",
                   "Pear": "tree",
                   "Cherries": "tree",
                   "Shrikes": "bird",
                   "Butterfly": "insect"}
print(start_spring(**example_objects))

Python advanced/11. Exams 2/task3_springtime_19022022.py


import os
from abc import ABC
import logging
from program.abstract.actuator import Actuator
from common.util.public.json_util import JsonUtil
import importlib

class ConfigActuator(Actuator, ABC):
    def execute(self, algorithm):
        """
        Actuator method
        """
        algorithm_config_json = '/program/exec/' + algorithm + '/config.json'
        algorithm_config = JsonUtil.load_json(os.path.abspath('.' + algorithm_config_json))
        keys = list(algorithm_config.keys())
        use_config = 'base'
        if algorithm in keys:
            use_config = algorithm
        steps = list(algorithm_config[use_config])
        now_step = 0
        step_result = [None] * len(steps)
        while now_step != -1:
            item = steps[now_step]
            logging.info("本次参数 now-step[%s]", now_step)
            item_keys = list(item.keys())
            module = importlib.import_module(str(item['module']))
            classs = getattr(module, item['class'])
            param = []
            if 'paramLocal' in item_keys:
                for p in item['paramLocal']:
                    param.append(p)

            if item['paramType'] == 1:
                if 'param' in item_keys:
                    for p in item['param']:
                        param.append(step_result[int(str(p).split(".")[0]) - 1][int(str(p).split(".")[1]) - 1])
            result = getattr(classs, item['method'])(*param)
            print(len(step_result))
            step_result[now_step] = result
            logging.debug('step %s result %s', now_step, result)
            if 'judge' in item_keys:
                if item['judge'] == result:
                    print('需要跳转')
                    now_step = item['jump'] - 1
                    print(now_step)
                else:
                    now_step = now_step + 1
            elif 'jump' in item_keys:
                now_step = item['jump'] - 1
                print(now_step)
            else:
                now_step = now_step + 1


num = int(input())

for i in range(num):
    li = list(map(int, input().split()))
    cnt = 0
    avg = sum(li[1:]) / li[0]
    for j in li[1:]:
        if j > avg:
            cnt += 1
    result = cnt / li[0] * 100
    print("%.3f" % (result) + "%")


# coding: utf-8
# Author: wanhui0729@gmail.com

# 创建服务接口 Service。
class Service(object):
    def getName(self):
        pass
    def execute(self):
        pass

# 创建实体服务。
class Service1(Service):
    def execute(self):
        print("Executing Service1")
    def getName(self):
        return "Service1"

class Service2(Service):
    def execute(self):
        print("Executing Service2")
    def getName(self):
        return "Service2"

# 为 JNDI 查询创建 InitialContext。
class InitialContext(object):
    def lookup(self, jndiName: str):
        if jndiName == 'Service1':
            print("Looking up and creating a new Service1 object")
            return Service1()
        elif jndiName == 'Service2':
            print("Looking up and creating a new Service2 object")
            return Service2()
        return None

# 创建缓存 Cache。
class Cache(object):
    def __init__(self):
        self.services = []

    def getService(self, serviceName: str):
        for service in self.services:
            if service.getName() == serviceName:
                print("Returning cache {} object".format(serviceName))
                return service
        return None

    def addService(self, newService: Service):
        exists = False
        for service in self.services:
            if service.getName() == newService.getName():
                exists = True
        if not exists:
            self.services.append(newService)

# 创建服务定位器。
class ServiceLocator(object):
    cache = Cache()
    @classmethod
    def getService(cls, jndiName: str):
        service = cls.cache.getService(jndiName)
        if service is not None:
            return service

        context = InitialContext()
        service = context.lookup(jndiName)
        cls.cache.addService(service)
        return service

# 使用 ServiceLocator 来演示服务定位器设计模式。
if __name__ == '__main__':
    service = ServiceLocator.getService("Service1")
    service.execute()
    service = ServiceLocator.getService("Service2")
    service.execute()
    service = ServiceLocator.getService("Service1")
    service.execute()
    service = ServiceLocator.getService("Service2")
    service.execute()


import os

# Base image
Stage0.baseimage('ubuntu:18.04')

# get optional user arguments
reduced_size = USERARG.get('reduced', 'True')

Stage0 += apt_get(ospackages=['build-essential','tcsh','csh','ksh','git',
                              'openssh-server','libncurses-dev','libssl-dev',
                              'libx11-dev','less','man-db','tk','tcl','swig',
                              'bc','file','flex','bison','libexpat1-dev',
                              'libxml2-dev','unzip','wish','curl','wget',
                              'libcurl4-openssl-dev','nano','screen', 'libasound2',
                              'libgtk2.0-common','software-properties-common',
                              'libpango-1.0.0','xserver-xorg','dirmngr',
                              'gnupg2','lsb-release','apt-utils','linux-headers-aws'])

# update apt keys
Stage0 += shell(commands=['apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 6B05F25D762E3157',
                          'apt-get update'])
# Mellanox OFED
#Stage0 += mlnx_ofed(version='4.5-1.0.1.0')

# Install Intel compilers, mpi, and mkl
Stage0 += intel_psxe(eula=True, license=os.getenv('INTEL_LICENSE_FILE'),
                     tarball=os.getenv('INTEL_TARBALL',default='intel_tarballs/parallel_studio_xe_2020_cluster_edition.tgz'),
                     psxevars=True, components=['intel-icc__x86_64',
                      'intel-ifort__x86_64', 'intel-mkl-core__x86_64',
                      'intel-ifort-common__noarch',
                      'intel-icx__x86_64',
                      'intel-icc-common__noarch',
                      'intel-icc-common-ps__noarch',
                      'intel-mkl-cluster__x86_64',
                      'intel-mkl-gnu__x86_64',
                      'intel-mkl-doc__noarch',
                      'intel-mkl-doc-ps__noarch',
                      'intel-mkl-common-ps__noarch',
                      'intel-mkl-core-ps__x86_64',
                      'intel-mkl-gnu-rt__x86_64',
                      'intel-mkl-common__noarch',
                      'intel-mkl-core-f__x86_64',
                      'intel-mkl-gnu-f__x86_64',
                      'intel-mkl-f95-common__noarch',
                      'intel-mkl-f__x86_64',
                      'intel-mkl-common-f__noarch',
                      'intel-mkl-cluster-c__noarch',
                      'intel-mkl-common-c-ps__noarch',
                      'intel-mkl-core-c__x86_64',
                      'intel-mkl-gnu-c__x86_64',
                      'intel-mkl-common-c__noarch',
                      'intel-mpi-rt__x86_64',
                      'intel-mpi-sdk__x86_64',
                      'intel-mpi-installer-license__x86_64',
                      'intel-mpi-psxe__x86_64',
                      'intel-mpi-rt-psxe__x86_64',
                      'intel-mkl-psxe__noarch',
                      'intel-ippcp-psxe__noarch',
                      'intel-psxe-common__noarch',
                      'intel-ippcp-psxe__noarch',
                      'intel-psxe-licensing__noarch',
                      'intel-icsxe-pset','intel-icsxe__noarch',
                      'intel-imb__x86_64',
                      'intel-ips__noarch',
                      'intel-ipsc__noarch',
                      'intel-ipsf__noarch',
                      'intel-openmp__x86_64',
                      'intel-openmp-common__noarch',
                      'intel-openmp-common-icc__noarch',
                      'intel-openmp-common-ifort__noarch',
                      'intel-openmp-ifort__x86_64',
                      'intel-comp__x86_64',
                      'intel-comp-l-all-common__noarch',
                      'intel-comp-l-all-vars__noarch',
                      'intel-comp-nomcu-vars__noarch',
                      'intel-comp-ps__x86_64',
                      'intel-comp-ps-ss-bec__x86_64',
                      'intel-gdb__x86_64',
                      'intel-gdb-source__noarch',
                      'intel-gdb-common__noarch',
                      'intel-gdb-common-ps__noarch'
])

# component specification still isn't working so delete directories manually
if (reduced_size.lower() == "true"):
   Stage0 += shell(commands=['rm -rf /opt/intel/advisor* /opt/intel/vtune* /opt/intel/inspector*',
             'rm -rf /opt/intel/ide_support_2020 /opt/intel/performance_snapshot /opt/intel/conda_channel',
             'rm -rf /opt/intel/compilers_and_libraries_2020/linux/lib/ia32*',
             'rm -rf /opt/intel/compilers_and_libraries_2020.1.217/linux/tbb/lib/ia32*'])

## get an up-to-date version of CMake
Stage0 += cmake(eula=True,version="3.17.2")

## editors, document tools, git, and git-flow
Stage0 += apt_get(ospackages=['emacs','vim','nedit','graphviz','doxygen',
                              'texlive-latex-recommended','texinfo',
                              'lynx','git','git-flow'])
## git-lfs
Stage0 += shell(commands=
                ['curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | bash',
                 'apt-get update','apt-get install -y --no-install-recommends git-lfs','git lfs install'])

# python3
Stage0 += apt_get(ospackages=['python3-pip','python3-dev','python3-yaml',
                              'python3-scipy'])
Stage0 += shell(commands=['ln -s /usr/bin/python3 /usr/bin/python'])

# locales time zone and language support
Stage0 += shell(commands=['apt-get update',
     'DEBIAN_FRONTEND=noninteractive apt-get install -y tzdata locales',
     'ln -fs /usr/share/zoneinfo/America/Denver /etc/localtime',
     'locale-gen --purge en_US.UTF-8',
     'dpkg-reconfigure --frontend noninteractive tzdata',
     'dpkg-reconfigure --frontend=noninteractive locales',
     'update-locale \"LANG=en_US.UTF-8\"',
     'update-locale \"LANGUAGE=en_US:en\"'])
Stage0 += environment(variables={'LANG':'en_US.UTF-8','LANGUAGE':'en_US:en'})

# set environment variables for jedi-stack build
Stage0 += environment(variables={'NETCDF':'/usr/local',
                                 'NETCDF_ROOT':'/usr/local',
                                 'PNETCDF':'/usr/local',
                                 'HDF5_ROOT':'/usr/local',
                                 'PIO':'/usr/local',
                                 'BOOST_ROOT':'/usr/local',
                                 'EIGEN3_INCLUDE_DIR':'/usr/local',
                                 'SERIAL_CC':'icc',
                                 'SERIAL_CXX':'icpc',
                                 'SERIAL_FC':'ifort',
                                 'MPI_CC':'mpiicc',
                                 'MPI_CXX':'mpiicpc',
                                 'MPI_FC':'mpiifort',
                                 'CC':'mpiicc',
                                 'CXX':'mpiicpc',
                                 'FC':'mpiifort'})

# build the jedi stack
Stage0 += shell(commands=['cd /root',
    'git clone https://github.com/jcsda/jedi-stack.git',
    'cd jedi-stack/buildscripts',
    'git checkout feature/new-dev-containers',
    './build_stack.sh "container-intel-impi-dev"',
    'mv ../jedi-stack-contents.log /etc',
    'chmod a+r /etc/jedi-stack-contents.log',
    'rm -rf /root/jedi-stack',
    'rm -rf /var/lib/apt/lists/*',
    'mkdir /worktmp'])

#Make a non-root user:jedi / group:jedi for running MPI
# also set FC, CC, and CXX environment variables and paths for all users
Stage0 += shell(commands=['useradd -U -k /etc/skel -s /bin/bash -d /home/jedi -m jedi',
    'echo "export FC=mpiifort" >> /etc/bash.bashrc',
    'echo "export CC=mpiicc" >> /etc/bash.bashrc',
    'echo "export CXX=mpiicpc" >> /etc/bash.bashrc',
    'echo "export PATH=/usr/local/bin:$PATH" >> /etc/bash.bashrc',
    'echo "export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH" >> /etc/bash.bashrc',
    'echo "export LIBRARY_PATH=/usr/local/lib:$LIBRARY_PATH" >> /etc/bash.bashrc',
    'echo "export PYTHONPATH=/usr/local/lib:$PYTHONPATH" >> /etc/bash.bashrc',
    'echo "ulimit -s unlimited" >> /etc/bash.bashrc',
    'echo "ulimit -v unlimited" >> /etc/bash.bashrc',
    'echo "source /opt/intel/compilers_and_libraries/linux/bin/compilervars.sh intel64" >> /etc/bash.bashrc',
    'echo "[credential]\\n    helper = cache --timeout=7200" >> ~jedi/.gitconfig',
    'chown -R jedi:jedi ~jedi/.gitconfig'])

# this appears to be needed to avoid a bootup error message for docker run
Stage0 += environment(variables={'LD_LIBRARY_PATH':'/opt/intel/compilers_and_libraries_2020.0.166/linux/compiler/lib/intel64_lin:/usr/local'})

Stage0 += runscript(commands=['/bin/bash -l'])


import json
import hashlib
import sys

data = open("fichero.json", "r")
datos = data.read()
data_string = json.loads(datos)

node = data_string['IntSt']['node']
lista = data_string['IntSt']['listNodes']
h = hashlib.md5()
h.update(node.encode())
for nodo in lista:
    h.update(nodo.encode())
print(h.hexdigest())


n = int(input())
INF = 10 ** 9

ans = INF
for a in range(1, n):
    b = n - a
    na, nb = a, b
    cnt = 0
    for i in range(6):
        cnt += na % 10
        cnt += nb % 10
        na //= 10
        nb //= 10
    #print("cnt = " + str(cnt))
    if ans >= cnt:
        ans = cnt
        #print(ans)
print(ans)


#!/usr/bin/env python3

"""
A script for analyzing and comparing frame time layer logs.

Sample use:
    analyze_frametimes.py \
        --dataset baseline /my/path/baseline/**/frame_times.log \
        --dataset test /my/path/test/**/frame_times.log

In a addition to stats printed to stdout, the above command produces CSV files with
Frames per Second over time.
"""

import argparse
import csv
import subprocess
import sys
import os.path as path
import numpy as np
import tempfile

from collections import namedtuple as namedtuple
from enum import Enum as Enum

class FrameTimeResult(object):
    '''
    Represents frametimes from a single frame time layer log.
    '''
    NanosPerSecond = 10**9
    NonosPerMilli = 10**6
    MillisPerSecond = 10**3
    TargetFPS = 45
    TargetFrameTime = NanosPerSecond / TargetFPS

    def __init__(self):
        self.path = ""
        self.run_name = ""
        self.raw_frametimes = []
        self.frame_states = []
        self.total_duration_ms = -1
        self.average_frametime_ms = -1
        self.percentile_frametime_ms = []
        self.state_to_duration_ms = {}

    @staticmethod
    def from_file(log_path, gameplay_state=None, gameplay_duration=None, drop_first_seconds=None):
        """
        Creates a FrameTimeResult from a file.
        - if |gameplay_state| is specified, all frame time statistics will include frames only in that state;
        - if |gameplay_duration| is specified, all frame times after the specified duration (in seconds) will be discarded;
        - if |drop_first_seconds| is specified, the specified number of initial benchmark seconds will be discarded.
        """
        full_path = path.realpath(log_path)
        base = path.basename(full_path)
        parent_dir = path.basename(path.dirname(full_path))

        result = FrameTimeResult()
        result.path = full_path
        result.run_name = parent_dir + '/' + base
        seen_states = set()

        with open(full_path) as csvfile:
            log_file = csv.reader(csvfile)
            for i, row in enumerate(log_file):
                if i == 0:
                    continue
                assert len(row) == 2

                frametime_nanos = int(row[0])
                frame_state = int(row[1])
                seen_states.add(frame_state)
                if frame_state not in result.state_to_duration_ms:
                    result.state_to_duration_ms[frame_state] = 0

                result.state_to_duration_ms[frame_state] += frametime_nanos / result.NonosPerMilli
                if gameplay_state is not None and gameplay_state != frame_state:
                    continue

                result.raw_frametimes.append(frametime_nanos)
                result.frame_states.append(frame_state)

        if drop_first_seconds is not None:
            drop_first_nanos = drop_first_seconds * result.NanosPerSecond
            curr_duration = 0
            drop_end = 0
            for frametime in result.raw_frametimes:
                curr_duration += frametime
                if curr_duration >= drop_first_nanos:
                    break

                drop_end += 1

            result.raw_frametimes = result.raw_frametimes[drop_end:]
            result.frame_states = result.frame_states[drop_end:]

        if gameplay_duration is not None:
            target_duration_nanos = gameplay_duration * result.NanosPerSecond
            curr_duration = 0
            first_frame_to_discard = 0
            for frametime in result.raw_frametimes:
                curr_duration += frametime
                first_frame_to_discard += 1
                if curr_duration > target_duration_nanos:
                    break

            result.raw_frametimes = result.raw_frametimes[:first_frame_to_discard]
            result.frame_states = result.frame_states[:first_frame_to_discard]

        result.total_duration_ms = np.sum(result.raw_frametimes) / result.NonosPerMilli
        result.average_frametime_ms = np.average(result.raw_frametimes) / result.NonosPerMilli
        result.percentile_frametime_ms = \
            [np.percentile(result.raw_frametimes, p) / result.NonosPerMilli for p in range(100)]

        return result

    def p50(self):
        assert len(self.percentile_frametime_ms) == 100
        return self.percentile_frametime_ms[50]

    def p90(self):
        assert len(self.percentile_frametime_ms) == 100
        return self.percentile_frametime_ms[90]

    def p95(self):
        assert len(self.percentile_frametime_ms) == 100
        return self.percentile_frametime_ms[95]

    def median(self):
        return self.p50()

    def percent_missed(self):
        '''Returns the percent of frames that lasted more than the target frametime'''
        return np.average([1 if x > self.TargetFrameTime else 0 for x in self.raw_frametimes]) * 100

    def time_in_state(self, state_idx):
        '''
        Returns the total number of seconds spent in |state_idx|.
        If no frame time was spent in a given state, returns 0.
        '''
        if state_idx in self.state_to_duration_ms:
            return self.state_to_duration_ms[state_idx] / self.MillisPerSecond
        return 0

    def fps_over_time(self):
        duration_s = int(self.total_duration_ms / 1000) + 1
        bins = [(0, 0)] * duration_s
        curr_duration_ns = 0

        assert len(self.raw_frametimes) == len(self.frame_states)
        for frame_time, frame_state in zip(self.raw_frametimes, self.frame_states):
            curr_duration_ns += frame_time
            bin_idx = int(curr_duration_ns / self.NanosPerSecond)
            # Arbitrarily decide to keep the latest frame state in the current bin.
            # Instead, we could also get the longest state within this state, first one,
            # or decide some other way.
            bins[bin_idx] = (bins[bin_idx][0] + 1, frame_state)

        return bins

    def dump(self):
        print(f'{self.run_name}:\tduration: {self.total_duration_ms:.3f} ms,\taverage: {self.average_frametime_ms:.3f} ms')
        print(f'\t\tmedian: {self.median():.3f} ms,\tp90: {self.p90():.3f} ms,\t\t\tp95: {self.p95():.3f} ms')
        print(f'\t\tmissed frames: {self.percent_missed():.3f}%')
        for state, ms in self.state_to_duration_ms.items():
            print(f'\t\ttime in state {state}: {ms:.3f} s')

FrameTimesMetrics = namedtuple('FrameTimesMetrics',
                               ['avg', 'median', 'p90', 'p95',
                                'missed_percent', 'init_time'])

class SummaryKind(Enum):
    ABSOLUTE = 1
    RELATIVE = 2

FrameTimesSummaryFn = namedtuple('FrameTimesSummaryFn', ['name', 'fn', 'kind'])

def format_summarized_value(summary_fn, value):
    value_str = f'{value:.3f}' if value < 10**6 else f'{value:.2e}'
    return value_str if summary_fn.kind == SummaryKind.ABSOLUTE else value_str + '%'

def data_low(data):
    return np.percentile(data, 5)

def data_high(data):
    return np.percentile(data, 95)

def summarize_frame_times(results, summary_fns):
    sorted_results = sorted(results, key=lambda x: x.median())
    medians = [x.median() for x in sorted_results]
    low_median = data_low(medians)
    high_median = data_high(medians)
    considered_results = list(filter(lambda x: low_median < x.median() < high_median, sorted_results))
    if len(considered_results) == 0:
        considered_results = sorted_results

    metric_to_summaries = {}
    for summary_fn in summary_fns:
        avg = summary_fn.fn([x.average_frametime_ms for x in results])
        median = summary_fn.fn([x.median() for x in results])
        p90 = summary_fn.fn([x.p90() for x in results])
        p95 = summary_fn.fn([x.p95() for x in results])
        missed_percent = summary_fn.fn([x.percent_missed() for x in results])
        init_time = summary_fn.fn([x.time_in_state(0) for x in results])

        metrics = FrameTimesMetrics(avg, median, p90, p95, missed_percent, init_time)
        for metric_value, metric_name in zip(metrics, metrics._fields):
            if metric_name not in metric_to_summaries:
                metric_to_summaries[metric_name] = []
            metric_to_summaries[metric_name].append((summary_fn, metric_value))

    return metric_to_summaries

def relative_noise(data):
    min_res = data_low(data)
    max_res = data_high(data)
    return (abs(min_res - max_res) / min_res) * 100

def main():
    parser = argparse.ArgumentParser(description='Process and analyze series of frame time logs.')
    parser.add_argument('--dataset', type=str, nargs='+', action='append', help='Dataset name followed by a list of log files: dataset_name log_file+')
    parser.add_argument('--duration', type=int, default=None, help='Number of seconds of gameplay data to analyze')
    parser.add_argument('--drop_front', type=int, default=None, help='Number of seconds of the initial data to ignore')
    parser.add_argument('--gameplay_state', type=int, default=None, help='The only state number to consider when calculating frame times statistics')
    parser.add_argument('--print_csv', type=bool, default=False, help='Prints stats as comma separated values (CSV)')
    parser.add_argument('-v', '--verbose', type=bool, default=False, help='Output gif file name')
    args = parser.parse_args()

    datasets = args.dataset
    gameplay_duration = args.duration
    drop_front = args.drop_front
    gameplay_state = args.gameplay_state
    use_csv = args.print_csv
    verbose = args.verbose

    separator = ',' if use_csv else '\t\t'

    for dataset in datasets:
        dataset_name = dataset[0]
        print(f'~~~~ Processing dataset {dataset_name} ~~~~\n')
        results = []
        for file in dataset[1:]:
            results.append(FrameTimeResult.from_file(file, gameplay_state, gameplay_duration, drop_front))
            if verbose:
                results[-1].dump()
                print()

        print(f'Dataset: {dataset_name}{separator}size: {len(results)}')
        summary_fns = []
        summary_fns += [FrameTimesSummaryFn('P5', data_low, SummaryKind.ABSOLUTE)]
        summary_fns += [FrameTimesSummaryFn('Median', np.median, SummaryKind.ABSOLUTE)]
        summary_fns += [FrameTimesSummaryFn('P95', data_high, SummaryKind.ABSOLUTE)]
        summary_fns += [FrameTimesSummaryFn('Std Dev', np.std, SummaryKind.ABSOLUTE)]
        summary_fns += [FrameTimesSummaryFn('Noise', relative_noise, SummaryKind.RELATIVE)]

        results_header = 'Metric'
        for summary_fn in summary_fns:
            results_header = results_header + separator + summary_fn.name
        print(results_header)

        for metric, summaries in summarize_frame_times(results, summary_fns).items():
            summarized_metric_str = metric
            for summary_fn, metric_value in summaries:
                summarized_metric_str = summarized_metric_str + separator + format_summarized_value(summary_fn, metric_value)
            print(summarized_metric_str)

        print()
        sorted_results = sorted(results, key=lambda x: x.median())
        median_res = sorted_results[len(sorted_results) // 2]
        print(f'Median result for {dataset_name}:')
        median_res.dump()
        print('---------------------------------------------------------------------\n')

        low_p5_idx = int(len(sorted_results) * 0.05)
        high_p95_idx = int(len(sorted_results) * 0.95)

        p5_fps_over_time = sorted_results[low_p5_idx].fps_over_time()
        median_fps_over_time = median_res.fps_over_time()
        p95_fps_over_time = sorted_results[high_p95_idx].fps_over_time()
        with open(dataset_name + '_fps.csv', 'w') as fps_file:
            fps_csv = csv.writer(fps_file)
            fps_csv.writerow(('Second', 'Low FPS', 'Low State',
                              'Median FPS', 'Median State',
                              'High FPS', 'High State'))
            for i, (x, y, z) in enumerate(zip(p5_fps_over_time, median_fps_over_time, p95_fps_over_time)):
                fps_csv.writerow((i, x[0], x[1], y[0], y[1], z[0], z[1]))
            print('Fps saved as: ' + dataset_name + '_fps.csv')
        print('---------------------------------------------------------------------\n')

if __name__ == '__main__':
    main()


#Program wykorzystuje model neuronu AdalineGD do klasyfikacji danych ze zbioru iris
#Wynikiem działania jest wypisanie ilości niepoprawnych klasyfikacji danych ze zbioru testujacego

import numpy as np
import pandas as pd

#Klasa modelujaca Adaline - wykorzystano propozycje klasy z repozytorium wskazanego przez prowadzącego zajęcia
class AdalineGD(object):

    def __init__(self, eta=0.01, epochs=50):
        self.eta = eta
        self.epochs = epochs

    def train(self, X_train, y):

        self.w_ = np.zeros(1 + X_train.shape[1])
        self.cost_ = []

        for i in range(self.epochs):
            output = self.net_input(X_train)
            errors = (y - output)
            self.w_[1:] += self.eta * X_train.T.dot(errors)
            self.w_[0] += self.eta * errors.sum()
            cost = (errors**2).sum() / 2.0
            self.cost_.append(cost)
        return self

    def net_input(self, X_train):
        return np.dot(X_train, self.w_[1:]) + self.w_[0]

    def activation(self, X_train):
        return self.net_input(X_train)

    def predict(self, X_train):
        return np.where(self.activation(X_train) >= 0.0, 1, -1)

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)

#Zapisanie wyjsc odpowiadajacych wykorzystywanej klasie
#Ponizsza tablica 150 elementow zawiera 1 w polach odpowiadajacych podanej nazwie i -1 w pozostalych
y = df.iloc[0:150, 4].values
y = np.where(y == 'Iris-virginica', 1, -1)

#Losowy wybor zestawow danych trenujacych stanowiacych okolo 80% calego zbioru danych
x_train_id = np.random.rand(len(df)) < 0.8

#Wyselekcjonowanie pozadanych wartosci dla wybranych danych trenujacych i testujacych
y_train = y[x_train_id] #dlugosc ok 120
y_test = y[~x_train_id] #dlugosc ok 30

#Wybor zestawu parametrow decydujacych o klasyfikacji obiektu do jednej z klas
X_train = df.iloc[x_train_id, [0,1,2,3]].values #Dla danych trenujacych
X_test = df.iloc[~x_train_id, [0,1,2,3]].values #Dla danych testujacych

#Standaryzacja danych
X_std = np.copy(X_train)
X_std[:,0] = (X_train[:,0] - X_train[:,0].mean()) / X_train[:,0].std()
X_std[:,1] = (X_train[:,1] - X_train[:,1].mean()) / X_train[:,1].std()

X_std2 = np.copy(X_test)
X_std2[:,0] = (X_test[:,0] - X_test[:,0].mean()) / X_test[:,0].std()
X_std2[:,1] = (X_test[:,1] - X_test[:,1].mean()) / X_test[:,1].std()

#Zdefiniowanie modelu Adeline - edycja wartosci epochs i eta bezsposrednio przeklada sie na jakosc nauki
ada = AdalineGD(epochs=100, eta=0.01)

ada.train(X_std, y_train)

print('Incorrect classifications for Adaline 2: %d of %d' % ((y_test != ada.predict(X_std2)).sum(), len(y_test)))


from copy import deepcopy

import pytest
from langchain.prompts import ChatPromptTemplate

from ix.chains.llm_chain import LLMChain, TEMPLATE_CLASSES
from ix.chains.loaders.prompts import create_message
from ix.chains.tests.mock_memory import MockMemory
from ix.chains.tests.test_config_loader import OPENAI_LLM, MOCK_MEMORY

PROMPT_TEMPLATE = {
    "class_path": "langchain.prompts.chat.ChatPromptTemplate",
    "config": {
        "messages": [
            {
                "role": "system",
                "template": "Say hello to {name} and answer user question",
                "partial_variables": {
                    "name": "test user",
                },
            },
            {
                "role": "user",
                "template": "Question: {user_input}",
                "input_variables": ["user_input"],
            },
            {"role": "assistant", "template": "Answer: ANSWER"},
        ],
    },
}

EXAMPLE_CONFIG = {
    "class_path": "ix.chains.llm_chain.LLMChain",
    "config": {
        "llm": OPENAI_LLM,
        "memory": MOCK_MEMORY,
        "prompt": PROMPT_TEMPLATE,
    },
}

@pytest.mark.django_db
class TestChatPromptTemplate:
    def test_create_message(self):
        message = {
            "role": "user",
            "template": "hello {name} i will answer {user_input}",
            "input_variables": ["user_input"],
            "partial_variables": {"name": "test user"},
        }

        result = create_message(message)

        assert isinstance(result, TEMPLATE_CLASSES["user"])
        assert result.prompt.partial_variables == {"name": "test user"}

    def test_from_config(self, load_chain):
        config = deepcopy(PROMPT_TEMPLATE)
        chain = load_chain(config)
        assert isinstance(chain, ChatPromptTemplate)
        assert len(chain.messages) == 3
        assert isinstance(chain.messages[0], TEMPLATE_CLASSES["system"])
        assert isinstance(chain.messages[1], TEMPLATE_CLASSES["user"])
        assert isinstance(chain.messages[2], TEMPLATE_CLASSES["assistant"])

@pytest.mark.django_db
class TestLLMChain:
    def test_from_config(self, load_chain, mock_openai_key):
        config = deepcopy(EXAMPLE_CONFIG)
        chain = load_chain(config)

        assert isinstance(chain, LLMChain)
        assert (
            chain.prompt.messages[0].prompt.partial_variables
            == EXAMPLE_CONFIG["config"]["prompt"]["config"]["messages"][0][
                "partial_variables"
            ]
        )
        assert chain.prompt.messages[1].prompt.partial_variables == {}
        assert isinstance(chain.memory, MockMemory)


import cv2
import numpy as np
import logging
from typing import List, Tuple, Union, Generator, Optional
from random import shuffle, uniform
from pathlib import Path
from scipy import ndimage
from functools import lru_cache

SEGMENTATION_DIRECTORY_LOCATION: str = r'E:\Downloads\fish_conservation\segmentation'
# Set this to where you want the images saved
OUTPUT_DIRECTORY_LOCATION: str = r'E:\Downloads\fish_conservation\segmentation\output\\'

def load_output_image(location: str) -> np.ndarray:
    """
    Loads the output image as a grayscale image with one
    channel.
    :param location: The absolute path to the image
    :return:
    """
    image = cv2.imread(location)
    logging.debug(f"image shape: {image.shape}")

    image_converted: np.ndarray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    image_converted: np.ndarray = np.reshape(image_converted, (image_converted.shape[0], image_converted.shape[1], 1))
    logging.debug(f"image converted: {image_converted.shape}")
    return image_converted

def scale_mask(mask: np.ndarray) -> np.ndarray:
    return (mask > 30).astype(int)

def rotate(image: np.ndarray, mask: np.ndarray, deg_range: int) -> Tuple[np.ndarray, np.ndarray]:
    """
    Randomly rotates within the deg_range clockwise or counter-clockwise.
    :param image: image to rotate
    :param mask: mask to rotate the same amount
    :param deg_range:
    :return: (image rotated, mask rotated)
    """
    if deg_range is None:
        return image, mask

    rotation_amount: int = uniform(-deg_range, deg_range)
    image_new = ndimage.rotate(image, rotation_amount, reshape=False)
    mask_new = ndimage.rotate(mask, rotation_amount, reshape=False)
    return image_new, mask_new

@lru_cache(maxsize=None)
def cached_read_image_mask(image_location: str, mask_location: str) -> Tuple[np.ndarray, np.ndarray]:
    """
    A cached function to read both the image and the mask
    :param image_location: The location to load the image
    :param mask_location:  The location to load the corresponding mask
    :return: the image and the mask in that order
    """
    logging.debug("Requesting {}, and {}".format(image_location, mask_location))
    image: np.ndarray = cv2.imread(image_location)
    mask: np.ndarray = load_output_image(mask_location)
    return image, mask

def generate_image_data(batch_size: int,
                        location: str,
                        number_of_images: Optional[int] = None,
                        starting_with: Optional[str] = None,
                        deg_range: Optional[int] = None,
                        save_transformed_images: Optional[bool] = False):
    """
    Generates image data for a fit_generator method of Keras.
    :param deg_range: The range degrees the images can be rotated within randomly
    :param batch_size: The number of images to include in a single batch.
    :param number_of_images: This will allow you to select how many of the images to loop on.
    :param location: The location of the test folder to use, this must have Mask and Fish folders inside.
    :param starting_with: The string the images are expected to start with.
    :return: The images currently
    """

    batch_images: np.ndarray = np.zeros((batch_size, 768, 768, 3))
    batch_masks: np.ndarray = np.zeros((batch_size, 768, 768, 1))

    list_of_image_locations: List[str]
    list_of_mask_locations: List[str]
    list_of_image_locations, list_of_mask_locations = get_images_list(location, starting_with)

    if number_of_images is not None:
        assert len(list_of_image_locations) >= number_of_images, "The number of images  needs " \
                                                                 "to be equal or less than the " \
                                                                 "number in the mask directory."
    list_of_image_locations = list_of_image_locations[:number_of_images]
    list_of_mask_locations = list_of_mask_locations[:number_of_images]
    logging.info(f"list_of_image_locations: {list_of_image_locations}")
    logging.info(f"list_of_mask_locations: {list_of_mask_locations}")

    image_mask_location: List[Tuple[str, str]] = list(zip(list_of_image_locations, list_of_mask_locations))

    # Count the number of times the loop has progressed
    number_of_loops: int = 0

    while True:
        logging.debug("While loop entered.")

        # Shuffle the two image lists together.
        # Stops the order from being memorized.
        logging.debug("Shuffling data")
        shuffle(image_mask_location)

        # Marks the next image container that will be written over.
        placeholder: int = 0

        # Take each of these place them into a batch and yield them
        image_location: str
        mask_location: str
        number_of_images_processed: int = 0
        for image_location, mask_location in image_mask_location:

            # Read the image and mask in
            image: np.ndarray
            mask: np.ndarray
            image, mask = cached_read_image_mask(image_location, mask_location)

            # Only performs transformations after the first loop
            if number_of_loops > 0:
                logging.debug("Rotating data")
                image, mask = rotate(image, mask, deg_range)
                if save_transformed_images:
                    # Save the images
                    save_image(image, number_of_images_processed)
                    save_image(mask, number_of_images_processed, mask=True)
                    number_of_images_processed += 1

            mask: np.ndarray = scale_mask(mask)
            batch_images[placeholder, :, :, :] = image
            batch_masks[placeholder, :, :, :] = mask

            placeholder += 1
            logging.debug(f"placeholder: {placeholder}")

            if placeholder == batch_size:
                placeholder = 0
                yield batch_images, batch_masks

        # This is to handle the final batch that could be shorter than the others
        if placeholder > 0:
            logging.debug("A final small batch is being created.")

            batch_images_small: np.ndarray = batch_images[0:placeholder, :, :, :]
            batch_masks_small: np.ndarray = batch_masks[0:placeholder, :, :, :]

            yield batch_images_small, batch_masks_small

            # Reset for the next set of batches
            placeholder = 0
        number_of_loops += 1

def get_images_list(location_to_train: str, starting_with: Union[str, None]) -> Tuple[List[str], List[str]]:
    """
    Walks through the image and mask folders to obtain two lists of masks and images.
    :param location_to_train:
    :param starting_with:
    :return:
    """
    logging.debug("get_images_list ")

    image_locations: List = []
    mask_locations: List = []

    # Walk through from the location
    location_path: Path = Path(location_to_train)
    image_location: Path = location_path.joinpath("Fish")
    mask_location: Path = location_path.joinpath("Mask")

    assert image_location.exists(), "The 'Fish' folder doesn't exists"
    assert mask_location.exists(), "The 'Mask' folder doesn't exists"

    # Check for what to start with
    image_location_dir: Generator
    if starting_with is not None:
        image_location_dir = image_location.glob(starting_with)
        assert image_location_dir is not None, "The image_location_dir with glob results in None"
    else:
        image_location_dir = image_location.iterdir()

    file_or_directory: Path
    for file_or_directory in image_location_dir:
        if not file_or_directory.is_file():
            continue
        # Check the same file exists in the "Fish" folder
        logging.debug("File found: " + file_or_directory.name)
        if mask_location.joinpath(file_or_directory.name).exists():
            logging.debug("Matching mask found: " + file_or_directory.name)
            mask_locations.append(str(mask_location.joinpath(file_or_directory.name).resolve()))
            image_locations.append(str(image_location.joinpath(file_or_directory.name).resolve()))
            logging.debug("A matching mask was found for file: " + file_or_directory.name)
        else:
            logging.debug("A matching mask was not found for file: " + file_or_directory.name)
    return image_locations, mask_locations

def save_image(image: np.ndarray, number, mask: Optional[bool] = False) -> None:
    image_out: np.ndarray
    name: str
    if mask:
        image_out = image * 255.0
        name = f"{number}_mask.png"
    else:
        image_out = image
        name = f"{number}.png"

    cv2.imwrite(OUTPUT_DIRECTORY_LOCATION + name, image_out)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format='%(name)s - %(levelname)s - %(message)s')
    loop = 0
    for image_batch, mask_batch in generate_image_data(10, SEGMENTATION_DIRECTORY_LOCATION + "\\train", deg_range=180):
        # assert image_batch.shape == (10, 768, 768, 3), f"{str(image.shape)}"
        # assert mask.shape == (10, 768, 768, 1)

        # Using a warning to take note of it.
        logging.info("Completed loop")

        for i in range(image_batch.shape[0]):
            save_image(image_batch[i], i + loop)
            save_image(mask_batch[i], i + loop, mask=True)
        loop +=1
        # Save the image
        # save_image(image_batch[0])


import gym
import numpy as np

from garage.envs.base import Step

class PointEnv(gym.Env):
    """A simple 2D point environment.

    Attributes:
        observation_space (:obj:`gym.spaces.Box`): The observation space
        action_space (:obj:`gym.spaces.Box`): The action space

    Args:
        goal (:obj:`np.ndarray`, optional): A 2D array representing the goal
            position
        done_bonus (float, optional): A numerical bonus added to the reward
            once the point as reached the goal
        never_done (bool, optional): Never send a `done` signal, even if the
            agent achieves the goal.
    """

    def __init__(
            self,
            goal=np.array((1., 1.), dtype=np.float32),
            done_bonus=0.,
            never_done=False,
    ):
        self._goal = np.array(goal, dtype=np.float32)
        self._done_bonus = done_bonus
        self._never_done = never_done

        self._point = np.zeros_like(self._goal)

    @property
    def observation_space(self):
        return gym.spaces.Box(low=-np.inf,
                              high=np.inf,
                              shape=(2, ),
                              dtype=np.float32)

    @property
    def action_space(self):
        return gym.spaces.Box(low=-0.1,
                              high=0.1,
                              shape=(2, ),
                              dtype=np.float32)

    def reset(self):
        self._point = np.zeros_like(self._goal)
        return np.copy(self._point)

    def step(self, action):
        # enforce action space
        a = action.copy()  # NOTE: we MUST copy the action before modifying it
        a = np.clip(a, self.action_space.low, self.action_space.high)

        dist = np.linalg.norm(self._point - self._goal)
        done = dist < np.linalg.norm(self.action_space.low)

        # dense reward
        reward = -dist
        # done bonus
        if done:
            reward += self._done_bonus

        # sometimes we don't want to terminate
        done = done and not self._never_done

        return Step(np.copy(self._point), reward, done)

    def render(self, mode='human'):
        pass


n = int(input())

xy = []
p = []
for _ in range(n):
    x, y, pi = map(int, input().split())
    xy.append([x, y])
    p.append(pi)

INF = 1 << 30
def judge(s):
    dist = [[INF]*n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            xi, yi = xy[i]
            xj, yj = xy[j]
            if p[i] * s >= abs(xi - xj) + abs(yi - yj):
                dist[i][j] = 1
    # ワーシャルフロイド法
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    for i in range(n):
        if dist[i].count(INF) == 0:
            return True
    return False
# 二分探索
left = 0
right = 1 << 32
while right - left > 1:
    mid = (right + left) >> 1
    if judge(mid):
        right = mid
    else:
        left = mid
print(right)


import turtle

for x in range(8):
    turtle.forward(100)
    turtle.left(45)
turtle.penup()
turtle.goto(0,100)

turtle.write('STOP', font=("Arial", 30, "normal"))

import time
time.sleep(5)


from django.urls import path
from .views import FuncionariosList, FuncionariosEdit, FuncionariosDelete, FuncionariosNovo

urlpatterns = [
    path('funcionarios', FuncionariosList.as_view(), name='list_funcionarios'),
    path('editar/<int:pk>', FuncionariosEdit.as_view(), name='update_funcionarios'),
    path('deletar/<int:pk>', FuncionariosDelete.as_view(), name='delete_funcionarios'),
    path('novo', FuncionariosNovo.as_view(), name='create_funcionarios'),
]


# -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 13:52:49 2020

@author: shi9
"""

import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '../')

import SE
import QP
#import Asympt_nD
import matplotlib.pyplot as plt
#import sys
import numpy as np
#from IPython import get_ipython

from decimal import Decimal, getcontext

# This script is used to drive member functions in QP
# to find phase space islands/separatrices and plot results
######################################
# run mode
# mode =  1 : run all tests of constituent functions
#             1D Scan, xCritical, critical solutions, 2D scan
#        -1 : run quick tests of constituent functions
#             1D Scan, xCritical
#             no critical solutions
#             no low-resolution contour
#
#         2 : run Boundary and plot figure.
#             find phase space island/separatrix for given A and R
#        -2 : read boundary data and plot figure
#
#        otherwise: only load instances of class

mode = -1

######################################
# dimension of the problem
dim = 2

# parameters of ODE
R = 10.0 # source size
A = 247.5735556419664 # source amplitude

# final time for plot of critical cases
tf = 2*max(1,R)

# customization of search grid
#customize = True
customize = False

# customized search parameters
if customize:
    # initial conditions & center of search box, decimal precision
    # specify high precision using string
    q0D=Decimal('1.4')
    p0D=Decimal('-1.4')

    # box angle
    theta = 10
    # box size
    Lx = 6
    Ly = 3
    # number of grid points
    Nx = 33
    Ny = 33

    # expected number of islands in the search interval
    NI = 1
    # expected number of separatrix in the search interval
    NS = 1
    # if automatically scan in addition to customized scan
    ifauto = True

# for SolveUntil
Ntmax = 2**24
epsilon = 1e-2

# decimal precision
prec = 28
getcontext().prec = prec # default is 28
# for QP convergence during refinement
epsilon_bisection = 10**(-prec+5)
#epsilon_bisection = 1e-6

if abs(mode)==2:
    # file path
    #fhead = f'../../data/{dim}D/manual/e{epsilon}/'
    fhead = '../../data/1D/manual/'
    # file tail
    ftail = f'{dim}D_R{R}_A{A}_N{Ntmax}_e{epsilon}.txt'

    # file namefor island boundary
    fnameQPb = fhead + 'Boundary' + ftail
    # file name for separatrix
    fnameQPs = fhead + 'Separatrix' + ftail

# rescaling q = f + a*w, t = u*z
# defaults are f=0, a=1, and u=1
f, a, u = 0, 1, 1
#f = float(q0D) # requires float
#a = 1e-12
#u = 1

# print debug messages
#ifdebug = False
ifdebug = True

# plot equal scale in q and p directions
equal = True
#equal = False

# parameters for making plots
fontsize = 12 # fontsize of labels
color = 'r' # color of scatter plot
markersize = 8

##############################################################################
##############################################################################
# specify the problem
ode = SE.ODE(R, A, dim, f=f, a=a, u=u)

# instantiate island
island = QP.Island(ode, Ntmax=Ntmax, epsilon=epsilon)
# update default parameters
island.epsilon_bisection = epsilon_bisection
if customize:
    island.NC = 2*NI
    island.NS = NS
#island.Nsample_refine = 101
repr(island)
# updating plotting parameters
island.fontsize = fontsize
island.color = color
island.markersize = markersize

# specify search box
if customize:
    sample = QP.Sample(theta=theta,Nx=Nx,Ny=Ny,Lx=Lx,Ly=Ly,q0D=q0D,p0D=p0D)
else:
    sample = QP.Sample() # default low resolution Nx=Ny=33
    sample.auto(ode) # load auto parameters suggested by ODE in 1D case

##############################################################################
if abs(mode) == 1:# run test of constituent functions
    # test scan in x direction, starting from t=0
    if customize:
        xsample = QP.Sample(Lx=Lx,Ly=Ly,q0D=q0D,p0D=p0D,ifauto=ifauto,\
                            Nx=Nx,Ny=1,theta=theta)
    else:
        xsample = None

    print(40*'#'+'\nDetermine critical points,customize =',customize)
    plt.figure()
    xcD,xfc,xsD = island.xCritical(sample=xsample, ifplot=True, debug=ifdebug)
    print(f'xRefine depth = {island.depth}')

if mode==1:
    ###########################
    print(40*'#'+'\nPlotting critical solutions...')
    # plot near criticl cases (boundary + separatrix), starting from t=0
    ncs = len(xcD) + len(xsD)
    if ncs>0: # if there are critical cases
        # concatenate numpy array
        xcsD = np.concatenate((xcD, xsD))
        # time step
        dt = island.dt  # dt = abs(epsilon)*min(1,R)
        # number of time steps
        Nt = int(tf/dt)
        plt.figure()
        for i in range(ncs):
            # default t0=0
            cds = SE.Initial(Nt=Nt, dt=abs(dt), q0D=xcsD[i], p0D=0)
            sol = SE.Solution(ode, cds, Ntmax=Ntmax, epsilon=epsilon)
            sol.fontsize=fontsize
            ttmp, yntmp = sol.Solve(ifplot=True)

        plt.ylim((-1.5, 1.5))
        #plt.legend(bbox_to_anchor=(2, 0.4), loc='right', fontsize=fontsize)
        #plt.legend(loc='best', fontsize=fontsize)
        plt.axhline(y=0, color='grey')
        plt.axhline(y=-1, color='grey', linestyle=':')
        plt.axhline(y=1, color='grey', linestyle=':')
        #plt.show()

    ###########################
    print(40*'#'+'\nPloting phase space island using contour...')
    # plot phase space island using contour
    if sample.Nx>1 and sample.Ny>1:
        plt.figure()
        Q, P, Flags = island.Scan(sample, ifplot=True)
        # mark search lines along x and y directions
        sample.drawbox()
        plt.show()

##############################################################################
# find phase space island and save data, starting from t=0
if mode==2 or (mode==-2 and dim>1 and (not customize)):
    print('Computing boundary of phase space island, '+repr(ode))
    print('customize = ', customize)
    # compute boundary in q-p space
    island.Boundary(sample)
    # write data
    if dim == 1 or customize:
        island.save(fnameQPb, sample,'boundary')
        island.save(fnameQPs, sample,'separatrix')
    # report boundary info
    if dim > 1 and (not customize):
        print('qb =', island.qbD)
        print('asymptotics =', island.fb)
        print('qs =', island.qsD)

if abs(mode) == 2: # read data and plot phase space island
    print('Reading boundary and separatrix files and plot figure...')
    # 1D read file
    if dim==1 or (dim>1 and customize):
        island.load(fnameQPb)
        island.load(fnameQPs)
    # plot island boundary
    #plt.figure()
    island.plot(data='boundary', equal=equal)
    island.plot(data='separatrix', equal=equal)
    # plot search box
    sample.Ny = max(sample.Ny,2) # also draw box for n-D case
    sample.drawbox()
    #plt.show()


# -*- coding:utf-8 -*-
from collections import Counter
import pickle
import numpy as np
import tensorflow.contrib.keras as kr

# tag dict
tag2label = {"O": 0, "B-PER": 1, "I-PER": 2, "B-LOC": 3, "I-LOC": 4, "B-ORG": 5, "I-ORG": 6}

def read_data(filename):
    content, label, sentences, tag = [], [], [], []
    with open(filename, encoding='utf-8') as file:
        lines = file.readlines()
    for eachline in lines:
        if eachline != '\n':
            [char, tag_] = eachline.strip().split()
            sentences.append(char)
            tag.append(tag_)
        else:
            content.append(sentences)
            label.append(tag)
            sentences, tag = [], []
    return content, label

def build_vocab(filenames, vocab_size=5000):
    wordlist = []
    word = {}
    word['<PAD>'] = 0
    j = 1
    for filename in filenames:
        content, _ = read_data(filename)
        for sen_ in content:
            wordlist.extend(sen_)
    counter = Counter(wordlist)
    count_pari = counter.most_common(vocab_size)
    word_, _ = list(zip(*count_pari))
    for key in word_:
        if key.isdigit():
            key = '<NUM>'
        if key not in word:
            word[key] = j
        j += 1

    word['<UNK>'] = j
    with open('word2id.pkl', 'wb') as fw:  # 将建立的字典 保存
        pickle.dump(word, fw)
    return word

def sequence2id(filename, word2id_file):
    content2id, label2id = [], []
    content, label = read_data(filename)
    with open(word2id_file, 'rb') as fr:
        word = pickle.load(fr)
    for i in range(len(label)):
        label2id.append([tag2label[x] for x in label[i]])
    for j in range(len(content)):
        w = []
        for key in content[j]:
            if key.isdigit():
                key = '<NUM>'
            elif key not in word:
                key = '<UNK>'
            w.append(word[key])
        content2id.append(w)
    return content2id, label2id

if __name__ == '__main__':
    sentences, labels = read_data('train_data')
    print("corpus including {0} sentences".format(len(sentences)))

    file_names = ['train_data', 'test_data']
    word2id = build_vocab(file_names)
    print("words in corpus: {}".format(len(word2id)))

    content2id, label2id = sequence2id('train_data')
    print('sentence example: {}'.format(content2id[1]))
    print('label example: {}'.format(label2id[1]))


# -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 17:40:22 2018

@author: Eric
"""
import pandas as pd
import numpy as np

def merge(name):
    new = '.\\all_outputs\\new_out_' + name + '.csv'
    to_be = '.\\all_outputs\\out_' + name + '.csv'
    old = '.\\all_outputs\\old_out_' + name + '.csv'

    # read in first data
    dfo = pd.read_csv(old, header = None, na_values= "", engine = 'python')
    dfo.fillna("", inplace=True)
    dfo = np.asarray(dfo)

    # read in second data
    dfn = pd.read_csv(new, header = None, na_values= "", engine = 'python')
    dfn.fillna("", inplace=True)
    dfn = np.asarray(dfn)

    # New data formating
    dfo = np.append(dfo, dfn[len(dfo) - 1:], axis = 0)

    df = pd.DataFrame(data=dfo[1:], columns=dfo[0])

    df.to_csv(to_be, index = False)
    return None

names = ['krystie', 'sergii']
#names = ['sergii']
for n in names:
    merge(n)


import numpy as np
from abc import ABC, abstractmethod

from constants import THETA, UTILITY_STEP
from helpers import is_higher_then_all_in_by

class ProbabilisticClassifier(ABC):
    def __init__(self, hard_fp=1):
        super().__init__()
        self.classifiers = []
        self.probabilities = np.array([])
        self.fp = []
        self.hard_fp = hard_fp
        self.logger = None

    def initialize(self, negative_data, negative_data_utility, positive_data, positive_data_utility, logger,
                   val_data=None):
        """
        Creates initial classifier

        Parameters
        ----------
        negative_data : np.array
            Data to be classified (all labeled 1)
        negative_data_utility : np.array
            utility values of negative data
        positive_data : np.array
            Data to be classified (all labeled 0)
        positive_data_utility : np.array
            utility values of positive data

        validation_data : np.array
            Data to be used for cross-validation
        """
        self.negative_data = negative_data
        self.negative_data_weights = negative_data_utility
        self.val_data = val_data

        self.negative_data = np.vstack(
            (self.negative_data, np.zeros(self.negative_data[0].shape), 10 * np.ones(self.negative_data[0].shape)))
        self.negative_data_weights = np.hstack((self.negative_data_weights, 100, 100))
        self.update(positive_data, positive_data_utility, np.array([1]), np.empty([1, 0]))
        self.negative_data = self.negative_data[:-2, :]
        self.negative_data_weights = self.negative_data_weights[:-2]
        self.logger = logger

    def classify_all(self, point):
        """
        Evaluate point on all classifiers.

        Parameters
        ----------
        point : vector
            point to be evaluated

        Returns
        -------
        np.vector
            zero-one vector, each position in vector is one classifier evaluation of a point,
            zero for positive, one for negative
        """
        point = point.reshape(1, -1)
        return np.fromiter(map(lambda x: self.classify_by_one_classifier(point, x), self.classifiers), dtype=np.float64)

    def classify(self, point):
        """
        Probabilistic evaluation on classifiers.

        Parameters
        ----------
        point : vector
            point to be evaluated

        Returns
        -------
        float
            probability of negative class (negative = benign point)
        """
        if self.probabilities.shape[0] == len(self.classifiers):
            #print(f"self.classify_all(point) = {self.classify_all(point)}")
            #print(
            #    f"self.classify_all(point).dot(self.probabilities) = {self.classify_all(point).dot(self.probabilities)}")
            return self.classify_all(point).dot(self.probabilities)

    def update_support(self, support):
        """
        Sets new probabilities on classifiers.

        Parameters
        ----------
        support : vector
            probabilities of classifiers
        """
        self.probabilities = support

    def support_size(self):
        """
        Gets the size of actual support.

        Returns
        ----------
        int
            number of the classifiers with probability > 0
        """
        return np.sum(self.probabilities > THETA)

    def classify_last(self, point):
        """
        Evaluate point on the last classifier.

        Parameters
        ----------
        point : vector
            point to be evaluated

        Returns
        -------
        int
            zero for positive, one for negative
        """
        point = point.reshape(1, -1)
        return self.classify_by_one_classifier(point, self.classifiers[-1])

    @abstractmethod
    def classify_by_one_classifier(self, point, classifier):
        """
        Evaluate point on the classifier.

        Parameters
        ----------
        points : np.array(n,d)
            point to be evaluated
        classifier
            classifier on which the point has to be evaluated

        Returns
        -------
        float
            number from <0, 1> interval - zero for positive, one for negative
        """
        pass

    def all_classifiers_utilities(self, att_support, game_matrix):
        """
        Gets expected utilities of all classifiers.

        Parameters
        ----------
        att_support : np.array
            Actual attackers strategy
        game_matrix : np.array
            Game matrix

        Returns
        -------
        np.array
            expected utilities of classifiers
        """
        if att_support.shape[0] < game_matrix.shape[0]:
            att_support = np.pad(att_support, (0, 1), 'constant')

        utilities = att_support.dot(game_matrix)

        return utilities

    def get_matrix_column(self, new_classifier, positive_data, positive_data_utility):
        """
        Gets column of game matrix corresponding to the new classifier

        Parameters
        ----------
        new_classifier : classifier
            new classifier for evaluation
        positive_data : np.array
            List of all attackers points
        positive_data_utility : np.array
            Utilities of all attackers points

        Returns
        -------
        np.array
            new column of matrix
        """
        column = np.float64(
            np.apply_along_axis(lambda x: self.classify_by_one_classifier(x.reshape(1, -1), new_classifier),
                                1, positive_data))
        column *= np.float64(positive_data_utility).reshape(-1, 1)
        return column

    def classifier_utility(self, att_support, column):
        """
        Gets expected utility of new classifier.

        Parameters
        ----------
        att_support : np.array
            Actual attackers strategy
        column : np.array
            new column of the matrix corresponding to the newly added classifier

        Returns
        -------
        float
            expected utility of classifier
        """
        new_utility = att_support.dot(column)
        return new_utility

    def expand_classifiers(self, new_classifier, positive_data, positive_data_utility, att_support, game_matrix,
                           utilities=None, new_utility=None, column=None, thld=UTILITY_STEP):

        """
        Expands set of classifiers by a new one, if it has higher utility than thld.

        Parameters
        ----------
        new_classifier : classifier
            new classifier for evaluation
        positive_data : np.array
            List of all attackers points
        positive_data_utility : np.array
            Utilities of all attackers points
        att_support : np.array
            Actual attackers strategy
        game_matrix : np.array
            Game matrix
        utilities : np.array
            expected utilities of classifiers
        new_utility : float
            expected utility of new classifier
        column : np.array
            new column of the matrix corresponding to the newly added classifier
        thld : float
            threshold on difference between utilities

        Returns
        -------
        np.array
            new column of matrix or None, if new classifier is not added
        """

        if utilities is None:
            utilities = self.all_classifiers_utilities(att_support, game_matrix)

        if new_utility is None:
            column = self.get_matrix_column(new_classifier, positive_data, positive_data_utility)
            new_utility = self.classifier_utility(att_support, column)

        if not self.logger is None:
            self.logger.info(f"classifier utilities = {utilities}")
            self.logger.info(f"new classifier utility = {new_utility}")

        try:
            if not self.logger is None:
                self.logger.debug(f"tree {new_classifier.tree_.threshold}")
        except:
            pass

        if is_higher_then_all_in_by(utilities, new_utility,
                                    thld):  # np.all(np.abs(utilities - new_utility) > thld): #distance of utilities
            if not self.logger is None:
                self.logger.info(f"classifier added")
            self.classifiers.append(new_classifier)
            return column
        if not self.logger is None:
            self.logger.info(f"no new classifier added")
        return None

    @abstractmethod
    def update(self, positive_data, positive_data_utility, att_support, game_matrix):
        """
        Finds best classifier for data on the actual support.

        Parameters
        ----------
        positive_data : np.array
            data of positive class
        positive_data_utility : np.array
            utilities of points of positive class
        att_support
            probabilities of positive data - weights of points
        game_matrix
            utility matrix of the game

        Returns
        -------
        np.array
            utilities of points classified by new classifier, None if classifier not added
        """
        pass

    def prepare_data(self, positive_data, positive_data_utility, att_support):
        """
        Prepare data, labels and data weights for the classification

        Parameters
        ----------
        positive_data : np.array
            data of positive class
        positive_data_utility : np.array
            utilities of points of positive class
        att_support
            probabilities of positive data - weights of points

        Returns
        -------
        np.array
            all data for training
        np.array
            all data for validation
        np.array
            labels of data
        np.array
            weights of data
        """
        data = np.concatenate((self.negative_data, positive_data), axis=0)
        if self.val_data is None:
            validation_data = data
        else:
            data = np.concatenate((self.val_data, positive_data), axis=0)
        weights = self.negative_data_weights
        # weights = np.ones(self.negative_data.shape[0])

        att_weights = att_support * positive_data_utility
        weights = np.concatenate((weights, att_weights), axis=0)

        if self.logger:
            self.logger.debug(f"prepare data positive_data_utility = {positive_data_utility}")
            self.logger.debug(f"prepare data att_support = {att_support}")
            self.logger.debug(f"prepare data att_weights = {att_weights}")
            self.logger.debug(f"prepare data weights = {weights}")

        labels = np.ones(self.negative_data.shape[0], dtype=np.int)
        labels = np.concatenate((labels, np.zeros(positive_data.shape[0], dtype=np.int)), axis=0)

        return data, validation_data, labels, weights

    @abstractmethod
    def equals(self, cls1, cls2):
        """
        Compares, if two classifiers equals

        Parameters
        ----------
        cls1 : classifier
            first classifier
        cls 2 : classifier
            second classifier

        Returns
        -------
        bool
            equality of classifiers
        """
        return cls1 == cls2
        # TODO Needs overriding

    def used(self, cls):
        """
        Check, if the same classifier already is in the list

        Parameters
        ----------
        cls : classifier
            first classifier

        Returns
        -------
        bool
            lis contain cls
        """
        return any(map(lambda x: self.equals(cls, x), self.classifiers))

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

    def get_fp(self):
        """
        Returns the false-positive rate for all classifiers

        Returns
        -------
        float list
            list of all false-positive rates for all classifiers
        """
        if len(self.fp) < len(self.classifiers):
            for clf in self.classifiers[len(self.fp):]:
                classification = self.classify_by_one_classifier(self.negative_data, clf)
                self.fp.append(np.sum(np.abs(1 - classification)) / self.negative_data.shape[0])
                if not self.val_data is None:
                    classification = self.classify_by_one_classifier(self.val_data, clf)
                    self.fp[-1] += np.sum(np.abs(1 - classification)) / self.val_data.shape[0]
        return self.fp


# Uses python3
def edit_distance(a, b):
    #write your code here
    c = list()
    for i in range(len(a)+1):
        ci = list()
        for j in range(len(b)+1):
            ci.append(0)
        c.append(ci)
    for i in range(len(a)+1):
        for j in range(len(b)+1):
            if i == 0:
                c[i][j] = j
            elif j == 0:
                c[i][j] = i
            elif a[i-1] == b[j-1]:
                c[i][j] = c[i-1][j-1]
            else:
                c[i][j] = 1 + min(c[i][j-1], c[i-1][j], c[i-1][j-1])
    return c[len(a)][len(b)]

if __name__ == "__main__":
    print(edit_distance(input(), input()))


# -*- coding: utf-8 -*-
"""
Created on Wed Dec  6 15:48:01 2017

@author: ovj

%reset does magic

"""

import numpy as np
import matplotlib.pyplot as plt
import RamanFittingFunctions as RamFit #current WD correctly set? os.getcwd()
import scipy.constants as cst
import math

h = np.arange(0,1001,1)
WLin = [488,532,785]
Plotting =["b-","g-","r-"]
nALD = 1.650 # Corina Barbos, Danièle Blanc-Pelissier, Alain Fave & Elisabeth Blanquet et al. Characterization of Al2O3 Thin Films Prepared by Thermal ALD.
nAIR = 1.0
step = np.zeros((1,1001))
step[0,580:680]=1

IG = np.sin(4*math.pi*h/RamFit.relcm2nm(532,1685))+1.1
I2D = np.sin(4*math.pi*h/RamFit.relcm2nm(532,2670))+1.1

RamFit.relcm2nm(514.5,1586)
Ephoton = 10**9*(cst.h*cst.c)/(cst.e*1240) # energy in eV
RamFit.nm2Ephoton(1240)

fig1 = plt.figure("input")     # a new figure window
ax1 = fig1.add_subplot(111)# ax1 is an Axes element ("plotting Window"). Specify (nrows, ncols, axnum)
ax1.set_title("input intensities")
ax1.set_xlabel("height [nm]")
ax1.set_ylabel("intensity [arb.u.]")
ax1.plot(h,IG)
ax1.plot(h,I2D)
fig1.show()

fig2 = plt.figure("relInt")     # a new figure window
ax2 = fig2.add_subplot(111)# ax1 is an Axes element ("plotting Window"). Specify (nrows, ncols, axnum)
ax2.set_title("I2D/IG")
ax2.set_xlabel("height [nm]")
ax2.set_ylabel("I2D/IG [arb.u.]")
ax2.plot(h,I2D/IG)
fig2.show()

fig3 = plt.figure("Iin")     # a new figure window
ax3 = fig3.add_subplot(111)# ax1 is an Axes element ("plotting Window"). Specify (nrows, ncols, axnum)
ax3.set_title("I_incident vs. h - ALD")
ax3.set_xlabel("height [nm]")
ax3.set_ylabel("I_incident [arb.u.]")

for WL in WLin:
    Iin = np.sin(2*math.pi*h/WL*nALD)**2
    ax3.plot(h,Iin)

ax3.plot(h,step[0][:])
fig3.show()

fig4 = plt.figure("Iin")     # a new figure window
ax4 = fig4.add_subplot(111)# ax1 is an Axes element ("plotting Window"). Specify (nrows, ncols, axnum)
ax4.set_title("I_incident vs. h - Air/Vac")
ax4.set_xlabel("height [nm]")
ax4.set_ylabel("I_incident [arb.u.]")

for i,WL in enumerate(WLin):

    Iin = np.sin(2*math.pi*h/WL*nAIR)**2
    ax4.plot(h,Iin,Plotting[i])

ax4.plot(h,step[0][:],'k-')
fig4.show()


from src.config import *
import src.state as state
from src.components.PopUp import PopUp
from src.components.Button import Button

class Data: pass

# Menampilkan popup daftar level.
class BoxLevels(PopUp):

    def __init__(self):
        super().__init__('Levels', 'assets/images/backgrounds/levels.png')
        self._load_local_components()

    def _load_local_components(self):
        [bg_size_x, bg_size_y] = self.background.get_size()

        # Mengambil lokasi gambar.
        path_level_lock = 'assets/images/buttons/levels/lock.png'
        path_levels = []
        for i in range(8): path_levels.append(f'assets/images/buttons/levels/{i+1}.png')

        # Inisialisasi tombol level.
        self.__btn_levels = []
        btn_pos_x = (WIDTH/2) - (bg_size_x/2) + 136
        btn_pos_y = (HEIGTH/2) - (bg_size_y/2) + 160
        for i in range(8):
            btn = Data()
            btn.level = i + 1
            btn.active = Button(path_levels[i], [btn_pos_x, btn_pos_y], command_data=self.__start_level, data=btn.level, index=2)
            btn.not_active = Button(path_level_lock, [btn_pos_x, btn_pos_y])
            self.__btn_levels.append(btn)
            btn_pos_x += 220
            if not (i+1) % 4:
                btn_pos_x = (WIDTH/2) - (bg_size_x/2) + 136
                btn_pos_y += 140

    def __start_level(self, index_level):
        state.LEVEL_RUNNING = index_level
        state.PAGE_FRAME = -1
        state.PAGE = 'game-run'

    def render(self, screen):
        if self._show:
            self.render_popup(screen)
            for i in range(len(self.__btn_levels)):
                btn = self.__btn_levels[i]
                if (i+1) <= state.CURRENT_LEVEL: btn.active.render(screen)
                else: btn.not_active.render(screen)


from typing import Any, Union

import redis

from tracardi.config import RedisConfig
from tracardi.domain.resources.redis_resource import RedisCredentials
from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, Documentation, PortDoc, Form, FormField, \
    FormGroup, FormComponent
from tracardi.service.plugin.runner import ActionRunner
from tracardi.service.storage.driver.elastic import resource as resource_db
from tracardi.service.storage.redis.collections import Collection
from .model.config import Config
from tracardi.service.storage.redis_client import RedisClient
from tracardi.service.plugin.domain.result import Result
from tracardi.service.secrets import b64_decoder

def validate(config: dict) -> Config:
    return Config(**config)

class ReadFromMemoryAction(ActionRunner):

    client: Union[RedisClient, Any]
    config: Config

    async def set_up(self, init):
        self.config = validate(init)
        if self.config.resource.id == "":
            self.client = RedisClient()
        else:
            resource = await resource_db.load(self.config.resource.id)
            credentials = resource.credentials.get_credentials(self, output=RedisCredentials)

            uri = RedisConfig.get_redis_uri(
                credentials.url,
                credentials.user,
                credentials.password,
                credentials.protocol,
                credentials.database
            )
            self.client = redis.from_url(uri)

    async def run(self, payload: dict, in_edge=None) -> Result:
        try:
            dot = self._get_dot_accessor(payload)
            key = dot[self.config.key]
            prefix = self.config.prefix.strip()
            if prefix:
                key = f"{Collection.plugin_memory}{prefix}:{key}"
            else:
                key = f"{Collection.plugin_memory}{key}"
            result = self.client.get(name=key)
            if result is None:
                return Result(port="not-exists", value=payload)
            return Result(port="success", value={"value": b64_decoder(result)})

        except Exception as e:
            self.console.error(str(e))
            return Result(port="error", value={"message": str(e)})

def register() -> Plugin:
    return Plugin(
        start=False,
        spec=Spec(
            module=__name__,
            className='ReadFromMemoryAction',
            inputs=["payload"],
            outputs=["success", "not-exists", "error"],
            version='0.8.0',
            license="MIT + CC",
            author="Dawid Kruk, Risto Kowaczewski",
            init={
                "resource": {
                    "name": "",
                    "id": ""
                },
                "key": "",
                "prefix": ""
            },
            manual="read_from_memory_action",
            form=Form(
                groups=[
                    FormGroup(
                        name="Read from memory",
                        fields=[
                            FormField(
                                id="resource",
                                name="Resource",
                                description="Select remote redis server or leave it empty to read from local server.",
                                component=FormComponent(type="resource", props={"label": "Redis server", "tag": "redis"})
                            ),
                            FormField(
                                id="key",
                                name="Key",
                                description="Provide a key where the data will be stored. Think of a “key” as a "
                                            "unique identifier and a “value” as whatever data you want to associate "
                                            "with that key. Key can ba a value from profile, event, etc.",
                                component=FormComponent(type="dotPath", props={"label": "Key"})
                            ),
                            FormField(
                                id="prefix",
                                name="Key prefix",
                                description="Type key prefix if you would like to store different values for the "
                                            "same key. Key prefix can be any string. Leave empty if you do no need "
                                            "to prefix the key.",
                                component=FormComponent(type="text", props={"label": "Prefix"})
                            )
                        ]
                    )
                ]
            )
        ),
        metadata=MetaData(
            name='Read from Redis',
            desc='Reads value with given key from cross-instance memory.',
            icon='redis',
            group=["Redis"],
            tags=['redis'],
            documentation=Documentation(
                inputs={
                    "payload": PortDoc(desc="This port takes payload object.")
                },
                outputs={
                    "success": PortDoc(desc="This port returns data from memory if data was successfully read."),
                    "not-exists": PortDoc(desc="This port returns payload if data does not exist."),
                    "error": PortDoc(desc="This port returns some error detail if there was an error while reading data"
                                          " from memory.")
                }
            )
        )
    )


# -*- coding: utf-8 -*-
import logging
import requests
from werkzeug import urls
from odoo import _, fields, models
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

class PaymentProvider(models.Model):
    """inherit model of payment provider and add fields"""
    _inherit = 'payment.provider'

    code = fields.Selection(
        selection_add=[('multi_safe_pay', "multi safe pay")],
        ondelete={'multi_safe_pay': 'set default'})
    api_key = fields.Char(string="API Key")

    def _msp_make_request(self, endpoint, data=None, method='POST'):
        """ Make a request at multisafepay endpoint"""
        self.ensure_one()
        endpoint = f'/v1/json/{endpoint.strip("/")}'
        url = urls.url_join('https://testapi.multisafepay.com/', endpoint)
        headers = {
            "Accept": "application/json",
            "api-key": self.api_key,
            "Content-Type": "application/json",
        }
        try:
            response = requests.request(method, url, json=data, headers=headers,
                                        timeout=60)
        except requests.exceptions.RequestException:
            _logger.exception("unable to communicate with MultiSafePay: %s",
                              url)
            raise ValidationError("MultiSafePay: " + _(
                "Could not establish the connection to the API."))
        return response.json()


# encoding=utf-8
import random,os
from PIL import Image

'''
Delete non-jpg files
'''
def DeleteNoJPGFile(dir):
    w = os.walk(dir)
    for path,subpath,files in w:
        for file in files:
            ext = os.path.splitext(file)[1]
            if ext.lower() != '.jpg':
                fullpath = os.path.join(path,file)
                os.remove(fullpath)
                print('delete {0}'.format(fullpath))

'''
Rename file name with prefix and 6 bit number
'''
def RenameFileName(dir,prefix='logo_'):
    w = os.walk(dir)
    num = 1
    for path, subpath, files in w:
        for file in files:
            ext = os.path.splitext(file)[1]
            newfileename = "{0}{1}.jpg".format(prefix,'%06d'%(num))
            num=num+1
            if ext.lower() == '.jpg':
                fullpath = os.path.join(path, file)
                newpath = os.path.join(path,newfileename )
                print(fullpath,newpath)
                os.rename(fullpath,newpath)
                print('rename {0} to {1}'.format(fullpath,newfileename))
'''
Rename directiory name with frefix and 2 bit number
'''
def RenameDir(dir,prefix='sam_'):
    w = os.walk(dir)
    num = 0
    for path, subpath, files in w:
        for sp in subpath:
            newpath = "{0}{1}".format(prefix,'%02d'%(num))
            num=num+1
            print(subpath,newpath)
            os.rename(os.path.join(path,sp),os.path.join(path,newpath))
            print('rename {0} to {1}'.format(subpath,newpath))

'''
Delete the duplicate file, using the file hash method
'''
import hashlib,shutil
def DeleteDuplx(dir):
    backdir = os.path.join(r'D:\img\samples\duplicate')
    if not os.path.exists(backdir):
        os.makedirs(backdir)

    h = hashlib.md5
    picSet = {}

    w = os.walk(dir)
    num = 1
    for path, subpath, files in w:
        for file in files:
            ext = os.path.splitext(file)[1]
            num = num + 1
            if ext.lower() == '.jpg':
                fullpath = os.path.join(path, file)

                picMd5 = ''
                with open(fullpath, 'rb') as pic:
                    picMd5 = hashlib.md5(pic.read()).hexdigest()

                if picMd5 in picSet:
                    shutil.move(fullpath,os.path.join(backdir,file))
                    print('move {0} to {1}!'.format(fullpath,backdir))
                else:
                    picSet[picMd5]=fullpath
                    # print('put {0} to dictionary,and the MD5 is : {1}'.format(fullpath,picMd5))
'''
Resize image size and save as file with prefix and 6 bit number
'''
def Resize(dir,targetdir,width,height,prefix='sam_'):
    if not os.path.exists(targetdir):
        os.makedirs(targetdir)

    num = 0
    w = os.walk(dir)
    for path, subpath, files in w:
        for file in files:
            ext = os.path.splitext(file)[1]
            if ext.lower() == '.jpg':
                fullpath = os.path.join(path, file)
                img = Image.open(fullpath)
                out =img.resize((width,height),Image.ANTIALIAS)
                newfilename = "{0}{1}.jpg".format(prefix,'%06d'%(num))
                num = num+1
                resizedir =os.path.join(targetdir,newfilename)
                out.save(resizedir)

                print('resize {0} to {1}'.format(file,resizedir))

# copy all file to targetdir
def CopyFile(sourdir,targetdir,prefix='m_'):
    if not os.path.exists(targetdir):
        os.makedirs(targetdir)
    num = 0
    w = os.walk(sourdir)
    for path,subpath,files in w:
        for file in files:
            fullpath = os.path.join(path,file)
            newfilename = '{}{}.jpg'.format(prefix,'%06d'%(num))
            tarfullpath = os.path.join(targetdir, newfilename)
            num+=1
            shutil.copy(fullpath, tarfullpath)
            print('move {0} to {1}!'.format(fullpath, tarfullpath))
# copy source file with regurl experssion to target
import re
def CopyFile3(sourdir,targetdir,sourRE = r'\\sam_\d\d',prefix='m_'):
    if not os.path.exists(targetdir):
        os.makedirs(targetdir)
    num = 0
    w = os.walk(sourdir)

    for path,subpath,files in w:
        print(path)
        if re.match(sourRE,path) is  not None:# and re.match('.*sam_\d{2}_\d',path) is None:
            print(path)
            # for file in files:
            #     fullpath = os.path.join(path,file)
            #     newfilename = '{}{}.jpg'.format(prefix,'%06d'%(num))
            #     tarfullpath = os.path.join(targetdir, newfilename)
            #     num+=1
            #     shutil.copy(fullpath, tarfullpath)
            #     print('move {0} to {1}!'.format(fullpath, tarfullpath))

#copy source dir with postfix to targetdir
def CopyFile(sourdir,postfix,targetdir,prefix='m_'):
    if not os.path.exists(targetdir):
        os.makedirs(targetdir)
    num = 0
    w = os.walk(sourdir)
    for path,subpath,files in w:
        print(path)
        if path.endswith(postfix):

            for file in files:
                fullpath = os.path.join(path,file)
                newfilename = '{}{}.jpg'.format(prefix,'%06d'%(num))
                tarfullpath = os.path.join(targetdir, newfilename)
                num+=1
                shutil.copy(fullpath, tarfullpath)
                print('move {0} to {1}!'.format(fullpath, tarfullpath))

if __name__ == '__main__':
    # RenameDir(r'D:\img\samples\resultbyimg')

    dir = r'D:\img\cnnSamples\nor'
    RenameFileName(dir,prefix='nor_')

    # sd = r'D:\img\samples\mil by m\mil sam00-22'
    # td = r'D:\img\samples\mil by m\mil_by_m'
    # CopyFile3(sd,td,sourRE='sam_\d[2][^_]',prefix='m_')

    # dir = r'D:\img\samples\normal'
    # targetdir = r'D:\img\samples\nor_100X100'
    #
    # Resize(dir,targetdir,100,100,prefix='nor_')
    #
    # # DeleteNoJPGFile(path)
    # # RenameFileName(path,'normal_')
    #
    # DeleteDuplx(path)


class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        n = len(nums)
        total = 0
        res = float('-inf')
        for i in range(n):
            total += nums[i]
            if i >= k:
                total -= nums[i - k]
            if i >= k - 1:
                res = max(res, total)
        return res / k


from collections import defaultdict

t = int(input())

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, a):
        if a == self.parent[a]:
            return a
        self.parent[a] = self.find(self.parent[a])
        return self.parent[a]

    def union(self, a, b):
        parent_a = self.find(a)
        parent_b = self.find(b)
        if parent_a != parent_b:
            if self.size[parent_a] < self.size[parent_b]:
                parent_a, parent_b = parent_b, parent_a
            self.parent[parent_b] = parent_a
            self.size[parent_a] += self.size[parent_b]

for _ in range(t):
    n = int(input())
    pairs = []
    dsu = DSU(n)
    for _ in range(n):
        u, v = map(int, input().split())
        pairs.append((u, v))
    for i in range(n):
        for j in range(i + 1, n):
            a, b = pairs[i]
            c, d = pairs[j]
            if max(a, c) <= min(b, d):
                dsu.union(i, j)
    res = 0
    ctr = [0] * n
    comps = defaultdict(set)
    for i in range(n):
        comps[dsu.find(i)].add(i)
    print(comps)
    for i in comps:
        if dsu.size[i] > 2:
            for j in comps[i]:
                ctr[j] += 1
        if dsu.size[i] < 2:
            res += dsu.size[i]
    deletes = set()
    for i in comps:
        if dsu.size[i] > 2:
            mx = (-1, -1)
            for j in comps[i]:
                mx = max(mx, (ctr[j], j))
            if mx[1] not in deletes:
                deletes.add(mx[1])
                res += 1
    print(res)


# -*- coding: utf-8 -*-
#
# WebVTT format subtitle files translation
# Takes care of parsing and quirks of subtitles,
# and passes the text to a translation service.
#
import re
import requests
import sys
import webvtt

SERVICE_URL = 'http://localhost:5009/translate'

# Translate sometimes decides names are typoed words and mis-translates them
# We hide them as strings that it will not touch, and later replace back
NAME_CODES = {
    'Frøya': 'Fabiana',
    'Orm': 'Ognyan',
    'Varg': 'Vancho',
    'Liv': 'Linda',
}

RE_WORD_HYPHENATION = re.compile(r'(?<=\S)-\n(?=\S)')

def update_text(caption, new_text, flag_name):
    d = caption.__dict__.setdefault('preprocess', {})
    if caption.text != new_text:
        d[flag_name] = caption.text
        caption.text = new_text

def encode_names(captions, back=False):
    for caption in captions:
        for name, code in NAME_CODES.items():
            if back:
                if 'person_name' not in caption.preprocess:
                    continue # to avoid some weird materialization of characters
                name, code = code, name
            update_text(caption, re.sub(r'\b{}\b'.format(name), code, caption.text), 'person_name')

def fix_hyphenation(captions):
    '''Translate doesn't understand hyphenations across lines, so we join them.'''
    for caption in captions:
        update_text(caption, re.sub(RE_WORD_HYPHENATION, '', caption.text), 'hyphenation')
        update_text(caption, re.sub(r'^-(?=\S)', '- ', caption.text), 'leading_hyphen')

def revert_hyphenation(captions):
    for caption in captions:
        if 'leading_hyphen' in caption.preprocess:
            caption.text = re.sub('^- ', '-', caption.text)

def translate_texts(captions, method='inplace'):
    '''Translate in-place the caption texts using service'''
    # To send all captions in one batch text,
    # we join them with a recognizable separator.
    # We can't send the VTT file, because Translate
    # will mangle the timestamps
    sep = '\n~~~~\n'
    text = sep.join(c.text for c in captions)

    resp = requests.post(SERVICE_URL, data={'text': text})

    translated = resp.content.decode('utf-8').split(sep)

    for c, t in zip(captions, translated):
        if method == 'inplace':
            c.text = t
        elif method == 'concat':
            c.text = '{}\n---\n{}'.format(c.text, t)
        else:
            raise Exception('Unsupported translation method {}'.format(method))

def translate_captions_file(inbuf, outbuf, method='inplace'):
    '''Translates captions from input buffer to output buffer'''
    captions = webvtt.read_buffer(inbuf)

    # Preprocess
    encode_names(captions)
    fix_hyphenation(captions)

    # Main
    translate_texts(captions, method)

    # Postprocess
    encode_names(captions, back=True)
    revert_hyphenation(captions)

    captions.write(outbuf)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--method', default='inplace')
    args = parser.parse_args()

    # Handle filename stuff outside (e.g. translate.py <$in >$out)
    translate_captions_file(sys.stdin, sys.stdout, args.method)