from flask import jsonify, g
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from flask_jwt_extended import jwt_required
from sqlalchemy import func

from ..db import db
from ..models.masters import ItemModel, AccountModel
from ..models.transactions.inventory_balances import InventoryBalancesModel
from ..schemas.inventory_balance_schema import PlainInventoryBalanceSchema, InventoryBalanceSchema, BalanceSearchSchema
from ..signals import inventory_accounting

blp = Blueprint("Inventory Balances", __name__, description="Inventory Balances Actions")

@blp.route("/balance/search/")
class Invoices(MethodView):
    @jwt_required(fresh=True)
    @blp.arguments(BalanceSearchSchema, location="query")
    def get(self, data):
        name = data.get("item_name", "")
        balances = []
        number = 0
        items = ItemModel.query.filter(ItemModel.item_name.ilike(name)).all()
        if len(items) < 1:
            abort(404, message="No such item")
        for item in items:
            result = db.session.query(
                InventoryBalancesModel.item_id,
                func.sum(InventoryBalancesModel.quantity).label('total_quantity'),
                func.sum(InventoryBalancesModel.quantity * InventoryBalancesModel.unit_cost).label('total_value')
            ).group_by(InventoryBalancesModel.item_id).filter_by(item_id=item.id).all()

            for row in result:
                item_id = row.item_id
                item_name = ItemModel.query.get(item_id).item_name
                total_quantity = row.total_quantity
                total_value = row.total_value
                number += 1
                item = {"number": number, "item_name": item_name, "quantity": total_quantity, "value": total_value}
                balances.append(item)

        return {"balances": balances}

@blp.route("/inventory-balances")
class InventoryBalanceView(MethodView):
    @jwt_required(fresh=True)
    @blp.arguments(PlainInventoryBalanceSchema)
    @blp.response(201, InventoryBalanceSchema)
    def post(self, data):
        inv_item = ItemModel.query.filter_by(item_name=data.get("item_name")).first()
        account = AccountModel.query.filter_by(account_name=data.get("account_name"),
                                               account_category="Inventory Adjustment Account").first()
        item = ItemModel.query.get(inv_item.id)
        if not item:
            abort(404, message="Item does not exist")
        if not account:
            abort(404, message="No inventory adjustment account found of that name")
        data.pop("item_name")
        data.pop("account_name")
        amount = data.get("quantity", 0) * data.get("unit_cost", 0)
        balance = InventoryBalancesModel(**data, item_id=inv_item.id)
        balance.save_to_db()
        try:
            inventory_accounting(balance_id=balance.id, item_id=balance.item_id, debit_id=item.category.account_id,
                                 credit_id=account.id, amount=amount)
        except:
            balance.delete_from_db()
            abort(500, message="Did not create accounting")
        return balance

    @jwt_required(fresh=True)
    def get(self):
        items = []
        number = 0
        result = db.session.query(
            InventoryBalancesModel.item_id,
            func.sum(InventoryBalancesModel.quantity).label('total_quantity'),
            func.sum(InventoryBalancesModel.quantity * InventoryBalancesModel.unit_cost).label('total_value')
        ).group_by(InventoryBalancesModel.item_id).all()

        for row in result:
            item_id = row.item_id
            item_name = ItemModel.query.get(item_id).item_name
            total_quantity = row.total_quantity
            total_value = row.total_value
            number += 1
            item = {"number": number, "item_name": item_name, "quantity": total_quantity, "value": total_value}
            items.append(item)
        g.items = items
        return ({"balances": items})

@blp.route("/inventory-issue")
class InventoryBalanceView(MethodView):
    @jwt_required(fresh=True)
    @blp.arguments(PlainInventoryBalanceSchema)
    def post(self, data):
        inv_item = ItemModel.query.filter_by(item_name=data.get("item_name")).first()
        account = AccountModel.query.filter_by(account_name=data.get("account_name"),
                                               account_category="Inventory Adjustment Account").first()
        if not inv_item:
            abort(404, message="Item does not exist")
        if not account:
            abort(404, message="No inventory adjustment account found of that name")
        data.pop("item_name")
        data.pop("account_name")
        sale_item_quantity = db.session.query(db.func.sum(InventoryBalancesModel.quantity)).filter_by(
            item_id=inv_item.id).scalar()
        if sale_item_quantity <= 0:
            abort(400, message="You do not have enough quantity")
        issue_items = InventoryBalancesModel.query.filter_by(item_id=inv_item.id).order_by(
            InventoryBalancesModel.date).all()

        if sale_item_quantity >= data["quantity"]:
            remaining_qty = data["quantity"]
            for item in issue_items:
                if remaining_qty > 0:
                    if item.quantity >= remaining_qty:
                        item.quantity -= remaining_qty
                        remaining_qty = 0
                        item.update_db()
                        amount = data["quantity"] * item.unit_cost
                        try:
                            inventory_accounting(balance_id=item.id, item_id=inv_item.id,
                                                 debit_id=account.id, credit_id=inv_item.category.account_id,
                                                 amount=amount)
                        except:
                            item.delete_from_db()
                            abort(500, message="Did not create accounting")

                    else:
                        remaining_qty -= item.quantity
                        item.quantity = 0
                        item.update_db()
                        amount = data["quantity"] * item.unit_cost
                        try:
                            inventory_accounting(balance_id=item.id, item_id=inv_item.id,
                                                 debit_id=account.id, credit_id=inv_item.category.account_id,
                                                 amount=amount)
                        except:
                            item.delete_from_db()
                            abort(500, message="Did not create accounting")
                else:
                    break

        return ({"balances": "reduced"})


import math
l=int(input())
n=input()
if n.count("0")==l-1:
    print(n)
else:
    if l%2==0:
        a=l//2
        b=l//2
    else:

        a=int(math.floor(l/2))
        b=int(math.ceil(l/2))

    while a!=-1 and n[a]=="0":
            a-=1
    while b!=l and n[b]=="0":
            b+=1
    st1=(l+1)*"0"+n[:a]
    st2=(l+1)*"0"+n[a:]
    st3=(l+1)*"0"+n[:b]
    st4=(l+1)*"0"+n[b:]
  #  print(st1,st2)
   # print(st3,st4)

    mlab=max(len(st1),len(st2))-1
    mlba=max(len(st3),len(st4))-1
    d=["0"]*(l+1)
    c=0
    i=-1
    while i>=-(l+1):
        u=str(int(st1[i])+int(st2[i])+c)
       # print(u)
        if len(u)>1:
            c=int(u[0])
            k=u[1]
            d[i]=str(u[1])
        else:
            d[i]=str(u)
            c=0
        i-=1
    d1=[0]*(l+1)
    i=-1
    c=0
    while i>=-l:
        u=str(int(st3[i])+int(st4[i])+c)
        if len(u)>1:
            c=int(u[0])
            k=u[1]
            d1[i]=str(u[1])
        else:
            d1[i]=str(u)
            c=0
        i-=1
   # print(d,d1)
    while d[0]==0 or d[0]=="0" :
        d.pop(0)
    while d1[0]==0 or d1[0]=="0" :
        d1.pop(0)
    if len(d)>len(d1):
        print("".join(d1))
    elif len(d1)>len(d):
        print("".join(d))
    else:
        res=0
        for i in range(len(d)):
            if d[i]<d1[i]:
                res=0
                break
            elif d1[i]<d[i]:
                res=1
                break
        if res==1:
            print("".join(d1))
        else:
            print("".join(d))


#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser(description='''This script takes the output returned from swarmv2.2.2 -w flag, which is a list of lists '\n' containing the sequence ids for each swarm, and converts it into a '\n' ASV count matrix. It will also write a reduced fasta file for the representative nodes if you want to remove swarms below a particular count threshold''')
parser.add_argument('-f' , help = "A list of accession numbers for the genomes you want to recover")
parser.add_argument('-o' , help = "The path to the genome contained in the ncbi server. you can use this as input for the gen-ncbi-wget-commands.py script")
parser.add_argument('-n' , help = "The complete collection of ncbi genomes as a text file. You can find out how to get this file here https://github.com/jvineis/get-ncbi-genomes")
args = parser.parse_args()

outfile = open(args.o, 'w')

ncbi_dict = {}
for line in open(args.n,'r'):
    x = line.strip().split('\t')
    ncbi_dict[x[0]] = x[0:len(x)]

for id in open(args.f, 'r'):
    x = id.strip()
    if x in ncbi_dict.keys():
        outfile.write(ncbi_dict[x][19]+'\n')


import pandas as pd
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import confusion_matrix
from sklearn import preprocessing
from sklearn import metrics

df_train = pd.read_csv("C:\\Users\\kp\\Pictures\\Assignments\\Naive Bayes\\SalaryData_Train.csv",header=0)
df_test = pd.read_csv("C:\\Users\\kp\\Pictures\\Assignments\\Naive Bayes\\SalaryData_Test.csv",header=0)
string_columns=["workclass","education","maritalstatus","occupation","relationship","race","sex","native"]

categorical_data = preprocessing.LabelEncoder()
for i in string_columns:
    df_train[i] = categorical_data.fit_transform(df_train[i])
    df_test[i] = categorical_data.fit_transform(df_test[i])

column_names = df_train.columns
train_X = df_train[column_names[0:13]]
train_y = df_train[column_names[13]]
test_X = df_test[column_names[0:13]]
test_y = df_test[column_names[13]]

#Gaussian Naive Bayes' Classifier used for Features which are in the form of continuous datatype
gaussian_nbc = GaussianNB()
#Multinomial Naive Bayes' Classifier used for Features which in the form of continuous datatype but mainly used for Document Classification
multinomial_nbc = MultinomialNB()

pred_gaussian = gaussian_nbc.fit(train_X,train_y).predict(test_X)
confusion_matrix(test_y,pred_gaussian)
print ("Gaussian Naive Bayes model accuracy(in %):",metrics.accuracy_score(test_y, pred_gaussian)*100)

pred_multinomial = multinomial_nbc.fit(train_X,train_y).predict(test_X)
confusion_matrix(test_y,pred_multinomial)
print("MultiNomial Naive Bayes model accuracy(in %):",metrics.accuracy_score(test_y, pred_multinomial)*100)

Supervised Learning/Classification/Naive Bayes Classification/Naive_Bayes_Classifier.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 17:54:50 2019

