## 例子例子

# """
# 接口返回信息:
# {code:"201",data:["2021-03-03 19:23"]}
# #显示服务器实时时间
# """

from flask import Flask, jsonify

from config.configs import AUTH_key

import time

# """
# 插件注册
def register_plugin(app):
  @app.route(AUTH_key+'/uploader',methods=['GET','POST'])
  def upload_file_1():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            #filename = secure_filename(file.filename)
            #获得文件名
            filename=file.filename

            #获得全路径
            basedir = os.path.abspath(os.path.dirname(__file__))
            #生成随机时间
            randname=time.strftime("%Y.%m.%d.%H.%M.%S", time.localtime())+str(random.randint(1,233333))
            #来个文件名
            file_dir = os.path.join(app.config['UPLOAD_FOLDER'],randname+"_"+filename)
            #try:
            file.save(file_dir)
            all_path=basedir+"\\"+file_dir #全部目录
            str1="上传文件成功!
\n"+"文件目录:" +all_path+"
正在尝试打印:"+"
"

            if ispic(all_path):
                str1+="[dayi]检测到了你上传了图片文件，正在暴力转为pdf
\n"
                all_path_tmp=all_path
                all_path=con_pic2pdf(all_path)
                if(all_path=="[error]"):
                    str1+="[error!!]转换pdf失败，你这是图片还是啥？
\n"
                    str1+="[error!!]我也不知道咋了这是，给你继续执行了吧
\n"
                    all_path=all_path_tmp

            if all_path.split('.')[-1] in ["doc","docx"]:
                all_path = con_doc2pdf(all_path)

            # if all_path.split('.')[-1] in ["ppt","pptx"]:
            #     all_path = con_ppt2pdf(all_path)

            # if all_path.split('.')[-1] in ["xls","xlsx"]:
            #     all_path = con_xls2pdf(all_path)
            # 暂时还没实现

            if all_path.split('.')[-1] == "txt":
                all_path = con_txt2pdf(all_path)

            if request.form.get("blackAndWhitePrinting"):
                str1 += "正在将文档转化为黑白
"
                if all_path.split('.')[-1] != "pdf":
                    str1 += "你上传的格式暂时不支持黑白打印，已经跳过文档处理
\n"
                else:
                    all_path = con2BW(all_path)
                    if all_path == 'Error':
                        str1 += '转换失败了
'
                        return render_template("echo.html",echo_str=str1)

            if not request.form.get("printAllPages"):
                pass
                # 页码选择

            print_info=print_file(all_path)#打印

            if request.form.get("deleteAfterPrinting"):
                os.remove(all_path)

            str1+=print_info
            return render_template("echo.html",echo_str=str1)
        else:
            str1="不合法文件类型！，当前合法类型："
            str1+=str(ALLOWED_EXTENSIONS)
            return render_template("echo.html",echo_str=str1)
    else:
        return render_template('upload.html')

#加载插件
def load_plugin(app):
  register_plugin(app)


import os
import json
import requests
import gzip
from argparse import ArgumentParser
from datetime import datetime
from collections import defaultdict
from typing import List
from multiprocessing.pool import ThreadPool

STORAGE_API_AT = 'https://www.googleapis.com/storage/v1/b/fpga-tool-perf/o'
TESTRES_PREFIX = 'artifacts/prod/foss-fpga-tools/fpga-tool-perf'
TEST_RESULT_DELIMITER = 'results-generic-all.json.gz'
DOWNLOAD_BASE_URL = 'https://storage.googleapis.com/fpga-tool-perf'

# Iterage over all result pages in GCS JSON API.
def iter_result_pages(url: str):
    req_url = url
    while True:
        resp = requests.get(
            url=req_url, headers={'Content-Type': 'application/json'})
        data = resp.json()

        yield data

        next_page_token = data.get('nextPageToken')
        if not next_page_token:
            break
        req_url = f'{url}&pageToken={next_page_token}'

def get_compound_result_file_path(test_run: int, builds: str):
    url = f'{STORAGE_API_AT}?delimiter={TEST_RESULT_DELIMITER}' \
          f'&prefix={TESTRES_PREFIX}/{builds}/{test_run}/'

    for data in iter_result_pages(url):
        prefixes = data.get('prefixes')
        if prefixes:
            return prefixes[0]

def download_meta(path: str, binary: bool = False):
    print(f'Downloading `{path}`')

    req_url = f'{DOWNLOAD_BASE_URL}/{path}'
    resp = requests.get(
        url=req_url, headers={"Content-Type": "application/json"})

    if not binary:
        return resp.text
    return resp.content

def are_results_compound(prefixes: List[str]):
    return len(prefixes) == 1

def datetime_from_str(s: str):
    return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')

def merge_results(metas, filter=None):
    earliest_dt = datetime.now()
    projects = defaultdict(lambda: {'results': defaultdict(lambda: [])})

    for meta in metas:
        try:
            dt = datetime_from_str(meta['date'])
            if dt < earliest_dt:
                earliest_dt = dt

            results = projects[meta['project']]['results']

            if filter is not None:
                if not filter(meta):
                    continue

            # This is a rather incomplete list, but it should do the job
            results['board'].append(meta['board'])
            results['toolchain'].append(meta['toolchain'])
            results['runtime'].append(meta['runtime'])
            results['resources'].append(meta['resources'])
            results['maximum_memory_use'].append(meta['maximum_memory_use'])
            results['max_freq'].append(meta['max_freq'])
            results['device'].append(meta['device'])

        except KeyError as e:
            print(f'Skipping a meta file because of {e}')

    for project in projects.values():
        project['date'] = \
            f'{earliest_dt.year}-{earliest_dt.month}-{earliest_dt.day}T' \
            f'{earliest_dt.hour}:{earliest_dt.minute}:{earliest_dt.second}'

    return projects

def get_legacy_metas(gcs_paths: list, test_no: int):
    for path in gcs_paths:
        try:
            meta_json = download_meta(path)
        except requests.exceptions.ConnectionError as e:
            print(f'ERROR: failed to download {path}: {e}')
            continue
        meta: dict
        try:
            meta = json.loads(meta_json)
        except json.decoder.JSONDecodeError:
            # Yes this has actually happened once for some reason
            print('ERROR: CAN\'T DECODE THE JSON FROM GCS')
            with open(f'faulty_json-{test_no}.json', 'w') as f:
                f.write(meta_json)
            continue
        yield meta

def download_and_merge_legacy(gcs_paths: list, test_no: int):
    def accept_generic_all_build_only(meta):
        return meta['build_type'] == 'generic-all' and meta['build'] == '000'

    metas = get_legacy_metas(gcs_paths, test_no)
    merged = merge_results(metas, filter=accept_generic_all_build_only)
    return merged

def download_and_split_compound(gcs_compound_path: str):
    meta_json_gz = download_meta(gcs_compound_path, binary=True)
    meta_json = gzip.decompress(meta_json_gz).decode()
    meta = json.loads(meta_json)

    projects = defaultdict(lambda: {'results': defaultdict(lambda: [])})

    meta_results = meta['results']
    zipped = zip(meta_results['board'], meta_results['project'],
                 meta_results['toolchain'], meta_results['runtime'],
                 meta_results['resources'], meta_results['maximum_memory_use'],
                 meta_results['max_freq'], meta_results['device'],
                 meta_results['wirelength'])

    for board, project, toolchain, runtime, resources, maximum_mem_use, \
            max_freq, device, wirelength in zipped:

        project_res = projects[project]['results']
        project_res['board'].append(board)
        project_res['toolchain'].append(toolchain)
        project_res['runtime'].append(runtime)
        project_res['resources'].append(resources)
        project_res['maximum_memory_use'].append(maximum_mem_use)
        project_res['max_freq'].append(max_freq)
        project_res['device'].append(device)
        project_res['wirelength'].append(wirelength)

    for project in projects.values():
        project['date'] = meta['date']

    return projects

def get_test_run_numbers(start: int, end: str, builds: str):
    url = f'{STORAGE_API_AT}?delimiter=/&prefix={TESTRES_PREFIX}/{builds}/'

    for data in iter_result_pages(url):
        for prefix in data['prefixes']:
            no = int(prefix.split('/')[-2])
            if no >= start and (end == '_' or no <= int(end)):
                yield no

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

def get_download_specs(test_info):
    test_no = test_info['test_no']
    builds = test_info['builds']

    print(f'Preparing downloads for test {test_no}')
    gcs_compound_path = None
    gcs_paths = None
    try:
        gcs_compound_path = get_compound_result_file_path(test_no, builds)
    except Exception as e:
        print(
            f'Failed to fetch patches for test run no. {test_no}, cause: {e}')
        return None

    if gcs_compound_path:
        return dict(test_no=test_no, paths=gcs_compound_path, compound=True)

    return None

def download_from_specs(specs):
    test_no = specs['test_no']
    if specs['compound']:
        merged = download_and_split_compound(specs['paths'])
    else:
        merged = download_and_merge_legacy(specs['paths'], test_no)

    for project_name, merged_data in merged.items():
        project_dir = os.path.join(specs['output_dir'], project_name)
        out_filename = os.path.join(project_dir, f'meta-{test_no}.json')
        os.makedirs(project_dir, exist_ok=True)
        merged_json = json.dumps(merged_data, indent=4)
        with open(out_filename, 'w') as f:
            f.write(merged_json)

    print(f'Downloaded test no. {test_no}')

def main():
    parser = ArgumentParser()
    parser.add_argument(
        'builds', type=str, help='Builds type (e.g. `nightly`)')
    parser.add_argument('from_tr', type=int, help='First test run number')
    parser.add_argument(
        'to_tr', type=str, help='Last test run number (use `_` for "latest")')
    parser.add_argument(
        'output_dir', type=str, help='Output directory for downloaded data')
    parser.add_argument(
        '--pool-size', type=int, default=8, help='Size of thread pool')
    args = parser.parse_args()

    if not os.path.isdir(args.output_dir):
        print('ERROR: Output path is not a directory!')
        exit(-1)

    print(f'Using {args.pool_size} parallel threads.')
    pool = ThreadPool(args.pool_size)
    test_numbers = list(
        get_test_run_numbers(args.from_tr, args.to_tr, args.builds))

    print('Preparing downloads ...', flush=True)
    tests = [
        dict(test_no=test_no, builds=args.builds) for test_no in test_numbers
    ]
    download_specs = pool.map(get_download_specs, tests)
    download_specs = list(filter(
        None, download_specs))  # remove None resulting from errors

    for specs in download_specs:
        specs['output_dir'] = args.output_dir

    url_count = 0
    for specs in download_specs:
        if not specs['compound']:
            url_count += len(specs['paths'])
        else:
            url_count += 1

    print(f'Downloading {url_count} URLs ...', flush=True)
    results = pool.map(download_from_specs, download_specs)

    print('Done')

if __name__ == "__main__":
    main()


from setuptools import setup, find_packages

install_requires = [
    "redis==5.0.1",
    "typing_extensions==4.8.0",
    "pydantic==2.4.2",
    "pydantic_core==2.10.1",
    "elasticsearch==8.10.0",
    "flask==3.0.0",
    "flask-socketio==5.3.6",
    "pytest==7.4.2",
    "kazoo==2.9.0"
]

setup(
    name='noauth',
    version='0.1.0',
    packages=find_packages(exclude=['tests', 'tests.*']),
    install_requires=install_requires,
    tests_require=[
        'pytest',
    ],
)


import re

from utils.output import ListOutput, ListOutputItem

GREP_PLUGIN_RE = re.compile('\] (.*?).grep\(uri=".*"\) took (.*?)s to run')

