import imaplib
import email
import datetime
import time
import sys

# Config
EMAIL = "<YOUR EMAIL>"
PW = "<YOUR PASSWORD>"
FOLDER_TO_DELETE_FROM = '"[Google Mail]/All Mail"'
TRASH_FOLDER = '"[Google Mail]/Trash"'
METHOD_TO_USE = "delete_unread_promotions_not_important"
FILTER_DATE = "2021-12-31"  # delete emails up to this date

# All search methods will append the FILTER_DATE above
METHOD_SEARCH = {
    "delete_unread_promotions_not_important": "category:promotions NOT is: important in:unread",
    "delete_unread_promotions": "category:promotions in:unread",
    "delete_read_promotions": "category:promotions in:read",
    "delete_unread": "in:unread",
    "delete_unread_not_important": "NOT is: important in:unread",
}

def get_unix_timestamp(date_char=FILTER_DATE):
    dto = datetime.datetime.strptime(date_char, "%Y-%m-%d")
    return round(time.mktime(dto.timetuple()))

def delete_emails(method=METHOD_TO_USE):
    imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    imap.login(EMAIL, PW)
    # print(imap.list())
    # 1 set search criteria
    imap.select(FOLDER_TO_DELETE_FROM)
    gmail_search = f'"{METHOD_SEARCH[method]} before:{get_unix_timestamp()}"'
    typ, [msg_ids] = imap.search(None, "X-GM-RAW", gmail_search)
    id_list = [msg_ids.decode("utf-8")][0].split()
    num_emails = len(id_list)

    if query_yes_no(
        f"Do you wish to proceed with deletion of {num_emails}?"
    ):
        if num_emails == 0:
            print("No emails matching search criteria")
        else:
            print("Number of emails to be deleted:", num_emails)
            if isinstance(msg_ids, bytes):
                msg_ids = msg_ids.decode()

            # 2. Bulk move to trash folder
            msg_ids = ",".join(msg_ids.split(" "))
            print("Moving to Trash using X-GM_LABELS.")
            imap.store(msg_ids, "+X-GM-LABELS", "\\Trash")

            # 3. Empty trash
            print("Emptying Trash")
            imap.select(TRASH_FOLDER)
            imap.store("1:*", "+FLAGS", "\\Deleted")  # Flag all Trash as Deleted
            imap.expunge()
    else:
        print(f"Skipping deletion of {num_emails} emails")

    print("Completed and logging out")
    imap.close()
    imap.logout()

def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
            It must be "yes" (the default), "no" or None (meaning
            an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")

# run program with defaults set in config
if __name__ == "__main__":
    delete_emails()


import pickle

train_data=pickle.load(open('data.pickle','rb'))
train_target=pickle.load(open('target.pickle','rb'))
#loading arrays saved in last code

print(train_data.shape)
print(train_target.shape)

print(train_data.shape)

from sklearn.neighbors import KNeighborsClassifier

clsfr=KNeighborsClassifier()
clsfr.fit(train_data,train_target)

#training the KNN

import joblib

joblib.dump(clsfr,'KNN_model.sav')
#save the train machine learning model


n, p = map(int, input().split())
array = list(map(int, input().split()))

array = list(set(array))
result = []

for i in range(len(array) - 2):
    for j in range(i + 1, len(array) - 1):
        for k in range(j + 1, len(array)):
            sum = array[i] + array[j] + array[k]
            result.append(sum)

result = list(set(result))
result.sort(reverse=True)

print(result[p-1])

## 첫번째 예제만 맞춤...

######## SOLUTION #########
## 3개를 뽑을때는 중복을 제거하면 안되었었는데 제거해서 결과 값이 다르게 나와버렸다.
## set에서 add 쓰기

n, k = map(int, input().split())
a = list(map(int, input().split()))
res = set()
for i in range(n):
    for j in range(i+1, n):
        for m in range(j+1, n):
            res.add(a[i]+a[j]+a[m])
res = list(res)
res.sort(reverse=True)
print(res[k-1])


import cv2
import numpy as np
import turtle

def array_pic(pic):
    image = cv2.imread(pic,0)
    edges = cv2.Canny(image,80,130)
    img_gray = cv2.cvtColor(edges,cv2.COLOR_BAYER_BG2GRAY)
    ret, thresh = cv2.threshold(img_gray,127,255,0)

    image,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    #contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    xy = []
    for i in range(0,len(contours)):
        x,y,w,h = cv2.boundingRect(contours[i])
        list_xy = [x,y]
        xy.append(list_xy)
    with open("./1.txt",'w') as f:
        for i in xy :
            f.write(str(i))
        f.close()
    return xy
    # file = open("array.txt", mode="x")
    # file.writelines(str(contours))
    # file.close()
    # cv2.imshow("1.jpg",image)
    # cv2.waitKey(0)

def draw(xy):
    # with open("./1.txt",'w') as f:
        # f.write(xy)

    turtle.pensize(2)
    turtle.setup(width=0.6,height=1.0)
    turtle.speed("fastest")
    for array in xy[::-1]:
        turtle.penup()
        turtle.goto((array[0])-600,-(array[1])+300)
        turtle.pendown()
        turtle.forward(1)
        # print(turtle.pos())

    turtle.done()

if __name__ == "__main__":
    pic = "./data2/ysu.png"
    xy = array_pic(pic)
    draw(xy)


from sklearn.ensemble import AdaBoostClassifier,RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline#连续处理操作
from sklearn.preprocessing import StandardScaler#标准化
from sklearn.datasets import make_moons,make_circles,make_classification#数据多样化的建立
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier#需要注意的是版本的对应，这个玩意需要scikit-learn。1.1以上的版本，需要保证python的版本3.9.
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from matplotlib.colors import ListedColormap
from sklearn.inspection import DecisionBoundaryDisplay
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#分类器名称
names = [
    'Nearest Neighbors',
    'Linear SVM',
    'RBF SVN',
    'Decision Tree',
    'Random Forest',
    'Neural Net',
    'AdaBoost',
    'Native Bayes',
]

#分类器实例化
classifier = [
    KNeighborsClassifier(3),
    SVC(kernel='linear',C=0.025),
    SVC(gamma=2,C=1),
    DecisionTreeClassifier(max_depth=5),
    RandomForestClassifier(max_depth=5,n_estimators=10,max_features=1),
    MLPClassifier(alpha=1,max_iter=1000),#float，可选，默认为0.0001。L2惩罚（正则化项）参数。
    AdaBoostClassifier(),
    GaussianNB(),
]

#数据的建立
X,y = make_classification(n_features=2,n_redundant=0,n_informative=2,random_state=1, n_clusters_per_class=1)
rng = np.random.RandomState(2)#设置随机变量，以重复多次实验。
X = X + 2*rng.uniform(size=X.shape)#在原有的数据基础之上加上一些噪音。
linearly_separable = (X,y)
datasets = [
    make_moons(noise=0.3,random_state=0),
    make_circles(noise=0.2,factor=0.5,random_state=1),
    linearly_separable,
]

plt.figure(figsize=(27,9))
i = 1

for ds_cnt,ds in enumerate(datasets):
    X,y = ds
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.4,random_state=42)

    x_min,x_max = X[:,0].min() - 0.5,X[:,0].max() + 0.5
    y_min,y_max = X[:,1].min() - 0.5,X[:,1].max() + 0.5

    #just plot the dataset first
    cm = plt.cm.RdBu#颜色图
    cm_bright = ListedColormap(["#FF0000", "#0000FF"])
    ax = plt.subplot(len(datasets),len(classifier)+1,i)
    if ds_cnt == 0:
        ax.set_title('Input data')
    #Plot the training points
    ax.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap = cm_bright,edgecolors = 'k')
    #Plot the testing points
    ax.scatter(X_test[:,0],X_test[:,1],cmap = cm_bright,edgecolors = 'k',c=y_test,alpha=0.6)

    ax.set_xlim(x_min,x_max)
    ax.set_ylim(y_min,y_max)
    ax.set_xticks(())
    ax.set_yticks(())
    i = i + 1

    #iterate over classifier
    for name,clf in zip(names,classifier):

        ax = plt.subplot(len(datasets),len(classifier) + 1,i)

        clf = make_pipeline(StandardScaler(),clf)
        clf.fit(X_train,y_train)
        score = clf.score(X_test,y_test)
        DecisionBoundaryDisplay.from_estimator(
            clf, X, cmap=cm, alpha=0.8, ax=ax, eps=0.5
        )

        #Plot the training points
        ax.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap=cm_bright,edgecolors='k')
        #Plot the testing points
        ax.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap=cm_bright,edgecolors='k',alpha=0.6)

        ax.set_xlim(x_min,x_max)
        ax.set_ylim(y_min,y_max)
        ax.set_xticks(())
        ax.set_yticks(())
        if ds_cnt == 0:
            ax.set_title(name)
        ax.text(x_max - 0.3,y_min + 0.3,('%.2f' % score).lstrip('0'),size=15,horizontalalignment='right')
        i = i + 1

plt.tight_layout()
plt.show()


# author: David Kromka
import math

# Function to calculate entropy
def calculate_entropy(num_states):
    # Probability of each state in equiprobable distribution
    probability = 1 / num_states
    # Calculate entropy using the formula: H = -Σ(P(x_i) * log2(P(x_i)))
    entropy = -sum(probability * math.log2(probability) for _ in range(num_states))
    return entropy

# System X with 8 states
num_states_8 = 8
entropy_8_states = calculate_entropy(num_states_8)
print(f"Entropy for System X with {num_states_8} states: {entropy_8_states:.2f} bits")

# System X with 128 states
num_states_128 = 128
entropy_128_states = calculate_entropy(num_states_128)
print(f"Entropy for System X with {num_states_128} states: {entropy_128_states:.2f} bits")


"""
This code implements the computation of some particular fairness metrics for tree
trained with sklearn

These metrics are introduced in :
    Zafar, Muhammad Bilal, et al. "Fairness Constraints: A Flexible Approach for Fair Classification."
    Journal of Machine Learning Research 20.75 (2019): 1-42.

Last modification : 10 November 2020
           Author : Delchevalerie Valentin
            email : valentin.delchevalerie@unamur.be
"""

import numpy as np

# Disparate impact
def getDisparateImpact(X_train, algebraicTree, controled_axis=-1):
    """
    This function returns the Disparate Impact (DI) of the tree.

    A DI close to zero means that the model is fair.
    """

    N = np.shape(X_train)[0]
    z_bar = np.mean(X_train[:,controled_axis])

    DI = 0.0
    for i in range(N):
        DI += (X_train[i,controled_axis] - z_bar) * algebraicTree.signedDistance(X_train[i,:])

    return np.abs(DI/N)

# Disparate mistreatment w.r.t overall misclassification
def getDisparateMistreatment_overall(X_train, y_train, algebraicTree, controled_axis=-1):
    """
    This function returns the Disparate Mistreatment (DM) of the tree
    w.r.t overall misclassification.

    A DM close to zero means that the model is fair.
    """

    N = np.shape(X_train)[0]
    N_1 = np.shape(np.where(X_train[:,controled_axis] == 1)[0])[0]
    N_0 = N - N_1
    coeff1 = N_1/N
    coeff2 = N_0/N

    DM = 0.0
    for i in range(N):
        if X_train[i,controled_axis] == 0:
            DM -= coeff1 * algebraicTree.misclassifiedDistance(X_train[i,:], y_train[i])
        else:
            DM += coeff2 * algebraicTree.misclassifiedDistance(X_train[i,:], y_train[i])

    return np.abs(DM)

# Disparate mistreatment w.r.t false positive rates and false negative rates
def getDisparateMistreatment_fpfn(X_train, y_train, algebraicTree, controled_axis=-1):
    """
    This function returns the Disparate Mistreatment (DM) of the tree
    w.r.t false positive rates and false negative rates.

    A DM close to zero means that the model is fair.
    """

    indices = np.where((y_train == 0) | (y_train == -1))[0]
    N_neg = np.shape(indices)[0]
    N_1_neg = np.shape(np.where((X_train[:,controled_axis] == 1) & ((y_train == 0) | (y_train == -1)))[0])[0]
    N_0_neg = np.shape(np.where((X_train[:,controled_axis] == 0) & ((y_train == 0) | (y_train == -1)))[0])[0]
    coeff1 = N_1_neg/N_neg
    coeff2 = N_0_neg/N_neg

    DM = 0.0
    for i in indices:
        if X_train[i,controled_axis] == 0:
            DM -= coeff1 * algebraicTree.misclassifiedDistance(X_train[i,:], y_train[i])
        else:
            DM += coeff2 * algebraicTree.misclassifiedDistance(X_train[i,:], y_train[i])

    return np.abs(DM)


