import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import numpy as np
import matplotlib.pyplot as plt
from vispy import app, visuals, scene
from matrixGridMap import *

def plot_girdMap(gridMap: matrixGridMap3D):
    """
    plot the grid map
    """
    vol = gridMap.get_data().astype(np.int16) * 100
    vol = vol.transpose((2,1,0))

    canvas = scene.SceneCanvas(keys='interactive', title='Grid Map 3D', show=True)
    view = canvas.central_widget.add_view()
    volume = scene.visuals.Volume(vol, clim=(0,200), parent=view.scene, method='mip')
    cam = scene.cameras.TurntableCamera(parent=view.scene, name='Turntable')
    view.camera = cam

    canvas.app.run()

def show_gridMap_with_bullet(gridMap: matrixGridMap3D, pclient):
    import pybullet as p
    import pybullet_data
    """
    Load obstacles into the pybullet simulation environment
    :param pclient: pybullet client
    :param obstacles: dict of obstacles, temporarily support:
        {type: "box", center(1x3 array), half_extend(1x3 array), yaw_rad, fixed(bool)}
        {type: "cylinder", center(1x3 array), radius, height, fixed(bool)}
        {type: "ball", center(1x3 array), radius, fixed(bool)}
        {type: "height_field", scale(1x3 array), grid_size(1x2 array), height_data(MxN)}(seperatly loaded)
    """
    if p.getNumBodies(physicsClientId=pclient) == 0:
        p.setAdditionalSearchPath(pybullet_data.getDataPath())
        p.loadURDF("plane.urdf", [0, 0, 0], physicsClientId=pclient)

    uid_list = []
    only_height_field = None
    obstacles = gridMap.get_obs_dict()
    for (_, param) in obstacles.items():
        if param['type'] == "box":
            direction_quat = p.getQuaternionFromEuler([0., 0., param['yaw_rad']])
            visualShapeId = p.createVisualShape(shapeType=p.GEOM_BOX,
                                                halfExtents=param['half_extend'],
                                                physicsClientId=pclient)
            collisionShapeId = p.createCollisionShape(shapeType=p.GEOM_BOX,
                                                halfExtents=param['half_extend'],
                                                physicsClientId=pclient)
            uid = p.createMultiBody(baseMass=0 if param['fixed'] else 1.,
                                baseCollisionShapeIndex=collisionShapeId,
                                baseVisualShapeIndex=visualShapeId,
                                basePosition=param['center'],
                                baseOrientation=direction_quat,
                                useMaximalCoordinates=True,
                                physicsClientId=pclient)
        elif param['type'] == "cylinder":
            visualShapeId = p.createVisualShape(shapeType=p.GEOM_CYLINDER,
                                                radius=param['radius'],
                                                length=param['height'],
                                                physicsClientId=pclient)
            collisionShapeId = p.createCollisionShape(shapeType=p.GEOM_CYLINDER,
                                                radius=param['radius'],
                                                height=param['height'],
                                                physicsClientId=pclient)
            uid = p.createMultiBody(baseMass=0 if param['fixed'] else 1.,
                                baseCollisionShapeIndex=collisionShapeId,
                                baseVisualShapeIndex=visualShapeId,
                                basePosition=param['center'],
                                useMaximalCoordinates=True,
                                physicsClientId=pclient)
        elif param['type'] == 'ball':
            visualShapeId = p.createVisualShape(shapeType=p.GEOM_SPHERE,
                                                radius=param['radius'],
                                                physicsClientId=pclient)
            collisionShapeId = p.createCollisionShape(shapeType=p.GEOM_SPHERE,
                                                radius=param['radius'],
                                                physicsClientId=pclient)
            uid = p.createMultiBody(baseMass=0 if param['fixed'] else 1.,
                                baseCollisionShapeIndex=collisionShapeId,
                                baseVisualShapeIndex=visualShapeId,
                                basePosition=param['center'],
                                useMaximalCoordinates=True,
                                physicsClientId=pclient)
        elif param['type'] == "height_field":
            field = param['height_field']
            data = field.get_height_data()
            if only_height_field is None:
                terrainShape = p.createCollisionShape(shapeType=p.GEOM_HEIGHTFIELD,
                                                    meshScale=param['scale'],
                                                    heightfieldTextureScaling=(data.shape[0]-1)/2,
                                                    heightfieldData=param['height_data'].flatten(order='F'),
                                                    numHeightfieldRows=data.shape[0],
                                                    numHeightfieldColumns=data.shape[1],
                                                    physicsClientId=pclient)
                only_height_field = terrainShape
            else:
                terrainShape = p.createCollisionShape(shapeType=p.GEOM_HEIGHTFIELD,
                                                    meshScale=param['scale'],
                                                    heightfieldTextureScaling=(data.shape[0]-1)/2,
                                                    heightfieldData=param['height_data'],
                                                    numHeightfieldRows=data.shape[0],
                                                    numHeightfieldColumns=data.shape[1],
                                                    replaceHeightfieldIndex=only_height_field,
                                                    physicsClientId=pclient)
                continue
            uid = p.createMultiBody(baseMass=0,
                                baseCollisionShapeIndex=terrainShape,
                                physicsClientId=pclient)
            pos_bias = [data.shape[0]*param['scale'][0] / 2,
                        data.shape[1]*param['scale'][1] / 2,
                        0]
            p.resetBasePositionAndOrientation(uid, pos_bias, [0,0,0,1], physicsClientId=pclient)
            p.changeVisualShape(uid, -1, rgbaColor=[1,1,1,1], physicsClientId=pclient)
        else:
            print("Warning: undefined obstacle type! Loading nothing!")
            uid = -1
        uid_list.append(uid)
    return uid_list

