# a generator function
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf

#wd = pd.read_csv("Data/weather_data_clean.csv")
#wd = wd[['time_diff', 'azimuth', 'elevation',
#         'windX', 'windY', 'temp', 'rh',
#         'rain', 'leaf_wetness']]
#train_df = wd.iloc[:600000,:]
#val_df = wd.iloc[600000:700000,:]
#test_df = wd.iloc[700000:,:]

#print(wd.columns)

class WindowGenerator():
    def __init__(self, input_width, label_width, shift,
                 train_df, val_df, test_df,
                 label_columns = None):

        self.train_df = train_df
        self.val_df = val_df
        self.test_df = test_df

        # find the input column indicies:
        self.label_columns = label_columns
        if label_columns is not None:
            self.label_columns_indices = {name: i for i, name in
                                          enumerate(label_columns)}
        self.column_indices = {name: i for i, name in enumerate(train_df.columns)}

        # window parameters
        self.input_width = input_width
        self.label_width = label_width
        self.shift = shift

        self.total_window_size = input_width + shift

        self.input_slice = slice(0, input_width)
        self.input_indices = np.arange(self.total_window_size)[self.input_slice]

        self.label_start = self.total_window_size - self.label_width
        self.labels_slice = slice(self.label_start, None)
        self.label_indices = np.arange(self.total_window_size)[self.labels_slice]

    def __repr__(self):
        return '\n'.join([
            f'Total Window Size: {self.total_window_size}',
            f'Input Indices: {self.input_indices}',
            f'Label Indices: {self.label_indices}',
            f'Label Col Names: {self.label_columns}'
        ])

    def split_window(self, features):
        inputs = features[:, self.input_slice, :]
        labels = features[:, self.labels_slice, :]
        if self.label_columns is not None:
            labels = tf.stack(
                [labels[:, :, self.column_indices[name]] for name in self.label_columns],
                axis=-1
            )
        return inputs, labels

    def make_dataset(self, data):
        data = np.array(data, dtype=np.float32)
        ds = tf.keras.utils.timeseries_dataset_from_array(
            data = data,
            targets = None,
            sequence_length = self.total_window_size,
            sequence_stride = 1,
            shuffle = True, # ??? shuffels batch not time series sequence
            batch_size = 32 # this is the batch size produced by the data set
        )
        ds = ds.map(self.split_window)
        return ds

    def plot(self, model=None, plot_col='temp', max_subplots=3):
        inputs, labels = self.example
        plt.figure(figsize=(12, 8))
        plot_col_index = self.column_indices[plot_col]
        max_n = min(max_subplots, len(inputs))
        for n in range(max_n):
            plt.subplot(max_n, 1, n + 1)
            plt.ylabel(f'{plot_col} [normed]')
            plt.plot(self.input_indices, inputs[n, :, plot_col_index],
                     label='Inputs', marker='.', zorder=-10)

            if self.label_columns:
                label_col_index = self.label_columns_indices.get(plot_col, None)
            else:
                label_col_index = plot_col_index

            if label_col_index is None:
                continue

            plt.scatter(self.label_indices, labels[n, :, label_col_index],
                        edgecolors='k', label='Labels', c='#2ca02c', s=64)
            if model is not None:
                predictions = model(inputs)
                plt.scatter(self.label_indices, predictions[n, :, label_col_index],
                            marker='X', edgecolors='k', label='Predictions',
                            c='#ff7f0e', s=64)

            if n == 0:
                plt.legend()

        plt.xlabel('Time [h]')

    @property
    def train(self):
        return self.make_dataset(self.train_df)

    @property
    def val(self):
        return self.make_dataset(self.val_df)

    @property
    def test(self):
        return self.make_dataset(self.test_df)

    @property
    def example(self):
        result = getattr(self, '_example', None)
        if result is None:
            result = next(iter(self.train))
            self._example = result
        return result

#w1 = WindowGenerator(input_width=24*4, label_width=1, shift=0, label_columns=['leaf_wetness'])
#print( w1.train )

#example_window = tf.stack([np.array(train_df[:w1.total_window_size]),
#                           np.array(train_df[100:100+w1.total_window_size]),
#                           np.array(train_df[200:200+w1.total_window_size])
#                           ])

#for example_labels, example_inputs in w1.train.take(1):
#  print(f'Inputs shape (batch, time, features): {example_inputs.shape}')
#  print(f'Labels shape (batch, time, features): {example_labels.shape}')

#example_labels, example_inputs = w1.split_window(example_window)

#print('All shapes are: (batch, time, features)')
#print(f'Window shape: {example_window.shape}')
#print(f'Inputs shape: {example_inputs.shape}')
#print(f'Labels shape: {example_labels.shape}')

#print(train_df[200:200+w1.total_window_size])
#def generator(end):
#    value = 0
#    while value < end:
#        yield value
#       value += 1

#for value in generator(4):
#    print(value)


import json

from django import forms
from django.forms import BooleanField, CharField, ChoiceField, Field, FileField, Form, ValidationError
from django.utils.encoding import smart_text
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy as ugettext

def html_escape(s):
    """Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.
    """
    s = s.replace("&", "&")
    s = s.replace("<", "<")
    s = s.replace(">", ">")
    s = s.replace(" ", " ")
    s = s.replace('"', """)
    s = s.replace("'", "'")

    return s

def html_exempt(s):
    s = s.replace("&", "&")
    s = s.replace("<", "<")
    s = s.replace(">", ">")
    s = s.replace(" ", " ")
    s = s.replace(""", '"')
    s = s.replace("'", "'")

    return s

class BaseForm(Form):
    def __init__(self, *args, **kwargs):
        if "is_create" in kwargs:
            if not kwargs["is_create"] and "table_name" in self.base_fields:
                required = self.base_fields["table_name"].required
                self.base_fields["table_name"] = forms.RegexField(
                    required=required,
                    regex=r"^[a-zA-Z][_a-zA-Z0-9]*$",
                    error_messages={"invalid": _("由英文字母、下划线或数字组成，且以字母开头")},
                    max_length=255,
                    label=_("计算标识"),
                )
            del kwargs["is_create"]
        super(BaseForm, self).__init__(*args, **kwargs)

    # strip leading or trailing whitespace
    def _clean_fields(self):
        for name, field in list(self.fields.items()):
            # value_from_datadict() gets the data from the data dictionaries.
            # Each widget type knows how to retrieve its own data, because some
            # widgets split data over several HTML fields.
            value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
            try:
                if isinstance(field, FileField):
                    initial = self.initial.get(name, field.initial)
                    value = field.clean(value, initial)
                else:
                    if isinstance(value, str):
                        value = field.clean(value.strip())
                    else:
                        value = field.clean(value)
                self.cleaned_data[name] = value
                if hasattr(self, "clean_%s" % name):
                    value = getattr(self, "clean_%s" % name)()
                    self.cleaned_data[name] = value
            except ValidationError as e:
                self.add_error(name, e)

    def format_errmsg(self):
        errors = self.errors
        # django 1.8，取declared_fields
        declared_fields = self.declared_fields
        errmsg_arr = []
        for _key in errors:
            _keymsg_arr = errors[_key]
            if _key in declared_fields:
                _label = declared_fields[_key].label
                label = _label if _label else _key
                _errmsg = []
                for _err in _keymsg_arr.data:
                    if _err.code in ["max_length", "min_length"]:
                        # 为了兼容django1.8 zh-hans表单中文翻译bug的问题
                        _msg = ugettext(_err.message % _err.params.get("limit_value", 0)) % _err.params
                    else:
                        _msg = _err.message
                    _errmsg.append("{}，{}".format(label, _msg))

                errmsg_arr.extend(_errmsg)
            if _key == "__all__":
                errmsg_arr.extend(_keymsg_arr)
        return errmsg_arr[0]

class MultiStrSplitByCommaField(Field):
    """
    多个字段，使用逗号隔开
    """

    def to_python(self, value):
        if not value:
            return []

        return [_v for _v in value.split(",") if _v != ""]

    def validate(self, value):
        super(MultiStrSplitByCommaField, self).validate(value)

class MultiStrSplitBySemiconField(Field):
    """
    多个字段，使用分号隔开
    """

    def to_python(self, value):
        if not value:
            return []

        return [_v for _v in value.split(";") if _v != ""]

    def validate(self, value):
        super(MultiStrSplitBySemiconField, self).validate(value)

class MulChoiceFieldByComma(ChoiceField):
    """
    多选字段，使用逗号隔开
    """

    default_error_messages = {
        "invalid_choice": _("Select a valid choice. %(value)s is not one of the available choices."),
        "invalid_list": _("Enter a list of values."),
    }

    def to_python(self, value):
        if not value:
            return []
        else:
            value = value.split(",")
        return [smart_text(val) for val in value]

    def validate(self, value):
        """
        Validates that the input is a list or tuple.
        """
        if self.required and not value:
            raise ValidationError(self.error_messages["required"])
        # Validate that each value in the value list is in self.choices.
        for val in value:
            if not self.valid_value(val):
                raise ValidationError(self.error_messages["invalid_choice"] % {"value": val})

class ListField(Field):
    """
    列表字段
    """

    def to_python(self, value):
        if value is None:
            return []

        if not (isinstance(value, list)):
            raise ValidationError(_("字段类型必须为数组"))
        return value

    def validate(self, value):
        super(ListField, self).validate(value)

class DictField(Field):
    """
    字典字段
    """

    def to_python(self, value):
        if value is None:
            return None
        if not (isinstance(value, dict)):
            raise ValidationError(_("字段类型必须为字典类型"))
        return value

    def validate(self, value):
        super(DictField, self).validate(value)

class JSONField(Field):
    def to_python(self, value):
        if value is None:
            return None
        try:
            value = json.loads(value)
        except (TypeError, ValueError):
            try:
                # 若本身就是json格式，直接返回，为了兼容自更新情况
                json.dumps(value)
            except (TypeError, ValueError):
                raise ValidationError(_("字段格式不对，必须符合json格式"))
            else:
                return value
        return value

class HtmlEscapeCharField(CharField):
    """
    转义 html 相关字符，其他使用方式与 CharField 一致
    """

    def to_python(self, value):
        raw_value = super(HtmlEscapeCharField, self).to_python(value)
        return html_exempt(raw_value)

    def clean(self, value):
        cleaned_value = super(HtmlEscapeCharField, self).clean(value)
        return html_escape(cleaned_value)

def check_ip_rule(ipaddr):
    ipaddr = str(ipaddr)
    addr = ipaddr.strip().split(".")  # 切割IP地址为一个列表
    # print addr
    if len(addr) != 4:  # 切割后列表必须有4个参数
        return False
    for i in range(4):
        try:
            addr[i] = int(addr[i])  # 每个参数必须为数字，否则校验失败
        except BaseException:
            return False
        if addr[i] <= 255 and addr[i] >= 0:  # 每个参数值必须在0-255之间
            pass
        else:
            return False
        i += 1
    else:
        return True

class BooleanFieldsRequiredMixin(Form):
    """
    当BooleanField通过设置required为True时要求用户必须传入该参数，但允许该字段值为False，原表单认证会不通过
    为解决这种情况，表单类继承该类，嗯，就是这么坑
    1. https://stackoverflow.com/questions/10440937/what-is-wrong-with-the-django-forms-booleanfield-unit-test-case
    2. https://code.djangoproject.com/ticket/5957
    """

    def clean(self):
        for field_name, field in list(self.fields.items()):
            # Only BooleanField not subclasses of it.
            if not isinstance(field, BooleanField):
                continue

            if field_name not in self.data:
                self._errors[field_name] = self.error_class([ValidationError(_("该参数为必需项"))])

        return super(BooleanFieldsRequiredMixin, self).clean()

