from typing import *
from graphviz import Digraph, nohtml
from operator import itemgetter

def binary_search_to_insert(arr, key, getter=None):
    min = 0
    max = len(arr)
    if getter is None:
        while min != max:
            middle = (min+max)//2
            if arr[middle] == key:
                return middle
            if key < arr[middle]:
                max = middle
            else:
                min = middle+1
    else:
        while min < max:
            middle = (min+max)//2
            if getter(key) == getter(arr[middle]):
                return middle
            if getter(key) < getter(arr[middle]):
                max = middle
            else:
                min = middle+1
    return min

class Item:
    index = 0
    def __init__(self, key, value):
        self._key = key
        self._value = value
        Item.index += 1
        self.index = Item.index

    @property
    def key(self):
        return self._key

    @property
    def value(self):
        return self._value

    def __getitem__(self, key):
        if key == 'key':
            return self.key
        else:
            return self.value

    def __repr__(self):
        return f'<Item {{{self.key}:{self.value}}}>'

    def __str__(self):
        return f'{{{self.key}:{self.value}}}'

class Node:
    index = 0
    def __init__(self, isLeaf):
        self.isLeaf = isLeaf
        self.items = []
        self.pointers = [None]
        self.parent = None
        self.posInParent = 0
        Node.index += 1
        self.index = Node.index+1

    @property
    def size(self):
        return len(self.items)

    def setPointers(self, index, child):
        if len(self.pointers) <= index:
            self.pointers.append(child)
        else:
            self.pointers[index] = child

    def insertToLeaf(self, item):
        pos = binary_search_to_insert(self.items, item, itemgetter('key'))
        if pos < self.size:
            prevSize = self.size
            self.items.append(None)
            self.pointers.append(None)
            for i in reversed(range(pos, prevSize)):
                self.items[i+1] = self.items[i]
                self.pointers[i+1] = None
            self.items[pos] = item
        else:
            self.items.append(item)
            self.pointers.append(None)

    def bubbleToParent(self, pos, middleItem, leftChild, rightChild):
        if middleItem.key == 15:
            pass
        pos = self.posInParent
        parent = self.parent
        if parent is None:
            parent = Node(False)
        leftChild.parent = parent
        leftChild.posInParent = pos
        rightChild.parent = parent
        rightChild.posInParent = pos+1

        print(f'{id(leftChild.parent)}')
        print(f'{id(rightChild.parent)}')

        prevSize = parent.size
        parent.items.append(None)
        parent.pointers.append(None)
        # 先移动尾部，最右孩子指针
        parent.pointers[prevSize+1] = parent.pointers[prevSize]
        if parent.pointers[prevSize+1] is not None:
            parent.pointers[prevSize+1].posInParent = prevSize+1
        for i in reversed(range(pos, prevSize)):
            parent.items[i+1] = parent.items[i]
            parent.pointers[i+1] = parent.pointers[i]
            parent.pointers[i+1].posInParent = i+1
        parent.items[pos] = middleItem
        parent.pointers[pos] = leftChild
        parent.pointers[pos+1] = rightChild
        print(f'{id(parent)}')
        return parent

    def split(self):
        middle = self.size//2
        leftChild = Node(self.isLeaf)
        leftChild.items = self.items[:middle]
        for i in range(middle+1):
            node = self.pointers[i]
            pos = i
            leftChild.setPointers(pos, node)
            if node is not None:
                node.parent = leftChild
                node.posInParent = i
        rightChild = Node(self.isLeaf)
        rightChild.items = self.items[middle+1:]
        for i in range(middle+1, self.size+1):
            node = self.pointers[i]
            pos = i-(middle+1)
            rightChild.setPointers(pos, node)
            if node is not None:
                node.parent = rightChild
                node.posInParent = i-(middle+1)
        return leftChild, self.items[middle], rightChild

class BTree:
    def __init__(self, rank):
        self.rank = rank
        self.root = Node(True)

    def traverse(self, g=None):
        print(f'###### traverse ######')
        self._traverse(self.root, g)
        pass

    def insert(self, item: Item):
        node = self._find_node_to_insert(self.root, item)
        node.insertToLeaf(item)
        if node.size <= self.rank-1:
            return
        print(item.key)
        while True:
            leftChild, middleItem, rightChild = node.split()
            print('########')
            parent = node.bubbleToParent(node.posInParent, middleItem, leftChild, rightChild)
            print(f'{id(parent)}')
            if parent.parent is None:
                self.root = parent
            node = parent
            print(f'{id(node)}')
            if node.size <= self.rank-1:
                break

    def _find_node_to_insert(self, node: Node, item: Item):
        if node.isLeaf:
            return node
        items_len =  node.size
        for i in range(items_len):
            if item.key < node.items[i].key:
                return self._find_node_to_insert(node.pointers[i], item)
        return self._find_node_to_insert(node.pointers[items_len], item)

    def _traverse(self, node, g, depth = 0):
        print(f'{" "*depth*4} _traverse')
        print(f'{" "*depth*4} pos = {node.posInParent}')
        if g is not None:
            nohtml_list = []
            for i in range(node.size):
                if node.pointers[i] is not None:
                    nohtml_list.append(f'<f{str(id(node.pointers[i]))}>')
                nohtml_list.append(f'{node.items[i].key}:{node.items[i].index}')
            if node.size > 0:
                if node.pointers[node.size] is not None:
                    nohtml_list.append(f'<f{str(id(node.pointers[node.size]))}>')
            print(f'{" "*depth*4} {str(id(node))}:{"|".join(nohtml_list)}')
            g.node(str(id(node)), nohtml('|'.join(nohtml_list)))
            if node.parent is not None:
                print(f'{" "*depth*4} {str(id(node.parent))}:f{str(id(node))} -> {str(id(node))}')
                g.edge(f'{str(id(node.parent))}:f{str(id(node))}', f'{str(id(node))}')

        for i in range(node.size):
            if node.pointers[i] is not None:
                self._traverse(node.pointers[i], g, depth+1)
            print(f'{" "*depth*4} {node.items[i]}')

        if node.size > 0:
            if node.pointers[node.size] is not None:
                self._traverse(node.pointers[node.size], g, depth+1)

def btree_easy_insert(btree, key):
    # print(f'insert {key}')
    btree.insert(Item(key, key))

def build_render():
    g = Digraph(format='png', node_attr={'shape': 'record', 'height': '.1'})
    return g

if __name__ == '__main__':
    arr = [1, 23, 12, 8, 9, 7]
    arr = map(lambda x: Item(x, x), arr)

    btree = BTree(5)
    for item in arr:
        btree.insert(item)
    # btree.traverse()
    btree_easy_insert(btree, 19)
    btree_easy_insert(btree, 28)
    # btree.traverse()
    btree_easy_insert(btree, 26)
    btree_easy_insert(btree, 18)
    btree_easy_insert(btree, 20)
    btree_easy_insert(btree, 10)
    btree_easy_insert(btree, 5)
    btree_easy_insert(btree, 2)
    btree_easy_insert(btree, 15)
    btree_easy_insert(btree, 16)
    btree_easy_insert(btree, 17)
    btree_easy_insert(btree, 15)
    btree_easy_insert(btree, 16)
    btree_easy_insert(btree, 16)
    btree_easy_insert(btree, 15)
    btree_easy_insert(btree, 15)
    btree_easy_insert(btree, 16)
    btree_easy_insert(btree, 16)
    btree_easy_insert(btree, 16)
    # btree_easy_insert(btree, 29)

    g = build_render()
    btree.traverse(g)
    g.render(filename='tmp/g', view=True)


from autovirt.structs import Message

def units_to_rise_salary(messages: list[Message]) -> list:
    units = []
    for message in messages:
        for attach in message.attaches:
            units.append(
                {
                    "id": attach["object_id"],
                    "name": attach["object_name"],
                    "salary_demanded": float(attach["tag"]),
                }
            )
    return units

def units_to_update_salary(units: list) -> list[dict]:
    res = []
    for unit in units:
        if float(unit["labor_level"]) < float(unit["employee_level_required"]):
            res.append(unit)
    return res


from abc import ABCMeta, abstractmethod
from functools import wraps
from typing import Callable, Iterable, List, Set, Union, Any

from ...errors import SlackObjectFormationError

class BaseObject:
    def __str__(self):
        return f"<slack.{self.__class__.__name__}>"

class JsonObject(BaseObject, metaclass=ABCMeta):
    @property
    @abstractmethod
    def attributes(self) -> Set[str]:
        """
        Provide a set of attributes of this object that will make up its JSON structure
        """
        return set()

    def validate_json(self) -> None:
        """
        Raises:
          SlackObjectFormationError if the object was not valid
        """
        for attribute in (func for func in dir(self) if not func.startswith("__")):
            method = getattr(self, attribute)
            if callable(method) and hasattr(method, "validator"):
                method()

    def get_non_null_attributes(self) -> dict:
        """
        Construct a dictionary out of non-null keys (from attributes property)
        present on this object
        """
        return {
            key: getattr(self, key, None)
            for key in sorted(self.attributes)
            if getattr(self, key, None) is not None
        }

    def to_dict(self, *args: Any) -> dict:
        """
        Extract this object as a JSON-compatible, Slack-API-valid dictionary

        Args:
          *args: Any specific formatting args (rare; generally not required)

        Raises:
          SlackObjectFormationError if the object was not valid
        """
        self.validate_json()
        return self.get_non_null_attributes()

    def __repr__(self):
        json = self.to_dict()
        if json:
            return f"<slack.{self.__class__.__name__}: {json}>"
        else:
            return self.__str__()

class JsonValidator:
    def __init__(self, message: str):
        """
        Decorate a method on a class to mark it as a JSON validator. Validation
            functions should return true if valid, false if not.

        Args:
            message: Message to be attached to the thrown SlackObjectFormationError
        """
        self.message = message

    def __call__(self, func: Callable) -> Callable[..., None]:
        @wraps(func)
        def wrapped_f(*args, **kwargs):
            if not func(*args, **kwargs):
                raise SlackObjectFormationError(self.message)

        wrapped_f.validator = True
        return wrapped_f

class EnumValidator(JsonValidator):
    def __init__(self, attribute: str, enum: Iterable[str]):
        super().__init__(
            f"{attribute} attribute must be one of the following values: "
            f"{', '.join(enum)}"
        )

def extract_json(
    item_or_items: Union[JsonObject, List[JsonObject], str], *format_args
) -> Union[dict, List[dict], str]:
    """
    Given a sequence (or single item), attempt to call the to_dict() method on each
    item and return a plain list. If item is not the expected type, return it
    unmodified, in case it's already a plain dict or some other user created class.

    Args:
      item_or_items: item(s) to go through
      format_args: Any formatting specifiers to pass into the object's to_dict
            method
    """
    try:
        return [
            elem.to_dict(*format_args) if isinstance(elem, JsonObject) else elem
            for elem in item_or_items
        ]
    except TypeError:  # not iterable, so try returning it as a single item
        return (
            item_or_items.to_dict(*format_args)
            if isinstance(item_or_items, JsonObject)
            else item_or_items
        )


import os
import cv2 as cv
import numpy as np
import labeling as lbl

