# あなたは本の表紙を作っています。
# 本の表紙は最大で10文字分の幅しかありません。
#
# 表紙に印刷する文字列 S が与えられるので 10 文字ごとに改行して出力するプログラムを作成してください。
#
# 例えば入力例 1 では
#
# PaizaPaizaPaiza
#
# と入力されるので
#
# PaizaPaiza
# Paiza
#
# と出力してください。

# string型が既にcharの配列のためリストに変更する必要なし
strs = input()
ret = []

for i in range(len(strs)):
    ret.append(strs[i])
    if (i + 1) % 10 == 0:
        ret.append("\n")

print(''.join(ret))

Python/スキルチェック問題/Dランク問題/D134_タイトルの長さ★.py

D134_タイトルの長さ★.py


# A Python program to print topological sorting of a graph
# using indegrees
from collections import defaultdict

# Class to represent a graph
class Graph:
    def __init__(self, vertices):
        self.graph = defaultdict(list)  # dictionary containing adjacency List
        self.V = vertices  # No. of vertices4

    # function to add an edge to graph
    def addEdge(self, u, v):
        self.graph[u].append(v)

    # The function to do Topological Sort.
    def topologicalSort(self):

        # Create a vector to store indegrees of all
        # vertices. Initialize all indegrees as 0.
        in_degree = [0] * (self.V)

        # Traverse adjacency lists to fill indegrees of
        # vertices.  This step takes O(V+E) time
        for i in self.graph:
            for j in self.graph[i]:
                in_degree[j] += 1

        # Create an queue and enqueue all vertices with
        # indegree 0
        queue = []
        for i in range(self.V):
            if in_degree[i] == 0:
                queue.append(i)

        # Initialize count of visited vertices
        cnt = 0

        # Create a vector to store result (A topological
        # ordering of the vertices)
        top_order = []

        # One by one dequeue vertices from queue and enqueue
        # adjacents if indegree of adjacent becomes 0
        while queue:

            # Extract front of queue (or perform dequeue)
            # and add it to topological order
            u = queue.pop(0)
            top_order.append(u)

            # Iterate through all neighbouring nodes
            # of dequeued node u and decrease their in-degree
            # by 1
            for i in self.graph[u]:
                in_degree[i] -= 1
                # If in-degree becomes zero, add it to queue
                if in_degree[i] == 0:
                    queue.append(i)

            cnt += 1

        # Check if there was a cycle
        if cnt != self.V:
            print("There exists a cycle in the graph")
        else:
            # Print topological order
            print(top_order)

g = Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);

print("Following is a Topological Sort of the given graph")
g.topologicalSort()


import logging
from pathlib import Path

from asr.datasets.custom_audio_dataset import CustomAudioDataset
from asr.text_encoder.ctc_text_encoder import CTCTextEncoder
from asr.utils.parse_config import ConfigParser

logger = logging.getLogger(__name__)

class CustomDirAudioDataset(CustomAudioDataset):
    def __init__(self, audio_dir, transcription_dir=None, *args, **kwargs):
        data = []

        for path in Path(audio_dir).iterdir():
            entry = {}

            if path.suffix in [".mp3", ".wav", ".flac", ".m4a"]:
                entry["path"] = str(path)

                if transcription_dir and Path(transcription_dir).exists():
                    transc_path = Path(transcription_dir) / (path.stem + '.txt')

                    if transc_path.exists():

                        with transc_path.open() as f:
                            entry["text"] = f.read().strip()

            if len(entry) > 0:
                data.append(entry)

        super().__init__(data, *args, **kwargs)

if __name__ == "__main__":
    text_encoder = CTCTextEncoder.get_simple_alphabet()
    config_parser = ConfigParser.get_default_configs()

    ds = CustomDirAudioDataset("data/datasets/custom/audio",
                               text_encoder=text_encoder, config_parser=config_parser)
    item = ds[0]


import logging
import os
import numpy as np
import torch
import torch.optim as optim
from torch.autograd import Variable
from tqdm import tqdm

import utils
import model.crnn as crnn
from model import data_loader
from evaluate import evaluate
import matplotlib.pyplot as plt
import torch.nn as nn

import pandas as pd

def train(model, optimizer, loss_fn, dataloader):
    # set model to training mode
    model.train()

    # summary for current training loop and a running average object for loss
    losses = []

    # Use tqdm for progress bar
    with tqdm(total=len(dataloader)) as t:
        for i, (train_batch, labels_batch) in enumerate(dataloader):

            model = model.to(device=device)  # move the model parameters to CPU/GPU
            model.train()  # put model to training mode

            train_batch = train_batch.to(device=device, dtype=dtype)
            labels_batch = labels_batch.to(device=device, dtype=dtype)

            # compute forward pass
            output_batch = model(train_batch)

            #criterion = nn.L1Loss()
            #loss = criterion(output_batch, labels_batch)
            loss = loss_fn(output_batch, labels_batch)

            # save each batch loss, this can be done also once in a while
            losses.append(loss.item())

            # clear previous gradients, compute gradients of all variables wrt loss
            optimizer.zero_grad()
            loss.backward()

            # performs updates using calculated gradients
            optimizer.step()

            # in case you want to print the training loss after every n iterations
            #if i % print_every == 0:
               # print('Iteration %d, loss = %.4f' % (i, loss.item()))

            # update the average loss
            #loss_avg = torch.mean(torch.FloatTensor(losses))
            #logging.info("- Train average loss : " + loss_avg)
            # t.set_postfix(loss='{:05.3f}'.format(loss_avg()))

            t.update()

    return np.mean(losses), losses

def train_and_evaluate(model, train_dataloader, val_dataloader, optimizer, loss_fn, epochs,
                       restore_file=None):

    epoch_train_losses = []
    batch_train_losses = []
    val_losses = []

    # reload weights from restore_file if specified
    if restore_file is not None:
        restore_path = os.path.join(checkpoint_dir, restore_file + '.pth.tar')
        logging.info("Restoring parameters from {}".format(restore_path))
        utils.load_checkpoint(restore_path, model, optimizer)

    best_val_loss = float('inf')

    for epoch in range(epochs):
        # Run one epoch
        logging.info("Epoch {}/{}".format(epoch + 1, epochs))

        # compute number of batches in one epoch (one full pass over the training set)
        loss_avg_epoch, loss_avg_batch = train(model, optimizer, loss_fn, train_dataloader)
        epoch_train_losses.append(loss_avg_epoch)
        batch_train_losses += loss_avg_batch

        logging.info("- Training average loss : " + str(loss_avg_epoch))

        # Evaluate for one epoch on validation set
        val_loss_avg = evaluate(model, loss_fn, val_dataloader, device, dtype)
        val_losses.append(val_loss_avg)

        logging.info("- Validation average loss : " + str(val_loss_avg))

        is_best = val_loss_avg <= best_val_loss

        model.eval()
        error = 0
        num_samples = 0
        with torch.no_grad():
            for x, y in train_dataloader:
                x = x.to(device=device, dtype=dtype)  # move to device, e.g. GPU
                y = y.to(device=device, dtype=dtype)
                scores = model(x)
                error += np.sum(np.square(scores.numpy() - y.numpy()))
                num_samples += scores.shape[0]
            total_error = float(error) / num_samples
            print('Got mean train error of ' + str(total_error))

        model.eval()
        error = 0
        num_samples = 0
        with torch.no_grad():
            for x, y in val_dataloader:
                x = x.to(device=device, dtype=dtype)  # move to device, e.g. GPU
                y = y.to(device=device, dtype=dtype)
                scores = model(x)
                error += np.sum(np.square(scores.numpy() - y.numpy()))
                num_samples += scores.shape[0]
            total_error = float(error) / num_samples
            print('Got mean val error of ' + str(total_error))

        # If best_eval, best_save_path
        if is_best:
            logging.info("- Found new best evaluation loss")
            best_val_ = val_loss_avg

            # Save best val loss in a json file in the checkpoint directory
            best_val_path = "best_val_loss.txt"
            utils.save_dict_to_txt(val_loss_avg, results_dir, best_val_path, epoch)

        # Save latest val metrics in a json file in the checkpoint directory
        last_val_path = "last_val_loss.txt"
        utils.save_dict_to_txt(val_loss_avg, results_dir, last_val_path, epoch)

        # Save weights
        utils.save_checkpoint({'epoch': epoch + 1,
                               'state_dict': model.state_dict(),
                               'optim_dict' : optimizer.state_dict()},
                              is_best=is_best,
                              checkpoint=checkpoint_dir)

    # plot training history
    utils.show_train_hist(epoch_train_losses, results_dir, show=True, epoch_plot=True, save=True)
    utils.show_train_hist(batch_train_losses, results_dir, show=True, epoch_plot=False, save=True)
    utils.show_train_val_hist(epoch_train_losses, val_losses, results_dir, show=True, save=True)

if __name__ == '__main__':

    import os
    from PIL import Image

    '''
    filenames = os.listdir('data/train/img')
    filenames = [os.path.join('data/train/img', f) for f in filenames if f.endswith('.npy')]
    input = np.load(filenames[10])
    print(type(input))
    print(input.shape)
    print(np.min(input))
    print(np.max(input))
    print(np.mean(input))
    print(input)
    '''

    # training hyperparameters
    batch_size = 64
    lr = 0.000008
    epochs = 30
    data_dir = 'data'
    model_dir = 'model'
    checkpoint_dir = 'checkpoint'
    results_dir = 'results'
    print('learning rate', lr)
    print('epochs', epochs)
    #model parameters
    channels = 10
    vector_dim = 1
    restore_file=None

    USE_GPU = True
    dtype = torch.float32
    print_every = 1    # iterations before printing

    # use GPU if available
    if USE_GPU and torch.cuda.is_available():
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')

    # Set the random seed for reproducible experiments
    torch.manual_seed(230)
    if device == "cuda:0": torch.cuda.manual_seed(230)

    # Set the logger
    utils.set_logger(os.path.join(model_dir, 'train.log'))

    # Define the model and optimizer
    crnn_model = crnn.CRNN2(channels, vector_dim)

    optimizer = optim.Adam(crnn_model.parameters(), lr=lr, betas=(0.9, 0.999))

    # fetch loss function
    loss_fn = crnn.loss_fn

    # Create the input data pipeline
    logging.info("Loading the datasets...")

    # fetch dataloaders
    dataloaders = data_loader.fetch_dataloader(['train', 'val'], data_dir, batch_size)
    train_dl = dataloaders['train']
    #val_dl = None
    val_dl = dataloaders['val']
    #test_dl = dataloaders['test']

    logging.info("- done.")

    # Train the model
    logging.info("Starting training for {} epoch(s)".format(epochs))
    train_and_evaluate(crnn_model, train_dl, val_dl, optimizer, loss_fn, epochs, restore_file=restore_file)


import sys
import json
from api.delete_ocr_resource import DeleteUAIOcrResourceApi

# usage: python create_async_toframe_job.py config_file='controller-config.json'

def load_config(config_file):
    with open(config_file, 'r') as fp:
        config_params = json.loads(fp.read())
    public_key = config_params['public_key']
    private_key = config_params['private_key']
    return public_key, private_key

if __name__ == '__main__':
    if len(sys.argv) == 2:
        config_file = sys.argv[1]
    else:
        config_file = '../config_files/controller-config-online.json'

    resource_id = 'uaiocr-itgrdpmy'
    public_key, private_key = load_config(config_file)
    caller = DeleteUAIOcrResourceApi(public_key, private_key, resource_id)
    caller.call_api()


#!/usr/bin/env python
# coding: utf-8
import os
import codecs
from setuptools import setup, find_packages
import ibclient

def parse_requirements(filename):
    with open(filename) as f:
        required = f.read().splitlines()
        return required

long_desc = """
IBClient
===============
A Python SDK to access market data through Interactive Brokers TWS

"""

