import sys
import os
import os.path
import shutil

from cx_Freeze import setup, Executable

# Remove the existing folders folder
shutil.rmtree("build", ignore_errors=True)
shutil.rmtree("dist", ignore_errors=True)

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

###############################################################################
# Here is a list of the Executable options
###############################################################################
#
# "script":
#       the name of the file containing the script which is to be frozen
#
# "initScript":
#       the name of the initialization script that will be executed before
#       the actual script is executed; this script is used to set up the
#       environment for the executable; if a name is given without an absolute
#       path the names of files in the initscripts subdirectory of
#       the cx_Freeze package is searched
#
# "base":
#       the name of the base executable;
#       if a name is given without an absolute path the names of files
#       in the bases subdirectory of the cx_Freeze package is searched
#
# "path":
#       list of paths to search for modules
#
# "targetDir":
#       the directory in which to place the target executable
#       and any dependent files
#
# "targetName":
#       the name of the target executable; the default value is the name
#       of the script with the extension exchanged with the extension
#       for the base executable
#
# "includes":
#       list of names of modules to include
#
# "excludes":
#       list of names of modules to exclude
#
# "packages":
#       list of names of packages to include, including all
#       of the package's submodules
#
# "replacePaths":
#       Modify filenames attached to code objects, which appear
#       in tracebacks. Pass a list of 2-tuples containing paths to
#       search for and corresponding replacement values. A search for
#       '*' will match the directory containing the entire package,
#       leaving just the relative path to the module.
#
# "compress":
#       boolean value indicating if the module bytecode
#       should be compressed or not
#
# "copyDependentFiles":
#       boolean value indicating if dependent files should be
#       copied to the target directory or not
#
# "appendScriptToExe":
#       boolean value indicating if the script module should be
#       appended to the executable itself
#
# "appendScriptToLibrary":
#       boolean value indicating if the script module should be
#       appended to the shared library zipfile
#
# "icon":
#       name of icon which should be included in the executable
#       itself on Windows or placed in the target directory
#       for other platforms
#
# "namespacePackages":
#       list of packages to be treated as namespace packages
#       (path is extended using pkgutil)
#
# "shortcutName":
#       the name to give a shortcut for the executable when
#       included in an MSI package
#
# "shortcutDir":
#       the directory in which to place the shortcut when being
#       installed by an MSI package; see the MSI Shortcut table
#       documentation for more information on what values
#       can be placed here.
#
###############################################################################
MY_TARGET_EXE = Executable(
    # what to build
    script="iextract.py",
    initScript=None,
    # base='Win32GUI',
    base='Console',
    #  targetDir = r"dist",
    targetName="inkscape_extract.exe",
    #  compress = True,
    #  copyDependentFiles = True,
    #  appendScriptToExe = False,
    #  appendScriptToLibrary = False,
    icon=os.path.join(os.path.dirname(__file__), '..',
                      'nsis', 'icon', 'inkscape.ico'),
    trademarks="Florent Tournois @2017"
)

###############################################################################
# Here is a list of the build_exe options
###############################################################################
# 1) append the script module to the executable
APPEND_SCRIPT_TO_EXE = False
# 2) the name of the base executable to use which, if given as a relative
#       path, will be joined with the bases subdirectory of the cx_Freeze
#       installation; the default value is "Console"
BASE = "Console"
# 3) list of names of files to exclude when determining dependencies of
#       binary files that would normally be included; note that version
#       numbers that normally follow the shared object extension are
#       stripped prior to performing the comparison
BIN_EXCLUDES = []
# 4) list of names of files to include when determining dependencies of
#       binary files that would normally be excluded; note that version
#       numbers that normally follow the shared object extension are
#       stripped prior to performing the comparison
BIN_INCLUDES = []
# 5) list of paths from which to exclude files when determining
#       dependencies of binary files
BIN_PATH_EXCLUDES = []
# 6) list of paths from which to include files when determining
#       dependencies of binary files
BIN_PATH_INCLUDES = []
# 7) directory for built executables and dependent files,
#       defaults to build/
BUILD_EXE = "../../distribution/"
# 8) create a compressed zip file
COMPRESSED = False
# 9) comma separated list of constant values to include in the constants
#       module called BUILD_CONSTANTS in form <name>=<value>
CONSTANTS = []
# 10) copy all dependent files
COPY_DEPENDENT_FILES = True
# 11) create a shared zip file called library.zip which will contain
#       all modules shared by all executables which are built
CREATE_SHARED_ZIP = True
# 12) comma separated list of names of modules to exclude
EXCLUDES = ['Tkinter', 'email', 'unittest']
# 13) include the icon in the frozen executables on the Windows
#       platform and alongside the frozen executable on other platforms
ICON = os.path.join(os.path.dirname(__file__), '..',
                    'packaging', 'icon', 'ge.ico')
# 13) comma separated list of names of modules to include
INCLUDES = ['inkscape', 'lxml', 'bs4']
# 15) list containing files to be copied to the target directory;
#       it is expected that this list will contain strings or
#           2-tuples for the source and destination;
#       the source can be a file or a directory (in which case
#           the tree is copied except for .svn and CVS directories);
#       the target must not be an absolute path
#
# NOTE: INCLUDE FILES MUST BE OF THIS FORM OTHERWISE freezer.py line
#       128 WILL TRY AND DELETE dist/. AND FAIL!!!
# Here is a list of ALL the DLLs that are included in Python27\Scripts
INCLUDE_FILES = [
    ("inkscape\\template\\", "template\\"),
]
# 16) include the script module in the shared zip file
INCLUDE_IN_SHARED_ZIP = True
# 17) include the Microsoft Visual C runtime DLLs and (if necessary)
#       the manifest file required to run the executable without
#       needing the redistributable package installed
INCLUDE_MSVCR = False
# 18) the name of the script to use during initialization which,
#       if given as a relative path, will be joined with the initscripts
#       subdirectory of the cx_Freeze installation;
#       the default value is "Console"
INIT_SCRIPT = ""
# 19) comma separated list of packages to be treated as
#       namespace packages (path is extended using pkgutil)
NAMESPACE_PACKAGES = []
# 20) optimization level, one of 0 (disabled), 1 or 2
OPTIMIZE = 0
# 21) comma separated list of packages to include, which includes
#       all submodules in the package
PACKAGES = ['lxml', 'gzip']
# 22) comma separated list of paths to search; the default value is sys.path
PATH = sys.path + [os.path.dirname(__file__)]
# 23) Modify filenames attached to code objects, which appear in tracebacks.
#       Pass a comma separated list of paths in the form <search>=<replace>.
#       The value * in the search portion will match the directory
#       containing the entire package, leaving just the
#       relative path to the module.
REPLACE_PATHS = []
# 24) suppress all output except warnings
SILENT = False
# 25) list containing files to be included in the zip file directory;
#       it is expected that this list will contain strings or
#       2-tuples for the source and destination
ZIP_INCLUDES = []

LOCAL_OPTIONS = {
    #                            "append_script_to_exe": APPEND_SCRIPT_TO_EXE,
    #                            "base":                 BASE,
    #                            "bin_excludes":         BIN_EXCLUDES,
    #                            "bin_includes":         BIN_INCLUDES,
    #                            "bin_path_excludes":    BIN_PATH_EXCLUDES,
    #                            "bin_path_includes":    BIN_PATH_INCLUDES,
    "build_exe": BUILD_EXE,
    #  "compressed":           COMPRESSED,
    #                            "constants":            CONSTANTS,
    #  "copy_dependent_files": COPY_DEPENDENT_FILES,
    #                            "create_shared_zip":    CREATE_SHARED_ZIP,
    "excludes": EXCLUDES,
    #  "icon":                 ICON,
    "includes": INCLUDES,
    "include_files": INCLUDE_FILES,
    #                            "include_in_shared_zip":INCLUDE_IN_SHARED_ZIP,
    #                            "include_msvcr":        INCLUDE_MSVCR,
    #                            "init_script":          INIT_SCRIPT,
    #                            "namespace_packages":   NAMESPACE_PACKAGES,
    #                            "optimize":             OPTIMIZE,
    "packages": PACKAGES,
    "path": PATH,
    #                            "replace_paths":        REPLACE_PATHS,
    #                            "silent":               SILENT,
    #                            "zip_includes":         ZIP_INCLUDES,
}

setup(
    name="Inkscape Extract",
    version="0.1",
    description="Inkscape Extract",
    author="Florent Tournois",
    options={"build_exe": LOCAL_OPTIONS},
    executables=[MY_TARGET_EXE]
)


import requests
import json
import os
def get_pic_url(num):
    pic_url= []
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}
    for i in range(num):

        page_url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E5%9B%BE%E7%89%87&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=&copyright=&word=%E5%9B%BE%E7%89%87&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn={}&rn=30&gsm=1e&1561022599290='.format(30*i)
        r = requests.get(page_url, headers=headers).text
        res = json.loads(r)['data']
        if res:
            print(res)
            for j in res:
                try:
                    url = j['hoverURL']
                    pic_url.append(url)
                except:
                    print('该图片的url不存在')

    print(len(pic_url))
    return pic_url

def down_img(num):
    pic_url  =get_pic_url(num)

    if os.path.exists('D:\图片'):
        pass
    else:
        os.makedirs('D:\图片')

    path = 'D:\图片\\'
    for index,i in enumerate(pic_url):
        filename = path +   str(index) + '.jpg'
        print(filename)
        with open(filename, 'wb+') as f:
            f.write(requests.get(i).content)
if __name__ == '__main__':
    num = int(input('爬取几次图片：一次30张'))
    down_img(num)


# 导入opencv工具包
import cv2
# 导入numpy
import numpy as np
# 导入姿势识别器
from PoseDetector import PoseDetector

detector = PoseDetector()

# 方向与个数
squatdir = 0  # 0为站立，1为蹲下
squatcount = 0