if __name__ == "__main__":
    import os
    import time
    from heightField import constructHeightFieldFromImg

    path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + '/pictures/test.png'
    field = constructHeightFieldFromImg(path, 3.0, [0,0], cell_size=0.03, data_shape=(60,70))
    obs_dict = {'obs1': {'type': 'height_field', 'height_field':field}}

    start_time = time.time()
    map = matrixGridMap3D(center_crd=[0,0,0], half_extend=[3,3,2], cell_size=0.05)
    cons_time = time.time()
    print('construction time: ', cons_time - start_time)
    map.add_obstacles(obs_dict=obs_dict)
    load_time = time.time()
    print('load time: ', load_time - cons_time)

    plot_girdMap(map)


import snowflake.connector
import re
import json
import os
import base64

if __name__ == "__main__":
    with open("config/snowflake.json") as f:
        credentialJson = json.load(f)

    testHost = credentialJson["test"]["url"]
    testUser = credentialJson["test"]["user"]
    testDatabase = credentialJson["test"]["database"]
    testSchema = credentialJson["test"]["schema"]
    testWarehouse = credentialJson["test"]["warehouse"]
    pk = credentialJson["test"]["private_key"]

    pk_decode = base64.b64decode(pk)

    reg = "[^\/]*snowflakecomputing"  # find the account name
    account = re.findall(reg, testHost)
    if len(account) != 1 or len(account[0]) < 20:
        print(
            "Format error in 'host' field at profile.json, expecting account.snowflakecomputing.com:443")

    snowflake_conn = snowflake.connector.connect(
            user=testUser,
            private_key=pk_decode,
            account=account[0][:-19],
            warehouse=testWarehouse,
            database=testDatabase,
            schema=testSchema
        )
    cwd = os.getcwd()
    sql = "get @DO_NOT_DELETE_KAFKA_PERF_TEST_DATA file://{}/data;".format(cwd)
    print(sql)
    snowflake_conn.cursor().execute(sql)


import aiohttp