setup(
    name='ibclient',
    version=ibclient.__version__,
    description='A Python SDK to access market data through Interactive Brokers TWS',
    long_description=long_desc,
    author='Jin Xu',
    author_email='jin_xu1@qq.com',
    url='https://github.com/chrjxj/ibclient',
    license='BSD',
    keywords=['Interactive Brokers', 'TWS', 'IB', 'Stock', 'finance'],
    classifiers=[
        'Development Status :: 1 - Alpha',
        'License :: OSI Approved :: BSD License'
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ],
    packages=find_packages(),
    install_requires=parse_requirements('requirements.txt'),
    tests_require=parse_requirements('requirements.txt'),

)


# + - * / // **, %
# =, *, **=, ...
# <, >, >=, <=, ==, !=
# and, or, not
# Logic table
# 0 - False
# 1 - True

# AND
# 0 and 1 => 0
# 1 and 0 => 0
# 1 and 1 => 1
# 0 and 0 => 0

# OR
# 0 or 1 => 1
# 1 or 0 => 1
# 1 or 1 => 1
# 0 or 0 => 0

# NOT
# 1 not

# age = int(input("Enter age: "))  # age = 20
# role = input("Enter role: ")  # student

# if age >= 18 and role == student:
# if age >= 18 and role == teacher:
# if age >= 18:
# if age >= 18:
#     if role == "student" or role == "intern":
#         print("Ur a student and ur allowed")
#     elif role == "teacher":
#         print("Teacher access allowed")
#     else:
#         print("Ur guest")
# else:
#     print("not allowed")

# print(1 and 0 or 1) #  1
# print(1 and 0 and 1 and 1 and 1)
# print(10 or 20 or 30 or 40)

num1 = 10
num2 = 15

if num1 == 0 or num2 == 0:
    print("Success")

a = 10

print(not (a % 2 == 0))


arr = [10, 40, 60]
path = [0]*10
MIN = 21e8
n = int(input())

def rcr(level, total, cnt):
    global MIN

    if total>n:
        return
    elif total==n:
        if cnt < MIN:
            MIN = cnt
        return

    for i in range(len(arr)):
        rcr(level+1, total+arr[i], cnt+1)

rcr(0, 0, 0)
print(MIN)


#PICK 6 V1

#1. Used YouTube tutorial from computing101.net on how to create a lottery game in python
#  I adjusted the suggested use of a for loop to something more simple

#2.Used the example on stackoverflow on how to use random.sample and adjusted it to random.randint

"""
A ticket contains 6 numbers, 1 to 99, and the number of matches between
the ticket and the winning numbers determines the payoff. Order matters,
if the winning numbers are [5, 10] and your ticket numbers are [10, 5] you have 0 matches.
If the winning numbers are [5, 10, 2] and your ticket numbers are [10, 5, 2], you have 1 match.
Calculate your net winnings (the sum of all expenses and earnings).
"""

import random
#lists to store random numbers generated

#generate lottery winning numbers and add to list
#1. Generate a list of 6 random numbers representing a the winning ticket
def pick6():
    six_list=[]
    for _ in range(6):
        random_number = random.randint(1,99) #!!!! change to 99 before submission
        six_list.append(random_number)
    return six_list
#print(pick6())

winning_pick6 = pick6()
#print(winning_pick6)
#generate my gas staion random pick 6 ticket and add to list

#compare the numbers in the list by position in the list
def ticket_checker(winning_ticket):
    new_ticket = pick6()      #4. Generate a list of 6 random numbers representing the ticket
    correct_numbers = 0
    for index in range(6):
        if winning_ticket[index] == new_ticket[index]:
            correct_numbers +=1
   # print(winning_ticket)
    #print(new_ticket)
    #print(correct_numbers)
    return correct_numbers               #6 Find how many numbers match

#num_matches = ticket_checker(winning_pick6)
#print(num_matches)
num_matches = 0
#2. Start your balance at 0
winnings = 0

#3. Loop 100,000 times, for each loop:
for x in range(100000):
    winnings -= 2                                #5. Subtract 2 from your blance(you bought a ticket)
    num_matches = ticket_checker(winning_pick6)
    #print('matches', num_matches)
    #print('dollars expended', winnings)
    if num_matches == 1:
        winnings += 4          #7. Add to your balance the winnings from your matches
    elif num_matches ==2:
        winnings += 7
    elif num_matches == 3:
        winnings += 100
    elif num_matches == 4:
        winnings +=50000
    elif num_matches == 5:
        winnings += 1000000
    elif num_matches == 6:
        winnings += 25000000
print(winnings)       #8. After the loop, print the final balance


"""Example of a TensorBoard dynamic plugin."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import mimetypes
import os

from tensorboard.plugins import base_plugin
from werkzeug import wrappers

class ReactPlugin(base_plugin.TBPlugin):
  """WebpackReact Plugin for TensorBoard."""

  plugin_name = 'react'

  def __init__(self, context):
    """Instantiates WebpackReact via TensorBoard core.

    Args:
      context: A base_plugin.TBContext instance.
    """

  def get_plugin_apps(self):
    return {
        '/static/js/index.js': self.serve_static,
        '/static/js/main.js': self.serve_static,
        '/static/js/main.js.map': self.serve_static,
        '/static/css/main.css': self.serve_static,
        '/static/css/main.css.map': self.serve_static,
        '/static/media/logo.svg': self.serve_static,
    }

  def is_active(self):
    return True

  def _send_file(self, file_path):
    with open(file_path, 'rb') as file_obj:
      mimetype = mimetypes.guess_type(file_path)[0]
      return wrappers.Response(
          file_obj.read(), content_type=mimetype)

  @wrappers.Request.application
  def serve_static(self, request):
    path_frags = request.path.rsplit('/', 3)[-3:]
    if path_frags[0] != u'static':
      return

    build = os.path.join(os.path.dirname(__file__), 'frontend/build/')
    return self._send_file(os.path.join(build, *path_frags))

  def frontend_metadata(self):
    return super(ReactPlugin, self).frontend_metadata()._replace(
        tab_name='React Demo',
        es_module_path='/static/js/index.js',
    )

class ReactPluginLoader(base_plugin.TBLoader):
  """Loads React Plugin dynamically. Allows dynamic imorts."""

  def load(self, context):
    return ReactPlugin(context)


#!/usr/bin/env python3
"""Fetch RSS and post it to Slack channel.

2017/Sep/03 @ Zdenek Styblik <stybla@turnovfree.net>
"""
import argparse
import logging
import os
import sys
import time
import traceback
from typing import Dict, List, Tuple

import rss2irc
from slack import WebClient

SLACK_BASE_URL = WebClient.BASE_URL

def format_message(
        url: str, msg_attrs: Tuple[str, str], handle: str = ''
) -> Dict:
    """Return formatted message as Slack's BlockKit section.

    :param url: URL of news item.
    :param msg_attrs: tuple of title and category.
    :param handle: Handle of given feed.
    """
    if handle:
        if len(msg_attrs) > 1 and msg_attrs[1]:
            tag = '[{:s}-{:s}] '.format(handle, msg_attrs[1])
        else:
            tag = '[{:s}] '.format(handle)

    else:
        tag = ''

    return {
        'type': 'section',
        'text': {
            'type': 'mrkdwn',
            'text': '{}<{}|{}>'.format(tag, url, msg_attrs[0])
        }
    }

def get_slack_token() -> str:
    """Get Slack token from ENV variable.

    :raises: `ValueError`
    """
    slack_token = os.environ.get('SLACK_TOKEN', None)
    if slack_token:
        return slack_token

    raise ValueError('SLACK_TOKEN must be set.')

def get_slack_web_client(token: str, base_url: str, timeout: int) -> WebClient:
    """Return instance of Slack Web Client."""
    return WebClient(token, base_url=base_url, timeout=timeout)

def main():
    """Fetch RSS feed and post RSS news to Slack."""
    logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
    logger = logging.getLogger('rss2slack')
    args = parse_args()
    if args.verbosity:
        logger.setLevel(logging.DEBUG)

    if args.cache_expiration < 0:
        logger.error("Cache expiration can't be less than 0.")
        sys.exit(1)

    try:
        slack_token = get_slack_token()
        data = rss2irc.get_rss(logger, args.rss_url, args.rss_http_timeout)
        if not data:
            logger.error('Failed to get RSS from %s', args.rss_url)
            sys.exit(1)

        news = rss2irc.parse_news(data)
        if not news:
            logger.info('No news?')
            sys.exit(0)

        cache = rss2irc.read_cache(logger, args.cache)
        rss2irc.scrub_cache(logger, cache)

        for key in list(news.keys()):
            if key in cache.items:
                logger.debug('Key %s found in cache', key)
                cache.items[key] = int(time.time()) + args.cache_expiration
                news.pop(key)

        slack_client = get_slack_web_client(
            slack_token, base_url=args.slack_base_url,
            timeout=args.slack_timeout
        )
        if not args.cache_init:
            for url in list(news.keys()):
                msg_blocks = [
                    format_message(url, news[url], args.handle)
                ]
                try:
                    post_to_slack(
                        logger, msg_blocks, slack_client, args.slack_channel,
                    )
                except ValueError:
                    news.pop(url)
                finally:
                    time.sleep(args.sleep)

        expiration = int(time.time()) + args.cache_expiration
        for key in list(news.keys()):
            cache.items[key] = expiration

        rss2irc.write_cache(cache, args.cache)
        # TODO(zstyblik): remove error file
    except Exception:
        logger.debug(traceback.format_exc())
        # TODO(zstyblik):
        # 1. touch error file
        # 2. send error message to the channel
    finally:
        sys.exit(0)

def parse_args() -> argparse.Namespace:
    """Return parsed CLI args."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--cache',
        dest='cache', type=str, default=None,
        help='File which contains cache.'
    )
    parser.add_argument(
        '--cache-expiration',
        dest='cache_expiration', type=int,
        default=rss2irc.EXPIRATION,
        help='Time, in seconds, for how long to keep items in cache.'
    )
    parser.add_argument(
        '--cache-init',
        dest='cache_init', action='store_true', default=False,
        help='Prevents posting news to IRC. This is useful '
             'when bootstrapping new RSS feed.'
    )
    parser.add_argument(
        '--handle',
        dest='handle', type=str, default=None,
        help='Handle/callsign of this feed.'
    )
    parser.add_argument(
        '--rss-url',
        dest='rss_url', type=str, required=True,
        help='URL of RSS Feed.'
    )
    parser.add_argument(
        '--rss-http-timeout',
        dest='rss_http_timeout', type=int,
        default=rss2irc.HTTP_TIMEOUT,
        help='HTTP Timeout. Defaults to {:d} seconds.'.format(
            rss2irc.HTTP_TIMEOUT
        )
    )
    parser.add_argument(
        '--slack-base-url',
        dest='slack_base_url', type=str,
        default=SLACK_BASE_URL,
        help='Base URL for Slack client.'
    )
    parser.add_argument(
        '--slack-channel',
        dest='slack_channel', type=str, required=True,
        help='Name of Slack channel to send formatted news to.'
    )
    parser.add_argument(
        '--slack-timeout',
        dest='slack_timeout', type=int,
        default=rss2irc.HTTP_TIMEOUT,
        help='Slack API Timeout. Defaults to {:d} seconds.'.format(
            rss2irc.HTTP_TIMEOUT
        )
    )
    parser.add_argument(
        '--sleep',
        dest='sleep', type=int, default=2,
        help='Sleep between messages in order to avoid '
             'possible excess flood/API call rate limit.'
    )
    parser.add_argument(
        '-v', '--verbose',
        dest='verbosity', action='store_true', default=False,
        help='Increase logging verbosity.'
    )
    return parser.parse_args()

def post_to_slack(
        logger: logging.Logger, msg_blocks: List,
        slack_client: WebClient, slack_channel: str,
) -> None:
    """Post news to Slack channel."""
    try:
        logger.debug('Will post %s', repr(msg_blocks))
        rsp = slack_client.chat_postMessage(
            channel=slack_channel, blocks=msg_blocks
        )
        logger.debug('Response from Slack: %s', rsp)
        if not rsp or rsp["ok"] is False:
            raise ValueError("Slack response is not OK.")
    except ValueError:
        logger.debug(traceback.format_exc())
        raise

