import json
import numpy as np
from sklearn.model_selection import train_test_split
import time
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, TensorDataset

def load_data(data_path):
    """
    Load data from JSON file and return features and labels

    Parameters:
    - data_path: path to JSON file (string)

    Return:
    - X: features from data (numpy array)
    - y: labels for data (numpy array)

    Resource:
        https://github.com/musikalkemist/DeepLearningForAudioWithPython/blob/master/19-%20How%20to%20implement%20an%20RNN-LSTM%20for%20music%20genre%20classification/code/19-%20How%20to%20implement%20an%20RNN-LSTM%20for%20music%20genre%20classification.py
    """

    # open file for reading
    with open(data_path, "r") as fp:
        data = json.load(fp)

    # store features and labels as np arrays
    X = np.array(data["mfcc"])
    y = np.array(data["labels"])

    return X, y

def prepare_datasets(data_path, test_size, validation_size):
    """
    Loads data and splits it into train, validation and test sets.

    Parameters:
    - test_size: percentage of data set to allocate for testing (float)
    - validation_size: percentages of training set to allocate for validation (float)

    Return:
    - X_train: training set (numpy array)
    - X_validation: training validation set (numpy array)
    - X_test: testing set (numpy array)
    - y_train: labels for training set (numpy array)
    - y_validation: labels for training validation set (numpy array)
    - y_test: labels for testing set (numpy array)

    Resource:
        https://github.com/musikalkemist/DeepLearningForAudioWithPython/blob/master/19-%20How%20to%20implement%20an%20RNN-LSTM%20for%20music%20genre%20classification/code/19-%20How%20to%20implement%20an%20RNN-LSTM%20for%20music%20genre%20classification.py
    """
    # load data
    X, y = load_data(data_path)

    # create train, validation and test split
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size)
    X_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size=validation_size)

    return X_train, X_validation, X_test, y_train, y_validation, y_test

def get_data_loaders(data_path):
    """
    Create and return PyTorch DataLoader objects for the training, validation, and test data

    Parameters:
    - data_path: Path to JSON file with data (string)

    Return:
    - train_loader: training data (DataLoader)
    - val_loader: val data (DataLoader)
    - test_loader: test data (DataLoader)
    """
    batch_size = 32

    # get train, validation, test splits
    X_train, X_validation, X_test, y_train, y_validation, y_test = prepare_datasets(data_path, 0.2, 0.2)

    train_features = torch.Tensor(X_train)
    train_targets = torch.Tensor(y_train)
    val_features = torch.Tensor(X_validation)
    val_targets = torch.Tensor(y_validation)
    test_features = torch.Tensor(X_test)
    test_targets = torch.Tensor(y_test)

    train_dataset = TensorDataset(train_features, train_targets)
    val_dataset = TensorDataset(val_features, val_targets)
    test_dataset = TensorDataset(test_features, test_targets)

    train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=False, drop_last=True)
    val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, drop_last=True)
    test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, drop_last=True)

    return train_loader, val_loader, test_loader

def train(model, train_loader, val_loader, k_epochs, device):
    """
    Time and train model for k_epochs using the train_loader while regulating performance
    using the val_loader

    Parameters:
    - model: model to train with
    - train_loader: data to train on (DataLoader)
    - val_loader: data to validate and regulate performance (DataLoader)
    - k_epochs: number of epochs to run training on (int)
    - device: device to move to

    Guidance from CS451 lecture notes
    """

    begin = time.time()

    loss_fn = nn.BCEWithLogitsLoss() # Loss function for binary classification
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    # Printing purposes
    last_epoch = len(model.training_info['train_losses'])

    for epoch in range(k_epochs):

        # Training
        model.train() #Set model to training mode
        train_loss = 0
        correct = 0
        total = 0

        for i, data in enumerate(train_loader, 0):
            X, y = data
            X = X.to(device)
            y = y.to(device)

            optimizer.zero_grad()

            output = model(X)

            # Training Loss
            loss = loss_fn(output.squeeze(), y)
            loss.backward()
            optimizer.step()
            train_loss += loss.item()

            # Training Accuracy
            predicted = (output.sigmoid() >= 0.5).float()
            predicted = predicted.view(-1) # modify dimensions
            total += y.size(0)
            correct += (predicted == y.float()).sum().item()

        # Calculate training loss and accuracy
        train_loss /= len(train_loader)
        train_accuracy = 100. * (correct / total)

        # Add training loss and accuracy to model's history
        model.training_info['train_losses'].append(train_loss)
        model.training_info['train_accuracies'].append(train_accuracy)

        # Validation
        model.eval() # Set model to evaluation mode
        val_loss = 0
        correct = 0
        total = 0

        # Do not store computational graph since we are simulating testing
        with torch.no_grad():
            for i, data in enumerate(val_loader, 0):
                X, y = data
                X = X.to(device)
                y = y.to(device)

                output = model(X)

                # Validation Loss
                loss = loss_fn(output.squeeze(), y)
                val_loss += loss.item()

                # Validation Accuracy
                predicted = (output.sigmoid() >= 0.5).float()
                predicted = predicted.view(-1) # modify dimensions
                total += y.size(0)
                correct += (predicted == y.float()).sum().item()

            # Calculate validation loss and accuracy
            val_loss /= len(val_loader)
            val_accuracy = 100. * (correct / total)

            # Add validation loss and accuracy to model's history
            model.training_info['val_losses'].append(val_loss)
            model.training_info['val_accuracies'].append(val_accuracy)

        print(f'Epoch {last_epoch+epoch+1}:')
        print(f'\tTrain Loss={train_loss:.4f} Train Accuracy={train_accuracy:.2f}%')
        print(f'\tVal Loss  ={val_loss:.4f} Val Accuracy  ={val_accuracy:.2f}%')

    end = time.time()
    print(f'Finished training in {round(end - begin)}s')

def test(model, test_loader, device):
    """
    Test performance of model based on test_loader

    Parameters:
    - model: model to test
    - test_loader: test data to assess performance (DataLoader)
    - device: device to move to

    Guidance from CS451 lecture notes
    """
    correct = 0
    total = 0

    # Do no store computational graph since we are testing
    with torch.no_grad():
        for data in test_loader:
            X, y = data
            X = X.to(device)
            y = y.to(device)

            y_hat = model(X)

            predicted = (y_hat.sigmoid() >= 0.5).float()
            predicted = predicted.view(-1) # modify dimensions

            # compute the accuracy
            total += y.size(0)
            correct += (predicted == y).sum().item()

    print(f'Test accuracy: {100 * correct // total} %')

def plot_history(title, model, graph_path):
    """
    Plot the models history of training/validation accuracies and
    training/validation losses on separate graphs based on what is
    stored in its training info. Save the created graphs at graph_path.

    Parameters:
    - title: title to give graph (string)
    - model: model whose history to inspect
    - graph_path: path for storing images of graphs (string)
    """

    fig, axs = plt.subplots(2)

    fig.suptitle(title, fontweight='heavy')

    # create accuracy sublpot
    axs[0].plot(model.training_info["train_accuracies"], label="train accuracy")
    axs[0].plot(model.training_info["val_accuracies"], label="val accuracy")
    axs[0].set_ylabel("Accuracy")
    axs[0].set_xlabel("Epoch")
    axs[0].legend(loc="lower right")
    axs[0].set_title("Accuracy eval")

    # create error sublpot
    axs[1].plot(model.training_info["train_losses"], label="train error")
    axs[1].plot(model.training_info["val_losses"], label="val error")
    axs[1].set_ylabel("Error")
    axs[1].set_xlabel("Epoch")
    axs[1].legend(loc="upper right")
    axs[1].set_title("Error eval")

    fig.tight_layout()

    plt.savefig(graph_path)
    plt.show()


import numpy as np
import os
import pickle

from collections import defaultdict
from ..dataset.qa import Database
from ..utilities.answer_utils import EvalAIAnswerPreprocessor, compute_answers_scores
from ..utilities.config import *
from ..utilities.vocab import VocabDict

def filter_answers(answers_dset, evalai_answer_processor, num_ans):
    print("[FILTER ANSWERS] Top %s answers..." % num_ans)
    answers_dict = defaultdict(lambda: 0)
    for ans in answers_dset:
        gtruth = ans["multiple_choice_answer"]
        gtruth = evalai_answer_processor(gtruth)
        answers_dict[gtruth] += 1
    answers_list = sorted(answers_dict, key=answers_dict.get, reverse=True)
    answers_list = [t.strip() for t in answers_list if len(t.strip()) > 0]
    assert "<unk>" not in answers_list
    answers_list = ["<unk>"] + answers_list[: num_ans - 1]
    print("[FILTER ANSWERS] Top %s answers...DONE" % num_ans)
    return answers_list

def extract_answers(annotations, valid_answers_list, evalai_answer_processor):
    print("[EXTRACT ANSWERS] ...")
    answers = [None] * len(annotations)
    for i in range(len(annotations)):
        question_id = annotations[i]["question_id"]
        all_answers = [
            evalai_answer_processor(answer["answer"])
            for answer in annotations[i]["answers"]
        ]

        valid_answers = [None] * len(all_answers)
        for j, answer in enumerate(all_answers):
            if answer in valid_answers_list:
                valid_answers[j] = answer
            else:
                valid_answers[j] = "<unk>"

        answers[i] = dict(question_id=question_id, valid_answers=valid_answers)
    print("[EXTRACT ANSWERS] ...DONE")
    return answers

def compute_target(dataroot, outputs_dir, evalai_answer_processor, num_ans, split):
    print("[COMPUTE TARGET] %s set." % split)
    train2014 = Database(dataroot, "train2014")
    train_annotations = train2014.load("annotations")
    val2014 = Database(dataroot, "val2014")
    val_annotations = val2014.load("annotations")

    answers_dset = train_annotations + val_annotations
    vocab_entry = filter_answers(answers_dset, evalai_answer_processor, num_ans)

    answer_file_name = "answers_top%s_vocab.txt" % num_ans
    answer_file = (os.path.join(outputs_dir, answer_file_name),)
    with open(answer_file, "w") as f:
        f.writelines([w + "\n" for w in vocab_entry])

    answer_vocab = VocabDict(vocab_entry)
    valid_answers_list = answer_vocab.word_lists

    if split == "train":
        ans = extract_answers(
            train_annotations, valid_answers_list, evalai_answer_processor
        )
    elif split == "val":
        ans = extract_answers(
            val_annotations, valid_answers_list, evalai_answer_processor
        )

    targets = []
    for i in range(len(ans)):
        question_id = ans[i]["question_id"]
        valid_answers = ans[i]["valid_answers"]
        answers_indices = [answer_vocab.word2idx(ans) for ans in valid_answers]
        answers_scores = compute_answers_scores(
            answers_indices, answer_vocab.num_vocab, answer_vocab.UNK_idx
        )

        targets.append(
            {
                "question_id": question_id,
                "answers_indices": answers_indices,
                "answers_scores": answers_scores,
            }
        )
    target_file = os.path.join(outputs_dir, split + "_target.pkl")
    pickle.dump(targets, open(target_file, "wb"))
    print("[COMPUTE TARGET] %s set....DONE" % split)
    return

