# 주어진 데이터를 기반으로 이진 트리를 만들고,
# 만들어진 트리에서 특정 자료가 있는지 없는지를 검색해서 결과를 보여줌
# 트리 구조의 자료를 보여주기 위하여 '깊이 우선 탐색', '너비 우선 탐색'을 적용함

# 노드의 형식을 정의하는 부분
class Node(object):
    def __init__(self, data):
        self.data = data
        self.left = self.right = None

class BinarySearchTree(object):
    def __init__(self):
        self.root = None

    # 이진 트리에 데이터를 넣는 부분
    def insert(self, data):
        self.root = self._insert_value(self.root, data)
        return self.root is not None

    def _insert_value(self, node, data):
        if node is None:
            node = Node(data)
        else:
            if data <= node.data:
                node.left = self._insert_value(node.left, data)
            else:
                node.right = self._insert_value(node.right, data)
        return node

    # 이진 트리에서 데이터를 찾는 부분
    def find(self, key):
        return self._find_value(self.root, key)

    def _find_value(self, root, key):
        if root is None or root.data == key:
            return root is not None
        elif key < root.data:
            return self._find_value(root.left, key)
        else:
            return self._find_value(root.right, key)

    # 이진 트리에서 데이터를 지우는 부분
    def delete(self, key):
        self.root, deleted = self._delete_value(self.root, key)
        return deleted

    def _delete_value(self, node, key):
        if node is None:
            return node, False

        delted = False
        if key == node.data:
            deleted = True
            if node.left and node.right:
                parent, child = node, node.right
                while child.left is not None:
                    parent, child = child, child.left
                child.left = node.left
                if parent != node:
                    parent.left = child.right
                    child.right = node.right
                node = child
            elif node.left or node.right:
                node = node.left or node.right
            else:
                node = None
        elif key < node.data:
            node.left, deleted = self._delete_value(node.left, key)
        else:
            node.right, deleted = self._delete_value(node.right, key)
        return node, deleted

    # 데이터를 출력하는 부분
    def DFTravel(self):
        def _DFTravel(root):
            if root is None:
                pass
            else:
                print(root.data, end=' ')
                _DFTravel(root.left)
                _DFTravel(root.right)
        _DFTravel(self.root)

    # 데이터를 출력하는 부분
    def LFTravel(self):
        def _LFTravel(root):
            if root is None:
                pass
            else:
                _LFTravel(root.left)
                print(root.data, end=' ')
                _LFTravel(root.right)
        _LFTravel(self.root)

    # 데이터를 출력하는 부분
    def LRTravel(self):
        def _LRTravel(root):
            if root is None:
                pass
            else:
                _LRTravel(root.left)
                _LRTravel(root.right)
                print(root.data, end=' ')
        _LRTravel(self.root)

    # 데이터를 출력하는 부분
    def layerTravel(self):
        def _layerTravel(root):
            queue = [root]
            while queue:
                root = queue.pop(0)
                if root is not None:
                    print(root.data, end=' ')
                    if root.left:
                        queue.append(root.left)
                    if root.right:
                        queue.append(root.right)
        _layerTravel(self.root)

# 데이터의 선언
data = [20, 6, 8, 12, 78, 32, 65, 32, 7, 9]
tree = BinarySearchTree()

# 트리 구조의 완성
for x in data:
    tree.insert(x)

# 트리 안의 데이터 존재에 대한 확인 및 조작
print(tree.find(9))

print(tree.find(3))

print(tree.delete(78))
print(tree.delete(6))
print(tree.delete(11))

# 트리 구조의 데이터 출력
print("\n@@@@@@")
tree.DFTravel() # 깊이 우선 탐색 중 전위 순회 : 뿌리 > 왼쪽 트리 > 오른쪽 트리
print("\n======")
tree.LFTravel() # 깊이 우선 탐색 중 중위 순회 : 왼쪽 트리 > 뿌리 > 오른쪽 트리
print("\n******")
tree.LRTravel() # 깊이 우선 탐색 중 후위 순회 : 왼쪽 트리 > 오른쪽 트리 > 뿌리 노드
print("\n&&&&&&")
tree.layerTravel() # 너비 우선 탐색 : 뿌리 노드부터 깊이순으로 방문

그림으로 정리한 알고리즘과 자료구조 자바+파이썬/4장 지료구조/4.11 이진 트리/파이썬으로 이진 트리를 만들고 데이터를 찾아 출력하는 프로그램.py

파이썬으로 이진 트리를 만들고 데이터를 찾아 출력하는 프로그램.py


import unittest
import logging
import codecs

from nltools import misc
from zamiaprolog.logicdb import LogicDB
from zamiaprolog.parser  import PrologParser
from zamiaprolog.runtime import PrologRuntime
from zamiaprolog.logic   import NumberLiteral

UNITTEST_MODULE = 'unittests'

recorded_moves = []

def record_move(g, rt):

    global recorded_moves

    rt._trace ('CALLED BUILTIN record_move', g)

    pred = g.terms[g.inx]
    args = pred.args
    if len(args) != 2:
        raise PrologRuntimeError('record_move: 2 args expected.')

    arg_from  = rt.prolog_eval(args[0], g.env, g.location)
    arg_to    = rt.prolog_eval(args[1], g.env, g.location)

    recorded_moves.append((arg_from, arg_to))

    return True

def multi_binder(g, rt):

    global recorded_moves

    rt._trace ('CALLED BUILTIN multi_binder', g)

    pred = g.terms[g.inx]
    args = pred.args
    if len(args) != 2:
        raise PrologRuntimeError('multi_binder: 2 args expected.')

    var_x  = rt.prolog_get_variable(args[0], g.env, g.location)
    var_y  = rt.prolog_get_variable(args[1], g.env, g.location)

    res = []
    for x in range(2):

        lx = NumberLiteral(x)

        for y in range(2):
            ly = NumberLiteral(y)

            res.append({var_x: lx, var_y: ly})

    return res

class TestEmbeddings (unittest.TestCase):

    def setUp(self):

        #
        # db, store
        #

        db_url = 'sqlite:///foo.db'

        # setup compiler + environment

        self.db     = LogicDB(db_url, echo=False)
        self.parser = PrologParser(self.db)
        self.rt     = PrologRuntime(self.db)

        # self.rt.set_trace(True)

        self.db.clear_module(UNITTEST_MODULE)

    def tearDown(self):
        self.db.close()

    #@unittest.skip("temporarily disabled")
    def test_custom_builtins(self):

        global recorded_moves

        self.parser.compile_file('samples/hanoi2.pl', UNITTEST_MODULE)

        clause = self.parser.parse_line_clause_body('move(3,left,right,center)')
        logging.debug('clause: %s' % clause)

        # register our custom builtin
        recorded_moves = []
        self.rt.register_builtin('record_move', record_move)

        solutions = self.rt.search(clause)
        logging.debug('solutions: %s' % repr(solutions))
        self.assertEqual (len(solutions), 1)

        self.assertEqual (len(recorded_moves), 7)

    #@unittest.skip("temporarily disabled")
    def test_custom_builtin_multiple_bindings(self):

        self.rt.register_builtin('multi_binder', multi_binder)

        clause = self.parser.parse_line_clause_body('multi_binder(X,Y)')
        logging.debug('clause: %s' % clause)
        solutions = self.rt.search(clause)
        logging.debug('solutions: %s' % repr(solutions))
        self.assertEqual (len(solutions), 4)

    def _custom_directive(self, db, module_name, clause, user_data):
        # logging.debug('custom_directive has been run')
        self.assertEqual (len(clause.head.args), 3)
        self.assertEqual (unicode(clause.head.args[0]), u'abc')
        self.assertEqual (clause.head.args[1].f, 42)
        self.assertEqual (clause.head.args[2].s, u'foo')

        self.directive_mark = True

    #@unittest.skip("temporarily disabled")
    def test_custom_directives(self):

        self.parser.register_directive('custom_directive', self._custom_directive, None)
        self.directive_mark = False

        # self.parser.compile_file('samples/dir.pl', UNITTEST_MODULE)
        clauses = self.parser.parse_line_clauses('custom_directive(abc, 42, \'foo\').')

        self.assertEqual (self.directive_mark, True)

if __name__ == "__main__":

    logging.basicConfig(level=logging.DEBUG)
    # logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)

    unittest.main()


from embed import EmbedMessage, SelectClassView
from nextcord.ext import commands
from nextcord import Member
from timetable import *

import asyncio

