# authomatic Nudget Elastic Band Method (NEB) for vacancy migration energy barrier with LAMMPS
# Stefano Segantin
# Politecnico di Torino

# ---------- DISCUSSION ------------------------------------------------------------------------------------------------
# this routine relies on the assumption that the position in the box of all the atoms rests the same in the intial
# simulation and in the NEB simulation. It is not always like that. In order to do that you need to use the same number
# of parallelized core in both the simulations

########################################################################################################################
# import section
import os
import numpy as np
import NEB_stats as neb
import NEB_readout as nebro
import pandas as pd

myDir = os.getcwd()
os.chdir(myDir)
initialfile = r'data.***.0'
myneb = neb.NEBstats(initialfile)  # this just opens the
mynebro = nebro.NEBreadout()

microstructure = "BCC"
ao = 3.31642067489331  # lattice constant
N_rnd_atoms = 1  # number of random atoms to pick
finalfile = r"final.***"
lmpInFile = r"***_neb_py.in"
nebOutFile = r"***_neb_py.xlsx"

vacancies = []
neighbors = []
MainInfo = []
atom_coords = myneb.atomCoords()
box_size = myneb.boxSize()
num_atoms = myneb.numAtoms()
MI = []
counter = 0
for sample in range(N_rnd_atoms):
    print("NUMBER OF VACANCY SAMPLED = %s" % (sample))
    rndvacancy = myneb.randAtomID(num_atoms, atom_coords, box_size, ao, 1)
    vacancyID = int(rndvacancy[0])
    neighbors = myneb.atomNN(atom_coords, microstructure, ao, vacancyID)
    vacancies.append(rndvacancy)
    NNs = []
    for NN in neighbors:
        file = myneb.writeFinalFile(finalfile, rndvacancy, NN)
        NNs.append(NN)

        txtin = (r""" # Nudged elastic band (NEB) analysis
#Politecnico di Torino

# ---------- INITIALIZATION ----------------------------------------------------
clear
timer		full
units		metal  # A ps K bar eV
dimension	3
boundary	p p p
atom_style	atomic
atom_modify	map array

variable	ao equal %s
# ---------- GEOMETRY DEFINITION -----------------------------------------------
lattice	bcc ${ao}
read_data %s

group

# ---------- create vacancy ----------------------------------------------------
group   vacancy id %s
delete_atoms group vacancy compress no

# ---------- FORCE FIELD -------------------------------------------------------
pair_style
pair_coeff	* *
neigh_modify    every 1 delay 0 check yes

# ---------- dumb run ----------------------------------------------------------
run		0
# ---------- SETTINGS ----------------------------------------------------------
# COMPUTES
compute	csym all centro/atom bcc
compute	eng all pe/atom
compute	eatoms all reduce sum c_eng
# VARIABLES
variable	N equal count(all)
variable	Eavg equal c_eatoms/$N

# ---------- DYNAMICS ----------------------------------------------------------
# ---------- energy minimization -----------------------------------------------
# PRINT-SCREEN
thermo
thermo_style
displace_atoms all random
minimize

# --------- NEB analysis -------------------------------------------------------
variable	u uloop
reset_timestep	0
fix		1 all neb
timestep
min_style	quickmin
neb		 final %s
""" % (str(ao), str(initialfile), str(vacancyID), str(finalfile)))

        with open(lmpInFile, 'w') as input_file:
            input_file.write(txtin)

        os.system('mpiexec -np 10 lmp_mpi -partition 10x1 -in %s' % lmpInFile)
        # get the info about the climbing replica
        Creplica_data, Creplica_num = mynebro.climbingReplica()
        Ebarrier = mynebro.energyBarrier(Creplica_data[-1])
        MI.append([rndvacancy[0], rndvacancy[1], NN[0], NN[1], Ebarrier])

    neighbors.append(NNs)
    MainInfo.append(MI)

MI = np.array(MI)
df = pd.DataFrame(MI)
df.to_excel(excel_writer=nebOutFile)


from django.db import connection

def ingredient_name_and_amount_query(receipt_id):
    with connection.cursor() as cursor:
        cursor.execute(f"SELECT ingredient_calories.ingredient_name, receipt_ingredient.amount, receipt_ingredient.amount_type \
                        FROM  receipt_ingredient \
                        Inner Join ingredient_calories on \
                        receipt_ingredient.ingredient_name_frk_id = ingredient_calories.id \
                        where receipt_ingredient.recipe_frk_id = %s", (receipt_id,))
        rows = cursor.fetchall()
        ingredients_of_receipt = []
        for row in rows:
            ingredient = {"ingredient_name": row[0], "amount": row[1], "amount_type": row[2]}
            ingredients_of_receipt.append(ingredient)
        return ingredients_of_receipt

# total_receipt_cal_per_100gr:
def total_receipt_cal_per_100gr(receipt_id):
    with connection.cursor() as cursor:
        cursor.execute(f"select (COALESCE(SUM (ingredient_calories.ingredient_calories_per_100_gr_or_ml), 0) * 100)/COALESCE(SUM(receipt_ingredient.amount),0) \
                       from receipt_ingredient, ingredient_calories \
                       WHERE ingredient_calories.id = receipt_ingredient.ingredient_name_frk_id and \
                       receipt_ingredient.recipe_frk_id = %s \
                       group by receipt_ingredient.recipe_frk_id", (receipt_id,))
        total_cal = cursor.fetchone()[0]
        return total_cal

# search_recipe_by_category:
def search_recipe_by_category(category):
    with connection.cursor() as cursor:
        cursor.execute(f"SELECT recipe.id, recipe.recipe_name, recipe.pic_url \
                       FROM  recipe \
                       where recipe.recipe_category = %s", (category,))
        rows = cursor.fetchall()
        all_recipes_by_category = []
        for row in rows:
            recipe_details = {"recipe_id": row[0], "recipe_name": row[1], "recipe_url": row[2]}
            # all_recipes_by_category[row[0]] = recipe_details
            all_recipes_by_category.append(recipe_details)
        print(all_recipes_by_category)
        return all_recipes_by_category


import numpy as np
from random import randrange

from backend.rl_base_classes.mp_base_classes import FPATrimsAndTurns, MovingTargetFPATrimsAndTurns
from backend.rl_environments import DiscreteEnv
from backend.base_aircraft_classes.target_classes import MovingTarget

def run_actions(_initial_state, _env, _actions, plot=False):
    done = False
    i = 0
    max_i = len(_actions)
    _ = _env.reset(initial_state=_initial_state)
    while not done and i < max_i:
        action = _actions[i]
        _, __, done, ___ = _env.step(action)
        i += 1

    if plot:
        _env.agent.plot_state_history(style='3d')

agent = 'MovingTargetFPATrimsAndTurns'
initial_state = np.array((19000, np.deg2rad(35.1), np.deg2rad(-179.6), 6000, 0, -np.pi/2))
target_state = np.array((00000, np.deg2rad(40.4), np.deg2rad(-86.9), 100, 0, 0))

if agent == 'FPATrimsAndTurns':
    env = DiscreteEnv(FPATrimsAndTurns(initial_state, target_state[:3]))
elif agent == 'MovingTargetFPATrimsAndTurns':
    target = MovingTarget(target_state)
    env = DiscreteEnv(MovingTargetFPATrimsAndTurns(initial_state, target))

for trial in range(500):
    actions = [randrange(0, env.agent.n_actions) for __ in range(100)]
    run_actions(initial_state, env, actions, plot=False)
    print(f'Finished trial {trial}\n')


import copy, re

from django.core import validators
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _

__all__ = ['EmptyValidator', 'KeysValidator', 'MD5ChecksumValidator']

class EmptyValidator(validators.RegexValidator):
    regex = r'\S+'
    message = _('This field cannot be blank.')
    code = 'blank'

@deconstructible
class KeysValidator(object):
    """
    A validator designed for HStore to require, even restrict keys.

    Code mostly borrowed from:

    https://github.com/django/django/blob/master/django/contrib/postgres/validators.py
    """

    messages = {
        'missing_keys': _('Some keys were missing: %(keys)s'),
        'extra_keys': _('Some unknown keys were provided: %(keys)s'),
    }
    strict = False

    def __init__(self, required_keys=None, optional_keys=None, strict=False, messages=None):
        self.required_keys = set(required_keys or [])
        self.optional_keys = set(optional_keys or [])
        if not self.required_keys and not self.optional_keys:
            raise ImproperlyConfigured('You must set at least `required_keys` or `optional_keys`')
        self.strict = strict
        if messages is not None:
            self.messages = copy.copy(self.messages)
            self.messages.update(messages)

    def __call__(self, value):
        keys = set(value.keys())
        if self.required_keys:
            missing_keys = self.required_keys - keys
            if missing_keys:
                raise ValidationError(
                    self.messages['missing_keys'],
                    code='missing_keys',
                    params={'keys': ', '.join(missing_keys)})
        if self.strict:
            extra_keys = keys - self.required_keys - self.optional_keys
            if extra_keys:
                raise ValidationError(
                    self.messages['extra_keys'],
                    code='extra_keys',
                    params={'keys': ', '.join(extra_keys)})

    def __eq__(self, other):
        return (
            isinstance(other, self.__class__)
            and self.required_keys == other.required_keys
            and self.optional_keys == other.optional_keys
            and self.messages == other.messages
            and self.strict == other.strict
        )

    def __ne__(self, other):
        return not self == other

class MD5ChecksumValidator(validators.RegexValidator):
    regex = re.compile(r'[0-9a-f]{32}')


from .models import TodoModel
from django import forms

class TodoForm(forms.ModelForm):
    class Meta:
        model = TodoModel
        fields = '__all__'

        labels ={
            'subject':'',
            'details':'',
        }

        widgets = {
         'subject': forms.TextInput(attrs={'class': 'form-control bg-info rounded-5  p-3','rows': 2,'cols': 1,'placeholder': 'Enter Subjecct','id': 'id_content' }),
         'details': forms.Textarea(attrs={'class': 'form-control bg-info border-0 p-3','rows': 3,'cols': 1,'placeholder': 'Write Details','id': 'id_content' })
        }


from bs4 import BeautifulSoup
from urllib.request import urlopen,Request,urlretrieve,build_opener,install_opener
import os
import random
from main.models import Post,Images
from django.core.files import File
from django.contrib.auth.models import User
from main.categories import user_agent_list

class ScrapeFunction:
    user_agent=user_agent = random.choice(user_agent_list)
    headers = {'User-Agent': user_agent }

    def __init__(self,):
        super().__init__()

    def getHTML(self,link):
        try:
            html = urlopen(link).read()
        except Exception as e:
            req = Request(link, headers=self.headers)
            html = urlopen(req).read()

        response = BeautifulSoup(html, "html.parser")
        return response