for _i in range(1,4):
    prefix = 'frame_1_{:02d}'.format(_i)
    img = cv.imread('frames/{:s}.png'.format(prefix),0)
    tile_size = 16
    tile_num_x = 77
    tile_num_y = 77
    _path = 'data/'+prefix+'_data_'+str(tile_size)
    if os.path.isdir(_path) is False:
        os.makedirs(_path)
    # cv.imshow('original',img)
    img = cv.medianBlur(img,21)

    print(_i)
    # get border from user and save it
    selected_border = lbl.input(img).getPoints()
    cv.imwrite(_path+'/selected_border.png',np.array(selected_border*255,dtype=np.uint8))

    # get border from saved file and tile and class the data
    selected_border = cv.imread(_path+'/selected_border.png',0)/255
    lbl.tile_and_save(img,tile_size,selected_border, _path)


# -*- coding: utf-8 -*-
r"""Test for foo.py

This outputs:

  - test results to value of variable "test_dir"

This depends on:

  - source files written from the value of "source_dir"

Examples of usage:

  - default usage:

        python -m pytest test_foo.py

descriptions:
    every function is a separate test, combined usage with pytest module
"""

import os
# import pytest
import filecmp  # for compare file contents
import numpy as np
# import shilofue.Foo as Foo  # import test module
from shilofue.Group import  *
# from matplotlib import pyplot as plt
# from shutil import rmtree  # for remove directories

test_dir = ".test"
test_local_dir = os.path.join(test_dir, "test_group")
source_dir = os.path.join(os.path.dirname(__file__), 'fixtures', 'test_group')

if not os.path.isdir(test_dir):
    # check we have the directory to store test result
    os.mkdir(test_dir)

# make new test directory
if os.path.isdir(test_local_dir):
    rmtree(test_local_dir)
os.mkdir(test_local_dir)

def test_documentation_group_in_dir():
    '''
    test the implementation of documentation
    Asserts:
    '''
    group_dir = os.path.join(source_dir, "test_documentation_group_in_dir")
    assert(os.path.isdir(group_dir))
    GDoc = GDOC()
    GDoc.execute(group_dir, o_dir=test_local_dir)
    # assert something
    mkd_file = os.path.join(test_local_dir, "documentation", "group_doc.mkd")
    mkd_file_std = os.path.join(group_dir, "group_doc_std.mkd")
    assert(os.path.isfile(mkd_file)) # assert file generation
    assert(filecmp.cmp(mkd_file, mkd_file_std)) # assert file contents
    latex_file = os.path.join(test_local_dir, "documentation", "group_doc.tex")
    latex_file_std = os.path.join(group_dir, "group_doc_std.tex")
    assert(os.path.isfile(latex_file)) # assert file generation
    assert(filecmp.cmp(latex_file, latex_file_std)) # assert file contents

# notes

# to check for error message
    # with pytest.raises(SomeError) as _excinfo:
    #    foo()
    # assert(r'foo' in str(_excinfo.value))

# assert the contents of file
    # assert(filecmp.cmp(out_path, std_path))


import tensorflow as tf
# 所有参数
RNN_Cell = tf.nn.rnn_cell.LSTMCell
hidden_size = 450
batch_size = 64
cell_nums = 2
epoch_num = 10
lr = 0.001
clip = 5.0
dropout = 0.75
num_tags = 16
update_embedding = True
embedding_dim = 200
shuffle = False
isTrain = False
CRF = True
max_model_num = 5


#!/usr/bin/env python3

def _blocked_vertically(tree_height, tree_grid, row, col_start, col_end):
    for test_col in range(col_start, col_end):
        if tree_grid[row][test_col] >= tree_height:
            return True
    return False

def _blocked_horizontally(tree_height, tree_grid, col, row_start, row_end):
    for test_row in range(row_start, row_end):
        if tree_grid[test_row][col] >= tree_height:
            return True
    return False

def part1(tree_grid):
    num_visible = 0
    for row in range(len(tree_grid)):
        for col in range(len(tree_grid[0])):
            if (row == 0) or (row == (len(tree_grid) - 1)) or (col == 0) or (col == (len(tree_grid[0]) - 1)):
                num_visible += 1 # tree is on the outside, always going to be visible
            else:
                tree_height = tree_grid[row][col]
                visible = (
                    not _blocked_vertically(tree_height, tree_grid, row, 0, col) or # check up
                    not _blocked_vertically(tree_height, tree_grid, row, col + 1, len(tree_grid[0])) or # check down
                    not _blocked_horizontally(tree_height, tree_grid, col, 0, row) or # check left
                    not _blocked_horizontally(tree_height, tree_grid, col, row + 1, len(tree_grid)) # check right
                )
                num_visible = num_visible + 1 if visible else num_visible

    return num_visible

def _viewing_distance(tree_grid, row, col, row_start, row_end, col_start, col_end, hstep=1, vstep=1):
    tree_height = tree_grid[row][col]
    distance = 0
    for test_row in range(row_start, row_end, hstep):
        for test_col in range(col_start, col_end, vstep):
            if tree_grid[test_row][test_col] >= tree_height:
                distance += 1
                return distance
            distance += 1
    return distance

def part2(tree_grid):
    highest_scenic_score = 0
    for row in range(len(tree_grid)):
        for col in range(len(tree_grid[0])):
            scenic_score = 1
            scenic_score *= _viewing_distance(tree_grid, row, col, row, row+1, col - 1, -1, vstep=-1) # up
            scenic_score *= _viewing_distance(tree_grid, row, col, row, row+1, col + 1, len(tree_grid[0])) # down
            scenic_score *= _viewing_distance(tree_grid, row, col, row - 1, -1, col, col + 1, hstep=-1) # left
            scenic_score *= _viewing_distance(tree_grid, row, col, row + 1, len(tree_grid), col, col + 1) # right
            if scenic_score > highest_scenic_score:
                highest_scenic_score = scenic_score

    return highest_scenic_score

if __name__ == "__main__":
    tree_grid = []
    with open("input.txt", 'r') as f:
        for line in f:
            tree_grid.append([int(x) for x in line.strip()])

    print(f"Part 1: {part1(tree_grid)}")
    print(f"Part 2: {part2(tree_grid)}")


# testing.py

from contextlib import contextmanager
import typing

from .core import (
    ParserElement,
    ParseException,
    Keyword,
    __diag__,
    __compat__,
)