import sys, fileinput, os, subprocess
from Utils import modifyConfig, getTrainScript, getExportScript, resetEnv

# system path 추가
sys.path.append('D:\\TF_Object_Detection_API')
sys.path.append('D:\\TF_Object_Detection_API\\slim')

num_step = 1500
save_step = 500
current_step = save_step
train_dir = './retrained_model'
pipeline_config_path = './model_configs/mask_rcnn_resnet101_atrous_coco.config'

base_save_path = './exported_model/mask_rcnn_resnet101'
if not os.path.isdir(base_save_path):
    os.mkdir(base_save_path)

train_py_script = getTrainScript(train_dir, pipeline_config_path)

while current_step < num_step:
    print('[Step] : {}' .format(current_step))
    modifyConfig(pipeline_config_path, current_step)

    # retrain
    try:
        subprocess.run([exec(train_py_script)])
    except:
        print('에러를 완벽히 잡아내진 못했지만 실행에는 문제가 없음')
    resetEnv()

    # export
    export_py_script = getExportScript(pipeline_config_path, current_step, base_save_path)
    try:
        subprocess.run([exec(export_py_script)])
    except:
        print('에러를 완벽히 잡아내진 못했지만 실행에는 문제가 없음')
    resetEnv()

    current_step += save_step

print('[Step] : {}' .format(num_step))
modifyConfig(pipeline_config_path, num_step)
try:
    subprocess.run([exec(train_py_script)])
except:
    print('에러를 완벽히 잡아내진 못했지만 실행에는 문제가 없음')
resetEnv()

export_py_script = getExportScript(pipeline_config_path, current_step, base_save_path)
try:
    subprocess.run([exec(export_py_script)])
except:
    print('에러를 완벽히 잡아내진 못했지만 실행에는 문제가 없음')
resetEnv()


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

import io
import os
import sys
from shutil import rmtree

from setuptools import find_packages, setup, Command

# Package meta-data.
NAME = 'bams'
DESCRIPTION = 'Bayesian Active Model Selection.'
URL = 'https://github.com/Dallinger/bams'
EMAIL = 'dallinger-admin@lists.berkeley.edu'
AUTHOR = 'Gustavo Malkomes and Jordan Suchow'
VERSION = None

# What packages are required for this module to be executed?
REQUIRED = [
    "numpy",
    "scipy",
    "pybind11",
    "george",
    "matplotlib",
    "sobol_seq",
]

here = os.path.abspath(os.path.dirname(__file__))

# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
    with open(os.path.join(here, NAME, '__version__.py')) as f:
        exec(f.read(), about)
else:
    about['__version__'] = VERSION

class UploadCommand(Command):
    """Support setup.py upload."""

    description = 'Build and publish the package.'
    user_options = []

    @staticmethod
    def status(s):
        """Prints things in bold."""
        print('\033[1m{0}\033[0m'.format(s))

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        try:
            self.status('Removing previous builds…')
            rmtree(os.path.join(here, 'dist'))
        except OSError:
            pass

        self.status('Building Source and Wheel (universal) distribution…')
        os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))

        self.status('Uploading the package to PyPi via Twine…')
        os.system('twine upload dist/*')

        self.status('Pushing git tags…')
        os.system('git tag v{0}'.format(about['__version__']))
        os.system('git push --tags')

        sys.exit()

# Where the magic happens:
setup(
    name=NAME,
    version=about['__version__'],
    description=DESCRIPTION,
    author=AUTHOR,
    author_email=EMAIL,
    url=URL,
    packages=find_packages(exclude=('tests',)),
    # If your package is a single module, use this instead of 'packages':
    # py_modules=['mypackage'],

    # entry_points={
    #     'console_scripts': ['mycli=mymodule:cli'],
    # },
    install_requires=REQUIRED,
    include_package_data=True,
    license='MIT',
    classifiers=[
        # Trove classifiers
        # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy'
    ],
    # $ setup.py publish support.
    cmdclass={
        'upload': UploadCommand,
    },
    setup_requires=['setuptools-markdown==0.2'],
    long_description_markdown_filename="README.md"
)


s = input()
tmp = ""
for i in range(len(s)):
    if len(tmp) != 0 and not s[i].isnumeric() and s[i-1].isnumeric():
        print(tmp)
        tmp = "";
    if s[i].isupper():
        tmp += s[i]
    elif s[i] == '-':
        tmp += " loosen "
    elif s[i] == '+':
        tmp += " tighten "
    elif s[i].isnumeric():
        tmp += s[i]
print(tmp)


from nltk import ngrams
import os
import json
from sutime import SUTime
import inflect
import re

re_compile = re.compile(r'^\'(.*)\'$')

grams_len = 6
default_date_field = 'ENTRY_DATE'
default_year = '2018'

def get_phrases_from_text(seed, text, threshold):
    phrases_text = []
    phrases = []
    for i in reversed(range(2,6)):
        phrases += list(ngrams(text.split(), i))
    for phrase in phrases:
        phrase = " ".join(phrase)
        if s_utils.get_similarity(seed, phrase) > threshold:
            phrases_text.append(phrase)
    return phrases_text

def get_aggregations_mappings(filename):
    with open(filename) as f:
        mappings = f.readlines()
    field_mappings = {}
    for mapping in mappings:
        mapping_tokens = mapping.split(':')
        mapping_synonyms = mapping_tokens[1].split(',')
        mapping_synonyms_clean = []
        for mapping_synonym in mapping_synonyms:
            mapping_synonyms_clean.append(mapping_synonym.replace('\n', '').strip())
        field_mappings[mapping_tokens[0].strip()] = mapping_synonyms_clean
    return field_mappings

def get_field_type(filename, field_type):
    with open(filename) as f:
        mappings = f.readlines()

    field_mappings = []
    for mapping in mappings:
        mapping_tokens = mapping.split(':')
        mapping_synonyms = mapping_tokens[1].split(',')
        mapping_synonyms_clean = []
        for mapping_synonym in mapping_synonyms:
            mapping_synonyms_clean.append(mapping_synonym.replace('\n', '').strip().lower())
        if field_type in mapping_tokens[0]:
            field_mappings.append(mapping_tokens[0][0:str(mapping_tokens[0]).index(' (')])
    return field_mappings

def get_field_mappings(filename):
    with open(filename) as f:
        mappings = f.readlines()

    field_mappings = {}
    for mapping in mappings:
        mapping_tokens = mapping.split(':')
        mapping_synonyms = mapping_tokens[1].split(',')
        mapping_synonyms_clean = []
        for mapping_synonym in mapping_synonyms:
            mapping_synonyms_clean.append(mapping_synonym.replace('\n', '').strip().lower())
        field_mappings[mapping_tokens[0][0:str(mapping_tokens[0]).index(' (')]] = mapping_synonyms_clean
    return field_mappings

def get_value_mappings(filename):
    with open(filename) as f:
        mappings = f.readlines()

    field_mappings = {}
    i = 0
    index_mappings = {}
    index_mappings[0] = 'Branch'
    index_mappings[1] = 'POLICY_NUMBER'
    index_mappings[2] = 'Product'
    index_mappings[3] = 'Zone'
    index_mappings[4] = 'Branch'
    index_mappings[5] = 'Status'
    index_mappings[6] = 'AGENT_NAME'
    index_mappings[7] = 'Employee_Name'
    index_mappings[8] = 'Business'

    for index_mapping in index_mappings:
        field_mappings[index_mappings[index_mapping]] = set()

    for mapping in mappings:
        if i>0:
            mappings_tokens = mapping.split('~')
            row_count = 0
            for mapping_token in mappings_tokens:
                mapping_str = mapping_token.replace('\n', '').strip().lower()
                if len(mapping_str)>0:
                    field_mappings[index_mappings[row_count]].add(mapping_str)
                row_count+=1
        i+=1
    return field_mappings

def get_ngrams(text_qry):
    grams_qry = {}
    for i in range(1, grams_len):
        grams = list(ngrams(text_qry.split(), i))
        grams_str = []
        for gram in grams:
            grams_str.append(' '.join(str(i) for i in gram))
        grams_qry[i] = grams_str
    return grams_qry

def get_date_fields(text_qry, date_type_fields, field_mappings):
    date_fields = []
    for date_field in date_type_fields:
        for field_mapping in field_mappings[date_field]:
            if field_mapping in text_qry:
                date_fields.append(date_field)
    return date_fields

def is_plural(gram, values):
    p = inflect.engine()
    for value in values:
        if gram == p.plural(value):
            return value
    return ''

def pluralize_singularize(text_qry):
    qry = text_qry.lower().replace(',', ' ')
    tokens = qry.split()
    p = inflect.engine()
    plural_tokens = []
    singular_tokens = []

    for token in tokens:
        if(len(token)>len(p.plural(token))):
            plural_tokens.append(token)
        else:
            plural_tokens.append(p.plural(token))
        if p.singular_noun(token) == False:
            singular_tokens.append(token)
        else:
            singular_tokens.append(p.singular_noun(token))
    plural_text = ' '.join(plural_tokens)
    singular_text = ' '.join(singular_tokens)
    return get_ngrams(plural_text + ' ' + singular_text)

def is_ranking_qry(text_grams):
    ranking_terms = ['top', 'bottom', 'highest', 'lowest', 'best', 'worst']
    for ranking_term in ranking_terms:
        if ranking_term in text_grams:
            return True
    return False

def get_n (text):
    list_of_words = ['top', 'bottom', 'highest', 'lowest', 'best', 'worst']
    for i in range(0, len(list_of_words)):
        if list_of_words[i] in text:
            expression = text.split(list_of_words[i])
            trim_str = expression[1].strip()
            number = ''
            for i in trim_str:
                if i.isdigit():
                    if i !=' ':
                        number = number + i
                    else:
                        break
                else:
                    break
            return number

def stem_string(ps, text_qry):
    text_tokens = text_qry.replace(', ', ' ').split()
    stem_tokens = []
    for text_token in text_tokens:
        stem_tokens.append(ps.stem(text_token))
    return ' '.join(stem_tokens)

def get_stem_map(ps, value_mappings):
    stem_map = {}
    for value_mapping in value_mappings.keys():
        for value_map in value_mappings[value_mapping]:
            stem_map[stem_string(ps, value_map)] = value_map
    return stem_map

field_mappings = get_field_mappings("resources/mappings.txt")
value_mappings = get_value_mappings("resources/valueMappings.csv")
aggregation_mappings = get_aggregations_mappings("resources/aggregations.txt")
timecomp_mappings = get_aggregations_mappings("resources/timeComparison.json")
date_type_fields = get_field_type("resources/mappings.txt", 'date')
sutime = SUTime(jars='python-sutime/jars/', mark_time_ranges=True)

qry = "which branches are linked to Aditya Birla Insurance Brokers Ltd"
grams_qry = pluralize_singularize(qry)

stem_map = get_stem_map(ps, value_mappings)

is_ranking_qry(qry)

field_equals = {}
fields = {}
field_aggregations = {}
field_groups = {}
limit = ''
order = 'DESC'
for gram_cnt in range(grams_len-1, 0, -1):
    grams = grams_qry[gram_cnt]
    for gram in grams:
        gram_stem = stem_string(ps, gram)
        if gram_stem in stem_map.keys():
            value_mapped = stem_map[gram_stem]
            for value_mapping in value_mappings.keys():
               if value_mapped in value_mappings[value_mapping]:
                   if not value_mapping in field_equals.keys():
                       not_in_value_field = True
                       for field_equal in field_equals.keys():
                           if "'" + stem_map[gram_stem] + "'" == field_equals[field_equal]:
                               not_in_value_field = True
                       if not_in_value_field:
                           field_equals[value_mapping] = "'" + stem_map[gram_stem] + "'"
        for field_mapping in field_mappings.keys():
           if gram in field_mappings[field_mapping]:
               if not field_mapping in fields.keys():
                   not_in_field = True
                   for field in fields.keys():
                       if gram in fields[field]:
                           not_in_field = False
                   if not_in_field:
                       fields[field_mapping] = gram