def request_tracer(results_collector):
    """
    Provides request tracing to aiohttp client sessions.
    :param results_collector: a dict to which the tracing results will be added.
    :return: an aiohttp.TraceConfig object.
    :example:
    >>> import asyncio
    >>> import aiohttp
    >>> from aiohttp_trace import request_tracer
    >>>
    >>>
    >>> async def func():
    >>>     trace = {}
    >>>     async with aiohttp.ClientSession(trace_configs=[request_tracer(trace)]) as client:
    >>>         async with client.get('https://github.com') as response:
    >>>             print(trace)
    >>>
    >>> asyncio.get_event_loop().run_until_complete(func())
    {'dns_lookup_and_dial': 43.3, 'connect': 334.29, 'transfer': 148.48, 'total': 526.08, 'is_redirect': False}
    """

    async def on_request_start(session, context, params):
        context.on_request_start = session.loop.time()
        context.is_redirect = False

    async def on_connection_create_start(session, context, params):
        since_start = session.loop.time() - context.on_request_start
        context.on_connection_create_start = since_start

    async def on_request_redirect(session, context, params):
        since_start = session.loop.time() - context.on_request_start
        context.on_request_redirect = since_start
        context.is_redirect = True

    async def on_dns_resolvehost_start(session, context, params):
        since_start = session.loop.time() - context.on_request_start
        context.on_dns_resolvehost_start = since_start

    async def on_dns_resolvehost_end(session, context, params):
        since_start = session.loop.time() - context.on_request_start
        context.on_dns_resolvehost_end = since_start

    async def on_connection_create_end(session, context, params):
        since_start = session.loop.time() - context.on_request_start
        context.on_connection_create_end = since_start

    async def on_request_chunk_sent(session, context, params):
        since_start = session.loop.time() - context.on_request_start
        context.on_request_chunk_sent = since_start

    async def on_request_end(session, context, params):
        total = session.loop.time() - context.on_request_start
        context.on_request_end = total

        try:
            dns_lookup_and_dial = context.on_dns_resolvehost_end - context.on_dns_resolvehost_start
        except AttributeError:
            dns_lookup_and_dial = 0

        connect = context.on_connection_create_end - dns_lookup_and_dial
        transfer = total - context.on_connection_create_end
        is_redirect = context.is_redirect

        results_collector['dns_lookup_and_dial'] = round(dns_lookup_and_dial * 1000, 2)
        results_collector['connect'] = round(connect * 1000, 2)
        results_collector['transfer'] = round(transfer * 1000, 2)
        results_collector['total'] = round(total * 1000, 2)
        results_collector['is_redirect'] = is_redirect

    trace_config = aiohttp.TraceConfig()

    trace_config.on_request_start.append(on_request_start)
    trace_config.on_request_redirect.append(on_request_redirect)
    trace_config.on_dns_resolvehost_start.append(on_dns_resolvehost_start)
    trace_config.on_dns_resolvehost_end.append(on_dns_resolvehost_end)
    trace_config.on_connection_create_start.append(on_connection_create_start)
    trace_config.on_connection_create_end.append(on_connection_create_end)
    trace_config.on_request_end.append(on_request_end)
    trace_config.on_request_chunk_sent.append(on_request_chunk_sent)

    return trace_config


# coding: utf-8
from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap
from flask_paginate import Pagination, get_page_parameter
from flask_cors import CORS
import datetime
import pandas as pd
from info_api import module_api  # 附加模块
import sqlite3
import jieba
import re

app = Flask(__name__)
app.debug = True
app.config["JSON_AS_ASCII"] = False
bootstrap = Bootstrap(app)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

# 指定时区
BJT = datetime.timezone(datetime.timedelta(hours=+8), 'BJT')

# 从其他模块(.py)调用
app.register_blueprint(module_api)