class CommandLesson(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.embed = EmbedMessage()

    @commands.group(name="lesson", aliases=['class'])
    async def lesson(self, ctx: commands.Context):
        if ctx.invoked_subcommand is None:
            await ctx.channel.send(
                f"{ctx.author.mention} 님! 명령어를 잘못 입력하신 것 같습니다!",
                embed=self.embed.command()
            )

    @lesson.command(name="author")
    async def lesson_author(self, ctx: commands.Context):
        await ctx.send(f"{ctx.author.mention} 님, 지금부터 선생님에 대한 소개를 하겠습니다.", embed=self.embed.introduce())

    @lesson.command(name="question")
    async def lesson_question(self, ctx: commands.Context):
        await ctx.send(f"{ctx.author.mention} 님! 선생님에게 질문할 내용이 있으신가 보군요?", embed=self.embed.question())

    @lesson.command(name="select")
    async def lesson_select(self, ctx: commands.Context):
        view = SelectClassView()
        await ctx.send(
            f"{ctx.author.mention} 님! 아래 버튼들 중에서 수강한 과목을 눌러주세요!",
            embed=self.embed.select_lang_default(), view=view, delete_after=10.0
        )
        await view.wait()
        if view.lang is None:
            await ctx.send(
                f"{ctx.author.mention} 님! 시간이 지나 과목 선택이 취소 되었습니다!",
                embed=self.embed.select_lang_failed(), delete_after=10.0)
        else:
            guild = ctx.guild
            role = guild.get_role(view.role[view.lang])
            await guild.get_member(ctx.author.id).add_roles(role)

class CommandTimetable(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.embed = EmbedMessage()
        self.weekday = {'Mon': "월요일", 'Tue': "화요일", 'Wed': "수요일", 'Thu': "목요일", 'Fri': "금요일"}
        self.role = {os.getenv('PYTHON_ROLE_ID'): "Python", os.getenv('MAKECODE_ROLE_ID'): "MakeCode"}

    @commands.group(name="timetable", aliases=['tt', 'ttable'])
    async def timetable(self, ctx: commands.Context):
        if ctx.invoked_subcommand is None:
            await ctx.channel.send(
                f"{ctx.author.mention} 님! 명령어를 잘못 입력하신 것 같습니다!",
                embed=self.embed.command()
            )

    @timetable.command(name="show", aliases=['s'])
    async def timetable_show(self, ctx: commands.Context, day: str = None):
        if day is None:
            await ctx.send(
                f"{ctx.author.mention} 님, 시간표를 열람할 요일을 입력해주세요!", embed=self.embed.timetable_daily_failed()
            )
        elif day in self.weekday:
            class_info = get_day_class(day)
            if class_info is not None:
                await ctx.send(
                    f"{ctx.author.mention} 님, **{self.weekday[day]}**의 시간표를 가져왔어요! 한번 봐주세요!",
                    embed=self.embed.timetable_daily(class_info, self.weekday[day])
                )
            else:
                await ctx.send(
                    f"{ctx.author.mention} 님, 해당 요일에는 수업이 존재하지 않아요!", embed=self.embed.timetable_daily_empty()
                )
        else:
            await ctx.send(
                f"{ctx.author.mention} 님, 요일은 영어로만 입력이 가능해요!", embed=self.embed.timetable_daily_failed()
            )

    # 시간표 추가 명령어 : [timetable add <요일> <시간> <학생>]
    @timetable.command(name="add", aliases=['a'])
    @commands.has_permissions(kick_members=True)
    async def timetable_add(self, ctx: commands.Context, day: str = None, time: int = None, student: Member = None):
        if day is None or day not in self.weekday:
            reason = "day"
        else:
            if time is None or not (0 <= time <= 23):
                reason = "time"
            else:
                if student is None:
                    reason = "student"
                else:
                    course_info = find_course(day, time)
                    if course_info:
                        await ctx.send(
                            f"{ctx.author.mention} 님, 해당 시간대에는 이미 다른 수업이 존재해요!",
                            embed=self.embed.timetable_modify_failed("add")
                        )
                    else:
                        # self.role 내의 role id 중에서 해당 학생이 가진 id가 있다면 이를 list에 추가함.
                        course = [role_id for role_id in self.role.keys() if student.get_role(int(role_id)) is not None][0]
                        if course:
                            add_student(day, time, self.role[course], student)
                            class_info = get_day_class(day)
                            await ctx.send(
                                f"{ctx.author.mention} 님, 성공적으로 **{student}** 학생의 수업을 추가했어요!",
                                embed=self.embed.timetable_modify(class_info, "add")
                            )
                        else:
                            await ctx.send(
                                f"{ctx.author.mention} 님, 현재 해당 학생에게 주어진 과목 역할이 없어요!",
                                embed=self.embed.timetable_add_failed("course")
                            )
                    return
        await ctx.send(
            f"{ctx.author.mention} 님, 명령어 입력을 잘못한 것 같아요!",
            embed=self.embed.timetable_add_failed(reason)
        )

    # 시간표 추가 명령어 : [timetable remove <학생>]
    @timetable.command(name="remove", aliases=['r'])
    @commands.has_permissions(kick_members=True)
    async def timetable_remove(self, ctx: commands.Context, student: Member = None):
        if student is not None:
            course_info = find_student(student)
            if course_info is not None:
                remove_student(student)
                class_info = get_day_class(course_info['weekday'])
                await ctx.send(
                    f"{ctx.author.mention} 님, 성공적으로 **{student.nick} 학생** 의 수업을 삭제했어요!",
                    embed=self.embed.timetable_modify(class_info, "del")
                )
            else:
                await ctx.send(
                    f"{ctx.author.mention} 님, 해당 학생은 현재 수업을 수강 중이지 않아요!",
                    embed=self.embed.timetable_modify_failed("del")
                )
            return
        await ctx.send(f"{ctx.author.mention} 님, 명령어 입력을 잘못한 것 같아요!.", embed=self.embed.timetable_add_failed('wrong'))

def setup(bot):
    bot.add_cog(CommandLesson(bot))
    bot.add_cog(CommandTimetable(bot))


# -*- coding: utf-8 -*-
"""
Created on 2018-03-01
@author: sun
Project:云推送-新增渠道模版（短信）
"""
import sys
import time
from selenium.webdriver.support import expected_conditions as EC
from Constant.Constant_Path import *
from Eslink_Case.Test_etbc_qa_push.Push_Message_Send.etbc_qa_push_message import *
from Utils.Getcsv_readline import csv_search
from Utils.ScreenShot import Screenshot
from Utils.Sys_Prompt import is_Sys_Prompt
from Utils.pull_down_list import is_pull_down_list
from Utils.test_db import MySQL

def is_channel_template(self):
        u"""渠道模板菜单"""
        try:
            puth_title=u"渠道模板"
            locator_title=("id","menuitem-1158-itemEl")
            is_push_message = EC.text_to_be_present_in_element(locator_title,puth_title)(self.browser)
            self.assertTrue(is_push_message)
            logger_message.loginfo(u"%s\t方法名：%s\t渠道模板 %s" % (send_time,sys._getframe().f_code.co_name,is_push_message))
            self.browser.find_element_by_id("menuitem-1158-itemEl").click()
            self.browser.implicitly_wait(10)
        except Exception as is_channel_template_msg:
            Screenshot(self,u'渠道模板异常')
            print(u"%s\t方法名：%s\t渠道模板异常%s" % (send_time,sys._getframe().f_code.co_name,is_channel_template_msg))
            logger_message.logwarning(u"%s\t方法名：%s\t渠道模板异常%s" % (send_time,sys._getframe().f_code.co_name,is_channel_template_msg))

def is_add_channel_template(self):
        u'''添加csv文件新增渠道模版'''
        try:
            template_message=csv_search.csv_test(filename=Push_Template_path().push_template,indexs=3)
            time.sleep(0.5)
            self.browser.implicitly_wait(10)
            self.browser.find_element_by_xpath('.//*[@id="add"]').click()
            self.browser.implicitly_wait(5)
            self.browser._switch_to.default_content()
            self.browser.switch_to.frame(self.browser.find_element_by_tag_name("iframe"))
            time.sleep(0.5)
            self.browser.switch_to.frame(self.browser.find_element_by_id("layui-layer-iframe2"))
            self.browser.find_element_by_xpath('//*[@id="name"]').send_keys(template_message[1])     #模版名称：Name
            self.browser.implicitly_wait(5)
            self.browser.find_element_by_xpath('//*[@id="%s"]'%template_message[2]).click()          #模版状态：State,tmp-disable:禁用,tmp-enable:启用
            self.browser.implicitly_wait(5)
            self.browser.find_element_by_xpath('//*[@data-id="channelId"]').click()
            self.browser.implicitly_wait(5)
            is_pull_down_list(self,template_message[3],".//*[@id='query-form']/div[3]/div/div/div/div/ul/li")  #渠道名称：ChannelId
            self.browser.implicitly_wait(5)
            self.browser.find_element_by_xpath('.//*[@id="code"]').send_keys(template_message[5])     #模版编号:Code
            self.browser.implicitly_wait(5)
            self.browser.find_element_by_xpath('.//*[@id="content"]').send_keys(template_message[6])  #模版内容:Content
            self.browser.implicitly_wait(5)
            # self.browser.find_element_by_xpath('.//*[@id="escapeContent"]').send_keys(template_message[7])  #转义模版:EscapeContent
            # logger_message.loginfo('\n%s\n新增模版名称：%s\n模版状态：%s\n渠道名称：%s\n模版编号:%s\n模版内容：%s\n转义模版：%s'%
            #       (send_time,template_message[1],template_message[2],template_message[3],template_message[5],template_message[6],template_message[7]))

            self.browser.implicitly_wait(5)
            self.browser.find_element_by_xpath('.//*[@id="btn-add"]').click()
            is_Sys_Prompt(self)
        except Exception as is_add_channel_template_error:
            Screenshot(self,u'添加csv文件新增短信渠道模版-异常')
            print(u'%s\t方法名：%s\t添加csv文件新增短信渠道模版-异常：%s' % (send_time,sys._getframe().f_code.co_name,is_add_channel_template_error))
            logger_message.logwarning(u'%s\t方法名：%s\t添加csv文件新增短信渠道模版-异常：%s' % (send_time,sys._getframe().f_code.co_name,is_add_channel_template_error))
            raise

def is_check_messageTemplate(self):
    u'''确认是否存在短信模版'''
    try:
        template_message=csv_search.csv_test(filename=Push_Template_path().push_template,indexs=2)
        time.sleep(0.5)
        database=MySQL()
        template_code = template_message[5]
        template_name=template_message[1]
        sql="Select * FROM push_channelmessagetemplate WHERE `code` = '%s' AND name = '%s';" % (template_code,template_name)
        print(sql)
        logger_message.loginfo(u"%s\t方法名：%s\t模版名称：%s\t模版编号：%s"%(send_time,template_name,template_code))
        result=database.query(sql)
        print(result)
        if len(result) == 1:
            print('存在模版:%s'%template_name)
            logger_message.loginfo(u"%s\t方法名：%s模版信息：%s"%(send_time,sys._getframe().f_code.co_name,result))
            sql="DELETE FROM push_channelmessagetemplate WHERE `code` = '%s';" % template_code
            database.query(sql)
        else:
            print('不存在模版:%s'%template_name)
            logger_message.loginfo(u"%s\t方法名：%s模版信息：%s"%(send_time,sys._getframe().f_code.co_name,result))

    except Exception as is_check_template_Error:
        Screenshot(self,u'模版查询异常')
        logger_message.loginfo(u"%s\t方法名：%s\t模版查询异常：%s"%(send_time,sys._getframe().f_code.co_name,is_check_template_Error))
        logger_message.loginfo(u"%s\t方法名：%s\t模版查询异常：%s"%(send_time,sys._getframe().f_code.co_name,is_check_template_Error))
        raise


import PlanAhorro

def mostrarCuotasMinimas(lista):
    valor=float(input("Ingrese un valor de cuota Maxima: "))
    i = 0
    band = True
    print("Datos de los Planes cuyo importe de cuota es menor a {} son: ".format(valor))
    while i < len(lista):
        if valor > lista[i].importeCuota():
            print("Codigo del plan: ", lista[i].getCodigo())
            print("Modelo: ", lista[i].getModeloVehiculo())
            print("Version del vehiculo: ", lista[i].getVersionVehiculo())
            print()
            band = False
        i+=1
    if band:
        print("ERROR: No se encontraron planes con importes de cuotas minimos al ingresado!")


import pandas as pd
import numpy as np
from dimod import BinaryQuadraticModel
from dwave.system import LeapHybridSampler
import matplotlib.pyplot as plt
import warnings
from collections import Counter
import cirq

class teamResults:

    def __init__(self,df) -> None:
        self.df = df

    def classical(self):
        sim = {}

        for j in range(100):

            games = []

            for i in range(len(self.df)):
                if self.df['VisitorPPG'][i] > 0.8*np.exp(np.random.rand(1))*self.df['HomePPG'][i]:
                    games.append(self.df['Visitor'][i])
                else:
                    games.append(self.df['Home'][i])

                cts = Counter(games)
                sim[j] = list(cts.items())
        tms = {}

        for i in range(100):
            for j in sim[i]:
                try:
                    tms[j[0]].append(j[1])

                except:
                    tms[j[0]] = [j[1]]
        return tms

    def quantum(self):
        qubit = cirq.GridQubit(0, 0)
        circuit = cirq.Circuit(
            cirq.X(qubit)**0.5,
            cirq.measure(qubit, key='m')
        )
        lst = []
        for i in range(100):
            simulator = cirq.Simulator()
            result = simulator.run(circuit, repetitions=5)
            lst.append(result)

        dicts ={}
        for i in lst:
            try:
                dicts[str(i)].append(1)
            except:
                dicts[str(i)] = [1]
        return dicts

if __name__ == '__main__':
    pass


import pickle

def add_tofile(protein1,protein2,specie1,specie2):
    file="-".join(sorted([specie1,specie2])) #   "a-b"
    try:
        file=open(f"{file}.txt","a+")
        file.write(f"{protein1} {protein2}\n")
    finally:
        file.close()

def write_file(spe_pro_dict): # {specie : [protein] , s : [p]}
    a=tuple(spe_pro_dict.keys())
    s=set()
    for each in a:
        if each!=a[-1]:

            for i in a:
                if i!=each:
                    s.add(tuple(sorted([each,i])))

    for (a,b) in s:
        if spe_pro_dict[a]!=[] and spe_pro_dict[b]!=[]:
            add_tofile(spe_pro_dict[a][0],spe_pro_dict[b][0],a,b)

try:

    f5=open("5iid_sim_CIQ_15000_5000_5000.txt","r")       # r - cleaning this file

    p=[]

    p2=[]
    for line in f5:
        try:
            human,mouse,rat,cow,dog = line.rstrip().split("\t")

            x={"human":[],"rat":[],"mouse":[],"cow":[],"dog":[]}

            if "-" not in human:
                x["human"].append(human)

            if "-" not in rat:
                x["rat"].append(rat)

            if "-" not in mouse:
                x["mouse"].append(mouse)

            if "-" not in cow:
                x["cow"].append(cow)

            if "-" not in dog:
                x["dog"].append(dog)

            write_file(x)
        except Exception as ex:
            print(ex)
            print(uniq)
            print(line)
            break

    print(len(p))
    print(p)

finally:

    f5.close()


import math
numbers = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."}

def extract(string, types=float):
    num = ""
    for data in string:
        if (data in numbers):
            num += data
    if (types == int):
        return int(math.floor(float(num)))
    else:
        return types(num)


from __future__ import print_function
from __future__ import absolute_import
from __future__ import division

from compas.geometry import distance_point_point_xy
from compas.geometry import distance_point_line_xy
from compas.geometry import closest_point_on_segment_xy

def is_ccw_xy(a, b, c, colinear=False):
    """Determine if c is on the left of ab when looking from a to b,
    and assuming that all points lie in the XY plane.

    Parameters
    ----------
    a : [float, float, float] | :class:`~compas.geometry.Point`
        Base point defined by XY(Z) coordinates.
    b : [float, float, float] | :class:`~compas.geometry.Point`
        First end point defined by XY(Z) coordinates.
    c : [float, float, float] | :class:`~compas.geometry.Point`
        Second end point defined by XY(Z) coordinates.
    colinear : bool, optional
        If True, colinear points will return a positive result.

    Returns
    -------
    bool
        True if ccw.
        False otherwise.

    References
    ----------
    For more info, see [1]_.

    .. [1] Marsh, C. *Computational Geometry in Python: From Theory to Application*.
           Available at: https://www.toptal.com/python/computational-geometry-in-python-from-theory-to-implementation

    Examples
    --------
    >>> print(is_ccw_xy([0,0,0], [0,1,0], [-1, 0, 0]))
    True

    >>> print(is_ccw_xy([0,0,0], [0,1,0], [+1, 0, 0]))
    False

    >>> print(is_ccw_xy([0,0,0], [1,0,0], [2,0,0]))
    False

    >>> print(is_ccw_xy([0,0,0], [1,0,0], [2,0,0], True))
    True

    """
    ab_x = b[0] - a[0]
    ab_y = b[1] - a[1]
    ac_x = c[0] - a[0]
    ac_y = c[1] - a[1]
    if colinear:
        return ab_x * ac_y - ab_y * ac_x >= 0
    return ab_x * ac_y - ab_y * ac_x > 0

def is_colinear_xy(a, b, c):
    """Determine if three points are colinear on the XY-plane.

    Parameters
    ----------
    a : [float, float, float] | :class:`~compas.geometry.Point`
        Point 1 defined by XY(Z) coordinates.
    b : [float, float, float] | :class:`~compas.geometry.Point`
        Point 2 defined by XY(Z) coordinates.
    c : [float, float, float] | :class:`~compas.geometry.Point`
        Point 3 defined by XY(Z) coordinates.

    Returns
    -------
    bool
        True if the points are colinear.
        False otherwise.

    """
    ab_x = b[0] - a[0]
    ab_y = b[1] - a[1]
    ac_x = c[0] - a[0]
    ac_y = c[1] - a[1]
    return ab_x * ac_y == ab_y * ac_x

def is_polygon_convex_xy(polygon, colinear=False):
    """Determine if the polygon is convex on the XY-plane.

    Parameters
    ----------
    polygon : sequence[point] | :class:`~compas.geometry.Polygon`
        The XY(Z) coordinates of the corners of a polygon.
        The vertices are assumed to be in order.
        The polygon is assumed to be closed: the first and last vertex in the sequence should not be the same.
    colinear : bool, optional
        Are points allowed to be colinear?

    Returns
    -------
    bool
        True if the polygon is convex.
        False otherwise.

    """
    a = polygon[-2]
    b = polygon[-1]
    c = polygon[0]
    direction = is_ccw_xy(a, b, c, colinear)
    for i in range(-1, len(polygon) - 2):
        a = b
        b = c
        c = polygon[i + 2]
        if direction != is_ccw_xy(a, b, c, colinear):
            return False
    return True

def is_point_on_line_xy(point, line, tol=1e-6):
    """Determine if a point lies on a line on the XY-plane.

    Parameters
    ----------
    point : [float, float, float] | :class:`~compas.geometry.Point`
        XY(Z) coordinates of a point.
    line : [point, point] | :class:`~compas.geometry.Line`
        XY(Z) coordinates of two points defining a line.
    tol : float, optional
        A tolerance for membership verification.

    Returns
    -------
    bool
        True if the point is in on the line.
        False otherwise.

    """
    return distance_point_line_xy(point, line) <= tol

def is_point_on_segment_xy(point, segment, tol=1e-6):
    """Determine if a point lies on a given line segment on the XY-plane.

    Parameters
    ----------
    point : [float, float, float] | :class:`~compas.geometry.Point`
        XY(Z) coordinates of a point.
    segment : [point, point] | :class:`~compas.geometry.Line`
        XY(Z) coordinates of two points defining a segment.
    tol : float, optional
        A tolerance for membership verification.

    Returns
    -------
    bool
        True if the point is on the line segment.
        False otherwise.

    """
    a, b = segment

    if not is_point_on_line_xy(point, segment, tol=tol):
        return False

    d_ab = distance_point_point_xy(a, b)

    if d_ab == 0:
        return False

    d_pa = distance_point_point_xy(a, point)
    d_pb = distance_point_point_xy(b, point)

    if d_pa + d_pb <= d_ab + tol:
        return True

    return False

def is_point_on_polyline_xy(point, polyline, tol=1e-6):
    """Determine if a point is on a polyline on the XY-plane.

    Parameters
    ----------
    point : [float, float, float] | :class:`~compas.geometry.Point`
        XY(Z) coordinates.
    polyline : sequence[point] | :class:`~compas.geometry.Polyline`
        XY(Z) coordinates of the points of the polyline.
    tol : float, optional
        The tolerance for membership verification.

    Returns
    -------
    bool
        True if the point is on the polyline.
        False otherwise.

    """
    for i in range(len(polyline) - 1):
        a = polyline[i]
        b = polyline[i + 1]
        c = closest_point_on_segment_xy(point, (a, b))

        if distance_point_point_xy(point, c) <= tol:
            return True

    return False

def is_point_in_triangle_xy(point, triangle, colinear=False):
    """Determine if a point is in the interior of a triangle lying on the XY-plane.

    Parameters
    ----------
    point : [float, float, float] | :class:`~compas.geometry.Point`
        XY(Z) coordinates of a point.
    triangle : [point, point, point]
        XY(Z) coordinates of the corners of the triangle.
    colinear : bool, optional
        Allow points to be colinear.

    Returns
    -------
    bool
        True if the point is in the convex polygon.
        False otherwise.

    """
    a, b, c = triangle
    ccw = is_ccw_xy(c, a, point, colinear)

    if ccw != is_ccw_xy(a, b, point, colinear):
        return False

    if ccw != is_ccw_xy(b, c, point, colinear):
        return False

    return True

def is_point_in_convex_polygon_xy(point, polygon):
    """Determine if a point is in the interior of a convex polygon lying on the XY-plane.

    Parameters
    ----------
    point : [float, float, float] | :class:`~compas.geometry.Point`
        XY(Z) coordinates of a point (Z will be ignored).
    polygon : sequence[point] | :class:`~compas.geometry.Polygon`
        A sequence of XY(Z) coordinates of points representing the locations of the corners of a polygon (Z will be ignored).
        The vertices are assumed to be in order. The polygon is assumed to be closed:
        the first and last vertex in the sequence should not be the same.

    Returns
    -------
    bool
        True if the point is in the convex polygon
        False otherwise.

    Warnings
    --------
    Does not work for concave polygons.

    """
    ccw = None
    for i in range(-1, len(polygon) - 1):
        a = polygon[i]
        b = polygon[i + 1]
        if ccw is None:
            ccw = is_ccw_xy(a, b, point, True)
        else:
            if ccw != is_ccw_xy(a, b, point, True):
                return False
    return True

def is_point_in_polygon_xy(point, polygon):
    """Determine if a point is in the interior of a polygon lying on the XY-plane.

    Parameters
    ----------
    point : [float, float, float] | :class:`~compas.geometry.Point`
        XY(Z) coordinates of a point (Z will be ignored).
    polygon : sequence[point] | :class:`~compas.geometry.Polygon`
        A sequence of XY(Z) coordinates of points representing the locations of the corners of a polygon (Z will be ignored).
        The vertices are assumed to be in order.
        The polygon is assumed to be closed.
        The first and last vertex in the sequence should not be the same.

    Returns
    -------
    bool
        True if the point is in the polygon.
        False otherwise.

    Warnings
    --------
    A boundary check is not yet implemented. This should include a tolerance value.

    """
    x, y = point[0], point[1]
    polygon = [(p[0], p[1]) for p in polygon]  # make 2D
    inside = False
    for i in range(-1, len(polygon) - 1):
        x1, y1 = polygon[i]
        x2, y2 = polygon[i + 1]
        if y1 != y2:
            xinters = (y - y1) * (x2 - x1) / (y2 - y1) + x1
        else:
            xinters = None
        if y > min(y1, y2):
            if y <= max(y1, y2):
                if x <= max(x1, x2):
                    if x1 == x2 or (xinters is not None and x <= xinters):
                        inside = not inside
    return inside

def is_point_in_circle_xy(point, circle):
    """Determine if a point lies in a circle lying on the XY-plane.

    Parameters
    ----------
    point : [float, float, float] | :class:`~compas.geometry.Point`
        XY(Z) coordinates of a point (Z will be ignored).
    circle : [[point, vector], float] | :class:`~compas.geometry.Circle`
        Center and radius of the circle on the XY plane.

    Returns
    -------
    bool
        True if the point lies in the circle.
        False otherwise.

    """
    dis = distance_point_point_xy(point, circle[0][0])
    if dis <= circle[1]:
        return True
    return False

def is_polygon_in_polygon_xy(polygon1, polygon2):
    """Determine if a polygon is in the interior of another polygon on the XY-plane.

    Parameters
    ----------
    polygon1 : sequence[point] | :class:`~compas.geometry.Polygon`
        List of XY(Z) coordinates of points representing the locations of the corners of the exterior polygon (Z will be ignored).
        The vertices are assumed to be in order. The polygon is assumed to be closed:
        the first and last vertex in the sequence should not be the same.
    polygon2 : sequence[point] | :class:`~compas.geometry.Polygon`
        List of XY(Z) coordinates of points representing the locations of the corners of the interior polygon (Z will be ignored).
        The vertices are assumed to be in order. The polygon is assumed to be closed:
        the first and last vertex in the sequence should not be the same.

    Returns
    -------
    bool
        True if polygon2 is inside polygon1.
        False otherwise.

    """
    if is_polygon_convex_xy(polygon1) and is_polygon_convex_xy(polygon2):
        for pt in polygon2:
            if not is_point_in_convex_polygon_xy(pt, polygon1):
                return False
        return True
    else:
        for i in range(len(polygon1)):
            line = [polygon1[-i], polygon1[-i - 1]]
            for j in range(len(polygon2)):
                line_ = [polygon2[-j], polygon2[-j - 1]]
                if is_intersection_segment_segment_xy(line, line_):
                    return False
        for pt in polygon2:
            if is_point_in_polygon_xy(pt, polygon1):
                return True
        return False

def is_intersection_line_line_xy(l1, l2, tol=1e-6):
    """Verifies if two lines intersect on the XY-plane.

    Parameters
    ----------
    l1 : [point, point] | :class:`~compas.geometry.Line`
        XY(Z) coordinates of two points defining a line.
    l2 : [point, point] | :class:`~compas.geometry.Line`
        XY(Z) coordinates of two points defining a line.
    tol : float, optional
        A tolerance for intersection verification.

    Returns
    -------
    bool
        True if the lines intersect in one point
        False if the lines are skew, parallel or lie on top of each other.

    """
    raise NotImplementedError

def is_intersection_segment_segment_xy(ab, cd):
    """Determines if two segments, ab and cd, intersect.

    Parameters
    ----------
    ab : [point, point] | :class:`~compas.geometry.Line`
        Two points representing the start and end points of a segment.
        Z coordinates will be ignored.
    cd : [point, point] | :class:`~compas.geometry.Line`
        Two points representing the start and end points of a segment.
        Z coordinates will be ignored.

    Returns
    -------
    bool
        True if the segments intersect.
        False otherwise.

    Notes
    -----
    The segments intersect if both of the following conditions are true:

    * `c` is on the left of `ab`, and `d` is on the right, or vice versa.
    * `d` is on the left of `ac`, and on the right of `bc`, or vice versa.

    """
    a, b = ab
    c, d = cd
    return is_ccw_xy(a, c, d) != is_ccw_xy(b, c, d) and is_ccw_xy(a, b, c) != is_ccw_xy(a, b, d)


import sys
from collections import defaultdict
import numpy as np
T = int(sys.stdin.readline())

def replace(c, j, v):
    a, b = str(v[0]), str(v[1])
    a = '0'*(len(c)-len(a)) + a
    b = '0'*(len(c)-len(b)) + b
    return a, b

def match(c,j, C, J):
    C, J = str(C), str(J)

    c = '0'*(3-len(c)) + c
    C = '0'*(3-len(C)) + C
    j = '0'*(3-len(j)) + j
    J = '0'*(3-len(J)) + J
    for a, b in zip(c,C):
        if a != b and a != '?':
            return False
    for a, b in zip(j,J):
        if a != b and a != '?':
            return False
    return True

for case in range(1, T+1):

    sys.stderr.write("Case #%d: \n" % case)
    sys.stdout.write("Case #%d: " % case)
    c, j = sys.stdin.readline().split()
    counts = defaultdict(list)
    currBest, currList = 9999999, []
    for C in range(0, 1000):
        for J in range(0, 1000):
            if abs(C-J) <= currBest and match(c, j, C, J):
                if abs(C-J) < currBest:
                    currBest = abs(C-J)
                    currList = [(C,J)]
                if abs(C-J) == currBest:
                    currList.append((C,J))

    counts[currBest] = currList
    m = min(counts.keys())
    if len(counts[m]) > 1:
        v = min(counts[m], key=lambda x: x[0])
        N = sum(map(lambda x: 1 if x[0] == v[0] else 0, counts[m]))
        if N == 1:
            v = replace(c, j, v)
            sys.stdout.write("%s %s\n" % (v[0], v[1]))
        else:
            v = min(counts[m], key=lambda x: x[1])
            v = replace(c, j, v)
            sys.stdout.write("%s %s\n" % (v[0], v[1]))
    else:
        v = replace(c, j, counts[m][0])
        sys.stdout.write("%s %s\n" % (v[0], v[1]))


'''
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the
non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
'''
from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        for num in nums:
            if num == 0:
                nums.remove(0)
                nums.insert(len(nums),0)

        return nums

    def moveZeroes1(self, nums: List[int]) -> None:
        c = 0

        for i in range(len(nums)):
            print (f"outside if :{nums[i]}")
            if nums[i]:
                print(f"inside if :{nums[i]}")

                nums[c] = nums[i]
                c += 1

        while c < len(nums):
            nums[c] = 0
            c += 1
        return nums

num = [0, 1, 0, 3, 12]

s = Solution()
print(s.moveZeroes(num))
num = [0, 1, 0, 0, 1, 2, 3, 12]

print(s.moveZeroes1(num))


#!/usr/bin/env python

import sys
import copy
import rospy
import actionlib
from threading import Lock, Event
from std_msgs.msg import String
from sensor_msgs.msg import Image, JointState
from geometry_msgs.msg import *
from std_msgs.msg import Float32MultiArray
import time

import franka_gripper
import franka_gripper.msg
from franka_msgs.msg import FrankaState, ErrorRecoveryGoal, ErrorRecoveryAction, ErrorRecoveryActionGoal
from franka_msgs.srv import SetFullCollisionBehavior, SetCartesianImpedance, SetJointImpedance
from rospy_message_converter import message_converter

from controller_manager_msgs.srv import ListControllers
from controller_manager_msgs.srv import SwitchController

import moveit_commander
from moveit_commander.conversions import pose_to_list
import moveit_msgs.msg
from moveit_msgs.msg import Constraints, OrientationConstraint

import numpy as np
from math import pi
from panda_interface.utils.general_utils import AttrDict, ParamDict
from panda_interface.utils.transform_utils import mat2quat, quat2mat, quat_multiply
from panda_interface.utils.ros_utils import create_pose_msg
from panda_interface.move_group_interface import PandaMoveGroupInterface
from panda_interface.collision_behaviour_interface import CollisionBehaviourInterface
from panda_interface.gripper import GripperInterface

class PandaArmInterface(object):
    def __init__(self, config=AttrDict()):
        self._hp = self._default_hparams().overwrite(config)

        self._joint_names = rospy.get_param("/franka_control/joint_names")
        self._joint_limits = self._get_joint_limits()
        # self._neutral_pose_joints = self._get_neutral_pose()
        self._neutral_pose_joints = dict(zip(self._joint_names, self._get_neutral_pose()))

        self._movegroup_interface = PandaMoveGroupInterface()
        self._collision_behaviour_interface = CollisionBehaviourInterface()
        self._collision_behaviour_interface.set_ft_contact_collision_behaviour()
        self._gripper = GripperInterface()

        rospy.wait_for_service('/controller_manager/switch_controller')
        self.switcher_srv = rospy.ServiceProxy('/controller_manager/switch_controller', SwitchController)

        self.franka_state = None
        self.error_recovery_client = actionlib.SimpleActionClient('/franka_control/error_recovery',
                                                                  ErrorRecoveryAction)

        # Waits until the action server has started up and started
        # listening for goals.
        print ("Waiting for error recovery server in franka_control")
        self.error_recovery_client.wait_for_server()
        print ("Found error recovery server")
        self.recover_from_errors()

        rospy.loginfo("Waiting for Franka States")
        self.state_subscriber = rospy.Subscriber('/franka_state_controller/franka_states',
                                                 FrankaState,
                                                 self._update_states)
        rospy.loginfo("Connected to Franka States")

        self.joint_subscriber = rospy.Subscriber('/franka_state_controller/joint_states',
                                                 JointState,
                                                 self._update_joints)

        self._cartesian_pose = None
        self._cartesian_effort = None
        self._cartesian_velocity = None
        self._timestamp_secs = None
        self._joint_angles = AttrDict()
        self._joint_velocity = AttrDict()
        self._joint_effort = AttrDict()

        if self.is_in_controller_list('cartesian_velocity_controller'):
            self.switch_controllers('cartesian_velocity_controller')
            rospy.loginfo("Waiting for current target velocity")
            self.cmd_vel_pub = rospy.Publisher("/franka_control/target_velocity", Twist, queue_size=1)
            rospy.loginfo("Connected to current trarget velocity")

        if self.is_in_controller_list('cartesian_pose_impedance_controller'):
            self.switch_controllers('cartesian_pose_impedance_controller')
            rospy.loginfo("Waiting for cartesian pose impedance publisher")
            self.cmd_pose_impedance_pub = rospy.Publisher("/cartesian_impedance_controller/desired_pose", PoseStamped, queue_size=10)
            rospy.sleep(1.)
            rospy.loginfo("Connected to cartesian pose impedance publisher")
        self.switch_controllers('position_joint_trajectory_controller')

    def _get_neutral_pose(self):
        joint_states = []
        for name in self._joint_names:
            joint_states.append(rospy.get_param("/franka_control/neutral_pose/{}".format(name)))
        return np.array(joint_states)

    def _get_joint_limits(self):
        """
        Get joint limits as defined in ROS parameter server
        (/franka_control/joint_config/joint_velocity_limit)
        :return: Joint limits for each joints
        :rtype: franka_core_msgs.msg.JointLimits
        """
        keys = ['position_upper', 'position_lower', 'velocity', 'accel', 'effort']
        lims = AttrDict()
        for key in keys:
            lims[key] = []
        vel_lim = rospy.get_param("/franka_control/joint_config/joint_velocity_limit")
        pos_min_lim = rospy.get_param("/franka_control/joint_config/joint_position_limit/lower")
        pos_max_lim = rospy.get_param("/franka_control/joint_config/joint_position_limit/upper")
        eff_lim = rospy.get_param("/franka_control/joint_config/joint_effort_limit")
        acc_lim = rospy.get_param("/franka_control/joint_config/joint_acceleration_limit")

        for i in range(len(self._joint_names)):
            lims.position_upper.append(pos_max_lim[self._joint_names[i]])
            lims.position_lower.append(pos_min_lim[self._joint_names[i]])
            lims.velocity.append(vel_lim[self._joint_names[i]])
            lims.accel.append(acc_lim[self._joint_names[i]])
            lims.effort.append(eff_lim[self._joint_names[i]])

        return lims

    def _default_hparams(self):
        default_dict = ParamDict({
            'group_name': 'panda_arm',
            'hand_group_name': 'hand',
            'load_gripper': True,
            'ee_safety_zone': [[0.30, 0.76], [-0.25, 0.25], [0.01, 0.4]],
        })
        return default_dict

    def ee_inside_safety_zone(self, xyz):
        return xyz[0] >= self._hp.ee_safety_zone[0][0] and xyz[0] <= self._hp.ee_safety_zone[0][1] and \
            xyz[1] >= self._hp.ee_safety_zone[1][0] and xyz[1] <= self._hp.ee_safety_zone[1][1] and \
            xyz[2] >= self._hp.ee_safety_zone[2][0] and xyz[2] <= self._hp.ee_safety_zone[2][1]

    def _update_states(self, msg):
        cart_pose_mat = np.asarray(msg.O_T_EE).reshape(4, 4, order='F')

        self._cartesian_pose = AttrDict(
            position=cart_pose_mat[:3, 3],
            orientation=mat2quat(cart_pose_mat),
            ori_mat=cart_pose_mat[:3, :3],
        )

        self._cartesian_velocity = AttrDict(
            linear=np.array(msg.O_dP_EE[:3]),
            angular=np.array([msg.O_dP_EE[3:]])
        )

        self._cartesian_effort = AttrDict(
            force=msg.O_F_ext_hat_K[:3],
            torque=msg.O_F_ext_hat_K[3:]
        )

        self._stiffness_frame_effort = AttrDict(
            force=msg.K_F_ext_hat_K[:3],
            torque=msg.K_F_ext_hat_K[3:]
        )

        self._cartesian_contact = msg.cartesian_contact
        self._cartesian_collision = msg.cartesian_collision

        self._joint_contact = msg.joint_contact
        self._joint_collision = msg.joint_collision

        # self._joint_inertia = np.array(msg.mass_matrix).reshape(7, 7, order='F')

        self.q_d = msg.q_d
        self.dq_d = msg.dq_d

        self._F_T_NE = msg.F_T_NE # should be constant normally
        # self._NE_T_EE = msg.NE_T_EE
        self._F_T_EE = msg.F_T_EE

        # self._gravity = np.array(msg.gravity)
        # self._coriolis = np.array(msg.coriolis)
        self._errors = message_converter.convert_ros_message_to_dictionary(
            msg.current_errors
        )
        self.franka_state = msg

    def _update_joints(self, msg):
        for i, name in enumerate(self._joint_names):
            if name in self._joint_names:
                self._joint_angles[name] = msg.position[i]
                self._joint_velocity[name] = msg.velocity[i]
                self._joint_effort[name] = msg.effort[i]

    def joint_angle(self, joint_name):
        return self._joint_angles[joint_name]

    def joint_angles(self):
        return copy.deepcopy(self._joint_angles)

    def joint_ordered_angles(self):
        return np.array([self._joint_angles[name] for name in self._joint_names])

    def joint_velocity(self, joint_name):
        return self._joint_velocity[joint_name]

    def joint_velocities(self):
        return copy.deepcopy(self._joint_velocity)

    def joint_effort(self, joint_name):
        return self._joint_effort[joint_name]

    def joint_efforts(self):
        return copy.deepcopy(self._joint_effort)

    def tip_pose(self):
        return copy.deepcopy(self._cartesian_pose)

    def tip_velocity(self):
        return copy.deepcopy(self._cartesian_velocity)

    def tip_effort(self, in_base_frame=True):
        return copy.deepcopy(self._cartesian_effort) if in_base_frame else copy.deepcopy(self._stiffness_frame_effort)

    def set_joint_position_speed(self, speed=0.3):
        """
        Set ratio of max joint speed to use during joint position
        moves (only for move_to_joint_positions).
        Set the proportion of maximum controllable velocity to use
        during joint position control execution. The default ratio
        is `0.3`, and can be set anywhere from [0.0-1.0] (clipped).
        Once set, a speed ratio will persist until a new execution
        speed is set.
        :type speed: float
        :param speed: ratio of maximum joint speed for execution
                      default= 0.3; range= [0.0-1.0]
        """
        if speed > 0.3:
            rospy.logwarn("{}: Setting speed above 0.3 could be risky!! Be extremely careful.".format(
                self.__class__.__name__))
        if self._movegroup_interface:
            self._movegroup_interface.set_velocity_scale(speed * 2)
        self._speed_ratio = speed

    def set_gripper_speed(self, speed):
        if self._gripper:
            self._gripper.set_velocity(speed)

    def exec_gripper_cmd(self, pos, force=None):
        """
        Move gripper joints to the desired width (space between finger joints), while applying
        the specified force (optional)
        :param pos: desired width [m]
        :param force: desired force to be applied on object [N]
        :type pos: float
        :type force: float
        :return: True if command was successful, False otherwise.
        :rtype: bool
        """
        if self._gripper is None:
            return

        width = min(self._gripper.MAX_WIDTH, max(self._gripper.MIN_WIDTH, pos))

        if force:
            holding_force = min(
                max(self._gripper.MIN_FORCE, force), self._gripper.MAX_FORCE)

            return self._gripper.grasp(width=width, force=holding_force)

        else:
            return self._gripper.move_joints(width)

    def exec_cartesian_pose_impedance_cmd(self, pos, ori=None):
        running = self.controller_is_running('cartesian_pose_impedance_controller')
        if not running:
            print ("Switching to position control")
            resp = self.switch_controllers('cartesian_pose_impedance_controller')

        pose = PoseStamped()
        pose.header.stamp = rospy.Time(0)
        if ori is None:
            ori = self._cartesian_pose['orientation']

        pose.pose.orientation.x = ori[0]
        pose.pose.orientation.y = ori[1]
        pose.pose.orientation.z = ori[2]
        pose.pose.orientation.w = ori[3]

        pose.pose.position.x = pos[0]
        pose.pose.position.y = pos[1]
        pose.pose.position.z = pos[2]

        current_pose = self.tip_pose()
        if np.abs(current_pose.position[0] - pos[0]) > 0.1 or np.abs(current_pose.position[1]-pos[1]) > 0.1 or np.abs(current_pose.position[2] - pos[2]) > 0.1:
            raise ValueError('Invalid position value')

        self.cmd_pose_impedance_pub.publish(pose)

    def exec_cartesian_velocity_cmd(self, twist):
        if not isinstance(twist, Twist):
            new_twist = Twist()
            new_twist.linear.x = twist[0]
            new_twist.linear.y = twist[1]
            new_twist.linear.z = twist[2]
            twist = new_twist

        running = self.controller_is_running('cartesian_velocity_controller')
        if not running:
            print ("Switching to position control")
            resp = self.switch_controllers('cartesian_velocity_controller')
        #
        # Clip x-velocity if outsize the safety zone and request is to further violate it
        #
        if self._cartesian_pose.position[0] < self._hp.ee_safety_zone[0][0] and twist.linear.x < 0:
            twist.linear.x = 0.0

        if self._cartesian_pose.position[0] > self._hp.ee_safety_zone[0][1] and twist.linear.x > 0:
            twist.linear.x = 0.0

        #
        # Clip y-velocity if outsize the safety zone and request is to further violate it
        #
        if self._cartesian_pose.position[1] < self._hp.ee_safety_zone[1][0] and twist.linear.y < 0:
            twist.linear.y = 0.0

        if self._cartesian_pose.position[1] > self._hp.ee_safety_zone[1][1] and twist.linear.y > 0:
            twist.linear.y = 0.0

        #
        # Clip z-velocity if outsize the safety zone and request is to further violate it
        #
        if self._cartesian_pose.position[2] < self._hp.ee_safety_zone[2][0] and twist.linear.z < 0:
            twist.linear.z = 0.0

        if self._cartesian_pose.position[2] > self._hp.ee_safety_zone[2][1] and twist.linear.z > 0:
            twist.linear.z = 0.0

        print(twist)
        self.cmd_vel_pub.publish(twist)

    def recover_from_errors(self):
        goal = ErrorRecoveryActionGoal()
        # goal = ErrorRecoveryGoal()
        self.error_recovery_client.send_goal(goal)
        print ("Waiting for recovery goal")
        self.error_recovery_client.wait_for_result()
        print ("Done")
        return self.error_recovery_client.get_result()

    def move_to_neutral(self, timeout=15, speed=0.15):
        self.set_joint_position_speed(speed)
        self.move_to_joint_positions(self._neutral_pose_joints, timeout)

    def move_to_joint_positions(self, positions,
                                timeout=10.0,
                                threshold=0.00085,
                                test=None, use_moveit=True):

        running = self.controller_is_running('position_joint_trajectory_controller')
        if not running:
            print ("Switching to position control")
            resp = self.switch_controllers('position_joint_trajectory_controller')

        if use_moveit and self._movegroup_interface:
            self._movegroup_interface.go_to_joint_positions(
                [positions[n] for n in self._joint_names], tolerance=threshold
            )
        else:
            if use_moveit:
                rospy.logwarn("{}: MoveGroupInterface was not found! Using JointTrajectoryActionClient instead.".format(
                    self.__class__.__name__))
            raise NotImplementedError

        rospy.loginfo("{}: Trajectory controlling complete".format(
            self.__class__.__name__))

    def get_flange_pose(self, pos=None, ori=None):
        """
        Get the pose of flange (panda_link8) given the pose of the end-effector frame.
        .. note:: In sim, this method does nothing.
        :param pos: position of the end-effector frame in the robot's base frame, defaults to current end-effector position
        :type pos: np.ndarray, optional
        :param ori: orientation of the end-effector frame, defaults to current end-effector orientation
        :type ori: quaternion.quaternion, optional
        :return: corresponding flange frame pose in the robot's base frame
        :rtype: np.ndarray, quaternion.quaternion
        """
        if pos is None:
            pos = self._cartesian_pose['position']

        if ori is None:
            ori = self._cartesian_pose['orientation']

        # get corresponding flange frame pose using transformation matrix
        F_T_EE = np.asarray(self._F_T_EE).reshape(4, 4, order="F")
        mat = quat2mat(ori)

        new_ori = mat.dot(F_T_EE[:3,:3].T)
        new_pos = pos - new_ori.dot(F_T_EE[:3, 3])

        return new_pos, mat2quat(new_ori).astype(np.float64)

    def move_to_cartesian_delta(self, pos, ori=None, use_moveit=True):
        current_pose = self._cartesian_pose
        desired_pos = current_pose['position'] + pos
        if ori is None:
            ori = np.array([0, 0, 0, 1])
        desired_ori = quat_multiply(current_pose['orientation'], ori)
        return self.move_to_cartesian_pose(desired_pos, desired_ori, use_moveit=use_moveit)

    def move_to_cartesian_pose(self, pos, ori=None, use_moveit=True):
        if not use_moveit or self._movegroup_interface is None:
            rospy.logerr("{}: MoveGroupInterface was not found! Aborting cartesian planning.".format(
                self.__class__.__name__))
            return

        running = self.controller_is_running('position_joint_trajectory_controller')
        if not running:
            print ("Switching to position control")
            resp = self.switch_controllers('position_joint_trajectory_controller')

        if ori is None:
            ori = self._cartesian_pose['orientation']

        self._movegroup_interface.go_to_cartesian_pose(
            create_pose_msg(*self.get_flange_pose(pos, ori))
        )
        rospy.loginfo("{}: Trajectory controlling complete".format(
            self.__class__.__name__))

    def switch_controllers(self, start_controller):
        stop_controller = self.get_current_controller()
        try:
            req = {'start_controllers': [start_controller] if start_controller is not None else [],
                   'stop_controllers': [stop_controller] if stop_controller is not None else [],
                   'strictness': 2,  # 2=strict, 1=best effort
                    #'start_asap': True, # for some reason this was excluded from ROS melodic
                    #'timeout': 3,  # in seconds
            }
            resp = self.switcher_srv(**req)
            rospy.sleep(0.2)
            return resp
        except rospy.ServiceException as e:
            print("Service call failed: %s"%e)

    def get_current_controller(self):
        controller_status = self.query_controller_status()
        for cs in controller_status.controller:
            if cs.state == 'running' and cs.name != "franka_state_controller":
                return cs.name
        # print("No controller found")

    def controller_is_running(self, name):
        controller_status = self.query_controller_status()
        for cs in controller_status.controller:
            if cs.name == name:
                return cs.state == 'running'

        return False

    def is_in_controller_list(self, name):
        controller_status = self.query_controller_status()
        for cs in controller_status.controller:
            if cs.name == name:
                return True
        return False

    def query_controller_status(self):
        rospy.wait_for_service('/controller_manager/list_controllers')
        try:
            srv = rospy.ServiceProxy('/controller_manager/list_controllers', ListControllers)
            resp = srv()
            return resp
        except rospy.ServiceException as e:
            print("Service call failed: %s"%e)

    def set_collision_threshold(self, cartesian_forces=None, joint_torques=None):
        """
        Set Force Torque thresholds for deciding robot has collided.
        :return: True if service call successful, False otherwise
        :rtype: bool
        :param cartesian_forces: Cartesian force threshold for collision detection [x,y,z,R,P,Y] (robot motion stops if violated)
        :type cartesian_forces: [float] size 6
        :param joint_torques: Joint torque threshold for collision (robot motion stops if violated)
        :type joint_torques: [float] size 7
        """
        if self._collision_behaviour_interface:
            return self._collision_behaviour_interface.set_collision_threshold(joint_torques=joint_torques, cartesian_forces=cartesian_forces)
        else:
            rospy.logwarn("No CollisionBehaviourInterface object found!")

    def set_cartesian_impedance(self, cb=None):
        current = self.get_current_controller()
        self.switch_controllers(None)
        rospy.wait_for_service("/franka_control/set_cartesian_impedance")
        if cb is None:
            cb = [2000, 2000, 2000, 300, 300, 300]

        try:
            cartesian_impedance_srv = rospy.ServiceProxy("/franka_control/set_cartesian_impedance", SetCartesianImpedance)
            resp = cartesian_impedance_srv(cb)
            rospy.sleep(0.2)
            self.switch_controllers(current)
            return resp.success
        except rospy.ServiceException as e:
            print("Service call failed: %s"%e)

    def set_joint_impedance(self, cb=None):
        current = self.get_current_controller()
        self.switch_controllers(None)
        rospy.wait_for_service("/franka_control/set_joint_impedance")
        if cb is None:
            cb = [3000, 3000, 3000, 2500, 2500, 2000, 2000]

        try:
            joint_impedance_srv = rospy.ServiceProxy("/franka_control/set_joint_impedance", SetJointImpedance)
            # resp = joint_impedance_srv(**cb)
            resp = joint_impedance_srv(cb)
            rospy.sleep(0.2)
            self.switch_controllers(current)
            return resp.success
        except rospy.ServiceException as e:
            print("Service call failed: %s"%e)

    def is_in_safe_state(self):
        return (not self.is_in_collision_mode() and \
                not self.is_in_user_stop_mode() and \
                not self.error_in_current_state())

    def is_in_contact_mode(self):
        if self.franka_state is None:
            return False

        return any(self.franka_state.joint_contact)

    def is_in_collision_mode(self):
        if self.franka_state is None:
            return False

        return self.franka_state.robot_mode == FrankaState.ROBOT_MODE_REFLEX

    def is_in_move_mode(self):
        if self.franka_state is None:
            return False

        return self.franka_state.robot_mode == FrankaState.ROBOT_MODE_MOVE

    def is_in_idle_mode(self):
        if self.franka_state is None:
            return False

        return self.franka_state.robot_mode == FrankaState.ROBOT_MODE_IDLE

    def is_in_user_stop_mode(self):
        if self.franka_state is None:
            return False
        return self.franka_state.robot_mode == FrankaState.ROBOT_MODE_USER_STOPPED

    def error_in_current_status(self):
        return not all([e == False for e in list(self._errors.values())])

    def get_robot_status(self):
        return AttrDict(
            robot_mode=self.franka_state.robot_mode,
            robot_status=(not self.is_in_collision_mode() and not self.is_in_user_stop_mode()),
            errors=self._errors,
            error_in_current_status=self.error_in_current_status()
        )

    @property
    def gripper(self):
        return self._gripper

    @property
    def coriolis_comp(self):
        return self._coriolis

    @property
    def gravity_comp(self):
        return self._gravity

    @property
    def movegroup_interface(self):
        return self._movegroup_interface

    @property
    def joint_limits(self):
        return self._joint_limits

    @property
    def joint_names(self):
        return self._joint_names

    @property
    def errors(self):
        return self._errors


import csv
import requests
from bs4 import BeautifulSoup

url = "https://finance.naver.com/sise/sise_market_sum.nhn?sosok=0&page="

filename = "시가총액 1-200.csv"
f = open(filename, "w", encoding="utf-8-sig", newline="") # 개행 없이 데이터를 넣는다
writer = csv.writer(f) # writer 를 이용해서 f 를 쓸 수 있음

title = "N	종목명	현재가	전일비	등락률	액면가	시가총액	상장주식수	외국인비율	거래량	PER	ROE".split("\t")
# ['N', '종목명', '현재가', ...]
writer.writerow(title)

for page in range(1, 2):
    res = requests.get(url + str(page))
    res.raise_for_status()
    soup = BeautifulSoup(res.text, "lxml")

    date_rows = soup.find("table", attrs={"class":"type_2"}).find("tbody").find_all("tr")
    for row in date_rows:
        columns = row.find_all("td")
        if len(columns) <= 1:
            continue # "td" element 가 1개 이하인 columns 리스트는 빼고
        data = [column.get_text().strip() for column in columns] # strip() : 인자로 전달된 문자를 양쪽에서 제거
        # print(data)
        writer.writerow(data)


from .db import db, environment, SCHEMA, add_prefix_for_prod
from sqlalchemy.sql import func
from sqlalchemy.orm import validates

class WorkspaceInvitation(db.Model):
    __tablename__ = 'workspace_invitations'

    if environment == "production":
        __table_args__ = {'schema': SCHEMA}

    id = db.Column(
      db.Integer,
      primary_key=True
    )
    sender_id = db.Column(
      db.Integer,
      db.ForeignKey(add_prefix_for_prod("users.id")),
      nullable=False
    )
    recipient_id = db.Column(
      db.Integer,
      db.ForeignKey(add_prefix_for_prod("users.id")),
      nullable=False
    )
    workspace_id = db.Column(
      db.Integer,
      db.ForeignKey(add_prefix_for_prod("workspaces.id")),
      nullable=False
    )
    status = db.Column(
      db.String(30),
      default="pending",
      nullable=False
    )
    created_at = db.Column(
      db.DateTime,
      nullable=False,
      default=func.now()
    )

    sender = db.relationship(
      "User",
      foreign_keys="WorkspaceInvitation.sender_id",
      back_populates="sent_workspace_invitations"
    )
    recipient = db.relationship(
      "User",
      foreign_keys="WorkspaceInvitation.recipient_id",
      back_populates="received_workspace_invitations"
    )
    workspace = db.relationship(
      "Workspace",
      foreign_keys="WorkspaceInvitation.workspace_id",
      back_populates="associated_invitations"
    )

    recipient_id_index = db.Index(
      'ix_workspace_invitations_recipient_id',
      recipient_id
    )
    sender_id_index = db.Index(
      'ix_workspace_invitations_sender_id',
      sender_id
    )
    created_at_index = db.Index(
      'ix_workspace_invitations_created_at',
      created_at
    )

    @validates("status")
    def validate_role(self, key, value):
      if value != "pending" and value != "accepted" and value != "ignored":
        raise ValueError("Status must be 'pending', 'accepted', or 'ignored'")
      return value

    def to_dict(self):
      return {
        'id': self.id,
        'senderEmail': self.sender.email,
        'recipientEmail': self.recipient.email,
        'workspaceId': self.workspace_id,
        'workspaceName': self.workspace.name,
        'status': self.status,
        'createdAt': self.created_at
      }


'''
The labyrinth has no walls, but bushes surround the path on each side.
If a players move into a bush, they lose.
The labyrinth is presented as a matrix (a list of lists): 1 is a bush and 0 is part of the path.
The labyrinth's size is 12 x 12 and the outer cells are also bushes. Players start at cell (1,1).
The exit is at cell (10,10). You need to find a route through the labyrinth.
Players can move in only four directions--South (down [1,0]), North (up [-1,0]), East (right [0,1]),
West (left [0, -1]). The route is described as a string consisting of different characters: "S"=South,
"N"=North, "E"=East, and "W"=West.
Input: A labyrinth map as a list of lists with 1 and 0.
Output: The route as a string that contains "W", "E", "N" and "S".
Precondition: Outer cells are pits.
len(labyrinth) == 12
all(len(row) == 12 for row in labyrinth)
'''
#Your code here
#You can import some modules or create additional functions

ori_right = ['N', 'W', 'S', 'E']
ori_left = ['N', 'E', 'S', 'W']

def turn_right(ori):
    return ori_right[ori_right.index(ori) - 1]

def turn_left(ori):
    return ori_left[ori_left.index(ori) - 1]

def front_watch(maze_map, ori, px, py):
    if ori == 'N':
        px -= 1
    if ori == 'E':
        py += 1
    if ori == 'S':
        px += 1
    if ori == 'W':
        py -= 1
    return maze_map[px][py]

def real_walk(ori, px, py):
    if ori == 'N':
        px -= 1
    if ori == 'E':
        py += 1
    if ori == 'S':
        px += 1
    if ori == 'W':
        py -= 1
    return px, py

def left_watch(maze_map, ori, px, py):
    ori = turn_left(ori)
    return front_watch(maze_map, ori, px, py)

def right_watch(maze_map, ori, px, py):
    ori = turn_right(ori)
    return front_watch(maze_map, ori, px, py)

def walk(maze_map, ori, px, py, result):
    if left_watch(maze_map, ori, px, py) == 0:
        ori = turn_left(ori)
    if front_watch(maze_map, ori, px, py) == 0:
        result += ori
        px, py = real_walk(ori, px, py)
        return [result, ori, px, py]
    else:
        ori = turn_right(ori)
        return walk(maze_map, ori, px, py, result)

def checkio(maze_map):
    orientation = 'E'
    position = [1, 1]
    result = ''
    while 1:
        result, orientation, position[0], position[1] = walk(maze_map, orientation, position[0], position[1], result)
        if position[0] == 10 and position[1] == 10:
            break
    return result

# def checkio(maze_map):
#     def canwalk(come, px, py):
#         out = ''
#         if maze_map[px-1][py] == 0:
#             out += 'N'
#         if maze_map[px][py+1] == 0:
#             out += 'E'
#         if maze_map[px+1][py] == 0:
#             out += 'S'
#         if maze_map[px][py-1] == 0:
#             out += 'W'
#         if come == 'N':
#             come = 'S'
#         elif come == 'S':
#             come = 'N'
#         elif come == 'W':
#             come = 'E'
#         elif come == 'E':
#             come = 'W'
#         out = out.replace(come, '')
#         return out
#     def walk(orientation, px, py):
#         if orientation == 'N':
#             px -= 1
#         if orientation == 'E':
#             py += 1
#         if orientation == 'S':
#             px += 1
#         if orientation == 'W':
#             py -= 1
#         return [px, py]
#     def load(save_p, save_choose, save_result):
#         position = save_p[-1]
#         del save_p[-1]
#         choose = save_choose[-1]
#         del save_choose[-1]
#         result = save_result[-1]
#         del save_result[-1]
#         return [position, choose, result]
#     def save(position, choose, result, save_p, save_choose, save_result):
#         save_p.append(position)
#         save_choose.append(choose)
#         save_result.append(result)
#     position = [1, 1]
#     choose = canwalk('', position[0], position[1])
#     result = ''
#     save_p = []
#     save_choose = []
#     save_result = []
#     while 1:
#         if len(choose) == 0:
#             if len(save_p) > 0:
#                 position, choose, result = load(save_p, save_choose, save_result)
#                 continue
#         orientation = choose[0]
#         if len(choose) > 1:
#             if position in save_p:
#                 if position == save_p[-1]:
#                     del save_p[-1]
#                     del save_choose[-1]
#                     del save_result[-1]
#                 position, choose, result = load(save_p, save_choose, save_result)
#                 continue
#             save(position, choose.replace(orientation, ''), result, save_p, save_choose, save_result)
#         position = walk(orientation, position[0], position[1])
#         result += orientation
#         if position[0] == 10 and position[1] == 10:
#             return result
#         choose = canwalk(orientation, position[0], position[1])

if __name__ == '__main__':
    #This code using only for self-checking and not necessary for auto-testing
    def check_route(func, labyrinth):
        MOVE = {"S": (1, 0), "N": (-1, 0), "W": (0, -1), "E": (0, 1)}
        #copy maze
        route = func([row[:] for row in labyrinth])
        pos = (1, 1)
        goal = (10, 10)
        for i, d in enumerate(route):
            move = MOVE.get(d, None)
            if not move:
                print("Wrong symbol in route")
                return False
            pos = pos[0] + move[0], pos[1] + move[1]
            if pos == goal:
                return True
            if labyrinth[pos[0]][pos[1]] == 1:
                print("Player in the pit")
                return False
        print("Player did not reach exit")
        return False

    # These assert are using only for self-testing as examples.
    assert check_route(checkio, [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
        [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
        [1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1],
        [1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1],
        [1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1],
        [1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "First maze"
    assert check_route(checkio, [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Empty maze"
    assert check_route(checkio, [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Up and down maze"
    assert check_route(checkio, [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
        [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
        [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
        [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
        [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Dotted maze"
    assert check_route(checkio, [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1],
        [1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1],
        [1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1],
        [1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
        [1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Need left maze"
    assert check_route(checkio, [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1],
        [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
        [1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "The big dead end."
    print("The local tests are done.")


__author__ = 'erol.selitektay'
import csv
class csvLibrary(object):

    def read_csv_file(self, filename):
        '''
        Reads data from given csv file.

        Example:

        ${data} Read Csv File  "path-to-csvfile"

        You can get the data such as ${data[rowNumber][ColumnNumber]}

        Starting point is [0][0]
        '''
        data = []
        with open(filename, 'rb') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                data.append(row)
        return data
        csvfile.close()


# Python Object-Oriented programming

'''
data and functions = attributes and methods ( a function associated with a class)

Class
Instance of class
Class variables
Instance variables ## this video
'''

class Employee:
    num_of_emps = 0
    raise_amount = 1.04
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@outlook.com'

        Employee.num_of_emps += 1

    def fullname (self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(float(self.pay) * self.raise_amount)

    @classmethod
    def set_raise_amt(cls, amount):
        cls.raise_amount = amount

    @classmethod
    def from_string(cls, emp_str):
        first, last, pay = emp_str.split('-')
        return cls(first, last, pay)

    @staticmethod
    def is_workday(day):
        if day.weekday() == 5 or day.weekday() == 6:
            return False
        return True

import datetime
my_date = datetime.date(2016, 7, 10)
print(Employee.is_workday(my_date))

# print(Employee.num_of_emps)
emp1 = Employee('Alex', 'Bourg', 50000)
emp2 = Employee('Anne', 'Smith', 60000)

emp_str_1 = 'John-Doe-7000'
emp_str_2 = 'Steven-Smith-3000'
emp_str_3 = 'Jane-Doe-9000'

new_emp_1 = Employee.from_string(emp_str_1)

# print(emp1.pay)
# emp1.apply_raise()
# print(emp1.pay)

# print(emp1.__dict__)
# print(Employee.__dict__)
# Employee.set_raise_amt(1.06)

# emp1.raise_amount = 1.05
# print(Employee.raise_amount)
# print(emp1.raise_amount)
# print(emp2.raise_amount)

# print(Employee.num_of_emps)

print(new_emp_1.email)


#!/usr/bin/env python

import rospy
import numpy as np
from math import ceil
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

class SimpleBot:

    def __init__(self):
        self.dist_to_wall_in_front = float('inf')
        self.range_left = float('inf')
        self.range_right = float('inf')
        rospy.init_node('simple_bot')
        self.rate = rospy.Rate(10)

    def update_dist_callback(self, msg):
        ranges = msg.ranges
        mid_index = (int)(len(ranges) / 2)
        self.dist_to_wall_in_front = ranges[mid_index]
        self.range_left=ranges[1]

        theta = np.pi/2.0-msg.angle_max
        self.range_right=ranges[len(ranges)-1]*np.cos(theta)

    def main(self):

        laser_sub = rospy.Subscriber('/scan', LaserScan, self.update_dist_callback)
        vel_pub = rospy.Publisher('/mobile_base/commands/velocity', Twist)

        while not rospy.is_shutdown():
            print(self.range_right)

            if self.dist_to_wall_in_front < 0.5:
                if self.range_right < 0.5:
                    msg = Twist()
                    msg.angular.z=0.2
                    vel_pub.publish(msg)
                else:
                    msg = Twist()
                    msg.angular.z=-0.2
                    vel_pub.publish(msg)
                # Stop
                #msg = Twist()
                #vel_pub.publish(msg)
            else:
                # GO
                msg = Twist()
                msg.linear.x = 0.3
                vel_pub.publish(msg)

                if self.range_right >0.5:
                    msg = Twist()
                    msg.angular.z=-0.2
                    vel_pub.publish(msg)

            self.rate.sleep()

if __name__ == "__main__":
    simple_bot = SimpleBot()
    simple_bot.main()


import pyaudio
import keyboard
import tempfile
import wave
from openai import OpenAI
from dotenv import load_dotenv
import os

# Parameters for recording
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 1024
HOTKEY_START = "ctrl+alt+l"
HOTKEY_STOP = "ctrl+alt+s"
load_dotenv()
client = OpenAI()

def start_recording():
    audio = pyaudio.PyAudio()

    recorded_data = None  # This will store the audio data

    while True:
        if keyboard.is_pressed(HOTKEY_START):
            print("Recording started...")
            stream = audio.open(format=FORMAT, channels=CHANNELS,
                                rate=RATE, input=True,
                                frames_per_buffer=CHUNK)
            frames = []

            # Keep recording until 's' is pressed
            while not keyboard.is_pressed(HOTKEY_STOP):
                data = stream.read(CHUNK)
                frames.append(data)

            print("Recording stopped.")

            # Stop and close the stream
            stream.stop_stream()
            stream.close()
            # Terminate the PortAudio interface
            audio.terminate()

            # Store the audio data in the recorded_data variable
            recorded_data = b''.join(frames)
            break

    # Generate a unique filename for the temporary WAV file
    temp_filename = tempfile.mktemp(suffix=".wav")

    # Save the audio data to the temporary WAV file
    with wave.open(temp_filename, 'wb') as wf:
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(pyaudio.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(recorded_data)

    # Re-open the temporary file in binary read mode for transcription
    with open(temp_filename, 'rb') as f:
        response = client.audio.transcriptions.create(
            model="whisper-1",
            file=f,
            response_format='json'
        )

    # Clean up by removing the temporary file
    os.remove(temp_filename)

    return response.text


#This example is to modeling a car using the decomposition model.

class Automovil:
    def __init__(self, modelo, marca, color):  #Constructor init
        self.modelo = modelo  #inicializamos las variables de instancias
        self.marca = marca
        self.color = color
        self._estado = "en_reposo"   #Usamos una variable privada con el _ al principio. Damos un estado, comienza en reposo.
        self.motor = Motor(cilindros=4)

    def acelerar(self, tipo="despacio"):
        if tipo == "rapida":
            self._motor.inyecta_gasolina(10)
        else:
            self._motor.inyecta_gasolina(3)

        self._estado = "en_movimiento"

class Motor:
    def __init__(self, cilindros, tipo="gasolina"):  # tipo="gasolina" este es un parámetro por defecto o default keyword.
        self.cilindros = cilindros
        self.tipo = tipo
        self._temperatura = 0

    def inyecta_gasolina(self, cantidad):
        pass


'''
Created on 08.11.2012

@author: himikof
'''
import unittest
import struct

from nfw.protocol import StatefulProtocol

from twisted.internet.defer import inlineCallbacks

class MockProtocol(StatefulProtocol):
    @inlineCallbacks
    def stateMachine(self):
        self.cmd = yield self.readInt32()
        self.str = yield self.readString()

    def protocolError(self, failure):
        raise failure

class TestProtocol(unittest.TestCase):

    def setUp(self):
        self.p = MockProtocol()

    def tearDown(self):
        del self.p

    def testRead(self):
        d1 = self.p.readBytes(4)
        d2 = self.p.readUnpacked('3s')
        self.assertFalse(d1.called)
        self.assertFalse(d2.called)
        self.p.dataReceived(b'1234567')
        self.assertTrue(d1.called)
        self.assertEqual(d1.result, b'1234')
        self.assertTrue(d2.called)
        self.assertEqual(d2.result, ('567',))

    def testSM(self):
        teststr = u'\u041f\u0440\u0438\u0432\u0435\u0442!'
        encoded = teststr.encode('utf8')
        self.p.dataReceived(struct.pack('!I', 42))
        self.p.dataReceived(struct.pack('!I', len(encoded)) + encoded)
        self.assertEqual(self.p.cmd, 42)
        self.assertEqual(self.p.str, teststr)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()