@author: ubuntu
"""
import pickle
import numpy as np

from dataset.base_dataset import BasePytorchDataset

class Cifar10Dataset(BasePytorchDataset):
    """原版数据集地址http://www.cs.toronto.edu/~kriz/cifar.html
    cifar10: 10个类别，每个类别6000张
    cifar100: 100个类别，每个类别600张
    单张图片为RGB 32x32的小图，总计60,000张，其中50,000张训练集，10,000张测试集
    该数据集没有索引，所以只能一次性加载到内存
    输入：data_type(数据集类型)，包括train训练集和test测试集
    输出：n,h,w,c (bgr格式), 所有图片源数据都统一用这种格式(包括voc/coco)
    """
    def __init__(self, root_path='/home/ubuntu/MyDatasets/cifar-10-batches-py/',
                 data_type='train', img_transform=None, label_transform=None, bbox_transform=None, **kwargs):
        super().__init__()
        self.img_transform = img_transform
        self.label_transform = label_transform
        self.bbox_transform = bbox_transform

        train_path = [root_path + 'data_batch_1',
                      root_path + 'data_batch_2',
                      root_path + 'data_batch_3',
                      root_path + 'data_batch_4',
                      root_path + 'data_batch_5']
        test_path = [root_path + 'test_batch']

        if data_type == 'train':
            self.path = train_path
        elif data_type == 'test':
            self.path = test_path
        else:
            raise ValueError('wrong data type, only support train/test.')
        self.meta_path = root_path + 'batches.meta'

        dataset = self.get_dataset()
        self.imgs = dataset['data']
        self.labels = dataset['target']
        self.bboxes = dataset.get('bbox', None)
        self.CLASSES = dataset['target_names']

    def get_dataset(self):
        datas = []
        labels = []
        # 获取标签
        with open(self.meta_path, 'rb') as f:  # 参考cifar源网站的python代码
            dict = pickle.load(f, encoding='bytes')
            label_names = [label.decode('utf-8') for label in dict[b'label_names']]  # decode用于去掉前缀的b
        # 获取数据
        for path in self.path:
            with open(path, 'rb') as f:
                dict = pickle.load(f, encoding='bytes')
                data = dict[b'data']               # (10000, 3072)
                label = np.array(dict[b'labels'])  # (10000,)
            datas.append(data)
            labels.append(label)
        cat_datas = np.concatenate(datas, axis=0)  # (n, 3072)->(50000,3072)
        cat_labels = np.concatenate(labels)        # (n,)->(50000,)
        # 分别提取R/G/B组成(C,H,W): 原始顺序参考官网说明
        cat_datas = cat_datas.reshape(-1, 3, 32, 32).transpose(0,2,3,1)[...,[2,1,0]]  # (b,c,h,w)->(b,h,w,c), rgb->bgr
        # 按sklearn格式返回数据
        dataset = {}
        dataset['data'] = cat_datas
        dataset['target'] = cat_labels
        dataset['target_names'] = label_names
        return dataset

    def __getitem__(self, idx):
        """常规数据集传出的是多个变量，这里改为传出dict，再在定制collate中处理堆叠
        注意：要求传出的为OrderedDict，这样在自定义collate_fn中不会出错。
        """
        data_dict = {}
        img = self.imgs[idx]
        label = self.labels[idx]

        if self.label_transform is not None:
            label = self.label_transform(label)

        if self.img_transform is not None:
            img, ori_shape, scale_shape, pad_shape, scale_factor, flip = self.img_transform(img)  # transform输出img(img, ori_shape, scale_factor), label

        img_meta = dict(ori_shape = ori_shape,
                        scale_shape = scale_shape,
                        pad_shape = pad_shape,
                        scale_factor = scale_factor,
                        flip = flip)

        data_dict = dict(img = img,
                         img_meta = img_meta,
                         gt_labels = label,
                         stack_list = ['img'])
        return data_dict

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

class Cifar100Dataset(Cifar10Dataset):
    """原版数据集地址http://www.cs.toronto.edu/~kriz/cifar.html

    cifar10: 10个类别，每个类别6000张
    cifar100: 100个类别，每个类别600张
    单张图片为RGB 32x32的小图，总计60,000张，其中50,000张训练集，10,000张测试集
    """
    def __init__(self, root_path='../dataset/source/cifar100/', data_type='train',
                 norm=None, label_transform_dict=None, one_hot=None,
                 binary=None, shuffle=None):

        train_path = [root_path + 'train']
        test_path = [root_path + 'test']

        if data_type == 'train':
            self.path = train_path
        elif data_type == 'test':
            self.path = test_path
        else:
            raise ValueError('wrong data type, only support train/test.')
        self.meta_path = [root_path + 'meta']

        dataset = self.get_dataset()
        self.imgs = dataset['data']
        self.labels = dataset['target']
        self.CLASSES = dataset['target_names']


from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from alchemy.models import *

def blacklist(request, blackemail):
	if not request.user.is_authenticated():
		return render(request, 'index.html')

	context = {}
	email2blacklist = get_object_or_404(popEmails, id=blackemail)

	if request.method == "POST":
		EmailInSpam, EmailInSpamCreated = spamAddress.objects.get_or_create(emailAddress=str(email2blacklist.fromEmail).lower(), emailHash=email2blacklist.emailHash, ipAddress=email2blacklist.senderip)
		EmailInSpam.score += 1
		EmailInSpam.save()

		if EmailInSpamCreated:
			EmailInSpam.addedByUser.add(request.user)

		if email2blacklist.whitelist:
			email2blacklist.whitelist = False

		email2blacklist.blacklist = True
		email2blacklist.save()
		return HttpResponseRedirect('/dashboard')

	context['email2blacklist'] = email2blacklist

	return render(request, 'blacklist.html', context)


"""Implementing Kruskal's algorithm using Disjoint sets."""

class DisjointSets():

    def __init__(self,n): #n:num of vertices/nodes

        self.parent = list(range(n))
        self.rank = [0]*n #rank of each vertex initially will be 0

    #find the root of the set containing u
    def find(self,u):

        if self.parent[u] != u:   #if the u is not the parent node

            #using path compressions set parent of each node in the cluster to be the root node
            self.parent[u] = self.find(self.parent[u])  #find the parent of u's parent
            print(f"{u}'s parent: {self.parent[u]}" )

        return self.parent[u]  # we can return this because now parent of u is the root of the disjoint set

    def union(self,u,v):

        print("rank og ",self.rank)
        print("parent og",self.parent)
        print(f" u: {u} and  v : {v}" )

        pu = self.find(u)
        pv = self.find(v)
        print(f"parent of u : {pu} and parent of v: {pv}" )

        if pu == pv:  #if root of both is same they are already in the same set
            print("cannot perform union since they are already in the same family")
            return False

        if self.rank[pu] > self.rank[pv]:

                self.parent[pv] = pu  #parent of root v is now parent of root of u

        elif self.rank[pu] < self.rank[pv]:

                self.parent[pu] = pv #parent of root v is now parent of root of v

        else:

            self.parent[pv] = pu
            self.rank[pu] += 1

            print("rank",self.rank)
            print("parent",self.parent)

        return True

def kruskal(edges, n):

    edges.sort()  #first sort the edges of the graph

    dsu = DisjointSets(n)

    mst = []  #to store the final mst

    for weight, u, v in edges: #for all the edges in ascending order add to mst if it doesnt produce a cycle

        if dsu.union(u, v):
            mst.append(( weight, u, v))

    return mst

n = 5
edges = [(10, 0, 1), (6, 0, 2), (5, 0, 3), (15, 1, 3), (4, 2, 3)]

mst = kruskal(edges, n)
print(mst)


from copy import deepcopy
from typing import Optional

import numpy as np
import pytest
import rospy
from geometry_msgs.msg import PoseStamped, Point, Quaternion, PointStamped, Vector3Stamped, Pose
from numpy import pi
from std_srvs.srv import Trigger
from tf.transformations import quaternion_from_matrix, quaternion_about_axis, rotation_from_matrix, quaternion_matrix

import giskardpy.utils.tfwrapper as tf
from giskardpy.configs.hsr import HSR_StandAlone, HSR_Mujoco
from giskardpy.model.utils import make_world_body_box
from giskardpy.python_interface import GiskardWrapper
from giskardpy.utils.utils import launch_launchfile
from utils_for_tests import compare_poses, GiskardTestWrapper

class HSRTestWrapper(GiskardTestWrapper):
    default_pose = {
        'arm_flex_joint': 0.0,
        'arm_lift_joint': 0.0,
        'arm_roll_joint': 0.0,
        'head_pan_joint': 0.0,
        'head_tilt_joint': 0.0,
        'wrist_flex_joint': 0.0,
        'wrist_roll_joint': 0.0,
    }
    better_pose = default_pose

    def __init__(self, config=None):
        self.tip = 'hand_gripper_tool_frame'
        self.robot_name = 'hsr'
        if config is None:
            config = HSR_StandAlone
        self.gripper_group = 'gripper'
        # self.r_gripper = rospy.ServiceProxy('r_gripper_simulator/set_joint_states', SetJointState)
        # self.l_gripper = rospy.ServiceProxy('l_gripper_simulator/set_joint_states', SetJointState)
        self.odom_root = 'odom'
        super().__init__(config)
        self.robot = self.world.groups[self.robot_name]

    def move_base(self, goal_pose):
        self.set_cart_goal(goal_pose, tip_link='base_footprint', root_link=self.world.root_link_name)
        self.plan_and_execute()

    def open_gripper(self):
        self.command_gripper(1.24)

    def close_gripper(self):
        self.command_gripper(0)

    def command_gripper(self, width):
        js = {'hand_motor_joint': width}
        self.set_joint_goal(js)
        self.plan_and_execute()

    def reset_base(self):
        p = PoseStamped()
        p.header.frame_id = 'map'
        p.pose.orientation.w = 1
        self.move_base(p)

    def reset(self):
        self.clear_world()
        # self.close_gripper()
        self.reset_base()
        self.register_group('gripper',
                            root_link_group_name=self.robot_name,
                            root_link_name='hand_palm_link')

    def teleport_base(self, goal_pose, group_name: Optional[str] = None):
        self.set_seed_odometry(base_pose=goal_pose, group_name=group_name)
        self.allow_all_collisions()
        self.plan_and_execute()

class HSRTestWrapperMujoco(HSRTestWrapper):
    def __init__(self):
        # self.r_gripper = rospy.ServiceProxy('r_gripper_simulator/set_joint_states', SetJointState)
        # self.l_gripper = rospy.ServiceProxy('l_gripper_simulator/set_joint_states', SetJointState)
        self.mujoco_reset = rospy.ServiceProxy('hsrb4s/reset', Trigger)
        self.odom_root = 'odom'
        super().__init__(HSR_Mujoco)

    def reset_base(self):
        p = PoseStamped()
        p.header.frame_id = tf.get_tf_root()
        p.pose.orientation.w = 1
        self.set_localization(p)
        self.wait_heartbeats()

    def teleport_base(self, goal_pose, group_name: Optional[str] = None):
        self.move_base(goal_pose)

    def set_localization(self, map_T_odom: PoseStamped):
        pass
        # super(HSRTestWrapper, self).set_localization(map_T_odom)

    def reset(self):
        self.mujoco_reset()
        super().reset()

    def command_gripper(self, width):
        pass

@pytest.fixture(scope='module')
def giskard(request, ros):
    launch_launchfile('package://hsr_description/launch/upload_hsrb.launch')
    c = HSRTestWrapper()
    # c = HSRTestWrapperMujoco()
    request.addfinalizer(c.tear_down)
    return c

@pytest.fixture()
def box_setup(zero_pose: HSRTestWrapper) -> HSRTestWrapper:
    p = PoseStamped()
    p.header.frame_id = 'map'
    p.pose.position.x = 1.2
    p.pose.position.y = 0
    p.pose.position.z = 0.1
    p.pose.orientation.w = 1
    zero_pose.add_box(name='box', size=(1, 1, 1), pose=p)
    return zero_pose

