#coding=utf-8
import requests
import random
import time

from common import get_param_md5
import yaml

with open('test.yaml',encoding='utf-8') as f:
    res = yaml.load(f,Loader=yaml.FullLoader)
    host = res['host']
    acc = res['acc']
    test_count = res['test_count']

    print(host)
    print(acc)
    print(test_count)

from collections import OrderedDict as ODict

def test_webpay(orderno, username, gamemoney, time, sig):
    url_template = host + 'webpay?orderno={0}&username={1}&gamemoney={2}&time={3}&sign={4}'

    url = url_template.format(orderno, username, gamemoney, time, sig)
    print('the url is '+ url)

    result = requests.get(url)
    print(result.content)

def test_api(api,orderdict):
    param_url  = '&'.join(['{0}={1}'.format(k,orderdict[k]) for k in  orderdict])
    url = '{host}{api}?{params}'.format(host=host,api=api,params=param_url)
    print('the url is ',url)
    result = requests.get(url)
    print(result.content)

def __test_webpay():
    #订单号不能一样
    orderno = str(random.randint(1,1000000))
    orderno = 10
    print(orderno)
    username = 'gsx'
    gamemoney = random.randint(1,100)
    _time = int(time.time())

    sig = get_param_md5(orderno, username, gamemoney, _time)
    print('the sig is ',sig)

    test_webpay(orderno, username, gamemoney, _time, sig)

def __chagnePasswd():
    #订单号不能一样
    odict = ODict()

    odict['username'] = 'gsx'
    odict['passwd'] = 'abcde'
    odict['time'] = int(time.time())

    sign = get_param_md5( *[odict[k] for k in odict] )
    odict['sign'] = sign

    test_api('changuser',odict)

def __sendItem():
    #订单号不能一样
    odict = ODict()

    odict['chaid'] = 1025
    odict['itemid'] = 1000
    odict['itemcount'] = 2
    odict['mailbt'] = '122'
    odict['mailnr'] = '1434'

    odict['time'] = int(time.time())

    sign = get_param_md5( *[odict[k] for k in odict] )
    print(sign)
    odict['sign'] = sign

    test_api('senditem',odict)

def __queryRoleListByAcc():
    #订单号不能一样
    odict = ODict()
    odict['acc'] = 'gsx4'
    odict['time'] = int(time.time())

    sign = get_param_md5( *[odict[k] for k in odict] )
    odict['sign'] = sign

    test_api('rolelistbyacc',odict)

def __queryAccByRoleName():
    #订单号不能一样
    odict = ODict()
    odict['name'] = '123'
    odict['time'] = int(time.time())

    sign = get_param_md5( *[odict[k] for k in odict] )
    odict['sign'] = sign
    #odict['sign'] = 'pip'

    test_api('accbyrolename',odict)

def __queryAccDayCash():
    #订单号不能一样
    odict = ODict()
    odict['acc'] = acc
    odict['time'] = int(time.time())

    sign = get_param_md5( *[odict[k] for k in odict] )
    odict['sign'] = sign
    #odict['sign'] = 'pip'

    test_api('queryTodayCashConsume',odict)

def __SubAccCash():
    #订单号不能一样
    odict = ODict()
    odict['acc'] = 'gsx'
    odict['cash'] = 1
    odict['time'] = int(time.time())

    sign = get_param_md5( *[odict[k] for k in odict] )
    odict['sign'] = sign
    #odict['sign'] = 'pip'

    test_api('subAccCash',odict)

def __queryAccApi(api):
    #订单号不能一样
    odict = ODict()
    odict['acc'] = 'gsx'
    odict['time'] = int(time.time())

    sign = get_param_md5( *[odict[k] for k in odict] )
    odict['sign'] = sign
    #odict['sign'] = 'pip'

    test_api(api,odict)

for i in range(test_count):
    __queryAccDayCash()

# __queryAccDayCash()
# api = 'queryTodayRoleOnlineInfo'
# __queryAccApi(api)

# api = 'queryAccRoleListInfo'
# __queryAccApi(api)

# api = 'queryAccCash'
# __queryAccApi(api)

# __SubAccCash()

# api = 'queryAccRoleEnchantInfo'
# __queryAccApi(api)


import os
from utils import fs
from format.ctr import CTR

def func(args):
	for srcpath in fs.walkdir(args.src, '*.ctr'):
		ctrfile = CTR()
		ctrfile.load(srcpath)

		# Editing code here
		# ...

		dstpath = srcpath.replace(args.src, args.dst, 1)
		fs.makedir(dstpath)
		ctrfile.save(dstpath)


a = []

with open("data.txt", "r") as f:
	for line in f:
		a.append(line.split("\n")[0])

for i in range(200):
	for j in range(200):
		if (i != j):
			suma = int(a[i]) + int(a[j])
			if (suma == 2020):
				print (a[i], a[j], 'iloczyn: ', int(a[i])*int(a[j]))


"""
Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

Input: nums = [3,2,3]
Output: 3
Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2
"""
from typing import List

def majorityElement(nums: List[int]) -> int:
    res = {}

    for num in range(len(nums)):
        if nums[num] not in res:
            res[nums[num]] = 1
        else:
            res[nums[num]] += 1

    return max(res, key=res.get)

if __name__ == '__main__':
    nums = [3, 2, 3]
    fc = majorityElement(nums)
    expected_result = 3
    assert expected_result == fc, fc
    print(fc)

    nums = [2, 2, 1, 1, 1, 2, 2]
    fc = majorityElement(nums)
    expected_result = 2
    assert expected_result == fc, fc
    print(fc)


import os
import imageio
import itertools
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from tqdm import tqdm
from sklearn import svm
from sklearn.multiclass import OneVsRestClassifier
from sklearn.model_selection import KFold
from sklearn.metrics import roc_curve, auc, confusion_matrix
from mpl_toolkits.axes_grid1 import Grid
import sis_utils
import util_functions
import uabCrossValMaker
import uabPreprocClasses
import uab_collectionFunctions
import uab_DataHandlerFunctions
import bohaoCustom.uabPreprocClasses as bPreproc
from bohaoCustom import uabMakeNetwork_DeepLabV2
from bohaoCustom import uabMakeNetwork_UNet

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

# settings
img_dir, task_dir = sis_utils.get_task_img_folder()
np.random.seed(1004)
model_name = 'unet'
verify = False
force_run = True

# make network
input_size_fit = (299, 299)
if model_name == 'deeplab':
    input_size = (321, 321)
    # define place holder
    X = tf.placeholder(tf.float32, shape=[None, input_size[0], input_size[1], 3], name='X')
    y = tf.placeholder(tf.int32, shape=[None, input_size[0], input_size[1], 1], name='y')
    mode = tf.placeholder(tf.bool, name='mode')
    model = uabMakeNetwork_DeepLabV2.DeeplabV3({'X':X, 'Y':y},
                                               trainable=mode,
                                               input_size=input_size,)
else:
    input_size = (572, 572)
    # define place holder
    X = tf.placeholder(tf.float32, shape=[None, input_size[0], input_size[1], 3], name='X')
    y = tf.placeholder(tf.int32, shape=[None, input_size[0], input_size[1], 1], name='y')
    mode = tf.placeholder(tf.bool, name='mode')
    model = uabMakeNetwork_UNet.UnetModelCrop({'X': X, 'Y': y},
                                              trainable=mode,
                                              input_size=input_size, )

blCol = uab_collectionFunctions.uabCollection('inria')
opDetObj = bPreproc.uabOperTileDivide(255)          # inria GT has value 0 and 255, we map it back to 0 and 1
# [3] is the channel id of GT
rescObj = uabPreprocClasses.uabPreprocMultChanOp([], 'GT_Divide.tif', 'Map GT to (0, 1)', [3], opDetObj)
rescObj.run(blCol)
img_mean = blCol.getChannelMeans([0, 1, 2])         # get mean of rgb info

# extract patches
extrObj = uab_DataHandlerFunctions.uabPatchExtr([0, 1, 2, 4],
                                                cSize=(input_size[0], input_size[1]),
                                                numPixOverlap=int(model.get_overlap()),
                                                extSave=['jpg', 'jpg', 'jpg', 'png'],
                                                isTrain=True,
                                                gtInd=3,
                                                pad=model.get_overlap()/2)
patchDir = extrObj.run(blCol)
# get validation set
# use uabCrossValMaker to get fileLists for training and validation
idx, file_list = uabCrossValMaker.uabUtilGetFolds(patchDir, 'fileList.txt', 'force_tile')

# load patch names
patch_file = os.path.join(task_dir, 'incep_inria_{}.txt'.format(model_name))
with open(patch_file, 'r') as f:
    patch_names = f.readlines()
# make truth
truth_file_building = os.path.join(task_dir, 'truth_inria_building_{}.npy'.format(model_name))
truth_file_buidling10 = os.path.join(task_dir, 'truth_inria_building10_{}.npy'.format(model_name))
if (not os.path.exists(truth_file_building)) or (not os.path.exists(truth_file_buidling10)):
    print('Making ground truth building...')
    truth_building = np.zeros(len(patch_names))
    truth_building10 = np.zeros(len(patch_names))
    for cnt, file in enumerate(tqdm(patch_names)):
        gt_name = os.path.join(patchDir, '{}_GT_Divide.png'.format(file[:-1]))
        gt = imageio.imread(gt_name)
        if model_name == 'unet':
            portion = np.sum(util_functions.crop_center(gt, 388, 388)) / (388 * 388)
        else:
            portion = np.sum(gt) / (321 * 321)
        if portion > 0.1:
            truth_building[cnt] = 1
        if portion // 0.1 <= 5:
            truth_building10[cnt] = portion // 0.1
        else:
            truth_building10[cnt] = 6
    np.save(truth_file_building, truth_building)
    np.save(truth_file_buidling10, truth_building10)
else:
    truth_building = np.load(truth_file_building)
    truth_building10 = np.load(truth_file_buidling10)

# verify gt
if verify:
    fig = plt.figure(figsize=(12, 8))
    grid = Grid(fig, rect=111, nrows_ncols=(4, 5), axes_pad=0.25, label_mode='L')
    rand_idx = np.random.permutation(len(patch_names))
    rand_patch_names = [patch_names[rand_i] for rand_i in rand_idx]
    for cnt, file in enumerate(rand_patch_names[:20]):
        gt_name = os.path.join(patchDir, '{}_GT_Divide.png'.format(file[:-1]))
        gt_img = imageio.imread(gt_name)
        gt_building = truth_building10[rand_idx[cnt]]
        grid[cnt].imshow(gt_img)
        grid[cnt].set_title(gt_building)
    plt.show()

# load features
feature_file = os.path.join(task_dir, 'incep_inria_{}.csv'.format(model_name))
feature = pd.read_csv(feature_file, sep=',', header=None).values
assert len(idx) == feature.shape[0]

# do on valid set
idx = np.array(idx)
truth_building = truth_building[idx < 6]
truth_building10 = truth_building10[idx < 6]
feature = feature[idx < 6, :]

# do cross validation
pred_file_name = os.path.join(task_dir, 'incep_building_pred_{}.npy'.format(model_name))
if (not os.path.exists(pred_file_name)) or force_run:
    kf = KFold(n_splits=5, shuffle=True)
    clf = svm.SVC(probability=True)
    pred_building = []
    truth_building_rearrange = []
    pbar = tqdm(kf.split(feature))
    for cnt, (train_idx, test_idx) in enumerate(pbar):
        pred_file_name_seperate = os.path.join(task_dir, 'incep_building_pred_{}_loo{}.npy'.format(model_name, cnt))
        pbar.set_description('Training building on fold {}'.format(cnt))
        X_train, X_test = feature[train_idx, :], feature[test_idx, :]
        y_train, y_test = truth_building[train_idx], truth_building[test_idx]
        clf.fit(X_train, y_train)
        pred = clf.predict_proba(X_test)[:,1]
        pred_building.append(pred)
        truth_building_rearrange.append(y_test)
        np.save(pred_file_name_seperate, [pred, y_test])
    pred_building = np.concatenate(pred_building)
    truth_building_rearrange = np.concatenate(truth_building_rearrange)
    np.save(pred_file_name, [pred_building, truth_building_rearrange])