if __name__ == '__main__':
    main()


import os
import json
import logging
import opencryptobot.constants as con

from argparse import ArgumentParser
from opencryptobot.database import Database
from opencryptobot.telegrambot import TelegramBot
from opencryptobot.config import ConfigManager as Cfg
from logging.handlers import TimedRotatingFileHandler

class OpenCryptoBot:

    def __init__(self):
        # Parse command line arguments
        self.args = self._parse_args()

        # Load config file
        Cfg(self.args.config)

        # Set up logging
        log_path = self.args.logfile
        log_level = self.args.loglevel
        self._init_logger(log_path, log_level)

        # Create database
        db_path = self.args.database
        self.db = Database(db_path)

        # Create bot
        bot_token = self._get_bot_token()
        self.tg = TelegramBot(bot_token, self.db)

    # Parse arguments
    def _parse_args(self):
        desc = "Telegram bot for crypto currency info"
        parser = ArgumentParser(description=desc)

        # Config file path
        parser.add_argument(
            "-cfg",
            dest="config",
            help="path to conf file",
            default=os.path.join(con.CFG_DIR, con.CFG_FILE),
            required=False,
            metavar="FILE")

        # Save logfile
        parser.add_argument(
            "--no-logfile",
            dest="savelog",
            action="store_false",
            help="don't save logs to file",
            required=False,
            default=True)

        # Use database
        parser.add_argument(
            "--no-database",
            dest="savedata",
            action="store_false",
            help="save command history to database",
            required=False,
            default=True)

        # Logfile path
        parser.add_argument(
            "-log",
            dest="logfile",
            help="path to logfile",
            default=os.path.join(con.LOG_DIR, con.LOG_FILE),
            required=False,
            metavar="FILE")

        # Log level
        parser.add_argument(
            "-lvl",
            dest="loglevel",
            type=int,
            choices=[0, 10, 20, 30, 40, 50],
            help="Disabled, Debug, Info, Warning, Error, Critical",
            default=30,
            required=False)

        # Module log level
        parser.add_argument(
            "-mlvl",
            dest="mloglevel",
            help="set log level for a module",
            default=None,
            required=False)

        # Database path
        parser.add_argument(
            "-db",
            dest="database",
            help="path to SQLite database file",
            default=os.path.join(con.DAT_DIR, con.DAT_FILE),
            required=False,
            metavar="FILE")

        # Bot token
        parser.add_argument(
            "-tkn",
            dest="token",
            help="Telegram bot token",
            required=False,
            default=None)

        # Webhook
        parser.add_argument(
            "--webhook",
            dest="webhook",
            action="store_true",
            help="use webhook instead of polling",
            required=False,
            default=False)

        return parser.parse_args()

    # Configure logging
    def _init_logger(self, logfile, level):
        logger = logging.getLogger()
        logger.setLevel(level)

        log_format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s'

        # Log to console
        console_log = logging.StreamHandler()
        console_log.setFormatter(logging.Formatter(log_format))
        console_log.setLevel(level)

        logger.addHandler(console_log)

        # Save logs if enabled
        if self.args.savelog:
            # Create 'log' directory if not present
            log_path = os.path.dirname(logfile)
            if not os.path.exists(log_path):
                os.makedirs(log_path)

            file_log = TimedRotatingFileHandler(
                logfile,
                when="H",
                encoding="utf-8")

            file_log.setFormatter(logging.Formatter(log_format))
            file_log.setLevel(level)

            logger.addHandler(file_log)

        # Set log level for specified modules
        if self.args.mloglevel:
            for modlvl in self.args.mloglevel.split(","):
                module, loglvl = modlvl.split("=")
                logr = logging.getLogger(module)
                logr.setLevel(int(loglvl))

    # Read bot token from file
    def _get_bot_token(self):
        if self.args.token:
            return self.args.token

        token_path = os.path.join(con.CFG_DIR, con.TKN_FILE)

        try:
            if os.path.isfile(token_path):
                with open(token_path, 'r') as file:
                    return json.load(file)["telegram"]
            else:
                exit(f"ERROR: No token file '{con.TKN_FILE}' found at '{token_path}'")
        except KeyError as e:
            cls_name = f"Class: {type(self).__name__}"
            logging.error(f"{repr(e)} - {cls_name}")
            exit("ERROR: Can't read bot token")

    def start(self):
        if self.args.webhook:
            self.tg.bot_start_webhook()
        else:
            self.tg.bot_start_polling()

        self.tg.bot_idle()


numbers = int(input())
l = []
count = 0
while count<numbers:
	l.append(1)
	if len(l)>=2:
		try:
			while l[-1] == l[-2]:
				v = l[-1]
				del l[-1]
				del l[-1]
				l.append(v+1)
			if l[-1] != l[-2]:
				count+=1
		except:
			count +=1
			continue
	else:
		count+=1

string = ''
for i in range(len(l)-1):
	string = string+str(l[i]) + ' '
string = string + str(l[-1])
print(string)


# from memory

class Solution:
    def topKFrequent(self, nums: list[int], k: int) -> list[int]:
        counter = {}
        for num in nums:
            counter[num] = counter.get(num, 0) + 1

        occurrences = [[] for i in range(len(nums) + 1)]
        for num, count in counter.items():
            occurrences[count].append(num)

        result = []
        for count in range(len(occurrences) - 1, 0, -1):
            for num in occurrences[count]:
                result.append(num)
                if len(result) == k:
                    return result


import pytest

import abjad

def test_get_duration_01():
    """
    Container duration in seconds equals sum of leaf durations in seconds.
    """

    staff = abjad.Staff("c'8 d'8 e'8 f'8")
    mark = abjad.MetronomeMark(abjad.Duration(1, 4), 38)
    abjad.attach(mark, staff[0])
    mark = abjad.MetronomeMark(abjad.Duration(1, 4), 42)
    abjad.attach(mark, staff[2])
    score = abjad.Score([staff])

    assert abjad.lilypond(score) == abjad.string.normalize(
        r"""
        \new Score
        <<
            \new Staff
            {
                \tempo 4=38
                c'8
                d'8
                \tempo 4=42
                e'8
                f'8
            }
        >>
        """
    )

    assert abjad.get.duration(score, in_seconds=True) == abjad.Duration(400, 133)

def test_get_duration_02():
    """
    Container can not calculate duration in seconds without metronome mark.
    """

    container = abjad.Container("c'8 d'8 e'8 f'8")
    with pytest.raises(Exception):
        abjad.get.duration(container, in_seconds=True)

def test_get_duration_03():
    """
    Clock duration equals duration divide by effective tempo.
    """

    staff = abjad.Staff("c'8 d'8 e'8 f'8")
    mark = abjad.MetronomeMark(abjad.Duration(1, 4), 38)
    abjad.attach(mark, staff[0])
    mark = abjad.MetronomeMark(abjad.Duration(1, 4), 42)
    abjad.attach(mark, staff[2])
    abjad.Score([staff])

    assert abjad.lilypond(staff) == abjad.string.normalize(
        r"""
        \new Staff
        {
            \tempo 4=38
            c'8
            d'8
            \tempo 4=42
            e'8
            f'8
        }
        """
    )

    assert abjad.get.duration(staff[0], in_seconds=True) == abjad.Duration(15, 19)
    assert abjad.get.duration(staff[1], in_seconds=True) == abjad.Duration(15, 19)
    assert abjad.get.duration(staff[2], in_seconds=True) == abjad.Duration(5, 7)
    assert abjad.get.duration(staff[3], in_seconds=True) == abjad.Duration(5, 7)

def test_get_duration_04():
    """
    Clock duration can not calculate without metronome mark.
    """

    note = abjad.Note("c'4")
    with pytest.raises(Exception):
        abjad.get.duration(note, in_seconds=True)


#!/usr/bin/python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
#讀取 訓練/驗證 資料
x_val = np.load('x_validation.npy')
x_train = np.load('x_train.npy')
y_val = np.load('y_validation.npy')
y_train = np.load('y_train.npy')
#增加一行1 對齊bias term
x_val = np.concatenate((np.ones((x_val.shape[0], 1)), x_val),axis=1)
x_train = np.concatenate((np.ones((x_train.shape[0], 1)), x_train),axis=1)
#計算Ein,Eval
Lambda = [1000,100,10,1, 0.1, 0.01,0.001,0.0001]
Eval = []
Ein = []
for j in range(len(Lambda)):
    w = np.load("model_lambda_"+str(Lambda[j])+".npy")
    y_hat_val = np.dot(x_val, w)
    y_hat_train = np.dot(x_train, w)
    err1 = abs(y_val - y_hat_val).sum()/len(y_val)
    err2 = abs(y_train - y_hat_train).sum()/len(y_train)
    Eval.append(err1)
    Ein.append(err2)
print(Eval)
print("min of Eval :", np.min(np.array(Eval)))

#plot
Eval = np.array(Eval)
Ein = np.array(Ein)
Lambda = np.array(Lambda)
plt.plot(Lambda, Eval, label=u'Eval')
plt.plot(Lambda, Ein, label=u'Ein')
plt.legend()
plt.xlabel("Lambda")
plt.ylabel("ave_abs_Error")
plt.ylim(4.5, 4.65)
plt.xscale('log')
plt.show()
#結論為lambda = 0.001 時驗證資料錯誤最低


import torch
import torch.nn as nn

from layers import Embedding,Posting_embedding,Multihead_attention

device = torch.device('cuda')

class Encoder_Layer(nn.Module):
    def __init__(self,num_heads,emb_size):
        super(Encoder_Layer, self).__init__()
        self.emb_size = emb_size
        self.hidden=[4*emb_size,emb_size]
        self.num_heads = num_heads
        self.activation =  torch.nn.ReLU()
        self.liner1 = nn.Linear(self.emb_size, self.hidden[0], bias=True).to(device)
        self.liner2 = nn.Linear(self.hidden[0], self.hidden[1], bias=True).to(device)

        self.attention=Multihead_attention(emb_size, num_heads, causality = False).to(device)

    def feedFworad(self,x):
        outputs = self.activation(self.liner1(x))
        outputs = self.liner2(outputs)
        #残差连接
        outputs +=x
        outputs = torch.normal(outputs)
        return outputs

    def forward(self,inputs1,inputs2):
        # self-attention部分
        outputs = self.attention(inputs1,inputs2)

        #feed Forward部分
        return self.feedFworad(outputs)

class Encoder(nn.Module):
    def __init__(self,num_de,num_encoders,emb_size,num_heads=8):
        super(Encoder, self).__init__()
        self.emb_size = emb_size
        self.num_de = num_de
        self.num_encoders = num_encoders

        self.num_heads = num_heads
        # self.de_embedding = Embedding(num_en,emb_size,zero_pad=True,scale=True)
        self.en_embedding = Embedding(num_de,emb_size,zero_pad=True,scale=True).to(device)
        self.en_positional = Posting_embedding(emb_size,zero_pad=False,scale=False).to(device)

        for h in range(self.num_encoders):
            setattr(self,"encoder_"+str(h),Encoder_Layer(num_heads, emb_size).to(device))

    def forward(self,x):
        # Embedding部分
        self.enc = self.en_embedding(x)
        self.enc += self.en_positional(x)

        # 多个Encoder——layer部分
        for i in range(self.num_encoders):
            self.enc = getattr(self,"encoder_"+str(i))(self.enc,self.enc)

        return self.enc