class TestJointGoals:
    def test_mimic_joints(self, zero_pose: HSRTestWrapper):
        arm_lift_joint = zero_pose.world.search_for_joint_name('arm_lift_joint')
        zero_pose.open_gripper()
        hand_T_finger_current = zero_pose.world.compute_fk_pose('hand_palm_link', 'hand_l_distal_link')
        hand_T_finger_expected = PoseStamped()
        hand_T_finger_expected.header.frame_id = 'hand_palm_link'
        hand_T_finger_expected.pose.position.x = -0.01675
        hand_T_finger_expected.pose.position.y = -0.0907
        hand_T_finger_expected.pose.position.z = 0.0052
        hand_T_finger_expected.pose.orientation.x = -0.0434
        hand_T_finger_expected.pose.orientation.y = 0.0
        hand_T_finger_expected.pose.orientation.z = 0.0
        hand_T_finger_expected.pose.orientation.w = 0.999
        compare_poses(hand_T_finger_current.pose, hand_T_finger_expected.pose)

        js = {'torso_lift_joint': 0.1}
        zero_pose.set_joint_goal(js, check=False)
        zero_pose.allow_all_collisions()
        zero_pose.plan_and_execute()
        np.testing.assert_almost_equal(zero_pose.world.state[arm_lift_joint].position, 0.2, decimal=2)
        base_T_torso = PoseStamped()
        base_T_torso.header.frame_id = 'base_footprint'
        base_T_torso.pose.position.x = 0
        base_T_torso.pose.position.y = 0
        base_T_torso.pose.position.z = 0.8518
        base_T_torso.pose.orientation.x = 0
        base_T_torso.pose.orientation.y = 0
        base_T_torso.pose.orientation.z = 0
        base_T_torso.pose.orientation.w = 1
        base_T_torso2 = zero_pose.world.compute_fk_pose('base_footprint', 'torso_lift_link')
        compare_poses(base_T_torso2.pose, base_T_torso.pose)

    def test_mimic_joints2(self, zero_pose: HSRTestWrapper):
        arm_lift_joint = zero_pose.world.search_for_joint_name('arm_lift_joint')
        zero_pose.open_gripper()

        tip = 'hand_gripper_tool_frame'
        p = PoseStamped()
        p.header.frame_id = tip
        p.pose.position.z = 0.2
        p.pose.orientation.w = 1
        zero_pose.set_cart_goal(goal_pose=p, tip_link=tip,
                                root_link='base_footprint')
        zero_pose.allow_all_collisions()
        zero_pose.plan_and_execute()
        np.testing.assert_almost_equal(zero_pose.world.state[arm_lift_joint].position, 0.2, decimal=2)
        base_T_torso = PoseStamped()
        base_T_torso.header.frame_id = 'base_footprint'
        base_T_torso.pose.position.x = 0
        base_T_torso.pose.position.y = 0
        base_T_torso.pose.position.z = 0.8518
        base_T_torso.pose.orientation.x = 0
        base_T_torso.pose.orientation.y = 0
        base_T_torso.pose.orientation.z = 0
        base_T_torso.pose.orientation.w = 1
        base_T_torso2 = zero_pose.world.compute_fk_pose('base_footprint', 'torso_lift_link')
        compare_poses(base_T_torso2.pose, base_T_torso.pose)

    def test_mimic_joints3(self, zero_pose: HSRTestWrapper):
        arm_lift_joint = zero_pose.world.search_for_joint_name('arm_lift_joint')
        zero_pose.open_gripper()
        tip = 'head_pan_link'
        p = PoseStamped()
        p.header.frame_id = tip
        p.pose.position.z = 0.15
        p.pose.orientation.w = 1
        zero_pose.set_cart_goal(goal_pose=p, tip_link=tip,
                                root_link='base_footprint')
        zero_pose.plan_and_execute()
        np.testing.assert_almost_equal(zero_pose.world.state[arm_lift_joint].position, 0.3, decimal=2)
        base_T_torso = PoseStamped()
        base_T_torso.header.frame_id = 'base_footprint'
        base_T_torso.pose.position.x = 0
        base_T_torso.pose.position.y = 0
        base_T_torso.pose.position.z = 0.902
        base_T_torso.pose.orientation.x = 0
        base_T_torso.pose.orientation.y = 0
        base_T_torso.pose.orientation.z = 0
        base_T_torso.pose.orientation.w = 1
        base_T_torso2 = zero_pose.world.compute_fk_pose('base_footprint', 'torso_lift_link')
        compare_poses(base_T_torso2.pose, base_T_torso.pose)

    def test_mimic_joints4(self, zero_pose: HSRTestWrapper):
        joint_goal = {'torso_lift_joint': 0.25}
        zero_pose.set_joint_goal(joint_goal, check=False)
        zero_pose.allow_all_collisions()
        zero_pose.plan_and_execute()
        np.testing.assert_almost_equal(zero_pose.world.state['hsrb/arm_lift_joint'].position, 0.5, decimal=2)

class TestCartGoals:
    def test_save_graph_pdf(self, kitchen_setup):
        box1_name = 'box1'
        pose = PoseStamped()
        pose.header.frame_id = kitchen_setup.default_root
        pose.pose.orientation.w = 1
        kitchen_setup.add_box(name=box1_name,
                              size=(1,1,1),
                              pose=pose,
                              parent_link='hand_palm_link',
                              parent_link_group='hsrb')
        kitchen_setup.world.save_graph_pdf()

    def test_move_base(self, zero_pose: HSRTestWrapper):
        map_T_odom = PoseStamped()
        map_T_odom.pose.position.x = 1
        map_T_odom.pose.position.y = 1
        map_T_odom.pose.orientation = Quaternion(*quaternion_about_axis(np.pi / 3, [0, 0, 1]))
        zero_pose.teleport_base(map_T_odom)

        base_goal = PoseStamped()
        base_goal.header.frame_id = 'map'
        base_goal.pose.position.x = 1
        base_goal.pose.orientation = Quaternion(*quaternion_about_axis(pi, [0, 0, 1]))
        zero_pose.set_cart_goal(base_goal, 'base_footprint')
        zero_pose.allow_all_collisions()
        zero_pose.plan_and_execute()

    def test_rotate_gripper(self, zero_pose: HSRTestWrapper):
        r_goal = PoseStamped()
        r_goal.header.frame_id = zero_pose.tip
        r_goal.pose.orientation = Quaternion(*quaternion_about_axis(pi, [0, 0, 1]))
        zero_pose.set_cart_goal(r_goal, zero_pose.tip)
        zero_pose.allow_all_collisions()
        zero_pose.plan_and_execute()

class TestConstraints:

    def test_open_fridge(self, kitchen_setup: HSRTestWrapper):
        handle_frame_id = 'iai_kitchen/iai_fridge_door_handle'
        handle_name = 'iai_fridge_door_handle'
        kitchen_setup.open_gripper()
        base_goal = PoseStamped()
        base_goal.header.frame_id = 'map'
        base_goal.pose.position = Point(0.3, -0.5, 0)
        base_goal.pose.orientation.w = 1
        kitchen_setup.move_base(base_goal)

        bar_axis = Vector3Stamped()
        bar_axis.header.frame_id = handle_frame_id
        bar_axis.vector.z = 1

        bar_center = PointStamped()
        bar_center.header.frame_id = handle_frame_id

        tip_grasp_axis = Vector3Stamped()
        tip_grasp_axis.header.frame_id = kitchen_setup.tip
        tip_grasp_axis.vector.x = 1

        kitchen_setup.set_json_goal('GraspBar',
                                    root_link=kitchen_setup.default_root,
                                    tip_link=kitchen_setup.tip,
                                    tip_grasp_axis=tip_grasp_axis,
                                    bar_center=bar_center,
                                    bar_axis=bar_axis,
                                    bar_length=.4)
        x_gripper = Vector3Stamped()
        x_gripper.header.frame_id = kitchen_setup.tip
        x_gripper.vector.z = 1

        x_goal = Vector3Stamped()
        x_goal.header.frame_id = handle_frame_id
        x_goal.vector.x = -1
        kitchen_setup.set_align_planes_goal(tip_link=kitchen_setup.tip,
                                            tip_normal=x_gripper,
                                            goal_normal=x_goal)
        kitchen_setup.allow_all_collisions()
        # kitchen_setup.add_json_goal('AvoidJointLimits', percentage=10)
        kitchen_setup.plan_and_execute()

        kitchen_setup.set_open_container_goal(tip_link=kitchen_setup.tip,
                                              environment_link=handle_name,
                                              goal_joint_state=1.5)
        # kitchen_setup.set_json_goal('AvoidJointLimits', percentage=40)
        kitchen_setup.allow_all_collisions()
        # kitchen_setup.add_json_goal('AvoidJointLimits')
        kitchen_setup.plan_and_execute()
        kitchen_setup.set_kitchen_js({'iai_fridge_door_joint': 1.5})

        kitchen_setup.set_open_container_goal(tip_link=kitchen_setup.tip,
                                              environment_link=handle_name,
                                              goal_joint_state=0)
        kitchen_setup.allow_all_collisions()
        # kitchen_setup.set_json_goal('AvoidJointLimits', percentage=40)
        kitchen_setup.plan_and_execute()
        kitchen_setup.set_kitchen_js({'iai_fridge_door_joint': 0})

        kitchen_setup.plan_and_execute()

        kitchen_setup.set_joint_goal(kitchen_setup.better_pose)
        kitchen_setup.allow_self_collision()
        kitchen_setup.plan_and_execute()

