#has errors

k = int(input())
input()

out = []

def get(a_list,index):
    return(a_list[index])

for i in range(k):
    m,n = input().split()

    elementsAdded = list(map(int,input().split()))
    getsAfter = list(map(int,input().split()))

    p = 0
    for j in range(len(elementsAdded)):
        out.append(elementsAdded[j])
        out.sort()
        maxi = max(out)

        if p <= getsAfter[p] and getsAfter[p] <= maxi:
            print(get(out,p))
            p += 1


import os
import socket
import ssl
from logging import getLogger

import pnp.infra.utils.pnp_constants as consts
from pnp.infra.system.certificate import get_certificates_location

def load_csdl_ssl_context(cafile_='', default_certs=False, trustpool=False):
    """Returns SSLContext object initialized to meet CSDL standards.

    Args:
        cafile_ (str, optional): Path to CA file containing PEM encoded cert(s).
            Defaults to empty string.
        default_certs (bool, optional): Load default OpenSSL certificates.
            Defaults to False.
        trustpool (bool, optional): Load an existing Trustpool bundle. Defaults
            to False.

    Returns:
        SSLContext: SSL Context loaded with requested certificates.

    """
    # Important to overload ssl.match_hostname in order support verifying the
    # identity of HTTPS server's certificate through the IP address in the
    # Subject Alternate Name field
    ssl.match_hostname = _match_hostname_ip
    ssl_context = ssl.SSLContext(consts.CSDL_SSL_PROTOCOL)
    ssl_context.verify_mode = ssl.CERT_REQUIRED
    # Set hostname verification during TLS handshake
    ssl_context.check_hostname = consts.CSDL_SSL_CHECK_HOSTNAME
    # Set CSDL approved ciphers in OpenSSL cipher list format
    ssl_context.set_ciphers(':'.join(consts.CSDL_CIPHERS))
    if cafile_ == 'default' or default_certs or consts.DEFAULT_CERTS_ENABLED:
        ssl_context.load_default_certs(ssl.Purpose.SERVER_AUTH)
    if trustpool:
        trustpool_path = get_certificates_location('trustpool')
        if os.path.isfile(os.path.join(trustpool_path, 'trustpool.pem')):
            ssl_context.load_verify_locations(trustpool_path)
    try:
        if cafile_:
            ssl_context.load_verify_locations(cafile=cafile_)
    except (ssl.SSLError, IOError, TypeError):
        if cafile_ != 'default':
            getLogger(__name__).exception("Failed to load configured cafile")
    return ssl_context

def _match_hostname_ip(cert, hostname):
    """This function is copied from ssl.match_hostname available in Python 2.7.9
    and has been extended to support server identity verification through
    IP Address in the subjectAltName field of cert. Verify that *cert* (in
    decoded format as returned by SSLSocket.getpeercert()) matches the
    *hostname*.  RFC 2818 and RFC 6125 rules are followed, but IP addresses are
    not accepted for *hostname*.

    CertificateError is raised on failure. On success, the function returns
    nothing.
    """
    if not cert:
        raise ValueError("empty or no certificate, match_hostname needs a "
                         "SSL socket or SSL context with either "
                         "CERT_OPTIONAL or CERT_REQUIRED")
    dnsnames = []
    san = cert.get('subjectAltName', ())
    for key, value in san:
        if key == 'DNS':
            if ssl._dnsname_match(value, hostname):  # pylint: disable=protected-access
                return
            elif hostname.endswith('.'):  # don't enforce trailing-dot in FQDN
                if ssl._dnsname_match(value, hostname[:-1]):  # pylint: disable=protected-access
                    return
            dnsnames.append(value)
        # PNP SPECIFIC CODE STARTS HERE
        elif key == 'IP Address':
            # Enhancement: if _ip_address_match(value, hostname): return
            if _ssl_ip_address_match(value, hostname):
                return
            dnsnames.append(value)
        # PNP SPECIFIC CODE ENDS HERE
    if not dnsnames:
        # The subject is only checked when there is no dNSName entry
        # in subjectAltName
        for sub in cert.get('subject', ()):
            for key, value in sub:
                if key == 'commonName':
                    if ssl._dnsname_match(value, hostname):  # pylint: disable=protected-access
                        return
                    dnsnames.append(value)
    if len(dnsnames) > 1:
        raise ssl.CertificateError("hostname %r doesn't match either of %s" %
                                   (hostname, ', '.join(map(repr, dnsnames))))  # pylint: disable=bad-builtin
    elif len(dnsnames) == 1:
        raise ssl.CertificateError("hostname %r doesn't match %r" %
                                   (hostname, dnsnames[0]))
    else:
        raise ssl.CertificateError("no appropriate commonName or subjectAltName"
                                   " fields were found")

def _ssl_ip_address_match(value, ip_address):
    """Retruns True if ip_address matches value"""
    # Remove any extra whitespace characters from cert value
    value = value.strip()
    # Determine ip_address protocol version and convert to packed, binary format
    address_family = socket.AF_INET
    try:
        binary_ip_address = socket.inet_aton(ip_address)
    except socket.error:
        address_family = socket.AF_INET6
        try:
            binary_ip_address = socket.inet_pton(address_family, ip_address)
        except socket.error:
            # ip_address is neither IPv6 nor IPv4
            return False
    # Convert value to packed, binary format and enforce address family
    try:
        binary_value = socket.inet_pton(address_family, value)
    except socket.error:
        return False
    # Compare the two addresses after converting each to packed, binary format
    return binary_value == binary_ip_address


from pokemon_stat_calc import StatCalculator
from pokemon_csv import base_stats
import pandas as pd
from funcs import inclusive_range
import numpy as np

frames = []
global_ivs = {stat: 15 for stat in ["hp", "attack", "defense", "sp_attack", "sp_defense", "speed"]}
for i in range(386):
    d = {}
    species = base_stats.index[i]
    bs = base_stats.iloc[i].to_dict()
    for j in inclusive_range(1, 100):
        stats = StatCalculator(level = j, ivs = global_ivs, nature = "Bashful", base_stats = bs)
        total_stat = int(np.sum(list(stats.values())))
        d[i * j] = {
            "species": species,
            "level": j,
            "total_stat": total_stat
        }
    f = pd.DataFrame.from_dict(d).transpose()
    frames.append(f)

a = pd.concat(frames)


# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
"""
import sys

sys.path.append('..')

from nerpy.ner_model import NERModel

def test_get_entity():
    from seqeval.metrics.sequence_labeling import get_entities
    seq = ['B-PER', 'I-PER', 'I-PER', 'O', 'B-LOC', 'O']
    r = get_entities(seq)
    print(r)
    # [('PER', 0, 2), ('LOC', 4, 4)]
    sent = ['温家宝在京的']
    line_entities = get_entities(seq)
    pairs = []
    for i in line_entities:
        word = sent[0][i[1]: i[2] + 1]
        entity_type = i[0]
        pairs.append((word, entity_type))
    print(pairs)


import itertools as it
import re
from collections import namedtuple
from copy import deepcopy
from inspect import cleandoc

import numpy as np

from getml.data.roles import (
    join_key,
    numerical,
    target,
    text,
    time_stamp,
    unused_float,
    unused_string,
)

from ..templates import environment
from .formatter import (
    MAX_CELL_WIDTH,
    _clip_cell,
    _FormatColumn,
    _Formatter,
    _IndexColumn,
    _infer_precision,
)
from .helpers import _get_data_frame_content

UNITS = ["D", "h", "m", "s", "ms"]
"""
Numpy datetime units.
"""

UNITS_FORMATS = dict(
    D="{:%Y-%m-%d}",
    h="{:%Y-%m-%d %H}",
    m="{:%Y-%m-%d %H:%M}",
    s="{:%Y-%m-%d %H:%M:%S}",
    ms="{:%Y-%m-%d %H:%M:%S.%f}",
)
"""
A mapping of numpy datetime units to strftime format specifiers.
"""

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

def _get_subroles(col):
    subroles = {}

    subroles["exclude"] = [
        _parse_subrole(subrole)
        for subrole in getattr(col, "subroles", [])
        if subrole.startswith("exclude ")
    ]
    subroles["include"] = [
        _parse_subrole(subrole)
        for subrole in getattr(col, "subroles", [])
        if subrole.startswith("include ")
    ]
    subroles["only"] = [
        _parse_subrole(subrole)
        for subrole in getattr(col, "subroles", [])
        if subrole.startswith("only ")
    ]

    return subroles

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

def _parse_subrole(subrole):
    prefix = re.compile(r"^(exclude |include |only )")
    return re.sub(prefix, "", subrole)

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

def _structure_subroles(df):
    subroles = {"exclude": [], "include": [], "only": []}
    df_subroles = [_get_subroles(df[col]) for col in df.colnames]

    for col_subroles in df_subroles:
        for cat, values in subroles.items():
            values.append(col_subroles[cat])

    return subroles

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

def _infer_resolution(cells):
    cells = np.array(cells, dtype="datetime64")
    deltas = np.unique(cells[1:] - cells[:-1])

    for unit in UNITS:
        normalized_deltas = np.array(
            [np.timedelta64(delta, "ms") for delta in deltas]
        ) / np.timedelta64(1, unit)
        if all(np.mod(normalized_deltas, 1) == 0):
            return unit

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

def _max_digits(cells):
    cells = [cell for cell in cells if "." in cell]
    if len(cells) > 0:
        return max(len(cell.split(".")[1]) for cell in cells)
    return 0

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

class _DataFrameFormatter(_Formatter):
    """
    A Formatter for DataFrames.
    """

    max_rows = 10

    template = environment.get_template("data_frame.jinja2")

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

    def __init__(self, df, num_head=max_rows // 2, num_tail=max_rows // 2):
        self.colnames = df.colnames
        self.n_rows = len(df)
        self.name = df.name
        self.memory_usage = df.memory_usage

        num_head = min(num_head, self.n_rows // 2 + 1)
        num_tail = min(num_tail, self.n_rows // 2)

        roles = [df[colname].role for colname in df.colnames]

        units = [df[colname].unit for colname in df.colnames]

        self.units = None

        self.subroles = {
            cat: subroles
            for cat, subroles in _structure_subroles(df).items()
            if any(subrole for subrole in subroles)
        }

        head = _get_data_frame_content(name=df.name, start=0, length=num_head)["data"]
        tail = _get_data_frame_content(
            name=df.name, start=int(self.n_rows - num_tail), length=num_tail
        )["data"]

        rows = head + tail

        columns = [list(col) for col in zip(*rows)]

        headers = [self.colnames] + [roles]

        if any(unit != "" for unit in units):
            self.units = units
            headers += [units]

        if self.subroles:
            headers += [[""] * len(columns)] + [
                subroles
                for subroles in self.subroles.values()
                if any(subrole for subrole in subroles)
            ]

        headers = list(zip(*headers))

        self.data = [
            _DataFrameFormatColumn(
                headers=list(header),
                cells=cells,
                max_cells=self.max_rows,
                n_cells=self.n_rows,
                role=role,
            )
            for header, role, cells in zip(headers, roles, columns)
        ]

        index_headers = ["name"]
        if self.roles:
            index_headers += ["role"]
        if self.units:
            index_headers += ["unit"]
        if self.subroles:
            index_headers += ["subroles:"] + [f"- {cat:7}" for cat in self.subroles]

        self._add_index(index_headers)

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

    def __len__(self):
        return self.n_rows

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

    def _render_footer_lines(self, footer):
        if footer.url is None or footer.name is None:
            return cleandoc(
                f"""
                {footer.n_rows} rows x {footer.n_cols} columns
                memory usage: {footer.memory_usage:.2f} MB
                type: {footer.type}
                """
            )
        return cleandoc(
            f"""
            {footer.n_rows} rows x {footer.n_cols} columns
            memory usage: {footer.memory_usage:.2f} MB
            name: {footer.name}
            type: {footer.type}
            url: {footer.url}
            """
        )

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

    def _add_index(self, headers):
        index_column = _IndexColumn(
            headers=headers,
            n_cells=self.n_rows or self.max_rows + 1,
            length=self.max_rows,
        )

        self.data = [index_column] + self.data

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

    def _render_html(self, footer=None):
        headers = self._render_head()
        rows = self._render_body(as_html=True)

        precisions = [getattr(column, "precision", None) for column in self.data]

        cell = namedtuple("cell", ["role", "value"])
        headers = [
            [cell(role, header) for role, header in zip(self.roles, headers)]
            for headers in headers
        ]
        rows = [
            [cell(role, value) for role, value in zip(self.roles, row)] for row in rows
        ]

        return self.template.render(
            headers=headers, rows=rows, precisions=precisions, footer=footer
        )

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

    def _render_body(self, as_html=False):
        for col in self.data:
            if col._instances_are(str):
                col.data = [_clip_cell(cell, MAX_CELL_WIDTH) for cell in col.data]

        columns_formatted = [column._format_cells() for column in self.data]

        columns_clipped = [column._clip() for column in columns_formatted]

        if as_html:
            cells = [column._unnest_and_strip_html() for column in columns_clipped]
        else:
            cells = [column._expand_cells() for column in columns_clipped]

        rows = [list(row) for row in zip(*cells)]

        return rows

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

    def _render_string(self, footer=None):

        lines = super()._render_string()

        footer_lines = self._render_footer_lines(footer) if footer else ""

        return lines + "\n\n\n" + footer_lines

    @property
    def roles(self):
        return [getattr(column, "role", None) for column in self.data]

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

class _DataFrameFormatColumn(_FormatColumn):
    """
    A Formatter for columns of a DataFrame.

    The cell format is set based on the column's role.
    """

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

    def __init__(self, *args, n_cells, role=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.n_cells = n_cells
        self.resolution = None
        self.role = role

        # self.parse_cells()
        if self.role in [numerical, target, time_stamp, join_key, unused_float]:
            self.precision = _max_digits(self.data)

        self.cell_template = self.default_cell_template
        self.header_template = self.default_header_template

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

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

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

    def _format_cells(self):
        """
        A patch to justify time stamps. This is necessary because afaik we are not able
        to specify justification within strftime format strings.
        """
        cells_formatted = super()._format_cells()

        if self.role == "time_stamp":
            cells_formatted.data = [
                cell.ljust(self.width) for cell in cells_formatted.data
            ]

        return cells_formatted

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

    def _clip(self):
        ellipses = "..." + getattr(self, "precision", 0) * " "
        column_clipped = deepcopy(self)

        if self.role is None:
            ellipses = [self.header_template.format(ellipses)]
            if self.nested:
                ellipses = [ellipses]
            column_clipped.data += ellipses
            return column_clipped

        return super()._clip(ellipses=ellipses)

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

    def _parse_cells(self):
        # some fun parsing
        if self.role == time_stamp:
            if all(cell.isdigit() for cell in self.data):
                self.data = np.array(self.data, dtype="float")
                self.data = np.array(self.data, dtype="datetime64[s]").tolist()
            else:
                self.data = np.array(self.data, dtype="datetime64[ms]").tolist()

            resolutions = list(
                set(
                    [
                        _infer_resolution(self.data[: len(self.data) // 2]),
                        _infer_resolution(self.data[len(self.data) // 2 :]),
                    ]
                )
            )

            # sort resolutions in ascending order and pick the smallest one
            self.resolution = sorted(
                resolutions, key=lambda res: UNITS.index(res), reverse=True
            )[0]

        if self.role in [numerical, target, join_key, unused_float]:
            # this logic might be too simplistic, but data comes from the engine
            # in a standardized format anyway, so...¯\_(ツ)_/¯
            if any("." in cell for cell in self.data):
                self.data = [float(cell) for cell in self.data]
                self.precision = _infer_precision(self.data)
            elif all(cell.isdigit() for cell in self.data):
                self.data = [int(cell) for cell in self.data]

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

    @property
    def default_cell_template(self):

        if getattr(self, "role", None) in [
            join_key,
            numerical,
            target,
            time_stamp,
            unused_float,
        ]:
            if all(str(cell).isdigit() for cell in self.data):
                return "{:" f">{self.width}" "}"
            return "{:" f" {self.width}.{self.precision}d" "}"

        return super().default_cell_template

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

    @property
    def default_header_template(self):

        if getattr(self, "role", None) in [
            join_key,
            numerical,
            target,
            time_stamp,
            unused_float,
        ]:
            return "{:" f">{self.width}" "}"

        return super().default_header_template


import dialogflow_v2 as dialogflow
import re

class DialogflowManager:

    def __init__(self, project_id, session_id, language_code):

        self.project_id = project_id
        self.session_id = session_id

        self.intents_client = dialogflow.IntentsClient()
        self.parent = self.intents_client.project_agent_path(project_id)
        self.intents = self.intents_client.list_intents(self.parent)

        self.contexts_client = dialogflow.ContextsClient()
        self.context_parent = self.contexts_client.session_path(project_id, session_id)

        self.session_client = dialogflow.SessionsClient()
        self.session = self.session_client.session_path(project_id, session_id)
        self.lang_code = "es"

    def get_intents(self):
        return self.intents

    def get_contexts(self):
        return self.contexts_client.list_contexts(self.context_parent)

    def set_contexts(self, contexts):
        self.contexts_client.delete_all_contexts(self.context_parent)
        for c in contexts:
            self.contexts_client.create_context(self.context_parent, c)

    def create_context(self, context):
        self.contexts_client.create_context(self.context_parent, context)

    def delete_context(self, context):
        self.contexts_client.delete_context(self.context_parent, context)

    def request_fulfillment_text(self, text):
        res = ""
        if text:
            text_input = dialogflow.types.TextInput(text=text, language_code=self.lang_code)
            query_input = dialogflow.types.QueryInput(text=text_input)
            try:
                response = self.session_client.detect_intent(session=self.session, query_input=query_input)
                res = self.handleResponse(response)
            except Exception:
                raise

        return res

    def handleResponse(self, response):
        res = {}
        res['text'] = response.query_result.fulfillment_text
        res['intent'] = response.query_result.intent.display_name
        res['params'] = {}
        values = ['_dialog_context', '-followup']
        #'contexts/__system_counters__']
        word = re.compile("|".join(values))

        for context in response.query_result.output_contexts:
            if word.search(context.name):
                for param in context.parameters:
                    res['params'][param] = context.parameters[param]
                break

        word = re.compile('mood_')

        for param in response.query_result.parameters:
            if word.search(param.lower()):
                res['params'][param.lower()] = response.query_result.parameters[param]
        return res


from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import pytest
from mne.utils import check_version
from numpy.testing import assert_allclose

if check_version("mne", "1.6"):
    from mne._fiff.constants import FIFF
else:
    from mne.io.constants import FIFF

from mne_lsl import logger
from mne_lsl.lsl import StreamInlet, local_clock, resolve_streams
from mne_lsl.player import PlayerLSL as Player
from mne_lsl.utils._tests import match_stream_and_raw_data

logger.propagate = True

def _create_inlet(name: str) -> StreamInlet:
    """Create an inlet to the open-stream."""
    streams = resolve_streams()
    assert len(streams) == 1
    assert streams[0].name == name
    inlet = StreamInlet(streams[0])
    inlet.open_stream()
    return inlet

def test_player(caplog, fname, raw, close_io):
    """Test a working and valid player."""
    name = "Player-test_player"
    player = Player(fname, name=name)
    assert "OFF" in player.__repr__()
    streams = resolve_streams(timeout=0.1)
    assert len(streams) == 0
    player.start()
    assert "ON" in player.__repr__()
    streams = resolve_streams()
    assert len(streams) == 1
    assert streams[0].name == name

    # try double start
    caplog.set_level(30)  # WARNING
    caplog.clear()
    player.start()
    assert "player is already started" in caplog.text

    # connect an inlet to the player
    inlet = StreamInlet(streams[0])
    inlet.open_stream()
    data, ts = inlet.pull_chunk()
    now = local_clock()
    assert_allclose(now, ts[-1], rtol=0, atol=0.1)  # 100 ms of freedom for slower CIs
    assert data.shape[1] == len(player.info["ch_names"])

    # check sampling rate
    fs = 1 / np.diff(ts)
    assert_allclose(fs, player.info["sfreq"])

    # check inlet information
    sinfo = inlet.get_sinfo()
    assert sinfo.n_channels == len(player.info["ch_names"])
    assert sinfo.get_channel_names() == player.info["ch_names"]
    assert sinfo.get_channel_types() == player.get_channel_types()
    assert sinfo.get_channel_units() == [
        str(int(ch["unit_mul"])) for ch in player.info["chs"]
    ]

    # check player vs raw
    assert player.info["sfreq"] == raw.info["sfreq"]
    assert player.info["ch_names"] == raw.info["ch_names"]
    assert player.get_channel_types() == raw.get_channel_types()
    assert [ch["unit_mul"] for ch in player.info["chs"]] == [
        ch["unit_mul"] for ch in raw.info["chs"]
    ]

    # check that the returned data array is in raw
    match_stream_and_raw_data(data.T, raw)
    close_io()

def test_player_context_manager(fname):
    """Test a working and valid player as context manager."""
    name = "Player-test_player_context_manager"
    streams = resolve_streams(timeout=0.1)
    assert len(streams) == 0
    with Player(fname, name=name):
        streams = resolve_streams(timeout=0.1)
        assert len(streams) == 1
        assert streams[0].name == name
    streams = resolve_streams(timeout=0.1)
    assert len(streams) == 0

def test_player_invalid_arguments(fname):
    """Test creation of a player with invalid arguments."""
    with pytest.raises(FileNotFoundError, match="does not exist"):
        Player("invalid-fname.something")
    with pytest.raises(ValueError, match="Unsupported file type"):
        Player(Path(__file__))
    with pytest.raises(TypeError, match="'name' must be an instance of str or None"):
        Player(fname, name=101)
    with pytest.raises(TypeError, match="'chunk_size' must be an integer"):
        Player(fname, name="101", chunk_size=101.0)
    with pytest.raises(ValueError, match="strictly positive integer"):
        Player(fname, name="101", chunk_size=-101)

def test_player_stop_invalid(fname):
    """Test stopping a player that is not started."""
    player = Player(fname, name="Player-test_stop_player_invalid")
    with pytest.raises(RuntimeError, match="The player is not started"):
        player.stop()
    player.start()
    player.stop()

def test_player_unit(mock_lsl_stream, raw, close_io):
    """Test getting and setting the player channel units."""
    player = mock_lsl_stream
    name = player.name
    assert player.get_channel_types() == raw.get_channel_types()
    assert player.get_channel_types(unique=True) == raw.get_channel_types(unique=True)
    ch_units = player.get_channel_units()
    assert ch_units == [(FIFF.FIFF_UNIT_NONE, FIFF.FIFF_UNITM_NONE)] + [
        (FIFF.FIFF_UNIT_V, FIFF.FIFF_UNITM_NONE)
    ] * (len(player.ch_names) - 1)

    # try setting channel units on a started player
    with pytest.raises(RuntimeError, match="player is already started"):
        player.set_channel_units({"F7": -6, "Fpz": "uv", "Fp2": "microvolts"})
    inlet = _create_inlet(name)
    data, _ = inlet.pull_chunk()
    match_stream_and_raw_data(data.T, raw)
    close_io()

    # try setting channel units after stopping the player
    player.set_channel_units({"F7": -6, "Fpz": "uv", "Fp2": "microvolts"})
    player.start()
    inlet = _create_inlet(name)
    data, _ = inlet.pull_chunk()
    raw_ = raw.copy().apply_function(lambda x: x * 1e6, picks=["F7", "Fpz", "Fp2"])
    match_stream_and_raw_data(data.T, raw_)
    close_io()

    # try re-setting the channel unit
    player.set_channel_units({"F7": -3})
    player.start()
    inlet = _create_inlet(name)
    data, _ = inlet.pull_chunk()
    raw_ = raw.copy()
    raw_.apply_function(lambda x: x * 1e3, picks="F7")
    raw_.apply_function(lambda x: x * 1e6, picks=["Fpz", "Fp2"])
    match_stream_and_raw_data(data.T, raw_)
    close_io()

def test_player_rename_channels(mock_lsl_stream, raw, close_io):
    """Test channel renaming."""
    player = mock_lsl_stream
    name = player.name
    assert player._sinfo.get_channel_names() == player.info["ch_names"]
    with pytest.raises(RuntimeError, match="player is already started"):
        player.rename_channels(mapping={"F7": "EEG1"})
    inlet = _create_inlet(name)
    sinfo = inlet.get_sinfo()
    assert sinfo.get_channel_names() == player.info["ch_names"]
    close_io()

    # test changing channel names
    player.rename_channels({"F7": "EEG1", "Fp2": "EEG2"})
    raw_ = raw.copy().rename_channels({"F7": "EEG1", "Fp2": "EEG2"})
    player.start()
    inlet = _create_inlet(name)
    sinfo = inlet.get_sinfo()
    assert sinfo.get_channel_names() == player.info["ch_names"]
    assert sinfo.get_channel_names() == raw_.info["ch_names"]
    close_io()

    # test re-changing the channel names
    player.rename_channels({"EEG1": "EEG101", "EEG2": "EEG202"})
    raw_.rename_channels({"EEG1": "EEG101", "EEG2": "EEG202"})
    player.start()
    inlet = _create_inlet(name)
    sinfo = inlet.get_sinfo()
    assert sinfo.get_channel_names() == player.info["ch_names"]
    assert sinfo.get_channel_names() == raw_.info["ch_names"]
    close_io()

def test_player_set_channel_types(mock_lsl_stream, raw, close_io):
    """Test channel type setting."""
    player = mock_lsl_stream
    name = player.name
    assert player._sinfo.get_channel_types() == player.get_channel_types(unique=False)
    assert player.get_channel_types(unique=False) == raw.get_channel_types(unique=False)
    with pytest.raises(RuntimeError, match="player is already started"):
        player.set_channel_types(mapping={"F7": "misc"})
    inlet = _create_inlet(name)
    sinfo = inlet.get_sinfo()
    assert sinfo.get_channel_types() == player.get_channel_types(unique=False)
    close_io()

    # test changing types
    player.set_channel_types(mapping={"F7": "eog", "Fp2": "eog"})
    raw_ = raw.copy().set_channel_types(mapping={"F7": "eog", "Fp2": "eog"})
    player.start()
    inlet = _create_inlet(name)
    sinfo = inlet.get_sinfo()
    assert sinfo.get_channel_types() == player.get_channel_types(unique=False)
    assert sinfo.get_channel_types() == raw_.get_channel_types(unique=False)
    close_io()

    # test rechanging types
    player.set_channel_types(mapping={"F7": "eeg", "Fp2": "ecg"})
    raw_ = raw.copy().set_channel_types(mapping={"Fp2": "ecg"})
    player.start()
    inlet = _create_inlet(name)
    sinfo = inlet.get_sinfo()
    assert sinfo.get_channel_types() == player.get_channel_types(unique=False)
    assert sinfo.get_channel_types() == raw_.get_channel_types(unique=False)
    close_io()

    # test unique
    assert sorted(player.get_channel_types(unique=True)) == sorted(
        raw.get_channel_types(unique=True)
    )

def test_player_anonymize(fname, close_io):
    """Test anonymization."""
    name = "Player-test_player"
    player = Player(fname, name=name)
    assert player.name == name
    assert player.fname == fname
    player.info["subject_info"] = dict(
        id=101,
        first_name="Mathieu",
        sex=1,
    )
    with pytest.warns(RuntimeWarning, match="partially implemented"):
        player.anonymize()
    assert player.info["subject_info"] == dict(id=0, first_name="mne_anonymize", sex=0)
    player.start()
    assert "ON" in player.__repr__()
    with pytest.raises(RuntimeError, match="player is already started"):
        player.anonymize()
    close_io()

def test_player_set_meas_date(fname, close_io):
    """Test player measurement date."""
    name = "Player-test_player"
    player = Player(fname, name=name)
    assert player.name == name
    assert player.fname == fname
    assert player.info["meas_date"] is None
    with pytest.warns(RuntimeWarning, match="partially implemented"):
        meas_date = datetime(2023, 1, 25, tzinfo=timezone.utc)
        player.set_meas_date(meas_date)
    assert player.info["meas_date"] == meas_date
    player.start()
    assert "ON" in player.__repr__()
    with pytest.raises(RuntimeError, match="player is already started"):
        player.set_meas_date(datetime(2020, 1, 25, tzinfo=timezone.utc))
    assert player.info["meas_date"] == meas_date
    close_io()


import logging
import multiprocessing
import os
import shutil
import subprocess

SOURCE_BASE_URL = 'http://ftp.gnu.org/gnu/glibc'
GLIBC_VERSION = 'glibc-2.27'

PATH_THIS = os.path.abspath (os.path.dirname (__file__))
PATH_ARTIFACTS = os.path.join (os.path.dirname (PATH_THIS), 'artifacts')
PATH_GLIBC = os.path.join (PATH_ARTIFACTS, GLIBC_VERSION)
PATH_GLIBC_BUILD = os.path.join (PATH_ARTIFACTS, 'glibc-build')
PATH_GLIBC_OUTPUT = os.path.join (PATH_ARTIFACTS, 'glibc-output')
PATH_LINUX_OUTPUT = os.path.join (PATH_ARTIFACTS, 'linux-output')

#-----------------------------------------------------------------------------
# build

def build ():
   logging.info ('Building %s' % GLIBC_VERSION)
   fetch ()
   clean ()

   if not os.path.exists (PATH_GLIBC_BUILD):
      os.makedirs (PATH_GLIBC_BUILD)

   configure ()
   make ()

   if not os.path.exists (PATH_GLIBC_OUTPUT):
      os.makedirs (PATH_GLIBC_OUTPUT)

   install ()

#-----------------------------------------------------------------------------
# fetch

def fetch ():
   if not os.path.exists (PATH_ARTIFACTS):
      os.makedirs (PATH_ARTIFACTS)

   if not os.path.exists (PATH_GLIBC):
      logging.info ('   Downloading')

      dl_cmd = [
         'wget', '-q',
         '-O', os.path.join (PATH_ARTIFACTS, '%s.tar.bz2' % GLIBC_VERSION),
         '%s/%s.tar.bz2' % (SOURCE_BASE_URL, GLIBC_VERSION)
      ]

      subprocess.check_call (dl_cmd)

      logging.info ('   Extracting')

      tar_cmd = [
         'tar', '-xf', os.path.join (PATH_ARTIFACTS, '%s.tar.bz2' % GLIBC_VERSION)
      ]

      subprocess.check_call (tar_cmd, cwd = PATH_ARTIFACTS)

#-----------------------------------------------------------------------------
# clean

def clean ():
   logging.info ('   Cleaning')

   if os.path.exists (PATH_GLIBC_BUILD):
      shutil.rmtree (PATH_GLIBC_BUILD)

   if os.path.exists (PATH_GLIBC_OUTPUT):
      shutil.rmtree (PATH_GLIBC_OUTPUT)

#-----------------------------------------------------------------------------
# configure

def configure ():
   logging.info ('   Configuring')

   log_file = open (os.path.join (PATH_ARTIFACTS, '%s-configure-log.txt' % GLIBC_VERSION), 'w')

   cmd = [
      os.path.join (PATH_GLIBC, 'configure'),
      '--prefix=',
      '--with-headers=%s/include' % PATH_LINUX_OUTPUT,
      '--without-gd',
      '--without-selinux',
      '--disable-werror',
      'CFLAGS=-Os -s -fno-stack-protector -fomit-frame-pointer -U_FORTIFY_SOURCE'
   ]
   subprocess.check_call (cmd, cwd = PATH_GLIBC_BUILD, stdout = log_file, stderr = log_file)

#-----------------------------------------------------------------------------
# make

def make ():
   logging.info ('   Building')

   log_file = open (os.path.join (PATH_ARTIFACTS, '%s-make-log.txt' % GLIBC_VERSION), 'w')

   cmd = [
      'make',
      '-j', '%d' % multiprocessing.cpu_count ()
   ]
   subprocess.check_call (cmd, cwd = PATH_GLIBC_BUILD, stdout = log_file, stderr = log_file)

#-----------------------------------------------------------------------------
# install

def install ():
   logging.info ('   Installing')

   log_file = open (os.path.join (PATH_ARTIFACTS, '%s-make-install-log.txt' % GLIBC_VERSION), 'w')

   cmd = [
      'make', 'install',
      'DESTDIR=%s' % PATH_GLIBC_OUTPUT,
      '-j', '%d' % multiprocessing.cpu_count ()
   ]
   subprocess.check_call (cmd, cwd = PATH_GLIBC_BUILD, stdout = log_file, stderr = log_file)


from models.classifier import Classifier
import models.xor_resnet as XOR
import torch
import torch.nn as nn
import torch.nn.functional as F

import torchvision.models as models

XORS = {
    'xor_resnet18': XOR.resnet18,
    'xor_resnet34': XOR.resnet34,
    'xor_resnet50': XOR.resnet50,
    'xor_resnet101': XOR.resnet101,
    'xor_resnet152': XOR.resnet152
}

class Model(nn.Module):
	def __init__(self, args, nclass):
		super(Model, self).__init__()

		self.nclass = nclass
		if args.dataset == 'embedding':
			self.backbone = Classifier(self.nclass)
		elif 'xor_resnet' in args.arch:
			self.backbone = XORS[args.arch](pretrained=args.pretrained)
			final_feature = self.backbone.fc.in_features
			self.backbone.fc = nn.Linear(final_feature, self.nclass)
		else:
			self.backbone = models.__dict__[args.arch](pretrained=args.pretrained)
			final_feature = self.backbone.fc.in_features
			self.backbone.fc = nn.Linear(final_feature, self.nclass)

	def forward(self, input):
		x = self.backbone(input)
		return x


#Author: Michael Elgin (melgin@uwyo.edu)

#File to preprocess data from ../data/cifar-10-batches-py
#Assumes cifar-10-batches-py contains the extract from cifar-10-python.tar.gz
#Extracts the wanted 32x32 images to new folder(s) with their labels.
#This file should only need to be executed once.

import os
import pickle
import matplotlib.pyplot as plt

def main():

	DATA_PATH = "../data/cifar-10-batches-py/"
	IMG_PATH = "../data/32/"
	LABELS_PATH = "../data/labels/" #To match all datasets

	#asserts will stop the file from running if it need not be.
	assert(os.path.exists(DATA_PATH))
	assert(len(os.listdir(DATA_PATH)) != 0) #stuff inside
	assert(not (os.path.exists(IMG_PATH) and os.path.exists(LABELS_PATH)))

	os.mkdir(IMG_PATH)
	os.mkdir(IMG_PATH + "train")
	os.mkdir(IMG_PATH + "test")
	os.mkdir(LABELS_PATH)

	#This list becomes the labels for horse and ship subsets of cifar-10
	train_label_subset = []
	test_label_subset = []

	#horses and ships now get gathered with their labels in sync
	batch_files = [DATA_PATH + 'data_batch_' + str(i) for i in range(1,6)] + [DATA_PATH + "test_batch"]
	item = 0
	for batch_file in batch_files:
		with open(batch_file, 'rb') as f:
			batch_dict = pickle.load(f, encoding='bytes')
		batch_data = batch_dict[b'data']
		batch_labels = batch_dict[b'labels']
		for i in range(len(batch_labels)):
			if (batch_labels[i] == 7) or (batch_labels[i] == 8): #horse or ship
				img = batch_data[i].reshape(3,32,32)
				img = img.transpose(1,2,0) #Ref binarystudy.com
				if (batch_file == DATA_PATH + "test_batch"):
					test_label_subset.append(batch_labels[i])
					plt.imsave(IMG_PATH + "test/" + str(item) + ".png", img)
				else:
					train_label_subset.append(batch_labels[i])
					plt.imsave(IMG_PATH + "train/" + str(item) + ".png", img)
				item += 1

	assert(len(train_label_subset) == 10000) #5000 horse + 5000 ship
	assert(len(test_label_subset) == 2000) #1000 horse + 1000 ship

	#Convert to 0 and 1
	train_label_subset = [(0 if label == 7 else 1) for label in train_label_subset]
	test_label_subset = [(0 if label == 7 else 1) for label in test_label_subset]

	with open(LABELS_PATH + "train.pickle", "wb") as f:
		pickle.dump(train_label_subset, f)
	with open(LABELS_PATH + "test.pickle", "wb") as f:
		pickle.dump(test_label_subset, f)

if __name__ == "__main__":
	main()


import numpy as np

def preprocess(df, cols):
    df = df.sort_values(by=['Group', 'Donor', 'Islet', 'Cell'])
    df['X'], df['Y'] = (df['XMin'] + df['XMax']) / 2, (df['YMin'] + df['YMax']) / 2
    df = df.drop(['XMin', 'XMax', 'YMin', 'YMax', 'Helper T cell', 'Cytotoxic T cell', 'Inactive T cell', 'M1 mac', 'M2 mac', 'M1/M2 mac', 'Other mac', 'HLA-DR+ EC', 'CD34+ EC', 'HLA-DR+ CD34+ EC'], axis=1)
    ct2nct = {'α cell': 'Alpha cells', 'δ cell': 'Delta cells', 'β cell': 'Beta cells', 'γ cell': 'Gamma cells', 'ɛ cell': 'Epsilon cells', 'T cell': 'T cells', 'Macrophage': 'Macrophages', 'Other immune cell': 'Other immune cells', 'EC': 'Endothelial cells', 'Pericyte': 'Pericytes'}
    df = df.rename(columns=ct2nct).rename(columns={'Donor': 'Sample', 'Islet': 'Image'})
    def annotate(row):
        for ct in ct2nct.values():
            if row[ct] == 1:
                return ct
        return np.nan
    df['CT'] = df.apply(lambda r: annotate(r), axis=1)
    df = df.dropna(subset=['CT'])
    df = df[cols + ['Arg1 Positive Classification', 'Ki67 Positive Classification']]
    return df


"""
https://leetcode.com/problems/student-attendance-record-ii/
"""

class Solution:
    def checkRecord(self, n: int) -> int:
        """
        Suppose dp[i] is the number of all the rewarded sequences without 'A'
        having their length equals to i, then we have:
            1. Number of sequence ends with 'P': dp[i - 1]
            2. Number of sequence ends with 'L':
                2.1 Number of sequence ends with 'PL': dp[i - 2]
                2.2 Number of sequence ends with 'LL':
                    2.2.1 Number of sequence ends with 'PLL': dp[i - 3]
                    2.2.2 Number of sequence ends with 'LLL': 0 (not allowed)

            So dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3], 3 <= i <= n

        Then all the rewarding sequences with length n are divided into
        two cases as follows:
            1. Number of sequences without 'A': dp[n]
            2. Number of sequence with A in the middle, since we could only
                have at most one A in the sequence to get it rewarded,
                suppose A is at the ith position, then we have:
                    A[i] = dp[i] * dp[n - 1 - i]

                Then the number of such sequences is:
                    sum(A[i] for i in range(n))

        Then our final result will be dp[n] + sum(A[i] for i in range(n)).

        Corner cases:
            1. dp[0] = 1: which means the only case when the sequence is an
                empty string.
            2. dp[1] = 2: 'L', 'P'
            3. dp[2] = 4: 'LL', 'LP', 'PL', 'PP'
        """
        if not n:
            return 0

        if n == 1:
            return 3

        MOD = 10 ** 9 + 7
        dp = [1, 2, 4] + [0] * (n - 2)

        # Calculate sequences without 'A'.
        for i in range(3, n + 1):
            dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3]) % MOD

        # Calculate final result.
        rslt = dp[n] % MOD
        for i in range(n):
            rslt += (dp[i] * dp[n - 1 - i]) % MOD

        return rslt % MOD

print(Solution().checkRecord(2))


from model import Transformer
from torch.utils.data import DataLoader
import torch
import torch.nn as nn
from DataLoader import SensorDataset
import logging
import time # debugging
from plot import *
from helpers import *
from joblib import load
from icecream import ic

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s %(message)s", datefmt="[%Y-%m-%d %H:%M:%S]")
logger = logging.getLogger(__name__)

def inference(path_to_save_predictions, forecast_window, dataloader, device, path_to_save_model, best_model):

    # 将device转换为torch.device类型
    device = torch.device(device)

    # 创建Transformer模型实例，将其转换为double类型，并将其移动到指定的device上
    model = Transformer().double().to(device)

    # 加载预训练模型
    model.load_state_dict(torch.load(path_to_save_model+best_model))

    # 定义损失函数为均方误差
    criterion = torch.nn.MSELoss()

    # 初始化验证集损失为0
    val_loss = 0

    # 关闭梯度计算
    with torch.no_grad():

        # 将模型设置为评估模式
        model.eval()

        # 对于25个plot
        for plot in range(25):

            for index_in, index_tar, _input, target, sensor_number in dataloader:

                # starting from 1 so that src matches with target, but has same length as when training
                # 将输入数据的维度从 (batch_size, seq_len, feature_dim) 转换为 (seq_len, batch_size, feature_dim)
                src = _input.permute(1,0,2).double().to(device)[1:, :, :] # 47, 1, 7: t1 -- t47
                # 将目标数据的维度从 (batch_size, seq_len, feature_dim) 转换为 (seq_len, batch_size, feature_dim)
                target = target.permute(1,0,2).double().to(device) # t48 - t59

                # 将模型下一个输入设置为当前输入数据
                next_input_model = src
                # 初始化所有预测结果为空列表
                all_predictions = []

                for i in range(forecast_window - 1):

                    # 用模型预测下一个时间步的值
                    prediction = model(next_input_model, device) # 47,1,1: t2' - t48'

                    if all_predictions == []:
                        all_predictions = prediction # 47,1,1: t2' - t48'
                    else:
                        # 将预测结果拼接到 all_predictions 中
                        all_predictions = torch.cat((all_predictions, prediction[-1,:,:].unsqueeze(0))) # 47+,1,1: t2' - t48', t49', t50'

                    # 获取当前时间步之后的所有位置编码
                    pos_encoding_old_vals = src[i+1:, :, 1:] # 46, 1, 6, pop 位置编码的第一个值: t2 -- t47
                    # 获取最后一个预测值的位置编码
                    pos_encoding_new_val = target[i + 1, :, 1:].unsqueeze(1) # 1, 1, 6, 添加最后一个预测值的位置编码: t48
                    # 将所有位置编码与预测值匹配
                    pos_encodings = torch.cat((pos_encoding_old_vals, pos_encoding_new_val)) # 47, 1, 6: t2 -- t48 的位置编码

                    # 将当前时间步之后的输入数据和最后一个预测值拼接在一起，作为下一个时间步的输入数据
                    next_input_model = torch.cat((src[i+1:, :, 0].unsqueeze(-1), prediction[-1,:,:].unsqueeze(0))) #t2 -- t47, t48'
                    # 将位置编码拼接在一起，作为下一个时间步的输入数据
                    next_input_model = torch.cat((next_input_model, pos_encodings), dim = 2) # 47, 1, 7 input for next round

                true = torch.cat((src[1:,:,0],target[:-1,:,0]))
                loss = criterion(true, all_predictions[:,:,0])
                val_loss += loss

            val_loss = val_loss/10 # 将验证集的损失除以10，得到平均损失
            scaler = load('scalar_item.joblib') # 加载标量
            # 将输入数据的湿度值转换为原始值
            src_humidity = scaler.inverse_transform(src[:,:,0].cpu())
            # 将目标数据的湿度值转换为原始值
            target_humidity = scaler.inverse_transform(target[:,:,0].cpu())
            # 将所有预测结果的湿度值转换为原始值
            prediction_humidity = scaler.inverse_transform(all_predictions[:,:,0].detach().cpu().numpy())
            # 绘制预测结果图像
            plot_prediction(plot, path_to_save_predictions, src_humidity, target_humidity, prediction_humidity, sensor_number, index_in, index_tar)

        logger.info(f"Loss On Unseen Dataset: {val_loss.item()}")


from header import ATree
import os
import sys

# find the initial state and goal state
def read_input(file_path):
    initial_state = []
    goal_state = []
    fd = open(file_path, 'r')

    # find the initial state
    for i in range(4):
        line = fd.readline().strip('\n').split(' ')
        initial_state.append([])
        for j in line:
            initial_state[i].append(int(j))

    # skip empty line
    fd.readline()

    # find goal state
    for i in range(4):
        line = fd.readline().strip('\n').split(' ')
        goal_state.append([])
        for j in line:
            goal_state[i].append(int(j))

    return initial_state, goal_state

def find_goal_state(init_state, goal_state, output_file):
    atree = ATree(init_state, goal_state)
    atree.search_goal()
    print('Solving...')

    # create a new output file
    if os.path.exists(output_file):
        os.remove(output_file)
    fd = open(output_file, 'a')

    # write initial state
    for i in range(4):
        st = str(init_state[i][0]) + ' ' + str(init_state[i][1]) + ' ' + str(init_state[i][2]) + ' ' + str(
            init_state[i][3]) + '\n'
        fd.write(st)
    fd.write('\n')

    # write goal state
    for i in range(4):
        st = str(goal_state[i][0]) + ' ' + str(goal_state[i][1]) + ' ' + str(goal_state[i][2]) + ' ' + str(
            goal_state[i][3]) + '\n'
        fd.write(st)
    fd.write('\n')

    # write depth
    fd.write(str(atree.depth))
    fd.write('\n')

    # write number of nodes
    fd.write(str(atree.nodes_num))
    fd.write('\n')

    # write actions
    st = ''
    for action in atree.actions_to_goal:
        st += action + ' '
    st += '\n'
    fd.write(st)

    # write costs
    st = ''
    for cost in atree.cost_of_node:
        st += str(cost) + ' '
    fd.write(st)
    print('Finished.')

def main():
    # get input file
    input_file = sys.argv[1]

    # name output file
    output_file = 'Output'+input_file[5]+'.txt'

    initial_stat, goal_state = read_input(input_file)
    find_goal_state(initial_stat, goal_state, output_file)

if __name__ == "__main__":
    main()


from crawler import extract_news
import os

from bson.son import SON
from bson.json_util import dumps, loads
from dotenv import load_dotenv, find_dotenv
from flask import jsonify
from pymongo import MongoClient

load_dotenv(find_dotenv())

connection_string = os.environ.get("MONGODB_CONNECTION_STRING")
client = MongoClient(connection_string)

db = client["dgPadProjectDB"]
collection = db["MayadeenNews"]

"""This function is the one in which we insert our pipeline to aggregate, it's created to avoid redundant repetitive code"""
def aggregationQuery(pipeline):
    cursor = collection.aggregate(
        pipeline,
        allowDiskUse=True
    )

    try:
        cursorList = list(cursor)
        jsonData = dumps(cursorList, indent=2)
        return jsonData
    finally:
        cursor.close()