else:
    pred_building, truth_building_rearrange = np.load(pred_file_name)

pred_file_name = os.path.join(task_dir, 'incep_building10_pred_{}.npy'.format(model_name))
if (not os.path.exists(pred_file_name)) or force_run:
    kf = KFold(n_splits=5, shuffle=True)
    clf = OneVsRestClassifier(svm.SVC(probability=True))
    pred_city = []
    truth_building10_rearrange = []
    pbar = kf.split(feature)
    for cnt, (train_idx, test_idx) in enumerate(pbar):
        pred_file_name_seperate = os.path.join(task_dir, 'incep_building10_pred_{}_loo{}.npy'.format(model_name, cnt))
        pbar.set_description('Training building10 on fold {}'.format(cnt))
        X_train, X_test = feature[train_idx, :], feature[test_idx, :]
        y_train, y_test = truth_building10[train_idx], truth_building10[test_idx]
        clf.fit(X_train, y_train)
        pred = clf.predict(X_test)
        pred_city.append(pred)
        truth_building10_rearrange.append(y_test)
        np.save(pred_file_name, [pred_building, truth_building_rearrange])
    pred_city = np.concatenate(pred_city)
    truth_city_rearrange = np.concatenate(truth_building10_rearrange)
    np.save(pred_file_name, [pred_city, truth_city_rearrange])
else:
    pred_city, truth_city_rearrange = np.load(pred_file_name)