def get_grep_plugin_performance(scan_log_filename, scan):
    scan.seek(0)

    grep_plugin_times = {}

    for line in scan:
        match = GREP_PLUGIN_RE.search(line)
        if match:
            plugin_name = match.group(1)
            run_time = float(match.group(2))

            if plugin_name in grep_plugin_times:
                grep_plugin_times[plugin_name] += run_time
            else:
                grep_plugin_times[plugin_name] = run_time

    def sort_by_second(a, b):
        return cmp(b[1], a[1])

    times = grep_plugin_times.items()
    times.sort(sort_by_second)

    times_top_10 = times[:10]
    times_top_10 = sum(total_run_time for plugin_name, total_run_time in times_top_10)

    output = ListOutput('grep_plugin_performance')

    output.append(ListOutputItem('Top10 most time consuming plugins run for (seconds)', times_top_10))

    times = dict(times)
    output.append(ListOutputItem('Plugins run time information (in seconds)', times))

    return output


#！/usr/bin/env python
# _*_ coding:utf-8 _*_
# encoding=utf-8
'''
利用jieba提取高频词并生成图云
'''

import jieba
import jieba.analyse
import codecs
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from collections import Counter
import matplotlib.pyplot as plt
from scipy.misc import imread

def generatet_wordcloud(content):
    path = 'PingFang.ttc'
    bg_pic = imread('/Users/felix_zhao/Downloads/microscope.png')
    img_colors = ImageColorGenerator(bg_pic)
    wordcloud = WordCloud(font_path=path, background_color="white",
                          mask=bg_pic,  # 设置背景图片
                          stopwords=STOPWORDS.add('/Users/felix_zhao/Desktop/stopWord.txt'),
                          max_font_size=100,
                          max_words=100,  # 显示最大词数
                          color_func=img_colors,
                          random_state=42)  # 随机配色方案
    wordcloud = wordcloud.generate(content)
    plt.show(wordcloud.recolor(color_func=img_colors))
    plt.imshow(wordcloud)
    plt.axis('off')
    plt.show()
    wordcloud.to_file('/Users/felix_zhao/Desktop/wordcloud.jpg')

if __name__ == '__main__':
    fr = codecs.open('/Volumes/Transcend/abstract/origin_ab.txt', 'r', encoding='utf-8').read()
    words = jieba.lcut(fr)

    exclude_words = codecs.open('/Users/felix_zhao/Desktop/stopWord.txt', 'r', encoding="utf-8")
    for word in words:
        if word in exclude_words.readlines():
            words.remove(word)
    data = r' '.join(words)
    generatet_wordcloud(data)
    print('已生成图云')

    # 设置停用词
    stopkey = jieba.analyse.set_stop_words('/Users/felix_zhao/Desktop/stopWord.txt')
    print(stopkey)
    # 获取关键词频率
    tags = jieba.analyse.extract_tags(fr, topK=10, withWeight=True)
    for tag in tags:
        print(tag)

    # 获取高频词
    counts = {}
    for word in words:
        if len(word) == 1:
            continue
        else:
            counts[word] = counts.get(word, 0) + 1  # dict.get(key, default=None) get()方法返回指定键的值

    items = list(counts.items())

    items.sort(key=lambda x : x[1], reverse = True)  # key=lambda 元素: 元素[字段索引] 这里表示对元素第二个字段（频次）进行排序
    for i in range(20):
        word, count = items[i]
        # print(word, count)
        print('{0:<10}{1:>5}'.format(word, count))


#! /usr/bin/env python

"""
@author: David Diaz Vico
@license: MIT
"""

import argparse
from sacred.observers import FileStorageObserver

from skdatasets import fetch
from skdatasets.utils.estimator import json2estimator
from skdatasets.utils.experiment import experiment

def main(
    dataset=fetch, estimator=json2estimator, observers=[FileStorageObserver(".results")]
):
    parser = argparse.ArgumentParser(description="Run an experiment.")
    parser.add_argument("-r", "--repository", type=str, help="repository")
    parser.add_argument("-c", "--collection", type=str, default=None, help="collection")
    parser.add_argument("-d", "--dataset", type=str, help="dataset")
    parser.add_argument("-e", "--estimator", type=str, help="estimator")
    args = parser.parse_args()
    e = experiment(dataset, estimator)
    e.observers.extend(observers)
    e.run(
        config_updates={
            "dataset": {
                "repository": args.repository,
                "collection": args.collection,
                "dataset": args.dataset,
            },
            "estimator": {"estimator": args.estimator},
        }
    )

if __name__ == "__main__":
    main()


# Created by zhai at 2018/1/12
# Email: zsp1197@163.com
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from Tools import *
from BeeTools import *
import os
path = '/home/uftp/hubei/ori'
users_list = os.listdir(path)

has_meter=False
has_normal=False

for user in users_list:
    user_path=os.path.join(path,user)
    appliances_list = os.listdir(user_path)
    appliances_list=[appliance for appliance in appliances_list if appliance.split(sep='.')[-1]=='xls']
    print(appliances_list)
    for appliance_file_name in appliances_list:
        if('meter' in appliance_file_name):
            if(not has_meter):
                meter=read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))
                has_meter=True
            else:
                meter=aggregate_with_resample([meter,read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))])
        else:
            if(not has_normal):
                normal=read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))
                has_normal=True
            else:
                normal=aggregate_with_resample([normal,read_xls_fill(filepath=os.path.join(path,user,appliance_file_name))])
    meter.plot(label='meter')
    normal.plot(label='sum of appliances')
    print(user)
    normal_consumption=ps_consumption(normal)
    meter_consumption=ps_consumption(meter)
    print(normal_consumption)
    print(meter_consumption)
    print(normal_consumption/meter_consumption)
    plt.title(user)
    plt.legend()
    # plt.show()
    plt.show(block=False)
print()


import logging
logger = logging.getLogger(__name__)
import json
import zlib
from zipfile import ZipFile
import re

from production import db
from production import utils

def main():
    logging.basicConfig(
        level=logging.INFO,
        format='%(levelname).1s %(module)10.10s:%(lineno)-4d %(message)s')

    conn = db.get_conn()
    cur = conn.cursor()

    legends = {}
    for part_number, part_name in (1, 'initial'), (2, 'teleports'), (3, 'clones'):
        with ZipFile(utils.project_root() / 'tasks' / f'part-{part_number}-{part_name}.zip') as z:
            with z.open(f'part-{part_number}-legend.txt') as fin:
                for line in fin:
                    name, legend = line.decode().split(' - ', maxsplit=1)
                    legends[name] = legend.rstrip()

            for filename in z.namelist():
                if filename.endswith('-legend.txt'):
                    continue
                m = re.match(r'(prob-\d{3}).desc$', filename)
                assert m, filename
                name = m.group(1)

                with z.open(filename, 'r') as fin:
                    task = fin.read().decode()

                data = zlib.compress(task.encode())
                extra = dict(legend=legends[name])

                cur.execute('''
                    INSERT INTO tasks(
                        name, data, extra, invocation_id, time)
                    VALUES (%s, %s, %s, %s, NOW())
                    ON CONFLICT DO NOTHING
                    RETURNING id
                    ''',
                    [name, data, json.dumps(extra), db.get_this_invocation_id(conn)])
                res = cur.fetchall()
                if res:
                    [[task_id]] = res
                    logger.info(f'Uploaded {name!r} as /task/{task_id}')
                else:
                    logger.info(f'Task {name!r} already exists')

    db.record_this_invocation(conn, status=db.Stopped())
    conn.commit()

if __name__ == '__main__':
    main()


from typing import List

# 높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라.
inputValue = [0,1,0,2,1,0,1,3,2,1,2,1]
# inputValue = [1,2,1,2,3,1,0,2]

# => 6

def trap(self, height: List[int]) -> int:
    if not height:
        return 0

    volume = 0
    # 인덱스
    left, right = 0, len(height) - 1
    # 최대 길이 = 현재 위치 길이
    left_max, right_max = height[left], height[right]

    while left < right:
        # 현재 위치 길이 vs 최대 길이
        left_max, right_max = max(height[left], left_max), max(height[right], right_max)
        # 더 높은 쪽을 향해 투 포인터 이동
        if left_max <= right_max:
            volume += left_max - height[left]
            left += 1
        else:
            volume += right_max - height[right]
            right -= 1
    print(left_max,right_max)
    return volume

def trap2(self, height: List[int]) -> int:
    stack = []
    volume = 0
    for i in range(len(height)):
        print(inputValue)
        print(i,'>>','stack',stack)
        print(i,'>>','현재위치의 높이:',height[i])

        # 변곡점을 만나는 경우 (현재 위치의 높이가 이전 위치의 높이보다 크면 이전 위치를 꺼내어 탑으로 둔다.)
        while stack and height[i] > height[stack[-1]]:
            print(i,'>>','현재위치의 높이:',height[i],'height[stack[-1]]:', height[stack[-1]])
            # 스택에서 꺼낸다.
            top = stack.pop()
            print(i,'>>','top:',top)
            print(i,'>>','length',len(stack))
            if not len(stack):
                break

            # 이전과의 차이만큼 물 높이 처리
            distance = i - stack[-1] - 1
            print(i,'>>','distance:',distance)
            # 지금 높이? 이전이전 높이? - 최고높이
            print(i,'>>','현재위치의 높이:',height[i],'height[stack[-1]]:', height[stack[-1]],'height[top]:', height[top])
            waters = min(height[i], height[stack[-1]]) - height[top]

            volume += distance * waters

        stack.append(i)
    return volume

print(trap2('',inputValue))


from controller.reroute import reset
from spoofer.spoof import spoofed
from utils.debug import dbg, WARNING, SUCCESS, INFO

def spoofer_reset():
    if len(spoofed) > 0:
        dbg("Resetting routing..", WARNING)

        for item in spoofed:
            src = spoofed[item]['info'][0]
            dest = spoofed[item]['info'][1]
            reset(src, dest)
            dbg("Rerouted 'Target: %s > Destination: %s'" % (src, dest), INFO)
            reset(dest, src)
            dbg("Rerouted 'Destination: %s > Target: %s'" % (dest, src), INFO)
        dbg("All done.", SUCCESS)


# @title: Memory management on the device
# @author: Shaurya

from numba import vectorize
import numpy as np
from time import perf_counter

# timeit
def timeit(f):
    def decorate(*args,**kwargs):
        start=perf_counter()
        result=f(*args,**kwargs)
        end=perf_counter()
        try:
            print(f'Time taken to execute {f.__name__}: {end-start}s')
        except AttributeError as e:
            print("GPU bound problem ")
            print(e)
            print('Time taken to execute: %.2fs'%(end-start))
        return result
    return decorate

@timeit
@vectorize(['float32(float32,float32)'],target='cuda')
def add_ufunc(x,y):
    return x+y

n=1000000
x=np.arange(n).astype(np.float32)
y=2*x
add_ufunc(x,y)

# Numba can create its own GPU array object but not as fully fledged as a Cupy array
from numba import cuda
x_device=cuda.to_device(x)
y_device=cuda.to_device(y)
print(x_device)
print(y_device)
print(x_device.shape)

add_ufunc(x_device,y_device)

# we are still allocating device array for the output and copying
# it back to the CPU
#? define the output buffer
out_device=cuda.device_array(shape=(n,),dtype=np.float32)
out_device.shape
out_device.alloc_size
add_ufunc(x_device,y_device,out=out_device)

# if we want to get it back to the CPU, we can use the copy_to_host() method
out_host=out_device.copy_to_host()
out_host.shape

#! CuPy interoperability
import cupy as cp
x_cp=cp.asarray(x)
y_cp=cp.asarray(y)

out_cp=cp.empty_like(y_cp)
out_cp.shape
y_cp.shape
x_cp.shape

x_cp.__cuda_array_interface__

add_ufunc(x_cp,y_cp,out=out_cp)


import csv
import sys
from bs4 import BeautifulSoup
import urllib,urllib2
import geopy,geopy.distance
from optparse import OptionParser

