"""
Clean up software environments created by `coiled-bisect.py`, aka all environments that start with a given prefix.
"""
import asyncio
import sys
import coiled

ACCOUNT = "dask-engineering"

async def delete_senvs(prefix: str):
    async with coiled.Cloud(asynchronous=True) as client:
        senvs = await client.list_software_environments(ACCOUNT)
        matches = [s for s in senvs if s.split("/")[1].startswith(prefix)]
        input(f"Going to delete {matches}. Press enter to confirm, Ctrl-C to exit: ")

        await asyncio.gather(
            *(
                client.delete_software_environment(senv, account=ACCOUNT)
                for senv in matches
            )
        )

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(
            "Pass the software environment prefix as the only CLI argument, like `python cleanup.py senv-foo`"
        )
        sys.exit(1)

    asyncio.run(delete_senvs(sys.argv[1]))


from os.path import join, getsize, split
from os import remove
from zlib import crc32
from shutil import copyfile
from platformio.util import get_systype

lod_header = bytes("""#$mode=flsh_spi32m
#$sectormap=(16 x 4k, 57 x 64k, 96 x 4k)
#$base=0x08000000
#$spacesize=0x08000000
#$XCV_MODEL=xcv_8955
#$PA_MODEL=pasw_rda6625
#$FLSH_MODEL=flsh_spi32m
#$FLASH_SIZE=0x400000
#$RAM_SIZE=0x00400000
#$RAM_PHY_SIZE=0x00400000
#$RAM_EXTAPP_SIZE=0
#$FLASH_EXTAPP_SIZE=0x40000
#$CALIB_BASE=0x3FA000
#$FACT_SETTINGS_BASE=0x3F4000
#$CODE_BASE=0x00000000
#$USER_DATA_BASE=0x3F6000
#$USER_DATA_SIZE=0x4000
#$BOOT_SECTOR=0x10000
#$PM_MODEL=pmu_8955
#$FM_MODEL=rdafm_8955
""", 'utf8')

def gen_lod_file(target, source, env):
    (target_lod, ) = target
    (source_elf, ) = source

    cmd = ["$OBJCOPY"]
    (source_path, source_name) = split(source_elf.get_abspath())
    tmp_bin = join(source_path, source_name + '.bin')

    cmd.extend(["-O", "binary"])
    cmd.append(source_elf.get_abspath())
    cmd.append(tmp_bin)
    env.Execute(env.VerboseAction(" ".join(cmd), " "))

    # fix bin size to sector boundary (0x10000)
    binsz = getsize(tmp_bin)
    f_binsz = (binsz + 0xFFFF) & ~0xFFFF
    # print("Binary size: %d" % binsz)
    f = open(tmp_bin, "rb")
    f_bin = bytearray(f.read())
    f.close()
    f_bin += bytes(b'\xff' * (f_binsz - binsz))
    # Fix header size
    f_bin[4:8] = f_binsz.to_bytes(4, "little")
    # Fix checksum
    f_bin[8:0xC] = crc32(f_bin).to_bytes(4, "little")
    # write final binary
    f = open(tmp_bin, "wb")
    f.write(f_bin)
    f.close()

    # write final lod file
    f = open(target_lod.get_abspath(), "wb")
    f.write(lod_header)
    address = 0x8250000
    for i in range(int(f_binsz / 4)):
        if address % 0x10000 == 0:
            f.write(bytes('@%08x\n' % address, "utf8"))
        x = i*4
        f.write(bytes('%08x\n' % int.from_bytes(f_bin[x:x+4], 'little'), "utf8"))
        address = address + 4
    f.close()
    remove(tmp_bin)

def gen_fota_file(target, source, env):
    if "darwin" in get_systype():
        print("Fota generate is only available on Windows/Linux.\n")
        return

    FRAMEWORK_DIR = env.PioPlatform().get_package_dir("framework-logicromsdk")
    (target_bin, ) = target
    (source_lod, ) = source
    (source_path, source_name) = split(source_lod.get_abspath())
    tmp_lod = join(source_path, 'tmp_' + source_name)
    empty_lod = join(FRAMEWORK_DIR, 'lib', 'rda8955', 'empty.lod')
    copyfile(empty_lod, tmp_lod)
    f_tmp = open(tmp_lod, "ab")
    with open(source_lod.get_abspath(), "rb") as src:
        src.seek(len(lod_header))
        f_tmp.write(src.read())
        src.close()
    f_tmp.close()
    env.Execute(env.VerboseAction(" ".join([
        '$FOTACREATE',
        '0x24F000',
        empty_lod,
        tmp_lod,
        target_bin.get_abspath()
    ]), " "))
    remove(tmp_lod)


from telebot import TeleBot, types

from config.config import ConfigYamlParser
from state.bot_state import BotState

# для простоты захардкодим путь до конфиг файла
_CONFIG_FILE_NAME = "./config/bot.yaml"
_config = ConfigYamlParser(config_file_name=_CONFIG_FILE_NAME)
_bot_state = BotState()
_bot = TeleBot(_config.get_bot_token())

def _show_start_message(chat_id):
    _bot.send_message(chat_id=chat_id,
                      text="Привет!\nЯ тестовый чат-бот для заказа еды.")

def _show_products_list_message(chat_id):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    for pr_name in _config.get_chat_products():
        markup.add(types.KeyboardButton(pr_name))
    _bot.send_message(chat_id=chat_id,
                      text="У вас есть возможность заказать несколько блюд.",
                      reply_markup=markup)

def _product_selected_reply(message):
    _bot_state.trigger("product_selected", message.text)

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    for pr_size in _config.get_chat_products_sizes():
        markup.add(types.KeyboardButton(pr_size))
    _bot.send_message(chat_id=message.chat.id,
                      text=f"Вы выбрали продукт '{_bot_state.get_product_name().lower()}'.\nКакой размер вы хотите?",
                      reply_markup=markup)

def _product_size_selected_reply(message):
    _bot_state.trigger("size_selected", message.text)

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    for payment_method in _config.get_chat_payment_method():
        markup.add(types.KeyboardButton(payment_method))
    _bot.send_message(chat_id=message.chat.id,
                      text=f"Вы выбрали продукт '{_bot_state.get_product_name().lower()}'"
                           f" размера '{_bot_state.get_product_size().lower()}'.\nКакой метод оплаты?",
                      reply_markup=markup)

def _payment_selected_reply(message):
    _bot_state.trigger("payment_selected", message.text)

    _bot.send_message(chat_id=message.chat.id,
                      text=f"Вы выбрали продукт '{_bot_state.get_product_name().lower()}'"
                           f" размера '{_bot_state.get_product_size().lower()}."
                           f" Оплата {_bot_state.get_payment_method().lower()}.\nСпасибо за заказ")

    _show_products_list_message(message.chat.id)

@_bot.message_handler(commands=['start'])
def _start_message(message):
    chat_id = message.chat.id
    _show_start_message(chat_id)
    _show_products_list_message(chat_id)

@_bot.message_handler(content_types="text")
def _message_reply(message):
    if _bot_state.is_waiting_for_product_name():
        _product_selected_reply(message)
    elif _bot_state.is_waiting_for_product_size():
        _product_size_selected_reply(message)
    elif _bot_state.is_waiting_for_payment_method():
        _payment_selected_reply(message)

def telegram_bot_start():
    _bot.infinity_polling()


import asyncio, discord
from discord.ext import commands
import time

client = commands.Bot(command_prefix='-')
status = False
channel = ''

@client.command()
async def get_channel(ctx):
    global channel
    for channel in client.get_all_channels():
        if 'bump' in channel.name:
            channel = client.get_channel(channel.id)

@client.event
async def bump():
    print(status, channel)
    while status == True:
        await channel.send("!d bump")
        await asyncio.sleep(7200)

@client.event
async def on_ready():
    print('bot online')
    await get_channel('x')
    await bump()

@client.event
async def on_guild_join(guild):
    await helpsheet('x')
    await get_channel('x')
    await bump()

@client.command()
async def bumpbot(ctx):
    global status
    on_off = True if str(ctx.message.content.split(' ')[1]) == 'on' else False
    msg_color = discord.Color.green() if on_off == True else discord.Color.red()
    status = on_off # change bot on/off status

    embed = discord.Embed(title=("BumpBot is now "+str(status)), color = msg_color)
    await channel.send(embed=embed) # send embedded msg to channel
    await bump()

@client.command()
async def helpsheet(ctx):
    embed = discord.Embed(title="__BumpBot Help Sheet__", description="Please refer to this sheet when using the BumpBot :)", color=discord.Color.purple()) #,color=Hex code
    embed.add_field(name="`-helpsheet`", value="Brings up this sheet!")
    embed.add_field(name="`-bumpbot [on/off]`", value="Turn the bot on or off.")
    await channel.send(embed=embed)

client.run('<key>')


class EnsemblingScores:
    def __init__(self):
        self.factors = {'composition_high_1':0.3,'composition':0.3,'places_composition':0.3,'places':0.2,'categories':0.1,'densecap':0.25,'mapi_tags':0.1,'mapi_cats':0.1,'mapi_people':0.2,'mapi':0.05,'txtembed':0.1}
        self.summary_map = {'composition':'composition','places_composition':'composition','places':'context','categories':'context','densecap':'objects','mapi_cats':'context','mapi_tags':'context','mapi_people':'faces','mapi':'faces','txtembed':'context'}
        return

    # json_out in UI format, simple additive ensembling
    def ensembling(self,json_out):
        for k,m in json_out.iteritems(): # iterate matches
            for o in m['output']: # iterate candidates for a given match
                summary = {'scores':{'objects':0.0,'faces':0.0,'composition':0.0,'context':0.0},
                           'processing_time':0.0}
                summary_sum = 0.0
                final_score = 0.0
                comp_score = 0.0 # compositional score
                comp_num = 0.0
                for g,v in o['features']['out'].iteritems(): # iterate generators of a match
                    factor = 1.0
                    for fa,fv in self.factors.iteritems():
                        if fa in g:
                            factor = fv
                            break
                    if g == 'composition_high_1':
                        #comp_num += 1.0
                        #comp_score += 3.0*v['score']#(1.0/comp_num) * factor*v['score']
                        final_score += self.factors[g]*v['score']
                        summary['scores'][self.summary_map['composition']] += 1.0
                    elif 'composition' in g:
                        comp_num += 1.0
                        comp_score += factor*v['score']#(1.0/comp_num) * factor*v['score']
                        summary['scores'][self.summary_map['composition']] += 1.0
                    elif 'categories' in g:
                        summary['scores'][self.summary_map['categories']] += 1.0
                    else:
                        if 'score' in v: # typically, captions have no score at the moment
                            final_score += factor*v['score']
                            summary['scores'][self.summary_map[g]] += 1.0
                        else:
                            summary_sum -= 1.0
                    summary_sum += 1.0
                if comp_num > 0.0:
                    final_score += comp_score / comp_num
                o['features']['score'] = final_score
                for s,sv in summary['scores'].iteritems():
                    sv /= summary_sum
                    summary['scores'][s] = sv
                o['features']['summary'] = summary
        return json_out


#exercice 3
"""
def afficheListe3(liste):
    for k in range(len(liste)-1):
        print(liste[k],end=' ')
    print(liste[len(liste)-1])
    print("\n")
"""

#exercice 4
"""
def moyenne(liste):
    taille=len(liste)
    somme=0
    for k in range(taille):
        somme = somme+tab(taille)
    moy = somme/taille
    return moy
#prgm principal ex 4
liste4=initListeAlea(30)
moy=moyenne(liste4)
print('La moyenne des valeurs du tableau est : ',moy)
"""

