"""This is main runner of generator

"""

import logging
import re
import sys
from argparse import ArgumentParser
from collections import namedtuple, OrderedDict
from datetime import date
from inspect import getfile
from itertools import groupby
from json import JSONDecodeError, loads
from os.path import basename
from pprint import pformat
from time import sleep

from jinja2 import Environment, FileSystemLoader, TemplateNotFound, UndefinedError
from pathlib2 import Path

ROOT = Path(__file__).absolute().parents[0]

sys.path.append(ROOT.parents[0].joinpath('lib/rpc_spec/InterfaceParser').as_posix())

try:
    from parsers.sdl_rpc_v2 import Parser
    from parsers.rpc_base import ParseError
    from model.interface import Interface
    from transformers.generate_error import GenerateError
    from transformers.enums_producer import EnumsProducer
    from transformers.functions_producer import FunctionsProducer
    from transformers.structs_producer import StructsProducer
except ImportError as message:
    print('%s.\nprobably you did not initialize submodule', message)
    sys.exit(1)

class Generator:
    """
    This class contains only technical features, as follow:
    - parsing command-line arguments, or evaluating required Paths interactively;
    - calling parsers to get Model from xml;
    - calling producers to transform initial Model to dict used in jinja2 templates
    Not required to be covered by unit tests cause contains only technical features.
    """

    def __init__(self):
        self.logger = logging.getLogger(self.__class__.__name__)
        self._env = None
        self.paths_named = namedtuple('paths_named', 'path_to_enum_class path_to_struct_class path_to_request_class '
                                                     'path_to_response_class path_to_notification_class enums_dir_name '
                                                     'structs_dir_name functions_dir_name rpc_creator')

    _version = '1.0.0'

    @property
    def get_version(self) -> str:
        """
        version of the entire generator
        :return: current entire generator version
        """
        return self._version

    @property
    def env(self):
        """
        :return: jinja2 Environment
        """
        return self._env

    @env.setter
    def env(self, value):
        """
        :param value: path with directory with templates
        :return: jinja2 Environment
        """
        if not Path(value).exists():
            self.logger.critical('Directory with templates not found %s', value)
            sys.exit(1)
        else:
            self._env = Environment(loader=FileSystemLoader(value))
            self._env.globals['year'] = date.today().year

    def config_logging(self, verbose):
        """
        Configuring logging for all application
        :param verbose: if True setting logging.DEBUG else logging.ERROR
        :return: None
        """
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter(fmt='%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s',
                                               datefmt='%H:%M:%S'))
        root_logger = logging.getLogger()

        if verbose:
            handler.setLevel(logging.DEBUG)
            self.logger.setLevel(logging.DEBUG)
            root_logger.setLevel(logging.DEBUG)
        else:
            handler.setLevel(logging.ERROR)
            self.logger.setLevel(logging.ERROR)
            root_logger.setLevel(logging.ERROR)
        logging.getLogger().handlers.clear()
        root_logger.addHandler(handler)

    def evaluate_output_directory(self, output_directory):
        """
        :param output_directory: path to output_directory
        :return: validated path to output_directory
        """
        if output_directory.startswith('/'):
            path = Path(output_directory).absolute().resolve()
        else:
            path = ROOT.joinpath(output_directory).resolve()
        if not path.exists():
            self.logger.warning('Directory not found: %s, trying to create it', path)
            try:
                path.mkdir(parents=True, exist_ok=True)
            except OSError as message1:
                self.logger.critical('Failed to create directory %s, %s', path.as_posix(), message1)
                sys.exit(1)
        return path

    def get_parser(self):
        """
        Parsing command-line arguments, or evaluating required Paths interactively.
        :return: an instance of argparse.ArgumentParser
        """

        if len(sys.argv) == 2 and sys.argv[1] in ('-v', '--version'):
            print(self.get_version)
            sys.exit(0)

        Paths = namedtuple('Paths', 'name path')
        xml = Paths('source_xml', ROOT.parents[0].joinpath('lib/rpc_spec/MOBILE_API.xml'))
        required_source = not xml.path.exists()

        out = Paths('output_directory', ROOT.parents[0].joinpath('lib/js/src/rpc'))
        output_required = not out.path.exists()

        parser = ArgumentParser(description='Proxy Library RPC Generator')
        parser.add_argument('-v', '--version', action='store_true', help='print the version and exit')
        parser.add_argument('-xml', '--source-xml', '--input-file', required=required_source,
                            help='should point to MOBILE_API.xml')
        parser.add_argument('-xsd', '--source-xsd', required=False)
        parser.add_argument('-d', '--output-directory', required=output_required,
                            help='define the place where the generated output should be placed')
        parser.add_argument('-t', '--templates-directory', nargs='?', default=ROOT.joinpath('templates').as_posix(),
                            help='path to directory with templates')
        parser.add_argument('-r', '--regex-pattern', required=False,
                            help='only elements matched with defined regex pattern will be parsed and generated')
        parser.add_argument('--verbose', action='store_true', help='display additional details like logs etc')
        parser.add_argument('-e', '--enums', required=False, action='store_true',
                            help='only specified elements will be generated, if present')
        parser.add_argument('-s', '--structs', required=False, action='store_true',
                            help='only specified elements will be generated, if present')
        parser.add_argument('-m', '-f', '--functions', required=False, action='store_true',
                            help='only specified elements will be generated, if present')
        parser.add_argument('-y', '--overwrite', action='store_true',
                            help='force overwriting of existing files in output directory, ignore confirmation message')
        parser.add_argument('-n', '--skip', action='store_true',
                            help='skip overwriting of existing files in output directory, ignore confirmation message')

        args, unknown = parser.parse_known_args()

        if unknown:
            self.logger.critical('found unknown arguments: %s', ' '.join(unknown))
            parser.print_help(sys.stderr)
            sys.exit(1)

        if args.skip and args.overwrite:
            self.logger.critical('please select only one option skip or overwrite')
            sys.exit(1)

        if not args.enums and not args.structs and not args.functions:
            args.enums = args.structs = args.functions = True

        for intermediate in (xml, out):
            if not getattr(args, intermediate.name) and intermediate.path.exists():
                while True:
                    try:
                        if args.overwrite:
                            self.logger.warning('%s set to %s', intermediate.name, intermediate.path)
                            setattr(args, intermediate.name, intermediate.path.as_posix())
                            break

                        confirm = input('Confirm default path {} for {} Y/Enter = yes, N = no'
                                        .format(intermediate.path, intermediate.name))
                        if confirm.lower() == 'y' or not confirm:
                            self.logger.warning('%s set to %s', intermediate.name, intermediate.path)
                            setattr(args, intermediate.name, intermediate.path.as_posix())
                            sleep(0.05)
                            break
                        if confirm.lower() == 'n':
                            self.logger.warning('provide argument %s', intermediate.name)
                            sys.exit(1)
                    except KeyboardInterrupt:
                        print('\nThe user interrupted the execution of the program')
                        sys.exit(1)

        args.output_directory = self.evaluate_output_directory(args.output_directory)

        return args

    def versions_compatibility_validating(self):
        """version of generator script requires the same or lesser version of parser script.
        if the parser script needs to fix a bug (and becomes, e.g. 1.0.1) and the generator script stays at 1.0.0.
        As long as the generator script is the same or greater major version, it should be parsable.
        This requires some level of backward compatibility. E.g. they have to be the same major version.

        """

        regex = r'(\d+\.\d+).(\d)'

        parser_origin = Parser().get_version
        parser_split = re.findall(regex, parser_origin).pop()
        generator_split = re.findall(regex, self.get_version).pop()

        parser_major = float(parser_split[0])
        generator_major = float(generator_split[0])

        if parser_major > generator_major:
            self.logger.critical('Generator (%s) requires the same or lesser version of Parser (%s)',
                                 self.get_version, parser_origin)
            sys.exit(1)

        self.logger.info('Parser type: %s, version %s,\tGenerator version %s',
                         basename(getfile(Parser().__class__)), parser_origin, self.get_version)

    def get_file_content(self, file_name: Path) -> list:
        """

        :param file_name:
        :return:
        """
        try:
            with file_name.open('r') as file:
                content = file.readlines()
            return content
        except FileNotFoundError as message1:
            self.logger.error(message1)
            return []

    def get_key_words(self, file_name=ROOT.parents[0].joinpath('lib/rpc_spec/RpcParser/RESERVED_KEYWORDS')):
        """
        :param file_name:
        :return:
        """
        content = self.get_file_content(file_name)
        content = tuple(map(lambda e: re.sub(r'\n', r'', e).strip().casefold(), content))
        content = tuple(filter(lambda e: not re.search(r'^#+\s+.+|^$', e), content))
        return content

    def get_mappings(self, file_name=ROOT.joinpath('mapping.json')):
        """
        The key name in *.json is equal to property named in jinja2 templates
        :param file_name: path to file with manual mappings
        :return: dictionary with custom manual mappings
        """

        content = self.get_file_content(file_name)
        try:
            return loads(''.join(content))
        except JSONDecodeError as message1:
            self.logger.error(message1)
            return {}

    def get_paths(self, file_name=ROOT.joinpath('paths.ini')):
        """
        :param file_name: path to file with Paths
        :return: namedtuple with Paths to key elements
        """
        content = self.get_file_content(file_name)
        if not content:
            self.logger.critical('%s not found', file_name)
            sys.exit(1)
        data = OrderedDict()
        for line in content:
            if line.startswith('#'):
                self.logger.warning('commented property %s, which will be skipped', line.strip())
                continue
            if re.match(r'^(\w+)\s?=\s?(.+)', line):
                if len(line.split('=')) > 2:
                    self.logger.critical('can not evaluate value, too many separators %s', str(line))
                    sys.exit(1)
                name, var = line.partition('=')[::2]
                if name.strip() in data:
                    self.logger.critical('duplicate key %s', name)
                    sys.exit(1)
                data[name.strip().lower()] = var.strip()

        missed = list(set(self.paths_named._fields) - set(data.keys()))
        if missed:
            self.logger.critical('in %s missed fields: %s ', content, str(missed))
            sys.exit(1)

        return self.paths_named(**data)

    def write_file(self, file_name, template, data):
        """
        Calling producer/transformer instance to transform initial Model to dict used in jinja2 templates.
        Applying transformed dict to jinja2 templates and writing to appropriate file
        :param file_name: output js file
        :param template: name of template
        :param data: transformed moder ready for apply to Jinja2 template
        """
        try:
            render = self.env.get_template(template).render(data)
            with file_name.open('w', encoding='utf-8') as file:
                file.write(render)
        except (TemplateNotFound, UndefinedError, AttributeError) as message1:
            self.logger.error('skipping %s, %s', file_name.as_posix(), message1)

    def process(self, directory, skip, overwrite, items, transformer):
        """
        Process each item from initial Model. According to provided arguments skipping, overriding or asking what to to.
        :param directory: output directory for writing output files
        :param skip: if file exist skip it
        :param overwrite: if file exist overwrite it
        :param items: elements initial Model
        :param transformer: producer/transformer instance
        """
        directory.mkdir(parents=True, exist_ok=True)
        for item in items.values():
            data = transformer.transform(item)
            if 'template' in data:
                template = data['template']
            else:
                template = type(item).__name__.lower() + '_template.js'
            file = directory.joinpath(data['name'] + '.js')
            self.process_common(skip, overwrite, file, template, data)

    def process_function_name(self, file, dir_name, skip, overwrite, functions, transformer, mappings):
        """
        :param file:
        :param dir_name:
        :param skip:
        :param overwrite:
        :param functions:
        :param transformer:
        :param mappings:
        :return:
        """
        if dir_name.startswith('..'):
            dir_name = dir_name[1:]

        creator = namedtuple('creator', 'function_name class_name type')
        data = {'name': file.stem, 'imports': [], 'cases': []}

        grouped = [{'name': k, 'type': [x for x in v]} for k, v in groupby(functions.values(), key=lambda x: x.name)]

        for item in grouped:
            name = item['name']
            for func in item['type']:
                kind = func.message_type.name.capitalize()
                if kind == 'Response':
                    name += kind
                key = name + kind
                if key in mappings and 'name' in mappings[key]:
                    name = mappings[key]['name']
                data['imports'].append(transformer.imports(what=name, wherefrom='{}/{}.js'.format(dir_name, name)))
                if kind != 'Response':
                    data['cases'].append(creator(name, name, kind.upper()))
                elif kind == 'Response' and len(item['type']) == 1:
                    data['cases'].append(creator(item['name'], name, kind.upper()))

        self.process_common(skip, overwrite, file, file.stem + '_template.js', data)

    def process_common(self, skip, overwrite, file, template, data):
        """
        :param skip:
        :param overwrite:
        :param file:
        :param template:
        :param data:
        :return:
        """
        if file.is_file():
            if skip:
                self.logger.info('Skipping %s', file.name)
                return
            if overwrite:
                self.logger.info('Overriding %s', file.name)
                file.unlink()
                self.write_file(file, template, data)
            else:
                while True:
                    try:
                        confirm = input('File already exists {}. Overwrite? Y/Enter = yes, N = no\n'
                                        .format(file.name))
                        if confirm.lower() == 'y' or not confirm:
                            self.logger.info('Overriding %s', file.name)
                            self.write_file(file, template, data)
                            break
                        if confirm.lower() == 'n':
                            self.logger.info('Skipping %s', file.name)
                            break
                    except KeyboardInterrupt:
                        print('\nThe user interrupted the execution of the program')
                        sys.exit(1)
        else:
            self.logger.info('Writing new %s', file.name)
            self.write_file(file, template, data)

    def filter_pattern(self, interface, pattern):
        """
        :param interface: initial Model
        :param pattern: regex-pattern from command-line arguments to filter element from initial Model
        :return: initial Model
        """
        names = tuple(interface.enums.keys()) + tuple(interface.structs.keys())

        if pattern:
            match = {i: OrderedDict() for i in vars(interface).keys()}
            match['params'] = interface.params
            empty = True
            for key, value in vars(interface).items():
                if key == 'params':
                    continue
                for name, item in value.items():
                    if re.match(pattern, item.name):
                        if hasattr(item, 'message_type'):
                            log = '{}/{} {} match with {}'.format(
                                key, item.name, item.message_type.name.title(), pattern)
                        else:
                            log = '{}/{} match with {}'.format(key, item.name, pattern)
                        self.logger.info(log)
                        if key in match:
                            match[key][name] = item
                            empty = False
            if empty:
                self.logger.warning('no one match with %s', pattern)
                sys.exit(0)
            return Interface(**match), names
        return interface, names

    @staticmethod
    def evaluate_instance_directory(dir_name):
        """
        :param dir_name: property from paths.ini (ENUMS|STRUCTS|FUNCTIONS)_DIR_NAME
        :return: substring after float dot
        """
        pattern = re.search(r'^([./]*)(.+)', dir_name)
        if pattern:
            return pattern.group(2)
        raise GenerateError('Can not evaluate directory {}'.format(dir_name))

    def main(self):
        """
        Entry point for parser and generator
        :return: None
        """
        args = self.get_parser()
        self.config_logging(args.verbose)
        self.logger.debug('parsed arguments:\n%s', pformat((vars(args))))
        self.env = args.templates_directory

        self.versions_compatibility_validating()

        paths = self.get_paths()

        try:
            interface = Parser().parse(args.source_xml, args.source_xsd)
        except ParseError as error1:
            self.logger.error(error1)
            sys.exit(1)

        filtered, names = self.filter_pattern(interface, args.regex_pattern)

        key_words = self.get_key_words()
        mappings = self.get_mappings()

        functions_transformer = FunctionsProducer(paths, names, mappings, key_words)
        if args.enums and filtered.enums:
            directory = args.output_directory.joinpath(self.evaluate_instance_directory(paths.enums_dir_name))
            self.process(directory, args.skip, args.overwrite, filtered.enums,
                         EnumsProducer(paths, mappings, key_words))
        if args.structs and filtered.structs:
            directory = args.output_directory.joinpath(self.evaluate_instance_directory(paths.structs_dir_name))
            self.process(directory, args.skip, args.overwrite, filtered.structs,
                         StructsProducer(paths, names, mappings, key_words))
        if args.functions and filtered.functions:
            directory = args.output_directory.joinpath(self.evaluate_instance_directory(paths.functions_dir_name))
            self.process(directory, args.skip, args.overwrite, filtered.functions, functions_transformer)
        self.process_function_name(args.output_directory.joinpath(paths.rpc_creator), paths.functions_dir_name,
                                   args.skip, args.overwrite, interface.functions, functions_transformer,
                                   mappings.get('functions', OrderedDict()))

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