if __name__ == "__main__":
    evalai_answer_processor = EvalAIAnswerPreprocessor()
    compute_target(dataroot, outputs_dir, evalai_answer_processor, num_answers, train)
    compute_target(dataroot, outputs_dir, evalai_answer_processor, num_answers, val)


import urllib.request
import zipfile
import os
import shutil
import yaml

from datetime import datetime

def read_yaml(file_path):
    with open(file_path, "r") as f:
        return yaml.safe_load(f)

def download():
    url = "https://github.com/Dimbreath/GenshinData/archive/refs/heads/master.zip"
    print ("Downloading...")
    print(datetime.now().time())
    filename, headers = urllib.request.urlretrieve(url, filename="./DimbreathDatamine.zip")
    print ("Download complete!")
    print(datetime.now().time())

def unzip():
    if os.path.exists("./DimbreathDatamine.zip"):
        print("\nUnzipping...")
        print(datetime.now().time())
        with zipfile.ZipFile("./DimbreathDatamine.zip", 'r') as zip_ref:
            try:
                zip_ref.extractall("./DimbreathDatamine")
            except FileNotFoundError:
                print(
"""Error: FileNotFoundError

Please do not tamper with the files mid download.
Run this program again to fix it.""")
                input("\n\nPress Enter to Exit")
                exit()
        print("Unzipped!")
        print(datetime.now().time())
    else:
        print("No file to UNZIP.")

def delZIP():
    print("\nRemoving ZIP...")
    print(datetime.now().time())
    if os.path.exists("./DimbreathDatamine.zip"):
        os.remove("./DimbreathDatamine.zip")
        print("Zip removed!")
        print(datetime.now().time())
    else:
        print("No ZIP file to delete.")

def moveAndDelExtra():
    print("\nRemoving extra files...")
    print(datetime.now().time())
    if os.path.exists(".\DimbreathDatamine\GenshinData-master"):
        try:
            shutil.rmtree(".\DimbreathDatamine\ExcelBinOutput", ignore_errors=True)
            shutil.move(".\DimbreathDatamine\GenshinData-master\ExcelBinOutput",".\DimbreathDatamine")

            shutil.rmtree(".\DimbreathDatamine\TextMap", ignore_errors=True)
            shutil.move(".\DimbreathDatamine\GenshinData-master\TextMap",".\DimbreathDatamine")
        except:
            print(
"""Ignoring Errors AHHHHHHHHHHHHH!!!!!!!!!

Lowkey though, run the file again to fix :).

Error: shutil.Error: Destination not found.""")
            input("\n\nPress Enter to Exit")
            exit()

        shutil.rmtree(".\DimbreathDatamine\GenshinData-master", ignore_errors=True)
        print("Extra files removed!")
    else:
        print("No extra files found.")
    print(datetime.now().time())
    print("\nFile Extraction Complete!")

def extractLang():
    print("\nExtracting languages...")
    print(datetime.now().time())

    for lang in read_yaml("config.yaml")[list(read_yaml("config.yaml").keys())[3]].keys():
        if not read_yaml("config.yaml")[list(read_yaml("config.yaml").keys())[3]][lang]:
            path = ".\DimbreathDatamine\GenshinData-master\TextMap\%s" % lang
            if os.path.exists(path):
                os.remove(path)

    print("\nLanguages Extracted!")
    print(datetime.now().time())

download()
unzip()
delZIP()
extractLang()
moveAndDelExtra()

input("\n\nPress Enter to Exit")
exit()


# 메서드 오버라이딩

# 이번에는 FourCal 클래스를 다음과 같이 실행해보자
cal = FourCal(4, 0)
cal.div()
# Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#   result = self.first / self.second
# ZeroDivisionError: division by zero
# FourCal 클래스의 객체 cal에 4와 0 값을 설정하고 div 메서드를 호출하면 4를 0으로 나누려고 하기 때문에 위와 같은 ZeroDivisionError 오류가 발생한다
# 하지만 0으로 나눌때 오류가 아닌 0을 돌려주도록 만들고 싶다면 어떻게 해야 할까?

# 다음과 같이 FourCal 클래스를 상속하는 SafeFourCal 클래스를 만들어보자
class SafeFourCal(FourCal):
    def div(self):
        if self.second == 0:
            return 0
        else:
            return self.first / self.second
# SafeFourCal 클래스는 FourCal 클래스에 있는 div 메서드를 동일한 이름으로 다시 작성하였다
# 이렇게 부모 클래스에 있는 메서드를 동일한 이름으로 다시 만드는 것을 메서드 오버라이딩(Overriding, 덮어쓰기)이라고 한다
# 이렇게 메서드를 오버라이딩하면 부모클래스의 메서드 대신 오버라이딩한 메서드가 호출된다
# SafeFourCal 클래스에 오버라이딩한 div 메서드는 나누는 값이 0인 경우에는 0을 돌려주도록 수정하였다
cal = SafeFourCal(4, 0)
cal.div()
# 0
# FourCal 클래스와는 달리 ZeroDivisionError가 발생하지 않고 의도한 대로 0을 돌려주는 것을 확인할 수 있다


"""

"""

import fractions

def max_fraction(a,b):
    #print(a,b)
    if len(a)==1:
        return a[0],b[0]
    else:
        max_num = a[0]
        max_den = b[0]
        for i in range(1,len(a)):
            max_num = max_num + a[i]
            max_den = max_den + b[i]
        return max_num,max_den