plt.figure()
fpr_rf, tpr_rf, _ = roc_curve(truth_building_rearrange, pred_building)
plt.plot(fpr_rf, tpr_rf, label='{} AUC = {:.2f}'.format(model_name, auc(fpr_rf, tpr_rf)))
plt.plot([0, 1], [0, 1], color='grey', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Building')
plt.legend(loc="lower right")

'''plt.figure()
cnf_matrix = confusion_matrix(truth_city_rearrange, pred_city)
np.set_printoptions(precision=2)
plot_confusion_matrix(cnf_matrix,
                      classes=['0~10', '10~20', '20~30', '30~40', '40~50', '50~60', '60~100'], normalize=True,
                      title='CM Building10 ({})'.format(model_name))'''
plt.show()


import os
import yaml
from pyDtsTool import DeviceTree, Node
from pyDtsTool.node_properties import *
from pyDtsTool.common import tuple_representer

class Dictifier(object):
    def __init__(self, dt: DeviceTree):
        """Converts DeviceTree into dictionary and can export to YAML format"""
        self.dt = dt
        self.data = {}
        self.yaml_name = os.path.splitext(os.path.split(dt.filename)[-1])[0] + '.yaml'

    def generate(self):
        data = self.data
        data['filename'] = self.dt.filename
        data['gcc_include'] = self.dt.gcc_include
        data['gcc_define'] = self.dt.gcc_define
        data['dts_version'] = self.dt.dts_version
        data['nodes'] = {}
        root_node = self.dt.nodes_by_name.get('/', None)
        if root_node is not None:
            data['nodes'][0] = self.dictify_node(root_node)
        for _, node in self.dt.nodes_by_ref.items():
            data['nodes'][len(data['nodes'])] = self.dictify_node(node)
        self.data.update(data)

    def dictify_node(self, dtnode: Node):
        data = {t: n for t, n in dtnode.names.items() if n is not None}
        if len(dtnode.dtc['include']) > 0:
            data['dtc_include'] = dtnode.dtc['include']
        if len(dtnode.dtc['delete-node']) > 0:
            data['dtc_delete_node'] = dtnode.dtc['delete-node']
        if len(dtnode.dtc['delete-property']) > 0:
            data['dtc_delete_property'] = dtnode.dtc['delete-property']
        data['properties'] = dict(dtnode.property_map)
        if len(dtnode.children) > 0:
            data['children'] = {}
            for i, child in enumerate(dtnode.children):
                data['children'][i] = self.dictify_node(child)
        return data

    def to_yaml(self, filename=None):
        yaml.add_representer(tuple, tuple_representer)
        if filename is None:
            if self.yaml_name in [None, '.yaml']:
                self.yaml_name = 'exported.yaml'
        else:
            self.yaml_name = filename
        with open(self.yaml_name, 'w+') as fp:
            yaml.dump(self.data, fp, default_flow_style=False)


CONFIG_DELIMITER = "="

# Filenames and directory names
CONFIG_NAMES = [
    "rose-app.conf",
    "rose-meta.conf",
    "rose-suite.conf",
    "rose-suite.info",
]
GLOB_CONFIG_FILE = "rose*.conf"
META_CONFIG_NAME = "rose-meta.conf"
CONFIG_META_DIR = "meta"
SUB_CONFIG_NAME = "rose-app.conf"
SUB_CONFIGS_DIR = "app"
SUB_CONFIG_FILE_DIR = "file"
INFO_CONFIG_NAME = "rose-suite.info"
TOP_CONFIG_NAME = "rose-suite.conf"
META_DEFAULT_VN_DIR = "HEAD"

# Optional configurations - not applicable to rose.conf optional configs.
GLOB_OPT_CONFIG_FILE = "rose-*-*.conf"
RE_OPT_CONFIG_FILE = "rose-.*?-(.+).conf$"

# Configuration specification names
CONFIG_SECT_CMD = "command"
CONFIG_SECT_TOP = ""
CONFIG_OPT_META_PATH = "meta-path"
CONFIG_OPT_META_TYPE = "meta"
CONFIG_OPT_OWNER = "owner"
CONFIG_OPT_PROJECT = "project"
INFO_CONFIG_DEFAULT_META_IDS = [
    "=access-list",
    "=description",
    "=owner",
    "=project",
    "=sub-project",
    "=title",
    "=type",
]
SUB_CONFIG_DEFAULT_META_IDS = [
    "=file-install-root",
    "=meta",
    "=mode",
    "=opts",
    "command",
    "file:",
    "poll",
]
CONFIG_SETTING_INDEX_DEFAULT = "1"

# Metadata specification names
META_DIR_MACRO = "macros"
META_DIR_WIDGET = "widget"
META_PROP_COMPULSORY = "compulsory"
META_PROP_COPY_MODE = "copy-mode"
META_PROP_DESCRIPTION = "description"
META_PROP_DUPLICATE = "duplicate"
META_PROP_ELEMENT_TITLES = "element-titles"
META_PROP_FAIL_IF = "fail-if"
META_PROP_HELP = "help"
META_PROP_LENGTH = "length"
META_PROP_MACRO = 'macro'
META_PROP_NS = "ns"
META_PROP_PATTERN = "pattern"
META_PROP_RANGE = "range"
META_PROP_SORT_KEY = "sort-key"
META_PROP_TITLE = "title"
META_PROP_TRIGGER = "trigger"
META_PROP_TYPE = "type"
META_PROP_URL = "url"
META_PROP_VALUES = "values"
META_PROP_VALUE_TITLES = "value-titles"
META_PROP_VALUE_HINTS = "value-hints"
META_PROP_WARN_IF = "warn-if"
META_PROP_WIDGET = "widget"

# Value used to denote copy mode never or clear for a metadata setting.
COPY_MODE_NEVER = "never"
COPY_MODE_CLEAR = "clear"

# Value used to denote "on" for a metadata setting.
META_PROP_VALUE_TRUE = "true"
META_PROP_VALUE_FALSE = "false"  # Not actually used.

# Allowed type settings (that actually do something)
# "meta" and "file" are for internal use.
TYPE_VALUES = [
    "boolean",
    "character",
    "integer",
    "logical",
    "quoted",
    "raw",
    "real",
    "meta",
    "file",
    "python_list",
    "python_boolean",
    "spaced_list",
]

# Preferred Fortran logical and environment boolean syntax
TYPE_BOOLEAN_VALUE_FALSE = "false"
TYPE_BOOLEAN_VALUE_TRUE = "true"
TYPE_LOGICAL_VALUE_FALSE = ".false."
TYPE_LOGICAL_VALUE_TRUE = ".true."
TYPE_LOGICAL_FALSE_TITLE = "false"
TYPE_LOGICAL_TRUE_TITLE = "true"

# Preferred Python boolean syntax
TYPE_PYTHON_BOOLEAN_VALUE_FALSE = "False"
TYPE_PYTHON_BOOLEAN_VALUE_TRUE = "True"

# File variable names in the specification.
FILE_VAR_CHECKSUM = "checksum"
FILE_VAR_MODE = "mode"
FILE_VAR_SOURCE = "source"

# Paths in the Rose distribution.
FILEPATH_README = "README.md"

__version__ = "2.1.1.dev"


from uuid import UUID

import app.core.schemas as schemas
import app.db.crud as crud
from fastapi import APIRouter, Body, HTTPException, Query

network_router = APIRouter()

@network_router.get("/", response_model=list[schemas.Network])
def read_network_measurements(
    user_id: UUID = Query(None), skip: int = 0, limit: int = 100
):
    if user_id is None:
        return crud.get_network_measurements(skip, limit)
    else:
        return crud.get_user_network_measurements(user_id, skip, limit)

@network_router.post("/create", response_model=schemas.Network)
def create_network_measurements_for_user(
    user_id: UUID = Query(...),
    landmark_id: int = Query(...),
    network: schemas.NetworkCreate = Body(...),
):
    db_user = crud.get_user_by_id(id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    db_landmark = crud.get_landmark_by_id(id=landmark_id)
    if db_landmark is None:
        raise HTTPException(status_code=404, detail="Landmark not found")
    return crud.create_user_network_measurement(user_id, landmark_id, network)


import datetime
import logging

LOGGER = logging.getLogger(__name__)

class AutomationPage:

    def __init__(self, driver, config):
        self.driver = driver
        self.config = config

    def title(self):
        return self.driver.title

    def take_screenshot_to_compare(self, file_name):
        file_path = "./results/{}".format(file_name)
        self.driver.set_window_size(1200, 3305)
        self.driver.find_element_by_tag_name('body').screenshot(file_path)
        LOGGER.info("> Took capture [ {} ]".format(file_path))
        return file_path

    def take_screenshot(self):
        time = datetime.datetime.now()
        file_name = "./results/{}_{}.png".format(
            type(self).__name__.lower(),
            time.strftime("%Y%m%d_%H%M%S"))
        self.driver.save_screenshot(file_name)
        LOGGER.info("> Took capture [ {} ]".format(file_name))


import sys
sys.setrecursionlimit(100000)

def dfs(v, visited):
    visited[v] = 1
    for e in arr[v]:
        if visited[e] == 0:
            dfs(e, visited)

    return sum(visited)

n, m = map(int, input().split(' '))
arr = [[] for _ in range(n+1)]

for _ in range(m):
    x, y = map(int, input().split(' '))
    #arr[x].append(y)
    arr[y].append(x)

result = [0]
for i in range(n):
    visited = [0] * (n+1)
    result.append(dfs(i+1, visited))

for i in range(len(result)):
    if result[i] == max(result):
        print(i, end = ' ')

Solution/BOJ/1325 효율적인 해킹(dfs) - 시간초과.py


from distutils.core import setup
from rd import __version__

long_description = open('README.rst').read()

setup(name="rd",
    version=str(__version__),
    packages=["rd"],
    description="Package for serializing and deserializing of XRD and JRD documents",
    author="Jeremy Carbaugh",
    author_email="jcarbaugh@gmail.com",
    license="BSD",
    url="http://github.com/jcarbaugh/python-rd/",
    long_description=long_description,
    install_requires=["isodate", "pytz", "requests"],
    platforms=["any"],
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Natural Language :: English",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ],
)


import nonebot
import os
from nonebot.adapters.onebot.v11 import Event, Bot, MessageSegment
from .sql_sgin import data_select

def repla(li):
    lis = []
    for i in li:
        oew = i.replace('.amr', '')
        lis.append(oew)
    return lis

mu = nonebot.on_fullmatch(msg=r"纯宝唱首歌", priority=3, block=True)

@mu.got(key='', prompt="什么歌呢")
async def _(bot: Bot, event: Event):
    if data_select(event.get_user_id()) != None:
        if int(data_select(event.get_user_id())[2]) >= 20:
            l = repla(os.listdir(r'.\music'))
            s = str(event.get_message())
            if s in l:
                await bot.send(event=event, message=MessageSegment.record(file=rf'file:///E:\desktop\云酱bot\nonebotfile\nonebotfile\plugins\music\{s}.amr'))
            else:
                await mu.send(MessageSegment.text(f'目前仅支持{l}'))
        else:
            await bot.send(event=event, message=MessageSegment.text('好感度不够，纯宝不能给你唱歌'))
    else:
        await bot.send(event=event, message=MessageSegment.text('还...还不会唱歌...要你签到了,然后我再去学学'))


# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 09:43:25 2020

@author: Admin
"""

import tensorflow as tf
from tensorflow.keras import layers
import numpy as np

class OutputLayer(layers.Layer):
    def __init__(self, **kwargs):
        super(OutputLayer, self).__init__(**kwargs)

    def build(self, input_shapes):
        shape_wp1 = 5*input_shapes[1][1]
        shape_wp2 = shape_wp1
        self.wp1 = self.add_weight(name = "Start_index_pred",
                                   shape = (1, shape_wp1),
                                   initializer = "random_normal",
                                   trainable = True)
        self.wp2 = self.add_weight(name = "Start_index_pred",
                                   shape = (1, shape_wp2),
                                   initializer = "random_normal",
                                   trainable = True)
        super(OutputLayer, self).build(input_shapes)

    def call(self, inputs): # inputs comprises of: G(?, 800, 114) m1_tensor(?, 200, 114) and m2_tensor(?, 200, 114)
        G, m1_tensor, m2_tensor = inputs

        def concat_G(my_inputs):
            G, m_tensor = my_inputs
            result = tf.keras.backend.transpose(tf.keras.layers.concatenate([G, m_tensor], 0))  # result was of shape (10d, T) then transposed to (T, 10d)
            return result

        def output_layer(inputs_Gs):
            G_M1 = inputs_Gs
            m = 0
            for i in range(0, G_M1.get_shape()[0]): # i is of shape (10d, )
                scalar = tf.keras.backend.dot(self.wp1, tf.keras.backend.expand_dims(G_M1[i], 1))
                if m == 0:
                    p1 = scalar
                else:
                    p1 = tf.keras.layers.concatenate([p1, scalar], 1)
                m += 1
            p1 = tf.keras.backend.reshape(p1, [114])
            print("\np1 is: ", p1)
            return p1

        def output_layer1(input_G):
            G_M2 = input_G
            m = 0
            for i in range(0, G_M2.get_shape()[0]):
                scalar = tf.keras.backend.dot(self.wp2, tf.keras.backend.expand_dims(G_M2[i], 1))
                if m == 0:
                    p2 = scalar
                else:
                    p2 = tf.keras.layers.concatenate([p2, scalar], 1)
                m += 1
            p2 = tf.keras.backend.reshape(p2, [114])
            print("\np2 is: ", p2)
            print("\nFinished 2 for loops!!!!!!!!!!!!\n")
            return p2

        G_M1 = tf.keras.backend.map_fn(concat_G, (G, m1_tensor), dtype = 'float32')
        print("\nG_M1 is: ", G_M1)

        G_M2 = tf.keras.backend.map_fn(concat_G, (G, m2_tensor), dtype = 'float32')
        print("G_M2 is: ", G_M2)

        p1 = tf.keras.backend.map_fn(output_layer, (G_M1), dtype = 'float32')
        p2 = tf.keras.backend.map_fn(output_layer1, (G_M2), dtype = 'float32')

        print("\nOUT!!!\np1 is: ", p1)
        print("p2 is: ", p2)

        p1_pred = tf.keras.activations.softmax(p1)

        p2_pred = tf.keras.activations.softmax(p2)

        output_final = tf.keras.backend.stack([p1_pred, p2_pred], axis = 1)

        print("\nOutput_final is: ", output_final)
        print("Finished forming prediction vectors: " + str(output_final.get_shape()) + "\n")
        print("Trainable weight matrix is: ", self.trainable_weights)
        return output_final

if __name__ == "__main__":
    G_M1 = np.array([[1.2,2.0], [2.2,3.3], [35.1,36.1], [24.1,2.5], [5.1,6.1], [1.2,13.1]])
    G_M2 = np.array([[12.1,13.1], [23.1,2.4], [2.5,2.6], [35.1,3.6], [35.1,3.6], [35.1,3.6]])
    inputs = {}
    inputs["G_M1"] = tf.convert_to_tensor(G_M1, dtype = tf.float32)
    inputs["G_M2"] = tf.convert_to_tensor(G_M2, dtype = tf.float32)
    output_layer = OutputLayer()
    hi = output_layer(inputs)
    print(hi)
    print("End of file")


from future_diffusion.DiscoSetup import *
from future_diffusion.disco import *

import torch
import cv2
import io
import math
from PIL import ImageOps
import requests
from torch.nn import functional as F
import torchvision.transforms as T
import torchvision.transforms.functional as TF
import torch
import warnings
warnings.filterwarnings("ignore", category=UserWarning)

from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
from midas.transforms import Resize, NormalizeImage, PrepareForNet

# Initialize MiDaS depth model.
# It remains resident in VRAM and likely takes around 2GB VRAM.
# You could instead initialize it for each frame (and free it after each frame) to save VRAM.. but initializing it is slow.
default_models = {
    "midas_v21_small": f"{model_path}/midas_v21_small-70d6b9c8.pt",
    "midas_v21": f"{model_path}/midas_v21-f6b98070.pt",
    "dpt_large": f"{model_path}/dpt_large-midas-2f21e586.pt",
    "dpt_hybrid": f"{model_path}/dpt_hybrid-midas-501f0c75.pt",
    "dpt_hybrid_nyu": f"{model_path}/dpt_hybrid_nyu-2ce69ec7.pt",}

def init_midas_depth_model(midas_model_type="dpt_large", optimize=True):
    midas_model = None
    net_w = None
    net_h = None
    resize_mode = None
    normalization = None

    print(f"Initializing MiDaS '{midas_model_type}' depth model...")
    # load network
    midas_model_path = default_models[midas_model_type]

    if midas_model_type == "dpt_large": # DPT-Large
        midas_model = DPTDepthModel(
            path=midas_model_path,
            backbone="vitl16_384",
            non_negative=True,
        )
        net_w, net_h = 384, 384
        resize_mode = "minimal"
        normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
    elif midas_model_type == "dpt_hybrid": #DPT-Hybrid
        midas_model = DPTDepthModel(
            path=midas_model_path,
            backbone="vitb_rn50_384",
            non_negative=True,
        )
        net_w, net_h = 384, 384
        resize_mode="minimal"
        normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
    elif midas_model_type == "dpt_hybrid_nyu": #DPT-Hybrid-NYU
        midas_model = DPTDepthModel(
            path=midas_model_path,
            backbone="vitb_rn50_384",
            non_negative=True,
        )
        net_w, net_h = 384, 384
        resize_mode="minimal"
        normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
    elif midas_model_type == "midas_v21":
        midas_model = MidasNet(midas_model_path, non_negative=True)
        net_w, net_h = 384, 384
        resize_mode="upper_bound"
        normalization = NormalizeImage(
            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
        )
    elif midas_model_type == "midas_v21_small":
        midas_model = MidasNet_small(midas_model_path, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True})
        net_w, net_h = 256, 256
        resize_mode="upper_bound"
        normalization = NormalizeImage(
            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
        )
    else:
        print(f"midas_model_type '{midas_model_type}' not implemented")
        assert False

    midas_transform = T.Compose(
        [
            Resize(
                net_w,
                net_h,
                resize_target=None,
                keep_aspect_ratio=True,
                ensure_multiple_of=32,
                resize_method=resize_mode,
                image_interpolation_method=cv2.INTER_CUBIC,
            ),
            normalization,
            PrepareForNet(),
        ]
    )

    midas_model.eval()

    if optimize==True:
        if DEVICE == torch.device("cuda"):
            midas_model = midas_model.to(memory_format=torch.channels_last)
            midas_model = midas_model.half()

    midas_model.to(DEVICE)

    print(f"MiDaS '{midas_model_type}' depth model initialized.")
    return midas_model, midas_transform, net_w, net_h, resize_mode, normalization

#@title 1.5 Define necessary functions

# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869

import py3d_tools as p3dT
import disco_xform_utils as dxf

def interp(t):
    return 3 * t**2 - 2 * t ** 3

def perlin(width, height, scale=10, device=None):
    gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device)
    xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device)
    ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device)
    wx = 1 - interp(xs)
    wy = 1 - interp(ys)
    dots = 0
    dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys)
    dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys)
    dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys))
    dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys))
    return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale)

def perlin_ms(octaves, width, height, grayscale, device=device):
    out_array = [0.5] if grayscale else [0.5, 0.5, 0.5]
    # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0]
    for i in range(1 if grayscale else 3):
        scale = 2 ** len(octaves)
        oct_width = width
        oct_height = height
        for oct in octaves:
            p = perlin(oct_width, oct_height, scale, device)
            out_array[i] += p * oct
            scale //= 2
            oct_width *= 2
            oct_height *= 2
    return torch.cat(out_array)

def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True):
    out = perlin_ms(octaves, width, height, grayscale)
    if grayscale:
        out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0))
        out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB')
    else:
        out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1])
        out = TF.resize(size=(side_y, side_x), img=out)
        out = TF.to_pil_image(out.clamp(0, 1).squeeze())

    out = ImageOps.autocontrast(out)
    return out

def regen_perlin():
    if perlin_mode == 'color':
        init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
        init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
    elif perlin_mode == 'gray':
        init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
        init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
    else:
        init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
        init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)

    init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
    del init2
    return init.expand(batch_size, -1, -1, -1)

def fetch(url_or_path):
    if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):
        r = requests.get(url_or_path)
        r.raise_for_status()
        fd = io.BytesIO()
        fd.write(r.content)
        fd.seek(0)
        return fd
    return open(url_or_path, 'rb')

def read_image_workaround(path):
    """OpenCV reads images as BGR, Pillow saves them as RGB. Work around
    this incompatibility to avoid colour inversions."""
    im_tmp = cv2.imread(path)
    return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB)

def parse_prompt(prompt):
    if prompt.startswith('http://') or prompt.startswith('https://'):
        vals = prompt.rsplit(':', 2)
        vals = [vals[0] + ':' + vals[1], *vals[2:]]
    else:
        vals = prompt.rsplit(':', 1)
    vals = vals + ['', '1'][len(vals):]
    return vals[0], float(vals[1])

def sinc(x):
    return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))

def lanczos(x, a):
    cond = torch.logical_and(-a < x, x < a)
    out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))
    return out / out.sum()

def ramp(ratio, width):
    n = math.ceil(width / ratio + 1)
    out = torch.empty([n])
    cur = 0
    for i in range(out.shape[0]):
        out[i] = cur
        cur += ratio
    return torch.cat([-out[1:].flip([0]), out])[1:-1]

def resample(input, size, align_corners=True):
    n, c, h, w = input.shape
    dh, dw = size

    input = input.reshape([n * c, 1, h, w])

    if dh < h:
        kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)
        pad_h = (kernel_h.shape[0] - 1) // 2
        input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')
        input = F.conv2d(input, kernel_h[None, None, :, None])

    if dw < w:
        kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)
        pad_w = (kernel_w.shape[0] - 1) // 2
        input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')
        input = F.conv2d(input, kernel_w[None, None, None, :])

    input = input.reshape([n, c, h, w])
    return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)

def save_settings(args):
  setting_list = {
    'text_prompts': args.text_prompts,
    'image_prompts': args.image_prompts,
    'clip_guidance_scale': args.clip_guidance_scale,
    'tv_scale': args.tv_scale,
    'range_scale': args.range_scale,
    'sat_scale': args.sat_scale,
    # 'cutn': cutn,
    'cutn_batches': args.cutn_batches,
    'max_frames': args.max_frames,
    'interp_spline': args.interp_spline,
    # 'rotation_per_frame': rotation_per_frame,
    'init_image': args.init_image,
    'init_scale': args.init_scale,
    'skip_steps': args.skip_steps,
    # 'zoom_per_frame': zoom_per_frame,
    'frames_scale': args.frames_scale,
    'frames_skip_steps': frames_skip_steps,
    'perlin_init': args.perlin_init,
    'perlin_mode': args.perlin_mode,
    'skip_augs': args.skip_augs,
    'randomize_class': args.randomize_class,
    'clip_denoised': args.clip_denoised,
    'clamp_grad': args.clamp_grad,
    'clamp_max': args.clamp_max,
    'seed': args.seed,
    'fuzzy_prompt': args.fuzzy_prompt,
    'rand_mag': args.rand_mag,
    'eta': args.eta,
    'width': args.width_height[0],
    'height': args.width_height[1],
    'diffusion_model': diffusion_model,
    'use_secondary_model': use_secondary_model,
    'steps': args.steps,
    'diffusion_steps': args.diffusion_steps,
    'diffusion_sampling_mode': args.diffusion_sampling_mode,
    'ViTB32': args.ViTB32,
    'ViTB16': args.ViTB16,
    'ViTL14': args.ViTL14,
    'RN101': args.RN101,
    'RN50': args.RN50,
    'RN50x4': args.RN50x4,
    'RN50x16': args.RN50x16,
    'RN50x64': args.RN50x64,
    'cut_overview': str(args.cut_overview),
    'cut_innercut': str(args.cut_innercut),
    'cut_ic_pow': args.cut_ic_pow,
    'cut_icgray_p': str(args.cut_icgray_p),
    'key_frames': args.key_frames,
    'max_frames': args.max_frames,
    'midas_depth_model': args.midas_depth_model,
    'midas_weight': args.midas_weight,
    'near_plane': args.near_plane,
    'far_plane': args.far_plane,
    'fov': args.fov,
    'padding_mode': args.padding_mode,
    'sampling_mode': args.sampling_mode,
    'video_init_path':args.video_init_path,
    'extract_nth_frame':args.extract_nth_frame,
    'video_init_seed_continuity': args.video_init_seed_continuity,
    'turbo_mode':turbo_mode,
    'turbo_steps':turbo_steps,
    'turbo_preroll':turbo_preroll,
  }
  # print('Settings:', setting_list)
  with open(f"{batchFolder}/{batch_name}({args.batchNum})_settings.txt", "w+") as f:   #save settings
    json.dump(setting_list, f, ensure_ascii=False, indent=4)


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 11 17:08:51 2017

@author: 5000 Series
"""

import statistics

my_lis = [12,45,235,45,4,45,4,54,5,45,4,5]

print(statistics.mean(my_lis))

my_lis = [1,2,3,4,5]

try:
    print(statistics.mode(my_lis))
except Exception as exp:
    print("Error: ",exp)

Python Programming A Concise Introduction by Wesleyan University/Week 4/stats.py


from __future__ import division

import itertools
import numpy as np
from numpy.testing import assert_allclose, assert_equal, assert_raises
from pyoperators import (
    Cartesian2SphericalOperator, CompositionOperator, ConstantOperator,
    HardThresholdingOperator, IdentityOperator, MultiplicationOperator,
    NormalizeOperator, NumexprOperator, PowerOperator, ReciprocalOperator,
    RoundOperator, SqrtOperator, SquareOperator, SoftThresholdingOperator,
    Spherical2CartesianOperator)
from pyoperators.utils import product
from pyoperators.utils.testing import (
    assert_is_instance, assert_is_type, assert_same)

def test_cartesian_spherical():
    vecs = ((1, 0, 0), (0, 1, 0), (0, 0, 1),
            ((1, 0, 0), (0, 1, 0), (0, 0, 1)),
            (((1, 0, 0), (0, 1, 0)),))
    shapes = ((), (), (), (3,), (1, 2))

    def func(c, v, s, d):
        c2s = Cartesian2SphericalOperator(c, degrees=d)
        s2c = Spherical2CartesianOperator(c, degrees=d)
        a = s2c(c2s(v))
        assert_equal(a.shape, s + (3,))
        assert_allclose(a, v, atol=1e-16)
    for c in Cartesian2SphericalOperator.CONVENTIONS:
        for v, s in zip(vecs, shapes):
            for d in (False, True):
                yield func, c, v, s, d

def test_cartesian_spherical_error():
    assert_raises(TypeError, Cartesian2SphericalOperator, 3)
    assert_raises(ValueError, Cartesian2SphericalOperator, 'bla')
    op = Cartesian2SphericalOperator('zenith,azimuth')

    def func(i, o):
        if i.shape == (3,) and o.shape == (2,):
            op(i, o)
            return
        assert_raises(ValueError, op.__call__, i, o)
    for i, o in itertools.product((np.array(1.), np.zeros(2), np.zeros(3)),
                                  (np.array(1.), np.zeros(2), np.zeros(3))):
        yield func, i, o

def test_cartesian_spherical_rules():
    def func(c1, c2):
        op1 = Cartesian2SphericalOperator(c1)
        op2 = Spherical2CartesianOperator(c2)
        op = op1(op2)
        if c1 == c2:
            assert_is_type(op, IdentityOperator)
        else:
            assert_is_type(op, CompositionOperator)
    for c1 in 'zenith,azimuth', 'azimuth,elevation':
        op = Cartesian2SphericalOperator(c1)
        assert_is_type(op.I, Spherical2CartesianOperator)
        assert_equal(op.convention, c1)
        for c2 in 'zenith,azimuth', 'azimuth,elevation':
            yield func, c1, c2

def test_spherical_cartesian():
    dirs_za = ((0, 0), (20, 0), (130, 0), (10, 20), (20, 190),
               ((0, 0), (20, 0), (130, 0), (10, 20), (20, 130)),
               (((0, 0), (20, 200), (130, 300)),))
    dirs_az = ((0, 0), (0, 20), (0, 130), (20, 10), (190, 20),
               ((0, 0), (0, 20), (0, 130), (20, 10), (130, 20)),
               (((0, 0), (200, 20), (300, 130)),))
    dirs_ea = ((90, 0), (70, 0), (-40, 0), (80, 20), (70, 190),
               ((90, 0), (70, 0), (-40, 0), (80, 20), (70, 130)),
               (((90, 0), (70, 200), (-40, 300)),))
    dirs_ae = ((0, 90), (0, 70), (0, -40), (20, 80), (190, 70),
               ((0, 90), (0, 70), (0, -40), (20, 80), (130, 70)),
               (((0, 90), (200, 70), (300, -40)),))
    shapes = ((), (), (), (), (), (5,), (1, 3))

    op_ref = Spherical2CartesianOperator('zenith,azimuth')
    refs = [op_ref(np.radians(v)) for v in dirs_za]

    def func(c, v, s, d, r):
        orig = v
        if not d:
            v = np.radians(v)
        s2c = Spherical2CartesianOperator(c, degrees=d)
        c2s = Cartesian2SphericalOperator(c, degrees=d)
        assert_allclose(s2c(v), r)
        a = c2s(s2c(v))
        if not d:
            a = np.degrees(a)
        assert_equal(a.shape, s + (2,))
        assert_allclose(a, orig, atol=1e-16)
    for c, vs in (('zenith,azimuth', dirs_za),
                  ('azimuth,zenith', dirs_az),
                  ('elevation,azimuth', dirs_ea),
                  ('azimuth,elevation', dirs_ae)):
        for v, s, r in zip(vs, shapes, refs):
            for d in (False, True):
                yield func, c, v, s, d, r

def test_spherical_cartesian_error():
    assert_raises(TypeError, Spherical2CartesianOperator, 3)
    assert_raises(ValueError, Spherical2CartesianOperator, 'bla')
    op = Spherical2CartesianOperator('zenith,azimuth')

    def func(i, o):
        if i.shape == (2,) and o.shape == (3,):
            op(i, o)
            return
        assert_raises(ValueError, op.__call__, i, o)
    for i, o in itertools.product((np.array(1.), np.zeros(2), np.zeros(3)),
                                  (np.array(1.), np.zeros(2), np.zeros(3))):
        yield func, i, o

def test_spherical_cartesian_rules():
    def func(c1, c2):
        op1 = Spherical2CartesianOperator(c1)
        op2 = Cartesian2SphericalOperator(c2)
        op = op1(op2)
        if c1 == c2:
            assert_is_type(op, IdentityOperator)
        else:
            assert_is_type(op, CompositionOperator)
    for c1 in 'zenith,azimuth', 'azimuth,elevation':
        op = Spherical2CartesianOperator(c1)
        assert_is_type(op.I, Cartesian2SphericalOperator)
        assert_equal(op.convention, c1)
        for c2 in 'zenith,azimuth', 'azimuth,elevation':
            yield func, c1, c2

def test_rounding():
    a = np.array([-3.5, -3, -2.6, -2.5, -2.4, 0, 0.2, 0.5, 0.9, 1, 1.5])
    r = RoundOperator('rtz')
    yield assert_equal, r(a), [-3, -3, -2, -2, -2, 0, 0, 0, 0, 1, 1]
    #r = RoundOperator('rti')
    #yield assert_equal, r(a), [-4, -3, -3, -3, -3, 0, 1, 1, 1, 2]
    r = RoundOperator('rtmi')
    yield assert_equal, r(a), [-4, -3, -3, -3, -3, 0, 0, 0, 0, 1, 1]
    r = RoundOperator('rtpi')
    yield assert_equal, r(a), [-3, -3, -2, -2, -2, 0, 1, 1, 1, 1, 2]
    #r = RoundOperator('rhtz')
    #yield assert_equal, r(a), [-3, -3, -3, -2, -2, 0, 0, 0, 1, 1, 1]
    #r = RoundOperator('rhti')
    #yield assert_equal, r(a), [-4, -3, -3, -3, -2, 0, 0, 1, 1, 2]
    r = RoundOperator('rhtmi')
    yield assert_equal, r(a), [-4, -3, -3, -3, -2, 0, 0, 0, 1, 1, 1]
    r = RoundOperator('rhtpi')
    yield assert_equal, r(a), [-3, -3, -3, -2, -2, 0, 0, 1, 1, 1, 2]
    r = RoundOperator('rhte')
    yield assert_equal, r(a), [-4, -3, -3, -2, -2, 0, 0, 0, 1, 1, 2]
    #r = RoundOperator('rhto')
    #yield assert_equal, r(a), [-3, -3, -3, -2, -2, 0, 0, 0, 1, 1, 1]
    #r = RoundOperator('rhs')
    #mask = np.array([True,True,False,True,True,True,False,True,True], np.bool)
    #result = r(a)
    #yield assert_equal, result[mask], [-3,-3,-2,0,0,1,1]
    #yield assert_, result[2] in (-3,-2)
    #yield assert_, result[-4] in (0,1)

def test_normalize():
    n = NormalizeOperator()

    def func(shape):
        vec = np.arange(product(shape)).reshape(shape)
        exp = vec / np.sqrt(np.sum(vec ** 2, axis=-1))[..., None]
        assert_same(n(vec), exp)
    for shape in ((2,), (4,), (2, 3), (4, 5, 2)):
        yield func, shape

def test_numexpr1():
    d = 7.
    op = NumexprOperator('2.*exp(input)+d', {'d': d})
    assert op(3.) == 2*np.exp(3.)+d

def test_numexpr2():
    op = NumexprOperator('3*input') + NumexprOperator('2*input')
    assert_equal(op(np.arange(10)), 5*np.arange(10))

def test_power():
    values = -1, 0, 0.5, 1, 2, 3
    cls = (ReciprocalOperator, ConstantOperator, SqrtOperator,
           IdentityOperator, SquareOperator, PowerOperator)

    def func(n, c):
        op = PowerOperator(n)
        assert_is_type(op, c)
        if isinstance(op, PowerOperator):
            assert_equal(op.n, n)
    for v, c in zip(values, cls):
        yield func, v, c

def test_power_rule_comp():
    ops = (ReciprocalOperator(), SqrtOperator(), SquareOperator(),
           PowerOperator(2.5))
    op = CompositionOperator(ops)
    assert_is_type(op, PowerOperator)
    assert_equal(op.n, -2.5)

def test_power_rule_mul():
    ops = (ReciprocalOperator(), SqrtOperator(), SquareOperator(),
           PowerOperator(2.5))
    op = MultiplicationOperator(ops)
    assert_is_type(op, PowerOperator)
    assert_equal(op.n, 4)

def test_hard_thresholding():
    x = [-1., -0.2, -0.1, 0, 0.2, 0.1, 2, 3]
    lbda = 0.2
    H = HardThresholdingOperator(lbda)
    expected = [-1, 0, 0, 0, 0, 0, 2, 3]
    assert_equal(H(x), expected)
    x = np.array(x)
    H(x, x)
    assert_equal(x, expected)
    lbda2 = [0.3, 0.1, 2]
    shape = np.asarray(lbda2).shape
    G = HardThresholdingOperator(lbda2)
    assert_equal(G.shapein, shape)
    K = G(H)
    assert_is_instance(K, HardThresholdingOperator)
    assert_equal(K.a, np.maximum(lbda, lbda2))
    assert_equal(K.shapein, shape)
    K = H(G)
    assert_is_instance(K, HardThresholdingOperator)
    assert_equal(K.a, np.maximum(lbda, lbda2))
    assert_equal(K.shapein, shape)

    H = HardThresholdingOperator([0, 0])
    assert_is_instance(H, IdentityOperator)
    assert_equal(H.shapein, (2,))

    H = HardThresholdingOperator(0)
    assert_is_instance(H, IdentityOperator)
    assert H.flags.square
    assert_equal(H.flags.shape_input, 'implicit')
    assert_equal(H.flags.shape_output, 'implicit')

def test_soft_thresholding():
    x = [-1., -0.2, -0.1, 0, 0.1, 0.2, 2, 3]
    lbda = np.array(0.2)
    S = SoftThresholdingOperator(lbda)
    expected = [-1, 0, 0, 0, 0, 0, 2, 3] - lbda * [-1, 0, 0, 0, 0, 0, 1, 1]
    assert_equal(S(x), expected)
    x = np.array(x)
    S(x, x)
    assert_equal(x, expected)
    lbda2 = [0.3, 0.1, 2]
    shape = np.asarray(lbda2).shape
    T = SoftThresholdingOperator(lbda2)
    assert_equal(T.shapein, shape)

    S = SoftThresholdingOperator([0, 0])
    assert_is_instance(S, IdentityOperator)
    assert_equal(S.shapein, (2,))

    S = SoftThresholdingOperator(0)
    assert_is_instance(S, IdentityOperator)
    assert S.flags.square
    assert_equal(S.flags.shape_input, 'implicit')
    assert_equal(S.flags.shape_output, 'implicit')


n = 10
# n = 12

def solution(n):
    answer = 0
    min = 1000000
    for x in range(1, n):
        tmp = n % x
        if tmp == 1 and x < min:
            min = x
    answer = min
    return answer

print(solution(n))

나머지가1이되는수찾기.py


import json

class Trie:
    def find_matches(self, document):
        matches = set()

        for i in range(len(document)):
            level = self.root  # dictionary to hold current level
            for j in range(i, len(document)):
                if document[j] not in level:
                    level = self.root
                    break
                else:
                    level = level[document[j]]
                    if self.end_symbol in level:
                        matches.add(document[i:j+1])
        return matches

    # don't touch below this line

    def add(self, word):
        current = self.root
        for letter in word:
            if letter not in current:
                current[letter] = {}
            current = current[letter]
        current[self.end_symbol] = True

    def __init__(self):
        self.root = {}
        self.end_symbol = "*"

def test(words, document):
    trie = Trie()
    for word in words:
        trie.add(word)
    print("Trie:")
    print(json.dumps(trie.root, sort_keys=True, indent=2))
    print("-------------------------------------")
    matches = trie.find_matches(document)
    print(f"Document: '{document}'")
    print("Matches:")
    for match in sorted(matches):
        print(f" - {match}")
    print("=====================================")

def main():
    test(["bad", "baddie", "badguy", "suck"], "the badguy really sucks")
    test(["be", "bad", "back", "bat"], "he is back at bat")

main()


from flask import Flask, flash, request, redirect, url_for, render_template
import torch
import yaml
import os
import cv2
from IPython.core.magic import register_line_cell_magic
from IPython.display import Image, clear_output  # to display images
# from app import app
import urllib.request
from werkzeug.utils import secure_filename
import shutil
from timeit import default_timer as timer

UPLOAD_FOLDER = 'static/uploads/'

app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route("/")
def home():
    return render_template("try1.html")

@app.route('/', methods=['POST'])
def upload_image():
    start = timer()
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        f = os.path.join('static/uploads', filename)
        os.system(f'python yolov5\detect.py --weights ACV_pro_YOLOv5s_best.pt --img 416 --conf 0.4 --source {f}')

        all_subdirs = [os.path.join('runs\detect',d) for d in os.listdir('runs\detect')]
        latest_subdir = max(all_subdirs, key=os.path.getmtime)
        f_t = os.listdir(latest_subdir)[0]
        print(f_t)
        file_to_move = os.path.join(latest_subdir, f_t)
        dest = os.path.join(r'static\uploads',f_t)

        shutil.move( file_to_move, dest)
                #print('upload_image filename: ' + filename)
        end = timer()
        flash('Detected in:')
        flash(abs(end - start))
        flash('Image successfully uploaded and detected below')

        return render_template('try1.html', filename=filename)
    else:
        flash('Allowed image types are -> png, jpg, jpeg, gif')
        return redirect(request.url)

@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return redirect(url_for('static', filename='uploads/' + filename), code=301)

@app.route("/<name>")
def user(name):
    return "Hello {name}".format(name=name)

@app.route("/admin")
def admin():
    return redirect(url_for("home"))

if __name__ == "__main__":
    app.run(debug=True)


import matplotlib.pyplot as plt
import hashlib
from z8 import hyperLogLog, h_2

MAX32 = 2**32

n_vals = [n for n in range(1,10001)]

def SHA32(x):
    return (int.from_bytes(hashlib.sha512(str(x).encode()).digest(), 'big') % MAX32)/MAX32

def bblSort(M, k):
    x = M[k-1]
    i = k-2
    while M[i] > x:
        i -= 1
    M[i+2:k] = M[i+1:k-1]
    M[i+1] = x

def minCount(MM, h, k):
    M = [1] * k
    for x in MM:
        hash = h(x)
        if hash < M[k-1] and hash not in M:
            M[k-1] = hash
            bblSort(M, k)
    if M[k-1] == 1:
        return sum(1 for a in M if a != 1)
    else:
        return (k-1)/M[k-1]

if __name__ == "__main__":
    ratios_hll = []
    ratios_mc = []
    counter = 1
    for n in n_vals:
        print(n)
        MM = [i for i in range(counter,counter+n)]
        ratios_hll.append(hyperLogLog(MM,5,h_2)[1]/n)
        ratios_mc.append(minCount(MM,SHA32,5)/n)
        counter += n

    plt.scatter(n_vals, ratios_mc, s=1, label='minCount')
    plt.scatter(n_vals, ratios_hll, s=1, label='HyperLogLog')
    plt.title("minCount vs HyperLogLog")
    plt.legend()
    plt.xlabel("n")
    plt.ylabel("n_est/n")
    plt.savefig("L3/charts/z8_vs.png", dpi=300)
    plt.close()


def turtle(coord, direction):
	x = coord[0]
	y = coord[1]
	moove = yield
	while moove:
		if moove=='f':
			if direction==0:
				x+=1
			elif direction==1:
				y+=1
			elif direction==2:
				x-=1
			else:
				y-=1
		elif moove=='l':
			direction = (direction+1)%4
		elif moove=='r':
			direction = (direction-1)%4
		moove = yield (x, y)

# robo = turtle((0,0),0)
# start = next(robo)
# for c in "flfrffrffr":
# 	print(*robo.send(c))

# "f" (переход на 1 шаг вперёд), "l" (поворот против часовой стрелки на 90°) и "r" (поворот по часовой стрелке на 90°)


from operator import itemgetter
from itertools import groupby

def stime_to_decimal(s):
    """Lololo."""
    return s.hour + s.minute / 60

def group_time(records):
    """Lololo."""
    records.sort(key=itemgetter(6, 1))
    result = [
        [stime_to_decimal(time), *[item[0] for item in group]]
        for time, group in groupby(records, key=itemgetter(6))
    ]
    return result

def group_sensor(records):
    """Lololo."""
    records.sort(key=itemgetter(1))
    result = ['X', *[key[1] for key, _ in groupby(
        records, key=itemgetter(1, 2))]]
    return result

def group_category(records):
    """Lololo."""
    records.sort(key=itemgetter(3))
    result = [{
        'id': key[0],
        'name': key[1],
        'measure': key[2],
        'data': [*[item for item in group]],
    } for key, group in groupby(records, key=itemgetter(3, 4, 5))]

    for item in result:
        item['rows'] = group_time(item['data'])
        item['cols'] = group_sensor(item['data'])
        item.pop('data')

    return result

# [
#   {
#     "cols": [
#       "X",
#       "Sens 1",
#       "Sens 2"
#     ],
#     "id": 1,
#     "measure": "AAA",
#     "name": "Cat 1",
#     "rows": [
#       [
#         10.916666666666666,
#         17.0,
#         14.0
#       ]
#     ]
#   },
#   {
#     "cols": [
#       "X",
#       "Sens 3"
#     ],
#     "id": 2,
#     "measure": "AAA",
#     "name": "Cat 2",
#     "rows": [
#       [
#         10.916666666666666,
#         13.0
#       ]
#     ]
#   }
# ]


import logging

def getLogger(fileName) -> logging:
    # create logger
    logger = logging.getLogger(fileName)
    logger.setLevel(logging.ERROR)
    ch  = logging.FileHandler('logs/' + fileName + '.log')
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    return logger


"""
Transformers for video interaction events.

NOTE: Currently Open edX only emits legacy events for video interaction i.e.
- load_video
- play_video
- stop_video
- complete_video (proposed)
- pause_video
- seek_video

Currently, mobile apps emits these events using the new names but will be
added in edx-platform too. Therefore, we are adding support for legacy event names
as well as new names.

The (soon to be) updated event names are as following:
- edx.video.loaded
- edx.video.played
- edx.video.stopped
- edx.video.paused
- edx.video.position.changed
- edx.video.completed (proposed)
"""
from datetime import timedelta

from isodate import duration_isoformat

from event_routing_backends.helpers import convert_seconds_to_iso, make_video_block_id
from event_routing_backends.processors.caliper.registry import CaliperTransformersRegistry
from event_routing_backends.processors.caliper.transformer import CaliperTransformer

EVENTS_ACTION_MAP = {
    'load_video': 'Retrieved',
    'edx.video.loaded': 'Retrieved',

    'play_video': 'Started',
    'edx.video.played': 'Started',

    'stop_video': 'Ended',
    'edx.video.stopped': 'Ended',

    'complete_video': 'Ended',
    'edx.video.completed': 'Ended',

    'pause_video': 'Paused',
    'edx.video.paused': 'Paused',

    'seek_video': 'JumpedTo',
    'edx.video.position.changed': 'JumpedTo',
}

class BaseVideoTransformer(CaliperTransformer):
    """
    Base transformer for video interaction events.
    """
    type = 'MediaEvent'

    def get_action(self):
        """
        Return action for the caliper event.

        Returns:
            str
        """
        return EVENTS_ACTION_MAP[self.get_data('name', True)]

    def get_object(self):
        """
        Return object for the caliper event.

        Returns:
            str
        """
        self.event_version = "1.0"
        self.backend_name = 'caliper'
        caliper_object = self.transformed_event['object']
        data = self.get_data('data')
        course_id = self.get_data('context.course_id', True)
        video_id = self.get_data('data.id', True)
        object_id = make_video_block_id(course_id=course_id, video_id=video_id)

        caliper_object.update({
            'id': object_id,
            'type': 'VideoObject',
            'duration': duration_isoformat(timedelta(
                    seconds=data.get('duration', 0)
            ))
        })
        caliper_object['extensions'] = {'course_id': course_id}
        extensions = self.extract_subdict_by_keys(
            data, ['id', 'new_time', 'old_time', 'currentTime']
        )

        if 'currentTime' in extensions:
            extensions['currentTime'] = convert_seconds_to_iso(extensions['currentTime'])
        if 'new_time' in extensions:
            extensions['new_time'] = convert_seconds_to_iso(seconds=extensions['new_time'])
        if 'old_time' in extensions:
            extensions['old_time'] = convert_seconds_to_iso(seconds=extensions['old_time'])
        caliper_object['extensions'].update(extensions)

        return caliper_object

@CaliperTransformersRegistry.register('load_video')
@CaliperTransformersRegistry.register('edx.video.loaded')
class LoadVideoTransformer(BaseVideoTransformer):
    """
    Transform the events fired when a video is loaded.
    """
    type = 'Event'

@CaliperTransformersRegistry.register('stop_video')
@CaliperTransformersRegistry.register('edx.video.stopped')
@CaliperTransformersRegistry.register('complete_video')
@CaliperTransformersRegistry.register('edx.video.completed')
class StopVideoTransformer(BaseVideoTransformer):
    """
    Transform the events fired when a video is completed.

    Please note that "complete_video" doesn't exist currently but is
    expected to be added.
    """

@CaliperTransformersRegistry.register('play_video')
@CaliperTransformersRegistry.register('edx.video.played')
@CaliperTransformersRegistry.register('pause_video')
@CaliperTransformersRegistry.register('edx.video.paused')
class PlayPauseVideoTransformer(BaseVideoTransformer):
    """
    Transform the events fired when a video is played or paused.
    """
    additional_fields = ('target', )

    def get_object(self):
        """
        Return transformed object for the caliper event.

        Returns:
            dict
        """
        caliper_object = super().get_object()

        # currentTime is included in the `target` of transformed event
        # therefore no need to include it in the `extensions`.
        caliper_object['extensions'].pop('currentTime', None)

        return caliper_object

    def get_target(self):
        """
        Return target for the caliper event.

        Returns:
            str
        """
        current_time = convert_seconds_to_iso(
            seconds=self.get_data('data.currentTime')
        )

        return {
            'id': self.transformed_event['object']['id'],
            'type': 'MediaLocation',
            'currentTime': current_time
        }

@CaliperTransformersRegistry.register('seek_video')
@CaliperTransformersRegistry.register('edx.video.position.changed')
class SeekVideoTransformer(BaseVideoTransformer):
    """
    Transform the events fired when a video is seeked.
    """


# coding: utf-8

# In[101]:

import requests
from bs4 import BeautifulSoup

r=requests.get("https://pythonhow.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/")
c=r.content

soup=BeautifulSoup(c,"html.parser")

all=soup.find_all("div",{"class":"propertyRow"})

#remove all \n in the string
all[0].find("h4",{"class":"propPrice"}).text.replace("\n","").replace(" ","")

page_nr=soup.find_all("a",{"class":"Page"})[-1].text

# In[102]:

l=[]
base_url="https://pythonhow.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/t=0&s="
for page in range(0,int(page_nr)*10,10):
    print(base_url+str(page)+".html")
    r=requests.get(base_url+str(page)+".html")
    c=r.content
    soup=BeautifulSoup(c,"html.parser")
    all=soup.find_all("div",{"class":"propertyRow"})
    for item in all:
        d={}
        d["Address"]=item.find_all("span",{"class","propAddressCollapse"})[0].text
        try:
            d["Locality"]=item.find_all("span",{"class","propAddressCollapse"})[1].text
        except:
            d["Locality"]=None

        d["Price"]=item.find("h4",{"propPrice"}).text.replace("\n","").replace(" ","")

        try:
            d["Beds"]=item.find("span",{"class","infoBed"}).find("b").text
        except:
            d["Beds"]=None

        try:
            d["Area"]=item.find("span",{"class","infoSqFt"}).find("b").text
        except:
            d["Area"]=None

        try:
            d["Full Baths"]=item.find("span",{"class","infoValueFullBath"}).find("b").text
        except:
            d["Full Baths"]=None

        try:
            d["Half Baths"]=item.find("span",{"class","infoValueHalfBath"}).find("b").text
        except:
            d["Half Baths"]=None

        for column_group in item.find_all("div",{"class":"columnGroup"}):
    #         print(column_group)
            for feature_group, feature_name in zip(column_group.find_all("span",{"class":"featureGroup"}),column_group.find_all("span",{"class":"featureName"})):
    #             print(feature_group.text, feature_name.text)
                if "Lot Size" in feature_group.text:
                    d["Lot Size"]=feature_name.text
        l.append(d)

# In[97]:

len(l)

# In[103]:

import pandas
df=pandas.DataFrame(l)
df

# In[105]:

df.to_csv("output.csv")

# In[ ]:
# Address Area    Beds    Full Baths  Half Baths  Locality    Lot Size    Price
# 0   0 Gateway   None    None    None    None    Rock Springs, WY 82901  NaN $725,000
# 1   1003 Winchester Blvd.   None    4   4   None    Rock Springs, WY 82901  0.21 Acres  $452,900
# 2   600 Talladega   3,154   5   3   None    Rock Springs, WY 82901  NaN $396,900
# 3   3239 Spearhead Way  3,076   4   3   1   Rock Springs, WY 82901  Under 1/2 Acre, $389,900
# 4   522 Emerald Street  1,172   3   3   None    Rock Springs, WY 82901  Under 1/2 Acre, $254,000
# 5   1302 Veteran's Drive    1,932   4   2   None    Rock Springs, WY 82901  0.27 Acres  $252,900
# 6   1021 Cypress Cir    1,676   4   3   None    Rock Springs, WY 82901  Under 1/2 Acre, $210,000
# 7   913 Madison Dr  1,344   3   2   None    Rock Springs, WY 82901  Under 1/2 Acre, $209,000
# 8   1344 Teton Street   1,920   3   2   None    Rock Springs, WY 82901  Under 1/2 Acre, $199,900
# 9   4 Minnies Lane  1,664   3   2   None    Rock Springs, WY 82901  2.02 Acres  $196,900
# 10  9339 Sd 26900   2,560   None    None    None    Rocksprings, TX 78880   NaN $1,700,000
# 11  RR674P13 Hwy 377    2,000   None    None    None    Rocksprings, TX 78880   NaN $1,100,000
# 12  0 Hwy 41    None    None    None    None    Rocksprings, TX 78880   NaN $1,080,000
# 13  9339 Sd 26900   2,560   None    None    None    Rocksprings, TX 78880   NaN $908,350
# 14  CR450 Hwy 377   None    None    None    None    Rocksprings, TX 78880   NaN $905,000
# 15  Cr 240 Cr 240   1,398   None    None    None    Rocksprings, TX 78880   NaN $695,000
# 16  RR674 Hwy 377   1,738   None    None    None    Rocksprings, TX 78880   NaN $605,000
# 17  9770a Sd 26900  1,080   None    None    None    Rocksprings, TX 78880   NaN $559,805
# 18  Lot17 CR 2630   None    None    None    None    Rocksprings, TX 78880   NaN $504,000
# 19  Tr12,16 CR 520  None    None    None    None    Rocksprings, TX 78880   NaN $410,000
# 20  32575 S Shadow Mountain Road    2,318   3   2   None    Black Canyon City, AZ 85324 NaN $299,900
# 21  32750 S Shangrila Drive 2,120   3   2   None    Black Canyon City, AZ 85324 NaN $167,500
# 22  0000 Black Canyon Highway   None    None    None    None    Black Canyon City, AZ 85324 5 Acres $150,000
# 23  34775 S CHOLLA Drive    1,220   3   2   None    Black Canyon City, AZ 85324 NaN $129,500
# 24  33403 S. HA-WA-SI TERRACE   2,000   4   2   None    BLACK CANYON CITY, AZ 85324 NaN $129,000
# 25  34263 S Bertha Street   2,260   5   2   None    Black Canyon City, AZ 85324 NaN $80,000
# 26  33160 S Canyon Road 1,248   3   2   None    Black Canyon City, AZ 85324 NaN $77,900
# 27  19421 E Todd Evans Road 1,404   3   2   None    Black Canyon City, AZ 85324 NaN $70,500
# 28  18688 E AGUA Vista  None    None    None    None    Black Canyon City, AZ 85324 0.7 Acres   $70,000
# 29  50600 N Old Black Canyon Road   None    None    None    None    Black Canyon City, AZ 85324 3 Acres $67,500
# 30  20101 E SQUAW VALLEY Road   None    None    None    None    Black Canyon City, AZ 85324 NaN $54,900
# 31  33259 S Canyon Road 1,056   3   1   None    Black Canyon City, AZ 85324 NaN $45,600
# 32  34558 S ROADRUNNER RD   784 2   1   None    Black Canyon City, AZ 85324 Under 1/2 Acre  $40,000
# 33  19260 E Scenic Loop Road    None    None    None    None    Black Canyon City, AZ 85324 2.35 Acres  $30,000
# 34  19000 E MAREN Avenue    None    None    None    None    Black Canyon City, AZ 85324 2.05 Acres  $29,000
# 35  19350 E SAGUARO Drive   None    None    None    None    Black Canyon City, AZ 85324 0.73 Acres  $28,995
# 36  20650 E Amethyst Place  None    None    None    None    Black Canyon City, AZ 85324 0.31 Acres  $15,000


import gensim as gensim
import numpy as np
from nltk.tokenize import RegexpTokenizer
# from stop_words import get_stop_words
from nltk.stem.porter import PorterStemmer
from gensim import corpora, models, similarities
import gensim
from nltk.corpus import brown
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.lancaster import LancasterStemmer
from gensim import corpora, models, similarities

'''
gensim的lda模型实践03

'''

tokenizer = RegexpTokenizer(r'\w+')
# en_stop=[]
# with open("stopwords.txt", "r", encoding='UTF-8') as f:  # 读文本
# # create English stop words list
#     en_stop=f.readlines()
courses =[]
with open("coursera_corpus.txt", "r", encoding='UTF-8') as f:  # 读文本
    # create English stop words list
    courses =f.readlines()
courses_name = [course.split('\t')[0] for course in courses]
# print(courses_name[0:10])
# print(brown.readme())
# print(brown.words()[0:10])
# print(brown.tagged_words()[0:10])
# print(len(brown.words()))

texts_lower = [[word for word in document.lower().split()] for document in courses]

#注意其中很多标点符号和单词是没有分离的，所以我们引入nltk的word_tokenize函数，并处理相应的数据：
texts_tokenized = [[word.lower() for word in word_tokenize(document)] for document in courses]
english_stopwords = stopwords.words('english')
texts_filtered_stopwords = [[word for word in document if not word in english_stopwords] for document in
                            texts_tokenized]
#停用词被过滤了，不过发现标点符号还在，这个好办，我们首先定义一个标点符号list:
english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%', '...']
texts_filtered = [[word for word in document if not word in english_punctuations] for document in texts_filtered_stopwords]

#更进一步，我们对这些英文单词词干化（Stemming)
st = LancasterStemmer()
texts_stemmed = [[st.stem(word) for word in docment] for docment in texts_filtered]

#去掉在整个语料库中出现次数为1的低频词
all_stems = sum(texts_stemmed, [])
stems_once = set(stem for stem in set(all_stems) if all_stems.count(stem) == 1)
texts = [[stem for stem in text if stem not in stems_once] for text in texts_stemmed]

dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]

lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=10)#这里我们拍脑门决定训练topic数量为10的LSI模型：
index = similarities.MatrixSimilarity(lsi[corpus])
ml_course = texts[210]
ml_bow = dictionary.doc2bow(ml_course)
ml_lsi = lsi[ml_bow]
sims = index[ml_lsi]
sort_sims = sorted(enumerate(sims), key=lambda item: -item[1])