#exercice 5
"""
def estPresent1(valeur,liste):
    reponse=False
    for k in range(len(liste)):
        if valeur==liste[k]:
            reponse == True
    return reponse
#programme princpal 5
liste5=initListeAlea(40)
afficheListe3(liste5)
valeur=int(input("Saisir une valeur entre -30 et 20 : "))
present=estPresent1(valeur,liste5)
if present:
    print('Le nombre ',valeur,' est dans le tableau')
else:
    print('Le nombre ',valeur," n'est pas dans le tableau")
"""

#exercice 6
"""
def nombreOccurence(valeur,liste):
    resultat=0
    for k in range(len(liste)):
        if valeur==liste[k]:
            resutalt=resultat+1
    return resultat

liste6=initListeAlea(40)
afficheListe3(liste6)
valeur=int(input("entrez une valeur entre -30 et 20 : "))
nombre = nombreOccurence(valeur,liste6)
print('le nombre ',valeur,' est présent ', nombre,' fois dans la liste')
"""

#exercice 8

def modifListe(liste,val):
    liste[0]=1
    liste[1]=4
    liste[2]=9
    val=100
#programme principal

liste1 = [10,10,10]
valeur=10
print('avant:liste1[0]',liste1[0],'liste1[1]',liste1[1],'liste1[2]',liste1[2])
print('avant:valeur',valeur)
modifListe(liste1,valeur)
print('après:liste1[0]',liste1[0],'liste1[1]',liste1[1],'liste1[2]',liste1[2])
print('après:valeur',valeur)


# coding=utf-8

import sys
sys.path.append('ccentity')
sys.path.append('ccevent')
sys.path.append('ccrequest')
sys.path.append('ccvariable')

import __main__

import time
import random

import ccentity
import ccentity.entity
import ccentity.entity.ttypes
import ccentity.playing
import ccentity.playing.ttypes

import ccevent
import ccevent.ttypes
import ccevent.actor.ttypes
import ccevent.playing.ttypes
import ccevent.role.ttypes

import ccrequest
import ccrequest.ttypes
import ccrequest.playing.ttypes

import ccvariable
import ccvariable.ttypes

import log
import variable_table

import idol_types
import proxy

from thrift import TSerialization

# 增加奖励(玩家ID, 副本模板ID)
def add_award(actor, template):
  log.log_debug("idol.add_award(%d, %d)" % (actor, template))

  request_proxy = variable_table.get_variable(ccvariable.ttypes.Variable.REQUEST_PROXY)

  # 获取副本配置
  playing_config = idol_types.Config.get(template)
  if playing_config == None:
    log.log_error("获取 副本配置失败(%d)" % template)
    return None

  # 请求增加副本奖励
  request = ccrequest.playing.ttypes.RequestPlayingAddAward()
  request.actor_ = actor
  request.playing_template_ = template
  # 奖励
  request.awards_ = playing_config.get_awards()
  # 抽奖
  draw_awards = playing_config.get_draw_awards()
  draw_awards_size = len(draw_awards)
  if draw_awards_size > 0:
    request.draw_award_ = draw_awards[random.randint(0, draw_awards_size - 1)]
  else:
    request.draw_award_ = ccentity.playing.ttypes.PlayingAwardField(\
        ccentity.resource.ttypes.ResourceType.MIN, 0, 0)

  # 序列化
  request_data = TSerialization.serialize(request)
  # 发送请求
  request_proxy.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_ADD_AWARD,\
      request_data, len(request_data))

# 请求领取奖励
def award_actor(actor, template, result):
  proxy.Logging.debug("[idol] award_actor(%d,%d)" % (actor, template))
  if result.awarded_ == True:
    return None
  # 获取副本配置
  playing_config = idol_types.Config.get(template)
  if playing_config == None:
    log.log_error("获取 副本配置失败(%d)" % template)
    return None
  # 抽奖
  draw_awards = playing_config.get_draw_awards()
  if draw_awards == None:
    proxy.Logging.error("[idol] playing_config.get_draw_awards() failed.")
    return None
  # 请求增加副本奖励
  request = ccrequest.playing.ttypes.RequestPlayingAwardActor()
  request.actor_ = actor
  request.playing_template_ = template
  # 固定奖励
  request.awards_ = playing_config.get_awards()
  # 抽奖
  draw_award = None
  playing_id = idol_types.PlayingManager.get_actor_playing(actor)
  if playing_id != 0:
    playing = idol_types.PlayingManager.get(playing_id)
    if playing != None:
      playing_actor = playing.get_actor(actor)
      if playing_actor != None:
        draw_award = playing_actor.get_draw_award_item()
  if draw_award == None:
    draw_items_size = len(draw_awards)
    if draw_items_size > 0:
      request.awards_.append(draw_awards[random.randint(0, draw_items_size - 1)])
  else:
    request.awards_.append(draw_award)
  # 发送请求
  proxy.Request.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_AWARD_ACTOR, request)
  proxy.Logging.debug("[idol] request REQUEST_PLAYING_AWARD_ACTOR")

# 更新记录
def update_record(actor, playing_template, result, record):
  result_value_size = len(result.values_)
  if result_value_size != 1:
    proxy.Logging.error("[idol] update_record(%d,%d) result values size=%d" %\
        (actor, playing_template, result_value_size))
    return None
  # 副本时间
  result_spend_secs = result.values_[0]
  # 副本时间
  record_spend_secs = record.spend_secs_
  # 如果时间不小于当前记录，直接返回
  if record_spend_secs > 0 and result_spend_secs >= record_spend_secs:
    return None
  else:
    # 更新副本记录
    request = ccrequest.playing.ttypes.RequestPlayingUpdateRecord()
    request.actor_ = actor
    request.playing_template_ = playing_template
    request.record_ = ccentity.playing.ttypes.PlayingRecordField(record.period_count_,
      result_spend_secs, record.first_pass_awarded_)
    request.record_.values_ = []
    # 发送请求
    proxy.Request.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_UPDATE_RECORD, request)
    proxy.Logging.debug("[idol] request REQUEST_PLAYING_UPDATE_RECORD")

# 自动完成副本
def auto_finish(actor, playing_template, record, result, finish_count):
  spend_secs = record.spend_secs_
  # 更新记录
  request = ccrequest.playing.ttypes.RequestPlayingUpdateRecord()
  request.actor_ = actor
  request.playing_template_ = playing_template
  request.record_ = record
  request.record_.period_count_ += finish_count
  # 发送请求
  proxy.Request.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_UPDATE_RECORD, request)
  proxy.Logging.debug("[plot] request REQUEST_PLAYING_UPDATE_RECORD")
  # 更新结果
  request = ccrequest.playing.ttypes.RequestPlayingUpdateResult()
  request.actor_ = actor
  request.playing_template_ = playing_template
  request.result_ = ccentity.playing.ttypes.PlayingResultField(\
      False, finish_count, result.paid_award_count_, [])
  request.result_.values_.append(spend_secs)
  # 发送请求
  proxy.Request.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_UPDATE_RESULT, request)
  proxy.Logging.debug("[plot] request REQUEST_PLAYING_UPDATE_RESULT")

def initialize():
  for pos in range(7, 15):
    playing_config = idol_types.PlayingConfig(pos, 60, 10)
    if playing_config.initialize() == False:
      proxy.Logging.error("[idol] init PlayingConfig(%d) failed." % pos)
      return False
    idol_types.Config.add(playing_config)

  # 获取事件交互代理
  communicator_proxy = variable_table.get_variable(ccvariable.ttypes.Variable.COMMUNICATOR_PROXY)

  # 关注增加副本奖励事件
  communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_PLAYING_REQUEST_ADD_AWARD, 1, \
      ccevent.ttypes.ChannelType.CHANNEL_PLAYING, "playing_idol_on_event_playing_request_add_award")

  # 关注副本创建/销毁事件(副本7~14)
  for pos in range(7, 15):
    communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_PLAYING_CREATE, pos, \
        ccevent.ttypes.ChannelType.CHANNEL_PLAYING, "playing_idol_on_event_playing_create")
    communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_PLAYING_DESTORY, pos, \
        ccevent.ttypes.ChannelType.CHANNEL_PLAYING, "playing_idol_on_event_playing_destory")

  proxy.Logging.debug("[idol] initialize")

def finalize():
  communicator_proxy = variable_table.get_variable(ccvariable.ttypes.Variable.COMMUNICATOR_PROXY)

  # 关注副本创建/销毁事件(副本7~14)
  for pos in range(7, 15):
    communicator_proxy.unfollow(ccevent.ttypes.EventType.EVENT_PLAYING_CREATE, pos, \
        ccevent.ttypes.ChannelType.CHANNEL_PLAYING, "playing_idol_on_event_playing_create")
    communicator_proxy.unfollow(ccevent.ttypes.EventType.EVENT_PLAYING_DESTORY, pos, \
        ccevent.ttypes.ChannelType.CHANNEL_PLAYING, "playing_idol_on_event_playing_destory")

  proxy.Logging.debug("[idol] finalize")


import datetime
import logging
from typing import Optional
from collections import defaultdict
from pathlib import Path
from betfairlightweight.resources.bettingresources import MarketBook, MarketCatalogue

from .. import config
from .blotter import Blotter
from ..execution.transaction import Transaction

logger = logging.getLogger(__name__)