def main():
    t = int(input())
    for i in range(t):
        n = int(input())
        a = []
        b = []
        for j in range(n):
            num,den = input().split("/")
            a.append(int(num))
            b.append(int(den))
        for j in range(n):
            max_num,max_den = max_fraction(a[j:],b[j:])
            gcd = fractions.gcd(max_num,max_den)
            print(str(max_num//gcd)+"/"+str(max_den//gcd))
        print()

if __name__ == '__main__':
    main()


from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

def all_events():
    accounts = ["2u","my"]
    events = []
    for acc in accounts:
        events.extend(events_by_account(acc))
    return events

def events_by_account(acc):
    pickle_file_name = f"{acc}-token.pickle"
    creds_file_name = f"{acc}-credentials.json"
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(pickle_file_name):
        with open(pickle_file_name, 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                creds_file_name, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(pickle_file_name, 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    return events_result.get('items', [])

if __name__ == '__main__':
    all_events()


import os
import sys
import argparse
import multiprocessing
import subprocess

def preprocess_rgb(sequence):
    sys.stderr.write(('Processing sequence {}\n'.format(sequence)))
    command = 'imgp -x 640x480 -wf {}/*.color.jpg'.format(sequence)
    subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, check=True)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_dir', help='Path to directory containing sequences to preprocess', required=True)
    parser.add_argument('--nproc', default=8, help='Number of processes to spawn')
    args = parser.parse_args()

    print("Finding all sequences to process")
    sequences = next(os.walk(args.data_dir))[1]
    sequences.sort()
    sequences = [os.path.join(args.data_dir, seq) for seq in sequences]

    print('Preprocess start')
    pool = multiprocessing.Pool(processes=args.nproc)
    pool.map(preprocess_rgb, sequences)

    pool.close()
    pool.join()
    print('Done')

if __name__ == "__main__":
    main()


# BlendArMocap is split into separated modules which may access cgt_core.
# Every module has to be registered to be active.

from .cgt_core.cgt_interface import cgt_core_registration
from .cgt_mediapipe import cgt_mp_registration
from .cgt_transfer import cgt_transfer_registration
# from .cgt_socket_ipc import cgt_ipc_registration
from .cgt_freemocap import fm_registration

modules = [
    # cgt_ipc_registration,
    cgt_core_registration,
    cgt_mp_registration,
    fm_registration,
    cgt_transfer_registration,
]

def register():
    for module in modules:
        module.register()

def unregister():
    for module in modules:
        module.unregister()


import pandas as pd

# Create a sample dataframe
data = {'Column1': [1, 2, 'N/A', 4, 5],
        'Column2': ['N/A', 'A', 'B', 'C', 'N/A']}
df = pd.DataFrame(data)

# Replace 'N/A' with NaN

# Alternatively, you can read the data while loading the dataframe
# df = pd.read_csv('your_data.csv', na_values=['N/A'])

print(df)


# -*- coding: utf-8 -*-
# @Author  : MengYangD
# @FileName: unet.py

# refer:
# https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_model.py
# https://github.com/usuyama/pytorch-unet/blob/master/pytorch_unet.py
# https://github.com/jvanvugt/pytorch-unet/blob/master/unet.py

import torch.nn as nn
import torch.nn.functional as F
from .unet_parts import *
from maskrcnn_benchmark.utils.registry import Registry
from maskrcnn_benchmark.layers import FrozenBatchNorm2d

class BaseStem(nn.Module):
    def __init__(self, cfg, norm_func):
        super(BaseStem, self).__init__()

        out_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS

        self.conv1 = nn.Conv2d(
            3, out_channels, kernel_size=7, stride=2, padding=3, bias=False
        )
        self.bn1 = norm_func(out_channels)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = F.relu_(x)
        x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
        return x

class StemWithFixedBatchNorm(BaseStem):
    def __init__(self, cfg):
        super(StemWithFixedBatchNorm, self).__init__(
            cfg, norm_func=FrozenBatchNorm2d
        )

class UNet(nn.Module):
    def __init__(self, cfg):
        super(UNet, self).__init__()
        # Translate string names to implementations
        stem_module = _STEM_MODULES[cfg.MODEL.RESNETS.STEM_FUNC]
        self.stem = stem_module(cfg)
        in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS

        self.inc = inconv(in_channels, 64)
        self.down1 = down_sample(64, 128)
        self.down2 = down_sample(128, 256)
        self.down3 = down_sample(256, 512)
        self.down4 = down_sample(512, 1024)

        self.up1 = up_sample(1024, 512, padding=1, up_mode='upsample')
        self.up2 = up_sample(512, 256, padding=1, up_mode='upsample')
        self.up3 = up_sample(256, 128, padding=1, up_mode='upsample')
        self.up4 = up_sample(128, 64, padding=1, up_mode='upsample')

        # self.outc = outconv(64,2)

    def forward(self, x):
        # x1 = self.inc(x)
        x1 = self.stem(x)
        print('------------')
        print('x1,', x1.shape)
        x2 = self.inc(x1)
        print('------------')
        print('x2,', x2.shape)
        down1 = self.down1(x2)
        down2 = self.down2(down1)
        down3 = self.down3(down2)
        down4 = self.down4(down3)
        print('------------')
        print('d1,', down1.shape)
        print('------------')
        print('d2,', down2.shape)
        print('------------')
        print('d3,', down3.shape)
        print('------------')
        print('d4,', down4.shape)

        up1 = self.up1(down4, down3)
        up2 = self.up2(up1, down2)
        up3 = self.up3(up2, down1)
        up4 = self.up4(up3, x1)
        # out = self.outc(up4)

        outputs_res = [up4, up2, up3, up1]

        # return F.sigmoid(out)
        return outputs_res

_STAGE_SPECS = Registry({
    "UNet-FPN": UNet,
})

_STEM_MODULES = Registry({
    "StemWithFixedBatchNorm": StemWithFixedBatchNorm,
})


from unittest import TestCase

from mock import call, patch, Mock

from gofer.rmi.model import protocol
from gofer.rmi.model.parent import Monitor, Call
from gofer.rmi.model.parent import Result, Progress, Error, Raised, Ping

MODULE = 'gofer.rmi.model.parent'

class TestMonitor(TestCase):

    @patch(MODULE + '.sleep')
    def test_run(self, sleep):
        context = Mock()
        context.cancelled.side_effect = [False, True]
        child = Mock()

        # test
        m = Monitor(context, child)
        m.run()

        # validation
        child.terminate.assert_called_once_with()
        sleep.assert_called_once_with(0.10)

    @patch(MODULE + '.Monitor.join')
    def test_stop(self, join):
        context = Mock()
        child = Mock()

        # test
        m = Monitor(context, child)
        m.stop()

        # validation
        self.assertEqual(m.poll, False)
        join.assert_called_once_with()

class TestReplies(TestCase):

    def test_result(self):
        payload = 'done'
        reply = Result(payload)

        # test
        try:
            reply()
            self.fail(msg='End not raised')
        except protocol.End as end:
            self.assertEqual(end.result, payload)

    @patch(MODULE + '.Context.current')
    def test_progress(self, current):
        class P(object):
            report = Mock()
        context = Mock()
        context.progress = P()
        current.return_value = context
        payload = protocol.ProgressPayload(1, 2, 3)
        reply = Progress(payload)

        # test
        reply()

        context.progress.report.assert_called_once_with()
        self.assertEqual(context.progress.__dict__, payload.__dict__)

    def test_error(self):
        payload = 18
        reply = Error(payload)
        self.assertRaises(Exception, reply)

    def test_raised(self):
        payload = ValueError()

        # test
        reply = Raised(payload)
        try:
            reply()
            self.fail(msg='ValueError not raised')
        except ValueError as e:
            self.assertEqual(e, payload)

    def test_ping(self):
        payload = 1234
        reply = Ping(payload)
        reply()

class TestCall(TestCase):

    @patch(MODULE + '.Call.read')
    @patch(MODULE + '.Target')
    @patch(MODULE + '.Context')
    @patch(MODULE + '.Process')
    @patch(MODULE + '.Pipe')
    @patch(MODULE + '.Monitor')
    def test_call(self, monitor, pipe, process, context, target, read):
        pipe.return_value = Mock(reader=Mock(), writer=Mock())

        # test
        _call = Call(Mock(), 1, 2, a=1, b=2)
        _call()

        # validation
        pipe.assert_called_once_with()
        pipe.return_value.writer.close.assert_called_once_with()
        target.assert_called_once_with(_call.method, *_call.args, **_call.kwargs)
        process.assert_called_once_with(target.return_value, pipe.return_value)
        monitor.assert_called_once_with(context.current.return_value, process.return_value)
        monitor.return_value.start.assert_called_once_with()
        read.assert_called_once_with(pipe.return_value.reader)
        monitor.return_value.stop.assert_called_once_with()
        process.return_value.wait.assert_called_once_with()

    @patch(MODULE + '.protocol.Reply')
    def test_read(self, reply):
        replies = [Mock(), Mock(side_effect=protocol.End(18))]
        reply.read.side_effect = replies
        _call = Call(Mock())
        pipe = Mock()

        # test
        retval = _call.read(pipe)

        # validation
        self.assertEqual(
            reply.read.call_args_list,
            [
                call(pipe),
                call(pipe)
            ])
        self.assertEqual(retval, 18)


from collections import defaultdict

# Class to represent a graph
from sys import stdin

import heapq
class Graph:
    def __init__(self, vertices):
        self.graph = defaultdict(list)  # dictionary containing adjacency List
        self.V = vertices  # No. of vertices

    # 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:
            self.graph[i].sort()
            for j in self.graph[i]:
                in_degree[j] += 1

        # Create an queue and enqueue all vertices with
        # indegree 0
        li = []
        heapq.heapify(li)
        for i in range(self.V):
            if in_degree[i] == 0:
                heapq.heappush(li,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 li:

            # Extract front of queue (or perform dequeue)
            # and add it to topological order
            u = heapq.heappop(li)
            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:
                    heapq.heappush(li, i)

            cnt += 1

        # Check if there was a cycle
        return top_order

l = 1
while True:
    try:
        n = int(input())
        g = {}
        g2 = {}
        for i in range(n):
            s = str(input())
            g[s] = i
            g2[i] = s
        e = int(input())
        g1 = Graph(n)
        for i in range(e):
            f, t = list(map(str, input().split()))
            k = g[f]
            k1 = g[t]
            g1.addEdge(k, k1)

        order = []
        for i in g1.topologicalSort():
            order.append(g2[i])

        order = " ".join(order)
        print("Case #{}: Dilbert should drink beverages in this order: {}.".format(l, order))
        print()
        input()

        l += 1
    except(EOFError):
        break
from heapq import heappush, heappop

def topological_sort(graph, indegree, ordering):
    global N
    global names
    zero_indegree = []

    for u in range(N):
        if indegree[u] == 0:
            heappush(zero_indegree, u)

    while zero_indegree:
        u = heappop(zero_indegree)
        ordering.append(names[u])

        for v in graph[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                heappush(zero_indegree, v)

tc = 1
while True:
    try:
        N = int(input())
    except EOFError:
        exit()

    vertices = dict()
    names = []
    graph = [[] for _ in range(N)]
    indegree = [0] * N

    for i in range(N):
        beverage = input()
        vertices[beverage] = i
        names.append(beverage)

    M = int(input())
    for _ in range(M):
        beverage_1, beverage_2 = input().split()
        u, v = vertices[beverage_1], vertices[beverage_2]
        graph[u].append(v)
        indegree[v] += 1

    ordering = []
    topological_sort(graph, indegree, ordering)

    print('Case #{}: Dilbert should drink beverages in this order: '.format(tc), end='')
    print(*ordering, end='.\n\n')
    tc += 1
    input()

from heapq import heappush, heappop

def topological_sort(graph, indegree, ordering):
    global N
    global names
    zero_indegree = []

    for u in range(N):
        if indegree[u] == 0:
            heappush(zero_indegree, u)

    while zero_indegree:
        u = heappop(zero_indegree)
        ordering.append(names[u])

        for v in graph[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                heappush(zero_indegree, v)

tc = 1
while True:
    try:
        N = int(input())
    except EOFError:
        exit()

    vertices = dict()
    names = []
    graph = [[] for _ in range(N)]
    indegree = [0] * N

    for i in range(N):
        beverage = input()
        vertices[beverage] = i
        names.append(beverage)

    M = int(input())
    for _ in range(M):
        beverage_1, beverage_2 = input().split()
        u, v = vertices[beverage_1], vertices[beverage_2]
        graph[u].append(v)
        indegree[v] += 1

    ordering = []
    topological_sort(graph, indegree, ordering)

    print('Case #{}: Dilbert should drink beverages in this order: '.format(tc), end='')
    print(*ordering, end='.\n\n')
    tc += 1
    input()

def topoSort(adj, indegree):
    zero_indegree = queue.PriorityQueue()
    topoSorted = []

    for i in range(n):
        if indegree[i] == 0:
            zero_indegree.put(i)

    while not zero_indegree.empty():
        u = zero_indegree.get()
        topoSorted.append(u)
        for v in adj[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                zero_indegree.put(v)

    return topoSorted

def main():
    global n, m
    n, m = map(int, input().split())
    adj = [[] for _ in range(n)]
    indegree = [0 for _ in range(n)]

    for i in range(m):
        u, v = map(int, input().split())
        adj[u-1].append(v-1)
        indegree[v-1] += 1

    res = topoSort(adj, indegree)
    if (len(res) < n):
        print("Sandro fails.")
        return 0

    for i in range(n):
        print("{} ".format(res[i] + 1), end="")

if __name__ == "__main__":
    main()

import sys

sys.setrecursionlimit(10 ** 6)

def dfs(u, graph, visited, ordering):
    global parent
    visited[u] = True

    for v in graph[u]:
        if not visited[v]:
            dfs(v, graph, visited, ordering)

    ordering.append(u)

def topological_sort(graph, ordering):
    global N
    visited = [False] * (N + 1)
    for u in range(1, N + 1):
        if not visited[u]:
            dfs(u, graph, visited, ordering)

N, K = map(int, input().split())
graph = [[] for _ in range(N + 1)]
indegree = [0] * (N + 1)

for u in range(1, K + 1):
    n, *adj_u = list(map(int, input().split()))
    graph[u] = adj_u

parent = [0] * (N + 1)
ordering = []
topological_sort(graph, ordering)

for i in range(N - 1):
    parent[ordering[i]] = ordering[i + 1]

for u in range(1, N + 1):
    print(parent[u])

from sys import stdin

t = int(input())

while t:
    a = [int(x) for x in stdin.readline().split()]

    ans = 0
    while True:
        b = [int(x) for x in stdin.readline().split()]
        dp = [[0 for i in range(len(b))] for j in range(len(a))]
        if len(b) == 1:
            break

        for i in range(len(a)):
            for j in range(len(b)):
                if i == 0 or j == 0:
                    dp[i][j] = 0
                elif a[i-1] == b[j-1]:
                    dp[i][j] = dp[i-1][j-1]  + 1
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        ans = max(dp[-1][-1], ans)
    print(ans)
    t -= 1

from sys import stdin

t1 = int(input())

while t1:
    t1 -= 1
    n, w = [int(x) for x in stdin.readline().split()]
    c = [0] * (n+1)
    p = [0] *  (n+1)
    t = [0] *  (n+1)
    for i in range(1,n+1):
        c[i], p[i], t[i] =  [int(x) for x in stdin.readline().split()]
    dp = [[0] * (w+2) for _ in range(n+2)]
    for i in range(1, n+1):
        for j in range(1,w+1):
            dp[i][j] = max(dp[i-1][j],dp[i][j-1])
            if j >= t[i]:
                dp[i][j] = max(dp[i][j] , p[i]*c[i] + dp[i-1][j-t[i]])

    print(dp[n][w])


from util import file_util as util
from . import view
from . import customer
import util.wrapper as wrapper

class CustomerController:
    def __init__(self):
        """Initializes the controller object"""
        self.file_util = util.FileUtil(_table_name="customer")
        self.data = self.file_util.read_data()
        self.fields = ["name", "email", "phone", "national_id", "customer_id"]
        self.table_headers = ["Customer ID", "Name", "National ID", "Phone", "Email"]

    def displayMenu(self):
        """Displays the customer submenu and rerouting the user request to perform required transactions"""
        while True:
            user_choice = view.display_customer_sub_menu()
            if user_choice == "1":
                name, national_id, phone, email = view.add_customer_view()
                if name is not None:
                    if wrapper.isValidEmail(email):
                        if wrapper.isValidPhone(phone):
                            if wrapper.safe_str_to_number(national_id) is not None:
                                self.save_new_customer(customer.Customer(name, national_id, phone, email))
                            else:
                                wrapper.print_error_message("\nRegistration Failed! Invalid national ID")
                        else:
                            wrapper.print_error_message('\nRegistration Failed! Invalid Phone Number')
                    else:
                        wrapper.print_error_message('\nRegistration Failed! Invalid Email')
                else:
                    wrapper.print_error_message('\nSubmission aborted!')
            elif user_choice == "2":
                customer_id, field, new_value = view.update_customer_view()
                if 0 < field <= 4:
                    if customer_id is not None:
                        self.update_customer(customer_id, self.fields[field - 1], new_value)
                    else:
                        wrapper.print_error_message('\nSubmission aborted!')
                else:
                    wrapper.print_error_message("\nFailed to process your request. Invalid field.")

            elif user_choice == "3":
                customer_id = view.delete_customer_view()
                if customer_id is not None:
                    self.delete_customer(customer_id)
            elif user_choice == "4":
                self.display_all_customers()
            elif user_choice == "5":
                field, keyword = view.search_customer_view()
                if 0 < field <= 4:
                    if field is not None:
                        self.search_customer(self.fields[field - 1], keyword)
                    else:
                        wrapper.print_error_message('\nSubmission aborted!')
                else:
                    wrapper.print_error_message("\nFailed to process your request. Invalid field.")
            elif user_choice == "0":
                break
            else:
                wrapper.print_error_message('\nFailed to process your request. Invalid choice.')

    def save_new_customer(self, model):
        """Adds a new customer into the system"""
        self.data.append(model.to_dict())
        self.file_util.write_data(self.data)
        wrapper.print_success_message("\nSaved successfully")

    def customer_exists(self, _customer_id):
        """Checks if the provided customer id exists """
        for record in self.data:
            if record["customer_id"] == _customer_id:
                return True
        return False

    def customer_email(self, _customer_id):
        """Retrieves the customer"""
        for record in self.data:
            if record["customer_id"] == _customer_id:
                return record['email']
        return None

    def update_customer(self, customer_id, field, new_value):
        """Updates the given customer field with the provided new value"""
        for i in range(len(self.data)):
            if self.data[i]["customer_id"] == customer_id:
                self.data[i][field] = new_value
                self.file_util.write_data(self.data)
                wrapper.print_success_message("\nUpdate successful!")
                return
        wrapper.print_error_message("\nUpdate failed. Customer ID not found")

    def display_all_customers(self):
        """Displays all the saved members"""
        table_data = list()
        for i in range(len(self.data)):
            table_data.append(self.data[i])
        wrapper.print_title("\nAll customers")
        if len(table_data) > 0:
            self.__prepare_table_data(table_data)
        else:
            wrapper.print_title("\n\tNo customer records yet")

    def search_customer(self, field, keyword):
        """Finds a member using a specific field and keyword provided"""
        table_data = list()
        for i in range(len(self.data)):
            if keyword.lower() in str(self.data[i][field]).lower():
                table_data.append(self.data[i])
        wrapper.print_title("\nSearch result for {}:'{}'".format(field, keyword))
        if len(table_data) > 0:
            self.__prepare_table_data(table_data)
        else:
            wrapper.print_title("\n\tNo customer found")

    def delete_customer(self, customer_id):
        """Removes the customer from the storage files"""
        for i in range(len(self.data)):
            if self.data[i]["customer_id"] == customer_id:
                self.data.pop(i)
                self.file_util.write_data(self.data)
                wrapper.print_success_message("\nDelete successful!")
                return
        wrapper.print_error_message("\nDelete failed. Customer ID not found")

    def __prepare_table_data(self, _raw_data):
        """Prepares the data to be printed out in tables"""
        table_data = list()
        table_data.append(self.table_headers)
        for datum in _raw_data:
            table_data.append(list(datum.values()))
        wrapper.printDataTable(table_data)


'''
alpha_num = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
def alpha_to_num(data, index, return_list):
    if index >= len(data):
        return return_list
    for i in range(10):
        flag = True
        for j in range(len(alpha_num[i])):
            if data[index + j] != alpha_num[i][j]:
                flag = False
                break
        if flag is True:
            return_list.append(i)
            alpha_to_num(data, index + len(alpha_num[i]), return_list)
            break
def solution(s):
    alpha = []
    answer = []
    return_list = []
    for char in s:
        if char.isalpha():
            alpha.append(char)
        else:
            if len(alpha):
                alpha_to_num(alpha, 0, return_list)
                alpha.clear()
                answer = answer + return_list
                return_list.clear()
            answer.append(int(char))
    if len(alpha):
        (alpha_to_num(alpha, 0, return_list))
        alpha.clear()
        answer = answer + return_list
        return_list.clear()
    return int(''.join(map(str, answer)))
'''

#간단하게 딕셔너리로 구현 가능..!

num_dic = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}

def solution(s):
    answer = s
    for key, value in num_dic.items():
        answer = answer.replace(key, value)
    print(int(answer))

solution(input())

카카오코테연습/level1/숫자문자열과영단어.py

숫자문자열과영단어.py


'''
University of Latvia Faculty of Computing Qualification paper:
Implementation of the board game "Scrabble"

bag.py:
Contains the class modelling the game bag of tiles.

Author:         Matīss Apinis (ma17058)
Date created:   2019/04/28
Date edited:    2019/05/27
'''

'''
Represents the bag of tiles, contains all tiles which haven't been drawn yet.
Initialized with the exact distribution of tiles, grab() will choose one tile
from the bag at random. If none are available, it will return None
'''

# Libraries:
from random import shuffle

# Local files:
import tile

class Bag:
	# Dictionary of tiles by letter as key with 2-tuple as value containing its score value and copy count in bag:
	def __init__(self):
		self.tiles = []

		self.add('A', 1, 9)
		self.add('B', 3, 2)
		self.add('C', 3, 2)
		self.add('D', 2, 4)
		self.add('E', 1, 12)
		self.add('F', 4, 2)
		self.add('G', 2, 3)
		self.add('H', 4, 2)
		self.add('I', 1, 9)
		self.add('J', 8, 1)
		self.add('K', 5, 1)
		self.add('L', 1, 4)
		self.add('M', 3, 2)
		self.add('N', 1, 6)
		self.add('O', 1, 8)
		self.add('P', 3, 2)
		self.add('Q', 10, 1)
		self.add('R', 1, 6)
		self.add('S', 1, 4)
		self.add('T', 1, 6)
		self.add('U', 1, 4)
		self.add('V', 4, 2)
		self.add('W', 4, 2)
		self.add('X', 8, 1)
		self.add('Y', 4, 4)
		self.add('Z', 10, 1)
		self.add(' ', 0, 2)

		shuffle(self.tiles)

	'''
   	Pulls a new tile from the game bag if it’s not empty.
   	'''
	def pull_tile(self):
		if self.is_bag_empty():
			return None

		return self.tiles.pop()

	'''
	Checks whether the game bag is empty or not.
	'''
	def is_bag_empty(self):
		return len(self.tiles) == 0

	'''
	Randomizes the sequence in which tiles would be pulled out of the game bag.
	'''
	def shuffle(self):
		shuffle(self.tiles)

	def return_tile(self, tile):
		self.tiles.append(tile)

	'''
	Adds n copies of a newly created game tile to the game bag.
	'''
	def add(self, letter, points, n):
		for i in range(n):
			self.tiles.append(tile.Tile(letter, points))


from .core import *

class UserBased(CollaborativeFiltering):
    def __init__(self):
        CollaborativeFiltering.__init__(self)

    def most_similar_set_to(self, subset):
        pairs = []
        for other_set, similarity in enumerate(self.usr_matrix[subset]):
            if subset != other_set and similarity > 0:  # find other users
                pairs += [(other_set, similarity)]  # with nonzero similarity

        return sorted(pairs,  # sort them by most similar
                      key=lambda x: x[-1], reverse=True)

    def user_based(self, subset, include_current_items=False):
        # sum up the similarities
        suggestions = defaultdict(float)
        for other_set, similarity in self.most_similar_set_to(subset):
            for ele in self.dataset[other_set]:
                suggestions[ele] = similarity

        # convert them to a sorted list
        suggestions = sorted(suggestions.items(), key=lambda x: x[-1], reverse=True)

        # and (maybe) exclude already-interests
        if include_current_items:
            return suggestions

        else:
            return [(suggestion, weight)  # filtering the suggestion already had
                    for suggestion, weight in suggestions if suggestion not in self.dataset[subset]]


class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """

        res = []
        for i in range(len(obstacleGrid)):
            res.append([])
            for j in range(len(obstacleGrid[0])):
                if obstacleGrid[i][j] == 1:
                    res[i].append(0)
                else:
                    if i != 0 and j != 0:
                        res[i].append(res[i][j - 1] + res[i-1][j])
                    elif i == 0 and j == 0:
                        res[i].append(1)
                    elif i == 0:
                        res[i].append(res[i][j - 1])
                    elif j == 0:
                        res[i].append(res[i-1][j])
        return res[len(obstacleGrid) - 1][len(obstacleGrid[0]) - 1]


import time
from inbox import constants
from inbox.models import PrimaryDomain
from tests import AppEngineFlaskTestCase
from inbox.helpers import IMAPHelper, DriveHelper, MigrationHelper
from secret_keys import (
    TEST_LOGIN, TEST_PASS, TEST_OAUTH2_CONSUMER_KEY,
    TEST_OAUTH2_CONSUMER_SECRET, TEST_PRIMARY_CREDENTIALS,
    TEST_PRIMARY_ADMIN_EMAIL, TEST_PRIMARY_REFRESH_TOKEN,
    TEST_FAKE_PRIMARY_CREDENTIALS
)
from inbox.util import OAuthEntity
import mock
from fixtures import RFC_822_TEST
import email

class ImapHelperTestCase(AppEngineFlaskTestCase):
    def test_login(self):
        imap = IMAPHelper()
        result, data = imap.login(TEST_LOGIN, TEST_PASS)
        self.assertEquals('OK', result, "Couldn't login successfully")
        imap.close()

    def init(self, key, secret):
        self.key = TEST_OAUTH2_CONSUMER_KEY
        self.secret = TEST_OAUTH2_CONSUMER_SECRET

    @mock.patch.object(OAuthEntity, '__init__', init)
    def test_oauth1_2lo_login(self):
        imap = IMAPHelper()
        imap.oauth1_2lo_login("administrador@eforcers.com.co")
        imap.close()

    def test_list_messages(self):
        imap = IMAPHelper()
        result, data = imap.login(TEST_LOGIN, TEST_PASS)
        self.assertEquals('OK', result, "Couldn't login successfully")

        data = imap.list_messages()
        self.assertNotEquals(0, len(data), "Couldn't list messages successfully")
        imap.close()

    def test_get_message(self):
        imap = IMAPHelper()
        result, data = imap.login(TEST_LOGIN, TEST_PASS)
        self.assertEquals('OK', result, "Couldn't login successfully")

        data = imap.list_messages()
        self.assertNotEquals(0, len(data), "Couldn't list messages successfully")

        result, data = imap.get_message(data[0])
        self.assertEquals('OK', result, "Couldn't get message successfully")
        imap.close()

    def test_get_localized_labels(self):
        imap = IMAPHelper()
        result, data = imap.login(TEST_LOGIN, TEST_PASS)
        imap.get_localized_labels()
        self.assertNotEqual("",
                            imap.all_labels[constants.GMAIL_TRASH_KEY],
                            "Trash label is missing")
        self.assertNotEqual("",
                            imap.all_labels[constants.GMAIL_ALL_KEY],
                            "Trash label is missing")
        imap.close()

    def test_copy_message(self):
        imap = IMAPHelper()
        result, data = imap.login(TEST_LOGIN, TEST_PASS)
        self.assertEquals('OK', result, "Couldn't login successfully")

        imap.create_label('testlabel')

        prev_number_messages = len(imap.list_messages(criteria='label:testlabel'))

        messages = imap.list_messages()

        imap.copy_message(msg_id=messages[0], destination_label='testlabel')
        new_number_messages = len(imap.list_messages(criteria='label:testlabel'))

        self.assertEquals(prev_number_messages,
                          new_number_messages - 1,
                          "The message wasn't copied")

        imap.remove_message_label(msg_id=messages[0], prev_label='testlabel')

        new_number_messages = len(imap.list_messages(criteria='label:testlabel'))

        self.assertEquals(prev_number_messages,
                          new_number_messages,
                          "The message label wasn't removed")

class DriveHelperTestCase(AppEngineFlaskTestCase):

    def test_init(self):
        admin_email = TEST_PRIMARY_ADMIN_EMAIL

        drive = DriveHelper(credentials_json=TEST_PRIMARY_CREDENTIALS,
                    admin_email=admin_email,
                    refresh_token=TEST_PRIMARY_REFRESH_TOKEN)
        folder = drive.get_folder('anything')

    def test_get_and_create_folder(self):
        admin_email = TEST_PRIMARY_ADMIN_EMAIL

        drive = DriveHelper(credentials_json=TEST_PRIMARY_CREDENTIALS,
                    admin_email=admin_email,
                    refresh_token=TEST_PRIMARY_REFRESH_TOKEN)

        # Create and check folder
        folder = drive.get_folder('integration-test-folder')
        self.assertEquals(None, folder, "Folder shouldn't exist")

        folder = drive.create_folder('integration-test-folder')
        self.assertNotEquals(None, folder, "Folder exists now")

        created_folder = drive.get_folder('integration-test-folder')
        self.assertEquals(created_folder, folder, "Folder wasn't created")

        # Create and check subfolder
        sub_folder = drive.get_folder('integration-test-subfolder')
        self.assertEquals(None, sub_folder, "Folder shouldn't exist")

        parents = [{'id': folder['id']}]
        sub_folder = drive.create_folder(
            'integration-test-subfolder', parents=parents)
        self.assertNotEquals(None, sub_folder, "Subfolder exists now")

        created_subfolder = drive.get_folder(
            'integration-test-subfolder', parent_id=folder['id'])
        self.assertEquals(created_subfolder, sub_folder, "Subfolder wasn't created")

        # Garbage collect
        drive.service.files().delete(fileId=folder['id']).execute()
        drive.service.files().delete(fileId=sub_folder['id']).execute()

    def test_insert_file_and_get_metadata(self):
        admin_email = TEST_PRIMARY_ADMIN_EMAIL

        drive = DriveHelper(credentials_json=TEST_PRIMARY_CREDENTIALS,
                    admin_email=admin_email,
                    refresh_token=TEST_PRIMARY_REFRESH_TOKEN)

        # Create in root
        created_file = drive.insert_file("integration-test.txt", 'plain/text', 'lorem ipsum')
        self.assertNotEquals(None, created_file, "File wasn't created")

        saved_file = drive.get_metadata(title="integration-test.txt")
        self.assertEquals(created_file['md5Checksum'],
                          saved_file['md5Checksum'], "The file wasn't created")

        # Create in a folder
        created_folder = drive.create_folder("integration-text-folder")
        self.assertNotEquals(None, created_folder, "Folder wasn't created")

        created_folder_file = drive.insert_file(
            "integration-foldertest.txt", 'plain/text', 'lorem ipsum',
            parent_id=created_folder['id'])
        self.assertNotEquals(None, created_folder_file,
                             "File wasn't created")

        saved_folder_file = drive.get_metadata(
            "integration-foldertest.txt", parent_id=created_folder['id'])
        self.assertEquals(created_folder_file['md5Checksum'],
                          saved_folder_file['md5Checksum'],
                          "File in folder wasnn't created")

        # Garbage Collect
        drive.service.files().delete(fileId=created_folder['id']).execute()
        drive.service.files().delete(fileId=created_file['id']).execute()
        drive.service.files().delete(fileId=created_folder_file['id']).execute()

    def test_insert_permission(self):
        admin_email = TEST_PRIMARY_ADMIN_EMAIL

        drive = DriveHelper(credentials_json=TEST_PRIMARY_CREDENTIALS,
                    admin_email=admin_email,
                    refresh_token=TEST_PRIMARY_REFRESH_TOKEN)

        # Create in root
        created_file = drive.insert_file("integration-test.txt", 'plain/text', 'lorem ipsum')
        self.assertNotEquals(None, created_file, "File wasn't created")

        permission = drive.insert_permission(file_id=created_file['id'],
                                value='dev@eforcers.com',
                                type='user', role='reader')

        self.assertNotEquals(None, permission, "Permission not set")

        drive.service.files().delete(fileId=created_file['id']).execute()

class MigrationHelperTestCase(AppEngineFlaskTestCase):

    def test_init_and_insert(self):
        msg = email.message_from_string(RFC_822_TEST)

        imap = IMAPHelper()
        imap.oauth1_2lo_login(user_email='administrador@eforcers.com.co')

        messages = imap.list_messages(
                           criteria='pruebamigration-uniquehash-34lkj3lk5j3l4kj3lk4j')

        # Delete messages from previous tests
        for message in messages:
            result, label_data = imap.get_message_labels(msg_id=message)
            if not result:
                assert False
                imap.remove_message_label(
                    msg_id=message, prev_label='integration-tests')
            imap.delete_message(msg_id=message)

        messages = imap.list_messages(
                           criteria='pruebamigration-uniquehash-34lkj3lk5j3l4kj3lk4j')
        prev_number_messages = len(messages)

        self.assertEquals(0, prev_number_messages,
                          "Message cleanup wasn't executed")

        time.sleep(1)

        migration = MigrationHelper(
                credentials_json=TEST_PRIMARY_CREDENTIALS,
                refresh_token=TEST_PRIMARY_REFRESH_TOKEN)
        result = migration.migrate_mail(
            user_email='administrador@eforcers.com.co',
            msg=msg, labels=['integration-tests'])

        if not result:
            assert False

        time.sleep(15)

        messages = imap.list_messages(
                           criteria='pruebamigration-uniquehash-34lkj3lk5j3l4kj3lk4j')
        number_messages = len(messages)

        if len(messages) == 0:
            messages = imap.list_messages(
                           criteria='pruebamigration-uniquehash-34lkj3lk5j3l4kj3lk4j',
                           only_from_trash=True)
            number_messages = len(messages)

        self.assertEquals(1, number_messages,
                          "Message cleanup wasn't executed")

        for message in messages:
            result, label_data = imap.get_message_labels(msg_id=message)
            if not result:
                assert False
            labels = (((label_data[0].split('('))[2].split(')'))[0]).split()
            self.assertIn('integration-tests', labels,
                          "Label wasn't preserved")

        imap.close()


from fpdf import FPDF
import matplotlib.pyplot as plt

# pdf.add_font('custom_font', fname = './copy.ttf')

n = int(input('ENTER COUNT : '))
names = []

for i in range(0, n) :
    name = input('ENTER NAME : ')
    names.append(name)

def make_pdf(name, dir) :
    pdf = FPDF(orientation = 'L', unit = 'mm', format = 'A4')
    pdf.add_page()
    pdf.image('./template.png', h = 210, w = 300, x = 0, y = 0)
    pdf.set_font('Helvetica', 'B', 48)
    pdf.set_text_color(255, 157, 125)
    pdf.set_xy(0,100)
    pdf.cell(w = 300, h = 10, txt = name, align = 'C')
    pdf.output(dir + '/' + name + '.pdf', 'F')

for name in names :
    make_pdf(name, './outputs')

# orange 255, 157, 125
# yellow 237, 255, 122

#1414 x 2000


import sys
class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:

        c1=0
        c2=0
        ele1=-sys.maxsize
        ele2=-sys.maxsize
        for i in range(0,len(nums)):
            if(c1==0 and nums[i]!=ele2):
                ele1=nums[i]
                c1+=1
            elif(c2==0 and nums[i]!=ele1):
                ele2=nums[i]
                c2+=1
            elif(nums[i]==ele1):
                c1+=1
            elif(nums[i]==ele2):
                c2+=1
            else:
                c1-=1
                c2-=1
        co1=0
        co2=0
        for i in range(0,len(nums)):
            if(nums[i]==ele1):
                co1+=1
            elif(nums[i]==ele2):
                co2+=1

        ls=[]

        mini=len(nums)//3 +1
        if(co1>=mini):
            ls.append(ele1)
        if(co2>=mini):
            ls.append(ele2)
        return ls


import os
import ftplib

#FTP and file system code credit
#https://medium.com/@rrfd/ftp-access-with-python-1d096b061ef3

print('Connecting to server...')

locationName = 'hnx'

master_directory = os.path.dirname(os.getcwd())
data_directory = master_directory + '\\data\\'
solrad_directory = data_directory + 'solrad_data\\' + locationName + '\\'

try:
    ftp = ftplib.FTP('aftp.cmdl.noaa.gov')
    ftp.login()
    print('Connected')
except ftplib.all_errors as e:
    errorcode_string = str(e).split(None, 1)[0]

#Setting the current working directory to 2019
ftp.cwd('/data/radiation/solrad/' + locationName + '/2019/')
#ftp.cwd('/data/radiation/solrad/realtime/' + locationName)

directoryName = solrad_directory
print(directoryName)
#if not os.path.exists(directoryName):
#    os.makedirs(directoryName)

os.chdir(directoryName)

dateStart = 19122
dateEnd =   19129

currentDownloadDate = dateStart;

print( ftp.nlst())

while currentDownloadDate <= dateEnd:

    tempFileName = locationName + '%s.dat' % currentDownloadDate
    file = open(tempFileName, 'wb')

    print('Downloading %s' % tempFileName)

    try:
        ftp.retrbinary('RETR %s' % tempFileName, file.write)
        print('Successfully downloaded %s' % tempFileName)
    except ftplib.all_errors as e:
        print('Error downloading %s' % tempFileName)
        errorcode_string = str(e).split(None, 1)[0]

    currentDownloadDate += 1

ftp.close()
print('Closed')


from scrapy import signals
from scrapy.http import Request, Response
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from pymongo.collection import Collection, ReturnDocument

from crawler.seeder import Seeder
from crawler.utils import getMongoCollection

class IITDSpider(CrawlSpider):
    name = "iitd"

    allowed_domains = [
        'iitd.ac.in',
        'iitd.ernet.in'
    ]

    rules = [
        Rule(LinkExtractor(), follow=True, callback="parse_item",
             process_request="process_request")
    ]

    start_urls = [
        'http://iitd.ac.in',
    ]

    def start_requests(self):
        self.mongo_collection: Collection = getMongoCollection()
        for url in self.start_urls:
            doc = self.mongo_collection.find_one_and_update({
                "url": url
            }, {
                "$setOnInsert": {
                    "crawl_details": [],
                }
            }, upsert=True, return_document=ReturnDocument.AFTER)

        for doc in Seeder(self.mongo_collection).seed():
            url = doc['url']
            self.logger.info(f"Got {url} from seeder")
            yield Request(url, meta={"mongo_doc": doc})

    def process_request(self, request: Request, response: Response):
        self.logger.debug('Processing request')

        if "mongo_doc" not in request.meta:
            request.meta["mongo_doc"] = self.mongo_collection.find_one_and_update(
                {"url": request.url},
                {"$setOnInsert": {"crawl_details": []}},
                upsert=True,
                return_document=ReturnDocument.AFTER
            )

        # Drop this request if it has already been crawled
        if len(request.meta["mongo_doc"]["crawl_details"]) != 0:
            return None

        return request

    def parse_item(self, response):
        self.logger.info(f'Visited URL {response.url}')
        item = {
            "request": response.request,
            "elastic_doc": {
                'url': response.url,
                'status': response.status,
                'title': response.xpath("//title").get(),
                'body': response.xpath("//body").get(),
                'link_text': response.meta['link_text'],
            },
        }

        return item


One = int(input("Tapez un nombre entre 1 et 10: "))
Two = int(input("Tapez un nombre entre 1 et 10: "))

if (One >= 1) and (One <= 10):
   if (Two >= 1) and (Two <= 10):
      print("Votre nombre secret est : ", One * Two)
   else:
      print("La seconde valeur est incorrecte !")
else:
   print("La première valeur est incorrecte !")


def main():
    from functools import partial
    from .core import SteadyExceptionHandler
    # from send_gmail import Send_Gmail

    # エラーによる停止時に自動メール送信
    # mailObj = Send_Gmail('py.auto.send@gmail.com')
    exceptionHandle = SteadyExceptionHandler(
        lambda : print('エラー発生'),
        # partial(
        #     mailObj.send,
        #     mail_title='エラー発生',
        #     mail_text='エラー発生により、jupyterの実行を停止しました。',
        #     mail_to='hiroki.sugiura.915@gmail.com'
        # )
    )

if __name__ == '__main__':
    main()


from setuptools import find_packages, setup

with open("README.md", "r") as fh:
    long_description = fh.read()
setup(
    name="Mountain_Scott_ds12",
    version="1.0",
    author="Mountain Scott",
    author_email="mountainscott@yahoo.com",
    description="Helper functions for splitting and adding columns to dataframes",
    long_description=long_description,
    long_description_content_type="text/markdown", # required if using a md file for long desc
    license="MIT",
    url="https://github.com/Elswayre/Ray_lambda_ds12",
    #keywords="",
    packages=find_packages() # ["lambdata_mountain"]
)


# Quiz Game Using Python

print("Welcome To The Quiz Game!")

score = 0

playing = input("Do you wanna play?(Yes/No): ")
playing = playing.lower()

if playing != "yes":
    quit()

print('''LET'S BEGIN!

''')

answer = input("Which company owns Google?: ")
answer = answer.lower()

if answer == "alphabet":
    print("Correct!")
    score +=1

else:
    print("Incorrect!")

answer = input("Where is the Statue of Liberty located?: ")
answer = answer.lower()

if answer == "new york":
    print("Correct!")
    score +=1

else:
    print("Incorrect!")

answer = input("Who is the father of Computer?: ")
answer = answer.lower()

if answer == "charles babbage":
    print("Correct!")
    score +=1

else:
    print("Incorrect!")

answer = input("What's the full form of WWW?: ")
answer = answer.lower()

if answer == "world wide web":
    print("Correct!")
    score +=1

else:
    print("Incorrect!")

answer = int(input("When was the film TITANIC released?: "))

if answer == 1997:
    print("Correct!")
    score +=1

else:
    print("Incorrect!")

print("The Quiz is Over!:)")

print(f"Congrats, You Scored {score} out of 5.")


import os
import json

from gtts import gTTS
from pydub import AudioSegment

from classifier.classifier import PatchClassifier
from sonifier.sonified_result import SonifiedResult

class Sonifier:
    def __init__(self, spec_filename, patch_size=96, use_gpu=True, verbose=False):
        self.patch_size = patch_size
        with open(spec_filename, "r") as f:
            self.spec = json.loads(f.read())
        self.verbose = verbose
        self.tags = []
        self.doc_features = []

        root = self.spec["root"]
        for data in self.spec["data"]:
            self.doc_features.append(data["doc_features"])
            folder = root + ('%s/' % data["id"])
            width, height = data["width"], data["height"]
            verbose_temp = 0.1
            aggregated_tags = { "text": 0, "image": 0, "graph": 0, "ad": 0 }
            num_patch = len(data["patches"])
            for patch in data["patches"]:
                tags = patch["tags"]
                aggregated_tags["text"] += tags[0] / num_patch
                aggregated_tags["image"] += tags[1] / num_patch
                aggregated_tags["graph"] += tags[2] / num_patch
                aggregated_tags["ad"] += tags[3] / num_patch
            self.tags.append(aggregated_tags)

    def generate_glance_mp3(self, data_id, output_filename):
        self.save_tts_mp3("구성요소 비율", "glance_temp.mp3", 1.5)
        scale = min(5, self.spec["data"][data_id]["height"] / 1500)
        duration_text = self.tags[data_id]["text"] * scale
        duration_image = (self.tags[data_id]["image"] + self.tags[data_id]["graph"]) * scale
        duration_ad = self.tags[data_id]["ad"] * scale

        freqs_text = [261.63]
        freqs_image = [293.66, 392.00]
        freqs_ad = [493.88, 523.25, 587.33]

        sr = SonifiedResult()
        sr.append_sinewave(freqs_text, duration_milliseconds=duration_text * 1000) #volume can be also adjusted by volume=0.0~1.0
        #sr.append_silence(duration_milliseconds=500)
        sr.append_sinewave(freqs_image, duration_milliseconds=duration_image * 1000) #volume can be also adjusted by volume=0.0~1.0
        #sr.append_silence(duration_milliseconds=500)
        sr.append_sinewave(freqs_ad, duration_milliseconds=duration_ad * 1000) #volume can be also adjusted by volume=0.0~1.0
        sr.append_silence(duration_milliseconds=200)
        sr.save_wav(output_filename)

        glance_0 = AudioSegment.from_mp3("glance_temp.mp3")
        glance_1 = AudioSegment.from_wav(output_filename)
        (glance_0 + glance_1).export(output_filename, format="mp3")

    def generate_keywords_mp3(self, data_id, output_filename):
        sentence = " ".join(self.doc_features[data_id]["keywords"])
        self.save_tts_mp3(sentence, output_filename, 1.5)

    def generate_summary_mp3(self, data_id, output_filename):
        doc_feature = self.doc_features[data_id]
        num_imgs = int(doc_feature["num_imgs"])
        num_links = int(doc_feature["num_links"])
        num_headers = int(doc_feature["num_headers"])
        num_tables = int(doc_feature["num_tables"])
        sentence = f"헤더 {num_headers}개 링크 {num_links}개 이미지 {num_imgs}개 표 {num_tables}개"
        self.save_tts_mp3(sentence, output_filename, 1.5)

    def generate_defaults_mp3(self, data_id, output_filename):
        doc_feature = self.doc_features[data_id]
        title = doc_feature['title']
        navs = " ".join(doc_feature['navs']) if len(doc_feature['navs']) > 0 else "이 없습니다."
        headers = " ".join(doc_feature['headers'][:5]) if len(doc_feature['headers']) > 0 else "가 없습니다."
        sentence = f"페이지 제목 {title} 네비게이션 {navs} 헤더 {headers}"
        self.save_tts_mp3(sentence, output_filename, 1.5)

    def generate_merged_sg_mp3(self, glance_filename, keyword_filename, default_filename, output_filename):
        glance = AudioSegment.from_mp3(glance_filename)
        keyword = AudioSegment.from_mp3(keyword_filename)
        default = AudioSegment.from_mp3(default_filename)
        (glance + keyword + default)[:15*1000].export(output_filename, format="mp3")

    def generate_merged_ss_mp3(self, summary_filename, default_filename, output_filename):
        summary = AudioSegment.from_mp3(summary_filename)
        default = AudioSegment.from_mp3(default_filename)
        (summary + default)[:15*1000].export(output_filename, format="mp3")

    @staticmethod
    def speed_change(sound, speed=1.0):
        # Manually override the frame_rate. This tells the computer how many
        # samples to play per second
        sound_with_altered_frame_rate = sound._spawn(sound.raw_data, overrides={
            "frame_rate": int(sound.frame_rate * speed)
        })
        # convert the sound with altered frame rate to a standard frame rate
        # so that regular playback programs will work right. They often only
        # know how to play audio at standard frame rate (like 44.1k)
        return sound_with_altered_frame_rate.set_frame_rate(sound.frame_rate)

    def save_tts_mp3(self, sentence, output_filename, speed=1):
        tts = gTTS(sentence, lang='ko')
        tts.save(output_filename)
        if speed != 1:
            reopened = AudioSegment.from_mp3(output_filename)
            self.speed_change(reopened, speed=1.3).export(output_filename, format="mp3")


"""makeNovel Build Command

makeNovel – Build Command
=========================
Main function for the build command

File History:
Created:   2018-03-15 [0.1.0]

"""

import logging
import getopt
import mknov   as mn

from os import path, getcwd, pardir

from mknov.error   import ErrHandler, ErrCodes
from mknov.config  import Config
from mknov.main    import MakeNovel

logger = logging.getLogger(__name__)

def buildProject(sysArgs):

    # Valid Input Options
    shortOpt = "hm:at"
    longOpt  = [
        "help",
        "master=",
        "all",
        "timeline",
    ]

    helpMsg = (
        "makenovel {version} build\n"
        "\n"
        "Usage:\n"
        " -h, --help      Print this message.\n"
        " -m, --master=   Specify the master document. If none is specified,\n"
        "                   the previously used file will be used.\n"
        " -a, --all       Build all items.\n"
        " -t, --timeline  Build novel timeline.\n"
    ).format(
        version   = mn.__version__,
        status    = mn.__status__,
        copyright = mn.__copyright__
    )

    # Default Values
    masterFile    = mn.CFG.masterFile
    buildTimeLine = False

    # Parse Options
    try:
        inOpts, inArgs = getopt.getopt(sysArgs,shortOpt,longOpt)
    except getopt.GetoptError:
        print(helpMsg)
        exit(2)

    # Parse Input
    for inOpt, inArg in inOpts:
        if inOpt in ("-h","--help"):
            print(helpMsg)
            return True
        elif inOpt in ("-m","--master"):
            masterFile = inArg

    #
    # Execute Build
    #

    if masterFile == "":
        mn.OUT.errMsg("No master file specified")
        ErrHandler.terminateExec(ErrCodes.ERR_MISSINGINFO)
        exit(2)

    # Command Header
    mn.OUT.printHeader("This is %s build - version %s" % (
        mn.__appname__,mn.__version__), 72
    )

    # Echo Settings
    mn.OUT.infMsg("Master file: %s" % masterFile)

    theNovel = MakeNovel()
    theNovel.setMasterFile(masterFile)
    theNovel.buildInit()

    mn.OUT.infMsg("")
    mn.CFG.saveConfig()

    return False


import logging
from datetime import datetime

from odoo import models, fields

_logger = logging.getLogger(__name__)

class StockPicking(models.Model):
    _inherit = "stock.picking"

    commission_images_id = fields.Many2many(
        "commission.policy.image",
        "commission_policy_image_picking_rel",
        string="Historico de Comisiones",
    )

    def cron_action_assign_general_commission_to_picking(self):
        general_commission = self.env["commission.policy"].get_commission("all")
        uninvoiced_pickings_without_commission = self.search(
            [
                ("state", "not in", ["cancel", "draft"]),
                ("invoice_id", "=", False),
                ("picking_type_id", "=", 2),
                ("commission_images_id", "=", False),
            ]
        )
        invoiced_pickings_without_commission = self.search(
            [
                ("state", "not in", ["cancel", "draft"]),
                ("invoice_id", "!=", False),
                ("invoice_id.paid_seller", "=", "not_paid"),
                ("picking_type_id", "=", 2),
                ("commission_images_id", "=", False),
            ]
        )

        for picking in uninvoiced_pickings_without_commission:
            _logger.warning("==========PICKING: %s", picking)
            _logger.warning("just checkin' uninvoiced")
            general_commission.get_or_create_commission_image(picking, "all")

        for picking in invoiced_pickings_without_commission:
            _logger.warning("==========PICKING: %s", picking)
            _logger.warning("just checkin' invoiced")
            general_commission.get_or_create_commission_image(picking, "all")

    def cron_set_false_picking_images(self):
        uninvoiced_pickings_without_commission = self.search(
            [
                ("state", "not in", ["cancel", "draft"]),
                ("invoice_id", "=", False),
                ("picking_type_id", "=", 2),
            ]
        )
        invoiced_pickings_without_commission = self.search(
            [
                ("state", "not in", ["cancel", "draft"]),
                ("invoice_id", "!=", False),
                ("invoice_id.paid_seller", "=", "not_paid"),
                ("picking_type_id", "=", 2),
            ]
        )

        for picking in uninvoiced_pickings_without_commission:
            _logger.warning("==========PICKING: %s", picking)
            _logger.warning("just checkin' uninvoiced")
            picking.commission_images_id = False

        for picking in invoiced_pickings_without_commission:
            _logger.warning("==========PICKING: %s", picking)
            _logger.warning("just checkin' invoiced")
            picking.commission_images_id = False

    def exclude_out_from_older_general_commissons(self):
        images = self.env["commission.policy.image"].get_image_commission("all")
        active_image = images[0]
        unactive_images = images[1:]
        for image in unactive_images:
            active_image.pickings_id -= image.pickings_id

    def reset_product_brand_commission(self):
        CommissionPolicy = self.env["commission.policy"]

        sale_orders = self.env["sale.order"].search(
            [
                ("create_date", ">=", datetime(2022, 8, 4)),
                ("create_date", "<=", datetime.now()),
            ]
        )
        outs = sale_orders.picking_ids
        outs = outs.filtered(lambda x: x.picking_type_code == "outgoing")
        commissions = {
            "client": CommissionPolicy.get_commission("client"),
            "product": {
                "brand": CommissionPolicy.get_commission("product", "brand"),
            },
            "all": CommissionPolicy.get_commission("all"),
        }

        for out in outs:
            for line in out.move_line_ids_without_package:
                cancel_line_comparation = False
                if (
                    line.product_id.brand_id.id in commissions["product"]["brand"].brands_id.ids
                    and not cancel_line_comparation
                ):
                    if (
                        len(out.commission_images_id) == 1
                        and out.commission_images_id[0].policy_type == "all"
                    ):
                        _logger.warning("==========PICKING: %s", out)
                        _logger.warning("==========COMMISSION: %s", out.commission_images_id)
                        commission_i = out.commission_images_id[0]
                        commission_i.pickings_id -= out
                    commission = commissions["product"]["brand"].filtered(
                        lambda c: line.product_id.brand_id.id in c.brands_id.ids
                    )
                    _logger.warning("==========COMMISSION TO PICK: %s", commission.display_name)
                    _logger.warning("The damn commission: %s" % commission.display_name)
                    commission.get_or_create_commission_image(out, "product", "brand")
                    cancel_line_comparation = True
                if not out.commission_images_id.filtered(lambda x: x.policy_type == "client"):
                    _logger.warning(
                        "==========PICKING: %s",
                        out.commission_images_id.filtered(lambda x: x.policy_type == "client"),
                    )
                    if (
                        out.partner_id.id in commissions["client"].clients_id.ids
                        and not cancel_line_comparation
                    ):
                        commission = commissions["client"].filtered(
                            lambda c: out.partner_id.id in c.clients_id.ids
                        )
                        commission.get_or_create_commission_image(out, "client")
                        cancel_line_comparation = True
                if not out.commission_images_id.filtered(lambda x: x.policy_type == "all"):
                    _logger.warning(
                        "==========PICKING: %s",
                        out.commission_images_id.filtered(lambda x: x.policy_type == "all"),
                    )
                    if not cancel_line_comparation:
                        commissions["all"].get_or_create_commission_image(out, "all")

    def delete_duplicate_outs_in_client_commission(self):
        commission_policy_image = self.env["commission.policy.image"]
        commission_client = commission_policy_image.get_image_commission("client")

        for i, image in enumerate(commission_client):
            if i == 0:
                continue
            _logger.warning(
                "========== PRE-IMAGE A: %s ========== PRE-IMAGE B: %s"
                % (len(image.pickings_id), len(commission_client[i - 1].pickings_id)),
            )
            image.pickings_id -= commission_client[i - 1].pickings_id
            _logger.warning(
                "========== POST-IMAGE A: %s ========== POST-IMAGE B: %s"
                % (len(image.pickings_id), len(commission_client[i - 1].pickings_id)),
            )

    def delete_out_of_invalid_commission(self):
        commission_policy_image = self.env["commission.policy.image"]
        commission_images = {
            "client": commission_policy_image.get_image_commission("client"),
            "all": commission_policy_image.get_image_commission("all"),
        }

        for image in commission_images["client"]:
            outs = self.env["stock.picking"].search(
                [
                    ("create_date", ">=", datetime(2022, 8, 4)),
                    ("create_date", "<", image.create_date),
                    ("picking_type_code", "=", "outgoing"),
                    ("id", "in", image.pickings_id.ids),
                ]
            )
            image.pickings_id -= outs

        duplicate_outs = self.env["stock.picking"].search(
            [
                ("create_date", ">=", datetime(2022, 8, 4)),
                ("picking_type_code", "=", "outgoing"),
                ("id", "in", commission_images["client"].pickings_id.ids),
                ("id", "in", commission_images["all"].pickings_id.ids),
            ]
        )
        _logger.warning("==========DUPLICATES: %s", duplicate_outs)

        for image_all in commission_images["all"]:
            for image_client in commission_images["client"]:
                _logger.warning(
                    "========== PRE-IMAGE A: %s ========== PRE-IMAGE B: %s"
                    % (len(image_all.pickings_id), len(image_client.pickings_id)),
                )
                image_all.pickings_id -= image_client.pickings_id
                _logger.warning(
                    "========== POST-IMAGE A: %s ========== POST-IMAGE B: %s"
                    % (len(image_all.pickings_id), len(image_client.pickings_id)),
                )

        _logger.warning("==========DUPLICATES: %s", duplicate_outs)


import random as random
import sqlite3

class CardGenerator:
    IIN = 400000

    def __init__(self):
        self.pin = str(random.sample([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)).strip("[]").replace(',', '').replace(' ', '')
        self.card_number = str(CardGenerator.luhn_algorithm(self)).strip("[]").replace(',', '').replace(' ', '')
        self.balance = 0
    def luhn_algorithm(self):
        card = [4, 0, 0, 0, 0, 0] + random.sample([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)
        temp = card.copy()
        index = 0
        for digit in temp:
            if (index + 1) % 2 != 0:
                temp[index] = digit * 2
            index += 1
        index = 0
        for digit in temp:
            if digit > 9:
                temp[index] = digit - 9
            index += 1
        total = sum(temp)
        card.append((total * 9) % 10)
        return card

    def get_card_number(self):
        return self.card_number

    def get_pin(self):
        return self.pin

class Bank:
    def __init__(self):
        self.Accounts = []
        self.Accounts_details = {}
        self.conn = sqlite3.connect('card.s3db')
        self.cur = self.conn.cursor()
        self.cur.execute('''CREATE TABLE IF NOT EXISTS card(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            number TEXT NOT NULL,
            pin TEXT NOT NULL,
            balance INTEGER DEFAULT 0
            );
            ''')
        self.conn.commit()

    def run(self):
        while True:
            choice = input('1. Create an account \n2. Log into account\n0. Exit\n')
            if choice == '1':
                Bank.create_account(self)
            elif choice == '2':
                card = input('Enter your card number:\n')
                pin = input('Enter your PIN:\n')
                if Bank.check_account(self, card, pin):
                    print('You have successfully logged in!')
                    Bank.login(self, card)
                else:
                    print('Wrong card number or PIN!')
            else:
                print('Bye!')
                exit()

    def check_account(self, card_number, pin):
        self.cur.execute('SELECT * FROM card')
        bank_data = self.cur.fetchall()

        for a in bank_data:
            if a[1] == card_number:
                if a[2] == pin:
                    return True
                else:
                    return False

    def create_account(self):
        a = CardGenerator()
        self.cur.execute(f"INSERT INTO card(number, pin, balance) VALUES({a.get_card_number()}, {a.get_pin()}, {a.balance})")
        self.conn.commit()
        print('Your card number:')
        print(a.get_card_number() + '\n')
        print('Your card PIN:')
        print(a.get_pin() + '\n')

    def login(self, card_number):
        self.cur.execute(f'SELECT * FROM card WHERE number = {card_number}')
        card = self.cur.fetchall()
        while True:
            choice = input('''
            1. Balance
            2. Add income
            3. Do transfer
            4. Close account
            5. Log out
            0. Exit
            ''')
            if choice == '1':
                Bank.checkbal(self, card_number)
            elif choice == '2':
                income = int(input('Enter income:\n'))
                Bank.addmoney(self, card_number, income)
                self.conn.commit()
                print("Income was added!")
            elif choice == '3':
                transfercard = input('Transfer\nEnter card number:\n')
                Bank.transfer(self, card_number, transfercard)
                self.conn.commit()
            elif choice == '4':
                Bank.close(self, card_number)
                print('The account has been closed!')
                self.conn.commit()
                break
            elif choice == '5':
                print('You have successfully logged out!')
                break
            else:
                print('Bye!')
                exit()
    def checkbal(self, card_number):
        current_bal = self.cur.execute(f'SELECT balance FROM card WHERE number = {card_number}').fetchone()
        print(f'Balance: {current_bal[0]}')

    def addmoney(self, card_number, income):
        current_bal = self.cur.execute(f'SELECT balance FROM card WHERE number = {card_number}').fetchone()
        updated_bal = current_bal[0] + income
        self.cur.execute(f'UPDATE card SET balance = {updated_bal} WHERE number = {card_number}')

    def transfer(self, card_number, transfercard):
        if (card_number == transfercard):
            print("You can't transfer money to the same account!")
            return
        else:
            card = self.cur.execute('SELECT number FROM card;').fetchall()
            current_bal = self.cur.execute(f'SELECT balance FROM card WHERE number = {card_number}').fetchone()
            checksum = int(transfercard[-1])
            forsum = 0
            for i in range(len(transfercard) - 1):
                digit = int(transfercard[i])
                if (i % 2 == 0):
                    digit = 2 * digit
                if digit > 9:
                    digit = digit - 9
                forsum = forsum + digit

            if (forsum + checksum)% 10 != 0 :
                print("Probably you made a mistake in the card number. Please try again!")
            else:
                listofcard = []
                for i in card:
                    listofcard.append(i[0])
                if transfercard in listofcard:
                    transferamount = int(input('Enter how much money you want to transfer:\n'))
                    if transferamount > current_bal[0]:
                        print('Not enough money!')
                    else:
                        updated_bal = current_bal[0] - transferamount
                        current_bal2 = self.cur.execute(f'SELECT balance FROM card WHERE number = {transfercard}').fetchone()
                        updated_bal2 = current_bal2[0] + transferamount
                        self.cur.execute(f'UPDATE card SET balance = {updated_bal} WHERE number = {card_number}')
                        self.cur.execute(f'UPDATE card SET balance = {updated_bal2} WHERE number = {transfercard}')

                        print("Success!")
                else:
                    print("Such a card does not exist.")

    def close(self, card_number):
        self.cur.execute(f'DELETE FROM card WHERE number = {card_number};')

B = Bank()
B.run()


#!/usr/bin/env python
import rospy
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import cv2
import time
from camera import RSD435

def measure_walloutlet(sensor, outlet_cascade, fps):
    img = sensor.color_image()
    H,W = sensor.image_size()

    # detect outles in gray image
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    gray = cv2.GaussianBlur(gray, (3,3), 0)
    outlets = outlet_cascade.detectMultiScale(gray, 1.1, 20, minSize=(10,10))

    text_horizontal = 0
    for (x,y,w,h) in outlets:
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        u = int(x + 0.5*w)
        v = int(y + 0.5*h)
        point3d = sensor.point3d(u,v)
        # print(point3d)
        # update the FPS counter
        fps.update()
        fps.stop()
        # information will be displayed on the frame
        info = [
            ("FPS", "{:.2f}".format(fps.fps())),
            ("x", "{:.2f}".format(point3d[0])),
            ("y", "{:.2f}".format(point3d[1])),
            ("z", "{:.2f}".format(point3d[2]))
        ]

        # loop over the info tuples and draw them on our frame
        for (i, (k, v)) in enumerate(info):
            text = "{}: {}".format(k, v)
            cv2.putText(img, text, (10 + text_horizontal*100, H - ((i * 20) + 20)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

        text_horizontal += 1

    cv2.namedWindow("wall outlet measurement")
    img = cv2.resize(img, None, fx=1.5, fy=1.5)
    cv2.imshow('wall outlet measurement',img)
    cv2.waitKey(3)

if __name__ == '__main__':
    rospy.init_node("measure_walloutlet", anonymous=True, log_level=rospy.INFO)
    sensor = RSD435()
    outlet_cascade = cv2.CascadeClassifier('../classifier_usa/cascade.xml')
    fps = FPS().start()
    rate = rospy.Rate(10)
    try:
        while not rospy.is_shutdown():
            if sensor.ready():
                measure_walloutlet(sensor,outlet_cascade,fps)
            rate.sleep()
    except rospy.ROSInterruptException:
        pass
    cv2.destroyAllWindows()


from pygrpy.grpy_tensors import conglomerateMobilityMatrixAtCentre
import math
import numpy as np
import pygrpy.grpy_tensors

def stokesRadius(centres, sizes):
    """
    Returns stokes radius of given conglomerate of beads treating it as a rigid
    body. See:
    https://doi.org/10.1016/j.bpj.2018.07.015
    for details.

    Parameters
    ----------
    centers: np.array
        An ``N`` by 3 array describing locations of centres of ``N`` beads.
    sizes: np.array
        An array of length ``N`` describing radii of ``N`` beads.

    Returns
    -------
    float
        Diffusive hydrodynamic size of the specified particle.

    Example
    -------
    >>> import numpy as np
    >>> centres = np.array([[0,0,0],[0,0,1]])
    >>> sizes = np.array([1,1])
    >>> pygrpy.grpy.stokesRadius(centres,sizes)
    1.1860816944024204

    """
    mobility = conglomerateMobilityMatrixAtCentre(centres, sizes)
    return (3.0 / (6.0 * math.pi)) / (mobility[0][0] + mobility[1][1] + mobility[2][2])

def ensembleAveragedStokesRadius(ensemble_centres, sizes):
    """
    Returns stokes radius estimate given ensemble of configurations assuming no rigid bonds.
    See:
    https://doi.org/10.1017/jfm.2019.652
    for details.

    Parameters
    ----------
    ensemble_centres: np.array
        An ``M`` by ``N`` by 3 array describing ``M`` conformers each with ``N`` beads
    sizes: np.array
        An array of length ``N`` describing radii of ``N`` beads.

    Returns
    -------
    float
        Diffusive apparent hydrodynamic size of ensemble of conformers.

    Example
    -------
    >>> import numpy as np
    >>> ensemble_centres = 0.1*np.arange(10*5*3).reshape(10,5,3)
    >>> sizes = 0.5*np.arange(5) + 1
    >>> pygrpy.grpy.ensembleAveragedStokesRadius(ensemble_centres,sizes)
    3.0000008218278578

    """
    grand_grand_mu = np.array(
        [pygrpy.grpy_tensors.muTT(locations, sizes) for locations in ensemble_centres]
    )
    grand_mu = np.mean(grand_grand_mu, axis=0)
    grand_trace = np.trace(grand_mu, axis1=-2, axis2=-1)

    inv_mat = np.linalg.inv(grand_trace)
    total = np.sum(inv_mat)
    return total / (2 * np.pi)


import csv
import os

# Load the specific libraries
from flask import Flask, request
from pydantic import BaseModel

# Initiate the web server
app = Flask(__name__)

# Create a class "User" (cf. CSV header)
class User(BaseModel):
    uid: int
    first_name: str
    last_name: str
    department: str

# Get the current path of the file "user.csv"
filepath = os.path.join(
    os.path.dirname(os.path.realpath(__file__)), "..", "..", "user.csv"
)

# Load the user from the CSV in local memory
users = []
with open(filepath, "r") as f:
    titles = ["uid", "first_name", "last_name", "department"]
    with open(filepath, "r") as file:
        reader = csv.DictReader(file, titles)
        next(reader)  # skip header
        for csv_user in reader:
            users.append(User(**csv_user))

# Route (path of the URL) declaration
@app.route("/")
def hello_world():
    # Print hello world HTML web page
    return "<title>Hello world</title>
Hello, World!
"

@app.route("/user/<int:uid>", methods=["PUT", "GET"])
def get_user_by_id(uid):
    # Get or Update a user by it's Id
    user = users[uid].__dict__

    # Check if it's the verb is GET (means return a user)
    if request.method == "GET":
        return user

    # Update a user by it's Id
    users[uid] = User(
        **{
            "uid": uid,
            "first_name": request.args.get("first_name"),
            "last_name": request.args.get("last_name"),
            "department": request.args.get("department"),
        }
    )
    return users[uid].__dict__

@app.route("/user", methods=["POST", "GET"])
def mgt_user():
    # Get and Insert user

    # Check if it's the verb is POST (means insert new resource)
    if request.method == "POST":
        # 5.1 Add new user
        users.append(
            User(
                **{
                    "uid": len(users) + 1,
                    "first_name": request.args.get("first_name"),
                    "last_name": request.args.get("last_name"),
                    "department": request.args.get("department"),
                }
            )
        )
        return users[-1].__dict__

    # Get a user with the help of filtering
    args = request.args
    user_filtering = args.get("first_name")
    if user_filtering is None:
        return f"Invalid filter, got {args}, expect first_name=John"
    return [usr.__dict__ for usr in users if usr.first_name == user_filtering]

@app.route("/users")
def get_users():
    # Get the list of user
    return [usr.__dict__ for usr in users]

if __name__ == "__main__":
    # Start the Web server
    app.run(debug=True, port=5100)


from typing import List

class Solution:
    def rob(self, nums: List[int]) -> int:
        if(len(nums)==0):
            return 0
        if(len(nums)==1):
            return nums[0]
        dp=[0]*len(nums)
        dp[0]=nums[0]
        dp[1]=max(nums[0],nums[1])
        for i in range(2,len(nums)):
            dp[i]=max(nums[i]+dp[i-2],dp[i-1])
        return dp[len(nums)-1]

main=Solution()
a= [2,1]
print(main.rob(a))