import requests
from bs4 import BeautifulSoup

from ._exception_handling import ExceptionHandlingMetaclass
from ._schemaorg import SchemaOrg
from ._decorators import Decorators

# some sites close their content for 'bots', so user-agent must be supplied
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
}

class AbstractScraper(metaclass=ExceptionHandlingMetaclass):

    def __init__(self, url, exception_handling=True, meta_http_equiv=False, test=False):
        if test:  # when testing, we load a file
            with url:
                page_data = url.read()
        else:
            page_data = requests.get(url, headers=HEADERS).content

        self.exception_handling = exception_handling
        self.meta_http_equiv = meta_http_equiv
        self.soup = BeautifulSoup(page_data, "html.parser")
        self.schema = SchemaOrg(page_data, host=self.host())
        self.url = url
        # if self.schema.data:
        #     print("Class: %s has schema." % (
        #         self.__class__.__name__
        #     ))

    def url(self):
        return self.url

    def host(self):
        """ get the host of the url, so we can use the correct scraper """
        raise NotImplementedError("This should be implemented.")

    @Decorators.normalize_string_output
    @Decorators.schema_org_priority
    def title(self):
        raise NotImplementedError("This should be implemented.")

    @Decorators.schema_org_priority
    def total_time(self):
        """ total time it takes to preparate the recipe in minutes """
        raise NotImplementedError("This should be implemented.")

    @Decorators.schema_org_priority
    def yields(self):
        """ The number of servings or items in the recipe """
        raise NotImplementedError("This should be implemented.")

    @Decorators.schema_org_priority
    @Decorators.og_image_get
    def image(self):
        raise NotImplementedError("This should be implemented.")

    @Decorators.bcp47_validate
    @Decorators.schema_org_priority
    def language(self):
        """
        Human language the recipe is written in.

        May be overridden by individual scrapers.
        """
        candidate_languages = set()
        html = self.soup.find(
            'html',
            {'lang': True}
        )
        candidate_languages.add(html.get('lang'))

        # Deprecated: check for a meta http-equiv header
        # See: https://www.w3.org/International/questions/qa-http-and-lang
        meta_language = self.soup.find(
            'meta',
            {
                'http-equiv': lambda x: x and x.lower() == 'content-language',
                'content': True
            }
        ) if self.meta_http_equiv else None
        if meta_language:
            for language in meta_language.get('content').split(','):
                candidate_languages.add(language)
                break

        # If other langs exist, remove 'en' commonly generated by HTML editors
        if len(candidate_languages) > 1 and 'en' in candidate_languages:
            candidate_languages.remove('en')

        # Return the first candidate language
        for language in candidate_languages:
            return language

    @Decorators.schema_org_priority
    def ingredients(self):
        raise NotImplementedError("This should be implemented.")

    @Decorators.schema_org_priority
    def instructions(self):
        raise NotImplementedError("This should be implemented.")

    @Decorators.schema_org_priority
    def ratings(self):
        raise NotImplementedError("This should be implemented.")

    def reviews(self):
        raise NotImplementedError("This should be implemented.")

    def links(self):
        invalid_href = ('#', '')
        links_html = self.soup.findAll('a', href=True)

        return [
            link.attrs
            for link in links_html
            if link['href'] not in invalid_href
        ]


import os
import base64
from app.utils.const import pic_path

def getNameListsGuiyin():
    file_dir = pic_path
    guiyindict = {}
    product_list = []
    for dir in os.listdir(file_dir):
        productname = dir[:-22]
        timeperiod = dir[-22:]
        if not guiyindict.get(productname):
            guiyindict[productname] = []
            guiyindict[productname].append(timeperiod)
        else:
            guiyindict[productname].append(timeperiod)

        if productname not in product_list:
            product_list.append(productname)
    return guiyindict

def getGuiyinpics(product_name, time_period):
    dirname = product_name+time_period
    path1 = pic_path+'/'
    path = os.path.join(path1, dirname)
    pics_list = []
    for pic in os.listdir(path):
        if pic.endswith('.png'):
            pics_list.append(pic)
    return path, pics_list

def return_img_stream(img_local_path):
    """
    工具函数:
    获取本地图片流
    :param img_local_path:文件单张图片的本地绝对路径
    :return: 图片流
    """

    img_stream = ''
    with open(img_local_path, 'rb') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream).decode()
    return img_stream

def get_img_list(guiyindict, product_name):
    datelist = guiyindict[product_name]
    img_list = {}
    # 默认显示date最近的一个周
    path, picslist = getGuiyinpics(product_name, datelist[-1])
    for pic in picslist:
        img_path = os.path.join(path, pic)
        img_stream = return_img_stream(img_path)
        img_list[pic[:-4]] = img_stream
    return img_list, datelist


import logging
from datetime import timedelta
from typing import Callable

from crow_security import Panel

from homeassistant.const import (CONF_PASSWORD, CONF_EMAIL,)
from .consts import (CONF_PANEL_MAC, DOMAIN)
import crow_security as crow

from homeassistant.util import Throttle

_LOGGER = logging.getLogger(DOMAIN)

class CrowHub(object):

    def __init__(self, domain_config, hass):
        self._crow = crow
        self._hass = hass
        # noinspection PyPackageRequirements
        import jsonpath
        self.jsonpath = jsonpath.jsonpath
        self._mac = domain_config[CONF_PANEL_MAC]
        _LOGGER.info('Crow MAC: %s' % self._mac)
        # noinspection PyTypeChecker
        self._panel: Panel = None
        self._devices = None
        self._outputs = None
        self._measurements = None
        self._subscriptions = {}
        self.session = crow.Session(
            domain_config[CONF_EMAIL],
            domain_config[CONF_PASSWORD])

    @property
    def mac(self):
        return self._mac

    async def init_panel(self):
        self._panel = await self.session.get_panel(self._mac)

    @Throttle(timedelta(seconds=60))
    async def get_devices(self):
        try:
            _LOGGER.info('Got panel: %s' % self.panel)
            zones = await self.panel.get_zones()
            self._devices = zones
        except self._crow.Error as ex:
            _LOGGER.error('Crow operation failed, %s', ex)
            return False
        return True

    @Throttle(timedelta(seconds=30))
    async def _get_measurements(self):
        m = await self.panel.get_measurements()
        return m

    async def get_measurements(self):
        m = await self._get_measurements()
        if not m and self._measurements:
            return self._measurements
        elif m:
            self._measurements = m
        return m

    @Throttle(timedelta(seconds=30))
    async def _get_outputs(self):
        o = await self.panel.get_outputs()
        return o

    async def get_outputs(self):
        o = await self._get_outputs()
        if not o and self._outputs:
            return self._outputs
        elif o:
            self._outputs = o
        return o

    def set_output_state(self, output_id, state):
        return self._panel.set_output_state(output_id, state)

    def capture_cam_image(self, zone_id):
        return self._panel.capture_cam_image(zone_id)

    @property
    def panel(self):
        return self._panel

    def get(self, obj, jpath, *args):
        """Get values from the overview that matches the jsonpath."""
        res = self.jsonpath(obj, jpath % args)
        return res if res else []

    def get_first(self, obj, jpath, *args):
        """Get first value from the overview that matches the jsonpath."""
        res = self.get(obj, jpath, *args)
        return res[0] if res else None

    def subscribe(self, device_id, callback: Callable):
        self._subscriptions[device_id] = callback

    def ws_connect(self):
        async def ws_cb(msg):
            if msg.get('type') == 'info' and msg.get('data', {}).get('_id', {}).get('dect_interface') == 32768:
                _LOGGER.debug("Not processed message: %s", msg)
                return
            _LOGGER.debug("Received message from Crow: %s", msg)
            device_id = msg.get('data', {}).get('_id', {}).get('device_id')
            callback = self._subscriptions.get(device_id)
            if callback is not None:
                callback(msg)

        return self.session.ws_connect(self._mac, ws_cb)


# n x n 정사각형
# L R U D

n = int(input())
cmd = list(input().split())
x = 0
y = 0
for cor in cmd:
	if cor == 'R' and x + 1 <= n :
		x += 1
	elif cor == 'L' and x - 1 > 0:
		x -= 1
	elif cor == 'U' and y - 1 > 0:
		y = 1
	elif cor == 'D' and y + 1 <= n:
		y += 1
print(y + 1, x + 1)

# solution 2
# n = int(input())
# x, y = 1, 1
# cmd = input().split()

# dx = [0, 0, -1, 1]
# dy = [-1, 1, 0, 0]
# cmd_lst = ['L', 'R', 'U', 'D']

# for cor in cmd:
# 	for i in range(len(cmd_lst)):
# 		if cor == cmd_lst[i]:
# 			nx = x + dx[i]
# 			ny = y + dy[i]
# 	if nx < 1 or ny < 1 or nx > n or ny > n:
# 		continue
# 	x, y = nx, ny

# print(x, y)


n = eval(input())
order = {}
while(n != 0):
    n = n - 1
    nums = list(map(int,input().split(",")))
    fromTo = (nums[0],nums[1])
    order[fromTo] = nums[2]
k = eval(input())

answer = []
for m in range(k):
    answer.append(0)
for start,end in order:
    temp = order[(start,end)]
    for m in range(start-1,end):
        answer[m] += temp
print(answer)


from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from log import views
from content import views as content
from classes import views as classes
from attendance import views as attendance
from exam import views as exam
from marks import views as marks
from django.conf import settings
from django.conf.urls.static import static

from .views import GeneratePdf

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$',views.index,name='index'),
    url(r'^special/',views.special,name='special'),
    url(r'^log/',include('log.urls')),
    url(r'^logout/$', views.user_logout, name='logout'),
    path('sub', content.sub, name='sub'),
    path('subshow',content.subshow,name='subshow'),
    # path('subedit/<int:id>', views.edit),
    path('subupdate/<int:id>', content.subupdate,name='subupdate'),
    path('subdelete/<int:id>', content.subdestroy,name='subdelete'),
    path('proshow', views.proshow, name='proshow'),
    path('profileshow/<int:id>', views.profileshow, name='profileshow'),
    path('classes', classes.classes, name='classes'),
    path('classshow',classes.classshow,name='classshow'),
    # path('classupdate/<int:id>', classes.classupdate,name='classupdate'),
    path('classdelete/<int:id>', classes.classdestroy,name='classdelete'),
    path('classdetails', classes.classdetails, name='classdetails'),
    path('classdetailsshow',classes.classdetailsshow,name='classdetailsshow'),
    # path('classdetailsupdate/<int:id>', classes.classdetailsupdate,name='classdetailsupdate'),
    path('classdetailsdestroy/<int:id>', classes.classdetailsdestroy,name='classdetailsdestroy'),
    path('attend', attendance.attend, name='attend'),
    path('attendanceshow', attendance.attendanceshow, name='attendanceshow'),
    path('attendanceupdate/<int:id>', attendance.attendanceupdate, name='attendanceupdate'),
    path('attendancedestroy/<int:id>', attendance.attendancedestroy, name='attendancedestroy'),
    path('exam', exam.exam, name='exam'),
    path('examshow', exam.examshow, name='examshow'),
    path('examupdate/<int:id>', exam.examupdate, name='examupdate'),
    path('examdestroy/<int:id>', exam.examdestroy, name='examdestroy'),
    path('marks', marks.marks, name='marks'),
    path('marksshow', marks.marksshow, name='marksshow'),
    path('marksupdate/<int:id>', marks.marksupdate, name='marksupdate'),
    path('marksdestroy/<int:id>', marks.marksdestroy, name='marksdestroy'),
    path('studentreport/<int:id>', marks.studentreport, name='studentreport'),
    # url(r'^pdf/$',GeneratePdf.as_view()),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# -*- coding:utf-8 -*-