class Market:
    """
    Market data structure to hold latest marketBook,
    marketCatalogue and various properties. Also
    allows order placement through the Transaction
    class.
    """

    def __init__(
        self,
        flumine,
        market_id: str,
        market_book: MarketBook,
        market_catalogue: MarketCatalogue = None,
    ):
        self.flumine = flumine
        self.market_id = market_id
        self.closed = False
        self.date_time_created = datetime.datetime.utcnow()
        self.date_time_closed = None
        self.market_book = market_book
        self.market_catalogue = market_catalogue
        self.update_market_catalogue = True
        self.orders_cleared = []
        self.market_cleared = []
        self.context = {"simulated": {}}  # data store (raceCard / scores etc)
        self.blotter = Blotter(market_id)
        self._transaction_id = 0

    def __call__(self, market_book: MarketBook):
        if self.market_book and market_book.version != self.market_book.version:
            self.update_market_catalogue = True
        self.market_book = market_book

    def open_market(self) -> None:
        self.closed = False
        self.orders_cleared = []
        self.market_cleared = []
        logger.info(
            "Market %s opened",
            self.market_id,
            extra=self.info,
        )

    def close_market(self) -> None:
        self.closed = True
        self.date_time_closed = datetime.datetime.utcnow()
        logger.info(
            "Market %s closed",
            self.market_id,
            extra=self.info,
        )

    def transaction(self, async_place_orders: bool = None, client=None) -> Transaction:
        if async_place_orders is None:
            async_place_orders = config.async_place_orders
        if client is None:
            client = self.flumine.clients.get_default()
        self._transaction_id += 1
        return Transaction(
            self,
            id_=self._transaction_id,
            async_place_orders=async_place_orders,
            client=client,
        )

    # order
    def place_order(
        self,
        order,
        market_version: int = None,
        execute: bool = True,
        force: bool = False,
        client=None,
    ) -> bool:
        with self.transaction(client=client) as t:
            return t.place_order(order, market_version, execute, force)

    def cancel_order(
        self, order, size_reduction: float = None, force: bool = False
    ) -> bool:
        with self.transaction(client=order.client) as t:
            return t.cancel_order(order, size_reduction, force)

    def update_order(
        self, order, new_persistence_type: str, force: bool = False
    ) -> bool:
        with self.transaction(client=order.client) as t:
            return t.update_order(order, new_persistence_type, force)

    def replace_order(
        self, order, new_price: float, market_version: int = None, force: bool = False
    ) -> bool:
        with self.transaction(client=order.client) as t:
            return t.replace_order(order, new_price, market_version, force)

    @property
    def event(self) -> dict:
        event = defaultdict(list)
        market_start_datetime = self.market_start_datetime
        event_type_id = self.event_type_id
        for market in self.flumine.markets.events[self.event_id]:
            if (
                market_start_datetime == market.market_start_datetime
                or event_type_id == "1"
            ):
                event[market.market_type].append(market)
        return event

    @property
    def event_type_id(self) -> str:
        if self.market_catalogue:
            return self.market_catalogue.event_type.id
        elif self.market_book:
            return self.market_book.market_definition.event_type_id

    @property
    def event_id(self) -> str:
        if self.market_catalogue:
            return self.market_catalogue.event.id
        elif self.market_book:
            return self.market_book.market_definition.event_id

    @property
    def market_type(self) -> str:
        if self.market_catalogue:
            return self.market_catalogue.description.market_type
        elif self.market_book:
            return self.market_book.market_definition.market_type

    @property
    def seconds_to_start(self) -> float:
        return (self.market_start_datetime - datetime.datetime.utcnow()).total_seconds()

    @property
    def elapsed_seconds_closed(self) -> Optional[float]:
        if self.closed and self.date_time_closed:
            return (datetime.datetime.utcnow() - self.date_time_closed).total_seconds()

    @property
    def market_start_datetime(self):
        if self.market_book:
            return self.market_book.market_definition.market_time
        elif self.market_catalogue:
            return self.market_catalogue.market_start_time
        else:
            return datetime.datetime.utcfromtimestamp(0)

    @property
    def market_start_hour_minute(self) -> Optional[str]:
        msd = self.market_start_datetime
        if msd:
            return "{0:02d}{1:02d}".format(msd.hour, msd.minute)

    @property
    def event_name(self) -> Optional[str]:
        if self.market_catalogue:
            return self.market_catalogue.event.name
        elif self.market_book:
            return self.market_book.market_definition.event_name

    @property
    def country_code(self) -> Optional[str]:
        if self.market_catalogue:
            return self.market_catalogue.event.country_code
        elif self.market_book:
            return self.market_book.market_definition.country_code

    @property
    def venue(self) -> Optional[str]:
        if self.market_catalogue:
            return self.market_catalogue.event.venue
        elif self.market_book:
            return self.market_book.market_definition.venue

    @property
    def race_type(self) -> Optional[str]:
        if self.market_catalogue:
            return self.market_catalogue.description.race_type
        elif self.market_book:
            return self.market_book.market_definition.race_type

    @property
    def status(self) -> Optional[str]:
        if self.market_book:
            return self.market_book.status

    def cleared(self, client) -> dict:
        orders = self.blotter.client_orders(client, matched_only=True)
        profit = round(sum([order.profit for order in orders]), 2)
        return {
            "marketId": self.market_id,
            "eventId": self.event_id,
            "eventTypeId": self.event_type_id,
            "customerStrategyRef": config.customer_strategy_ref,
            "lastMatchedDate": None,
            "placedDate": None,
            "settledDate": None,
            "betCount": len(orders),
            "betOutcome": "WON" if profit >= 0 else "LOST",
            "commission": round(max(profit * client.commission_base, 0), 2),
            "profit": profit,
        }

    @property
    def info(self) -> dict:
        return {
            "market_id": self.market_id,
            "event_id": self.event_id,
            "event_type_id": self.event_type_id,
            "event_name": self.event_name,
            "market_type": self.market_type,
            "market_start_datetime": str(self.market_start_datetime),
            "country_code": self.country_code,
            "venue": self.venue,
            "race_type": self.race_type,
            "orders_cleared": self.orders_cleared,
            "market_cleared": self.market_cleared,
            "closed": self.closed,
        }


# Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

# Note that the same word in the dictionary may be reused multiple times in the segmentation.

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        n = len(s)
        dp = [False for i in range(n + 1)]
        dp[0] = True
        for i in range(1, n + 1):
            for w in wordDict:
                if dp[i - len(w)] and s[i - len(w) : i] == w:
                    dp[i] = True
        return dp[-1]


'''
Author : Aman Attrish
'''

# The main function of the walking algorithm to get all singular points in
# a given fingerprint image.
#
# Based on the paper:
#
# @article{Zhu2016WalkingTS,
#   title={Walking to singular points of fingerprints},
#   author={En Zhu and Xifeng Guo and Jianping Yin},
#   journal={Pattern Recognition},
#   year={2016},
#   volume={56},
#   pages={116-128}
# }
#
# Usage:
#   [sps, time] = walking(im), get singular points of image \im. The open
#   souce code "MATLAB and Octave Functions for Computer Vision and Image
#   Processing" is needed to correctly run this function. Please download
#   "MatlabFns.zip" from
#           http://www.peterkovesi.com/matlabfns/
#   and add all the folders and subfolders to Path.
#
#   [sps, time] = walking(im, mask, orientim), all preprocessing steps like
#   segmentaion and orientation field estimation are implemented outside
#   this function.
#
#   [sps, time] = walking(im, mask, orientim, ...), parameters are passed
#   in. The detailed meanings of parameters are shown below.
#
# @Inputs:
#   im:
#       image data, h by w
#   mask:
#       0, background; 1, foreground
#   orientim:
#       pixel-wise orientation field of \im, share the same size with \im.
#   step:
#       length of one walking step, default to 7 pixel
#   n:
#       number of starting points sampled along x-axis or y, default to 2
#   Td:
#       threshold for stopping the walking process, default to 2 pixel
#   R:
#       radius of the neighborhood of the candidate singular point,
#       default to 16 pixel
# @Outputs:
#   sps:
#       a structure with fields 'core' and 'delta', containing the detected
#       singular points
#   time:
#       processing time of the walking algorithm excluding the segmentation
#       and orientation field estimation.
#
# # Coded by Xifeng Guo. All rights reserved. 2015/4/16 % %
#

'''
For more info please visit https://www.peterkovesi.com/
'''

import numpy as np
import numpy.matlib
from ridge_segment import ridge_segment
from ridge_orient import ridge_orient

def walkonce(im, mask, dfim, start, step, Td):
	sp = []
	current =0
	path = np.array([start])
	while True:
		temp = path[current,:]
		ori = dfim[int(temp[0]), int(temp[1])]
		current = current + 1
		path = np.concatenate([path, temp + step*(np.around([[-np.sin(ori), np.cos(ori)]]))], axis=0)
		if (any(path[current,:] < 1) or any((path[current,:] - im.shape) > 0) or not mask[int(path[current,0]),int(path[current,1])]):
			break
		cpath = path[0:current,:]
		dcpath = cpath - np.matmul(np.ones((cpath.shape[0],1)), np.array([path[current,:]]))
		sqart = np.sqrt(dcpath[:,0]**2 + dcpath[:,1]**2)
		sqart = np.transpose(sqart).reshape((1,-1))
		sqart = np.fliplr(sqart)
		indx = np.argwhere(sqart < Td)
		if min(indx.shape)==0:
			ind = np.empty(shape=(0,0))
		else:
			ind = sqart.shape[1] - indx[0][1]
		if ind.size !=0:
			if current == ind:
				sp = path[current,:]
			elif (current - ind) <=11:
				sp =  np.around(np.sum(path[ind:current+1,:], axis=0)/(current - ind + 1))
			break
	return sp

def checkstable(im, mask, orientim, tempsp, step, Td, R):
	stable=0
	tempsp = np.array([tempsp])

	if min(tempsp.shape) !=0:
		stable=1
		trystart = np.matmul(np.ones((4,1)), tempsp) + np.array([[0,-1], [-1,0], [0,1], [1,0]])*R
		for j in range(0,4):
			if (any(trystart[j,:] < 1) or any((trystart[j,:] - im.shape) > 0) or not mask[int(trystart[j,0]),int(trystart[j,1])]):
				stable=0
				break
			newsp = walkonce(im, mask, orientim, trystart[j,:], step, Td)
			newsp = np.array([newsp])
			if min(newsp.shape) == 0 or np.linalg.norm(tempsp - newsp) > R:
				stable=0
				break
	return stable

def mergeneighbors(points, threshold):

	for i in range(0,points.shape[0]-1):
		if points[i,0] == 0:
			continue
		pointi = points[i,:]
		for j in range(i+1,points.shape[0]):
			if points[j,0] == 0:
				continue
			if (np.linalg.norm(points[i,:] - points[j,:]) < threshold):
				pointi = np.concatenate([pointi, points[j,:]], axis=0)
				points[j,:] = [0, 0]
		if len(pointi)>=2:
			pointi = pointi.reshape((-1,2))
		s = np.sum(pointi, axis=0)
		points[i,:] = np.around(np.array([[s[0], s[1]]])/pointi.shape[0])
	points = points[~np.all(points==0, axis=1)]
	return points