def countArticlesByMonthPipeline():
    return [
        {
            '$project': {
                'year': {
                    '$toInt': {
                        '$substr': [
                            '$publication_date', 0, 4
                        ]
                    }
                },
                'month': {
                    '$toInt': {
                        '$substr': [
                            '$publication_date', 5, 2
                        ]
                    }
                }
            }
        }, {
            '$group': {
                '_id': {
                    'year': '$year',
                    'month': '$month'
                },
                'count': {
                    '$sum': 1
                }
            }
        }, {
            '$sort': {
                '_id.year': 1,
                '_id.month': 1
            }
        }
    ]

def topKeywordsPipeline(limit: int):
    return [
        {
            '$project': {
                'keyword': {
                    '$split': [
                        '$keywords', ','
                    ]
                }
            }
        }, {
            '$unwind': {
                'path': '$keyword'
            }
        }, {
            '$group': {
                '_id': '$keyword',
                'keywordCount': {
                    '$sum': 1
                }
            }
        }, {
            '$sort': {
                'keywordCount': -1
            }
        }, {
            '$limit': limit
        }
    ]

def articlesWithImagePipeline():
    return [
        {
            '$match': {
                'image': {
                    '$ne': None
                }
            }
        }, {
            '$count': 'count'
        }
    ]

