from collections import namedtuple
import itertools

import torch
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import torch.nn.functional as F

import data_utils
import train_utils
from models import BinaryClassifier, LSTM, CNN
import part2_train_utils
import helpers

##############################################################################
# Settings
##############################################################################
CUDA = False

##############################################################################
# Load the dataset
##############################################################################
Data = namedtuple("Data", "corpus train dev test embeddings word_to_index")

data_utils.download_ask_ubuntu_dataset()
EMBEDDINGS, WORD_TO_INDEX = data_utils.load_part2_embeddings()
ASK_UBUNTU_CORPUS = data_utils.load_corpus(WORD_TO_INDEX)
ASK_UBUNTU_TRAIN_DATA = data_utils.load_train_data()
ASK_UBUNTU_DEV_DATA, ASK_UBUNTU_TEST_DATA = data_utils.load_eval_data()
ASK_UBUNTU_DATA = Data(ASK_UBUNTU_CORPUS, ASK_UBUNTU_TRAIN_DATA,\
                        ASK_UBUNTU_DEV_DATA, ASK_UBUNTU_TEST_DATA,\
                        EMBEDDINGS, WORD_TO_INDEX)

data_utils.download_android_dataset()
ANDROID_CORPUS = data_utils.load_android_corpus(WORD_TO_INDEX)
ANDROID_DEV_DATA, ANDROID_TEST_DATA = data_utils.load_android_eval_data()
ANDROID_DATA = Data(ANDROID_CORPUS, None,\
                      ANDROID_DEV_DATA, ANDROID_TEST_DATA,\
                      EMBEDDINGS, WORD_TO_INDEX)

##############################################################################
# Train and evaluate a baseline TFIDF model
##############################################################################
TOKENIZED_ANDROID_CORPUS = data_utils.load_tokenized_android_corpus()
TOKENIZED_ANDROID_CORPUS = [
    entry.title + entry.body for entry in TOKENIZED_ANDROID_CORPUS.values()
]
TFIDF_VECTORIZER = TfidfVectorizer()
TFIDF_VECTORS = TFIDF_VECTORIZER.fit_transform(TOKENIZED_ANDROID_CORPUS)
QUERY_TO_INDEX = dict(zip(ANDROID_DATA.corpus.keys(), range(len(ANDROID_DATA.corpus))))
AUC = helpers.evaluate_tfidf_auc(ANDROID_DATA.dev, TFIDF_VECTORS, QUERY_TO_INDEX)
print("AUC", AUC)
AUC = helpers.evaluate_tfidf_auc(ANDROID_DATA.test, TFIDF_VECTORS, QUERY_TO_INDEX)
print("AUC", AUC)

##############################################################################
# Train models by direct transfer and evaluate
##############################################################################
RESULTS = []
MARGINS = [0.2]
MAX_EPOCHS = 50
BATCH_SIZE = 32
FILTER_WIDTHS = [3]
POOL_METHOD = "average"
FEATURE_DIMS = [667]
DROPOUT_PS = [0.1]
NUM_HIDDEN_UNITS = [240]
LEARNING_RATES = [1E-3]
MODELS = []
LSTM_HYPERPARAMETERS = itertools.product(MARGINS, NUM_HIDDEN_UNITS, LEARNING_RATES)
for margin, num_hidden_units, learning_rate in LSTM_HYPERPARAMETERS:
    model = LSTM(EMBEDDINGS, num_hidden_units, POOL_METHOD, CUDA)
    criterion = helpers.MaxMarginLoss(margin)
    parameters = filter(lambda p: p.requires_grad, model.parameters())
    optimizer = torch.optim.Adam(parameters, lr=learning_rate)
    model, mrr = train_utils.train_model(model, optimizer, criterion, ASK_UBUNTU_DATA, \
                                    MAX_EPOCHS, BATCH_SIZE, CUDA, eval_data=ANDROID_DATA)
    torch.save(model.state_dict(), "./lstm_" +
                                    str(margin) + "_" +
                                    str(num_hidden_units) + "_" +
                                    str(learning_rate) + "_" +
                                    "auc=" + str(mrr))
    MODELS.append((mrr, margin, num_hidden_units, learning_rate))

##############################################################################
# Train models by adverserial domain adaptation and evaluate
##############################################################################
MAX_EPOCHS = 50
BATCH_SIZE = 32
MARGINS = [0.2]
FILTER_WIDTH = 2
POOL_METHOD = "average"
FEATURE_DIM = 240
DIS_NUM_HIDDEN_UNITS = [150, 200]
DIS_LEARNING_RATES = [-1E-3]
ENC_LEARNING_RATE = 1E-3
DIS_TRADE_OFF_RATES = [1E-7, 1E-8, 1E-9]

DIS_HYPERPARAMETERS = itertools.product(DIS_LEARNING_RATES, DIS_NUM_HIDDEN_UNITS, DIS_TRADE_OFF_RATES, MARGINS)

for dis_lr, dis_hidden_units, trade_off, margin in DIS_HYPERPARAMETERS:
    enc_model = LSTM(EMBEDDINGS, FEATURE_DIM, POOL_METHOD, CUDA)
    dis_model = BinaryClassifier(FEATURE_DIM, dis_hidden_units)
    model, auc = part2_train_utils.train_model(
        enc_model,
        dis_model,
        trade_off,
        ASK_UBUNTU_DATA,
        ANDROID_DATA,
        MAX_EPOCHS,
        BATCH_SIZE,
        ENC_LEARNING_RATE,
        dis_lr,
        margin,
        CUDA,
    )
    print("max auc", auc)
    torch.save(model.state_dict(), "./lstm_" +\
                                    str(margin) + "_" +\
                                    str(dis_hidden_units) + "_" +\
                                    str(trade_off) + "_" +\
                                    "auc=" + str(auc))


from django.urls import path
from . import views

app_name = 'cis'

urlpatterns = [
    path('cis/<status>/', views.CIListView.as_view(), name='ci_list'),
    path('ci/create/', views.CICreateView.as_view(), name='ci_create'),
    path('ci/upload/', views.ci_upload, name='ci_upload'),
    path('ci/<int:pk>', views.CIDetailView.as_view(), name='ci_detail'),
    path('ci/pack/send/', views.send_ci_pack, name='ci_pack_send'),
    path('places/', views.manage_client_places, name='manage_client_places'),
    path('place/create/', views.PlaceCreateView.as_view(), name='place_create'),
    path('place/<int:pk>', views.PlaceUpdateView.as_view(), name='place_update'),
    path('manufacturer/<int:pk>', views.ManufacturerDetailView.as_view(), name='manufacturer_detail'),
    path('appliances/', views.ApplianceListView.as_view(), name='appliance_list'),
    path('appliance/create/', views.ApplianceCreateView.as_view(), name='appliance_create'),
    path('appliance/<int:pk>', views.ApplianceUpdateView.as_view(), name='appliance_update'),
]


# 给你一个下标从 0 开始的整数数组 nums 。

# 现定义两个数字的 串联 是由这两个数值串联起来形成的新数字。

# 例如，15 和 49 的串联是 1549 。
# nums 的 串联值 最初等于 0 。执行下述操作直到 nums 变为空：

# 如果 nums 中存在不止一个数字，分别选中 nums 中的第一个元素和最后一个元素，将二者串联得到的值加到 nums 的 串联值 上，然后从 nums 中删除第一个和最后一个元素。
# 如果仅存在一个元素，则将该元素的值加到 nums 的串联值上，然后删除这个元素。
# 返回执行完所有操作后 nums 的串联值。

from typing import List

class Solution:
    def findTheArrayConcVal(self, nums: List[int]) -> int:

        ans = 0

        while(len(nums) > 0):
            if len(nums) == 1:
                ans += nums.pop()

            else:
                l = nums.pop(0)
                r = nums.pop()

                ans += int(str(l) + str(r))

        return ans

nums = [7,52,2,4]

a = Solution()
print(a.findTheArrayConcVal(nums))


from __future__ import annotations

__all__: list[str] = []

import argparse
import subprocess
import sys

import cmn

class _LintReturnCodes(cmn.ReturnCodes):
    """Return codes that can be received from pylint."""

    SUCCESS = 0
    # Error code 1 means a fatal error was hit
    ERROR = 2
    WARNING = 4
    ERROR_WARNING = 6
    REFACTOR = 8
    ERROR_REFACTOR = 10
    WARNING_REFACTOR = 12
    ERROR_WARNING_REFACTOR = 14
    CONVENTION = 16
    ERROR_CONVENTION = 18
    WARNING_CONVENTION = 20
    ERROR_WARNING_CONVENTION = 22
    REFACTOR_CONVENTION = 24
    ERROR_REFACTOR_CONVENTION = 26
    WARNING_REFACTOR_CONVENTION = 28
    ERROR_WARNING_REFACTOR_CONVENTION = 30
    USAGE_ERROR = 32

    COMMAND_NOT_FOUND = 200

def _run_lint(args: argparse.Namespace) -> int:
    """Runs pylint on python files in workspace.

    :param args: namespace object with args to run lint with.
    :return: return code from CLI.
    """
    rc = _LintReturnCodes.SUCCESS

    include_files = cmn.get_python_files(args.untracked_files)

    cmd = [cmn.which_python(), "-m", "pylint"] + list(include_files)

    try:
        subprocess.run(cmd, check=True)
    except FileNotFoundError as exc:
        if exc.errno is cmn.WinErrorCodes.FILE_NOT_FOUND.value:
            cmn.handle_missing_package_error(exc.filename)
            rc = _LintReturnCodes.COMMAND_NOT_FOUND
        else:
            raise
    except subprocess.CalledProcessError as exc:
        cmn.handle_cli_error(_LintReturnCodes, exc.returncode, exc.cmd, exc)
        rc = _LintReturnCodes.USAGE_ERROR

    return rc

def main() -> None:
    """Main function for pylint CLI. Parses and handles CLI input."""
    parser = argparse.ArgumentParser(description="Run pylint on given files.")
    parser.add_argument(
        "-u",
        "--untracked-files",
        action="store_true",
        default=False,
        help="run on files untracked by git",
    )

    args = parser.parse_args()

    rc = _run_lint(args)
    sys.exit(rc)

if __name__ == "__main__":
    main()


# -*-coding:utf-8-*-
from __future__ import absolute_import, unicode_literals
import tensorflow as tf
import numpy as np
import os

import matplotlib.pyplot as plt

from Utils.ReadAndDecode_Continous import read_and_decode_continous

val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/continous_data/test_continous.tfrecords'
# val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/continous_data/train_continous.tfrecords'
# val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/abij_test.tfrecords'
# val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/abij_train.tfrecords'
x_val, y_val = read_and_decode_continous(val_path)

test_batch = 1
min_after_dequeue_test = test_batch * 2

num_threads = 3
test_capacity = min_after_dequeue_test + num_threads * test_batch

# 使用shuffle_batch可以随机打乱输入
test_x_batch, test_y_batch = tf.train.shuffle_batch([x_val, y_val],
                                                    batch_size=test_batch, capacity=test_capacity,
                                                    min_after_dequeue=min_after_dequeue_test)

labels_type = 6
test_count = labels_type * 100
Test_iterations = test_count / test_batch

output_graph_def = tf.GraphDef()

pb_file_path = "../Model/gesture_cnn_lstm6.pb"
pb_lstm_file_path = "../Model/gesture_lstm.pb"

with open(pb_file_path, "rb") as f:
    output_graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(output_graph_def, name="")

# with open(pb_lstm_file_path, "rb") as f:
#     output_graph_def.ParseFromString(f.read())
#     _ = tf.import_graph_def(output_graph_def, name="")

# LABELS = ['A', 'B', 'C', 'F', 'G', 'H', 'I', 'J']
# LABELS = ['A', 'B',  'I', 'J']
label = [0, 1, 2, 3, 4, 5]