class PamakeoPress:

    def __init__(self):
        super().__init__()

    def news_items(self,link='http://pamakiopress.rw/'):
        try:
            get_html=ScrapeFunction().getHTML(link)
            #get_html=ScrapeFunction().getHTML('file:///home/hacker/Desktop/Video%20Toutorial/Amakuru%20yizewe%20yuzuye%20kandi%20kugihe%20-%20Pamakio%20Press.html')
            #articles=get_html.find_all('article',class_='mh-loop-item')
        except Exception as e:
            pass

        result=list()

        from_={
            'Amakuru':'mh_magazine_lite_posts_focus-3',
            'Imikino':'mh_magazine_lite_posts_focus-4',
            'Politiki':'mh_custom_posts-12',
            'Imyidagaduro':'mh_custom_posts-9',
            'Ubuzima':'mh_custom_posts-8'
            #'utunu n\'utundi'
        }
        i=0
        try:
            for category in from_:
                #print(category)
                #print('--'*15)
                articles=get_html.find(id=from_[category])
                user=User.objects.all().first()
                for li in articles.find_all('figure'):

                    im=Images()

                    news_link=li.find('a')['href']
                    thumbnail=self.getThumbnail(news_link)
                    title=self.getTitle()
                    result = urlretrieve(thumbnail)
                    im.image_from=title
                    im.image.save(os.path.basename(im.image_from+str(i) +'.png'), File(open(result[0], 'rb')))
                    post=Post.objects.filter(title=title).exists()

                    #check if post not exist
                    if post:
                        continue

                    post_item=Post()
                    category=self.getCategory()
                    post_from='PamakeoPress'
                    body=self.getContents()

                    #insert section
                    post_item.title=title
                    post_item.thumbnail=im.image
                    post_item.post_from=post_from
                    post_item.body=body
                    post_item.post_category=category
                    post_item.status='published'
                    post_item.author=user
                    post_item.save()

                    #print(user.username)
                i=i+1
            #continue
        except Exception as e:
            #scrape item section problem
            #print("error "+str(e))
            pass

        return i

    def getArticleLink(self,inThis):
        arlink=inThis.find('a')['href'].strip()
        return arlink

    def getThumbnail(self,l):
        other=ScrapeFunction().getHTML(l)
        self.contents=other.find(class_='mh-content')
        entry_thumb=self.contents.find(class_='entry-thumbnail')
        thumbnail=entry_thumb.find_all('img')[0]['src']
        if "https:" not in thumbnail:
            thumbnail="http://pamakiopress.rw/{}".format(thumbnail)
            #img_urls="file:///home/hacker/Downloads/{}".format(img_urls)
        return thumbnail

    def getContents(self):
        contents=self.contents.find(class_='entry-content mh-clearfix')
        htmlContent=contents
        i=0
        for img in contents.find_all('img'):
            i=i+1
            img_urls = img['src']

            if "https:" not in img_urls:
                img_urls="http://pamakiopress.rw/{}".format(img_urls)

            #img_urls="file:///home/hacker/Downloads/{}".format(img_urls)
            if i==1:
                #thumb=im.image
                htmlContent=contents
            im=Images()
            opener = build_opener()
            opener.addheaders = [('User-agent', 'Mozilla/5.0')]
            install_opener(opener)
            title=self.getTitle()
            im.image_from=title
            result=urlretrieve(img_urls)
            im.image.save(os.path.basename(im.image_from+str(i)+'.png'),File(open(result[0], 'rb')))
            im.save()
            htmlContent=str(htmlContent).replace(img['src'],'/media/'+str(im.image))

        htmlContent=str(htmlContent).replace("(adsbygoogle = window.adsbygoogle || []).push(\{\});",'')
        htmlContent=str(htmlContent).replace('<!-- 720x90 adsense -->','')
        htmlContent=str(htmlContent).replace('<!--CusAds1118-->','')

        return htmlContent

    def getCategory(self):
        category=self.contents.find(class_='entry-meta-categories')
        category=category.text.strip()
        #print(category)
        return category.capitalize()

    def getTitle(self):
        title=self.contents.find(class_='entry-title')
        title=title.text.strip()
        #print(title)
        return title

#v=PamakeoPress()
#v.getThumbnail()
#v.getContents()
#v.getCategory()
#v.getTitle()
#v.news_items()

'''
for article in articles:
    articlelink=self.getArticleLink(article.find('h3',class_='entry-title mh-loop-title'))
    get_thumbnail=self.getThumbnail(l=articlelink)
    title=self.getTitle()
    body=self.getContents()
    category=self.getCategory()
    result.append({
        'title':title,
        'body':body,
        'category':category,
        'thumbnail':get_thumbnail,
        'post_from':'PamakeoPress',
    })
    #print(get_thumbnail)
return result
#return get_html.getHTML(link)
result.append({
    'thumbnail':thumbnail,
    'title':title,
    'category':self.getCategory(),
    'post_from':'PamakeoPress',
    'body':self.getContents(),
})
'''


s=input()
s=' '+s
n=int(input())
for k in range(n):
	query=list(map(int,input().split()))
	i=query[0]
	j=query[1]
	count=0
	for t in range(i+1,j+1):
		if s[t]==s[t-1]:
			count+=1
	print(count)


import asyncio
import atexit
import logging
import os
import signal
import subprocess
import time

import supriya.exceptions

logger = logging.getLogger("supriya.server")

class ProcessProtocol:
    def __init__(self):
        self.is_running = False
        atexit.register(self.quit)

    def boot(self, options, scsynth_path, port):
        ...

    def quit(self):
        ...

class SyncProcessProtocol(ProcessProtocol):

    ### PUBLIC METHODS ###

    def boot(self, options, scsynth_path, port):
        if self.is_running:
            return
        options_string = options.as_options_string(port)
        command = "{} {}".format(scsynth_path, options_string)
        logger.info("Boot: {}".format(command))
        self.process = subprocess.Popen(
            command,
            shell=True,
            stderr=subprocess.STDOUT,
            stdout=subprocess.PIPE,
            start_new_session=True,
        )
        try:
            start_time = time.time()
            timeout = 10
            while True:
                line = self.process.stdout.readline().decode().rstrip()
                if line:
                    logger.info("Boot: {}".format(line))
                if line.startswith("SuperCollider 3 server ready"):
                    break
                elif line.startswith("ERROR:"):
                    raise supriya.exceptions.ServerCannotBoot(line)
                elif line.startswith(
                    "Exception in World_OpenUDP: bind: Address already in use"
                ):
                    raise supriya.exceptions.ServerCannotBoot(line)
                elif (time.time() - start_time) > timeout:
                    raise supriya.exceptions.ServerCannotBoot(line)
            self.is_running = True
        except supriya.exceptions.ServerCannotBoot:
            try:
                process_group = os.getpgid(self.process.pid)
                os.killpg(process_group, signal.SIGINT)
                self.process.terminate()
                self.process.wait()
            except ProcessLookupError:
                pass
            raise

    def quit(self):
        if not self.is_running:
            return
        process_group = os.getpgid(self.process.pid)
        os.killpg(process_group, signal.SIGINT)
        self.process.terminate()
        self.process.wait()
        self.is_running = False

class AsyncProcessProtocol(asyncio.SubprocessProtocol, ProcessProtocol):

    ### INITIALIZER ###

    def __init__(self):
        ProcessProtocol.__init__(self)
        asyncio.SubprocessProtocol.__init__(self)
        self.boot_future = None
        self.exit_future = None

    ### PUBLIC METHODS ###

    async def boot(self, options, scsynth_path, port):
        if self.is_running:
            return
        self.is_running = False
        options_string = options.as_options_string(port)
        command = "{} {}".format(scsynth_path, options_string)
        logger.info(command)
        loop = asyncio.get_running_loop()
        self.boot_future = loop.create_future()
        self.exit_future = loop.create_future()
        _, _ = await loop.subprocess_exec(
            lambda: self, *command.split(), stdin=None, stderr=None
        )

    def connection_made(self, transport):
        self.is_running = True
        self.transport = transport

    def pipe_data_received(self, fd, data):
        for line in data.splitlines():
            logger.info(line.decode())
            if line.strip().startswith(b"Exception"):
                self.boot_future.set_result(False)
            elif line.strip().startswith(b"SuperCollider 3 server ready"):
                self.boot_future.set_result(True)

    def process_exited(self):
        self.is_running = False
        self.exit_future.set_result(None)
        if not self.boot_future.done():
            self.boot_future.set_result(False)

    def quit(self):
        if not self.is_running:
            return
        if not self.boot_future.done():
            self.boot_future.set_result(False)
        if not self.exit_future.done():
            self.exit_future.set_result
        if not self.transport._loop.is_closed() and not self.transport.is_closing():
            self.transport.close()
        self.is_running = False


import findspark
findspark.init()
from operator import add
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql.types import IntegerType
from pyspark.sql import *

if __name__ == "__main__":
    spark = SparkSession \
        .builder \
        .appName("q4") \
        .getOrCreate()
    sc = SparkContext.getOrCreate()

    business = spark.read.format("csv").option("delimiter", ":").load("C:/Users/psait/Desktop/bda/business.csv").toDF("business_id", "tempCol1", "full_address", "tempCol3", "categories").drop("tempCol1", "tempCol3")
    review = spark.read.format("csv").option("delimiter", ":").load("C:/Users/psait/Desktop/bda/review.csv").toDF("review_id", "tempCol1", "user_id", "tempCol3", "business_id", "tempCol5", "stars").drop("tempCol1", "tempCol3", "tempCol5", "review_id")

    review = review.withColumn("stars", review["stars"].cast(IntegerType()))
    jf = business.join(review, "business_id").select("business_id", "full_address", "categories", "stars").groupBy("business_id",
                                                                                "full_address",
                                                                                "categories").avg(
        "stars");
    opframe = jf.toDF("business_id", "full_address", "categories", "avg_rating").sort("avg_rating",ascending = False).take(10)
    op = sc.parallelize(list(opframe)).toDF()
    final = op.rdd.map(lambda x :str(x[0]) + "\t" + str(x[1]) + "\t" + str(x[2]) + "\t" + str(x[3]))
    final.repartition(1).saveAsTextFile("C:/Users/psait/Desktop/bda/q4.txt")


num = int(input("임의의 자연수를 입력하시오. "))

is_prime = True

if num > 0 :
    for i in range(2,num) :
        if num % i == 0 :
             is_prime = False
else :
    print("자연수가 아닙니다.")

if is_prime :
    print("소수입니다.")
else :
    print("소수가 아닙니다.")

num = int(input("어디까지 소수를 출력할까요? "))

for i in range(4,num+1) :
    is_prime = True
    for j in range(2,i):
        if i % j == 0 :
            is_prime = False
    if is_prime :
        print(i)


#!/usr/bin/env python
# coding: utf-8

"""
https://leetcode.com/submissions/detail/86181181/
"""

def longest_common_prefix(strs):
    """
    :type strs: List[str]
    :rtype: str
    """
    if len(strs) == 0:
        return ''

    if len(strs) == 1:
        return strs[0]

    p = strs[0][:]

    for i in xrange(1, len(strs)):
        s = strs[i]
        t = ''

        for j in xrange(min(len(p), len(s))):
            if p[j] == s[j]:
                t += p[j]
            else:
                break

        if t == '':
            return ''
        else:
            p = t

    return p


import json
import os
import re
import sys

class Request(object):
    def __init__(self, getenv=os.getenv):
        self.getenv_ = getenv
        self.populate_options_()
        self.populate_args_()
        if sys.stdin.isatty() == False:
            self.input = json.load(sys.stdin)
        else:
            self.input = {}
        self.service_key = self.getenv_("COG_SERVICE_TOKEN")
        self.step = self.getenv_("COG_INVOCATION_STEP", None)

    def populate_options_(self):
        names = self.getenv_("COG_OPTS")
        if names is None:
            self.options = None
            return
        names = re.sub(r'(^"|"$)', r'', names)
        names = names.split(",")
        self.options = {}
        for name in names:
            name = name.upper()
            # Options that have a list value will have a
            # COG_OPT_<NAME>_COUNT environment variable set,
            # indicating how many values there are. Scalar values will
            # have no such environment variable
            count = self.getenv_("COG_OPT_%s_COUNT" % name)
            if count is None:
                self.options[name] = self.getenv_("COG_OPT_%s" % name)
            else:
                count = int(count)
                values = []
                for i in range(count):
                    values.append(self.getenv_("COG_OPT_%s_%d" % (name, i)))
                self.options[name] = values

    def populate_args_(self):
        arg_count = int(self.getenv_("COG_ARGC", "0"))
        if arg_count == 0:
            self.args = None
            return
        self.args = []
        for i in range(arg_count):
            self.args.append(self.getenv_("COG_ARGV_%d" % i))

    def get_optional_option(self, name):
        if name in self.options.keys():
            return self.options[name]
        return None