# @Author : tzy

import json
import time
import ElasticMode.logModule as log

from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
# 解决跨域问题
CORS(app, supports_credentials = True)

from MatchMode.mongo_utils import MongoDB, MongoPipline
from MatchMode.search_utils import SearchEngine
from ElasticMode.search_utils import ElasticSearchEngine

MODE = 2

@app.route("/search", methods = ["GET", "POST"])
def search():
    start = time.perf_counter()

    raw = request.get_data()
    data = json.loads(raw)
    keyword = data["keyword"]
    log.INFO("Keyword: {}, Mode: {}".format(keyword, MODE))

    if MODE == 1: # 匹配搜索
        tmp_result = match_search_engine.find(keyword)
        result = json.dumps(eval(str(tmp_result)))
    if MODE == 2: # ES搜索
        tmp_result = elastic_search_engine.search_by_keyword(keyword)
        result = json.dumps(tmp_result)

    end = time.perf_counter()
    log.INFO("Time-consuming for this search: {:.4f}s".format(end - start))
    # log.INFO("Result: {}".format(result))

    return result

@app.route("/author", methods = ["GET", "POST"])
def author():
    start = time.perf_counter()

    raw = request.get_data()
    data = json.loads(raw)
    name, department = data["keyword"].split('&')
    log.INFO("Name: {}, Domain: {}, Mode: {}".format(name, department, MODE))

    if MODE == 1: # 匹配搜索
        tmp_result = match_search_engine.find_by_name(name, department=department)
        result = json.dumps(eval(str(tmp_result)))
    if MODE == 2: # ES搜索
        tmp_result = elastic_search_engine.search_by_author(name, department)
        result = json.dumps(tmp_result)

    end = time.perf_counter()
    log.INFO("Time-consuming for this search: {:.4f}s".format(end - start))
    # log.INFO("Result: {}".format(result))

    return result

if __name__ == "__main__":
    log.INFO("Initialize the matchMode search engine")
    db = MongoDB('mydb')
    mongo_pipline = MongoPipline(db)
    allData = mongo_pipline.load_data_from_mongo(do_filter = True)
    match_search_engine = SearchEngine(allData)

    log.INFO("Initialize the elasticMode search engine")
    elastic_search_engine = ElasticSearchEngine()

    log.INFO("Start the server")
    app.run(host = '0.0.0.0', port = 5002, debug = False)


import pytest

from reservations.choices import ReservationTypeChoice
from tests.factories import ReservationFactory, ReservationUnitFactory
from tests.helpers import UserType
from tests.test_graphql_api.test_reservation.helpers import reservations_query

# Applied to all tests
pytestmark = [
    pytest.mark.django_db,
    pytest.mark.usefixtures("_disable_elasticsearch"),
]

def test_filter_reservations_by_reservation_type__single(graphql):
    # given:
    # - There is a reservation in a certain state
    # - A superuser is using the system
    reservation_unit = ReservationUnitFactory.create()
    reservation = ReservationFactory.create(reservation_unit=[reservation_unit], type=ReservationTypeChoice.NORMAL)
    graphql.login_user_based_on_type(UserType.SUPERUSER)

    # when:
    # - User tries to filter reservations by said type
    response = graphql(reservations_query(reservation_type=ReservationTypeChoice.NORMAL.value))

    # then:
    # - The reservation is returned without errors
    assert response.has_errors is False, response
    assert len(response.edges) == 1, response
    assert response.node(0) == {"pk": reservation.pk}

def test_filter_reservations_by_reservation_type__multiple(graphql):
    # given:
    # - There are reservations in a different states
    # - A superuser is using the system
    reservation_unit = ReservationUnitFactory.create()
    reservation_1 = ReservationFactory.create(reservation_unit=[reservation_unit], type=ReservationTypeChoice.NORMAL)
    reservation_2 = ReservationFactory.create(reservation_unit=[reservation_unit], type=ReservationTypeChoice.STAFF)
    ReservationFactory.create(reservation_unit=[reservation_unit], type=ReservationTypeChoice.BEHALF)
    graphql.login_user_based_on_type(UserType.SUPERUSER)

    # when:
    # - User tries to filter reservations by some of those states
    response = graphql(
        reservations_query(
            reservation_type=[
                ReservationTypeChoice.NORMAL.value,
                ReservationTypeChoice.STAFF.value,
            ]
        )
    )

    # then:
    # - The reservation is returned without errors, and contains those in the selected states
    assert response.has_errors is False, response
    assert len(response.edges) == 2, response
    assert response.node(0) == {"pk": reservation_1.pk}
    assert response.node(1) == {"pk": reservation_2.pk}


from bs4 import BeautifulSoup
import re
import json

from pyparsing import alphanums

def interfaceMain(
    target="../../docs/CarianArchive.html",
        transformedCarianArchiveFile="../../docs/carianArchiveTrans.json"
    ):
    findAllCategories(target, transformedCarianArchiveFile)

def findAllCategories(target="../../docs/CarianArchive.html", transformedCarianArchiveFile="../../docs/carianArchiveTrans.json"):
    with open(target) as openFile:
        soup = BeautifulSoup(openFile, 'html.parser')

    categories = soup.select('div')

    foundCategories = []
    for category in categories:
        categoryTitle = category.get('id')

        foundItems = []
        categoryItems = category.find_all('h3')
        for item in categoryItems:

            categoryItemNo, categoryItemName = categoryItemSplitter(item.contents)
            content = contentFinder(item)

            foundItems.append({
                'itemNo' : categoryItemNo,
                'itemName' : categoryItemName,
                'content' : content
            })

        foundCategories.append({
            'title' : categoryTitle,
            'items' : foundItems
        })

    with open(transformedCarianArchiveFile, 'w') as outfile:
        json.dump(foundCategories, outfile, indent=2)

def categoryItemSplitter(categoryItem="['Bone Ballista Bolt [53030000]']"):
    categoryItemStr = categoryItem[0]
    categoryItemNo = useRegex(categoryItemStr, '\\[.*\\]').translate({ord(ch):'' for ch in '[]'})
    categoryItemName = useRegex(categoryItemStr, "[a-zA-Z ':-]+[a-zA-Z]")

    return categoryItemNo, categoryItemName

def contentFinder(item):
    foundContent = ""
    if item is not None:
        for sibling in item.next_siblings:
            if sibling.name != "h3":
                text = sibling.text
                text = text.strip()
                text = text.strip('\n')
                text = text.replace("\n        ", " ")

                length = len(foundContent)
                if length > 0:
                    if foundContent[length - 1] != " ":
                        foundContent = foundContent + " " + text
                    else:
                        foundContent = foundContent + text
                else:
                    foundContent = foundContent + text
            else:
                break

    return foundContent

def useRegex(input="Bone Ballista Bolt [53030000]", pattern='\\[.*\\]'):
    group = re.search(pattern, input)
    if group is not None:
        return group.group(0)
    else:
        return "[na]"


import speech_recognition as sr
import pyttsx3

# initiating a speaking female robot
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty('voice',voices[1].id)

# initiating a listening robot
rec = sr.Recognizer()

                    # Starting a robot conversation
with sr.Microphone() as source:
    audio = rec.listen(source)
    text = rec.recognize_google(audio)
    Hello = "{}".format(text)

    if 'hello' in Hello or 'hi' in hello or 'good morning':
        engine.say("Hello")
        engine.runAndWait()

    with sr.Microphone() as source:
        audio1 = rec.listen(source)
        text1 = rec.recognize_google(audio1)
        ask = "{}".format(text1)

        if 'how are you ' in ask or 'how do you do' in ask:
            engine1 = say("Am fine , thank you")
            engine1.runAndWait()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File              : config.py
# Author            : Chi Han, Jiayuan Mao
# Email             : haanchi@gmail.com, maojiayuan@gmail.com
# Date              : 17.07.2019
# Last Modified Date: 26.11.2019
# Last Modified By  : Chi Han
#
# This file is part of the VCML codebase
# Distributed under MIT license

import argparse
import jacinle
import torch
import os
import shutil
from pprint import pprint

from utility.common import \
    make_dir, is_empty, yes_or_no, copytree_verbose
from .dataset_config import dataset_config_register