def batchtest():
    re_label = np.zeros(603, dtype=np.int64)
    pr_label = np.zeros(603, dtype=np.int64)
    ind = 0
    with tf.Session() as sess:
        init = tf.global_variables_initializer()

        sess.run(init)
        threads = tf.train.start_queue_runners(sess=sess)

        input_x = sess.graph.get_tensor_by_name("input:0")
        print(input_x)
        fc = sess.graph.get_tensor_by_name("fullconnection1:0")
        print(fc)

        output_cnn = sess.graph.get_tensor_by_name("output:0")
        print(output_cnn)

        input_x_lstm = sess.graph.get_tensor_by_name("input_lstm:0")
        print(input_x_lstm)

        softmax_lstm = sess.graph.get_tensor_by_name("softmax_lstm:0")
        print(softmax_lstm)
        output_lstm = sess.graph.get_tensor_by_name("output_lstm:0")
        print(output_lstm)

        for step_test in range(Test_iterations + 1):
            test_x, test_y = sess.run([test_x_batch, test_y_batch])
            if test_y == 6:
                continue
            if test_y == 7:
                continue

            x_ndarry_lstm = np.zeros(shape=(test_batch, 1024), dtype=np.float32)  # 定义一个长度为1024的array
            # if test_y==1:
            #     x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})
            #     out= sess.run(output_cnn, feed_dict={input_x: test_x[:, :, 0:550]})
            #     out_lstm=sess.run(output_lstm, feed_dict={input_x_lstm: x_ndarry_lstm})
            #     print out,out_lstm

            # tfrecords-->tensor(8,2200,2)-->4*tensor(8,550,2)-->cnn-->4*256-->lstm

            # train_x[0][1][1100][0] is the flag when write tfrecord
            if test_x[0][1][1100][0] == 1 * 6:  # 0.5s-->need train_x[:][1][0:550][0]

                x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})

            elif test_x[0][1][1100][0] == 2 * 6:  # 1s-->need train_x[:][1][0:1100][0]
                x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})
                x_ndarry_lstm[:, 256:512] = sess.run(fc, feed_dict={input_x: test_x[:, :, 550:1100]})

                # x_narray_cnn[0][:] = train_x[:][:][0:550]
                # x_narray_cnn[1][:] = train_x[:][:][550:1100]

            else:  # 2s-->need train_x[:][1][0:2200][0]
                x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})
                x_ndarry_lstm[:, 256:512] = sess.run(fc, feed_dict={input_x: test_x[:, :, 550:1100]})
                x_ndarry_lstm[:, 512:768] = sess.run(fc, feed_dict={input_x: test_x[:, :, 1100:1650]})
                x_ndarry_lstm[:, 768:1024] = sess.run(fc, feed_dict={input_x: test_x[:, :, 1650:2200]})
                # x_narray_cnn[0][:] = train_x[:][:][0:550]
                # x_narray_cnn[1][:] = train_x[:][:][550:1100]
                # x_narray_cnn[2][:] = train_x[:][:][1100:1650]
                # x_narray_cnn[3][:] = train_x[:][:][1650:2200]

            # print 0
            prediction_labels = sess.run(output_lstm, feed_dict={input_x_lstm: x_ndarry_lstm})
            print(str(step_test))
            print("real_label:", test_y)

            re_label[ind] = test_y

            # prediction_labels = np.argmax(out_softmax, axis=1)
            pr_label[ind] = prediction_labels
            ind += 1
            print("predict_label:", prediction_labels)
            print('')

    np.savetxt('../Data/re_label_lstmtrain_addlstm6.txt', re_label)
    np.savetxt('../Data/pr_label_lstmtrain_addlstm6.txt', pr_label)

if __name__ == '__main__':
    # singletest_data_pc("/home/dmrf/test_gesture/JS")
    # ReadDataFromTxt("/home/dmrf/下载/demodata/0_push left_1524492872166_1")
    batchtest()


numbers = [1, 2, 5, 7, 89, 90, 10, 20]

evens = []
for n in numbers:
    if n % 2 == 0:
        evens.append(n * n)

# list comprehension
evens = [
    n * n  # add value
    for n in numbers  # set to draw from
    if n % 2 == 0  # test for inclusion
]

print(evens)

results = [
    (1, 2, 70.1),
    (2, 2, 80.0),
    (4, 2, 20.0),
    (-4, 5, 100.0),
]

make_square = lambda n : n * n
# m = max(make_square(r[2]) for r in results)
m = max(r[2] for r in results)
print(m)

# Generator expression
evens = (
    n * n  # add value
    for n in numbers  # set to draw from
    if n % 2 == 0  # test for inclusion
)

for n in evens:
    print(n)


# ['基金编号', '购买成本', '基金名']
fundList = [
    ['160212', '3.6730', ' 国泰估值优势混合(LOF)'],
    ['001230', '1.2350', ' 鹏华医药科技股票']
]
# 发送基金日报的邮箱smtp服务器地址
senderIMAP = 'smtp.126.com'
# 发送基金日报的邮箱地址
senderEmailAddress = 'xxxxxxx@126.com'
# 发送基金日报的邮箱的smtp授权码
senderAuthCode = 'SNRRQHKFKEUNNSFT'
# 邮件主题
subject = '基金日报'
# 接收基金日报的邮箱地址
receiverEmailAddress = "xxxxxxxxxxxxxx@qq.com"


import subprocess
import os
import shutil
import pytest

TEMP_DIRECTORY = os.path.join(os.path.dirname(__file__), '..', 'tmp')
TEMP_HEADER = os.path.join(TEMP_DIRECTORY, 'header.h')
TEMP_SOURCE = os.path.join(TEMP_DIRECTORY, 'source.c')

def set_up():
    os.mkdir(TEMP_DIRECTORY)

def tear_down():
    shutil.rmtree(TEMP_DIRECTORY)

@pytest.fixture(autouse=True)
def run_around_tests():
    set_up()
    yield
    tear_down()

def read_file_content(filepath: str) -> str:
    with open(filepath, 'r') as file:
        return file.read()

def test_integration():
    # given:
    resource_dir = os.path.join(os.path.dirname(__file__), 'resource')
    input_path = os.path.join(resource_dir, 'example_header.h')
    expected_header = os.path.join(resource_dir, 'example_mock.h')
    expected_source = os.path.join(resource_dir, 'example_mock.c')

    # when:
    subprocess.run([
        'python', '-m', 'c_mock_generator.generate_mock',
        '-i', input_path,
        '-oh', TEMP_HEADER,
        '-oc', TEMP_SOURCE], check=True)

    # then:
    assert os.path.isfile(TEMP_HEADER)
    assert os.path.isfile(TEMP_SOURCE)

    assert read_file_content(TEMP_HEADER) == read_file_content(expected_header)
    assert read_file_content(TEMP_SOURCE) == read_file_content(expected_source)


#coding:utf-8
import sys
sys.path.insert(0, "./")
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
from flask import Flask
from flask import render_template, redirect, url_for
from flask import request, session, json
from flask import jsonify
from keywords.keywordExtract import getKeywords
from parser.analysis_doc import parser_doc, basicInfoExtract
from conflict.conflict_detect import Conflict
from retrieval.infoRetrieval import find_policy
from association.asso_analyze import Association

app = Flask(__name__)
app.config["SECRET_KEY"] = "123456"

conflict = Conflict()
asso = Association()

@app.route('/')
def hello_world():
    return '欢迎来到政策关联分析系统算法后台！！！'

@app.route('/dataProcess', methods=["POST", "GET"])
def dataProcess():
    '''
    对输入到数据库中的政策进行数据处理，进行信息提取操作。
    :return:
    '''
    if request.method == 'POST':
        datax = request.form.get('text',"")
        name = request.form.get("name", "")
        if datax:
            '''
            添加数据处理操作
            '''
            try:
                results = basicInfoExtract(datax, source_name=name)
                return jsonify({"error_code":0, "reason":"", "data":results})
            except:
                return jsonify({"error_code":3, "reason":"输入数据错误，无法进行解析", "data":""})
        else:
            return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
    else:
        return jsonify({"error_code":2, "reason":"请求方式错误，应使用post请求", "data":""})

@app.route("/keywords", methods=["POST","GET"])
def keywords():
    '''
    关键词提取
    :return:
    '''
    if request.method == 'POST':
        datax = request.form.get('text',"")
        number = int(request.form.get('number', 3))
        if datax:
            '''
            添加数据处理操作
            '''
            keyword = getKeywords(datax, num= number, use_value=False)
            results = {
                "keywords":keyword,#关键词
            }
            return jsonify({"error_code":0, "reason":"", "data":results})
        else:
            return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
    else:
        return jsonify({"error_code":2, "reason":"请求方式错误，应使用post请求", "data":""})

@app.route("/dataAnalyze", methods=["POST","GET"])
def dataAnalyze():
    '''
    政策文本结构化解析
    :return:
    '''
    if request.method == 'POST':
        datax = request.form.get('text',"")
        name = request.form.get('name', "")
        if datax:
            '''
            添加数据处理操作
            '''
            try:
                results = parser_doc(datax)
                return jsonify({"error_code":0, "reason":"", "data":results})
            except:
                return jsonify({"error_code": 3, "reason": "输入数据错误，无法进行解析", "data": ""})
        else:
            return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
    else:
        return jsonify({"error_code":2, "reason":"请求方式错误，应使用post请求", "data":""})

@app.route("/conflictDetection", methods=["POST", "GET"])
def conflictDetection():
    '''
    政策文本冲突检测
    :return:
    '''
    if request.method == 'POST':
        # datax = request.get_data()
        datax = request.form.get('policy',"")
        test_policy = request.form.get('test_policy', "")
        if datax and test_policy:
            '''
            添加数据处理操作
            '''
            try:
                datax = json.loads(datax)
                print("conflict input: %s"%(datax))
                results = conflict.conflict(datax, target_sent=test_policy)
            # results = {
            #     "result":"存在时间类型的冲突",
            #     "sentence":"到2020年，实现全面建设中国物联网体系平台。"
            # }
                return jsonify({"error_code":0, "reason":"", "data":results})
            except:
                return jsonify({"error_code": 3, "reason": "输入数据错误，无法进行解析", "data": ""})
        else:
            return jsonify({"error_code": 1, "reason": "没有输入政策数据或者是待检测文本", "data": ""})
    else:
        return jsonify({"error_code":2, "reason":"请求方式错误，应使用post请求", "data":""})

@app.route("/assoAnalyze", methods=["POST", "GET"])
def assoAnalyze():
    '''
    两个政策关联分析
    :return:
    '''
    if request.method == 'POST':
        policy1 = request.form.get('policy1', "")
        policy2 = request.form.get('policy2', "")
        if policy1 and policy2:
            '''
            添加数据处理操作
            '''
            try:
                policy1 = json.loads(policy1)
                policy2 = json.loads(policy2)
                results = asso.analyzeAll(policy1, policy2)
            # results = {
            #     "result":"对于政策A来说，政策B是起到理论指导作用",
            #     "policy1":{
            #         "1":["句子", "理论指导"],
            #         "2":["句子", "理论指导"],
            #
            #      },#第一个政策每句话的分析
            #     "policy2":{
            #         "1":["句子", "理论指导"],
            #         "2":["句子", "理论指导"],
            #      }#第二个政策每句话的分析
            # }
                return jsonify({"error_code":0, "reason":"", "data": results})
            except:
                return jsonify({"error_code": 3, "reason": "输入数据错误，无法进行解析", "data": ""})
        else:
            return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
    else:
        return jsonify({"error_code":2, "reason":"请求方式错误，应使用post请求", "data":""})