class Decoder_Layer(nn.Module):
    def __init__(self,num_heads,emb_size):
        super(Decoder_Layer, self).__init__()
        self.emb_size = emb_size
        self.hidden=[4*emb_size,emb_size]
        self.num_heads = num_heads
        self.attention =  torch.nn.ReLU()
        self.liner1 = nn.Linear(self.emb_size, self.hidden[0], bias=True)
        self.liner2 = nn.Linear(self.hidden[0], self.hidden[1], bias=True)
        #self-attention
        self.attention1=Multihead_attention(emb_size, num_heads, causality = True).to(device)
        #encoder-decoder attention
        self.attention2=Multihead_attention(emb_size, num_heads, causality = False).to(device)

    def feedFworad(self,x):
        outputs = self.activation(self.liner1(x))
        outputs = self.liner2(outputs)
        #残差连接
        outputs +=x
        outputs = torch.normal(outputs)
        return outputs

    def forward(self,dec,enc):
        # self-attention部分
        outputs = self.attention1(dec,dec)
        # encoder-decoder attention
        outputs = self.attention2(outputs,enc)
        #feed Forward部分
        return self.feedFworad(outputs)

class Decoder(nn.Module):
    def __init__(self,num_en,num_decoders,emb_size,num_heads=8):
        super(Decoder, self).__init__()
        self.emb_size = emb_size
        self.num_en = num_en
        self.num_decoders = num_decoders

        self.num_heads = num_heads
        # self.de_embedding = Embedding(num_en,emb_size,zero_pad=True,scale=True)
        self.dec_embedding = Embedding(num_en,emb_size,zero_pad=True,scale=True).to(device)
        self.dec_positional = Posting_embedding(emb_size,zero_pad=False,scale=False).to(device)

        for h in range(self.num_decoders):
            setattr(self,"encoder_"+str(h),Encoder_Layer(num_heads, emb_size).to(device))

    def forward(self,x,enc):
        # Embedding部分
        self.dec = self.dec_embedding(x)
        self.dec += self.dec_positional(x)

        for h in range(self.num_decoders):
            self.dec = getattr(self, "encoder_" + str(h))(self.dec,enc)

        return self.dec

class Transformer(nn.Module):
    def __init__(self,num_en,num_de,emb_size):
        super(Transformer, self).__init__()
        self.num_de = num_de
        self.num_en = num_en
        self.encoder = Encoder(num_de,num_encoders=6,emb_size=emb_size).to(device)
        self.decoder = Decoder(num_en,num_decoders=6,emb_size=emb_size).to(device)

        self.logits = nn.Linear(emb_size,num_en)

    def forward(self,x,dec_inpt):

        enc = self.encoder(x)
        dec = self.decoder(dec_inpt,enc)
        logits = self.logits(dec)

        preds = torch.argmax(logits,-1).int()
        return logits,preds


import sqlite3
from datamanager import DataManager

#turunan dari kelas data manager
class Person(DataManager):
	# untuk memasukkan data baru ke tabel person
	def setDataPerson(self, Nama, Alamat, NomorHP):
		# querynya insert val parameter nama, alamat, nohp
		self.query = 'INSERT INTO Person (Nama, Alamat, NomorHP) \
			VALUES (\'%s\', \'%s\', \'%s\')'
		self.query = self.query % (Nama, Alamat, NomorHP) #untuk menampilkan value
		#untuk menampilkan dilayar
		print('self.query : ', self.query )
		#diambil dari datamanager, jdi tidak perlu di declare lagi (execute query)
		self.executeQuery(self.query) #mengeksekusi query

	# untuk mendapatkan data
	def getDataPerson(self, Nama, Alamat, NomorHP):
		# menghasilkan output 1 data dan dimasukkan ke var idperson
		self.query = 'SELECT IdPerson FROM Person \
			where Nama=\'%s\' and Alamat=\'%s\' and NomorHP=\'%s\'' #yg ada di parameter
		self.query = self.query % (Nama, Alamat, NomorHP) #diambil dri parameter
		print('self.query : ', self.query )
		IdPerson = self.executeQuery(self.query, retVal=True) #krn ada hasil query ada 1 yaitu idperson maka dia dimasukan ke var idperson, value true krn ada data yg dihasilkan
		return IdPerson


#!/usr/bin/env python3

import rospy
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Odometry, OccupancyGrid
from project_reqs.msg import CustomMsg
import numpy as np

resolution = 0.1
MAP_WIDTH,MAP_HEIGHT = 2000, 2000
hits = np.full((MAP_WIDTH,MAP_HEIGHT), 1)
misses = np.full((MAP_WIDTH,MAP_HEIGHT), 1)
map = np.zeros((MAP_WIDTH,MAP_HEIGHT))

def hit_miss(robot_x, robot_y, robot_theta, angle_min, angle_increment, range_min, range_max,laser_ranges):
    global hits, misses, map
    # convert robot space to map space
    robot_x = robot_x + 50
    robot_y = robot_y + 50
    robot_x_int = int(robot_x/resolution)
    robot_y_int = int(robot_y/resolution)

    for i in range(len(laser_ranges)):
        if laser_ranges[i] < range_min or laser_ranges[i] > range_max :
            continue

        # calculate the end of point of the laser from the robot
        end_x = robot_x_int + laser_ranges[i]/resolution * np.cos(robot_theta + angle_min + i * angle_increment)
        end_y = robot_y_int + laser_ranges[i]/resolution * np.sin(robot_theta + angle_min + i * angle_increment)
        end_x = int(end_x)
        end_y = int(end_y)

        if end_x < 0 or end_x >= MAP_WIDTH or end_y < 0 or end_y >= MAP_HEIGHT:
            continue
        hits[end_y,end_x] = hits[end_y,end_x] + 10

        # calculate the distance between the end point and the robot
        dx = end_x - robot_x_int
        dy = end_y - robot_y_int
        dist = np.sqrt(dx**2 + dy**2)
        # divide the difference between the end point and the robot by the distance to get the step size
        # supose we have the the robot at (0,0) and the end point at (4,3)
        # the distance is 5 and the difference is (dx = 4, dy = 3)
        # to get the step size we divide the difference(dx, dy) by the distance 5 we got step size (dx = 4/5, dy = 3/5)
        dx/=dist
        dy/=dist
        # truncate the arrays to the same length
        pointx = np.arange(robot_x_int, end_x-dx, dx+0.001)
        pointy = np.arange(robot_y_int, end_y-dy, dy+0.001)
        min_len = min(len(pointx),len(pointy))
        pointx = pointx[:min_len]
        pointy = pointy[:min_len]
        pointx = pointx.astype(int)
        pointy = pointy.astype(int)
        misses[pointy,pointx] += 5

    map = hits / (hits + misses)
    map = map * 100
    map = map.astype(int)
    return map

def callback(CustomMsg):
    sm_msg = CustomMsg.sm
    nm_msg = CustomMsg.nm.pose.pose
    # Yaw = atan2(2(wz + xy), 1 - 2(y^2 + z^2)))
    Yaw = np.arctan2(2*(nm_msg.orientation.w*nm_msg.orientation.z + nm_msg.orientation.x*nm_msg.orientation.y), 1 - 2*(nm_msg.orientation.y**2 + nm_msg.orientation.z**2))
    map = hit_miss(nm_msg.position.x, nm_msg.position.y, Yaw, sm_msg.angle_min, sm_msg.angle_increment, sm_msg.range_min, sm_msg.range_max, sm_msg.ranges)

    occgrid = OccupancyGrid()
    occgrid.header = CustomMsg.nm.header
    # We think it is the time of the sent frame
    occgrid.header.stamp = rospy.Time()
    # We think it is the sequence of the sent frame
    occgrid.header.seq = 0
    # it the needed for the map to be displayed in rviz, so it can transformed to the robot frame
    occgrid.header.frame_id = 'robot_map'
    occgrid.info.resolution = resolution
    occgrid.info.width = MAP_WIDTH
    occgrid.info.height = MAP_HEIGHT
    occgrid.info.origin.position.x = -50
    occgrid.info.origin.position.y = -50
    # 0 -> free space, 100 -> occupied space
    occgrid.data = map.flatten().tolist()
    pub.publish(occgrid)

if __name__ == '__main__':
    try:
        rospy.init_node('mapping')
        rospy.loginfo('Starting Mapping node ...')
        # publisher to the sensor topic '/sensor_topic'
        pub = rospy.Publisher('/map_topic', OccupancyGrid, queue_size=1)
        # subscribing to the laser scan and odometry topics
        sub = rospy.Subscriber('/sensor_topic', CustomMsg, callback)
        rospy.spin()

    except rospy.ROSInterruptException:
        rospy.loginfo('Shutting down Mapping node')


import json

with open('Datasets/source-data.json') as aj:
    read_content = json.load(aj)

save_data = []

def data_access():

    question_access = read_content['results']
    for question_data in question_access:
        #print(question_data)
        replies_access = question_data['replies']
        for replies_data in replies_access:
            #print(replies_data)
            user_data = replies_data['user']['display_name']
            #print(user_data)
            save_data.append(user_data)

def save_file():
    with open('new_user_name.json', 'w') as file:
        json.dump(save_data, file)

data_access()
save_file()

who = 2
print(save_data[who])


from tkinter import *
import re

notes_lines_list = []
string_list_val = []
relevant_string_list_val = []
notes_list = []
notes_subject_list = []
merged_list = []
color_list = []
bool_val = False
list_length = 0
result = 0

root=Tk()
root.geometry('800x600')

def retrieve_input():
    global bool_val
    global string_list_val
    inputValue=textBox.get("1.0","end-1c")
    if inputValue:
        print("IV ", inputValue)
        string_list_val = inputValue.splitlines()
        for index in range(0,len(string_list_val)):
            if 'Pflichtfächer:' in string_list_val[index]:
                bool_val = True
            if bool_val:
                relevant_string_list_val.append(string_list_val[index])

        search_notes_and_subjects(relevant_string_list_val)
        select_subject_names()
        merge_lists()
        get_length()
        get_average()
        select_color()
        print(list_length)
        display_result()
    reset()

def reset():
    global notes_lines_list
    global string_list_val
    global relevant_string_list_val
    global notes_subject_list
    global merged_list
    global bool_val
    global list_length
    global result
    notes_lines_list = []
    string_list_val = []
    relevant_string_list_val = []
    notes_list = []
    notes_subject_list = []
    merged_list = []
    color_list = []
    bool_val = False
    list_length = 0
    result = 0

def search_notes_and_subjects(relevant_string_list_val):
    global notes_subject_list
    global notes_list
    subject_index = 0
    for index in range(0,len(relevant_string_list_val)):
        if re.search('^(\d{2}\s\w{2,})(\s)*(\w)*(\s)*\d{5,}\t(.*\s{1})*\t$', relevant_string_list_val[index]):
            subject_index = index
            for index in range(index,len(relevant_string_list_val)):
                if 'SL ' in relevant_string_list_val[index]:
                    break
                elif 'PL ' in relevant_string_list_val[index]:
                    string_val = relevant_string_list_val[index+2]
                    if ' ' in string_val and ',' in string_val and len(string_val) == 4:
                        string_val_without_whitespaces = string_val.replace(" ", "")
                        string_val_without_comma = string_val_without_whitespaces.replace(',','.')
                        note_val = float(string_val_without_comma)
                        notes_list.append(note_val)
                        notes_subject_list.append(relevant_string_list_val[subject_index])
                        break

def select_subject_names():
    global notes_subject_list
    list_val = []
    for subject in notes_subject_list:
        line = re.sub("^(\d{2}\s\w{2,})(\s)*(\w)*(\s)*\d{5,}\t", "", subject)
        result_subject_name_val = re.sub("\t", "", line)
        result_subject_name = result_subject_name_val.rstrip()
        list_val.append(result_subject_name)
    notes_subject_list = list_val

def merge_lists():
    global merged_list
    global notes_list
    global notes_subject_list
    for index in range(0,len(notes_subject_list)):
        merged_list.append(notes_subject_list[index])
        try:
            merged_list.append(notes_list[index])
        except IndexError:
            break

def get_length():
    global list_length
    if len(notes_list) == len(notes_subject_list):
        list_length = len(notes_list)

def get_average():
    global notes_list
    global result
    sum = 0
    for note in notes_list:
        sum = sum + note
    result = sum / len(notes_list)