# print(sort_sims[0:10])
#取按相似度排序的前10门课程：
for i,v in sort_sims[0:10]:
    print(courses_name[i],v)


from django.urls import path
from . import views

app_name = 'TestAuthenticate' # if you are writing this in anchor tag <a> you have to write " name='' " of urls in html files

urlpatterns = [
    path('', views.home, name='homepage'),
    path('register/', views.register, name='registerpage'),
    path('login/', views.login_function, name='loginpage'),
    path('logout/', views.logout_user, name='logout'),
]


#!/usr/bin/env python3
import re
import sys
import socket
import dns.query
import dns.message
import dns.resolver
import dns.reversename
from dns.dnssec import algorithm_to_text
from dns.zone import *
from time import sleep
from time import time
import argparse
import urllib

DNS_PORT_NUMBER = 53
DNS_QUERY_TIMEOUT = 4.0

class DnsHelper:
    def __init__(self, domain, ns_server=None, request_timeout=3.0, proto="tcp"):
        self._domain = domain
        self._proto = proto
        if ns_server:
            self._res = dns.resolver.Resolver(configure=False)
            self._res.nameservers = [ns_server]
        else:
            self._res = dns.resolver.Resolver(configure=True)
        # Set timing
        self._res.timeout = request_timeout
        self._res.lifetime = request_timeout

    def check_tcp_dns(self, address):
        """
        Function to check if a server is listening at port 53 TCP. This will aid
        in IDS/IPS detection since a AXFR will not be tried if port 53 is found to
        be closed.
        """
        s = socket.socket()

        s.settimeout(DNS_QUERY_TIMEOUT)
        try:
            s.connect((address, DNS_PORT_NUMBER))
        except Exception:
            return False
        else:
            return True

    def resolve(self, target, type, ns=None):
        """
        Function for performing general resolution types returning the RDATA
        """
        if ns:
            res = dns.resolver.Resolver(configure=False, )
            res.nameservers = [ns]
        else:
            res = dns.resolver.Resolver(configure=True)

        tcp = True if self._proto == "tcp" else False
        answers = res.query(target, type, tcp=tcp)
        return answers

    def query(self, q, where, timeout=None, port=53, af=None, source=None, source_port=0, one_rr_per_rrset=False):
        if self._proto == "tcp":
            return dns.query.tcp(q, where, timeout, port, af, source, source_port, one_rr_per_rrset)
        else:
            return dns.query.udp(q, where, timeout, port, af, source, source_port, False, one_rr_per_rrset)

    def get_a(self, host_trg):
        """
        Function for resolving the A Record for a given host. Returns an Array of
        the IP Address it resolves to. It will also return CNAME data.
        """
        address = []
        tcp = True if self._proto == "tcp" else False
        try:
            ipv4_answers = self._res.query(host_trg, 'A', tcp=tcp)
            for ardata in ipv4_answers.response.answer:
                for rdata in ardata:
                    if rdata.rdtype == 5:
                        if rdata.target.to_text().endswith('.'):
                            address.append(["CNAME", host_trg, rdata.target.to_text()[:-1]])
                            host_trg = rdata.target.to_text()[:-1]
                        else:
                            address.append(["CNAME", host_trg, rdata.target.to_text()])
                            host_trg = rdata.target.to_text()
                    else:
                        address.append(["A", host_trg, rdata.address])
        except:
            return address
        return address

    def morty_c137(self, host):
        """
		Your standard A-Record DNS lookup ;)

        Function for resolving the A Record for a given host. Returns an Array of
        the IP Address it resolves to. It will also return CNAME data.
        """
        address = []
        tcp = True if self._proto == "tcp" else False
        try:
            ipv4_answers = self._res.query(host, 'A', tcp=tcp)
            for ardata in ipv4_answers.response.answer:
                for rdata in ardata:
                    if rdata.rdtype == 5:
                        if rdata.target.to_text().endswith('.'):
                            address.append(["CNAME", host, rdata.target.to_text()[:-1]])
                            host = rdata.target.to_text()[:-1]
                        else:
                            address.append(["CNAME", host, rdata.target.to_text()])
                            host = rdata.target.to_text()
                    else:
                        address.append(["A", host, rdata.address])
        except:
            return address
        return address

    def get_aaaa(self, host_trg):
        """
        Function for resolving the AAAA Record for a given host. Returns an Array of
        the IP Address it resolves to. It will also return CNAME data.
        """
        address = []
        tcp = True if self._proto == "tcp" else False
        try:
            ipv6_answers = self._res.query(host_trg, 'AAAA', tcp=tcp)
            for ardata in ipv6_answers.response.answer:
                for rdata in ardata:
                    if rdata.rdtype == 5:
                        if rdata.target.to_text().endswith('.'):
                            address.append(["CNAME", host_trg, rdata.target.to_text()[:-1]])
                            host_trg = rdata.target.to_text()[:-1]
                        else:
                            address.append(["CNAME", host_trg, rdata.target.to_text()])
                            host_trg = rdata.target.to_text()
                    else:
                        address.append(["AAAA", host_trg, rdata.address])
        except:
            return address
        return address

    def get_ip(self, hostname):
        """
        Function resolves a host name to its given A and/or AAAA record. Returns Array
        of found hosts and IPv4 or IPv6 Address.
        """
        found_ip_add = []
        found_ip_add.extend(self.get_a(hostname))
        found_ip_add.extend(self.get_aaaa(hostname))

        return found_ip_add

    def get_mx(self):
        """
        Function for MX Record resolving. Returns all MX records. Returns also the IP
        address of the host both in IPv4 and IPv6. Returns an Array
        """
        mx_records = []
        tcp = True if self._proto == "tcp" else False
        answers = self._res.query(self._domain, 'MX', tcp=tcp)
        for rdata in answers:
            try:
                name = rdata.exchange.to_text()
                ipv4_answers = self._res.query(name, 'A', tcp=tcp)
                for ardata in ipv4_answers:
                    if name.endswith('.'):
                        mx_records.append(['MX', name[:-1], ardata.address,
                                          rdata.preference])
                    else:
                        mx_records.append(['MX', name, ardata.address,
                                          rdata.preference])
            except:
                pass
        try:
            for rdata in answers:
                name = rdata.exchange.to_text()
                ipv6_answers = self._res.query(name, 'AAAA', tcp=tcp)
                for ardata in ipv6_answers:
                    if name.endswith('.'):
                        mx_records.append(['MX', name[:-1], ardata.address,
                                          rdata.preference])
                    else:
                        mx_records.append(['MX', name, ardata.address,
                                          rdata.preference])
            return mx_records
        except:
            return mx_records

    def get_ns(self):
        """
        Function for NS Record resolving. Returns all NS records. Returns also the IP
        address of the host both in IPv4 and IPv6. Returns an Array.
        """
        name_servers = []
        tcp = True if self._proto == "tcp" else False
        answer = self._res.query(self._domain, 'NS', tcp=tcp)
        if answer is not None:
            for aa in answer:
                name = aa.target.to_text()[:-1]
                ip_addrs = self.get_ip(name)
                for addresses in ip_addrs:
                    if re.search(r'^A', addresses[0]):
                        name_servers.append(['NS', name, addresses[2]])
        return name_servers

    def get_soa(self):
        """
        Function for SOA Record resolving. Returns all SOA records. Returns also the IP
        address of the host both in IPv4 and IPv6. Returns an Array.
        """
        soa_records = []
        tcp = True if self._proto == "tcp" else False
        querymsg = dns.message.make_query(self._domain, dns.rdatatype.SOA)

        try:
            if tcp:
                response = dns.query.tcp(querymsg, self._res.nameservers[0], self._res.timeout)
            else:
                response = dns.query.udp(querymsg, self._res.nameservers[0], self._res.timeout)

            if len(response.answer) > 0:
                answers = response.answer
            elif len(response.authority) > 0:
                answers = response.authority
            for rdata in answers:
                # A zone only has one SOA record so we select the first.
                name = rdata[0].mname.to_text()
                ipv4_answers = self._res.query(name, 'A', tcp=tcp)
                for ardata in ipv4_answers:
                    if name.endswith('.'):
                        soa_records.append(['SOA', name[:-1], ardata.address])
                    else:
                        soa_records.append(['SOA', name, ardata.address])
        except (dns.resolver.NXDOMAIN, dns.exception.Timeout, dns.resolver.NoAnswer, socket.error, dns.query.BadResponse):
            print('Error while resolving SOA record.')
            return soa_records

        try:
            for rdata in answers:
                name = rdata.mname.to_text()
                ipv4_answers = self._res.query(name, 'AAAA', tcp=tcp)
                for ardata in ipv4_answers:
                    if name.endswith('.'):
                        soa_records.append(['SOA', name[:-1], ardata.address])
                    else:
                        soa_records.append(['SOA', name, ardata.address])

            return soa_records
        except:
            return soa_records

    def get_spf(self):
        """
        Function for SPF Record resolving returns the string with the SPF definition.
        Prints the string for the SPF Record and Returns the string
        """
        spf_record = []
        tcp = True if self._proto == "tcp" else False
        try:
            answers = self._res.query(self._domain, 'SPF', tcp=tcp)
            for rdata in answers:
                name = ''.join(rdata.strings)
                spf_record.append(['SPF', name])
        except:
            return None

        return spf_record

    def get_txt(self, target=None):
        """
        Function for TXT Record resolving returns the string.
        """
        txt_record = []
        tcp = True if self._proto == "tcp" else False
        if target is None:
            target = self._domain
        try:
            answers = self._res.query(target, 'TXT', tcp=tcp)
            for rdata in answers:
                string = "".join(rdata.strings)
                txt_record.append(['TXT', target, string])
        except:
            return []

        return txt_record

    def get_ptr(self, ipaddress):
        """
        Function for resolving PTR Record given it's IPv4 or IPv6 Address.
        """
        found_ptr = []
        tcp = True if self._proto == "tcp" else False
        n = dns.reversename.from_address(ipaddress)
        try:
            answers = self._res.query(n, 'PTR', tcp=tcp)
            for a in answers:
                if a.target.to_text().endswith('.'):
                    found_ptr.append(['PTR', a.target.to_text()[:-1], ipaddress])
                else:
                    found_ptr.append(['PTR', a.target.to_text(), ipaddress])
            return found_ptr
        except:
            return None

    def get_srv(self, host):
        """
        Function for resolving SRV Records.
        """
        record = []
        tcp = True if self._proto == "tcp" else False
        try:
            answers = self._res.query(host, 'SRV', tcp=tcp)
            for a in answers:
                if a.target.to_text().endswith('.'):
                    target = a.target.to_text()[:-1]
                else:
                    target = a.target.to_text()

                ips = self.get_ip(target)

                if ips:
                    for ip in ips:
                        if re.search('(^A|AAAA)', ip[0]):
                            record.append(['SRV', host, target, ip[2],
                                          str(a.port), str(a.weight)])

                else:
                    record.append(['SRV', host, target, "no_ip",
                                  str(a.port), str(a.weight)])
        except:
            return record
        return record

    def get_nsec(self, host):
        """
        Function for querying for a NSEC record and retrieving the rdata object.
        This function is used mostly for performing a Zone Walk against a zone.
        """
        tcp = True if self._proto == "tcp" else False
        answer = self._res.query(host, 'NSEC', tcp=tcp)
        return answer

    def from_wire(self, xfr, zone_factory=Zone, relativize=True):
        """
        Method for turning returned data from a DNS AXFR in to RRSET, this method will not perform a
        check origin on the zone data as the method included with dnspython
        """
        z = None
        for r in xfr:
            if z is None:
                if relativize:
                    origin = r.origin
                else:
                    origin = r.answer[0].name
                rdclass = r.answer[0].rdclass
                z = zone_factory(origin, rdclass, relativize=relativize)
            for rrset in r.answer:
                znode = z.nodes.get(rrset.name)
                if not znode:
                    znode = z.node_factory()
                    z.nodes[rrset.name] = znode
                zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype,
                                           rrset.covers, True)
                zrds.update_ttl(rrset.ttl)
                for rd in rrset:
                    rd.choose_relativity(z.origin, relativize)
                    zrds.add(rd)

        return z

    def init_morty(self, domain):
        print("\n\033[91m##########################################################")
        print("#                                                        #")
        print("#                                                        #")
        print("#\033[94m                  Wubbalubbadubdub!                     \033[91m#")
        print("#                                                        #")
        print("#                                                        #")
        print("########################################################## \n \033[0m")
        print("""Options:\n1) A\n2) NS\n3) MX\n4) SOA\n5) SPF\n6) PTR\n7) TXT\n""")
        options = int(input("Select what information you're looking for: "))

        if options not in range(1,8):
            print("Nice choice, Commander-in-Queef\n")
            return

        if options == 1:
            try:
                A = resolver.morty_c137(domain)
                ip = A[0][2]
                print("IPv4 Address of {} --> {}".format(domain, ip))
            except:
                print("I'm Mr. Meeseeks!  Look at me!")
                print("Look @me! - no A record Jerry....\n")

        elif options == 2:
            NS = resolver.get_ns()
            print(NS)

        elif options == 3:
            try:
                MX = resolver.get_mx()
                print(MX)
            except:
                print("\nAww Geez Maaannn....\n")
                print("MX records cost 25 schmeckles, and you have insufficient funds\n")

        elif options == 4:
            try:
                SOA = resolver.get_soa()
                print(SOA)
            except:
                print("\nAww Geez Maaannn....\n")
                print("Looks like you are SOL on finding that SOA record\n")

        elif options == 5:
            try:
                SPF = resolver.get_spf()
                if SPF is not None:
                    print(SPF)
                else:
                    print("\nAww Geez Maaannn....\n")
                    print("\nYour SPF record is empty....\n")
            except:
                print("Aww Geez Maaannn....\n")
                print("Rick c137 must have placed your SPF record in another dimension....\n")

        elif options == 6:
            try:
                PTR = resolver.get_ptr()
                if PTR is not None:
                    print(PTR)
                else:
                    print("\nAww Geez Maaannn....\n")
                    print("\nThat's not an Amphetatron-Friendly place...\n")
                    print("\nYour PTR record is empty....\n")
            except:
                print("\nAww Geez Maaannn....\n")
                print("\nNo PTR record must mean that that's not an Amphetatron-Friendly place...\n")

        elif options == 7:
            try:
                TXT = resolver.get_txt()
                if TXT is not None:
                    print("Heeerreeee ya go w/that TXT record:\n")
                    print(TXT)
                else:
                    print("\nAww Geez Maann....\n")
                    print("\nYour TXT record is not found....\n")
            except:
                print("\nAwww Geeeez Maaan....\n")
                print("TXT record must be in another time-space....\n")