@app.route("/assoSingleAnalyze", methods=["POST", "GET"])
def assoSingleAnalyze():
    '''
    两个政策关联分析
    :return:
    '''
    if request.method == 'POST':
        policy1 = request.form.get('policy1',"")
        policy2 = request.form.get('policy2', "")
        sentence = request.form.get('sentence', "")
        id = request.form.get('id', None)
        if policy1 and policy2 and sentence and id is not None:
            try:
                id = int(id)
                '''
                添加数据处理操作
                '''
                policy1 = json.loads(policy1)
                policy2 = json.loads(policy2)
                results = asso.assoSingleAnalyze(policy1, policy2, sentence, id)
                # results = {
                #     "policy":{
                #         "1":["句子", "相似"],
                #         "2":["句子", "不相似"],
                #     }
                # }
                return jsonify({"error_code":0, "reason":"", "data":results})
            except:
                return jsonify({"error_code": 3, "reason": "输入数据错误，无法进行解析", "data": ""})
        else:
            return jsonify({"error_code": 1, "reason": "没有输入政策数据或者输入信息不完整", "data": ""})
    else:
        return jsonify({"error_code":2, "reason":"请求方式错误，应使用post请求", "data":""})

@app.route("/policyFind", methods=["POST", "GET"])
def policyFind():
    '''
    政策查找
    :return:
    '''
    if request.method == 'POST':
        policy1 = request.form.get('policy',"")
        policy_lis = request.form.get('policy_lis', "")
        number = int(request.form.get('number', 10))

        if policy1 and policy_lis and number :
            '''
            添加数据处理操作
            '''
            try:
                print(policy_lis)
                if not isinstance(policy_lis, list):
                    policy_lis = policy_lis.split("#")
                res = find_policy(policy1, policy_lis, int(number))
                print(res)
                results = {
                    "result":"#".join(res)#"大数据#互联网#人工智能#物联网"
                }
                return jsonify({"error_code":0, "reason":"", "data":results})
            except:
                return jsonify({"error_code": 3, "reason": "输入数据错误，无法进行解析", "data": ""})
        else:
            return jsonify({"error_code": 1, "reason": "没有输入政策数据或者输入信息不完整", "data": ""})
    else:
        return jsonify({"error_code":2, "reason":"请求方式错误，应使用post请求", "data":""})

if __name__ == '__main__':
    app.debug = True
    app.run(host="0.0.0.0", port = 5005, debug=True)


import pandas as pd
import os
import sys

file = sys.argv[1]

names = pd.read_csv("classroom.csv").Name

for name in names:
    os.system("git -C repositories/{} pull".format(name))
    os.system("cp ../quizzes/{}.py repositories/{}".format(file, name))
    os.system("git -C repositories/{} add {}.py".format(name, file))
    os.system('git -C repositories/{} commit {}.py -m "Quiz"'.format(name, file))
    os.system("git -C repositories/{} push".format(name))


class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.account_balance = 0
    def make_deposit(self, amount):	# takes an argument that is the amount of the deposit
        self.account_balance += amount	# the specific user's account increases by the amount of the value received
    def make_withdrawal(self, amount):
        self.account_balance -= amount
    def display_user_balance(self):
        print(f"User: {self.name}, Balance: ${self.account_balance}")
    def transfer_money(self, other_user, amount):
        self.account_balance -= amount
        other_user.account_balance += amount

justin = User("Justin","thisjustin.com")
chris = User("Christian","notsochristian.com")
brayan = User("Brayan","wtfudoin.com")

justin.make_deposit(100)
justin.make_deposit(100)
justin.make_deposit(100)
justin.make_withdrawal(130)
justin.display_user_balance()

chris.make_deposit(150)
chris.make_deposit(150)
chris.make_withdrawal(50)
chris.make_withdrawal(50)
chris.display_user_balance()

brayan.make_deposit(300)
brayan.make_withdrawal(75)
brayan.make_withdrawal(75)
brayan.make_withdrawal(75)
brayan.display_user_balance()

justin.transfer_money(brayan,200)
justin.display_user_balance()
brayan.display_user_balance()


import re
from typing import NamedTuple, Optional

from magma.magmad.check import subprocess_workflow

class LscpuCommandParams(NamedTuple):
    pass

class LscpuCommandResult(NamedTuple):
    error: Optional[str]
    core_count: Optional[int]
    threads_per_core: Optional[int]
    architecture: Optional[str]
    model_name: Optional[str]

def get_cpu_info() -> LscpuCommandResult:
    """
    Execute lscpu command via subprocess. Blocks while waiting for output.
    """
    return list(
        subprocess_workflow.exec_and_parse_subprocesses(
            [LscpuCommandParams()],
            _get_lscpu_command_args_list,
            parse_lscpu_output,
        ),
    )[0]

def _get_lscpu_command_args_list(_):
    return ['lscpu']

def parse_lscpu_output(stdout, stderr, _):
    """
    Parse stdout output from a lscpu command.
    """

    def _create_error_result(err_msg):
        return LscpuCommandResult(
            error=err_msg, core_count=None,
            threads_per_core=None, architecture=None,
            model_name=None,
        )
    if stderr:
        return _create_error_result(stderr)

    stdout_decoded = stdout.decode()
    try:
        cores_per_socket = int(
            re.search(
                r'Core\(s\) per socket:\s*(.*)\n',
                str(stdout_decoded),
            ).group(1),
        )
        num_sockets = int(
            re.search(
                r'Socket\(s\):\s*(.*)\n',
                str(stdout_decoded),
            ).group(1),
        )
        threads_per_core = int(
            re.search(
                r'Thread\(s\) per core:\s*(.*)\n',
                str(stdout_decoded),
            ).group(1),
        )
        architecture = re.search(
            r'Architecture:\s*(.*)\n',
            str(stdout_decoded),
        ).group(1)
        model_name = re.search(
            r'Model name:\s*(.*)\n',
            str(stdout_decoded),
        ).group(1)
        return LscpuCommandResult(
            error=None,
            core_count=cores_per_socket * num_sockets,
            threads_per_core=threads_per_core,
            architecture=architecture,
            model_name=model_name,
        )
    except (AttributeError, IndexError, ValueError) as e:
        return _create_error_result(
            'Parsing failed: %s\n%s' % (e, stdout_decoded),
        )


# Sets: unordered, mutable, no duplicates

# initialize 01
movies = {"50 shades of grey", "365", "The dictator", "Borat"}
# print(movies)

# initialize 02
web_series = set(["Suits", "Lucifer", "Dark", "Friends"])
# print(web_series)

# empty
# web_series = set()
# print(type(web_series))

# string initialize
hello_set = set("Hello")
# print(hello_set)

# insert value
web_series.add("The 100")
# web_series.add("Friend")
# print(web_series)

# delete value
# web_series.remove("Darkk")

# web_series.discard("Dark")

# clear all values
# web_series.clear()
# print(web_series)

web_series = movies.copy()

movies.add("Ready player one")

# print(web_series)

# union
gangs_of_wasseypur = {"Pankaj T", "Rajkumar R", "Nawazuddin S", "Huma Q"}
mirzapur = {"Pankaj T", "Ali Fazal", "Divyenndu", "Huma Q"}

# anurag_cast = gangs_of_wasseypur.union(mirzapur)

# print(anurag_cast)

# # intersection
# anurag_cast = gangs_of_wasseypur.intersection(mirzapur)
# print(anurag_cast)

# difference
anurag_cast = gangs_of_wasseypur.difference(mirzapur)
# print(anurag_cast)

# gangs_of_wasseypur = ["Pankaj T", "Rajkumar R", "Nawazuddin S", "Huma Q"]
# mirzapur = ["Pankaj T", "Ali Fazal", "Divyenndu", "Huma Q"]
# # anurag_cast = list()

# output = ["Rajkumar R", "Nawazuddin S", "Ali Fazal", "Divyenndu"]

# for cast in gangs_of_wasseypur:
#     if cast not in mirzapur:
#         anurag_cast.append(cast)

# anurag_cast = [cast for cast in gangs_of_wasseypur if cast not in mirzapur]

# print(anurag_cast)

# symmetric difference
anurag_cast = gangs_of_wasseypur.symmetric_difference(mirzapur)
# print(anurag_cast)

# update
web_series.update(gangs_of_wasseypur)
# print(web_series)

# intersection update
# mirzapur.intersection_update(gangs_of_wasseypur)
# print(mirzapur)

# difference update
# mirzapur.difference_update(gangs_of_wasseypur)
# print(mirzapur)

# symmetric difference update
# mirzapur.symmetric_difference_update(gangs_of_wasseypur)
# print(mirzapur)

# is subset
animated_movies = {"Big Hero 6", "Kung Fu Panda",
                   "Tangled", "Coco", "The Good Dinosaur"}

disney_movies = {"Tangled", "Coco"}

print(disney_movies.issubset(animated_movies))

# is superset
print(animated_movies.issuperset(disney_movies))

# is disjoint
print(animated_movies.isdisjoint(disney_movies))

# frozenset

numbers = frozenset({"a", "b"})
print(numbers)


class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        mapp = defaultdict(int)
        heap = []
        ans = []
        for word in words:
            mapp[word] -= 1

        for key,val in mapp.items():
            heappush(heap,(val,key))

        for _ in range(k):
            temp = heappop(heap)
            ans.append(temp[1])

        return ans


import workAssyncFile
from sora.prediction import prediction
from sora.prediction.occmap import plot_occ_map as occmap
import json
import datetime
import restApi
import os

def __clearName(name):
    name = "".join(x for x in name if x.isalnum() or x==' ' or x=='-' or x=='_')
    name = name.replace(' ', '_')
    return name

def processRequest(data, output):
    outputFile = generateMap(data,output, False)
    f = open (outputFile, "rb")
    content = f.read()
    return content

def processFile(input, output, fileName):
    f = open (os.path.join(input,fileName), "r")
    data = json.loads(f.read())
    generateMap(data, output, True)

def generateMap(data, output, forced=False):
    if 'body' in data:
        return generateMapWithIternet(data, output, forced)
    else:
        return generateMapWithoutIternet(data, output, forced)

def generateMapWithIternet(data, output, forced=False):
    body = data['body']
    strDate = data['date']
    strTime = data['time']
    fileName = __clearName(body+" "+strDate.replace("-","")+" "+strTime.replace(":",""))
    outputFile = os.path.join(output,fileName+".jpg")
    if forced or not os.path.exists(outputFile):
        v = (strDate+'-'+strTime).replace(":","-").split('-')
        dtRef = datetime.datetime(int(v[0]), int(v[1]), int(v[2]), int(v[3]), int(v[4]), int(v[5]))
        time0 = dtRef-datetime.timedelta(hours=4, minutes=0) #fuso 3
        time1 = time0+datetime.timedelta(hours=2, minutes=0)
        dtRef = dtRef - datetime.timedelta(hours=3, minutes=0)

        pred = prediction(body=body, time_beg=time0, time_end=time1, step=10, divs=1, verbose=False)
        for p in pred:
            p.plot_occ_map(nameimg=fileName, path=output, fmt='jpg')

    return outputFile

def generateMapWithoutIternet(data, output, forced=False):
    name = data["name"]
    radius = data["radius"]
    coord = data["coord"]
    time = data["time"]
    ca = data["ca"]
    pa = data["pa"]
    vel = data["vel"]
    dist = data["dist"]
    mag = data["mag"]
    longi = data["longi"]
    v = time.split("T")
    strDate = v[0]
    if '.' in v[1]:
        v[1] = v[1].split('.')[0]
    strTime = v[1]
    fileName = __clearName(name+" "+strDate.replace("-","")+" "+strTime.replace(":",""))
    outputFile = os.path.join(output,fileName+".jpg")
    if forced or not os.path.exists(outputFile):
        occmap(name, radius, coord, time, ca, pa, vel, dist, mag=mag, longi=longi, dpi=50,  nameimg=fileName, path=output, fmt='jpg')

    return outputFile