def countArticlesByMonthQuery():
    return aggregationQuery(countArticlesByMonthPipeline())

def topKeywordsQuery():
    return aggregationQuery(topKeywordsPipeline(100))

def articlesWithImageQuery():
    return aggregationQuery(articlesWithImagePipeline())

def countAllDocuments():
    count = collection.count_documents({})
    return jsonify(count)

"""Calls to crawl the news off news website"""
# extract_news('https://www.aljazeera.com/sitemap.xml', 'aljazeera_sitemap.json', 'aljazeera_news.jsonl')
# extract_news('https://www.almayadeen.net/sitemaps/news.xml', 'almayadeen_sitemap.json', 'almayadeen_news.jsonl')


poem = '''There was a young lady named Bright,
Whose speed was far faster than light;
She started ond day
In a relative way,
And returned on the previous night.'''

print(len(poem))

fout = open('relativity', 'wt')
fout.write(poem)
fout.close()

fout = open('relativity', 'wt')
print('[print] ', poem, file=fout, sep='', end='')
fout.close()

fout = open('relativity', 'wt')
size = len(poem)
offset = 0
chunk = 100
while True:
    if offset > size:
        break
    fout.write(poem[offset:offset+chunk])
    offset += chunk
fout.close()

try:
    fout = open('relativity', 'xt')
    fout.write('stomp stomp stomp')