for field in fields.keys():
    for aggregation in aggregation_mappings.keys():
        for aggregation_str in aggregation_mappings[aggregation]:
            if (aggregation_str + ' ' + fields[field] in qry) or (aggregation_str + ' of ' + fields[field] in qry)  or (aggregation_str + ' value of ' + fields[field] in qry) or (aggregation_str + ' number of ' + fields[field] in qry):
                 field_aggregations[aggregation] = field
    if 'per ' + fields[field] in qry or fields[field] + ' wise' in qry:
        field_groups[field] = field

time_expressions = sutime.parse(qry)
time_expressions_text = ''
time_begin = ''
time_end = ''
time_value = ''
no_date_field = True
if(len(time_expressions)>0):
    for date_field in date_type_fields:
        if date_field.lower() not in qry:
            for date_field_mapped in field_mappings[date_field]:
                if date_field_mapped in qry:
                    no_date_field = False
                    break
        else:
            no_date_field = False
            break
    time_expressions_text = time_expressions[0]['text']
    if 'from' in time_expressions_text and 'to ' in time_expressions_text:
        time_begin = time_expressions[0]['value']['begin']
        time_end = time_expressions[0]['value']['end']
        if 'XXXX' in time_begin:
            time_begin = time_begin.replace('XXXX', default_year)
        if 'XXXX' in time_end:
            time_end = time_end.replace('XXXX', default_year)
    else:
        time_value = time_expressions[0]['value']
        time_value = time_value.replace('XXXX', default_year)

if no_date_field:
    if len(time_begin)>0 and len(time_end)>0:
        field_equals[default_date_field] = default_date_field + " >= '" + time_begin + "' AND " + default_date_field + " <= '" + time_end + "'"
    elif len(time_expressions_text)>0 and len(time_value)>0:
        for timecomp_mapping in timecomp_mappings.keys():
            for time_comparison in timecomp_mappings[timecomp_mapping]:
                if (time_comparison + ' ' +  time_expressions_text) in qry:
                    field_equals[default_date_field] = timecomp_mapping + " '" + time_value + "'"
                    break
        if default_date_field not in field_equals.keys():
                field_equals[default_date_field] = '== ' + time_value
else:
    date_fields = get_date_fields(qry, date_type_fields, field_mappings)
    if len(date_fields)==1:
        for timecomp_mapping in timecomp_mappings.keys():
            for time_comparison in timecomp_mappings[timecomp_mapping]:
                if (time_comparison + ' ' +  time_expressions_text) in qry:
                    field_equals[date_fields[0]] = timecomp_mapping + " '" + time_value + "'"
        if date_fields[0] not in field_equals.keys():
            field_equals[date_fields[0]] = '== ' + time_value

def construct_qry(table_name, field_equals, fields, field_aggregations, field_groups):
    sql_qry = "SELECT * FROM " + table_name
    i=0
    for field_group in field_groups.keys():
        if i==0:
            sql_qry = sql_qry + ' GROUP BY ' + field_groups[field_group]
        else:
            sql_qry = sql_qry + ' , ' + field_groups[field_group]
        i+=1
    i=0
    for field_equal in field_equals.keys():
        if 'date' in field_equal.lower():
            if i==0:
                sql_qry = sql_qry + ' WHERE ' + field_equals[field_equal]
            else:
                sql_qry = sql_qry + ' AND ' + field_equals[field_equal]
            i+=1
        else:
            if i==0:
                sql_qry = sql_qry + ' WHERE ' + field_equal + " = " + field_equals[field_equal]
            else:
                sql_qry = sql_qry + ' OR ' + field_equal + " = " + field_equals[field_equal]
            i+=1

    i = 0
    query_field = ''
    if len(field_aggregations.keys())>0:
        for field_aggregation in field_aggregations.keys():
            if i > 0:
                query_field = query_field + ', '
            query_field = query_field + field_aggregation + '(' + field_aggregations[field_aggregation] + ')'
            i += 1
        if len(query_field)>0:
            sql_qry = sql_qry.replace ('*', query_field )
    elif len(fields.keys())>0:
        for field in fields.keys():
            if i > 0:
                query_field = query_field + ', '
            query_field = query_field + field
            i += 1
        if len(query_field)>0:
            sql_qry = sql_qry.replace ('*', query_field )
    return sql_qry

construct_qry("AppoloTable", field_equals, fields, field_aggregations, field_groups)


import time
from typing import Dict
from dotenv import load_dotenv
import os
import jwt
from bson.objectid import ObjectId

load_dotenv()

JWT_SECRET = os.getenv("SECRET")
JWT_ALGORITHM = os.getenv("ALGORITHM")

def token_response(token: str):
    return {
        "access_token": token
    }

def signJWT(user_id: str, email: str) -> Dict[str, str]:
    payload = {
        "user_id": user_id,
        "email": email,
        "expires": time.time() + 600 # 10 minutes
    }
    token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
    return token_response(token)

def decodeJWT(token: str) -> dict:
    try:
        decoded_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
        return decoded_token if decoded_token["expires"] >= time.time() else None
    except Exception as e:
        print("Got error trying to decode JWT: " + str(e))
        return {}


import typing

import dolfinx.fem
import dolfinx.fem.petsc
import dolfinx.mesh
import mpi4py.MPI
import nbvalx.tempfile
import numpy as np
import petsc4py.PETSc
import pytest
import ufl

import rbnicsx.backends

@pytest.fixture
def mesh() -> dolfinx.mesh.Mesh:
    """Generate a unit square mesh for use in tests in this file."""
    comm = mpi4py.MPI.COMM_WORLD
    return dolfinx.mesh.create_unit_square(comm, 2 * comm.size, 2 * comm.size)

def test_backends_export_import_function(mesh: dolfinx.mesh.Mesh) -> None:
    """Check I/O for a dolfinx.fem.Function."""
    V = dolfinx.fem.functionspace(mesh, ("Lagrange", 1))
    function = dolfinx.fem.Function(V)
    function.vector.set(1.0)

    with nbvalx.tempfile.TemporaryDirectory(mesh.comm) as tempdir:
        rbnicsx.backends.export_function(function, tempdir, "function")

        function2 = rbnicsx.backends.import_function(V, tempdir, "function")
        assert np.allclose(function2.vector.array, function.vector.array)

def test_backends_export_import_functions(mesh: dolfinx.mesh.Mesh) -> None:
    """Check I/O for a list of dolfinx.fem.Function."""
    V = dolfinx.fem.functionspace(mesh, ("Lagrange", 1))
    functions = list()
    indices = list()
    for i in range(2):
        function = dolfinx.fem.Function(V)
        function.vector.set(i + 1)
        functions.append(function)
        indices.append(i)

    with nbvalx.tempfile.TemporaryDirectory(mesh.comm) as tempdir:
        rbnicsx.backends.export_functions(functions, np.array(indices, dtype=float), tempdir, "functions")

        functions2 = rbnicsx.backends.import_functions(V, tempdir, "functions")
        assert len(functions2) == 2
        for (function, function2) in zip(functions, functions2):
            assert np.allclose(function2.vector.array, function.vector.array)

def test_backends_export_import_vector(mesh: dolfinx.mesh.Mesh) -> None:
    """Check I/O for a petsc4py.PETSc.Vec."""
    V = dolfinx.fem.functionspace(mesh, ("Lagrange", 1))
    v = ufl.TestFunction(V)
    linear_form = ufl.inner(1, v) * ufl.dx
    linear_form_cpp = dolfinx.fem.form(linear_form)
    vector = dolfinx.fem.petsc.assemble_vector(linear_form_cpp)
    vector.ghostUpdate(addv=petsc4py.PETSc.InsertMode.ADD, mode=petsc4py.PETSc.ScatterMode.REVERSE)

    with nbvalx.tempfile.TemporaryDirectory(mesh.comm) as tempdir:
        rbnicsx.backends.export_vector(vector, tempdir, "vector")

        vector2 = rbnicsx.backends.import_vector(linear_form_cpp, mesh.comm, tempdir, "vector")
        assert np.allclose(vector2.array, vector.array)

def test_backends_export_import_vectors(mesh: dolfinx.mesh.Mesh) -> None:
    """Check I/O for a list of petsc4py.PETSc.Vec."""
    V = dolfinx.fem.functionspace(mesh, ("Lagrange", 1))
    v = ufl.TestFunction(V)
    linear_forms = [ufl.inner(i + 1, v) * ufl.dx for i in range(2)]
    linear_forms_cpp = dolfinx.fem.form(linear_forms)
    vectors = [dolfinx.fem.petsc.assemble_vector(linear_form_cpp) for linear_form_cpp in linear_forms_cpp]
    [vector.ghostUpdate(
        addv=petsc4py.PETSc.InsertMode.ADD, mode=petsc4py.PETSc.ScatterMode.REVERSE) for vector in vectors]

    with nbvalx.tempfile.TemporaryDirectory(mesh.comm) as tempdir:
        rbnicsx.backends.export_vectors(vectors, tempdir, "vectors")

        vectors2 = rbnicsx.backends.import_vectors(linear_forms_cpp[0], mesh.comm, tempdir, "vectors")
        assert len(vectors2) == 2
        for (vector, vector2) in zip(vectors, vectors2):
            assert np.allclose(vector2.array, vector.array)

def test_backends_export_import_matrix(  # type: ignore[no-any-unimported]
    mesh: dolfinx.mesh.Mesh,
    to_dense_matrix: typing.Callable[[petsc4py.PETSc.Mat], np.typing.NDArray[petsc4py.PETSc.ScalarType]]
) -> None:
    """Check I/O for a petsc4py.PETSc.Mat."""
    V = dolfinx.fem.functionspace(mesh, ("Lagrange", 1))
    u = ufl.TrialFunction(V)
    v = ufl.TestFunction(V)
    bilinear_form = ufl.inner(u, v) * ufl.dx
    bilinear_form_cpp = dolfinx.fem.form(bilinear_form)
    matrix = dolfinx.fem.petsc.assemble_matrix(bilinear_form_cpp)
    matrix.assemble()

    with nbvalx.tempfile.TemporaryDirectory(mesh.comm) as tempdir:
        rbnicsx.backends.export_matrix(matrix, tempdir, "matrix")

        matrix2 = rbnicsx.backends.import_matrix(bilinear_form_cpp, mesh.comm, tempdir, "matrix")
        assert np.allclose(to_dense_matrix(matrix2), to_dense_matrix(matrix))

def test_backends_export_import_matrices(  # type: ignore[no-any-unimported]
    mesh: dolfinx.mesh.Mesh,
    to_dense_matrix: typing.Callable[[petsc4py.PETSc.Mat], np.typing.NDArray[petsc4py.PETSc.ScalarType]]
) -> None:
    """Check I/O for a list of petsc4py.PETSc.Mat."""
    V = dolfinx.fem.functionspace(mesh, ("Lagrange", 1))
    u = ufl.TrialFunction(V)
    v = ufl.TestFunction(V)
    bilinear_forms = [(i + 1) * ufl.inner(u, v) * ufl.dx for i in range(2)]
    bilinear_forms_cpp = dolfinx.fem.form(bilinear_forms)
    matrices = [dolfinx.fem.petsc.assemble_matrix(bilinear_form_cpp) for bilinear_form_cpp in bilinear_forms_cpp]
    [matrix.assemble() for matrix in matrices]

    with nbvalx.tempfile.TemporaryDirectory(mesh.comm) as tempdir:
        rbnicsx.backends.export_matrices(matrices, tempdir, "matrices")

        matrices2 = rbnicsx.backends.import_matrices(bilinear_forms_cpp[0], mesh.comm, tempdir, "matrices")
        for (matrix, matrix2) in zip(matrices, matrices2):
            assert np.allclose(to_dense_matrix(matrix2), to_dense_matrix(matrix))


#!/usr/bin/env python3
"""Example script which creates the smallest possible type 0 midi file.

All the midi events are in the same track chunk, which only contains one note
on and off event.

"""

import sys
from os.path import abspath, dirname, join

from miditk.smf import MidiFileWriter

try:
    outfile = sys.argv[1]
except IndexError:
    outfile = join(dirname(dirname(abspath(__file__))), 'tests', 'testoutput', 'minimal-type0.mid')

with open(outfile, 'wb') as smf:
    midi = MidiFileWriter(smf)

    # write file and track header
    midi.header()
    midi.start_of_track()

    # musical events
    midi.note_on(channel=0, note=0x40)

    midi.update_ticks(192)
    midi.note_off(channel=0, note=0x40)

    # end track and midi file
    midi.end_of_track()
    midi.eof()