if __name__ == '__main__':
    waf = workAssyncFile.WorkAssyncFile(os.getenv('INPUT_PATH', '~/media/input'),os.getenv('OUTPUT_PATH', '~/media/output'))
    waf.setProcessFile(processFile)
    waf.start()

    api = restApi.RespApi(port=os.getenv('PORT', 8000), cachePath=os.getenv('CACHE_PATH', '~/media/output'))
    api.setProcessReponse(processRequest)
    api.start()


import time

h = input('Enter hex: ').lstrip('#')
RGB = tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
r, g, b = RGB

Ri = (r / 255)
Gi = (g / 255)
Bi = (b / 255)
print("{:0.2f}, {:0.2f}, {:0.2f}".format(Ri, Gi, Bi))
time.sleep(10)
exit()


# -*- coding: utf-8 -*-

from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QTabWidget
from .movies_view import MoviesTab
from .games_view import GamesTab
from .music_view import MusicTab

class Window(QMainWindow):
    """Main Window."""

    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        self.setWindowTitle("Media Library")
        self.resize(720, 360)
        self.table_widget = MyTableWidget(self)
        self.setCentralWidget(self.table_widget)

class MyTableWidget(QWidget):
    """Container for all the tabs."""

    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        # Initialize tabs
        self.tabs = QTabWidget()
        self.moviesTab = MoviesTab(self)
        self.gamesTab = GamesTab(self)
        self.musicTab = MusicTab(self)

        # Add tabs for each media type
        self.tabs.addTab(self.moviesTab, "Movies")
        self.tabs.addTab(self.gamesTab, "Games")
        self.tabs.addTab(self.musicTab, "Music")

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)


"""
Created on Thu Dec 10 22:51:52 2020

@author: yzaghir

Image Arthmeric Opeations Add -
We can add two images with the OpenCV function , cv.add()
-Resize the two images and make sur they are exactly the same size before adding

"""

# import cv library
import cv2 as cv
#import numpy as np

# read image from computer
img1 = cv.imread("images/abhi2.jpg")
img2 = cv.imread("images/flower1.jpg")

#macke sur both images are same size before adding
# pickup matrix of number from image
cropped_image1 = img1[60:200 , 50:200]
cropped_image2 = img2[60:200 , 50:200]

cv.imshow("cropped 1" , cropped_image1)
cv.imshow("cropped 2" , cropped_image2)

# adding the images
added_image = cv.add(cropped_image1 , cropped_image2)
cv.imshow("Added Image" , added_image)

# adding the images
subtracted_image = cv.subtract(cropped_image1 , cropped_image2)
cv.imshow("Subtracted Image" , subtracted_image)


import scipy as sci
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
import scipy.integrate

#Definitionen
G=6.67408e-11
m_nd=1.989e+30 #Masse der Sonne
r_nd=5.326e+12
v_nd=30000
t_nd=79.91*365*24*3600*0.51
K1=G*t_nd*m_nd/(r_nd**2*v_nd)
K2=v_nd*t_nd/r_nd

#Definition der Massen
m1=1.1 #Alpha Centauri A
m2=0.907 #Alpha Centauri B
m3=1.0 #Dritter Stern
#Definition der Anfangs-Positionen
r1=np.array([-0.5,0,0], dtype="float64")
r2=np.array([0.5,0,0], dtype="float64")
r3=np.array([0,1,0], dtype="float64")

#Definition der Anfangs-Geschwindigkeiten
v1=np.array([0.01,0.01,0], dtype="float")
v2=np.array([-0.05,0,-0.1], dtype="float64")
v3=np.array([0,-0.01,0], dtype="float64")

#Updaten der COM Formeln
r_com=(m1*r1+m2*r2+m3*r3)/(m1+m2+m3)
v_com=(m1*v1+m2*v2+m3*v3)/(m1+m2+m3)

#Bewegungsgleichungen
def ThreeBodyEquations(w,t,G,m1,m2,m3):
    r1=w[:3]
    r2=w[3:6]
    r3=w[6:9]
    v1=w[9:12]
    v2=w[12:15]
    v3=w[15:18]
    r12=sci.linalg.norm(r2-r1)
    r13=sci.linalg.norm(r3-r1)
    r23=sci.linalg.norm(r3-r2)

    dv1bydt=K1*m2*(r2-r1)/r12**3+K1*m3*(r3-r1)/r13**3
    dv2bydt=K1*m1*(r1-r2)/r12**3+K1*m3*(r3-r2)/r23**3
    dv3bydt=K1*m1*(r1-r3)/r13**3+K1*m2*(r2-r3)/r23**3
    dr1bydt=K2*v1
    dr2bydt=K2*v2
    dr3bydt=K2*v3
    r12_derivs=np.concatenate((dr1bydt,dr2bydt))
    r_derivs=np.concatenate((r12_derivs,dr3bydt))
    v12_derivs=np.concatenate((dv1bydt,dv2bydt))
    v_derivs=np.concatenate((v12_derivs,dv3bydt))
    derivs=np.concatenate((r_derivs,v_derivs))
    return derivs

init_params=np.array([r1,r2,r3,v1,v2,v3])
init_params=init_params.flatten() #Erstellen eines 1D Array
time_span=np.linspace(0,20,500) #20 Perioden und 500 Punkte

#Integrieren der Funktion
three_body_sol=sci.integrate.odeint(ThreeBodyEquations,init_params,time_span,args=(G,m1,m2,m3))

r1_sol=three_body_sol[:,:3]
r2_sol=three_body_sol[:,3:6]
r3_sol=three_body_sol[:,6:9]

#Erstellen der Figur
fig=plt.figure(figsize=(15,15))
#Erstellen der Achsen
ax=fig.add_subplot(111,projection="3d")
#Ploten der Orbits
ax.plot(r1_sol[:,0],r1_sol[:,1],r1_sol[:,2],color="darkblue")
ax.plot(r2_sol[:,0],r2_sol[:,1],r2_sol[:,2],color="tab:red")
ax.plot(r3_sol[:,0],r3_sol[:,1],r3_sol[:,2],color="tab:green")
#Plotten der finalen Position der Körper
ax.scatter(r1_sol[-1,0],r1_sol[-1,1],r1_sol[-1,2],color="darkblue",marker="o",s=100,label="Alpha Centauri A")
ax.scatter(r2_sol[-1,0],r2_sol[-1,1],r2_sol[-1,2],color="tab:red",marker="o",s=100,label="Alpha Centauri B")
ax.scatter(r3_sol[-1,0],r3_sol[-1,1],r3_sol[-1,2],color="tab:green",marker="o",s=100,label="Third Star")
#Hinzufügen der Beschriftungen
ax.set_xlabel("x-Koordinate",fontsize=14)
ax.set_ylabel("y-Koordinate",fontsize=14)
ax.set_zlabel("z-Kordinate",fontsize=14)
ax.set_title("Visualisierung der Orbits von Objekten im Raum\n",fontsize=14)
ax.legend(loc="upper left",fontsize=14)

ani = animation.FuncAnimation(fig, ThreeBodyEquations, frames=1000, interval=50)
plt.show()


import sys
from collections import deque

MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]
input = sys.stdin.readline

def isrange(x: int, y: int) -> bool:
    return 0 <= x < n and 0 <= y < n

def get_lands(x: int, y: int, island: int) -> set[tuple[int, int]]:
    lands: set[tuple[int, int]] = set()
    que: deque[tuple[int, int]] = deque()

    que.append((x, y))
    lands.add((x, y))
    board[x][y] = island

    while que:
        x, y = que.popleft()

        for movex, movey in MOVES:
            nextx: int = x + movex
            nexty: int = y + movey

            if not isrange(nextx, nexty):
                continue
            if board[nextx][nexty] == 0:
                continue
            if (nextx, nexty) in lands:
                continue

            que.append((nextx, nexty))
            lands.add((nextx, nexty))
            board[nextx][nexty] = island

    return lands

def get_bridge_length(lands: set[tuple[int, int]], island: int) -> int:
    length: int = 0
    que: deque[tuple[int, int]] = deque()
    visited: list[list[bool]] = [[False for _ in range(n)] for _ in range(n)]

    for x, y in lands:
        que.append((x, y))
        visited[x][y] = True

    while que:
        for _ in range(len(que)):
            x, y = que.popleft()

            for movex, movey in MOVES:
                nextx: int = x + movex
                nexty: int = y + movey

                if not isrange(nextx, nexty):
                    continue
                if board[nextx][nexty] == island:
                    continue
                if visited[nextx][nexty]:
                    continue

                if board[nextx][nexty] > 0:
                    return length

                que.append((nextx, nexty))
                visited[nextx][nexty] = True

        length += 1

    return -1

def solve() -> int:
    island: int = 2
    length: int = sys.maxsize

    for x, row in enumerate(board):
        for y, elem in enumerate(row):
            if elem == 1:
                lands = get_lands(x, y, island)
                length = min(length, get_bridge_length(lands, island))
                island += 1

    return length

if __name__ == "__main__":
    n = int(input())
    board = [list(map(int, input().split())) for _ in range(n)]

    print(solve())


from random import randint
import numpy

def fill_unassigned(row):
    '''
    >>> a = numpy.array([1, 0, 5, 5, 0, 2])
    >>> fill_unassigned(a)
    >>> a
    array([1, 3, 5, 5, 4, 2])
    '''
    usednums, c = set(row), 1
    for i, x in enumerate(row):
        if x != 0:
            continue
        while c in usednums:
            c += 1
        row[i] = c
        usednums.add(c)

def join_sets(row, a, b):
    '''
    >>> a = numpy.array([1, 1, 2, 2, 3, 2])
    >>> join_sets(a, 1, 2)
    >>> a
    array([1, 1, 1, 1, 3, 1])
    '''
    row[numpy.where(row == b)[0]] = a

def make_bottom_walls(row):
    sets = {}
    for x in row:
        sets[x] = sets.get(x, 0) + 1
    guarded = {k: randint(0, v - 1) for k, v in sets.items()}
    bwalls = numpy.zeros(row.shape, dtype='bool')
    for i, x in enumerate(row):
        sets[x] -= 1
        if guarded[x] == sets[x]:
            continue
        if randint(0, 1):
            bwalls[i] = True
    return bwalls

def genmaze_eller(cellcount, heightcount):
    #     0   1
    # +xxx+xxx+xxx+
    # x   |   |   x
    # +---+---+---+  0
    # x   |   |   x
    # +xxx+xxx+xxx+

    all_right_walls = numpy.zeros((cellcount - 1, heightcount), dtype=numpy.bool_)
    all_bottom_walls = numpy.zeros((cellcount, heightcount - 1), dtype=numpy.bool_)

    row = numpy.arange(1, cellcount + 1, dtype=numpy.int16)
    rwalls = numpy.zeros((cellcount - 1,), dtype=numpy.bool_)
    rwalls_req = numpy.zeros(rwalls.shape, dtype=numpy.bool_)
    for y in range(heightcount):
        fill_unassigned(row)
        rwalls[:] = False
        rwalls_req[:] = False
        for x in range(cellcount - 1):
            if row[x] == row[x + 1]:
                rwalls_req[x] = True
                continue
            if randint(0, 1):
                rwalls[x] = True
            else:
                join_sets(row, row[x], row[x + 1])

        if y == heightcount - 1:  # last row condition
            break
        all_right_walls[:, y] = rwalls_req | rwalls

        bwalls = make_bottom_walls(row)
        all_bottom_walls[:, y] = bwalls
        row[bwalls] = 0

    # walls in last row
    for x in range(cellcount - 1):
        if row[x + 1] != row[x]:
            rwalls[x] = False
            join_sets(row, row[x], row[x + 1])
    all_right_walls[:, heightcount - 1] = rwalls | rwalls_req

    return {
        'width': cellcount,
        'height': heightcount,
        'rwalls': all_right_walls,
        'bwalls': all_bottom_walls,
    }