@app.route('/')
def index():
    year = request.args.get('year')
    conn = sqlite3.connect('../KPIEnMicroMsg.db')
    cur = conn.cursor()

    now = datetime.datetime.now(BJT)
    ranking_timestamp = now - datetime.timedelta(days=365)
    max_year = ranking_timestamp.strftime("%Y")

    if year is None:
        year = max_year

    stop_year = (datetime.datetime.strptime(year, "%Y")).strftime("%Y")
    sql = "SELECT imgflag, conRemark, count( * ) AS counts,dense_RANK( ) OVER ( ORDER BY count( * ) DESC ) AS ranking " \
          " FROM kpimessage WHERE strftime('%%Y',date) == '%s' GROUP BY conRemark ORDER BY counts DESC" % (
                  '%s' % year)
    cursor = cur.execute(sql)

    exercise_data_list = cursor.fetchall()

    page = request.args.get(get_page_parameter(), type=int, default=1)
    res = exercise_data_list[(page - 1) * 100: page * 100]
    pagination = Pagination(page=page, total=len(exercise_data_list), per_page=100, css_framework='bootstrap4')

    return render_template('index.html', results=res, start_year=year,
                           stop_year=stop_year, max_year=max_year, pagination=pagination)

@app.route('/hapi')
def hapi():
    year = request.args.get('year')
    conn = sqlite3.connect('../KPIEnMicroMsg.db')
    cur = conn.cursor()

    now = datetime.datetime.now(BJT)
    ranking_timestamp = now - datetime.timedelta(days=365)
    max_year = ranking_timestamp.strftime("%Y")

    if year is None:
        year = max_year

    stop_year = (datetime.datetime.strptime(year, "%Y")).strftime("%Y")
    sql = "SELECT imgflag, conRemark, count( * ) AS counts, dense_RANK( ) OVER ( ORDER BY count( * ) DESC ) AS " \
          "ranking FROM kpimessage WHERE strftime('%%Y',date)== '%s' AND content LIKE '%s' GROUP BY conRemark ORDER " \
          "BY counts DESC" % (
              '%s' % year, '%哈哈哈%')
    cursor = cur.execute(sql)

    exercise_data_list = cursor.fetchall()

    page = request.args.get(get_page_parameter(), type=int, default=1)
    res = exercise_data_list[(page - 1) * 100: page * 100]
    pagination = Pagination(page=page, total=len(exercise_data_list), per_page=100, css_framework='bootstrap4')

    return render_template('hapi.html', results=res, start_year=year,
                           stop_year=stop_year, max_year=max_year, pagination=pagination)