class Args:
    def __init__(self):
        raw_args = self.parse_args()
        raw_args = self.post_process(raw_args)
        self.__dict__.update(vars(raw_args))

    @staticmethod
    def parse_args():
        parser = argparse.ArgumentParser()
        dir_args = {}
        group = None

        def dir_add_argument(arg_name, **kwargs):
            assert group is not None
            if group not in dir_args:
                dir_args[group] = []
            arg_name = '--' + group + '_' + arg_name[2:]
            dir_args[group].append(arg_name.strip('-'))
            parser.add_argument(arg_name, **kwargs)

        # options determining what experiment to run
        parser.add_argument('--mode', type=str, default='run-experiment',
                            required=True,
                            choices=['run-experiment',
                                     'build-dataset',
                                     'output-dataset'],
                            )
        parser.add_argument('--task', required=True,
                            choices=['GQA', 'CLEVR', 'CUB'])
        parser.add_argument('--dataset', type=str, default='')
        parser.add_argument('--visual_inputs', type=str, nargs='*',
                            choices=['plain', 'image', 'detection'],
                            default=['image', 'detection'],
                            )
        parser.add_argument('--experiment', type=str, required=True,
                            help='controls the dataset processing')
        parser.add_argument('--num_parallel', type=int, default=1)
        parser.add_argument('--ipython', action='store_true',
                            help='ipython embedding before running')
        parser.add_argument('--in_epoch', nargs='+', type=str,
                            default=['train', 'test', 'val'],
                            choices=['train', 'test', 'val',
                                     'test_ref'])
        parser.add_argument('--test_every', type=int, default=1)
        parser.add_argument('--old', action='store_true',
                            help='run in an old way')
        parser.add_argument('--webpage',
                            default='http://vcml.csail.mit.edu/data')

        # settings for training parameters
        parser.add_argument('--batch_size', type=int, default=10, metavar='N',
                            help='input batch size for training (default: 64)')
        parser.add_argument('--epochs', type=int, default=100, metavar='N',
                            help='number of epochs to train (default: 10)')
        parser.add_argument('--lr', type=float, default=1e-3, metavar='LR')
        parser.add_argument('--init_variance', type=float, default=1e-4,
                            help='parameter initialization variance')
        parser.add_argument('--random_seed', type=int, default=-1,
                            help='-1 if no manual random seed is set')
        parser.add_argument('--curriculum_training', type=int, default=0)
        parser.add_argument('--num_workers', default=0, type=int)
        parser.add_argument('--balance_classification', action='store_true')

        # model-related options
        parser.add_argument('--model_similarity', default='cosine',
                            choices=['cosine', 'tree_cosine'])
        parser.add_argument('--model', default='VCML',
                            choices=[
                                'VCML',
                                'NSCL',
                                'GRUCNN',
                                'BERTvariant',
                                'GRU',
                                'BERT',
                                # 'MAC',
                            ])

        # arguments determining methods for building & composing dataset
        parser.add_argument('--size', type=int, default=600000)
        parser.add_argument('--questionsPimage', type=int, default=3)
        parser.add_argument('--with_checktable', action='store_true')
        parser.add_argument('--filter_out_original_test', action='store_true')
        parser.add_argument('--confidence_th', type=int, default=4,
                            help='when dataset')
        parser.add_argument('--fewshot_ratio', type=float, default=0.1)

        parser.add_argument('--most_frequent', type=int, default=-1,
                            help='use most frequent concepts')
        parser.add_argument('--generalization_ratio', type=float, default=0.25,
                            help='ratio of concepts for generalization')
        parser.add_argument('--conceptual_question_ratio', type=float,
                            default=0.1,
                            help='ratio of conceptual questions')
        parser.add_argument('--split_ratio', type=float, nargs='+',
                            default=[0.7, 0.2, 0.1])
        parser.add_argument('--debiasing_leak', type=int, default=200)
        parser.add_argument('--visual_mix_ratio', type=float, default=0.01)
        parser.add_argument('--output_visual', action='store_true')

        # adding dataset-specific relative directories

        parser.add_argument('--data_dir', default='../data/vcml_data/')
        # GQA dataset
        group = 'GQA'
        parser.add_argument('--GQA_root_dir',
                            default='GQA')
        dir_add_argument('--image_dir', default='raw/images')
        dir_add_argument('--sceneGraph_dir', default='raw/sceneGraphs/')
        dir_add_argument('--dataset_dir',
                         default='augmentation')

        # CLEVR dataset
        group = 'CLEVR'
        parser.add_argument('--CLEVR_root_dir',
                            default='CLEVR')
        dir_add_argument('--image_dir', default='raw/images')

        dir_add_argument('--sceneGraph_dir', default='detections')
        dir_add_argument('--dataset_dir',
                         default='augmentation')
        dir_add_argument('--ref_scene_json', type=str,
                         default='kexin_scenes/scenes.json')
        dir_add_argument('--ref_image_dir', type=str,
                         default='kexin_scenes/images')

        # CUB dataset
        group = 'CUB'
        parser.add_argument('--CUB_root_dir',
                            default='CUB')
        dir_add_argument('--image_dir', default='raw/images')

        dir_add_argument('--sceneGraph_dir',
                         default='augmentation/sceneGraphs')
        dir_add_argument('--dataset_dir',
                         default='augmentation')

        # image setting
        parser.add_argument('--box_scale', type=int, default=1024,
                            help='bounding box size')
        parser.add_argument('--image_scale', type=int, default=224)
        parser.add_argument('--null_image', default='NULLIMAGE')

        # visualization & checkpointing
        parser.add_argument('--log_dir', type=str,
                            default='../data/log')
        parser.add_argument('--glove_pretrained_dir',
                            default='../data/log/checkpoints')
        parser.add_argument('--history_length', type=int, default=10000)
        parser.add_argument('--silent', action='store_true',
                            help='turning off logging and visualizing')
        parser.add_argument('--visualize_relation', type=str,
                            help='metaconcept for visualization')
        parser.add_argument('--name', type=str, default='')
        parser.add_argument('--pretrained', action='store_true')
        parser.add_argument('--resume', action='store_true')
        parser.add_argument('--clear_cache', action='store_true')
        parser.add_argument('--cache_dir', default='cache/')
        parser.add_argument('--not_build_reasoning', action='store_true')
        parser.add_argument('--temp_dir', type=str,
                            default='/tmp/torch_extensions_hc')

        # model parameters
        parser.add_argument('--true_th', type=float, default=0.7)
        parser.add_argument('--temperature', type=float, default=10)
        parser.add_argument('--conceptual_weight', type=float, default=1,
                            help='weight for conceptual questions')
        parser.add_argument('--embed_dim', type=int, default=50)
        parser.add_argument('--feature_dim', type=int, default=512)
        parser.add_argument('--metaconcept_hidden_dim', type=int, default=10)
        parser.add_argument('--hidden_dim', type=int, default=100)
        parser.add_argument('--fix_resnet', action='store_true')
        parser.add_argument('--other_offset', default=0., type=float,
                            help='offset for logits of other concepts')
        parser.add_argument('--sample_size', default=100000, type=int,
                            help='num of sample points for intergral')
        parser.add_argument('--detach_in_rel', action='store_true',
                            help='detach concept in relation calculation')
        parser.add_argument('--pretrained_embedding', action='store_true')
        parser.add_argument('--finetune_embedding', action='store_true')
        parser.add_argument('--force_off_lm', action='store_true')
        parser.add_argument('--force_on_lm', action='store_true')
        parser.add_argument('--dropout', type=float, default=0)
        parser.add_argument('--penalty', type=float, default=0)
        parser.add_argument('--length_penalty', type=float, default=0)

        # temporary configurations for debugging
        parser.add_argument('--test_only', action='store_true')
        parser.add_argument('--concept_filter', type=int, nargs='*',
                            default=[])
        parser.add_argument('--use_gt_program', action='store_true')

        args = parser.parse_args()
        args.dir_args = dir_args
        return args

    def post_process(self, args):
        if args.name == '':
            args.name = args.experiment
        args.dataset_config = dataset_config_register
        args.root_dir = os.path.abspath('.')
        args.cache_dir = os.path.join(args.data_dir, args.cache_dir)

        # pytorch config initialization
        args.num_gpus = torch.cuda.device_count()
        args.use_cuda = args.num_gpus > 0
        if args.use_cuda:
            args.cudas = [
                torch.device(f'cuda: {i}')
                for i in range(args.num_gpus)
            ]

        # getting group-related paths
        group = args.task
        args.group_dir = os.path.join(
            args.data_dir, getattr(args, group+'_root_dir'))
        for arg_name in args.dir_args[group]:
            path_arg = getattr(args, arg_name)
            setattr(args, arg_name.replace(group+'_', ''),
                    os.path.join(args.group_dir, path_arg))

        # building directories
        if args.mode == 'run-experiment':
            self.makedir_runExperiment(args)
        elif args.mode == 'build-dataset':
            self.makedir_buildDataset(args)
        elif args.mode == 'output-dataset':
            self.makedir_outputDataset(args)

        # dataset split
        args.split_ratio = dict(zip(
            ['train', 'val', 'test'],
            args.split_ratio
        ))

        return args

    def update(self, args):
        self.__dict__.update(args)

    @property
    def str(self):
        dicts = {k: str(v) for k, v in self.__dict__.items()}
        formatted = jacinle.kvformat(dicts)
        return formatted

    def makedir_runExperiment(self, args):
        args.local_log_dir = os.path.join(
            args.log_dir, args.model, args.task, args.name)
        args.cache_log_dir = os.path.join(args.log_dir, 'cache')

        if not args.silent and not is_empty(args.local_log_dir):
            cache_or_not(args.local_log_dir, args.cache_log_dir,
                         '.'.join([args.model, args.task]),
                         not args.pretrained)
        if not args.silent:
            make_dir(args.local_log_dir)

        if args.resume:
            if not args.silent:
                load_or_not(args.cache_log_dir, args.local_log_dir,
                            '.'.join([args.model, args.task]))
            args.ckpt_version = input(
                'Which version of ckpt you want to load? (default: `best`): '
            ) or 'best'
            if args.num_parallel == 1:
                args.ckpt_index = input(
                    'There is only one trial in your current run, what index '
                    'would you like to load? (default: 0): '
                ) or '0'
            else:
                args.ckpt_index = None

    def makedir_outputDataset(self, args):
        args.output_dir = os.path.join(
            args.group_dir, 'augmentation/questions',
            args.name)
        shutil.rmtree(args.output_dir, True)

    def makedir_buildDataset(self, args):
        pass

def cache_or_not(path, log_dir, tag, remove):
    if not yes_or_no(f'non-empty {path} detected, cache it?'):
        if remove:
            assert yes_or_no('The path will be removed, sure about it?')
            print('Removing the path')
            shutil.rmtree(path)
    else:
        print('Caching the folder')
        make_dir(log_dir)
        cache_dir = os.path.join(log_dir, tag)
        suffix = input('please specify the name for this cache:'
                       f' {cache_dir}.')
        if suffix != '':
            cache_dir = f'{cache_dir}.{suffix}'

        if os.path.exists(cache_dir):
            shutil.rmtree(cache_dir)
        if remove:
            shutil.move(path, cache_dir)
        else:
            copytree_verbose(path, cache_dir)

def load_or_not(cache_dir, target_dir, tag):
    if yes_or_no('Load previous cache as ckpt?'):
        shutil.rmtree(target_dir)
        sub_folders = os.listdir(cache_dir)
        contain_tag = list(filter(lambda x: tag in x, sub_folders))
        pprint(dict(enumerate(contain_tag)))
        index = int(input('Which folder would you choose? '))
        folder = os.path.join(cache_dir, contain_tag[index])
        copytree_verbose(folder, target_dir)


from db.booking import Booking
from db.calendar import Calendar
from db.customer import Customer
from datetime import datetime, timedelta
from app.auth import login_required

from flask import (
    Blueprint, flash, redirect, render_template, request, url_for, g
)

bp = Blueprint('booking', __name__, url_prefix='/booking')

@bp.route('/')
def index():
    booking = Booking.objects
    return booking.to_json()

@bp.route('/books', methods=['GET','POST'])
@login_required
def books():

    booked_nights = []
    listing_id = int(request.form.get('listing_id'))
    print("listing id: " + str(listing_id))
    nights = int(request.form.get('nights'))
    start_date = request.form.get('date')
    cal_list = Calendar.objects(listing_id=listing_id).all()
    customer = Customer.objects(id=g.user['id']).get()
    tot_price = 0

    night_tracker = nights

    d1 = datetime.strptime(start_date, "%Y-%m-%d")

    for listing in cal_list:
        d2 = datetime.strptime(listing.date, "%Y-%m-%d")
        if listing.date >= start_date and night_tracker > 0 and abs((d2-d1).days) < night_tracker:
            booked_nights.append(listing.date)
            listing.update(available="f")
            night_tracker -= 1
            tot_price += float(listing.price[1:])
        elif night_tracker == 0:
            break

    booking = Booking(
        customer_name=customer.first_name + " " + customer.last_name,
        customer_id=customer.id,
        listing_id=str(listing_id),
        listing_dates=booked_nights,
        total_price=tot_price,
        order_status="approved",
        order_date=datetime.now(),
    ).save()

    customer.update(add_to_set__orders=booking)

    print(g.user['id'])
    return render_template("kryptedbnb/booked.html", night_count=nights)


from pathlib import Path

def human_readable(bytes):
    """
    Function used for translating a large byte value into something people can
    actually read.
    """
    for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]:
        if bytes < 1024.0 or unit == "PiB":
            break
        bytes /= 1024.0

    return f"{bytes:.2f} {unit}"

def check_file_path_existence(path):
    """
    Checks if a given path exists.
    Path can be a string or a pathlib.Path object.

    They both get converted to pathlib.Path objects anyways...
    """
    temp = Path(path)
    if temp.exists():
        return True

    return False


#Hacking on CSV files!

import csv