def usage():
    print("Usage: $ ./morty.py [domain]\n")
    print("Example: $ ./morty.py waynesplanet.com\n")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        usage()
        sys.exit(11)
    else:
        args = sys.argv[1:]
        domain = args[0]
        resolver = DnsHelper(domain)
        resolver.init_morty(domain)


import os

esm_model_names = ['esm1_t34_670M_UR50S',
                   'esm1_t34_670M_UR50D',
                   'esm1_t34_670M_UR100',
                   'esm1_t12_85M_UR50S',
                   'esm1_t6_43M_UR50S',
                   'esm1b_t33_650M_UR50S',
                   'esm_msa1_t12_100M_UR50S',
                   'esm_msa1b_t12_100M_UR50S',
                   'esm1v_t33_650M_UR90S_1',
                   'esm1v_t33_650M_UR90S_2',
                   'esm1v_t33_650M_UR90S_3',
                   'esm1v_t33_650M_UR90S_4',
                   'esm1v_t33_650M_UR90S_5',
                   'esm_if1_gvp4_t16_142M_UR50',
                   'esm2_t6_8M_UR50D',
                   'esm2_t12_35M_UR50D',
                   'esm2_t30_150M_UR50D',
                   'esm2_t33_650M_UR50D',
                   'esm2_t36_3B_UR50D',
                   'esm2_t48_15B_UR50D']