@app.route('/userdata')
def userdata():
    user = request.args.get('user')
    type = request.args.get('type')

    # # 词云开始
    # def remove_stop_words(f):
    #     d = open("stopwords/cn_stopwords.txt", "r", encoding='utf-8')
    #     stop_words = {}.fromkeys(d.read().split("\n"))
    #     for stop_word in stop_words:
    #         f = f.replace(stop_word, '')
    #     return f
    #     d.close()
    #
    # # 生成词云
    # def create_word_cloud(f):
    #     # 设置本地的simhei字体文件位置
    #     FONT_PATH = os.environ.get("FONT_PATH", os.path.join(os.path.dirname(__file__), "simhei.ttf"))
    #     f = remove_stop_words(f)
    #     cut_text = " ".join(jieba.cut(f, cut_all=False, HMM=True))
    #     image = np.array(Image.open('mask.png'))
    #     wc = WordCloud(
    #         background_color="white",
    #         mask=image,
    #         font_path=FONT_PATH,
    #         max_words=200,
    #         max_font_size=150,
    #         prefer_horizontal=1,
    #         scale=4
    #     )
    #     wordcloud = wc.generate(cut_text)
    #     # 写词云图片
    #     wordcloud.to_file("static/wordcloud/" + user + ".jpg")
    #     # 显示词云文件
    #     plt.imshow(wordcloud)
    #     plt.axis("off")
    #
    # def get_content_from_weixin():
    #     # 创建数据库连接
    #     # 这里需要把 找到的weixin.db 放到根目录，具体方法之前文稿讲过
    #     conn = sqlite3.connect("../KPIEnMicroMsg.db")
    #     # 获取游标
    #     cur = conn.cursor()
    #     # 创建数据表
    #     # 查询当前数据库中的所有数据表
    #     sql = "SELECT name FROM sqlite_master WHERE type = 'table' and name like 'kpi%'"
    #     cur.execute(sql)
    #     tables = cur.fetchall()
    #     content = ''
    #     for table in tables:
    #         sql = "SELECT content FROM " + table[
    #             0] + " where strftime('%Y', date ) =='2020' and conRemark = '" + user + "' "
    #         cur.execute(sql)
    #         temp_result = cur.fetchall()
    #         for temp in temp_result:
    #             content = content + str(temp)
    #     # 提交事务
    #     conn.commit()
    #     # 关闭游标
    #     cur.close()
    #     # 关闭数据库连接
    #     conn.close()
    #     return content
    #
    # content = get_content_from_weixin()
    # # 去掉HTML标签里的内容
    # new_sentence = re.sub(r'[^\u4e00-\u9fa5]', ' ', content)
    # # 将聊天记录生成词云
    # create_word_cloud(new_sentence)
    # # 词云结束
    conn = sqlite3.connect('../KPIEnMicroMsg.db')
    cur = conn.cursor()
    now = datetime.datetime.now(BJT)
    ranking_timestamp = now - datetime.timedelta(days=365)
    max_year = ranking_timestamp.strftime("%Y")
    year = request.args.get('year')

    if user is None:
        year = max_year

    stop_year = (datetime.datetime.strptime(year, "%Y")).strftime("%Y")
    if user is None: user = ""

    if type == "hapi":
        title = '哈哈哈'
        sql = "SELECT strftime( '%%Y-%%m-%%d', date ) AS day, count( date ) AS count, imgflag FROM kpimessage WHERE conRemark = " \
              "'%s' AND strftime('%%Y',date)== '%s' AND content LIKE '%s' GROUP BY day" % ('%s' % user, year, '%哈哈哈%')
    elif type == "buca":
        title = '划水'
        sql = "SELECT strftime('%%Y-%%m-%%d', date ) AS day, count( date ) AS count, imgflag FROM kpimessage WHERE conRemark " \
              "='%s' AND strftime('%%Y', date ) =='%s' GROUP BY day" % ('%s' % user, year)

    cursor = cur.execute(sql)
    exercise_data_list = cursor.fetchall()
    res1 = pd.DataFrame(list(exercise_data_list), columns=['day', 'count', 'imgflag'])
    chartcal = str(res1['day'].values.tolist())
    chartcre = res1['count'].values.tolist()
    img = res1['imgflag'].values[1]
    result = ''

    page = request.args.get(get_page_parameter(), type=int, default=1)
    res = exercise_data_list[(page - 1) * 100: page * 100]
    pagination = Pagination(page=page, total=len(exercise_data_list), per_page=100, css_framework='bootstrap4')

    return render_template('userdata.html', stop_year=stop_year, results=res, pagination=pagination, user=user,
                           chartcal=chartcal,
                           chartcre=chartcre, img=img, title=title)

@app.route('/user')
def user():
    year = request.args.get('year')
    conn = sqlite3.connect('../KPIEnMicroMsg.db')
    cur = conn.cursor()

    now = datetime.datetime.now(BJT)
    ranking_timestamp = now - datetime.timedelta(days=365)
    max_year = ranking_timestamp.strftime("%Y")

    if year is None:
        year = max_year

    stop_year = (datetime.datetime.strptime(year, "%Y")).strftime("%Y")
    sql = "select imgflag,conRemark from kpimessage where strftime('%%Y',date)== '%s' GROUP BY conRemark ORDER BY conRemark desc" % (
            '%s' % year)
    cursor = cur.execute(sql)

    exercise_data_list = cursor.fetchall()

    page = request.args.get(get_page_parameter(), type=int, default=1)
    res = exercise_data_list[(page - 1) * 100: page * 100]
    pagination = Pagination(page=page, total=len(exercise_data_list), per_page=100, css_framework='bootstrap4')

    return render_template('user.html', results=res, start_year=year,
                           stop_year=stop_year, max_year=max_year, pagination=pagination)