def select_color():
    global notes_list
    global color_list
    for note in notes_list:
        if note <= 2.3:
            color_list.append('green')
        elif note >= 2.7 and note <= 3.3:
            color_list.append('orange')
        elif note >= 3.3 and note <= 4.0:
            color_list.append('red')

def display_result():
    list_x_vals = [410, 750]
    list_entry_width = [55, 5]
    y_val = 5
    index_merged_list = 0
    index_color_list = 0
    for i in range(0, list_length):
        for j in range(2):
            e = Entry(relief=GROOVE, width=list_entry_width[j], background=color_list[index_color_list])
            e.place(x=list_x_vals[j], y=y_val)
            e.insert(END, merged_list[index_merged_list])
            index_merged_list = index_merged_list + 1
        y_val = y_val + 20
        index_color_list = index_color_list + 1
    durchschnitt_label = Label(root, text="Durchschnitt: ")
    durchschnitt_label.place(x=1, y=450)
    durchschnitt_result_label = Label(root, text=round(result,2), )
    durchschnitt_result_label.place(x=80, y=450)

textBox=Text(root, height=25, width=50)
textBox.place(x=0, y=0)
buttonCommit=Button(root, height=1, width=56, text="Calc",
                    command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.place(x=1, y=410)

mainloop()


import unittest
from models.base import Base
from models.rectangle import Rectangle
import io
import sys
"""tests the subclass Rectangle"""

class testRectangleClass(unittest.TestCase):
    """test whether the rectangle is an instance of the Base class"""
    def test_rect_instances(self):
        r1 = Rectangle(10, 2)
        self.assertIsInstance(Rectangle(10, 2), Base)
        r2 = Rectangle(2, 10)
        self.assertIsInstance(Rectangle(2, 10), Base)
        r3 = Rectangle(10, 2, 0, 0, 12)
        self.assertIsInstance(Rectangle(10, 2, 0, 0, 12), Base)

    """test for type & value errors in the attributes"""
    def test_for_errors(self):
        self.assertRaises(Exception)

    """test the values used to calculate area"""
    def test_area(self):
        r1 = Rectangle(3, 2)
        self.assertEqual(r1.area(), 6)
        r2 = Rectangle(2, 10)
        self.assertEqual(r2.area(), 20)
        r3 = Rectangle(8, 7, 0, 0, 12)
        self.assertEqual(r3.area(), 56)

class testStdout(unittest.TestCase):
    """test that actual output is equal to actual"""

    @staticmethod
    def capture_output(rect, method):
        capture = io.StringIO()
        sys.stdout = capture
        if method == "print":
            print(rect)
        else:
            rect.display()
        sys.stdout = sys.__stdout__
        return (capture)

    """print # in stdout"""
    def test_display(self):
        r1 = Rectangle(4, 6)
        capture = testStdout.capture_output(r1, "display")
        self.assertEqual("####\n####\n####\n####\n####\n####\n", capture.getvalue())
        r2 = Rectangle(2, 2)
        capture = testStdout.capture_output(r2, "display")
        self.assertEqual("##\n##\n", capture.getvalue())

    """test the string representation of Rectangle"""
    def test_str(self):
        r1 = Rectangle(4, 6, 2, 1, 12)
        capture = testStdout.capture_output(r1, "print")
        correct = "[Rectangle] (23) 2/1 - 4/6\n".format(r1.id)
        r2 = Rectangle(5, 5, 1)
        capture = testStdout.capture_output(r1, "print")
        correct = "[Rectangle] (12) 2/1 - 4/6\n".format(r2.id)
        self.assertEqual(correct, capture.getvalue())
        r1 = Rectangle(10, 2, 1, 9)
        capture = testStdout.capture_output(r1, "print")
        correct = "[Rectangle] (1) 1/9 - 10/2\n".format(r1.id)

    """test display with x and y included"""
    def test_dislayOne(self):
        r1 = Rectangle(2, 3, 2, 2)
        capture = testStdout.capture_output(r1, "display")
        self.assertEqual("\n\n  ##\n  ##\n  ##\n", capture.getvalue())
        r2 = Rectangle(3, 2, 1, 0)
        capture = testStdout.capture_output(r2, "display")
        self.assertEqual(" ###\n ###\n", capture.getvalue())

    """test for updated arguments"""
    def test_updates(self):
        r1 = Rectangle(10, 10, 10, 10)
        capture = testStdout.capture_output(r1, "print")
        correct = "[Rectangle] (19) 10/10 - 10/10\n".format(r1.id)
        self.assertEqual(correct, capture.getvalue())
        r1 = Rectangle(10, 10, 10, 10)
        r1.update(89)
        self.assertEqual("[Rectangle] (89) 10/10 - 10/10", str(r1))
        r1 = Rectangle(10, 10, 10, 10)
        r1.update(89, 2)
        self.assertEqual("[Rectangle] (89) 10/10 - 2/10", str(r1))
        r1 = Rectangle(10, 10, 10, 10)
        r1.update(89, 2, 3)
        self.assertEqual("[Rectangle] (89) 10/10 - 2/3", str(r1))
        r1 = Rectangle(10, 10, 10, 10)
        r1.update(89, 2, 3, 4)
        self.assertEqual("[Rectangle] (89) 4/10 - 2/3", str(r1))
        r1 = Rectangle(10, 10, 10, 10)
        r1.update(89, 2, 3, 4, 5)
        self.assertEqual("[Rectangle] (89) 4/5 - 2/3", str(r1))

    """test for kwargs"""
    def test_kwargs(self):
        r1 = Rectangle(10, 10, 10, 10)
        capture = testStdout.capture_output(r1, "print")
        correct = "[Rectangle] (1) 10/10 - 10/10\n".format(r1.id)
        r1.update(height=1)
        self.assertEqual("[Rectangle] (16) 10/10 - 10/1", str(r1))
        r1.update(width=1, x=2)
        self.assertEqual("[Rectangle] (16) 2/10 - 1/1", str(r1))
        r1.update(y=1, width=2, x=3, id=89)
        self.assertEqual("[Rectangle] (89) 3/1 - 2/1", str(r1))
        r1.update(x=1, height=2, y=3, width=4)
        self.assertEqual("[Rectangle] (89) 1/3 - 4/2", str(r1))

class testDictionary:
    """tests the dictionary representation of the Rectangle"""
    def test_dictionary(self):
        r1 = Rectangle(10, 2, 1, 9)
        correct = {'x': 1, 'y': 9, 'id': 1, 'height': 2, 'width': 10}
        self.assertDictEqual(correct, r1.to_dicionary)

    """test for rectangle that fails to convert to dictionary representation"""
    def test_dictWithNoChange(self):
        r1 = (10, 2, 1, 9)
        r2 = Rectangle(1, 1)
        r2.update(**r1_dictionary())
        self.assertNotEqual(r1, r2)

    """testing the args in the dictionary"""
    def test_dictArg(self):
        r1 = (10, 2, 1, 9)
        with self.assertRaises(TypeError):
            r.to_dictionary(1)

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


import matplotlib.pyplot as plt

"""
x = [24.45,44.45,47.36,51.795]
y = [0.351,0.162,0.175,0.1076]
plt.plot(x, y, label = "line 1")
"""
#neu
x = [44.77,57.11,59.06,62.57]
y = [0.351,0.162,0.175,0.1076]
plt.plot(x, y, label = "Relationship GTM score and detection accuracy")

x1 = [44.77,62.57]
y1 = [0.35,0.11]
plt.plot(x1, y1, label = "line 2")
##

"""
x1 = [24.45,51.795]
y1 = [0.350,0.1145]
plt.plot(x1, y1, label = "line 2")
"""
plt.axhline(y=0.24, color='r', linestyle='--',label='GTM when score labeling from scratch')
plt.axvline(x=52.82, ymax = 0.54, color='b',label='hintern',linestyle=':')
# naming the x axis
plt.xlabel('detection accuracy')
# naming the y axis
plt.ylabel('GTM score')

# giving a title to my graph
plt.title('Relationship between detection accuracy and ground truth quality')
#plt.legend()

# function to show the plot
plt.show()


def productExSelf(nums):
    res = [1] * len(nums)

    pre_fix = 1

    for i in range(len(nums)):
        res[i] =  pre_fix
        pre_fix = pre_fix*nums[i]

    post_fix = 1
    for i in range(len(nums)-1, -1 , -1):
        res[i] = res[i]*post_fix
        post_fix = post_fix*nums[i]
    return res

#prefix ber korse, r akane kno number er prefix mane oi number er age porjonto number er gun, r atake store kora hoi current number er niche

#tarpor postfix a kno number er er porer number teke sesh number porjonto gun foler sateh prefix er gun e ans

# arr = [1,2,3,4]

# print(productExSelf(arr))

def maxSubArr(nums):
    m = nums[0]
    total = 0
    for num in nums:
        if total < 0:
            total = 0
        total+=num

        m = max(m, total)

    return m

# protibar add houar somoi max value er sathe compare kora hoi.

arr = [-2, 1,-3, 4, -1, 2, 1, -5, 4]

# print(maxSubArr(arr))

def climbing_stairs(n):
    if n == 0:
        return 1
    if n < 0 :
        return 0

    res = 0

    res+= climbing_stairs(n-1)
    res+= climbing_stairs(n-2)
    return res

# print(climbing_stairs(4))
total = 5
arr = [1,2,5]

# total = 100
# arr = [3,5,7,8,9,10,11]

def coinEx(amount, coins):
    memo = {}

    def helper(amount , coins, index):
        if amount == 0:
            return 1
        if amount < 0 or index == len(coins):
            return 0

        key = str(amount) + "mridul" + str(index)
        if key in memo:
            return memo[key]

        res = 0
        for i in range(index,len(coins)):
            if amount>= coins[i]:
                res+=helper(amount-coins[i], coins, i)
        memo[key] = res

        return res

    return helper(amount, coins, 0)

# print(coinEx(total,arr))

# def coinEx(amount, coins):
#     memo = {}

#     def helper(amount , coins, index):
#         if amount == 0:
#             return 1
#         if amount < 0 or index == len(coins):
#             return 0

#         key = str(amount) + "mridul" + str(index)

#         if key in memo:
#             return memo[key]

#         res = 0
#         i = index
#         while i < len(coins):
#             if amount>= coins[i]:
#                 res+=helper(amount-coins[i], coins, i)
#             i+=1

#         memo[key] = res

#         return res

#     # print(memo)

#     return helper(amount, coins, 0)-1

# print(coinEx(total,arr))

def fac(n):
    if n == 1 or n == 0:
        return 1
    res = 0

    print(n)
    res+=  n * fac(n-1)
    return res

# print(fac(3))

# print(18/0)

arr = [10,9,2,5,3,7,101,18]

def lis(nums):
    def helper(i):
        ans = 1
        j = 0
        while j < i:
            if nums[j]<nums[i]:
                ans=max(ans, helper(j)+1)
            j+=1
        return ans

    ans = 0

    for i in range(len(nums)):
        ans = max(ans, helper(i))
    return ans

# print(lis(arr))

# s = "leetcode"
# wordDict = ["leet","code"]

# s = "applepenapple"
# wordDict=["apple","pen"]

# s = "bccdbacdbdacddabbaaaadababadad"
# wordDict=["cbc","bcda","adb","ddca","bad","bbb","dad","dac","ba","aa","bd","abab","bb","dbda","cb","caccc","d","dd","aadb","cc","b","bcc","bcd","cd","cbca","bbd","ddd","dabb","ab","acd","a","bbcc","cdcbd","cada","dbca","ac","abacd","cba","cdb","dbac","aada","cdcda","cdc","dbc","dbcb","bdb","ddbdd","cadaa","ddbc","babb"]

# def word_break(s, wordDict):
#     map = {}
#     def helper(i):
#         if i == len(s):
#             return True

#         if i > len(s):
#             return False
#         if i in map:
#             return map[i]

#         res = False
#         for word in wordDict:
#             word_length = len(word)
#             # print("word is ",word)
#             # print("substring is ",s[i:][:word_length])
#             if word == s[i:][:word_length]:
#                 if helper(i+word_length):
#                     res = True

#         pass
#         map[i] = res
#         return res

#     return helper(0)

# print(word_break(s, wordDict))

a = [2,3,6,7]
t = 7

def combinationSum(candidates, target):
    res = []

    def helper(total,rarr, index):

        if total == target:
            res.append(rarr)

        if total > target:
            return

        for i in range(index,len(candidates)):
            if candidates[i] <= target:
                helper(total+candidates[i], rarr+[candidates[i]], i)

    helper(0,[],0)

    return res

# print(combinationSum(a,t))

# print([3]+[2])

# nums = [1,2,3,1]
# for i in range(0,len(nums),1):
#     print(nums[i])

n = [1,2,3,1]

# n = [2,7,9,3,1]

def rob(nums):

    def helper(index,step, depth, ar):
        if depth == len(nums)-1:
            # print("depth is ", depth)
            # print("nums is", nums[index])
            # return nums[index]
            print(ar, sum(ar))
            return sum(ar)

        s = 0

        if not (index % 2 == 0):
            s = 1

        res = 0
        for i in range(s,len(nums),step):
            # print(nums[i])
            # if not (i == index):
            r = helper(i, 2, depth+1, ar+[nums[i]])
            # print("total is ", r)
            res = max(res, r)

        return res

    return helper(0,1,1,[])

# print(rob(n))

coins = [1,2,5]

amount = 11

coins = [1,2]
amount = 3

def coinChange(coins, amount):

    dp = {}
    def helper(amount, branch):

        if amount == 0:
            return 0

        if amount in dp:
            return dp[amount]

        res = float("+inf")
        for coin in coins:
            if amount - coin >= 0:
                res = min(res, helper(amount - coin, branch + [coin])+1)

        dp[amount] = res
        return res

    return helper(amount,[])

# print(coinChange(coins, amount))

s = "leetcode"
w = "leet"

# print(s[4:][:len(w)])
# print(s[4:][:3])
# print(s[4:])

# ami jei rokom chai ai rokom recursion banano lagbe

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, val):

        newNode = Node(val)

        if self.head == None:
            self.head =  newNode
        else:
            tempt = self.head
            while tempt:
                lastNode = tempt
                tempt = tempt.next
            lastNode.next = newNode

    def appendArr(self, arr):
        for item in arr:
            self.append(item)

    def returnHead(self):
        return self.head

    def printLinkList(self):

        printVal = self.head
        while printVal is not None:
            print(printVal.val)
            printVal = printVal.next