from __future__ import unicode_literals

import uuid

from django.conf import settings
from django.db import migrations, models

import django_cleanhtmlfield.fields

from eric.projects.models.models import FileSystemStorageLimitByUser

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('projects', '0083_elementlock'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='resource',
            name='availability',
        ),
        migrations.RenameField(
            model_name='resource',
            old_name='address',
            new_name='location',
        ),
        migrations.RenameField(
            model_name='resource',
            old_name='title',
            new_name='name',
        ),
        migrations.AddField(
            model_name='resource',
            name='contact',
            field=models.TextField(blank=True, default='', verbose_name='Contact of this resource'),
        ),
        migrations.AddField(
            model_name='resource',
            name='inventory_number',
            field=models.CharField(default=uuid.uuid4, max_length=64, null=True, verbose_name='Inventory number of the resource'),
        ),
        migrations.AddField(
            model_name='resource',
            name='projects',
            field=models.ManyToManyField(blank=True, related_name='resources', to='projects.Project', verbose_name='Which projects is this resource associated to'),
        ),
        migrations.AddField(
            model_name='resource',
            name='responsible_unit',
            field=models.CharField(blank=True, default='', max_length=256, verbose_name='Responsible unit of the resource'),
        ),
        migrations.AddField(
            model_name='resource',
            name='terms_of_use_pdf',
            field=models.FileField(blank=True, max_length=512, null=True, storage=FileSystemStorageLimitByUser(), upload_to='', verbose_name='Terms of Use PDF file'),
        ),
        migrations.AddField(
            model_name='resource',
            name='user_availability',
            field=models.CharField(choices=[('GLB', 'Global'), ('PRJ', 'Only for project members'), ('USR', 'Only selected users')], default='GLB', max_length=3, verbose_name='User availability for this resource'),
        ),
        migrations.AddField(
            model_name='resource',
            name='user_availability_selected_users',
            field=models.ManyToManyField(blank=True, related_name='resources', to=settings.AUTH_USER_MODEL, verbose_name='The selected users this resource is available for'),
        ),
        migrations.AlterField(
            model_name='resource',
            name='name',
            field=models.CharField(max_length=256, verbose_name='Name of the resource'),
        ),
        migrations.AlterField(
            model_name='resource',
            name='location',
            field=models.TextField(blank=True, default='', verbose_name='Location of this resource'),
        ),
        migrations.AlterField(
            model_name='resource',
            name='description',
            field=django_cleanhtmlfield.fields.HTMLField(blank=True, verbose_name='Description of the resource'),
        ),
        migrations.AlterField(
            model_name='resource',
            name='type',
            field=models.CharField(choices=[('ROOM', 'Room'), ('LABEQ', 'Lab Equipment'), ('OFFEQ', 'Office Equipment'), ('ITRES', 'IT-Resource')], default='ROOM', max_length=5, verbose_name='Type of this resource'),
        ),
    ]


'''
You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer

Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps
Example 2:

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Conclusion : the first thing we need to know is how to use the dynamic programing method to
optimize this question and then try to find out the sub_problems.
In this case: the sub_problem is : we use dp[i] to describle how many ways we can use to climd to the Number i
Then we look at the dp[i-2] and dp[i-1] because we can use this two solved problems to sovle the dp[i],
because we can take 2 steps from dp[i-2] to dp[i] as well as 1 step from dp[i-1] to dp[i]
Then we could get the equation like : dp[i] = dp[i-1] + dp[i-2]
In the following two solutions:
The first one is Memorization method
The secod one is Bottom-up method
'''
class Solution(object):

    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        # Trying to use dynamic programing
        # What if we define the sub_problems as Xi which is the number of way for us to climb to i
        # Memorizarion
        memo = [-1 for i in range(n + 1)]

        def iterate(num):
            # trivial case
            if num < 0:
                return 0
            elif num == 0:
                return 1
            elif memo[num] != -1:
                return memo[num]
            else:
                ans = iterate(num - 1) + iterate(num - 2)
                memo[num] = ans
                return ans
        iterate(n)
        return memo[n]

    # Bottom up method:
    def climbStairs2(self,n):
        dp = []
        dp.append(1)
        dp.append(1)
        for i in range(2, n+1):
            dp.append(dp[i-1] + dp[i-2])
        return dp[n]

solution = Solution()
testcases = [1, 2, 3, 4, 5, 6, 35]
for case in testcases:
    print (solution.climbStairs(case))
for case in testcases:
    print (solution.climbStairs2(case))


#!/usr/bin/python3

import archinstall
from archinstall import User

ADDITIONAL_PACKAGES=[
    # X
    "xorg",
    "xorg-xinit",
    "xterm",

    # gfx
    "mesa",
    "xf86-video-intel",

    # audio
    "alsa-utils",
    "alsa-tools",

    # dev
    "vim",
    "python",
    "archinstall",

    # gaming for gamers
    "ttf-liberation",
    "steam",

    # virtualization (REMOVEME)
    "hyperv",
    "open-vm-tools",
    "qemu-guest-agent",
    "virtualbox-guest-utils-nox",

    # network
    "networkmanager",
]