import shutil
from tempfile import NamedTemporaryFile
#write a very basic CSV file

#+w means read/or/write and overwrite an existing file or create a new one
with open("templates/data.csv", "w+") as csvfile:
	writer = csv.writer(csvfile)
	writer.writerow(["Title", "Description"])
	writer.writerow(["Row 1", "Some descriptionm"])
	writer.writerow(["Row 2", "Some other kind of description"])

# Now to read our file we created in the code block above:
with open("templates/data.csv", "r") as csvfile:
	reader = csv.reader(csvfile)
	for row in reader:
		print(row)

#Using DictReader to open an existing csv file as a dictionary
with open("templates/books.csv", "r") as csvfile:
	reader = csv.DictReader(csvfile)
	for row in reader:
		print(row)

#Using append and DictWriter to add to an existing CSV file w/o overwriting things
with open("templates/books.csv", "a") as csvfile:
	#You have to provide a list of field names to properly map how the CSV will be read/written
	fieldnames = ["title", "author"]
	writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
	writer.writerow({"title": "1984", "author": "George Orwell"})

#as a challenge - try to abscract the last 2 code blocks into their own functions we can call repeatedly to inject data into a csv file.

def get_lenght(file_path):
	return 1
def append_books(file_path, title, author):
	return []

#Here's how to edit an existing csv file using temp files so
#you don't accidentally clobber your existing file contents

filename = "templates/books.csv"
tempfile = NamedTemporaryFile(delete=False)

#rb is used for writing/create new
with open(filename, "rb") as tempcsv, tempfile:
	reader = csv.DictReader(tempcsv)
	fieldnames = ["title", "author"]

	#Yes - you need to reference tempfile as your argument here
	writer = csv.DictWriter(tempfile, fieldnames=fieldnames)
	writer.writeheader()

	for row in reader:
		print(row)
		if (row["author"] == ""):
			row["author"] = "Unknown"
		writer.writerow(row)
#This next line copies our temp file to the exiting real file of books.csv
	shutil.move(tempfile.name, filename)

def get_author(author=None):
	filename = 'templates/books.csv'
	with open(filename, "r") as csvfile:
		reader = csv.DictReader(csvfile)
		items = []
		for row in reader:
			if author is not None:
				if author == row.get("author"):
					items.append(row)
		print("Boo yaaaa grandma!")
		print(items)

get_author("George Orwell")


tmp = input()
n, m = [int(i) for i in tmp.split(" ")]
arr = input()
arr = [int(i) for i in arr.split(" ")]
maxN = 300000
ff = [0 for i in range(maxN << 2)]
sum = [0 for i in range(maxN << 2)]
arr.insert(0, 0)

def pb(rt):
    if ff[rt] % 2 == 0:
        sum[rt] = sum[rt << 1 | 1] | sum[rt << 1]
    else:
        sum[rt] = sum[rt << 1 | 1] ^ sum[rt << 1]

def build(l, r, rt):
    sum[rt] = 0
    ff[rt << 1] = 0
    ff[rt << 1 | 1] = 0
    if l == r:
        sum[rt] = arr[l]
        ff[rt] = -1
        return
    mid = (l + r) >> 1
    build(l, mid, rt << 1)
    build(mid + 1, r, rt << 1 | 1)
    ff[rt] = ff[rt << 1] + 1
    pb(rt)

def update(l, r, p, d, rt):
    if l == r:
        sum[rt] = d
        return
    mid = (l + r) >> 1
    if p <= mid:
        update(l, mid, p, d, rt << 1)
    else:
        update(mid + 1, r, p, d, rt << 1 | 1)
    pb(rt)

num = 1 << n
ff[1] = 1
build(1, num, 1)
for i in range(m):
    tmp = input()
    u, v = [int(k) for k in tmp.split(" ")]
    update(1, num, u, v, 1)
    print(sum[1])


import re
from batchalign.document import *
from batchalign.utils import *

from batchalign.constants import ENDING_PUNCT

def retokenize(intermediate_output):
    """Retokenize the output of the ASR system from one giant blob to utterances

    Ideally, we'd split by utterances. For the custom-trained models that
    we ship with Batchalign, indeed that's what happens; they are trained to
    delineate sentences through utterance boundaries. However, for non-English
    ASR we rely on third party solutinos which doesn't have such facilities.

    Therefore, we at least split by sentences to get a relative tokenization.
    """

    final_outputs = []

    for speaker, utterance in intermediate_output:

        # we go through each of the words, and if the word is an
        # ending PUNCT, or if the word ENDS in a PUNCT, we split it out
        # as a sub-utterance
        tmp = []
        for word, bullet in utterance:
            tmp.append((word, bullet))
            if word in ENDING_PUNCT or word[-1] in ENDING_PUNCT:
                final_outputs.append((speaker, tmp))
                tmp = []

    return final_outputs

def retokenize_with_engine(intermediate_output, engine):
    """Retokenize `intermediate_input` given utterance engine `engine`

    This function is different from `retokenize` because it doesn't look
    at the original punctuation from the document at all; intsead, it retokenizes
    using a seperate utterance tokenization engine.

    Parameters
    ----------
    intermediate_output : List
        Rev.AI style output.

    engine : UtteranceEngine
        The utterance Engine to use.
    """

    final_outputs = []

    for speaker, utterance in intermediate_output:
        joined = " ".join([i[0] for i in utterance])
        split = engine(joined)

        # chop out the final delimiter and split
        split = [(i[:-1].split(" "), i[-1]) for i in split]

        # align the utterance against original splits and generate final outputs
        for new_ut, delim in split:
            tmp = []

            for _ in new_ut:
                tmp.append(utterance.pop(0))

            final_outputs.append((speaker, tmp+[[delim, [None, None]]]))

    return final_outputs

def process_generation(output, lang="eng", utterance_engine=None):
    """Process Rev.AI style ASR generation

    Parameters
    ----------
    output : dict
        The raw Rev.AI style output from your ASR engine.
    lang : str
        The language ID.
    utterance_engine : optional
        Utterance segmentation engine to use.

    Returns
    -------
    Document
        The reassembled document.
    """

    doc = Document()
    utterance_col = []

    for utterance in output["monologues"]:
        # get a list of words
        words = utterance["elements"]
        # coallate words (not punct) into the shape we expect
        # which is ['word', [start_ms, end_ms]]. Yes, this would
        # involve multiplying by 1000 to s => ms
        words = [[i["value"], [round(i["ts"]*1000),
                                round(i["end_ts"]*1000)]] # the shape
                for i in words # for each word
                    if i["type"] == "text" and
                    not re.match(r'<.*>', i["value"])] # if its text (i.e. not "pause")

        # sometimes, the system outputs two forms with a space as one single
        # word. we need to interpolate the space between them
        final_words = []
        # go through the words, if there is a space, split time in n parts
        for word, (i,o) in words:
            # split the word
            word_parts = word.split(" ")
            # if we only have one part, we don't interpolate
            if len(word_parts) == 1:
                final_words.append([word, [i,o]])
                continue
            # otherwise, we interpolate the itme
            cur = i
            div = (o-i)//len(word_parts)
            # for each part, add the start and end
            for part in word_parts:
                final_words.append([part.strip(), [cur, cur+div]])
                cur += div
        # if the final words is > 300, split into n parts
        if len(final_words) > 300:
            # for each group, append
            for i in range(0, len(final_words), 300):
                # concatenate with speaker tier and append to final collection
                # not unless the crop is empty
                if len(final_words[i:i+300]) > 0:
                    utterance_col.append((utterance["speaker"], final_words[i:i+300]))
        else:
            # concatenate with speaker tier and append to final collection
            if len(final_words) > 0:
                utterance_col.append((utterance["speaker"], final_words))

    # if we have an uttetrance engine, we will use that to retokenize; otherwise
    # we retokenize via scanning for punctation
    if utterance_engine:
        results = retokenize_with_engine(utterance_col, utterance_engine)
    else:
        results = retokenize(utterance_col)

    final_utterances = []
    for speaker, utterance in results:
        participant = Tier(lang=lang, corpus="corpus_name",
                           id=f"PAR{speaker}",
                           name=f"Participant")
        words = []
        for word, (start,end) in utterance:
            if word not in ENDING_PUNCT:
                words.append(Form(text=word, time=(int(start), int(end))))
            else:
                words.append(Form(text=word, time=None))

        final_utterances.append(Utterance(
            tier=participant,
            content = words
        ))

    doc.content = final_utterances
    doc.langs = [lang]

    return doc


"""copy is a new array which is a copy of original array and view is just a view of
original array. if any changes done in copy will not effect the original array, if
changes done in view will effect the original array. """

#make a copy change the original array and display both array
import numpy as np
from numpy.core.fromnumeric import ndim
arr1=np.array([1,2,3,4,5])
x=arr1.copy()
arr1[0]=10
print(arr1)
print(x)

#Make a view, change the original array and display both array.
arr2=np.array([2,4,6,8,10])
y=arr2.view()
arr2[1]=50
print(arr2)
print(y)

#Make a view, change the view and display both array
arr3=np.array([10,20,30,40])
z=arr3.view()
z[2]=100
print(arr3)
print(z)

#check array have own array using base method if array owns the data will return none
a=arr3.copy()
b=arr3.view()
print(a.base)
print(b.base)

"""Shape of an array: Shape of an array provides no. of elements in each dimension. it
returns a tuple with no. of its index having no. of corresponding elements. """
arr = np.array([[1, 2, 3, 4], [5, 6, 7,8]])
print(arr.shape)

"""Reshape of array: Reshaping means change the shape of an array. we know shape of an
array means no. of elements in each dimension. so through reshaping we can change it
means add or remove dimensions or change no. of elements in each dimension. """
#convert 1-D array into 2-D array with its 4 dimension having 3 elements each.
arr4 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
arr5=arr4.reshape(4,3)
print(arr5)

#convert 1-D into 3-D array will have 2 arrays that contains 3 array, each with 2 elements
arr6 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
arr7=np.array([[[1,2],[2,4]],[[5,6],[7,8]],[[9,10],[11,12]]])
arr8=np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]])
arr9=arr6.reshape(2,3,2)
arr10=arr6.reshape(3,2,2)
print(arr9)
print(arr10)

#convert multidimensional array into 1-D array we are using reshape(-1) methos
arr8=np.array([[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]])
arr11=arr8.reshape(-1)
print(arr11)

#convert 3-d into 2-d array
arr12=arr8.reshape(3,4)
print(arr12)

"""Numpy Array: Iterating: Iterating means going through elements one by one """
#Iterate on the elements of the following 1-D array
import numpy as np
arr13=np.array([2,4,6,8])
for x in arr13:
    print(x)

#Iterate the elements of 2-D array
arr14=np.array([[2,4,6,8],[10,12,14,16]])
for x in arr14:
    print(x)
    for y in x:
        print(y)

#Iterate elements of 3-D array
arr15=np.array([[[1,2,3,4,5],[6,7,8,9,10]],
[[11,12,13,14,15],[16,17,18,19,20]]])
print(arr15)
for x in arr15:
    print(x)

for a in arr15:
    for b in a:
        for c in b:
            print(c)

"""Iterating array using nditer(): this nditer() function can be used from basic to
advance iteration. in basic we are using for loop for n time and this is difficult to
write so we can use nditer() this will print each element of array"""