class CheckboxInput(forms.CheckboxInput):
    """
    为 BooleanField 设置默认值共用类
    """

    def __init__(self, default=False, *args, **kwargs):
        super(CheckboxInput, self).__init__(*args, **kwargs)
        self.default = default

    def value_from_datadict(self, data, files, name):
        if name not in data:
            return self.default
        return super(CheckboxInput, self).value_from_datadict(data, files, name)


y = 10
def func():
    x = 4
    global y # To modify a global varible inside a local scope, I need to use local keyword.
    y = y + 1 # 1. Now if we write only this to change the global variable, this won't work.
              # gives an error.
              # 2. But I write global y before this. Then y variable is recognized now.
              # 3. Important Note: Just to access the varible, I didn't need to do that.
              # Only if I want to change that, then this statement(global y) needed.
    print("x:", x)
    print("y:", y) # y is global here is this can be accessed from any part of this module.
    print(dir())
func()

print(dir()) # here x doesn't appear, because it's local to the function


import json
import os
import argparse
from asyncio.locks import Semaphore
from collector import Collector
import asyncio
from downloader import Downloader
from reporter import Reporter, INFO, NETWORK
from cacher import Cacher, tmp_save
from waiter import Waiter
import aiohttp
import bs4
import urllib.parse

def parse_gallely(html, userdata):
    '''
    ギャラリーページからデータと画像URL取得
    別プロセスで処理
    '''
    doc = bs4.BeautifulSoup(html, 'lxml')
    results = []
    for e in doc.select('.like_mark'):
        link = 'https:' + e.select_one('.img img')['data-originalretina']
        data = {
            'snapid': e['data-snapid'],
            'saves': int(e.select_one('.btn_save span').text.strip()),
            'likes': int(e.select_one('.btn_like span').text.strip()),
            'link': e.select_one('.over')['href']
        }

        # データが渡されたときはつける
        if userdata:
            data['user'] = userdata

        # first name if exists
        elem_first_name = e.select_one('.namefirst')
        if elem_first_name:
            data['first_name'] = elem_first_name.text.strip()

        # height if exists
        elem_height = e.select_one('.height')
        if elem_height:
            data['height'] = elem_height.text.strip()
        data['url'] = link

        results.append((link, data))

    return results

def parse_user(html):
    '''
    ユーザー一覧ページから各ユーザーページへのリンクとユーザーデータ取得
    別プロセスで処理
    '''
    results = []
    doc = bs4.BeautifulSoup(html, 'lxml')
    for e in doc.select('#list_1column li.list'):
        link = 'https://wear.jp' + e.select_one('.over')['href']
        type_e = e.select_one('h3.name span')
        if not type_e:
            user_type = 'normal'
        elif 'wearista' in type_e['class']:
            user_type = 'wearista'
        elif 'shopstaff' in type_e['class']:
            user_type = 'shopstaff'
        else:
            user_type = ''

        shopname_e = e.select_one('.shopname')
        if not shopname_e:
            shopname = ''
        else:
            shopname = shopname_e.text.strip()

        data = {
            'userid': e.select_one('.over')['href'].replace('/', ''),
            'name': e.select_one('h3.name').text.strip(),
            'info': list(map(lambda li: li.text.strip(), e.select('ul.info li'))),
            'meta': list(map(lambda li: li.text.strip(), e.select('ul.meta li'))),
            'brands': list(map(lambda li: li.text.strip(), e.select('.fav_brand ul li'))),
            'user_type': user_type,
            'shopname': shopname,
        }

        results.append((link, data))

    return results

class WearCollector(Collector):
    def __init__(self,
                 reporter: Reporter,
                 waiter: Waiter,
                 outdir: str,
                 useragent: str = ''):
        super(WearCollector, self).__init__()
        self.reporter: Reporter = reporter
        self.waiter = waiter
        self.outdir = outdir
        self.useragent = useragent
        self.cacher = Cacher(self.outdir)
        # 非同期処理の同時接続数制御
        self.semaphore = Semaphore(2)
        # ファイルダウンローダ
        self.downloader = Downloader(self.waiter, self.semaphore, self.reporter)

    async def download_user_page(self, url: str, page_num):
        url = url + f'?pageno={page_num}'

        # キャッシュがあれば使う
        filename = urllib.parse.quote(url, safe='') + '.html'
        content, info = self.cacher.get(filename)
        if content and info:
            html = content
            realurl = info.get('realurl')
            self.reporter.report(INFO, f'use cache {url}')
        else:
            await self.waiter.wait(url)
            async with self.semaphore:
                self.reporter.report(INFO, f'fetching {url}', type=NETWORK)
                async with aiohttp.request('get', url, headers={'user-agent': self.useragent}) as res:
                    html = await res.text()
                    realurl = str(res.url)
                    self.cacher.set(filename, html, {'status': res.status, 'realurl': realurl})

        # 終了条件
        if page_num >= 2 and realurl.count('?pageno') == 0:
            return False
        else:
            for url, data in await self.run_in_executor(parse_user, html):
                await self.add_future('gallery', self.gallery_collector(url, 1, 501, userdata=data))
            return True

    async def user_collector(self, url: str, pagestart: int, pageend: int):
        await self.queued_paging(
            pagestart, pageend,
            lambda page: self.download_user_page(url, page))

    async def download_gallery_page(self, url: str, page_num: int, userdata=None):
        url = url + f'?pageno={page_num}'
        filename = urllib.parse.quote(url, safe='') + '.html'
        content, info = self.cacher.get(filename)
        if content and info:
            html = content
            realurl = info.get('realurl')
            self.reporter.report(INFO, f'use cache {url}')
        else:
            await self.waiter.wait(url)
            async with self.semaphore:
                self.reporter.report(INFO, f'fetching {url}', type=NETWORK)
                async with aiohttp.request('get', url, headers={'user-agent': self.useragent}) as res:
                    html = await res.text()
                    realurl = str(res.url)
                    self.cacher.set(filename, html, {'status': res.status, 'realurl': realurl})

        # 終了条件
        if page_num >= 2 and realurl.count('?pageno') == 0:
            return False
        else:
            for url, data in await self.run_in_executor(parse_gallely, html, userdata):
                imagefile = urllib.parse.quote(url, safe='')
                tmp_save(os.path.join(self.outdir, imagefile+'.json'), json.dumps(data))
                imagepath = os.path.join(self.outdir, imagefile)
                if not os.path.exists(imagepath):
                    await self.add_future('image', self.downloader.download_file(
                        url, imagepath, headers={'user-agent': self.useragent}))
            return True

    async def gallery_collector(self, url: str, pagestart: int, pageend: int, userdata=None):
        await self.queued_paging(
            pagestart, pageend,
            lambda page: self.download_gallery_page(url, page, userdata=userdata))

if __name__ == "__main__":

    parser = argparse.ArgumentParser('wear')
    parser.add_argument('url', action='store', help='URL')
    parser.add_argument('--pagestart', '-ps', type=int, required=True)
    parser.add_argument('--pageend', '-pe', type=int, required=True)
    parser.add_argument('--useragent', '-ua', type=str, default='')
    parser.add_argument('--waitlist', '-wl', type=str, default='wait.json')
    parser.add_argument('--outdir', '-o', type=str, required=True)
    parser.add_argument('--loglevel', '-ll', default=2, type=int, help='log level')
    parser.add_argument('--wait', '-w', default='5', nargs='+', type=str, help='interval for http requests. default is none. `-w 0.5` `-w random 1 2.5`')
    args = parser.parse_args()

    c = WearCollector(
        reporter=Reporter(args.loglevel),
        waiter=Waiter(args.wait, args.waitlist),
        outdir=args.outdir,
        useragent=args.useragent
    )
    asyncio.run(
        c.run(c.user_collector(args.url, args.pagestart, args.pageend))
    )


import os
import platform
import shutil
import subprocess
import sys
import zipfile

from sys import platform as _platform
from os import system

print('You are Running on a', platform.system(), 'System')
#path1="1.sh"
#path2="Secret.png"

def clear():
    if _platform == "linux" or _platform == "linux2" or _platform == "darwin":
        system('clear')
    if _platform == "win32":
        system('cls')

clear()
path1 = input("Enter the path to the File/Files to be hidden: ")
path2 = input("Enter the path to the file in which you want to hide the files:")
filename, file_extension = os.path.splitext(path2)
clear()

def writesh():
    print('Creating Custom Command')
    try:
        file = open('command.sh', 'w')
        file.close()
    except:
        print('Something Went Wrong!')
        sys.exit(0)
def zippp():
    secretfiles = zipfile.ZipFile('secret.zip', mode='w')
    # os.chdir(path1)

    try:
        print('Zipping File ', path1)
        secretfiles.write(path1)

    finally:
        print('Closing')
        secretfiles.close()

if os.path.isdir(path1):
    print("\n Directory Found")
    print("\n Zipping Directory")
    #zippp()
    shutil.make_archive('secret', 'zip', path1)
    if _platform == "linux" or _platform == "linux2" or _platform == "darwin":
        print('Linux/Unix System Found')
        #subprocess.call([ "echo", path2, "secret.zip > output"+file_extension])
        writesh()
        file = open("command.sh","w")
        file.write("#!/bin/bash")
        com = "\n cat " + path2 + " secret.zip "+ " > output"+file_extension
        file.write(com)
        file.close()
        subprocess.call(["bash","command.sh"])
        print("output"+file_extension + " Contains your hidden flies :)")
        exit

    if _platform == "win32":
        exit
        #os.system('echo $path2')

elif os.path.isfile(path1):
    print("\n File Found")
    if _platform == "linux" or _platform == "linux2" or _platform == "darwin":
        print('Linux/Unix System found')
        #subprocess.call(["cat", path2, path1, "output"+file_extension])
        writesh()
        file = open("command.sh","w")
        file.write("#!/bin/bash")
        com = "\n cat " + path2 + " " + path1 + " > output"+file_extension
        file.write(com)
        file.close()
        subprocess.call(["bash","command.sh"])
        print("output"+file_extension + " Contains your hidden flies :)")

        exit

    if _platform == "win32":
        exit
else:
    print("\nSomehow the input was neither a file or path.\nIs the path correct?")


from ast import dump
from random import getstate
import re
from typing import final
from flask import Flask, render_template,request, url_for, flash, redirect,current_app
from flask_mysqldb import MySQL
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class State(FlaskForm):
    statename = StringField(label=('Enter state Name:'), validators=[DataRequired()])
    stateab = StringField(label=('Enter state Ab:'), validators=[DataRequired()])
    submit = SubmitField(label=('Submit'))

app = Flask(__name__)
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'artgallery'
app.config['SECRET_KEY'] = 'df0331cefc6c2b9a5d0208a726a5d1c0fd37324feba25506'
mysql = MySQL(app)
def getCustomers(state):
    query = '''select c.cID, c.name, c.street, c.city, c.stateAb,s.stateName, c.zipcode
from customer c
join state s
on s.stateAb = c.stateAb
where s.stateAb like %s or s.stateName like %s '''
    cur = mysql.connection.cursor()
    cur.execute(query, (state,state))
    rv = cur.fetchall()
    print(cur._executed)
    cur.close()
    return rv

def getStates():
        query = '''select * from state'''
        cur = mysql.connection.cursor()
        cur.execute(query)
        rv = cur.fetchall()
        print(rv)
        flash(cur._executed)
        cur.close()
        return rv

def createState(statename,stateab):
    try:
        query = '''insert into state(statename,stateab) values(%s,%s)'''
        cur = mysql.connection.cursor()
        cur.execute(query,(statename,stateab))
        mysql.connection.commit()
        cur.close()
    except:
        print('exception')
        mysql.connection.rollback()
    # finally:
        # mysql.connection.close()