#get_html return the html code of a given page with adresse: url
def get_html(url):
    request = urllib2.Request(url)
    request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
    request.add_header('Content-Type','')
    response = urllib2.urlopen(request)
    return(response)

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                          help="write report to FILE", metavar="FILE")

(options, args) = parser.parse_args()
filename=options.filename
rootname=filename.split('.')[0]

f = open(filename, 'r')
csvfile=csv.reader(f)
header=csvfile.next()
output="nautical distance,country,port,long,lat\n"

#while True:
#    try:
#        geolocator = geopy.Nominatim()
#        location = geolocator.geocode("Trieste")
#        break
#    except:
#        pass
#
#print("Trieste:"+str(location.latitude)+","+str( location.longitude)+"\n")
#trieste=(location.latitude,location.longitude)
#output=output+"trieste"+","+str(location.latitude)+","+str( location.longitude)+","+"0"+"\n"

for row in csvfile:
    place=""
    if(row[2]==""):
        place=row[1]
    else:
        place=row[2]

    print(place)
    while True:
        try:
            geolocator = geopy.Nominatim()
            location = geolocator.geocode(place)
            print("here")
            break
        except :
            e = sys.exc_info()[0]
            if e == geopy.exc.GeocoderQueryError:
                break
            print("fail"+str(e))
            pass
    if(location is not None ):
        cur=(location.latitude,location.longitude)
        #dist=geopy.distance.vincenty(trieste,cur)
        #print("distance:"+str(dist))
        output=output+row[0]+",\""+row[1]+"\",\""+row[2]+"\","+str(location.latitude)+","+str( location.longitude)+"\n"

of = open(""+rootname+"-loc.csv", 'w')
of.write(output)
of.close


from django.shortcuts import render
import tensorflow as tf
from numpy import *
import base64
from PIL import Image, ImageFilter
from django.http import JsonResponse
import pandas as pd

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.optimizers import Adam
from keras.utils import np_utils

#for image compare
from skimage import measure
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
import random
from pathlib import Path
from resizeimage import resizeimage

# Create your views here.

def refresh_model(request):
    train_data = pd.read_csv('train.csv')
    test_data = pd.read_csv('test.csv')
    y_train  = train_data.iloc[:, 0].values
    x_train = train_data.iloc[:, 1:].values
    x_train = x_train.reshape(len(x_train), 32, 32)
    y_test  = test_data.iloc[:, 0].values
    x_test = test_data.iloc[:, 1:].values
    x_test = x_test.reshape(len(x_test), 32, 32)
    x_train = tf.keras.utils.normalize(x_train, axis = 1)
    x_test = tf.keras.utils.normalize(x_test, axis = 1)
    x_train = x_train.reshape(len(x_train), 32, 32, 1)
    x_test = x_test.reshape(len(x_test), 32, 32, 1)

    number_of_classes = 46
    y_train = np_utils.to_categorical(y_train, number_of_classes)
    y_test = np_utils.to_categorical(y_test, number_of_classes)
    model = Sequential()
    model.add(Conv2D(32, (5, 5), input_shape=(x_train.shape[1], x_train.shape[2], 1), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Conv2D(32, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(number_of_classes, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])
    model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=10, batch_size=200)
    model.save('nepali_character_recognition_model.h5')
    return JsonResponse({'result': "Model refreshed successfully."})

def show_main_page(request):
        context = {
        "title": "DIGIT RECOGNITION APP"
        }
        return render(request, 'main_app/index.html', context)

def predict_digit(request):
        result = list(request.POST.keys())

        if(request.method == 'POST'):
                character_recognition_model = tf.keras.models.load_model('nepali_character_recognition_model.h5')
                data = result[0][22:]
                img = base64.b64decode(data)

                fh = open("png_image.png", "wb")
                fh.write(img)
                fh.close()
                #print("Success: PNG image of canvas created.")

                im = Image.open("png_image.png")
                rgb_im = im.convert('RGB')
                rgb_im.save('jpg_image.jpg')
                #print("Success: PNG image converted to RGB.")

                im=Image.open('jpg_image.jpg')
                img = array(im.resize((32, 32), Image.ANTIALIAS).convert("L"))
                data = img.reshape([1, 1024])
                data = (data/255)
                data = reshape(data, (32, 32))

                data = data.reshape(1, 32, 32, 1)
                #print(data)
                #print("Success: Data generated form RGB image.")

                predictions = character_recognition_model.predict(data)
                prediction = argmax(predictions[0])

                top_two_predictions = np.argpartition(predictions[0], -2)[-2:]
                first_prediction = str(top_two_predictions[1])
                second_prediction = str(top_two_predictions[1])
                print(top_two_predictions)

                # start image compare ================================================================================================================================================================================

                #retrieving the canvas image-------------------------------------------------------------
                #converting canvas img to 32 by 32 bit (size of training dataset)
                with open('jpg_image.jpg', 'r+b') as f:
                        with Image.open(f) as image:
                                cover = resizeimage.resize_cover(image, [32, 32])
                                cover.save('user_image.png', image.format)

                user_image = cv2.imread("user_image.png")
                user_image = cv2.cvtColor(user_image, cv2.COLOR_BGR2GRAY)
                cv2.imwrite('C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Temp\\canvas_image.png', user_image)
                #---------------------------------------------------------------------------------------

                # prediction.item() contains the character label predicted by the model
                print("==============================================================================================================================")
                print("Model prediction: " + first_prediction)
                similarity = image_compare(first_prediction)
                print('probability: ' + str(predictions[0][int(first_prediction)]))
                print("==============================================================================================================================")
                # end image compare=========================================================================================================================================================

                return JsonResponse({'result': first_prediction, 'probability': str(predictions[0][int(first_prediction)]), 'similarity': similarity})

def train_model(request):
        character_recognition_model = tf.keras.models.load_model('nepali_character_recognition_model.h5')
        canvas_data = uint8(request.POST.get('canvas_data'))

        im=Image.open('colors.jpg')
        img = array(im.resize((32, 32), Image.ANTIALIAS).convert("L"))
        data = img.reshape([1, 1024])
        data = (data/255)
        data = reshape(data, (32, 32))
        data = data.reshape(1, 32, 32, 1)
        number_of_classes = 46
        canvas_data = canvas_data.reshape(1, 1)
        canvas_data = np_utils.to_categorical(canvas_data, number_of_classes)
        print(canvas_data.shape)
        character_recognition_model.fit( data, canvas_data, epochs = 1)
        character_recognition_model.save('nepali_character_recognition_model.h5')
        print("SUCCESS: model fit.")
        return JsonResponse({'result':"Model Trained"})

def image_compare(prediction):
    # retrieving the image of that predicted character from the train dataset------
    p = 'C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Test' + '\\' + prediction
    path = Path(p)
    files = os.listdir(path)
    index = random.randrange(0, len(files))
    avg_similarity = 0

    for i in range(0, len(files)):
        predicted_character_image = cv2.imread("Test\\" + prediction + "\\" + files[i])
        predicted_character_image = cv2.cvtColor(predicted_character_image, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Temp\\original_image.png', predicted_character_image)

    # predicted_character_image = cv2.imread("Test\\" + prediction + "\\" + files[index])
    # predicted_character_image = cv2.cvtColor(predicted_character_image, cv2.COLOR_BGR2GRAY)
    # cv2.imwrite('C:\\Users\\pjmes\\Desktop\\Nepali-character-recognition-application\\Temp\\original_image.png', predicted_character_image)
    # #------------------------------------------------------------------------

        original = cv2.imread("Temp\\original_image.png")
        image_to_compare = cv2.imread("Temp\\canvas_image.png")

        # 1) Check if 2 images are equals
        if original.shape == image_to_compare.shape:
            # print("The images have same size and channels")
            difference = cv2.subtract(original, image_to_compare)
            b, g, r = cv2.split(difference)

        # 2) Check for similarities between the 2 images
        sift = cv2.xfeatures2d.SIFT_create()
        kp_1, desc_1 = sift.detectAndCompute(original, None)
        kp_2, desc_2 = sift.detectAndCompute(image_to_compare, None)

        index_params = dict(algorithm=0, trees=5)
        search_params = dict()
        flann = cv2.FlannBasedMatcher(index_params, search_params)

        matches = flann.knnMatch(desc_1, desc_2, k=2)

        good_points = []
        for m, n in matches:
            if m.distance < 0.75*n.distance:
                good_points.append(m)

        # Define how similar they are
        number_keypoints = 0
        if len(kp_1) <= len(kp_2):
            number_keypoints = len(kp_1)
        else:
            number_keypoints = len(kp_2)

        print("Similarity: ", len(good_points) / number_keypoints * 100)

        similarity = len(good_points) / number_keypoints * 100
        result = cv2.drawMatches(original, kp_1, image_to_compare, kp_2, good_points, None)
        cv2.imwrite("Temp\\feature_matching_"+str(i)+".jpg", result)
        avg_similarity = avg_similarity + similarity

    avg_similarity = avg_similarity/len(files)
    print("average_similarity: " + str(avg_similarity))
    return avg_similarity


import socket
import protocols
import json
import getopt
import sys

class Client:
    MIN_PLAYERS = 1
    MAX_PLAYERS = 4
    MIN_STAGES = 1
    MAX_STAGES = 10
    NO_NAME = ""
    DEFAULT_IP = '127.0.0.1'
    DEFAULT_PORT = 8080

    def __init__(self, number_of_players, number_of_stages, player_name, server_hostname, server_port):
        self.number_of_players = number_of_players
        self.number_of_stages = number_of_stages
        self.player_name = player_name
        self.my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.my_socket.connect((server_hostname, server_port))
        self.end = False

    def send_join_message(self):
        message = {"header": protocols.JOIN, "name": self.player_name}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_welcome_message(self, message):
        menu = message["menu"]
        options_range = message["options range"]
        print("{}".format(menu))
        print("options range: {}".format(options_range))
        self.send_server_option()

    @staticmethod
    def choose_options():
        correct_input = False
        option = None
        while not correct_input:
            try:
                user_input = int(input("Choose an option: "))
                if user_input == 1:
                    option = 1
                    correct_input = True
                    print("You created a new game")
                elif user_input == 2:
                    option = 2
                    correct_input = True
                elif user_input == 3:
                    option = 3
                    correct_input = True
                    print("You exit from the server")
                else:
                    print("This option is not valid. You must choose 1, 2 or 3")
            except ValueError:
                print("This option is not valid. You must choose 1, 2 or 3")
        return option

    def send_server_option(self):
        message = {"header": protocols.SEND_SERVER_OPTION, "option": self.choose_options(),
                   "number of players": self.number_of_players, "number of stages": self.number_of_stages}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_choose_character(self, message):
        menu = message["menu"]
        options_range = message["options range"]
        print("{}".format(menu))
        print("options range: {}".format(options_range))
        self.send_character()

    @staticmethod
    def choose_characters():
        correct_input = False
        option = None
        while not correct_input:
            try:
                user_input = int(input("Choose one character to play: "))
                if user_input == 1:
                    correct_input = True
                    option = 1
                    print("Your character is Bookworm")
                elif user_input == 2:
                    correct_input = True
                    option = 2
                    print("Your character is Worker")
                elif user_input == 3:
                    correct_input = True
                    option = 3
                    print("Your character is Procrastinator")
                elif user_input == 4:
                    correct_input = True
                    option = 4
                    print("Your character is Whatsapper")
                else:
                    print("This is an invalid option")
            except ValueError:
                print("This is an invalid option")
        return option

    def send_character(self):
        message = {"header": protocols.SEND_CHARACTER, "option": self.choose_characters()}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_send_games(self, message):
        available_games = message["games list"]
        games_id = message["games id"]
        print("\t\t\t--- SERVER GAME LIST ---")
        print("{}".format(available_games))
        print("options range: {}".format(games_id))
        self.send_game_choice()

    def choose_game(self):
        try:
            user_input = int(input("Choose a game: "))
            return user_input
        except ValueError:
            print("This option is not valid. You will exit from the server.")
            self.end = True

    def send_game_choice(self):
        message = {"header": protocols.SEND_GAME_CHOICE, "game id": self.choose_game()}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_send_valid_game(self, message):
        joined = message["joined"]
        if joined:
            print("joined: {}".format(joined))
        if not joined:
            print("The game you tried to join is full.")
            self.end = True

    @staticmethod
    def control_server_message(message):
        msg = message["message"]
        print(msg)

    def control_your_turn_message(self, message):
        msg = message["message"]
        options_range = message["options range"]
        print("{}".format(msg))
        print("options range: {}".format(options_range))
        self.send_character_command()

    @staticmethod
    def choose_command():
        correct_input = False
        user_input = ""
        while not correct_input:
            user_input = input()
            if user_input == 'a':
                correct_input = True
            elif user_input == 's':
                correct_input = True
            else:
                print("The character is not valid. Please, enter 'a' to attack or 's' to use your skill")
        return user_input

    def send_character_command(self):
        message = {"header": protocols.SEND_CHARACTER_COMMAND, "command": self.choose_command()}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_send_end_game_message(self, message):
        win = message["win"]
        if win:
            print("***************************************************************************")
            print("\t\tAll enemies have been defeated. You won!")
            print("***************************************************************************")
        else:
            print("***************************************************************************")
            print("\t\tAll players have been defeated. Try again")
            print("***************************************************************************")
        self.end = True

    def control_send_dc_server(self, message):
        reason = message["reason"]
        print(reason)
        self.end = True

    def send_dc_me(self):
        message = {"header": protocols.SEND_DC_ME}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())

    def control_message(self, message):
        header = message["header"]
        print("{} message received".format(header))
        if header == protocols.WELCOME:
            self.control_welcome_message(message)
        elif header == protocols.CHOOSE_CHARACTER:
            self.control_choose_character(message)
        elif header == protocols.SEND_GAMES:
            self.control_send_games(message)
        elif header == protocols.SEND_VALID_GAME:
            self.control_send_valid_game(message)
        elif header == protocols.SERVER_MSG:
            self.control_server_message(message)
        elif header == protocols.YOUR_TURN:
            self.control_your_turn_message(message)
        elif header == protocols.SEND_END_GAME:
            self.control_send_end_game_message(message)
        elif header == protocols.SEND_DC_SERVER:
            self.control_send_dc_server(message)
        else:
            print("Invalid message received")

    def start(self):
        name = self.player_name
        message = {"header": protocols.JOIN, "name": name}
        protocols.send_one_message(self.my_socket, json.dumps(message).encode())
        while not self.end:
            try:
                buffer = protocols.recv_one_message(self.my_socket)
                message = json.loads(buffer.decode())
                self.control_message(message)
            except TypeError:
                self.end = True
                print("Server was disconnected")
            except KeyboardInterrupt:
                self.end = True
                self.send_dc_me()
        self.my_socket.close()

class ArgsError(Exception):
    def __init__(self, msg):
        super().__init__("Error: {}".format(msg))

def parse_args():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "p:s:n:i:o:", ["players=", "stages=", "name=", "ip=", "port="])
    except getopt.GetoptError:
        raise ArgsError("You enter wrong arguments. Finishing program")

    number_of_players = Client.MIN_PLAYERS
    number_of_stages = Client.MIN_STAGES
    ip_address = Client.DEFAULT_IP
    port_address = Client.DEFAULT_PORT
    player_name = Client.NO_NAME
    try:
        for o, a in opts:
            if o in ("-p", "--players"):
                number_of_players = int(a)
            if o in ("-s", "--stages"):
                number_of_stages = int(a)
            if o in ("-n", "--name"):
                player_name = str(a)
            if o in ("-i", "--ip"):
                ip_address = str(a)
            if o in ("-o", "--port"):
                port_address = int(a)
    except ValueError:
        raise ArgsError("Type of arguments is wrong. Finishing program")
    return number_of_players, number_of_stages, player_name, ip_address, port_address