def debug_draw_maze(maze):
    from PIL import Image, ImageDraw

    WorldSize.cell = 20
    w, h = maze['width'], maze['height']
    img = Image.new('RGB', (w * WorldSize.cell, h * WorldSize.cell))
    draw = ImageDraw.Draw(img)
    draw.rectangle((0, 0, w * WorldSize.cell - 1, h * WorldSize.cell - 1), fill=(0, 0, 0))
    for y in range(h):
        for x in range(w - 1):
            if maze['rwalls'][x, y]:
                draw.line((
                    x * WorldSize.cell + WorldSize.cell, y * WorldSize.cell,
                    x * WorldSize.cell + WorldSize.cell, y * WorldSize.cell + WorldSize.cell
                ), fill=(255, 255, 255))
    for y in range(h - 1):
        for x in range(w):
            if maze['bwalls'][x, y]:
                draw.line((
                    x * WorldSize.cell, y * WorldSize.cell + WorldSize.cell,
                    x * WorldSize.cell + WorldSize.cell, y * WorldSize.cell + WorldSize.cell
                ), fill=(255, 255, 255))
    img.show()

if __name__ == '__main__':
    maze = genmaze_eller(30, 30)
    debug_draw_maze(maze)


# -*- coding:utf-8 -*-

# 请设计一个函数，用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
# 路径可以从矩阵中的任意一个格子开始，
# 每一步可以在矩阵中向左，向右，向上，向下移动一个格子。
# 如果一条路径经过了矩阵中的某一个格子，则该路径不能再进入该格子。
#
# 例如
#      a b c e
#      s f c s
#      a d e e
# 矩阵中包含一条字符串"bcced"的路径，
# 但是矩阵中不包含"abcb"路径，
# 因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后，
# 路径不能再次进入该格子。

# -*- coding:utf-8 -*-
class Solution:

    def hasPath(self, matrix, rows, cols, path):
        # write code here
        flag = [False for _ in range(len(matrix))]
        for i in range(rows):
            for j in range(cols):
                # 遍历
                if self.judge(matrix, rows, cols, flag, i, j, path, 0):
                    return True
        return False

    def judge(self, matrix, rows, cols, flag, i, j, path, level):
        index = i * cols + j
        # 判断越界条件,递归终止条件
        if i >= rows or j >= cols or i < 0 or j < 0 or \
                matrix[index] != path[level] or \
                flag[index] == True:
            return False

        if level == len(path) - 1:
            return True

        flag[index] = True

        if (self.judge(matrix, rows, cols, flag, i + 1, j, path, level + 1) or \
                self.judge(matrix, rows, cols, flag, i, j + 1, path, level + 1) or \
                self.judge(matrix, rows, cols, flag, i - 1, j, path, level + 1) or \
                self.judge(matrix, rows, cols, flag, i, j - 1, path, level + 1)):
            return True

        flag[index] = False
        return False


"""
Neural Networks - Deep Learning
Heart Disease Predictor ( Binary Classification )
Author: Dimitrios Spanos Email: dimitrioss@ece.auth.gr
"""
import numpy as np
from cvxopt import matrix, solvers

# ------------
#   Kernels
# ------------

def poly(x, z, d=3, coef=1, g=1):
    return (g * np.dot(x, z.T) + coef) ** d

def rbf(x, z, sigma):
    return np.exp(-np.linalg.norm(x-z,axis=1)**2 / (2*(sigma**2)))

def linear(x, z):
    return np.matmul(x, z.T)

def sigmoid(x, z, g=1, coef=0):
    return np.tanh(g * np.dot(x, z.T) + coef)

# ------------
#     SVM
# ------------

class my_SVM:

    def __init__(self, C, kernel='linear', sigma=1):
        self.C = C
        self.kernel = kernel
        self.sigma = sigma
        self.sv = 0
        self.sv_y = 0
        self.alphas = 0
        self.w = 0
        self.b = 0

    def fit(self, X, y):

        # Calculate the Kernel(xi,xj)
        m, n = X.shape
        K = np.zeros((m,m))
        if self.kernel == 'rbf':
            for i in range(m):
                K[i,:] = rbf(X[i,np.newaxis], X,  sigma=self.sigma)
        elif self.kernel == 'poly':
            for i in range(m):
                K[i,:] = poly(X[i,np.newaxis], X)
        elif self.kernel == 'sigmoid':
            for i in range(m):
                K[i,:] = sigmoid(X[i,np.newaxis], X)
        elif self.kernel == 'linear':
            for i in range(m):
                K[i,:] = linear(X[i,np.newaxis], X)

        # Solve the QP Problem
        P = matrix(np.outer(y, y) * K)
        q = matrix(-np.ones((m, 1)))
        A = matrix(matrix(y.T), (1, m), 'd')
        b = matrix(np.zeros(1))
        G = matrix(np.vstack((np.eye(m)*-1, np.eye(m))))
        h = matrix(np.hstack((np.zeros(m),np.ones(m)*self.C)))
        solvers.options['show_progress'] = False
        solution = solvers.qp(P, q, G, h, A, b)

        # Get the solution's results
        alphas = np.array(solution['x'])
        S = (alphas > 1e-4).flatten()
        self.sv = X[S]
        self.sv_y = y[S]
        self.w = np.dot((y.reshape(-1,1) * alphas).T, X)[0]
        self.alphas = alphas[S] # get rid of alphas ~= 0
        self.b = np.mean(self.sv_y - np.dot(self.sv, self.w.T))

        #print("w:", self.w)
        #print("b:", self.b)

    def predict(self, X):

        K_xi_x = 0
        if self.kernel == 'rbf':
            K_xi_x = rbf(self.sv, X, self.sigma)
        elif self.kernel == 'poly':
            K_xi_x = poly(self.sv, X)
        elif self.kernel == 'sigmoid':
            K_xi_x = sigmoid(self.sv, X)
        elif self.kernel == 'linear':
            K_xi_x = linear(self.sv, X)

        sum = 0
        for i in range(len(K_xi_x)):
            sum +=self.alphas[i] * self.sv_y[i]* K_xi_x[i]

        prod = sum + self.b
        prediction = np.sign(prod)
        return prediction


class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        d={}
        for i in nums:
            if i in d:
                d[i]+=1
            else:
                d[i]=1
        d=sorted(d, key=d.get, reverse=True)
        return(d[0])


from datetime import datetime, date, time
import time
from collections import OrderedDict

def parametrized_decor(parameter):
  def decor(foo):
    def new_foo(*args, **kwargs):
      print(datetime.now())
      print(f'Имя функции - {foo.__name__}')
      if args is not None:
        print(f'Позиционные аргументы args - {args}')
      if kwargs is not None:
        print(f'Именованные аргументы kwargs - {kwargs}')
      result = foo(*args, **kwargs)
      print('result: ', result)
      print('result type: ', type(result))
      return result
    return new_foo
  return decor

if __name__ == '__main__':
  # foo(1, 2)

  documents_list = [{
      "type": "passport",
      "number": "2207 876234",
      "name": "Василий Гупкин"
  }, {
      "type": "invoice",
      "number": "11-2",
      "name": "Геннадий Покемонов"
  }]

  @parametrized_decor(parameter=None)
  def give_name(doc_list, num):
    for doc_dict in doc_list:
      if num == doc_dict['number']:
        print(
            f"Документ под номером {num} соответствует имени {doc_dict['name']}"
        )

  give_name(documents_list, '11-2')

  print("____" * 15)
  @parametrized_decor(parameter=None)
  def summator(x, y):
    return x + y

  three = summator(1, 2)
  five = summator(2, 3)
  result = summator(three, five)


from django.shortcuts import render
from django.http import Http404, HttpResponse, JsonResponse
from django.template import loader
from catalog.models import *
from django.forms.models import model_to_dict
import random
from django.views.decorators.csrf import csrf_exempt
from django.middleware.csrf import get_token
import json
# Create your views here.

def index(request):
    template = loader.get_template('template.html')
    context = {}
    questions_id = []
    related_choices = []
    ID = ""
    name = ""
    # get all available modules and randomly pick one
    module = list(modules.objects.all().values('module_name'))
    randomed = [i for i in range(len(module))]
    random.shuffle(randomed)
    context['module'] = module[randomed[0]]
    #print(context)
    #
    # get related questions and pass to html template
    module_id = list(modules.objects.filter(module_name=context['module']['module_name']).values("id"))[0]['id']
    question = list(questions.objects.all().filter(questions_under_id=module_id))
    random.shuffle(question)
    context['question'] = question
    #print(context)
    #
    #get related answers and pass to html template
    #print(question)
    for i in question:
        questions_id.append(i.id)
    #print(questions_id)
    for id in questions_id:
        related_choices.append(list(answers.objects.filter(answers_under_id=id)))
    context['answer'] = related_choices
    #print(context['answer'])
    #
    # get Id & scores and pass to html template
    name = module[randomed[0]]["module_name"]
    print(name)
    Id = modules.objects.filter(module_name=name).values('id')
    for each in Id:
        ID = each['id']
    print(ID)
    Scores = scores.objects.filter(score_under_id=ID).order_by('scores').reverse()
    print(Scores)
    context['scores'] = Scores
    return HttpResponse(template.render(context,request))

def newScore(request):
    print("SUCCESS : AJAX ENTERED!")
    template = loader.get_template('template.html')
    context = {}
    under_ID = ""
    if request.method == "POST" :
        # handle save logic
        if request.body:
            jsonLoad = json.loads(request.body)
            Scores = jsonLoad['scores']
            username = jsonLoad['username']
            module = jsonLoad['module']
        else :
            return JsonResponse({"errors": ["POST object has insufficient parameters!"]})
        ID = modules.objects.filter(module_name=module).values('id')
        for each in ID:
            under_ID = each['id']
        errors = scores(scores=Scores, gameId=username, score_under_id=under_ID)
        errors.save()
    return HttpResponse(template.render(context,request))


import os
import csv
import queue
import logging
import argparse
import traceback
import itertools
import numpy as np

import tensorflow.compat.v1 as tf

from fedlearner.trainer.bridge import Bridge
from fedlearner.model.tree.tree import BoostingTreeEnsamble
from fedlearner.trainer.trainer_master_client import LocalTrainerMasterClient
from fedlearner.trainer.trainer_master_client import DataBlockInfo