def walking(img):

	#initializing the dictionary
	sps = {}
	sps['core'] = []
	sps['delta'] = []

	step = 7
	n = 2
	Td = 2
	R = 16

	blksze = 16;
	thresh = 0.3;
	normim, mask = ridge_segment(img,blksze,thresh);
	mask[(mask.shape[0]//blksze)*blksze+1:mask.shape[0],:] = 0
	mask[:,(mask.shape[1]//blksze)*blksze+1:mask.shape[1]] = 0

	orientim = ridge_orient(normim, 1, 3, 3)
	orientim = np.pi - orientim

	#sampling starting point

	I,J = np.where(mask==1)
	edge0 = np.array([min(I),min(J)])
	edge1 = np.array([max(I),max(J)])
	d = (edge1-edge0)//(n+1)
	sampled_rows = np.array(range(edge0[0]+d[0], edge0[0] + d[0]*n + 1,d[0]))    #If some error comes, consider +1 also
	sampled_cols = np.array(range(edge0[1]+d[1], edge0[1] + d[1]*n + 1,d[1]))
	sampled_points = np.transpose([[np.kron(sampled_rows, np.ones((1,n)))],[np.matlib.repmat(sampled_cols, 1, n)]])
	sampled_points = np.reshape(sampled_points,(4,2))

	#Detect Cores
	for r in range(0,4):
		if len(sps['core']) != 0:
			break
		WDFc1 = 2.0*orientim + (r+1)*np.pi/2
		core1 = np.array([[]])
		core2 = np.array([[]])
		for i in range(0,sampled_points.shape[0]):
			p = sampled_points[i,:]
			if (not mask[int(p[0]),int(p[1])]):
				continue
			if min(core1.shape) == 0:
				tempsp = walkonce(img, mask, WDFc1, p, step, Td)
				if checkstable(img, mask, WDFc1, tempsp, step, Td, R):
					core1 = tempsp
			if min(core2.shape) == 0:
				tempsp = walkonce(img, mask, WDFc1-np.pi, p, step, Td)
				if checkstable(img, mask, WDFc1-np.pi, tempsp, step, Td, R):
					core2 = tempsp
		if min(core1.shape)==0:
			sps['core'] = np.array([core2])
		elif min(core2.shape)==0:
			sps['core'] = np.array([core1])
		else:
			sps['core'] = np.concatenate([core1,core2], axis=0)

	#Detect Deltas
	for r in range(0,4):
		if len(sps['delta']) != 0:
			break
		WDFd = -2.0*orientim + (r+1)*np.pi/2
		for i in range(0,sampled_points.shape[0]):
			p = sampled_points[i,:]
			if (not mask[int(p[0]),int(p[1])]):
				continue
			tempsp = walkonce(img, mask, WDFd, p, step, Td)
			if checkstable(img, mask, WDFd, tempsp, step, Td, R):
				sps['delta'] = np.concatenate([sps['delta'],tempsp], axis=0)
		if len(sps['delta']) >=2:
			sps['delta'] = sps['delta'].reshape((-1,2))

	sps['core'] = np.array([sps['core']])
	sps['delta'] = np.array([sps['delta']])

	sps['core'] = sps['core'].reshape((-1,2))
	sps['delta'] = sps['delta'].reshape((-1,2))

	sps['core'] = np.fliplr(mergeneighbors(sps['core'],20))
	sps['delta'] = np.fliplr(mergeneighbors(sps['delta'],20))
	return sps


"""Module for manipulating data."""

import math
import random

import numpy as np
import scipy.interpolate

from sklearn.utils import check_random_state

# TODO numpy doc

def one_hot(array, n_classes=None):
    """Return one of k vectors for an array of class indices.

    :param array: 1D array containing N integers from 0 to k-1.
    :param classes: Amount of classes, k. If None, this will be inferred
        from array (and might take longer).
    :returns: A 2D array of shape (N, k).
    """
    if n_classes is None:
        n_classes = len(set(array.tolist()))
    n = array.shape[0]
    arr = np.zeros((n, n_classes), dtype=np.float32)
    arr[xrange(n), array] = 1.
    return arr

def shuffle(data):
    """Shuffle the first dimension of an indexable object in place."""
    for i in range(len(data) - 2):
        swappartner = random.randint(i + 1, len(data) - 1)
        a, b = data[swappartner][:], data[i][:]
        data[i][:], data[swappartner][:] = b, a

def shuffle_many(arrays, axes, random_state=None):
    rng = check_random_state(random_state)

    # We need to swap the axes of the arrays so that the axes along to shuffle
    # is the first for each. We don't need to swap back, since these will be
    # views.
    arrays = [i.swapaxes(0, j) for i, j in zip(arrays, axes)]

    assert all(i.shape[0] == arrays[0].shape[0] for i in arrays[1:])

    permutation = rng.permutation(arrays[0].shape[0])

    for old_index, new_index in enumerate(permutation):
        for a in arrays:
            a[old_index], a[new_index] = a[new_index], a[old_index]

def padzeros(lst, front=True, return_mask=False):
    # TODO add docs for ``front``
    """Given a list of arrays, pad every array with up front  zeros until they
    reach unit length.

    Each element of `lst` can have a different first dimension, but has to be
    equal on the other dimensions.
    """
    n_items = len(lst)
    # Get the longest item.
    maxlength = max(len(i) for i in lst)
    restshape = list(lst[0].shape)[1:]
    item_shape = [maxlength] + restshape
    total_shape = [n_items] + item_shape

    data = scipy.zeros(total_shape, dtype=lst[0].dtype)
    if return_mask:
        mask = scipy.zeros(total_shape, dtype=lst[0].dtype)
    for i in range(n_items):
        # Iterate over indices because we work in place of the list.
        thislength = lst[i].shape[0]
        if front:
            data[i][-thislength:] = lst[i]
            if return_mask:
                mask[i][-thislength:] = 1
        else:
            data[i][:thislength] = lst[i]
            if return_mask:
                mask[i][:thislength] = 1

    if return_mask:
        return data, scipy.asarray(mask)
    return data

def collapse_seq_borders(arr):
    """Given an array of ndim 3, return a view of ndim 2 where the first
    dimension is flattened out."""
    if not arr.ndim == 3:
        raise ValueError("only for arrays of ndim 3")
    arr2 = arr[:]
    arr2.shape = arr.shape[0] * arr.shape[1], arr.shape[2]
    return arr2

def uncollapse_seq_borders(arr, shape):
    """Return a view of ndim 3, given an array of ndim 2, where the first
    dimension is expanded to 2 dimensions of the given shape."""
    if not arr.ndim == 2:
        raise ValueError("only for arrays of ndim 2")
    arr2 = arr[:]
    arr2.shape = shape[0], shape[1], arr.shape[1]
    return arr2

def skip(X, n, d=1):
    """Return an array X with the same number of rows, but only each `n`'th
    block of `d` consecutive columns is kept.

    Crude way of reducing the dimensionality of time series."""
    X_ = X.reshape((X.shape[0], X.shape[1] / d, d))
    X_ = X_[:, ::n, :]
    return X_.reshape((X.shape[0], X_.size / X.shape[0]))

def interleave(lst):
    """Given a list of arrays, interleave the arrays in a way that the
    first dimension represents the first dimension of every array.

    This is useful for time series, where multiple time series should be
    processed in a single swipe."""
    arr = scipy.asarray(lst)
    return scipy.swapaxes(arr, 0, 1)

def uninterleave(lst):
    """Given an array of interleaved arrays, return an uninterleaved version of
    it."""
    arr = scipy.asarray(lst)
    return scipy.swapaxes(arr, 0, 1)

def interpolate(X, n_intermediates, kind='linear'):
    """Given an array of shape (j, k), return an array of size
    (j * n_intermediates, k) where each i * n_intermediated element refers to
    the i'th element in X while all the others are linearly interpolated."""
    X_ = scipy.empty((X.shape[0] * n_intermediates, X.shape[1]))
    grid = scipy.mgrid[0:X.shape[0]]

    finegrid = scipy.linspace(0, X.shape[0] - 1, X.shape[0] * n_intermediates)
    for i in range(X.shape[1]):
        f = scipy.interpolate.interp1d(grid, X[:, i], kind=kind)
        X_[:, i] = f(finegrid)
    return X_

def n_windows(X, size, offset):
    """Given an array `X` representing a sequence along its first axis, return
    the number of windows of `size` with `offset` that fit into it."""
    return max(int(math.ceil((X.shape[0] - size + 1.) / offset)), 0)

def windowify(X, size, offset=1):
    """Return a static array that represents a sliding window dataset of size
    `size` given by the list of arrays `."""
    windows = []
    for i, window in enumerate(iter_windows(X, size, offset)):
        windows.append(window[np.newaxis])

    return np.concatenate(windows)

def iter_windows(X, size, offset=1):
    """Return an iterator that goes over a sequential dataset with a sliding
    time window.

    `X` is expected to be a list of arrays, where each array represents a
    sequence along its first axis."""
    for seq in X:
        for j in [k * offset for k in range(n_windows(seq, size, offset))]:
            yield seq[j:j + size]

def split(X, maxlength):
    """Return a list of sequences where each sequence has a length of at most
    `maxlength`.

    Given a list of sequences `X`, the sequences are split accordingly."""
    new_X = []
    for seq in X:
        n_new_seqs, rest = divmod(seq.shape[0], maxlength)
        if rest:
            n_new_seqs += 1
        for i in range(n_new_seqs):
            new_X.append(seq[i * maxlength:(i + 1) * maxlength])
    return new_X

def collapse(X, n):
    """Return a list of sequences, where `n` consecutive timesteps have been
    collapsed into a single timestep by concatenation for each sequence.

    Timesteps are cut off to ensure divisibility by `n`."""
    dim = X[0].shape[1]
    new_X = []
    for seq in X:
        seq = scipy.ascontiguousarray(seq)
        length = seq.shape[0]
        keep = length / n * n
        seq = seq[:keep]
        seq.shape = length / n, dim * n
        new_X.append(seq)

    return new_X

def uncollapse(X, n):
    """Return a list of sequences, where each timestep is divided into `n`
    consecutive timesteps."""
    new_X = []
    dim = X[0].shape[1]
    for seq in X:
        length = seq.shape[0]
        new_X.append(seq.reshape((length * n, dim / n)))
    return new_X

def consecutify(seqs):
    """Given sequences of equal second dimension, put them into a consecutive
    memory block M and return it. Also return a list of views to that block that
    represent the given sequences."""
    n_rows = sum(i.shape[0] for i in seqs)
    n = seqs[0].shape[1]
    block = scipy.empty((n_rows, n))
    new_seqs = []
    start = 0
    for seq in seqs:
        stop = start + seq.shape[0]
        block[start:stop] = seq
        new_seqs.append(block[start:stop])
        start = stop
    return block, new_seqs

def sample(arr, n, axis=0, with_replacement=False):
    indices = range(arr.shape[axis])
    all_slice = slice(0, arr.shape[axis])
    sampled_indices = random.sample(indices, n)
    slices = tuple(all_slice if i != axis else sampled_indices
                   for i in range(arr.ndim))
    return arr[slices]


def toRoman(numb:int):
    symbol=["I","IV","V","IX","X","XL","L","XC","C"]
    val=[1,4,5,9,10,40,50,90,100]
    roman=""
    i=8
    while numb!=0:
        if numb>=val[i]:
            roman+=symbol[i]
            numb-=val[i]
        else: i-=1
    return roman

# page=[]
symbol=["I","V","X","L","C"]
nub=[0,0,0,0,0]
N=int(input())
for i in range(1,N+1):
    ans=toRoman(i)
    # page.append(ans)
    for ele in ans:
        for j in range(5):
            if ele==symbol[j]:
                nub[j]+=1
# print(page)
for e in nub:print(e,end=" ")


"""https://www.hackerrank.com/challenges/piling-up/problem."""
from collections import deque

def validation():
    """https://www.hackerrank.com/challenges/piling-up/problem."""
    result = []
    no_testcases = int(input())
    for _ in range(no_testcases):
        dq = deque()
        n = int(input())
        dq.extend(list(map(int, input().split())))
        length_dq = len(dq)
        while length_dq > 1:
            max_dq = max(dq[0], dq[1], dq[-2], dq[-1])
            if dq[0] == max_dq:
                dq.popleft()
                length_dq -= 1
            elif dq[-1] == max_dq:
                dq.pop()
                length_dq -= 1
            else:
                break

        if length_dq == 1:
            result.append('Yes')
        else:
            result.append('No')

    for i in result:
            print(i)

if __name__ == '__main__':
    validation()


# -*- coding: utf-8 -*-
"""
Задание 19.3a

Создать функцию send_command_to_devices, которая отправляет
список указанных команды show на разные устройства в параллельных потоках,
а затем записывает вывод команд в файл. Вывод с устройств в файле может быть в любом порядке.

Параметры функции:
* devices - список словарей с параметрами подключения к устройствам
* commands_dict - словарь в котором указано на какое устройство отправлять какие команды. Пример словаря - commands
* filename - имя файла, в который будут записаны выводы всех команд
* limit - максимальное количество параллельных потоков (по умолчанию 3)

Функция ничего не возвращает.

Вывод команд должен быть записан в файл в таком формате (перед выводом каждой команды надо написать имя хоста и саму команду):

R2#sh arp
Protocol  Address          Age (min)  Hardware Addr   Type   Interface
Internet  192.168.100.1          87   aabb.cc00.6500  ARPA   Ethernet0/0
Internet  192.168.100.2           -   aabb.cc00.6600  ARPA   Ethernet0/0
R1#sh ip int br
Interface                  IP-Address      OK? Method Status                Protocol
Ethernet0/0                192.168.100.1   YES NVRAM  up                    up
Ethernet0/1                192.168.200.1   YES NVRAM  up                    up
R1#sh arp
Protocol  Address          Age (min)  Hardware Addr   Type   Interface
Internet  10.30.0.1               -   aabb.cc00.6530  ARPA   Ethernet0/3.300
Internet  10.100.0.1              -   aabb.cc00.6530  ARPA   Ethernet0/3.100
R3#sh ip int br
Interface                  IP-Address      OK? Method Status                Protocol
Ethernet0/0                192.168.100.3   YES NVRAM  up                    up
Ethernet0/1                unassigned      YES NVRAM  administratively down down
R3#sh ip route | ex -

Gateway of last resort is not set

      10.0.0.0/8 is variably subnetted, 4 subnets, 2 masks
O        10.1.1.1/32 [110/11] via 192.168.100.1, 07:12:03, Ethernet0/0
O        10.30.0.0/24 [110/20] via 192.168.100.1, 07:12:03, Ethernet0/0

Порядок команд в файле может быть любым.

Для выполнения задания можно создавать любые дополнительные функции, а также использовать функции созданные в предыдущих заданиях.

Проверить работу функции на устройствах из файла devices.yaml и словаре commands
"""

# Этот словарь нужен только для проверки работа кода, в нем можно менять IP-адреса
# тест берет адреса из файла devices.yaml

commands = {
    "192.168.100.3": ["sh ip int br", "sh ip route | ex -"],
    "ios-xe-mgmt.cisco.com": ["sh int desc", "sh ip int br"],
    "192.168.100.2": ["sh int desc"]
}

from datetime import datetime
import time
from itertools import repeat
from concurrent.futures import ThreadPoolExecutor
import logging
from pprint import pprint

import netmiko
import yaml

logging.getLogger('paramiko').setLevel(logging.WARNING)

logging.basicConfig(
    format = '%(threadName)s %(name)s %(levelname)s: %(message)s',
    level=logging.INFO)

def send_show_command_to_devices(device, command):
	final = []
	start_msg = '===> {} Connection: {}'
	received_msg = '<=== {} Received:   {}'
	ip = device['host']
	if commands.get(device['host']):
		command = commands[device['host']]
	logging.info(start_msg.format(datetime.now().time(), ip))

	with netmiko.ConnectHandler(**device) as ssh:
		ssh.enable()
		output1 = ssh.send_command(strip_command=False, command_string=command[0])
		final.append(device['host']+'#'+output1+'\n')
		output2 = ssh.send_command(strip_command=False, command_string=command[1])
		final.append(device['host']+'#'+output2+'\n')
		logging.info(received_msg.format(datetime.now().time(), ip))
	return final

with open('devices2.yaml') as f:
	devices = yaml.safe_load(f)

with ThreadPoolExecutor(max_workers=3) as executor:
	result = executor.map(send_show_command_to_devices, devices, commands)
	for output in result:
		pprint(output)
		f = open('show.txt', 'a')
		for line in output:
			f.write(line)
'''
ios-xe-mgmt.cisco.com#sh int desc
Interface                      Status         Protocol Description
Gi1                            up             up       MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2                            admin down     down     Network Interface
Gi3                            admin down     down     Network Interface
Lo15                           up             up       Added By KaussezPausies
Lo100                          up             up       Added By KaussezPausies
ios-xe-mgmt.cisco.com#sh ip int br
Interface              IP-Address      OK? Method Status                Protocol
GigabitEthernet1       10.10.20.48     YES NVRAM  up                    up
GigabitEthernet2       unassigned      YES NVRAM  administratively down down
GigabitEthernet3       unassigned      YES NVRAM  administratively down down
Loopback15             unassigned      YES unset  up                    up
Loopback100            172.16.55.1     YES other  up                    up
'''


#!/usr/bin/env python3
import sys
import os
import re
import subprocess

def get_paths():
    """Get the data to make the path for the elements of the page."""
    try:
        # Get the name introduce by the terminal.
        name = sys.argv[1]
        path = name
        # If the there is a argument for the path of the directory then we will use it.
        if sys.argv[2]:
            path = '{}/{}_page'.format(sys.argv[2], name)
        # Print the name of the page and the name that will have the directory of the page.
        print("Nombre: {name}, Path: {path}".format(name=name, path=path))
        # If the directory does not exist create one.
        if not os.path.exists(path):
            subprocess.run(['mkdir', path])
        # Return the name of the page and the name of the directory
        return name, path
    except IndexError as e:
        # When a error happend finish the program, with the error message on the screen."
        print("Error: {}".format(e))
        sys.exit(1)

def renaming(name:str, version:int = 1):
    """This function is to rewrite the name with the form that it has to be, example: 'list_detail' => 'ListDetail'"""
    if version == 1:
        names:list[str] = name.split("_")
        result = ''
        for element in names:
            result = '{}{}'.format(result, element.capitalize())
    elif version == 2:
        names:list[str] = name.split("_")
        result = ''
        for element in names:
            if element == names[0]:
                result = '{}{}'.format(result, element)
            else:
                result = '{}{}'.format(result, element.capitalize())
    return result

def create(name: str, path: str, path_placeholder: str, tipo: str):
    """Function to create the file of the page path passed at the arguments."""
    # Pattern to change the names of the classes.
    pattern = r"Placeholder"
    # Pattern to change the names of the imports.
    pattern2 = r"placeholder_"
    # Pattern to change the names of the builders
    pattern3 = r"builder\: \(Placeholder"
    # The path to create the file.
    full_path = "{path}/{name}_{type}.dart".format(path=path, name=name, type=tipo)
    # Check if the file already exists, if the file exists the function does not make any changes
    # to the file.
    if not os.path.exists(full_path):
        # Lines updated of the file.
        rows = []
        # Open the file that make the placeholder.
        with open(path_placeholder, 'r') as placeholder:
            # Read line by line of the file and make the changes.
            for line in placeholder:
                # If the pattern2 exists make the change of the name (imports).
                if re.search(pattern2, line):
                    rows.append(re.sub(pattern2, '{}_'.format(name.lower()), line))
                # If the patter3 of the builders is in the line then the program will change that for the text.
                elif re.search(pattern3, line):
                    rows.append(re.sub(pattern3, 'builder: ({}'.format(renaming(name, 2)), line))
                else:
                    # Changes and rename the names (Classes).
                    rows.append(re.sub(pattern, renaming(name), line))
            # Close the file.
            placeholder.close()
        # Open the file in the path.
        with open(full_path, 'w') as file:
            # Write the lines in the file.
            file.writelines(rows)
            # Close the file.
            file.close()

def main():
    """Automation of the creation of one page in flutter using the State Managment with 'GET'"""
    # The paths of the placeholders.
    placeholder_controller = "/Users/macbook/Documents/Harry/commands/placeholders/lib/src/placeholder_controller.dart"
    placeholder_binding = "/Users/macbook/Documents/Harry/commands/placeholders/lib/src/placeholder_binding.dart"
    placeholder_page = '/Users/macbook/Documents/Harry/commands/placeholders/lib/src/placeholder_page.dart'
    # Get the name and the path of the directory.
    name, path = get_paths()
    # Create the controller for the page.
    create(name=name, path=path, tipo='controller', path_placeholder=placeholder_controller)
    # Create the binding for the page.
    create(name=name, path=path, tipo='binding', path_placeholder=placeholder_binding)
    # Create the visual part of the page.
    create(name=name, path=path, tipo='page', path_placeholder=placeholder_page)
    # Exit the program.
    sys.exit(0)

# Init the progra.
if __name__ == '__main__':
    main()


def check_technology_eligibility(xlsx_dict,technology_dict):

    technology_types = list(xlsx_dict["library_preparation_protocol"]["library_preparation_protocol.library_construction_method.ontology_label"].values)
    assert all(t in technology_dict.keys() for t in technology_types),"1 or more technology types are not eligible." \
                                                               " Please remove ineligible technologies and their linked" \
                                                               " samples and try again."

    assert len(technology_types) == 1,"Only 1 technology type is allowed per SCEA E-HCAD id. " \
                                      "Please split the dataset by the technology type and run them separately."

def check_species_eligibility(xlsx_dict):

    biomaterial_tab = ["donor_organism","specimen_from_organism","cell_line","organoid","cell_suspension"]

    species_list = []
    for biomaterial in biomaterial_tab:
        if biomaterial in xlsx_dict.keys():
            species_key = "%s.genus_species.ontology_label" % (biomaterial)
            species_list.extend(list(xlsx_dict[biomaterial][species_key].values))
    species_list = list(set(species_list))
    species_list = [x for x in species_list if str(x) != 'nan']

    assert all("||" not in s for s in species_list),"The dataset contains biomaterials linked to >1 species (pooled). To be eligible for SCEA each biomaterial must be" \
                                                    " linked to 1 species only (Human or Mouse). Please remove the relevant biomaterials from the dataset" \
                                                    " and run again."

    assert all(s in ["Homo sapiens","Mus musculus"] for s in species_list),"1 or more species are not eligible. Species must be" \
                                                                           " either Homo sapiens or Mus musculus."

    assert len(species_list) == 1,"Only 1 species is allowed per SCEA E-HCAD id. " \
                                      "Please split the dataset by species and run them separately."

def check_for_pooled_samples(xlsx_dict):

    biomaterial_tab = ["donor_organism","specimen_from_organism","cell_line","organoid","cell_suspension","sequence_file"]

    input_biomaterial_list = []
    for biomaterial in biomaterial_tab:
        if biomaterial in xlsx_dict.keys():
            for key in biomaterial_tab:
                input_biomaterial_key = "%s.biomaterial_core.biomaterial_id" % (key)
                if input_biomaterial_key in xlsx_dict[biomaterial].keys():
                    input_biomaterial_list.extend(list(xlsx_dict[biomaterial][input_biomaterial_key].values))

    input_biomaterial_list = list(set(input_biomaterial_list))
    input_biomaterial_list = [x for x in input_biomaterial_list if str(x) != 'nan']

    assert all("||" not in i for i in input_biomaterial_list),"The dataset contains pooled biomaterials. Pooled biomaterials are not eligible." \
                                                              " Please remove the relevant biomaterials from the dataset" \
                                                              " and run again."

def check_donor_exists(xlsx_dict):

    assert 'donor_organism' in xlsx_dict.keys(),"The dataset does not include donor organism biomaterials." \
                                                        " Cell lines, organoids and cell suspensions must be derived from a specimen linked" \
                                                        " to a donor." \
                                                        ""

    assert len(list(xlsx_dict['donor_organism']['donor_organism.biomaterial_core.biomaterial_id'])) >= 1,"The dataset does not include donor_organism biomaterials." \
                                                        " Cell lines, organoids and cell suspensions must be derived from a specimen linked" \
                                                        " to a donor." \
                                                        ""

def check_specimen_exists(xlsx_dict):

    assert 'specimen_from_organism' in xlsx_dict.keys(),"The dataset does not include specimen_from_organism biomaterials." \
                                                        " Cell lines, organoids and cell suspensions must be derived from a specimen linked" \
                                                        " to a donor." \
                                                        ""

    assert len(list(xlsx_dict['specimen_from_organism']['specimen_from_organism.biomaterial_core.biomaterial_id'])) >= 1,"The dataset does not include specimen_from_organism biomaterials." \
                                                        " Cell lines, organoids and cell suspensions must be derived from a specimen linked" \
                                                        " to a donor." \
                                                        ""

def check_input_to_cell_suspension(xlsx_dict):

    biomaterials = ["specimen_from_organism","cell_line","organoid"]
    input_types = []
    for biomaterial in biomaterials:
        key = "%s.biomaterial_core.biomaterial_id" % biomaterial
        if key in xlsx_dict["cell_suspension"].columns:
            cell_suspension_ids = list(xlsx_dict["cell_suspension"][key])
            cell_suspension_ids = [x for x in cell_suspension_ids if str(x) != 'nan']
            if len(cell_suspension_ids) >= 1:
                input_types.append(biomaterial)
    input_types = list(set(input_types))
    assert len(input_types) == 1,"All inputs to cell suspensions should be of an identical biomaterial type. For example cell suspensions should all be linked to cell lines only organoids only or specimens only. Please split the dataset by the input biomaterial type."

def check_cell_lines_linked(xlsx_dict):

    cell_line_key = "cell_line.biomaterial_core.biomaterial_id"
    specimen_key = "specimen_from_organism.biomaterial_core.biomaterial_id"

    assert specimen_key in xlsx_dict["cell_line"].columns,"Cell_lines are not linked to" \
                                                 " a specimen id. Please link all cell_lines to an input specimen."

    # Check that cell lines are not linked to an input cell line
    for column in xlsx_dict["cell_line"].columns:
        if "cell_line.biomaterial_core.biomaterial_id." in column:
            cell_line_as_input = [x for x in list(xlsx_dict["cell_line"][column]) if str(x) != 'nan']
            assert len(cell_line_as_input) == 0,"Cell line input biomaterial type should be specimen id. Cell line cannot be used" \
                                                " as input to a cell line."

    input_specimen_ids = [x for x in list(xlsx_dict["cell_line"][specimen_key]) if str(x) != 'nan']
    cell_line_ids = list(xlsx_dict["cell_line"][cell_line_key])
    assert len(input_specimen_ids) == len(cell_line_ids),"1 more more cell_lines are not linked to" \
                                                 " a specimen id. Please link all cell_lines to an input specimen."

def check_organoids_linked(xlsx_dict):

    if "specimen_from_organism.biomaterial_core.biomaterial_id" in xlsx_dict["organoid"].columns:
        input_specimen_ids = [x for x in list(xlsx_dict["organoid"]["specimen_from_organism.biomaterial_core.biomaterial_id"]) if str(x) != 'nan']
    else:
        input_specimen_ids = []

    if "cell_line.biomaterial_core.biomaterial_id" in xlsx_dict["organoid"].columns:
        input_cell_line_ids = [x for x in list(xlsx_dict["organoid"]["cell_line.biomaterial_core.biomaterial_id"]) if str(x) != 'nan']
    else:
        input_cell_line_ids = []

    # Check that organoids are not linked to an input organoid
    for column in xlsx_dict["organoid"].columns:
        if "organoid.biomaterial_core.biomaterial_id." in column:
            organoid_as_input = [x for x in list(xlsx_dict["organoid"][column]) if str(x) != 'nan']
            assert len(organoid_as_input) == 0,"Organoid input biomaterial type should be specimen id or cell line id. Organoid cannot be used" \
                                                " as input to an organoid."

    # Check that all organoid ids are linked to the same input biomaterial type; all specimen ids or all cell line ids.
    if len(input_cell_line_ids) > 0:
        assert len(input_specimen_ids) == 0,"Organoids are linked to more than 1 input biomaterial type. Please link all organoids" \
                                                                        " to 1 input biomaterial type (specimen or cell line). The dataset cen be split by biomaterial type" \
                                                                         " if needed."
    if len(input_specimen_ids) > 0:
        assert len(input_cell_line_ids) == 0,"Organoids are linked to more than 1 input biomaterial type. Please link all organoids" \
                                                                        " to 1 input biomaterial type (specimen or cell line). The dataset cen be split by biomaterial type" \
                                                                        " if needed."

    # Check that all organoid ids are linked to a specimen id or a cell line id.
    organoid_ids = list(xlsx_dict["organoid"]["organoid.biomaterial_core.biomaterial_id"])
    assert len(input_specimen_ids) == len(organoid_ids) or len(input_cell_line_ids) == len(organoid_ids),"1 more more organoids are not linked to" \
                                                 " a specimen id or cell line id. Please link all organoids to an input specimen or cell line."

def check_biomaterial_linkings(xlsx_dict):

    biomaterial_tabs = ["donor_organism", "specimen_from_organism", "cell_line", "organoid", "cell_suspension"]
    biomaterial_tabs = [tab for tab in biomaterial_tabs if tab in xlsx_dict.keys()]

    biomaterial_id_dict = {}
    for biomaterial_tab in biomaterial_tabs:

        biomaterial_id_dict[biomaterial_tab] = {"ids":[],"input_tabs":[],"input_ids":[]}
        biomaterial_id_dict[biomaterial_tab]["ids"] = list(xlsx_dict[biomaterial_tab]["%s.biomaterial_core.biomaterial_id" % (biomaterial_tab)])
        biomaterial_id_key = "%s.biomaterial_core.biomaterial_id" % (biomaterial_tab)
        biomaterial_id_dict[biomaterial_tab]["input_tabs"] = [tab for tab in biomaterial_tabs if biomaterial_id_key in xlsx_dict[tab].columns]
        biomaterial_id_dict[biomaterial_tab]["input_tabs"].remove(biomaterial_tab)
        for tab in biomaterial_id_dict[biomaterial_tab]["input_tabs"]:
            biomaterial_id_dict[biomaterial_tab]["input_ids"].extend(xlsx_dict[tab][biomaterial_id_key])
        if biomaterial_id_key in xlsx_dict["sequence_file"].columns:
            biomaterial_id_dict[biomaterial_tab]["input_ids"].extend(list(xlsx_dict["sequence_file"][biomaterial_id_key]))
        biomaterial_id_dict[biomaterial_tab]["input_ids"] = [x for x in biomaterial_id_dict[biomaterial_tab]["input_ids"] if str(x) != 'nan']

        new_input_ids = []
        for input_id in biomaterial_id_dict[biomaterial_tab]["input_ids"]:
            if "||" in input_id:
                new_input_ids.extend(input_id.split("||"))
            else:
                new_input_ids.append(input_id)
        biomaterial_id_dict[biomaterial_tab]["input_ids"] = new_input_ids

        for id in biomaterial_id_dict[biomaterial_tab]["ids"]:
            assert id in biomaterial_id_dict[biomaterial_tab]["input_ids"],"Biomaterial id %s is an orphan biomaterial. Please fix the linking" \
                                                                           " and run again." % (id)

def check_protocol_linkings(xlsx_dict):

    protocol_tabs = ["collection_protocol", "dissociation_protocol", "enrichment_protocol", "differentiation_protocol", "library_preparation_protocol", "sequencing_protocol"]
    biomaterial_tabs = ["donor_organism", "specimen_from_organism", "cell_line", "organoid", "cell_suspension", "sequence_file"]

    protocol_id_dict = {}
    for protocol_tab in protocol_tabs:
        if protocol_tab in xlsx_dict.keys():
            protocol_id_key = "%s.protocol_core.protocol_id" % (protocol_tab)
            protocol_id_dict[protocol_tab] = {"ids":[],"input_ids":[]}
            protocol_id_dict[protocol_tab]["ids"] = list(xlsx_dict[protocol_tab][protocol_id_key])
            for biomaterial_tab in biomaterial_tabs:
                if biomaterial_tab in xlsx_dict.keys():
                    new_cols = []
                    for col in xlsx_dict[biomaterial_tab].columns:
                        if "protocol_id" in col:
                            new_cols.append(col.split("protocol_id")[0] + "protocol_id")
                        else:
                            new_cols.append(col)
                    xlsx_dict[biomaterial_tab].columns = new_cols
                    if protocol_id_key in xlsx_dict[biomaterial_tab].columns:
                        protocol_id_dict[protocol_tab]["input_ids"].extend(list(xlsx_dict[biomaterial_tab][protocol_id_key]))

            input_ids = [item for item in protocol_id_dict[protocol_tab]["input_ids"] if str(item) != 'nan']
            for input_id in input_ids:
                if "||" in input_id:
                    new_input_ids = input_id.split("||")
                    protocol_id_dict[protocol_tab]["input_ids"].extend(new_input_ids)

            protocol_id_dict[protocol_tab]["input_ids"] = set(protocol_id_dict[protocol_tab]["input_ids"])

            for id in protocol_id_dict[protocol_tab]["ids"]:
                assert id in protocol_id_dict[protocol_tab]["input_ids"], "Protocol id %s is an orphan protocol. Please fix the linking" \
                          " and run again." % (id)

def get_experimental_design(xlsx_dict: {}):

    if 'cell_line' in xlsx_dict.keys():
        if xlsx_dict['cell_line'].empty:
            cell_line = False
        else:
            cell_line = True
    else:
        cell_line = False

    if 'organoid' in xlsx_dict.keys():
        if xlsx_dict['organoid'].empty:
            organoid = False
        else:
            organoid = True
    else:
        organoid = False

    if cell_line and not organoid:
        experimental_design = "cell_line_only"
    elif not cell_line and organoid:
        experimental_design = "organoid_only"
    elif cell_line and organoid:
        experimental_design = "organoid"
    else:
        experimental_design = "standard"

    return experimental_design


import json
import os
import traceback
from django.conf import settings

import requests
from bs4 import BeautifulSoup as bs

from utils.logger import log
from .gmail_utils import find_nth

def parse_job_detail(body):
    """Parse html body and get job posting details
    Args:
      body: email html body
    Returns:
      String values which represent details of job post in JSON format.
    """
    try:
        link = body[find_nth(body, 'https://www.linkedin.com/comm/jobs/view/', 1): find_nth(body, '?trk', 1)]
        url = requests.get(link)
        html_text = url.text
        s = find_nth(html_text, '', 1)
        e = html_text.rfind('-->') + 10
        plain_data = html_text[s: e]
        plain_data = plain_data.replace('', '')
        soup = bs(plain_data, "html.parser")
        try:
            poster_information = soup.find('code', id='posterInformationModule')
            poster_information_json = poster_information.getText()
        except:
            poster_information_json = '{}'
        try:
            decorated_job_posting = soup.find('code', id='decoratedJobPostingModule')
            decorated_job_posting_json = decorated_job_posting.getText()
        except:
            decorated_job_posting_json = '{}'
        try:
            top_card_v2 = soup.find('code', id='topCardV2Module')
            top_card_v2_json = top_card_v2.getText()
        except:
            top_card_v2_json = '{}'

        return poster_information_json, decorated_job_posting_json, top_card_v2_json
    except Exception as e:
        log(traceback.format_exception(None, e, e.__traceback__), 'e')
        return '{}', '{}', '{}'

def get_access_token_with_code(code):
    try:
        if settings.DEBUG:
            redirect_uri = 'http://localhost:8080/action-linkedin-oauth2'
        else:
            redirect_uri = 'https://' + settings.SITE_URL + '/action-linkedin-oauth2'
        post_data = {'grant_type': 'authorization_code', 'code': code,
                     'redirect_uri': redirect_uri,
                     'client_id': os.environ.get('JOBHAX_LINKEDIN_CLIENT_KEY', ''),
                     'client_secret': os.environ.get('JOBHAX_LINKEDIN_CLIENT_SECRET', '')}
        log(post_data, 'e')
        response = requests.post('https://www.linkedin.com/uas/oauth2/accessToken',
                                 data=post_data, headers={'content-type': 'application/x-www-form-urlencoded'})
        json_res = json.loads(response.text)
        log(json_res, 'e')
        return json_res['access_token']
    except Exception as e:
        log(traceback.format_exception(None, e, e.__traceback__), 'e')
        return None


# -*- coding: utf-8 -*-
"""
Created on Wed Apr  1 11:18:01 2020

@author: Pratiksha
"""

def isSubsequence(s, t):
    x=0
    if len(s)==0:
        return True
    elif len(t)>0:
        for i in range(len(t)):
            if s[x]==t[i]:
                x+=1
            if x==len(s):
                return True

        return False
    else:
        return False
a,b=map(str,input().split())
x=isSubsequence(a,b)
if x:
    print('Is a Subsequence')
else:
    print('Not a Subsequence')


import platform
import argparse
from packaging import version

parser = argparse.ArgumentParser()
parser.add_argument('--min-version', help='Minimum Python version')
args = parser.parse_args()

actual_py=version.parse(platform.python_version())
min_py=version.parse(args.min_version)

if (min_py > actual_py):
    print(f"Error: Python version is {actual_py}, but required {min_py} or higher!")
    exit(1)


import LSystem
import turtle
import random

def weed(turtle, screen):

    instructions = (LSystem.LSystem(4,'H'))
    print(instructions)

    #RULES:
    """
    H
    H --> HFX[+H][-H]
    X --> X[-FFF][+FFF]FX
    """

    def turtle_draw(turtle, instructions, steps, angle):
        instructions = (LSystem.LSystem(4,'H'))
        turtle.speed(0)
        turtle.left(90)
        position_list = ''
        heading_list = []
        x_position = []
        y_position = []
        for char in instructions:
            if char == 'F':
                turtle.forward(steps)
            elif char == '+':
                turtle.right(angle)
            elif char == '-':
                turtle.left(angle)
            elif char == '[':
                x_position = x_position + [turtle.xcor()]
                y_position = y_position + [turtle.ycor()]
                heading_list = heading_list + [turtle.heading()]
            elif char == ']':
                turtle.goto(x_position.pop(), y_position.pop())
                turtle.setheading(heading_list.pop())

    rand = random.randrange(10,50,1)
    rand = rand / 10
    print(rand)
    rand2 = random.randrange(15,45)
    turtle_draw(turtle, instructions, rand, rand2)


"""
    email_reply_parser is a python library port of GitHub's Email Reply Parser.

    For more information, visit https://github.com/zapier/email-reply-parser
"""

import re

class EmailReplyParser(object):
    """ Represents a email message that is parsed.
    """

    @staticmethod
    def read(text):
        """ Factory method that splits email into list of fragments

            text - A string email body

            Returns an EmailMessage instance
        """
        return EmailMessage(text).read()

    @staticmethod
    def parse_reply(text):
        """ Provides the reply portion of email.

            text - A string email body

            Returns reply body message
        """
        return EmailReplyParser.read(text).reply

class EmailMessage(object):
    """ An email message represents a parsed email body.
    """

    SIG_REGEX = re.compile(r'(--|__|-\w)|(^Sent from my (\w+\s*){1,3})')
    QUOTE_HDR_REGEX = re.compile('On.*wrote:$')
    QUOTED_REGEX = re.compile(r'(>+)')
    HEADER_REGEX = re.compile(r'^\*?(From|Sent|To|Subject):\*? .+')
    _MULTI_QUOTE_HDR_REGEX = r'(?!On.*On\s.+?wrote:)(On\s(.+?)wrote:)'
    MULTI_QUOTE_HDR_REGEX = re.compile(_MULTI_QUOTE_HDR_REGEX, re.DOTALL | re.MULTILINE)
    MULTI_QUOTE_HDR_REGEX_MULTILINE = re.compile(_MULTI_QUOTE_HDR_REGEX, re.DOTALL)

    def __init__(self, text):
        self.fragments = []
        self.fragment = None
        self.text = text.replace('\r\n', '\n')
        self.found_visible = False

    def read(self):
        """ Creates new fragment for each line
            and labels as a signature, quote, or hidden.

            Returns EmailMessage instance
        """

        self.found_visible = False

        is_multi_quote_header = self.MULTI_QUOTE_HDR_REGEX_MULTILINE.search(self.text)
        if is_multi_quote_header:
            self.text = self.MULTI_QUOTE_HDR_REGEX.sub(is_multi_quote_header.groups()[0].replace('\n', ''), self.text)

        # Fix any outlook style replies, with the reply immediately above the signature boundary line
        #   See email_2_2.txt for an example
        self.text = re.sub('([^\n])(?=\n ?[_-]{7,})', '\\1\n', self.text, re.MULTILINE)

        self.lines = self.text.split('\n')
        self.lines.reverse()

        for line in self.lines:
            self._scan_line(line)

        self._finish_fragment()

        self.fragments.reverse()

        return self

    @property
    def reply(self):
        """ Captures reply message within email
        """
        reply = []
        for f in self.fragments:
            if not (f.hidden or f.quoted):
                reply.append(f.content)
        return '\n'.join(reply)

    def _scan_line(self, line):
        """ Reviews each line in email message and determines fragment type

            line - a row of text from an email message
        """
        is_quote_header = self.QUOTE_HDR_REGEX.match(line) is not None
        is_quoted = self.QUOTED_REGEX.match(line) is not None
        is_header = is_quote_header or self.HEADER_REGEX.match(line) is not None

        if self.fragment and len(line.strip()) == 0:
            if self.SIG_REGEX.match(self.fragment.lines[-1].strip()):
                self.fragment.signature = True
                self._finish_fragment()

        if self.fragment \
                and ((self.fragment.headers == is_header and self.fragment.quoted == is_quoted) or
                         (self.fragment.quoted and (is_quote_header or len(line.strip()) == 0))):

            self.fragment.lines.append(line)
        else:
            self._finish_fragment()
            self.fragment = Fragment(is_quoted, line, headers=is_header)

    def quote_header(self, line):
        """ Determines whether line is part of a quoted area

            line - a row of the email message

            Returns True or False
        """
        return self.QUOTE_HDR_REGEX.match(line[::-1]) is not None

    def _finish_fragment(self):
        """ Creates fragment
        """

        if self.fragment:
            self.fragment.finish()
            if self.fragment.headers:
                # Regardless of what's been seen to this point, if we encounter a headers fragment,
                # all the previous fragments should be marked hidden and found_visible set to False.
                self.found_visible = False
                for f in self.fragments:
                    f.hidden = True
            if not self.found_visible:
                if self.fragment.quoted \
                        or self.fragment.headers \
                        or self.fragment.signature \
                        or (len(self.fragment.content.strip()) == 0):

                    self.fragment.hidden = True
                else:
                    self.found_visible = True
            self.fragments.append(self.fragment)
        self.fragment = None

class Fragment(object):
    """ A Fragment is a part of
        an Email Message, labeling each part.
    """

    def __init__(self, quoted, first_line, headers=False):
        self.signature = False
        self.headers = headers
        self.hidden = False
        self.quoted = quoted
        self._content = None
        self.lines = [first_line]

    def finish(self):
        """ Creates block of content with lines
            belonging to fragment.
        """
        self.lines.reverse()
        self._content = '\n'.join(self.lines)
        self.lines = None

    @property
    def content(self):
        return self._content.strip()


""" [CompareHS.py Documentation] """
from src.core.Comparator import Comparator
from src.core.Database import Database

class CompareHS(Comparator):
    """ [Class DocString] """

    def __init__(self, left_directory, left_selected_files, right_directory, right_selected_files):
        super().__init__(left_directory, left_selected_files,
                         right_directory, right_selected_files)

        # self.thelist = None
        # self.listOfLineNumbers1 = None
        # self.listOfLineNumbers2 = None
        # self.listOfLineMatches = None
        # self.listOfFileNames1 = None
        # self.listOfFileNames2 = None

    def compare(self):
        """ [Function DocString] """
        # TODO Default Comparison Code

        # Queries all lines associated with the left and right directories
        query1 = f"select Content.line_content from Content where Content.directory_ID = '{self.left_directory_ID}'"
        query2 = f"select content.line_content from codematcher.content where content.directory_ID = '{self.right_directory_ID}'"

        # Queries the file names associated with the content from the left and right directories
        query3 = f"select file_name from `file` join content on content.file_ID = `file`.file_ID where content.directory_ID = '{self.left_directory_ID}'"
        query4 = f"select file_name from `file` join content on content.file_ID = `file`.file_ID where content.directory_ID = '{self.right_directory_ID}'"

        # Executes the first two queries and inserts the data into two lists
        tableData1 = self.database.EXECUTE(query1)
        tableData2 = self.database.EXECUTE(query2)

        # Executes the 3rd and 4th queries and inserts the data into two lists
        file_names_one = self.database.EXECUTE(query3)
        file_names_two = self.database.EXECUTE(query4)

        # Changes each line in the list to a string and inserts it into a new list
        tableData1_list_str = []
        for item in tableData1:
            tableData1_list_str.append(str(item))

        tableData2_list_str = []
        for item in tableData2:
            tableData2_list_str.append(str(item))

        # Removes unnecessary data from the list and inserts it into a new list
        tableData1_r = []
        for x in tableData1_list_str:
            x = x.removeprefix("(\'")
            x = x.removesuffix("\',)")
            x = x.replace("\\n", "").replace("\\\\n", "").replace("\\r", "").replace("\\\\r", "").replace(
                "\\t", "").replace("\\\\t", "").replace("\\f", "").replace("\\\\f", "").replace("\\\\", "")
            tableData1_r.append(x)

        tableData2_r = []
        for x in tableData2_list_str:
            x = x.removeprefix("(\'")
            x = x.removesuffix("\',)")
            x = x.replace("\\n", "").replace("\\\\n", "").replace("\\r", "").replace("\\\\r", "").replace(
                "\\t", "").replace("\\\\t", "").replace("\\f", "").replace("\\\\f", "").replace("\\\\", "")
            tableData2_r.append(x)

        # Comparison algorithm

        # Flag is used when there are no matches found
        flag = 1

        # the_list is used to hold all matches found
        the_list = []
        list_ofLineNumbers1 = []
        list_ofLineNumbers2 = []
        list_ofLineMatches = []
        list_ofFileNames1 = []
        list_ofFileNames2 = []

        # Outside if/elif/else is used to check the length of the lists to prevent input mismatch
        if len(tableData1_r) > len(tableData2_r):

            # Two for loops are used to index the lists
            for i in range(len(tableData1_r)):
                for j in range(len(tableData2_r)):

                    # If statement checks if there is a match
                    if tableData1_r[i] == tableData2_r[j]:

                        # If the match is an empty space, it skips the line
                        if tableData1_r[i] == "":
                            break

                        # The nonempty line is put into a string and then inserted into the_list
                        strr = f"Line {i+1} in {file_names_one[i][0]} matches line {j+1} in {file_names_two[j][0]} : {tableData1_r[i]}"
                        the_list.append(strr)
                        list_ofLineNumbers1.append(i+1)
                        list_ofLineNumbers2.append(j+1)
                        list_ofLineMatches.append(tableData1_r[i])
                        list_ofFileNames1.append(file_names_one[i][0])
                        list_ofFileNames2.append(file_names_two[j][0])

                        # Flag is set to 0 because there was at least one match
                        flag = 0

            # If no matches are found, then the_list reflects that
            if flag == 1:
                strr = "No matches found."
                the_list.append(strr)

        elif len(tableData1_r) < len(tableData2_r):

            # Two for loops are used to index the lists
            for i in range(len(tableData1_r)):
                for j in range(len(tableData2_r)):

                    # If statement checks if there is a match
                    if tableData2_r[j] == tableData1_r[i]:

                        # If the match is an empty space, it skips the line
                        if tableData1_r[i] == "":
                            break

                        # The nonempty line is put into a string and then inserted into the_list
                        strr = f"Line {i+1} in {file_names_one[i][0]} matches line {j+1} in {file_names_two[j][0]} : {tableData1_r[i]}"
                        the_list.append(strr)
                        list_ofLineNumbers1.append(i+1)
                        list_ofLineNumbers2.append(j+1)
                        list_ofLineMatches.append(tableData1_r[i])
                        list_ofFileNames1.append(file_names_one[i][0])
                        list_ofFileNames2.append(file_names_two[j][0])

                        # Flag is set to 0 because there was at least one match
                        flag = 0

            # If no matches are found, then the_list reflects that
            if flag == 1:
                strr = "No matches found."
                the_list.append(strr)

        elif len(tableData1_r) == len(tableData2_r):

            # Two for loops are used to index the lists
            for i in range(len(tableData1_r)):
                for j in range(len(tableData2_r)):

                    # If statement checks if there is a match
                    if tableData1_r[i] == tableData2_r[j]:

                        # If the match is an empty space, it skips the line
                        if tableData1_r[i] == "":
                            break

                        # The nonempty line is put into a string and then inserted into the_list
                        strr = f"Line {i+1} in {file_names_one[i][0]} matches line {j+1} in {file_names_two[j][0]} : {tableData1_r[i]}"
                        the_list.append(strr)
                        list_ofLineNumbers1.append(i+1)
                        list_ofLineNumbers2.append(j+1)
                        list_ofLineMatches.append(tableData1_r[i])
                        list_ofFileNames1.append(file_names_one[i][0])
                        list_ofFileNames2.append(file_names_two[j][0])

                        # Flag is set to 0 because there was at least one match
                        flag = 0

            # If no matches are found, then the_list reflects that
            if flag == 1:
                strr = "No matches found."
                the_list.append(strr)

        # This else statement should never execute because all possible list lengths are checked
        # If this executes, something is severely wrong
        else:
            print("You should not be here.")

        self.thelist = the_list
        self.listOfLineNumbers1 = list_ofLineNumbers1
        self.listOfLineNumbers2 = list_ofLineNumbers2
        self.listOfLineMatches = list_ofLineMatches
        self.listOfFileNames1 = list_ofFileNames1
        self.listOfFileNames2 = list_ofFileNames2

        print("[Comparison Results: HS]")


import pygame
import random
#################################################
# 기본 초기화 (반드시 해야하는 것들)
pygame.init()

# 화면 크기 설정 (480 x 640)
screen_width = 480 # 가로 크기
screen_height = 640 # 세로 크기
screen = pygame.display.set_mode((screen_width, screen_height))

# 화면 타이틀 설정
pygame.display.set_caption("Hee DDONG Game") # 게임 이름

# FPS
clock = pygame.time.Clock()
#################################################

# 1. 사용자 게임 초기화 (배경화면, 게임 이미지, 좌표, 속도, 폰트 등)
# 배경 만들기
background = pygame.image.load("C:\\Users\\wkdgm\\OneDrive\\Documents\\Python_Game\\pygame_ddong\\background.png")

# 캐릭터 만들기
character = pygame.image.load("C:\\Users\\wkdgm\\OneDrive\\Documents\\Python_Game\\pygame_ddong\\character.png")
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_x_pos = (screen_width / 2) - (character_width / 2)
character_y_pos = screen_height - character_height

# 이동 위치
to_x = 0
character_speed = 10

# 똥 만들기 (적군)
ddong = pygame.image.load("C:\\Users\\wkdgm\\OneDrive\\Documents\\Python_Game\\pygame_ddong\\enemy.png")
ddong_size = ddong.get_rect().size
ddong_width = ddong_size[0]
ddong_height = ddong_size[1]
ddong_x_pos = random.randint(0, screen_width - ddong_width)
ddong_y_pos = 0
ddong_speed = 10

# Font 정의
game_font = pygame.font.Font(None, 40)
total_time = 10
start_ticks = pygame.time.get_ticks() # 시작 시간 정의

# 게임 종료 메시지
game_result = "Game Over"

running = True # 게임이 진행 중인가
while running:
    dt = clock.tick(30)

    # 2. 이벤트 처리 (키보드, 마우스 등)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                to_x -= character_speed
            elif event.key == pygame.K_RIGHT:
                to_x += character_speed

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                to_x = 0

    # 3. 게임 캐릭터 위치 정의
    character_x_pos += to_x

    if character_x_pos < 0:
        character_x_pos = 0
    elif character_x_pos > screen_width - character_width:
        character_x_pos = screen_width - character_width

    ddong_y_pos += ddong_speed # 똥이 떨어짐

    if ddong_y_pos > screen_height:
        ddong_y_pos = 0
        ddong_x_pos = random.randint(0, screen_width - ddong_width)

    # 4. 충돌 처리
    character_rect = character.get_rect()
    character_rect.left = character_x_pos
    character_rect.top = character_y_pos

    ddong_rect= ddong.get_rect()
    ddong_rect.left = ddong_x_pos
    ddong_rect.top = ddong_y_pos

    if character_rect.colliderect(ddong_rect):
        game_result = "Game Over"
        running = False

    # 5. 화면에 그리기
    screen.blit(background, (0, 0))
    screen.blit(character, (character_x_pos, character_y_pos))
    screen.blit(ddong, (ddong_x_pos, ddong_y_pos))

     # 경과 시간 계산
    elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 # ms -> s
    timer = game_font.render("Time : {}".format(int(total_time - elapsed_time)), True, (255,255,255))
    screen.blit(timer, (10, 10))

    # 시간 초과 했다면
    if total_time-elapsed_time <= 0:
        game_result = "Mission Complete"
        running = False

    pygame.display.update() # 게임 화면을 다시 그리기(반드시 계속 호출 되어야 함)

# 게임 오버 메시지
msg = game_font.render(game_result, True, (255,255,0))  # 노란색
msg_rect = msg.get_rect(center=(int(screen_width/2), int(screen_height/2)))
screen.blit(msg, msg_rect)
pygame.display.update()

# 2초 대기
pygame.time.delay(2000)

# pygame 종료
pygame.quit()


# configurations are of format model_timesteps and contain the seeds used on the model that pertains
model_sac = "sac"
env_cheetah = "HalfCheetah-v2"

# general experiment configs
#trajectory_length = [1000, 500, 50]
attack_model_size = [1000]
num_shadow_models = [5]
#threshold_arr = [0.1, 0.3, 0.5, 0.7, 0.9]


from typing import Tuple

import cv2
import numba
import numpy as np
from vinbigdata import BoxCoordsFloat, BoxCoordsInt

def is_interactive():
    import __main__ as main
    return not hasattr(main, '__file__')

@numba.jit
def compute_intersection_area(bbox1: BoxCoordsInt, bbox2: BoxCoordsInt) -> int:
    x1 = max(bbox1[0], bbox2[0])
    y1 = max(bbox1[1], bbox2[1])
    x2 = min(bbox1[2], bbox2[2])
    y2 = min(bbox1[3], bbox2[3])
    h = x2 - x1
    w = y2 - y1
    if h < 0:
        h = 0
    if w < 0:
        h = 0
    return h * w

@numba.jit
def compute_area(bbox: BoxCoordsInt) -> int:
    return (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])

@numba.jit
def compute_union_area(bbox1: BoxCoordsInt, bbox2: BoxCoordsInt) -> int:
    x1 = min(bbox1[0], bbox2[0])
    y1 = min(bbox1[1], bbox2[1])
    x2 = max(bbox1[2], bbox2[2])
    y2 = max(bbox1[3], bbox2[3])
    h = x2 - x1
    w = y2 - y1
    if h < 0:
        h = 0
    if w < 0:
        h = 0
    return h * w

def resize(img: np.array, max_size: Tuple[int, int]) -> np.array:
    return cv2.resize(img, max_size, interpolation=cv2.INTER_LANCZOS4)

@numba.jit
def rel2abs(box: BoxCoordsFloat, img_shape: Tuple[int, int]) -> BoxCoordsFloat:
    return (box[0] * img_shape[0], box[1] * img_shape[1], box[2] * img_shape[0], box[3] * img_shape[1])

@numba.jit
def abs2rel(box: BoxCoordsFloat, img_shape: Tuple[int, int]) -> BoxCoordsFloat:
    return (box[0] / img_shape[0], box[1] / img_shape[1], box[2] / img_shape[0], box[3] / img_shape[1])


import json
import time
import os
from pymongo import MongoClient

############### 数据初始化，修改数据库链接后，直接运行本程序 ####################

############################## 工具配置 start ################################

# mongodb连接字符串
MONGODB_URI='mongodb://127.0.0.1:27017/'

############################## 工具配置 end ##################################

# 地区
LOCATION=["de-DE", "en-CA", "en-GB", "en-IN", "en-US", "fr-FR", "it-IT", "ja-JP", "zh-CN"]
# 必应接口
BINGAPI='https://cn.bing.com/HPImageArchive.aspx?n=1&format=js&idx=0'
# 必应URL
BINGURL='https://cn.bing.com'

'''
初始化连接
@mkt 地区，默认zh-CN
'''
def db_init(mkt="zh-CN"):
    URI = os.environ.get("MONGODB_URI")
    client = MongoClient(URI)
    db = client.bing
    if mkt=="zg-CN":
        return db['cn']
    if mkt=="ja-JP":
        return db['jp']
    if mkt=="it-IT":
        return db['it']
    if mkt=="fr-FR":
        return db['fr']
    if mkt=="en-US":
        return db['us']
    if mkt=="en-IN":
        return db['in']
    if mkt=="en-GB":
        return db['gb']
    if mkt=="en-CA":
        return db['ca']
    if mkt=="de-DE":
        return db['de']
    return db['cn']
    return collection

'''
根据地区插入多条json数据
@mkt 地区
@obj 插入数据
'''
def insert_many(mkt,obj):
    collection = db_init(mkt)
    collection.insert_many(obj)

def read_json(run_type):
    with open(f'{run_type}_all.json', 'r', encoding="utf-8") as f:
        return json.load(f)['data']

# 格式化必应接口数据
def format_data(lists):
    res=[]
    lists=lists[::-1]
    id=1
    for bing_json_data in lists:
        timearray=time.strptime(str(bing_json_data['datetime']),'%Y-%m-%d')
        datetime=time.strftime('%Y-%m-%d', timearray)
        json_data={}
        json_data['id']=id
        json_data['title']=bing_json_data.get("title","")
        json_data['url']=bing_json_data['url'].replace("&rf=LaDigue_1920x1080.jpg&pid=hp","")
        json_data['datetime']=datetime
        json_data['copyright']=bing_json_data.get("copyright","")
        json_data['copyrightlink']=bing_json_data.get("copyrightlink","")
        json_data['hsh']=bing_json_data.get("hsh","")
        json_data['created_time']=str(time.strftime('%Y-%m-%d', time.localtime()))
        res.append(json_data)
        id=id+1
    return res

# 初始化数据
def init_data():
    for mkt in LOCATION:
        print("初始化"+mkt)
        lists=read_json(mkt)
        lists=format_data(lists)
        insert_many(mkt,lists)
        print("初始化结束\n")

# 删除数据库，慎用
def del_database():
    URI = os.environ.get("MONGODB_URI")
    client = MongoClient(URI)
    client.drop_database('bing')

if __name__=='__main__':
    os.environ['MONGODB_URI']=MONGODB_URI
    del_database()
    init_data()


class Node:

    def __init__(self, data):
        self.data = data
        self.next = None

def takeInput():
    inputlist = [int(x) for x in input().split()]
    head = None
    for ele in inputlist:
        if ele == -1:
            break
        Newnode = Node(ele)
        if head is None:
            head = Newnode
            temp = head
        else:
            temp.next = Newnode
            temp = temp.next

    return head

def printlist(head):
    while head is not None:
        print(head.data, '->', end='')
        head = head.next
    print('None')

def get_ele(head, n):
    prev = None
    temp = head
    while n > 1:
        prev = temp
        temp = temp.next
        n -= 1

    return prev, temp

def reverse(head):
    if head == None or head.next is None:
        return head, head
    smallhead, smalltail = reverse(head.next)
    smalltail.next = head
    head.next = None
    return smallhead, head

def reverseLL(head, m, n):
    if m >= n:
        return head
    if head is None or head.next is None:
        return head
    if m != 1:
        prev1, cur1 = get_ele(head, m)
        prev2, cur2 = get_ele(head, n)
        temp = cur2.next
        cur2.next = None
        new_head, new_tail = reverse(cur1)
        prev1.next = new_head
        new_tail.next = temp
    else:
        prev2, cur2 = get_ele(head, n)
        temp = cur2.next
        cur2.next = None
        new_head, new_tail = reverse(head)
        new_tail.next = temp
        head = new_head
    return head

head = takeInput()
new_head = reverseLL(head, 1, 4)
printlist(new_head)


#!/usr/bin/env python
#-*- encoding:utf-8 -*-
ls=[];
for a in range(1,4):
    for b in range(1,5):
        for c in range(1,4):
            if a!=b and b!=c and a!=c:
                ls.append([a,b,c]);
print("总数量",len(ls));
print(ls);
print(">>>>>>>>>>>>>>>>");
line=[];
for i in range(123,433):
    a=i%10;
    b=(i%100)//10;
    c=(i%1000)//100;
    if a!=b and b!=c and a!=c and 0<a<5 and 0<b<5 and 0<c<5:
        print(i);
        line.append(i);
print("the total is :",len(line));