from ctypes import *
import warnings

from pyglet.gl.glu import *
from pyglet.util import asstr

class GLUInfo:
    """Information interface for the GLU library.

    A default instance is created automatically when the first OpenGL context
    is created.  You can use the module functions as a convenience for
    this default instance's methods.

    If you are using more than one context, you must call `set_active_context`
    when the context is active for this `GLUInfo` instance.
    """
    have_context = False
    version = '0.0.0'
    extensions = []

    _have_info = False

    def set_active_context(self):
        """Store information for the currently active context.

        This method is called automatically for the default context.
        """
        self.have_context = True
        if not self._have_info:
            self.extensions = asstr(cast(gluGetString(GLU_EXTENSIONS), c_char_p).value).split()
            self.version = asstr(cast(gluGetString(GLU_VERSION), c_char_p).value)
            self._have_info = True

    def have_version(self, major, minor=0, release=0):
        """Determine if a version of GLU is supported.

        :Parameters:
            `major` : int
                The major revision number (typically 1).
            `minor` : int
                The minor revision number.
            `release` : int
                The release number.

        :rtype: bool
        :return: True if the requested or a later version is supported.
        """
        if not self.have_context:
            warnings.warn('No GL context created yet.')
        ver = '%s.0.0' % self.version.split(' ', 1)[0]
        imajor, iminor, irelease = [int(v) for v in ver.split('.', 3)[:3]]
        return imajor > major or\
               (imajor == major and iminor > minor) or \
               (imajor == major and iminor == minor and irelease >= release)

    def get_version(self):
        """Get the current GLU version.

        :return: the GLU version
        :rtype: str
        """
        if not self.have_context:
            warnings.warn('No GL context created yet.')
        return self.version

    def have_extension(self, extension):
        """Determine if a GLU extension is available.

        :Parameters:
            `extension` : str
                The name of the extension to test for, including its
                ``GLU_`` prefix.

        :return: True if the extension is provided by the implementation.
        :rtype: bool
        """
        if not self.have_context:
            warnings.warn('No GL context created yet.')
        return extension in self.extensions

    def get_extensions(self):
        """Get a list of available GLU extensions.

        :return: a list of the available extensions.
        :rtype: list of str
        """
        if not self.have_context:
            warnings.warn('No GL context created yet.')
        return self.extensions

# Single instance useful for apps with only a single context (or all contexts
# have same GLU driver, common case).
_glu_info = GLUInfo()

set_active_context = _glu_info.set_active_context
have_version = _glu_info.have_version
get_version = _glu_info.get_version
have_extension = _glu_info.have_extension
get_extensions = _glu_info.get_extensions


"""Australian-specific Form helpers."""

from django.forms.fields import CharField, RegexField, Select
from django.utils.translation import gettext_lazy as _

from .au_states import STATE_CHOICES
from .validators import AUBusinessNumberFieldValidator, AUCompanyNumberFieldValidator, AUTaxFileNumberFieldValidator

class AUPostCodeField(RegexField):
    """
    Australian post code field.

    Assumed to be 4 digits.
    Northern Territory 3-digit postcodes should have leading zero.
    """

    default_error_messages = {
        'invalid': _('Enter a 4 digit postcode.'),
    }

    def __init__(self, max_length=4, **kwargs):
        super().__init__(r'^\d{4}$', max_length=max_length, **kwargs)

class AUStateSelect(Select):
    """A Select widget that uses a list of Australian states/territories as its choices."""

    def __init__(self, attrs=None):
        super().__init__(attrs, choices=STATE_CHOICES)

class AUBusinessNumberField(CharField):
    """
    A form field that validates input as an Australian Business Number (ABN).

    .. versionadded:: 1.3
    .. versionchanged:: 1.4
    """

    default_validators = [AUBusinessNumberFieldValidator()]

    def to_python(self, value):
        value = super().to_python(value)
        if value in self.empty_values:
            return value
        return value.upper().replace(' ', '')

    def prepare_value(self, value):
        """Format the value for display."""
        if value is None:
            return value

        spaceless = ''.join(value.split())
        return '{} {} {} {}'.format(spaceless[:2], spaceless[2:5], spaceless[5:8], spaceless[8:])

class AUCompanyNumberField(CharField):
    """
    A form field that validates input as an Australian Company Number (ACN).

    .. versionadded:: 1.5
    """

    default_validators = [AUCompanyNumberFieldValidator()]

    def to_python(self, value):
        value = super().to_python(value)
        if value in self.empty_values:
            return value
        return value.upper().replace(' ', '')

    def prepare_value(self, value):
        """Format the value for display."""
        if value is None:
            return value

        spaceless = ''.join(value.split())
        return '{} {} {}'.format(spaceless[:3], spaceless[3:6], spaceless[6:])

class AUTaxFileNumberField(CharField):
    """
    A form field that validates input as an Australian Tax File Number (TFN).

    .. versionadded:: 1.4
    """

    default_validators = [AUTaxFileNumberFieldValidator()]

    def prepare_value(self, value):
        """Format the value for display."""
        if value is None:
            return value

        spaceless = ''.join(value.split())
        return '{} {} {}'.format(spaceless[:3], spaceless[3:6], spaceless[6:])


import numpy as np
import cv2
import time

INITIAL_ROI = True
FURTHER_ROI = False
CENTER = 995

def cvShow(img, name):
    """
    显示可调控窗口
    :parmam img: 原始图像
    :parmam name: 生成图像窗口名称
    """
    cv2.namedWindow(name, cv2.WINDOW_NORMAL)
    cv2.imshow(name, img)

def retinex(image, sigma_list):
    retinex_output = np.zeros_like(image)
    for sigma in sigma_list:
        # 对图像应用高斯模糊
        blurred = cv2.GaussianBlur(image, (0, 0), sigma)
        image[image == 0] = 1e-10
        blurred[blurred == 0] = 1e-10
        # 计算原始图像和模糊图像的对数差值
        log_scale_diff = np.log(image) - np.log(blurred)

        # 将对数差值添加到输出中
        retinex_output += log_scale_diff

    # 对输出图像进行归一化
    retinex_output = (retinex_output / len(sigma_list)) * 255
    retinex_output = np.uint8(np.clip(retinex_output, 0, 255))

    return retinex_output

def inital_process(img):
    """
    图片进行初步处理
    :param img: 原始图像
    :return: 返回初步处理图像
    """
    # 灰度处理
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    '''
    # 图像增强
    clahe = cv2.createCLAHE(
        clipLimit=2.0, tileGridSize=(10, 10))  # 对图像进行分割,10*10
    gray = clahe.apply(gray)  # 进行直方图均衡化
    # 高斯滤波
    blur = cv2.GaussianBlur(gray, (3, 3), 1)
    kernel_2 = np.ones((3, 3), np.uint8)
    # 腐蚀膨胀操作
    erosion = cv2.erode(blur, kernel=kernel_2, iterations=2)
    dilate = cv2.dilate(erosion, kernel_2, iterations=1)

    edges = cv2.Canny(dilate, 250, 180)
    '''

    # 改进Retinex增强图像
    sigma_list = [15, 80, 250]
    image = gray.astype(np.float32) / 255.0
    image = retinex(image, sigma_list)
    # 边缘检测
    edges = cv2.Canny(image, 250, 180)

    return edges

def region_of_interest(img, vertices, sign):
    """
    生成ROI区域
    :param img: 原始图像,是提取了物体边缘的图像
    :param vertices: 多边形坐标
    :return: 返回只保留了ROI区域内的物体边缘的图像
    """
    # 生成和img大小一致的图像矩阵,全部填充0(黑色)
    roi = np.zeros_like(img)
    # vertices即梯形区域顶点,填充梯形内部区域为白色
    if (sign):
        ignore_mask_color = 255
    else:
        roi = cv2.bitwise_not(roi)
        ignore_mask_color = 0
    # 填充函数,将vertices多边形区域填充为指定的灰度值
    cv2.fillPoly(roi, vertices, color=ignore_mask_color)
    # 显示ROI区域
    # cvShow(roi, 'ROI')
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    # 两张图片上的像素进行与操作,ROI区域中已经填充白色,其他是黑色
    # img中是canny算子提取的物体边缘是白色，其他区域是黑色
    # 黑色与黑色与运算还是黑色，白色与白色与运算还是白色，白色与黑色与运算是黑色
    # bitwise_and即两张图片上相同位置像素点上的灰度值进行与运算
    masked_image = cv2.bitwise_and(img, roi)
    # cvShow(masked_image, 'masked_image')
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    return masked_image

def calculate_slope(line):
    """
    计算斜率
    :param line: np.array([[x_1,y_1,x_2,y_2]])
    :return:
    """
    x_1, y_1, x_2, y_2 = line[0]
    return (y_2 - y_1) / (x_2 - x_1)

def bypass_angle_filter(lines, low_thres, high_thres):
    """
    角度滤波器
    :param lines: 概率霍夫变换得到的直线的端点对集合
    :param low_thres:低阈值
    :param high_thres:高阈值
    :return:得到过滤后的直线端点对集合
    """
    filtered_lines = []
    if lines is None:
        return filtered_lines
    for line in lines:
        for x1, y1, x2, y2 in line:
            # 过滤掉角度0或90度的直线
            if x1 == x2 or y1 == y2:
                continue
            # 保留角度在low_thres到high_thres之间的直线,角度按360度的标度来算
            angle = abs(np.arctan((y2 - y1) / (x2 - x1)) * 180 / np.pi)
            if low_thres < angle < high_thres:
                filtered_lines.append([[x1, y1, x2, y2]])
    return filtered_lines

def reject_abnormal_lines(lines, threshold):
    """
    剔除斜率不一致线段
    :param lines: 线段集合,np.array([[x_1,y_1,x_2,y_2]])
    :return:
    """
    # 计算线段斜率集合
    slopes = [calculate_slope(line) for line in lines]
    while len(lines) > 0:
        # 计算斜率平均值
        mean = np.mean(slopes)
        # 计算斜率与平均值差值集合
        diff = [abs(s - mean) for s in slopes]
        # 索引差值最大值下标
        idx = np.argmax(diff)
        if diff[idx] > threshold:
            # 删除此直线
            slopes.pop(idx)
            lines.pop(idx)
        else:
            break
    return lines

def least_squares_fit(lines):
    """
    将lines中的线段拟合成一条
    :param lines: 线段集合,np.array([[x_1,y_1,x_2,y_2]])
    :return: 线段上两点,np.array([[xmin,ymin],[xmax,ymax]])
    """
    # 取出所有坐标点
    x_coords = np.ravel([[line[0][0], line[0][2]] for line in lines])
    y_coords = np.ravel([[line[0][1], line[0][3]] for line in lines])
    # 进行直线拟合,得到多项式系数 k,b
    poly = np.polyfit(x_coords, y_coords, deg=1)
    # 根据多项式系数,计算两个直线上的点，用于唯一确定这条直线 val用于求y = k*x + b
    point_min = (np.min(x_coords), np.polyval(poly, np.min(x_coords)))
    point_max = (np.max(x_coords), np.polyval(poly, np.max(x_coords)))
    return np.array([point_min, point_max], dtype=np.int64)

def dispose_line(edges):
    """
    处理初步处理后图像生成霍夫线集合
    :param edges: 初步处理图像
    :return: lines 霍夫线集合 np.array([[x_1,y_1,x_2,y_2]])
    """
    # 霍夫变换获取所有线段
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=30,
                            minLineLength=10, maxLineGap=100)
    # lines = cv2.HoughLinesP(masked, 1, np.pi/180, threshold=100,
    #                     minLineLength=100, maxLineGap=30)
    return lines

def generate_line(lines):
    """
    生成所需绘制线条
    :param lines: 初步处理图像
    :return: left_line,right_line 所生成两侧直线点集np.array([[x_1,y_1],[x_2,y_2]])
    """
    print('检测出线条点集对总数目:', len(lines))
    lines = bypass_angle_filter(lines, 60, 90)
    print('角度滤波后点集对总数目:', len(lines))
    # 按照斜率划分皮带左右侧
    # 列表生成式
    left_belt = [line for line in lines if calculate_slope(line) < 0]
    print('左侧点集对数目:', len(left_belt))
    right_belt = [line for line in lines if calculate_slope(line) > 0]
    print('右侧点集对数目:', len(right_belt))
    # 过滤线段
    left_belt = reject_abnormal_lines(left_belt, 0.005)
    print('左侧过滤后点集对数目:', len(left_belt))
    right_belt = reject_abnormal_lines(right_belt, 0.005)
    print('右侧过滤后点集对数目:', len(right_belt))
    # 线段拟合
    left_line = least_squares_fit(left_belt)
    right_line = least_squares_fit(right_belt)

    return left_line, right_line