if __name__ == '__main__':
    try:
        players, stages, nick, ip, port = parse_args()
        if (players < Client.MIN_PLAYERS or players > Client.MAX_PLAYERS) and \
                (Client.MIN_STAGES <= stages <= Client.MAX_STAGES):
            raise ArgsError("The number of players must be between 1 and 4. Finishing program")
        elif (Client.MIN_PLAYERS <= players <= Client.MAX_PLAYERS) and \
                (stages < Client.MIN_STAGES or stages > Client.MAX_STAGES):
            raise ArgsError("The number of stages must be between 1 and 10. Finishing program")
        elif (players < Client.MIN_PLAYERS or players > Client.MAX_PLAYERS) and \
                (stages < Client.MIN_STAGES or stages > Client.MAX_STAGES):
            raise ArgsError("The number of players must be between 1 and 4. "
                            "The number of stages must be between 1 and 10. Finishing program")
        elif nick == Client.NO_NAME:
            raise ArgsError("You must introduce a name for the player. Finishing program")
        client = Client(players, stages, nick, ip, port)
        client.start()
    except ArgsError as err:
        print(err)
    except KeyboardInterrupt:
        print("Client closed by CTRL+C")
    except ConnectionRefusedError:
        print("This server is not connected. Try again")


import mock
import pytest

from paasta_tools import firewall_logging

@mock.patch.object(firewall_logging, "lookup_service_instance_by_ip")
def test_syslog_to_paasta_log(mock_lookup_service_instance_by_ip, mock_log):
    syslog_data = fake_syslog_data("my-hostname", SRC="1.2.3.4")
    mock_lookup_service_instance_by_ip.return_value = ("myservice", "myinstance")

    firewall_logging.syslog_to_paasta_log(syslog_data, "my-cluster")

    assert mock_log.mock_calls == [
        mock.call(
            service="myservice",
            component="security",
            level="debug",
            cluster="my-cluster",
            instance="myinstance",
            line="my-hostname: my-prefix IN=docker0 SRC=1.2.3.4",
        )
    ]

@mock.patch.object(firewall_logging, "lookup_service_instance_by_ip")
def test_syslog_to_paasta_log_no_container(
    mock_lookup_service_instance_by_ip, mock_log
):
    syslog_data = fake_syslog_data("my-hostname", SRC="1.2.3.4")
    mock_lookup_service_instance_by_ip.return_value = (None, None)
    firewall_logging.syslog_to_paasta_log(syslog_data, "my-cluster")
    assert mock_log.mock_calls == []

def test_parse_syslog_undecodable():
    assert (
        firewall_logging.parse_syslog(b"<4>Jun  6 07:52:38 myhost \xba~\xa6r") is None
    )

@pytest.mark.parametrize(
    "syslog_data",
    [
        "<4>Jun  6 07:52:38 myhost someothermessage: hello world",
        "<4>Jun  6 07:52:38 myhost kernel: hello world",
        "<4>Jun  6 07:52:38 myhost kernel [0.0]: hello world",
    ],
)
@mock.patch.object(firewall_logging, "lookup_service_instance_by_ip")
def test_syslog_to_paasta_log_bad_message(
    mock_lookup_service_instance_by_ip, syslog_data, mock_log
):
    firewall_logging.syslog_to_paasta_log(syslog_data.encode(), "my-cluster")
    assert mock_lookup_service_instance_by_ip.mock_calls == []
    assert mock_log.mock_calls == []

@mock.patch.object(
    firewall_logging,
    "services_running_here",
    return_value=[
        ("service1", "instance1", "00:00:00:00:00", "1.1.1.1"),
        ("service1", "instance2", "00:00:00:00:00", "2.2.2.2"),
    ],
)
@mock.patch.object(firewall_logging, "log")
def test_lookup_service_instance_by_ip(my_mock_log, mock_services_running_here):
    assert firewall_logging.lookup_service_instance_by_ip("1.1.1.1") == (
        "service1",
        "instance1",
    )
    assert firewall_logging.lookup_service_instance_by_ip("2.2.2.2") == (
        "service1",
        "instance2",
    )
    assert firewall_logging.lookup_service_instance_by_ip("3.3.3.3") == (None, None)
    assert my_mock_log.info.mock_calls == [
        mock.call("Unable to find container for ip 3.3.3.3")
    ]

def test_parse_args():
    assert firewall_logging.parse_args([]).listen_host == "127.0.0.1"
    assert firewall_logging.parse_args([]).listen_port == 1516
    assert firewall_logging.parse_args([]).verbose is False
    assert firewall_logging.parse_args(["-v"]).verbose is True
    assert firewall_logging.parse_args(["-p", "1234"]).listen_port == 1234
    assert firewall_logging.parse_args(["-l", "0.0.0.0"]).listen_host == "0.0.0.0"

@mock.patch.object(firewall_logging, "logging")
def test_setup_logging(logging_mock):
    firewall_logging.setup_logging(True)
    assert logging_mock.basicConfig.mock_calls == [mock.call(level=logging_mock.DEBUG)]