if archinstall.arguments.get('help', None):
    archinstall.log(' - Optional filesystem type via --filesystem=<fs type>')
    archinstall.log(' - Optional systemd network via --network')
    archinstall.log()

archinstall.arguments['harddrive'] = archinstall.select_disk(archinstall.all_blockdevices())
if archinstall.arguments['harddrive']:
    archinstall.arguments['harddrive'].keep_partitions = False

    print(f"Formatting {archinstall.arguments['harddrive']} in ", end='')
    with archinstall.Filesystem(archinstall.arguments['harddrive'], archinstall.GPT) as fs:
        # Use the whole disk
        if archinstall.arguments['harddrive'].keep_partitions is False:
            fs.use_entire_disk(root_filesystem_type=archinstall.arguments.get('filesystem', 'btrfs'))

        boot = fs.find_partition('/boot')
        root = fs.find_partition('/')

        boot.format('fat32')
        root.format(root.filesystem)
        root.mount('/mnt')
        boot.mount('/mnt/boot')

with archinstall.Installer('/mnt') as installation:
    if installation.minimal_installation(multilib=True):
        installation.set_hostname('arch-fgbox')
        installation.add_bootloader()
        installation.copy_iso_network_config(enable_services=True)

        installation.add_additional_packages(ADDITIONAL_PACKAGES)
        installation.install_profile('minimal')

        # Linksys router security model for now :P
        user_sudo = True
        admin_user = User('admin', 'password', user_sudo)
        installation.user_create(admin_user)


import json
from flask import request
import bson
import pymongo
from loguru import logger
from bson import json_util
from flasgger import swag_from
from flask_restful import Resource

from luizalabs_project.modules.databases import CustomerDB
from luizalabs_project.api.api_utils import Response, verify_auth

class CustomersListAPI(Resource):

    @swag_from('docs/customersListAPI_get.yml')
    @verify_auth
    def get(self):
        logger.info("Recovering information from all customer.")

        try:
            database = CustomerDB()

            return json.loads(json_util.dumps(database.show_all()))
        except (bson.errors.InvalidId, pymongo.errors.OperationFailure):
            logger.exception("Database Failure !!!")

            return Response.error()

        return Response.error()

class CustomerListAPI(Resource):
    @swag_from('docs/customerListAPI_get.yml')
    @verify_auth
    def get(self, customer_id):
        logger.info("Recovering information from a customer.")

        try:
            database = CustomerDB()

            return json.loads(json_util.dumps(database.show_one(customer_id)))
        except (bson.errors.InvalidId, pymongo.errors.OperationFailure):
            logger.exception("Database Failure !!!")

            return Response.error()

        return Response.error()

class CustomerAPI(Resource):

    @swag_from('docs/customerAPI_post.yml')
    @verify_auth
    def post(self):
        logger.info("Adding new customer.")

        try:
            req = request.json
            name, email = req['name'], req['email']

        except (KeyError, TypeError):
            logger.exception("Parameters error !!!")

            return Response.parameters_error()

        try:
            database = CustomerDB()

            result = database.add(name, email)

            if result:
                return Response.custom_success(
                    dict(message="Customer added with success")
                )

            return Response.custom_error(dict(message="Email already in use"))

        except pymongo.errors.OperationFailure:
            logger.exception("Database Failure !!!")

            return Response.error()

        return Response.error()

    @swag_from('docs/customerAPI_put.yml')
    @verify_auth
    def put(self):
        logger.info("Updating a customer.")

        try:
            req = request.json
            customer_id = req['customer_id']
            name = req['name'] if 'name' in req.keys() else None
            email = req['email'] if 'email' in req.keys() else None

            if (not name) and (not email):
                return Response.custom_error(
                    dict(message='Please, update need name or '
                         'email as parameters'))

        except (KeyError, TypeError):
            logger.exception("Parameters error !!!")

            return Response.parameters_error()

        try:
            database = CustomerDB()

            result = database.update(customer_id, name, email)

            if result:
                return Response.custom_success(
                    dict(message="Customer updated with success")
                )

            return Response.custom_error(dict(message="Couldn't update "
                                              "the user, email already in use")
                                         )

        except pymongo.errors.OperationFailure:
            logger.exception("Database Failure !!!")

            return Response.error()

        return Response.error()

    @swag_from('docs/customerAPI_delete.yml')
    @verify_auth
    def delete(self):
        logger.info("Deleting customer.")

        try:
            req = request.json

            customer_id = req['customer_id']

        except (KeyError, TypeError):
            logger.exception("Parameters error !!!")

            return Response.parameters_error()

        try:
            database = CustomerDB()
            result = database.remove(customer_id)

            if result:
                return Response.custom_success(
                    dict(message="Customer removed with success")
                )

            return Response.custom_error(dict(message="Couldn't remove "
                                              "the user")
                                         )

        except pymongo.errors.OperationFailure:
            logger.exception("Database Failure !!!")

            return Response.error()

        return Response.error()


class ComplexNumbers:

    def __init__( self, real, imaginary ):

        self.real = real
        self.imaginary = imaginary

    def plus( self, other ):

        self.real += other.real
        self.imaginary += other.imaginary

        return ( self.real, self.imaginary )

    def multiply( self, other ):

        real = ( self.real * other.real ) - ( self.imaginary * other.imaginary )
        self.imaginary = ( self.real * other.imaginary ) + ( self.imaginary * other.real )
        self.real = real

        return ( self.real, self.imaginary )

    def print( self ):

        print( str( self.real ) + " + i" + str( self.imaginary ) )

r, i = map( int, input().split() )
c1 = ComplexNumbers( r, i )
r, i = map( int, input().split() )
c2 = ComplexNumbers( r, i )
o = int( input() )

if o == 1:
    c1.plus( c2 )
    c1.print()
elif o == 2:
    c1.multiply( c2 )
    c1.print()

Coding Ninjas/Moderate/Complex Number Class.py


from scrapy.http import HtmlResponse
from scrapy.selector import Selector
url ='https://www.cryptocompare.com/coins/{}/overview'

def crawl_data(token):
    full_path = url.format(token)
    response = HtmlResponse(url=full_path)
    Selector(response=response)

crawl_data("BTC")


import os
import pandas as pd
from os.path import join
import json

from ._config import get_data_home
from . import _github_api

def load_commits(user, project, data_home=None):
    """
    Reads the commits json files from the data folder.

    Parameters
    ----------
    user : string
        user or organization name, e.g. "matplotlib"

    project : string
        project name, e.g, "matplotlib"

    Returns
    -------
    commits
    """
    # XXX We need to sometime update that folder - how to do that?
    # XXX for some projects, that's going to get ugly…
    data_home = get_data_home(data_home)
    filepath = join(data_home, user, project, "commits.json")
    try:
        commits = pd.read_json(filepath)
    except ValueError:
        return None
    return commits

def update_commits(user, project, auth, since=None,
                   max_pages=100, per_page=100,
                   data_home=None, **params):
    """Update the commit data for a repository.

    Parameters
    ----------
    user : string
        The user / organization of the repository
    project : string
        The repository name
    auth : string (user:api_key)
        The username / API key for github, separated by a colon.
    singe : ???
        ???
    max_pages : int
        The maximum number of pages to return in the GET request.
    per_page : int
        The number of commits to return per page.
    data_home : string
        A path to where the data is stored.
    params : dict-like
        Will be passed to `get_frames`.

    Returns
    -------
    raw : json
        The raw json returned by the github API.
    """
    auth = _github_api.colon_seperated_pair(auth)
    url = 'https://api.github.com/repos/{}/{}/commits'.format(user, project)
    raw = _github_api.get_frames(auth, url, since=since,
                                 max_pages=max_pages,
                                 per_page=per_page,
                                 **params)
    path = get_data_home(data_home=data_home)
    filename = os.path.join(path, user, project, "commits.json")
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError:
        pass
    with open(filename, "w") as f:
        json.dump(raw, f)
    return raw

def is_doc(commits, use_message=True, use_files=True):
    """
    Find commits that are documentation related.

    Parameters
    ----------
    commits : pd.DataFrame
        pandas dataframe containing the commits information.

    use_message : bool, optional, default: True

    use_files: bool, optional, default: True
    """
    is_doc_message = commits.message.apply(lambda x: "doc" in x.lower())
    is_doc_files = commits.added.apply(lambda x: "doc" in " ".join(x).lower())
    is_doc = is_doc_message | is_doc_files
    is_doc.rename("is_doc", inplace=True)
    return is_doc


# -*- coding: utf-8 -*-
"""
Created on Sat Aug  3 07:53:44 2019

@author: A_Normal_PC
"""

from graphics import *
from pandas import *

class Check(object):

    def __init__(self, loc, half_size, NAME, PRICE):
        """
        loc is a tuple with x y coordinates of the center of rectangle
        """
        self.disabled=True
        self.clicked=False
        self.name=NAME
        self.price=PRICE
        p1=Point(loc[0]-half_size,loc[1]-half_size)
        p2=Point(loc[0]+half_size,loc[1]+half_size)
        self.rectangle=Rectangle(p1,p2) # x1<x2  y1<y2
        self.rectangle.setFill("white")
        self.name_text=Text(Point(loc[0]+275,loc[1]), NAME)
        self.name_text.setSize(int(half_size*0.9))
        self.name_text.setFill("Yellow")
        self.price_text=Text(Point(loc[0]+525,loc[1]), PRICE)
        self.price_text.setSize(int(half_size))
        self.price_text.setFill("Yellow")

    def draw(self,win):
        self.rectangle.draw(win)
        self.name_text.draw(win)
        self.disabled=False

        if self.clicked:
            self.price_text.draw(win)

    def undraw_check(self):
        self.rectangle.undraw()
        self.name_text.undraw()
        self.disabled=True
        self.price_text.undraw()

    def draw_without_rect(self,win):
        self.disabled=True
        self.name_text.draw(win)
        self.price_text.draw(win)

    def undraw_without_rect(self):
        self.disabled=True
        self.name_text.undraw()
        self.price_text.undraw()

    def click(self,win):
        if not self.disabled:
            if self.clicked==False:
                self.rectangle.setFill("red")
                self.clicked= not self.clicked
                self.price_text.draw(win)
                return self.price
            else:
                self.rectangle.setFill("white")
                self.clicked= not self.clicked
                self.price_text.undraw()
                return -self.price
        pass