import logging
import traceback

import psycopg2
from django.db import IntegrityError

from apps.fyle_expense.models import Expense, ExpenseGroup
from apps.task_log.exceptions import MissingMappingsError
from apps.task_log.models import TaskLog
from apps.xero_workspace.models import EmployeeMapping, CategoryMapping, ProjectMapping, Invoice, InvoiceLineItem, \
    FyleCredential, XeroCredential
from apps.xero_workspace.utils import connect_to_fyle, connect_to_xero
from fyle_jobs import FyleJobsSDK
from fyle_xero_integration_web_app import settings

LOGGER = logging.getLogger(__name__)

def schedule_expense_group_creation(workspace_id, user):
    """
    Schedule Expense Group creation
    :param workspace_id:
    :param user:
    :return:
    """

    task_log = TaskLog.objects.create(
        workspace_id=workspace_id,
        type="FETCHING EXPENSES",
        status="IN_PROGRESS"
    )

    try:
        fyle_sdk_connection = connect_to_fyle(workspace_id)
        jobs = FyleJobsSDK(settings.FYLE_JOBS_URL, fyle_sdk_connection)
        created_job = jobs.trigger_now(
            callback_url='{0}{1}'.format(
                settings.API_BASE_URL,
                '/workspace_jobs/{0}/expense_group/trigger/'.format(
                    workspace_id
                )
            ),
            callback_method='POST',
            object_id=task_log.id,
            payload={
                'task_log_id': task_log.id
            },
            job_description=f'Fetch expenses: Workspace id - {workspace_id}, user - {user}'
        )
        task_log.task_id = created_job['id']
        task_log.save()
    except FyleCredential.DoesNotExist:
        LOGGER.error('Error: Fyle Credentials not found for this workspace.')
        task_log.detail = {
            'error': 'Please connect your Source (Fyle) Account'
        }
        task_log.status = 'FYLE CONNECTION ERROR'
        task_log.save()

def schedule_invoice_creation(workspace_id, expense_group_ids, user):
    """
    Schedule Invoice creation
    :param workspace_id:
    :param expense_group_ids:
    :param user:
    :return:
    """
    expense_groups = ExpenseGroup.objects.filter(
        workspace_id=workspace_id, id__in=expense_group_ids).all()
    fyle_sdk_connection = connect_to_fyle(workspace_id)
    jobs = FyleJobsSDK(settings.FYLE_JOBS_URL, fyle_sdk_connection)

    for expense_group in expense_groups:
        task_log = TaskLog.objects.create(
            workspace_id=expense_group.workspace.id,
            expense_group=expense_group,
            type='CREATING INVOICE',
            status='IN_PROGRESS'
        )

        created_job = jobs.trigger_now(
            callback_url='{0}{1}'.format(
                settings.API_BASE_URL,
                '/workspace_jobs/{0}/expense_group/{1}/invoice/trigger/'.format(
                    workspace_id,
                    expense_group.id
                )
            ),
            callback_method='POST',
            object_id=task_log.id,
            payload={
                'task_log_id': task_log.id
            },
            job_description=f'Create invoice: Workspace id - {workspace_id}, \
            user - {user}, expense group id - {expense_group.id}'
        )
        task_log.task_id = created_job['id']
        task_log.save()

def fetch_expenses_and_create_groups(workspace_id, task_log, user):
    """
    Fetch expenses and create expense groups
    :param workspace_id
    :param task_log
    :param user
    """
    expense_group_ids = []
    try:
        updated_at = None
        task_logs = TaskLog.objects.filter(workspace__id=workspace_id, type='FETCHING EXPENSES',
                                           status='COMPLETE')
        if task_logs:
            updated_at = task_logs.latest().created_at
        expenses = Expense.fetch_paid_expenses(workspace_id, updated_at)
        expense_objects = Expense.create_expense_objects(expenses)
        connection = connect_to_fyle(workspace_id)
        expense_groups = ExpenseGroup.group_expense_by_report_id(expense_objects, workspace_id, connection)
        expense_group_objects = ExpenseGroup.create_expense_groups(expense_groups)
        for expense_group in expense_group_objects:
            expense_group_ids.append(expense_group.id)
        task_log.status = 'COMPLETE'
        task_log.detail = 'Expense groups created successfully!'
        task_log.save()
        schedule_invoice_creation(workspace_id, expense_group_ids, user)

    except FyleCredential.DoesNotExist:
        LOGGER.error('Error: Fyle Credentials not found for this workspace.')
        task_log.detail = {
            'error': 'Please connect your Source (Fyle) Account'
        }
        task_log.status = 'FYLE CONNECTION ERROR'
        task_log.save()

    except Exception:
        error = traceback.format_exc()
        LOGGER.exception(f'Error: Workspace id - {workspace_id}\n{error}')
        task_log.detail = {
            'error': 'Please contact system administrator.'
        }
        task_log.status = 'FATAL'
        task_log.save()

    return expense_group_ids

def check_mappings(expense_group):
    mappings_error = ""
    employee_email = expense_group.description.get("employee_email")
    if not EmployeeMapping.objects.filter(workspace=expense_group.workspace,
                                          employee_email=employee_email).exists():
        mappings_error += f"Employee mapping missing for employee_email: {employee_email} \n"

        try:
            EmployeeMapping.objects.create(workspace=expense_group.workspace,
                                           employee_email=employee_email, invalid=True)
        except (psycopg2.errors.UniqueViolation, IntegrityError):
            pass

    for expense in expense_group.expenses.all():
        if not CategoryMapping.objects.filter(workspace=expense_group.workspace,
                                              category=expense.category).exists():
            mappings_error += f"Category mapping missing for category name: {expense.category} \n"

            try:
                CategoryMapping.objects.create(workspace=expense_group.workspace, category=expense.category,
                                               sub_category=expense.sub_category,
                                               invalid=True)
            except (psycopg2.errors.UniqueViolation, IntegrityError):
                pass

        if expense.project is not None:
            if not ProjectMapping.objects.filter(workspace=expense_group.workspace,
                                                 project_name=expense.project).exists():
                mappings_error += f"Project mapping missing for project_name: {expense.project}"

                try:
                    ProjectMapping.objects.create(workspace=expense_group.workspace,
                                                  project_name=expense.project, invalid=True)
                except (psycopg2.errors.UniqueViolation, IntegrityError):
                    pass

    if mappings_error:
        raise MissingMappingsError(message=mappings_error)

def create_invoice_and_post_to_xero(expense_group, task_log):
    """
    Creates an Xero Invoice
    :param expense_group:
    :param task_log:
    :return:
    """
    try:
        check_mappings(expense_group)
        invoice_id = Invoice.create_invoice(expense_group)
        InvoiceLineItem.create_invoice_line_item(invoice_id, expense_group)
        xero_sdk_connection = connect_to_xero(expense_group.workspace.id)
        invoice_obj = Invoice.objects.get(id=invoice_id)
        invoice_data = generate_invoice_request_data(invoice_obj)
        response = post_invoice(invoice_data, xero_sdk_connection)
        for invoice in response["Invoices"]:
            invoice_obj.invoice_id = invoice["InvoiceID"]
            invoice_obj.save()
        expense_group.status = 'Complete'
        expense_group.save()
        task_log.invoice = invoice_obj
        task_log.detail = 'Invoice created successfully!'
        task_log.status = 'COMPLETE'
        task_log.save()

    except XeroCredential.DoesNotExist:
        LOGGER.error('Error: Xero Credentials not found for this workspace.')
        expense_group.status = 'Failed'
        expense_group.save()
        task_log.detail = {
            'error': 'Please connect your Destination (Xero) Account'
        }
        task_log.status = 'XERO CONNECTION ERROR'
        task_log.save()

    except MissingMappingsError as error:
        LOGGER.error(f'Error: {error.message}')
        expense_group.status = 'Failed'
        expense_group.save()
        task_log.detail = {
            'error': error.message
        }
        task_log.status = 'MISSING MAPPINGS'
        task_log.save()

    except Exception:
        error = traceback.format_exc()
        LOGGER.exception(f'Error: Workspace id - {task_log.workspace.id}\n{error}')
        expense_group.status = 'Failed'
        expense_group.save()
        task_log.detail = {
            'error': 'Please contact system administrator.'
        }
        task_log.status = 'FATAL'
        task_log.save()

def generate_invoice_request_data(invoice):
    """
    Generate invoice request data as defined by Xero
    :param invoice
    :return: request_data
    """

    request_data = {
        "Type": "ACCPAY",
        "Contact": {
            "Name": invoice.contact_name,
        },
        "DateString": str(invoice.date),
        "InvoiceNumber": invoice.invoice_number,
        "LineAmountTypes": "Exclusive",
        "LineItems": []
    }

    for line_item in invoice.invoice_line_items.all():
        request_data["LineItems"].append({
            "Description": line_item.description,
            "Quantity": "1",
            "UnitAmount": str(line_item.amount),
            "AccountCode": line_item.account_code,
            "Tracking": [{
                "Name": line_item.tracking_category_name,
                "Option": line_item.tracking_category_option,
            }]
        })

    return request_data

def post_invoice(data, xero):
    """ Makes an API call to create invoices in Xero
    :param data: Request data for the invoice API
    :param xero: Xero connection object
    :return response: response data from Xero API
    """
    response = xero.invoices.post(data)
    return response


#!/usr/bin/env python
# _*_ coding: utf-8 _*_
import os
import shutil
import argparse

"""
for i in `find .   -maxdepth 1  | awk -F '/' '{ print $2 }' | grep -v "\ "`; do
    echo "-----------------------------------------$i---------------------------------";
    python gen_dao.py  --dir=$i ; done

可自动生成dao文件，并移动到public目录下[cdb_mtnc/public/db_access/xxx]：
   1.通过sql文件生成model及mappers，并生成dao文件 【较少用】
        python gen_dao.py  --dir=test --sql=yes
   2.根据models及mappers生成dao文件  【常用】
        python gen_dao.py  --dir=test
"""

step = 0

def red_print(msg):
    global step
    step += 1
    print("\033[0;33;40m\t" + str(step) + msg + "\033[0m")
def yellow_print(msg):
    print("\033[0;31;40m\tError: " + msg + "\033[0m")

def copy_files(src_dir, dest_dir):
     for file in os.listdir(src_dir):
         if file == "daos.h":
            continue
         src_file = os.path.join(src_dir, file)
         dest_file = os.path.join(dest_dir, file)
         if os.path.isfile(src_file):
             if not os.path.exists(dest_dir):
                 os.makedirs(dest_dir)
             if not os.path.exists(dest_file) or(os.path.exists(dest_file) and (os.path.getsize(dest_file) != os.path.getsize(src_file))):
                     open(dest_file, "wb").write(open(src_file, "rb").read())
         if os.path.isdir(src_file):
             copyFiles(src_file, dest_file)