except FileExistsError:
    print('[Exception Error] relativity already exists!. That was a close one.')

# Text File Read : read(), readline(), readlines()
# read() : 인자 없이 호출하면 전체 파일을 읽을 수 있음. but, 메모리 관리에 신경 써야함.

fin = open('relativity', 'rt')
poem = fin.read()
fin.close()
print(len(poem))

# 문자를 다 읽어서 끝에 도달하면, read()는 빈 문자열('')을 반환. if not fragment에서 gragment가 False 가되어 not False는
# True 가 되어 while 문을 탈출함.

poem = ''
fin = open('relativity', 'rt')
chunk = 100
while True:
    fragment = fin.read(chunk)
    if not fragment:
        break
    poem += fragment
fin.close()
print(len(poem))

# readline()
poem = ''
fin = open('relativity', 'rt')
while True:
    line = fin.readline()
    if not line:
        break
    poem += line
fin.close()
print('readline(): ', len(poem))

# text file을 가장 읽기 쉬운 방법은 이터레이터(iterator)를 사용하는 것.
# 이터레이터는 한번에 한 라인씩 반환한다.
poem = ''
fin = open('relativity', 'rt')
for line in fin:
    poem += line
print('iterator file read: ', len(poem))

# readlines()
fin = open('relativity', 'rt')
lines = fin.readlines()
fin.close()
print('readlines(): ', len(lines))
print('lines: ', lines)
print('lines[0]:', lines[0])
for line in lines:
    print(line, end='')


#!/usr/bin/env python3
# -*- coding: utf8 -*-