ll = LinkedList()

ll.appendArr(range(10))

# ll.printLinkList()

print(ll.returnHead().val)

# print()


#!/usr/bin/env python
#  coding=utf-8
#!C:\Python27\python.exe

from k8s import Connection
from kuby import Kuby
import argparse

class Main():

    def get_args():

        parser = argparse.ArgumentParser()

        parser.add_argument('--server',
                            required=True,
                            action='store',
                            help='Server Address')

        parser.add_argument('--token',
                            required=True,
                            action='store',
                            help="ApiToken")

        parser.add_argument('--namespace',
                            required=False,
                            action='store',
                            help="Namespace")

        args = parser.parse_args()

        return args

    args = get_args()
    k8s = Kuby(args.server,args.token)
    '''
    result = k8s.getNamespaces()
    if result == False:
        print("Error")
    else:
        for i in result:
            print(i)
    result = k8s.getNamespacesDetails("default")
    if result == False:
        print("Error")
    else:
        for i in result:
            print(i)
        print(result)

    #result = k8s.getPodLog("","")
    result = k8s.getPodContainers("","")
    if result == False:
        print("Error")
    else:
        for i in result:
            print(i)
    '''
    result = k8s.getPodLog("","","")
    if result == False:
        print("Error")
    else:
        print(result)
    result = k8s.getPodContainers("", "")
    if result == False:
        print("Error")
    else:
        for i in result:
            print(i)


import copy

playerX = "X"
playerO = "O"
playerEmpty ="-"

class GameState(object):
    player=""
    curBoardNumber=0
    lastMove=0
    lastBoardNumber=0
    boards= [[playerEmpty for x in range(1,10)] for o in range(1,10)]
    xPlayerScore=0
    oPlayerScore=0

    def setPlayer(self,player):
        self.player=player

    def move(self,board,move, me):
        if board == None:
            board = self.curBoardNumber

        xbefore = self.score(board,playerX)
        obefore = self.score(board,playerO)

        if me:
            self.boards[board-1][move-1]= self.player
        elif self.player == playerO:
            self.boards[board-1][move-1]= playerX
        else:
            self.boards[board-1][move-1]= playerO

        xafter = self.score(board,playerX)
        oafter = self.score(board,playerO)

        difx= xafter-xbefore
        difo = oafter-obefore

        self.xPlayerScore +=difx
        self.oPlayerScore+=difo

        self.lastMove=move
        self.lastBoardNumber=board
        self.curBoardNumber=move

    def score(self,board,player):
        score =0
        winners=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]

        for combos in winners:
            count =0
            for i in combos:
                if self.boards[board-1][i]==player:
                    count+=1
                elif self.boards[board-1][i]!=playerEmpty:
                    count-=2
            if count ==3:
                score +=10000
            elif count==2:
                score +=10
            elif count==1:
                score+=3

        return score

    def checkLegalMove(self,move):
        return self.boards[self.curBoardNumber-1][move-1]==playerEmpty

    def getMoves(self):
        moves=[]
        for i in range(1,10):
            if self.checkLegalMove(i):
                moves.append(i)
        return moves

    def getScore(self):
        if self.player == playerX:
            return self.xPlayerScore-self.oPlayerScore
        else:
            return self.oPlayerScore-self.xPlayerScore

    def __copy__(self):
        copied = GameState()
        copied.player = copy.deepcopy(self.player)
        copied.curBoardNumber=copy.deepcopy(self.curBoardNumber)
        copied.lastMove=copy.deepcopy(self.lastMove)
        copied.lastBoardNumber=copy.deepcopy(self.lastBoardNumber)
        copied.boards= copy.deepcopy(self.boards)
        copied.xPlayerScore=copy.deepcopy(self.xPlayerScore)
        copied.oPlayerScore=copy.deepcopy(self.oPlayerScore)
        return copied

    def nextBoard(self,me,move):
        newB = copy.copy(self)
        newB.move(move,self.curBoardNumber,not me)
        return newB

    def isEnd(self):
        winners=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
        for i in range(9):
            for combo in winners:
                xcount =0
                ocount =0
                for j in combo:
                    if self.boards[i][j]==playerX:
                        xcount = xcount +1
                    elif self.boards[i][j]==playerO:
                        ocount = ocount +1
                if ocount ==3 or xcount ==3:
                    print('Somones won')
                    return True
        return False


from zugubul.models.infer import infer

from pympi import Elan

def test_infer_lid():
    wav_fp = r'C:\projects\zugubul\tests\wavs\test\test.wav'
    model_path = 'markjosims/wav2vec2-large-mms-1b-tira-lid'

    eaf = infer(wav_fp, model_path, inference_method='local')

    annotations = eaf.get_annotation_data_for_tier('default-lt')

    for a in annotations:
        assert a[2] in ('ENG', 'TIC')


'''
Create a class called Circle. Upon initialization, it should receive a radius (number). Create a class attribute called pi which should be equal to 3.14. Create 3 instance methods:
-	set_radius(new_radius) - changes the radius
-	get_area() - returns the area of the circle
-	get_circumference() - returns the circumference of the circle

'''

class Circle:
    pi = 3.14

    def __init__(self, radius):
        self.radius = radius

    def set_radius(self, new_radius):
        self.radius = new_radius

    # better clearly define that pi is a class attribute
    def get_area(self):
        area = self.radius * self.radius * Circle.pi
        return area

    def get_circumference(self):
        return 2 * Circle.pi * self.radius

circle = Circle(10)
circle.set_radius(12)
print(circle.get_area())
print(circle.get_circumference())

# each inatance has its own radius
circle_2 = Circle(50)
print(circle.radius)    # 12
print(circle_2.radius)  # 50

# the class attribute for the two instances is the same
print(circle.pi)    # 3.14
print(circle_2.pi)  # 3.14

# UNLIKE instance attributes, class attributes can be accessed via the class as well
print(Circle.pi)        # 3.14
print(Circle.radius)    # throws attribute error


# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3618/

#  Concatenation of Consecutive Binary Numbers
# Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.

# Example 1:

# Input: n = 1
# Output: 1
# Explanation: "1" in binary corresponds to the decimal value 1.
# Example 2:

# Input: n = 3
# Output: 27
# Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
# After concatenating them, we have "11011", which corresponds to the decimal value 27.

class Solution:
    def concatenatedBinary(self, n: int) -> int:
        modulo = 1000000007
        result = 0
        offset =0
        for i in range(1,n+1):
            while (1<< offset) <= i :
                offset+=1
            result = result<<offset
            result+= i
            result %= modulo
        return result

s = Solution()
for n in [1,3,12,32]:
    print(n, s.concatenatedBinary(n))


# medidas

desviacion = 0.0
neumedicion = 0.0
peso_ideal = 1545.5
munidad = 0
mmedicion = 0
moperador = 0
band = 0

arch = open('medi.txt','r')
arch2 = open('MedidasDesviadas.txt', 'w')
arch3 = open('MedidasAceptadas.txt', 'w')

N = arch.readline()

for registro in arch:
    linea = registro.split(',')
    print(linea)

    Numero_operador = linea[0]
    print('Número del Operador:', Numero_operador)
    Medicion = float(linea[1])
    print('Medición Registrada:', Medicion)
    unidad_medicion = linea[2].rstrip("\n")
    print('Unidad de Medición Utilizada:', unidad_medicion)

    if unidad_medicion == ' l':
        neumedicion = float((Medicion * 0.4536) * 1000)
        print('%.2f' % neumedicion)

    if unidad_medicion == ' k':
        neumedicion = float(Medicion * 1000)
        print('%.2f' % neumedicion)

    desviacion = ((peso_ideal - neumedicion) / peso_ideal) * 100
    print('%.2f' % desviacion)

    if band == 0:
        mpordesviacion = desviacion
        munidad = unidad_medicion
        moperador = Numero_operador
        mmedicion = Medicion
        band = 1

    if desviacion > mpordesviacion:
        mpordesviacion = desviacion
        munidad = unidad_medicion
        moperador = Numero_operador
        mmedicion = Medicion

    if desviacion < 5:
        arch3.write(Numero_operador + ', ' + str(neumedicion) + 'g, ' + str(desviacion) + '% \n')
        print('Medida Aceptada: ', Numero_operador, ', ', neumedicion, ' g')

    else:
        arch2.write(Numero_operador + ', ' + str(neumedicion) + 'g, ' + str(neumedicion) + '% \n')
        print('Medida no Aceptada: ', Numero_operador, ', ', neumedicion, ' g')

arch.close()
arch2.close()
arch3.close()

print('Mayor porcentaje de desviacion: ', moperador, ', ', mmedicion, ', ', munidad)


import time
import os

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.common.by import By

os.environ['PATH'] += r"C:/Users/ASUS/Documents/pyprojects/seleniumdrivers"

url = "https://www.bbcgoodfood.com"

website = url.replace("https://www.", "")
website = website.replace(".com/", "")

driver = webdriver.Firefox()

driver.get(url)

# Wait for the cookie consent banner to be visible
driver.implicitly_wait(20)
alert = driver.switch_to.alert
alert.accept()
try:
    popup = driver.find_element(By.ID, 'notice')

    agree_button = popup.find_element(By.CSS_SELECTOR, 'button[title="AGREE"]')
    agree_button.click()

except Exception as e:
    print("An error occurred:", e)


import argparse
import os
import utils.utils as utils
import numpy as np
from PIL import Image
import shutil