'''
目前不太理解的地方：worker、verbosity、max-bins、ignore-fields
'''
def create_argument_parser():
    parser = argparse.ArgumentParser(
        description='FedLearner Tree Model Trainer.')
    #训练角色，leader还是follower
    parser.add_argument('role', type=str,
                        help="Role of this trainer in {'local', "
                             "'leader', 'follower'}")
    #监听本地地址，ip+port
    parser.add_argument('--local-addr', type=str,
                        help='Listen address of the local bridge, ' \
                             'in [IP]:[PORT] format')
    #同伴地址，ip+port
    parser.add_argument('--peer-addr', type=str,
                        help='Address of peer\'s bridge, ' \
                             'in [IP]:[PORT] format')
    #分布式训练时，应用程序的id，默认空
    parser.add_argument('--application-id', type=str, default=None,
                        help='application id on distributed ' \
                             'training.')
    #current worker的排名，等级，默认0
    parser.add_argument('--worker-rank', type=int, default=0,
                        help='rank of the current worker')
    #总的worker数量，默认1
    parser.add_argument('--num-workers', type=int, default=1,
                        help='total number of workers')
    #mode，可以为 train,test,eval,默认为train
    parser.add_argument('--mode', type=str, default='train',
                        help='Running mode in train, test or eval.')
    #数据文件的路径
    parser.add_argument('--data-path', type=str, default=None,
                        help='Path to data file.')
    #验证数据文件的路径，仅用于test模式
    parser.add_argument('--validation-data-path', type=str, default=None,
                        help='Path to validation data file. ' \
                             'Only used in train mode.')
    #bool变量，默认为false，预测不需要数据
    parser.add_argument('--no-data', type=bool, default=False,
                        help='Run prediction without data.')
    #使用的文件扩展
    parser.add_argument('--file-ext', type=str, default='.csv',
                        help='File extension to use')
    #输入文件类型
    parser.add_argument('--file-type', type=str, default='csv',
                        help='input file type: csv or tfrecord')
    #加载已存储模型的路径
    parser.add_argument('--load-model-path',
                        type=str,
                        default=None,
                        help='Path load saved models.')
    #存储输出模型的位置
    parser.add_argument('--export-path',
                        type=str,
                        default=None,
                        help='Path to save exported models.')
    #保存模型的检查点
    parser.add_argument('--checkpoint-path',
                        type=str,
                        default=None,
                        help='Path to save model checkpoints.')
    #存储预测输出的路径
    parser.add_argument('--output-path',
                        type=str,
                        default=None,
                        help='Path to save prediction output.')
    #控制打印日志的数量，默认为1
    parser.add_argument('--verbosity',
                        type=int,
                        default=1,
                        help='Controls the amount of logs to print.')
    #损失函数的选择，默认为logistic
    parser.add_argument('--loss-type',
                        default='logistic',
                        choices=['logistic', 'mse'],
                        help='What loss to use for training.')
    #学习率，梯度下降中的步长，默认为0.3
    parser.add_argument('--learning-rate',
                        type=float,
                        default=0.3,
                        help='Learning rate (shrinkage).')
    #boost 迭代次数，默认为5
    parser.add_argument('--max-iters',
                        type=int,
                        default=5,
                        help='Number of boosting iterations.')
    #决策树的最大深度，默认为3
    parser.add_argument('--max-depth',
                        type=int,
                        default=3,
                        help='Max depth of decision trees.')
    #L2正则化参数，默认为1.0
    parser.add_argument('--l2-regularization',
                        type=float,
                        default=1.0,
                        help='L2 regularization parameter.')
    #最大的直方图维度
    parser.add_argument('--max-bins',
                        type=int,
                        default=33,
                        help='Max number of histogram bins.')
    #并行线程的数量，默认1
    parser.add_argument('--num-parallel',
                        type=int,
                        default=1,
                        help='Number of parallel threads.')
    #bool类型，如果被设置为true，数据第一列被认为是双方都匹配的example id
    parser.add_argument('--verify-example-ids',
                        type=bool,
                        default=False,
                        help='If set to true, the first column of the '
                             'data will be treated as example ids that '
                             'must match between leader and follower')
    #通过名字来忽略数据域，默认空字符串
    parser.add_argument('--ignore-fields',
                        type=str,
                        default='',
                        help='Ignore data fields by name')
    #分类特征的字段名称，特征的值应该为非负整数
    parser.add_argument('--cat-fields',
                        type=str,
                        default='',
                        help='Field names of categorical features. Feature'
                             ' values should be non-negtive integers')
    #是否使用流传输，默认为否
    parser.add_argument('--use-streaming',
                        type=bool,
                        default=False,
                        help='Whether to use streaming transmit.')
    #是否发送预测评分给follower，默认为false
    parser.add_argument('--send-scores-to-follower',
                        type=bool,
                        default=False,
                        help='Whether to send prediction scores to follower.')
    #是否发送指标（metrics）给follower，默认为follower
    parser.add_argument('--send-metrics-to-follower',
                        type=bool,
                        default=False,
                        help='Whether to send metrics to follower.')

    return parser

def parse_tfrecord(record):
    example = tf.train.Example()
    example.ParseFromString(record)

    parsed = {}
    for key, value in example.features.feature.items():
        kind = value.WhichOneof('kind')
        if kind == 'float_list':
            assert len(value.float_list.value) == 1, "Invalid tfrecord format"
            parsed[key] = value.float_list.value[0]
        elif kind == 'int64_list':
            assert len(value.int64_list.value) == 1, "Invalid tfrecord format"
            parsed[key] = value.int64_list.value[0]
        elif kind == 'bytes_list':
            assert len(value.bytes_list.value) == 1, "Invalid tfrecord format"
            parsed[key] = value.bytes_list.value[0]
        else:
            raise ValueError("Invalid tfrecord format")

    return parsed

def extract_field(field_names, field_name, required):
    if field_name in field_names:
        return []

    assert not required, \
        "Field %s is required but missing in data"%field_name
    return None

def read_data(file_type, filename, require_example_ids,
              require_labels, ignore_fields, cat_fields):
    logging.debug('Reading data file from %s', filename)

    if file_type == 'tfrecord':
        reader = tf.io.tf_record_iterator(filename)
        reader, tmp_reader = itertools.tee(reader)
        first_line = parse_tfrecord(next(tmp_reader))
        field_names = first_line.keys()
    else:
        fin = tf.io.gfile.GFile(filename, 'r')
        reader = csv.DictReader(fin)
        field_names = reader.fieldnames

    example_ids = extract_field(
        field_names, 'example_id', require_example_ids)
    raw_ids = extract_field(
        field_names, 'raw_id', False)
    labels = extract_field(
        field_names, 'label', require_labels)

    ignore_fields = set(filter(bool, ignore_fields.strip().split(',')))
    ignore_fields.update(['example_id', 'raw_id', 'label'])
    cat_fields = set(filter(bool, cat_fields.strip().split(',')))
    for name in cat_fields:
        assert name in field_names, "cat_field %s missing"%name

    cont_columns = list(filter(
        lambda x: x not in ignore_fields and x not in cat_fields, field_names))
    cont_columns.sort(key=lambda x: x[1])
    cat_columns = list(filter(
        lambda x: x in cat_fields and x not in cat_fields, field_names))
    cat_columns.sort(key=lambda x: x[1])

    features = []
    cat_features = []
    for line in reader:
        if file_type == 'tfrecord':
            line = parse_tfrecord(line)
        if example_ids is not None:
            example_ids.append(str(line['example_id']))
        if raw_ids is not None:
            raw_ids.append(str(line['raw_id']))
        if labels is not None:
            labels.append(float(line['label']))
        features.append([float(line[i]) for i in cont_columns])
        cat_features.append([int(line[i]) for i in cat_columns])

    features = np.array(features, dtype=np.float)
    cat_features = np.array(cat_features, dtype=np.int32)
    if labels is not None:
        labels = np.asarray(labels, dtype=np.float)

    return features, cat_features, cont_columns, cat_columns, \
        labels, example_ids, raw_ids

def read_data_dir(file_ext, file_type, path, require_example_ids,
                  require_labels, ignore_fields, cat_fields):
    if not tf.io.gfile.isdir(path):
        return read_data(
            file_type, path, require_example_ids,
            require_labels, ignore_fields, cat_fields)

    files = []
    for dirname, _, filenames in tf.io.gfile.walk(path):
        for filename in filenames:
            _, ext = os.path.splitext(filename)
            if file_ext and ext != file_ext:
                continue
            subdirname = os.path.join(path, os.path.relpath(dirname, path))
            files.append(os.path.join(subdirname, filename))

    features = None
    for fullname in files:
        ifeatures, icat_features, icont_columns, icat_columns, \
            ilabels, iexample_ids, iraw_ids = read_data(
                file_type, fullname, require_example_ids,
                require_labels, ignore_fields, cat_fields
            )
        if features is None:
            features = ifeatures
            cat_features = icat_features
            cont_columns = icont_columns
            cat_columns = icat_columns
            labels = ilabels
            example_ids = iexample_ids
            raw_ids = iraw_ids
        else:
            assert cont_columns == icont_columns, \
                "columns mismatch between files %s vs %s"%(
                    cont_columns, icont_columns)
            assert cat_columns == icat_columns, \
                "columns mismatch between files %s vs %s"%(
                    cat_columns, icat_columns)
            features = np.concatenate((features, ifeatures), axis=0)
            cat_features = np.concatenate(
                (cat_features, icat_features), axis=0)
            if labels is not None:
                labels = np.concatenate((labels, ilabels), axis=0)
            if example_ids is not None:
                example_ids.extend(iexample_ids)
            if raw_ids is not None:
                raw_ids.extend(iraw_ids)

    assert features is not None, "No data found in %s"%path

    return features, cat_features, cont_columns, cat_columns, \
        labels, example_ids, raw_ids

def train(args, booster):
    X, cat_X, X_names, cat_X_names, y, example_ids, _ = read_data_dir(
        args.file_ext, args.file_type, args.data_path, args.verify_example_ids,
        args.role != 'follower', args.ignore_fields, args.cat_fields)

    if args.validation_data_path:
        val_X, val_cat_X, val_X_names, val_cat_X_names, val_y, \
            val_example_ids, _ = \
            read_data_dir(
                args.file_ext, args.file_type, args.validation_data_path,
                args.verify_example_ids, args.role != 'follower',
                args.ignore_fields, args.cat_fields)
        assert X_names == val_X_names, \
            "Train data and validation data must have same features"
        assert cat_X_names == val_cat_X_names, \
            "Train data and validation data must have same features"
    else:
        val_X = val_cat_X = X_names = val_y = val_example_ids = None

    if args.output_path:
        tf.io.gfile.makedirs(os.path.dirname(args.output_path))
    if args.checkpoint_path:
        tf.io.gfile.makedirs(args.checkpoint_path)

    booster.fit(
        X, y,
        cat_features=cat_X,
        checkpoint_path=args.checkpoint_path,
        example_ids=example_ids,
        validation_features=val_X,
        validation_cat_features=val_cat_X,
        validation_labels=val_y,
        validation_example_ids=val_example_ids,
        output_path=args.output_path,
        feature_names=X_names,
        cat_feature_names=cat_X_names)

def write_predictions(filename, pred, example_ids=None, raw_ids=None):
    logging.debug("Writing predictions to %s.tmp", filename)
    headers = []
    lines = []
    if example_ids is not None:
        headers.append('example_id')
        lines.append(example_ids)
    if raw_ids is not None:
        headers.append('raw_id')
        lines.append(raw_ids)
    headers.append('prediction')
    lines.append(pred)
    lines = zip(*lines)

    fout = tf.io.gfile.GFile(filename+'.tmp', 'w')
    fout.write(','.join(headers) + '\n')
    for line in lines:
        fout.write(','.join([str(i) for i in line]) + '\n')
    fout.close()

    logging.debug("Renaming %s.tmp to %s", filename, filename)
    tf.io.gfile.rename(filename+'.tmp', filename, overwrite=True)

def test_one_file(args, bridge, booster, data_file, output_file):
    if data_file is None:
        X = cat_X = X_names = cat_X_names = y = example_ids = raw_ids = None
    else:
        X, cat_X, X_names, cat_X_names, y, example_ids, raw_ids = \
            read_data(
                args.file_type, data_file, args.verify_example_ids,
                False, args.ignore_fields, args.cat_fields)

    pred = booster.batch_predict(
        X,
        example_ids=example_ids,
        cat_features=cat_X,
        feature_names=X_names,
        cat_feature_names=cat_X_names)

    if y is not None:
        metrics = booster.loss.metrics(pred, y)
    else:
        metrics = {}
    logging.info("Test metrics: %s", metrics)

    if args.role == 'follower':
        bridge.start(bridge.new_iter_id())
        bridge.receive(bridge.current_iter_id, 'barrier')
        bridge.commit()

    if output_file:
        tf.io.gfile.makedirs(os.path.dirname(output_file))
        write_predictions(output_file, pred, example_ids, raw_ids)

    if args.role == 'leader':
        bridge.start(bridge.new_iter_id())
        bridge.send(
            bridge.current_iter_id, 'barrier', np.asarray([1]))
        bridge.commit()