class Confirm_check(object):

    def __init__(self, loc, half_size, width_mod, length_mod,name, color):
        """
        loc is a tuple with x y coordinates of the center of rectangle
        """
        self.disabled=True
        self.clicked=False
        self.name=name
        self.price=-1
        loc=(340,loc[1])
        p1=Point(loc[0]-half_size*width_mod,loc[1]-half_size*length_mod)
        p2=Point(loc[0]+half_size*width_mod,loc[1]+half_size*length_mod)
        self.rectangle=Rectangle(p1,p2) # x1<x2  y1<y2
        self.rectangle.setFill(color)
        self.name_text=Text(Point(loc[0],loc[1]), self.name)
        self.name_text.setSize(int(half_size*0.75))

    def draw(self,win):
        self.rectangle.draw(win)
        self.name_text.draw(win)
        self.disabled=False

    def undraw_check(self):
        self.rectangle.undraw()
        self.name_text.undraw()
        self.disabled=True

    def click(self,win):
        if not self.disabled:
            self.clicked= not self.clicked
            return self.price

class Checklist(object):

    def __init__(self, window, data, X_check_center, check_size, Y_start, gap):
        self.checkout=[]
        self.check_list=[]
        self.data_list=[] # tuples of items (name, price)
        self.win=window
        self.Y_start=Y_start
        self.check_size=check_size
        self.X_check_center=X_check_center
        self.gap=gap

        df = pandas.read_excel( data, sheet_name='Sheet1')
        names = df["სამუშაო"]
        prices= df["ფასი"]
        for i in range(len(names)):
                self.data_list.append((names[i],prices[i]))

        Y_current=Y_start
        for a in self.data_list:
            print(a)
            self.check_list.append( Check((X_check_center, Y_current+check_size/2), check_size/2, a[0], a[1]) )
            self.check_list[-1].draw(window)
            Y_current+=check_size+gap

        self.check_list.append( Confirm_check((X_check_center+200, Y_current+gap*5+check_size/2), check_size*0.75, 5, 1.5,"დადასტურება", "Yellow") )
        self.check_list[-1].draw(window)

    def draw_list(self):
        for a in self.check_list:
            a.draw(self.win)

    def undraw_list(self):
        for a in self.check_list:
            a.undraw_check()

    def getCheckoutText(self):
        text="\n "
        for a in self.checkout[:-2]:
            text+="{} {} \n ".format(a.name,a.price)

        return text

    def draw_checkout(self):
        self.checkout=[]
        gap=self.gap
        check_size=self.check_size
        X_check_center=self.X_check_center
        Y_current=self.Y_start
        for a in self.check_list[:-1]:
            if a.clicked==True:
                self.checkout.append( Check((-50, Y_current+check_size/2), check_size/2, a.name, a.price) )
                self.checkout[-1].draw_without_rect(self.win)
                Y_current+=check_size+gap

        self.checkout.append( Entry( Point(X_check_center+260, Y_current+gap*5+check_size/2), 30))
        self.checkout[-1].draw(self.win)
        self.checkout[-1].setFill("White")

        self.checkout.append( Text( Point(X_check_center+40, Y_current+gap*5+check_size/2), "ტელეფონის ნომერი:"))
        self.checkout[-1].setSize(int(check_size*0.35))
        self.checkout[-1].setFill("Yellow")
        self.checkout[-1].draw(self.win)

        Y_current+=check_size+gap
        self.check_list.append( Confirm_check((X_check_center+200, Y_current+gap*5+check_size/2), check_size*0.75, 5, 1.5, "შეკვეთის განთავსება", "Yellow") )
        self.check_list[-1].draw(self.win)

        Y_current+=check_size+gap*5
        self.check_list.append( Confirm_check((X_check_center+200, Y_current+gap*5+check_size/2), check_size*0.75, 5, 1, "დაბრუნება", "Gray") )
        self.check_list[-1].draw(self.win)

    def undraw_checkout(self):
        for a in range(2):
            self.check_list[-1].undraw_check()
            self.check_list=self.check_list[:-1]

        for a in range(2):
            self.checkout[-1].undraw()
            self.checkout=self.checkout[:-1]

        for a in self.checkout:
            a.undraw_without_rect()


import glob
import matplotlib.pyplot as plt
import numpy as np
from tools.paper.plotting.plot_utils import plot_save
from matplotlib import rc, rcParams

# activate latex text rendering
# rc('text', usetex=True)
# rc('axes', linewidth=2)
# rc('font', weight='bold')
# rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath']

DLMC_DATA = "/sdb/cache/workingset_size/dlmc"
SS_DATA = "/sdb/cache/workingset_size/ss"

plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams.update({'font.size': 14})
plt.rcParams["figure.figsize"] = (7, 6)
plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] = 0

SS_SPARSITY_RANGES = [0.7, 1.0]
DLMC_SPARSITY_RANGES = [0.7, 1.0]

np.random.seed(42)

fig, ax = plt.subplots()
ax.spines.right.set_visible(False)
ax.spines.top.set_visible(False)

def rand_jitter(arr):
    stdev = .005 * (max(arr) - min(arr))
    return arr + np.random.randn(len(arr)) * stdev

tile_sizes = np.load(f"{DLMC_DATA}/tile_sizes.npy")
dlmc_files = np.random.choice(glob.glob(DLMC_DATA + "/**/*_working_set.npz", recursive=True), 200)

tile_sizes = np.load(f"{SS_DATA}/tile_sizes.npy")
ss_files = np.random.choice(glob.glob(SS_DATA + "/**/*_working_set.npz", recursive=True), 200)

for file in ss_files:
    working_set_sizes = np.load(file)
    cov = working_set_sizes["cov"]
    if len(cov) == 0: continue
    sparsity = working_set_sizes["sparsity"]

    if sparsity < SS_SPARSITY_RANGES[0] or sparsity > SS_SPARSITY_RANGES[1]: continue
    last_ss = plt.scatter(rand_jitter(tile_sizes[:len(cov)]), cov, color="navy", label="SuiteSparse",
                          alpha=float(sparsity), s=1)

for file in dlmc_files:
    working_set_sizes = np.load(file)
    cov = working_set_sizes["cov"]
    sparsity = working_set_sizes["sparsity"]

    if sparsity < DLMC_SPARSITY_RANGES[0] or sparsity > DLMC_SPARSITY_RANGES[1]: continue
    last_dlmc = plt.scatter(rand_jitter(tile_sizes[:len(cov)]), cov, color="orangered", label="DLMC",
                            alpha=float(sparsity), s=1)

ticks = [f'{i}x{i}' for i in tile_sizes]
plt.xticks(tile_sizes[::6], ticks[::6], rotation=45)
plt.xlabel(r"Tile Size")
plt.ylabel(r"Coefficient of Variation")

#plt.tight_layout()

lgnd = plt.legend(handles=[last_ss, last_dlmc], loc='upper right')
lgnd.legendHandles[0]._sizes = [10]
lgnd.legendHandles[1]._sizes = [10]
#
plt.margins(x=0)
plt.tight_layout()

plot_save("working_set_size")


import os
import torch
from diffusers.models.cross_attention import LoRACrossAttnProcessor
from diffusers import StableDiffusionPipeline
import json

import argparse

parser = argparse.ArgumentParser("generate images from a unet lora checkpoint")
parser.add_argument("--unet_weight", default="", type=str)
parser.add_argument("--prompts", default="validation_prompts_500.json", type=str)
parser.add_argument("--folder", default="dump", type=str)
parser.add_argument("--negative_prompt", default="Weird image. ", type=str)
parser.add_argument("--world_size", default=-1, type=int)
parser.add_argument("--rank", default=-1, type=int)

args = parser.parse_args()

use_command_line_rank = args.world_size > 0 and args.rank >= 0

unet_weight = args.unet_weight
negative_prompt = args.negative_prompt

local_rank = 0
for v in ('LOCAL_RANK', 'MPI_LOCALRANKID', 'SLURM_LOCALID', 'OMPI_COMM_WORLD_LOCAL_RANK'):
    if v in os.environ:
        local_rank = int(os.environ[v])
        if use_command_line_rank:
            # make sure that only use one GPU when directly specify world size and rank from command line
            assert local_rank == 0
        break

if use_command_line_rank:
    rank = args.rank
else:
    rank = 0
    for v in ('RANK', 'PMI_RANK', 'SLURM_PROCID', 'OMPI_COMM_WORLD_RANK'):
        if v in os.environ:
            rank = int(os.environ[v])
            break

if use_command_line_rank:
    world_size = args.world_size
else:
    world_size = 1
    for v in ('WORLD_SIZE', 'PMI_SIZE', 'SLURM_NTASKS', 'OMPI_COMM_WORLD_SIZE'):
        if v in os.environ:
            world_size = int(os.environ[v])
            break

with open(args.prompts) as f:
    pairs = json.load(f)

pipeline = StableDiffusionPipeline.from_pretrained(
    "CompVis/stable-diffusion-v1-4",
    torch_dtype=torch.float16,
).to(local_rank)

if unet_weight:
    model_weight = torch.load(unet_weight, map_location='cpu')
    unet = pipeline.unet
    lora_attn_procs = {}
    lora_rank = list(set([v.size(0) for k, v in model_weight.items() if k.endswith("down.weight")]))
    assert len(lora_rank) == 1
    lora_rank = lora_rank[0]
    for name in unet.attn_processors.keys():
        cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
        if name.startswith("mid_block"):
            hidden_size = unet.config.block_out_channels[-1]
        elif name.startswith("up_blocks"):
            block_id = int(name[len("up_blocks.")])
            hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
        elif name.startswith("down_blocks"):
            block_id = int(name[len("down_blocks.")])
            hidden_size = unet.config.block_out_channels[block_id]

        lora_attn_procs[name] = LoRACrossAttnProcessor(
            hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=lora_rank
        ).to(local_rank)
    unet.set_attn_processor(lora_attn_procs)
    unet.load_state_dict(model_weight, strict=False)

if not os.path.exists(args.folder):
    os.makedirs(args.folder)

generator = torch.Generator(device='cuda').manual_seed(rank + 1)

for i, pair in enumerate(pairs):
    if i % world_size != rank:
        continue
    if os.path.exists(f"{args.folder}/{i}.jpg"):
        continue
    with torch.no_grad():
        raw_images = pipeline([pair], num_inference_steps=50, generator=generator, negative_prompt=[negative_prompt]).images
    for j, image in enumerate(raw_images):
        image.save(f"{args.folder}/{i}.jpg", quality=90)


'''Unit tests'''

import os
import io
from collections import deque

import requests

from cert_session import Session, _create_certifi_temp

def get_lines_from_file(path):
    with open(path) as fh:
        return fh.readlines()

def get_line_count_path(path):
    with open(path) as fh:
        return get_line_count_fh(fh)

def get_line_count_fh(fh):
    lines = 0

    for _ in fh:
        lines += 1

    return lines

def test_get_line_count_fh():
    fh = io.StringIO('Line1\nLine2\nLine3\n')
    assert get_line_count_fh(fh) == 3

def test_get_line_count_fh_unterminated():
    fh = io.StringIO('Line1\nLine2\nLine3')
    assert get_line_count_fh(fh) == 3