class ESMWrapper:
    def __init__(self,
                 model_name='esm2_t33_650M_UR50D',
                 repr_layers='0,3,6,12,24,32,33',
                 include='logits,mean,per_tok,contacts',
                 extract_script='sh /home/hew/python/AggNet/framework/module/esm/esm2/extract.sh'):
        self.model_name = model_name
        self.repr_layers = repr_layers
        self.include = include
        self.extract_script = extract_script

    def get_command(self, input, output):
        return f'{self.extract_script} {self.model_name} {input} {output} {self.repr_layers} {self.include}'

    def extract(self, input, output):
        command = self.get_command(input, output)
        return os.system(command)


import argparse
import contextlib
import datetime
import os
import six
import sys
import time
import unicodedata
import dropbox

parser = argparse.ArgumentParser(description='Sync ~/Downloads to Dropbox')
parser.add_argument('token', nargs='?', default='Downloads',
                    help='your access token')

def main():
    args = parser.parse_args()
    dbx = dropbox.Dropbox(args.token);
    #upload(dbx)
    data = download(dbx)
    with open("README2.md", 'wb') as f:
        f.write(data)
        f.close()

def download(dbx):
    try:
        md, res = dbx.files_download("/hi.md")
    except dropbox.exceptions.HttpError as err:
        print('*** HTTP error', err)
        return None
    data = res.content
    print(len(data), 'bytes; md:', md)
    return data