@app.route('/personal')
def personal():
    user = request.args.get('user')
    year = request.args.get('year')
    conn = sqlite3.connect('../KPIEnMicroMsg.db')
    cur = conn.cursor()

    now = datetime.datetime.now(BJT)
    ranking_timestamp = now - datetime.timedelta(days=365)
    max_year = ranking_timestamp.strftime("%Y")

    if year is None:
        year = max_year

    stop_year = (datetime.datetime.strptime(year, "%Y")).strftime("%Y")
    sql = "SELECT count (content) as postimes, SUM(LENGTH( content ) - 1) as textcount FROM kpimessage WHERE " \
          "conRemark == '%s' and  strftime( '%%Y', date ) == '%s' AND LENGTH( content ) < 100 " % ('%s' % user, year)
    cursor = cur.execute(sql)
    bucacount = cursor.fetchall()
    res1 = pd.DataFrame(list(bucacount), columns=['postimes', 'textcount'])
    postimes = str(res1['postimes'].values[0])
    textcount = str(res1['textcount'].values[0])
    sql = "SELECT strftime( '%%H', date ) AS huatime, count( date ) AS count FROM kpimessage WHERE conRemark = '%s' " \
          "AND strftime( '%%Y', date ) == '%s' GROUP BY huatime ORDER BY count DESC LIMIT 1 " % ('%s' % user, year)
    cursor = cur.execute(sql)
    huatime = cursor.fetchall()
    res1 = pd.DataFrame(list(huatime), columns=['huatime', 'count'])
    huatime = str(res1['huatime'].values[0])
    huacount = str(res1['count'].values[0])

    def remove_stop_words(f):
        d = open("stopwords/cn_stopwords.txt", "r", encoding='utf-8')
        stop_words = {}.fromkeys(d.read().split("\n"))
        for stop_word in stop_words:
            f = f.replace(stop_word, '')
        return f
        d.close()

    sql = "SELECT content FROM kpimessage where conRemark = '%s' and strftime('%%Y', date ) =='%s'" % (
        '%s' % user, year)
    cur.execute(sql)
    temp_result = cur.fetchall()
    content = ''
    for temp in temp_result:
        content = content + str(temp)

    new_sentence = re.sub(r'[^\u4e00-\u9fa5]', ' ', content)
    f = remove_stop_words(new_sentence)
    words = jieba.lcut(f)  # 使用精确模式对文本进行分词
    counts = {}  # 通过键值对的形式存储词语及其出现的次数

    for word in words:
        if len(word) == 1 or len(word) > 2:  # 单个词语不计算在内
            continue
        else:
            counts[word] = counts.get(word, 0) + 1  # 遍历所有词语，每出现一次其对应的值加 1

    items = list(counts.items())  # 将键值对转换成列表
    items.sort(key=lambda x: x[1], reverse=True)  # 根据词语出现的次数进行从大到小排序
    for i in items:
        sql = "select content from kpimessage where conRemark = '%s' and strftime('%%Y', date ) =='%s' and content like '%%%s%%' AND LENGTH( content ) < 20 limit 4" % (
            '%s' % user, year, i[0])  # 获取关键词会出现空的情况所以出错
        cur.execute(sql)
        mentionedr = cur.fetchall()
        mentioned = i
        if len(mentionedr) == 0:
            i[+1]
            continue
        else:
            sql = "select content from kpimessage where conRemark = '%s' and strftime('%%Y', date ) =='%s' and content like '%%%s%%' AND LENGTH( content ) < 40 limit 4" % (
                '%s' % user, year, i[0])  # 获取关键词会出现空的情况所以出错
            cur.execute(sql)
            mentionedr = cur.fetchall()
            while len(mentionedr) < 4:
                mentionedr.append(' ')
            break

    sql = "WITH day AS ( SELECT strftime( '%%Y-%%m-%%d', date ) AS day FROM kpimessage WHERE conRemark = '%s' AND strftime( '%%Y', date ) == '%s' GROUP BY day ) SELECT count( * ) FROM day" % (
        '%s' % user, year)
    cur.execute(sql)
    Ndays = cur.fetchall()
    Ndays = pd.DataFrame(list(Ndays), columns=['Ndays'])
    Ndays = str(Ndays['Ndays'].values[0])

    sql = "SELECT strftime( '%%m月%%d日', date ) AS haday, count( date ) AS count FROM kpimessage WHERE conRemark = '%s' AND strftime( '%%Y', date ) == '%s' AND content LIKE '%%%s%%' GROUP BY haday ORDER BY count desc LIMIT 1" % (
        '%s' % user, year, '哈哈哈')
    cur.execute(sql)
    special_day = cur.fetchall()
    special_day = pd.DataFrame(list(special_day), columns=['haday', 'count'])
    special_date = str(special_day['haday'].values[0])

    sql = "SELECT strftime( '%%H点%%M分', date ) AS haday, content FROM kpimessage WHERE conRemark = '%s' AND strftime( '%%Y年%%m月%%d日', date ) == '%s年%s' AND content LIKE '%%%s%%' order by haday desc LIMIT 1" % (
        '%s' % user, stop_year, special_date, '哈哈哈')
    cur.execute(sql)
    latestend = cur.fetchall()
    latestend = pd.DataFrame(list(latestend), columns=['time', 'content'])

    sql = "WITH user AS( SELECT conRemark FROM kpimessage WHERE strftime( '%%Y', date ) =='%s' and conRemark != '%s' GROUP BY conRemark ) select count(*) as count from user" % (
        '%s' % stop_year, user)
    cur.execute(sql)
    partner = cur.fetchall()

    sqll = "SELECT conRemark FROM kpimessage WHERE strftime( '%%Y', date ) =='%s' and conRemark != '%s' GROUP BY conRemark" % (
        '%s' % stop_year, user)
    cur.execute(sqll)
    partnername = cur.fetchall()
    partnername = pd.DataFrame(list(partnername), columns=['name'])
    partnername = partnername['name'].values.tolist()
    content = ''
    for i in partnername:
        content = content + '' + str(i) + ' '

    conn.commit()
    # 关闭游标
    cur.close()
    # 关闭数据库连接
    conn.close()

    return render_template('personal.html', start_year=year, stop_year=stop_year, max_year=max_year, user=user,
                           postimes=postimes, textcount=textcount, huatime=huatime, huacount=huacount,
                           mentioned=mentioned, mentionedr=mentionedr, Ndays=Ndays, special_day=special_day,
                           latestend=latestend, partner=partner[0], partnername=content)

@app.errorhandler(404)
def page_not_found(error):
    return render_template('not_found.html'), 404

@app.errorhandler(500)
def internal_server_error(error):
    return render_template('internal_server_error.html'), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=11111)


from setuptools import setup, find_packages

VERSION = '1.0.0'
DESCRIPTION = 'OIG scanner'
LONG_DESCRIPTION = 'OIG scanner'

# Setting up
setup(
        name="oigscanner",
        version=VERSION,
        author="Alexandr Lagornii",
        author_email="alexandrlagornii@gmail.com",
        description=DESCRIPTION,
        long_description=LONG_DESCRIPTION,
        packages=find_packages(),
        install_requires=[],
        keywords=['python', 'oigscanner'],
        classifiers= [
            "Intended Audience :: Enterprise",
            "Programming Language :: Python :: 3",
            "Operating System :: Microsoft :: Windows",
        ]
)