for x in np.nditer(arr15):
    print(x)

"""Enumerated Iteration using ndenumerate(): Enumerate means mentioning sequence number
of elements one by one. Sometime we have required corresponding index of elements while
itering. for this purpose we are using ndnumerate() function."""

#enumerate the following 1-D array
import numpy as np
arr16=np.array([2,4,6,8,10])
for indx, x in np.ndenumerate(arr16):
    print(indx,x)

#enumerate the 2-D array
arr17=np.array([[1,2,3,4,5],[2,4,6,8,10],[10,20,30,40,50]])
for indx,x in np.ndenumerate(arr17):
    print(indx,x)


import threading
import time
from collections import deque

aof_buf = deque()

def aof_handle():
    f = open('backup.aof', 'a+')
    while True:
        if len(aof_buf) > 0:
            req = aof_buf.popleft()
            f.write(str(req) + "\n")
            f.flush()
        else:
            time.sleep(0.1)

def start():
    t = threading.Thread(target=aof_handle, daemon=True)
    t.start()

def write_aof(data):
    aof_buf.append(data)


#import sys
#import os
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SeparableConv2D, DepthwiseConv2D
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Dense, Add, Activation, Dropout, Flatten, Conv2D, MaxPooling2D, LeakyReLU
from tensorflow.keras.layers import BatchNormalization, Lambda, Average
from tensorflow.keras.layers import Concatenate, UpSampling2D
from tensorflow.image import resize_nearest_neighbor
from tensorflow.keras import Model
from keras.utils.vis_utils import plot_model
from keras.utils.vis_utils import model_to_dot
from keras.engine.topology import get_source_inputs
# Import Own Lib
#sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
from depthwise_conv2d import DepthwiseConvolution2D

def _depthwise_convolution2D(input, alpha, deepwise_filter_size, kernel_size, strides, padding='same', bias=False):
    x= DepthwiseConvolution2D(int(deepwise_filter_size * alpha), kernel_size, strides=strides, padding=padding, use_bias=bias)(input)
    x= BatchNormalization()(x)
    x = LeakyReLU(alpha=0.1)(x)
    return  x

def _convolution2D(input, alpha, deepwise_filter_size, kernel_size, strides, padding='same', bias=False):
    x = Conv2D(int(deepwise_filter_size * alpha), kernel_size, strides=strides, padding=padding, use_bias=bias)(input)
    x = BatchNormalization()(x)
    x = LeakyReLU(alpha=0.1)(x)

    return x

def resize_like(input_tensor, ref_tensor, scale): # resizes input tensor wrt. ref_tensor
    H, W = ref_tensor.get_shape()[1], ref_tensor.get_shape()[2]
    return tf.image.resize_nearest_neighbor(input_tensor, [H.value*scale, W.value*scale])

class LightFlow():

    def __init__(self):
        pass

    @staticmethod
    def build(input_tensor = None, input_shape=None, plot=False):

        input_image = Input(shape=input_shape)
        concat_axis = 3
        alpha = 1.0

        #################################################
        # ENCODER
        #################################################

        # Conv1_dw / Conv1

        conv1_dw = _depthwise_convolution2D(input_image, alpha, 6,  (3, 3), strides=(2, 2))
        conv1 = _convolution2D(conv1_dw, alpha, 32, (1, 1), strides=(1, 1))

        # Conv2_dw / Conv2
        conv2_dw = _depthwise_convolution2D(conv1, alpha, 32,  (3, 3), strides=(2, 2))
        conv2 = _convolution2D(conv2_dw, alpha, 64, (1, 1), strides=(1, 1) )

        # Conv3_dw / Conv3
        conv3_dw = _depthwise_convolution2D(conv2, alpha, 64,  (3, 3), strides=(2, 2))
        conv3 = _convolution2D(conv3_dw, alpha, 128, (1, 1), strides=(1, 1))

        # Conv4a_dw / Conv4a
        conv4a_dw = _depthwise_convolution2D(conv3, alpha, 128,  (3, 3), strides=(2, 2))
        conv4a = _convolution2D(conv4a_dw, alpha, 256, (1, 1), strides=(1, 1) )

        # Conv4b_dw / Conv4b
        conv4b_dw = _depthwise_convolution2D(conv4a, alpha, 256,  (3, 3), strides=(1, 1))
        conv4b = _convolution2D(conv4b_dw, alpha, 256, (1, 1), strides=(1, 1))

        # Conv5a_dw / Conv5a
        conv5a_dw = _depthwise_convolution2D(conv4b, alpha, 256,  (3, 3), strides=(2, 2))
        conv5a = _convolution2D(conv5a_dw, alpha, 512, (1, 1), strides=(1, 1))

        # Conv5b_dw / Conv5b
        conv5b_dw = _depthwise_convolution2D(conv5a, alpha, 512,  (3, 3), strides=(1, 1))
        conv5b = _convolution2D(conv5b_dw, alpha, 512, (1, 1), strides=(1, 1))

        # Conv6a_dw / Conv6a
        conv6a_dw = _depthwise_convolution2D(conv5b, alpha, 512,  (3, 3), strides=(2, 2))
        conv6a = _convolution2D(conv6a_dw, alpha, 1024, (1, 1), strides=(1, 1))

        # Conv6b_dw / Conv6b
        conv6b_dw = _depthwise_convolution2D(conv6a, alpha, 1024,  (3, 3), strides=(1, 1))
        conv6b =  _convolution2D(conv6b_dw, alpha, 1024, (1, 1), strides=(1, 1))

        #################################################
        # DECODER
        #################################################

        # Conv7_dw / Conv7
        conv7_dw =  _depthwise_convolution2D(conv6b, alpha, 1024,  (3, 3), strides=(1, 1))
        conv7 = _convolution2D(conv7_dw, alpha, 256, (1, 1), strides=(1, 1))

        # Conv8_dw /Conv8
        conv7_resized_tensor = Lambda(resize_like, arguments={'ref_tensor':conv7, 'scale': 2})(conv7)
        concat_op1 = Concatenate(axis=concat_axis)([conv7_resized_tensor, conv5b])

        conv8_dw = _depthwise_convolution2D(concat_op1, alpha, 768,  (3, 3), strides=(1, 1))
        conv8 = _convolution2D(conv8_dw, alpha, 128, (1, 1), strides=(1, 1))

        # Conv9_dw /Conv9
        conv8_resized_tensor = Lambda(resize_like, arguments={'ref_tensor':conv8, 'scale': 2})(conv8)
        concat_op2 = Concatenate(axis=concat_axis)([conv8_resized_tensor, conv4b])

        conv9_dw = _depthwise_convolution2D(concat_op2, alpha, 384, (3,3), strides=(1,1))
        conv9 = _convolution2D(conv9_dw, alpha, 64, (1,1), strides=(1,1))

        # Conv10_dw / Conv10
        coonv9_resized_tensor = Lambda(resize_like, arguments={'ref_tensor':conv9, 'scale': 2})(conv9)
        concat_op3 = Concatenate(axis=concat_axis)([coonv9_resized_tensor, conv3])

        conv10_dw = _depthwise_convolution2D(concat_op3, alpha, 192, (3,3), strides=(1,1))
        conv10 = _convolution2D(conv10_dw, alpha, 32, (1,1), strides=(1,1))

        # Conv11_dw / Con11
        conv10_resized_tensor = Lambda(resize_like, arguments={'ref_tensor':conv10, 'scale': 2})(conv10)
        concat_op3 = Concatenate(axis=concat_axis)([conv10_resized_tensor, conv2])

        conv11_dw = _depthwise_convolution2D(concat_op3, alpha, 96, (3,3), strides=(1,1))
        conv11 = _convolution2D(conv11_dw, alpha, 16, (1,1), strides=(1,1))

        ##################################################
        # Optical Flow Predictions
        ##################################################

        # Conv12_dw / conv12
        conv12_dw = _depthwise_convolution2D(conv7, alpha, 256, (3,3), strides = (1,1))
        conv12 = _convolution2D(conv12_dw, alpha, 2, (1,1), strides=(1,1))

        # Conv13_dw / conv13
        conv13_dw = _depthwise_convolution2D(conv8, alpha, 128, (3,3), strides = (1,1))
        conv13 = _convolution2D(conv13_dw, alpha, 2, (1,1), strides=(1,1))

        # Conv14_dw / conv14
        conv14_dw = _depthwise_convolution2D(conv9, alpha, 64, (3,3), strides=(1,1))
        conv14 = _convolution2D(conv14_dw, alpha, 2, (1,1), strides=(1,1))

        # Conv15_dw / con15
        conv15_dw = _depthwise_convolution2D(conv10, alpha, 32, (3,3), strides=(1,1))
        conv15 = _convolution2D(conv15_dw, alpha, 2, (1,1), strides=(1,1))

        # Conv16_dw / conv16
        conv16_dw = _depthwise_convolution2D(conv11, alpha, 16, (3,3), strides=(1,1))
        conv16 = _convolution2D(conv16_dw, alpha, 2, (1,1), strides=(1,1))

        ###################################################
        # Multiple Optical Flow Predictions Fusion
        ###################################################

        conv12_resized_tensor_x16 = Lambda(resize_like, arguments={'ref_tensor':conv12, 'scale': 16})(conv12)
        conv13_resized_tensor_x8 = Lambda(resize_like, arguments={'ref_tensor':conv13, 'scale': 8})(conv13)
        conv14_resized_tensor_x4 = Lambda(resize_like, arguments={'ref_tensor':conv14, 'scale': 4})(conv14)
        conv15_resized_tensor_x2 = Lambda(resize_like, arguments={'ref_tensor':conv15, 'scale': 2})(conv15)

        # 96x128x2
        average = Average()([conv12_resized_tensor_x16,
                                conv13_resized_tensor_x8,
                                conv14_resized_tensor_x4,
                                conv15_resized_tensor_x2,
                                conv16])

        # Fuse GT with prediction
        average = Lambda(resize_like, arguments={'ref_tensor':average, 'scale': 4})(average)
        # Ensure that the model takes into account
        # any potential predecessors of `input_tensor`.
        if input_tensor is not None:
            input_image = get_source_inputs(input_tensor)
        else:
            pass

        # Create model for debug
        model = Model(inputs=input_image, outputs=average, name='lightflow')

        return model

def main(plot = True):
    INPUT_SHAPE = (384, 512,6)
    model = LightFlow.build(input_shape=INPUT_SHAPE)
    if plot is True:
        plot_model(model, to_file='LightFLow.png', show_shapes=True)
        #model_to_dot(model, show_shapes=True, show_layer_names=True, rankdir='TB').create(prog='dot', format='svg')
    print(model.summary())

if __name__ == '__main__':
    main()


"""Day X"""

from dataclasses import dataclass, field
import os
import pytest
from typing import List, Dict, Callable, Optional

INPUT = """addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop"""