class DataBlockLoader(object):
    def __init__(self, role, bridge, data_path, ext,
                 worker_rank=0, num_workers=1, output_path=None):
        self._role = role
        self._bridge = bridge
        self._num_workers = num_workers
        self._worker_rank = worker_rank
        self._output_path = output_path

        self._tm_role = 'follower' if role == 'leader' else 'leader'

        if data_path:
            files = None
            if not tf.io.gfile.isdir(data_path):
                files = [os.path.basename(data_path)]
                data_path = os.path.dirname(data_path)
            self._trainer_master = LocalTrainerMasterClient(
                self._tm_role, data_path, files=files, ext=ext)
        else:
            self._trainer_master = None

        self._count = 0
        if self._role == 'leader':
            self._block_queue = queue.Queue()
            self._bridge.register_data_block_handler(self._data_block_handler)
            self._bridge.start(self._bridge.new_iter_id())
            self._bridge.send(
                self._bridge.current_iter_id, 'barrier', np.asarray([1]))
            self._bridge.commit()
        elif self._role == 'follower':
            self._bridge.start(self._bridge.new_iter_id())
            self._bridge.receive(self._bridge.current_iter_id, 'barrier')
            self._bridge.commit()

    def _data_block_handler(self, msg):
        logging.debug('DataBlock: recv "%s" at %d', msg.block_id, msg.count)
        assert self._count == msg.count
        if not msg.block_id:
            block = None
        elif self._trainer_master is not None:
            block = self._trainer_master.request_data_block(msg.block_id)
            return False
        else:
            block = DataBlockInfo(msg.block_id, None)
        self._count += 1
        self._block_queue.put(block)
        return True

    def _request_data_block(self):
        while True:
            for _ in range(self._worker_rank):
                self._trainer_master.request_data_block()
            block = self._trainer_master.request_data_block()
            for _ in range(self._num_workers - self._worker_rank - 1):
                self._trainer_master.request_data_block()
            if block is None or self._output_path is None or \
                    not tf.io.gfile.exists(os.path.join(
                        self._output_path, block.block_id) + '.output'):
                break
        return block

    def get_next_block(self):
        if self._role == 'local':
            return self._request_data_block()

        if self._tm_role == 'leader':
            while True:
                block = self._request_data_block()
                if block is not None:
                    if not self._bridge.load_data_block(
                            self._count, block.block_id):
                        continue
                else:
                    self._bridge.load_data_block(self._count, '')
                break
            self._count += 1
        else:
            block = self._block_queue.get()
        return block

def test(args, bridge, booster):
    if not args.no_data:
        assert args.data_path, "Data path must not be empty"
    else:
        assert not args.data_path and args.role == 'leader'

    data_loader = DataBlockLoader(
        args.role, bridge, args.data_path, args.file_ext,
        args.worker_rank, args.num_workers, args.output_path)

    while True:
        data_block = data_loader.get_next_block()
        if data_block is None:
            break
        if args.output_path:
            output_file = os.path.join(
                args.output_path, data_block.block_id) + '.output'
        else:
            output_file = None
        test_one_file(
            args, bridge, booster, data_block.data_path, output_file)

def run(args):
    if args.verbosity == 0:
        logging.basicConfig(level=logging.WARNING)
    elif args.verbosity == 1:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.DEBUG)

    assert args.role in ['leader', 'follower', 'local'], \
        "role must be leader, follower, or local"
    assert args.mode in ['train', 'test', 'eval'], \
        "mode must be train, test, or eval"
    #follower或leader
    if args.role != 'local':
        bridge = Bridge(args.role, int(args.local_addr.split(':')[1]),
                        args.peer_addr, args.application_id, 0,
                        streaming_mode=args.use_streaming)
    else:
        bridge = None

    try:
        #boost
        booster = BoostingTreeEnsamble(
            bridge,
            learning_rate=args.learning_rate,
            max_iters=args.max_iters,
            max_depth=args.max_depth,
            l2_regularization=args.l2_regularization,
            max_bins=args.max_bins,
            num_parallel=args.num_parallel,
            loss_type=args.loss_type,
            send_scores_to_follower=args.send_scores_to_follower,
            send_metrics_to_follower=args.send_metrics_to_follower)
        #加载已存储的模型
        if args.load_model_path:
            booster.load_saved_model(args.load_model_path)
        #训练不需要bridge，为什么呢
        if args.mode == 'train':
            train(args, booster)
        #测试，评估模型需要bridge
        else:  # args.mode == 'test, eval'
            test(args, bridge, booster)
        #把模型存起来
        if args.export_path:
            booster.save_model(args.export_path)
    except Exception as e:
        logging.fatal(
            'Exception raised during training: %s',
            traceback.format_exc())
        raise e
    finally:
        #结束bridge
        if bridge:
            bridge.terminate()

if __name__ == '__main__':
    run(create_argument_parser().parse_args())


# Time limit exceeded at sight
# range(n + 1 -i) in the second roop
# You don't need to add the third roop.
# Alternatively, you should use (k =) n - i - j
n , y= map(int, input().split())

for i in range(n + 1):
    for j in range(n + 1):
        for k in range(n + 1):
            if i + j + k == n:
                if  10000 * i + 5000 * j + 1000 * k == y:
                    print(i, j, k)
                    exit()

print(-1, -1, -1)

# Sample answer
n , y= map(int, input().split())

for i in range(n + 1):
    for j in range(n + 1 - i):
            if  10000 * i + 5000 * j + 1000 * (n - i - j) == y:
                print(i, j, n - i - j)
                exit()

print(-1, -1, -1)


import transformers
import torch.nn as nn
import config
import torch

class BERT_wmm(nn.Module):
     def __init__(self, keep_tokens):
         super(BERT_wmm,self).__init__()
         self.bert=transformers.BertModel.from_pretrained(config.BERT_PATH)
         self.fc=nn.Linear(768,768)
         self.layer_normalization=nn.LayerNorm((64, 768))
         # self.bert_drop=nn.Dropout(0.2)
         self.out=nn.Linear(768,6932)

         if keep_tokens is not None:
             self.embedding = nn.Embedding(6932, 768)
             weight = torch.load(config.BERT_EMBEDDING)
             weight = nn.Parameter(weight['weight'][keep_tokens])
             self.embedding.weight = weight
             self.bert.embeddings.word_embeddings = self.embedding
             print(weight.shape)

     def forward(self, ids, mask, token_type_ids):
         out1, _=self.bert(
             ids,
             attention_mask=mask,
             token_type_ids=token_type_ids,
             return_dict=False
         )
         # mean pooling
         # max pooling
         # concat
         # bert_output=self.bert_drop(out1)
         output=self.fc(out1)
         layer_normalized=self.layer_normalization(output)
         final_output=self.out(layer_normalized)
         return final_output


def load_train_test(train_file, test_file):
    """
    load data from train and test files out of the project
    Args:
        train_file: a string of train data address
        test_file: a string of test data address
    Returns:
        train_feature: none
        train_label: none
        test_feature: none
        test_label: none
    """
    # load train data from train file
    train_feature = []
    train_label = []
    file_read = open(train_file)
    for line in file_read.readlines():
        data = line.strip().split()
        train_label.append(int(data[0]))  # the first column is the label, data type: int
        # from the second column to the end are the features, data type: float
        _feature = [float(item) for item in data[1:]]
        train_feature.append(_feature)
    # load test data from test file
    test_feature = []
    test_label = []
    file_read = open(test_file)
    for line in file_read.readlines():
        data = line.strip().split()
        test_label.append(int(data[0]))  # the first column is the label, data type: int
        # from the second column to the end are the features, data type: float
        _feature = [float(item) for item in data[1:]]
        test_feature.append(_feature)
    return train_feature, train_label, test_feature, test_label


import sqlite3
import os
import shlex
class Database():

    def __init__(self, db_file):
        """Connect to the SQLite DB"""
        try:
            self.conn = sqlite3.connect(db_file)
            self.cursor = self.conn.cursor()
        except BaseException as err:
            #print(str(err))
            self.conn = None
            self.cursor = None

    def create_table(self, table_name, columns):
        query = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join([f'{k} {v}' for k, v in columns.items()])})"
        self.cursor.execute(query)
        self.conn.commit()

    def create_index(self, index_name, table_name, column_list):
        #query = f"CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({column_list})"
        query = f"CREATE INDEX IF NOT EXISTS idx_hash ON file_hash(filepath, filehash)"
        self.cursor.execute(query)
        self.conn.commit()

    def delete_table(self, table_name):
        query = f"DROP TABLE IF EXISTS {table_name}"
        self.cursor.execute(query)
        self.conn.commit()

    def add_record(self, table_name, record):
        query = f"INSERT INTO {table_name} ({', '.join(record.keys())}) VALUES ({', '.join(['?' for _ in record.values()])})"
        #print(query)
        self.cursor.execute(query, list(record.values()))
        self.conn.commit()

    def delete_record(self, table_name, condition):
        query = f"DELETE FROM {table_name} WHERE {condition}"
        self.cursor.execute(query)
        self.conn.commit()

    def run_query(self, query):
        #print(query)
        self.cursor.execute(query, args)
        return self.cursor.fetchall()

    def show_all_records(self, table_name):
        query = f"SELECT * FROM {table_name}"
        self.cursor.execute(query)
        return self.cursor.fetchall()

    def show_record(self, table_name, filepath):
        file_path = (filepath)
        #query = f"SELECT * FROM {table_name} WHERE {condition}"
        #print(f"SELECT filename,filepath, filehash, timestamp  FROM {table_name}  WHERE filepath = '{file_path}'")
        query = f'SELECT filename,filepath, filehash, timestamp  FROM {table_name}  WHERE filepath = "{file_path}"'
        self.cursor.execute(query)
        return self.cursor.fetchall()

    def update_record(self, table, filepath, filehash):
        """Update the SQLite File Table"""
        file_path = filepath
        #print(f"file path: {file_path}")
        query = f"UPDATE {table}  SET filehash = '{filehash}' WHERE filepath = '{file_path}'"
        self.cursor.execute(query)
        return self.cursor.fetchall()

    def is_rec_modifed(filepath,filehash,timestamp):
        """Check record for any changes
           Returning false until function is completed"""
        return False

    def show_duplicate_records(self, table_name, index_name, value):
        query = f"SELECT filename, filepath, filehash FROM {table_name} WHERE {index_name} = '{value}'"
        self.cursor.execute(query)
        return self.cursor.fetchall()

    def show_all_tables(self):
        query = "SELECT name FROM sqlite_master WHERE type='table'"
        self.cursor.execute(query)
        return self.cursor.fetchall()

    def close_connection(self):
        self.conn.close()

if __name__ == '__main__':
    db = Database('test.db')
    db.create_table('users', {'id': 'INTEGER PRIMARY KEY', 'name': 'TEXT', 'email': 'TEXT'})
    db.add_record('users', {'name': 'Alice', 'email': 'alice@example.com'})
    db.add_record('users', {'name': 'Bob', 'email': 'bob@example.com'})
    db.add_record('users', {'name': 'Charlie', 'email': 'charlie@example.com'})
    print(db.show_all_records('users'))
    print(db.show_record('users', "name='Alice'"))
    db.delete_record('users', "name='Bob'")
    print(db.show_all_records('users'))
    db.delete_table('users')
    db.close_connection()
    os.remove('test.db')


# BFS
from collections import deque
import sys
input = lambda: sys.stdin.readline()

def bfs(i, c): # 정점, 색상
    q = deque([i])
    visited[i] = True
    color[i] = c
    while q:
        i = q.popleft()
        for j in arr[i]:
            if not visited[j]:
                visited[j] = True
                q.append(j)
                color[j] = 3- color[i]
            else:
                if color[i] == color[j]:
                    return False
    return True