def test_create_certifi_temp(cert_path):
    tmp_path = _create_certifi_temp(cert_path)
    assert tmp_path

    with open(tmp_path) as ftmp:
        tail_lines = list(deque(ftmp, maxlen=get_line_count_path(cert_path)))

    assert tail_lines == get_lines_from_file(cert_path)
    os.unlink(tmp_path)

def test_cert_session_exit(cert_path):
    sess = Session(cert_path)
    assert sess
    assert isinstance(sess, type(requests.session()))
    assert sess == sess.__enter__()

    path = sess.verify
    assert os.path.exists(path)

    sess.__exit__(None, None, None)
    assert not os.path.exists(path)

def test_cert_session_exit_with_exception(cert_path):
    sess = Session(cert_path)
    assert sess
    assert isinstance(sess, type(requests.session()))
    assert sess == sess.__enter__()

    path = sess.verify
    assert os.path.exists(path)

    sess.__exit__(Exception, None, None)
    assert os.path.exists(path)

    os.unlink(path)


from unittest import TestCase, skipIf
import time
import re
import sys
import multiprocessing as mp
from queue import Empty
from unittest.mock import patch

import qcodes
from qcodes.process.helpers import set_mp_method, kill_queue
from qcodes.process.qcodes_process import QcodesProcess
from qcodes.process.stream_queue import get_stream_queue, _SQWriter
from qcodes.process.server import ServerManager, RESPONSE_OK, RESPONSE_ERROR
import qcodes.process.helpers as qcmp
from qcodes.utils.helpers import in_notebook, LogCapture
from qcodes.utils.timing import calibrate

BREAK_SIGNAL = '~~BREAK~~'

class sqtest_echo:
    def __init__(self, name, delay=0.01, has_q=True):
        self.q_out = mp.Queue()
        self.q_err = mp.Queue()
        self.p = QcodesProcess(target=sqtest_echo_f,
                               args=(name, delay, self.q_out, self.q_err,
                                     has_q),
                               name=name)
        self.p.start()
        self.delay = delay
        self.resp_delay = delay * 2 + 0.03

    def send_out(self, msg):
        self.q_out.put(msg)
        time.sleep(self.resp_delay)

    def send_err(self, msg):
        self.q_err.put(msg)
        time.sleep(self.resp_delay)

    def halt(self):
        if not (hasattr(self, 'p') and self.p.is_alive()):
            return
        self.q_out.put(BREAK_SIGNAL)
        self.p.join()
        time.sleep(self.resp_delay)
        for q in ['q_out', 'q_err']:
            if hasattr(self, q):
                queue = getattr(self, q)
                kill_queue(queue)
                kill_queue(queue)  # repeat just to make sure it doesn't error

    def __del__(self):
        self.halt()

def sqtest_echo_f(name, delay, q_out, q_err, has_q):
    while True:
        time.sleep(delay)

        if not q_out.empty():
            out = q_out.get()

            if out == BREAK_SIGNAL:
                # now test that disconnect works, and reverts to
                # regular stdout and stderr
                if has_q:
                    try:
                        get_stream_queue().disconnect()
                    except RuntimeError:
                        pass
                    print('stdout ', end='', flush=True)
                    print('stderr ', file=sys.stderr, end='', flush=True)
                break

            print(out, end='', flush=True)

        if not q_err.empty():
            print(q_err.get(), file=sys.stderr, end='', flush=True)

def sqtest_exception():
    raise RuntimeError('Boo!')

class TestMpMethod(TestCase):
    def test_set_mp_method(self):
        start_method = mp.get_start_method()
        self.assertIn(start_method, ('fork', 'spawn', 'forkserver'))

        # multiprocessing's set_start_method is NOT idempotent
        with self.assertRaises(RuntimeError):
            mp.set_start_method(start_method)

        # but ours is
        set_mp_method(start_method)

        # it will still error on gibberish, but different errors depending
        # on whether you force or not
        with self.assertRaises(RuntimeError):
            set_mp_method('spoon')
        with self.assertRaises(ValueError):
            set_mp_method('spoon', force=True)

        # change the error we look for to test strange error handling
        mp_err_normal = qcmp.MP_ERR
        qcmp.MP_ERR = 'who cares?'
        with self.assertRaises(RuntimeError):
            set_mp_method('start_method')
        qcmp.MP_ERR = mp_err_normal

class TestQcodesProcess(TestCase):
    def setUp(self):
        mp_stats = calibrate(quiet=True)
        self.MP_START_DELAY = mp_stats['mp_start_delay']
        self.MP_FINISH_DELAY = mp_stats['mp_finish_delay']
        self.SLEEP_DELAY = mp_stats['sleep_delay']
        self.BLOCKING_TIME = mp_stats['blocking_time']
        self.sq = get_stream_queue()

    @skipIf(getattr(qcodes, '_IN_NOTEBOOK', False),
            'called from notebook')
    def test_not_in_notebook(self):
        # below we'll patch this to True, but make sure that it's False
        # in the normal test runner.
        self.assertEqual(in_notebook(), False)

        # and make sure that processes run this way do not use the queue
        with self.sq.lock:
            p = sqtest_echo('hidden', has_q=False)
            time.sleep(self.MP_START_DELAY)
            p.send_out('should go to stdout;')
            p.send_err('should go to stderr;')
            p.halt()

            self.assertEqual(self.sq.get(), '')

    @patch('qcodes.process.qcodes_process.in_notebook')
    def test_qcodes_process_exception(self, in_nb_patch):
        in_nb_patch.return_value = True

        with self.sq.lock:
            name = 'Hamlet'
            p = QcodesProcess(target=sqtest_exception, name=name)

            initial_outs = (sys.stdout, sys.stderr)

            # normally you call p.start(), but for this test we want
            # the function to actually run in the main process
            # it will run the actual target, but will print the exception
            # (to the queue) rather than raising it.
            p.run()

            # output streams are back to how they started
            self.assertEqual((sys.stdout, sys.stderr), initial_outs)
            time.sleep(0.01)
            exc_text = self.sq.get()
            # but we have the exception in the queue
            self.maxDiff = None
            self.assertGreaterEqual(exc_text.count(name + ' ERR'), 5)
            self.assertEqual(exc_text.count('Traceback'), 1, exc_text)
            self.assertEqual(exc_text.count('RuntimeError'), 2)
            self.assertEqual(exc_text.count('Boo!'), 2)

    @patch('qcodes.process.qcodes_process.in_notebook')
    def test_qcodes_process(self, in_nb_patch):
        in_nb_patch.return_value = True

        queue_format = re.compile(
            '^\[\d\d:\d\d:\d\d\.\d\d\d p\d( ERR)?\] [^\[\]]*$')

        with self.sq.lock:
            p1 = sqtest_echo('p1')
            p2 = sqtest_echo('p2')
            time.sleep(self.MP_START_DELAY + p1.delay + p2.delay)

            self.assertEqual(self.sq.get(), '')

            procNames = ['<{}>'.format(name)
                         for name in ('p1', 'p2')]

            reprs = [repr(p) for p in mp.active_children()]
            for name in procNames:
                self.assertIn(name, reprs)

            # test each individual stream to send several messages on same
            # and different lines

            for sender, label, term in ([[p1.send_out, 'p1] ', ''],
                                         [p1.send_err, 'p1 ERR] ', '\n'],
                                         [p2.send_out, 'p2] ', '\n'],
                                         [p2.send_err, 'p2 ERR] ', '']]):
                sender('row row ')
                sender('row your boat\n')
                sender('gently down ')
                time.sleep(0.01)
                data = [line for line in self.sq.get().split('\n') if line]
                expected = [
                    label + 'row row row your boat',
                    label + 'gently down '
                ]
                # TODO - intermittent error here
                self.assertEqual(len(data), len(expected), data)
                for line, expected_line in zip(data, expected):
                    self.assertIsNotNone(queue_format.match(line), data)
                    self.assertEqual(line[14:], expected_line, data)

                sender(' the stream' + term)
                # no label/header as we're continuing  the previous line
                self.assertEqual(self.sq.get(), ' the stream' + term)

            p1.send_out('marco')
            p2.send_out('polo\n')  # we don't see these single terminators
            p1.send_out('marco\n')  # when we change streams
            p2.send_out('polo')
            time.sleep(0.01)

            data = self.sq.get().split('\n')
            for line in data:
                if line:
                    self.assertIsNotNone(queue_format.match(line))

            data_msgs = [line[14:] for line in data]
            expected = [
                '',
                'p1] marco',
                'p2] polo',
                'p1] marco',
                'p2] polo'
            ]
            self.assertEqual(data_msgs, expected)

            # Some OS's start more processes just for fun... so don't test
            # that p1 and p2 are the only ones.
            # self.assertEqual(len(reprs), 2, reprs)

            p1.halt()
            p2.halt()
            # both p1 and p2 should have finished now, and ended.
            reprs = [repr(p) for p in mp.active_children()]
            for name in procNames:
                self.assertNotIn(name, reprs)

class TestStreamQueue(TestCase):
    def test_connection(self):
        sq = get_stream_queue()
        sq.connect('')
        # TODO: do we really want double-connect to raise? or maybe
        # only raise if the process name changes?
        with self.assertRaises(RuntimeError):
            sq.connect('')
        sq.disconnect()
        with self.assertRaises(RuntimeError):
            sq.disconnect()

    def test_del(self):
        sq = get_stream_queue()
        self.assertTrue(hasattr(sq, 'queue'))
        self.assertTrue(hasattr(sq, 'lock'))
        self.assertIsNotNone(sq.instance)

        sq.__del__()

        self.assertFalse(hasattr(sq, 'queue'))
        self.assertFalse(hasattr(sq, 'lock'))
        self.assertIsNone(sq.instance)

        sq.__del__()  # just to make sure it doesn't error

    # this is basically tested in TestQcodesProcess, but the test happens
    # in a subprocess so coverage doesn't know about it. Anyway, there are
    # a few edge cases left that we have to test locally.
    def test_sq_writer(self):
        sq = get_stream_queue()
        with sq.lock:
            sq_clearer = _SQWriter(sq, 'Someone else')
            sq_clearer.write('Boo!\n')

            # apparently we need a little delay to make sure the queue
            # properly appears populated.
            time.sleep(0.01)

            sq.get()
            sq_name = 'A Queue'
            sqw = _SQWriter(sq, sq_name)

            # flush should exist, but does nothing
            sqw.flush()

            lines = [
                'Knock knock.\nWho\'s there?\n',
                'Interrupting cow.\n',
                'Interr-',
                'MOO!\n',
                ''
            ]

            for line in lines:
                sqw.write(line)

            time.sleep(0.01)

            # _SQWriter doesn't do any transformations to the messages, beyond
            # adding a time string and the stream name
            for line in lines:
                if not line:
                    self.assertEqual(sq.queue.empty(), True)
                    continue

                self.assertEqual(sq.queue.empty(), False)
                timestr, stream_name, msg = sq.queue.get()
                self.assertEqual(msg, line)
                self.assertEqual(stream_name, sq_name)

            # now test that even if the queue is unwatched the messages still
            # go there. If we're feeling adventurous maybe we can test if
            # something was actually printed.
            sqw.MIN_READ_TIME = -1
            new_message = 'should get printed\n'
            sqw.write(new_message)

            time.sleep(0.01)

            self.assertEqual(sq.queue.empty(), False)
            self.assertEqual(sq.queue.get()[2], new_message)

            # test that an error in writing resets stdout and stderr
            # nose uses its own stdout and stderr... so keep them (as we will
            # force stdout and stderr to several other things) so we can put
            # them back at the end
            nose_stdout = sys.stdout
            nose_stderr = sys.stderr
            sys.stdout = _SQWriter(sq, 'mock_stdout')
            sys.stderr = _SQWriter(sq, 'mock_stderr')
            self.assertNotIn(sys.stdout, (sys.__stdout__, nose_stdout))
            self.assertNotIn(sys.stderr, (sys.__stderr__, nose_stderr))

            sqw.MIN_READ_TIME = 'not a number'
            with self.assertRaises(TypeError):
                sqw.write('trigger an error')

            self.assertEqual(sys.stdout, sys.__stdout__)
            self.assertEqual(sys.stderr, sys.__stderr__)

            sys.stdout = nose_stdout
            sys.stderr = nose_stderr
            time.sleep(0.01)
            sq.get()