@dataclass
class Proc:
    instr: List[str]
    pc: int = 0
    reg_x: int = 1
    clock: int = 1
    pending: Optional[int] = None

    def addx(self, n: str):
        self.pending = int(n)

    def noop(self):
        pass

    def tick(self) -> int:
        retval = self.reg_x
        if self.pending is not None:
            self.reg_x += self.pending
            self.pending = None
        else:
            instr = self.instr[self.pc]
            op, *args = instr.split(" ")
            getattr(self, op)(*args)
            self.pc += 1
        self.clock += 1
        return retval

    def watch(self, points: List[int]) -> int:
        seen = []
        track = sorted(points)
        next_i = 0
        while self.clock < track[-1]:
            self.tick()
            if self.clock >= track[next_i]:
                next_i += 1
                print(f"{self.clock} {self.reg_x} : {self.clock * self.reg_x}")
                seen.append(self.reg_x * self.clock)
        return sum(seen)

    def draw(self) -> str:
        out = []
        self.pc = 0
        self.clock = 1
        self.reg_x = 1
        self.pending = None

        while self.pc < len(self.instr):
            x_pos = self.tick()
            char = (self.clock - 2) % 40
            visible = False
            if char == 0 and self.clock > 3:
                out.append("\n")
            if char - 1 <= x_pos <= char + 1:
                visible = True
                out.append("#")
            else:
                out.append(".")
            # print(f"{self.clock - 1} {char} {self.reg_x} {visible}")
        return "".join(out)

@pytest.fixture
def example() -> List[str]:
    return [i.strip() for i in INPUT.splitlines()]

def test_example(example):
    ex = Proc(example)
    out = ex.watch([20, 60, 100, 140, 180, 220])
    assert out == 13140
    assert (
        ex.draw()
        == """##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######....."""
    )

def part1(inputs: List[str]) -> int:  # pylint: disable=unused-argument
    proc = Proc(inputs)
    return proc.watch([20, 60, 100, 140, 180, 220])

def test_part1() -> None:
    inputs = get_inputs()
    assert part1(inputs) == 17940

def part2(inputs: List[str]) -> int:  # pylint: disable=unused-argument
    out = Proc(inputs).draw()
    print(out)
    return out

def test_part2() -> None:
    inputs = get_inputs()
    assert (
        part2(inputs)
        == """####..##..###...##....##.####...##.####.
...#.#..#.#..#.#..#....#.#.......#....#.
..#..#....###..#..#....#.###.....#...#..
.#...#....#..#.####....#.#.......#..#...
#....#..#.#..#.#..#.#..#.#....#..#.#....
####..##..###..#..#..##..#.....##..####."""
    )

def get_inputs() -> List[str]:
    base, _ = os.path.splitext(os.path.basename(__file__))
    if os.path.exists(base + ".txt"):
        return [i.strip() for i in open(base + ".txt")]
    return []

def test_get_inputs() -> None:
    inputs = get_inputs()
    assert len(inputs) > 0

if __name__ == "__main__":
    test_get_inputs()
    inputs = get_inputs()
    print(part1(inputs))
    test_part1()
    print(part2(inputs))
    test_part2()


from sys import stdin, stdout
from math import ceil
t = int(stdin.readline())
bands = [
    (180000, 0),
    (300000, 0.1),
    (400000, 0.15),
    (300000, 0.20),
    (1000000000, 0.25)]
def tax(income, band):
    if income <= 0:
        return 0
    taxable = min(income, bands[band][0]) * bands[band][1] + tax(income - bands[band][0], band + 1)
    #print taxable
    return taxable
for tc in range(1, t+1):
    k = int(stdin.readline())
    taxable = ceil(tax(k, 0))
    if taxable > 0:
        taxable = max(2000, int(taxable))
    else:
        taxable = 0
    stdout.write('Case {}: {}\n'.format(tc, taxable))


from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^about\-us/', include('about_us.urls')),
    url(r'^$', 'about_us.views.home', name='home'),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^assets/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
   )


# -*- coding: utf-8 -*-
from collections import deque

from cadnano.undocommand import UndoCommand

class UndoStack(object):
    def __init__(self, limit: int = 10):
        self.undostack = deque()    # not using deque maxlen because pattern is awkward
        self.redostack = []
        self.limit = limit

        self.top_macro = None
        self.current_macro = None
        self.macro_stack = []
        self.macro_count = 0
    # end def

    def push(self, undocommand: UndoCommand):
        if self.macro_count > 0:
            self.current_macro.addCommand(undocommand)
        else:
            self.appendUndoStack(undocommand)
    # end def

    def appendUndoStack(self, undocommand: UndoCommand):
        stack = self.undostack
        stack.append(undocommand)
        undocommand.redo()
        if len(stack) > self.limit:
            stack.popleft()
    # end def

    def beginMacro(self, message: str):
        new_macro = UndoCommand(message)
        if self.current_macro is not None:
            self.macro_stack.append(self.current_macro)
        self.current_macro = new_macro
        if self.macro_count == 0:
            self.top_macro = new_macro
        self.macro_count += 1
        # print('b', new_macro, self.macro_count)
    # end def

    def endMacro(self):
        self.macro_count -= 1
        try:
            self.current_macro = self.macro_stack.pop()
        except Exception:
            self.current_macro = None
        # print('e', self.current_macro self.macro_count)
        if self.macro_count == 0:
            self.appendUndoStack(self.top_macro)
    # end def

    def undo(self):
        if self.canUndo():
            undo_cmd = self.undostack.pop()
            undo_cmd.undo()
            self.redostack.append(undo_cmd)
    # end def

    def redo(self):
        if self.canRedo():
            redo_cmd = self.redostack.pop()
            redo_cmd.redo()
            self.undostack.append(redo_cmd)
    # end def

    def canUndo(self) -> bool:
        return True if len(self.undostack) > 0 else False
    # end def

    def canRedo(self) -> bool:
        return True if len(self.redostack) > 0 else False
    # end def

    def setUndoLimit(self, lim: int):
        self.limit = lim
    # end def


import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = x**2
y2 = x*3+1

plt.figure(num=1)
l1, = plt.plot(x, y2, label='liner')
l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='square')

plt.xlim(-4, 3)
plt.ylim(-1, 10)
plt.xlabel('X axis')
plt.ylabel('Y axis')
new_ticks = np.linspace(-4, 3, 15)
plt.xticks(new_ticks)
plt.yticks([-1, 0, 1.3, 8], [r'$really\ bad$', r'$bad$', r'$good$', r'$really\ good$'])
# to use '$ $' for math text and nice looking, e.g. '$\pi$'

# gca = 'get current axis'
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')# ACCEPTS: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ]
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))# data: depend on y data
ax.spines['left'].set_position(('data', 0))

plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='upper left')
"""legend( handles=(line1, line2, line3),
           labels=('label1', 'label2', 'label3'),
           'upper right')
    The *loc* location codes are::
          'best' : 0,          (currently not supported for figure legends)
          'upper right'  : 1,
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,"""

plt.show()


import numpy as np
import sympy as sp
from sympy.utilities.lambdify import lambdify