def line_pro_count(img, left_line, right_line):
    """
    图像中延伸并绘制线段
    :param img: 输入图像
    :param left_line: 左侧线段点
    :param right_line: 右侧线段点
    """
    # 取出左右线条点
    left_src_line_1 = tuple(left_line[0])
    left_src_line_2 = tuple(left_line[1])
    right_src_line_1 = tuple(right_line[0])
    right_src_line_2 = tuple(right_line[1])
    # 设置延伸方位
    y_up = 350
    y_down = 900
    y_buttom = 1000
    # 计算左右侧斜率与截距
    left_k = (left_src_line_2[1] - left_src_line_1[1]) / \
        (left_src_line_2[0] - left_src_line_1[0])
    left_b = left_src_line_1[1] - left_k * left_src_line_1[0]
    right_k = (right_src_line_2[1] - right_src_line_1[1]) / \
        (right_src_line_2[0] - right_src_line_1[0])
    right_b = right_src_line_1[1] - right_k * right_src_line_1[0]
    # 计算左侧延长点
    left_x_up = int((y_up - left_b)/left_k)
    left_up = (left_x_up, y_up)
    left_x_down = int((y_down - left_b)/left_k)
    left_down = (left_x_down, y_down)
    left_x_buttom = int((y_buttom - left_b)/left_k)
    # 计算右侧延长点
    right_x_up = int((y_up - right_b)/right_k)
    right_up = (right_x_up, y_up)
    right_x_down = int((y_down - right_b)/right_k)
    right_down = (right_x_down, y_down)
    right_x_buttom = int((y_buttom - right_b)/right_k)

    # 计算皮带中心点坐标
    pixels_between_lines = (left_x_buttom + right_x_buttom)/2

    data = pixels_between_lines - CENTER
    # 判定跑偏并绘制边缘线
    if(data > 0):
        thresh_right = int(pixels_between_lines*0.03)
        if(abs(data) > thresh_right):
            img_show(img,left_up,left_down,False)
            img_show(img,right_up,right_down,False)
            print("右侧跑偏")
        else:
            img_show(img,left_up,left_down,True)
            img_show(img,right_up,right_down,True)
            print("正常")
    else:
        thresh_left= int(pixels_between_lines*0.05)
        if(abs(data) > thresh_left):
            img_show(img,left_up,left_down,False)
            img_show(img,right_up,right_down,False)
            print("左侧跑偏")
        else:
            img_show(img,left_up,left_down,True)
            img_show(img,right_up,right_down,True)
            print("正常")
'''
    # 判定跑偏并绘制边缘线
    if (data > thresh):
        cv2.line(img, left_up, left_down, color=(0, 0, 255), thickness=5)
        cv2.line(img, right_up, right_down, color=(0, 0, 255), thickness=5)
        if((pixels_between_lines - CENTER) > 0):
            print("右侧跑偏")
        else:
            print("左侧跑偏")
    else:
        cv2.line(img, left_up, left_down, color=(0, 255, 0), thickness=5)
        cv2.line(img, right_up, right_down, color=(0, 255, 0), thickness=5)
        print("正常")
'''

def img_show(img, left_line, right_line,sign):
    """
    图像中绘制线段
    :param img: 输入图像
    :param left_line: 左侧线段点
    :param right_line: 右侧线段点
    """
    if(sign):
        cv2.line(img, left_line, right_line, color=(0, 255, 0), thickness=5)
    else:
        cv2.line(img, left_line, right_line, color=(0, 0, 255), thickness=5)

if __name__ == '__main__':
    start_time = time.time()
    img = cv2.imread('D:\Project\Python\img\\belt.jpg')
    cv2.waitKey(0)
    # img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
    imgCopy = img.copy()
    edges = inital_process(img)
    vertices = np.array([[[150, 730], [301, 380], [1453, 380], [1618, 730]]])
    masked = region_of_interest(edges, vertices=vertices, sign=INITIAL_ROI)

    # 右侧过滤
    vertices_further_1 = np.array(
        [[[1570, 730], [1500, 540], [1600, 540], [1700, 730]]])
    masked = region_of_interest(
        masked, vertices=vertices_further_1, sign=FURTHER_ROI)

    vertices_further_2 = np.array(
        [[[200, 700], [210, 600], [250, 600], [240, 700]]])
    masked = region_of_interest(
        masked,
        vertices=vertices_further_2, sign=FURTHER_ROI)
    # 右跑偏过滤
    '''
    vertices_further_3 = np.array(
        [[[220, 670], [262, 405], [370, 405], [330, 670]]])
    masked = region_of_interest(
        masked, vertices=vertices_further_3, sign=FURTHER_ROI)
    '''
    lines = dispose_line(masked)
    left_line, right_line = generate_line(lines)
    line_pro_count(imgCopy, left_line, right_line)
    cvShow(imgCopy, 'img')
    end_time = time.time()
    execution_time = end_time - start_time
    print("代码块运行时间：", execution_time, "秒")

    # video = cv2.VideoCapture('top.mp4')
    # # 获取视频的帧速率
    # fps = video.get(cv2.CAP_PROP_FPS)

    # # 设置视频的帧速率
    # video.set(cv2.CAP_PROP_FPS, fps / 2)

    # while (video.isOpened()):
    #     # read()返回两个值 ret为bool frame为视频一帧图像
    #     ret, frame = video.read()
    #     # flip()函数进行图像水平翻转 参数查阅文档
    #     # frame = cv2.flip(frame,-1)
    #     imgCopy = frame.copy()
    #     edges = inital_process(frame)
    #     vertices = np.array([[[150, 730], [301, 380], [1453, 380], [1618, 730]]])
    #     # vertices = np.array([[[220, 730], [300, 240], [1510, 350], [1650, 730]]])
    #     masked = region_of_interest(edges, vertices=vertices,sign=INITIAL_ROI)
    #     vertices_further_1 = np.array([[[1570,730],[1500,540],[1600,540],[1700,730]]])
    #     masked = region_of_interest(masked,vertices=vertices_further_1,sign=FURTHER_ROI)
    #     vertices_further_2 = np.array([[[200,700],[210,600],[250,600],[240,700]]])
    #     masked = region_of_interest(masked,vertices=vertices_further_2,sign=FURTHER_ROI)
    #     lines = dispose_line(masked)
    #     left_line, right_line = generate_line(lines)
    #     line_pro_count(imgCopy, left_line, right_line)
    #     cvShow(imgCopy, 'img')
    #     if cv2.waitKey(1) & 0xFF == 27:
    #         break
    # 释放捕捉对象

    cv2.waitKey(0)
    cv2.destroyAllWindows()


from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from googleapiclient.http import MediaFileUpload
from datetime import datetime

work_dt = datetime.today().strftime("%Y%m%d")

try :
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('/home/kizacademy/projects/mysite/storage.json')
creds = store.get()