def gen_dao():
    path = os.getcwd() + "/" + args.dir
    os.chdir(path)
    flag = False
    if not os.path.exists('cowboy'):
        red_print(".create cowboy link.")
        os.symlink("../../cowboy", "cowboy")
    if args.sql:
        red_print(".update models and mappers by sql ")
        flag = os.system("./cowboy -u -o -x -m")
    else:
        red_print(".gen dao.cpp from mappers and models ")
        flag = os.system("./cowboy -o -x -m")
    if not flag:
        red_print(".gen dao files done")
        move_dao_files()
    else:
        yellow_print("gen dao files err ")
        exit(-1)

def move_dao_files():
    cur_path = os.getcwd()
    #yellow_print(path)
    path = cur_path.split("tools")[0]
    #yellow_print(path)
    global dest_dir
    dest_dir = path + "public/db_access/" + args.dir
    red_print(".move dao files to: " + dest_dir )
    os.popen("rm -rf " + dest_dir)
    os.system("mkdir " + dest_dir)
    copy_files("dao",    dest_dir)
    copy_files("model",  dest_dir)
    copy_files("mapper", dest_dir)

def parse_options():
    global args
    info = """1.python gen_dao.py --dir=xxxx  --sql=yes
       2.python gen_dao.py --dir=xxxx  """
    parser = argparse.ArgumentParser(usage=info, description="")
    parser.add_argument("--dir",  required=True, help="\tgen dao.cpp from which dir.", dest="dir")
    parser.add_argument("-sql", "--sql", default=False, dest="sql", help="\tupdate models and mappers by sql.")
    args = parser.parse_args()
    if not os.path.exists(args.dir):
        yellow_print("dir "  + args.dir + " not exits!")
        exit()

if __name__ == '__main__':
    parse_options()
    gen_dao()
    red_print(".all done ")
    print("new files:__________________________")
    os.system("ls -l --full-time " + dest_dir)


import numpy as np
import torch

from homan.utils.nmr_renderer import OrthographicRenderer, PerspectiveRenderer
import neural_renderer as nr

def visualize_perspective(image, predictions, K=None):
    perspect_renderer = PerspectiveRenderer(image_size=max(image.shape))
    new_image = image.copy()
    # 2 * factor to be investigated !
    verts = 2 * torch.Tensor(predictions["verts"]).cuda().unsqueeze(0)
    faces = torch.Tensor(predictions["faces"]).cuda().unsqueeze(0)
    K = torch.Tensor(K).cuda().unsqueeze(0)
    trans = torch.Tensor([0, 0, 0]).cuda().unsqueeze(0)
    for i in range(len(verts)):
        v = verts[i:i + 1]
        new_image = perspect_renderer(vertices=v,
                                      faces=faces,
                                      color_name="blue",
                                      image=new_image,
                                      translation=trans,
                                      K=K)
    return (new_image * 255).astype(np.uint8)

def visualize_orthographic(image, predictions):
    ortho_renderer = OrthographicRenderer(image_size=max(image.shape))
    new_image = image.copy()
    verts = torch.Tensor(predictions["verts"]).cuda().unsqueeze(0)
    faces = torch.Tensor(predictions["faces"]).cuda().unsqueeze(0)
    cams = torch.Tensor(predictions["cams"]).cuda().unsqueeze(0)
    for i in range(len(verts)):
        v = verts[i:i + 1]
        cam = cams[i:i + 1]
        new_image = ortho_renderer(vertices=v,
                                   faces=faces,
                                   cam=cam,
                                   color_name="blue",
                                   image=new_image)
    return (new_image * 255).astype(np.uint8)

def visualize_hand_object(model,
                          images,
                          verts_hand_gt=None,
                          verts_object_gt=None,
                          dist=3,
                          viz_len=7,
                          init=False,
                          gt_only=False,
                          image_size=640,
                          max_in_batch=2):
    if gt_only:
        rends, masks = model.render_gt(
            model.renderer,
            verts_hand_gt=verts_hand_gt,
            verts_object_gt=verts_object_gt,
            viz_len=viz_len,
            max_in_batch=max_in_batch,
        )
    elif verts_hand_gt is None:
        rends, masks = model.render(model.renderer,
                                    viz_len=viz_len,
                                    max_in_batch=max_in_batch)
    else:
        rends, masks = model.render_with_gt(model.renderer,
                                            verts_hand_gt=verts_hand_gt,
                                            verts_object_gt=verts_object_gt,
                                            viz_len=viz_len,
                                            init=init,
                                            max_in_batch=max_in_batch)
    bs = rends.shape[0]
    # Rendered frontal image
    new_images = []
    for image, rend, mask in zip(images, rends, masks):
        if image.max() > 1:
            image = image / 255.0
        h, w, c = image.shape
        L = max(h, w)
        new_image = np.pad(image.copy(), ((0, L - h), (0, L - w), (0, 0)))
        new_image[mask] = rend[mask]
        new_image = (new_image[:h, :w] * 255).astype(np.uint8)
        new_images.append(new_image)

    # Rendered top-down image
    theta = 1.3
    x, y = np.cos(theta), np.sin(theta)
    obj_verts, _ = model.get_verts_object()
    mx, my, mz = obj_verts.mean(dim=(0, 1)).detach().cpu().numpy()

    K = model.renderer.K
    R2 = torch.cuda.FloatTensor([[[1, 0, 0], [0, x, -y], [0, y, x]]])
    t2 = torch.cuda.FloatTensor([mx, my + dist, mz])
    top_renderer = nr.renderer.Renderer(image_size=image_size,
                                        K=K,
                                        R=R2,
                                        t=t2,
                                        orig_size=1)
    top_renderer.background_color = [1, 1, 1]
    top_renderer.light_direction = [1, 0.5, 1]
    top_renderer.light_intensity_direction = 0.3
    top_renderer.light_intensity_ambient = 0.5
    top_renderer.background_color = [1, 1, 1]
    if verts_hand_gt is None:
        top_down, _ = model.render(model.renderer,
                                   rotate=True,
                                   viz_len=viz_len,
                                   max_in_batch=max_in_batch)
    elif gt_only:
        top_down, _ = model.render_gt(
            model.renderer,
            verts_hand_gt=verts_hand_gt,
            verts_object_gt=verts_object_gt,
            viz_len=viz_len,
            rotate=True,
            max_in_batch=max_in_batch,
        )
    else:
        top_down, _ = model.render_with_gt(model.renderer,
                                           verts_hand_gt=verts_hand_gt,
                                           verts_object_gt=verts_object_gt,
                                           rotate=True,
                                           viz_len=viz_len,
                                           init=init,
                                           max_in_batch=max_in_batch)
    top_down = (top_down * 255).astype(np.uint8)
    return np.stack(new_images), top_down


# fit a second degree polynomial to the economic data
from numpy import arange,sin,log,tan
from pandas import read_csv
from scipy.optimize import curve_fit
from matplotlib import pyplot

# define the true objective function
def objective(x):
	return 0.01006304431397636*sin(0.009997006528342673*x+0.010000006129223197)+0.3065914809778943*x+0.01033913912969194

# load the dataset
url = 'output.csv'
dataframe = read_csv(url, header=None)
data = dataframe.values
# choose the input and output variables
x, y = data[1:, 0], data[1:, -1]
# plot input vs output
pyplot.scatter(x, y)
#convert string to float
x=[float(i) for i in x]
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x),max(x),1)
# calculate the output for the range
y_line = objective(x_line)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, color='red')
pyplot.show()


from geometry_msgs.msg import Twist
import pyzbar.pyzbar as pyzbar
from datetime import datetime
import pyrealsense2 as rs
import numpy as np
import schedule
import rospy
import time
import cv2

frame_crop_x1 = 0
frame_crop_y1 = 120
frame_crop_x2 = 639
frame_crop_y2 = 479

minLineLength = 30
maxLineGap = 15

speed = 0
angle = 0
avr_x = 0
turn = -0.5

code_start = "start"
barcode_data_line_QR = []
text_0 = ""
text_1 = ""

## 동일한 qr코드 인식시 스피드 0 or 움직임
view_same_QR = 0
view_start_QR_and_no_product = 0

obstacle_view = 0

cap_0 = cv2.VideoCapture(2)
cap_1 = cv2.VideoCapture(4)

cap_1.set(cv2.CAP_PROP_FRAME_HEIGHT,180)
cap_1.set(cv2.CAP_PROP_FRAME_WIDTH,320)

def cam_0_read():
    global retval_0, frame_0, original, gray_line_0, gray_line_1
    retval_0, frame_0 = cap_0.read()
    original = frame_0
    gray_line_0 = cv2.cvtColor(frame_0, cv2.COLOR_BGR2GRAY)
    gray_line_1 = cv2.cvtColor(frame_0, cv2.COLOR_BGR2GRAY)

def cam_1_read():
    global retval_1, frame_1, gray_product_0
    retval_1, frame_1 = cap_1.read()
    gray_product_0 = cv2.cvtColor(frame_1, cv2.COLOR_BGR2GRAY)

def cam_0_use_line():
    global retval_0, frame_0, original, theta
    blurred = gray_line_0[frame_crop_y1:frame_crop_y2,frame_crop_x1:frame_crop_x2]
    blurred = cv2.boxFilter(blurred, ddepth=-1, ksize=(31,31))
    retval2 ,blurred = cv2.threshold(blurred, 100, 255, cv2.THRESH_BINARY)
    edged = cv2.Canny(blurred, 85, 85)
    lines = cv2.HoughLinesP(edged,1,np.pi/180,10,minLineLength,maxLineGap)
    max_diff = 1000
    final_x = 0
    if ( lines is not None ):
        if ( lines is not None ):
            add_line = 0
            for line in lines:
                x1, y1, x2, y2 = line[0]
                cv2.line(original,(x1+frame_crop_x1,y1+frame_crop_y1),(x2+frame_crop_x1,y2+frame_crop_y1),(0,255,0),3)
                mid_point = ( x1 + x2 ) / 2
                diff = abs((640/2) - mid_point)
                if ( max_diff > diff ) :
                    max_diff = diff
                    final_x = mid_point
                add_line = add_line + final_x
            average_x = add_line / len(lines)
        if ( int(average_x) != 0 ) :
            original = cv2.circle(original,(int(average_x),int((frame_crop_y1+frame_crop_y2)/2)),5,(0,0,255),-1)
            original = cv2.rectangle(original,(int(frame_crop_x1),int(frame_crop_y1)),(int(frame_crop_x2),int(frame_crop_y2)),(0,0,255),1)
        frame_0 = original
        theta = int(( int(average_x) - 320.0 ) / 640.0 * 100)
    if ( lines is None ):
        theta = -50

def cam_0_use_qrcode():
    global barcode_data_line_QR, barcode_type_line_QR
    decoded_line_QR = pyzbar.decode(gray_line_1)
    for _ in decoded_line_QR:
        x, y, w, h = _.rect
        barcode_data_line_QR = _.data.decode("utf-8")
        barcode_type_line_QR = _.type
        cv2.rectangle(frame_0, (x, y), (x + w, y + h), (0, 0, 255), 2)
        text_0 = '%s (%s)' % (barcode_data_line_QR, barcode_type_line_QR)
        cv2.putText(frame_0, text_0, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2, cv2.LINE_AA)
    if decoded_line_QR == [] :
        barcode_data_line_QR = "QR_X"