def save_files(dst_path,files):

    src_path = files['root']
    file_type = files['file_type']

    for file in files['files']:
        src_f = os.path.join(src_path,file) + '.' + file_type
        #img = Image.open(src_f)
        dst_f = os.path.join(dst_path,file) + '.' + file_type
        shutil.copy(src_f, dst_f)
        #img.save(dst_f)

def match_file_pair(ref_files,src_files):
    indices,_ = match_file_pair_list(ref_files['files'],src_files['files'])
    ref_files_cp = ref_files.copy()
    src_files_cp = src_files.copy()
    src_files_cp['files'] = np.array(src_files['files'])[indices]
    return(ref_files_cp,src_files_cp)

def match_file_pair_list(ref_files,src_files):
    #  use sub_raster as reference
    matched_files = []
    indices = []
    for i,file in enumerate(src_files):
        if file in ref_files:
            matched_files.append(file)
            indices.append(i)

    return(indices,matched_files)

def main_set_selection(src_dir,ref_dir,dst_dir):

    if not os.path.isdir(src_dir):
        return(NameError)

    # Get src files
    src_files = utils.get_files(src_dir)
    ref_files = utils.get_files(ref_dir)

    # find positive masks
    ref_files,src_files = match_file_pair(ref_files,src_files)

    #Build destination path
    path_split = src_dir.split(os.sep)
    src_dir = os.sep.join(path_split[0:-1])
    src_dir= os.path.join(src_dir,'pos_' + path_split[-1])

    if not os.path.isdir(ref_dir):
        os.makedirs(ref_dir)

    if not os.path.isdir(src_dir):
        os.makedirs(src_dir)

    # Save files to dest dir
    save_files(src_dir,src_files)

if __name__=='__main__':

    # TEST_SAVE_SUB_IM()
    parser = argparse.ArgumentParser(description='Split and save sub tiff images')
    parser.add_argument('--src_dir',
                        default =  '/home/tiago/workspace/valdoeiro/x7_/dsm',
                        help='')
    parser.add_argument('--ref_dir',
                        default =  '/home/tiago/workspace/valdoeiro/x7_/pos_masks',
                        help='')
    parser.add_argument('--dest_dir',
                        default = 'changed',
                        help='')

    args = parser.parse_args()

    src_dir  = args.src_dir
    dest_dir = args.dest_dir
    ref_dir = args.ref_dir

    print("="*50)
    print("src file: %s"%(src_dir))
    print("Dest. directory: %s"%(dest_dir))
    print("ref file: %s"%(ref_dir))

    print("="*50)

    main_set_selection(src_dir,ref_dir,dest_dir)


# this script executes the virtualenv bootstrapping script.  Destination dir is projectroot/.venv
# requires python>=3.3
import os
import platform
import subprocess
import venv
import os.path
from subprocess import Popen, PIPE
import sys
from threading import Thread
from urllib.parse import urlparse
from urllib.request import urlretrieve

class ExtendedEnvBuilder(venv.EnvBuilder):
	#class imported from: https://gist.github.com/vsajip/4673395
    """
    This builder installs setuptools and pip so that you can pip or
    easy_install other packages into the created environment.

    :param nodist: If True, setuptools and pip are not installed into the
                   created environment.
    :param nopip: If True, pip is not installed into the created
                  environment.
    :param progress: If setuptools or pip are installed, the progress of the
                     installation can be monitored by passing a progress
                     callable. If specified, it is called with two
                     arguments: a string indicating some progress, and a
                     context indicating where the string is coming from.
                     The context argument can have one of three values:
                     'main', indicating that it is called from virtualize()
                     itself, and 'stdout' and 'stderr', which are obtained
                     by reading lines from the output streams of a subprocess
                     which is used to install the app.

                     If a callable is not specified, default progress
                     information is output to sys.stderr.
    """

    def __init__(self, *args, **kwargs):
        self.nodist = kwargs.pop('nodist', False)
        self.nopip = kwargs.pop('nopip', False)
        self.progress = kwargs.pop('progress', None)
        self.verbose = kwargs.pop('verbose', False)
        super().__init__(*args, **kwargs)

    def post_setup(self, context):
        """
        Set up any packages which need to be pre-installed into the
        environment being created.

        :param context: The information for the environment creation request
                        being processed.
        """
        os.environ['VIRTUAL_ENV'] = context.env_dir
        if not self.nodist:
            self.install_setuptools(context)

    def reader(self, stream, context):
        """
        Read lines from a subprocess' output stream and either pass to a progress
        callable (if specified) or write progress information to sys.stderr.
        """
        progress = self.progress
        while True:
            s = stream.readline()
            if not s:
                break
            if progress is not None:
                progress(s, context)
            else:
                if not self.verbose:
                    sys.stderr.write('.')
                else:
                    sys.stderr.write(s.decode('utf-8'))
                sys.stderr.flush()
        stream.close()

    def install_script(self, context, name, url):
        _, _, path, _, _, _ = urlparse(url)
        fn = os.path.split(path)[-1]
        binpath = context.bin_path
        distpath = os.path.join(binpath, fn)
        # Download script into the env's binaries folder
        urlretrieve(url, distpath)
        progress = self.progress
        if self.verbose:
            term = '\n'
        else:
            term = ''
        if progress is not None:
            progress('Installing %s ...%s' % (name, term), 'main')
        else:
            sys.stderr.write('Installing %s ...%s' % (name, term))
            sys.stderr.flush()
        # Install in the env
        args = [context.env_exe, fn]
        p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
        t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
        t1.start()
        t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
        t2.start()
        p.wait()
        t1.join()
        t2.join()
        if progress is not None:
            progress('done.', 'main')
        else:
            sys.stderr.write('done.\n')
        # Clean up - no longer needed
        os.unlink(distpath)

    def install_setuptools(self, context):
        """
        Install setuptools in the environment.

        :param context: The information for the environment creation request
                        being processed.
        """
        url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
        self.install_script(context, 'setuptools', url)
        # clear up the setuptools archive which gets downloaded
        pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
        files = filter(pred, os.listdir(context.bin_path))
        for f in files:
            f = os.path.join(context.bin_path, f)
            os.unlink(f)

## script
venv_name = '.venv'
venv_path = os.path.join(os.getcwd(), venv_name)

if platform.system() == 'Windows':
	bin = os.path.join(venv_path, 'Scripts')
	os.system('python -m venv {}'.format(venv_name))
else:
	builder = ExtendedEnvBuilder(clear=True, nopip=True)
	builder.create(venv_path)
	bin = os.path.join(venv_path, 'bin')
	easy_install = os.path.join(bin, 'easy_install')
	subprocess.call([easy_install, 'pip'])

print('installing packages')

pip = os.path.join(bin, 'pip')

subprocess.call([pip, 'install', '-r', 'requirements.txt'])


from functools import cache

# iterative dp solution
class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        l1, l2 = len(s1), len(s2)
        if l1 + l2 != len(s3):
            return False

        if l2 > l1:
            s1, l1, s2, l2 = s2, l2, s1, l1

        dp = [False] * (l2 + 1)
        dp[0] = True
        j = 0
        while j < l2 and s2[j] == s3[j]:
            dp[j + 1] = True
            j += 1

        for i in range(l1):
            new_dp = [False] * (l2 + 1)
            new_dp[0] = dp[0] and s1[i] == s3[i]
            for j in range(1, l2 + 1):
                new_dp[j] = (dp[j] and s1[i] == s3[i + j]) or (new_dp[j - 1] and s2[j - 1] == s3[i + j])
            dp = new_dp

        return dp[l2]

# recursive dp solution
class Solution2:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        l1, l2, l3 = len(s1), len(s2), len(s3)
        if l1 + l2 != l3:
            return False

        @cache
        def dp(i, j) -> bool:
            if i + j == l3:
                return True
            return ((i < l1 and s1[i] == s3[i + j] and dp(i + 1, j)) or
                    (j < l2 and s2[j] == s3[i + j] and dp(i, j + 1)))

        return dp(0, 0)

def main():
    sol = Solution()
    assert sol.isInterleave(s1="aabcc", s2="dbbca", s3="aadbbcbcac") is True
    print('Test 1 ... ok')
    assert sol.isInterleave(s1="aabcc", s2="dbbca", s3="aadbbbaccc") is False
    print('Test 2 ... ok')
    assert sol.isInterleave(s1="", s2="", s3="")

if __name__ == '__main__':
    main()


import logging
from typing import Any, MutableMapping, Optional
from cloudformation_cli_python_lib import (
    Action,
    HandlerErrorCode,
    OperationStatus,
    ProgressEvent,
    Resource,
    SessionProxy,
)

from datadog_api_client.v2 import ApiException
from datadog_api_client.v2.api.downtimes_api import DowntimesApi
from datadog_api_client.v2.model.downtime_create_request import DowntimeCreateRequest as DDDowntimeCreateRequest
from datadog_api_client.v2.model.downtime_create_request_attributes import (
    DowntimeCreateRequestAttributes as DDDowntimeCreateRequestAttributes,
)
from datadog_api_client.v2.model.downtime_create_request_data import (
    DowntimeCreateRequestData as DDDowntimeCreateRequestData,
)
from datadog_api_client.v2.model.downtime_monitor_identifier import (
    DowntimeMonitorIdentifier as DDDowntimeMonitorIdentifier,
)
from datadog_api_client.v2.model.downtime_monitor_identifier_id import (
    DowntimeMonitorIdentifierId as DDDowntimeMonitorIdentifierId,
)
from datadog_api_client.v2.model.downtime_monitor_identifier_tags import (
    DowntimeMonitorIdentifierTags as DDDowntimeMonitorIdentifierTags,
)
from datadog_api_client.v2.model.downtime_notify_end_state_actions import (
    DowntimeNotifyEndStateActions as DDDowntimeNotifyEndStateActions,
)
from datadog_api_client.v2.model.downtime_notify_end_state_types import (
    DowntimeNotifyEndStateTypes as DDDowntimeNotifyEndStateTypes,
)
from datadog_api_client.v2.model.downtime_resource_type import DowntimeResourceType as DDDowntimeResourceType
from datadog_api_client.v2.model.downtime_schedule_create_request import (
    DowntimeScheduleCreateRequest as DDDowntimeScheduleCreateRequest,
)
from datadog_api_client.v2.model.downtime_schedule_one_time_create_update_request import (
    DowntimeScheduleOneTimeCreateUpdateRequest as DDDowntimeScheduleOneTimeCreateUpdateRequest,
)
from datadog_api_client.v2.model.downtime_schedule_one_time_response import (
    DowntimeScheduleOneTimeResponse as DDDowntimeScheduleOneTimeResponse,
)
from datadog_api_client.v2.model.downtime_schedule_recurrence_create_update_request import (
    DowntimeScheduleRecurrenceCreateUpdateRequest as DDDowntimeScheduleRecurrenceCreateUpdateRequest,
)
from datadog_api_client.v2.model.downtime_schedule_recurrences_response import (
    DowntimeScheduleRecurrencesResponse as DDDowntimeScheduleRecurrencesResponse,
)
from datadog_api_client.v2.model.downtime_schedule_recurrences_update_request import (
    DowntimeScheduleRecurrencesUpdateRequest as DDDowntimeScheduleRecurrencesUpdateRequest,
)
from datadog_api_client.v2.model.downtime_status import DowntimeStatus as DDDowntimeStatus
from datadog_api_client.v2.model.downtime_update_request import DowntimeUpdateRequest as DDDowntimeUpdateRequest
from datadog_api_client.v2.model.downtime_update_request_attributes import (
    DowntimeUpdateRequestAttributes as DDDowntimeUpdateRequestAttributes,
)
from datadog_api_client.v2.model.downtime_update_request_data import (
    DowntimeUpdateRequestData as DDDowntimeUpdateRequestData,
)

from .version import __version__
from datadog_cloudformation_common.api_clients import client
from datadog_cloudformation_common.utils import errors_handler, http_to_handler_error_code
from .models import (
    MonitorIdentifier,
    Recurrences,
    ResourceHandlerRequest,
    ResourceModel,
    Schedule,
    TypeConfigurationModel,
)