def updateState(oldstatename,statename,stateab):
    try:
        print(oldstatename)
        print(statename)
        print(stateab)
        query = '''update state set statename = %s, stateab= %s where statename = %s'''
        cur = mysql.connection.cursor()
        cur.execute(query,(statename,stateab,oldstatename))
        print(cur._executed)
        mysql.connection.commit()
        cur.close()
    except:
        print('exception')
        mysql.connection.rollback()

def removestate(statename):
    try:
        cur = mysql.connection.cursor()
        cur.execute('''delete from state where statename like %s''',(statename,))
        mysql.connection.commit()
        cur.close()
    except:
        flash('cannot delete foreign key ')
    # finally:
        # mysql.connection.close()

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/arts', methods = ('GET', 'POST'))
def listArts():
    # data
     if request.method == 'GET':
        return render_template('arts.html',result=getCustomers('texas') )
     else:
        state = request.form['state']
        if not state:
            flash('state is required!')
        else:
            return render_template('arts.html',result=getCustomers(state))

@app.route('/add')
def addArt():
    return render_template('add.html')

@app.route('/states', methods = ('GET', 'POST'))
def states():
    form = State()
    if request.method == 'POST' and form.validate_on_submit():
        print('valid form')
        statename = request.form['statename']
        stateab = request.form['stateab']
        createState(statename,stateab)
        return redirect('/states')
    if request.method == 'GET':
        return render_template('states.html',result=getStates(),form=form)

@app.route('/deletestate/<id>')
def deletestate(id):
    removestate(id)
    return redirect('/states')

@app.route('/updatestate', methods = ['POST'])
def updatestate():
    form = State()
    if request.method == 'POST' and form.validate_on_submit():
        print('valid form')
        oldstatename = request.form['oldstatename']
        statename = request.form['statename']
        stateab = request.form['stateab']
        updateState(oldstatename,statename,stateab)
        return redirect('/states')


# Name: Juan Pablo Duque Ochoa
# OSU Email: duqueocj@oregonstate.edu
# Course: CS261 - Data Structures
# Assignment: (6) Portfolio Project - HashMap Implementation
# Due Date: 06/05/2022
# Description: Implementation of HashMap class with chaining for collision resolution.

from a6_include import (DynamicArray, LinkedList,
                        hash_function_1, hash_function_2)

class HashMap:
    def __init__(self, capacity: int, function) -> None:
        """
        Initialize new HashMap that uses
        separate chaining for collision resolution
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        self._buckets = DynamicArray()
        for _ in range(capacity):
            self._buckets.append(LinkedList())

        self._capacity = capacity
        self._hash_function = function
        self._size = 0

    def __str__(self) -> str:
        """
        Override string method to provide more readable output
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        out = ''
        for i in range(self._buckets.length()):
            out += str(i) + ': ' + str(self._buckets[i]) + '\n'
        return out

    def get_size(self) -> int:
        """
        Return size of map
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        return self._size

    def get_capacity(self) -> int:
        """
        Return capacity of map
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        return self._capacity

    # ------------------------------------------------------------------ #

    def put(self, key: str, value: object) -> None:
        """
        Update the key / value pair in the hash map. If the key exists in
        the hash map, its associated value is replaced with the new value.
        If the key is not in the hash map, a key / value pair is added.
        """
        index = self.get_index(key)
        link_list: LinkedList = self._buckets[index]
        node = link_list.contains(key)
        if node:
            node.value = value
        else:
            link_list.insert(key, value)
            self._size += 1

    def empty_buckets(self) -> int:
        """
        Return the number of empty buckets in the hash table.
        """
        count = 0
        for index in range(self._capacity):
            if self._buckets[index].length() == 0:
                count += 1
        return count

    def table_load(self) -> float:
        """
        Return the current hash table load factor.
        """
        count = 0
        for index in range(self._capacity):
            count += self._buckets[index].length()
        return count / self._capacity

    def clear(self) -> None:
        """
        Clear the contents of the hash map without changing the underlying
        hash table capacity.
        """
        self.__init__(self._capacity, self._hash_function)

    def resize_table(self, new_capacity: int) -> None:
        """
        Change the capacity of the internal hash table. All existing
        key / value pairs remain in the new hash map, and all
        hash table links are rehashed.
        """
        if new_capacity < 1:
            return
        buckets = self._buckets
        capacity = self._capacity
        self._capacity = new_capacity
        self.clear()
        for index in range(capacity):
            for node in buckets[index]:
                self.put(node.key, node.value)

    def get(self, key: str) -> object:
        """
        Return the value associated with the given key or None if the key
        is not in the hash.
        """
        index = self.get_index(key)
        node = self._buckets[index].contains(key)
        return None if not node else node.value

    def contains_key(self, key: str) -> bool:
        """
        Return True if the given key is in the hash map and False otherwise.
        """
        index = self.get_index(key)
        node = self._buckets[index].contains(key)
        return node is not None

    def remove(self, key: str) -> None:
        """
        Remove the given key and its associated value from the hash map.
        """
        index = self.get_index(key)
        removed = self._buckets[index].remove(key)
        if removed:
            self._size -= 1
        return

    def get_keys(self) -> DynamicArray:
        """
        Return a DynamicArray that contains all the keys stored in the hash map.
        """
        arr = DynamicArray()
        for index in range(self._capacity):
            for node in self._buckets[index]:
                arr.append(node.key)
        return arr

    def get_index(self, key) -> int:
        """
        Return hashed index.
        """
        return self._hash_function(key) % self._capacity