def cam_1_use_qrcode():
    global barcode_data_product_QR, barcode_type_product_QR
    decoded_product_QR = pyzbar.decode(gray_product_0)
    for _ in decoded_product_QR:
        a, b, c, d = _.rect
        barcode_data_product_QR = _.data.decode("utf-8")
        barcode_type_product_QR = _.type
        cv2.rectangle(frame_1, (a, b), (a + c, b + d), (0, 0, 255), 2)
        text_1 = '%s (%s)' % (barcode_data_product_QR, barcode_type_product_QR)
        cv2.putText(frame_1, text_1, (a, b), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2, cv2.LINE_AA)
    if decoded_product_QR == [] :
        barcode_data_product_QR = "QR_X"

def cam_lidar_read():
    global pipeline
    pipeline = rs.pipeline()
    config = rs.config()
    config.enable_stream(rs.stream.depth, 320, 240, rs.format.z16, )
    pipeline.start(config)

def cam_lidar_use():
    global add_num, add_edge_num, add_edge_remain_num, image_all, left_view
    frames = pipeline.wait_for_frames()
    depth = frames.get_depth_frame()
    coverage = [0]*32
    image_all = []
    add_num = 0
    add_edge_num = 0
    add_edge_remain_num = 0
    for y in range(240):
        for x in range(320):
            dist = depth.get_distance(x, y)
            if 0 < dist and dist < 1:
                coverage[x//10] += 1
        if y%20 is 19:
            line = ""
            for c in coverage:
                line += " 12345678"[c//25]
            coverage = [0]*32
            image_all.append(line)
            for a in range(1,32):
                if line[a] == " " : add_num = add_num
                else : add_num = add_num + int(line[a])
            for a in range(1,2):
                if line[a] == " " : add_edge_num = add_edge_num
                else : add_edge_num = add_edge_num + int(line[a])
            for a in range(3,32):
                if line[a] == " " : add_edge_remain_num = add_edge_remain_num
                else : add_edge_remain_num = add_edge_remain_num + int(line[a])

def speed_and_angle_make():
    global angle, speed
    angle = round((-theta) * (0.012), 2)
    speed = 0.3 - abs(angle * 0.2)

def speed_and_angle_turn():
    global angle, speed
    speed = 0
    angle = turn

def speed_and_angle_main():
    global angle, speed, barcode_data_product_QR, barcode_data_line_QR, turn, obstacle_view, view_same_QR, view_start_QR_and_no_product

    if barcode_data_line_QR == "right_turn"  : turn = -0.5
    if barcode_data_line_QR == "left_turn" : turn = 0.5

    if view_same_QR == 0 and view_start_QR_and_no_product == 0 :
        if obstacle_view == 0 :
            if theta != -50:
                if add_num <= 10                                                                                : speed_and_angle_make()
                if add_num <= 10 and barcode_data_product_QR != "QR_X" and barcode_data_product_QR == barcode_data_line_QR : view_same_QR = 1
                if add_num <= 10 and barcode_data_product_QR == "QR_X" and barcode_data_line_QR    == "start"              : view_start_QR_and_no_product = 1
                if add_num >  10 :
                    speed = 0
                    obstacle_view = 1
            if theta == -50 : speed_and_angle_turn()

        if obstacle_view == 1 :
            if add_num != 0 :
                if add_edge_num        > 0 and add_edge_remain_num == 0 : angle = -0.4
                if add_edge_remain_num > 0 and add_edge_num == 0 : angle = -0.4
                if add_edge_remain_num > 0 and add_edge_num > 0 : angle = -0.4
                speed = 0.2
            if add_num == 0                  : angle = 0.4
            if theta != -50 and add_num == 0 : obstacle_view = 0

    if view_same_QR == 1 or view_start_QR_and_no_product == 1:
        speed = 0
        angle = 0
        if view_same_QR == 1                 and barcode_data_product_QR == "QR_X" : view_same_QR = 0
        if view_start_QR_and_no_product == 1 and barcode_data_product_QR != "QR_X" : view_start_QR_and_no_product = 0

def talker():
    global speed, angle
    rospy.init_node("line_qr_sensor")
    pub = rospy.Publisher("/cmd_vel", Twist, queue_size=10)
    msg = Twist()

    cam_lidar_read()

    while not rospy.is_shutdown():

        msg.linear.x = speed
        msg.angular.z = angle
        pub.publish(msg)

        cam_0_read()
        cam_0_use_line()
        cam_0_use_qrcode()

        cam_1_read()
        cam_1_use_qrcode()

        cam_lidar_use()

        speed_and_angle_main()

        for y in range(12):
            print(image_all[y])
        print(add_num)
        print("장애물 : ", obstacle_view)
        print("세타값 : ", theta)
        print("턴값 : ", turn)
        cv2.imshow('frame_0', frame_0)
        cv2.imshow('frame_1', frame_1)

        key = cv2.waitKey(25)
        if key == 27: #ESC
            break

if __name__ == "__main__":
    try:
        talker()
    except rospy.ROSInterruptException:
        pass


# -*- coding: utf-8 -*-
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from employee.models import Employee
from employee.serializers import employee_serializer

# Create your views here.
@csrf_exempt
def employee_list(request):
    """
    Get all employee from db and return in json format
    Post (save) a new employee in the database
    """
    if request.method == 'GET':
        #Get all object form database
        employee = Employee.objects.all()
        #Serializer all
        serializer = employee_serializer(employee, many=True)
        #return to the request
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        #retrive the post content
        data = JSONParser().parse(request)
        # Serializer it
        serializer = employee_serializer(data=data)
        if serializer.is_valid():
            # if is correct, save in the database
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        #otherside return an error (400)
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt
def employee_detail(request, pk):
    """
    Get details, update or delete a specific (pk) employee
    """
    try:
        #Find employee by the id
        employee = Employee.objects.get(pk=pk)
    except Employee.DoesNotExist:
        #if not exist!!
        return HttpResponse(status=404)

    #if the request is get
    if request.method == 'GET':
        #return the employee in Json
        serializer = employee_serializer(employee)
        return JsonResponse(serializer.data)

    #if request is put
    elif request.method == 'PUT':
        #parse the body request content
        data = JSONParser().parse(request)
        #Serializer the employee
        serializer = employee_serializer(employee, data=data)
        if serializer.is_valid():
            #save if is valid
            serializer.save()
            return JsonResponse(serializer.data)
        #otherside return 400 - bad Request
        return JsonResponse(serializer.errors, status=400)

    #if request is delete
    elif request.method == 'DELETE':
        #end of live of the employee
        employee.delete()
        #return No content
        return HttpResponse(status=204)


from fastapi import FastAPI, APIRouter, HTTPException, status
from pydantic import BaseModel,json
from api.settings import  base_url
import pandas as pd
import requests
import json
from typing import List, Optional
from routers.users import user_login
import datetime

vehicle_router = APIRouter(tags=["Vehicle"])

@vehicle_router.get("/labels/{labelId}")
def get_color(labelId):
    url = f'{base_url}/dev/index.php/v1/labels/{labelId}'
    access_token = user_login()
    headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"}
    response = requests.request("GET",url, headers=headers)
    return response.json()

@vehicle_router.get("/filter/hu")
def filter():
    with open("response.json","r",encoding="utf-8") as file:
        data = json.load(file)
        filtered_data = [x for x in data if x["hu"] != None]

    with open("filter_hu.json", "w") as write_file:
        json.dump(filtered_data, write_file, indent=4)
    return filtered_data

@vehicle_router.get("/hu")
def check_hu(datas):
    strToday = datetime.datetime.today().strftime('%Y-%m-%d')
    dateToday = datetime.datetime.strptime(strToday, '%Y-%m-%d')
    for data in datas:
        if data["hu"] and data["colored"]:
            hu = datetime.datetime.strptime(data["hu"], "%Y-%m-%d")
            result = (dateToday.year - hu.year) * 12 + (dateToday.month - hu.month)
            if result < 3:
                data["colorCode"] = "#007500"
            elif result < 12:
                data["colorCode"] = "#FFA500"
            else:
                 data["colorCode"] = "#b30000"

    return datas

@vehicle_router.post("/upload")
def upload(kys:List[str],url, colored:Optional[bool] = True):

    csvDataFrame = pd.read_csv(url,  encoding='utf8',sep=';',header=None,names=kys)

    df = pd.DataFrame(csvDataFrame)
    df["colored"] = colored
    datas = df.to_json(orient="table",indent=4)

    check_hu(datas)

    current_date = datetime.datetime.now().isoformat('-',"hours")

    with pd.ExcelWriter(f"vehicles_{current_date}.xlsx") as writer:
        datas.to_excel(writer)

    dataframe = pd.read_excel(f"vehicles_{current_date}.xlsx")

    dataframe.to_json('vehicle.json', index=False, orient="table", indent=4)

    new_data = datas["data"]
    return new_data

@vehicle_router.post("/vehicle")
def post_data():
    url = f"{base_url}/dev/index.php/v1/vehicles/select/active"
    access_token = user_login()
    headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"}

    response = requests.request("GET",url,headers= headers)

    data = json.load(open('vehicle.json'))
    new_data = data["data"]

    with open("sorted_vehicle.json", "w", encoding="utf-8") as file1:
        json.dump(sorted(new_data, key=lambda x: (x["gruppe"] is None, x["gruppe"])), file1 ,indent=4)

    with open("response.json", "w",encoding="utf-8") as file:
        json.dump(response.json(), file, indent=4)

    return response.json()

@vehicle_router.get("/search")
def search_field(key):
    search_data = []
    with open("reesponse.json","r",encoding="utf-8") as file:
        data = json.load(file)
        s_data = {}
        for src in data:
            if src[key]:

                s_data[key] = src[key]
                s_data["kurzname"] = src["kurzname"]
                s_data["info"] = src["info"]
                search_data.append(s_data)

            else:
                return HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="Data does not exist.")

    return search_data
@vehicle_router.post("/merge")
def merge_data(url1, url2)->dict:
    csvData1 = pd.read_csv(url1,  encoding='utf8',sep=';',error_bad_lines=False)
    csvData2 = pd.read_csv(url2,  encoding='utf8',sep=';',error_bad_lines=False)

    df1 = pd.DataFrame(csvData1)
    df2 = pd.DataFrame(csvData2)
    merge_data = pd.concat([df1,df2]).drop_duplicates().reset_index(drop=True)

    merge_data.to_json("merged_data.json", indent=4)
    return merge_data


class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        length1 = len(nums1) - 1

        i = m - 1
        j = n - 1

        if n == 0:
            return nums2

        while j >= 0 and i >= 0:
            if nums1[i] > nums2[j]:
                nums1[length1] = nums1[i]
                i -= 1
                length1 -= 1

            else:
                nums1[length1] = nums2[j]
                j -= 1
                length1 -= 1

        #only a few tip..
        if i < 0:
            nums1[0:length1+1] = nums2[:j+1]

        return nums1

if __name__ == '__main__':
    nums1 = [1, 2, 3, 0, 0, 0]
    m = 3
    nums2 = [2, 5, 6]
    n = 3

    nums1 = [2,0]
    m = 1
    nums2 = [1]
    n = 1

    nums1 = [0]
    m = 1
    nums2 = [1]
    n = 1

    print( Solution().merge(nums1, m, nums2, n) )


# mypy: ignore-errors

import streamlit as st
from bokeh.models import CustomJS
from bokeh.models.widgets import Button
from streamlit_bokeh_events import streamlit_bokeh_events

REC_GIF = "ai_talks/assets/icons/rec_on.gif"

def get_js_code(lang: str) -> str:
    return """
        var value = "";
        var rand = 0;
        var recognition = new webkitSpeechRecognition();
        recognition.continuous = false;
        recognition.interimResults = true;
    """ + f"recognition.lang = '{lang}';" + """
        document.dispatchEvent(new CustomEvent("GET_ONREC", {detail: 'start'}));

        recognition.onspeechstart = function () {
            document.dispatchEvent(new CustomEvent("GET_ONREC", {detail: 'running'}));
        }
        recognition.onsoundend = function () {
            document.dispatchEvent(new CustomEvent("GET_ONREC", {detail: 'stop'}));
        }
        recognition.onresult = function (e) {
            var value2 = "";
            for (var i = e.resultIndex; i < e.results.length; ++i) {
                if (e.results[i].isFinal) {
                    value += e.results[i][0].transcript;
                    rand = Math.random();

                } else {
                    value2 += e.results[i][0].transcript;
                }
            }
            document.dispatchEvent(new CustomEvent("GET_TEXT", {detail: {t:value, s:rand}}));
            document.dispatchEvent(new CustomEvent("GET_INTRM", {detail: value2}));

        }
        recognition.onerror = function(e) {
            document.dispatchEvent(new CustomEvent("GET_ONREC", {detail: 'stop'}));
        }
        recognition.start();
    """

def show_speak_btn() -> Button:
    stt_button = Button(label=st.session_state.locale.speak_btn, button_type="success", width=100)
    stt_button.js_on_event("button_click", CustomJS(code=get_js_code(st.session_state.locale.lang_code)))
    return stt_button

def get_bokeh_result() -> dict:
    stt_button = show_speak_btn()
    return streamlit_bokeh_events(
        bokeh_plot=stt_button,
        events="GET_TEXT,GET_ONREC,GET_INTRM",
        key="listen",
        refresh_on_update=False,
        override_height=75,
        debounce_time=0,
    )

def show_voice_input() -> None:
    if "input" not in st.session_state:
        st.session_state.input = {"text": "", "session": 0}
    result = get_bokeh_result()
    tr = st.empty()
    tr.code(st.session_state.input["text"])
    if result:
        if "GET_TEXT" in result and (
                result.get("GET_TEXT")["t"] != "" and result.get("GET_TEXT")["s"] != st.session_state.input["session"]):
            st.session_state.input["text"] = result.get("GET_TEXT")["t"]  # type: ignore
            tr.code(st.session_state.input["text"])
            st.session_state.input["session"] = result.get("GET_TEXT")["s"]
        if "GET_INTRM" in result and result.get("GET_INTRM") != "":
            tr.code(st.session_state.input["text"] + " " + result.get("GET_INTRM"))
        if "GET_ONREC" in result:
            if result.get("GET_ONREC") == "start":
                st.image(REC_GIF)
                st.session_state.input["text"] = ""
            elif result.get("GET_ONREC") == "running":
                st.image(REC_GIF)
            elif result.get("GET_ONREC") == "stop" and st.session_state.input["text"] != "":
                st.session_state.user_text = st.session_state.input["text"]
                st.session_state.input["text"] = ""


from database import *

class invitados(object):

    idInvitado = None
    nombre_invitado = None
    apellido_invitado = None
    descripcion = None
    url_imagen = None

    @staticmethod
    def cargar(id):
        info = Database().run("Select * FROM invitados WHERE idInvitado = '%s'" %(id))

        invitado = invitados()

        for item in info:
            invitado.idInvitado = item["idInvitado"]
            invitado.nombre_invitado = item["nombre_invitado"]
            invitado.apellido_invitado = item["apellido_invitado"]
            invitado.descripcion = item["descripcion"]
            invitado.url_imagen = item["url_imagen"]

        return invitado

    def alta(self):

        Database().run("INSERT INTO invitados Values (NULL, %s, '%s', '%s', '%s')" % (self.nombre_invitado,
                                                                                self.apellido_invitado,
                                                                                self.descripcion,
                                                                                self.url_imagen))

    def baja(self):

        Database().run("DELETE FROM eventos WHERE idInivitado = '%s'" %(self.idInvitado))

        Database().run("DELETE FROM invitados WHERE idInivitado = '%s'" %(self.idInvitado))

    def modificacion(self):

        Database().run("UPDATE invitados SET nombre_invitado = '%s', apellido_invitado = '%s', descripcion = '%s',"
                       "url_imagen = '%s'" %(self.nombre_invitado, self.apellido_invitado, self.descripcion,
                                             self.url_imagen))


from __future__ import annotations

import asyncio
import concurrent.futures
import dataclasses
import functools
import logging
import os
import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid

import jinja2

from .. import scraper

logger = logging.getLogger(__name__)

@dataclasses.dataclass
class MailConfig(object):
    from_addr: str
    host: str
    port: str
    tls: bool
    user: str = None
    passwd: str = None

def _do_send_email(cfg: MailConfig, to_addr: str, subject: str, text: str):
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = cfg.from_addr
    msg['To'] = to_addr
    msg['Date'] = formatdate(localtime=True)
    msg['Message-ID'] = make_msgid('punkow')

    txt = MIMEText(text)
    msg.attach(txt)

    smtp = smtplib.SMTP(host=cfg.host, port=cfg.port)

    if cfg.tls:
        smtp.starttls()

    if cfg.user is not None:
        smtp.login(cfg.user, cfg.passwd)

    try:
        smtp.sendmail(cfg.from_addr, [to_addr], msg.as_string())
    finally:
        smtp.quit()

    logger.info("Sent an email")

class Mailer(object):
    def __init__(self, loop: asyncio.AbstractEventLoop, config: MailConfig, base_url: str):
        self._loop = loop

        self._config = config
        self._base_url = base_url

        self._tpl = jinja2.Environment(
            loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),
                                                        'email_templates')),
            autoescape=jinja2.select_autoescape(['html', 'xml'])
        )
        self._executor = concurrent.futures.ProcessPoolExecutor(max_workers=2)

    async def _send_email(self, to_addr, subject, text):
        await self._loop.run_in_executor(self._executor, _do_send_email, self._config, to_addr, subject, text)

    async def send_success_email(self, email, booking: scraper.BookingResult):
        tpl = self._tpl.get_template("success.txt")

        text = tpl.render(meta=booking.metadata, change_url=scraper.BASE_URL + scraper.MANAGE_URL,
                          process_id=booking.process_id, auth_code=booking.auth_key)

        await self._send_email(email, "Your appointment was booked", text)

    async def send_confirmation_email(self, email, req_key):
        tpl = self._tpl.get_template("confirmation.txt")

        text = tpl.render(base_url=self._base_url, req_key=req_key)
        await self._send_email(email, "Your booking request was registered", text)

    async def send_cancel_email(self, email, req_key):
        tpl = self._tpl.get_template("cancel.txt")

        text = tpl.render(base_url=self._base_url, req_key=req_key)
        await self._send_email(email, "Your booking request was canceled", text)

    def start_queue(self) -> AsyncMailQueue:
        return AsyncMailQueue(self._loop, self)