if not creds or creds.invalid:
    print("make new storage data file ")
    flow = client.flow_from_clientsecrets('/home/kizacademy/projects/mysite/client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store, flags) \
            if flags else tools.run(flow, store)

DRIVE = build('drive', 'v3', http=creds.authorize(Http()))

folder_id = '130Fxlqmlua9QpWym6xyc24klYn60A_v9'
filename = 'db.sqlite3_' + work_dt
request_body = {'name': filename,
                'parents': [folder_id] } # 업로드할 파일의 정보 정의
media = MediaFileUpload('db.sqlite3') # 업로드할 파일
file = DRIVE.files().create(body=request_body,media_body=media).execute()
print("File ID :",file.get('id'))


import torch
import torch.nn as nn
import numpy as np
import math

# # Define neural network modules

class WAVSTFT(nn.Module):
    def __init__(self, win_size=320):
        super(WAVSTFT, self).__init__()
        window = torch.from_numpy(np.hanning(win_size).astype(np.float32))
        self.window_size = window.shape[-1]
        self.hop_length = self.window_size // 2
        window = window.unsqueeze(0).unsqueeze(-1)
        divisor = torch.ones(1, 1, 1, self.window_size * 4)
        divisor = nn.functional.unfold(
            divisor, (1, self.window_size), stride=self.hop_length
        )
        divisor = divisor * window.pow(2.0)
        divisor = nn.functional.fold(
            divisor,
            (1, self.window_size * 4),
            (1, self.window_size),
            stride=self.hop_length,
        )[:, 0, 0, :]
        divisor = (
            divisor[0, self.window_size: 2 * self.window_size]
            .unsqueeze(0)
            .unsqueeze(-1)
        )
        self.register_buffer("window", window)
        self.register_buffer("divisor", divisor)

    def magphase(self, complex_tensor: torch.Tensor):
        mag = complex_tensor.pow(2.0).sum(-1).pow(0.5 * 1.0)
        phase = torch.atan2(complex_tensor[..., 1], complex_tensor[..., 0])
        return mag, phase

    def add_window(self, x, divisor):
        out = x * self.window / divisor
        return out

    def frame(self, x):
        assert x.dim() == 2, x.shape
        out = x.unsqueeze(1).unsqueeze(1)
        out = nn.functional.pad(
            out, (self.window_size, self.window_size), "constant", 0
        )
        out = nn.functional.unfold(
            out, (1, self.window_size), stride=self.hop_length
        )  # B N T
        return out

    def overlap_and_add(self, x, length):
        assert x.dim() == 3, x.shape
        out = nn.functional.fold(
            x,
            (1, length + 2 * self.window_size),
            (1, self.window_size),
            stride=self.hop_length,
        )[:, 0, 0, :]
        out = out[:, self.window_size: -self.window_size]
        return out

    def rfft(self, x):
        assert x.dim() == 3, x.shape
        return torch.fft.rfft(x, dim=1)

    def irfft(self, x):
        assert x.dim() == 3, x.shape
        return torch.fft.irfft(x, dim=1)

    def STFT(self, x, return_aux=False):
        assert x.dim() == 2, x.shape
        out = self.frame(x)
        out = self.add_window(out, 1)
        out = self.rfft(out)
        if return_aux:
            mag, phase = self.magphase(torch.view_as_real(out))
            lps = torch.log(mag**2 + 1e-8)
            return out, mag, phase, lps
        else:
            return out

    def iSTFT(self, x, length):
        assert x.dim() == 3, x.shape
        out = self.irfft(x)
        out = self.add_window(out, self.divisor)
        out = self.overlap_and_add(out, length=length)
        return out

class TimeCompression(nn.Module):
    def __init__(self, dim1, dim2, dim3, dim4, steps):
        super().__init__()
        self.dim1 = dim1
        self.dim2 = dim2
        self.dim3 = dim3
        self.dim4 = dim4
        self.steps = steps
        self.trans1 = nn.Conv2d(
            self.dim1 * self.steps, self.dim2, 1, bias=False
        )
        self.trans2 = nn.Conv2d(self.dim3, self.dim4, 1, bias=False)

    def forward(self, x, inverse):
        # x B C T F
        if inverse:
            B, C, T, F = x.shape
            x = (
                self.trans2(x)
                .reshape(B, -1, 1, T, F)
                .permute(0, 1, 3, 2, 4)
                .contiguous()
            )  # B C T S F
            x = x.repeat(1, 1, 1, self.steps, 1).reshape(
                B, -1, T * self.steps, F
            )  # B C T*S F
            x = torch.nn.functional.pad(
                x, (0, 0, self.steps - 1, 0), "constant", 0
            )
            x = x[:, :, : -self.steps + 1, :]
            if self.pad > 0:
                x = x[:, :, self.pad:, :]
            return x
        else:
            B, C, T, F = x.shape
            if x.shape[-2] % self.steps == 0:
                self.pad = 0
            else:
                self.pad = self.steps - x.shape[-2] % self.steps
                x = torch.nn.functional.pad(
                    x, (0, 0, self.pad, 0), "constant", 0
                )
            x = (
                x.reshape(B, C, -1, self.steps, F)
                .permute(0, 1, 3, 2, 4)
                .contiguous()
            )  # B C S T F
            x = x.reshape(B, C * self.steps, -1, F)  # B C*S T F
            return self.trans1(x)

class FreqCompression(nn.Module):
    def __init__(
        self, nfreq, nfilters, in_dim, hidden_dim, out_dim, sample_rate=16000
    ):
        super().__init__()
        self.nfreq = nfreq
        self.nfilters = nfilters
        self.sample_rate = sample_rate
        self.in_dim = in_dim
        self.hidden_dim = hidden_dim
        self.out_dim = out_dim

        mel_scale = "htk"

        all_freqs = torch.linspace(0, sample_rate // 2, nfreq)
        # calculate mel freq bins
        m_min = self._hz_to_mel(0, mel_scale=mel_scale)
        m_max = self._hz_to_mel(sample_rate / 2.0, mel_scale=mel_scale)

        m_pts = torch.linspace(m_min, m_max, self.nfilters + 2)
        f_pts = self._mel_to_hz(m_pts, mel_scale=mel_scale)
        self.bounds = [
            0,
        ]
        for freq_inx in range(1, len(f_pts) - 1):
            self.bounds.append(
                (all_freqs > f_pts[freq_inx]).float().argmax().item()
            )
        self.bounds.append(nfreq)
        self.trans1 = nn.ModuleList()
        self.trans2 = nn.ModuleList()
        for freq_inx in range(self.nfilters):
            self.trans1.append(
                nn.Linear(
                    (self.bounds[freq_inx + 2] - self.bounds[freq_inx])
                    * self.in_dim,
                    self.hidden_dim,
                    bias=False,
                )
            )
            self.trans2.append(
                nn.Conv1d(
                    self.hidden_dim,
                    (self.bounds[freq_inx + 2] - self.bounds[freq_inx])
                    * self.out_dim,
                    1,
                )
            )

    def _hz_to_mel(self, freq: float, mel_scale: str = "htk") -> float:
        r"""
        Source: https://pytorch.org/audio/stable/
        _modules/torchaudio/functional/functional.html
        Convert Hz to Mels.

        Args:
            freqs (float): Frequencies in Hz
            mel_scale (str, optional): Scale to use:
            ``htk`` or ``slaney``. (Default: ``htk``)

        Returns:
            mels (float): Frequency in Mels
        """

        if mel_scale not in ["slaney", "htk"]:
            raise ValueError('mel_scale should be one of "htk" or "slaney".')

        if mel_scale == "htk":
            return 2595.0 * math.log10(1.0 + (freq / 700.0))

        # Fill in the linear part
        f_min = 0.0
        f_sp = 200.0 / 3

        mels = (freq - f_min) / f_sp

        # Fill in the log-scale part
        min_log_hz = 1000.0
        min_log_mel = (min_log_hz - f_min) / f_sp
        logstep = math.log(6.4) / 27.0

        if freq >= min_log_hz:
            mels = min_log_mel + math.log(freq / min_log_hz) / logstep

        return mels

    def _mel_to_hz(
        self, mels: torch.Tensor, mel_scale: str = "htk"
    ) -> torch.Tensor:
        """
        Source: https://pytorch.org/audio/stable/
        _modules/torchaudio/functional/functional.html
        Convert mel bin numbers to frequencies.

        Args:
            mels (torch.Tensor): Mel frequencies
            mel_scale (str, optional): Scale to use:
            ``htk`` or ``slaney``. (Default: ``htk``)

        Returns:
            freqs (torch.Tensor): Mels converted in Hz
        """

        if mel_scale not in ["slaney", "htk"]:
            raise ValueError('mel_scale should be one of "htk" or "slaney".')

        if mel_scale == "htk":
            return 700.0 * (10.0 ** (mels / 2595.0) - 1.0)

        # Fill in the linear scale
        f_min = 0.0
        f_sp = 200.0 / 3
        freqs = f_min + f_sp * mels

        # And now the nonlinear scale
        min_log_hz = 1000.0
        min_log_mel = (min_log_hz - f_min) / f_sp
        logstep = math.log(6.4) / 27.0

        log_t = mels >= min_log_mel
        freqs[log_t] = min_log_hz * torch.exp(
            logstep * (mels[log_t] - min_log_mel)
        )

        return freqs

    def forward(self, x, inverse):
        if inverse:
            # B C T F
            out = torch.zeros(
                [x.shape[0], self.out_dim, self.nfreq, x.shape[2]],
                dtype=x.dtype,
                layout=x.layout,
                device=x.device,
            )
            for freq_inx in range(self.nfilters):
                out[
                    :, :, self.bounds[freq_inx]: self.bounds[freq_inx + 2], :
                ] = out[
                    :, :, self.bounds[freq_inx]: self.bounds[freq_inx + 2], :
                ] + self.trans2[
                    freq_inx
                ](
                    x[:, :, :, freq_inx]
                ).reshape(
                    x.shape[0], self.out_dim, -1, x.shape[-2]
                )
            out[:, :, self.bounds[1]: self.bounds[-2], :] = (
                out[:, :, self.bounds[1]: self.bounds[-2], :] / 2.0
            )
            out = out.permute(0, 1, 3, 2).contiguous().tanh()
            return out
        else:
            x = x.reshape(x.shape[0], self.in_dim, *x.shape[-2:])  # B C T F
            x = x.permute(0, 2, 1, 3).contiguous()  # B T C F
            x = torch.stack(
                [
                    self.trans1[freq_inx](
                        x[
                            :,
                            :,
                            :,
                            self.bounds[freq_inx]: self.bounds[freq_inx + 2],
                        ].flatten(start_dim=2)
                    )
                    for freq_inx in range(self.nfilters)
                ],
                -1,
            )  # B T C F
            x = x.permute(0, 2, 1, 3).contiguous()
            return x

class UltraDualPath(nn.Module):
    def __init__(
        self,
        nfreq,
        in_dim,
        hidden_dim,
        out_dim,
        freq_cprs_ratio,
        time_cprs_ratio,
    ):
        super(UltraDualPath, self).__init__()
        self.nfreq = nfreq
        self.in_dim = in_dim
        self.hidden_dim = hidden_dim
        self.out_dim = out_dim
        self.freq_cprs_ratio = freq_cprs_ratio
        self.time_cprs_ratio = time_cprs_ratio
        self.compress_modules = [
            TimeCompression(
                self.in_dim,
                self.in_dim * 2,
                self.out_dim,
                self.out_dim,
                time_cprs_ratio,
            ),
            FreqCompression(
                self.nfreq,
                self.nfreq // self.freq_cprs_ratio,
                self.in_dim * 2,
                self.hidden_dim,
                self.out_dim,
            ),
        ]

    def forward(self, x, inverse):
        out = x
        # print(out.shape)
        if inverse:
            for m in self.compress_modules[::-1]:
                out = m(out, inverse)
                # print(out.shape)
        else:
            for m in self.compress_modules:
                out = m(out, inverse)
                # print(out.shape)
        return out

# # An example of run

# ## Define model and input

# ## Define network modules
win_size = 320
wavSTFT = WAVSTFT(win_size)  # 16khz, 20ms/10ms -> 320 samples
ultraCompress = UltraDualPath(
    win_size // 2 + 1, 3 * 2, 48, 48, 4, 4
)  # 3ch*(real+imag)
# ## Define input
wav = torch.rand(2, 3, 16000)  # nbatch=2, nchannels=3, nsamples=16000

# ## Run

# organize input
B, C, N = wav.shape
spec = wavSTFT.STFT(wav.reshape(B * C, N))
spec = torch.view_as_real(spec.reshape(B, C, *spec.shape[-2:]))  # B C F T 2
spec = spec.permute(0, 1, 4, 3, 2)  # B C 2 T F
spec = spec.reshape(B, C * 2, *spec.shape[-2:])
print(spec.shape)  # nbatch, nchannels*2, nframes, nfreqs

# compress
latent = ultraCompress(spec, 0)
print(latent.shape)  # nbatch, hidden_dim, nframes, nfreqs

# decompress
output = ultraCompress(latent, 1)
print(output.shape)  # nbatch, out_dim, nframes, nfreqs


import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

def train_lstm_model(data_file, sequence_length, batch_size=32, epochs=100, learning_rate=0.001, patience=10):
    # Load the stock price data
    df = pd.read_csv(data_file)
    dataset = df['Close'].values.reshape(-1, 1)

    # Scale the data
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(dataset)

    # Split the data into training and testing sets
    train_size = int(len(scaled_data) * 0.8)
    train_data = scaled_data[:train_size]
    test_data = scaled_data[train_size:]

    # Create sequences for the LSTM model
    def create_sequences(data, sequence_length):
        X = []
        y = []
        for i in range(len(data) - sequence_length):
            X.append(data[i:i+sequence_length])
            y.append(data[i+sequence_length])
        return np.array(X), np.array(y)

    X_train, y_train = create_sequences(train_data, sequence_length)
    X_test, y_test = create_sequences(test_data, sequence_length)

    # Build the LSTM model
    model = Sequential()
    model.add(LSTM(units=64, return_sequences=True, input_shape=(sequence_length, 1)))
    model.add(Dropout(0.2))
    model.add(LSTM(units=64, return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(units=64))
    model.add(Dropout(0.2))
    model.add(Dense(units=1))

    # Compile the model
    model.compile(optimizer=Adam(learning_rate=learning_rate), loss='mean_squared_error')

    # Define callbacks
    early_stopping = EarlyStopping(monitor='val_loss', patience=patience, verbose=1, restore_best_weights=True)
    checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)

    # Train the model
    history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=(X_test, y_test), callbacks=[early_stopping, checkpoint])

    # Load the best model
    model.load_weights('best_model.h5')

    # Evaluate the model
    train_loss = model.evaluate(X_train, y_train)
    test_loss = model.evaluate(X_test, y_test)

    print('Train Loss:', train_loss)
    print('Test Loss:', test_loss)

    # Make predictions
    last_sequence = train_data[-sequence_length:]
    last_sequence = last_sequence.reshape(1, sequence_length, 1)

    predicted_values = []
    for _ in range(len(test_data)):
        predicted_value = model.predict(last_sequence)
        predicted_values.append(predicted_value)
        last_sequence = np.append(last_sequence[:, 1:, :], [[predicted_value]], axis=1)

    predicted_values = np.array(predicted_values).reshape(-1, 1)
    predicted_values = scaler.inverse_transform(predicted_values)

    # Print the predicted stock prices
    for i in range(len(predicted_values)):
        print(f'Predicted Stock Price at Time Step {i+1}: {predicted_values[i][0]}')


#!/usr/bin/env python
# encoding: utf-8
# 作者：Ksar4
# 日期：2020/12/8 16:10
# 工具：PyCharm
# Python版本：3.7.0
""""""

"""
输入一个整数数组，实现一个函数来调整该数组中数字的顺序，使得所有的奇数位于数组的前半部分，所有的偶数位于数组的后半部分，
并保证奇数和奇数，偶数和偶数之间的相对位置不变。

"""

"""

"""

class Solution:
    def reOrderArray(self, array):
        # 类似于快速排序 根据index交换值
        for i in range(1, len(array)):
            if array[i] % 2 == 1:
                j = i - 1
                value = array[i]
                while j >= 0:
                    if array[j] % 2 == 0:
                        array[j+1] = array[j]
                    else:
                        break
                    j -= 1
                array[j+1] = value
        return array

    def reOrderArray_1(self , array ):
        odd = []
        even = []
        for i in array:
            if i % 2:
                odd.append(i)
            else:
                even.append(i)
        for j in even:
            odd.append(j)
        return odd

if __name__ == "__main__":

    s= Solution()
    print(s.reOrderArray([2,3,4,5]))

13_调整数组顺序使奇数位于偶数之前.py


import json

#importing mbs.json file
with open("mbs.json","r") as read_files:
    data7=json.load(read_files)
#print(data7[0])
def mbs_data():
    mbs_model=[]
    for i in range(2):
         faculty_model.append(data7[i]['Year'])
    #list of availabl faculties
    print(mbs_model)

#for full info
def mbs_info(usermodel):
    usermodel = usermodel.upper()
    mbs_model = []
    for i in range(2):
        mbs_model.append(data7[i]['Year'])
    print(mbs_model)

    if usermodel in mbs_model:
        #index of usermodel
        x=mbs_model.index(usermodel)
        extract_model=data7[x]['Year']
        if extract_model==usermodel:
            print("KBC Bot: BBS "+ data7[x]['Year']+" year details:\n")
            print("Shift: "+data7[x]['Shift']+"\t\tYear Fee: "+data7[x]['Year_fee']+"\n")
            print("Course list:\n")
            for i in range(len(data7[x]['Subjects'])):
                print("*  "+data7[x]['Subjects'][i])
            if len(data7[x]['Electives'])>0:
                print("\nElective Subjects: (Choose at least one from below):\n")
                for i in range(len(data7[x]['Electives'])):
                    print("*  "+data7[x]['Electives'][i])

#for fee only
def year_fee(usermodel):
    usermodel = usermodel.upper()
    mbs_model = []
    for i in range(2):
        mbs_model.append(data7[i]['Year'])
    if usermodel in mbs_model:
        #index of usermodel
        x = mbs_model.index(usermodel)
        extract_model = data7[x]['Year']
        if extract_model == usermodel:
            print("\nKBC Bot: The fee for "+ data7[x]['Year'] +" year is "+ data7[x]['Year_fee'])

#z=input()
#mbs_info(z)
#year_fee(z)


from django.conf.urls import url
from . import views
from django.urls import path, re_path

app_name = 'retirecenterapp'
urlpatterns = [
    path('', views.home, name='home'),
    re_path(r'^home/$', views.home, name='home'),
    path('order_list', views.order_list, name='order_list'),
    path('order/create/', views.order_new, name='order_new'),
    path('order/<int:pk>/edit/', views.order_edit, name='order_edit'),
    path('order/<int:pk>/delete/', views.order_delete, name='order_delete'),
    path('profile_display', views.profile_display, name='profile_display'),
    path('profile_edit', views.profile_edit, name='profile_edit'),

]


'''A man is having 1 lakh in his bank account in the rate of interest is 12% per annum,
in the the 5th month he is withdrawal 25k,
in the 9th month 10k rupees deposited to his account,
End of the financial year how much he is having in his account.'''
#simple interest
p=100000
st1=(p*(4/12)*12)/100
p=p-25000
st2=(p*(4/12)*12)/100
p=p+10000
st3=(p*(4/12)*12)/100
p=p+st1+st2+st3
print(p)

'''Object Identity:Memory ,unique and constant for the lifetime of the object'''
a=100
print("Memory",id(a)) #function

'''using for and while '''
#how many times statemnets is getting executed--n times
n=int(input())
temp=0
while(n!=0):
    rem=n%10
    temp=temp+rem
    n=n//10
print("using while",temp)
for i in range(n):
    rem = n % 10
    temp = temp + rem
    n = n // 10
print("using for",temp)

'''space comlexity'''
 #struct, Union

#int-4
#double-6
#char-1

'''struct'''
# int---4               int---4          int---4
# char---1             int---4          double---8
# space 8bytes         space--8         space---12
'''union'''
# int---4            int---4          int---4
# char---1           int---4          double---8
# space--4           space---4         space---8

'''
 struc{
    double-------8+1+7=16
    char
}
 int
 double---------4+4+8+1+7=24
 char'''


from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.utils import platform

class BluetoothScreen(Screen):
    import functions.blt_func as blt
    import functions.socket_manager as socket_m

    def search_devices(self):
        if platform=='win':
            self.ids.blt_device_list.clear_widgets()
            devices_found, self.ids.devices_found.text = self.blt.search_new_devices()
            if len(devices_found) > 0:
                self.ids.blt_device_list.remove_widget(self.ids.devices_found)

                for device in devices_found:
                    self.ids.blt_device_list.add_widget(
                        Button(
                            #id = str(device[0]),
                            text="connect to " + str(device[1]),
                            on_press=(lambda x: self.try_connection(str(device[0])))
                        )
                    )
                    #self.ids.str(device[0]).bind(on_press=self.try_connection)
            else:
                pass
        elif platform=='android':
            self.ids.devices_found.text = "Sorry, no implemented yet :p"

    def try_connection(self, addr):
        print("try_connection")
        self.connection_socket = self.blt.try_connection(addr)
        self.socket_m.conection_socket = self.connection_socket
        if self.connection_socket is not None:
            self.ids.connected_bluetooth.text = "Device connected"
            self.ids.blt_send_data.disabled = False
            self.disconnect_button = Button(
                text="disconnect device",
                on_press=(
                    lambda x: self.close_connection(self.connection_socket)
                )
            )
            self.ids.connection_layout.add_widget(self.disconnect_button)
        else:
            pass

    def close_connection(self, socket):
        self.blt.close_connection(socket)
        self.ids.connection_layout.remove_widget(self.disconnect_button)
        self.ids.blt_send_data.disabled = True
        self.ids.connected_bluetooth.text = "No connected Devices!"

    def send_message(self):
        message = self.ids.blt_message.text
        self.blt.send_message(self.connection_socket, message)

    def send_coordinates(self, controll):
        self.blt.send_message(self.connection_socket, controll)


'''
Created on 23 Mar 2018

@author: s258115
'''
import sys
import csv
import json

print('Hello')
print(sys.version)

# Open the CSV
f = open( 'c:/Temp/test.csv', 'rU' )
# Change each fieldname to the appropriate field name.
reader = csv.DictReader( f, fieldnames = ( "fieldname0","fieldname1","fieldname2","fieldname3" ))
# Parse the CSV into JSON
out = json.dumps( [ row for row in reader ] )

print('JSON parsed!')

# Save the JSON
f = open( 'c:/Temp/test.json', 'w')
f.write(out)
print('JSON saved!')


import unittest
from searchindex.search import SearchableIndex

class SearchIndexTestCase(unittest.TestCase):
    def setUp(self):
        self.corpus = SearchableIndex("wikipedia_example.tsv")
        # [("query","the top document expected")]
        self.query_options = [
        	("Berlin", "Olympiastadion Berlin"),
        	("The", "The Warriors"),
        	("Ludwig van Beethoven", "Christian Gottlob Neefe"),
        	("STRING_WHICH_MOST_LIKELY_DOESNOT_APPEAR ANOTHER_STRANGE_STRING", None)
        ]

class SearchKeywordTestCase(SearchIndexTestCase):
    def runTest(self):
    	for query in self.query_options:
    		results = self.corpus.search(query[0])
    		self.assertEqual(results[0][1] if len(results)>0 else None , query[1],
                         'SearchIndex: incorrect search for query [%s]' % query[0])


#Faça um algoritmo que receba dois vetores A[1 .. n] e B[1 .. m] e decida se existe um índice i tal que A[i] = B[i].
#obs: fazer duas leituras, uma para cada vetor e retornar um booleano (True ou False).
#Ex:
#Input: [1, 3, 5, 7, 'a', 'aba']
#[33, 9, 0]
#Output: False

A, B = eval(input()), eval(input())
for i in range(len(A)):
    for x in range(len(B)):
        if A[x] == B[x]:
            r = True
            break
        else:
            r = False
print(r)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        lis = []
        while head:
            lis.append(head.val)
            head = head.next
        lis = sorted(lis)
        dummy = ListNode(0)
        ptn = dummy

        for num in lis:
            ptn.next = ListNode(num)
            ptn = ptn.next
        return dummy.next


inputs = [(x.split()[1], x.split()[7]) for x in open('input.txt', 'r').readlines()]

order = ''

while len(inputs) > 0:
	available = [i for i in inputs if i[0] not in [x[1] for x in inputs]]
	available.sort(key=lambda x: (x[0], x[1]))
	selected = available[0]
	if selected[0] not in order:
		order += selected[0]
	if len(inputs) == 1:
		order += selected[1]
	inputs = [x for x in inputs if x[0] not in order]
print(order)


import matplotlib.pyplot as plt
import numpy as np

x1, x2, y = np.loadtxt("outfile.txt", unpack = True)
n_bins = 100

plt.figure(1)
plt.hist(x1, n_bins, normed = True)
plt.xlabel("$x_1$")
plt.ylabel("density")
plt.savefig("x1.pdf", format = "pdf", bbox_inches = "tight")
plt.close(1)

plt.figure(2)
plt.hist(x2, n_bins, normed = True)
plt.xlabel("$x_2$")
plt.ylabel("density")
plt.savefig("x2.pdf", format = "pdf", bbox_inches = "tight")
plt.close(2)

# plt.figure(3)
# plt.hist(x3, n_bins, normed = True)
# plt.xlabel("$x_3$")
# plt.ylabel("density")
# plt.savefig("x3.pdf", format = "pdf", bbox_inches = "tight")
# plt.close(3)

plt.figure(4)
plt.hist(y, n_bins, normed = True)
plt.xlabel("$y$")
plt.ylabel("density")
plt.savefig("y.pdf", format = "pdf", bbox_inches = "tight")
plt.close(4)

print(np.mean(x1))
print(np.mean(x2))
#print(np.mean(x3))
print(np.mean(y))


import numpy as np
from argparse import ArgumentParser
import argparse
import torch
import pytorch_lightning as pl
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks import TQDMProgressBar
from pytorch_lightning.profiler import PyTorchProfiler
import torch.utils.tensorboard
from torch.utils.tensorboard import SummaryWriter
import warnings
warnings.filterwarnings("ignore")
from tabulate import tabulate
from time import time
import json

class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,
                      argparse.MetavarTypeHelpFormatter):
    pass