@mock.patch.object(firewall_logging, "MultiUDPServer")
def test_run_server(udpserver_mock):
    firewall_logging.run_server("myhost", 1234)
    assert udpserver_mock.mock_calls == [
        mock.call(("myhost", 1234), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
    ]

@mock.patch.object(firewall_logging, "logging")
@mock.patch.object(firewall_logging, "MultiUDPServer")
@mock.patch.object(firewall_logging, "signal")
def test_main_single_worker(signal_mock, udpserver_mock, logging_mock):
    firewall_logging.main(["-w", "1"])
    assert logging_mock.basicConfig.mock_calls == [
        mock.call(level=logging_mock.WARNING)
    ]
    assert udpserver_mock.mock_calls == [
        mock.call(("127.0.0.1", 1516), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
    ]

@mock.patch.object(firewall_logging, "logging")
@mock.patch.object(firewall_logging, "MultiUDPServer")
@mock.patch.object(firewall_logging.os, "fork", return_value=0)
@mock.patch.object(firewall_logging, "signal")
def test_main_two_workers(signal_mock, fork_mock, udpserver_mock, logging_mock):
    firewall_logging.main(["-w", "2"])
    assert logging_mock.basicConfig.mock_calls == [
        mock.call(level=logging_mock.WARNING)
    ]
    assert udpserver_mock.mock_calls == [
        mock.call(("127.0.0.1", 1516), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
        mock.call(("127.0.0.1", 1516), firewall_logging.SyslogUDPHandler),
        mock.call().serve_forever(),
    ]

def fake_syslog_data(hostname, **kwargs):
    prefix = (
        f"<4>Jun  6 07:52:38 {hostname} kernel: [2736265.340132] my-prefix IN=docker0 "
    )
    fields_str = " ".join(map("=".join, kwargs.items()))
    return (prefix + fields_str + " \n").encode()

@pytest.yield_fixture
def mock_log():
    with mock.patch.object(firewall_logging, "_log", autospec=True) as mock_log:
        yield mock_log


from kivy.uix.screenmanager import Screen
from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.toolbar import MDToolbar
from kivymd.icon_definitions import md_icons
from kivymd.uix.button import MDFillRoundFlatButton
from kivymd.uix.label import MDLabel
from kivymd.uix.textfield.textfield import MDTextField

class IMCApp(MDApp):
    def calcul_IMC(self, args) -> None:
        self.weightTextField.text = self.weightTextField.text.replace(',','.')
        self.heightTextField.text = self.heightTextField.text.replace(',','.')

        try:
            weight = float(self.weightTextField.text)
            height = float(self.heightTextField.text)
            imc = round(weight / (height**2), 2)
            comment = ""
            if imc < 18.5:
                comment = "Insuffisance pondérale"
            elif imc < 25:
                comment = "Corpulence normale"
            elif imc < 30:
                comment = "Surpoids"
            elif imc < 35:
                comment = "Obésité modérée"
            elif imc < 40:
                comment = "Obésité sévère"
            else:
                comment = "Obésité morbide"

            self.labelIMC.text = f"Votre IMC est de : {str(imc)}\n {comment}"
        except:
            pass

    def resetFields(self) -> None:
        self.weightTextField.text = ""
        self.heightTextField.text = ""
        self.labelIMC.text = "Remplissez les champs et cliquez sur le bouton ;)"

    def build(self):
        screen = Screen()

        # Top Toolbar
        self.toolbar = MDToolbar(title="Calcultateur d'IMC")
        self.toolbar.pos_hint = {"top": 1}
        self.toolbar.right_action_items= [
            ["rotate-3d-variant", lambda _: self.resetFields()]
        ]
        screen.add_widget(self.toolbar)

        # Bouton calculer IMC
        self.calculateIMCButton = MDFillRoundFlatButton(
            text="Calculer mon IMC...",
            pos_hint={"center_x": 0.5, "center_y": 0.2},
            on_press=self.calcul_IMC
        )
        screen.add_widget(self.calculateIMCButton)

        # champ de texte poids
        self.weightTextField = MDTextField(
            hint_text="Entrer votre poids (kg)",
            halign="center",
            pos_hint={"center_x": 0.5, "center_y": 0.4},
            icon_right="scale",
            required = True,
            size_hint = (.8, 1)
        )
        screen.add_widget(self.weightTextField)

        # champ de texte taille
        self.heightTextField = MDTextField(
            hint_text="Entrer votre taille (m)",
            halign="center",
            pos_hint={"center_x": 0.5, "center_y": 0.6},
            icon_right="arrow-expand-vertical",
            required = True,
            size_hint = (.8, 1)
        )
        screen.add_widget(self.heightTextField)

        # label résultat IMC
        self.labelIMC = MDLabel(
            text="Remplissez les champs et cliquez sur le bouton ;)",
            pos_hint={"center_x": 0.5, "center_y": 0.8},
            halign="center",
            size_hint =(.8, 1)
        )
        screen.add_widget(self.labelIMC)

        return screen

IMCApp().run()


import os
import argparse

from tqdm import tqdm
from PIL import Image

def prepreprocess(src_path, result_path, upscale_factor):
    src_path_list = os.listdir(src_path)
    for file_name in tqdm(src_path_list):
        image = Image.open(os.path.join(src_path, file_name)).convert('RGB')
        image_w, image_h = image.size
        image_size = (int(image_w / upscale_factor), int(image_h / upscale_factor))
        image = image.resize(image_size, Image.BICUBIC)
        image.save(os.path.join(result_path, file_name))

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='prepreprocess script')
    parser.add_argument('--src_path', default='./datasets/Set5/', type=str,
                    help='path of source image files')
    parser.add_argument('--result_path', default='./datasets/Set5_X2/', type=str,
                    help='path of output ')
    parser.add_argument('--upscale_factor', default=2, type=int,
                    help='upscale_factor')
    args = parser.parse_args()

    if not os.path.exists(args.src_path):
        print("---", "ERROR! the input path is not exist", "---")
        exit(-1)
    if not os.path.exists(args.result_path):
        os.makedirs(args.result_path)

    prepreprocess(args.src_path, args.result_path, args.upscale_factor)


import streamlit as st
import time
import numpy as np
import pandas as pd

def yes_or_no_q(question):
    '''질문에 대한 답을 리턴해줍니다.'''
    answer = st.radio(question, ['네', '아니요'])
    if answer == '네':
        return 1
    elif answer == '아니요':
        return 0

def question(placeholder):

    # 초기 설정
    base_df = pd.DataFrame(columns = ['BMI', 'Smoking', 'AlcoholDrinking', 'Stroke',
                                    'PhysicalHealth', 'MentalHealth', 'DiffWalking', 'Sex',
                                    'PhysicalActivity', 'SleepTime', 'Asthma', 'KidneyDisease',
                                    'SkinCancer', 'AgeCategory_1824', 'AgeCategory_2529',
                                    'AgeCategory_3034', 'AgeCategory_3539', 'AgeCategory_4044',
                                    'AgeCategory_4549', 'AgeCategory_5054', 'AgeCategory_5559',
                                    'AgeCategory_6064', 'AgeCategory_6569', 'AgeCategory_7074',
                                    'AgeCategory_7579', 'AgeCategory_80orolder',
                                    'Race_AmericanIndianAlaskanNative', 'Race_Asian', 'Race_Black',
                                    'Race_Hispanic', 'Race_Other', 'Race_White', 'GenHealth_Excellent',
                                    'GenHealth_Fair', 'GenHealth_Good', 'GenHealth_Poor',
                                    'GenHealth_Verygood', 'Diabetic_No', 'Diabetic_Noborderlinediabetes',
                                    'Diabetic_Yes', 'Diabetic_Yesduringpregnancy'])

    base_df.loc[0, ['AgeCategory_1824', 'AgeCategory_2529',
                    'AgeCategory_3034', 'AgeCategory_3539', 'AgeCategory_4044',
                    'AgeCategory_4549', 'AgeCategory_5054', 'AgeCategory_5559',
                    'AgeCategory_6064', 'AgeCategory_6569', 'AgeCategory_7074',
                    'AgeCategory_7579', 'AgeCategory_80orolder',
                    'Race_AmericanIndianAlaskanNative', 'Race_Asian', 'Race_Black',
                    'Race_Hispanic', 'Race_Other', 'Race_White', 'GenHealth_Excellent',
                    'GenHealth_Fair', 'GenHealth_Good', 'GenHealth_Poor',
                    'GenHealth_Verygood', 'Diabetic_No', 'Diabetic_Noborderlinediabetes',
                    'Diabetic_Yes', 'Diabetic_Yesduringpregnancy']] = 0

    with placeholder.form("my_form"):
        # 몸무게
        weight = st.number_input('몸무게를 입력해주세요(단위 : kg)')
        # 키
        height = st.number_input(label = '키를 입력해주세요(단위 : cm)')
        # 나이(범주화 필요)
        AgeCategory = st.number_input('당신의 나이는 몇 살입니까(만 나이)?')
        if AgeCategory <= 24:
            base_df.loc[0, 'AgeCategory_1824'] = 1
        elif AgeCategory <= 29:
            base_df.loc[0, 'AgeCategory_2529'] = 1
        elif AgeCategory <= 34:
            base_df.loc[0, 'AgeCategory_3034'] = 1
        elif AgeCategory <= 39:
            base_df.loc[0, 'AgeCategory_3539'] = 1
        elif AgeCategory <= 44:
            base_df.loc[0, 'AgeCategory_4044'] = 1
        elif AgeCategory <= 49:
            base_df.loc[0, 'AgeCategory_4549'] = 1
        elif AgeCategory <= 54:
            base_df.loc[0, 'AgeCategory_5054'] = 1
        elif AgeCategory <= 59:
            base_df.loc[0, 'AgeCategory_5559'] = 1
        elif AgeCategory <= 64:
            base_df.loc[0, 'AgeCategory_6064'] = 1
        elif AgeCategory <= 69:
            base_df.loc[0, 'AgeCategory_6569'] = 1
        elif AgeCategory <= 74:
            base_df.loc[0, 'AgeCategory_7074'] = 1
        elif AgeCategory <= 79:
            base_df.loc[0, 'AgeCategory_7579'] = 1
        else:
            base_df.loc[0, 'AgeCategory_80orolder'] = 1

        # 신체 부상
        PhysicalHealth = int(st.number_input('지난 30일 동안 질병과 부상을 포함해 아픈 일수는 며칠입니까?'))
        base_df.loc[0, 'PhysicalHealth'] = PhysicalHealth
        # 정신건강
        MentalHealth = int(st.number_input('지난 30일 동안 정신 건강이 좋지 않았던 횟수(일수)는 며칠입니까?'))
        base_df.loc[0, 'MentalHealth'] = MentalHealth
        # 수면 시간
        SleepTime = st.number_input('최근 한달 간 평균 수면시간을 입력해주세요(단위 : 시간)')
        base_df.loc[0, 'SleepTime'] = SleepTime
        # 인종
        Race = st.selectbox('당신의 인종은 무엇입니까?', ['아시안', '백인', '히스패닉', '흑인', '기타', '알래스카/미국 원주민'])
        if Race == '아시안':
            base_df.loc[0, 'Race_Asian'] = 1
        elif Race == '백인':
            base_df.loc[0, 'Race_White'] = 1
        elif Race == '히스패닉':
            base_df.loc[0, 'Race_Hispanic'] = 1
        elif Race == '흑인':
            base_df.loc[0, 'Race_Black'] = 1
        elif Race == '기타':
            base_df.loc[0, 'Race_Other'] = 1
        elif Race == '알래스카/미국 원주민':
            base_df.loc[0, 'Race_AmericanIndianAlaskanNative'] = 1

        # 당뇨
        Diabetic = st.selectbox('당뇨병인 적이 한번이라도 있습니까?', ['네', '아니요', '애매하다', '임신 중에만 당뇨병이였다(여성만 해당)'])
        if Diabetic == '네':
            base_df.loc[0, 'Diabetic_Yes'] = 1
        elif Diabetic == '아니요':
            base_df.loc[0, 'Diabetic_No'] = 1
        elif Diabetic == '애매하다':
            base_df.loc[0, 'Diabetic_Noborderlinediabetes'] = 1
        elif Diabetic == '임신 중에만 당뇨병이였다(여성만 해당)':
            base_df.loc[0, 'Diabetic_Yesduring pregnancy'] = 1

        # 건강
        GenHealth = st.selectbox('본인이 느끼기에 당신의 건강 정도는?', ['훌륭하다', '아주 좋다' , '좋다' , '그저 그렇다' , '나쁘다'])
        if GenHealth == '훌륭하다':
            base_df.loc[0, 'GenHealth_Excellent'] = 1
        elif GenHealth == '아주 좋다':
            base_df.loc[0, 'GenHealth_Verygood'] = 1
        elif GenHealth == '좋다':
            base_df.loc[0, 'GenHealth_Good'] = 1
        elif GenHealth == '그저 그렇다':
            base_df.loc[0, 'GenHealth_Fair'] = 1
        elif GenHealth == '나쁘다':
            base_df.loc[0, 'GenHealth_Poor'] = 1

        # 흡연 여부
        Smoking = yes_or_no_q('당신은 평생 동안 적어도 100개 이상의 담배를 피우셨습니까?')
        base_df.loc[0, 'Smoking'] = Smoking
        # 술
        AlcoholDrinking = yes_or_no_q('당신은 과음자입니까?(남성은 주에 14잔 이상 , 여성은 주에 7잔 이상')
        base_df.loc[0, 'AlcoholDrinking'] = AlcoholDrinking
        # 뇌졸중
        Stroke = yes_or_no_q('당신은 뇌졸중 경험이 있습니까?')
        base_df.loc[0, 'Stroke'] = Stroke
        # 운동능력
        DiffWalking = yes_or_no_q('계단을 오를 때 힘들다고 느끼십니까?')
        base_df.loc[0, 'DiffWalking'] = DiffWalking
        # 육체활동
        PhysicalActivity = yes_or_no_q('운동을 하십니까?')
        base_df.loc[0, 'PhysicalActivity'] = PhysicalActivity
        # 천식
        Asthma = yes_or_no_q('천식에 걸린 적이 있습니까?')
        base_df.loc[0, 'Asthma'] = Asthma
        # 신장 질환
        KidneyDisease = yes_or_no_q('신장 질환이 있습니까?')
        base_df.loc[0, 'KidneyDisease'] = KidneyDisease
        # 피부암
        SkinCancer = yes_or_no_q('피부암에 걸린 적이 있습니까?')
        base_df.loc[0, 'SkinCancer'] = SkinCancer
        # 성별
        Sex = st.radio('당신의 성별은 무엇입니까?', ['남자', '여자'])
        if Sex == '남자':
            Sex = 1
        else :
            Sex = 0
        base_df.loc[0, 'Sex'] = Sex
        # BMI
        if height > 0:
            # BMI 계산 및
            BMI = round(weight / ((height/100) ** 2) , 2)
        else:
            BMI = 0
        base_df.loc[0, 'BMI'] = BMI

        time.sleep(4)
        submitted = st.form_submit_button("AI 예측")

        # base_df 조정(다른 컬럼 조정)
        base_df = base_df.append(base_df.loc[[0,0,0,0,0]]).reset_index(drop = True)

        # 당신이 담배를 피우지 않았다면
        if base_df.at[0, 'Smoking'] == 1:
            base_df.at[1, 'Smoking'] = 0

        # 당신이 과음을 하지 않는다면
        if base_df.at[0, 'AlcoholDrinking'] == 1:
            base_df.at[2, 'AlcoholDrinking'] = 0

        # 잠이 부족한 당신이 수면을 취한다면
        if base_df.at[0, 'SleepTime'] <= 6:
            base_df.at[3, 'SleepTime'] = 9

        # 당신이 정상 범주의 BMI 지수를 가질 경우
        if (base_df.at[0, 'BMI'] < 18.5) or (base_df.at[0, 'BMI'] > 25):
            base_df.at[4, 'BMI'] = 22

        # 당신이 운동을 한다면
        if base_df.at[0, 'PhysicalActivity'] == 0:
            base_df.at[5, 'PhysicalActivity'] = 1

        return base_df, submitted


#The complete source code for mplwidget.py is:
# Python Qt4 bindings for GUI objects
from PyQt5 import QtGui, QtCore, QtWidgets
# import the Qt4Agg FigureCanvas object, that binds Figure to
# Qt4Agg backend. It also inherits from QWidget
import matplotlib as MPL
MPL.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
# Matplotlib Figure object
from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):
    """Class to represent the FigureCanvas widget"""
    def __init__(self):
        # setup Matplotlib Figure and Axis after defining standard font properties
        font = {'family' : 'serif',
                'weight' : 'bold',
                'size'   : 8}
        axes = {'labelsize' : 12,
                'labelcolor' : 'green'}

        #MPL.rc('font', **font)  # pass in the font dict as kwargs
        #MPL.rc('axes', **axes)
        MPL.rcParams['figure.facecolor'] = 'white'
        MPL.rcParams['figure.autolayout'] = 'TRUE'
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        # initialization of the canvas
        FigureCanvas.__init__(self, self.fig)
        # we define the widget as expandable
        FigureCanvas.setSizePolicy(self,
        QtWidgets.QSizePolicy.Preferred,
        QtWidgets.QSizePolicy.Preferred)
        # notify the system of updated policy
        FigureCanvas.updateGeometry(self)

class MplWidget(QtWidgets.QWidget):
    """Widget defined in Qt Designer"""
    def __init__(self, parent = None):
        # initialization of Qt MainWindow widget
        QtWidgets.QWidget.__init__(self, parent)
        # set the canvas to the Matplotlib widget
        self.canvas = MplCanvas()

        ## create a vertical box layout
        self.hbl = QtWidgets.QHBoxLayout()
        self.vbl = QtWidgets.QVBoxLayout()
        self.loadButton = QtWidgets.QPushButton('load curve')
        self.loadButton.setMaximumWidth(100)
        self.loadButton.clicked.connect(self.loadCurve)
        self.labelLayout = QtWidgets.QHBoxLayout()
        # create Labels to show data points from picker
        self.curveLabel = QtWidgets.QLabel('curve: ')
        self.dataLabel = QtWidgets.QLabel('data point: ')
        self.labelLayout.addWidget(self.curveLabel)
        self.labelLayout.addWidget(self.dataLabel)
        self.labelLayout.addWidget(self.loadButton)

        self.vbl.addLayout(self.labelLayout)
        # create a tabWidget as central widget
        self.tab = QtWidgets.QTabWidget()
        # add TabWidget to vertical box
        self.hbl.addWidget(self.tab)
        # add mpl Widget to vertical box
        self.tab.addTab(self.canvas, 'curves')
        # add a tab for data table
        self.dataTable = QtWidgets.QTableWidget()
        self.tab.addTab(self.dataTable, 'data')
        # set the layout to th vertical box
        self.vbl.addLayout(self.hbl)

        self.setLayout(self.vbl)

        self.clip = QtWidgets.QApplication.clipboard()

        self.canvas.mpl_connect('pick_event', self.on_pick)

    def on_pick(self, event):
        # The event received here is of the type
        # matplotlib.backend_bases.PickEvent
        #
        # It carries lots of information, of which we're using
        # only a small amount here.
        #
        thisline = event.artist
        if thisline is not self.legend.legend:
            xdata, ydata = thisline.get_data()
            ind = event.ind
            self.curveLabel.setText('curve: {}'.format(thisline.get_label()))
            self.dataLabel.setText('selected point: x = {}  y = {}'.format(xdata[ind[0]], ydata[ind[0]]))

    def keyPressEvent(self, e):
        if (e.modifiers() & QtCore.Qt.ControlModifier):
            selected = self.dataTable.selectedRanges()

            if e.key() == QtCore.Qt.Key_C: #copy
                s = ""

                for r in range(selected[0].topRow(), selected[0].bottomRow()+1):
                    for c in range(selected[0].leftColumn(), selected[0].rightColumn()+1):
                        try:
                            s += str(self.dataTable.item(r,c).text()) + "\t"
                        except AttributeError:
                            s += "\t"
                    s = s[:-1] + "\n" #eliminate last '\t'
                self.clip.setText(s)

    def loadCurve(self):
        pass


import click
import json
from ranx import Run
import os

@click.command()
@click.argument("run_path")
@click.argument("testset")
def main(run_path, testset):
    print("RUN???")
    with open(testset) as f:
        bioasq_testset ={q_data["id"]:q_data for q_data in json.load(f)["questions"] }

    run = Run.from_file(run_path).to_dict()
    bioasq_struct = {"questions":[]}

    for q_id, docs_dict in run.items():
        prev_score = 1
        doc_list = []
        for doc_id, doc_score in docs_dict.items():
            assert doc_score<=prev_score
            prev_score=doc_score

            doc_list.append(f"http://www.ncbi.nlm.nih.gov/pubmed/{doc_id}")
            #http://www.ncbi.nlm.nih.gov/pubmed/
            #http://pubmed.ncbi.nlm.nih.gov/

        bioasq_struct["questions"].append({"id": q_id,
                                           "type": bioasq_testset[q_id]["type"],
                                           "body": bioasq_testset[q_id]["body"],
                                           "documents": doc_list[:10],
                                           "snippets": []})

    outdir = f"{os.path.dirname(run_path)}_bioasq_format"
    outfile_name = os.path.basename(run_path)
    path_to_w = os.path.join(outdir, outfile_name)
    print(path_to_w)
    with open(path_to_w, "w") as fOut:
        json.dump(bioasq_struct, fOut)

if __name__ == '__main__':
    main()


import sys
from pathlib import Path
from core import HandleFile as fileHandler
from core import TextHighlighter as txt
import core.VAM as VAM
import core.FirstSolver as firstSolver
import core.DataClasses as dataClass

def run(filePath: str):
    validateFilePath = Path(filePath)
    if validateFilePath.is_file():
        readFile = fileHandler.handleFile(filePath)

    else:
        txt.coloredPrint("Error! File don't exists!", txt.styleOfHighlight.ERROR, True)
        raise Exception("Program stopped!")

    print("Starting connection finder! It may take a while\n")

    finalCost, deliveredProducts, outputArr = firstSolver.SolutionFinder(readFile)

    dataClass.reset()
    readFile = fileHandler.handleFileWithoutValidation(filePath)

    finalCostVAM, deliveredProductsVAM, outputArrVAM, balanceValue = VAM.VAM(readFile)

    txt.coloredPrint("Comparing results!", txt.styleOfHighlight.WARNING, True, True)

    sumOfNeeds = dataClass.Pharmacy.sumOfNeeds
    deliveredProductsVAM -= abs(balanceValue)

    if deliveredProducts == deliveredProductsVAM:
        if finalCost > finalCostVAM:
            print("VAM got better results! Saving to file...\n")
            fileHandler.save2file(outputArrVAM)

        else:
            print("First solver got better results! Saving to file...\n")
            fileHandler.save2file(outputArr)

    elif deliveredProducts == sumOfNeeds and deliveredProductsVAM != sumOfNeeds:
        print("Only first solver delivered all vaccines! Saving to file...\n")
        fileHandler.save2file(outputArr)

    elif deliveredProducts != sumOfNeeds and deliveredProductsVAM == sumOfNeeds:
        print("Only VAM delivered all vaccines! Saving to file...\n")
        fileHandler.save2file(outputArrVAM)

    else:
        txt.coloredPrint("Warning both of solvers could't deliver all vaccines! Saving both to results files!", txt.styleOfHighlight.WARNING, True)
        fileHandler.save2file(outputArrVAM, "outputVAM.txt")
        fileHandler.save2file(outputArr, "outputFirst.txt")

    print("Program finished!\n")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        inputFilePath = sys.argv[1]
        print("\nStarting program!\n")
        run(inputFilePath)

    else:
        txt.coloredPrint("Error! Too few arguments!", txt.styleOfHighlight.ERROR, True)
        raise Exception("Program stopped!")


from datetime import datetime
import cv2
import torch
import numpy as np
import time

def score_frame(frame):
    """
    Takes a single frame as input, and scores the frame using yolo5 model.
    :param frame: input frame in numpy/list/tuple format.
    :return: Labels and Coordinates of objects detected by model in the frame.
    """
    model.to('cuda' if torch.cuda.is_available() else 'cpu')
    frame = [frame]
    results = model(frame)
    results.print()

    labels, cord = results.xyxyn[0][:, -1], results.xyxyn[0][:, :-1]
    return labels, cord

def class_to_label(x):
    """
    For a given label value, return corresponding string label.
    :param x: numeric label
    :return: corresponding string label
    """
    return int(x)

def plot_boxes(results, frame):
    """
    Takes a frame and its results as input, and plots the bounding boxes and label on to the frame.
    :param results: contains labels and coordinates predicted by model on the given frame.
    :param frame: Frame which has been scored.
    :return: Frame with bounding boxes and labels ploted on it.
    """
    labels, cord = results
    n = len(labels)
    x_shape, y_shape = frame.shape[1], frame.shape[0]
    for i in range(n):
        row = cord[i]
        if row[4] >= 0.2:
            x1, y1, x2, y2 = int(
                row[0]*x_shape), int(row[1]*y_shape), int(row[2]*x_shape), int(row[3]*y_shape)
            bgr = (0, 255, 0)
            cv2.rectangle(frame, (x1, y1), (x2, y2), bgr, 2)
            cv2.putText(frame, str(model.names[class_to_label(labels[i])]) + " " + str(round(float(row[4]),2)), (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.9, bgr, 2)

    return frame

if __name__ == "__main__":

    # model = torch.hub.load('ultralytics/yolov5', 'custom', 'best.pt')
    model = torch.hub.load('ultralytics/yolov5', 'yolov5m', pretrained=True)

    # fc = 0
    # FPS = 0
    # display_time = 2
    # start_time = time.time()

    vid = cv2.VideoCapture('Traffic1.m4v')
    # while vid.isOpened():
    #     ret, frm = vid.read()
    #     if not ret:
    #         break
    #     modelframe = model(frm)
    #     results = score_frame(frm)
    #     frame = plot_boxes(results, frm)
    #     print("---------")
    #     print(type(modelframe))
    #     print("---------")
    #     print(type(frm))
    #     print("---------")
    #     print(type(frame))

    while vid.isOpened():
        """
        ret, frame = vid.read()
        assert ret
        results = score_frame(frame)
        frame = plot_boxes(results, frame)
        if not (frame is None):
            fc += 1
            TIME = time.time() - start_time
            if (TIME) >= display_time:
                FPS = fc / (TIME)
                fc = 0
                start_time = time.time()
            fps_disp = "FPS: " + str(FPS)[:5]
            image = cv2.putText(
                frame,
                fps_disp,
                (10, 25),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.7,
                (0, 255, 0),
                2,
            )
            cv2.imshow("frame", image)
        if cv2.waitKey(1) == ord("q"):
            break
        """
        start_time = time.perf_counter()
        # --
        ret, frm = vid.read()
        if not ret:
            break
        results = score_frame(frm)
        frame = plot_boxes(results, frm)
        # --
        end_time = time.perf_counter()
        dt = str(datetime.now())
        fps = 1 / np.round(end_time - start_time, 3)
        cv2.putText(frame, f'FPS: {int(fps)}' + " "*14 + dt, (20, 70),
                    cv2.FONT_HERSHEY_DUPLEX, 0.7, (172, 7, 237), 2)
        cv2.imshow("Public camera", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    vid.release()
    cv2.destroyAllWindows()
    print("\nExiting.")


import json
from http.server import BaseHTTPRequestHandler, HTTPServer

class RequestHandler(BaseHTTPRequestHandler):
    def _send_response(self, message):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(bytes(message, "utf8"))

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        data = json.loads(post_data)
        with open('curl_data.txt', 'w') as file:
            file.write(json.dumps(data))
        self._send_response("Data saved to curl_data.txt")

def run(server_class=HTTPServer, handler_class=RequestHandler, port=80):
    server_address = ('', 80)
    httpd = server_class(server_address, handler_class)
    print(f'Starting server on port {port}')
    httpd.serve_forever()

run()


#!/usr/bin/env python3

import os
import json
import argparse
import subprocess as sp

# A set of category folder names in current sample viewer.
# Only run the checks when a file path is within one of these category folders.
categories = {
    'analysis',
    'display_information',
    'editing',
    'feature_layers',
    'geometry',
    'group_layers',
    'hydrography',
    'image_layers',
    'kml',
    'local_server',
    'map',
    'map_view',
    'network_analysis',
    'ogc',
    'portal',
    'raster',
    'real_time',
    'scene',
    'search',
    'symbology',
    'tiled_layers',
    'utility_network'
}

def run_mdl(readme_path: str):
    print("**** markdownlint style checker (mdl) ****")
    code = sp.call(f'mdl --style /style.rb "{readme_path}"', shell=True)
    # Returns 0 if mdl style checks pass. Returns 1 if errors occur.
    return code

def run_style_check(dirname: str):
    print("**** README_style_checker ****")
    code1 = sp.call(f'python3 /README_style_checker.py -s "{dirname}"', shell=True)
    print("**** metadata_style_checker ****")
    code2 = sp.call(f'python3 /metadata_style_checker.py -s "{dirname}"', shell=True)
    # Adds together exit codes from README_style_checker and metadata_style_checker.
    # Returns 0 if both style checks pass. Returns > 0 if either fails with an exit code of 1.
    return code1 + code2

def read_json(filenames_json_data):
    return [filename for filename in filenames_json_data]

def load_json_file(path: str):
    try:
        json_file = open(path, 'r')
        json_data = json.load(json_file)
    except Exception as err:
        print(f'Error reading JSON - {path} - {err}')
        raise err
    else:
        json_file.close()
    return json_data

def main():
    msg = 'Entry point of the docker to run mdl and style check scripts.'
    parser = argparse.ArgumentParser(description=msg)
    parser.add_argument('-s', '--string', help='A JSON array of file paths.')
    args = parser.parse_args()
    files = None

    print("** Starting checks **")
    if args.string:
        files = read_json(json.loads(args.string))
        if not files:
          if files == []:
            print('No changed files detected.')
            exit(0)
          else:
            print('Invalid input file paths string, abort.')
            exit(1)
    else:
        print('Invalid arguments, abort.')
        exit(1)

    return_code = 0
    # A set of dirname strings to avoid duplicate checks on the same sample.
    samples_set = set()

    for f in files:

        if not os.path.exists(f):
            # The changed file is deleted, no need to style check.
            continue

        path_parts = os.path.normpath(f).split(os.path.sep)

        if len(path_parts) != 3:
            # If the file is not in the root folder for the individual sample, omit.
            # E.g. might be in unrelated folders such as root category folders or '/gradle', '/src' etc.
            continue

        # Get filename and folder name of the changed sample.
        filename = os.path.basename(f)
        dir_path = os.path.dirname(f)
        l_name = filename.lower()

        if l_name != 'readme.md' and l_name != 'readme.metadata.json':
            # If the file is not a readme or readme.metadata file, omit.
            continue

        # Print debug information for current sample.
        if dir_path not in samples_set:
            print(f'*** Checking {dir_path} ***')

            # Check if the capitalization of doc filenames are correct.
            if l_name == 'readme.md' and filename != 'README.md':
                print(f'Error: {dir_path} filename has wrong capitalization')
                return_code += 1
                continue

            if l_name == 'readme.metadata.json' and filename != 'README.metadata.json':
                print(f'Error: {dir_path} filename has wrong capitalization')
                return_code += 1
                continue

            # Run the markdownlint linter on README file.
            if filename == 'README.md':
                # Run the linter on markdown file.
                return_code += run_mdl(f)

            # Run the other Python checks on the whole sample folder.
            if dir_path not in samples_set:
                samples_set.add(dir_path)
                return_code += run_style_check(dir_path)

    if return_code != 0:
        # Non-zero code occurred during the process.
        exit(return_code)
    else:
        exit(0)

if __name__ == '__main__':
    main()


import os
import os.path as osp
import logging
from collections import OrderedDict
import json
import os
NPU_CALCULATE_DEVICE = 0
if os.getenv('NPU_CALCULATE_DEVICE') and str.isdigit(os.getenv('NPU_CALCULATE_DEVICE')):
    NPU_CALCULATE_DEVICE = int(os.getenv('NPU_CALCULATE_DEVICE'))

def parse(opt_path, is_train=True):
    # remove comments starting with '//'
    json_str = ''
    with open(opt_path, 'r') as f:
        for line in f:
            line = line.split('//')[0] + '\n'
            json_str += line
    opt = json.loads(json_str, object_pairs_hook=OrderedDict)

    opt['is_train'] = is_train

    # datasets
    for phase, dataset in opt['datasets'].items():
        phase = phase.split('_')[0]
        dataset['phase'] = phase
        is_lmdb = False
        if 'dataroot_HR' in dataset and dataset['dataroot_HR'] is not None:
            dataset['dataroot_HR'] = os.path.expanduser(dataset['dataroot_HR'])
            if dataset['dataroot_HR'].endswith('lmdb'):
                is_lmdb = True
        if 'dataroot_HR_bg' in dataset and dataset['dataroot_HR_bg'] is not None:
            dataset['dataroot_HR_bg'] = os.path.expanduser(dataset['dataroot_HR_bg'])
        if 'dataroot_LR' in dataset and dataset['dataroot_LR'] is not None:
            dataset['dataroot_LR'] = os.path.expanduser(dataset['dataroot_LR'])
            if dataset['dataroot_LR'].endswith('lmdb'):
                is_lmdb = True
        dataset['data_type'] = 'lmdb' if is_lmdb else 'img'

        if phase == 'train' and 'subset_file' in dataset and dataset['subset_file'] is not None:
            dataset['subset_file'] = os.path.expanduser(dataset['subset_file'])

    # path
    for key, path in opt['path'].items():
        if path and key in opt['path']:
            opt['path'][key] = os.path.expanduser(path)
    if is_train:
        experiments_root = os.path.join(opt['path']['root'], 'experiments', opt['name'])
        opt['path']['experiments_root'] = experiments_root
        opt['path']['models'] = os.path.join(experiments_root, 'models')
        opt['path']['training_state'] = os.path.join(experiments_root, 'training_state')
        opt['path']['log'] = experiments_root
        opt['path']['val_images'] = os.path.join(experiments_root, 'val_images')

        # change some options for debug mode
        if 'debug' in opt['name']:
            opt['train']['val_freq'] = 8
            opt['logger']['print_freq'] = 2
            opt['logger']['save_checkpoint_freq'] = 8
            opt['train']['lr_decay_iter'] = 10
    else:  # test
        results_root = os.path.join(opt['path']['root'], 'results', opt['name'])
        opt['path']['results_root'] = results_root
        opt['path']['log'] = results_root

    # export CUDA_VISIBLE_DEVICES
    gpu_list = ','.join(str(x) for x in opt['gpu_ids'])
    os.environ['CUDA_VISIBLE_DEVICES'] = gpu_list
    print('export CUDA_VISIBLE_DEVICES=' + gpu_list)

    return opt

class NoneDict(dict):
    def __missing__(self, key):
        return None

# convert to NoneDict, which return None for missing key.
def dict_to_nonedict(opt):
    if isinstance(opt, dict):
        new_opt = dict()
        for key, sub_opt in opt.items():
            new_opt[key] = dict_to_nonedict(sub_opt)
        return NoneDict(**new_opt)
    elif isinstance(opt, list):
        return [dict_to_nonedict(sub_opt) for sub_opt in opt]
    else:
        return opt

def dict2str(opt, indent_l=1):
    '''dict to string for logger'''
    msg = ''
    for k, v in opt.items():
        if isinstance(v, dict):
            msg += ' ' * (indent_l * 2) + k + ':[\n'
            msg += dict2str(v, indent_l + 1)
            msg += ' ' * (indent_l * 2) + ']\n'
        else:
            msg += ' ' * (indent_l * 2) + k + ': ' + str(v) + '\n'
    return msg

def check_resume(opt):
    '''Check resume states and pretrain_model paths'''
    logger = logging.getLogger('base')
    if opt['path']['resume_state']:
        if opt['path']['pretrain_model_G'] or opt['path']['pretrain_model_D']:
            logger.warning('pretrain_model path will be ignored when resuming training.')

        state_idx = osp.basename(opt['path']['resume_state']).split('.')[0]
        opt['path']['pretrain_model_G'] = osp.join(opt['path']['models'],
                                                   '{}_G.pth'.format(state_idx))
        logger.info('Set [pretrain_model_G] to ' + opt['path']['pretrain_model_G'])
        if 'gan' in opt['model']:
            opt['path']['pretrain_model_D'] = osp.join(opt['path']['models'],
                                                       '{}_D.pth'.format(state_idx))
            logger.info('Set [pretrain_model_D] to ' + opt['path']['pretrain_model_D'])


# -*- coding: utf-8 -*-
"""
Created on Sun Mar  6 11:09:54 2022

@author: kevin
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Mar  5 11:19:31 2022

@author: kevin
"""

from pywebio.input import *
from pywebio.output import *
from pywebio.pin import *
from pywebio import start_server
import queue
from header import queryUrl
#import moduleInput,moduleOutput
import requests
#from moduleManager import *
from strategy import *
import json

def inputerrun(data):

    data={"msg": data,
        }

    rr=requests.post(queryUrl,json=data)

    data=json.loads(rr.text)
    if data['result_code']!='success':

        print(data)
#    print(data)
def testFunc():

    ss='小太阳帮我记录宝宝1点已经吃人奶瓶喂'
    inputerrun(ss)

def inputFunc():
    # input的合法性校验
    # 自定义校验函数

    def check_validate(n):
        pass

    # myAge = input('点击输入框进行语音输入', type=TEXT, validate=None, help_text='点击输入框进行语音输入',onchange=inputChange)
    myTxt = textarea(label='点击输入框进行语音输入', rows=3,
                     type=TEXT, validate=None, help_text='点击输入框进行语音输入',
                     onchange=inputerrun)
#
#    put_textarea(im.newMsg)

if __name__ == '__main__':
#    testFunc()

    start_server(
        applications=[inputFunc, ],
        debug=True,
        port=3086,
        auto_open_webbrowser=True,
        remote_access=False,
    )
#
#    cm.join()


import numpy as np
from utils import IoU

'''
Compute average precision given each result of prediction and the confidence

Parameters:
    prediction:     a list of dictionary.
                    for example [{'TP':True, 'confidence':0.65}, {'TP':False, 'confidence':0.4}]
                    set TP to True if the prediction is true positive
                    set TP to False if the prediction is false positive

    num_gt_example: int, number of ground truth examples

    validate:       bool, turn it on to check the inputs

Returns:
    ap:             int, average precision. note that we assume the inputs belongs to the same class
                    it is possible to utilize this functionality to compute mean average precision via multiple classes

    recall:         recalls computed over different confidence threshold, numpy array of shape (N,)

    precision:      precision computed over different confidence threshold, numpy array of shape (N,)

'''
def VocAveragePrecision(prediction, num_gt_example, validate=False):
    def CheckInput(prediction, num_gt_example):
        num_true_positive = 0
        for d in prediction:
            keys = list(d.keys())
            assert 'TP' in keys and 'confidence' in keys and type(d['TP']) is bool
            assert len(keys) == 2
            if d['TP']: num_true_positive +=1
        assert num_true_positive <= num_gt_example
        return

    if validate: CheckInput(prediction, num_gt_example)

    prediction.sort(key=lambda x:x['confidence'], reverse=True)
    prediction = [info['TP'] for info in prediction]
    prediction = np.array(prediction)

    tp = (prediction==True).astype(np.int)
    fp = (prediction==False).astype(np.int)

    cumulative_tp = np.cumsum(tp)
    cumulative_fp = np.cumsum(fp)

    # precision_scores = cumulative_tp / (np.arange(len(prediction)) + 1)
    precision = cumulative_tp / (cumulative_tp + cumulative_fp)
    recall = cumulative_tp / num_gt_example

    '''
    metric      rank(confidence)    extream_value
    precision   inf                 1
    precision   -inf                0
    recall      inf                 0
    recall      -inf                1
    '''
    precision = np.array([1.0] + list(precision) + [0.0])
    recall = np.array([0.0] + list(recall) + [1.0])

    for i in range(len(precision)-2, -1, -1):
        precision[i] = max(precision[i], precision[i+1])

    i_list = []
    for i in range(1, len(recall)):
        if recall[i] != recall[i-1]:
            i_list.append(i)

    ap = 0.0
    for i in i_list:
        ap += ((recall[i]-recall[i-1])*precision[i])
    return ap, recall, precision

'''
Compute average precision given predictions of images

Parameters:
    gt_info:        a dictionary of files, representing the ground truth infomation
                    of each image, for example
                        {'1.jpg':bboxes_01, '2.jpg':bboxes_02}
                    each key represents each image file, and the bboxes_01 is
                    the numpy array of shape (K, 4), representing K ground truth
                    objects.

    predictions_info:
                    a list, each element in the list representing a prediction, for example: [prediction01, prediction02]
                    each prediction is a dictionary, for example
                        {'bbox': array([165., 214., 230., 255.]), 'confidence':0.85, 'file_id':'2.jpg'}
                    bbox is numpy array of shape (4, )
                    file_id should be consistent with the files in gt_info

    num_gt_example: int, number of ground truth examples

    validate_input: bool, turn it on to check the inputs

    min_overlap:    should be in (0, 1) default value is 0.5 (defined in the PASCAL VOC2012 challenge)

Returns:
    ap:             int, average precision. note that we assume the inputs belongs to the same class
                    it is possible to utilize this functionality to compute mean average precision via multiple classes

    recall:         recalls computed over different confidence threshold, numpy array of shape (N,)

    precision:      precision computed over different confidence threshold, numpy array of shape (N,)

'''
def AveragePrecisionOnImages(gt_info, predictions_info, num_gt_example, min_overlap=0.5, validate_input=False):
    result = []
    used_info = {}
    # set 'used' tag for each ground truch bbox
    for file_id in gt_info:
        boxes = gt_info[file_id]
        size = boxes.shape[0]
        used = np.zeros(shape=[size]).astype(np.bool)
        used_info[file_id] = used

    for idx, prediction in enumerate(predictions_info):
        file_id = prediction['file_id']
        box_pred = prediction['bbox']

        boxes_gt = gt_info[file_id]
        iou = IoU(box_pred, boxes_gt)
        idx = iou.argmax()
        used = used_info[file_id][idx]
        confidence = prediction['confidence']

        if iou[idx] >= min_overlap and not used:
            result.append({'TP':True, 'confidence':confidence})
            used_info[file_id][idx] = True
        else:
            result.append({'TP':False, 'confidence':confidence})

    ap, recall, precision = VocAveragePrecision(result, num_gt_example, validate=validate_input)
    return ap, recall, precision


# -*- coding: utf-8 -*-
from typing import List

from module.baseState import BaseState
from module.battleStates.stateBattle import StateBattle
from module.constant.state import State
from module.facilityStates.stateArmorShop import StateArmorShop
from module.facilityStates.stateBarbar import StateBarbar
from module.facilityStates.stateDrugs import StateDrugs
from module.facilityStates.stateExaminations import StateExaminations
from module.facilityStates.stateHelmetShop import StateHelmetShop
from module.facilityStates.stateShieldShop import StateShieldShop
from module.facilityStates.stateSurgery import StateSurgery
from module.facilityStates.stateWeaponShop import StateWeaponShop
from module.fieldStates.baseFieldState import BaseFieldState
from module.fieldStates.stateBlacktower import StateBlackTower
from module.fieldStates.stateCemetery import StateCemetery
from module.fieldStates.stateCity import StateCity
from module.fieldStates.stateColordBlack import StateColordBlack
from module.fieldStates.stateColordBlue import StateColordBlue
from module.fieldStates.stateColordGreen import StateColordGreen
from module.fieldStates.stateColordPurple import StateColordPurple
from module.fieldStates.stateColordRed import StateColordRed
from module.fieldStates.stateColordWhite import StateColordWhite
from module.fieldStates.stateColordYellow import StateColordYellow
from module.fieldStates.stateDungeonB1 import StateDungeonB1
from module.fieldStates.stateDungeonB2 import StateDungeonB2
from module.fieldStates.stateDungeonB3 import StateDungeonB3
from module.fieldStates.stateDungeonB4 import StateDungeonB4
from module.fieldStates.stateDungeonB5 import StateDungeonB5
from module.fieldStates.stateWellB1 import StateWellB1
from module.fieldStates.stateWellB2 import StateWellB2
from module.fieldStates.stateWellB3 import StateWellB3
from module.fieldStates.stateWellB4 import StateWellB4
from module.systemStates.stateCamp import StateCamp
from module.systemStates.stateEnding import StateEnding
from module.systemStates.stateMakeChracter import StateMakeCharacter
from module.systemStates.stateTitle import StateTitle

class StateStack(object):
    '''
    Stateをスタックで保持するクラス
    '''
    def __init__(self) -> None:
        '''
        クラス初期化
        '''
        # StateのEnumと対応するStateクラスの辞書
        self.__stateDict = {
            State.TITLE: StateTitle,
            State.MAKECHARACTER: StateMakeCharacter,
            State.CAMP: StateCamp,
            State.ENDING: StateEnding,
            State.CEMETERY: StateCemetery,
            State.CITY: StateCity,
            State.WELLB1: StateWellB1,
            State.WELLB2: StateWellB2,
            State.WELLB3: StateWellB3,
            State.WELLB4: StateWellB4,
            State.DUNGEONB1: StateDungeonB1,
            State.DUNGEONB2: StateDungeonB2,
            State.DUNGEONB3: StateDungeonB3,
            State.DUNGEONB4: StateDungeonB4,
            State.DUNGEONB5: StateDungeonB5,
            State.COLORD_YELLOW: StateColordYellow,
            State.COLORD_RED: StateColordRed,
            State.COLORD_PURPLE: StateColordPurple,
            State.COLORD_GREEN: StateColordGreen,
            State.COLORD_BLUE: StateColordBlue,
            State.COLORD_WHITE: StateColordWhite,
            State.COLORD_BLACK: StateColordBlack,
            State.BLACKTOWER: StateBlackTower,
            State.ARMORSHOP: StateArmorShop,
            State.BARBAR: StateBarbar,
            State.DRUGS: StateDrugs,
            State.EXAMINATIONS: StateExaminations,
            State.HELMETSHOP: StateHelmetShop,
            State.SHIELDSHOP: StateShieldShop,
            State.SURGERY: StateSurgery,
            State.WEAPONSHOP: StateWeaponShop,
            State.BATTLE: StateBattle,
        }

        # スタックを初期化する
        self.clear()

        if __debug__:
            print("StateStack : Initialized.")

    def update(self) -> None:
        '''
        現在先頭にあるStateのupdateメソッドを実行する
        '''
        if len(self.states) > 0 and self.states[0] != None:
            self.states[0].update()

    def draw(self) -> None:
        '''
        現在先頭にあるStateのrenderメソッドを実行する
        '''
        if len(self.states) > 0 and self.states[0] != None:
            self.states[0].draw()

    def push(self, stateEnum: int, **kwargs) -> None:
        '''
        stateEnumで指定されたStateクラスのインスタンスを生成し、スタックの先頭に追加する。\n
        追加されるStateクラスはbuildStateメソッドによりスタック操作メソッドが追加された後、onEnterメソッドが実行される。
        '''
        if __debug__:
            print(f"StateStack : push({stateEnum}).")

        # stateEnumで指定されたStateクラスのインスタンスを生成する
        state = self.getInstance(stateEnum, **kwargs)

        # スタックの先頭に追加する
        self.states.insert(0, state)

        # インスタンスの生成に成功した場合
        if state != None:
            # State開始時の処理を呼び出す
            self.states[0].onEnter()

        if __debug__:
            print("StateStack : pushed -> " + str(state))

    def pop(self) -> None:
        '''
        スタックの先頭からStateを削除する。\n
        削除前にStackのonExitメソッドが実行される。
        '''
        if __debug__:
            print("StateStack : pop " + str(self.states[0]))

        # State終了時の処理を呼び出す
        if self.states[0] != None:
            self.states[0].onExit()

        # スタックの先頭からStateを削除する。
        self.states.pop(0)

        # スタックの戦闘になったStateのonEnterメソッドを実行する
        if self.states[0] != None:
            self.states[0].onEnter()

    def isField(self) -> bool:
        '''
        現在のStateがBaseFieldの派生クラスかを判定する
        '''
        if len(self.states) > 0 and isinstance(self.states[0], BaseFieldState):
            return True
        else:
            return False

    def clear(self) -> None:
        '''
        スタックを初期化し、stateNameに指定されたstateをスタックに登録する
        '''
        if __debug__:
            print("StateStack : clear")

        # スタック初期化
        self.states = []

    def setStates(self, states) -> None:
        '''
        List型で指定されたスタックをすべて設定する。\n
        データロード時のみ使用すること。
        '''
        self.states = states

    def getStates(self) -> List:
        '''
        stateのリストを取得する
        '''
        return self.states

    def getInstance(self, stateEnum: int, **kwargs) -> BaseState:
        '''
        StateのEnum値に該当するstateクラスを取得する
        '''
        # 戻り値の初期化
        state = None

        # 引数がNoneの時はNoneを返す
        if stateEnum == None:
            return None

        # stateの辞書からstateEnumに該当するstateクラスを取得する
        c = self.__stateDict.get(stateEnum, None)

        # stateクラスの取得に成功した場合、コールバックメソッドを登録し、インスタンスを生成する
        if c != None:
            kwargs["stateStack"] = self
            state = c(**kwargs)

        return state

stateStack = StateStack()