class Single_Vehicle_Model:

    def __init__(self, parameter) -> None:
        """
        state: [x, y, theta] where x, y are the in the rear axis
        current pose: [x + l * cos(theta) y + l * sin(theta), theta]
        control: [v, w]

        for symbolic:
        state: [x, y, theta]
        robot_end_state: [x, y, theta]

        for collision avoidance:
        robot_state: [x, y, theta, radius]

        obstacle_state: [o_x, o_y, o_radius]
        """
        # system states
        self.state_dim = 3
        self.control_dim = 2

        x, y, theta = sp.symbols('x y theta')
        robot_radius = sp.Symbol('robot_radius')
        self.state = sp.Matrix([x, y, theta])
        self.robot_state = sp.Matrix([x, y, theta, robot_radius])
        self.l = parameter['l']
        self.margin = parameter['margin']

        e_x, e_y, e_theta = sp.symbols('e_x e_y e_theta')
        self.target_state = sp.Matrix([e_x, e_y, e_theta])

        o_x, o_y, o_radius = sp.symbols('o_x, o_y, o_radius')
        self.obstacle_state = sp.Matrix([o_x, o_y, o_radius])
        self.obstacle_status = sp.Matrix([o_x, o_y])

        o_vx, o_vy = sp.symbols('o_vx, o_vy')
        self.obstacle_dynamics = sp.Matrix([o_vx, o_vy])

        # system dynamics and clf, cbf
        self.f = None
        self.f_symbolic = None

        self.g = None
        self.g_symbolic = None

        # CLF
        self.clf = None
        self.clf_symbolic = None

        # Lie derivative of clf w.r.t f / g as a function
        self.dx_clf = None
        self.dx_clf_symbolic = None
        self.lf_clf = None
        self.lf_clf_symbolic = None
        self.lg_clf = None
        self.lg_clf_symbolic = None

        # target dynamics, for trajectory tracking
        # To do
        self.dtarget_clf = None
        self.dtarget_clf_symbolic = None
        self.dt_clf = None
        self.dt_clf_symbolic = None

        # CBF
        self.cbf = None
        self.cbf_symbolic = None

        # Lie derivative of cbf w.r.t f / g as a function
        self.dx_cbf = None
        self.dx_cbf_symbolic = None
        self.lf_cbf = None
        self.lf_cbf_symbolic = None
        self.lg_cbf = None
        self.lg_cbf_symbolic = None

        # dcbf / dt, time derivative of other items
        self.dox_cbf = None
        self.dox_cbf_symbolic = None
        self.dt_cbf = None
        self.dt_cbf_symbolic = None

        self.init_system()

    def init_system(self):

        # Define the system dynamics, CLF and CBF in a symbolic way
        self.f_symbolic, self.g_symbolic = self.define_system_dynamics()
        self.f = lambdify([self.state], self.f_symbolic)
        self.g = lambdify([self.state], self.g_symbolic)

        # choose for a type of clf
        self.clf_symbolic = self.define_clf_cross_term()
        # self.clf_symbolic = self.define_clf_rear()
        # self.clf_symbolic = self.define_clf_center()
        self.clf = lambdify([self.state, self.target_state], self.clf_symbolic)

        self.cbf_symbolic = self.define_cbf()
        # self.cbf_symbolic = self.define_cbf_center()
        self.cbf = lambdify([self.robot_state, self.obstacle_state], self.cbf_symbolic)

        self.lie_derivatives_calculator()
        self.time_differential_cbf()

    def define_system_dynamics(self):
        f = sp.Matrix([0, 0, 0])
        g = sp.Matrix([[sp.cos(self.state[2]), 0], [sp.sin(self.state[2]), 0], [0, 1]])
        return f, g

    def define_clf_center(self):
        """
        define the clf with the center position of robot
        x = x_p + l * cos(theta)
        y = y_p + l * sin(theta)
        """
        H = sp.Matrix([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.1]])
        relative_x = self.state[0] - self.target_state[0]
        relative_y = self.state[1] - self.target_state[1]
        relative_orientation = self.state[2] - self.target_state[2]

        relative_state = sp.Matrix([relative_x, relative_y, relative_orientation])
        clf = (relative_state.T @ H @ relative_state)[0, 0]
        return clf

    def define_clf_rear(self):
        """
        define the clf with the center position of robot represented by the rear
        x = x_p + l * cos(theta)
        y = y_p + l * sin(theta)
        """
        H = sp.Matrix([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]])
        relative_x = self.state[0] + self.l * (sp.cos(self.state[2]) - sp.cos(self.target_state[2])) - self.target_state[0]
        relative_y = self.state[1] + self.l * (sp.sin(self.state[2]) - sp.sin(self.target_state[2])) - self.target_state[1]
        relative_orientation = self.state[2] - self.target_state[2]

        relative_state = sp.Matrix([relative_x, relative_y, relative_orientation])
        clf = (relative_state.T @ H @ relative_state)[0, 0]
        return clf

    def define_clf_cross_term(self):
        """ define the clf with croos term """
        relative_x = self.state[0] - self.target_state[0]
        relative_y = self.state[1] - self.target_state[1]
        relative_orientation = self.state[2] - self.target_state[2]
        H = sp.Matrix([[1.00, 0.00, 0.05],
                       [0.00, 1.00, 0.05],
                       [0.05, 0.05, 0.26]])  # 0.26 static # 0.45 dynamic

        relative_state = sp.Matrix([relative_x, relative_y, relative_orientation])
        clf = (relative_state.T @ H @ relative_state)[0, 0]
        return clf

    def time_differential_clf_center(self):
        """ contain the differential of the target position """
        self.dtarget_clf_symbolic = sp.Matrix([self.clf_symbolic]).jacobian(self.target_state)
        self.dtarget_clf = lambdify([self.state, self.target_state], self.dx_clf_symbolic)

        # only change the x coordinate
        self.dt_clf_symbolic = (self.dtarget_clf_symbolic @ sp.Matrix([0.5, 0, 0]))[0, 0]
        self.dt_clf = lambdify([self.state, self.target_state], self.dt_clf_symbolic)

    def define_cbf(self):
        """ with rear axis """
        relative_x = self.robot_state[0] + self.l * sp.cos(self.robot_state[2]) - self.obstacle_state[0]
        relative_y = self.robot_state[1] + self.l * sp.sin(self.robot_state[2]) - self.obstacle_state[1]
        cbf = relative_x ** 2 + relative_y ** 2 - (self.robot_state[3] + self.obstacle_state[2] + self.margin) ** 2
        return cbf

    def define_cbf_center(self):
        """ with center """
        relative_x = self.robot_state[0] - self.obstacle_state[0]
        relative_y = self.robot_state[1] - self.obstacle_state[1]
        cbf = relative_x ** 2 + relative_y ** 2 - (self.robot_state[3] + self.obstacle_state[2] + self.margin) ** 2
        return cbf

    def lie_derivatives_calculator(self):

        # dx_clf, lf_clf, lg_clf shape in (1, 3) and (1, 1) (1, u_dim)
        self.dx_clf_symbolic = sp.Matrix([self.clf_symbolic]).jacobian(self.state)
        self.dx_clf = lambdify([self.state, self.target_state], self.dx_clf_symbolic)

        self.lf_clf_symbolic = (self.dx_clf_symbolic @ self.f_symbolic)[0, 0]
        self.lf_clf = lambdify([self.state, self.target_state], self.lf_clf_symbolic)

        self.lg_clf_symbolic = self.dx_clf_symbolic @ self.g_symbolic
        self.lg_clf = lambdify([self.state, self.target_state], self.lg_clf_symbolic)

        # dx_cbf, lf_cbf, lg_cbf shape in (1, 3) and (1, 1) (1, u_dim)
        self.dx_cbf_symbolic = sp.Matrix([self.cbf_symbolic]).jacobian(self.state)
        self.dx_cbf = lambdify([self.state, self.obstacle_state], self.dx_cbf_symbolic)

        self.lf_cbf_symbolic = (self.dx_cbf_symbolic @ self.f_symbolic)[0, 0]
        self.lf_cbf = lambdify([self.state, self.obstacle_state], self.lf_cbf_symbolic)

        self.lg_cbf_symbolic = self.dx_cbf_symbolic * self.g_symbolic
        self.lg_cbf = lambdify([self.state, self.obstacle_state], self.lg_cbf_symbolic)

    def time_differential_cbf(self):
        """ calculate the other terms of cbf: dcbf / dt, and obstacle.dynamics as additional parameter """
        self.dox_cbf_symbolic = sp.Matrix([self.cbf_symbolic]).jacobian(self.obstacle_status)
        self.dox_cbf = lambdify([self.state, self.obstacle_state], self.dox_cbf_symbolic)

        self.dt_cbf_symbolic = (self.dox_cbf_symbolic @ self.obstacle_dynamics)[0, 0]
        self.dt_cbf = lambdify([self.state, self.obstacle_state, self.obstacle_dynamics], self.dt_cbf_symbolic)

    def __str__(self) -> str:
        return f'Class contains the states {self.state}, \n' + \
                f'system dynamic f {self.f} and g {self.g} \n' \
                f'CBF {self.cbf}, \n'

    def dynamic(self, x, u):
        return self.f(x) + self.g(x) @ np.array(u).reshape(self.control_dim, -1)

    def get_next_state(self, current_state, u, dt):
        """ Fourth-order Rungekutta method """
        f1 = self.dynamic(current_state, u).T[0]
        f2 = self.dynamic(current_state + dt * f1 / 2, u).T[0]
        f3 = self.dynamic(current_state + dt * f2 / 2, u).T[0]
        f4 = self.dynamic(current_state + dt * f3, u).T[0]

        next_state = current_state + dt / 6 * (f1 + 2 * f2 + 2 * f3 + f4)
        return next_state

    def next_state(self, current_state, u, dt):
        """ simple one step """
        next_state = current_state
        next_state = next_state + dt * (self.f(current_state).T[0] + (self.g(current_state) @ np.array(u).reshape(self.control_dim, -1)).T[0])

        return next_state

if __name__ == "__main__":
    test_target = Single_Vehicle_Model({'l': 0.1, 'margin': 0.05})

    # print(test_target.cbf(np.array([0.5, 0.5, np.pi/3, 0.3]), [2.0, 2.0, 0.3]))
    # print(test_target.dx_cbf([0.5, 0.5, np.pi/3], [2.0, 2.0, 0.3]))
    # print(test_target.lf_cbf([0.5, 0.5, np.pi/3], [2.0, 2.0, 0.3]))
    # print(test_target.lg_cbf([0.5, 0.5, np.pi/3], [2.0, 2.0, 0.3]))
    print(test_target.dox_cbf([0.5, 0.5, np.pi/3], [2.0, 2.0, 0.3]))
    print(test_target.dt_cbf([0.5, 0.5, np.pi/3], [2.0, 2.0, 0.3], [0.5, 0.28]))

    # print(test_target.clf([0.5, 0.5, 0], [2.0, 2.0, 0]))
    # print(test_target.dx_clf([0.5, 0.5, 0], [2.0, 2.0, 0]))
    # print(test_target.lf_clf([0.5, 0.5, 0], [2.0, 2.0, 0]))
    # print(test_target.lg_clf([0.5, 0.5, 0], [2.0, 2.0, 0]))


#!C:\python\python.exe
#-*- coding: utf-8 -*-
#處理stdio輸出編碼，以避免亂碼
import codecs, sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
import cgi
import shop1 as sp
#連線DB
from dbConfig import conn, cur
#先印出http 表頭
print("Content-Type: text/html; charset=utf-8\n")
print("""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>範例1</title>

""")

#查詢
form = cgi.FieldStorage()
number=form.getvalue('num')
Price=form.getvalue('pr')
Name=form.getvalue('na')
sp.addNew(Name,number,Price)