def upload(dbx):
    with open("README.md", 'rb') as f:
        data = f.read()
    try:
        res = dbx.files_upload(
            data, "/hi.md", dropbox.files.WriteMode.overwrite,
            mute=True)
    except dropbox.exceptions.ApiError as err:
        print('*** API error', err)
        return None
    print('uploaded as', res.name.encode('utf8'))
    return res

if __name__ == '__main__':
    print(main())


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/20 9:58
# @Author  : lichangjian
import sys
import traceback

def _db_helper_result_config(objects=None, msg='', status=0):
    """
    数据库返回格式配置
    :param objects:
    :param msg:
    :param status:
    :return:
    """
    if isinstance(objects, list):
        count = len(objects)
    elif objects is None:
        count = 0
    elif isinstance(objects, dict):
        # 已按固定格式处理，直接返回
        if list(objects.keys()) == ['status', 'msg', 'count', 'objects']:
            return objects
        else:
            count = 1
    else:
        count = 1
    return {"status": status, "msg": msg, "count": count, "objects": objects}

def db_helper_result_format(func):
    """
    数据库返回格式规范化
    :param func:
    :return:
    """

    def to_convert_result(*args, **keyargs):
        try:
            return _db_helper_result_config(status=1, msg='success', objects=func(*args, **keyargs))
        except Exception:
            exc_type, exc_instance, exc_traceback = sys.exc_info()
            print('exc', exc_type, exc_instance, exc_traceback)
            print('traceback', traceback.format_exc())
            if len(exc_instance.args) >= 2:
                msg = exc_instance.args[0]
                objects = exc_instance.args[1]
            else:
                msg = str(exc_instance)
                objects = None
            return _db_helper_result_config(status=0, msg=msg, objects=objects)

    return to_convert_result