# Use this logger to forward log messages to CloudWatch Logs.
LOG = logging.getLogger(__name__)
TYPE_NAME = "Datadog::Monitors::DowntimeSchedule"
TELEMETRY_TYPE_NAME = "monitors-downtime-schedule"

resource = Resource(TYPE_NAME, ResourceModel, TypeConfigurationModel)
test_entrypoint = resource.test_entrypoint

@resource.handler(Action.CREATE)
@errors_handler
def create_handler(
    session: Optional[SessionProxy],
    request: ResourceHandlerRequest,
    callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
    model = request.desiredResourceState
    type_configuration = request.typeConfiguration

    downtime = build_downtime_create_from_model(model)
    with client(
        type_configuration.DatadogCredentials.ApiKey,
        type_configuration.DatadogCredentials.ApplicationKey,
        type_configuration.DatadogCredentials.ApiURL,
        TELEMETRY_TYPE_NAME,
        __version__,
    ) as api_client:
        api_instance = DowntimesApi(api_client)
        try:
            resp = api_instance.create_downtime(downtime)
            model.Id = resp.data.id
        except ApiException as e:
            LOG.exception("Exception when calling DowntimesApi->create_downtime: %s\n", e)
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resourceModel=model,
                message=f"Error creating downtime: {e}",
                errorCode=http_to_handler_error_code(e.status),
            )

    return read_handler(session, request, callback_context)

@resource.handler(Action.UPDATE)
@errors_handler
def update_handler(
    session: Optional[SessionProxy],
    request: ResourceHandlerRequest,
    callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
    model = request.desiredResourceState
    type_configuration = request.typeConfiguration

    downtime = build_downtime_update_from_model(model)
    with client(
        type_configuration.DatadogCredentials.ApiKey,
        type_configuration.DatadogCredentials.ApplicationKey,
        type_configuration.DatadogCredentials.ApiURL,
        TELEMETRY_TYPE_NAME,
        __version__,
    ) as api_client:
        api_instance = DowntimesApi(api_client)
        try:
            resp = api_instance.update_downtime(model.Id, downtime)
        except ApiException as e:
            LOG.exception("Exception when calling DowntimesApi->update_downtime: %s\n", e)
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resourceModel=model,
                message=f"Error updating downtime: {e}",
                errorCode=http_to_handler_error_code(e.status),
            )

    return read_handler(session, request, callback_context)

@resource.handler(Action.DELETE)
@errors_handler
def delete_handler(
    session: Optional[SessionProxy],
    request: ResourceHandlerRequest,
    callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
    model = request.desiredResourceState
    type_configuration = request.typeConfiguration

    with client(
        type_configuration.DatadogCredentials.ApiKey,
        type_configuration.DatadogCredentials.ApplicationKey,
        type_configuration.DatadogCredentials.ApiURL,
        TELEMETRY_TYPE_NAME,
        __version__,
    ) as api_client:
        api_instance = DowntimesApi(api_client)

        try:
            resp = api_instance.get_downtime(model.Id)
            if resp.data.attributes.status == DDDowntimeStatus.CANCELED:
                # Return a 404 to indicate the downtime was already deleted
                return ProgressEvent(
                    status=OperationStatus.FAILED,
                    resourceModel=None,
                    message="Downtime {model.Id} already canceled",
                    errorCode=HandlerErrorCode.NotFound,
                )
        except ApiException as e:
            # Log error but continue in case of failure to get, this should not prevent the next call to delete
            LOG.exception("Exception when calling DowntimeApi->get_downtime: %s\n", e)

        try:
            api_instance.cancel_downtime(model.Id)
        except ApiException as e:
            LOG.exception("Exception when calling DowntimesApi->cancel_downtime: %s\n", e)
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resourceModel=model,
                message=f"Error canceling downtime: {e}",
                errorCode=http_to_handler_error_code(e.status),
            )

    return ProgressEvent(
        status=OperationStatus.SUCCESS,
        resourceModel=None,
    )

@resource.handler(Action.READ)
@errors_handler
def read_handler(
    session: Optional[SessionProxy],
    request: ResourceHandlerRequest,
    callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
    model = request.desiredResourceState
    type_configuration = request.typeConfiguration

    with client(
        type_configuration.DatadogCredentials.ApiKey,
        type_configuration.DatadogCredentials.ApplicationKey,
        type_configuration.DatadogCredentials.ApiURL,
        TELEMETRY_TYPE_NAME,
        __version__,
    ) as api_client:
        api_instance = DowntimesApi(api_client)
        try:
            resp = api_instance.get_downtime(model.Id)
        except ApiException as e:
            LOG.exception("Exception when calling DowntimesApi->get_downtime: %s\n", e)
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resourceModel=model,
                message=f"Error getting downtime: {e}",
                errorCode=http_to_handler_error_code(e.status),
            )

        # If downtime is disabled, return a NotFound error code to indicate so
        if resp.data.attributes.status == DDDowntimeStatus.CANCELED:
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resourceModel=model,
                message=f"downtime {model.Id} is canceled",
                errorCode=HandlerErrorCode.NotFound,
            )

        attributes = resp.data.attributes

        model.Id = resp.data.id
        model.Scope = attributes.scope
        model.DisplayTimezone = getattr(attributes, "display_timezone", None)
        model.Message = getattr(attributes, "message", None)
        model.MuteFirstRecoveryNotification = getattr(attributes, "mute_first_recovery_notification", None)
        model.NotifyEndStates = (
            [str(s) for s in attributes.notify_end_states] if hasattr(attributes, "notify_end_states") else None
        )
        model.NotifyEndTypes = (
            [str(s) for s in attributes.notify_end_types] if hasattr(attributes, "notify_end_types") else None
        )

        monitor_identifier = attributes.monitor_identifier.get_oneof_instance()
        if isinstance(monitor_identifier, DDDowntimeMonitorIdentifierId):
            model.MonitorIdentifier = MonitorIdentifier(MonitorId=monitor_identifier.monitor_id, MonitorTags=None)
        elif isinstance(monitor_identifier, DDDowntimeMonitorIdentifierTags):
            model.MonitorIdentifier = MonitorIdentifier(MonitorId=None, MonitorTags=monitor_identifier.monitor_tags)

        if attributes.schedule:
            schedule = attributes.schedule.get_oneof_instance()
            if isinstance(schedule, DDDowntimeScheduleOneTimeResponse):
                model.Schedule = Schedule(
                    Start=schedule.start.isoformat() if schedule.start else None,
                    End=schedule.end.isoformat() if schedule.end else None,
                    Timezone=None,
                    Recurrences=None,
                )
            elif isinstance(schedule, DDDowntimeScheduleRecurrencesResponse):
                recurrences = []
                for r in schedule.recurrences:
                    recurrence = Recurrences(
                        Rrule=getattr(r, "rrule", None),
                        Start=getattr(r, "start", None),
                        Duration=getattr(r, "duration", None),
                    )
                    recurrences.append(recurrence)
                model.Schedule = Schedule(
                    Start=None,
                    End=None,
                    Timezone=getattr(schedule, "timezone", None),
                    Recurrences=recurrences,
                )

    return ProgressEvent(
        status=OperationStatus.SUCCESS,
        resourceModel=model,
    )

def build_downtime_create_from_model(model: ResourceModel) -> DDDowntimeCreateRequest:
    scope = model.Scope
    if model.MonitorIdentifier.MonitorId is not None:
        monitor_identifier = DDDowntimeMonitorIdentifier(monitor_id=model.MonitorIdentifier.MonitorId)
    elif model.MonitorIdentifier.MonitorTags is not None:
        monitor_identifier = DDDowntimeMonitorIdentifier(monitor_tags=model.MonitorIdentifier.MonitorTags)
    else:
        raise Exception("Invalid value for MonitorIdentifier")

    attributes = DDDowntimeCreateRequestAttributes(scope=scope, monitor_identifier=monitor_identifier)

    if model.DisplayTimezone is not None:
        attributes.display_timezone = model.DisplayTimezone
    if model.Message is not None:
        attributes.message = model.Message
    if model.MuteFirstRecoveryNotification is not None:
        attributes.mute_first_recovery_notification = model.MuteFirstRecoveryNotification
    if model.NotifyEndStates is not None:
        attributes.notify_end_states = [DDDowntimeNotifyEndStateTypes(s) for s in model.NotifyEndStates]
    if model.NotifyEndTypes is not None:
        attributes.notify_end_types = [DDDowntimeNotifyEndStateActions(s) for s in model.NotifyEndTypes]
    if model.Schedule is not None:
        schedule = DDDowntimeScheduleCreateRequest()
        if model.Schedule.Recurrences is not None:
            recurrences = []
            for r in model.Schedule.Recurrences:
                recurrence = DDDowntimeScheduleRecurrenceCreateUpdateRequest(duration=r.Duration, rrule=r.Rrule)
                if r.Start is not None:
                    recurrence.start = r.Start
                recurrences.append(recurrence)
            schedule.recurrences = recurrences

            if model.Schedule.Timezone is not None:
                schedule.timezone = model.Schedule.Timezone
        # We fall back to one time schedule if recurrence(required property is not set)
        else:
            schedule = DDDowntimeScheduleCreateRequest()
            if model.Schedule.Start is not None:
                schedule.start = model.Schedule.Start
            if model.Schedule.End is not None:
                schedule.end = model.Schedule.End
        attributes.schedule = schedule

    return DDDowntimeCreateRequest(
        data=DDDowntimeCreateRequestData(
            attributes=attributes,
            type=DDDowntimeResourceType.DOWNTIME,
        ),
    )

def build_downtime_update_from_model(model: ResourceModel) -> DDDowntimeUpdateRequest:
    scope = model.Scope
    if model.MonitorIdentifier.MonitorId is not None:
        monitor_identifier = DDDowntimeMonitorIdentifier(monitor_id=model.MonitorIdentifier.MonitorId)
    elif model.MonitorIdentifier.MonitorTags is not None:
        monitor_identifier = DDDowntimeMonitorIdentifier(monitor_tags=model.MonitorIdentifier.MonitorTags)
    else:
        raise Exception("Invalid value for MonitorIdentifier")

    attributes = DDDowntimeUpdateRequestAttributes(scope=scope, monitor_identifier=monitor_identifier)

    if model.DisplayTimezone is not None:
        attributes.display_timezone = model.DisplayTimezone
    if model.Message is not None:
        attributes.message = model.Message
    if model.MuteFirstRecoveryNotification is not None:
        attributes.mute_first_recovery_notification = model.MuteFirstRecoveryNotification
    if model.NotifyEndStates is not None:
        attributes.notify_end_states = [DDDowntimeNotifyEndStateTypes(s) for s in model.NotifyEndStates]
    if model.NotifyEndTypes is not None:
        attributes.notify_end_types = [DDDowntimeNotifyEndStateActions(s) for s in model.NotifyEndTypes]
    if model.Schedule is not None:
        if model.Schedule.Recurrences is not None:
            schedule = DDDowntimeScheduleRecurrencesUpdateRequest()
            recurrences = []
            for r in model.Schedule.Recurrences:
                recurrence = DDDowntimeScheduleRecurrenceCreateUpdateRequest(duration=r.Duration, rrule=r.Rrule)
                if r.Start is not None:
                    recurrence.start = r.Start
                recurrences.append(recurrence)
            schedule.recurrences = recurrences

            if model.Schedule.Timezone is not None:
                schedule.timezone = model.Schedule.Timezone
        else:
            schedule = DDDowntimeScheduleOneTimeCreateUpdateRequest()
            if model.Schedule.Start is not None:
                schedule.start = model.Schedule.Start
            if model.Schedule.End is not None:
                schedule.end = model.Schedule.End
        attributes.schedule = schedule

    return DDDowntimeUpdateRequest(
        data=DDDowntimeUpdateRequestData(
            attributes=attributes,
            type=DDDowntimeResourceType.DOWNTIME,
            id=model.Id,
        ),
    )