if __name__ == '__main__':
    k = int(input())
    for _ in range(k): # 테스트 케이스
        v,e = map(int, input().split())
        color = [0] * (v+1)
        arr = [[] for _ in range(v+1)]
        for _ in range(e):
            a,b = map(int, input().split())
            arr[a].append(b)
            arr[b].append(a)

        answer = True
        visited = [False] * (v+1)
        for i in range(1, v+1):
            if not visited[i]:
                if not bfs(i, 1): # return False이면 종료
                    answer = False
                    break
        print('YES' if answer else 'NO')

# DFS -> 메모리 초과
# from collections import deque
# import sys
# input = lambda: sys.stdin.readline()
# sys.setrecursionlimit(10**6)

# def dfs(i, c): # 정점, 색상
#     color[i] = c
#     for j in arr[i]:
#         if color[j] == 0:
#             if not dfs(j, 3-c):
#                 return False
#         elif color[i] == color[j]:
#             return False
#     return True

# if __name__ == '__main__':
#     k = int(input())
#     for _ in range(k): # 테스트 케이스
#         v,e = map(int, input().split())
#         color = [0] * (v)
#         arr = [[] for _ in range(v)]
#         for _ in range(e):
#             a,b = map(int, input().split())
#             arr[a-1].append(b-1)
#             arr[b-1].append(a-1)

#         answer = True
#         for i in range(0, v):
#             if color[i] == 0:
#                 if not dfs(i, 1):
#                     answer = False
#         print('YES' if answer else 'NO')


'''
@ Carlos Suarez 2020
'''
import requests
import datetime
import time
import json
from cachetools import TTLCache
import ssl
import sys

class MoodleControlador():

    def __init__(self,domain,token,cert):
        self.domain = domain
        self.token = token
        self.cert = cert

    #Moodle LTI

    def getGrabacionesMoodleContextoLTI(self,moodle_id,tiempo):
        endpoint = 'https://' + self.domain + '/contexts/?extId=' + moodle_id
        bearer = "Bearer " + self.token
        headers = {
            "Authorization":bearer,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.get(endpoint,headers=headers,verify=self.cert)
        if r.status_code == 200:
            jsonInfo = json.loads(r.text)
            if jsonInfo['size'] > 0:
                contexto_id = jsonInfo['results'][0]['id']
                return contexto_id
            else:
                return None
        else:
            print("Error Moodle ContextoLTI:" , str(r))

    def grabacionesMoodleLTI(self,contexto_id):
        endpoint = 'https://' + self.domain + '/recordings/?contextId=' + contexto_id
        bearer = "Bearer " + self.token
        headers = {
            "Authorization":bearer,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.get(endpoint,headers=headers)
        if r.status_code == 200:
            jsonInfo = json.loads(r.text)
            return jsonInfo
        else:
            print("Error GrabacionesLTL: " , str(r))

    def get_moodleLTI_recording_data(self,recording_id):
        authStr = 'Bearer ' + self.token
        url = 'https://' + self.domain + '/recordings/' + recording_id + '/data'
        credencial ={
           'Authorization': authStr,
           'Content-Type': 'application/json',
           'Accept': 'application/json'
        }
        r = requests.get(url,headers=credencial, verify=self.cert)
        if r.status_code == 200:
            res = json.loads(r.text)
            return res
        else:
            print(r)

    #Moodle plugin

    def moodleSesionName(self,sesionId):
        endpoint = 'https://' + self.domain + '/sessions/'  + sesionId
        credencial = {
            "Authorization":"Bearer " + self.token,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.get(endpoint,headers=credencial,verify=self.cert)
        if r.status_code == 200:
            res = json.loads(r.text)
            return res['name']
        else:
            print("Error Session:", str(r))

    def listaCompletaSessiones(self,criteria):
        listaFiltrada = []
        endpoint = 'https://' + self.domain + '/sessions'
        credencial = {
            "Authorization":"Bearer " + self.token,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.get(endpoint,headers=credencial,verify=self.cert)
        if r.status_code == 200:
            res = json.loads(r.text)
            resultado = res['results']
            for sesion in resultado:
                if criteria in sesion['name']:
                   listaFiltrada.append({'id':sesion['id'], 'name':sesion['name']})

            return listaFiltrada
        else:
            print("Error Session:", str(r))

    def listaCompletaMoodleGrabaciones(self):
        listaGrabaciones = []
        endpoint = 'https://' + self.domain + '/recordings'
        credencial = {
            'Authorization': 'Bearer ' + self.token,
            'Accept':'application/json'
        }
        r = requests.get(endpoint,headers=credencial,verify=self.cert)
        if r.status_code == 200:
            jsonInfo = json.loads(r.text)
            resultado = jsonInfo['results']
            if len(resultado) == 0:
                print("No recordings found")
            else:
                for grabacion in resultado:
                    listaGrabaciones.append({'id':grabacion['id'], 'name':grabacion['name']})
                print(listaGrabaciones)

        else:
            print("Error listaGrabación Moodle:", str(r))

    def listaMoodleGrabaciones(self,sname):
        endpoint = 'https://' + self.domain + '/recordings?name='  + sname
        credencial = {
            "Authorization":"Bearer " + self.token,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        r = requests.get(endpoint,headers=credencial,verify=self.cert)
        if r.status_code == 200:
            res = json.loads(r.text)
            idx = 0
            recording_ids = []
            try:
                numero_grabaciones = len(res['results'])
                if numero_grabaciones <= 0:
                    return None
                while idx < numero_grabaciones:
                    if 'storageSize' in res['results'][idx]:
                        recording_ids.append({
                            'recording_id':res['results'][idx]['id'],
                            'recording_name':res['results'][idx]['name'],
                            'duration':res['results'][idx]['duration'],
                            'storageSize':res['results'][idx]['storageSize'],
                            'created':res['results'][idx]['created']
                        })
                    else:
                        recording_ids.append({
                            'recording_id':res['results'][idx]['id'],
                            'recording_name':res['results'][idx]['name'],
                            'duration':res['results'][idx]['duration'],
                            'storageSize':0,
                            'created':res['results'][idx]['created']
                        })
                    idx += 1
                return recording_ids
            except TypeError:
                return None
        else:
            return None


import logging

from ab.base import NavTable
from ab.base import Link, Data, Item

class Console (object):

    def __init__ (self):
        self._indent = 0
        self._nt = NavTable()
        self.logger = logging.getLogger ('ab')
        self.log = lambda msg, level=logging.INFO: self.logger.info (msg)

    def reset (self):
        self._indent = 0
        self._nt = NavTable()

    def indent_more (self):
        self._indent += 2
        return self._indent

    def indent_less (self):
        self._indent -= 2
        return self._indent

    def indent (self):
        return self._indent

    #  def add_nav_entry (self, **kwa):
    #      href = kwa.get ('href')
    #
    #      if href:
    #          no = self._nt.set (href = href)
    #          return no
    #
    #
    #  def nav_table (self):
    #      if not len (self._nt):
    #          raise UserWarning ('empty nav table')
    #
    #      return self._nt
    #
    #
    #  def next_target_no (self):
    #      self._target_no += 1

    def draw (self, thing):
        out = '\n'

        # if type (thing) in [list, tuple]:
        if type (thing) is list:
            self.indent_more()

            for t in thing:
                out += self.draw (t)

            self.indent_less()

        elif isinstance (thing, Item):
            out += '{indent}[{index}] {prompt} ({href})'.format (
                indent = ' ' * self.indent(),
                index  = self._nt.set (href = thing.href),
                prompt = 'Permaurl',
                href   = 'GET ' + thing.href,
            )

            out += self.draw (thing.data)
            out += self.draw (thing.links)

        elif isinstance (thing, Data):
            out += '{indent}{prompt}: {value}'.format (
                indent = ' ' * self.indent(),
                prompt = thing.prompt,
                value  = thing.value,
            )

        elif isinstance (thing, Link):
            out += '{indent}[{index}] {prompt} ({method} {href})'.format (
                indent = ' ' * self.indent(),
                index  = self._nt.set (href = thing.href),
                prompt = thing.prompt,
                method = thing.method,
                href   = thing.href,
            )

        else:
            out += '<%s>' % thing

        return out


import wx
import ResizableRuneTag
'''
Created on 23/lug/2011

@author: Marco
'''

class DrawableFrame(wx.Window):
    '''
    Allows user to put resizable rune tags in a A4 like white frame
    Configuration realized on that frame is then replicated proportionally at export time
    '''

    def __init__(self, parent, height, width):
        wx.Window.__init__(self, parent)
        self.SetSize((height, width))
        self.SetMinSize((height, width))
        self.SetMaxSize((height, width))
        self.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.resizableRuneTags = []
        '''
        Constructor
        '''

    def DrawRuneTag(self, runeTagName, position, size, originalSize, info):
        self.resizableRuneTags.append(ResizableRuneTag.ResizableRuneTag(self, runeTagName, size, position, originalSize, info))

    def Clear(self):
        for resizableRuneTag in self.resizableRuneTags:
            resizableRuneTag.Destroy()

    def checkSpecificPosition(self, changedRuneTag):
        for tag in self.resizableRuneTags:
            if changedRuneTag != tag:
                radius1 = (tag.GetSize().GetHeight())/2 - 5
                radius2 = (changedRuneTag.GetSize().GetHeight())/2 - 5
                deltax = (tag.GetPosition().x + radius1) - (changedRuneTag.GetPosition().x + radius2)
                deltay = (tag.GetPosition().y + radius1) - (changedRuneTag.GetPosition().y + radius2)
                distance = (deltax*deltax + deltay*deltay)**(0.5)
                radiusSum = radius1 + radius2
                if distance <= radiusSum:
                    self.Parent.Parent.runeTagInfo.UpdateOverlap("In the output pdf file\n some slots of "+changedRuneTag.name+" RuneTag\n may laps over "+tag.name+"RuneTag")
                else:
                    self.Parent.Parent.runeTagInfo.UpdateOverlap("")

    def checkPosition(self):
        size = len(self.resizableRuneTags)
        for i in range(0, size):
            for j in range(i+1, size):
                tag1 = self.resizableRuneTags[i]
                tag2 = self.resizableRuneTags[j]
                radius1 = (tag1.GetSize().GetHeight())/2 - 5
                radius2 = (tag2.GetSize().GetHeight())/2 - 5
                deltax = (tag1.GetPosition().x + radius1) - (tag2.GetPosition().x + radius2)
                deltay = (tag1.GetPosition().y + radius1) - (tag2.GetPosition().y + radius2)
                distance = (deltax**2 + deltay**2)**(0.5)
                radiusSum = radius1 + radius2
                if distance <= radiusSum:
                    self.Parent.Parent.runeTagInfo.UpdateOverlap("In the output pdf file some slots of\n"+tag1.name+" RuneTag\n may laps over\n"+tag2.name+" RuneTag")
                else:
                    self.Parent.Parent.runeTagInfo.UpdateOverlap("")


from __future__ import annotations

import pytest

from randovania.lib import migration_lib

def test_migrate_to_version_missing_migration() -> None:
    data = {
        "schema_version": 1,
    }

    with pytest.raises(
        migration_lib.UnsupportedVersion,
        match=(
            "Requested a migration from something 1, but it's no longer supported. "
            "You can try using an older Randovania version."
        ),
    ):
        migration_lib.apply_migrations(data, [None], version_name="something")

def test_migrate_to_version_data_too_new() -> None:
    data = {
        "schema_version": 3,
    }

    with pytest.raises(
        migration_lib.UnsupportedVersion,
        match=(
            "Found version 3, but only up to 2 is supported. This file was created using a newer Randovania version."
        ),
    ):
        migration_lib.apply_migrations(data, [None])