from YakDB.Graph.BasicAttributes import BasicAttributes
from YakDB.Graph.ExtendedAttributes import ExtendedAttributes
from YakDB.Graph.Node import Node
from YakDB.Graph.Edge import Edge
from YakDB.Exceptions import ParameterException
from YakDB.Graph.Exceptions import ConsistencyException
from YakDB.Graph.Identifier import Identifier
from YakDB.Iterators import KeyValueIterator
from YakDB.Graph.Iterators import NodeIterator

class Graph:
    """
    A directed graph represented
    as adjacency list in multiple tables in a YakDB database.

    """
    def __init__(self,  conn, nodeTableId=2,  edgeTableId=3, extendedAttributesTable=4, partsync=True):
        """
        Create a new graph from a YakDB connection.
        @param partsync Set this to false if you do not need to assume any write
            guarantees subsequent reads to return the written value.
            A False value guarantees better write performance.
        """
        self.conn = conn
        self.nodeTableId = nodeTableId
        self.edgeTableId = edgeTableId
        self.extendedAttributesTable = extendedAttributesTable
        self.partsyncFlag = partsync
    @property
    def partsync(self):
        """
        Whether the graph guarantees reads directly following writes
        always return the written value.
        If this is set to true (default), it has a negative effect
        on write latency and therefore throughput.
        """
        return self.partsyncFlag
    @partsync.setter
    def partsync(self, flag):
        """
        Set or clear the partsync flag.
        """
        if type(flag) is not bool:
            raise ParameterException("flag value must be a bool!")
        self.partsyncFlag = flag
    def createNode(self,  nodeId, basicAttrs=None, save=True):
        """
        Add a node to the graph.
        If a node with the same ID already exists in the graph,
        the already-existing node will be ignored wären auch noch stromsparender.

        (its existing basic attributes will be overwritten),
        but its extended attributes won't be modified

        @param basicAttributes A dictionary of basic attributes or None to use empty set
        @param save Set this to false to avoid writing the node to the database.
        @return the node object.
        """
        node = Node(nodeId, self, basicAttrs)
        if save: node.save()
        return node
    def createEdge(self, sourceNode, targetNode, type="", basicAttrs=None, save=True):
        """
        Create a directed edge between two nodes.

        If you use node IDs instead of nodes as parameters,
        the nodes will not be saved automatically and will not contain
        any basic attributes.
        You can save the nodes

        @param sourceNode A source node identifier or a Node instance that acts as source
        @param targetNode A target node identifier or a Node instance that acts as target
        @param type The type of the edge
        @return The edge instance
        """
        #Check if both nodes are from the same graph.
        if isinstance(sourceNode, Node) and isinstance(targetNode, Node):
            if sourceNode.graph() != targetNode.graph():
                raise ConsistencyException("Source and target node are not from the same graph")
        #If the arguments are strings, ensure they're proper identifiers

        #Ensure we have strings because the edge constructor takes them
        if isinstance(sourceNode, Node):
            sourceNode = sourceNode.id
        if isinstance(targetNode, Node):
            targetNode = targetNode.id
        #Create the edge and save it to the database
        edge = Edge(sourceNode, targetNode, self, type, basicAttrs)
        if save: edge.save()
        return edge
    def deleteNode(self, nodeId,  deleteExtAttrs=True):
        """
        Delete a node.
        If the node does not exist, the request will be ignored.
        @param deleteExtAttrs If this is set to true, all node extended attributes will be deleted as well.
            Otherwise, when creating a node with the same ID, it will automatically inherit the extended attributes left in the database.
        """
        #Delete the node itself
        self._deleteNodeKeys(nodeId)
        #Delete extended attributes
        if deleteExtAttrs:
            deleteExtendedAttributeRange(nodeId)
    @property
    def nodes(self):
        """
        Get a list of all nodes in the graph
        """
        return self.scanNodes()
    def iternodes(self, startKey=None, endKey=None, limit=None, chunkSize=1000, keyFilter=None, valueFilter=None):
        """
        Get a node iterator
        """
        kvIt = KeyValueIterator(self.conn, tableNo=self.nodeTableId, startKey=startKey, endKey=endKey, chunkSize=chunkSize, limit=limit, keyFilter=keyFilter, valueFilter=valueFilter)
        return NodeIterator(self, kvIt)
    def scanNodes(self, startKey=None, endKey=None, limit=None):
        """
        Do a scan over the node table.
        @return A list of Node objects
        """
        nodes = []
        scanResult = self.conn.scan(self.nodeTableId, startKey, endKey, limit)
        for (key, value) in scanResult.iteritems():
            #If the edge and node table are the same, we need to skip edges
            if key.find("\x1F") != -1: #Type separator
                continue
            basicAttrs = BasicAttributes._parseAttributeSet(value)
            node = Node(key, self, basicAttrs)
            nodes.append(node)
        return nodes
    def _scanEdges(self, startKey, endKey, limit=None):
        """
        Do a scan over the edge table.
        Internally used by the Node class.
        @param startKey The edge table start key
        @param endKey The edge table start key
        @return a list of edge objects
        """
        scanResult = self.conn.scan(self.edgeTableId, startKey, endKey, limit)
        edges = []
        for (key, value) in scanResult.iteritems():
            #Deserialize key and value
            edgeTuple = Edge._deserializeEdge(key)
            basicAttrs = BasicAttributes._parseAttributeSet(value)
            edge = Edge(edgeTuple[0], edgeTuple[1], self, edgeTuple[2], basicAttrs)
            edges.append(edge)
        return edges
    def _countEdges(self, startKey, endKey):
        """
        Do a scan over the edge table.
        Internally used by the Node class.
        @param startKey The edge table start key
        @param endKey The edge table start key
        @return a list of edge objects
        """
        return self.conn.count(self.edgeTableId, startKey, endKey)
    def nodeExists(self, nodeId):
        """
        Check if a node (or a list of nodes exists within the database
        @param
        @return A list of bools, in the same order as the argument array, True if the node exists.
        """
        return self.exists(self.nodeTableId, nodeId)
    def saveEdge(self, edge):
        """
        Write an edge to the database.
        @param edge The Edge instance to save
        """
        self.saveEdges([edge])
    def saveEdges(self, edges):
        """
        Save multiple edges at once.
        @param edges The edge list to save
        """
        putDict = {}
        for edge in edges:
            if not isinstance(edge, Edge):
                raise ParameterException("Edge parameter must by an Edge instance!")
            serializedBasicAttrs = edge.basicAttributes.serialize()
            putDict[edge.activeKey] = serializedBasicAttrs
            putDict[edge.passiveKey] = serializedBasicAttrs
        self.conn.put(self.edgeTableId, putDict, partsync=self.partsyncFlag)
    def saveNode(self, node):
        """
        Save a node and its basic attribute set into the database.
        """
        if not isinstance(node, Node):
            raise ParameterException("Node parameter must by a Node instance!")
        self.conn.put(self.nodeTableId,
                      {node.id : node.basicAttributes.serialize()},
                      partsync=self.partsyncFlag)
    def getNode(self, nodeId, loadBasicAttributes=True):
        """
        Read a node from the database (by ID).
        @param nodeId The ID to load
        @param loadBasicAttributes Set this to false if you want to ignore basic attributes.
            If this parameter is set to False, no database operations are involved.
            A common usecase is when you know you don't have
        @return The node instance
        """
        basicAttributes = {}
        if loadBasicAttributes:
            basicAttributes = _readNodeBasicAttributes(self, nodeId)
        return Node(nodeId, self, basicAttributes)
    def readExtendedAttributes(self, entityId, keys):
        """
        Read a list of extended attributes by key set
        @param dbKeys An array of database keys to read, or a single string to read
        @return An array of values, in the same order as the keys.
        """
        if type(keys) is str: keys = [keys]
        dbKeys = [ExtendedAttributes._serializeKey(entityId, key) for key in keys]
        return self.conn.read(self.extendedAttributesTable, dbKeys)
    def scanExtendedAttributes(self, entityId, startAttribute=None, endAttribute=None, limit=None):
        """
        Load a set of extended attributes by scanning the extended attribute range.

        @param limit Set this to a integer to impose a limit on the number of keys. None means no limit.
        @return A dictionary of the extended attributes (key = extended attribute key)
        """
        #Calculate the start and end database keys
        dbStartKey, dbEndKey = ExtendedAttributes._getEntityScanKeys(entityId)
        if startAttribute is not None:
            dbStartKey = ExtendedAttributes._serializeKey(entityId, startAttribute)
        if endAttribute is not None:
            dbEndKey = ExtendedAttributes._serializeKey(entityId, endAttribute)
        #Do the scan
        scanResult = self.conn.scan(self.extendedAttributesTable, dbStartKey,  dbEndKey,  limit)
        #Strip the entity name and separator from the scanned keys
        ret = {}
        for key,value in scanResult.iteritems():
            attrKey = ExtendedAttributes._getAttributeKeyFromDBKey(key)
            ret[attrKey] = value
        return ret
    def deleteExtendedAttributes(self, entityId, keyList):
        """
        Executes a deletion on the extended attribute tables
        @param keyList A list of database keys to delete (single string is also allowed
        """
        if type(keyList) is str: keyList = []
        dbKeys = [ExtendedAttributes._serializeKey(entityId, key) for key in keyList]
        self.conn.delete(self.extendedAttributesTable, keyList, partsync=self.partsyncFlag)
    def deleteExtendedAttributeRange(self, entityId, startAttribute=None, endAttribute=None, limit=None):
        """
        Delete a range of extended attributes.
        @param entityId The entity Id to delete attributes for
        """
        dbStartKey, dbEndKey = ExtendedAttributes._getEntityScanKeys(entityId)
        if startKey is not None:
            dbStartKey = ExtendedAttributes._serializeKey(entityId, startKey)
        if endKey is not None:
            dbEndKey = ExtendedAttributes._serializeKey(entityId, endKey)
        self.conn.deleteRange(self.extendedAttributesTable, dbStartKey,  dbEndKey,  limit)
    def saveExtendedAttributes(self, entityId, attrDict):
        """
        Save one or multiple extended attributes to the database
        @param node The node to serialize for
        @param attrDict A dictionary from key to value
        """
        if type(attrDict) is not dict:
            raise ParameterException("attrDict parameter must be a Dictionary!")
        dbDict = {}
        for key, value in attrDict.iteritems():
            dbKey = ExtendedAttributes._serializeKey(entityId, key)
            dbDict[dbKey] = value
        self.conn.put(self.extendedAttributesTable, dbDict, partsync=self.partsyncFlag)
    def _readNodeBasicAttributes(self, node):
        """
        Load a node entry from the database (by node ID) and return
        the value (= basic attributes)
        """
        return self.conn.read(self.nodeTableId,  node)
    def _deleteEdgeKeys(self, keys):
        """
        Internal function to delete a list of keys in the edge table
        """
        self.conn.delete(self.edgeTableId, keys, partsync=self.partsyncFlag)
    def _deleteNodeKeys(self, keys):
        """
        Internal function to delete a list
        """
        self.conn.delete(self.nodeTableId, keys, partsync=self.partsyncFlag)