def find_mode(da: DynamicArray) -> (DynamicArray, int):
    """
    Receive a DynamicArray and return a tuple containing a DynamicArray comprising
    the mode (most occurring) value/s of the array, and an integer that represents
    the highest frequency (how many times they appear). O(N).
    """
    # Separate instance of Chaining HashMap
    map = HashMap(da.length() // 3, hash_function_1)
    arr_freq = DynamicArray()
    size = da.length()
    # Populate hash map with elements and their frequency values
    for index in range(size):
        if not map.contains_key(da[index]):
            map.put(da[index], 1)
        else:
            value = map.get(da[index])
            value += 1
            map.put(da[index], value)
    # Create keys array
    arr_key = map.get_keys()
    freq = 0
    # Populate array with elements of highest frequency
    for idx in range(arr_key.length()):
        # Get the frequency value
        val: int = int(map.get(arr_key[idx]))
        # Get the key
        key = arr_key[idx]
        if val > freq:
            arr_freq = DynamicArray()
            arr_freq.append(key)
            freq = val
        elif val == freq:
            arr_freq.append(arr_key[idx])
    return arr_freq, freq

# ------------------- BASIC TESTING ---------------------------------------- #

if __name__ == "__main__":

    print("\nPDF - put example 1")
    print("-------------------")
    m = HashMap(50, hash_function_1)
    for i in range(150):
        m.put('str' + str(i), i * 100)
        if i % 25 == 24:
            print(m.empty_buckets(), m.table_load(), m.get_size(), m.get_capacity())

    print("\nPDF - put example 2")
    print("-------------------")
    m = HashMap(40, hash_function_2)
    for i in range(50):
        m.put('str' + str(i // 3), i * 100)
        if i % 10 == 9:
            print(m.empty_buckets(), m.table_load(), m.get_size(), m.get_capacity())

    print("\nPDF - empty_buckets example 1")
    print("-----------------------------")
    m = HashMap(100, hash_function_1)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key1', 10)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key2', 20)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key1', 30)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key4', 40)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())

    print("\nPDF - empty_buckets example 2")
    print("-----------------------------")
    m = HashMap(50, hash_function_1)
    for i in range(150):
        m.put('key' + str(i), i * 100)
        if i % 30 == 0:
            print(m.empty_buckets(), m.get_size(), m.get_capacity())

    print("\nPDF - table_load example 1")
    print("--------------------------")
    m = HashMap(100, hash_function_1)
    print(m.table_load())
    m.put('key1', 10)
    print(m.table_load())
    m.put('key2', 20)
    print(m.table_load())
    m.put('key1', 30)
    print(m.table_load())

    print("\nPDF - table_load example 2")
    print("--------------------------")
    m = HashMap(50, hash_function_1)
    for i in range(50):
        m.put('key' + str(i), i * 100)
        if i % 10 == 0:
            print(m.table_load(), m.get_size(), m.get_capacity())

    print("\nPDF - clear example 1")
    print("---------------------")
    m = HashMap(100, hash_function_1)
    print(m.get_size(), m.get_capacity())
    m.put('key1', 10)
    m.put('key2', 20)
    m.put('key1', 30)
    print(m.get_size(), m.get_capacity())
    m.clear()
    print(m.get_size(), m.get_capacity())

    print("\nPDF - clear example 2")
    print("---------------------")
    m = HashMap(50, hash_function_1)
    print(m.get_size(), m.get_capacity())
    m.put('key1', 10)
    print(m.get_size(), m.get_capacity())
    m.put('key2', 20)
    print(m.get_size(), m.get_capacity())
    m.resize_table(100)
    print(m.get_size(), m.get_capacity())
    m.clear()
    print(m.get_size(), m.get_capacity())

    print("\nPDF - resize example 1")
    print("----------------------")
    m = HashMap(20, hash_function_1)
    m.put('key1', 10)
    print(m.get_size(), m.get_capacity(), m.get('key1'), m.contains_key('key1'))
    m.resize_table(30)
    print(m.get_size(), m.get_capacity(), m.get('key1'), m.contains_key('key1'))

    print("\nPDF - resize example 2")
    print("----------------------")
    m = HashMap(75, hash_function_2)
    keys = [i for i in range(1, 1000, 13)]
    for key in keys:
        m.put(str(key), key * 42)
    print(m.get_size(), m.get_capacity())

    for capacity in range(111, 1000, 117):
        m.resize_table(capacity)

        m.put('some key', 'some value')
        result = m.contains_key('some key')
        m.remove('some key')

        for key in keys:
            # all inserted keys must be present
            result &= m.contains_key(str(key))
            # NOT inserted keys must be absent
            result &= not m.contains_key(str(key + 1))
        print(capacity, result, m.get_size(), m.get_capacity(), round(m.table_load(), 2))

    print("\nPDF - get example 1")
    print("-------------------")
    m = HashMap(30, hash_function_1)
    print(m.get('key'))
    m.put('key1', 10)
    print(m.get('key1'))

    print("\nPDF - get example 2")
    print("-------------------")
    m = HashMap(150, hash_function_2)
    for i in range(200, 300, 7):
        m.put(str(i), i * 10)
    print(m.get_size(), m.get_capacity())
    for i in range(200, 300, 21):
        print(i, m.get(str(i)), m.get(str(i)) == i * 10)
        print(i + 1, m.get(str(i + 1)), m.get(str(i + 1)) == (i + 1) * 10)

    print("\nPDF - contains_key example 1")
    print("----------------------------")
    m = HashMap(10, hash_function_1)
    print(m.contains_key('key1'))
    m.put('key1', 10)
    m.put('key2', 20)
    m.put('key3', 30)
    print(m.contains_key('key1'))
    print(m.contains_key('key4'))
    print(m.contains_key('key2'))
    print(m.contains_key('key3'))
    m.remove('key3')
    print(m.contains_key('key3'))

    print("\nPDF - contains_key example 2")
    print("----------------------------")
    m = HashMap(75, hash_function_2)
    keys = [i for i in range(1, 1000, 20)]
    for key in keys:
        m.put(str(key), key * 42)
    print(m.get_size(), m.get_capacity())
    result = True
    for key in keys:
        # all inserted keys must be present
        result &= m.contains_key(str(key))
        # NOT inserted keys must be absent
        result &= not m.contains_key(str(key + 1))
    print(result)

    print("\nPDF - remove example 1")
    print("----------------------")
    m = HashMap(50, hash_function_1)
    print(m.get('key1'))
    m.put('key1', 10)
    print(m.get('key1'))
    m.remove('key1')
    print(m.get('key1'))
    m.remove('key4')

    print("\nPDF - get_keys example 1")
    print("------------------------")
    m = HashMap(10, hash_function_2)
    for i in range(100, 200, 10):
        m.put(str(i), str(i * 10))
    print(m.get_keys())

    m.resize_table(1)
    print(m.get_keys())

    m.put('200', '2000')
    m.remove('100')
    m.resize_table(2)
    print(m.get_keys())

    print("\nPDF - find_mode example 1")
    print("-----------------------------")
    da = DynamicArray(["apple", "apple", "grape", "melon", "melon", "peach"])
    map = HashMap(da.length() // 3, hash_function_1)
    mode, frequency = find_mode(da)
    print(f"Input: {da}\nMode: {mode}, Frequency: {frequency}")

    print("\nPDF - find_mode example 2")
    print("-----------------------------")
    test_cases = (
        ["Arch", "Manjaro", "Manjaro", "Mint", "Mint", "Mint", "Ubuntu", "Ubuntu", "Ubuntu", "Ubuntu"],
        ["one", "two", "three", "four", "five"],
        ["2", "4", "2", "6", "8", "4", "1", "3", "4", "5", "7", "3", "3", "2"]
    )

    for case in test_cases:
        da = DynamicArray(case)
        map = HashMap(da.length() // 3, hash_function_2)
        mode, frequency = find_mode(da)
        print(f"Input: {da}\nMode: {mode}, Frequency: {frequency}\n")


def is_linked(vector1,vector2):
    difference = (vector1[0]-vector2[0],vector1[1]-vector2[1])
    choice = [(0,1),(0,-1),(1,0),(-1,0)]
    if difference in choice:
        return True
    else:
        return False

class Block():
    def __init__(self,initial):
        self.block = [initial]
        self.head = self.block[0]
        self.tail = self.block[len(self.block)-1]
        self.leftBound = initial[0]
        self.rightBound = initial[0]
        self.upBound = initial[1]
        self.downBound = initial[1]
        self.length = len(self.block)
        self.lowest = initial

    def add_block(self,vector):
        x = vector[0]
        y = vector[1]
        if is_linked(vector,self.tail) and not(vector in self.block):
            if y > self.downBound:
                self.lowest = vector
            self.block.append(vector)
            self.leftBound = min(self.leftBound,x)
            self.rightBound = max(self.rightBound,x)
            self.upBound = min(self.upBound,y)
            self.downBound = max(self.downBound,y)
            self.tail = vector
            self.length += 1
        else:
            pass
            #print('New block is unconnected to the old block.')
    def connect_block(self,vector):
        if vector not in self.block:
            self.block.append(vector)
            self.length + 1

    def delete_block(self,vector):
        if vector in self.block:
            del(self.block[self.block.index(vector)])
            self.length - 1

    def moveByVector(self,vector):
        newBlock = list()
        x = vector[0]
        y = vector[1]

        for i in range(self.length):
            temp = (self.block[i][0]+x,self.block[i][1]+y)
            newBlock.append(temp)

        self.block = newBlock
        self.leftBound += x
        self.rightBound += x
        self.upBound += y
        self.downBound += y
        self.lowest = (self.lowest[0]+x,self.lowest[1]+y)

    def addVector(self,vector):
        newBlock = list()
        x = vector[0]
        y = vector[1]

        for i in range(self.length):
            temp = (self.block[i][0]+x,self.block[i][1]+y)
            newBlock.append(temp)

        return newBlock

    def getBound(self):
        self.leftBound = None
        for i in self.block:
            x = i[0]
            y = i[1]
            if self.leftBound == None:
                self.leftBound = x
                self.rightBound = x
                self.upBound = y
                self.downBound = y
                self.lowest = i
            else:
                self.leftBound = min(self.leftBound,x)
                self.rightBound = max(self.rightBound,x)
                self.upBound = min(self.upBound,y)
                self.downBound = max(self.downBound,y)
                if y == self.downBound:
                    self.lowest = i

    def rotate(self,sign):
        'sign= 1:clockwise'
        'sign=-1:counter-clockwise'
        mid = (self.leftBound + self.rightBound)/2
        temp_block = list()
        temp_upBound = None
        for instance in self.block:
            temp_x = instance[0]
            temp_y = instance[1]
            new_x = sign*temp_y
            new_y = -1*sign*temp_x
            temp_block.append((new_x,new_y))
            if temp_upBound == None:
                temp_upBound = new_y
                temp_leftBound = new_x
                temp_rightBound = new_x
            else:
                temp_upBound = min(temp_upBound,new_y)
                temp_leftBound = min(temp_leftBound,new_x)
                temp_rightBound = max(temp_rightBound,new_x)
        temp_mid = (temp_leftBound + temp_rightBound)/2
        dif_y = int(self.upBound - temp_upBound)
        dif_x = int(mid - temp_mid)
        newBlock = list()
        for i in temp_block:
            temp_x = i[0]
            temp_y = i[1]
            new_x = temp_x + dif_x
            new_y = temp_y + dif_y
            newBlock.append((new_x,new_y))
        return newBlock

    def replace(self,newBlock):
        for i in self.block:
            self.delete_block(i)
        self.block = newBlock
        self.getBound()
        print('New block replaced.')


# 큰 수의 법칙
# 첫 째 줄에 N, M, K 입력 각 자연수는 공백으로 구분
# 둘째 줄에 N개의 자연수가 주어진다. 각 자연수는 공백으로 구분
# 입력으로 주어지는 K <= M
# M: M번 더하기 K: 인덱스가 최대 K번 연속 N: 배열의 크기
# 출력: K번 동일한 수 반복하지 않고 M번 더한 값

# 첫 째 줄에 N, M, K 입력 각 자연수는 공백으로 구분
n, m, k = map(int, input().split())

# 둘째 줄에 N개의 자연수가 주어진다. 각 자연수는 공백으로 구분
data = list(map(int, input().split()))
data.sort()
first = data[n-1] # 가장 큰 수
second = data[n-2] # 두 번째로 가장 큰 수

result = 0

# first와 second를 인덱스가 K번 겹치지 않으면서 M번 더한다.
while True:
    # 동일한 인덱스가 K번 겹치지 않으면서
    for i in range(k):
        if m == 0:
            break
        result += first
        m -= 1

    if m == 0:
        break
    result += second
    m -= 1

print(result)
#########################
# 숫자 카드 게임
# n = 행의 개수, m = 열의 개수
n, m = map(int, input().split())
result = 0

# 한 줄씩 입력받아 확인
for i in range(n):
    data = list(map(int, input().split()))
    min_value = 10001
    for a in data:
        min_value = min(min_value, a)
    result = max(result, min_value)
print(result)
# min()함수: ()안에 들어간 value 중 가장 작은 값
# max()함수: ()안에 들어간 value 중 가장 큰 값


import numpy as np
import cv2

width, height = 800, 800

# Create blank image
img = np.zeros((height, width, 3), dtype=np.uint8)

# color the image
location = 0
shade = 20
n_shades = 255
for i in range(n_shades):
    img[0:height, location:location+width//n_shades, 1:3] = shade
    location += width//n_shades
    shade += 255//n_shades

# Save image
cv2.imwrite("my_img.png", img)


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

class Solution:
    def __init__(self) -> None:
        # TODO:
        # Load data from data/chipotle.tsv file using Pandas library and
        # assign the dataset to the 'chipo' variable.
        file = 'data/chipotle.tsv'
        self.chipo = pd.read_csv(file, sep='\t')

    def top_x(self, count) -> None:
        # TODO
        # Top x number of entries from the dataset and display as markdown format.
        topx = self.chipo.head(count)
        print(topx.to_markdown())

    def count(self) -> int:
        # TODO
        # The number of observations/entries in the dataset.
        return self.chipo.shape[0]

    def info(self) -> None:
        # TODO
        # print data info.
        return self.chipo.info()

    def num_column(self) -> int:
        # TODO return the number of columns in the dataset
        # print(self.chipo.shape[1])
        # for index in self.chipo.columns['index']
        #     print(index)
        return self.chipo.shape[1]

    def print_columns(self) -> None:
        # TODO Print the name of all the columns.
        # return self.chipo.columns.to_series()
        return self.chipo.columns.to_list()

    def most_ordered_item(self):
        # TODO
        a = self.chipo[['item_name','quantity','order_id']]
        # print(a)
        a = a.groupby('item_name',as_index=False)
        # print(a)
        a = a.sum()
        # print(a)
        a = a.sort_values(by=['quantity'],ascending = False)
        # print(a)
        a = a.head(1)
        # print(a)
        item_name = a['item_name'].values[0]
        order_id = a['order_id'].values[0]
        quantity = a['quantity'].values[0]
        return item_name, order_id, quantity

    def total_item_orders(self) -> int:
       # TODO How many items were orderd in total?
        return self.chipo['quantity'].sum()

    def total_sales(self) -> float:
        # TODO
        # 1. Create a lambda function to change all item prices to float.
        # 2. Calculate total sales.
        # df_list = self.chipo['item_price'].value_counts()
        # df_list2 = self.chipo['quantity'].to_list()
        # x = self.chipo
        # self.chipo['item_price'] = self.chipo['item_price'][1:-1]
        # print('***  ' + self.chipo['item_price'])
        # x= lambda a:a'

        a = self.chipo['item_price'].apply(lambda x:float(x.replace('$','')))
        aa = self.chipo['quantity'] * a
        # print(a)
        # pd.np.multiply(self.chipo['item_price'],)
        # sum = 0.0
        # for i in df_list:
        #     sum+=float(i.replace('$',''))
        # print(sum)
        return aa.sum()

    def num_orders(self) -> int:
        # TODO
        # How many orders were made in the dataset?
        # print(self.chipo['order_id'].tail(1))
        # print(self.chipo['order_id'].tail(1).iat[0])
        return self.chipo['order_id'].tail(1).iat[0]

    def average_sales_amount_per_order(self) -> float:
        # TODO
        # print(round(Solution.total_sales(self)/Solution.num_orders(self),2))
        return round(Solution.total_sales(self)/Solution.num_orders(self),2)

    def num_different_items_sold(self) -> int:
        # TODO
        # How many different items are sold?
        # self.chipo['item_name'].unique()
        # print(self.chipo['item_name'].unique().shape)
        return self.chipo['item_name'].unique().shape[0]

    def plot_histogram_top_x_popular_items(self, x: int) -> None:
        from collections import Counter
        letter_counter = Counter(self.chipo.item_name)
        # print(type(letter_counter))
        # print(letter_counter)
        # print(letter_counter.items())
        # print(pd.DataFrame(letter_counter.items()))
        # TODO
        # 1. convert the dictionary to a DataFrame
        # print(pd.DataFrame.from_dict(letter_counter))
        df = pd.DataFrame(letter_counter.items())
        # print(df)
        # 2. sort the values from the top to the least value and slice the first 5 items
        # print(df.sort_values(1, ascending=False).head(x))
        final = df.sort_values(1, ascending=False).head(x)
        # 3. create a 'bar' plot from the DataFrame
        final.plot.bar(x=0,y=1,rot=0)
        # 4. set the title and labels:
        #     x: Items
        #     y: Number of Orders
        #     title: Most popular items
        plt.xlabel('Items')
        plt.ylabel('Number of Orders')
        plt.suptitle('Most popular items')
        # 5. show the plot. Hint: plt.show(block=True).
        plt.show(block = True)
        # pass

    def scatter_plot_num_items_per_order_price(self) -> None:
        # TODO
        # 1. create a list of prices by removing dollar sign and trailing space.
        self.chipo['item_price'] = self.chipo['item_price'].apply(lambda x:float(x.replace('$','')))
        # print(self.chipo)
        # 2. groupby the orders and sum it.
        orderedChipo = self.chipo.groupby('order_id').sum()
        # print(orderedChipo)
        # a = self.chipo['item_price'].replace('$','')
        # print(a)

        # 3. create a scatter plot:
        #       x: orders' item price
        #       y: orders' quantity
        #       s: 50
        #       c: blue
        orderedChipo.plot.scatter(x='item_price',y='quantity',s=50,c='blue')
        plt.xlabel('Order Price')
        plt.ylabel('Num Items')
        plt.suptitle('Numer of items per order price')
        # 4. set the title and labels.
        #       title: Numer of items per order price
        #       x: Order Price
        #       y: Num Items
        plt.show(block = True)

def test() -> None:
    solution = Solution()
    solution.top_x(10)
    count = solution.count()
    print(count)
    assert count == 4622
    solution.info()
    print(solution.print_columns())
    count = solution.num_column()
    assert count == 5
    item_name, order_id, quantity = solution.most_ordered_item()
    assert item_name == 'Chicken Bowl'
    assert order_id == 713926
    assert quantity == 761
    total = solution.total_item_orders()
    assert total == 4972
    assert 39237.02 == solution.total_sales()
    assert 1834 == solution.num_orders()
    assert 21.39 == solution.average_sales_amount_per_order()
    assert 50 == solution.num_different_items_sold()
    solution.plot_histogram_top_x_popular_items(5)
    solution.scatter_plot_num_items_per_order_price()

if __name__ == "__main__":
    # execute only if run as a script
    test()


def inside(parses,d_A_BC,d_BC_A,words,alpha,gamma,phi,n_lenOfsen):
    #此循环表示每个非终结符->各个单词的概率
    for i in range(n_lenOfsen):
        A=[x for x in d_BC_A[words[i]]][0]  #非终结符(符号)
        parses[(i,i)].append(A)  #向[i,i]添加元素
        #A->wi 此为Inside算法
        alpha[(i,i)][A]=d_A_BC[A][words[i]]
        #此为CYK算法
        gamma[(i,i)][A]=d_A_BC[A][words[i]]
    for j in range(1,n_lenOfsen):
        for i in range(n_lenOfsen-j):
            for k in range(i,i+j):
                for B in parses[(i,k)]:
                    for C in parses[(k+1,i+j)]:
                        #' '.join((B,C))将B和C合并为一个字符串，通过空格分隔
                        As=[x for x in d_BC_A[' '.join((B,C))]]
                        if As:
                           for A in As:
                               parses[(i,i+j)].append(A)
                               #比如d_A_BC['VP']['VBD NP']  此为Inside算法
                               alpha[(i,i+j)][A] +=d_A_BC[A][' '.join((B,C))]*alpha[(i,k)][B]*alpha[(k+1,i+j)][C]
                               #此为Inside算法
                               prob=d_A_BC[A][' '.join((B,C))]*gamma[(i,k)][B]*gamma[(k+1,i+j)][C]
                               #CYK算法选择句法结构树t使其具有最大概率
                               if prob>gamma[(i,i+j)][A]:
                                  gamma[(i,i+j)][A]=prob
                                  phi[(i,i+j)][A]=(k,B,C)


from buildhat import Motor, ColorSensor, ForceSensor
import kociemba  # for custom event to solve cubes
from math import *
import os, struct, time

# constants
flipperMotor = Motor('D')
flipperHome = 12
flipperHold = 143
flipperFlip = 274 - 360
flipperScanEdge = 198 - 360
flipperScanCenter = 243 - 360
flipperScanCorner = 184 - 360
flipperSpin = 43

rotaterMotor = Motor('C')
rotaterHome = 0

button = ForceSensor('B')

# Enums (spike prime doesnt support enum library)
# turn direction
prime = 1
regular = 2

colorTable = ['white', 'red', 'green', 'yellow', 'orange', 'blue']
faceTable = ['U', 'R','F','D','L','B']

class Face():
    U = 0
    R = 1
    F = 2
    D = 3
    L = 4
    B = 5

# calibration data
colorReference = [None] * 6
calibrationFile = os.path.expanduser("~/cubecolors")

# load color reference
colorReference = [None] * 6
#if os.path.isfile('data/cubecolors'):
try:
    with open(calibrationFile, 'rb') as file:
        print("Reading calibration file")
        for face in range(6):
            colorReference[face] = struct.unpack('4I', file.read(16))
            file.close
except:
    print("No calibration data.  please calibrate the cube.")

scaner = ColorSensor('A')
#color values go here

#pos = motor.get_position()
#print("hello {}".format(pos))

# Functions
def Initialize():
    # setting the home state for the two motors
    flipperMotor.release = False
    rotaterMotor.release = False
    flipperMotor.set_default_speed(20)
    rotaterMotor.set_default_speed(20)
    flipperMotor.run_to_position(flipperHome, direction="anticlockwise")
    rotaterMotor.run_to_position(rotaterHome)

def Solved():
    # what will happon when the cube is solved
    flipperMotor.run_to_position(flipperHome, direction="anticlockwise")
    rotaterMotor.run_for_degrees(0)
    # add fun stuff

def turnD(count, direction = regular):
    # turning the D layer on the cube
    flipperMotor.run_to_position(flipperHold)
    internal_rotateY(count, direction)

def rotateY(count, direction = regular):
    # rotating the cube on the y-axis
    if flipperMotor.get_position()-20 < flipperHold and flipperMotor.get_position()+20 > flipperHold:
        flipperMotor.run_to_position(flipperSpin, direction="anticlockwise" )

    if direction == regular :
        rotaterMotor.run_for_degrees(90 * count)
    else:
        rotaterMotor.run_for_degrees(-90 * count)

def internal_rotateY(count, direction = regular):
    # alowing the cube carier to turn the cube
    if direction == regular :
        rotaterMotor.run_for_degrees(-90 * count)
    else:
        rotaterMotor.run_for_degrees(90 * count)

def flipX(count):
    # fliping the cube on the x-axis
    for x in range(count):
        flipperMotor.run_to_position(flipperHold)
        time.sleep(.3)
        flipperMotor.run_to_position(flipperFlip)
        time.sleep(.5)

def calibrate():
    # the motion to calibrate the colors
    flipperMotor.run_to_position(flipperHold)
    flipX(1)
    calibrateCenter(Face.U)
    flipX(1)
    calibrateCenter(Face.F)
    flipX(1)
    calibrateCenter(Face.D)
    flipX(1)
    calibrateCenter(Face.B)
    rotateY(1)
    flipX(1)
    calibrateCenter(Face.R)
    flipX(2)
    calibrateCenter(Face.L)
    rotateY(1, prime)
    flipX(1)
    rotateY(1, prime)
    # save color reference
    with open(calibrationFile,'wb')as file:
        for rgb in colorReference:
            file.write(struct.pack('4I',*rgb))
    file.close

def calibrateCenter(face):
    # scaning the centers to compair the color to other peices
    flipperMotor.run_to_position(flipperScanCenter)
    time.sleep(0.5)
    rgb = scaner.get_color_rgbi()
    colorReference[face] = rgb
    print('{} center {}R {}G {}B {}I'.format(face,rgb[0],rgb[1],rgb[2],rgb[3]))

def getSide(rgb):
    bestSide = -1
    bestSideE = 100000000000
    # loop all the calibrarion colors and return the index of the closest one
    for currentSide in range(6):
        refRgb = colorReference[currentSide]
        # fancy math
        eTotal = colorDistance(rgb, refRgb)
        # er = abs (rgb[0] - refRgb[0])
        # eg = abs (rgb[1] - refRgb[1])
        # eb = abs (rgb[2] - refRgb[2])
        # eTotal = er + eg + eb
        # may need to inprove this compairison
        if eTotal < bestSideE:
            bestSide = currentSide
            bestSideE = eTotal
    return bestSide

#             |************|
#             |*U1**U2**U3*|
#             |************|
#             |*U4**U5**U6*|
#             |************|
#             |*U7**U8**U9*|
# ____________|************|_________________________
# ************|************|************|************|
# *L1**L2**L3*|*F1**F2**F3*|*R1**R2**R3*|*B1**B2**B3*|
# ************|************|************|************|
# *L4**L5**L6*|*F4**F5**F6*|*R4**R5**R6*|*B4**B5**B6*|
# ************|************|************|************|
# *L7**L8**L9*|*F7**F8**F9*|*R7**R8**R9*|*B7**B8**B9*|
# ************|************|************|************|
# ------------|************|-------------------------
#             |*D1**D2**D3*|
#             |************|
#             |*D4**D5**D6*|
#             |************|
#             |*D7**D8**D9*|
#             |************|

scanResult = [None] * (6 * 9)
scanColorResult = [[None]*9] * 6

def scanCube():
    # scaning the whole cube
    flipperMotor.run_to_position(flipperHold)
    flipX(1)
    scanFace(Face.U)
    flipX(1)
    scanFace(Face.F)
    flipX(1)
    scanFace(Face.D)
    flipX(1)
    rotateY(2)
    scanFace(Face.B)
    rotateY(1, prime)
    flipX(1)
    rotateY(1)
    scanFace(Face.R)
    flipX(2)
    rotateY(2)
    scanFace(Face.L)
    # puttting the cube back in the right orentation
    rotateY(2)
    flipX(1)
    rotateY(1, prime)
    cubeString = ''.join(scanResult)
    print("cubestring = %s" % cubeString)
    for i in range(6):
        print("{} = {}".format(faceTable[i], ' '.join(scanColorResult[i])))

    # send the cube state to the raspberry pi to be solved
    return cubeString

def scanFace(face):
    # center
    flipperMotor.run_to_position(flipperScanCenter)
    scanTile(face, 5)

    # scan the tiles
    position = 0
    rotaterMotor.run_to_position(position)
    tiles = [8,9,6,3,2,1,4,7]
    for tileIndex in range(8):
        if (tileIndex % 2 == 1): # odd number must be a corner
            flipperMotor.run_to_position(flipperScanCorner)
        else:
            flipperMotor.run_to_position(flipperScanEdge)
        scanTile(face, tiles[tileIndex])
        position += 45
        angle = position if position <= 180 else position - 360
        print("{} - {}".format(position, angle))
        rotaterMotor.run_to_position(angle)
    time.sleep(0.3)

def scanTile(face, tile):
    # stating the location and color
    rgb = scaner.get_color_rgbi()
    color = getSide(rgb)
    scanResult[(face*9) + tile - 1] = faceTable[color]
    scanColorResult[face][tile - 1] = colorTable[color] # for debugging
    print("{}-{} color is {}".format(faceTable[face], tile, colorTable[color]))

#  UUUUUUUUU RRRFRRRRR FLFFFFFFF DDDDDDDDD LLLRLLLLL BBBBBBBBB

def uMove(count, direction = regular):
    flipX(2)
    turnD(count, direction)
    flipX(2)

def fMove(count, direction = regular):
    rotateY(2)
    flipX(1)
    turnD(count, direction)
    rotateY(2)
    flipX(1)

def bMove(count, direction = regular):
    flipX(1)
    turnD(count, direction)
    flipX(3)

def rMove(count, direction = regular):
    rotateY(1, prime)
    flipX(1)
    turnD(count, direction)
    rotateY(2)
    flipX(1)
    rotateY(1, prime)

def lMove(count, direction = regular):
    rotateY(1)
    flipX(1)
    turnD(count, direction)
    rotateY(2)
    flipX(1)
    rotateY(1)

def dMove(count, direction = regular):
    turnD(count, direction)

def solveCube(solution: str):
    print("solving cube with moves: %s" % solution)
    moves = solution.split(' ')
    for move in moves:
        print("Executing move: %s" % move)
        face = move[0]
        count = 1
        direction = regular
        if len(move) == 2:
            if move[1] == "2":
                count = 2
            elif move[1] == "'":
                direction = prime
        # call the move function dynamicly using a nameing convention see https://www.danielmorell.com/blog/dynamically-calling-functions-in-python-safely
        globals()["{}Move".format(face.lower())](count, direction)

# compute distance between two colors.  see https://stackoverflow.com/questions/54242194/python-find-the-closest-color-to-a-color-from-giving-list-of-colors
def colorDistance(rgbi1, rgb2):
    r, g, b, i = rgbi1
    cr, cg, cb, ib = rgb2
    # pythagorean theorem
    return sqrt((r - cr)**2 + (g - cg)**2 + (b - cb)**2 + (i - ib)**2)

# in case we need super fancy math
# convert rgb to CIELAB color space. see https://en.wikipedia.org/wiki/CIELAB_color_space
def rgb2lab ( inputColor ) :

   num = 0
   RGB = [0, 0, 0]

   for value in inputColor :
       value = float(value) / 255

       if value > 0.04045 :
           value = ( ( value + 0.055 ) / 1.055 ) ** 2.4
       else :
           value = value / 12.92

       RGB[num] = value * 100
       num = num + 1

   XYZ = [0, 0, 0,]

   X = RGB [0] * 0.4124 + RGB [1] * 0.3576 + RGB [2] * 0.1805
   Y = RGB [0] * 0.2126 + RGB [1] * 0.7152 + RGB [2] * 0.0722
   Z = RGB [0] * 0.0193 + RGB [1] * 0.1192 + RGB [2] * 0.9505
   XYZ[ 0 ] = round( X, 4 )
   XYZ[ 1 ] = round( Y, 4 )
   XYZ[ 2 ] = round( Z, 4 )

   XYZ[ 0 ] = float( XYZ[ 0 ] ) / 95.047         # ref_X =  95.047   Observer= 2°, Illuminant= D65
   XYZ[ 1 ] = float( XYZ[ 1 ] ) / 100.0          # ref_Y = 100.000
   XYZ[ 2 ] = float( XYZ[ 2 ] ) / 108.883        # ref_Z = 108.883

   num = 0
   for value in XYZ :

       if value > 0.008856 :
           value = value ** ( 0.3333333333333333 )
       else :
           value = ( 7.787 * value ) + ( 16 / 116 )

       XYZ[num] = value
       num = num + 1

   Lab = [0, 0, 0]

   L = ( 116 * XYZ[ 1 ] ) - 16
   a = 500 * ( XYZ[ 0 ] - XYZ[ 1 ] )
   b = 200 * ( XYZ[ 1 ] - XYZ[ 2 ] )

   Lab [ 0 ] = round( L, 4 )
   Lab [ 1 ] = round( a, 4 )
   Lab [ 2 ] = round( b, 4 )

   return Lab

# main program
Initialize()

# wait for scramble and input

# tests
# calibrate()
cube = scanCube()
solution = kociemba.solve(cube)
solveCube(solution)

# print("Solving %s" % solution)
# m.run_for_rotations(-.1, 50)

# lMove(1)
# bMove(1, prime)
# dMove(1)
# rMove(2)
# bMove(1)
# lMove(1, prime)
# bMove(2)
# lMove(1)
# bMove(1, prime)
# lMove(2)
# dMove(2)
# bMove(2)
# rMove(2)
# bMove(1, prime)
# dMove(2)
# lMove(2)
# bMove(1, prime)
# uMove(2)
# dMove(2)
# lMove(1,prime)

#colorReference = [(49,13,99), (600,346,200), (50,500,50), (80,660,570), (6,760,50), (51,15,101)]
#print("1 best side is {}".format(getSide((50,14,100))))
#print("2 best side is {}".format(getSide((50,14,287))))
#print("3 best side is {}".format(getSide((789,660,570))))
#calibrate()
#turnD(1, regular)
#flipX(2)
#rotateY(2, prime)
#turnD(1, prime)
#rotateY(1)
#flipX(1)
#turnD(2)
#turnD(1)
#scanCube()

Solved()


import hashlib

PUZZLE_INPUT = 3012210

# PUZZLE_INPUT = 5

class Node:
    def __init__(self, number):
        self.number = number
        self.presents = 1
        self.next = None
        self.prev = None

head = Node(1)
prev = head
curr = None

for i in range(1, PUZZLE_INPUT):
    curr = Node(i + 1)
    prev.next = curr
    prev = curr

curr.next = head

curr = head

while curr != curr.next:
    curr.presents += curr.next.presents
    curr.next = curr.next.next
    curr = curr.next

# Part 1 = 1830117
print(f"answer = {curr.number}")

head = Node(1)
prev = head
curr = None

HALF = PUZZLE_INPUT // 2
half = None

for i in range(1, PUZZLE_INPUT):
    curr = Node(i + 1)
    prev.next = curr
    curr.prev = prev
    prev = curr
    if i == HALF:
        half = curr

curr.next = head
head.prev = curr

curr = head
num_elves = PUZZLE_INPUT

while curr != curr.next:
    curr.presents += half.presents
    half.prev.next = half.next
    half.next.prev = half.prev
    curr = curr.next
    if num_elves % 2 == 0:
        half = half.next
    else:
        half = half.next.next

    num_elves -= 1

# Part 2 = 1417887
print(f"answer = {curr.number}")


import sys

import ply.lex as lex

tokens = (
    'K_FOREACH',
    'K_PRINT',
    'K_WHILE',
    'K_REPEAT',
    'K_UNTIL',
    'K_BEGIN',
    'K_END',
    'K_DECLARE',
    'K_IF',
    'K_THEN',
    'K_MAIN',
    'K_INTEGER',
    'K_FLOAT',
    'OP_ASSIGN',
    'OP_ADD',
    'OP_SUB',
    'OP_MUL',
    'OP_DIV',
    'OP_LT',
    'OP_GT',
    'OP_LEQ',
    'OP_GEQ',
    'OP_EQ',
    'OP_DIFF',
    'CAR_A',
    'CAR_B',
    'CAR_C',
    'CAR_AB',
    'T_ID',
    'L_INTEGER',
    'L_FLOAT',
    'L_SEMICOLON',
    # based on what I've read on PLY, including semicolon as a token makes things a lot easier compare to in C.
    'T_EOF'
)

tokenNum = {
    'K_FOREACH': 200,
    'K_PRINT': 201,
    'K_WHILE': 202,
    'K_REPEAT': 203,
    'K_UNTIL': 204,
    'K_BEGIN': 205,
    'K_END': 206,
    'K_DECLARE': 209,
    'K_IF': 210,
    'K_THEN': 211,
    'K_MAIN': 212,
    'K_INTEGER': 213,
    'K_FLOAT': 214,
    'OP_ASSIGN': 220,
    'OP_ADD': 221,
    'OP_SUB': 222,
    'OP_MUL': 223,
    'OP_DIV': 224,
    'OP_LT': 225,
    'OP_GT': 226,
    'OP_LEQ': 227,
    'OP_GEQ': 228,
    'OP_EQ': 229,
    'OP_DIFF': 230,
    'CAR_A': 400,
    'CAR_B': 401,
    'CAR_C': 402,
    'CAR_AB': 403,
    'T_ID': 240,
    'L_INTEGER': 241,
    'L_FLOAT': 242,
    'T_EOF': 280,

}

t_L_SEMICOLON = r';'
t_OP_ADD = r'\+'
t_OP_SUB = r'-'
t_OP_MUL = r'\*'
t_OP_DIV = r'/'
t_OP_LEQ = r'<='
t_OP_GEQ = r'>='
t_OP_EQ = r'=='
t_OP_DIFF = r'!='
t_OP_LT = r'<'
t_OP_GT = r'>'
t_K_MAIN = r'main'
t_K_INTEGER = r'integer'
t_K_FLOAT = r'float'
t_K_FOREACH = r'foreach'
t_K_BEGIN = r'begin'
t_K_END = r'end'
t_K_REPEAT = r'repeat'
t_K_UNTIL = r'until'
t_K_WHILE = r'while'
t_K_DECLARE = r'declare'
t_K_IF = r'if'
t_K_THEN = r'then'
t_K_PRINT = r'print'
t_L_INTEGER = r'\d+'
t_T_ID = r'(_|[a-z])(_|[a-z]|[0-9])(_|[a-z]|[0-9])+'
t_L_FLOAT = r'(\+|-)*[0-9]+\.[0-9]+'
t_T_EOF = r'<<EOF>>'

t_OP_ASSIGN = r'='

def t_error(t):
    t.lexer.skip(1)

lexer = lex.lex()
for line in sys.stdin:
    lexer.input(line)
    tok = lexer.token()
    while tok:
        if not tok:
            break
        print('token = %d' % tokenNum[tok.type])
        tok = lexer.token()


"""Program: Project Euler 3   author: Kevin Radja   date:June/29/17.

What is the largest prime factor of the number 600851475143 ?
"""

# import operator
import functools

def primenumbers(number, recurv, templist):
    """Fine all the primenumbers of a number."""
    for j in recurv:
        templist = [i for i in templist if i % j != 0]

    for x in templist:
        if not recurv:
            if number % x == 0:
                recurv.append(x)
                primenumbers(number, recurv, templist)
        if number % x == 0 and x > recurv[-1]:
            recurv.append(x)
            '''while tempnumber != 1 and tempnumber in recurv:
                if tempnumber % x == 0:
                    tempnumber = number / x
                    recurv.append(x)'''
            answer = functools.reduce(lambda x, y: x * y, recurv)
            print('answer:')
            print(answer)
            print(number)
            if answer == number:
                print('worked')
                break
            else:
                print('hi')
                primenumbers(number, recurv, templist)
    return recurv

number = 13195
start = 2

templist = list(range(2, number))
x = primenumbers(number, [], templist)
print(x)


#import tensorflow as tf
import pandas as pd
from PIL import Image
import numpy as np
import os
import cv2

"""
解析csv文件， 并保存为图片
"""

emotions= {
	"0":"anger",
	"1":"disgust",
	"2":"fear",
	"3":"happy",
	"4":"sad",
	"5":"surprised",
	"6":"normal",
}

def createDir(dir):
	if not os.path.exists(dir):
		os.makedirs(dir)

def load_csv2pic(file):
	#读取csv文件
	faces_data = pd.read_csv(file)
	# print(type(faces_data)) <class 'pandas.core.frame.DataFrame'>
	# print(faces_data)
	image_count = 0
	# loc 定位列表中的行列取值
	for index in range(len(faces_data)):
		emotion_type = faces_data.loc[index][0]
		image_data = faces_data.loc[index][1]
		usage_data = faces_data.loc[index][2]

		# 将图片数据转换成48*48的格式，方便后续图片展示
		# map函数，映射， 将每个值转换为float 类型
		image_data_array = list(map(float, image_data.split()))
		image_data_array = np.asarray(image_data_array)
		# print(image_data_array.shape) 48*48=2304
		image_reshape = image_data_array.reshape(48, 48)
		# print(image_reshape)
		#
		#选择分类，并创建文件名
		dir_folder = usage_data
		emotion_type_folder = emotions[str(emotion_type)]
		image_reshape_path = os.path.join(dir_folder, emotion_type_folder )

		createDir(dir_folder)
		createDir(image_reshape_path)

		image_reshape_name = os.path.join(image_reshape_path,str(index) + '.jpg')
		#  fer2013都是灰度图，故mode=L,彩色为RGB https://blog.csdn.net/sempronx86/article/details/104096147?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-6.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-6.control
		Image.fromarray(image_reshape.astype('uint8'), mode='L').save(image_reshape_name)
		image_count = index

	print('总共有' + str(image_count) + '张图片')

		# pass
		# print(emotion_data)

def main():
	file = "./fer2013/fer2013.csv"
	load_csv2pic(file)
	pass

if __name__ == '__main__':
	main()


# python program for passing of attributes and methods of one class to another class
# this class contains employee details
class Emp:

    def __init__(self, id, name, salary,):  # constructor
        self.id = id
        self.name = name
        self.salary = salary

    def display(self):  # instance method
        print("Id = ", self.id)
        print("Name  = ", self.name)
        print("Salary = ", self.salary)
# this class displays employee details
class Myclass:

    @staticmethod
    def display(e):  # static method to receive Emp class instance and display employee details
        print("Id = ", e.id)
        print("Name  = ", e.name)
        print("Salary = ", e.salary)

e = Emp(56, "Madhu Kumar", 100000000.00)

Myclass.display(e)  # passing Emp class object e to Myclass-static method ie.display(e) and calling it


x = input().split()
a = int(x[0])
b = int(x[1])

d = []

def second(x):
    return x[1]

while(b):
    b-=1
    x = input().split()
    k = int(x[0])
    m = int(x[1])
    d.append((k, m))

d = sorted(d, key=second, reverse=True)
#print(d)
res = 0
for x in d:
    #print(a)
    if(a-x[0] >= 0):
        res += x[1]*x[0]
        a-=x[0]
    else:
        res += x[1]*a
        break

print(res)


import fire
import pandas as pd

class PersonBill():
    def __init__(self, name):
        self.name = name
        self.income = {}
        self.payment = {}
        self.need_pay = {}
        self.items = []

    def print_payment(self):
        for name, money in self.payment.items():
            print('需要向{}支付{}'.format(name, money))

    def print_need_pay(self):

        for obj, money in self.need_pay.items():
            _type = '收取' if money > 0 else '支付'
            print('{}需要向{}{}{}'.format(self.name, obj, _type, abs(money)))

class Bill():
    def __init__(self, csv_file):
        bill_df = pd.read_csv(csv_file)
        self.bill_df = bill_df[(bill_df['支付状态'] == 'Yes') & (bill_df['归档'] == 'No')]
        self.persons = self.get_all_person()
        self.person_detail = {}

        for person in self.persons:
            self.set_person_bill_detail(person)

    def run(self):
        self.handle_bill()
        self.get_all_person()
        for name, detail in self.person_detail.items():
            self.get_person_need_pay(name)
            detail.print_need_pay()

    def set_person_bill_detail(self, name):
        self.person_detail[name] = PersonBill(name)

    def get_all_person(self):
        persons = set(self.bill_df['参与人'])
        persons.update(set(self.bill_df['实际支付人']))

        all_multi_person = [person for person in persons if ',' in str(person)]
        one_persons = persons.difference(all_multi_person)

        for multi_person in all_multi_person:
            one_persons.update(set(multi_person.split(',')))

        return one_persons

    def a_pay_to_b(self, a, b, money):
        """
        a需要向b支付
        :param money: 金额
        :param a:
        :param b:
        :return:
        """
        # payment
        if not self.person_detail[a].payment.get(b, None):
            self.person_detail[a].payment[b] = money
        else:
            self.person_detail[a].payment[b] += money

        # income
        if not self.person_detail[b].income.get(a, None):
            self.person_detail[b].income[a] = money
        else:
            self.person_detail[b].income[a] += money

    def handle_bill(self):
        for index, item in self.bill_df.iterrows():
            self.handle_item(item)

    def handle_item(self, item):
        payer = item['实际支付人']
        if not isinstance(payer, float):
            if not isinstance(item['参与人'], float):
                participant = item['参与人'].split(',')
                money = item['金额']
                _type = item['支付类型']
                if _type == '平分':
                    avg = money / len(participant)
                    for person in participant:
                        if person != payer:
                            self.a_pay_to_b(person, payer, avg)

                if _type == '个人':
                    assert len(participant) == 1
                    if participant[0] != payer:
                        self.a_pay_to_b(participant[0], payer, money)

    def get_person_need_pay(self, person_name):
        payment = self.person_detail[person_name].payment
        income = self.person_detail[person_name].income

        person = [name for name in income.keys()]
        person.extend([name for name in payment.keys()])

        need_pay = {}
        for obj in person:
            need_pay[obj] = (income.get(obj, 0)) - (payment.get(obj, 0))

        self.person_detail[person_name].need_pay = need_pay

def main(file):
    bill = Bill(file)
    bill.run()

if __name__ == '__main__':
    fire.Fire(main)


#
# @lc app=leetcode id=39 lang=python3
#
# [39] Combination Sum
#
# https://leetcode.com/problems/combination-sum/description/
#
# algorithms
# Medium (68.28%)
# Likes:    15034
# Dislikes: 300
# Total Accepted:    1.4M
# Total Submissions: 2M
# Testcase Example:  '[2,3,6,7]\n7'
#
# Given an array of distinct integers candidates and a target integer target,
# return a list of all unique combinations of candidates where the chosen
# numbers sum to target. You may return the combinations in any order.
#
# The same number may be chosen from candidates an unlimited number of times.
# Two combinations are unique if the frequency of at least one of the chosen
# numbers is different.
#
# The test cases are generated such that the number of unique combinations that
# sum up to target is less than 150 combinations for the given input.
#
#
# Example 1:
#
#
# Input: candidates = [2,3,6,7], target = 7
# Output: [[2,2,3],[7]]
# Explanation:
# 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple
# times.
# 7 is a candidate, and 7 = 7.
# These are the only two combinations.
#
#
# Example 2:
#
#
# Input: candidates = [2,3,5], target = 8
# Output: [[2,2,2,2],[2,3,3],[3,5]]
#
#
# Example 3:
#
#
# Input: candidates = [2], target = 1
# Output: []
#
#
#
# Constraints:
#
#
# 1 <= candidates.length <= 30
# 2 <= candidates[i] <= 40
# All elements of candidates are distinct.
# 1 <= target <= 40
#
#
#

# @lc code=start
class Solution:
    def find(self,candidates,remains,temp):
        result = temp.copy()
        # print(candidates,remains,result)
        for i in range(len(candidates)):
            if remains - candidates[i] == 0:
                # print(candidates,remains,result)
                result.append(candidates[i])
                self.results.append(result)
                return
            elif (remains - candidates[i] > 0):
                result.append(candidates[i])
                self.find(candidates[i:],remains - candidates[i],result)
                result.remove(candidates[i])
            else:
                return
        return

    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        self.results = []
        self.find(candidates,target,[])
        return self.results

# @lc code=end


from .six.moves import reduce

def getattrs(o, *attrs, **kwargs):
    """
    >>> getattrs((), '__iter__', '__name__', 'strip')('_')
    'iter'
    >>> getattrs((), 'foo', 'bar', default=0)
    0
    """
    if 'default' in kwargs:
        default = kwargs['default']
        c = o
        for attr in attrs:
            try:
                c = getattr(c, attr)
            except AttributeError:
                return default
        return c
    else:
        return reduce(getattr, attrs, o)


from termcolor import *

def p(text, color):
	print(colored(text, color))

p('Red Text', 'red')
p('Blue Text', 'blue')
p('Green Text', 'green')
p('Cyan Text', 'cyan')
p('White Text', 'white')
p('Yellow Text', 'yellow')

print("\n")

input_text = f'''{colored("What", 'red')} {colored("Is", 'blue')} {colored("Your", 'green')} {colored("Name", 'cyan')}{colored("?", 'white')}\n'''

name = input(input_text)
hello = colored("Hello,", 'red')
n = colored(name, 'blue')
ex = colored("!", 'green')
print(hello, n + ex)

print(colored('\n1 + 1 = 2', 'cyan'))


from __future__ import annotations

import copy
import json
import os
import pathlib
import re
import sys
import traceback
from typing import Any, Dict, Sequence

# **********************************************************
# Update sys.path before importing any bundled libraries.
# **********************************************************
def update_sys_path(path_to_add: str, strategy: str) -> None:
    """Add given path to `sys.path`."""
    if path_to_add not in sys.path and os.path.isdir(path_to_add):
        if strategy == "useBundled":
            sys.path.insert(0, path_to_add)
        elif strategy == "fromEnvironment":
            sys.path.append(path_to_add)

# Ensure that we can import LSP libraries, and other bundled libraries.
update_sys_path(
    os.fspath(pathlib.Path(__file__).parent.parent / "libs"),
    os.getenv("LS_IMPORT_STRATEGY", "useBundled"),
)

# **********************************************************
# Imports needed for the language server goes below this.
# **********************************************************
import jsonrpc
import utils
from pygls import lsp, protocol, server, uris, workspace

WORKSPACE_SETTINGS = {}
RUNNER = pathlib.Path(__file__).parent / "runner.py"

MAX_WORKERS = 5
LSP_SERVER = server.LanguageServer(max_workers=MAX_WORKERS)

# **********************************************************
# Tool specific code goes below this.
# **********************************************************
TOOL_MODULE = "flake8"
TOOL_DISPLAY = "Flake8"

# Default arguments always passed to flake8.
TOOL_ARGS = ["--format='%(row)d,%(col)d,%(code).1s,%(code)s:%(text)s'"]

# Minimum version of flake8 supported.
MIN_VERSION = "5.0.0"

# **********************************************************
# Linting features start here
# **********************************************************

@LSP_SERVER.feature(lsp.TEXT_DOCUMENT_DID_OPEN)
def did_open(params: lsp.DidOpenTextDocumentParams) -> None:
    """LSP handler for textDocument/didOpen request."""
    document = LSP_SERVER.workspace.get_document(params.text_document.uri)
    diagnostics: list[lsp.Diagnostic] = _linting_helper(document)
    LSP_SERVER.publish_diagnostics(document.uri, diagnostics)

@LSP_SERVER.feature(lsp.TEXT_DOCUMENT_DID_SAVE)
def did_save(params: lsp.DidSaveTextDocumentParams) -> None:
    """LSP handler for textDocument/didSave request."""
    document = LSP_SERVER.workspace.get_document(params.text_document.uri)
    diagnostics: list[lsp.Diagnostic] = _linting_helper(document)
    LSP_SERVER.publish_diagnostics(document.uri, diagnostics)

@LSP_SERVER.feature(lsp.TEXT_DOCUMENT_DID_CLOSE)
def did_close(params: lsp.DidCloseTextDocumentParams) -> None:
    """LSP handler for textDocument/didClose request."""
    document = LSP_SERVER.workspace.get_document(params.text_document.uri)
    # Publishing empty diagnostics to clear the entries for this file.
    LSP_SERVER.publish_diagnostics(document.uri, [])

def _linting_helper(document: workspace.Document) -> list[lsp.Diagnostic]:
    try:
        result = _run_tool_on_document(document, use_stdin=False)
        if result and result.stdout:
            log_to_output(f"{document.uri} :\r\n{result.stdout}")

            # deep copy here to prevent accidentally updating global settings.
            settings = copy.deepcopy(_get_settings_by_document(document))
            return _parse_output_using_regex(
                result.stdout, severity=settings["severity"]
            )
    except Exception:
        LSP_SERVER.show_message_log(
            f"Linting failed with error:\r\n{traceback.format_exc()}",
            lsp.MessageType.Error,
        )
    return []

def _get_severity(
    code: str, code_type: str, severity: Dict[str, str]
) -> lsp.DiagnosticSeverity:
    """Converts severity provided by linter to LSP specific value."""
    value = severity.get(code, None) or severity.get(code_type, "Error")
    try:
        return lsp.DiagnosticSeverity[value]
    except KeyError:
        pass

    return lsp.DiagnosticSeverity.Error

DIAGNOSTIC_RE = re.compile(
    r"(?P<line>\d+),(?P<column>-?\d+),(?P<type>\w+),(?P<code>\w+\d+):(?P<message>[^\r\n]*)"
)

def _parse_output_using_regex(
    content: str, severity: Dict[str, str]
) -> list[lsp.Diagnostic]:
    lines: list[str] = content.splitlines()
    diagnostics: list[lsp.Diagnostic] = []

    line_at_1 = True
    column_at_1 = True

    line_offset = 1 if line_at_1 else 0
    col_offset = 1 if column_at_1 else 0
    for line in lines:
        if line.startswith("'") and line.endswith("'"):
            line = line[1:-1]
        match = DIAGNOSTIC_RE.match(line)
        if match:
            data = match.groupdict()
            position = lsp.Position(
                line=max([int(data["line"]) - line_offset, 0]),
                character=int(data["column"]) - col_offset,
            )
            diagnostic = lsp.Diagnostic(
                range=lsp.Range(
                    start=position,
                    end=position,
                ),
                message=data.get("message"),
                severity=_get_severity(data["code"], data["type"], severity),
                code=data["code"],
                source=TOOL_DISPLAY,
            )
            diagnostics.append(diagnostic)

    return diagnostics

# **********************************************************
# Linting features end here
# **********************************************************

# **********************************************************
# Required Language Server Initialization and Exit handlers.
# **********************************************************
@LSP_SERVER.feature(lsp.INITIALIZE)
def initialize(params: lsp.InitializeParams) -> None:
    """LSP handler for initialize request."""
    log_to_output(f"CWD Server: {os.getcwd()}")

    paths = "\r\n   ".join(sys.path)
    log_to_output(f"sys.path used to run Server:\r\n   {paths}")

    settings = params.initialization_options["settings"]
    _update_workspace_settings(settings)
    log_to_output(
        f"Settings used to run Server:\r\n{json.dumps(settings, indent=4, ensure_ascii=False)}\r\n"
    )

    if isinstance(LSP_SERVER.lsp, protocol.LanguageServerProtocol):
        if any(setting["logLevel"] == "debug" for setting in settings):
            LSP_SERVER.lsp.trace = lsp.Trace.Verbose
        elif any(
            setting["logLevel"] in ["error", "warn", "info"] for setting in settings
        ):
            LSP_SERVER.lsp.trace = lsp.Trace.Messages
        else:
            LSP_SERVER.lsp.trace = lsp.Trace.Off
    _log_version_info()

@LSP_SERVER.feature(lsp.EXIT)
def on_exit():
    """Handle clean up on exit."""
    jsonrpc.shutdown_json_rpc()

def _log_version_info() -> None:
    for value in WORKSPACE_SETTINGS.values():
        try:
            from packaging.version import parse as parse_version

            settings = copy.deepcopy(value)
            result = _run_tool(["--version"], settings)
            code_workspace = settings["workspaceFS"]
            log_to_output(
                f"Version info for linter running for {code_workspace}:\r\n{result.stdout}"
            )

            # This is text we get from running `flake8 --version`
            # Example:
            # 5.0.4 (mccabe: 0.7.0, pycodestyle: 2.9.1, pyflakes: 2.5.0) CPython 3.7.7
            # ^---^---- this is the version info we want
            first_line = result.stdout.splitlines(keepends=False)[0]
            actual_version = first_line.split(" ")[0]

            version = parse_version(actual_version)
            min_version = parse_version(MIN_VERSION)

            if version < min_version:
                log_error(
                    f"Version of linter running for {code_workspace} is NOT supported:\r\n"
                    f"SUPPORTED {TOOL_MODULE}>={min_version}\r\n"
                    f"FOUND {TOOL_MODULE}=={actual_version}\r\n"
                )
            else:
                log_to_output(
                    f"SUPPORTED {TOOL_MODULE}>={min_version}\r\n"
                    f"FOUND {TOOL_MODULE}=={actual_version}\r\n"
                )
        except:  # noqa: E722
            log_to_output(
                f"Error while detecting flake8 version:\r\n{traceback.format_exc()}"
            )

# *****************************************************
# Internal functional and settings management APIs.
# *****************************************************
def _update_workspace_settings(settings):
    for setting in settings:
        key = uris.to_fs_path(setting["workspace"])
        WORKSPACE_SETTINGS[key] = {
            **setting,
            "workspaceFS": key,
        }

def _get_settings_by_document(document: workspace.Document | None):
    if len(WORKSPACE_SETTINGS) == 1 or document is None or document.path is None:
        return list(WORKSPACE_SETTINGS.values())[0]

    document_workspace = pathlib.Path(document.path)
    workspaces = {s["workspaceFS"] for s in WORKSPACE_SETTINGS.values()}

    # COMMENT: about non workspace files
    while document_workspace != document_workspace.parent:
        if str(document_workspace) in workspaces:
            return WORKSPACE_SETTINGS[str(document_workspace)]
        document_workspace = document_workspace.parent

    return list(WORKSPACE_SETTINGS.values())[0]

# *****************************************************
# Internal execution APIs.
# *****************************************************
def _run_tool_on_document(
    document: workspace.Document,
    use_stdin: bool = False,
    extra_args: Sequence[str] = [],
) -> utils.RunResult | None:
    """Runs tool on the given document.

    if use_stdin is true then contents of the document is passed to the
    tool via stdin.
    """
    if str(document.uri).startswith("vscode-notebook-cell"):
        log_warning(f"Skipping notebook cells [Not Supported]: {str(document.uri)}")
        return None

    if utils.is_stdlib_file(document.path):
        log_warning(f"Skipping standard library file: {document.path}")
        return None

    # deep copy here to prevent accidentally updating global settings.
    settings = copy.deepcopy(_get_settings_by_document(document))

    code_workspace = settings["workspaceFS"]
    cwd = settings["workspaceFS"]

    use_path = False
    use_rpc = False
    if settings["path"]:
        # 'path' setting takes priority over everything.
        use_path = True
        argv = settings["path"]
    elif settings["interpreter"] and not utils.is_current_interpreter(
        settings["interpreter"][0]
    ):
        # If there is a different interpreter set use JSON-RPC to the subprocess
        # running under that interpreter.
        argv = [TOOL_MODULE]
        use_rpc = True
    else:
        # if the interpreter is same as the interpreter running this
        # process then run as module.
        argv = [TOOL_MODULE]

    argv += TOOL_ARGS + settings["args"] + extra_args

    if use_stdin:
        argv += ["--stdin-display-name", document.path, "-"]
    else:
        argv += [document.path]

    if use_path:
        # This mode is used when running executables.
        log_to_output(" ".join(argv))
        log_to_output(f"CWD Server: {cwd}")
        result = utils.run_path(
            argv=argv,
            use_stdin=use_stdin,
            cwd=cwd,
            source=document.source.replace("\r\n", "\n"),
        )
        if result.stderr:
            log_to_output(result.stderr)
    elif use_rpc:
        # This mode is used if the interpreter running this server is different from
        # the interpreter used for running this server.
        log_to_output(" ".join(settings["interpreter"] + ["-m"] + argv))
        log_to_output(f"CWD Linter: {cwd}")

        result = jsonrpc.run_over_json_rpc(
            workspace=code_workspace,
            interpreter=settings["interpreter"],
            module=TOOL_MODULE,
            argv=argv,
            use_stdin=use_stdin,
            cwd=cwd,
            source=document.source,
        )
        result = _to_run_result_with_logging(result)
    else:
        # In this mode the tool is run as a module in the same process as the language server.
        log_to_output(" ".join([sys.executable, "-m"] + argv))
        log_to_output(f"CWD Linter: {cwd}")
        # This is needed to preserve sys.path, in cases where the tool modifies
        # sys.path and that might not work for this scenario next time around.
        with utils.substitute_attr(sys, "path", [""] + sys.path[:]):
            try:
                result = utils.run_module(
                    module=TOOL_MODULE,
                    argv=argv,
                    use_stdin=use_stdin,
                    cwd=cwd,
                    source=document.source,
                )
            except Exception:
                log_error(traceback.format_exc(chain=True))
                raise
        if result.stderr:
            log_to_output(result.stderr)

    return result

def _run_tool(extra_args: Sequence[str], settings: Dict[str, Any]) -> utils.RunResult:
    """Runs tool."""
    code_workspace = settings["workspaceFS"]
    cwd = settings["workspaceFS"]

    use_path = False
    use_rpc = False
    if len(settings["path"]) > 0:
        # 'path' setting takes priority over everything.
        use_path = True
        argv = settings["path"]
    elif len(settings["interpreter"]) > 0 and not utils.is_current_interpreter(
        settings["interpreter"][0]
    ):
        # If there is a different interpreter set use JSON-RPC to the subprocess
        # running under that interpreter.
        argv = [TOOL_MODULE]
        use_rpc = True
    else:
        # if the interpreter is same as the interpreter running this
        # process then run as module.
        argv = [TOOL_MODULE]

    argv += extra_args

    if use_path:
        # This mode is used when running executables.
        log_to_output(" ".join(argv))
        log_to_output(f"CWD Server: {cwd}")
        result = utils.run_path(argv=argv, use_stdin=True, cwd=cwd)
        if result.stderr:
            log_to_output(result.stderr)
    elif use_rpc:
        # This mode is used if the interpreter running this server is different from
        # the interpreter used for running this server.
        log_to_output(" ".join(settings["interpreter"] + ["-m"] + argv))
        log_to_output(f"CWD Linter: {cwd}")
        result = jsonrpc.run_over_json_rpc(
            workspace=code_workspace,
            interpreter=settings["interpreter"],
            module=TOOL_MODULE,
            argv=argv,
            use_stdin=True,
            cwd=cwd,
        )
        result = _to_run_result_with_logging(result)
    else:
        # In this mode the tool is run as a module in the same process as the language server.
        log_to_output(" ".join([sys.executable, "-m"] + argv))
        log_to_output(f"CWD Linter: {cwd}")
        # This is needed to preserve sys.path, in cases where the tool modifies
        # sys.path and that might not work for this scenario next time around.
        with utils.substitute_attr(sys, "path", [""] + sys.path[:]):
            try:
                result = utils.run_module(
                    module=TOOL_MODULE, argv=argv, use_stdin=True, cwd=cwd
                )
            except Exception:
                log_error(traceback.format_exc(chain=True))
                raise
        if result.stderr:
            log_to_output(result.stderr)

    log_to_output(f"\r\n{result.stdout}\r\n")
    return result

def _to_run_result_with_logging(rpc_result: jsonrpc.RpcRunResult) -> utils.RunResult:
    error = ""
    if rpc_result.exception:
        log_error(rpc_result.exception)
        error = rpc_result.exception
    elif rpc_result.stderr:
        log_to_output(rpc_result.stderr)
        error = rpc_result.stderr
    return utils.RunResult(rpc_result.stdout, error)

# *****************************************************
# Logging and notification.
# *****************************************************
def log_to_output(
    message: str, msg_type: lsp.MessageType = lsp.MessageType.Log
) -> None:
    """Logs messages to Output > Flake8 channel only."""
    LSP_SERVER.show_message_log(message, msg_type)

def log_error(message: str) -> None:
    """Logs messages with notification on error."""
    LSP_SERVER.show_message_log(message, lsp.MessageType.Error)
    if os.getenv("LS_SHOW_NOTIFICATION", "off") in ["onError", "onWarning", "always"]:
        LSP_SERVER.show_message(message, lsp.MessageType.Error)

def log_warning(message: str) -> None:
    """Logs messages with notification on warning."""
    LSP_SERVER.show_message_log(message, lsp.MessageType.Warning)
    if os.getenv("LS_SHOW_NOTIFICATION", "off") in ["onWarning", "always"]:
        LSP_SERVER.show_message(message, lsp.MessageType.Warning)

def log_always(message: str) -> None:
    """Logs messages with notification."""
    LSP_SERVER.show_message_log(message, lsp.MessageType.Info)
    if os.getenv("LS_SHOW_NOTIFICATION", "off") in ["always"]:
        LSP_SERVER.show_message(message, lsp.MessageType.Info)

# *****************************************************
# Start the server.
# *****************************************************
if __name__ == "__main__":
    LSP_SERVER.start_io()