class pyparsing_test:
    """
    namespace class for classes useful in writing unit tests
    """

    class reset_pyparsing_context:
        """
        Context manager to be used when writing unit tests that modify pyparsing config values:
        - packrat parsing
        - bounded recursion parsing
        - default whitespace characters.
        - default keyword characters
        - literal string auto-conversion class
        - __diag__ settings

        Example::

            with reset_pyparsing_context():
                # test that literals used to construct a grammar are automatically suppressed
                ParserElement.inlineLiteralsUsing(Suppress)

                term = Word(alphas) | Word(nums)
                group = Group('(' + term[...] + ')')

                # assert that the '()' characters are not included in the parsed tokens
                self.assertParseAndCheckList(group, "(abc 123 def)", ['abc', '123', 'def'])

            # after exiting context manager, literals are converted to Literal expressions again
        """

        def __init__(self):
            self._save_context = {}

        def save(self):
            self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS
            self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS

            self._save_context[
                "literal_string_class"
            ] = ParserElement._literalStringClass

            self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace

            self._save_context["packrat_enabled"] = ParserElement._packratEnabled
            if ParserElement._packratEnabled:
                self._save_context[
                    "packrat_cache_size"
                ] = ParserElement.packrat_cache.size
            else:
                self._save_context["packrat_cache_size"] = None
            self._save_context["packrat_parse"] = ParserElement._parse
            self._save_context[
                "recursion_enabled"
            ] = ParserElement._left_recursion_enabled

            self._save_context["__diag__"] = {
                name: getattr(__diag__, name) for name in __diag__._all_names
            }

            self._save_context["__compat__"] = {
                "collect_all_And_tokens": __compat__.collect_all_And_tokens
            }

            return self

        def restore(self):
            # reset pyparsing global state
            if (
                ParserElement.DEFAULT_WHITE_CHARS
                != self._save_context["default_whitespace"]
            ):
                ParserElement.set_default_whitespace_chars(
                    self._save_context["default_whitespace"]
                )

            ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"]

            Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"]
            ParserElement.inlineLiteralsUsing(
                self._save_context["literal_string_class"]
            )

            for name, value in self._save_context["__diag__"].items():
                (__diag__.enable if value else __diag__.disable)(name)

            ParserElement._packratEnabled = False
            if self._save_context["packrat_enabled"]:
                ParserElement.enable_packrat(self._save_context["packrat_cache_size"])
            else:
                ParserElement._parse = self._save_context["packrat_parse"]
            ParserElement._left_recursion_enabled = self._save_context[
                "recursion_enabled"
            ]

            __compat__.collect_all_And_tokens = self._save_context["__compat__"]

            return self

        def copy(self):
            ret = type(self)()
            ret._save_context.update(self._save_context)
            return ret

        def __enter__(self):
            return self.save()

        def __exit__(self, *args):
            self.restore()

    class TestParseResultsAsserts:
        """
        A mixin class to add parse results assertion methods to normal unittest.TestCase classes.
        """

        def assertParseResultsEquals(
            self, result, expected_list=None, expected_dict=None, msg=None
        ):
            """
            Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,
            and compare any defined results names with an optional ``expected_dict``.
            """
            if expected_list is not None:
                self.assertEqual(expected_list, result.as_list(), msg=msg)
            if expected_dict is not None:
                self.assertEqual(expected_dict, result.as_dict(), msg=msg)

        def assertParseAndCheckList(
            self, expr, test_string, expected_list, msg=None, verbose=True
        ):
            """
            Convenience wrapper assert to test a parser element and input string, and assert that
            the resulting ``ParseResults.asList()`` is equal to the ``expected_list``.
            """
            result = expr.parse_string(test_string, parse_all=True)
            if verbose:
                print(result.dump())
            else:
                print(result.as_list())
            self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)

        def assertParseAndCheckDict(
            self, expr, test_string, expected_dict, msg=None, verbose=True
        ):
            """
            Convenience wrapper assert to test a parser element and input string, and assert that
            the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``.
            """
            result = expr.parse_string(test_string, parseAll=True)
            if verbose:
                print(result.dump())
            else:
                print(result.as_list())
            self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)

        def assertRunTestResults(
            self, run_tests_report, expected_parse_results=None, msg=None
        ):
            """
            Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of
            list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped
            with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.
            Finally, asserts that the overall ``runTests()`` success value is ``True``.

            :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests
            :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]
            """
            run_test_success, run_test_results = run_tests_report

            if expected_parse_results is not None:
                merged = [
                    (*rpt, expected)
                    for rpt, expected in zip(run_test_results, expected_parse_results)
                ]
                for test_string, result, expected in merged:
                    # expected should be a tuple containing a list and/or a dict or an exception,
                    # and optional failure message string
                    # an empty tuple will skip any result validation
                    fail_msg = next(
                        (exp for exp in expected if isinstance(exp, str)), None
                    )
                    expected_exception = next(
                        (
                            exp
                            for exp in expected
                            if isinstance(exp, type) and issubclass(exp, Exception)
                        ),
                        None,
                    )
                    if expected_exception is not None:
                        with self.assertRaises(
                            expected_exception=expected_exception, msg=fail_msg or msg
                        ):
                            if isinstance(result, Exception):
                                raise result
                    else:
                        expected_list = next(
                            (exp for exp in expected if isinstance(exp, list)), None
                        )
                        expected_dict = next(
                            (exp for exp in expected if isinstance(exp, dict)), None
                        )
                        if (expected_list, expected_dict) != (None, None):
                            self.assertParseResultsEquals(
                                result,
                                expected_list=expected_list,
                                expected_dict=expected_dict,
                                msg=fail_msg or msg,
                            )
                        else:
                            # warning here maybe?
                            print(f"no validation for {test_string!r}")

            # do this last, in case some specific test results can be reported instead
            self.assertTrue(
                run_test_success, msg=msg if msg is not None else "failed runTests"
            )

        @contextmanager
        def assertRaisesParseException(self, exc_type=ParseException, msg=None):
            with self.assertRaises(exc_type, msg=msg):
                yield

    @staticmethod
    def with_line_numbers(
        s: str,
        start_line: typing.Optional[int] = None,
        end_line: typing.Optional[int] = None,
        expand_tabs: bool = True,
        eol_mark: str = "|",
        mark_spaces: typing.Optional[str] = None,
        mark_control: typing.Optional[str] = None,
    ) -> str:
        """
        Helpful method for debugging a parser - prints a string with line and column numbers.
        (Line and column numbers are 1-based.)

        :param s: tuple(bool, str - string to be printed with line and column numbers
        :param start_line: int - (optional) starting line number in s to print (default=1)
        :param end_line: int - (optional) ending line number in s to print (default=len(s))
        :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default
        :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default="|")
        :param mark_spaces: str - (optional) special character to display in place of spaces
        :param mark_control: str - (optional) convert non-printing control characters to a placeholding
                                 character; valid values:
                                 - "unicode" - replaces control chars with Unicode symbols, such as "␍" and "␊"
                                 - any single character string - replace control characters with given string
                                 - None (default) - string is displayed as-is

        :return: str - input string with leading line numbers and column number headers
        """
        if expand_tabs:
            s = s.expandtabs()
        if mark_control is not None:
            mark_control = typing.cast(str, mark_control)
            if mark_control == "unicode":
                transtable_map = {
                    c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))
                }
                transtable_map[127] = 0x2421
                tbl = str.maketrans(transtable_map)
                eol_mark = ""
            else:
                ord_mark_control = ord(mark_control)
                tbl = str.maketrans(
                    {c: ord_mark_control for c in list(range(0, 32)) + [127]}
                )
            s = s.translate(tbl)
        if mark_spaces is not None and mark_spaces != " ":
            if mark_spaces == "unicode":
                tbl = str.maketrans({9: 0x2409, 32: 0x2423})
                s = s.translate(tbl)
            else:
                s = s.replace(" ", mark_spaces)
        if start_line is None:
            start_line = 1
        if end_line is None:
            end_line = len(s)
        end_line = min(end_line, len(s))
        start_line = min(max(1, start_line), end_line)

        if mark_control != "unicode":
            s_lines = s.splitlines()[start_line - 1 : end_line]
        else:
            s_lines = [line + "␊" for line in s.split("␊")[start_line - 1 : end_line]]
        if not s_lines:
            return ""

        lineno_width = len(str(end_line))
        max_line_len = max(len(line) for line in s_lines)
        lead = " " * (lineno_width + 1)
        if max_line_len >= 99:
            header0 = (
                lead
                + "".join(
                    f"{' ' * 99}{(i + 1) % 100}"
                    for i in range(max(max_line_len // 100, 1))
                )
                + "\n"
            )
        else:
            header0 = ""
        header1 = (
            header0
            + lead
            + "".join(f"         {(i + 1) % 10}" for i in range(-(-max_line_len // 10)))
            + "\n"
        )
        header2 = lead + "1234567890" * (-(-max_line_len // 10)) + "\n"
        return (
            header1
            + header2
            + "\n".join(
                f"{i:{lineno_width}d}:{line}{eol_mark}"
                for i, line in enumerate(s_lines, start=start_line)
            )
            + "\n"
        )


import os
import os.path as osp
import six
import shutil
import unittest
import glob
import gwgen
import numpy as np
import tempfile
from gwgen.main import GWGENOrganizer
import gwgen.utils as utils
from model_organization.config import setup_logging

test_root = osp.abspath(osp.dirname(__file__))

_test_stations = osp.join(test_root, 'test_stations.dat')

_short_test_stations = osp.join(test_root, 'test_stations_short.dat')

_long_test_stations = osp.join(test_root, 'test_stations_long.dat')

_eecra_test_stations = osp.join(test_root, 'eecra_test_stations.dat')

_short_eecra_test_stations = osp.join(test_root,
                                      'eecra_test_stations_short.dat')

setup_logging(osp.join(test_root, 'logging.yaml'))

on_travis = os.getenv('TRAVIS')

db_config = dict(
    database='travis_ci_test')

class BaseTest(unittest.TestCase):
    """Test the :class:`gwgen.main.ModuleOrganizer` class"""

    test_dir = None

    remove_at_cleanup = True

    use_db = True

    stations_type = 'normal'

    #: number of cores to use
    nprocs = None

    #: Boolean that is True, if the tests should be run in serial
    serial = False

    _station_files = {
        'normal': _test_stations,
        'short': _short_test_stations,
        'long': _long_test_stations,
        }

    _eecra_station_files = {
        'normal': _eecra_test_stations,
        'short': _short_eecra_test_stations,
        }

    @classmethod
    def setUpClass(cls):
        # try to connect to a postgres database
        if cls.use_db:
            try:
                utils.get_postgres_engine(create=True, test=True, **db_config)
                cls.use_db = True
            except:
                cls.use_db = False

    def setUp(self):
        from psyplot import rcParams
        self.test_dir = tempfile.mkdtemp(prefix='tmp_gwgentest')
        os.environ['GWGENCONFIGDIR'] = self.config_dir = osp.join(
            self.test_dir, 'config')
        if not osp.exists(self.test_dir):
            os.makedirs(self.test_dir)
        if not osp.exists(self.config_dir):
            os.makedirs(self.config_dir)
        self.test_db = osp.basename(self.test_dir)
        src_station_file = self._station_files[self.stations_type]
        self.stations_file = osp.join(self.test_dir,
                                      osp.basename(src_station_file))
        shutil.copyfile(src_station_file, self.stations_file)

        src_eecra_file = self._eecra_station_files[self.stations_type]
        self.eecra_stations_file = osp.join(self.test_dir,
                                            osp.basename(src_eecra_file))
        shutil.copyfile(src_eecra_file, self.eecra_stations_file)
        self.organizer = GWGENOrganizer()
        global_conf = self.organizer.config.global_config
        global_conf['data'] = osp.join(test_root, 'test_data')
        global_conf['use_relative_links'] = False
        global_conf['nprocs'] = self.nprocs or 'all'
        global_conf['serial'] = self.serial
        if self.use_db:
            self._clear_db()
            global_conf.update(db_config)
        rcParams['plotter.linreg.nboot'] = 1

    def tearDown(self):
        from psyplot import rcParams
        if self.remove_at_cleanup:
            if osp.exists(self.test_dir):
                shutil.rmtree(self.test_dir)
            if osp.exists(self.config_dir):
                shutil.rmtree(self.config_dir)
            if self.use_db:
                self._clear_db()
        rcParams.update_from_defaultParams(plotters=False)

        del self.organizer
        del self.test_dir
        del self.config_dir

    def _clear_db(self):
        engine = utils.get_postgres_engine(db_config['database'])[0]
        conn = engine.connect()
        for table in engine.table_names():
            conn.execute("DROP TABLE %s;" % table)
        conn.close()

    @property
    def stations(self):
        """A numpy array of the stations in :attr:`test_stations`"""
        return np.loadtxt(
            self.stations_file, dtype='S11', usecols=[0]).astype(
                np.str_)

    def _test_setup(self):
        """Test the setup of a project. We make this method private such that
        it is not called everytime"""
        self.organizer.setup(self.test_dir, 'test_project0', link=False)
        mpath = osp.join(self.test_dir, 'test_project0')
        self.assertTrue(osp.isdir(mpath))
        original_files = sorted(map(osp.basename, glob.glob(osp.join(
            osp.dirname(gwgen.__file__), 'src', '*.f90'))))
        copied_files = sorted(map(osp.basename, glob.glob(osp.join(
            mpath, 'src', '*.f90'))))
        self.assertEqual(original_files, copied_files)
        self.assertIn('test_project0', self.organizer.config.projects)

        # createa new project and let it automatically assign the name
        self.organizer.setup(self.test_dir)
        mpath = osp.join(self.test_dir, 'test_project1')
        self.assertTrue(osp.isdir(mpath))
        original_files = sorted(map(osp.basename, glob.glob(osp.join(
            osp.dirname(gwgen.__file__), 'src', '*.f90'))))
        copied_files = sorted(map(osp.basename, glob.glob(osp.join(
            mpath, 'src', '*.f90'))))
        self.assertEqual(original_files, copied_files)
        self.assertIn('test_project1', self.organizer.config.projects)

    def _test_init(self):
        """Test the intialization of a new experiment. We make this method
        private such that it is not called everytime"""
        self.organizer.setup(self.test_dir)
        projectname = self.organizer.projectname
        self.organizer.init(experiment='testexp0')
        expdir = osp.join(
            self.test_dir, projectname, 'experiments', 'testexp0')
        self.assertTrue(osp.exists(expdir),
                        msg='Experiment directory %s does not exist!' % expdir)
        self.assertIn('testexp0', self.organizer.config.experiments)

        # test without argument
        self.organizer.setup(self.test_dir)
        projectname = self.organizer.projectname
        self.organizer.init(experiment=None)
        expdir = osp.join(
            self.test_dir, projectname, 'experiments', 'testexp1')
        self.assertTrue(osp.exists(expdir),
                        msg='Experiment directory %s does not exist!' % expdir)
        self.assertIn('testexp1', self.organizer.config.experiments)

    @staticmethod
    def _test_url(url, *args, **kwargs):
        if six.PY3:
            from urllib import request
            request.urlopen(url, *args, **kwargs)
        else:
            import urllib
            urllib.urlopen(url, *args, **kwargs)

    def assertAlmostArrayEqual(self, actual, desired, rtol=1e-07, atol=0,
                               msg=None, **kwargs):
        """Asserts that the two given arrays are almost the same

        This method uses the :func:`numpy.testing.assert_allclose` function
        to compare the two given arrays.

        Parameters
        ----------
        actual : array_like
            Array obtained.
        desired : array_like
            Array desired.
        rtol : float, optional
            Relative tolerance.
        atol : float, optional
            Absolute tolerance.
        equal_nan : bool, optional.
            If True, NaNs will compare equal.
        err_msg : str, optional
            The error message to be printed in case of failure.
        verbose : bool, optional
            If True, the conflicting values are appended to the error message.
        """
        try:
            np.testing.assert_allclose(actual, desired, rtol=rtol, atol=atol,
                                       err_msg=msg or '', **kwargs)
        except AssertionError as e:
            if six.PY2:
                self.fail(e.message)
            else:
                self.fail(str(e))

# check if we are online by trying to connect to google
try:
    BaseTest._test_url('https://www.google.de')
    online = True
except:
    online = False


# Definition for singly-linked list.
# class ListNode:
#    def __init__(self, x):
#        self.val = x
#        self.next = None

class Solution:
    # @param A : head node of linked list
    # @param B : integer
    # @return the head node in the linked list
    def removeNthFromEnd(self, A, B):
        n, curr = 0, A
        while curr:
            n += 1
            curr = curr.next
        if n <= B: return A.next
        toDrop, i, curr = n - B, 1, A
        head = curr
        while curr:
            if i != toDrop:
                i += 1
            else:
                curr.next = curr.next.next
                break
            curr = curr.next
        return head

Linked Lists/List 2 pointer/Remove_Nth_Node_from_List_End.py


"""
912ms

N : 시험장
i번 시험장 응시자 수 : Ai
총감독관 감시 응시자수 : B명
부감독관 감시 응시자수 : C명
한 시험장 -> 총 : 1명, 부 : 여러 명
필요한 감독관 최소값

input
시험장 개수 : N
응시자 수 : Ai
감독관 수  : B, C
"""

# 입력
N = int(input())
Ai = list(map(int, input().split()))
B, C = map(int, input().split())
result = 0

for i in range(len(Ai)):                            # 시험장 수 만큼 반복
    if Ai[i] <= B:                                  # 총 감독관이 감시할 수 인원 수 이하면
        result += 1                                 # 결과에 1을 더함
    else:                                           # 총 감독관이 감시할 수 인원보다 많으면
        if (Ai[i] - B) % C:                         # (응시자 - 총감독관 감시자수)가 부감독관 감시자수와 나누어 떨어지지 않으면
            result += 1 + (Ai[i] - B) // C + 1      # 1 + (응시자 - 총감독관 감시자수)에서 부감독관 감시자수 나눈 몫 + 1
        else:                                       # 나누어 떨어지면
            result += 1 + (Ai[i] - B) // C          # 1 + (응시자 - 총감독관 감시자수)에서 부감독관 감시자수 나눈 몫을 더함

print(result)


from grandpy.grandpy_answers.answer import Answer
from grandpy.grandpy_answers.constants import (
    ANWS_BLANK, ANWS_CANT_FIND, ANWS_NONALLOWED,
    INTRO_NAME, INTRO_ADDRESS, INTRO_MAP, INTRO_DESCRIPTION, INTRO_MAX_SIZE)
from .constants import (
    TEST_GOOGLE_DATA as google_data,
    TEST_WIKIPEDIA_DATA as wikipedia_data)

def test_if_stops_because_function_work():
    """
    test whether grandpy's reply in case of a problem contains
    one of the planned texts.
    """
    answer1 = Answer.stops_because(Answer, 'blank_new_user_message')
    answer2 = Answer.stops_because(Answer, 'nonallowed_characters')
    answer3 = Answer.stops_because(Answer, 'cant_find_location')
    assert ( answer1['grandpyMessage'] in ANWS_BLANK
            and answer2['grandpyMessage'] in ANWS_NONALLOWED
            and answer3['grandpyMessage'] in ANWS_CANT_FIND )

def test_if_builds_with_data_function_work():
    """
    check if grandpy's answer contains all the expected data
    """
    answer = Answer.builds_with_data(Answer, google_data, wikipedia_data)
    assert ( answer['status'] == 'ok'
        and answer['grandpyMessage']['intro_name'] in INTRO_NAME
        and answer['grandpyMessage']['intro_address'] in INTRO_ADDRESS
        and answer['grandpyMessage']['intro_map'] in INTRO_MAP
        and answer['grandpyMessage']['intro_description'] in INTRO_DESCRIPTION
        and answer['grandpyMessage']['name'] == wikipedia_data['name']
        and answer['grandpyMessage']['address'] == google_data['address']
        and answer['grandpyMessage']['map_url'] == google_data['map_url']
        and answer['grandpyMessage']['description_first_part'] == (
            wikipedia_data['description'][:INTRO_MAX_SIZE-1])
        and answer['grandpyMessage']['description_collapsible_part'] == (
            wikipedia_data['description'][INTRO_MAX_SIZE-1:])
        and answer['grandpyMessage']['wikipedia_url'] == (
            wikipedia_data['wikipedia_url'])
)


hufflepuff = 0
gryffindor = 0
slytherin = 0
ravenclaw = 0

user = (input('Welcome to the Sorting Hat! Type in your name and let\'s begin! ' ))

q1 = int(input('Question 1: Do you like Dawn or Dusk? '
                    '\n 1) Dawn '
                    '\n 2) Dusk '
                    '\n '))

if q1 == 1:
     gryffindor += 1
     ravenclaw += 1
elif q1 == 2:
    hufflepuff += 1
    slytherin += 1
else:
    print('wrong input')

q2 = int(input('Question 2: When I\'m dead, I want people to remember me as: '
                    '\n 1) The Good'
                    '\n 2) The Great'
                    '\n 3) The Wise'
                    '\n 4) The Bold'
                    '\n '))

if q2 == 1:
    hufflepuff += 2
elif q2 == 2:
    slytherin += 2
elif q2 == 3:
    ravenclaw += 2
elif q2 == 4:
    gryffindor += 2
else:
    print('wrong input')

q3 = int(input('Question 3: Which kind of instrument most pleases your ears? '
                    '\n 1) The Violin'
                    '\n 2) The Trumpet'
                    '\n 3) The Piano'
                    '\n 4) The Drum'
                    '\n '))

if q3 == 1:
    slytherin += 4
elif q2 == 2:
    hufflepuff += 4
elif q2 == 3:
    ravenclaw += 4
elif q2 == 4:
    gryffindor += 4
else:
    print ('wrong input')

if slytherin > hufflepuff:
    if slytherin > ravenclaw:
        if slytherin > gryffindor:
            print("You are a Slytherin!")

if hufflepuff > slytherin:
    if hufflepuff > ravenclaw:
        if hufflepuff > gryffindor:
            print("You are a Hufflepuff!")

if ravenclaw > hufflepuff:
    if ravenclaw > slytherin:
        if ravenclaw > gryffindor:
            print("You are a Ravenclaw!")

if gryffindor > slytherin:
    if gryffindor > hufflepuff:
        if gryffindor > ravenclaw:
            print("You are a Gryffindor!")


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

# In[3]:

#Function for fibonacci series
def fibo(n) :
    #check if n is valid
    if n == 0:
        return 0
    elif n == 1 or n == 2:
        return 1
    else:
        return (fibo(n-1) + fibo(n-2))

# In[4]:

#driver program to print fibonacci series
n = int(input("enter a value : "))
print("fibonacci series: ", end = ' ')
for n in range(0,n):
    print(fibo(n),end = ' ')

# In[ ]:


from django_filters import filters
from django_filters.rest_framework import FilterSet

from medsupport.models import Hospital, Solution, SolutionCategory

# BaseInFilter let us provide comma separated values for OR filtering

class HospitalFilterSet(FilterSet):
    needs_categories = filters.BaseInFilter(
        field_name='needs__solution_type__solutions__categories',
    )
    categories = filters.BaseInFilter()
    region = filters.BaseInFilter()

    class Meta:
        model = Hospital
        fields = (
            'region',
            'categories',
            'needs_categories',
        )

class SolutionFilterSet(FilterSet):
    solution_type = filters.BaseInFilter()
    materials = filters.BaseInFilter()
    tools = filters.BaseInFilter()

    class Meta:
        model = Solution
        fields = (
            'solution_type',
            'materials',
            'tools',
        )


import sys
# sys.path.append(r"D:\CK_Dev\Maya_Dev\Tool_Dev\module")
# from Qt import QtWidgets, QtCore, QtGui
# from Qt.QtCompat import loadUi
from PySide2 import QtWidgets, QtCore, QtGui
from MadGoatToolkit import Ui_MainDialog

class MadGoatTookkitMain(QtWidgets.QDialog, Ui_MainDialog):
    def __init__(self, parent=None):
        super(MadGoatTookkitMain, self).__init__(parent)
        self.setupUi(self)

    def closeEvent(self, event):
        self.MyFavorate.saveFavorite()

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    # widget = loadUi(ui_path)
    widget = MadGoatTookkitMain()
    widget.show()
    app.exec_()


n = int(input())
numbers = list(map(int,input().split()))
# print(numbers)
def checkOddDivisor():
    for number in numbers:
        if number == 2:
            print("NO")
        for j in range(3,number,2):
            if number%j == 0:
                print('YES')
checkOddDivisor()


import bluetooth
import sys
import subprocess

target_name = "Europa"
Europa = 'D8:68:C3:94:47:DE'
cat = "/home/pi/Documents/cat.jpg"

def check_connection(device_name = "Europa"):
    dev_address = None
    devices = bluetooth.discover_devices()
    for device in devices:
        print(bluetooth.lookup_name(device))
        if (bluetooth.lookup_name(device) == device_name):
            dev_address = device
            break
    if (dev_address == None):
        sys.exit(device_name + " not found. Ensure that the name is correct, and that Bluetooth is available")
    return dev_address

def start_bluetooth_server(server_sock):
    port = bluetooth.PORT_ANY
    server_sock.bind(("", port))
    server_sock.listen(1)
    print("listening for connections")
    uuid = "00000000-0000-1000-8000-00805f9b34fb"
    bluetooth.advertise_service(server_sock, "Europa Interface",service_id = uuid, service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                   profiles=[bluetooth.SERIAL_PORT_PROFILE])
    client_sock, address = server_sock.accept()
    print(address)
    '''
    if (address != Europa):
        client_sock.close()
        server_sock.close()
        print("unrecognized bluetooth address connected to the hardware")
        sys.exit()
    '''
    #else:
    #print("Connected to " + address.toString())
    return client_sock

def repeat(europa_sock):
    # check to see what needs to be done
    command  = europa_sock.recv(1024)
    command = command.decode('ascii')
    #have all the actions sent at one time only push bluetooth info when action is nessecary
    print(command)

#Europa = check_connection()
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
europa_sock = start_bluetooth_server(server_sock)
europa_sock.send("AAAHHHHHHHHHH")
process = subprocess.Popen('sudo bt-obex -p ' + Europa + ' ' + cat, shell=True)
for i in range(10):
    repeat(europa_sock)


import gdata.photos.service
import gdata.media
import gdata.geo

from django.core.cache import cache

class Album:
    def __init__(self, entry, albumId=None):
        self.title = entry.title.text
        self.url = entry.GetHtmlLink()
        self.date = entry.timestamp.datetime()
        if (albumId):
            self.id = albumId
            self.description = entry.subtitle.text
        else:
            self.id = entry.GetAlbumId()
            if (entry.media.thumbnail.count > 0):
                self.thumb = entry.media.thumbnail[0].url

class Photo:
    def __init__(self, entry=None):
        if not entry:
            return

        if (entry.media.thumbnail.count > 0):
            self.thumb = entry.media.thumbnail[0].url

        self.id = entry.gphoto_id.text

def clear_cache():
    cache.delete('albums')
    cache.delete('albums_home')

def get_picasa_feed(path):
    gd_client = gdata.photos.service.PhotosService()
    return gd_client.GetFeed(path)

def get_albums_for_url(url, key):
    albums = cache.get(key)

    if not albums:
        feed = get_picasa_feed(url)
        albums = []
        for entry in feed.entry:
            albums.append(Album(entry))
        cache.set(key, albums)

    return albums

def get_home_albums(user):
    return get_albums_for_url('/data/feed/api/user/%s?kind=album&max-results=100&thumbsize=144c' % user,
                              'albums_home')

def get_albums(user):
    return get_albums_for_url('/data/feed/api/user/%s?kind=album&max-results=100&thumbsize=144c' % user,
                              'albums')

def get_album(user, albumId):
    feed = get_picasa_feed('/data/feed/api/user/%s/albumid/%s?kind=photo&thumbsize=104c' %
                           (user, albumId));
    album = Album(feed, albumId)
    album.thumb = feed.icon.text
    photos = []
    for entry in feed.entry:
        photos.append(Photo(entry))

    album.photos = photos
    return album

def get_photo(user, albumId, photoId):
    feed = get_picasa_feed('/data/feed/api/user/%s/albumid/%s/photoid/%s?imgmax=576' %
                              (user, albumId, photoId));

    photo = Photo()
    photo.url = feed.media.content[0].url;
    photo.id = feed.gphoto_id
    photo.caption = feed.subtitle.text

    photo.album = get_album(user, albumId)

    return photo


from flask import Flask, render_template
import requests

app = Flask(__name__)

@app.route('/')
def hello():
    return "
Enter  /guess/your_name  with URL
"

@app.route('/guess/<name>')
def home(name):

    response_age = requests.get(url=f'https://api.agify.io?name={name}')
    response_age.raise_for_status()
    data_age = response_age.json()
    my_age = data_age['age']
    response_gender = requests.get(url=f'https://api.genderize.io?name={name}')
    response_gender.raise_for_status()
    data_gender = response_gender.json()
    my_gender = data_gender['gender']
    name = name.capitalize()
    return render_template("index.html",na = name,age=my_age,gender=my_gender)

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

Gender and age predicting website with Flask/main.py


import numpy as np
import torch
import torch.nn as nn
from typing import Tuple, List, Union, Callable, Type, Iterator
from enum import Enum, unique
import torch.optim.optimizer

N = type(None)
V = np.array
VS = Union[Tuple[V, ...], List[V]]
VN = Union[V, N]
VNS = Union[VS, N]
T = torch.Tensor
TS = Union[Tuple[T, ...], List[T]]
TN = Union[T, N]
TNS = Union[TS, N]

V_Mesh = Tuple[V, V]
T_Mesh = Tuple[T, T]
D = torch.device
CPU = torch.device('cpu')
CUDA = lambda x: torch.device(f'cuda:{x}')

Optimizer = torch.optim.Adam
NoiseT = Union[int, Tuple[Union[bool, int], ...]]

@unique
class NoiseType(Enum):
    ALL_ZEROS = 0
    RANDOM = 1


from .Role import Role
import strings as s

class Mifioso(Role):
    icon = s.mifia_icon
    team = 'Evil'
    name = s.mifia_name
    powerdesc = s.mifia_power_description

    def __init__(self, player):
        super().__init__(player)
        self.target = None

    def __repr__(self) -> str:
        if self.target is None:
            return "<Role: Мафия>"
        else:
            return "<Role: Мафия, прицеливается {target}>".format(target=self.target.tusername)

    def power(self, arg):
        selected = self.player.game.findplayerbyusername(arg)
        if selected is None:
            self.player.message(s.error_username)
            return
        self.target = selected
        self.player.message(s.mifia_target_selected.format(target=self.target.tusername))

    def onendday(self):
        if self.player.game.votingmifia:
            self.target = None
        else:
            if self.target is not None:
                if self.target.protectedby is None:
                    self.target.kill()
                    self.player.game.message(s.mifia_target_killed.format(target=self.target.tusername, icon=self.target.role.icon, role=self.target.role.name))
                else:
                    self.player.game.message(s.mifia_target_protected.format(target=self.target.tusername, icon=self.target.protectedby.role.icon, protectedby=self.target.protectedby.tusername))
                self.target = None


R'''
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: if implementing in Java, please use a character array so that you can
perform this operation in place.)
EXAMPLE
Input: "Mr John Smith ", 13
Output: "Mr%20John%20Smith"
'''

# The algorithm must use character arrays not strings

def is_white_space(c):
    return c == ' ' or c == '\t' or c == '\n'

def url_ify_not_in_place(s, l):
    R'''
    This is kind of a brute force solution. It is O(n), but it is not an in place algorithm.
    '''

    arr = ['']*(len(s)*3)
    z = 0
    for i in range(l):
        if is_white_space(s[i]):
            if is_white_space(s[i+1]): continue # To get rid of continuous (contiguous?) white spaces and only keep one of them
            arr[z] = '%'
            arr[z+1] = '2'
            arr[z+2] = '0'
            z += 3
            print(arr)
        else:
            arr[z] = s[i]
            z += 1
            print(arr)

    return arr

def url_ify_semi_in_place(s, l):
    R'''This algorithm is O(n) and `in place` but still not a beautiful solution though.'''

    z = len(s)-1
    #space = len(s)

    for i in reversed(range(l)):
        if not is_white_space(s[i]):
            s[z] = s[i]
            z -= 1
        else:
            if is_white_space(s[i-1]): continue # To get rid of continuous (contiguous?) white spaces and only keep one of them
            s[z], s[z-1], s[z-2] = '0', '2', '%'
            z -= 3

    for i in range(z+1, len(s)):
        print(s[i], end='')
    return s[z+1:]

def url_ify_in_place(s, l):
    R'''
    This is a O(n) in-place solution, but writing it on paper was tricky and ultimately a lot of errors occured that were found and corrected in the IDE and after test runs.
    For instance, [duplicata] counts the `total` number of whites while whites counts the `non-adjacent whites` (meaning that if there are 03 whites in a row we will increment whites just by 1, as the 03 whites will be replaced by only one '%20').
    [duplicata] is very important to calculate the final index of each letter (the formula of [z]).
    In addition the position of the checks to see if whites follow each other is also very important. We need to check while counting and also when re-ordering the string to know where to skip.
    '''
    whites = 0
    duplicata = 0

    for i in range(l):
        if is_white_space(s[i]):
            duplicata += 1
            if not is_white_space(s[i+1]): # Condition 1 to get rid of continuous (contiguous?) white spaces and only keep one of them
                whites += 1

    m = 0
    z = whites * 3 + l - duplicata - 1 # -1 because the index starts from 0, z is kind of a length (a position)
    for i in reversed(range(l)):
        if is_white_space(s[i]):
            if is_white_space(s[i-1]): continue # Condition 2, works in tandem with condition 1 above
            s[z], s[z-1], s[z-2] = '0', '2', '%'
            z -= 3
            m += 3
        else:
            s[z] = s[i]
            z -= 1
            m += 1

    for i in range(m):
        print(s[i], end='')
    return s[:m]

print(url_ify_in_place(['1', ' ', '\t', '2', '', '', '', '', '', ''], 4))
#print(url_ify_semi_in_place('a\t\tb\n c \t\nd', 11))


import json
import random
import unittest
import requests
import responses

def random_cat_fact():
    response = requests.get('https://cat-fact.herokuapp.com/facts').json()
    facts = [fact['text'] for fact in response['all']]
    return random.choice(facts)

class RandomCatFactsTestCase(unittest.TestCase):

    @responses.activate
    #@mock.patch("requests.get")
    def test_random_cat_fact(self):
        facts = ["A cat has five toes on his front paws"]
        content = {
            'all': [{'text': fact} for fact in facts]
        }
        responses.add(
            responses.GET,
            'https://cat-fact.herokuapp.com/facts',
            body=json.dumps(content),
            content_type='application/json')

        fact = random_cat_fact()
        self.assertIn(fact, facts)

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


import os
import sys
import json

# ----------------------------------------------------------------------------------------------------------------------

class Fabric():

    def __init__(self, zfm_dir):
        self.config_dir = zfm_dir

        #
        # Node placeholder.
        #
        self.nodes = {}
        self.gcids = set()

    def _write_type(self, data, filename):
        filename = os.path.join(self.config_dir, filename)

        try:
            os.makedirs(self.config_dir, exist_ok=True)
            with open(filename, 'w') as f:
                json.dump(data, f,indent=4, separators=(",", ": "))
        except:
            print(sys.exc_info())
            sys.exit(1)

    def add_node(self,name,node):
        self.nodes[name] = node
        if node.node_type() != 'Switch':
            self.gcids |= set(node.GCIDs())

    def find_node(self,name):
        return self.nodes[name]

    def write(self):

        #
        # Bundle up the nodes so that we can write them as JSON.
        #
        switch_data  = {}
        compute_data = {}
        memory_data  = {}
        io_data      = {}

        for name,node in self.nodes.items():
            node_type = node.node_type()
            if   node_type == 'Switch'  : switch_data[name]  = node.configuration()
            elif node_type == 'Compute' : compute_data[name] = node.configuration()
            elif node_type == 'IO'      : io_data[name]      = node.configuration()
            elif node_type == 'Memory'  : memory_data[name]  = node.configuration()

        #
        # Create the directories and write the profiles for the nodes.
        #
        self._write_type(switch_data,  'switch_nodes.conf')
        self._write_type(compute_data, 'compute_nodes.conf')
        self._write_type(io_data,      'io_nodes.conf')
        self._write_type(memory_data,  'memory_nodes.conf')

# ----------------------------------------------------------------------------------------------------------------------


import logging
import pprint

from tornado import gen, ioloop
import tredis

@gen.engine
def run():
    client = tredis.Client([{"host": "127.0.0.1", "port": 6379, "db": 0}],
                           auto_connect=False)
    yield client.connect()
    value = yield client.info()
    pprint.pprint(value)
    ioloop.IOLoop.current().stop()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    io_loop = ioloop.IOLoop.current()
    io_loop.add_callback(run)
    io_loop.start()


import pandas as pd
import warnings
import matplotlib.pyplot as plt
from et_xmlfile import xmlfile
from matplotlib import font_manager, rc

font_path = './D2Coding-Ver1.3.2-20180524.ttf'
font_name = font_manager.FontProperties(fname=font_path).get_name()
rc('font', family=font_name)

df = pd.read_excel('./남북한발전전력량.xlsx')
df = pd.DataFrame(df.fillna(method='ffill'))
df.rename(columns={'전력량 (억㎾h)': '국가', '발전 전력별': '전력별'}, inplace=True)
df.set_index('국가', inplace=True)
print(df)
print()

south = pd.DataFrame(df.loc['남한'])
north = pd.DataFrame(df.loc['북한'])
print(south)
print(north)
print()

south.reset_index(inplace=True)
south.drop('국가', axis=1, inplace=True)
south.set_index('전력별', inplace=True)
south.replace({'-': 0}, inplace=True)
# south = south.loc['합계']

north.reset_index(inplace=True)
north.drop('국가', axis=1, inplace=True)
north.set_index('전력별', inplace=True)
north.replace({'-': 0}, inplace=True)
# north = north.loc['합계']

south.rename(index={'합계': '총발전량'}, inplace=True)
north.rename(index={'합계': '총발전량'}, inplace=True)

south = south.loc['총발전량']
north = north.loc['총발전량']
print(south)
print(north)
print()

# 스타일 지정
plt.style.use('ggplot')
plt.rcParams['axes.unicode_minus'] = False   # 마이너스 부호 출력 설정

# ax = north.plot(kind='area', stacked=True, alpha=0.2, figsize=(20, 10))
ax = south.plot(kind='area', stacked=False, alpha=0.2, figsize=(20, 10))
ax.set_title('대한민국 총발전량', size=30, color='brown', weight='bold')
ax.set_xlabel('기간', size=20, color='blue')
ax.set_ylabel('발전량', size=20, color='blue')
ax.legend(loc='best', fontsize=15)

plt.show()

ax = north.plot(kind='area', stacked=False, alpha=0.2, figsize=(20, 10))
ax.set_title('북조선 총발전량', size=30, color='brown', weight='bold')
ax.set_xlabel('기간', size=20, color='blue')
ax.set_ylabel('발전량', size=20, color='blue')
ax.legend(loc='best', fontsize=15)

plt.show()


import json
import argparse
import logging.config
import time
import re
from sys import argv
from datetime import date, datetime
from dataclasses import dataclass, field
from collections import defaultdict
from socrata import *
from utils import *
from storage import *

logger = logging.getLogger(__name__)

with open('phase_2/config.json', 'r') as f:
    config = json.load(f)

parser = argparse.ArgumentParser(description="Extract the dataset named Police Department Incident Reports: 2018 to Present \
                                 from The City and Condado of San Francisco. Socrata Open Data API have been used to programmatically \
                                 return the dataset.",
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
type_modes = ["LAST_DATE", "REFRESH"]
parser.add_argument("-m", "--mode", type=str, choices=type_modes, default=type_modes[0], required=True, help="the reference is the last date")
# parser.add_argument("-s", "--start_date", type=datetime.fromisoformat, default="2018-01-01", required=("--mode="+type_modes[1] in argv), help="used with refresh mode: from the desired date since 2018-01-01")
# parser.add_argument("-e", "--end_date", type=datetime.fromisoformat, default="2018-01-01", required=("--mode="+type_modes[1] in argv), help="used with refresh mode: from the desired date since 2018-01-01")
args = vars(parser.parse_args())

@dataclass
class Data:
    args: "defaultdict[dict]" = field(default_factory=lambda: defaultdict(dict), init=False)
    blob_list_inter: list = field(default_factory=list, init=False)
    blob_dict: "defaultdict[dict]" = field(default_factory=lambda: defaultdict(dict), init=False)
    date_list: list = field(default_factory=list, init=False)
    date_dict: "defaultdict[dict]" = field(default_factory=lambda: defaultdict(dict), init=False)
    day_range: int = field(init=False)
    end_date: str = field(init=False)
    get_url: str = field(init=False)
    get_headers: str = field(init=False)
    params: str = field(init=False)
    start_date: str = field(init=False)

    def __post_init__(self):
        self.get_url = config.get('api').get('domain').get('url') + config.get('api').get('dataset').get('san_francisco_data') + '.json'
        self.get_headers = config.get('api').get('headers')
        self.params = config.get('api').get('params')

    def list_dates(self):
        self.blob_list = Blob().list_blobs()
        pattern = "([0-9]{4}\-[0-9]{2}\-[0-9]{2})"

        for date in self.blob_list:
            dates = str(re.findall(pattern=pattern, string=date)).replace('[','').replace(']','').strip("'")
            self.blob_list_inter.append((datetime.fromisoformat(str(dates)) + timedelta(days=1, hours=0,minutes=0,seconds=0)).strftime("%Y-%m-%dT%H:%M:%S"))
            max_date = max(self.blob_list_inter)

        self.blob_dict["last_date"] = max_date
        logger.info('From {cls} the attr: {attr}'.format(cls=type(self.blob_dict).__name__, attr=self.blob_dict), exc_info=True)
        return self.blob_dict["last_date"]

    def ingestion(self):
        if args["mode"] == 'LAST_DATE':
            max_date = Data().list_dates()
            request = Socrata(url=self.get_url, headers=self.get_headers, parameters=self.params, start_date=max_date).api_connection()

            logger.info('From {cls} the attr: {attr}'.format(cls=type(request).__name__, attr=request), exc_info=True)

            if request.status_code != 200:
                logger.info('From {cls} the attr: {attr}'.format(cls=type(request.status_code).__name__, attr=request.status_code), exc_info=True)
                raise RuntimeError('Can''t retrieve latest timestamp.' + request.text)
            else:
                json.dumps(request.json(), indent=4)
                logger.info('From {cls} the attr: {attr}'.format(cls=type(request.json()).__name__, attr=request.json()[-1:]), exc_info=True)

            blob_name = str(datetime.fromisoformat(max_date).strftime("%Y-%m-%d")) + "_dataset_" + str(config.get('api').get('dataset').get('san_francisco_data')) + "_crimes_in_loaded_" + str(time.time_ns()) + ".json"
            blob = Blob_obj(blob_name=blob_name).blob_obj()

            logger.info('From {cls} the attr: {attr}'.format(cls=type(blob).__name__, attr=blob), exc_info=True)

            #with blob.open("w") as write_file:
            #    json.dump(request.json(), write_file, indent=4)
            message = f'{max_date} loaded in the {Bucket().bucket_name} bucket'

            logger.info('From {cls} the attr: {attr}'.format(cls=type(message).__name__, attr=message), exc_info=True)

        return request.json()

if __name__ == '__main__':
        Data


from sys import stdin
from collections import deque
input = stdin.readline

N, K = map(int, input().split())

dp = deque()
ysps_list = []
for i in range(N):
    dp.append(i+1)

while dp:
    for _ in range(K-1):
        dp.append(dp.popleft())

    ysps_list.append(dp.popleft())

print(str(ysps_list).replace('[', '<').replace(']', '>'))


#!/bin/python

from ortools.graph import pywrapgraph

def main():
    # The problem data. A directed edge (u, v) has a capacity c.
    u = [0, 0, 0, 1, 1, 2, 2, 3, 3]
    v = [1, 2, 3, 2, 4, 3, 4, 2, 4]
    c = [20, 30, 10, 40, 30, 10, 20, 5, 20]

    assert len(u) == len(v)
    assert len(v) == len(c)

    max_flow = pywrapgraph.SimpleMaxFlow()
    for i in range(len(u)):
        max_flow.AddArcWithCapacity(u[i], v[i], c[i])

    # Solve the problem, find max flow between nodes 0 and 1.
    status = max_flow.Solve(0, 4)
    if status == max_flow.OPTIMAL:
        print(f'Max flow: {max_flow.OptimalFlow()}')
        print()
        print('  Arc  Flow / Capacity')
        for i in range(max_flow.NumArcs()):
            print(f'{max_flow.Tail(i)} -> {max_flow.Head(i)} {max_flow.Flow(i)} / {max_flow.Capacity(i)}')

        print(f'Source side min-cut: {max_flow.GetSourceSideMinCut()}')
        print(f'Sink side min-cut: {max_flow.GetSinkSideMinCut()}')
    else:
        print('Unable to compute max-flow.')

if __name__ == '__main__':
    main()


from .preprocess import read_pcap, preprocess_df
import xgboost as xgb

def preprocess_data(folder_path):
    df = read_pcap(folder_path)
    done_df = preprocess_df(df)
    # done_df = done_df.loc[:, 'sport':'chksum']
    return done_df

def predict_models(apps_model_path, classes_model_path, df):
    dict_apps = {'vpn_bittorrent': 0, 'vpn_email2a': 1, 'vpn_facebook_audio2': 2, 'vpn_facebook_chat1a': 3, 'vpn_ftps_A': 4, 'vpn_hangouts_audio1': 5, 'vpn_hangouts_chat1a': 6, 'vpn_icq_chat1a': 7, 'vpn_netflix_A': 8, 'vpn_sftp_A': 9, 'vpn_skype_audio1': 10, 'vpn_skype_chat1a': 11, 'vpn_skype_files1a': 12, 'vpn_spotify_A': 13, 'vpn_vimeo_A': 14, 'vpn_voipbuster1a': 15, 'vpn_youtube_A': 16}
    dict_classes = {'chats': 0, 'voice_chats': 1, 'video': 2, 'audio': 3, 'files': 4, 'email': 5, 'sftp': 6, 'ftps': 7}
    # apps_model = xgb.XGBClassifier()
    # apps_model.load_model(apps_model_path)
    done_df = df.copy()
    # done_df['apps_class'] = [dict_apps.keys()[dict_apps.values().index(i)] for i in apps_model.predict(df)]

    classes_model = xgb.XGBClassifier()
    classes_model.load_model(classes_model_path)
    done_df['class2'] = classes_model.predict(df.loc[:, 'sport':'chksum'])

    print(len(done_df['class2']), len(done_df.loc[done_df['class2']==0]))
    # done_df['classes_model'] = [dict_classes.keys()[dict_apps.values().index(i)] for i in classes_model.predict(df)]
    return done_df

def save_csv(path, pcap_dir):
    done_df  = predict_models('saved_models/apps_model.txt', '/app/ml/saved_models/classes_model.txt', preprocess_data(pcap_dir))
    done_df.to_csv(path)


import os
import sys

from .main import main

def console_main() -> None:
    """The entry point for CLI with special handling for BrokenPipError. This function is
    not intended to be called as a function from another program."""
    try:
        main()
        sys.stdout.flush()
        sys.stderr.flush()
    except BrokenPipeError:
        # Python flushes standard streams on exit; redirect remaining output
        # to devnull to avoid another BrokenPipeError at shutdown
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(1)  # Python exits with error code 1 on EPIPE

if __name__ == "__main__":
    console_main()


number_of_balls = int(input())
max_value = 0
max_weight = 0
max_time_needed = 0
max_quality = 0

for snowball in range(number_of_balls):
    current_weight = int(input())
    current_time_needed = int(input())
    current_quality = int(input())

    current_value = (current_weight / current_time_needed) ** current_quality

    if current_value > max_value:
        max_value = current_value
        max_weight = current_weight
        max_time_needed = current_time_needed
        max_quality = current_quality

print(f"{max_weight} : {max_time_needed} = {int(max_value)} ({max_quality})")


from __future__ import annotations

import logging
import time
from threading import Lock

from .exclusionms.apihandler import load_active_exclusion_list, save_active_exclusion_list, get_exclusion_list_files, \
    clear_active_exclusion_list, add_exclusion_interval_query, get_excluded_points
from .exclusionms.components import DynamicExclusionTolerance, IncorrectToleranceException, ExclusionPoint
from .paserproducer.ddaproducer import DdaPasefProducer
from .paserproducer.prddataclasses import MsMsInfo
from .paserproducer.sampleinfo import has_key_pac_qualifier
from .paserproducer.serializer import ms2_pasef_spectrum_to_avro, calib_to_avro, extract_exp_name

_log = logging.getLogger(__name__)
_log.setLevel(logging.INFO)

def create_dda_pasef_plugin(paser_key_dict, config, requests_head, create_producer,
                            create_pac_worker, create_feedback_worker):
    return DdaPasefPlugin(paser_key_dict, config, requests_head, create_producer,
                          create_pac_worker, create_feedback_worker)

"""
------------------  Exclusion-MS calculate_mass Start ------------------
"""
def calculate_mass(mz: float, charge: int) -> float:
    return mz * charge - charge * 1.00727647
"""
------------------  Exclusion-MS calculate_mass Start ------------------
"""

class DdaPasefPlugin:
    """
    PASER (Parallel database Search Engine in Realtime).
    Utilizes ProLucid's GPU workspaces to search fragmented peptide spectra in real time. MsMs spectra are sent
    via a Kafka producer to a Kafka broker asynchronously to avoid blocking acquisition.
    This plugin starts a thread - pac thread. Within the thread blocking rest calls are made to paser-head for
    evaluation of pac qualifiers
    """

    def __init__(self, paser_key_dict, config, requests_head,
                 create_producer, create_pac_worker, create_feedback_worker):
        """
        The Plugin constructor is called from the timsEngine.exe when a method with reference to this plugin
        is loaded.
        the producer is not initialized in the constructor because the constructor is called with every method
        load event. This would create a new search result in IP2 every time a paser-method is loaded.
        :param config: object with configuration parameters
        """
        self._lock = Lock()
        # self._is_initialized is set to false the plugin basically does nothing and cannot affect acquisition.
        # It is set to false in the following cases
        # - no Hystar SampleInfo is available
        # - no acquisition was started
        # - a critical error occurred, e.g. connection to PaSER broke, or PaSER sends an internal critical error
        self._is_initialized = False
        self._reference_time = 0.0
        self._ms1_analysis_time = 0.0
        self._has_qualifier = None
        self._previous_ms2_info = MsMsInfo(0, range(-1, -1))
        self._current_ms2_info = MsMsInfo(0, range(-1, -1))
        self._ms2_spectrum_id = 0
        self._current_mob_trafo = None
        self._requests_head = requests_head
        self._config = config
        self._has_qualifier = has_key_pac_qualifier(paser_key_dict)

        _log.info(f"PaSER key {paser_key_dict}")
        self._producer = DdaPasefProducer(self._config, create_producer, self._uid)

        # create PAC worker, returns a queue where to push pac events to.
        self._pac_queue = create_pac_worker(config)

        """
        ------------------  Exclusion-MS Init Start ------------------
        """
        self._uid = paser_key_dict['uid']
        self._exid = None
        self._dynamic_tolerance = None
        if paser_key_dict.get('exlist'):
            self._exid = str(paser_key_dict.get('exlist').get('exid'))
            if paser_key_dict.get('exlist').get('dynamic') is True and paser_key_dict.get('exlist').get('tolerance'):
                try:
                    self._dynamic_tolerance = DynamicExclusionTolerance.from_tolerance_dict(
                        paser_key_dict.get('exlist').get('tolerance'))
                except IncorrectToleranceException as e:
                    _log.error(f'IncorrectToleranceException: {e}. Disabling dynamic exclusion')

        _log.info(f'exid: {self._exid}, dynamic tolerance: {self._dynamic_tolerance}')
        """
        ------------------ Exclusion-MS Init End ------------------
        """

    def analysis_started(self, analysis_directory, reference_time):
        _log.info(f"starting analysis, {analysis_directory}, {reference_time}")

        with self._lock:
            try:
                self._reference_time = reference_time
                self._previous_ms2_info = MsMsInfo(0, range(-1, -1))
                self._current_ms2_info = MsMsInfo(0, range(-1, -1))
                self._ms2_spectrum_id = 0
                # send start call to paser-head
                self._requests_head.start(self._uid, extract_exp_name(analysis_directory))
                self._is_initialized = True
                _log.debug("paser-plugin started")
            except Exception as e:
                _log.error(f"initialization of paser failed {e}")
                self._is_initialized = False

        """
        ------------------  Exclusion-MS analysis_started Start ------------------
        """
        try:
            if self._exid is not None:
                available_exclusion_lists = get_exclusion_list_files(self._config.exclusion_api.ip)
                _log.info(f'available exclusion lists: {available_exclusion_lists}')
                if self._exid not in available_exclusion_lists:
                    _log.info(f"Exclusion list with ID: {self._exid} not found. Making new list.")
                    clear_active_exclusion_list(self._config.exclusion_api.ip)
                    save_active_exclusion_list(self._config.exclusion_api.ip, self._exid)
                _log.info(f"Loading Exclusion list with ID: {self._exid}")
                load_active_exclusion_list(self._config.exclusion_api.ip, self._exid)
        except Exception as ex:
            _log.error(f"Error Loading ExclusionList {ex}. Disabling exclusion list for run.", exc_info=True)
            self._exid = None
        """
        ------------------ Exclusion-MS analysis_started End ------------------
        """

        _log.info("analysis started")

    def analysis_stopped(self):
        """
        This function is called when acquisition stops. Messages on the fly are flushed.
        There is a timeout of 30 seconds configured. So the flush-call might through a
        Kafka time-out exception. In any case exceptions from _send_calibration and flush need to be caught so
        that we can ensure that a) paser-head's stop REST service is called and b) stop-messages for paser_control
        topic are send to shutdown the workflow. For that purpose 3 try-except blocks are used.
        """
        _log.info("stopping analysis")
        with self._lock:
            # we might have the error case that acquisition was not dda-PASEF but a different
            # scan mode. In that case nothing was send and error message should be written
            # to the log
            if not self._ms1_analysis_time > 0.0:
                _log.error("No data send, this is most likely not a dda-PASEF acquisition ...")

            try:
                # send PAC trigger just if qualifier available
                if self._has_qualifier and self._pac_queue is not None:
                    if self._pac_queue.empty():
                        _log.info(f"send PAC request to {self._uid}")
                        self._pac_queue.put_nowait(self._uid)
                    else:
                        _log.info("a PAC message is currently processed")
            except Exception as ex:
                _log.error(f"flushing or pac failed when stopping {ex}")

            try:
                # now make sure stop messages are send to paser_control
                self._producer.send_status_stopped()
            except Exception as ex:
                _log.error(f"send stop messages to paser_control failed {ex}")

            """
            ------------------  Exclusion-MS analysis_stopped Start ------------------
            """
            try:
                if self._exid is not None:
                    save_active_exclusion_list(self._config.exclusion_api.ip, self._exid)
                    _log.info(f"Saved Exclusion List with name: {self._exid}")
            except Exception as ex:
                _log.error(f"Error Saving Exclusion List: {ex}")
                self._exid = None
            """
            ------------------  Exclusion-MS analysis_stopped End ------------------
            """

            try:
                # inform paser-head the analysis was stopped with data flushed
                self._requests_head.stop(self._uid)
            except Exception as ex:
                _log.error(f"send stop status to paser-head failed {ex}")
            finally:
                self._is_initialized = False
                _log.info("analysis stopped")

    def _get_analysis_time(self, monotonic_time):
        """Return current analysis time, or -1 if not acquiring data.

        Given the monotonic time of some data measured by the engine, the analysis time is exactly
        the time stamp that would be assigned in a TDF raw-data file (if that data were recorded).
        """
        if self._is_initialized is False:
            return -1
        return monotonic_time - self._reference_time

    def find_precursors(self, frame_peaks, transformators, ms1_monotonic_time, ms1_token):
        with self._lock:
            if self._is_initialized is False:
                return

            try:
                # we start a new cycle, copy current msms_info to the previous
                self._previous_ms2_info.ms1_frame_id = self._current_ms2_info.ms1_frame_id
                # a deep copy of range
                self._previous_ms2_info.precursor_range = self._current_ms2_info.precursor_range
                # increment ms1 frame id and invalidate precursor range
                self._current_ms2_info.ms1_frame_id += 1
                self._current_ms2_info.precursor_range = range(-1, -1)
                _log.debug(f"ms1 frame id: {self._current_ms2_info.ms1_frame_id}")

                self._ms1_analysis_time = self._get_analysis_time(ms1_monotonic_time)
                _log.debug(f"ms1 frame time {self._ms1_analysis_time}")
                self._current_mob_trafo = transformators.tims_transformator
            except Exception as ex:
                self._is_initialized = False
                _log.error(f"exception in find_precursors, uninitializing paser-plugin {ex}")

    def schedule_candidates(self, candidates, settings):
        _log.info(f'schedule_candidates got {len(candidates)} candidates')
        with self._lock:
            # If not currently not acquiring data: Skip
            if self._is_initialized is False or len(candidates) == 0:
                return

            try:
                min_id = min(candidates, key=lambda c: c.precursor.engine_id).precursor.engine_id
                max_id = max(candidates, key=lambda c: c.precursor.engine_id).precursor.engine_id
                self._current_ms2_info.precursor_range = range(min_id, max_id + 1)  # range end is exclusive

                _log.debug(
                    f"sched, prev: {self._previous_ms2_info.ms1_frame_id}, {self._previous_ms2_info.precursor_range}")
                _log.debug(
                    f"sched, curr: {self._current_ms2_info.ms1_frame_id}, {self._current_ms2_info.precursor_range}")
            except Exception as ex:
                self._is_initialized = False
                _log.error(f"exception schedule_candidates, uninitializing paser-plugin {ex}")

    """
    ------------------  Exclusion-MS process_candidates Start ------------------
    """
    def process_candidates(self, candidates, make_candidate, enable_individual_collision_energies):

        with self._lock:

            if self._is_initialized is False or len(candidates) == 0:
                return

            def is_candidate_valid(candidate) -> bool:
                if candidate.precursor.monoisotopic_mz is None or candidate.precursor.monoisotopic_mz == 0:
                    return False
                if candidate.precursor.charge is None or candidate.precursor.charge == 0:
                    return False
                if candidate.one_over_k0 is None or candidate.one_over_k0 == 0:
                    return False
                return True

            start_time = time.time()
            for i in sorted([i for i, candidate in enumerate(candidates) if not is_candidate_valid(candidate)],
                            reverse=True):
                candidates.pop(i)

            if len(candidates) == 0 or self._exid is None:
                return

            exclusion_points = []
            num_starting_candidates = len(candidates)
            for candidate in candidates:
                exclusion_points.append(ExclusionPoint(charge=candidate.precursor.charge,
                                                       mass=calculate_mass(candidate.precursor.monoisotopic_mz,
                                                                           candidate.precursor.charge),
                                                       rt=self._ms1_analysis_time,
                                                       ook0=candidate.one_over_k0,
                                                       intensity=candidate.precursor.intensity))

            try:
                exclusion_flags = get_excluded_points(self._config.exclusion_api.ip,
                                                      exclusion_points=exclusion_points)

                for i in sorted([i for i, flag in enumerate(exclusion_flags) if flag], reverse=True):
                    candidates.pop(i)

            except Exception as ex:
                _log.error(f'exception when excluding candidates: {ex}')
            finally:
                _log.info(f"starting candidates: {num_starting_candidates}, remaining candidates: {len(candidates)}")
                _log.info("--- %s process_candidates time (seconds) ---" % round((time.time() - start_time), 4))
    """
    ------------------  Exclusion-MS process_candidates End ------------------
    """

    def new_msms_spectra(self, spectra, ms2_monotonic_time):
        with self._lock:
            if self._is_initialized is False or len(spectra) == 0:
                return
            try:
                min_id = min(spectra, key=lambda s: s.precursor.engine_id).precursor.engine_id
                max_id = max(spectra, key=lambda s: s.precursor.engine_id).precursor.engine_id
                _log.debug(f"msms spectra: ({min_id}, {max_id})")

                for spec in spectra:
                    self._ms2_spectrum_id += 1
                    if spec.precursor.engine_id in self._previous_ms2_info.precursor_range:
                        ms1_frame_id = self._previous_ms2_info.ms1_frame_id
                        _log.debug(
                            f"spec {spec.precursor.engine_id}, prev cycle {self._previous_ms2_info.ms1_frame_id}")
                    elif spec.precursor.engine_id in self._current_ms2_info.precursor_range:
                        ms1_frame_id = self._current_ms2_info.ms1_frame_id
                        _log.debug(f"spec {spec.precursor.engine_id}, curr cycle {self._current_ms2_info.ms1_frame_id}")
                    else:
                        _log.warning(f"invalid msms spectrum id {spec.precursor.engine_id}")
                        continue

                    # Currently, we ignore ms2 spectra where precursor charge could not be detected.
                    # In that case charge is 0, and we ignore that ms2 spectrum.
                    if spec.precursor.charge is None:
                        continue

                    """
                    ------------------  Exclusion-MS new_msms_spectra Start ------------------
                    """
                    if self._dynamic_tolerance is not None and self._exid is not None:
                        self._exclude_ms2_spec(spec, self._ms2_spectrum_id, self._ms1_analysis_time)
                    """
                    ------------------  Exclusion-MS new_msms_spectra End ------------------
                    """

                    # Note, currently we ignore ms2 spectra where precursor charge and monoisotopic m/z could not be
                    # detected. So we do not have to worry about spectrum.precursor.monoisotopic_mz being None, here
                    ms2_record = self._map_ms2_spec(spec, ms1_frame_id, self._ms2_spectrum_id, self._ms1_analysis_time)
                    self._producer.publish_ms2_pasef_spectrum(ms2_record)
            except Exception as ex:
                self._is_initialized = False
                _log.error(f"exception publishing ms2 spectra, uninitializing paser-plugin {ex}")

    def _map_ms2_spec(self, spectrum, ms1_frame_id, ms2_spectrum_id, time_):
        precursor_mobility = 0.0
        if self._current_mob_trafo is not None:
            precursor_mobility = self._current_mob_trafo.scan_number_to_one_over_k0(spectrum.precursor.scan_number)
        else:
            _log.error("mobility transformator invalid")

        # mz values and intensity values are encoded as little endian ordered bytes here
        # note that .tobytes() also works on an empty array
        return ms2_pasef_spectrum_to_avro(ms2_id=ms2_spectrum_id, parent_id=ms1_frame_id, rt=time_,
                                          ooK0=precursor_mobility, mono_mz=spectrum.precursor.monoisotopic_mz,
                                          intensity=spectrum.precursor.intensity, charge=spectrum.precursor.charge,
                                          mz_arr=spectrum.mz_values, intensity_arr=spectrum.area_values)

    """
    ------------------  Exclusion-MS _exclude_ms2_spec Start ------------------
    """
    def _exclude_ms2_spec(self, spectrum, ms2_spectrum_id, time_):
        precursor_mobility = 0.0
        if self._current_mob_trafo is not None:
            precursor_mobility = self._current_mob_trafo.scan_number_to_one_over_k0(spectrum.precursor.scan_number)
        else:
            _log.error("mobility transformator invalid")

        mz = spectrum.precursor.monoisotopic_mz
        charge = spectrum.precursor.charge
        ook0 = precursor_mobility[0]
        rt = time_
        intensity = spectrum.precursor.intensity

        if None in [mz, charge, ook0, rt, intensity] or 0 in [mz, charge, ook0, rt, intensity]:
            return

        interval_id = f'{self._uid}_{ms2_spectrum_id}'
        mass = calculate_mass(mz, charge)

        exclusion_point = ExclusionPoint(charge=charge, mass=mass, rt=rt, ook0=ook0, intensity=intensity)
        exclusion_interval = self._dynamic_tolerance.construct_interval(interval_id=interval_id,
                                                                        exclusion_point=exclusion_point)
        try:
            add_exclusion_interval_query(exclusion_api_ip=self._config.exclusion_api.ip,
                                         exclusion_interval=exclusion_interval)
        except Exception as ex:
            _log.error(f'Problem posing new dynamic interval {ex}')

    """
    ------------------  Exclusion-MS _exclude_ms2_spec End ------------------
    """


#!/usr/bin/python3

import os, json

from log import logger

class ServiceMgr():
    def sys_call(self, command):
        output = subprocess.getoutput(command).strip()
        return None if output == '' else output

    def sys_return(self,command):
        return_value = subprocess.call(command,shell=True)
        return return_value

    def loadfile(self, fileurl):
        if not os.path.isfile(fileurl):
            return None
        f = open(fileurl, 'r')
        if not f :
            logger.info ("open file %s failed" % servicelistfile)
            return None
        return json.loads(f.read())

    def get_serviceconf(self, service, publicpath, privatepath):
        serviceconf = None
        serviceconf = self.loadfile(privatepath+service+'/'+service+'.config')
        if serviceconf is None:
            serviceconf = self.loadfile(publicpath+service+'/'+service+'.config')
        return serviceconf

    def parse_multinodes(self, multinodes, publicpath, imagename, imageowner, imagetype):
        privatepath = self.FS_PREFIX+'/global/images/'+imagetype+'/'+imageowner+'/'+imagename+'/home/init.c/'
        if imagename is 'base':
            privatepath = publicpath
        servicelist = multinodes.split('+')
        mservice = []
        oservice = []
        for service in servicelist:
            serviceconf = self.get_serviceconf(service, publicpath, privatepath)
            if serviceconf is None:
                continue
            else :
                if 'one' in serviceconf.keys():
                    oservice.append(service)
                else :
                    mservice.append(service)
        return [oservice, mservice]

    def replace_params(self, script, services):
        script = script.replace("$MASTER$", services['master'])
        return script

    def __init__(self):
        #self.FS_PREFIX = env.getenv('FS_PREFIX')
        self.FS_PREFIX = "/opt/docklet"

    def list_service(self, imagename, username, isshared):
        onenode_service = []
        multinode_service = []

        #get system service
        servicelistpath = self.FS_PREFIX + '/local/basefs/home/init.s/service.list'
        allservice = self.loadfile(servicelistpath)
        onenode_service.extend(allservice['one-node'])
        multinode_service.extend(allservice['multi-node'])

        #get image service
        if not imagename is 'base' :
            servicelistpath = self.FS_PREFIX + '/global/images/' + isshared + '/' + username + '/' + imagename + '/home/init.c/service.list'
            imageservice = self.loadfile(servicelistpath)
            if not imageservice is None:
                onenode_service.extend(imageservice['one-node'])
                multinode_service.extend(imageservice['multi-node'])

        onenode_service.sort()
        multinode_service.sort()

        result = {}
        result['onenode'] = onenode_service
        result['multinode'] = multinode_service

        return result

    def create_service(self, username, clustername, image, onenode, multinodes):
        imagename = image['name']
        imageowner = image['owner']
        imagetype = image['type']
        #servicepath = self.FS_PREFIX+'/global/users/'+username+'/clusters/'+clustername+'.service'
        publicpath = self.FS_PREFIX+'/local/basefs/home/init.s/'
        clustersize = 1
        services = {}
        services['host-0'] = []
        services['master'] = 'host-0'
        #one node cluster or multinode cluster
        if onenode is None and multinodes is None:
            return [clustersize, services]
        elif multinodes is None:
            if isinstance(onenode, str):
                services['host-0'].append(onenode)
            else:
                for service in onenode:
                    services['host-0'].append(service)
        else :
            clustersize = 2
            #parse multinode services into one-node type and multi-node type
            [oservice, mservice] = self.parse_multinodes(multinodes, publicpath, imagename, imageowner, imagetype)
            olen = len(oservice)
            mlen = len(mservice)
            if olen > clustersize:
                clustersize = olen
            for i in range(0, clustersize):
                services['host-'+str(i)] = []
            for i in range(0, olen):
                services['host-'+str(i)].append(oservice[i])
            if not mservice is None:
                for i in range(0, clustersize):
                    for j in range(0, mlen):
                        services['host-'+str(i)].append(mservice[j])

        logger.info ('service file content : %s' % services)
        #servicefile = open(servicepath, 'w')
        #servicefile.write(json.dumps(services))
        #servicefile.close()
        return [clustersize, services]

    def gen_servicecmd(self, clustername, username, info):
        publicpath = self.FS_PREFIX+'/local/basefs/home/init.s/'
        clustersize = info['size']
        servicelist = []
        for i in range(0, clustersize):
            servicecmd = []
            containername = info['containers'][i]['containername']
            privatepath = self.FS_PREFIX+'/local/volume/'+containername+"/upper/home/init.c/"
            services = info['services']['host-'+str(i)]
            for service in services:
                serviceconf = self.get_serviceconf(service, publicpath, privatepath)
                if 'one' in serviceconf.keys():
                    script = serviceconf['one']['path'] + ' ' + serviceconf['one']['params']
                    servicecmd.append(script)
                else :
                    if i == 0:
                        script = serviceconf['master']['path'] + ' ' + self.replace_params(serviceconf['master']['params'], info['services'])
                        servicecmd.append(script)
                    script = serviceconf['slave']['path'] + ' ' + self.replace_params(serviceconf['slave']['params'], info['services'])
                    servicecmd.append(script)
            servicelist.append(servicecmd)
        logger.info ("services cmd is : %s" % servicelist)
        return servicelist

if __name__ == '__main__':
    smgr = ServiceMgr()
    [flag, services] = smgr.create_service('root', 'lk', 'base', 'docklet', 'base', ['ssh', 'jupyter'], None)
    print ('services returned is %s' % services)
    [flag, services] = smgr.create_service('root', 'lk', 'base', 'docklet', 'base', None, 'apache2+mysql')
    print ('services returned is %s' % services)
    [flag, services] = smgr.create_service('root', 'lk', 'base', 'docklet', 'base', None, 'spark')
    print ('services returned is %s' % services)


class Solution:
    def findUnsortedSubarray(self, nums: List[int]) -> int:
        r = 0
        l = len(nums)

        for i in range(0, len(nums) - 1):
            for j in range(i+1, len(nums)):
                if nums[j] < nums[i]:
                    r = max(r, j)
                    l = min(l, i)

        return r - l + 1 if r - l > 0 else 0


from CubePostprocessor.base import SLICER_SLIC3R
from CubePostprocessor.flavor_makerbot import MakerBotFlavor

class Slic3rPrintFile(MakerBotFlavor):

    slicer_type = SLICER_SLIC3R
    # Tune this to make filament flow fit your needs
    FLOW_MULTIPLIER = 0.365 # ok for MK8 drive gear

    def __init__(self, debug=False):
        super().__init__(debug=debug)


t = int(input())

for i in range(t):
    women = list()
    men = list()

    n = int(input())
    for j in range(n):
        l = input().split()
        men.append([int(i) for i in l])
    for j in range(n):
        l = input().split()
        women.append([int(i) for i in l])

    wi = [-1] * n
    mi = [1] * n

    while -1 in wi:
        for m0 in range(n):
            w0 = men[m0][mi[m0]] - 1
            if (wi[w0] < 0):
                wi[w0] = m0
            else:
                p0 = women[w0][1:].index(wi[w0] + 1)
                p1 = women[w0][1:].index(m0 + 1)
                if p1 < p0:
                    mi[wi[w0]] = mi[wi[w0]] + 1
                    wi[w0] = m0
                elif p0 < p1:
                    mi[m0] = mi[m0] + 1

    for w in range(n):
        print(w + 1, wi[w] + 1)