parser = ArgumentParser(description='Training script for CpG', formatter_class=CustomFormatter)

dm_parse = parser.add_argument_group('DataModule', 'Data Module arguments')
dm_parse.add_argument('--dataset_path', type=str, default="",
                      help='Datapath of datasets')
dm_parse.add_argument('--dataset', type=str, default="HCC",
                      help='name of datasets')
dm_parse.add_argument('--segment_size', type=int, default=21,
                      help='Bin size in number of CpG sites (columns) that every batch will contain. If GPU memory is exceeded, this option can be lowered.')
dm_parse.add_argument('--val_keys', type=str, nargs='+', default=['chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19'],
                      help='Names/keys of validation chromosomes.')
dm_parse.add_argument('--test_keys', type=str, nargs='+', default=['chr2', 'chr4', 'chr6', 'chr8', 'chr10', 'chr12'],
                      help='Names/keys of test chromosomes.')
dm_parse.add_argument('--batch_size', type=int, default=10240,
                      help='Batch size.')
dm_parse.add_argument('--n_workers', type=int, default=12,
                      help='Number of worker threads to use in data loading. Increase if you experience a CPU bottleneck.')

model_parse = parser.add_argument_group('Model', 'CpGTIGMC Hyperparameters')
model_parse.add_argument('--gpu', type=int, default=0,
                         help='id of used GPU.')
model_parse.add_argument('--latent_dim', type=list, default=[32, 64, 128, 128, 64, 32],
                         help='latent_dim.')
model_parse.add_argument('--adj_dropout', type=float, default=0.2,
                         help='args.adj_dropout')
model_parse.add_argument('--lr', type=float, default=1e-3,
                         help='Learning rate.')
model_parse.add_argument('--lr_decay_factor', type=float, default=.99,#.5,
                         help='Learning rate multiplicative decay applied after every epoch.')
model_parse.add_argument('--warmup_steps', type=int, default=100,
                         help='Number of steps over which the learning rate will linearly warm up.')
model_parse.add_argument('--maxepochs', type=float, default=1,#type=int, default=1,
                         help='Number of maximum epoch.')

log_parse = parser.add_argument_group('Logging', 'Logging arguments')
log_parse.add_argument('--tensorboard', type=bool, default=True,
                       help='Whether to use tensorboard. If True, then training progress can be followed by using (1) `tensorboard --logdir logfolder/` in a separate terminal and (2) accessing at localhost:6006.')
log_parse.add_argument('--log_folder', type=str, default='logfolder',
                       help='Folder where the tensorboard logs will be saved. Will additinally contain saved model checkpoints.')
log_parse.add_argument('--experiment_name', type=str, default='graph_cpg',
                       help='Name of the run within the log folder.')
log_parse.add_argument('--earlystop', type=bool, default=True,
                       help='Whether to use early stopping after the validation loss has not decreased for `patience` epochs.')
log_parse.add_argument('--patience', type=int, default=5,
                       help='Number of epochs to wait for a possible decrease in validation loss before early stopping.')