class TestCollisionAvoidanceGoals:

    def test_self_collision_avoidance(self, zero_pose: HSRTestWrapper):
        r_goal = PoseStamped()
        r_goal.header.frame_id = zero_pose.tip
        r_goal.pose.position.z = 0.5
        r_goal.pose.orientation.w = 1
        zero_pose.set_cart_goal(r_goal, zero_pose.tip)
        zero_pose.plan_and_execute()

    def test_self_collision_avoidance2(self, zero_pose: HSRTestWrapper):
        js = {
            'arm_flex_joint': 0.0,
            'arm_lift_joint': 0.0,
            'arm_roll_joint': -1.52,
            'head_pan_joint': -0.09,
            'head_tilt_joint': -0.62,
            'wrist_flex_joint': -1.55,
            'wrist_roll_joint': 0.11,
        }
        zero_pose.set_joint_goal(js)
        zero_pose.allow_all_collisions()
        zero_pose.plan_and_execute()

        goal_pose = PoseStamped()
        goal_pose.header.frame_id = 'hand_palm_link'
        goal_pose.pose.position.x = 0.5
        goal_pose.pose.orientation.w = 1
        zero_pose.set_cart_goal(goal_pose, zero_pose.tip)
        zero_pose.plan_and_execute()

    def test_attached_collision1(self, box_setup: HSRTestWrapper):
        box_name = 'asdf'
        box_pose = PoseStamped()
        box_pose.header.frame_id = 'map'
        box_pose.pose.position = Point(0.85, 0.3, .66)
        box_pose.pose.orientation = Quaternion(0, 0, 0, 1)

        box_setup.add_box(box_name, (0.07, 0.04, 0.1), box_pose)
        box_setup.open_gripper()

        grasp_pose = deepcopy(box_pose)
        # grasp_pose.pose.position.x -= 0.05
        grasp_pose.pose.orientation = Quaternion(*quaternion_from_matrix([[0, 0, 1, 0],
                                                                          [0, -1, 0, 0],
                                                                          [1, 0, 0, 0],
                                                                          [0, 0, 0, 1]]))
        box_setup.set_cart_goal(grasp_pose, box_setup.tip)
        box_setup.plan_and_execute()
        box_setup.update_parent_link_of_group(box_name, box_setup.tip)

        base_goal = PoseStamped()
        base_goal.header.frame_id = box_setup.default_root
        base_goal.pose.position.x -= 0.5
        base_goal.pose.orientation.w = 1
        box_setup.move_base(base_goal)

    def test_collision_avoidance(self, zero_pose: HSRTestWrapper):
        js = {'arm_flex_joint': -np.pi / 2}
        zero_pose.set_joint_goal(js)
        zero_pose.plan_and_execute()

        p = PoseStamped()
        p.header.frame_id = 'map'
        p.pose.position.x = 0.9
        p.pose.position.y = 0
        p.pose.position.z = 0.5
        p.pose.orientation.w = 1
        zero_pose.add_box(name='box', size=(1, 1, 0.01), pose=p)

        js = {'arm_flex_joint': 0}
        zero_pose.set_joint_goal(js, check=False)
        zero_pose.plan_and_execute()


#   Auther      : Heinz Samuelsson
#   Date        : 2015-10-04
#   File        : switch1.py
#   Reference   : -
#   Description : 8 Clickable switches.
#   Python ver  : 2.7.3 (gcc 4.6.3)

import pygame, sys
from pygame.locals import *
import sys
import os

WINDOW_POS  = (90, 90)
WINDOW_SIZE = (1024, 500)
SWITCH_SIZE = (200, 200)

SWITCH_X_START_POSITION = 10
Y_POS = 90
X_POS = SWITCH_X_START_POSITION + 120

RED = (255, 0, 0)

#           x1         y1  x2             y2
SWITCH_1 = (X_POS,     Y_POS, X_POS,      210)  # 130
SWITCH_2 = (X_POS+110, Y_POS, X_POS+120,  210)  # 240
SWITCH_3 = (X_POS+220, Y_POS, X_POS+220,  210)  # 350
SWITCH_4 = (X_POS+330, Y_POS, X_POS+330,  210)  # 460
SWITCH_5 = (X_POS+440, Y_POS, X_POS+440,  210)  # 570
SWITCH_6 = (X_POS+550, Y_POS, X_POS+550,  210)  # 680
SWITCH_7 = (X_POS+660, Y_POS, X_POS+660,  210)  # 790
SWITCH_8 = (X_POS+770, Y_POS, X_POS+770,  210)  # 900

def draw_lines(screen):

    x, y = screen.get_size()

    # vertical lines
    pygame.draw.line(screen, RED, (10,Y_POS),  (x-10,Y_POS))
    pygame.draw.line(screen, RED, (10,210), (x-10,210))

    # horizontal lines
    pygame.draw.line(screen, RED, (130,10), (130,y-10))
    pygame.draw.line(screen, RED, (240,10), (240,y-10))
    pygame.draw.line(screen, RED, (350,10), (350,y-10))
    pygame.draw.line(screen, RED, (460,10), (460,y-10))
    pygame.draw.line(screen, RED, (570,10), (570,y-10))
    pygame.draw.line(screen, RED, (680,10), (680,y-10))
    pygame.draw.line(screen, RED, (790,10), (790,y-10))
    pygame.draw.line(screen, RED, (900,10), (900,y-10))

# check if and which switch that was clicked
def switch_clicked(pos):

    leftButtonOK  = False
    rightButtonOK = False

    # check mouse ON position for switch 1
    if ((pos[0] > SWITCH_1[0]-30) and (pos[0] < SWITCH_1[0]+30) and
        (pos[1] > SWITCH_1[1]-30) and (pos[1] < SWITCH_1[1]+30)):

        leftButtonOK = True
        return 'switchOn_1'

    # check mouse OFF position for switch 1
    elif ((pos[0] > SWITCH_1[2]-30) and (pos[0] < SWITCH_1[2]+30) and
          (pos[1] > SWITCH_1[3]-30) and (pos[1] < SWITCH_1[3]+30)):

        rightButtonOK = True
        return 'switchOff_1'

    # check mouse ON position for switch 2
    elif ((pos[0] > SWITCH_2[0]-30) and (pos[0] < SWITCH_2[0]+30) and
          (pos[1] > SWITCH_2[1]-30) and (pos[1] < SWITCH_2[1]+30)):

        leftButtonOK = True
        return 'switchOn_2'

    # check mouse OFF position for switch 2
    elif ((pos[0] > SWITCH_2[2]-30) and (pos[0] < SWITCH_2[2]+30) and
          (pos[1] > SWITCH_2[3]-30) and (pos[1] < SWITCH_2[3]+30)):
        rightButtonOK = True
        return 'switchOff_2'

    # check mouse ON position for switch 3
    elif ((pos[0] > SWITCH_3[0]-30) and (pos[0] < SWITCH_3[0]+30) and
          (pos[1] > SWITCH_3[1]-30) and (pos[1] < SWITCH_3[1]+30)):

        leftButtonOK = True
        return 'switchOn_3'

    # check mouse OFF position for switch 3
    elif ((pos[0] > SWITCH_3[2]-30) and (pos[0] < SWITCH_3[2]+30) and
          (pos[1] > SWITCH_3[3]-30) and (pos[1] < SWITCH_3[3]+30)):
        rightButtonOK = True
        return 'switchOff_3'

    # check mouse ON position for switch 4
    elif ((pos[0] > SWITCH_4[0]-30) and (pos[0] < SWITCH_4[0]+30) and
          (pos[1] > SWITCH_4[1]-30) and (pos[1] < SWITCH_4[1]+30)):

        leftButtonOK = True
        return 'switchOn_4'

    # check mouse OFF position for switch 4
    elif ((pos[0] > SWITCH_4[2]-30) and (pos[0] < SWITCH_4[2]+30) and
          (pos[1] > SWITCH_4[3]-30) and (pos[1] < SWITCH_4[3]+30)):
        rightButtonOK = True
        return 'switchOff_4'

    # check mouse ON position for switch 5
    elif ((pos[0] > SWITCH_5[0]-30) and (pos[0] < SWITCH_5[0]+30) and
          (pos[1] > SWITCH_5[1]-30) and (pos[1] < SWITCH_5[1]+30)):

        leftButtonOK = True
        return 'switchOn_5'

    # check mouse OFF position for switch 5
    elif ((pos[0] > SWITCH_5[2]-30) and (pos[0] < SWITCH_5[2]+30) and
          (pos[1] > SWITCH_5[3]-30) and (pos[1] < SWITCH_5[3]+30)):
        rightButtonOK = True
        return 'switchOff_5'

    # check mouse ON position for switch 6
    elif ((pos[0] > SWITCH_6[0]-30) and (pos[0] < SWITCH_6[0]+30) and
          (pos[1] > SWITCH_6[1]-30) and (pos[1] < SWITCH_6[1]+30)):

        leftButtonOK = True
        return 'switchOn_6'

    # check mouse OFF position for switch 6
    elif ((pos[0] > SWITCH_6[2]-30) and (pos[0] < SWITCH_6[2]+30) and
          (pos[1] > SWITCH_6[3]-30) and (pos[1] < SWITCH_6[3]+30)):
        rightButtonOK = True
        return 'switchOff_6'

    # check mouse ON position for switch 7
    elif ((pos[0] > SWITCH_7[0]-30) and (pos[0] < SWITCH_7[0]+30) and
          (pos[1] > SWITCH_7[1]-30) and (pos[1] < SWITCH_7[1]+30)):

        leftButtonOK = True
        return 'switchOn_7'

    # check mouse OFF position for switch 7
    elif ((pos[0] > SWITCH_7[2]-30) and (pos[0] < SWITCH_7[2]+30) and
          (pos[1] > SWITCH_7[3]-30) and (pos[1] < SWITCH_7[3]+30)):
        rightButtonOK = True
        return 'switchOff_7'

    # check mouse ON position for switch 8
    elif ((pos[0] > SWITCH_8[0]-30) and (pos[0] < SWITCH_8[0]+30) and
          (pos[1] > SWITCH_8[1]-30) and (pos[1] < SWITCH_8[1]+30)):

        leftButtonOK = True
        return 'switchOn_8'

    # check mouse OFF position for switch 8
    elif ((pos[0] > SWITCH_8[2]-30) and (pos[0] < SWITCH_8[2]+30) and
          (pos[1] > SWITCH_8[3]-30) and (pos[1] < SWITCH_8[3]+30)):
        rightButtonOK = True
        return 'switchOff_8'

def main():

    # position window
    os.environ["SDL_VIDEO_WINDOW_POS"] = "%d, %d" % WINDOW_POS

    pygame.init()
    screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32)

    pygame.display.set_caption('Switch test')

    # load switch images
    greenSwitch = pygame.image.load('switch_green.gif')
    redSwitch   = pygame.image.load('switch_red.gif')

    # fix background color to white
    background = pygame.Surface(screen.get_size())

    # fill with grey background
    background.fill((220, 220, 220))
    screen.blit(background,(0, 0))

    # blit all switches at the beginning
    for i in range(0, 8):
        screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+i*110, 30))

    # default value
    switchOnOff = 'None'

    while True:

       for event in pygame.event.get():
           # quit pressed?
           if event.type == QUIT:
               pygame.quit()
               sys.exit()

           # mouse button pressed?
           elif event.type == pygame.MOUSEBUTTONUP:
               mousePos = pygame.mouse.get_pos()
               switchOnOff = switch_clicked(mousePos)

           # if escape key then quit application
           elif event.type == pygame.KEYDOWN:
               if event.key == pygame.K_ESCAPE:
                   pygame.quit()
                   sys.exit()

       # blit switch 1 ON/OFF
       if switchOnOff == 'switchOn_1':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION, 30))
       elif switchOnOff == 'switchOff_1':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION, 30))

       # blit switch 2 ON/OFF
       elif switchOnOff == 'switchOn_2':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+110, 30))
       elif switchOnOff == 'switchOff_2':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+110, 30))

       # blit switch 3 ON/OFF
       elif switchOnOff == 'switchOn_3':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+220, 30))
       elif switchOnOff == 'switchOff_3':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+220, 30))

       # blit switch 4 ON/OFF
       elif switchOnOff == 'switchOn_4':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+330, 30))
       elif switchOnOff == 'switchOff_4':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+330, 30))

       # blit switch 5 ON/OFF
       elif switchOnOff == 'switchOn_5':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+440, 30))
       elif switchOnOff == 'switchOff_5':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+440, 30))

       # blit switch 6 ON/OFF
       elif switchOnOff == 'switchOn_6':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+550, 30))
       elif switchOnOff == 'switchOff_6':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+550, 30))

       # blit switch 7 ON/OFF
       elif switchOnOff == 'switchOn_7':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+660, 30))
       elif switchOnOff == 'switchOff_7':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+660, 30))

       # blit switch 8 ON/OFF
       elif switchOnOff == 'switchOn_8':
           screen.blit(pygame.transform.scale(greenSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+770, 30))
       elif switchOnOff == 'switchOff_8':
           screen.blit(pygame.transform.scale(redSwitch, SWITCH_SIZE), (SWITCH_X_START_POSITION+770, 30))

       #draw_lines(screen)
       pygame.display.flip()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Sat May 25 17:57:47 2019