#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import requests

class HttpUtil(object):

    @staticmethod
    def http_request(method, url, data, headers={'Content-Type': 'application/json'}):
        _header = headers.copy()
        if method.lower() == 'get':
            if "Content-Type" in _header:
                del _header["Content-Type"]
            response = requests.get(url, data=data, headers=_header)
        if method.lower() == 'post':
            response = requests.post(url, data=data, headers=headers)
        if method.lower() == 'patch':
            response = requests.patch(url, data=data, headers=headers)
        return response

    @staticmethod
    def http_upload(url, files, data="", headers={}):
        response = requests.post(url, files=files, data=data, headers=headers)
        return response


from Gerente import *
from Gerente import *

funcionarinho = Funcionario(1, 'Jorge', 2500)
funcionarinho.get_Funcionario()

gerentinho = Gerente(5, 'Paulo', 3400, 'padaria')
gerentinho.get_Gerente()

assistentinho = Assistente(65, 'Jango', 1400, '0004')
assistentinho.get_Assistente()


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

import os
import time

def get_files(path):
    files = os.listdir(path)
    for index, file in enumerate(files):
        file = os.path.join(path, file)
        files[index] = file
    return files

# вот так будет правильнее с параметрами
def time_track(func):

    def decorated_func(*args, **kwargs):
        started_at = time.time()
        result = func(*args, **kwargs)
        ended_at = time.time()
        elapsed = round(ended_at - started_at, 2)
        print()
        print(f'Функция работала {elapsed} секунд(ы)')
        return result

    return decorated_func

def check_volatility(volatilities, zero_volatilities):
    sorted_volatilities = sorted(volatilities, key=lambda x: x[1], reverse=True)
    max_volatilities = sorted_volatilities[:3]
    min_volatilities = sorted_volatilities[-3:]
    print("Максимлальная волатильность:")
    print_result(max_volatilities)
    print("Минимальная волатильность:")
    print_result(min_volatilities)
    print("Нулевая волатильность:")
    print_result(zero_volatilities)

def print_result(result: list):
    for item in result:
        if isinstance(item, tuple):
            print(*item)
        else:
            if not item == result[-1]:
                print(item, end=", ")
            else:
                print(item)


from .window import Window
from .time import Time
from .input import Input
from ..component.scene import Scenes
import pygame, sys
import pygame._sdl2 as pgsdl

class Application:
    @classmethod
    def init(
        cls,
        sdl_window: pgsdl.Window,
        target_fps: int = 0,
        accelerated: bool = True,
        input_elasticity: float = 1.5,
    ):
        pygame.init()
        Window._init(sdl_window, accelerated)
        Time._init(target_fps)
        Input._init(input_elasticity)

    @classmethod
    def run(cls):
        while True:
            events = pygame.event.get()
            Time._update()
            Input._update(events)

            for event in events:
                if event.type == pygame.QUIT:
                    Scenes.scene.on_quit()
                    pygame.quit()
                    sys.exit()
                Input._event(event)
                Scenes.scene.event(event)

            Window.renderer.draw_color = Scenes.scene.skybox_color
            Window.renderer.clear()

            Scenes.scene.update()
            Scenes.scene.draw()
            Scenes.scene.render()

            Window.renderer.present()


from typing import List

class Solution1:
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        result = []
        products.sort()
        for i, c in enumerate(searchWord):
            products = [p for p in products if len(p) > i and p[i] == c]
            result.append(products[:3])
        return result

class Solution:
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        result = []
        products.sort()

        for k, v in enumerate(searchWord):
            currentWord = searchWord[:k + 1]
            currentList = []

            for product in products:
                if product.startswith(currentWord):
                    currentList.append(product)
                    if len(currentList) == 3:
                        break

            result.append(currentList)

        return result

if True:
    s = Solution()
    products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"]
    searchWord = "mouse"
    res = s.suggestedProducts(products, searchWord)
    print("Result ", res)

if True:
    s = Solution()
    products = ["havana"]
    searchWord = "havana"
    res = s.suggestedProducts(products, searchWord)
    print("Result ", res)

if True:
    s = Solution()
    products = ["bags", "baggage", "banner", "box", "cloths"]
    searchWord = "bags"
    res = s.suggestedProducts(products, searchWord)
    print("Result ", res)

if True:
    s = Solution()
    products = ["havana"]
    searchWord = "tatiana"
    res = s.suggestedProducts(products, searchWord)
    print("Result ", res)