if __name__ == '__main__':
    parser = Trainer.add_argparse_args(parser)
    args = parser.parse_args()

    data_path = args.data_path
    datset_dict = {"HCC":"y_HCC.npz",
                    "MBL":"y_MBL.npz",
                    "Hemato":"y_Hemato.npz",
                    "Luo_Mouse":"y_Luo_Mouse.npz",#"Neuron-Mouse"
                    "Luo_Homo":"y_Luo_Homo.npz"#"Neuron-Homo"
                    }

    y = np.load(data_path + datset_dict[args.dataset])
    from datamodules import CpGGraphDataModule
    from graphcpg import CpGGraph

    datamodule = CpGGraphDataModule(y, segment_size=args.segment_size,
                                val_keys=args.val_keys, test_keys=args.test_keys,
                                batch_size=args.batch_size, n_workers=args.n_workers,
                                cell_nums=False)

    model = CpGGraph(latent_dim=args.latent_dim, adj_dropout=args.adj_dropout, cell_num=datamodule.cell_num,
                    segment_size=args.segment_size,
                    lr=args.lr, lr_decay_factor=args.lr_decay_factor, warmup_steps=args.warmup_steps)

    maxepochs = args.maxepochs

    args.log_folder += "/formal/"+str(maxepochs)+"/" + args.dataset
    if maxepochs < 1:
        limit_batch = maxepochs
        limit_batch_test = 1.0
        maxepochs = 1
    else:
        limit_batch = 1.0
        limit_batch_test = 1.0
        maxepochs = int(maxepochs)

    callbacks = [ModelCheckpoint(monitor='val_loss', mode='min',
                                # every_n_train_steps=save_steps,
                                save_top_k=1, save_last=True),
                TQDMProgressBar(refresh_rate=1)]

    if args.tensorboard:
        logger = TensorBoardLogger(args.log_folder, name=args.experiment_name)
        lr_monitor = LearningRateMonitor(logging_interval='step')
        callbacks += [lr_monitor]

    #wait for graph cards
    gpu_id = args.gpu
    time_start = time()
    trainer = Trainer.from_argparse_args(args, logger=logger, callbacks=callbacks, gpus=[gpu_id],
                                        max_epochs = maxepochs,
                                        limit_train_batches=limit_batch,
                                        limit_val_batches=limit_batch,
                                        limit_test_batches=limit_batch_test)
    datamodule.setup()
    time_process = time()
    process_timer = time_process - time_start
    trainer.fit(model, datamodule.train_dataloader(), datamodule.val_dataloader())
    time_train = time()
    train_timer = time_train - time_process
    # automatically loads the best weights
    trainer.test(model, datamodule.test_dataloader(), ckpt_path='best')
    time_test = time()
    test_timer = time_test - time_train

    writer = SummaryWriter(log_dir = logger.log_dir + '/table')
    print("Total preprocess time:"+str(np.round(process_timer/60, 2))+"mins")
    print("Total train time:"+str(np.round(train_timer/60, 2))+"mins")
    print("Total test time:"+str(np.round(test_timer/60, 2))+"mins")

    time_table = [["time"],
                  ["preprocess", str(np.round(process_timer/60, 2))],
                  ["train", str(np.round(train_timer/60, 2))],
                  ["test", str(np.round(test_timer/60, 2))]]
    time_table_header = ["time"]
    time_table_tabulate = tabulate(time_table, headers="firstrow", tablefmt='github')
    writer.add_text("GraphCpG Time (mins)", time_table_tabulate)
    writer.close()

    with open(logger.log_dir+'/commandline_args.txt', 'w') as f:
        json.dump(args.__dict__, f, indent=2)


import wx

#Setup of the application window
class AppWindow():
    app = wx.App()
    titlefnt=wx.Font(); titlefnt = titlefnt.Bold(); titlefnt.PointSize = 32
    main_wind=wx.Frame(None, title="VT Software", size=(1080,720))
    panel=wx.Panel(main_wind); panel.Size = (1080,720)

    def __init__(self):
        #titlefnt = wx.Font(); titlefnt = titlefnt.Bold(); titlefnt.PointSize = 32
        #main_wind = wx.Frame(None, title="VT Software", size=(1080,720))
        #panel = wx.Panel(main_wind); panel.Size = (1080,720)
        self.show_main_screen()
        self.create_menubar()
        self.main_wind.Show()
        self.app.MainLoop()

    def show_create_screen(self, x=None):
        self.panel.DestroyChildren()
        title_txt = wx.StaticText(self.panel, label="Create New Sound Profile", pos=(25,25))
        title_txt.SetFont(self.titlefnt)
        #inpt = wx.FileCtrl(panel, pos=(200,25))
        menubtn = wx.Button(self.panel, label="Back", pos=(25,600))
        menubtn.Bind(wx.EVT_BUTTON, self.show_main_screen)

    def show_load_screen(self, x=None):
        self.panel.DestroyChildren()
        title_txt = wx.StaticText(self.panel, label="Load Existing Sound Profile", pos=(25,25))
        title_txt.SetFont(self.titlefnt)
        menubtn = wx.Button(self.panel, label="Back", pos=(25,600))
        menubtn.Bind(wx.EVT_BUTTON, self.show_main_screen)

    def show_main_screen(self, x=None):
        self.panel.DestroyChildren()
        maintxt = wx.StaticText(self.panel, label="VoiceTrain v0.1", pos=(25,25)); maintxt.SetFont(self.titlefnt)
        loadbtn = wx.Button(self.panel, label="Use Existing Sound Profile", pos=(75,90))
        createbtn = wx.Button(self.panel, label="Make New Sound Profile", pos=(75,125))
        createbtn.Bind(wx.EVT_BUTTON, self.show_create_screen)
        #loadbtn.Bind(wx.EVT_BUTTON, mainclick("Load Existing"))

    def controls(cmd):
        if cmd=="Exit":
            self.main_wind.Close()
        elif cmd=="":
            print(" ")

    def create_menubar(self):
        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        savebtn = fileMenu.Append(-1,"&Save\tCtrl-S","Save Your Work")
        fileMenu.AppendSeparator()
        exitbtn = fileMenu.Append(-1,"&Exit","Exit Program")
        menubar.Append(fileMenu, "&File")
        window_menu = wx.Menu()
        main_menu_button = window_menu.Append(-1, "&Main Menu", "Go to the Startup Menu of the Program")
        load_menu_button = window_menu.Append(-1, "&Load Profile", "Load an existing sound profile")
        create_menu_button = window_menu.Append(-1, "&Create Profile", "Create a new sound profile")
        menubar.Append(window_menu, "&Windows")
        self.main_wind.SetMenuBar(menubar)

application = AppWindow()


def solve(strings : list[str]) -> list[int]:
    """
    :param strings: list[str]
    :return: list[int]
    """
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    res = []
    for i in strings:
        i = i.lower()
        temp = 0
        for j in range(len(i)):

            if alpha.index(i[j]) == j:
                temp += 1
        res.append(temp)
    return res

print(solve(["abode","ABc","xyzD"]))


# -*- coding:utf-8 -*-
import discord
import asyncio # 디스코드 모듈과, 보조 모듈인 asyncio를 불러옵니다.
import datetime
import os
import openpyxl

client = discord.Client() # discord.Client() 같은 긴 단어 대신 client를 사용하겠다는 선언입니다.

@client.event
async def on_ready(): # 봇이 준비가 되면 1회 실행되는 부분입니다.
    # 봇이 "반갑습니다"를 플레이 하게 됩니다.
    # 눈치 채셨을지 모르곘지만, discord.Status.online에서 online을 dnd로 바꾸면 "다른 용무 중", idle로 바꾸면 "자리 비움"으로 바뀝니다.
    await client.change_presence(status=discord.Status.online, activity=discord.Game("반갑습니다 :D"))
    print("I'm Ready!") # I'm Ready! 문구를 출력합니다.
    print(client.user.name) # 봇의 이름을 출력합니다.
    print(client.user.id) # 봇의 Discord 고유 ID를 출력합니다.

@client.event
async def on_message(message): # 메시지가 들어 올 때마다 가동되는 구문입니다.
    if(message.author.bot):
        return
    if 'http' in message.content and (message.channel.type is discord.ChannelType.private):
        await message.channel.send("링크는 보낼 수 없습니다")
        return
    if  (message.channel.type is discord.ChannelType.private): #and message.author.id!="700608102269059083":#제 봇 아이디
        file = openpyxl.load_workbook("cooltime.xlsx")
        sheet = file.active
        noww=datetime.datetime.now()
        h=noww.hour
        m=noww.minute
        s=noww.second
        time=int(h)*3600+int(m)*60+int(s)
        for i in range(1, 100):
            if str(sheet["A"+str(i)].value)==str(message.author.id):
                if(sheet["B"+str(i)].value != None):
                    if(int(sheet["B"+str(i)].value)>time-600):
                        print(message.author.name+"("+str(message.author.id)+") : "+message.content)
                        await message.channel.send(str(600-time+int(sheet["B"+str(i)].value))+"초 후에 문의 가능합니다.")#관리자에게 메세지가 가는 방식.
                        return
                else:
                    sheet["B"+str(i)].value=sheet["C"+str(i)].value
                    sheet["C"+str(i)].value=sheet["D"+str(i)].value
                    sheet["D"+str(i)].value=str(time)
                    file.save("cooltime.xlsx")
                    await message.channel.send('접수완료')
                    if not message.attachments:
                        print(message.author.name+"("+str(message.author.id)+") : "+message.content)
                        Channel_id=os.environ["CHANNEL_ID"]
                        channel = client.get_channel(int(Channel_id))
                        await channel.send(message.author.name+"("+str(message.author.id)+") : "+message.content)#관리자에게 메세지가 가는 방식.
                    else:
                        print(message.author.name+"("+str(message.author.id)+") : ")
                        Channel_id=os.environ["CHANNEL_ID"]
                        channel = client.get_channel(int(Channel_id))
                        await channel.send(message.author.name+" : ")
                        for i in range(len(message.attachments)):
                            print(message.attachments[i].url)
                            Channel_id=os.environ["CHANNEL_ID"]
                            channel = client.get_channel(int(Channel_id))
                            await channel.send(message.author.name+"("+str(message.author.id)+") : "+message.content)#관리자에게 메세지가 가는 방식.
                    return
        for j in range(1,100):
            if sheet["A"+str(j)].value==None:
                print("아이디넣었음")
                sheet["A"+str(j)].value=str(message.author.id)
                sheet["D"+str(j)].value=str(time)
                await message.channel.send('접수완료')
                if not message.attachments:
                    print(message.author.name+"("+str(message.author.id)+") : "+message.content)
                    Channel_id=os.environ["CHANNEL_ID"]
                    channel = client.get_channel(int(Channel_id))
                    await channel.send(message.author.name+"("+str(message.author.id)+") : "+message.content)#관리자에게 메세지가 가는 방식.
                    return
                else:
                    print(message.author.name+"("+str(message.author.id)+") : ")
                    Channel_id=os.environ["CHANNEL_ID"]
                    channel = client.get_channel(int(Channel_id))
                    await channel.send(message.author.name+"("+str(message.author.id)+") : ")
                    for i in range(len(message.attachments)):
                        print(message.attachments[i].url)
                        Channel_id=os.environ["CHANNEL_ID"]
                        channel = client.get_channel(int(Channel_id))
                        await channel.send(message.attachments[i].url)#관리자에게 메세지가 가는 방식.
                    return
    if message.content.startswith('!답장'):
        user = client.get_user(int(message.content[4:22]))
        await user.create_dm()
        await message.channel.send(str(user.name)+"에게 : "+str(message.content[23:]))
        channel = user.dm_channel
        await channel.send("답변 : "+str(message.content[23:]))
access_token=os.environ["BOT_TOKEN"]
client.run(access_token) # 아까 넣어놓은 토큰 가져다가 봇을 실행하라는 부분입니다. 이 코드 없으면 구문이 아무리 완벽해도 실행되지 않습니다.


from collections import deque
class Solution(object):
    def shortestPathBinaryMatrix(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m, n = len(grid), len(grid[1])
        if grid[0][0] != 0 or grid[m-1][n-1] != 0:
            return -1
        queue = deque([(0, 0, 1)])
        grid[0][0] = -1
        result = -1
        while queue:
            curr = queue.popleft()
            r, c = curr[0], curr[1]
            if r == m - 1 and c == n - 1:
                if result == -1:
                    result = curr[2]
                else:
                    result = min(result, curr[2])
            for i in [-1, 0, 1]:
                for j in [-1, 0, 1]:
                    if 0 <= r + i < m and 0 <= c + j < n and grid[r+i][c+j] == 0:
                        queue.append((r+i , c+j, curr[2]+1))
                        grid[r+i][c+j] = -1
        return result

Algorithm/Python/1000+/1091. Shortest Path in Binary Matrix.py