from django.shortcuts import render, redirect
import requests

# Create your views here.
from order.models import Order

def index(request):
    """
    IOS에서 해줄 부
    """
    if request.method == 'POST':

        URL = 'https://kapi.kakao.com/v1/payment/ready'
        headers = {
            "Authorization": "KakaoAK " + "f9f70eb192ef14919735fb40a6e599f5",
            "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
        }
        try:
            order_ins = Order.objects.last()
        except Order.DoesNotExist:
            order_ins = None

        if order_ins:
            cart_ins = order_ins.items.last().cart

            params = {
                "cid": "TC0ONETIME",  # 테스트용 코드
                "partner_order_id": f'{order_ins.id}',  # 주문번호
                "partner_user_id": 'admin',  # 유저 아이디
                "item_name": f'admin의 상품 구매',  # 구매 물품 이름
                "quantity": f'{cart_ins.quantity_of_goods}',  # 구매 물품 수량
                "total_amount": f'{order_ins.discount_payment}',  # 구매 물품 가격
                "tax_free_amount": "0",  # 구매 물품 비과세
                "approval_url": f"http://localhost:8000/api/order/{order_ins.id}/approve",
                "cancel_url": "https://developers.kakao.com/fail",
                "fail_url": "https://developers.kakao.com/cancel",
            }

            res = requests.post(URL, headers=headers, params=params)
            request.session['tid'] = res.json()['tid']  # 결제 고유 번호, 20자 결제 승인시 사용할 tid를 세션에 저장
            request.session['partner_order_id'] = order_ins.id
            request.session['partner_user_id'] = 'admin'
            next_url = res.json()['next_redirect_pc_url']  # 카카오톡 결제 페이지 Redirect URL

            request.session.modified = True
        return redirect(next_url)
    return render(request, 'base.html')

def success(request):
    """
    서버에서 할 부분
    """
    # 결제 성공
    URL = 'https://kapi.kakao.com/v1/payment/approve'
    headers = {
        "Authorization": "KakaoAK " + "f9f70eb192ef14919735fb40a6e599f5",
        "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
    }
    params = {
        "cid": "TC0ONETIME",  # 테스트용 코드
        "tid": request.session['tid'],  # 결제 요청시 세션에 저장한 tid
        "partner_order_id": "1",  # 주문번호
        "partner_user_id": "admin",  # 유저 아이디
        "pg_token": request.GET.get("pg_token"),  # 쿼리 스트링으로 받은 pg토큰
    }
    res = requests.post(URL, headers=headers, params=params)
    amount = res.json()['amount']['total']
    res = res.json()
    context = {
        'res': res,
        'amount': amount,
    }
    return render(request, 'success.html')

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


from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
from .models import Search, Result, Item, Dataset
from django_celery_results.models import TaskResult
import json

# function to receive signals when new tasks are created and start tasks to do in celery daemon
@receiver([m2m_changed], sender=Search.datasets.through)
def search_save_handler(sender, instance, action, **kwargs):
    if action == "post_add":
        instance.run()

#function to handle new taskresult related to searchs done on local databases
@receiver([post_save], sender=TaskResult)
def search_dataset_result(sender, instance, **kwargs):
    if "search_in_dataset" not in instance.task_name:
        return
    search = Search.objects.filter(query=instance.task_args[0]).latest("query")
    try:
        result = Result.objects.latest(search=search)
    except:
        result = Result(search=search)
        result.save()
    rows = json.loads(instance.result)
    dataset = Dataset.objects.filter(path=instance.task_args[1]).latest("path")
    for row in rows:
        item = Item(row=row, result=result, dataset=dataset)
        item.save()


import numpy
import matplotlib.pyplot  as plt

x = range(0, 10)
ax = numpy.array(x)
ay1 = ax * ax * ax
ay2 = ax ** 2 + numpy.sin(ax)
plt.plot(ax, ay1, 'ro--',)

plt.show()


full_price = 0
while True:
    try:
        tickets = input('Сколько билетов вы хотите купить?:')
        tickets = int(tickets)
        if type(tickets) == int:
            break
    except ValueError:
        print('Только целое число')
for i in range(tickets):
    i += 1
    while True:
        try:
            age = input(f'Для какого возраста билет №{i}? :')
            age = int(age)
            if age < 18:
                print('Билет бесплатный')
            elif 25 > age >= 18:
                full_price += 990
                print('Стоимость билета: 990 руб.')
            else:
                full_price += 1390
                print('Стоимость билета: 1390 руб.')
            if type(age) == int:
                break
        except ValueError:
            print('Только целое число')
if tickets > 5:
    full_price = full_price - ((full_price / 100) * 20)
    print(f'Сумма к оплате {full_price} руб. с учетом 20%-ой скидки на полную стоимость заказа за регистрацию больше 5-и человек')
else:
    print(f'Сумма к оплате {full_price} руб.')


#!/usr/bin/env python3
from __future__ import print_function

try:
    from ruamel import yaml
except ImportError:
    import yaml

# Map a Docker Compose "service" name to its image.
SERVICES = {
    'client': 'ubuntu:14.04',
    '8u121-jre-alpine': 'openjdk:8u121-jre-alpine',
    '8u121-jre': 'openjdk:8u121-jre',
}

# docker-compose.yml skeleton to fill out using "service" entries above.
COMPOSITION = {'services': {}, 'version': '3'}

def servicize(name, image):
    '''Create a docker-compose.yml service-section entry.

    Params
    ======
    name : str
        Name of the service.
    image : str
        Docker image to use (what your FROM line would contain).

    Returns
    =======
        dict describing the service. A name starting with 'client' is special.
    '''
    entry = {'command': ['/entrypoint.sh'],
             'image': image,
             'volumes': ['./entrypoint.sh:/entrypoint.sh:ro']}
    if not name.startswith('client'):
        entry['ports'] = ['9000', '9443']
        entry['healthcheck'] = {
            'test': 'curl --fail --insecure https://localhost:9443/'}
        entry['volumes'].append('./svc:/svc:ro')
    return entry

if __name__ == '__main__':
    for name, image in SERVICES.items():
        COMPOSITION['services'][name] = servicize(name, image)
    print(yaml.dump(COMPOSITION, default_flow_style=False, indent=4), end='')


#!/usr/bin/python
from flask import Flask
import os
from config import devConfig,prodConfig

app = Flask(__name__)

port = int(os.getenv('PORT', 5500))

import os
if os.environ['ENV'] == 'prod':
    prodConfig()
elif os.environ['ENV'] == 'dev':
    devConfig()

@app.route('/')
def root():
    return "Hello Intel"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port, debug=True)


#!/usr/bin/env python

import os
import pathlib

PIPELINE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
SRC_DIR = os.path.join(PIPELINE_DIR, "src")
UNIT_DIR = os.path.join(PIPELINE_DIR, "unit")

def convert_to_unittest(root, relative_path):
    # put _ut suffix in relative path subdirs
    p = pathlib.Path(os.path.dirname(relative_path))
    subdirs = [f"{d}_ut" for d in p.parts]
    subdirs = os.path.join(*subdirs) if len(subdirs) > 0 else ""

    # put _ut__define in the right place
    basename = os.path.basename(relative_path)
    basename_root, extension = os.path.splitext(basename)
    class_suffix = "__define"
    if basename_root.endswith(class_suffix):
        basename_root = basename_root[0:-len(class_suffix)]
    basename = f"{basename_root}_ut__define{extension}"

    return(os.path.join(os.path.join(root, subdirs), basename))

def find_unit_path(path, src_root, unit_root):
    """Remove prefix or fail.
    """
    if path.startswith(src_root):
        relative_path = path[len(src_root):]
        if relative_path.startswith("/"):
            relative_path = relative_path[1:]
        return(convert_to_unittest(unit_root, relative_path))
    raise FileNotFoundError from None

def main():
    print("#!/bin/sh")
    print()

    for dir, subdirs, files in os.walk(SRC_DIR):
        pro_files = [f for f in files if os.path.splitext(f)[1] == ".pro"]
        for f in files:
            if os.path.splitext(f)[1] != ".pro":
                continue

            src_filename = os.path.join(dir, f)
            unit_filename = find_unit_path(src_filename, SRC_DIR, UNIT_DIR)
            if not os.path.exists(unit_filename):
                unit_dir = os.path.dirname(unit_filename)
                if not os.path.exists(unit_dir):
                    os.makedirs(unit_dir)
                print(f"mgunit_template {src_filename} > {unit_filename}")

if __name__ == "__main__":
    main()


from copy import deepcopy
import sys

def lawler(Grafo):
	n = Grafo.qtd_vertices()
	# cria um array com o indice de todos os vertices do grafo
	vertices = [i for i in range(n)]

	# cria uma lista de todos os subconjuntos dos vertices do grafo, já inserindo o conjunto vazio
	subconjuntos = [[]]
	# preenche a lista com todos os subconjuntos diferentes possiveis
	criar_subconjunto(subconjuntos, [], vertices, n)
	# adiciona o conjunto de vertices em si como ultimo elemento
	subconjuntos.append(vertices)

	# ordena todas as listas, afim de facilitar a busca por elementos mais tarde
	for i in subconjuntos:
		i.sort(reverse=True)

	# cria e inicializa uma lista que conterá o número de cores necessárias para cada subconjunto
	X = [sys.maxsize for i in range(len(subconjuntos))]
	# define que o número de cores necessárias para colorir o conjunto vazio é 0
	X[0] = 0

	# para cada subconjunto de vertices
	for s in range(len(subconjuntos)):

		# cria o conjunto de todos os subconjuntos independentes dos vertices desse subgrafoo
		subconjuntos_independentes = []
		criar_conjunto_independente(Grafo, subconjuntos_independentes, [], subconjuntos[s])

		# para cada subconjunto indepedente criado
		for si in subconjuntos_independentes:
			# armazena em i a diferença entre o subconjunto e um de seus subconjuntos
			i = deepcopy(subconjuntos[s])
			for j in range(len(si)):
				i.remove(si[j])
			# ordena o resultado
			i.sort(reverse=True)

			# procura o indice desse subconjunto na lista de subconjuntos
			index = subconjuntos.index(i)

			# se o numero de cores desse subconjunto for menor que o numero de cores do subconjunto em si, atualiza o
			# numero de cores necessárias para se colorir esse subgrafo
			if X[index] + 1 < X[s]:
				X[s] = X[index] + 1

	# como o numero de cores necessárias para se colorir o grafo original; Esse numero está disponível no último indice do array
	# qualquer coisa só olhar na linha 14
	return X[len(X) - 1]