class ServerManagerTest(ServerManager):
    def _start_server(self):
        # don't really start the server - we'll test its pieces separately,
        # in the main process
        pass

class EmptyServer:
    def __init__(self, query_queue, response_queue, extras):
        query_queue.put('why?')
        response_queue.put(extras)

class CustomError(Exception):
    pass

def delayed_put(queue, val, delay):
    time.sleep(delay)
    queue.put(val)

class TestServerManager(TestCase):
    def check_error(self, manager, error_str, error_class):
        manager._response_queue.put(RESPONSE_ERROR, error_str)
        with self.assertRaises(error_class):
            manager.ask('which way does the wind blow?')

    def test_mechanics(self):
        extras = 'super secret don\'t tell anyone'

        sm = ServerManagerTest(name='test', server_class=EmptyServer,
                               shared_attrs=extras)
        sm._run_server()

        self.assertEqual(sm._query_queue.get(timeout=1), 'why?')
        self.assertEqual(sm._response_queue.get(timeout=1), extras)

        # builtin errors we propagate to the server
        builtin_error_str = ('traceback\n  lines\n and then\n'
                             '  OSError: your hard disk went floppy.')
        sm._response_queue.put((RESPONSE_ERROR, builtin_error_str))
        with self.assertRaises(OSError):
            sm.ask('which way does the wind blow?')

        # non-built-in errors we fall back on RuntimeError
        custom_error_str = ('traceback\nlines\nand then\n'
                            'CustomError: the Balrog is loose!')
        extra_resp1 = 'should get tossed by the error checker'
        extra_resp2 = 'so should this.'
        sm._response_queue.put((RESPONSE_OK, extra_resp1))
        sm._response_queue.put((RESPONSE_OK, extra_resp2))
        sm._response_queue.put((RESPONSE_ERROR, custom_error_str))

        # TODO: we have an intermittent failure below, but only when running
        # the full test suite (including pyqt and matplotlib?), not if we
        # run just this module, or at least not nearly as frequently.
        time.sleep(0.2)

        with LogCapture() as logs:
            with self.assertRaises(RuntimeError):
                sm.ask('something benign')
            self.assertTrue(sm._response_queue.empty())
        self.assertIn(extra_resp1, logs.value)
        self.assertIn(extra_resp2, logs.value)

        # extra responses to a query, only the last should be taken
        extra_resp1 = 'boo!'
        extra_resp2 = 'a barrel of monkeys!'
        sm._response_queue.put((RESPONSE_OK, extra_resp1))
        sm._response_queue.put((RESPONSE_OK, extra_resp2))
        time.sleep(0.05)
        p = mp.Process(target=delayed_put,
                       args=(sm._response_queue, (RESPONSE_OK, 42), 0.05))
        p.start()

        with LogCapture() as logs:
            self.assertEqual(sm.ask('what is the answer'), 42)
        self.assertIn(extra_resp1, logs.value)
        self.assertIn(extra_resp2, logs.value)

        # no response to a query
        with self.assertRaises(Empty):
            sm.ask('A sphincter says what?', timeout=0.05)

        # test halting an unresponsive server
        sm._server = mp.Process(target=time.sleep, args=(1000,))
        sm._server.start()

        self.assertIn(sm._server, mp.active_children())

        with LogCapture() as logs:
            sm.halt(0.01)
        self.assertIn('ServerManager did not respond '
                      'to halt signal, terminated', logs.value)

        self.assertNotIn(sm._server, mp.active_children())

    def test_pathological_edge_cases(self):
        # kill_queue should never fail
        kill_queue(None)

        # and halt should ignore AssertionErrors, which arise in
        # subprocesses when trying to kill a different subprocess
        sm = ServerManagerTest(name='test', server_class=None)

        class HorribleProcess:
            def is_alive(self):
                raise AssertionError

            def write(self):
                raise AssertionError

            def join(self):
                raise AssertionError

        sm._server = HorribleProcess()

        sm.halt()


from functions import is_palindrome as isp
from functions import reverse_int as rint

def is_lychrel(n):
    x = n*1
    for i in range(49):
        x = x + rint(x)
        if isp(x):
            return False
    else:
        return True

print(is_lychrel(1000))

print(is_lychrel(196))

def pb55():
    c = 0
    for n in range(1,10000):
        if is_lychrel(n):
            c += 1
    print(c)

pb55()


import cv2
import numpy as np
from threading import *
import time

face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

Video = cv2.VideoCapture(0)
time.sleep(3)

def face(faces):
    dimension=len(faces)
    if (dimension!=0):
        for (x,y,w,h) in faces:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
    else:
        pass

while True:
    check,frame=Video.read()

    faces=face_cascade.detectMultiScale(frame)
    face(faces)
    cv2.imshow('Captures',frame)
    key=cv2.waitKey(1)
    if key == ord('q'):
        break
Video.release()
cv2.destroyAllWindows()


'''10.	Write a program to count the number of unique words and the number of occurrences of each of those words from the question provided below.
Input:
"How much wood would a woodchuck chuck if the woodchuck could chuck wood?"
Output:
Number of unique words: x
abcd: p times
efgh: q times
rstu: t times
……
(Where abcd, efgh and stuv are words from the given input question; p, q and t are the number of instances these words appear in the input.)
'''

names =input("Enter the sentence")
data = names.split(" ")
unique = []

list_1 = {}
for word in data:
    if not word in list_1:
        list_1[word] = 1
    else:
        list_1[word] +=1

for word_1 in list_1:
    if list_1[word_1] == 1:
        unique.append(word_1)
        print(f"{word_1} : {list_1[word_1]}")

print(f"Unique word length is",len(unique))


# License: GNU Affero General Public License v3 or later
# A copy of GNU AGPL v3 should have been included in this software package in LICENSE.txt.

# for test files, silence irrelevant and noisy pylint warnings
# pylint: disable=protected-access,missing-docstring

import unittest

from Bio.Seq import Seq

import antismash
from antismash.common.test import helpers
from antismash.config import destroy_config, build_config
from antismash.modules import tfbs_finder

class TestTFBSFinder(unittest.TestCase):
    def setUp(self):
        self.options = build_config(["--minimal", "--enable-html", "--tfbs"],
                                    isolated=True, modules=antismash.get_all_modules())

    def tearDown(self):
        destroy_config()

    def test_options(self):
        assert not tfbs_finder.check_options(self.options)
        assert not tfbs_finder.check_prereqs(self.options)
        assert tfbs_finder.is_enabled(self.options)

        options = build_config(["--minimal", "--enable-html",
                                "--tfbs", "--tfbs-pvalue", "-1", "--tfbs-range", "-10"],
                               isolated=True, modules=antismash.get_all_modules())
        issues = tfbs_finder.check_options(options)
        assert len(issues) == 2
        assert "TFBS finder p-value is negative" in issues[0]
        assert "TFBS finder range is negative" in issues[1]

    def test_nisin(self):
        genbank = helpers.get_path_to_nisin_with_detection()
        results = helpers.run_and_regenerate_results_for_module(genbank, tfbs_finder, self.options)
        assert isinstance(results, tfbs_finder.TFBSFinderResults)
        assert results.pvalue == self.options.tfbs_pvalue
        assert results.start_overlap == self.options.tfbs_range
        assert results.record_id == 'HM219853.1'
        assert len(results.hits_by_region) == 1
        feature = results.hits_by_region[1][0]
        assert feature.name == 'NrtR'
        assert feature.start == 290
        assert feature.strand == -1
        self.assertAlmostEqual(feature.score, 24.636, delta=1e-3)

    def test_run_moods(self):
        sequence = Seq("GAATAACGTTAGGCTCAACGTTGCT")
        bg = tfbs_finder.tfbs_finder.get_bg_distribution(sequence)
        matrices = tfbs_finder.tfbs_finder.load_matrices(tfbs_finder.tfbs_finder.PWM_PATH)
        region_start = 100
        all_hits = tfbs_finder.tfbs_finder.run_moods(sequence, bg, matrices, 0.01, region_start)
        matrix_hits = {matrix.name: hits for matrix, hits in zip(matrices, all_hits) if hits}
        assert len(matrix_hits) == 4
        # the scores will be largely useless thanks to the high threshold, but
        # the positional information is worth testing
        expected_positions = {
            "BldD": [(10, -1)],
            "CsoR": [(2, 1)],
            "DmdR1": [(3, 1)],
            "OsdR": [(10, 1)],
        }
        for name, hits in expected_positions.items():
            for hit, expected in zip(matrix_hits[name], hits):
                assert (hit.pos - region_start, hit.strand) == expected


# !/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Author: qixitan
# @Email: qixitan@qq.com
# @FileName: ViT.py
# @Time: 2022/4/20 16:22

import torch
from torch import nn

from einops import rearrange
from einops.layers.torch import Reduce
from torch.nn import functional as F