@author: Elvis Ma
"""

import pandas as pd
import numpy as np
import os

wd="C:/Users/Elvis Ma/Desktop/Weekly Work/Forecast Numbers"
os.chdir(wd)
fcst_combine=pd.DataFrame()
fcst_book=pd.ExcelFile("FcstNum.xlsx")
for sheet in fcst_book.sheet_names:
    df=pd.read_excel(fcst_book, sheet_name=sheet)
    fcst_combine=fcst_combine.append(df)

fcst_combine.to_excel("fcst_combine.xlsx", sheet_name="all", index=False)


"""
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

All of the nodes' values will be unique.
p and q are different and both values will exist in the binary tree.
"""

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        self.p = p
        self.q = q
        res, _, _ = self._dfs(root)
        return res

    def _dfs(self, root):
        if not root:
            return None, False, False

        left_res, left_p, left_q = self._dfs(root.left)
        right_res, right_p, right_q = self._dfs(root.right)

        cur_p = True if root.val == p.val else False
        cur_q = True if root.val == q.val else False

        if left_res is not None:
            return left_res, True, True
        if right_res is not None:
            return right_res, True, True

        find_p = False
        if cur_p or left_p or right_p:
            find_p = True
        find_q = False
        if cur_q or left_q or right_q:
            find_q = True

        if find_p and find_q:
            return root, True, True

        return None, find_p, find_q

"""
Note:
Recurring can pass message back by using return. So we don't need to do the dfs twice(Check and Search)
"""


'''
Created on 28/ott/2009

@author: andrea pierleoni

Handles a set of Graphic Representation for biological Entities.

quote:
That's what I like in matplotlib: no matter how hard you try,
there's always a simpler solution you're not yet aware of...

'''
import operator, warnings
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle, Circle, Wedge, Polygon, FancyBboxPatch, FancyArrow
from matplotlib.font_manager import FontProperties
from matplotlib.text import Annotation

class BaseTrack(object):
    '''
    The :class:`BaseTrack` acts as a collector of :class:`~biograpy.features` \
    objects, and accounts for their ordering and color.
    The :class:`BaseTrack` is a functiona baseclass to use in order to generate\
    additional tracks.
    Track object have to be added to a :class:`~biograpy.drawer.Panel` instance\
    once they are filled with features

    ``track = BaseTrack(name = 'test')``

    gives a empty track with default values named ``'test'``

    Valid keyword arguments for :class:`BaseTrack` are:

        ===================== ==================================================
        Key                   Description
        ===================== ==================================================
        name                  Define the track `name`
        show_name             ``'top'`` | ``'bottom'`` |  ``None`` , default is
                              ``'top'`` . If a track `name` is specified  set
                              where the name wil be displayed
        name_font_size        default ``'small'``, accepts font size parameter
                              as in matplotlib
        name_font_family      default ``'serif'``, accepts font family
                              parameter as in matplotlib
        name_font_weight      default ``'semibold'``, accepts font weight
                              parameter as in matplotlib
        draw_axis             a list contanining this possible values:
                              ``'right'`` | ``'left'`` | ``'top'`` |
                              ``'bottom'`` | ``'force no axis'`` . default is
                              ``['bottom']``. each specified axis position will
                              be drawn. if ``'force no axis'`` is specified no
                              axis will be shown, this is only needed if tracks
                              are requested to be joined.
        x_use_sequence        if a string iterable is passed it will be used as
                              X tick labels
        xticks_major          set X major ticks as in matplotlib
        xticks_minor          set X minor ticks as in matplotlib
        xticklabels_major     set X major tick labels as in matplotlib
        xticklabels_minor     set X minor tick labels as in matplotlib
        yticks_major          set Y major ticks as in matplotlib
        yticks_minor          set Y minor ticks as in matplotlib
        yticklabels_major     set Y major tick labels as in matplotlib
        yticklabels_minor     set Y minor tick labels as in matplotlib
        show_xticklabels      ``True`` | ``False``. default is ``True``
        show_yticklabels      ``True`` | ``False``. default is ``False``
        tickfontsize_major    default ``'x-small'``, accepts font size parameter
                              as in matplotlib
        tickfontsize_minor    default ``'xx-small'``, accepts font size
                              parameter as in matplotlib
        track_height          specify the the axis heigth by pixel number.
                              default is ``0`` and will be set automatically
        max_score             default is ``None``, if not specified will be
                              dynamically computed basing on feature scores
        min_score             default is ``None``, if not specified will be
                              dynamically computed basing on feature scores
        norm                  score normalizing function. default is ``None``
                              and will be created using maximum and minimum
                              feature scores. could be any function taking a
                              int or float value an returning a float between
                              ``0.`` and ``1.``
        cm                    matplotlib colormap name to use for score-based
                              feature color. default is ``'Accent'``
        draw_cb               ``True`` | ``False``. default is ``False``. draws
                              a colorbar inside the track to explain score-based
                              feature color
        cb_alpha              colorbar alpha value, a float between ``0.`` and
                              ``1.``
        cb_label              colorbar label, a string
        track_lines           internal parameter used to defin track heigth in
                              automatic mode. default is
                              ``1*number_of feature_lines``. if forced can
                              results in wrong feature proportions
        sort_by               ``'score'`` | ``'length'`` | ``'collapse'`` |
                              ``None``.
                              default is ``'collapse'``

                              * ``'collapse'`` will arrange features in the \
                              minimum vertical space possible.
                              * ``'score'`` will arrange features basing \
                              on score values.
                              * ``'length'`` will arrange features basing \
                              on feature length.
                              * ``None`` will arrange features basing \
                              in the order they are passed to the track.
        sort_order            ``'top'`` | ``'bottom'``, default is ``'top'``.
                              use to reverse order
        ===================== ==================================================
'''

    Ycord = 0.0
    _betw_feat_space = 2

    default_cm='Accent'#deafult matplotlib colormap to use

    def __init__(self, *args, **kwargs):
        '''
        '''

        self.name = kwargs.get('name','')
        if self.name:
            self.show_name = kwargs.get('show_name', 'top')
        else:
            self.show_name = None
        self.max_score = kwargs.get('max_score', None)
        self.min_score = kwargs.get('min_score', None)
        self.draw_axis = kwargs.get('draw_axis', ["bottom"] )
        self.xticks_major = kwargs.get('xticks_major', None )
        self.xticks_minor = kwargs.get('xticks_minor', None )
        self.xticklabels_major = kwargs.get('xticklabels_major', None )
        self.xticklabels_minor = kwargs.get('xticklabels_minor', None )
        self.yticks_major = kwargs.get('yticks_major', None )
        self.yticks_minor = kwargs.get('yticks_minor', None )
        self.yticklabels_major = kwargs.get('yticklabels_major', None )
        self.yticklabels_minor = kwargs.get('yticklabels_minor', None )
        self.x_use_sequence = kwargs.get('x_use_sequence', False )
        self.show_xticklabels = kwargs.get('show_xticklabels', False )
        self.show_yticklabels = kwargs.get('show_yticklabels', False )
        self.tickfontsize =  kwargs.get('tickfontsize', 'x-small' )
        self.tickfontsize =  kwargs.get('tickfontsize_major', 'x-small' )
        self.tickfontsize_minor =  kwargs.get('tickfontsize_minor', 'xx-small' )
        self.ymax = 0
        self.track_height = kwargs.get('track_height', 0)

        self.norm = kwargs.get('norm', None)# normalizing function, if None build one. could be any function taking a value an returning a float between 0 and 1
        if not self.norm:
            self.norm = colors.normalize(vmin = self.min_score, vmax = self.max_score)

        self.cm = cm.get_cmap(kwargs.get('cm', self.default_cm))
        #self.colormap = cm.get_cmap(self.cm)
        self.draw_cb = kwargs.get('draw_cb', False)
        self.cb_alpha = kwargs.get('cb_alpha', 1)
        self.cb_label = kwargs.get('cb_label', None)

        self.name_font_size = kwargs.get('name_font_size', 'small' )
        self.name_font_family = kwargs.get('name_font_family', 'serif' )
        self.name_font_weight = kwargs.get('name_font_weight', 'semibold' )
        font_feat=FontProperties()
        font_feat.set_size(self.name_font_size)
        font_feat.set_family(self.name_font_family)
        font_feat.set_weight('semibold')
        self.name_font_feat = font_feat

        self.drawn_lines = kwargs.get('track_lines', 0 )
        if self.show_name:
            self.drawn_lines += 1

        self.sort_by = kwargs.get('sort_by', 'collapse' )# can also be: score, length, collapse or None. None means the features are plotted in the order they get added
        self.sort_order = kwargs.get('sort_order', 'top')# can be top or bottom
        self.features = [] # this will contains all the Graphicfeatures of the panel
        self.xmin = None
        self.xmax = None

        for feature in args:
            self.add_feature(feature)

    def add_feature(self, feature):
        '''add  :class:`~biograpy.features` object to track.'''
        def add(feature):
            self.features.append(feature)
            if self.xmin == None:
                self.xmin = feature.start
            else:
                self.xmin = min([feature.start, self.xmin])
            if self.xmax == None:
                self.xmax = feature.end
            else:
                self.xmax = max([feature.end, self.xmax])

        if isinstance(feature, list):
            for feat in feature:
                add(feature)
        else:
            add(feature)

    def append(self, feature):
        '''add  :class:`~biograpy.features` object to track.
        same as :func:`~biograpy.tracks.BaseTrack.add_feature`'''
        #check for graphicfeature istance?
        self.add_feature(feature)

    def extend(self, features):
        '''add a sequence of features to track'''
        #check for graphicfeature istance?
        for feature in features:
            self.add_feature(feature)

    def _collapse(self, dpi,):
        '''collapse features '''
        plt.draw()
        # this is necessary to estimate the text dimensions and avoid collisions until draw
        # is not called the text object do not know its renderer and cannot call get_window_extent method.
        line_controller=[]
        size_memory={}
        draw_features = []
        while len(draw_features) < len(self.features):
            for feat_numb, feat2draw in enumerate(self.features):
                '''estimate feature lenght'''
                if feat_numb not in size_memory:
                    xs_patches=[]
                    for patch in feat2draw.patches:
                        #for p in patch:
                        try:
                            bbox=patch.get_window_extent(None,)
                        except:
                            warnings.warn('could not find box coordinated for patch: '+str(patch) )
                            continue
                        xs_patches.append(bbox.xmax)
                        xs_patches.append(bbox.xmin)
                    for fname in feat2draw.feat_name:
                        # set the correct dpi to correctly estimate text size.
                        # required by Text class in matplotlib
                        bbox = fname.get_window_extent(dpi = dpi)
                        xs_patches.append(bbox.xmax)
                        xs_patches.append(bbox.xmin)
                    size_memory[feat_numb]={'left_margin' : min(xs_patches),
                                    'right_margin' : max(xs_patches)}

                ''' Check for collisions both on text and patches'''
                if feat_numb not in draw_features:
                    draw=True
                    for prev_start,prev_end in line_controller:
                        if  (prev_start <= size_memory[feat_numb]['left_margin'] <= prev_end) or \
                            (prev_start <= size_memory[feat_numb]['right_margin'] <= prev_end) or \
                            ((size_memory[feat_numb]['left_margin'] < prev_start < size_memory[feat_numb]['right_margin']) and \
                             (size_memory[feat_numb]['left_margin'] < prev_end < size_memory[feat_numb]['right_margin'])):
                            draw = False
                            break
                    if draw:
                        '''Draw if not collision '''
                        line_controller.append([size_memory[feat_numb]['left_margin'],size_memory[feat_numb]['right_margin']])
                        for patch in feat2draw.patches:
                            if isinstance(patch, Line2D):
                                current_ys = patch.get_ydata()
                                new_ys = map(operator.add, current_ys, [self.Ycord] * len(current_ys))
                                patch.set_ydata(new_ys)

                            elif isinstance(patch, FancyArrow):
                                current_xy=patch.get_xy()
                                new_xy=[]
                                for x, y in current_xy:
                                    new_xy.append([x, y + self.Ycord])
                                patch.set_xy(new_xy)
                            elif isinstance(patch, Annotation):
                                current_x, current_y = patch.xytext
                                patch.xytext = (current_x, current_y + self.Ycord)
                            else:
                                try:
                                    current_y = patch.get_y()
                                except AttributeError:
                                    current_y = patch.get_position()[1]
                                patch.set_y(current_y + self.Ycord)

                        for iname, fname in enumerate(feat2draw.feat_name):
                            y=fname.get_position()[1]
                            feat2draw.feat_name[iname].set_y(y + self.Ycord)
                            current_x, current_y = fname.xytext
                            feat2draw.feat_name[iname].xytext = (current_x, current_y + self.Ycord)
                        draw_features.append(feat_numb)

            #if len(draw_features) < len(self.features):
            self.Ycord-=self._betw_feat_space
            line_controller=[]
            self.drawn_lines += 1

    def _order_by_score(self,):
        '''order features by score '''
        feat_list = []
        for feat in self.features:
            feat_list.append([feat.score, feat])
        if self.sort_order == 'top':
            feat_list.sort()
        elif self.sort_order == 'bottom':
            feat_list.sort()
            feat_list.reverse()
        else:
            raise ValueError('Wrong Sort order option: %s'%self.sort_order )

        return [feat for (i,feat) in feat_list]

    def _order_by_length(self,):
        ''' order basing on the actual length of the feature patches in the figure '''

        feat_list = []
        for feat in self.features:
            xs_patches = []
            for patch in feat.patches:
                bbox=patch.get_window_extent(None)
                xs_patches.append(bbox.xmax)
                xs_patches.append(bbox.xmin)
            feat_list.append([max(xs_patches) - min(xs_patches), feat])
        if self.sort_order == 'top':
            feat_list.sort()
        elif self.sort_order == 'bottom':
            feat_list.sort()
            feat_list.reverse()
        else:
            raise ValueError('Wrong Sort order option: %s'%self.sort_order )

        return [feat for (i,feat) in feat_list]

    def _draw_ordered_features(self, feat_list = None,):
        '''draws one feature per line in the track in the order they are passed'''
        if not feat_list:
            feat_list = self.features
        for feat2draw in feat_list:
            for patch in feat2draw.patches:
                if isinstance(patch, Line2D):
                    current_ys = patch.get_ydata()
                    new_ys = map(operator.add, current_ys, [self.Ycord] * len(current_ys))
                    patch.set_ydata(new_ys)
                elif isinstance(patch, FancyArrow):
                    current_xy=patch.get_xy()
                    new_xy=[]
                    for x, y in current_xy:
                        new_xy.append([x, y + self.Ycord])
                    patch.set_xy(new_xy)
                elif isinstance(patch, Annotation):
                    current_x, current_y = patch.xytext
                    patch.xytext = (current_x, current_y + self.Ycord)
                else:
                    try:
                        current_y = patch.get_y()
                    except AttributeError:
                        current_y = patch.get_position()[1]
                    patch.set_y(current_y + self.Ycord)
            for iname, fname in enumerate(feat2draw.feat_name):
                y=fname.get_position()[1]
                feat2draw.feat_name[iname].set_y(y + self.Ycord)
                current_x, current_y = fname.xytext
                feat2draw.feat_name[iname].xytext = (current_x , current_y + self.Ycord)
            self.Ycord-=self._betw_feat_space
            self.drawn_lines += 1

    def _draw_features(self, **kwargs):
        '''draw features '''
        xoffset = kwargs.get('xoffset',0)
        for feat_numb, feat2draw in enumerate(self.features):
            if feat2draw.color_by_cm:
                if feat2draw.use_score_for_color:
                    feat2draw.cm_value = feat2draw.score
                    feat2draw.fc = self.cm(feat2draw.cm_value)
                    if not feat2draw.ec:
                        feat2draw.ec = feat2draw.fc
                else:# color by feature number
                    if not feat2draw.cm_value:
                        self.norm = colors.normalize(1,len(self.features)+1,)
                        feat2draw.cm_value = feat_numb +1
                    feat2draw.fc = self.cm(self.norm(feat2draw.cm_value))
            feat2draw.draw_feature()
            feat2draw.draw_feat_name(xoffset = xoffset)

    def _sort_features(self, dpi = 80, **kwargs):
        ''' sort features basing on the chosen mode '''
        self._draw_features(**kwargs)
        if self.sort_by =='collapse':
            self._collapse(dpi, )
        elif self.sort_by =='score':
            feat_list = self._order_by_score()
            self._draw_ordered_features(feat_list,)
        elif self.sort_by =='length':
            feat_list = self._order_by_length()
            self._draw_ordered_features(feat_list, )
        else:
            self._draw_ordered_features()

class PlotTrack(BaseTrack):
    '''

    The :class:`PlotTrack` acts as a collector of :class:`~biograpy.features` \
    objects that encodes for plots.
    Track object have to be added to a :class:`~biograpy.drawer.Panel` instance\
    once they are filled with features

    ``track = PlotTrack(name = 'test', ymin= 0, ymax = 10)``

    gives a empty plot track  named ``'test'`` with y axis ranging from 0 to 10.

    Valid keyword arguments for :class:`PlotTrack` are:

        ===================== ==================================================
        Key                   Description
        ===================== ==================================================
        name                  Define the track `name`
        show_name             ``'top'`` | ``'bottom'`` |  ``None`` , default is
                              ``'top'`` . If a track `name` is specified  set
                              where the name wil be displayed
        name_font_size        default ``'small'``, accepts font size parameter
                              as in matplotlib
        name_font_family      default ``'serif'``, accepts font family
                              parameter as in matplotlib
        name_font_weight      default ``'semibold'``, accepts font weight
                              parameter as in matplotlib
        draw_axis             a list contanining this possible values:
                              ``'right'`` | ``'left'`` | ``'top'`` |
                              ``'bottom'`` | ``'force no axis'`` . default is
                              ``['left', 'bottom']``. each specified axis
                              position will be drawn.
                              if ``'force no axis'`` is specified no
                              axis will be shown, this is only needed if tracks
                              are requested to be joined.
        ymin                  default is ``-1``. define minimum Y value to plot.
        ymax                  default is ``1``. define maximum Y value to plot.
        x_use_sequence        if a string iterable is passed it will be used as
                              X tick labels
        xticks_major          set X major ticks as in matplotlib
        xticks_minor          set X minor ticks as in matplotlib
        xticklabels_major     set X major tick labels as in matplotlib
        xticklabels_minor     set X minor tick labels as in matplotlib
        yticks_major          set Y major ticks as in matplotlib
        yticks_minor          set Y minor ticks as in matplotlib
        yticklabels_major     set Y major tick labels as in matplotlib
        yticklabels_minor     set Y minor tick labels as in matplotlib
        show_xticklabels      ``True`` | ``False``. default is ``True``
        show_yticklabels      ``True`` | ``False``. default is ``True``
        tickfontsize_major    default ``'x-small'``, accepts font size parameter
                              as in matplotlib
        tickfontsize_minor    default ``'xx-small'``, accepts font size
                              parameter as in matplotlib
        track_height          specify the the axis heigth by pixel number.
                              default is ``0`` and will be set automatically
        max_score             default is ``None``, if not specified will be
                              dynamically computed basing on feature scores
        min_score             default is ``None``, if not specified will be
                              dynamically computed basing on feature scores
        norm                  score normalizing function. default is ``None``
                              and will be created using maximum and minimum
                              feature scores. could be any function taking a
                              int or float value and returning a float between
                              ``0.`` and ``1.``
        cm                    matplotlib colormap name to use for score-based
                              feature color. default is ``'Accent'``
        draw_cb               ``True`` | ``False``. default is ``False``. draws
                              a colorbar inside the track to explain score-based
                              feature color
        cb_alpha              colorbar alpha value, a float between ``0.`` and
                              ``1.``
        cb_label              colorbar label, a string
        track_lines           default is ``4``. increase or decrease to make
                              the track bigger or smaller
        ===================== ==================================================

    '''

    def __init__(self,*args, **kwargs):
        BaseTrack.__init__(self, *args, **kwargs)

        self.Ycord = self.ymin = kwargs.get('ymin', -1)
        self.draw_axis = kwargs.get('draw_axis', ['left', 'bottom'] )
        self.ymax = kwargs.get('ymax', 1)
        self.show_yticklabels = kwargs.get('show_yticklabels', True )
        self.drawn_lines = kwargs.get('track_lines', 4 )#  number of features to be counted do determine track height

    def _collapse(self, dpi):
        plt.draw()

    def _order_by_score(self,):
        return self.features

    def _order_by_length(self,):
        return self.features

    def _draw_ordered_features(self, feat_list = None):
        return

    def _draw_features(self, **kwargs):
        xoffset = kwargs.get('xoffset',0)
        for feat_numb, feat2draw in enumerate(self.features):
            if feat2draw.color_by_cm:
                if feat2draw.use_score_for_color:
                    feat2draw.cm_value = feat2draw.score
                    feat2draw.fc = self.cm(feat2draw.cm_value)
                else:# color by feature number
                    if not feat2draw.cm_value:
                        self.norm = colors.normalize(1,len(self.features)+1,)
                        feat2draw.cm_value = feat_numb +1
                    feat2draw.fc = self.cm(self.norm(feat2draw.cm_value))
            feat2draw.draw_feature()
            feat2draw.draw_feat_name(xoffset = xoffset)

    def _sort_features(self, dpi = 80, **kwargs):
        self._draw_features(**kwargs)


'''
트리의 부모 찾기
'''

from collections import defaultdict
import sys
sys.setrecursionlimit(10**6)

N = int(sys.stdin.readline())
visited = [0 for _ in range(N + 1)]
graph = defaultdict(list)

for _ in range(1, N):
    node1, node2 = map(int, sys.stdin.readline().split())
    graph[node1].append(node2)
    graph[node2].append(node1)

def dfs(s):
    for i in graph[s]:
        if visited[i] == 0 :
            visited[i] = s
            dfs(i)

dfs(1)

for i in range(2, len(visited)):
    print(visited[i])


import mod1

num1 = 10
num2 = 5

result = mod1.add(num1, num2)

print(result)

a = int(input("첫번째 숫자: "))
b = int(input("두번째 숫자: "))
print ("1. 더하기 2. 빼기")
c = int(input("선택"))
if c == 1:
    print (mod1.add(a, b))
if c == 2:
    print (mod1.sub(a, b))


#!/usr/bin/env python
# activity.py
#
# Activity functions with keras.py
# DSDE Deep Learning
# June 2018
# Sam Friedman
# sam@broadinstitute.org

from __future__ import print_function

import os
import sys
import math
import h5py
import gzip
import pickle
import argparse
import matplotlib
import numpy as np
matplotlib.use('Agg')
from scipy import interp
from keras import metrics
import keras.backend as K
from random import shuffle
from Bio import Seq, SeqIO
from itertools import cycle
import matplotlib.pyplot as plt
from collections import Counter

from keras.optimizers import SGD, Adam
from keras.models import Sequential, Model
from sklearn.metrics import roc_curve, auc, roc_auc_score
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.layers.convolutional import Convolution1D, MaxPooling1D, Conv1D
from keras.layers import Input, Dense, Dropout, BatchNormalization, SpatialDropout1D, Activation, Flatten

data_path = '/dsde/data/deep/'
reference_fasta = data_path + 'Homo_sapiens_assembly19.fasta'
chrom_hmm_bed_file = data_path + 'wgEncodeAwgSegmentationCombinedGm12878.bed'
breakpoint_bed_file =  '/dsde/data/deep/vqsr/beds/icgc_bkp_sorted.bed'

amiguity_codes = {'K':[0,0,0.5,0.5], 'M':[0.5,0.5,0,0], 'R':[0.5,0,0,0.5], 'Y':[0,0.5,0.5,0], 'S':[0,0.5,0,0.5],
				  'W':[0.5,0,0.5,0], 'B':[0,0.333,0.333,0.334], 'V':[0.333,0.333,0,0.334],'H':[0.333,0.333,0.334,0],
				  'D':[0.333,0,0.333,0.334], 'N':[0.25,0.25,0.25,0.25]}

label_sets = {
	'chrom_hmm'  : {'TSS':0, 'PF':1, 'E':2, 'WE':3, 'CTCF':4, 'T':5, 'R':6 },
	'breakpoint' : {'WT':0, 'BREAKPOINT':1}
}

def run():
	args = parse_args()
	multilayer_perceptron_on_mnist(args)

def parse_args():
	parser = argparse.ArgumentParser()

	parser.add_argument('--mode', default='bp')
	parser.add_argument('--activation', default='relu',
		help="The neuronal activation type (keras string like 'relu' of make your own...")
	parser.add_argument('--window_size', default=64, type=int)
	parser.add_argument('--samples', default=1000, type=int)
	parser.add_argument('--activity', default=0, type=int)
	parser.add_argument('--reference_fasta', default=reference_fasta)
	parser.add_argument('--bed_file',default=breakpoint_bed_file)
	parser.add_argument('--inputs', default={'A':0, 'C':1, 'T':2, 'G':3})
	parser.add_argument('--epochs', default=15, type=int, help='Training epochs.')
	parser.add_argument('--batch_size', default=32, type=int, help='Training mini batch size.')
	parser.add_argument('--label_set', default='breakpoint', choices=label_sets.keys())
	parser.add_argument('--labels', default={})
	parser.add_argument('--conv_width', default=5, type=int, help='Width of 1D convolutional kernels.')
	parser.add_argument('--conv_dropout', default=0.0, type=float,
		help='Dropout rate in convolutional layers.')
	parser.add_argument('--conv_batch_normalize', default=False, action='store_true',
		help='Batch normalize convolutional layers.')
	parser.add_argument('--conv_layers', nargs='+', default=[128, 96, 64, 48], type=int,
		help='List of sizes for each convolutional filter layer')
	parser.add_argument('--kernel_initializer', default='he_normal',
		help='convolution kernel initializer.')
	parser.add_argument('--same_padding', default=False, action='store_true',
		help='Valid or same border padding on the convolutional layers.')
	parser.add_argument('--spatial_dropout', default=False, action='store_true',
		help='Spatial dropout on the convolutional layers.')
	parser.add_argument('--max_pools', nargs='+', default=[], type=int,
		help='List of maxpooling layers.')
	parser.add_argument('--fc_layers', nargs='+', default=[32], type=int,
		help='List of sizes for each fully connected layer')
	parser.add_argument('--fc_dropout', default=0.0, type=float,
		help='Dropout rate in fully connected  layers.')
	parser.add_argument('--fc_batch_normalize', default=False, action='store_true',
		help='Batch normalize fully connected layers.')
	parser.add_argument('--fc_initializer', default='he_normal',
		help='fully connected layer initializer')

	args = parser.parse_args()
	args.labels = label_sets[args.label_set]
	print('Arguments are', args)
	return args

def activity_1d_model_from_args(args):
	'''Build Reference 1d CNN model for classification.

	Architecture specified by parameters.
	Dynamically sets input channels based on args via defines.total_input_channels_from_args(args)
	Uses the functional API.
	Prints out model summary.

	Arguments
		args.labels: The output labels (e.g. BREAKPOINT, WT)

	Returns
		The keras model
	'''
	concat_axis = -1
	x = reference = Input(shape=(args.window_size, len(args.inputs)), name='reference')

	max_pool_diff = len(args.conv_layers)-len(args.max_pools)
	for  i,c in enumerate(args.conv_layers):

		x = Conv1D(filters=c, kernel_size=args.conv_width, activation='linear', padding=args.padding, kernel_initializer=args.kernel_initializer)(x)
		if args.conv_batch_normalize:
			x = BatchNormalization(axis=concat_axis)(x)
		x = Activation(args.activation)(x)

		if args.conv_dropout > 0 and args.spatial_dropout:
			x = SpatialDropout1D(args.conv_dropout)(x)
		elif conv_dropout > 0:
			x = Dropout(args.conv_dropout)(x)

		if i >= max_pool_diff:
			x = MaxPooling1D(args.max_pools[i-max_pool_diff])(x)

	x = Flatten()(x)

	for fc in args.fc_layers:
		if args.fc_batch_normalize:
			x = Dense(units=fc, activation='linear', kernel_initializer=args.fc_initializer)(x)
			x = BatchNormalization(axis=1)(x)
			x = Activation('relu')(x)
		else:
			x = Dense(units=fc, activation=args.activation)(x)

		if fc_dropout > 0:
			x = Dropout(fc_dropout)(x)

	prob_output = Dense(units=len(args.labels), activation='softmax')(x)

	model = Model(inputs=[reference], outputs=[prob_output])

	adam = Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
	my_metrics = [metrics.binary_accuracy]

	model.compile(optimizer=adam, loss='binary_crossentropy', metrics=my_metrics)
	model.summary()

	return model

def multilayer_perceptron_on_mnist(args):
	train, test, valid = load_data('mnist.pkl.gz')

	num_labels = 10
	train_y = make_one_hot(train[1], num_labels)
	valid_y = make_one_hot(valid[1], num_labels)
	test_y = make_one_hot(test[1], num_labels)

	mlp_model = Sequential()
	for fc in args.fc_layers:
		mlp_model.add(Dense(fc, activation=args.activation, input_dim=784))

	mlp_model.add(Dense(num_labels, activation='softmax'))
	mlp_model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
	mlp_model.summary()

	print('Train multilayer perceptron on MNIST. Test set loss and accuracy:', mlp_model.evaluate(test[0], test_y))
	mlp_model.fit(train[0], train_y, validation_data=(valid[0],valid_y), batch_size=32, epochs=args.epochs)
	print('Multilayer Perceptron trained. Test set loss and accuracy:', mlp_model.evaluate(test[0], test_y))

def make_one_hot(y, num_labels):
	ohy = np.zeros((len(y), num_labels))
	for i in range(0, len(y)):
		ohy[i][y[i]] = 1.0
	return ohy

def load_data(dataset):
	''' Loads the dataset
	:type dataset: string
	:param dataset: the path to the dataset (here MNIST)
	'''

	#############
	# LOAD DATA #
	#############

	# Download the MNIST dataset if it is not present
	data_dir, data_file = os.path.split(dataset)
	if data_dir == "" and not os.path.isfile(dataset):
		# Check if dataset is in the data directory.
		new_path = os.path.join(
			os.path.split(__file__)[0],
			"data",
			dataset
		)
		if os.path.isfile(new_path) or data_file == 'mnist.pkl.gz':
			dataset = new_path

	if (not os.path.isfile(dataset)) and data_file == 'mnist.pkl.gz':
		origin = ('http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz')
		print('Downloading data from %s' % origin)
		if not os.path.exists(os.path.dirname(dataset)):
			os.makedirs(os.path.dirname(dataset))
		if (sys.version_info > (3, 0)):
			from urllib.request import urlretrieve
			urlretrieve(origin, dataset)
		else:
			import urllib
			urllib.urlretrieve(origin, dataset)

	print('loading data...')

	# Load the dataset
	f = gzip.open(dataset, 'rb')
	if sys.version_info[0] == 3:
		u = pickle._Unpickler(f)
		u.encoding = 'latin1'
		train_set, valid_set, test_set = u.load()
	else:
		train_set, valid_set, test_set = pickle.load(f)

	f.close()
	#train_set, valid_set, test_set format: tuple(input, target)
	#input is an numpy.ndarray of 2 dimensions (a matrix)
	#which row's correspond to an example. target is a
	#numpy.ndarray of 1 dimensions (vector)) that have the same length as
	#the number of rows in the input. It should give the target
	#target to the example with the same index in the input.

	return train_set, valid_set, test_set

if '__main__'==__name__:
	run()


import argparse
import sys
import pandas as pd
import numpy as np
import logreg

if __name__ == '__main__':
    # command line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('filepath')
    args = parser.parse_args()

    df = pd.DataFrame()
    try:
        df = pd.read_csv(args.filepath)
    except FileNotFoundError:
        print(
            f'No such file or directory: \'{args.filepath}\'', file=sys.stderr)
        exit(1)

    df_index = df['Index']
    df = df.drop(columns=['Index']).reset_index(drop=True)
    test = df.select_dtypes(include=[np.number])
    test = test.drop(columns=['Hogwarts House'])

    model = logreg.LogisticRegression()
    model.load('params.npy')
    categories = np.load('categories.npy', allow_pickle=True)

    preds_prob = model.predict(test)
    preds = preds_prob.argmax(1)

    result = pd.DataFrame({'Index': df_index, 'Hogwarts House': [
                          categories[p] for p in preds]})
    result.to_csv('houses.csv', index=False)


# 2. lena 영상을 이용하여 가중 평균 값 필터링을 수행하시오.
# 마스크는 그림 4-7의 3x3과 5x5 마스크를 사용하여 각각의 결과를 한 화면에 출력하고, 원본 이미지와 비교하시오.
import numpy as np
from scipy import signal, misc
import matplotlib.pyplot as plt
from scipy import ndimage

def im_filtering(im, Filter, FilterSize):
    row, col = im.shape
    padding=int(FilterSize/2)

    Image_Buffer = np.zeros(shape=(row+2*padding,col+2*padding), dtype=np.uint8)
    Image_Buffer[padding:row+padding, padding:col+padding] = im[:,:]
    Image_New = np.zeros(shape=(row,col), dtype=np.uint8)
    for y in range(padding,row+padding):
        for x in range(padding,col+padding):
            buff = Image_Buffer[y-padding:y+padding+1,x-padding:x+padding+1]
            pixel = np.sum(buff * Filter)
            pixel = np.uint8(np.where(pixel>255,255,np.where(pixel<0,0,pixel)))
            Image_New[y-padding,x-padding] = pixel
    return Image_New

# 이미지 출력 함수
def image_print(img, title, print_num, current_num):
    print(print_num[0])
    plt.subplot(print_num[0],print_num[1],current_num)
    plt.title(title)
    plt.gray()
    plt.imshow(img)
    plt.axis('off')

lena = misc.imread('image/lena_256.bmp')

Weighted_Filter1=np.array([[1,2,1],[2,4,2],[1,2,1]])
Weighted_Filter1=Weighted_Filter1/np.sum(Weighted_Filter1)

Weighted_Filter2=np.array([[1,4,6,4,1],[4,16,24,16,4],[6,24,36,24,6],[1,4,6,4,1],[4,16,24,16,4]])
Weighted_Filter2=Weighted_Filter2/np.sum(Weighted_Filter2)

Image_New1 = im_filtering(lena, Weighted_Filter1, 3)
Image_New2 = im_filtering(lena, Weighted_Filter2, 5)

image_print(lena,"lena",(1,3),1)
image_print(Image_New1,"3X3",(1,3),2)
image_print(Image_New2,"5X5",(1,3),3)

plt.show()


from rq.job import Job
from app.schoology.types import Realm
from app.update_scheduler.models import ScheduledJob
from typing import Dict, List

from flask import g
from app.exts import db
from app.schoology.api import post_updates
from app.app import create_app
from rq import get_current_job

app = create_app()
app.app_context().push()

def post_update_task(realms: List[Realm], body: str, attachments: List[Dict]):
    job: Job = get_current_job()  # type: ignore

    with app.app_context():
        scheduled_job = ScheduledJob.query.get(job.id)
        if scheduled_job is None:
            app.logger.error(
                f'Scheduled job with id {job.id} could not be found when trying to post')
            return

        update = scheduled_job.update
        g.user_id = update.user_id
        responses = post_updates(realms, update.body, attachments)
        if type(responses) is list:
            app.logger.info('Posted updates with response codes: ' +
                            ', '.join([str(response.status_code) for response in responses]))

        job.cleanup(0)
        db.session.delete(update)  # type: ignore
        db.session.commit()  # type: ignore
        job.delete()
        g.user_id = -1


"""
Logger module.