print("商品已存入!")
print("
回管理端")
print("")


import basicFunction as basic
import sensitivyParameter as globalV

class arc(object):
    def __init__(self, ID, arcLength, downNode=None):
        self.ID = ID
        self.downstreamNode = downNode
        self.length = arcLength * 1000
        self.capacity = arcLength / (2 * globalV.vehicleEffectiveLength)  # max number of vehicles that can stay
        self.vehicles = []

    def clear(self):
        self.vehicles.clear()

    def timeDepartureArc(self, aimVehicle, timeArrival, timeDeparturePrvious,
                         delayTime):  # time for ith vehicle to leave the arc
        time1 = timeArrival + (self.length / aimVehicle.desiredSpeed)
        time2 = timeDeparturePrvious + (
                aimVehicle.reactionTime + (aimVehicle.effectiveLength / aimVehicle.desiredSpeed))
        res = basic.getMaximum2(time1, time2)
        return res + delayTime

    def timeDepartureArcFirst(self, aimVehicle, timeArrival):  # time for the first vehicle to leave the arc
        return timeArrival + (self.length / aimVehicle.desiredSpeed)

    def getDelay(
            self):  # the delay time for the next vehicle, only dependent on the number of vehicles currently in the arc
        numVehicle = len(self.vehicles)
        currentSpeed = (self.capacity - numVehicle) / self.capacity * globalV.revisedDesiredSpeed  # in km/h
        delayedSpeed = globalV.revisedDesiredSpeed * 0.277778 - currentSpeed
        return self.length / delayedSpeed  # in sec


from tkinter import *
import tkinter as tk

class ViewReportPage(tk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        self.parent = parent
        self.controller = controller
        self.initUI()

    def initUI(self):
        label_title = Label(self, text="View Report", font=("Sans-serif", 30))
        label_title.pack(side=TOP, anchor='w', padx=10, pady=10)
        label_description = Label(self, text="Please choose which report you want to reivew:", font=("Sans-serif", 20))
        label_description.pack(side=TOP, anchor='w', padx=10, pady=10)

        view_report1_label = Label(self, text="Top 25 popular manufacturers", fg="blue", cursor="hand2", font=("Sans-serif", 15,"underline"))
        view_report1_label.pack(side=TOP, anchor='w', padx=10, pady=10)
        view_report1_label.bind("<Button-1>", lambda event: self.controller.display("Report1"))

        view_report2_label = Label(self, text="Manufacturer/model search", fg="blue", cursor="hand2", font=("Sans-serif", 15,"underline"))
        view_report2_label.pack(side=TOP, anchor='w', padx=10, pady=10)
        view_report2_label.bind("<Button-1>", lambda event: self.controller.display("Report2"))

        view_report3_label = Label(self, text="Heating/cooling method details", fg="blue", cursor="hand2", font=("Sans-serif", 15,"underline"))
        view_report3_label.pack(side=TOP, anchor='w', padx=10, pady=10)
        view_report3_label.bind("<Button-1>", lambda event: self.controller.display("Report3"))

        view_report4_label = Label(self, text="Water heater statistics by state", fg="blue", cursor="hand2", font=("Sans-serif", 15,"underline"))
        view_report4_label.pack(side=TOP, anchor='w', padx=10, pady=10)
        view_report4_label.bind("<Button-1>", lambda event: self.controller.display("Report4"))

        view_report5_label = Label(self, text="Off-the-grid household dashboard", fg="blue", cursor="hand2", font=("Sans-serif", 15,"underline"))
        view_report5_label.pack(side=TOP, anchor='w', padx=10, pady=10)
        view_report5_label.bind("<Button-1>", lambda event: self.controller.display("Report5"))

        view_report6_label = Label(self, text="Household averages by radius", fg="blue", cursor="hand2", font=("Sans-serif", 15,"underline"))
        view_report6_label.pack(side=TOP, anchor='w', padx=10, pady=10)
        view_report6_label.bind("<Button-1>", lambda event: self.controller.display("Report6"))


from apprise.Apprise import Apprise
from monitor.database import session
from monitor.database.queries import get_plot_count
from monitor.format import *
from monitor.notifications.notification import Notification

class LostPlotsNotification(Notification):
    last_plot_count: int
    highest_plot_count: int
    alert_threshold: int

    def __init__(self, apobj: Apprise, alert_threshold: int) -> None:
        super().__init__(apobj)
        self.last_plot_count = None
        self.highest_plot_count = None
        self.alert_threshold = alert_threshold

    def condition(self) -> bool:
        with session() as db_session:
            self.last_plot_count = get_plot_count(db_session)

        if self.last_plot_count is not None and self.highest_plot_count is not None and self.last_plot_count < self.highest_plot_count - self.alert_threshold:
            return True
        else:
            self.highest_plot_count = self.last_plot_count
            return False

    def trigger(self) -> None:
        return self.apobj.notify(title='** ðŸš¨ Farmer Lost Plots! ðŸš¨ **',
                                 body="It seems like your farmer lost some plots\n" +
                                 f"Expected: {self.highest_plot_count}, Found: {self.last_plot_count}\n")

    def recover(self) -> None:
        return self.apobj.notify(title='** âœ… Farmer Plots recoverd! âœ… **',
                                 body="Your farmer's plot count has recovered to its previous value")


from core.logger.singleton_logger import SingletonLogger
from core.rest_client.request_manager import *
from jsonschema.validators import Draft7Validator

import json
logger = SingletonLogger().get_logger()

class Story_Helper:

    @staticmethod
    def create_stories(project_id):
        '''
        Create stories for a project
        :return: Project Json
        '''
        client = RequestManager()
        client.set_method('POST')
        client.set_endpoint('/projects/' + str(project_id) + '/stories')
        body = {"name": "Project Test"}
        client.set_body(json.dumps(body))
        response = client.execute_request()
        return response.json()

    @staticmethod
    def put_stories(id_project, id_stories):
        '''
        Update project with the labels
        :return: Project Json
        '''
        client = RequestManager()
        client.set_method('PUT')
        client.set_endpoint('/projects/' + str(id_project) + '/stories/' + str(id_stories))
        client.set_body(
            """
            {"labels":[{"name":"test label 1"}]}
            """
        )
        response = client.execute_request()
        return response.json()['labels']

    @staticmethod
    def delete_story(id_project, id_stories):
        '''
        Delete storie of a  project
        :param response: Json
        '''
        print("Eliminando el proyecto ")
        client = RequestManager()
        client.set_method('DELETE')
        client.set_endpoint('/projects/' + str(id_project) + "/stories/" + str(id_stories))
        client.execute_request()

    @staticmethod
    def account_me():
        '''
        Get my account id
        :return: Stories Json
        '''
        client = RequestManager()
        client.set_method('GET')
        client.set_endpoint('/me')
        response = client.execute_request()
        return response.json()

    @staticmethod
    def get_all_stories(id_project):
        '''
        Get all stories of a project
        :param id: Integer
        :return: Stories Json
        '''
        client = RequestManager()
        client.set_method('GET')
        client.set_endpoint('/projects/' + str(id_project) + "/stories")
        response = client.execute_request()
        return response.json()


import h5py
import numpy as np
import argparse

def main(raw_args=None):

    # argument parser
    parser = argparse.ArgumentParser(description="Save scan in single H5 file.")
    parser.add_argument(
        "-i", "--input", type=str, action="store", help="hdf5 input file"
    )
    parser.add_argument(
        "-m",
        "--scan_mode",
        type=int,
        action="store",
        help="magnet scan 0 pump and probe 1",
    )
    parser.add_argument(
        "-fi",
        "--first_index",
        type=int,
        action="store",
        help="first index file of the scan",
    )
    parser.add_argument(
        "-fp",
        "--first_pos",
        type=float,
        action="store",
        help="first corresponding parameter on scan",
    )
    parser.add_argument(
        "-li",
        "--last_index",
        type=int,
        action="store",
        help="last index file of the scan",
    )
    parser.add_argument(
        "-lp",
        "--last_pos",
        type=float,
        action="store",
        help="last corresponding parameter on scan",
    )
    parser.add_argument(
        "-s",
        "--step",
        type=float,
        action="store",
        help="parameter step between file index",
    )
    parser.add_argument(
        "-t0",
        "--t_zero",
        type=float,
        action="store",
        help="t0 motor scan position in mm for pump and probe experiments",
    )
    parser.add_argument(
        "-r",
        "--radial_sub",
        type=int,
        action="store",
        help="perform radial subtraction",
    )
    parser.add_argument(
        "-o", "--output", type=str, action="store", help="output label .h5 file"
    )
    args = parser.parse_args(raw_args)

    delay_step = round((3.33 / 0.5) * float(args.step), 2)

    if args.scan_mode == 0:
        size = np.arange(args.first_index, args.last_index + 1, 1)
        start = args.first_pos - args.t_zero
        finish = args.last_pos - args.t_zero
        label = np.arange(start, finish + 0.1, args.step)
        # label=np.around(label,3)
        print(label)
    else:
        if float(args.last_pos) > float(args.first_pos):
            size = np.arange(args.first_index, args.last_index + 1, 1)
            start = -1 * (args.last_pos - args.t_zero) * 6.6666
            finish = (args.t_zero - args.first_pos) * 6.6666
            label = np.flip(np.arange(start, finish + 0.1, delay_step))

    n = round(len(size) / 2)

    count = 0
    for i in label:
        if abs(i) < 1e-3:
            label[count] = 0.0
        count += 1

    f = h5py.File(args.output + ".h5", "w")
    stamps = []
    for idx, i in enumerate(size):
        print(label)
        file_path = f"{args.input}_{i}.h5"
        hf = h5py.File(file_path, "r")
        if args.radial_sub == 1:
            data_name = "rad_sub"
        else:
            data_name = "rad_average_mask"
        rad_0 = np.array(hf[data_name])
        norm_rad_0 = rad_0 / 1
        x = np.array(hf["rad_x"])
        radial_averages = list(zip(x, norm_rad_0))
        if args.scan_mode == 1:
            if idx % 2 == 0:
                f.create_dataset(
                    f"time_scan_{round(label[round((idx)/2)],1)}_laser_off",
                    data=radial_averages,
                )
                stamps.append(round(label[round((idx) / 2)], 1))
            else:
                f.create_dataset(
                    f"time_scan_{round(label[round((idx-1)/2)],1)}_laser_on",
                    data=radial_averages,
                )
        else:
            print(size, idx, label, label[idx])
            f.create_dataset(f"magnet_scan_{round(label[idx],1)}", data=radial_averages)
            stamps.append(label[idx])

        hf.close()
    f.create_dataset(f"scan_points", data=stamps)
    f.close()

if __name__ == "__main__":
    main()


from __future__ import print_function
import random
import string
import sys

WORDLIST_FILENAME = 'words.txt'
ATTEMPTS = 8

class Hangman(object):

    guesses = 0
    secret_word = ''
    letters_guessed = []

    def __init__(self):
        '''
        Construct method of Hangman class
        '''
        self.guesses = ATTEMPTS
        self.secret_word = self.load_words()
        self.start_hangman()

    def choice_word(self, wordlist):
        '''
        Choice a ramdom word of wordlist
        '''
        assert not (wordlist is None)

        while True:
            secret_word = random.choice(wordlist).lower()
            if self.different_letters() <= ATTEMPTS:
                break
            print('Choosing another word')

        return secret_word

    def load_words(self):
        '''
        Depending on the size of the word list, this function may
        take a while to finish.
        '''
        print('Loading word list from file...')
        # inFile: file
        in_file = open(WORDLIST_FILENAME, 'r')
        # line: string
        line = in_file.readline()
        # wordlist: list of strings
        wordlist = line.split()
        if len(wordlist) == 0:
            print('The file of words is empty')
            sys.exit(0)
        else:
            print('  ', len(wordlist), 'words loaded.')
            return self.choice_word(wordlist)

    def intro(self):
        '''
        Print the intro of the Hangman game
        '''
        print('\nWelcome to the game, Hangam!')
        print('I am thinking of a word that is', len(self.secret_word), 'letters long.')
        print('But the word have', self.different_letters(), 'different letters.')
        print('-------------')

    def different_letters(self):
        '''
        Count the differents letter in the secret word
        '''
        count = 0
        different_letters = []
        for letter in self.secret_word:
            if not letter in different_letters:
                count += 1
                different_letters.append(letter)
            else:
                pass

        return count

    def is_word_guessed(self):
        '''
        Verify if the letter guessed was guessed before
        '''
        for letter in self.secret_word:
            if not letter in self.letters_guessed:
                return False
            else:
                pass

        return True

    def get_available_letters(self, available):
        '''
        Get the letters that still available to guess
        '''
        assert not (available is None)

        for letter in available:
            if letter in self.letters_guessed:
                available = available.replace(letter, '')

        return available

    def get_guessed_word(self):
        '''
        Get the letters guessed that was in the secret word
        '''
        guessed = ''
        for letter in self.secret_word:
            if letter in self.letters_guessed:
                guessed += letter
            else:
                guessed += '_'

        return guessed

    def is_letter(self, letter):
        '''
        Validate if the content of string is a letter
        '''
        assert not (letter is None)

        try:
            int(letter)
            print('\nThe letter can\'t be a number !\n')
            return False
        except ValueError:
            return True

    def len_of_one(self, letter):
        '''
        Validate if the len of letter is one
        '''
        assert not (letter is None)

        if len(letter) == 1:
            return True
        elif len(letter) == 0:
            print('\nNo letter guessed\n')
            return False
        else:
            print('\nCan\'t guess more than one letter\n')
            return False

    def validate_letter(self, letter):
        '''
        Call the sub validations methods (is_letter and len_of_one)
        '''
        assert not (letter is None)

        if self.is_letter(letter):
            return self.len_of_one(letter)
        else:
            return False

    def read_letter_guessed(self):
        '''
        Read the input (letter guessed) in python 2.x and 3.x
        '''
        while True:
            print('Please guess a letter: ', end='')
            try:
                letter = raw_input().lower()
            except NameError:
                letter = input().lower()
                pass

            if self.validate_letter(letter):
                break

        self.verify_letter_guessed(letter)

    def verify_letter_guessed(self, letter):
        '''
        Verify if the input was already guessed, the correct letter
        or the incorrent letter
        '''
        assert not (letter is None)
        assert isinstance(letter, str)
        assert len(letter) == 1

        if letter in self.letters_guessed:
            guessed = self.get_guessed_word()
            print('Oops! You have already guessed that letter:', guessed)
        elif letter in self.secret_word:
            self.letters_guessed.append(letter)
            guessed = self.get_guessed_word()
            print('\nGood Guess:', guessed)
        else:
            self.guesses -= 1
            self.letters_guessed.append(letter)
            guessed = self.get_guessed_word()
            print('Oops! That letter is not in my word:',  guessed)
        print('------------')

    def start_hangman(self):
        '''
        Start the Hangman game
        '''
        self.intro()

        # Get a array with 'abcdefghijklmnopqrstuvwxyz'
        available = string.ascii_lowercase

        while  self.is_word_guessed() == False and self.guesses > 0:
            print('You have', self.guesses, 'guesses left.')
            available = self.get_available_letters(available)
            print('Available letters', available)
            self.read_letter_guessed()
        if self.is_word_guessed() == True:
            print('Congratulations, you won!')
        else:
            print('Sorry, you ran out of guesses. The word was', self.secret_word + '.')

if __name__ == '__main__':
    hangman = Hangman()