class AsyncMailQueue(object):
    def __init__(self, loop: asyncio.AbstractEventLoop, mailer: Mailer):
        self._loop = loop
        self._mailer = mailer
        self._queue = []

    async def __aenter__(self) -> AsyncMailQueue:
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if len(self._queue) != 0:
            try:
                await self._loop.run_in_executor(None, functools.partial(
                    concurrent.futures.wait, self._queue))
            except:
                logger.exception("Exception in waiting for mail sending")

    def _append_task(self, coro):
        self._queue.append(asyncio.run_coroutine_threadsafe(coro, self._loop))

    def send_success_email(self, email, booking: scraper.BookingResult):
        self._append_task(self._mailer.send_success_email(email, booking))

    def send_confirmation_email(self, email, req_key):
        self._append_task(self._mailer.send_confirmation_email(email, req_key))

    async def send_cancel_email(self, email, req_key):
        self._append_task(self._mailer.send_cancel_email(email, req_key))


'''
Link: https://www.lintcode.com/problem/722
'''

# Slightly modified from the solution from jiuzhang.com. Uses trie. Has O(n) time complexity, where n is the length of the array.
# It makes use of trie data structure, which makes string retrieval and comparison efficient. Otherwise it would be O(n^2).
class TrieNode:
    def __init__(self):
        self.sons = [None, None]

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, number):
        node = self.root
        for i in range(30, -1, -1):
            digit = number >> i & 1
            if not node.sons[digit]:
                node.sons[digit] = TrieNode()
            node = node.sons[digit]

    # Each time we call get_largest_xor(), it will always reach a prefix value previously stored into the trie, which is maximally different from
    # number, meaning that the found prefix value XOR number is the largest possible across all the prefix values stored in the trie. The returned
    # Result is that value. And the subarray yielding this maximum XOR value starts right after the found prefix value.
    def get_largest_xor(self, number):
        node = self.root
        result = 0
        for i in range(30, -1, -1):
            digit = number >> i & 1
            target = 1 - digit
            if node.sons[target]:
                result += 1 << i
                node = node.sons[target]
            else:
                node = node.sons[digit]
        return result

class Solution:
    """
    @param nums: the array
    @return: the max xor sum of the subarray in a given array
    """
    def maxXorSubarray(self, nums):
        trie = Trie()
        trie.insert(0)
        prefix_xor = 0
        max_xor = float('-inf')
        for num in nums:
            prefix_xor ^= num
            trie.insert(prefix_xor)
            max_xor = max(max_xor, trie.get_largest_xor(prefix_xor))
        return max_xor


from mysql.connector.errors import DatabaseError, ProgrammingError

from addData.add_data import add_user_data
from create_connection import get_cursor
from viewStatsClient.ask_batter_stats import ask_batter
from viewStatsClient.ask_game_queries import ask_game
from viewStatsClient.ask_pitcher_stats import ask_pitcher
from viewStatsClient.ask_team_stats import ask_team
from viewStatsClient.ask_umpire_queries import ask_umpire
from viewStatsClient.ask_venue_queries import ask_venue

def main():
    try:
        mydb, cursor = get_cursor()
    except ProgrammingError:
        print('Invalid credentials! Please fix and try again')
        return
    except DatabaseError:
        print('Connection timed out. IP address may be incorrect. Please fix and try again')
        return

    stats_dict = {
        1: ask_batter,
        2: ask_game,
        3: ask_pitcher,
        4: ask_umpire,
        5: ask_venue,
        6: ask_team,
        7: lambda var1, var2: None
    }

    stats_print_dict = {
        1: ". View Batter stats",
        2: ". View Game stats",
        3: ". View Pitcher stats",
        4: ". View Umpire stats",
        5: ". View Venue stats",
        6: ". View Team stats",
        7: ". Back"
    }

    while True:
        print('What would you like to do?')
        print('1. View Stats')
        print('2. Add Data')
        print('3. Exit')
        option = input('Enter your choice: ')
        try:
            option = int(option)
        except ValueError:
            print('Error: You must enter an integer between 1 and 3')
            continue

        if option < 1 or option > 3:
            print('Invalid option, please choose 1, 2, or 3')
            continue

        if option == 1:
            print('What Stats would you like to view')
            for x in stats_print_dict:
                print(str(x) + stats_print_dict[x])

            while True:
                option = input('Enter your choice: ')
                try:
                    option = int(option)
                except ValueError:
                    print('Error: You must enter an integer between 1 and 7')
                    continue

                if option not in stats_dict.keys():
                    print('Error: You must enter an integer between 1 and 7')
                    continue

                print("\033c", end="")
                stats_dict[option](mydb, cursor)
                break

        elif option == 2:
            add_user_data(mydb, cursor)
            continue

        elif option == 3:
            return