class PatchEmbedding(nn.Module):
    def __init__(self, inplanes: int = 3, patch_size: int = 16, emb_size: int = 768, image_size:int=224):
        super(PatchEmbedding, self).__init__()
        self.patch_size = patch_size
        self.projection = nn.Conv2d(inplanes, emb_size, kernel_size=patch_size, stride=patch_size)
        self.cls_token = nn.Parameter(torch.randn(1, 1, emb_size))
        self.positions = nn.Parameter(torch.randn((image_size//patch_size)**2+1, emb_size))

    def forward(self, x):
        out = self.projection(x)
        c, b, w, h = out.shape
        out = out.view(c, b, w*h).permute(0, 2, 1)
        cls_token = self.cls_token.repeat(c, 1, 1)
        out = torch.cat([cls_token, out], dim=1)
        out += self.positions
        return out

class MultiHeadAttention(nn.Module):
    def __init__(self, emb_size: int = 768, num_heads: int = 12, dropout: float = 0):
        super(MultiHeadAttention, self).__init__()
        self.emb_size = emb_size
        self.num_heads = num_heads
        # To speed up the calculation, we can use a single matrix to calculate Queries, keys, values.
        self.qkv = nn.Linear(emb_size, emb_size*3)
        self.att_drop = nn.Dropout(dropout)
        self.projection = nn.Linear(emb_size, emb_size)

    def forward(self, x: torch.Tensor, mask: torch.Tensor = None):
        # split keys, queries and values in num_heads
        qkv = rearrange(self.qkv(x), "b n (h d qkv) -> (qkv) b h n d", h=self.num_heads, qkv=3)
        queries, keys, values = qkv[0], qkv[1], qkv[2]
        # sum up over the last axis
        energy = torch.einsum('bhqd, bhkd -> bhqk', queries, keys)  # batch, num_heads, query_len, key_len
        if mask is not None:
            fill_value = torch.finfo(torch.float32).min
            energy.mask_fill(~mask, fill_value)
        scaling = self.emb_size ** (1 / 2)
        att = F.softmax(energy, dim=-1) / scaling
        att = self.att_drop(att)
        # sum up over the third axis
        out = torch.einsum('bhal, bhlv -> bhav ', att, values)
        out = rearrange(out, "b h n d -> b n (h d)")
        out = self.projection(out)
        return out

class ResidualAdd(nn.Module):
    def __init__(self, fn):
        super().__init__()
        self.fn = fn

    def forward(self, x, **kwargs):
        res = x
        x = self.fn(x, **kwargs)
        x += res
        return x

class FeedForwardBlock(nn.Sequential):  # 直接继承nn.Sequential 避免重复写forward
    def __init__(self, emb_size: int, expansion: int = 4, drop_p: float = 0.):
        super().__init__(
            nn.Linear(emb_size, expansion * emb_size),
            nn.GELU(),
            nn.Dropout(drop_p),
            nn.Linear(expansion * emb_size, emb_size),
        )

class TransformerEncoderBlock(nn.Sequential):
    def __init__(self,
                 emb_size: int = 768,
                 num_heads: int = 12,
                 drop_p: float = 0.,
                 forward_expansion: int = 4,
                 forward_drop_p: float = 0.,
                 ** kwargs):
        super().__init__(
            ResidualAdd(nn.Sequential(
                nn.LayerNorm(emb_size),
                MultiHeadAttention(emb_size, num_heads, **kwargs),
                nn.Dropout(drop_p)
            )),
            ResidualAdd(nn.Sequential(
                nn.LayerNorm(emb_size),
                FeedForwardBlock(
                    emb_size, expansion=forward_expansion, drop_p=forward_drop_p),
                nn.Dropout(drop_p)
            )
            ))

class TransformerEncoder(nn.Sequential):
    def __init__(self, depth: int = 12, num_heads: int = 8, **kwargs):
        super().__init__(*[TransformerEncoderBlock(num_heads=num_heads, **kwargs) for _ in range(depth)])

class ClassificationHead(nn.Sequential):
    def __init__(self, emb_size: int = 768, n_classes: int = 1000):
        super().__init__(
            Reduce('b n e -> b e', reduction='mean'),
            nn.LayerNorm(emb_size),
            nn.Linear(emb_size, n_classes))

class ViT_Ti(nn.Sequential):
    def __init__(self,
                 inplanes: int = 3,
                 emb_size: int = 192,
                 num_heads: int = 3,
                 img_size: int = 224,
                 depth: int = 12,
                 patch_size: int = 16,
                 num_classes: int = 1000,
                 **kwargs):
        super().__init__(
            PatchEmbedding(inplanes, patch_size, emb_size, img_size),
            TransformerEncoder(depth, emb_size=emb_size, num_heads=num_heads, **kwargs),
            ClassificationHead(emb_size, num_classes)
        )

class ViT_S(nn.Sequential):
    def __init__(self,
                 inplanes: int = 3,
                 emb_size: int = 384,
                 num_heads: int = 6,
                 img_size: int = 224,
                 depth: int = 12,
                 patch_size: int = 16,
                 num_classes: int = 1000,
                 **kwargs):
        super().__init__(
            PatchEmbedding(inplanes, patch_size, emb_size, img_size),
            TransformerEncoder(depth, emb_size=emb_size, num_heads=num_heads, **kwargs),
            ClassificationHead(emb_size, num_classes)
        )

class ViT_B(nn.Sequential):
    def __init__(self,
                 inplanes: int = 3,
                 emb_size: int = 768,
                 num_heads: int = 12,
                 img_size: int = 224,
                 depth: int = 12,
                 patch_size: int = 16,
                 num_classes: int = 1000,
                 **kwargs):
        super().__init__(
            PatchEmbedding(inplanes, patch_size, emb_size, img_size),
            TransformerEncoder(depth, emb_size=emb_size, num_heads=num_heads, **kwargs),
            ClassificationHead(emb_size, num_classes)
        )

class ViT_L(nn.Sequential):
    def __init__(self,
                 inplanes: int = 3,
                 emb_size: int = 1024,
                 num_heads: int = 16,
                 img_size: int = 224,
                 depth: int = 24,
                 patch_size: int = 16,
                 num_classes: int = 1000,
                 **kwargs):
        super().__init__(
            PatchEmbedding(inplanes, patch_size, emb_size, img_size),
            TransformerEncoder(depth, emb_size=emb_size, num_heads=num_heads, **kwargs),
            ClassificationHead(emb_size, num_classes)
        )


"""
https://contest.yandex.ru/contest/24810/run-report/77259556/

In this task, it is necessary to implement heap sort. In this case, the heap must be implemented independently;
it is impossible to use the implementations available in the language.
First, it is recommended to solve problems about sifting down and up.

Timofey decided to organize a sports programming competition to find talented interns.
Tasks are selected, participants are registered, tests are written.
It remains to figure out how the winner will be determined at the end of the competition.

Each participant has a unique login. When the competition ends, two indicators will be attached to it:
the number of solved problems Pi and the size of the penalty Fi.
The penalty is calculated for unsuccessful attempts and time spent on the task.

Timofey decided to sort the table of results in the following way: when comparing two participants,
the one with more problems solved will go higher. If the number of solved problems is equal,
the participant with the lowest penalty goes first. If the penalties are the same, then the first
one will be the one whose login comes earlier in alphabetical (lexicographical) order.

Timofey ordered sweatshirts for the winners and went to the store to pick them up the day before.
In his absence, he commissioned you to implement a Heapsort algorithm for the results table.

Input Example:
5
alla 4 100
gena 6 1000
gosha 2 90
rita 2 90
timofey 4 80

Output Example:
gena
timofey
alla
gosha
rita

Time Complexity: O(nlogn)
Space Complexity:O(logn)
"""

from dataclasses import dataclass

@dataclass
class User:
    """
    We are using here dataclass  which helps us to generate class code.
    More info - https://habr.com/ru/post/415829/

    When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary.
    In case if we need to allocate thousands of objects, it will take a lot of memory space.
    slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.
    More info - https://wiki.python.org/moin/UsingSlots
    """

    __slots__ = ['username', 'solved', 'errors']
    username: str
    solved: int
    errors: int

    def key(self):
        return -self.solved, self.errors, self.username

    def __gt__(self, other):
        # "Greater than" - means below in the list.
        #  This user has less Pi, greater Fi, and lesser alphabetical name.

        return self.key() > other.key()

    def __lt__(self, other):
        # "Lesser than" - means higher in the list.
        #  This user has greater Pi, less Fi, and greater alphabetical name.

        return self.key() < other.key()

def heapify(arr, n, i):
    # Find largest among root and children
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2

    if left < n and arr[i] < arr[left]:
        largest = left

    if right < n and arr[largest] < arr[right]:
        largest = right

    # If root is not largest, swap with largest and continue heapifying
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        heapify(arr, n, largest)

def heapsort(arr: list):
    n = len(arr)

    for user in range(n // 2, -1, -1):
        # To build a max-heap from any tree, we can thus start heapifying each sub-tree from the bottom up and
        # end up with a max-heap after the function is applied to all the elements including the root element.
        # In the case of a complete tree, the first index of a non-leaf node is given by n/2 - 1.
        # All other nodes after that are leaf-nodes and thus don't need to be heapified.

        heapify(arr, n, user)

    for user in range(n - 1, 0, -1):
        # Remove the root element and put at the end of the array (nth position)
        # Put the last item of the tree (heap) at the vacant place.
        arr[user], arr[0] = arr[0], arr[user]

        # Heapify the root element again so that we have the highest element at root.
        heapify(arr, user, 0)

def read_input_and_create_users():
    n = int(input())
    users = []

    for _ in range(n):
        username, solved, errors = input().split()
        users.append(User(username, int(solved), int(errors)))

    return users

if __name__ == '__main__':
    users = read_input_and_create_users()
    heapsort(users)

    for user in users:
        print(user.username)


import torch
import torch.nn as nn
from torch.autograd import Function
from torchvision.models.utils import load_state_dict_from_url

'''
Very easy template to start for developing your AlexNet with DANN
Has not been tested, might contain incompatibilities with most recent versions of PyTorch (you should address this)
However, the logic is consistent
'''

class ReverseLayerF(Function):
    # Forwards identity
    # Sends backward reversed gradients
    @staticmethod
    def forward(ctx, x, alpha):
        ctx.alpha = alpha

        return x.view_as(x)

    @staticmethod
    def backward(ctx, grad_output):
        output = grad_output.neg() * ctx.alpha

        return output, None

class RandomNetworkWithReverseGrad(nn.Module):
    #def __init__(self, **kwargs):
    def __init__(self, NUM_CLASSES=1000, NUM_DOMAINS=10):
        super(RandomNetworkWithReverseGrad, self).__init__()
        # adding conv parameters, took from AlexNet self.features = nn.Sequentia(etc.
        self.features = nn.Sequential(
        	nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        # adding fc parameters, took from AlexNet self.classifier = nn.Sequential( etc)
        self.classifier = nn.Sequential(
        	nn.Dropout(),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, NUM_CLASSES),
        )
        # same architecture of AlexNet's FC but adding a new densely connected branch with 2 output neurons (TO FINISH)
        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
        self.domain_classifier = nn.Sequential(
        	nn.Dropout(),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, NUM_DOMAINS),
        )

    def update(self):
        self.domain_classifier[1].weight.data = self.classifier[1].weight.data
        self.domanin_classifier[1].bias.data = self.classifier[1].bias.data

        self.domain_classifier[4].weight.data = self.classifier[4].weight.data
        self.domain_classifier[4].bias.data = self.classifier[4].bias.data

    def forward(self, x, alpha=None):
        features = self.features(x);
        features = self.avgpool(features)
        features = torch.flatten(features, 1)
        # If we pass alpha, we can assume we are training the discriminator
        if alpha is not None:
            # gradient reversal layer (backward gradients will be reversed)
            reverse_feature = ReverseLayerF.apply(features, alpha)
            discriminator_output = self.domain_classifier(features);
            return discriminator_output
        # If we don't pass alpha, we assume we are training with supervision
        else:
            # do something else
            class_outputs = self.classifier(features);
            return class_outputs

    def DANN_AlexNet(pretrained=False, progress=True, **kwargs):
        r"""AlexNet model architecture from the
        `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
        Args:
            pretrained (bool): If True, returns a model pre-trained on ImageNet
            progress (bool): If True, displays a progress bar of the download to stderr
    """
        model = RandomNetworkWithReverseGrad(**kwargs)
        if pretrained:
            state_dict = load_state_dict_from_url(model_urls['alexnet'],
                                                    progress = progress
                                                    )
            state_dict.popitem("classifier.6.weight")
            state_dict.popitem("classifier.6.bias")

            model.load_state_dict(state_dict, strict=False)
            model.update()
        return model


import csv
from fingerprint import main
import numpy as np

if __name__ == "__main__":
    test = []
    with open("./test_common.csv", "r", newline="") as r:
        reader = csv.reader(r)
        line = 0
        for row in reader:
            if line == 1:
                test.append(row)
            line = 1
    #print(np.array(test).shape)
    train = []
    with open("./train_common.csv", "r", newline="") as r:
        reader = csv.reader(r)
        line = 0
        for row in reader:
            if line == 1:
                train.append(row)
            line = 1
    #print(train)
    #dbclass = 5
    classNum = 10
    trainNum = 1
    testNum = 7
    right = 0
    #for db in range(dbclass):
    for index in range(classNum):
        trainImage = train[index][0]
        for te in range(testNum):
            testImage = test[testNum*index+te][0]
            image = []
            image.append(trainImage)
            image.append(testImage)
            result = main(image)
            if result == 1:
                right+=1
            print(index,te)
    print(right)
    print(right/len(test))


from pizza.default.fileInput import *
from pizza.default.fileOutput import *
import math

inputPath = '../input/'
outputPath = './output/'

exampleFile = 'example'
smallFile = 'small'
mediumFile = 'medium'
bigFile = 'big'

currentFile = bigFile

info, pizza = readAndParseInputFile(inputPath + currentFile + '.in')

print(info)
print(pizza)

size = math.floor(math.sqrt(int(info['maxCellsPerSlice'])))

slices = []

for x in range(0, int(info['rows'])-size+1, size):
    for y in range(0, int(info['columns'])-size+1, size):
        xend = x+size-1
        yend = y+size-1
        slices.append([x, y, xend, yend])

print(slices)

parseAndSaveOutputFile(slices, outputPath + currentFile + '.out')


from scipy.spatial import distance as dist
from collections import OrderedDict
import numpy as np
import cv2
import enum

class Colors(enum.IntEnum):
   Green = 0
   Red = 1
   Blue = 2
   Yellow = 3
   Cyan = 4
   Purple = 5

class ColorDetector:
   def __init__(self, colorSettings):
      self.initColors(colorSettings)

   def detectColor(self, frame, contour):
      # construct a mask for the contour, then compute the
      # average L*a*b* value for the masked region
      mask = np.zeros(frame.shape[:2], dtype="uint8")
      cv2.drawContours(mask, [contour], -1, 255, -1)
      mask = cv2.erode(mask, None, iterations=2)
      mean = cv2.mean(frame, mask=mask)[:3]
      # initialize the minimum distance found thus far
      minDist = (np.inf, None)
      # loop over the known L*a*b* color values
      for (i, color) in enumerate(self.colors):
          # compute the distance between the current L*a*b*
          # color value and the mean of the image
          distance = dist.euclidean(color, mean)
          # if the distance is smaller than the current distance,
          # then update the bookkeeping variable
          if distance < minDist[0]:
              minDist = (distance, i)
          # return the name of the color with the smallest distance
      return self.colorCodes[minDist[1]]

   def initColors(self, colorSettings):
      colors = OrderedDict()
      colors[Colors.Red] = colorSettings.baseRedColor
      colors[Colors.Purple] = colorSettings.basePurpleColor
      colors[Colors.Green] = colorSettings.baseGreenColor
      colors[Colors.Cyan] = colorSettings.baseCyanColor
      colors[Colors.Blue] = colorSettings.baseBlueColor
      colors[Colors.Yellow] = colorSettings.baseYellowColor

      # allocate memory for the L*a*b* image, then initialize
      # the color names list
      self.colors = np.zeros((len(colors), 1, 3), dtype="uint8")
      self.colorCodes = []
      # loop over the colors dictionary
      for (i, (colorCode, value)) in enumerate(colors.items()):
          self.colors[i] = value
          self.colorCodes.append(colorCode)


# http://www.checkio.org/mission/roman-numerals/solve/
__author__ = 'ken'

SYMBOLS = [
    [1000, "M"],
    [900, "CM"],
    [500, "D"],
    [400, "CD"],
    [100, "C"],
    [90, "XC"],
    [50, "L"],
    [40, "XL"],
    [10, "X"],
    [9, "IX"],
    [5, "V"],
    [4, "IV"],
    [1, "I"],
]

def checkio(data):
    syms = []
    for number, symbol in SYMBOLS:
        while number <= data:
            syms.append(symbol)
            data -= number
    return "".join(syms)

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio(6) == 'VI', '6'
    assert checkio(76) == 'LXXVI', '76'
    assert checkio(499) == 'CDXCIX', '499'
    assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888'


from brownie import VyraNft, accounts, config
from brownie.network import priority_fee
import os

metadata_dir = "/Users/user/projects/vera-nft/metadata/nft_metadata/ipfs_metadata/"

def main():
    account = accounts.add(config["wallets"]["from_key"])
    vyra_nft = VyraNft[-1]
    directory = os.fsencode(metadata_dir)
    for file in os.listdir(directory):
        metadata_file = os.fsdecode(file)
        metadata_json = open(f"{metadata_dir}{metadata_file}", encoding="utf-8").read()
        print(metadata_json)
        vyra_nft = VyraNft[len(VyraNft) - 1]
        vyra_nft.createCollectible(
            metadata_json,
            {
                "from": account,
                "amount": 8000000000000000,
                "gas_price": priority_fee(),
                "gas_limit": 12000000,
                "allow_revert": True,
            },
        )
        print("New NFT Minted\n")


from __future__ import print_function

import grpc
import numpy as np
import requests
import sys
import tensorflow.compat.v1 as tf_v1
import tensorflow as tf
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc

from util import preprocess_image

# The image URL is the location of the image we should send to the server
IMAGE_URL = 'https://tensorflow.org/images/blogs/serving/cat.jpg'

tf_v1.app.flags.DEFINE_string('server', 'localhost:8500', 'PredictionService host:port')
tf_v1.app.flags.DEFINE_string('image', '', 'path to image in JPEG format')
tf_v1.app.flags.DEFINE_string('model', 'resnet50', 'Name of model (resnet50 or Inceptionv3).')
FLAGS = tf_v1.app.flags.FLAGS

def main(_):
    if FLAGS.model == 'resnet50':
        image_size = 224
    elif FLAGS.model == 'inceptionv3':
        image_size = 299
    else:
        print('Please specify model as either resnet50 or Inceptionv3.')
        sys.exit(-1)

    if FLAGS.image:
        with open(FLAGS.image, 'rb') as f:
            data = f.read()
    else:
        # Download the image URL if a path is not provided as input
        dl_request = requests.get(IMAGE_URL, stream=True)
        dl_request.raise_for_status()
        data = dl_request.content

    channel = grpc.insecure_channel(FLAGS.server)
    stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
    request = predict_pb2.PredictRequest()
    request.model_spec.name = FLAGS.model
    request.model_spec.signature_name = 'serving_default'
    image_data = tf.reshape(preprocess_image(data, FLAGS.model, image_size), [1, image_size, image_size, 3])

    # Run the graph
    with tf_v1.Session() as sess:
        sess.run(tf_v1.global_variables_initializer())
        image_data = (sess.run(image_data))

    request.inputs['input'].CopyFrom(
        tf.make_tensor_proto(image_data, shape=[1, image_size, image_size, 3]))
    result = stub.Predict(request)
    print('Predicted class: ', str(np.argmax(result.outputs['predict'].float_val)))

if __name__ == '__main__':
    tf_v1.disable_eager_execution()
    tf_v1.app.run()


#local host server

import socket
import sys
import hashlib

GOOD = "260 OK\n"
SIG = "270 SIG\n"

def getfile(f):
    file = open(f, "r")
    arr = []
    for line in file:
        arr.append(line.strip())
    file.close()
    return arr

#prints out responses so i dont have to keep typing it
def get(sock):
    res = sock.recv(1024).decode("ASCII").strip()
    print(res)
    return res
#get just one byte
def getByte(sock):
    res = sock.recv(1).decode("ASCII")
    return res

def hash(msg, key):
    hsh = hashlib.sha256(msg.encode("ASCII"))
    hsh.update(key.encode("ASCII"))
    return hsh.hexdigest()

#escapes \ and .
def escape(msg):
    msg = msg.replace(".", "\\.")
    return msg
def unescape(msg):
    msg = msg.replace("\\.", ".")
    return msg

def main():
    keyFile = sys.argv[2]
    keys = getfile(keyFile)

    serverPort = int(sys.argv[1])
    ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ss.bind(('', serverPort))

    ss.listen(1)
    cs, addr = ss.accept()
    res = get(cs)
    #initial hello
    if res != "HELLO":
        print("ERROR")
        cs.close()
        ss.close()
        return
    cs.send(GOOD.encode("ASCII"))
    for k in keys:
        cmd = get(cs)
        if cmd == "DATA":
            msg = ""
            dt = getByte(cs)
            while dt != "\n":
                msg += dt
                dt = getByte(cs)
            msg = unescape(msg)
            print(msg)
            dt = get(cs)
            hsh = hash(msg,k)
            cs.send(SIG.encode("ASCII"))
            cs.send((hsh+"\n").encode("ASCII"))
            pf = get(cs)
            if pf != "PASS" and pf != "FAIL":
                print("ERROR")
                cs.close()
                break
            cs.send(GOOD.encode("ASCII"))
        else:
            if(cmd != "QUIT"):
                print("ERROR")
            cs.close()
            ss.close()
            return

if __name__ == "__main__":
    main()