# cria todos os subconjuntos possíveis, evitando repetições do tipo [1, 2, 3] e [3, 2, 1]
def criar_subconjunto(tds_subconjuntos, subconjunto_atual, vertices, n_vertices):
	# verificação adicionada para impedir que o próprio conjunto de vértices seja criado
	if len(subconjunto_atual) + 1 == n_vertices:
		return

	# array de vertices visitados
	visited = [False for i in range(len(vertices))]

	# para todo vertice no array de vértices passado na entrada
	for v in range(len(vertices)):
		# cria um novo conjunto de vértices vazio
		vertices_ = []
		# marca que o vértice no indice v foi visitado
		visited[v] = True
		# preenche o novo array de vertices com todos os vertices não visitados em iterações anteriores
		for i in range(len(vertices)):
			if visited[i] == False:
				vertices_.append(vertices[i])
		# cria uma cópia do subconjunto atual passado como parametro
		subconjunto_atual_ = deepcopy(subconjunto_atual)
		# adiciona o vertice do indice v nesse novo subconjunto
		subconjunto_atual_.append(vertices[v])
		# adiciona esse novo subconjunto ao conjunto de todos os subconjuntos criados ate entao
		tds_subconjuntos.append(subconjunto_atual_)
		# propaga a criacao de novos subconjuntos usando o subconjunto criado na iteracao atual como base,
		# e os vertices que ainda nao haviam sido visitados
		criar_subconjunto(tds_subconjuntos, subconjunto_atual_, vertices_, n_vertices)

def criar_conjunto_independente(Grafo, tds_subconjuntos, subconjunto_atual, vertices):
	# array de vertices visitados
	visited = [False for i in range(len(vertices))]

	# para todo vertice no array de vértices passado na entrada
	for v in range(len(vertices)):
		# cria um novo conjunto de vértices vazio
		vertices_ = []
		# marca que o vértice no indice v foi visitado
		visited[v] = True
		# preenche o novo array de vertices com todos os vertices não visitados em iterações anteriores
		for i in range(len(vertices)):
			if visited[i] == False:
				vertices_.append(vertices[i])
		# cria uma cópia do subconjunto atual passado como parametro
		subconjunto_atual_ = deepcopy(subconjunto_atual)
		# adiciona o vertice do indice v nesse novo subconjunto caso nao exista nenhuma aresta entre eles e os vertices que
		# ja se encontram no conjunto
		adicionar = True
		for u in subconjunto_atual:
			if Grafo.ha_aresta(vertices[i], u):
				adicionar = False
				break
		if adicionar:
			# caso o requisito seja atendido, adiciona o vertice
			subconjunto_atual_.append(vertices[v])

		# propaga a criacao de novos subconjuntos indepentes usando o subconjunto criado na iteracao atual como base,
		# e os vertices que ainda nao haviam sido visitados
		tds_subconjuntos.append(subconjunto_atual_)
		criar_conjunto_independente(Grafo, tds_subconjuntos, subconjunto_atual_, vertices_)


import re

from sauna.plugins import PluginRegister
from sauna.plugins.base import PsutilPlugin

my_plugin = PluginRegister('Processes')

@my_plugin.plugin()
class Processes(PsutilPlugin):

    @my_plugin.check()
    def count(self, check_config):
        num_pids = len(self.psutil.pids())
        return (
            self._value_to_status_less(num_pids, check_config),
            '{} processes'.format(num_pids)
        )

    @my_plugin.check()
    def zombies(self, check_config):
        zombies = [p for p in self.psutil.process_iter()
                   if p.status() == 'zombie']
        num_zombies = len(zombies)
        return (
            self._value_to_status_less(num_zombies, check_config),
            '{} zombies'.format(num_zombies)
        )

    def _count_running_processes(self, check_config):
        """Count the number of times a process is running.

        Processes are identified by their first argument 'exec' and
        additional 'args'.
        :rtype int
        """
        process_exec = check_config['exec']
        required_args = check_config.get('args', '').split()
        instances = 0

        for process in self.psutil.process_iter():
            try:
                cmdline = process.cmdline()
            except (self.psutil.NoSuchProcess, self.psutil.AccessDenied):
                # Zombies and processes that stopped throw NoSuchProcess
                continue

            # Often cmdline in an empty list
            if not cmdline:
                continue

            if cmdline[0] != process_exec:
                continue

            if self._required_args_are_in_cmdline(required_args, cmdline):
                instances += 1

        return instances

    @my_plugin.check()
    def running(self, check_config):
        process = check_config['exec']
        nb = check_config.get('nb')
        instances = self._count_running_processes(check_config)

        if instances == 0:
            return self.STATUS_CRIT, 'Process {} not running'.format(process)
        if nb is None:
            return self.STATUS_OK, 'Process {} is running'.format(process)
        if instances == nb:
            return self.STATUS_OK, 'Process {} is running'.format(process)
        return (self.STATUS_WARN,
                'Process {} is running {} times'.format(process, instances))

    @my_plugin.check()
    def file_descriptors(self, check_config):
        """Check that processes and system are not running out of fd."""
        check_config = self._strip_percent_sign_from_check_config(check_config)

        # Check fds of individuals processes
        names, worst_value = self._get_processes_exhausting_fds(check_config)
        if names:
            return (
                self._value_to_status_less(worst_value, check_config),
                'Processes running out of fd: {}'.format(', '.join(names))
            )

        # Check fds of whole system
        percent_used_fds = self._get_percent_system_used_fds()
        if (self._value_to_status_less(percent_used_fds, check_config) !=
                self.STATUS_OK):
            return (
                self._value_to_status_less(percent_used_fds, check_config),
                'System using {}% of file descriptors'.format(percent_used_fds)
            )

        return self.STATUS_OK, 'File descriptors under the limits'

    def _get_processes_exhausting_fds(self, check_config):
        processes_names = set()
        highest_percentage = 0
        for process in self.psutil.process_iter():
            try:
                open_fd = process.num_fds()
                limit_fd = self._get_process_fd_limit(process.pid)
                percentage = int(open_fd * 100 / limit_fd)
                if (self._value_to_status_less(percentage, check_config) !=
                        self.STATUS_OK):
                    processes_names.add(process.name())
                if percentage > highest_percentage:
                    highest_percentage = percentage
            except (self.psutil.NoSuchProcess, self.psutil.AccessDenied,
                    OSError):
                pass
        return processes_names, highest_percentage

    @classmethod
    def _get_process_fd_limit(cls, pid):
        """Retrieve the soft limit of usable fds for a process."""
        with open('/proc/{}/limits'.format(pid)) as f:
            limits = f.read()
        match = re.search(r'^Max open files\s+(\d+)\s+\d+\s+files',
                          limits, flags=re.MULTILINE)
        if not match:
            raise Exception('Cannot parse /proc/{}/limits'.format(pid))
        return int(match.group(1))

    @classmethod
    def _get_percent_system_used_fds(cls):
        """Percentage of opened file descriptors over the whole system.

        :rtype int
        """
        with open('/proc/sys/fs/file-nr') as f:
            # Weird behavior on Python 3.2 on Wheezy:
            # f.read() does not return the entire content of this
            # particular file while it should according to the docs.
            # As the file only contains a single line, f.readline()
            # does the job.
            file_nr = f.readline()
        match = re.match(r'^(\d+)\t\d+\t(\d+)$', file_nr)
        if not match:
            raise Exception('Cannot parse /proc/sys/fs/file-nr')
        system_opened_fds = int(match.group(1))
        system_max_fds = int(match.group(2))
        return int(system_opened_fds * 100 / system_max_fds)

    @classmethod
    def _required_args_are_in_cmdline(cls, required_args, cmdline):
        for arg in required_args:
            if arg not in cmdline[1:]:
                return False
        return True

    @staticmethod
    def config_sample():
        return '''
        # Information about processes
        - type: Processes
          checks:
            # Number of processes in the system
            - type: count
              warn: 400
              crit: 500
            # Number of zombies processes in the system
            - type: zombies
              warn: 1
              crit: 5
            # File descriptors
            - type: file_descriptors
              warn: 60%
              crit: 80%
            # Critical if process is not running
            - type: running
              name: docker_running
              exec: /usr/bin/docker
              args: daemon
        '''


import unittest
from healthcareai.supervised_model_trainer import SupervisedModelTrainer
import healthcareai.datasets as hcai_datasets
import sys
from io import StringIO

class TestTrainerDecorator(unittest.TestCase):

    """Tests for the training decorator.

    We will compare a decorated linear regression and a undecorated linear regression output. They should not be
    the same.

    """

    def setUp(self):
        df = hcai_datasets.load_diabetes()

        # Drop columns that won't help machine learning
        columns_to_remove = ['PatientID']
        df.drop(columns_to_remove, axis=1, inplace=True)

        self.regression_trainer = SupervisedModelTrainer(df,
                                                         'SystolicBPNBR',
                                                         'regression',
                                                         grain_column='PatientEncounterID',
                                                         impute=True,
                                                         verbose=False)

        def undecorated_lr(self):
            return self._advanced_trainer.linear_regression(randomized_search=False)

        self.regression_trainer.undecorated_lr = undecorated_lr.__get__(self.regression_trainer,
                                                                        self.regression_trainer.__class__)

    def test_decorator(self):
        out = StringIO()
        sys.stdout = out
        self.regression_trainer.linear_regression()
        decorated_output = out.getvalue().strip()

        out = StringIO()
        sys.stdout = out
        self.regression_trainer.undecorated_lr()
        undecorated_output = out.getvalue().strip()

        assert decorated_output != undecorated_output