if __name__ == '__main__':
    main()


from flask import *
from Graph import *
from AStar import *
app = Flask(__name__)

'''
Routers
'''

# Route to index
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/compute',methods=['POST'])
def compute():
    data  = request.data
    dataDict = json.loads(data)
    # Dokumentasi Pemakaian
    # dataDict erdiri atas
    # -size (jumlah node yang berarti node dari 0 sampai size-1)
    # -Node (node beserta latitude dan longitude)
    # -adj (ini adalah ajasensi list)
    # -start (start node)
    # -goal (goal node)
    # Berikut contoh json yang dikirimkan
    # {"size":4,"node":[{"latitude":-6.890853531500832,"longitude":107.60832433328301},{"latitude":-6.890821577490572,"longitude":107.61042718515068},{"latitude":-6.892493834467413,"longitude":107.60995511636406},{"latitude":-6.892493834467413,"longitude":107.60822777375847}],"adj":[[2,3],[3],[3,0],[2,1,0]],"start":3,"goal":2}
    # pengaksesan size -> dataDict['size']
    # Pengaksesan node 0 -> dataDict['node'][0]
    # Pengaksesan latitude node 0 -> dataDict['node'][0].latitude atau dataDict['node'][0]['latitude'] dicoba saalah satu seharusnya bisa salah satu
    # Pengaksesan adjasensi list node 0 -> dataDict['adj'][0] (hasil ini adalah list of node, yanng merupakan sisi yang bersisian dengan node 0)
    # Pengaksesan start -> dataDict['start'] , ini adalah node start
    # Pengaksesan goal -> dataDict['goal'] , ini adalah node goal
    print(dataDict)

    # get nodes from dataDict
    nodeList = []
    edgeList = []
    # create Graph
    G = Graph(nodeList, edgeList)

    # create and add nodes from dataDict to nodeList
    for i in range (0, len(dataDict['node'])):
        N = LocationNode(i, dataDict['node'][i]['longitude'], dataDict['node'][i]['latitude'])
        G.nodeList.append(N)
        i += 1

    # create and add edges from dataDict to edgeList
    for i in range (0, len(dataDict['adj'])):
        firstNode = G.nodeList[i]
        for j in range (0, len(dataDict['adj'][i])):
            if dataDict['adj'][i][j] > i:
                secondNode = G.nodeList[dataDict['adj'][i][j]]
                E = WeightedEdge(firstNode, secondNode, HarversineDistance(firstNode, secondNode))
                G.edgeList.append(E)

    # set edge list to solve
    SetEdgeList(G.edgeList)
    # set heuristic distance func for A* shortest path algorithm
    SetHeuristicDistanceFunc(HarversineDistance)
    # get solution path
    solution = GetShortestPath(G.nodeList[dataDict['start']], G.nodeList[dataDict['goal']])
    path, cost = solution

    # cast list of nodes in path into only its node indices
    pathNodeIdx = []
    for node in path:
        pathNodeIdx.append(node.value)
    # for node in pathNodeIdx:
    #     print(node)
    # print(cost)

    # get solution as a dictionary with key path and cost
    solutionDict = {
        'path' : pathNodeIdx,
        'cost' : cost
    }

    # convert the solution dictionary to json to be returned
    solutionJson = json.dumps(solutionDict)
    print(solutionJson)
    # Untuk pemakaian di peta/index.html
    # Klik 2 kali pin/marker untuk memasangkan edge atau sisi ke node lain, node yang ingin dipasangkan juga diklik 2 kali
    # Klik 1 kali pin/marker untuk menandai start node , warna akan berubah menjadi ungu
    # Klik kanan 1 kali pin/marker untuk menandai goal Node , warna akan berubah menjadi kuning , yang ini sabar agak lama
    # Klik pada peta untuk menambahkan pin
    # Pastikan semua kondisi diatas terpenuhi sebelum mengirim request

    #Return json
    #-Kalo bisa nanti kembaliannya list of node yang sudah terurut pathnya dari start ke goal, kalo bisa nama key json "path"
    #-Ditambah hitungan jarakanya , klo bisa keynya 'jarak'

    #PS
    #Kalo mau ngecek kembaliannya di console lognya sementara,nanti kalo udah selesai bilang biar aku parse di htmlnya
    #Mangats
    #kalo penjelasan diatas ada yang salah atau error langsung bilang ke aku yak.

    return solutionJson

if __name__ == '__main__':
    app.run(debug= True)


# 1072

import sys
import decimal
input = sys.stdin.readline

def get_victory_percent(x, y):
    # return int(y/x * 100)
    return y * 100 // x
    # 부동소수점 오차로 인해 해당 return 문에 대해서만 정답 처리가 됨.
    # int( / ) 와 // 의 차이를 이해해야 할듯 하다.
    # python float 다룰 때 주의!

# 1. 게임 횟수 x, 이긴 게임 수 y, 승률 z
x, y = map(int, input().split())
z = get_victory_percent(x, y)

answer = float('inf')

start = 1
end = 1000000000 # 최대 10억이 들어올 수 있어서 end 값을 10억으로 초기화

# 2. 범위 좁혀가며 이진 탐색
while start <= end:
        mid = (start + end) // 2

        # x, y 는 함께 증가 => 게임 진행 판수

        # mid번 더 진행했을 때 원래의 승률이 더 크다면
        # start를 mid 이상으로 두고 다시 탐색한다.
        if get_victory_percent(x+mid, y+mid) <= z:
            start = mid + 1
        else:
            # mid번 더 진행했을 때 처음 승률보다 크다면, answer은 현재 mid가 되고
            # end를 mid 이하로 두고 다시 탐색한다.
            answer = mid
            end = mid - 1

if answer == float('inf'): # 처음 진행했을 때보다 승률이 크게 변경되지 않은 경우
    print(-1)
else:
    print(answer)

# IDEA
# 해당 문제는 왜 이진 탐색으로 풀어야 할까? "1 ≤ X ≤ 1,000,000,000"
# 값이 최대 10억이 나올 수 있음 => O(N)으로 풀어도 시간 초과가 날 것이기 때문에, 연산을 줄일 수 있는 로직을 생각해나야함
# 다량의 데이터 검색을 하는 문제는 이진 탐색을 적용해볼 수 있음


import torch
import torch.nn as nn
import torch.nn.functional as F

class Block(nn.Sequential):
    def __init__(self, in_planes, out_planes, args):
        super(Block, self).__init__()

        self.x5_block = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1, bias=False),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.Dropout(args.dropout),
        )
        self.x6_block = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1, bias=False),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.Dropout(args.dropout),
        )
        self.x7_block = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1, bias=False),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            # nn.Dropout(args.dropout),
        )

    def forward(self, x4):
        x5 = self.x5_block(x4)
        x6 = self.x6_block(x4+x5)
        x7 = self.x7_block(x4+x5+x6)
        return x5, x6, x7

class DNN(nn.Module):
    def __init__(self, args):
        super(DNN, self).__init__()

        self.x1_block = nn.Sequential(
            nn.Conv2d(in_channels=6, out_channels=64, kernel_size=(3, 3), padding=1, bias=False),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.Dropout(args.dropout),
        )
        self.x2_block = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1, bias=False),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            nn.Dropout(args.dropout),
        )
        self.x3_block = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1, bias=False),
            nn.ReLU(),
            nn.BatchNorm2d(64),
            # nn.Dropout(args.dropout),
        )
        self.x4_pool = nn.MaxPool2d(2, 2)
        self.x5_6_7_block = Block(64, 64, args)
        self.x8_pool = nn.MaxPool2d(2, 2)
        self.x9_10_11_block = Block(64, 64, args)

        self.idm1 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(1, 1), padding=0, bias=False)
        self.xm2_block = Block(64, 64, args)
        self.idm2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(1, 1), padding=0, bias=False)
        self.xm4_block = Block(64, 64, args)
        self.idm4 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(1, 1), padding=0, bias=False)
        self.finm = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1, bias=False)

        self.idd1 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(1, 1), padding=0, bias=False)
        self.xd2_block = Block(64, 64, args)
        self.idd2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(1, 1), padding=0, bias=False)
        self.xd4_block = Block(64, 64, args)
        self.idd4 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(1, 1), padding=0, bias=False)
        self.find = nn.Conv2d(64, 1, kernel_size=3, stride=1, padding=1, bias=False)

    def forward(self, x):
        x1 = self.x1_block(x)
        x2 = self.x2_block(x1)
        x3 = self.x3_block(x1+x2)
        x4 = self.x4_pool(x1+x2+x3)
        x5, x6, x7 = self.x5_6_7_block(x4)
        x8 = self.x8_pool(x5+x6+x7)
        x9, x10, x11 = self.x9_10_11_block(x8)

        outm = self.idm1(x11)
        outm = F.interpolate(outm, scale_factor=2, mode='bilinear')
        _, _, outm = self.xm2_block(outm + x7)
        outm = self.idm2(outm)
        outm = F.interpolate(outm, scale_factor=2, mode='bilinear')
        _, _, outm = self.xm4_block(outm + x3)
        outm = self.idm4(outm)
        outm = self.finm(outm)

        outd = self.idd1(x11)
        outd = F.interpolate(outd, scale_factor=2, mode='bilinear')
        _, _, outd = self.xd2_block(outd + x7)
        outd = self.idd2(outd)
        outd = F.interpolate(outd, scale_factor=2, mode='bilinear')
        _, _, outd = self.xd4_block(outd + x3)
        outd = self.idd4(outd)
        outd = self.finm(outd)
        return outm, outd

if __name__ == '__main__':
    class DNNArg:
        dropout = 0.0

    net = DNN(DNNArg())
    y = net(torch.randn(1,3,224,224))
    print(y.size())


from os.path import dirname, realpath, join
import time
from datetime import datetime
from rich import box
from rich.table import Table
from rich.console import Console

SCRIPT_PATH = dirname(realpath(__file__))

class Results:
    RESULTS_PATH = "results"

    def __init__(self, results_name: str):
        self.method = ""
        self.start_time = None
        self.results_name = results_name
        self.results_path = join(SCRIPT_PATH, "..", "..", "performance_results", f"{results_name}.md")
        self.table = self.initiate_table()
        self.accuracies = list()

    @staticmethod
    def initiate_table():
        table = Table(title="", box=box.MINIMAL_DOUBLE_HEAD)
        table.add_column("Dataset")
        table.add_column("Method")
        table.add_column("Train \n size", justify="right")
        table.add_column("Test \n size", justify="right")
        table.add_column("Time", justify="right")
        table.add_column("Acc.", justify="right")
        return table

    def set_start_time(self):
        print("start time")
        self.start_time = time.time()

    def get_total_time(self):
        total_time = round(time.time() - self.start_time)
        print(f"{datetime.now():%Y_%m_%d_%H_%M}", f"finished in {total_time} seconds")
        return str(total_time) + "s"

    @staticmethod
    def format_dataset_name(name):
        return name.replace(".tsv", "").replace("_", " ")

    def save_result(self, dataset: str, method: str, accuracy: float, train_length: int, test_length: int):
        self.accuracies.append(accuracy)
        self.table.add_row(
            self.format_dataset_name(dataset),
            method,
            str(train_length),
            str(test_length),
            self.get_total_time(),
            str(round(accuracy)) + "%",
        )

    def write_results(self):
        accuracies_average = round(sum(self.accuracies) / len(self.accuracies))
        self.table.add_row("", "", "", "", "", "")
        self.table.add_row("average", "", "", "", "", str(accuracies_average) + "%")
        console = Console(record=True)
        console.print(self.table)
        console.save_text(self.results_path)