This file is subject to the terms and conditions defined in file 'LICENSE',
which is part of this source code package.
"""
# pylint: disable=unused-variable,too-few-public-methods,too-many-instance-attributes,too-many-arguments,too-many-branches,too-many-statements  # noqa

import logging
import uuid
from datetime import datetime, timezone
from logging.config import dictConfig

from flask import g

from .json_access_log_formatter import JSONAccessLogFormatter
from .json_default_log_formatter import JSONDefaultLogFormatter

class JSONLogger:
    """JSON logger for Flask application."""

    def __init__(self):
        """Initialize JSONLogger with default values."""

        # switches
        self.default_enabled = True
        self.access_enabled = True

        # level
        self.level = logging.ERROR

        # formatters
        self.default_formatter = JSONDefaultLogFormatter
        self.access_formatter = JSONAccessLogFormatter

        # handlers
        self.default_handler = {
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stderr',
            'formatter': 'default',
        }
        self.access_handler = {
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout',
            'formatter': 'access',
        }

        # rotation
        self.rotation_when_map = {
            'M': 'M',
            'H': 'H',
            'D': 'D',
            'W': 'W0',
        }
        self.rotation_backup_count_map = {
            'M': 60,
            'H': 24,
            'D': 7,
            'W': 4,
        }

    def init_app(self, app, *, default_formatter=None, access_formatter=None,
                 default_handler=None, access_handler=None):
        """Initialize Flask application for logging.

        :param app: The Flask application instance
        :type app: Flask
        :param default_formatter: An optional log formatter for default logger
        :type default_formatter: logging.Formatter
        :param access_formatter: An optional log formatter for access logger
        :type access_formatter: logging.Formatter
        :param default_handler: An optional configuration for default handler
        :type default_handler: dict
        :param access_handler: An optional configuration for access handler
        :type access_handler: dict
        """

        # we only really want to run this module in production mode
        if app.config.get('DEBUG') or app.config.get('TESTING'):
            app.logger.setLevel(self.level)

        else:

            # configure the logger
            self.config(app, default_formatter, access_formatter,
                        default_handler, access_handler)

            # set python's dictConfig() function
            self.set_dict_config()

            # disable default Flask logger
            logging.getLogger('werkzeug').disabled = True

            # apply custom log formatters
            logging.getLogger().handlers[0].formatter = \
                self.default_formatter()
            logging.getLogger('access_log').handlers[0].formatter = \
                self.access_formatter()

            @app.before_request
            def before_request():
                g.request_time = datetime.now(timezone.utc)
                g.request_uuid = uuid.uuid4()

            @app.after_request
            def after_request(response):
                """ Logging after every request. """
                logging.getLogger("access_log").info(
                    "", extra={'response': response})
                return response

    def config(self, app, default_formatter, access_formatter, default_handler,
               access_handler):
        """Configure the logger's local properties.

        :param app: The Flask application instance
        :type app: Flask
        :param default_formatter: An optional log formatter for default logger
        :type default_formatter: logging.Formatter
        :param access_formatter: An optional log formatter for access logger
        :type access_formatter: logging.Formatter
        :param default_handler: An optional configuration for default handler
        :type default_handler: dict
        :param access_handler: An optional configuration for access handler
        :type access_handler: dict
        """

        # set switches
        self.default_enabled = bool(app.config.get(
            'LOGGING_DEFAULT_ENABLED', self.default_enabled))
        self.access_enabled = bool(app.config.get(
            'LOGGING_ACCESS_ENABLED', self.access_enabled))

        # config default logger
        if self.default_enabled:

            # set level
            self.level = app.config.get('LOGGING_DEFAULT_LEVEL', self.level)

            # set formatter
            if default_formatter is not None:
                self.default_formatter = default_formatter

            # set handler
            if default_handler is not None:
                self.default_handler = default_handler

            # log to file
            if app.config.get('LOGGING_DEFAULT_FILE', False):
                del self.default_handler['stream']
                self.default_handler['class'] = 'logging.FileHandler'
                self.default_handler['mode'] = 'a'
                self.default_handler['filename'] = app.config.get(
                    'LOGGING_DEFAULT_FILE')

            # log to rotating file
            if (app.config.get('LOGGING_DEFAULT_FILE_ROTATION', False)
                    and app.config.get('LOGGING_DEFAULT_FILE', False)):

                when = self.rotation_when_map[
                    app.config.get('LOGGING_DEFAULT_FILE_ROTATION')]

                interval = 1
                if app.config.get(
                        'LOGGING_DEFAULT_FILE_ROTATION_INTERVAL'):
                    interval = app.config.get(
                        'LOGGING_DEFAULT_FILE_ROTATION_INTERVAL')

                retention = self.rotation_backup_count_map[app.config.get(
                    'LOGGING_DEFAULT_FILE_ROTATION')]
                if app.config.get(
                        'LOGGING_DEFAULT_FILE_ROTATION_RETENTION'):
                    retention = app.config.get(
                        'LOGGING_DEFAULT_FILE_ROTATION_RETENTION')

                del self.default_handler['mode']
                self.default_handler['class'] = \
                    'logging.handlers.TimedRotatingFileHandler'
                self.default_handler['when'] = when
                self.default_handler['interval'] = interval
                self.default_handler['backupCount'] = retention

        else:
            logging.getLogger().disabled = True

        # config access logger
        if self.access_enabled:

            # set level
            if access_formatter is not None:
                self.access_formatter = access_formatter

            # set formatter
            if access_handler is not None:
                self.access_handler = access_handler

            # set handler
            if app.config.get('LOGGING_ACCESS_FILE', False):
                del self.access_handler['stream']
                self.access_handler['class'] = 'logging.FileHandler'
                self.access_handler['mode'] = 'a'
                self.access_handler['filename'] = app.config.get(
                    'LOGGING_ACCESS_FILE')

            # log to rotating file
            if (app.config.get('LOGGING_ACCESS_FILE_ROTATION', False)
                    and app.config.get('LOGGING_ACCESS_FILE', False)):

                when = self.rotation_when_map[
                    app.config.get('LOGGING_ACCESS_FILE_ROTATION')]

                interval = 1
                if app.config.get('LOGGING_ACCESS_FILE_ROTATION_INTERVAL'):
                    interval = app.config.get(
                        'LOGGING_ACCESS_FILE_ROTATION_INTERVAL')

                retention = self.rotation_backup_count_map[app.config.get(
                    'LOGGING_ACCESS_FILE_ROTATION')]
                if app.config.get('LOGGING_ACCESS_FILE_ROTATION_RETENTION'):
                    retention = app.config.get(
                        'LOGGING_ACCESS_FILE_ROTATION_RETENTION')

                del self.access_handler['mode']
                self.access_handler['class'] = \
                    'logging.handlers.TimedRotatingFileHandler'
                self.access_handler['when'] = when
                self.access_handler['interval'] = interval
                self.access_handler['backupCount'] = retention

        else:
            logging.getLogger('access_log').disabled = True

    def set_dict_config(self):
        """Calls Python's dictConfig() to configure logging."""

        dictConfig({
            'version': 1,
            'loggers': {
                "": {
                    "level": self.level,
                    "handlers": ["default"],
                    "propagate": True,
                },
                "access_log": {
                    "level": 'INFO',
                    "handlers": ["access"],
                    "propagate": False,
                },
            },
            'formatters': {
                'default': {
                    'format': '%(message)s',
                },
                'access': {
                    'format': '%(message)s',
                },
            },
            'handlers': {
                'default': self.default_handler,
                'access': self.access_handler,
            }
        })