def squat(decimg):
    global squatcount,squatdir
    # 读取摄像头，img为每帧图片
    img = decimg

    h, w, c = img.shape
    # 识别姿势
    img = detector.find_pose(img, draw=True)
    # 获取姿势数据
    positions = detector.find_positions(img)

    if positions:
        # 获取下蹲的角度
        angle = detector.find_angle(img, 24, 26, 28)
        # 进度条长度
        bar = np.interp(angle, (50, 170), (w // 2 - 100, w // 2 + 100))
        cv2.rectangle(img, (w // 2 - 100, h - 150),
                      (int(bar), h - 100), (0, 255, 0), cv2.FILLED)
        # 角度小于55度认为下蹲
        if angle <= 55:
            if squatdir == 0:
                squatcount  = squatcount  + 0.5
                squatdir = 1
        # 角度大于120度认为站立
        if angle >= 120:
            if squatdir == 1:
                squatcount = squatcount + 0.5
                squatdir = 0
        cv2.putText(img, str(int(squatcount)), (w // 2, h // 2),
                    cv2.FONT_HERSHEY_SIMPLEX, 10, (255, 255, 255), 20, cv2.LINE_AA)

    # 打开一个Image窗口显示视频图片
    cv2.imshow('Image', img)


from matplotlib.pyplot import cla
from Data_Process import *
import torch

import sys
sys.path.append('D:\OneDrive - mail.nwpu.edu.cn\Optimal\Public\Python\Pre_Process')
from Data_Process import *
import torch as th
import math
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import random
from torch_geometric.nn import TransformerConv,GATConv,HeteroConv
import torch.nn.functional as F

from torch_geometric.nn import Linear, HGTConv
from my_hetero_conv import AttentHeteroConv

from torch_geometric.data import HeteroData
import torch_geometric.transforms as T
class GraphConvolution(Module):
    """
    Simple pygGCN layer, similar to https://arxiv.org/abs/1609.02907
    """

    def __init__(self, in_features, out_features, bias=True):
        super(GraphConvolution, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = Parameter(th.FloatTensor(in_features, out_features))
        if bias:
            self.bias = Parameter(th.FloatTensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

    def reset_parameters(self):
        stdv = 1. / math.sqrt(self.weight.size(1))
        self.weight.data.uniform_(-stdv, stdv)
        if self.bias is not None:
            self.bias.data.uniform_(-stdv, stdv)

    def forward(self, infeatn, adj):
        support = th.spmm(infeatn, self.weight)
        output = th.spmm(adj, support)
        if self.bias is not None:
            return output + self.bias
        else:
            return output

    def __repr__(self):
        return self.__class__.__name__ + ' (' \
               + str(self.in_features) + ' -> ' \
               + str(self.out_features) + ')'

class myGAE(torch.nn.Module):
    def __init__(self, data):
        super(myGAE, self).__init__()

        self.decoder_1 = torch.nn.Sequential(torch.nn.Linear(300, 300)).to('cuda:0')
        self.decoder_2 = torch.nn.Sequential(torch.nn.Linear(300, 300)).to('cuda:0')

        self.lin_dict = torch.nn.ModuleDict()
        for node_type in data.node_types:
            self.lin_dict[node_type] = Linear(-1, 300).to('cuda:0')

        self.conv_0 = HeteroConv({
            ('meta', 'is_concept_stock_of', "meta"): TransformerConv(300, 300, heads = 2, concat=False, beta=False),
            ('source_emb', 'is_source_of', "meta"): TransformerConv(300, 300, heads = 2, concat=False, beta=False),
            ("meta", "rev_is_source_of", "source_emb"): TransformerConv(300, 300, heads = 2, concat=False, beta=False),
        }, aggr = "sum").to('cuda:0')

        self.linear_a = torch.nn.Linear(300, 300).to('cuda:0')
        self.linear_b = torch.nn.Linear(300,300).to('cuda:0')
        # self.lin = Linear(300, 300)

        self.self_attention_1 = TransformerConv(300, 300, heads = 1, concat=False, beta=False).to('cuda:1')
        self.self_attention_2 = TransformerConv(300, 300, heads = 1, concat=False, beta=False).to('cuda:1')

    def Encoder(self, edge_concept, H_0, H_a, hetro_data, edge_a, edge_b):
        x_dict = hetro_data.x_dict
        edge_index_dict = hetro_data.edge_index_dict

        H_0 = self.self_attention_1(H_0.to('cuda:1'), edge_a.to('cuda:1'))
        H_a = self.self_attention_2(H_a.to('cuda:1'), edge_b.to('cuda:1'))

        # H_0 = self.linear_a(H_0.to('cuda:0'))
        # H_a = self.linear_b(H_a.to('cuda:0'))
        H_ens = H_0+H_a
        H_0 = F.normalize(H_0, dim=-1, p=2)
        H_a = F.normalize(H_a, dim=-1, p=2)
        H_ens = F.normalize(H_ens, dim=-1, p=2)

        x_dict['source_emb'] = torch.cat([H_0.to('cuda:0'), H_a.to('cuda:0')],dim=0).to('cuda:0')

        x_dict['meta'] = H_ens.to('cuda:0')

        # print(x_dict)
        # print(test)

        x_dict = self.conv_0(x_dict, edge_index_dict)

        representation = (x_dict['meta'])+H_ens.to('cuda:0')
        representation = F.normalize(representation, dim=-1, p=2)
        return representation

    def loss(self, H_2, batch_data, H_0, H_a):
        H_0 = H_0.to('cuda:0')
        H_a = H_a.to('cuda:0')

        concept_idxs = [x[0] for x in batch_data]
        pos_idxs = [x[1] for x in batch_data]
        neg_idxs = [x[2] for x in batch_data]

        emb_concept = H_2[concept_idxs]
        emb_pos_stock = H_2[pos_idxs]
        emb_neg_stock = H_2[neg_idxs]

        triplet_loss = torch.nn.TripletMarginLoss(margin=0.01, p=2)
        graph_loss = triplet_loss(emb_concept, emb_pos_stock, emb_neg_stock)

        # if self.training == False:
        #     print("debug")
        #     print(graph_loss)
        recon_loss = torch.nn.MSELoss()

        recon_H_0 = self.decoder_1(H_2)
        recon_H_a = self.decoder_2(H_2)

        recon_H_0 = F.normalize(recon_H_0, dim=-1, p=2)
        recon_H_a = F.normalize(recon_H_a, dim=-1, p=2)

        batch_size = 128
        sample_idx = random.sample(range(recon_H_0.shape[0]), batch_size)

        recon_loss_1 =  recon_loss(recon_H_0[sample_idx], H_0[sample_idx])
        recon_loss_2 = recon_loss(recon_H_a[sample_idx], H_a[sample_idx])

        alpha = 0.5
        loss = (1-alpha)*recon_loss_1+ alpha*recon_loss_2+ 0.001* graph_loss
        # loss = (1-alpha)*recon_loss_1+ alpha*recon_loss_2
        return loss

    def forward(self, concept_edge, H_0, H_a, batch_data, hetro_data, edge_a, edge_b):
        Latent_Representation = self.Encoder(concept_edge, H_0, H_a, hetro_data, edge_a, edge_b)
        loss = self.loss(Latent_Representation, batch_data, H_0, H_a)
        return loss, Latent_Representation


import os
import re
import shutil
import zipfile
from functools import partial
from os import path as op

import pooch
import pytest

from mne import datasets, read_labels_from_annot, write_labels_to_annot
from mne.datasets import fetch_dataset, fetch_infant_template, fetch_phantom, testing
from mne.datasets._fsaverage.base import _set_montage_coreg_path
from mne.datasets._infant import base as infant_base
from mne.datasets._phantom import base as phantom_base
from mne.datasets.utils import _manifest_check_download
from mne.utils import (
    ArgvSetter,
    _pl,
    catch_logging,
    get_subjects_dir,
    hashfunc,
    requires_good_network,
    use_log_level,
)

subjects_dir = testing.data_path(download=False) / "subjects"

def test_datasets_basic(tmp_path, monkeypatch):
    """Test simple dataset functions."""
    # XXX 'hf_sef' and 'misc' do not conform to these standards
    for dname in (
        "sample",
        "somato",
        "spm_face",
        "testing",
        "opm",
        "bst_raw",
        "bst_auditory",
        "bst_resting",
        "multimodal",
        "bst_phantom_ctf",
        "bst_phantom_elekta",
        "kiloword",
        "mtrf",
        "phantom_4dbti",
        "visual_92_categories",
        "fieldtrip_cmc",
    ):
        if dname.startswith("bst"):
            dataset = getattr(datasets.brainstorm, dname)
        else:
            dataset = getattr(datasets, dname)
        if str(dataset.data_path(download=False)) != ".":
            assert isinstance(dataset.get_version(), str)
            assert datasets.has_dataset(dname)
        else:
            assert dataset.get_version() is None
            assert not datasets.has_dataset(dname)
        print("%s: %s" % (dname, datasets.has_dataset(dname)))
    tempdir = str(tmp_path)
    # Explicitly test one that isn't preset (given the config)
    monkeypatch.setenv("MNE_DATASETS_SAMPLE_PATH", tempdir)
    dataset = datasets.sample
    assert str(dataset.data_path(download=False)) == "."
    assert dataset.get_version() != ""
    assert dataset.get_version() is None
    # don't let it read from the config file to get the directory,
    # force it to look for the default
    monkeypatch.setenv("_MNE_FAKE_HOME_DIR", tempdir)
    monkeypatch.delenv("SUBJECTS_DIR", raising=False)
    assert str(datasets.utils._get_path(None, "foo", "bar")) == op.join(
        tempdir, "mne_data"
    )
    assert get_subjects_dir(None) is None
    _set_montage_coreg_path()
    sd = get_subjects_dir()
    assert sd.name.endswith("MNE-fsaverage-data")
    monkeypatch.setenv("MNE_DATA", str(tmp_path / "foo"))
    with pytest.raises(FileNotFoundError, match="as specified by MNE_DAT"):
        testing.data_path(download=False)

@requires_good_network
def test_downloads(tmp_path, monkeypatch, capsys):
    """Test dataset URL and version handling."""
    # Try actually downloading a dataset
    kwargs = dict(path=str(tmp_path), verbose=True)
    # XXX we shouldn't need to disable capsys here, but there's a pytest bug
    # that we're hitting (https://github.com/pytest-dev/pytest/issues/5997)
    # now that we use pooch
    with capsys.disabled():
        with pytest.raises(RuntimeError, match="Do not download .* in tests"):
            path = datasets._fake.data_path(update_path=False, **kwargs)
        monkeypatch.setattr(
            datasets.utils, "_MODULES_TO_ENSURE_DOWNLOAD_IS_FALSE_IN_TESTS", ()
        )
        path = datasets._fake.data_path(update_path=False, **kwargs)
    assert op.isdir(path)
    assert op.isfile(op.join(path, "bar"))
    assert not datasets.has_dataset("fake")  # not in the desired path
    assert datasets._fake.get_version() is None
    assert datasets.utils._get_version("fake") is None
    monkeypatch.setenv("_MNE_FAKE_HOME_DIR", str(tmp_path))
    with pytest.warns(RuntimeWarning, match="non-standard config"):
        new_path = datasets._fake.data_path(update_path=True, **kwargs)
    assert path == new_path
    out, _ = capsys.readouterr()
    assert "Downloading" not in out
    # No version: shown as existing but unknown version
    assert datasets.has_dataset("fake")
    # XXX logic bug, should be "unknown"
    assert datasets._fake.get_version() == "0.0"
    # With a version but no required one: shown as existing and gives version
    fname = tmp_path / "foo" / "version.txt"
    with open(fname, "w") as fid:
        fid.write("0.1")
    assert datasets.has_dataset("fake")
    assert datasets._fake.get_version() == "0.1"
    datasets._fake.data_path(download=False, **kwargs)
    out, _ = capsys.readouterr()
    assert "out of date" not in out
    # With the required version: shown as existing with the required version
    monkeypatch.setattr(datasets._fetch, "_FAKE_VERSION", "0.1")
    assert datasets.has_dataset("fake")
    assert datasets._fake.get_version() == "0.1"
    datasets._fake.data_path(download=False, **kwargs)
    out, _ = capsys.readouterr()
    assert "out of date" not in out
    monkeypatch.setattr(datasets._fetch, "_FAKE_VERSION", "0.2")
    # With an older version:
    # 1. Marked as not actually being present
    assert not datasets.has_dataset("fake")
    # 2. Will try to update when `data_path` gets called, with logged message
    want_msg = "Correctly trying to download newer version"

    def _error_download(self, fname, downloader, processor):
        url = self.get_url(fname)
        full_path = self.abspath / fname
        assert "foo.tgz" in url
        assert str(tmp_path) in str(full_path)
        raise RuntimeError(want_msg)

    monkeypatch.setattr(pooch.Pooch, "fetch", _error_download)
    with pytest.raises(RuntimeError, match=want_msg):
        datasets._fake.data_path(**kwargs)
    out, _ = capsys.readouterr()
    assert re.match(r".* 0\.1 .*out of date.* 0\.2.*", out, re.MULTILINE), out

    # Hash mismatch suggestion
    # https://mne.discourse.group/t/fsaverage-hash-value-mismatch/4663/3
    want_msg = "MD5 hash of downloaded file (MNE-sample-data-processed.tar.gz) does not match the known hash: expected md5:e8f30c4516abdc12a0c08e6bae57409c but got a9dfc7e8843fd7f8a928901e12fb3d25. Deleted download for safety. The downloaded file may have been corrupted or the known hash may be outdated."  # noqa: E501

    def _error_download_2(self, fname, downloader, processor):
        url = self.get_url(fname)
        full_path = self.abspath / fname
        assert "foo.tgz" in url
        assert str(tmp_path) in str(full_path)
        raise ValueError(want_msg)

    shutil.rmtree(tmp_path / "foo")
    monkeypatch.setattr(pooch.Pooch, "fetch", _error_download_2)
    with pytest.raises(ValueError, match=".*known hash.*force_update=True.*"):
        datasets._fake.data_path(download=True, force_update=True, **kwargs)

@pytest.mark.slowtest
@testing.requires_testing_data
@requires_good_network
def test_fetch_parcellations(tmp_path):
    """Test fetching parcellations."""
    pytest.importorskip("nibabel")
    this_subjects_dir = str(tmp_path)
    os.mkdir(op.join(this_subjects_dir, "fsaverage"))
    os.mkdir(op.join(this_subjects_dir, "fsaverage", "label"))
    os.mkdir(op.join(this_subjects_dir, "fsaverage", "surf"))
    for hemi in ("lh", "rh"):
        shutil.copyfile(
            op.join(subjects_dir, "fsaverage", "surf", "%s.white" % hemi),
            op.join(this_subjects_dir, "fsaverage", "surf", "%s.white" % hemi),
        )
    # speed up by prenteding we have one of them
    with open(
        op.join(this_subjects_dir, "fsaverage", "label", "lh.aparc_sub.annot"), "wb"
    ):
        pass
    datasets.fetch_aparc_sub_parcellation(subjects_dir=this_subjects_dir)
    with ArgvSetter(("--accept-hcpmmp-license",)):
        datasets.fetch_hcp_mmp_parcellation(subjects_dir=this_subjects_dir)
    for hemi in ("lh", "rh"):
        assert op.isfile(
            op.join(
                this_subjects_dir, "fsaverage", "label", "%s.aparc_sub.annot" % hemi
            )
        )
    # test our annot round-trips here
    kwargs = dict(
        subject="fsaverage", hemi="both", sort=False, subjects_dir=this_subjects_dir
    )
    labels = read_labels_from_annot(parc="HCPMMP1", **kwargs)
    write_labels_to_annot(
        labels,
        parc="HCPMMP1_round",
        table_name="./left.fsaverage164.label.gii",
        **kwargs,
    )
    orig = op.join(this_subjects_dir, "fsaverage", "label", "lh.HCPMMP1.annot")
    first = hashfunc(orig)
    new = orig[:-6] + "_round.annot"
    second = hashfunc(new)
    assert first == second

_zip_fnames = ["foo/foo.txt", "foo/bar.txt", "foo/baz.txt"]

def _fake_zip_fetch(url, path, fname, *args, **kwargs):
    fname = op.join(path, fname)
    with zipfile.ZipFile(fname, "w") as zipf:
        with zipf.open("foo/", "w"):
            pass
        for fname in _zip_fnames:
            with zipf.open(fname, "w"):
                pass

@pytest.mark.parametrize("n_have", range(len(_zip_fnames)))
def test_manifest_check_download(tmp_path, n_have, monkeypatch):
    """Test our manifest downloader."""
    monkeypatch.setattr(pooch, "retrieve", _fake_zip_fetch)
    destination = op.join(str(tmp_path), "empty")
    manifest_path = op.join(str(tmp_path), "manifest.txt")
    with open(manifest_path, "w") as fid:
        for fname in _zip_fnames:
            fid.write("%s\n" % fname)
    assert n_have in range(len(_zip_fnames) + 1)
    assert not op.isdir(destination)
    if n_have > 0:
        os.makedirs(op.join(destination, "foo"))
        assert op.isdir(op.join(destination, "foo"))
    for fname in _zip_fnames:
        assert not op.isfile(op.join(destination, fname))
    for fname in _zip_fnames[:n_have]:
        with open(op.join(destination, fname), "w"):
            pass
    with catch_logging() as log:
        with use_log_level(True):
            # we mock the pooch.retrieve so these are not used
            url = hash_ = ""
            _manifest_check_download(manifest_path, destination, url, hash_)
    log = log.getvalue()
    n_missing = 3 - n_have
    assert ("%d file%s missing from" % (n_missing, _pl(n_missing))) in log
    for want in ("Extracting missing", "Successfully "):
        if n_missing > 0:
            assert want in log
        else:
            assert want not in log
    assert op.isdir(destination)
    for fname in _zip_fnames:
        assert op.isfile(op.join(destination, fname))

def _fake_mcd(manifest_path, destination, url, hash_, name=None, fake_files=False):
    if name is None:
        name = url.split("/")[-1].split(".")[0]
        assert name in url
        assert name in str(destination)
    assert name in manifest_path
    assert len(hash_) == 32
    if fake_files:
        with open(manifest_path) as fid:
            for path in fid:
                path = path.strip()
                if not path:
                    continue
                fname = op.join(destination, path)
                os.makedirs(op.dirname(fname), exist_ok=True)
                with open(fname, "wb"):
                    pass

def test_infant(tmp_path, monkeypatch):
    """Test fetch_infant_template."""
    monkeypatch.setattr(infant_base, "_manifest_check_download", _fake_mcd)
    fetch_infant_template("12mo", subjects_dir=tmp_path)
    with pytest.raises(ValueError, match="Invalid value for"):
        fetch_infant_template("0mo", subjects_dir=tmp_path)

def test_phantom(tmp_path, monkeypatch):
    """Test phantom data downloading."""
    # The Otaniemi file is only ~6MB, so in principle maybe we could test
    # an actual download here. But it doesn't seem worth it given that
    # CircleCI will at least test the VectorView one, and this file should
    # not change often.
    monkeypatch.setattr(
        phantom_base,
        "_manifest_check_download",
        partial(_fake_mcd, name="phantom_otaniemi", fake_files=True),
    )
    fetch_phantom("otaniemi", subjects_dir=tmp_path)
    assert op.isfile(tmp_path / "phantom_otaniemi" / "mri" / "T1.mgz")

@requires_good_network
def test_fetch_uncompressed_file(tmp_path):
    """Test downloading an uncompressed file with our fetch function."""
    dataset_dict = dict(
        dataset_name="license",
        url=(
            "https://raw.githubusercontent.com/mne-tools/mne-python/main/" "LICENSE.txt"
        ),
        archive_name="LICENSE.foo",
        folder_name=op.join(tmp_path, "foo"),
        hash=None,
    )
    fetch_dataset(dataset_dict, path=None, force_update=True)
    assert (tmp_path / "foo" / "LICENSE.foo").is_file()


import nltk
import re

def main():
    nltk.download('words')
    all_words = nltk.corpus.words.words()

    word = word_entry(1)
    check = check_word(word)
    guesses = compile_guesses(all_words, word, check)
    print_guesses(guesses)

def word_entry(n):
    while True:
        word = input(f"Enter word {n}: ")
        if len(word) == 5:
            return word
        print("Length of word is not 5, please enter a 5 letter word")

def check_word(word):
    print(word.upper())
    print("\nEnter (G)reen, (Y)ellow, or (N)ot for each character:\n")
    result = []
    for c in word.upper():
        inp = input(f"{c}: ").lower()
        if inp != 'g' and inp != 'y' and inp !='n':
            inp = 'n'
        result.append(inp)
    return result

def compile_guesses(all_words, word, check):
    yellows = []
    re_str = r'^'
    for i, c in enumerate(word):
        if check[i] == 'g': # Green (match)
            re_str += c
        elif check[i] == 'y': # Yellow (in word)
            yellows.append(c)
            re_str += r'\w'
        else: # Unknown (any character)
            re_str += r'\w'
    re_str += r'$'

    r = re.compile(re_str)

    matched_words = list(filter(r.match, all_words))

    for y in yellows:
        matched_words = list(filter(lambda x: y in x, matched_words))

    return matched_words

def print_guesses(guesses):
    print("\nGuesses: ")
    print("------------------------------")
    for g in guesses:
        print(g, end=' ')
    print("\n------------------------------")

if __name__ == "__main__":
    main()


'''
训练神经网络，并画出其损失曲线
'''

import os
import pickle
import matplotlib.pyplot as plt
from py_model.NN_model import *
from py_model.MNIST_data import *

INPUT_MODE=784
OUTPUT_MODE=10
LAYER_MODE=500
L1=0
L2=0.1
LEARNING_STEPS=1500
LEARNING_RATE=0.001
LEARNING_RATE_DECAY=0.00001
N_BATCHES=60
ALPHA=0.001

class NoModelError(Exception):
	pass

def train(filename='nn1.pkl',replace=False):
	filepath=os.path.join('../data/model/py',filename)
	if os.path.exists(filepath) and replace is False:
		print(f'模型文件：{filepath} 已经存在！')
	else:
		mnist=Mnist('../data/MNIST_uncompressed')
		x=np.where(mnist.train_images>0.4,1,0)
		y_=mnist.train_labels
		nn=NeuralNet(
					INPUT_MODE, OUTPUT_MODE, LAYER_MODE, L1, L2,
					LEARNING_STEPS, LEARNING_RATE, N_BATCHES,
					LEARNING_RATE_DECAY, ALPHA
					)
		nn.train(x,y_)
		with open(filepath,'wb') as f:
			pickle.dump(nn,f)
		show_cost(nn.cost_)

def show_cost(cost):
	plt.figure(figsize=(8,5))
	plt.plot(range(len(cost)),cost)
	plt.ylabel('Cost')
	plt.xlabel('Step')
	plt.tight_layout()
	plt.show()

def load_model(filename='nn1.pkl'):
	filepath=os.path.join('../data/model/py',filename)
	if os.path.exists(filepath):
		with open(filepath,'rb') as f:
			nn=pickle.load(f)
		return nn
	else:
		raise NoModelError(f'需加载的模型文件： {filepath} 不存在！')

def main():
	train()
	input()

if __name__=='__main__':
	main()


import socket
import time
import json
import random

# import subprocess

# _ = subprocess.call("route add 10.255.255.255 dev client1-eth0", shell=True)
# _ = subprocess.call("route add 10.255.255.255 dev client1-eth1", shell=True)
# _ = subprocess.call("ifconfig client1-eth1 10.0.0.10 netmask 255.0.0.0 broadcast 10.255.255.255", shell=True)

tx_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

tx_socket.bind(("", 8008))  # only to prevent icmp "not reachable"

rx_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
rx_socket.connect(("10.255.255.255", 8016))
# rx_socket.connect(("127.0.0.1", 8004))

cnt: int = 0
loop: int = 0
data = []
for i in range(0, 20):
    data.append(random.randint(a=0, b=1000))
_: str = ""
file = None

# try:
#     file = open("/tmp/log/client.LOG", "w")
#     file.write(f"Client started at {time.time()}")
#     _ = "logfile found"
# except Exception:
#     _ = "no logfile"
#     pass

print(f"starting client, {_}")
while True:
    try:
        msg = json.dumps(
            [
                {
                    "message": f"packet{loop}",
                    "type": "DATA",
                    "time": f"{time.time()}",
                    "data": data,
                }
            ],
            sort_keys=True,
            # indent=4,
            separators=(",", ": "),
        )
        rx_socket.sendall(msg.encode())

        # try:
        #     file = open("/tmp/log/client.txt", "w")
        #     file.write(f"sent msg, time : {time.time()}")
        #     file.close()
        # except Exception:
        #     pass

        if loop < 5:
            loop += 1
        else:
            loop = 0
        # data, addr = tx_socket.recvfrom(4096)  # use select.select() or sock.timeout() to only wait for recv time X
        # print(data)

        # try:
        #     file = open("/tmp/log/client.txt", "w")
        #     file.write(f"received msg : {data} from {addr}, time : {time.time()}")
        #     file.close()
        # except Exception:
        #     pass

        time.sleep(5)
    except Exception:
        # file.close()
        cnt += 1
        if cnt > 5:
            print("abort client")
            break


"""API-Routes to fetch static Data.

eg.: spells, classes, specs
"""

# IMPORT THIRD PARTY LIBRARIES
import fastapi

# IMPORT LOCAL LIBRARIES
from lorgs.models.raid_boss import RaidBoss
from lorgs.models.raid_zone import RaidZone
from lorgs.models.wow_class import WowClass
from lorgs.models.wow_role import WowRole
from lorgs.models.wow_spec import WowSpec
from lorgs.models.wow_spell import WowSpell

router = fastapi.APIRouter()

###############################################################################
#
#       Roles
#
###############################################################################

@router.get("/roles")
async def get_roles():
    """Get all roles (tank, heal, mpds, rdps)."""
    return {"roles": [role.as_dict() for role in WowRole.list()]}

###############################################################################
#
#       Classes
#
###############################################################################

@router.get("/classes")
async def get_classes():
    return {c.name_slug: c.as_dict() for c in WowClass.list()}

###############################################################################
#
#       Specs
#
###############################################################################

@router.get("/specs", tags=["specs"])
async def get_specs_all():
    all_specs = sorted(WowSpec.list())
    all_specs = [spec.as_dict() for spec in all_specs]  # type: ignore
    return {"specs": all_specs}

@router.get("/specs/{spec_slug}", tags=["specs"])
async def get_spec(spec_slug: str):
    spec = WowSpec.get(full_name_slug=spec_slug)
    if not spec:
        return "Invalid Spec.", 404
    return spec.as_dict()

@router.get("/specs/{spec_slug}/spells", tags=["specs"])
async def get_spec_spells(spec_slug: str):
    """Get all spells for a given spec.

    Args:
        spec_slug (str): name of the spec

    """
    spec = WowSpec.get(full_name_slug=spec_slug)
    if not spec:
        return "Invalid Spec.", 404

    abilities = spec.all_spells + spec.all_buffs + spec.all_debuffs + spec.all_events
    return {spell.spell_id: spell.as_dict() for spell in abilities}

###############################################################################
#
#       Spells
#
###############################################################################

@router.get("/spells/{spell_id}", tags=["spells"])
async def spells_one(spell_id: int):
    """Get a single Spell by spell_id."""
    spell = WowSpell.get(spell_id=spell_id)
    if not spell:
        return "Spell not found", 400
    return spell.as_dict()

@router.get("/spells", tags=["spells"])
async def spells_all():
    """Get all Spells."""
    spells = WowSpell.list()
    return {spell.spell_id: spell.as_dict() for spell in spells}

###############################################################################
#
#       Zones
#
###############################################################################

@router.get("/zones", tags=["raids"])
async def get_zones():
    """Get all raid-zones."""
    zones = RaidZone.list()
    return [zone.as_dict() for zone in zones]

@router.get("/zones/{zone_id}", tags=["raids"])
async def get_zone(zone_id: int):
    """Get a specific (raid-)Zone."""
    zone = RaidZone.get(id=zone_id)
    if not zone:
        return "Invalid Zone.", 404
    return zone.as_dict()

@router.get("/zones/{zone_id}/bosses", tags=["raids"])
async def get_zone_bosses(zone_id: int):
    """Get all Bosses in a given Raid Zone."""
    zone = RaidZone.get(id=zone_id)
    if not zone:
        return "Invalid Zone.", 404
    return {boss.name_slug: boss.as_dict() for boss in zone.bosses}

###############################################################################
#
#       Bosses
#
###############################################################################

@router.get("/bosses", tags=["raids"])
async def get_bosses():
    """Gets all Bosses
    Warning:
        this does not filter by raid.
        use "/zone/<zone_id>/bosses" to only get the bosses for a given raid.
    """
    return {"bosses": [boss.as_dict() for boss in RaidBoss.list()]}

@router.get("/bosses/{boss_slug}", tags=["raids"])
async def get_boss(boss_slug: str):
    """Get a single Boss.

    Args:
        boss_slug (string): name of the boss

    """
    boss = RaidBoss.get(full_name_slug=boss_slug)
    if not boss:
        return "Invalid Boss.", 404
    return boss.as_dict()

@router.get("/bosses/{boss_slug}/spells", tags=["raids"])
async def get_boss_spells(boss_slug: str):
    """Get Spells for a given Boss.

    Args:
        boss_slug (string): name of the boss

    """
    boss = RaidBoss.get(full_name_slug=boss_slug)
    if not boss:
        return "Invalid Boss.", 404

    spells = boss.all_spells + boss.all_buffs + boss.all_debuffs + boss.all_events
    return {spell.spell_id: spell.as_dict() for spell in spells}


import numpy as np

class CameraTracks:
    def __init__(self, index):
        self.index = index
        self.track_plots_ids = []
        self.track_new_plots_ids = []
        self.track_plots = []
        self.track_new_plots = []
        self.output_log = []

class TrackPlot:
    def __init__(self, track_id):
        self.id = track_id
        self.xs = np.array([], dtype=int)
        self.ys = np.array([], dtype=int)
        self.frameNos = np.array([], dtype=int)
        self.times = np.array([])
        self.colourized_times = []
        self.lastSeen = 0

        self.Q = 0
        self.turning_angle = np.array([])  # Degrees
        self.curvature = np.array([])
        self.pace = np.array([])
        self.track_feature_variable = np.array([])

    def update(self, location, frame_no, time=None):
        self.xs = np.append(self.xs, [int(location[0])])
        self.ys = np.append(self.ys, [int(location[1])])
        self.frameNos = np.append(self.frameNos, [frame_no])

        if time is not None:
            self.times = np.append(self.times, [time])

        self.lastSeen = frame_no

    def calculate_track_feature_variable(self, frameNo, fps):
        # Check if there is enough data to calculate turning angle (at least 3 points)
        # And that the data is still current
        if len(self.frameNos) >= 3 and self.frameNos[-1] == frameNo:
            # Check if the last 3 frames are consecutive
            if self.frameNos[-2] == self.frameNos[-1] - 1 and self.frameNos[-3] == self.frameNos[-2] - 1:
                # Retrieve the x and y values of the last 3 points and introduce t for readability
                t = 2
                x, y = self.xs[-3:], self.ys[-3:]

                # Turning angle
            #    xs = np.array([x[t] - x[t - 1], x[t - 1] - x[t - 2]])
            #    ys = np.array([y[t] - y[t - 1], y[t - 1] - y[t - 2]])

                # arctan2 returns the element-wise arc tangent, choosing the element correctly
                # Special angles excluding infinities:
                # y = +/- 0, x = +0, theta = +/- 0
                # y = +/- 0, x = -0, theta = +/- pi
                # whats a positive or negative 0?
            #    heading = np.arctan2(ys, xs) * 180 / np.pi

            #    turning_angle = heading[1] - heading[0]

            #    self.turning_angle = np.append(self.turning_angle, turning_angle)

                # Curvature
            #    a = np.sqrt((x[t] - x[t - 2]) ** 2 + (y[t] - y[t - 2]) ** 2)
            #    b = np.sqrt((x[t - 1] - x[t - 2]) ** 2 + (y[t - 1] - y[t - 2]) ** 2)
                c = np.sqrt((x[t] - x[t - 1]) ** 2 + (y[t] - y[t - 1]) ** 2)

            #    if b == 0 or c == 0:
            #        curvature = 0
            #    else:
            #       if abs((a ** 2 - b ** 2 - c ** 2) / (2 * b * c)) <= 1:
            #            curvature = np.arccos((a ** 2 - b ** 2 - c ** 2) / (2 * b * c))
                        # For whatever reason, the arccos of 1.0000000000000002 is nan
            #        else:
            #            curvature = 0
            #        if np.isnan(curvature):
            #            curvature = 0

            #    self.curvature = np.append(self.curvature, curvature)

                # Pace
                # Check if the data was returned in real time
                if self.times.size != 0:  # If so, dt is the difference in the time each consecutive frame was read
                    dt = self.times[-1] - self.times[-2]
                else:
                    # assume 30 FPS
                    dt = 1 / fps

                pace = c / dt
                self.pace = np.append(self.pace, pace)

                # track_feature_variable = np.mean(self.turning_angle) * np.mean(self.curvature) * np.mean(self.pace)
                # self.track_feature_variable = np.append(self.track_feature_variable, track_feature_variable)
                self.track_feature_variable = np.append(self.track_feature_variable, pace)

def combine_track_plots(index, camera_tracks, track_plot, frame_count):
    # appending of various variable value lists
    camera_tracks.track_plots[index].xs = np.append(camera_tracks.track_plots[index].xs, track_plot.xs)
    camera_tracks.track_plots[index].ys = np.append(camera_tracks.track_plots[index].ys, track_plot.ys)
    camera_tracks.track_plots[index].frameNos = np.append(camera_tracks.track_plots[index].frameNos, track_plot.frameNos)
    camera_tracks.track_plots[index].times = np.append(camera_tracks.track_plots[index].times, track_plot.times)
    camera_tracks.track_plots[index].colourized_times = np.append(camera_tracks.track_plots[index].colourized_times,
                                                                  track_plot.colourized_times)
    camera_tracks.track_plots[index].lastSeen = frame_count
    camera_tracks.track_plots[index].turning_angle = np.append(camera_tracks.track_plots[index].turning_angle,
                                                               track_plot.turning_angle)
    camera_tracks.track_plots[index].curvature = np.append(camera_tracks.track_plots[index].xs, track_plot.xs)
    camera_tracks.track_plots[index].pace = np.append(camera_tracks.track_plots[index].pace, track_plot.pace)
    camera_tracks.track_plots[index].track_feature_variable = np.append(camera_tracks.track_plots[index].track_feature_variable,
                                                                        track_plot.track_feature_variable)


from acasa.databaseManager import DataBaseManager

class Customer:
    def __init__(self) -> None:

        # Instance based attributes
        self.customer_id = 0
        self.first_name = ""
        self.last_name = ""
        self.db = DataBaseManager()

    def __repr__(self) -> str:
        return f"{self.first_name} {self.last_name}"

    def get_customer_info(self):
        self.first_name = input("Enter your first name: ").strip().title()
        self.last_name = input("Enter your last name: ").strip().upper()

    def insert_customer_into_db(self):
        sql = "INSERT INTO Customer(FirstName, LastName) VALUES (?,?);"

        data = (self.first_name, self.last_name)

        # Insert the Customer into DB and Return the Inserted Primary Key of the customer
        self.customer_id = self.db.insert_record(sql, data)

if __name__ == "__main__":
    cust1 = Customer()
    cust1.get_customer_info()

    print(cust1)


import random

class_roster = {'Jonathan Beltran': 0, 'Allison Fernandez': 1, 'Siddhanth Goyal': 0, 'Jingyu He': 0, 'Defne Ikiz': 0, 'Zirui Jiao': 0, 'Pranjal Joshi': 0, 'Dong Hyun Kim': 0, 'Ha Min Ko': 0, 'Kyle Lawson': 0, 'Christine Lee': 1, 'Connie Li': 1,
               'Qinyi Li': 0, 'Matthew Michalke': 0, 'Ho Wang Alastair Ng': 1, 'Jonghyun Park': 0, 'Alden Pexton': 2, 'Shriya Rathi': 2, 'Waylon Ryan': 1, 'Christian Thompson': 3, 'Angela Tsung': 2, 'Aaron Wendell': 0, 'Sarah Zazyczny': 0, 'Shiyue (Shirley) Zong': 0 }

def select_student(class_roster):
    min_value = min(class_roster.values())
    pool = []
    for student in class_roster:
        if class_roster[student] == min_value:
            pool.append(student)

    chosen_one = pool[random.randint(0, len(pool))]
    class_roster[chosen_one] += 1
    return chosen_one

print(select_student(class_roster))
print(class_roster)


import ipaddress
file_mhl = open('./mhl.txt')
try:
    mhl = file_mhl.read()
finally:
    file_mhl.close()

with open('./check_result/temp_file.txt') as file_object:
    for line in file_object:
        line = line[:-1]
        for temp in ipaddress.ip_network(line).hosts():
            if str(temp) in mhl:
                print("Find this:" + str(temp) + " from " + str(line))
                break


# -*- coding: utf-8 -*-
def application(environ, start_response):
    if environ["PATH_INFO"] == "/":
        respuesta = "
Página inicial
"
    elif environ["PATH_INFO"] == "/hola":
        respuesta = "
Bienvenidos a mi página web
"
    else:
        respuesta = "
<trong>Página incorrecta
"
    start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
    return respuesta

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    srv = make_server('localhost', 8080, application)
    srv.serve_forever()


#calculations.py -- things to web serve up

def monthly_pmt(price,int_r_pct=4.5,tax_pct=1.2, down_pct=20,hoa=0,years=30,pmts=12,):
	loan_amount = price*(100-down_pct)/100
	tax_monthly = loan_amount*(tax_pct)/(100-down_pct)/12

	monthly_eff = int_r_pct/(pmts*100)
	denom = 1-pow(1/(1+monthly_eff),pmts*years)
	pi_pay = loan_amount*monthly_eff/denom

	return pi_pay+tax_monthly+hoa #80$ monthly insurance guesstimate

def mortgage_payment_for_plot(int_r_pct=4.5,tax_pct=1.2, down_pct=20,hoa=0,years=30,pmts=12,):
	#returns xvals , yvals for bokeh plot
	start_cost = 50
	max_cost = 3000
	cost_step = 25
	range_x = range(start_cost,max_cost,cost_step)
	x_vals = [x for x in range_x]
	y_vals = [monthly_pmt(1000*x,int_r_pct,tax_pct,down_pct,hoa,years,pmts)
	 for x in range_x]
	return x_vals, y_vals

def savings_vs_year_for_plot(cagr = 5.5,egg = 5500,spend = 33000, investment = 5500, swr = 4):
	total = egg
	x_vals = [0]
	y_vals = [egg/1000]
	while swr*total/100 < 1.5*spend:
		x_vals.append(x_vals[-1]+1)
		total = total*(1+cagr/100)
		total+= investment
		y_vals.append(total/1000)
	return x_vals, y_vals


from odoo import models
from odoo.addons.account.models.chart_template import template

class AccountChartTemplate(models.AbstractModel):
    _inherit = 'account.chart.template'

    @template('mz')
    def _get_mz_template_data(self):
        return {
            'code_digits': '7',
            'property_account_receivable_id': 'l10n_mz_account_411',
            'property_account_payable_id': 'l10n_mz_account_421',
            'property_account_expense_categ_id': 'l10n_mz_account_61161',
            'property_account_income_categ_id': 'l10n_mz_account_711',
        }

    @template('mz', 'res.company')
    def _get_mz_res_company(self):
        return {
            self.env.company.id: {
                'account_fiscal_country_id': 'base.mz',
                'bank_account_code_prefix': '12',
                'cash_account_code_prefix': '11',
                'transfer_account_code_prefix': '456',
                'account_default_pos_receivable_account_id': 'l10n_mz_account_413',
                'income_currency_exchange_account_id': 'l10n_mz_account_7841',
                'expense_currency_exchange_account_id': 'l10n_mz_account_6941',
                'account_journal_early_pay_discount_loss_account_id': 'l10n_mz_account_695',
                'account_journal_early_pay_discount_gain_account_id': 'l10n_mz_account_785',
                'account_sale_tax_id': 'vat_sale_16',
                'account_purchase_tax_id': 'vat_purch_16_inventories',
            },
        }


#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# July 2015
# Pascal Beckstein (p.beckstein@hzdr.de)

# --------------------------------------------------------------------------- #
# --- Libraries ------------------------------------------------------------- #
# --------------------------------------------------------------------------- #

from foamTools.ioInfo import fileGetPath, objectIndent, objectHeader, objectFooter

import math as m

# --------------------------------------------------------------------------- #
# --- Parameters ------------------------------------------------------------ #
# --------------------------------------------------------------------------- #

geo_x =  0.061
geo_y =  0.086
geo_r =  0.009
geo_d =  0.009
geo_z = -0.010

off_n = 4
off_z = 0.017

arc_n = 12
arc_alpha = (m.pi/2.0)/arc_n

bundle_n = 10
bundle_r = geo_r/(bundle_n-1)
bundle_z = geo_d/(bundle_n-1)

fileNameBase = 'coil'

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

# Define short indented line with line break
def i(iL,cS,eS='\n'): return objectIndent(cS + eS,iLevel=iL)

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

for o in range(off_n):

    # Init points
    points = []

    # Init Points/Edges strings
    p=''
    e=''

    def a(n): return n*(bundle_n-1)
    def b(n): return a(n)+1

    for bundle in range(a(4)):

        if (bundle < b(1)):

            bun_x = geo_x + bundle*bundle_r
            bun_y = geo_y + bundle*bundle_r
            bun_r = geo_r + bundle*bundle_r
            bun_z = geo_z

        elif (bundle > a(1)) and (bundle < b(2)):

            bun_x = geo_x + a(1)*bundle_r
            bun_y = geo_y + a(1)*bundle_r
            bun_r = geo_r + a(1)*bundle_r
            bun_z = geo_z + bundle*bundle_z - a(1)*bundle_z

        elif (bundle > a(2)) and (bundle < b(3)):

            bun_x = geo_x + a(3)*bundle_r - bundle*bundle_r
            bun_y = geo_y + a(3)*bundle_r - bundle*bundle_r
            bun_r = geo_r + a(3)*bundle_r - bundle*bundle_r
            bun_z = geo_z + a(1)*bundle_z

        elif (bundle > a(3)) and (bundle < a(4)):

            bun_x = geo_x
            bun_y = geo_y
            bun_r = geo_r
            bun_z = geo_z + bundle*bundle_z - a(3)*bundle_z

        # Corner ++
        arc_alpha0 = 0.0
        for n in range(arc_n+1):

            x =  bun_x - bun_r + bun_r * m.cos(arc_alpha0 + n*arc_alpha)
            y =  bun_y - bun_r + bun_r * m.sin(arc_alpha0 + n*arc_alpha)
            z =  bun_z + o*off_z

            points.append([x, y, z])

        # Corner -+
        arc_alpha0 = m.pi/2.0
        for n in range(arc_n+1):

            x = -bun_x + bun_r + bun_r * m.cos(arc_alpha0 + n*arc_alpha)
            y =  bun_y - bun_r + bun_r * m.sin(arc_alpha0 + n*arc_alpha)
            z =  bun_z + o*off_z

            points.append([x, y, z])

        # Corner --
        arc_alpha0 = m.pi
        for n in range(arc_n+1):

            x = -bun_x + bun_r + bun_r * m.cos(arc_alpha0 + n*arc_alpha)
            y = -bun_y + bun_r + bun_r * m.sin(arc_alpha0 + n*arc_alpha)
            z =  bun_z + o*off_z

            points.append([x, y, z])

        # Corner +-
        arc_alpha0 = m.pi/2.0*3.0
        for n in range(arc_n+1):

            x =  bun_x - bun_r + bun_r * m.cos(arc_alpha0 + n*arc_alpha)
            y = -bun_y + bun_r + bun_r * m.sin(arc_alpha0 + n*arc_alpha)
            z =  bun_z + o*off_z

            points.append([x, y, z])

        shift = bundle*4*(arc_n+1)

        # Points string
        for pointi in range(len(points)-shift):

            pointI = pointi + shift

            point = points[pointI]

            p += i(1, '('+str(point[0])+' '+str(point[1])+' '+str(point[2])+')')

        # Edges string
        for pointi in range(len(points)-1-shift):

            pointI = pointi + shift

            e += i(1, '('+str(pointI)+' '+str(pointI+1)+')')

        e += i(1, '('+str(len(points)-1)+' '+str(shift)+')')

    # Write
    fileName = fileNameBase + str(o) + '.eMesh'
    with open(fileGetPath(fileName),'w') as f:

        f.write(objectHeader(fileName, 'featureEdgeMesh'))

        f.write(i(0, '// points:\n'))
        f.write(i(0, str(len(points))))
        f.write(i(0, '('))
        f.write(p)
        f.write(i(0, ')\n'))

        f.write(i(0, '// edges:\n'))
        f.write(i(0, str(len(points))))
        f.write(i(0, '('))
        f.write(e)
        f.write(i(0, ')\n'))

        f.write(objectFooter())

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


from math import sqrt
import numpy as np
import warnings
import matplotlib.pyplot as plt
from matplotlib import style
from collections import Counter

style.use('fivethirtyeight')

# plot1 = (1,3)
# plot2 = (2,5)

# euclidian_distance = sqrt((plot1[0]-plot2[0])**2+(plot1[1]-plot2[1])**2)

# print(euclidian_distance)

#create a dictionary with 2 classes:
dataset = {'k': [[1,2],[2,3],[3,1]], 'r': [[6,5],[7,7],[8,6]]}
new_feature = [5,7]

#plotting loop: i as classes (k and r), ii as their attribute lists
for i in dataset:
	for ii in dataset[i]:
		plt.scatter(ii[0],ii[1], s = 100, color = i)
plt.scatter(new_feature[0], new_feature[1])
plt.show()

#define k nearest neigbor algoP: which one is the nearest datapoint: have to calculate all
def k_nearest_neighbors(data, predict, k=3):
	if len(data) >=k:
		warnings.warn('K is set to a value less than total voting group')

	distances = []
	for group in data:
		for features in data[group]:
			#NOt fast enough so use numpy formula instead
			#euclidian_distance = sqrt((feature[0]-predict[0])**2+(feature[1]-predict[1])**2)
			euclidian_distance = np.linalg.norm(np.array(features)-np.array(predict))
			distances.append([euclidian_distance, group])
	votes = [i[1] for i in sorted(distances)[:k]]
	print(Counter(votes).most_common(1))
	vote_result = Counter(votes).most_common(1)[0][0]

	return vote_result

result = k_nearest_neighbors(dataset, new_feature, k=3)
print(result)


from django import http
from django.utils.six.moves.urllib.parse import urlparse

from wagtail.wagtailredirects import models

# Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py
class RedirectMiddleware(object):
    def process_response(self, request, response):
        # No need to check for a redirect for non-404 responses.
        if response.status_code != 404:
            return response

        # Get the path
        path = models.Redirect.normalise_path(request.get_full_path())

        # Get the path without the query string or params
        path_without_query = urlparse(path)[2]

        # Find redirect
        try:
            redirect = models.Redirect.get_for_site(request.site).get(old_path=path)
        except models.Redirect.DoesNotExist:
            if path == path_without_query:
                # don't try again if we know we will get the same response
                return response

            site = Site.find_for_request(request)
            try:
                redirect = models.Redirect.get(site=site, old_path=path_without_query)
            except models.Redirect.DoesNotExist:
                return response

        if redirect.is_permanent:
            return http.HttpResponsePermanentRedirect(redirect.link)
        else:
            return http.HttpResponseRedirect(redirect.link)


INPUT_FILE_PATH = "input/d9.txt"

DIR_MAP = {"R": ( 1, 0),
           "L": (-1, 0),
           "U": ( 0, 1),
           "D": ( 0,-1)}

def main():
    input = parse_input()
    print("Part 1 =", simulate(input, 2))
    print("Part 2 =", simulate(input, 10))

def simulate(input, knots):
    cmds = list(map(parse_cmd, input))
    tail_visits = set()
    start = (0, 0)
    rope = [start for i in range(0, knots)]
    tail_visits.add(start)
    cmd = cmds[0]
    for cmd in cmds:
        (dir, steps) = cmd
        for step in range(0, steps):
            rope[0] = move_head(rope[0], dir)
            for i in range(0, knots-1):
                rope[i+1] = adjust_tail(rope[i], rope[i+1])
            tail_visits.add(rope[-1])
    return len(tail_visits)

def parse_cmd(cmd):
    l = cmd.split(" ")
    return l[0], int(l[1])

def move_head(head, dir):
    return add_tuples(head, DIR_MAP.get(dir))

def adjust_tail(head, tail):
    if is_tail_touching(head, tail):
        return tail
    new_tail = add_tuples(tail, tail_move(head, tail))
    return new_tail

def tail_move(head, tail):
    # (x, y)
    #(-1, 1)(0, 1)(1, 1)
    #(-1, 0)(0, 0)(1, 0)
    #(-1,-1)(0,-1)(1,-1)
    diagonal_moves = [( 1,-1),
                      (-1, 1),
                      ( 1, 1),
                      (-1,-1)]
    moves = [( 0, 1),
             (-1, 0),
             ( 1, 0),
             ( 0,-1)]
    alloved_moves = moves
    if not tail_in_same_row_or_col(head, tail):
        alloved_moves = diagonal_moves

    for move in alloved_moves:
        new_tail = add_tuples(tail, move)
        if is_tail_touching(head, new_tail):
            return move

def tail_in_same_row_or_col(head, tail):
    return head[0] == tail[0] or head[1] == tail[1]

def add_tuples(a, b):
    return(a[0]+b[0], a[1]+b[1])

def is_tail_touching(head, tail):
    head_x, head_y = head
    tail_x, tail_y = tail
    return abs(head_x - tail_x) <= 1 and abs(head_y - tail_y) <= 1

def parse_input():
    with open(INPUT_FILE_PATH) as f:
        return list(map(lambda s: s.strip(), f.readlines()))

if __name__ == "__main__":
   main()


# attention.py

import torch
from torch import nn
import math
import torch.nn.functional as F
from train_utils import clones

def attention(query, key, value, mask=None, dropout=None):
    "Implementation of Scaled dot product attention"
    d_k = query.size(-1)
    scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
    if mask is not None:
        scores = scores.masked_fill(mask == 0, -1e9)
    p_attn = F.softmax(scores, dim = -1)
    if dropout is not None:
        p_attn = dropout(p_attn)
    return torch.matmul(p_attn, value), p_attn

class MultiHeadedAttention(nn.Module):
    def __init__(self, h, d_model, dropout=0.1):
        "Take in model size and number of heads."
        super(MultiHeadedAttention, self).__init__()
        assert d_model % h == 0
        # We assume d_v always equals d_k
        self.d_k = d_model // h
        self.h = h
        self.linears = clones(nn.Linear(d_model, d_model), 4)
        self.attn = None
        self.dropout = nn.Dropout(p=dropout)

    def forward(self, query, key, value, mask=None):
        "Implements Multi-head attention"
        if mask is not None:
            # Same mask applied to all h heads.
            mask = mask.unsqueeze(1)
        nbatches = query.size(0)

        # 1) Do all the linear projections in batch from d_model => h x d_k
        query, key, value = \
            [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
             for l, x in zip(self.linears, (query, key, value))]

        # 2) Apply attention on all the projected vectors in batch.
        x, self.attn = attention(query, key, value, mask=mask,
                                 dropout=self.dropout)

        # 3) "Concat" using a view and apply a final linear.
        x = x.transpose(1, 2).contiguous() \
             .view(nbatches, -1, self.h * self.d_k)
        return self.linears[-1](x)


import rpm
import os, subprocess, urllib, getpass
from argparse import ArgumentParser

SOURCES = '{0}/rpmbuild/SOURCES'.format(os.getenv('HOME'))

parser = ArgumentParser()

parser.add_argument('-u', '--user', help='SCP User', required=True)
parser.add_argument('--host', help='SCP Host', default='10.0.254.23')
parser.add_argument('-d', '--dest', help='SCP Destination directory', default='/usr/local/www/rpms')
parser.add_argument('-j', '--jail', help='Jail Type (content/database)', default='content')
parser.add_argument('-U', action='store_true', help='Update source archive.')
parser.add_argument('spec', help='RPM Spec file')
options = parser.parse_args()

if not os.path.exists(options.spec):
    raise RuntimeError("Provided spec file does not exists: `{0}`".format(options.spec))

transaction = rpm.ts()
spec = transaction.parseSpec(options.spec)
source_url = spec.sources[0][0]

source_file = spec.sourceHeader[rpm.RPMTAG_SOURCE][0]
if source_file is None:
    raise RuntimeError('Error, source file cannot be None.')

source_archive = '{0}/{1}'.format(SOURCES, source_file)

if not os.path.exists(source_archive) or options.U:
    if os.path.exists(source_archive):
        os.unlink(source_archive)
    print('Downloading `{0}`.'.format(source_url))
    urllib.urlretrieve(source_url, source_archive)

if not os.path.exists(source_archive):
    raise RuntimeError('Source archive missing! ({0})'.format(source_archive))

cmd = ['rpmbuild', '-bb', '--clean', options.spec]

process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
retcode = process.wait()
result_rpm = None
for line in process.stdout:
    # we are looking for something like this: Wrote: /usr/src/redhat/RPMS/i386/cdplayer-1.0-1.i386.rpm
    if not line.startswith('Wrote:'):
        continue

    result_rpm = line.split(" ")[1].strip()

if result_rpm is None or not os.path.exists(result_rpm):
    raise RuntimeError('RPM Build error: File `{0}` does not exists.'.format(result_rpm))

rpm = os.path.basename(result_rpm)

destination = "{0}/{1}/{2}".format(options.dest, options.jail, rpm)

dst = "{0}@{1}:{2}".format(options.user, options.host, destination)
cmd = ['scp']
cmd.append(result_rpm)
cmd.append(dst)
print("Uploading `{0}` to `{1}`".format(rpm, dst))
subprocess.Popen(cmd).wait()


from fastapi import FastAPI
from app.routers import router

app = FastAPI(
    title="FastAPI",
    description="API prueba",
    version="0.0.1",
    terms_of_service="http://example.com/terms/",
    contact={
        "name": "Deadpoolio the Amazing",
        "url": "http://x-force.example.com/contact/",
        "email": "dp@x-force.example.com",
    },
    license_info={
        "name": "Apache 2.0",
        "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
    },

)

app.include_router(router)


def couting_zero(n):
    count = 0
    i = 5
    #Keeps running so long as n is divisable by the next power of 5
    while( n//i >= 1):
        count += n//i
        #Increases 5 by 1 power each iteration of the loop
        i *= 5
    return int(count)

n = 10
print("How many zeros does", n, "! have")
print(couting_zero(n))
#I belive this would be O(n) since the amount of times the while loops executes is dependent on how large n is


import unittest
from unittest.mock import MagicMock, patch
from requests import Session

from src.kong_gateway_client.api import KongAPIClient
import json

class MockResponse:
    def __init__(self, json_data):
        self.json_data = json_data
        self.content = json.dumps(json_data).encode("utf-8") if json_data else b""

    def json(self):
        return self.json_data

    def ok(self):
        return True

    def raise_for_status(self):
        pass

class TestRoute(unittest.TestCase):
    def setUp(self):
        mock_response_auth = MagicMock()
        mock_response_auth.json.return_value = {"auth_key": "some_auth_value"}
        mock_response_auth.raise_for_status.return_value = None

        self.get_patcher = patch.object(Session, "get", return_value=mock_response_auth)
        self.request_patcher = patch.object(
            Session, "request", return_value=mock_response_auth
        )

        self.mock_get = self.get_patcher.start()
        self.mock_request = self.request_patcher.start()

        self.client = KongAPIClient(
            "http://mock-url", admin_token="mock-pass"
        ).get_kong_client()

    def tearDown(self):
        self.get_patcher.stop()
        self.request_patcher.stop()

    def test_route_create(self):
        mock_response_routes = MockResponse({"id": "123", "name": "test-route-1"})
        self.mock_request.return_value = mock_response_routes
        result = self.client.route.create("test-route-1", protocols=["http", "https"])
        self.assertEqual(result.name, "test-route-1")

    def test_route_get_by_id(self):
        mock_response = MockResponse(
            {
                "id": "123",
                "name": "test-route-1",
                "protocols": ["http"],
                "methods": ["GET"],
                "hosts": ["example.com"],
                "paths": ["/test-route"],
            }
        )
        self.mock_request.return_value = mock_response

        result = self.client.route.get("123")

        self.assertEqual(result.id, "123")
        self.assertEqual(result.name, "test-route-1")
        self.assertEqual(result.paths[0], "/test-route")

    def test_route_patch(self):
        mock_response = MockResponse(
            {
                "id": "123",
                "name": "updated-test-route-1",
                "protocols": ["http"],
                "methods": ["GET"],
                "hosts": ["example.com"],
                "paths": ["/updated-test-route"],
            }
        )
        self.mock_request.return_value = mock_response

        result = self.client.route.patch(
            "123", name="updated-test-route-1", protocols=["http"]
        )

        self.assertEqual(result.name, "updated-test-route-1")
        self.assertEqual(result.paths[0], "/updated-test-route")

    def test_route_put(self):
        mock_response = MockResponse(
            {
                "id": "123",
                "name": "recreated-test-route-1",
                "protocols": ["http"],
                "methods": ["GET"],
                "hosts": ["example.com"],
                "paths": ["/recreated-test-route"],
            }
        )
        self.mock_request.return_value = mock_response

        result = self.client.route.put(
            "123", name="recreated-test-route-1", protocols=["http"]
        )

        self.assertEqual(result.name, "recreated-test-route-1")
        self.assertEqual(result.paths[0], "/recreated-test-route")

    def test_route_delete(self):
        mock_response = MockResponse({})
        self.mock_request.return_value = mock_response

        result = self.client.route.delete("123")
        self.assertIsNone(result)

if __name__ == "__main__":
    unittest.main()


from services.option_implied_volatility_service import OptionImpliedVolatilityService
from services.option_suggestion_service import OptionSuggestionService
from services.dataframe_column_inserter_service import DataftrameColumnInserterService
import math
import pandas as pd

pd.set_option('display.width', 150)

serv = OptionImpliedVolatilityService(OptionSuggestionService(),DataftrameColumnInserterService())
print(serv)

underlyingPrice = 14.00
exercisePrice = 12.00

targetPrice = 2.20

time = 21
interest = 1.5 * 0.01
volatility = 76.5 * 0.01
dividend = 0 * 0.01

res = serv.impliedCallVolatility(underlyingPrice,exercisePrice,time,targetPrice,interest,dividend)

print(res)


import rubato as rb
from rubato import Input, Color, Time, Vector, Manifold
import objects

# Component overriding.

class PlayerController(rb.Component):
    def __init__(self, image_location, speed):

        super().__init__()  # you must call super().__init__()

        self.image = rb.Image(rel_path=image_location)
        self.speed = speed

    def setup(self):
        """
        Here you have access to the GameObject of the component and is where you should set any variables that depend
        on the GameObject.
        Automatically run once before the first update call.
        """
        # Only here can we get the rect from our game object and assign the image
        self.rect = self.gameobj.get(rb.Rectangle)

        # resizing our image to our hitbox's size
        self.image.resize(Vector(50, 50))
        self.gameobj.add(self.image)

    def update(self):
        """
        Called once per frame. Before the draw function.
        """

        # We moved the input into here. And changed it all to use delta_time
        if Input.key_pressed("a"):
            self.gameobj.pos.x -= self.speed * Time.delta_time
            self.rect.color = Color.red
        if Input.key_pressed("w"):
            self.gameobj.pos.y -= self.speed * Time.delta_time
        if Input.key_pressed("s"):
            self.gameobj.pos.y += self.speed * Time.delta_time
        if Input.key_pressed("d"):
            self.gameobj.pos.x += self.speed * Time.delta_time
            self.rect.color = Color.blue

class Coin(rb.Component):
    def __init__(self):
        super().__init__()
        self.image = rb.Image(rel_path="../art/Silver Coin.png")
        self.rect = rb.Rectangle(width=self.image.get_size().x, height=self.image.get_size().y)

    def setup(self):
        self.gameobj.add(self.image)
        self.gameobj.add(self.rect)
        self.rect.on_collide = self.on_collide  # Setting the rectangle with our custom on_collide function.

    def on_collide(self, manifold: Manifold):
        # A manifold is passed in when a collision occurs.
        # In short, it holds shape_a, which holds self under `.gameobj`, and shape_b which is what self collided with.
        # You may check the documentation for more information.
        if manifold.shape_b.gameobj.name == "player":  # We check if we collided with the player.
            objects.main.delete(self.gameobj)


from socket import *
import random

def getData():
    temp = str(random.randint(0, 40))
    humid = str(random.randint(0, 100))
    illum = str(random.randint(70, 150))
    return temp + ' ' + humid + ' ' + illum

port = 2500
BUFSIZE = 1024

sock = socket(AF_INET, SOCK_STREAM)
sock.bind(('', port))
sock.listen(5)

while True:
    conn, args = sock.accept()
    data = conn.recv(BUFSIZE).decode()

    if data == 'Request':
        conn.send(getData().encode())
    elif data == 'quit':
        break
    conn.close()

conn.close()
sock.close()


from django.shortcuts import render, HttpResponseRedirect, redirect
from .models import Todo, Date
from django.urls import reverse
from .forms import TodoForm
from django.utils import timezone
from django.contrib.auth.decorators import login_required
# Create your views here.

@login_required
def index(request):
    author = request.user
    dates = Date.objects.filter(author = author).exclude(strdate = timezone.now().strftime("%Y-%m-%d"))
    dates = dates.order_by('-strdate')

    return render(
        request,
        'todo/index.html',
        {
            'dates' : dates,
        }
    )

@login_required
def todo_list(request, date):
    author = request.user
    todos = Todo.objects.filter(author = author).filter(completed = False).filter(str_date = date)
    todosc = Todo.objects.filter(author = author).filter(completed = True).filter(str_date = date)

    return render(
        request,
        'todo/todo_list.html',
        {
            'todos' : todos,
            'todosc' : todosc
        }
    )

@login_required
def todo_today(request):
    author = request.user
    dates = Date.objects.filter(author = author).filter(strdate = timezone.now().strftime("%Y-%m-%d"))

    if(len(dates) == 0):
        new_date = Date()
        new_date.author = request.user
        new_date.save()

    todos = Todo.objects.filter(author = author).filter(completed = False).filter(str_date = timezone.now().strftime("%Y-%m-%d"))
    todosc = Todo.objects.filter(author = author).filter(completed = True).filter(str_date = timezone.now().strftime("%Y-%m-%d"))

    return render(
        request,
        'todo/todo_today.html',
        {
            'todos' : todos,
            'todosc' : todosc
        }
    )

@login_required
def todo_detail(request, pk):
    todo = Todo.objects.get(id=pk)

    return render(request, 'todo/todo_detail.html', {'todo' : todo})

@login_required
def todo_delete(request, pk):
    todo = Todo.objects.get(id=pk)

    todo.delete()

    previous_page = request.META.get('HTTP_REFERER')
    return HttpResponseRedirect(previous_page)

@login_required
def todo_post(request):
    if request.method == "POST":
        form = TodoForm(request.POST)
        if form.is_valid():
            todo = form.save(commit=False)
            todo.author = request.user
            todo.save()
            return redirect('/todo/today')
    else:
        form = TodoForm()

    return render(request, 'todo/todo_post.html', {'form': form})

@login_required
def todo_edit(request, pk):
    todo = Todo.objects.get(id=pk)
    if request.method == "POST":
        form = TodoForm(request.POST, instance=todo)
        if form.is_valid():
            todo = form.save(commit=False)
            todo.save()
            return redirect('/todo/today')
    else:
        form = TodoForm(instance=todo)

    return render(request, 'todo/todo_post.html', {'form': form})

@login_required
def todo_done(request, pk):
    todo = Todo.objects.get(id=pk)
    if(todo.completed == False) :
        todo.completed = True
    else :
        todo.completed = False

    todo.save()

    previous_page = request.META.get('HTTP_REFERER')
    return HttpResponseRedirect(previous_page)


from typing import Any, Callable

import wrapt

import numba as nb
import numpy as np
import pandas as pd
from numba import prange
from pandas.api.types import infer_dtype

from anndata import AnnData

from cellrank import logging as logg

jit_kwargs = {"nogil": True, "cache": True, "fastmath": True}

@nb.njit(parallel=False, **jit_kwargs)
def _np_apply_along_axis(func1d, axis: int, arr: np.ndarray) -> np.ndarray:
    """Apply a reduction function over a given axis.

    Parameters
    ----------
    func1d
        Reduction function that operates only on 1 dimension.
    axis
        Axis over which to apply the reduction.
    arr
        The array to be reduced.

    Returns
    -------
    The reduced array.
    """
    assert arr.ndim == 2
    assert axis in [0, 1]

    if axis == 0:
        result = np.empty(arr.shape[1])
        for i in range(len(result)):
            result[i] = func1d(arr[:, i])
        return result

    result = np.empty(arr.shape[0])
    for i in range(len(result)):
        result[i] = func1d(arr[i, :])

    return result

@nb.njit(**jit_kwargs)
def np_mean(array: np.ndarray, axis: int) -> np.ndarray:  # noqa
    return _np_apply_along_axis(np.mean, axis, array)

@nb.njit(**jit_kwargs)
def np_std(array: np.ndarray, axis: int) -> np.ndarray:  # noqa
    return _np_apply_along_axis(np.std, axis, array)

@nb.njit(**jit_kwargs)
def norm(array: np.ndarray, axis: int) -> np.ndarray:  # noqa
    return _np_apply_along_axis(np.linalg.norm, axis, array)

# this is faster than using flat array
@nb.njit(parallel=True)
def _random_normal(
    m: np.ndarray,
    v: np.ndarray,
    n_samples: int = 1,
) -> np.ndarray:
    """Sample number from normal distribution.

    Parameters
    ----------
    m
        Mean vector.
    v
        Variance vector.
    n_samples
        Number of samples to be generated.

    Returns
    -------
    Array of shape ``(n_samples x m.shape[0])``.
    """
    assert m.ndim == 1, "Means are not 1-dimensional."
    assert m.shape == v.shape, "Means and variances have different shape."

    if n_samples == 1:
        return np.expand_dims(np.array([np.random.normal(m[i], v[i]) for i in prange(m.shape[0])]), 0)  # noqa: NPY002

    return np.array(
        [[np.random.normal(m[i], v[i]) for _ in prange(n_samples)] for i in prange(m.shape[0])]  # noqa: NPY002
    ).T

@nb.njit(**jit_kwargs)
def _calculate_starts(indptr: np.ndarray, ixs: np.ndarray) -> np.ndarray:
    """Get the position where to put the data.

    Parameters
    ----------
    indptr
        Pointer of indices from :class:`~scipy.sparse.csr_matrix`.
    ixs
        Row indices for which to calculate the starts.

    Returns
    -------
    The starting positions.
    """
    starts = np.cumsum(indptr[ixs + 1] - indptr[ixs])
    return np.hstack((np.array([0], dtype=starts.dtype), starts))

def _get_basis(adata: AnnData, basis: str) -> np.ndarray:
    try:
        return adata.obsm[f"X_{basis}"]
    except KeyError:
        try:
            return adata.obsm[basis]  # e.g. 'spatial'
        except KeyError:
            raise KeyError(f"Unable to find a basis in `adata.obsm['X_{basis}']` or `adata.obsm[{basis!r}]`.") from None

def _ensure_numeric_ordered(adata: AnnData, key: str) -> pd.Series:
    if key not in adata.obs.keys():
        raise KeyError(f"Unable to find data in `adata.obs[{key!r}]`.")

    exp_time = adata.obs[key].copy()
    if not np.issubdtype(np.asarray(exp_time).dtype, np.number):
        try:
            exp_time = np.asarray(exp_time).astype(float)
        except Exception as e:  # noqa: BLE001/Cannot interpret
            raise TypeError(
                f"Unable to convert `adata.obs[{key!r}]` of type `{infer_dtype(adata.obs[key])}` to `float`."
            ) from e

    if not isinstance(exp_time.dtype, pd.CategoricalDtype):
        logg.debug(f"Converting `adata.obs[{key!r}]` to `categorical`")
        exp_time = np.asarray(exp_time)
        categories = sorted(set(exp_time[~np.isnan(exp_time)]))
        if len(categories) > 100:  # arbitrary threshold
            raise ValueError(
                f"Unable to convert `adata.obs[{key!r}]` to `categorical` since it "
                f"would create `{len(categories)}` categories."
            )
        exp_time = pd.Series(
            pd.Categorical(
                exp_time,
                categories=categories,
                ordered=True,
            )
        )

    if not exp_time.cat.ordered:
        logg.warning("Categories are not ordered. Using ascending order")
        exp_time.cat = exp_time.cat.as_ordered()

    exp_time = pd.Series(pd.Categorical(exp_time, ordered=True), index=adata.obs_names)
    if exp_time.isnull().any():
        raise ValueError("Series contains NaN value(s).")

    n_cats = len(exp_time.cat.categories)
    if n_cats < 2:
        raise ValueError(f"Expected to find at least `2` categories, found `{n_cats}`.")

    return exp_time

@wrapt.decorator
def require_tmat(
    wrapped: Callable[..., Any],
    instance: "KernelExpression",  # noqa: F821
    args: Any,
    kwargs: Any,
) -> Any:
    """Require that the transition matrix is computed before calling the wrapped function."""
    # this can trigger combinations, but not individual kernels
    if instance.transition_matrix is None:
        raise RuntimeError("Compute transition matrix first as `.compute_transition_matrix()`.")
    return wrapped(*args, **kwargs)


# Геопандас / Cвердловская обл.
import geopandas as gpd
import pandas as pd
from matplotlib import pyplot as plt
pd.set_option('display.max_columns', None)

#Свердловская обл общая граница
gpd_svd_L1 = gpd.read_file('~/PycharmProjects/maps/GeoData/svd/boundary-polygon-lvl4.shp', encoding='utf-8')
# районы и округа 73 шт 65763000
gpd_svd_L2 = gpd.read_file('~/PycharmProjects/maps/GeoData/svd/boundary-polygon-lvl6.shp', encoding='utf-8')
#сельские поселения 22 шт 65628420
gpd_svd_L3 = gpd.read_file('~/PycharmProjects/maps/GeoData/svd/boundary-polygon-lvl8.shp', encoding='utf-8')
#населенные пункты 2272  шт 65755000141
gpd_svd_L4 = gpd.read_file('~/PycharmProjects/maps/GeoData/svd/settlement-point.shp', encoding='utf-8')

print(gpd_svd_L3.info())
print(gpd_svd_L3[['NAME', 'oktmo', 'geometry']])

fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(10,5))
gpd_svd_L1.plot(ax=ax1, color='white', edgecolor='black')
gpd_svd_L2.plot(ax=ax2, color='white', edgecolor='black')
gpd_svd_L3.plot(ax=ax3, color='white', edgecolor='black')
gpd_svd_L4.plot(ax=ax4, color='white', edgecolor='black')
plt.show()


from math import ceil, cos, radians, sin
from PIL import Image, ImageDraw, ImageFont

vu_navy =   (  0,  31,  91)
vu_yellow = (255, 220,  79)
vu_orange = (248, 151,  40)
vu_green =  (193, 205,  35)
vu_blue =   ( 80, 145, 205)
vu_teal =   (  0, 146, 143)
vu_gray=    (148, 156, 166)

colors = [vu_navy, vu_blue, vu_orange, vu_yellow]

def comma(num):
    return '{:,}'.format(num)

def smart_text(draw, text, x, y, font, align="left", fillColor=(255, 255, 255), border=vu_navy):
    draw.text((x - 1, y), text, fill=border, font=font, align=align)
    draw.text((x, y - 1), text, fill=border, font=font, align=align)
    draw.text((x + 1, y), text, fill=border, font=font, align=align)
    draw.text((x, y + 1), text, fill=border, font=font, align=align)
    draw.text((x - 1, y + 1), text, fill=border, font=font, align=align)
    draw.text((x - 1, y - 1), text, fill=border, font=font, align=align)
    draw.text((x + 1, y + 1), text, fill=border, font=font, align=align)
    draw.text((x + 1, y - 1), text, fill=border, font=font, align=align)
    draw.text((x, y), text, fill=fillColor, font=font, align=align)

def bar_graph(filename, data, title=None, key=None, labels=None, numbers=True):
    bar_width = 60
    bar_gap = 15
    bar_border = 1
    padding = 20
    width = ((bar_width + bar_gap) * len(data)) - bar_gap + padding * 2
    height = 600

    im = Image.new("RGB", (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(im)
    gotham_font = ImageFont.truetype("fonts/opensans-semibold-webfont.ttf", 10)

    bottom_pad = 0
    if labels != None:
        for l in labels:
            _, th = draw.textsize(l, font=gotham_font, spacing=2)
            if th > bottom_pad:
                bottom_pad = th
    bottom = height - (padding / 2) - bottom_pad

    x = padding
    max = 0
    for arr in data:
        for d in arr:
            if d > max:
                max = d
    bar = 0
    totals = []
    for i in data[0]:
        totals.append(0)
    for arr in data:
        arr.sort(reverse=True)
        index = 0
        for d in arr:
            totals[index] += d
            if d == 0:
                continue
            bar_h = (height - bottom_pad - padding * 2) * (d / max)
            if index == 0:
                box = (
                    x - bar_border,
                    bottom - bar_h - bar_border,
                    x + bar_width + bar_border,
                    bottom + bar_border
                )
                draw.rectangle(box, fill=(0, 0, 0))
                if numbers:
                    c_arr = []
                    c_colors = []
                    for i in range(len(arr)):
                        if arr[i] > 0:
                            c_arr.append(arr[i])
                            c_colors.append(colors[i])
                    stats = ", ".join([comma(d) for d in c_arr])
                    _, h = draw.textsize("0,", font=gotham_font)
                    w, _ = draw.textsize(stats, font=gotham_font)
                    for i in range(len(c_arr)):
                        stats = ", ".join([comma(d) for d in c_arr[i:]])
                        draw.text((x + bar_width + bar_border - w, bottom - bar_h - h), comma(c_arr[i]), fill=c_colors[i], spacing=2, font=gotham_font)
                        if i == len(c_arr) - 1:
                            break
                        sub_w, _ = draw.textsize(comma(c_arr[i]), font=gotham_font)
                        w -= sub_w
                        draw.text((x + bar_width + bar_border - w, bottom - bar_h - h), ", ", fill=c_colors[0], spacing=2, font=gotham_font)
                        sub_w, _ = draw.textsize(", ", font=gotham_font)
                        w -= sub_w
            box = (
                x,
                bottom - bar_h,
                x + bar_width,
                bottom
            )
            draw.rectangle(box, fill=(colors[index]))
            index += 1
        if labels != None:
            draw.text((x, bottom + 3), labels[bar], fill=(0, 0, 0), spacing=2, font=gotham_font)
        x += bar_width + bar_gap
        bar += 1

    # Titles
    if title != None:
        gotham_title = ImageFont.truetype("fonts/opensans-semibold-webfont.ttf", 24)
        title_w, title_h = draw.textsize(title, font=gotham_title)
        draw.text((width - title_w - padding, padding), title, fill=(0, 0, 0), font=gotham_title)

    # Key
    if key != None:
        y = padding + 28
        max_w = 0
        max_h = 0
        for k in key:
            w, h = draw.textsize(k, font=gotham_font)
            if w > max_w:
                max_w = w
            if h > max_h:
                max_h = h
        for i in range(len(key)):
            # Bar
            draw.rectangle((width - max_w - padding - 20, y, width - padding, y + max_h + 9), fill=(colors[i]))
            smart_text(draw, key[i], width - max_w - padding - 10, y + 5, gotham_font)
            # Totals
            total_text = comma(totals[i])
            if i > 0:
                total_text += " (%.1f%%)" % (100 * totals[i] / totals[0])
            total_w, _ = draw.textsize(total_text, font=gotham_font)
            draw.text((width - total_w - max_w - padding - 25, y + 5), total_text, fill=(colors[i]), font=gotham_font)
            y += max_h + 9 + 5

    del draw
    im.save(filename)

def pie_chart(filename, data, gap=0):
    padding = 100
    width = height = 600 + padding
    full_width = width + padding

    im = Image.new("RGB", (full_width, full_width), (255, 255, 255))
    draw = ImageDraw.Draw(im)

    gotham_title = ImageFont.truetype("fonts/opensans-semibold-webfont.ttf", 48)
    title_w, title_h = draw.textsize(data["title"], font=gotham_title)
    draw.text(((padding + width - title_w) / 2, (padding - title_h) / 2), data["title"], fill=(0, 0, 0), font=gotham_title)

    levels = {}
    level_step = 50
    label_text = []
    label_colors = []
    for arc in data["arcs"]:
        label_text.append(arc["label"])
        label_colors.append(arc["color"])

        if not arc["level"] in levels:
            levels[arc["level"]] = -90
        perc = (360 * arc["value"] / data["total"])
        mid_angle_rad = radians(levels[arc["level"]] + perc / 2)
        shrink = arc["level"] * level_step
        arc_xy = (padding + shrink + gap * cos(mid_angle_rad),padding + shrink + gap * sin(mid_angle_rad) , width - shrink,height - shrink)
        draw.pieslice(arc_xy, levels[arc["level"]], levels[arc["level"]] + perc, fill=arc["color"])
        levels[arc["level"]] += perc

    gotham_medium = ImageFont.truetype("fonts/opensans-semibold-webfont.ttf", 12)
    _, line_height = draw.textsize("0g", font=gotham_medium)
    box_width = full_width / len(label_text)
    box_height = line_height * 4
    x = 0
    y = full_width - box_height
    for l in range(len(label_text)):
        draw.rectangle((x, y, x + box_width, y + box_height), fill=(label_colors[l]))
        text_w, text_h = draw.textsize(label_text[l], font=gotham_medium)
        smart_text(draw, label_text[l], x + (box_width - text_w) / 2, y + 2 + (box_height - text_h) / 2, border=(100,100,100), font=gotham_medium, align="center")
        x += box_width
    # draw.text(((padding + width - title_w) / 2, (padding - title_h) / 2), data["title"], fill=(0, 0, 0), font=gotham_title)

    del draw
    im.save(filename)

def box_chart(filename, data):
    width = height = 800
    gutter = 50
    im = Image.new("RGB", (width, height + gutter), (200, 200, 200))
    draw = ImageDraw.Draw(im)
    gotham_title = ImageFont.truetype("fonts/opensans-semibold-webfont.ttf", 24)

    data_total = 0
    min_width = 3
    min_value = (min_width + 1) * data["total"] / width
    for box in data["values"]:
        box_total = 0
        for v in box:
            box_total += v["value"]
        if box_total == 0:
            continue
        if box_total < min_value:
            data_total += min_value
        else:
            data_total += box_total

    pos_y = gutter
    pos_list = []
    sub_bar_pos = []
    for box in data["values"]:
        box_total = 0
        for v in box:
            box_total += v["value"]
        if box_total == 0:
            pos_list.append(pos_y)
            continue
        box_h = width * max(min_value, box_total) / data_total
        min_h = max(min_value, box_total) / box_h
        if len(box) == 1:
            draw.rectangle((0,pos_y , width,pos_y + box_h), fill=(box[0]["color"]))
        else:
            pos_x = 0
            for i in range(len(box)):
                v = box[i]
                if v["value"] == 0:
                    sub_bar_pos.append(pos_x)
                    continue
                link_gap = (len(data["key"]) - i) * 2
                box_w = width * max(min_h, v["value"]) / box_total
                draw.rectangle((pos_x,pos_y - link_gap , pos_x + box_w,pos_y + box_h + link_gap), fill=(v["color"]))
                sub_bar_pos.append(pos_x)
                pos_x += box_w
            sub_bar_pos.append(width)
        pos_y += box_h
        pos_list.append(pos_y)
    # Labels
    prev_label_y = 0
    for i in range(len(data["values"])):
        box = data["values"][i]
        if len(box) != 1:
            continue
        if box[0]["value"] == 0:
            continue
        label_w, label_h = draw.textsize(box[0]["label"], font=gotham_title)
        label_y = max(prev_label_y, pos_list[i] - label_h - 1)
        smart_text(draw, box[0]["label"], (width - label_w) / 2, label_y, font=gotham_title, fillColor=(0, 0, 0), border=box[0]["color"])
        prev_label_y = label_y + label_h + 1

    # chart_box = (0, 0, width, height)
    # region = im.crop(chart_box)
    # region = region.rotate(90)
    # im.paste(region, chart_box)

    gotham_label = ImageFont.truetype("fonts/opensans-semibold-webfont.ttf", 12)
    # draw.rectangle((0,0 , width,gutter), fill=(0, 0, 0))
    pos_x = 0
    gap = 2
    key_w = width / len(data["key"])
    for i in range(len(data["key"])):
        key = data["key"][i]
        # Rect
        draw.rectangle((pos_x,0, pos_x + key_w,gutter), fill=key["color"])
        # Gap Line
        if i == 1:
            draw.rectangle((sub_bar_pos[i],gutter - gap , pos_x + key_w  - 1,gutter), fill=key["color"])
            # Dividers
            draw.rectangle((sub_bar_pos[i],gutter - gap - 1 , pos_x  - 1,gutter - gap - 1), fill=(0, 0, 0))
            draw.rectangle((sub_bar_pos[i + 1],gutter , pos_x + key_w  - 1,gutter), fill=(0, 0, 0))
            if sub_bar_pos[i] > 2:
                draw.rectangle((sub_bar_pos[i] - 1,gutter - gap - 1 , sub_bar_pos[i] - 1,gutter), fill=(0, 0, 0))

        # Label
        key_label_w, key_label_h = draw.textsize(key["label"], font=gotham_label)
        smart_text(
            draw, key["label"],
            pos_x + (key_w - key_label_w) / 2, (gutter - key_label_h) / 2,
            font=gotham_label, align="center"
        )
        pos_x += key_w

    del draw
    im.save(filename)


from services.proto import approver_pb2

class SendApprovalServicer:
    def __init__(self, logger, activ_util, users_util):
        self._logger = logger
        self._activ_util = activ_util
        self._users_util = users_util

    def _build_activity(self, req):
        actor = self._activ_util.build_actor
        followed = actor(req.follow.followed.handle, req.follow.followed.host)
        follower = actor(req.follow.follower.handle, req.follow.follower.host)
        activity_type = 'Accept' if req.accept else 'Reject'

        return {
            '@context': self._activ_util.rabble_context(),
            'type': activity_type,
            'actor': followed,
            'object': {
                'type': 'Follow',
                'actor': follower,
                'object': followed,
            },
            'to': [follower],
        }

    def _get_local_user_id(self, handle):
        user = self._users_util.get_user_from_db(handle=handle,
                                                 host_is_null=True)
        if user is None:
            return None
        return user.global_id

    def SendApproval(self, req, context):
        resp = approver_pb2.ApprovalResponse()
        url = self._activ_util.build_inbox_url(req.follow.follower.handle,
                                               req.follow.follower.host)
        activity = self._build_activity(req)

        sender_id = self._get_local_user_id(req.follow.followed.handle)
        _, err = self._activ_util.send_activity(activity,
                                                url,
                                                sender_id=sender_id)
        if err is not None:
            resp.error = err
            resp.result_type = approver_pb2.ApprovalResponse.ERROR

        return resp


import os
import pandas as pd
from PIL import Image
import numpy as np
import warnings
warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning)
Image.MAX_IMAGE_PIXELS = None

def export_csv(root_imgs_path, csv_name):
    dic_categories = {'scenery' : [], 'furniture' : [], 'animal' : [], 'plant' : []}

    for path in os.listdir(root_imgs_path):
        c, name = path.split("_")
        if c in dic_categories.keys():
            dic_categories[c].append(name)

    # Show information
    total_objects = sum([len(dic_categories[c]) for c in dic_categories])
    # Object có số lượng ảnh lớn nhất
    max_len = max([len(dic_categories[c]) for c in dic_categories])
    print(f'total_objects = {total_objects}')
    print(f'object có nhiều ảnh nhất = {max_len}')

    # generate csv with pandas
    for c in dic_categories:
        dic_categories[c] += [""]*(max_len - len(dic_categories[c]))
    df = pd.DataFrame(dic_categories)
    df.to_csv("categories.csv", index=False)

    return dic_categories

def processing_data(images_path):
    dic_categories = {'animal' : [], 'plant' : [], 'furniture' : [], 'scenery' : []}
    count = 0

    for folder in os.listdir(images_path):
        if folder.split("_")[0] in dic_categories:
            path = images_path + folder
            list_dir = [path + '/' + name for name in os.listdir(path) if name.endswith((".jpg", ".png", ".jpeg"))]
            for p in list_dir:
                try:
                    #Step1:Open image, sử dụng Image của PIL để mở file ảnh theo path(biến p)
                    #thu được biến img chứa ảnh(lưu ý: biến thu được chứa ảnh dạng PIL)
                    img = Image.open(p)

                    #Step2: Verify image, Sau khi mở ảnh ở step1, thu được biến img chứa ảnh,
                    # .verify(): phát hiện ảnh lỗi
                    img.verify()

                    #Step3: Open image, Vì sau khi verify() hình ảnh sẽ bị đóng lại, vì vậy cần mở lại hình ảnh như Step1.
                    img = Image.open(p)

                    #Step4: Check width of image, nếu hình ảnh có width<10 thì xoá ảnh
                    if img.size[0] < 10:
                        os.remove(p)

                    #Step5: Only 3 channel image (color image), convert ảnh từ PIL sang numpy
                    #nếu hình ảnh có channel khác 3 thì xóa ảnh.
                    img = np.asarray(img)
                    if img.shape[2] != 3:
                        os.remove(p)

                except Exception as e:
                    print(e)
                    count += 1
                    print("error: ", p)
                    os.remove(p) # Các trường hợp ngoại lệ, ảnh lỗi,... sẽ bị xóa

if __name__ == '__main__':

    root_imgs_path = "./images/"
    csv_name = "categories.csv"
    dic_categories = export_csv(root_imgs_path, csv_name)

    root_imgs_path = "./images/"
    processing_data(images_path=root_imgs_path)