import os
import sys
# 在linux会识别不了包 所以要加临时搜索目录
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import execjs
import time
from datetime import datetime
import pandas as pd
import requests
import json
import akshare as ak

def get_var():
    '''
    获取js
    :return:
    '''
    js = '/opt/code/pythonstudy_space/05_quantitative_trading_hive/util/ths.js'
    with open(js) as f:
        comm = f.read()
    comms = execjs.compile(comm)
    result = comms.call('v')
    return result

def get_headers(cookie='Hm_lvt_78c58f01938e4d85eaf619eae71b4ed1=1672230413; historystock=688255%7C*%7C003816%7C*%7C002933%7C*%7C600706%7C*%7C688687; Hm_lvt_da7579fd91e2c6fa5aeb9d1620a9b333=1673161546; log=; user=MDq080MxOjpOb25lOjUwMDo1MTMxNDQ1NjI6NywxMTExMTExMTExMSw0MDs0NCwxMSw0MDs2LDEsNDA7NSwxLDQwOzEsMTAxLDQwOzIsMSw0MDszLDEsNDA7NSwxLDQwOzgsMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDEsNDA7MTAyLDEsNDA6MjQ6Ojo1MDMxNDQ1NjI6MTY3MzY1OTkxNTo6OjE1NzQ1NTQ5ODA6MjY3ODQwMDowOjFkZjgzN2I5YThiZTRiNzBhZTIyZTE2MzViYWFiYjlhODpkZWZhdWx0XzQ6MQ%3D%3D; userid=503144562; u_name=%B4%F3C1; escapename=%25u5927C1; ticket=90f706428300af2c9ad5b9bc8faf3498; user_status=0; utk=bd0610c31e8fad6a9f67c1c47f83cb90; Hm_lpvt_da7579fd91e2c6fa5aeb9d1620a9b333=1673661956; Hm_lpvt_78c58f01938e4d85eaf619eae71b4ed1=1673661957; v=A5hM9kejT7kEnWM9jZ0-eQlTac0vgfoIXu7QjdKD5lmEWjbzepHMm671oDEh'):
    '''
    获取请求头 设置自己的请求头在get_header配置
    :param cookie:
    :return:
    '''
    v = get_var()
    cookie = cookie.split('v=')
    cookie = cookie[0] + 'v=' + v
    headers={
        'Cookie':cookie ,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
    }
    return headers

def get_all_stock():
    '''
    获取全部自选股
    :return:
    '''
    headers=get_headers()
    url='https://t.10jqka.com.cn/newcircle/group/getSelfStockWithMarket/?'
    params={
        'callback': 'selfStock',
        '_': '1673617915586'
    }
    res=requests.get(url=url,params=params,headers=headers)
    text=res.text[10:len(res.text)-2]
    json_text=json.loads(text)
    df = pd.DataFrame(json_text['result'])
    return df

def add_stock_to_account(stock='600111'):
    '''
    添加股票到自选股
    :param stock:
    :return:
    '''
    url='https://t.10jqka.com.cn/newcircle/group/modifySelfStock/?'
    headers=get_headers()
    params={
        'callback':'modifyStock',
        'op': 'add',
        'stockcode': stock,
        '_': '1673620068115',
    }
    res = requests.get(url=url, params=params, headers=headers)
    text = res.text[12:len(res.text) - 2]
    json_text = json.loads(text)
    err=json_text['errorMsg']
    if err=='修改成功':
        print('{}加入自选股成功'.format(stock))
    else:
        print('{}{}'.format(stock,err))

def del_stock_from_account(stock='600111'):
    '''
    删除股票从自选股
    :param stock:
    :return:
    '''
    url = 'https://t.10jqka.com.cn/newcircle/group/modifySelfStock/?'
    headers = get_headers()
    df=get_all_stock()
    try:
        marker=df[df['code']==stock]['marketid'].tolist()[0]
        stockcode='{}_{}'.format(stock,marker)
        params={
            'op':'del',
            'stockcode':stock
        }
        res = requests.get(url=url, params=params, headers=headers)
        text = res.text
        json_text = json.loads(text)
        err = json_text['errorMsg']
        if err == '修改成功':
            print('{}删除自选股成功'.format(stock))
        else:
            print('{}{}'.format(stock, err))
    except:
        print('{}没有在自选股'.format(stock))

def all_zt_stock_add_account(date='20230113'):
    '''
    将涨停的股票全部加入自选股
    :return:
    '''
    df=ak.stock_zt_pool_em(date=date)
    for stock in df['代码'].tolist():
        add_stock_to_account(stock=stock)

def all_del_add_stocks(codes):
    '''
    将所有自选股删除并加入新股票
    :return:
    '''
    del_df = get_all_stock()
    d_n = 0
    a_n = 0

    url = 'https://t.10jqka.com.cn/newcircle/group/modifySelfStock/?'
    headers = get_headers()
    for stock in del_df['code'].tolist():
        try:
            marker = del_df[del_df['code'] == stock]['marketid'].tolist()[0]
            stockcode = '{}_{}'.format(stock, marker)
            params = {
                'op': 'del',
                'stockcode': stock
            }
            res = requests.get(url=url, params=params, headers=headers)
            text = res.text
            json_text = json.loads(text)
            err = json_text['errorMsg']
            if err == '修改成功':
                d_n = d_n+1
            else:
                print('{}{}'.format(stock, err))
        except:
            print('{}没有在自选股'.format(stock))

    for stock in codes:
        params = {
            'callback': 'modifyStock',
            'op': 'add',
            'stockcode': stock,
            '_': '1673620068115',
        }
        res = requests.get(url=url, params=params, headers=headers)
        text = res.text[12:len(res.text) - 2]
        json_text = json.loads(text)
        err = json_text['errorMsg']
        if err == '修改成功':
            a_n = a_n+1
        else:
            print('{}{}'.format(stock, err))

    print('删除自选股成功，删除了{}个；加入自选股成功，加入了{}个'.format(d_n,a_n))

# python /opt/code/pythonstudy_space/05_quantitative_trading_hive/util/同花顺自选股.py
if __name__=='__main__':
    start_time = time.time()
    codes = ['002689','002094','002651','002264','002808','002888','003040','002762','002238','002766','003028']
    all_del_add_stocks(codes)
    end_time = time.time()
    print('{}：程序运行时间：{}s，{}分钟'.format(os.path.basename(__file__),end_time - start_time, (end_time - start_time) / 60))


from typing import Type, TypeVar, MutableMapping, Any, Iterable, Generator

from datapipelines import (
    DataSource,
    PipelineContext,
    Query,
    NotFoundError,
    validate_query,
)
from .common import KernelSource, APINotFoundError
from ...data import Platform
from ...dto.thirdpartycode import VerificationStringDto
from ..uniquekeys import convert_region_to_platform

T = TypeVar("T")

def _get_default_locale(
    query: MutableMapping[str, Any], context: PipelineContext
) -> str:
    return query["platform"].default_locale

class ThirdPartyCodeAPI(KernelSource):
    @DataSource.dispatch
    def get(
        self,
        type: Type[T],
        query: MutableMapping[str, Any],
        context: PipelineContext = None,
    ) -> T:
        pass

    @DataSource.dispatch
    def get_many(
        self,
        type: Type[T],
        query: MutableMapping[str, Any],
        context: PipelineContext = None,
    ) -> Iterable[T]:
        pass

    #######################
    # Verification String #
    #######################

    _validate_get_verification_string_query = (
        Query.has("platform").as_(Platform).also.has("summoner.id").as_(str)
    )

    @get.register(VerificationStringDto)
    @validate_query(_validate_get_verification_string_query, convert_region_to_platform)
    def get_verification_string(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> VerificationStringDto:
        parameters = {"platform": query["platform"].value}
        endpoint = "lol/platform/v4/third-party-code/by-summoner/{summonerId}".format(
            summonerId=query["summoner.id"]
        )
        try:
            data = self._get(endpoint=endpoint, parameters=parameters)
        except (ValueError, APINotFoundError) as error:
            raise NotFoundError(str(error)) from error

        data = {"string": data}
        data["region"] = query["platform"].region.value
        data["summonerId"] = query["summoner.id"]
        return VerificationStringDto(data)

    _validate_get_many_verification_string_query = (
        Query.has("platforms").as_(Iterable).also.has("summoner.ids").as_(Iterable)
    )

    @get_many.register(VerificationStringDto)
    @validate_query(
        _validate_get_many_verification_string_query, convert_region_to_platform
    )
    def get_many_verification_string(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> Generator[VerificationStringDto, None, None]:
        def generator():
            parameters = {"platform": query["platform"].value}
            for platform, summoner_id in zip(query["platforms"], query["summoner.ids"]):
                platform = Platform(platform.upper())
                endpoint = (
                    "lol/platform/v4/third-party-code/by-summoner/{summonerId}".format(
                        summonerId=summoner_id
                    )
                )
                try:
                    data = self._get(endpoint=endpoint, parameters=parameters)
                except APINotFoundError as error:
                    raise NotFoundError(str(error)) from error

                data = {"string": data}
                data["region"] = platform.region.value
                data["summonerId"] = summoner_id
                yield VerificationStringDto(data)

        return generator()


# bottom-up solution
def coin_change_bottomup(coins, value):
    min_coins = [0] + [None] * (value - 1)
    for v in range(1, value):
        if v < min(coins):
            pass
        else:
            options = []
            for i in range(len(coins)):
                if v >= coins[i]:
                    options.append(min_coins[v - coins[i]])
                    # residual = (v - coins[i]) + 1
                    # options = min_coins[0:residual]
            min_coins[v] = min(options) + 1
    return min_coins[value - 1]

#print(coin_change_bottomup([9, 6, 5, 1], 12))

# top-down solution
import math

def coin_change_topdown(coins, value):
    memo = [0] + [None] * (value - 1)
    return coin_change_topdown_aux(coins, value, memo)

def coin_change_topdown_aux(coins, value, memo):
    memo = [None] * value
    if value == 0:
        return 0
    if memo[value-1] == None:
        min_coins = math.inf
        for i in range(1, len(coins)):
            if coins[i] <= value:
                min_coins = min(min_coins, 1 + coin_change_topdown_aux(coins, value - coins[i], memo))
        memo[value-1] = min_coins
    return memo[value-1]

#print(coin_change_topdown([9, 6, 5, 1], 12))


import boto3

class S3:
    def __init__(self, aws_access_key_id, aws_secret_access_key):
        self.s3_client = boto3.client(
            's3',
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key)
        self.s3 = boto3.resource(
            's3',
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key)

    def upload_file(self, file_name, bucket):
        """
        Function to upload a file to an S3 bucket
        """
        object_name = file_name.split('/')[-1]
        response = self.s3_client.upload_file(file_name, bucket, object_name)

        return response

    def download_file(self, file_name, bucket):
        """
        Function to download a given file from an S3 bucket
        """
        output = f"downloads/{file_name}"
        self.s3.Bucket(bucket).download_file(file_name, output)

        return output

    def delete_file(self, file_name, bucket):
        '''
        Function to delete a file from an S3 bucket
        '''
        self.s3.Object(bucket, file_name).delete()

    def list_files(self, bucket):
        """
        Function to list files in a given S3 bucket
        """
        contents = []
        try:
            for item in self.s3_client.list_objects(Bucket=bucket)['Contents']:
                contents.append(item)
        except KeyError:
            print("No contents available")
            contents.append("No items in the bucket... Add some...")
        return contents