import os
import uuid

import json
import datetime
import validators
from flask import Blueprint, jsonify
from flask import render_template
from flask import request, current_app as app
from flask import send_from_directory
from werkzeug.utils import secure_filename

from app.utils import allowed_file, hash_file, colors

VALID_DATA_SOURCES = ['json_upload', 'api_endpoint']

views = Blueprint('views', __name__)

@views.route('/', methods=['GET', ])
def index():
    """
    Display the generator GUI
    :return:
    """
    return render_template('index.html',
                           main_css=hash_file(os.path.abspath(app.config['STATICFILES_DIR'] + '/css/main.css')),
                           main_js=hash_file(os.path.abspath(app.config['STATICFILES_DIR'] + '/js/main.js')),
                           utils_js=hash_file(os.path.abspath(app.config['STATICFILES_DIR'] + '/js/utils.js')),
                           colors=colors())

@views.route('/favicon.ico')
def favicon():
    """
    Serve the favicon
    :return:
    """
    return send_from_directory(app.config['STATICFILES_DIR'], 'favicon.ico', mimetype='image/vnd.microsoft.icon')

@views.route('/health-check/')
def health_check():
    """
    Health check for Kubernetes
    :return:
    """
    return jsonify({
        "status": "ok"
    })

@views.route('/', methods=['POST', ])
def process(data=None, via_api=False):
    """
    Start the generation process when the form is submitted
    :return:
    """
    if not data:
        data = request.form
    email = data.get('email', None)
    data_source = data.get('data-source', None)
    build_type = data.get('build-type', None)
    is_auth_enabled = data.get('is-auth-enabled', 'false') == 'true'
    theme_colors = json.loads(data.get('colors', None))

    if not email or not data_source or data_source not in VALID_DATA_SOURCES or not validators.email(email):
        return jsonify(status='error', message='invalid data'), 400

    payload = {
        'creator_email': email,
        'is_auth_enabled': is_auth_enabled
    }

    identifier = str(uuid.uuid4())

    if data_source == 'api_endpoint':
        api_endpoint = data.get('api-endpoint', None)
        if not api_endpoint or not validators.url(api_endpoint):
            return jsonify(status='error', message='invalid endpoint url'), 400
        payload['endpoint_url'] = api_endpoint
    elif data_source == 'json_upload':
        if 'json-upload' not in request.files:
            return jsonify(status='error', message='data file is required for the selected source'), 400
        uploaded_file = request.files['json-upload']
        if uploaded_file.filename == '':
            return jsonify(status='error', message='data file is required for the selected source'), 400
        if uploaded_file and allowed_file(uploaded_file.filename, ['zip']):
            filename = secure_filename(identifier)
            file_save_location = os.path.join(app.config['UPLOAD_DIR'], filename)
            uploaded_file.save(file_save_location)
            payload['zip_file'] = file_save_location

    from app.tasks import generate_app_task  # A Local import to avoid circular import
    task = generate_app_task.delay(config=app.config, payload=payload, via_api=via_api, identifier=identifier, build_type=build_type, theme_colors=theme_colors)
    return jsonify(status='ok', identifier=identifier, started_at=datetime.datetime.now(), task_id=task.id)


import torch.nn as nn
from .EncodingModule import EncodingModule
from .DecodingModule import DecodingModule

class SkipConnectionModule(nn.Module):
    def __init__(self, encoding_module, decoding_module, inner_module=None):
        super(SkipConnectionModule, self).__init__()
        self._verify_compatibility(encoding_module, decoding_module, inner_module)
        self.encoding_module = encoding_module
        self.inner_module = inner_module
        self.decoding_module = decoding_module
        self.inner_channels = encoding_module.inner_channels
        self.outer_channels = encoding_module.outer_channels

    @staticmethod
    def _verify_compatibility(encoding_module, decoding_module, inner_module):
        assert isinstance(encoding_module, EncodingModule)
        assert isinstance(decoding_module, DecodingModule)
        assert encoding_module.inner_channels == decoding_module.inner_channels
        assert encoding_module.outer_channels == decoding_module.outer_channels
        assert isinstance(inner_module, nn.Module) or (inner_module is None)
        if inner_module is not None:
            assert encoding_module.inner_channels == inner_module.outer_channels

    def forward(self, outer_features):
        inner_features = self.encoding_module(outer_features)
        if self.inner_module is not None:
            inner_features = self.inner_module(inner_features)
        outer_features = self.decoding_module(inner_features, outer_features)
        return outer_features


import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

SECRET_KEY = 'fake-key'

INSTALLED_APPS = [
    'django.contrib.contenttypes',
    'taggit',
    'taggit_forms',

    'tests',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
    }
}

ROOT_URLCONF = 'tests.urls'


import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

# Load MNIST Dataset and separate training and testing data
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)

# Creating the model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)

model.save('handwritten.model')
model = tf.keras.models.load_model('handwritten.model')

# Evaluating the model
loss, accuracy = model.evaluate(x_test, y_test)

print("====")
print(f"Loss: {loss}")
print(f"Accuracy: {accuracy}")
print("====")

# Testing model on created 'digits' dataset
image_number = 1

while os.path.isfile(f"venv/digits/digit{image_number}.png"):
    try:
        print(f"Digit {image_number}")
        img = cv2.imread(f"venv/digits/digit{image_number}.png")[:,:,0]
        img = np.invert(np.array([img]))
        prediction = model.predict(img)
        print(f"Digit is most likely a {np.argmax(prediction)}")
        plt.imshow(img[0])
        plt.show()
        print("=====")
    except:
        print("Error!")
    finally:
        image_number += 1


class Solution:

    def isSubtree(self, root, subRoot) -> bool:
        # given two roots with matching values, verify subtrees
        # have the same values.
        def nodes_match(node1, node2):
            if node1.val != node2.val:
                return False

            left1, right1 = node1.left, node1.right
            left2, right2 = node2.left, node2.right

            # Recurse into children and combine their results
            # as our overall result.
            result = True
            if left1 and left2:
                result = nodes_match(left1, left2)
            else:
                # True if both None
                result = left1 is None and left2 is None
            if right1 and right2:
                return result and nodes_match(right1, right2)
            # True if both None
            return result and right1 is None and right2 is None

        # Find candidate nodes, i.e, nodes with node.val == subroot.val
        nodes, rootval = [root], subRoot.val
        while nodes:
            node = nodes.pop()
            if node.val == rootval:
                if nodes_match(node, subRoot):
                    return True

            left, right = node.left, node.right
            if left:
                nodes.append(left)
            if right:
                nodes.append(right)
        return False


"""
``spectavi.feature``
================
The feature detection/descriptor library of the spectavi.
"""

from spectavi.__libspectavi import clib
from cndarray.ndarray import NdArray
import ctypes as ct
from numpy.ctypeslib import ndpointer
import numpy as np

"""
==================================================================================
sift_filter
==================================================================================
"""

_sift_filter = clib.sift_filter
_sift_filter.restype = None
_sift_filter.argtypes = [ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                         ct.c_int,
                         ct.c_int,
                         ct.POINTER(NdArray), ]

def sift_filter(im):
    """
    Detect SIFT features and compute descriptors for a given image `im`.

    Parameters
    ----------
    im : float32 ndarray
        A (single channel/grayscale) image (2d).

    Returns
    -------
    kps : float ndarray
        A matrix of size `nkp` by 132 which contains the SIFT descriptor for
        each keypoint, where `nkp` is the number of keypoints found.

    """
    if len(im.shape) != 2:
        raise TypeError("Only 2d images are supported.")
    sift_ret = NdArray(dtype='float32')
    hgt, wid = im.shape
    _sift_filter(im, wid, hgt, sift_ret)
    return sift_ret.asarray()

_sift_filter_batch_create = clib.sift_filter_batch_create
_sift_filter_batch_create.restype = ct.c_void_p
_sift_filter_batch_create.argtypes = None

_sift_filter_batch_destroy = clib.sift_filter_batch_destroy
_sift_filter_batch_destroy.restype = None
_sift_filter_batch_destroy.argtypes = [ct.c_void_p]

_sift_filter_batch_register_image = clib.sift_filter_batch_register_image
_sift_filter_batch_register_image.restype = None
_sift_filter_batch_register_image.argtypes = [ct.c_void_p,
                                              ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                                              ct.c_int,
                                              ct.c_int,
                                              ct.POINTER(NdArray),]

_sift_filter_batch_process = clib.sift_filter_batch_process
_sift_filter_batch_process.restype = None
_sift_filter_batch_process.argtypes = [ct.c_void_p,
                                       ct.c_int, ]

def sift_filter_batch(ims,nthread=8):
    """
    Detect SIFT features and compute descriptors for a given list of images
    `ims`.

    Parameters
    ----------
    ims : list of float32 ndarrays
        A list of (single channel/grayscale) image (2d).

    Returns
    -------
    kps : list of float ndarray
        A list of matrices of size `nkp` by 132 which contain the SIFT
        descriptors of each keypoint, where `nkp` is the number of keypoints
        found in each image. Returns one matrix for each input image.

    """
    for im in ims:
        if len(im.shape) != 2:
            raise TypeError("Only 2d images are supported.")
    nims = len(ims)
    nthread = np.min([nims,nthread])
    sfb = _sift_filter_batch_create()
    sift_rets = [ NdArray(dtype='float32') for _ in range(nims) ]
    for im,ret in zip(ims,sift_rets):
        hgt, wid = im.shape
        _sift_filter_batch_register_image(sfb,im,wid,hgt,ret)
    _sift_filter_batch_process(sfb,nthread)
    _sift_filter_batch_destroy(sfb)
    return [ ret.asarray() for ret in sift_rets]

def sift_filter_striped(im,nthread=8,buffer_size=20):
    """
    Detect SIFT features and compute descriptors for one image using multiple
    threads.

    Parameters
    ----------
    im : float32 ndarray
        A (single channel/grayscale) image (2d).

    Returns
    -------
    kps : float ndarray
        A matrix of size `nkp` by 132 which contains the SIFT descriptor for
        each keypoint, where `nkp` is the number of keypoints found.

    Note: this function is intended to compte similar results to `sift_filter`;
    however, due to boundary effects of patching up an image, this is not
    usually true. The results should be very similar between the two
    computations.

    """
    hgt, _ = im.shape
    split_hgt = int(np.ceil(hgt / float(nthread) ))
    bboxes = list()
    ims = list()
    for iy in range(0,hgt,split_hgt):
        iy_start = iy
        iy_end = min([iy+split_hgt,hgt])
        bf_start = max([iy_start-buffer_size,0])
        bf_end = min([iy_end+buffer_size+1,hgt])
        bboxes.append([iy_start,iy_end,bf_start])
        ims.append(im[bf_start:bf_end])
    sifts = sift_filter_batch(ims,nthread=nthread)
    ret_sift = list()
    for bb,sift in zip(bboxes,sifts):
        iy_start,iy_end,bf_start = bb
        sy = sift[:,1]
        sy += bf_start
        idx = (sy > iy_start) & (sy < iy_end)
        ret_sift.append(sift[idx,:])
    return np.vstack(ret_sift)

"""
==================================================================================
ann_hnswlib
==================================================================================
"""

_ann_hnswlib = clib.ann_hnswlib
_ann_hnswlib.restype = None
_ann_hnswlib.argtypes = [ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                         ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                         ct.c_int,
                         ct.c_int,
                         ct.c_int,
                         ct.c_int,
                         ct.POINTER(NdArray), ]

def ann_hnswlib(x, y, k=2):
    """
    Run the Approximate Nearest Neighbour (ann) algorithm (using the NSWlib implementation.)

    Parameters
    ----------
    x : float32 ndarray
        The database to query against.
    y : float32 ndarray
        The query.
    k : int, optional
        The amount of nearest neighbours to calculate.

    Returns
    -------
    ann: uint64 ndarray
        The array of size `y.shape[0]` by `k` which is the index into `x`
        describing the `k` nearest neighbours for each entry of `y` in
        ascending order of distance.

    """
    xrows, xdim = x.shape
    yrows, ydim = y.shape
    assert ydim == xdim
    dim = xdim
    ann_ret = NdArray(dtype='uint64')
    _ann_hnswlib(x, y, xrows, yrows, dim, k, ann_ret)
    return ann_ret.asarray()

"""
==================================================================================
nn_bruteforce
==================================================================================
"""

_nn_bruteforce = clib.nn_bruteforce
_nn_bruteforce.restype = None
_nn_bruteforce.argtypes = [ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                           ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                           ct.c_int,
                           ct.c_int,
                           ct.c_int,
                           ct.c_int,
                           ct.c_float,
                           ct.c_float,
                           ct.POINTER(NdArray),
                           ct.POINTER(NdArray), ]

_nn_bruteforcei = clib.nn_bruteforcei
_nn_bruteforcei.restype = None
_nn_bruteforcei.argtypes = [ndpointer(ct.c_int, flags="C_CONTIGUOUS"),
                            ndpointer(ct.c_int, flags="C_CONTIGUOUS"),
                            ct.c_int,
                            ct.c_int,
                            ct.c_int,
                            ct.c_int,
                            ct.c_float,
                            ct.c_float,
                            ct.POINTER(NdArray),
                            ct.POINTER(NdArray), ]

_nn_bruteforcel1k2 = clib.nn_bruteforcel1k2
_nn_bruteforcel1k2.restype = None
_nn_bruteforcel1k2.argtypes = [ndpointer(ct.c_ubyte, flags="C_CONTIGUOUS"),
                               ndpointer(ct.c_ubyte, flags="C_CONTIGUOUS"),
                               ct.c_int,
                               ct.c_int,
                               ct.c_int,
                               ct.c_int,
                               ct.POINTER(NdArray),
                               ct.POINTER(NdArray), ]

def nn_bruteforce(x, y, p=.5, mu=0., k=2, use_int=False):
    """
    Nearest Neighbour algorithm using a pseudo-bruteforce technique.

    Can be used to compute nearest neighbours for any p-norm.

    Parameters
    ----------
    x : float32 ndarray
        The database to query against.
    y : float32 ndarray
        The query.
    p : float, optional
        p-value of norm.
    mu : float, optional
        Approximation value, when `mu`=0 computation is exact.
    k : int, optional
        The amount of nearest neighbours to calculate.

    Returns
    -------
    nn_idx: uint64 ndarray
        The array of size `y.shape[0]` by `k` which is the index into `x`
        describing the `k` nearest neighbours for each entry of `y` in
        ascending order of distance.
    nn_idx: float32 ndarray
        The array of size `y.shape[0]` by `k` which is the distance of the
        nearest neighbours in ascening order.

    """
    xrows, xdim = x.shape
    yrows, ydim = y.shape
    assert ydim == xdim
    dim = xdim
    nn_idx = NdArray(dtype='uint64')
    if not use_int:
        nn_dist = NdArray(dtype='float32')
        _nn_bruteforce(x, y, xrows, yrows, dim, k, p, mu, nn_idx, nn_dist)
    else:
        nn_dist = NdArray(dtype='int32')
        xi = np.round(100 * x).astype('int32')
        yi = np.round(100 * y).astype('int32')
        _nn_bruteforcei(xi, yi, xrows, yrows, dim, k, p, mu, nn_idx, nn_dist)
    return nn_idx.asarray(), nn_dist.asarray()

def nn_bruteforcel1k2(x, y, nthreads=1):
    """
    Highly optimized L1 NN with k=2, and inputs must be 8-unsigned bytes
    aligned to 16-byte boundaries.
    """
    xrows, xdim = x.shape
    yrows, ydim = y.shape
    assert ydim == xdim
    dim = xdim
    nn_idx = NdArray(dtype='uint64')
    nn_dist = NdArray(dtype='int32')
    _nn_bruteforcel1k2(x, y, xrows, yrows, dim, nthreads, nn_idx, nn_dist)
    return nn_idx.asarray(), nn_dist.asarray()

"""
==================================================================================
kmedians
==================================================================================
"""

_nn_kmedians = clib.nn_kmedians
_nn_kmedians.restype = None
_nn_kmedians.argtypes = [ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                         ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                         ct.c_int,
                         ct.c_int,
                         ct.c_int,
                         ct.c_int,
                         ct.c_int,
                         ct.c_int,
                         ct.c_int,
                         ct.POINTER(NdArray),
                         ct.POINTER(NdArray), ]

def nn_kmedians(x, y, k, c=5):
    xrows, dim = x.shape
    yrows, ydim = y.shape
    nmx = int(np.round(np.sqrt(xrows / c) * c))
    nmy = int(np.round(np.sqrt(yrows / c) * c))
    assert ydim == dim
    nn_idx = NdArray(dtype='uint64')
    nn_dist = NdArray(dtype='float32')
    _nn_kmedians(x, y, xrows, yrows, dim, nmx, nmy, c, k, nn_idx, nn_dist)
    return nn_idx.asarray(), nn_dist.asarray()

"""
==================================================================================
cascading_hash
==================================================================================
"""

_nn_cascading_hash = clib.nn_cascading_hash
_nn_cascading_hash.restype = None
_nn_cascading_hash.argtypes = [ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                               ndpointer(ct.c_float, flags="C_CONTIGUOUS"),
                               ct.c_int,
                               ct.c_int,
                               ct.c_int,
                               ct.c_int,
                               ct.c_int,
                               ct.c_int,
                               ct.c_int,
                               ct.POINTER(NdArray),
                               ct.POINTER(NdArray), ]

def nn_cascading_hash(x, y, k=2, m=None, n=2, g=2):
    xrows, xdim = x.shape
    yrows, ydim = y.shape
    assert ydim == xdim
    if m is None: # auto-tune `m` if specified with None
        # experiments show we want 6 points in each hash-code
       mrows = max([xrows,yrows])
       m = int(np.floor(np.log2(mrows / 6.)))
       if m < 4:
           # using hashes is not appropriate:
           return  nn_bruteforcel1k2((x+128).astype('uint8'),
                   (y+128).astype('uint8'),nthreads=8)
    dim = xdim
    cashash_idx = NdArray(dtype='uint64')
    cashash_dist = NdArray(dtype='float32')
    _nn_cascading_hash(x, y, xrows, yrows, dim, k, m, n, g, cashash_idx, cashash_dist)
    return cashash_idx.asarray(), cashash_dist.asarray()

"""
==================================================================================
normalization
==================================================================================
"""

def normalize_to_ubyte_and_multiple_16_dim(x,dtype='float32'):
    """
    Normalize a data matrix to:
    - have zero mean for each column
    - be in the range [-128,127]
    - return as required `dtype`
    The main use of this function is with `nn_cascading_hash` and
    `nn_bruteforcel1k2` which make assumptions range is between [-128,127] and
    [0,255] respectively.
    """
    x0 = x
    x0 = x0 - np.mean(x0,axis=0,keepdims=True) #de-mean
    max_per_col = np.max(x0,axis=0,keepdims=True)
    min_per_col = np.min(x0,axis=0,keepdims=True)
    norm = np.max(np.stack([max_per_col,-min_per_col]),axis=0)
    x0 = (x0) / norm * 128
    x0 = np.round(x0)
    x0[x0>127] = 127
    x0[x0<-128] = -128
    xrows, dim = x0.shape
    new_dim = int(np.ceil(dim / 16.) * 16)
    xx = np.zeros([xrows, new_dim])
    xx[:, :dim] = x0
    return xx.astype(dtype)

"""
==================================================================================
"""


import collections
import itertools
import os.path
import tkinter as tk

import gym
import gym.envs.registration
import gym.spaces

import numpy as np

UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
ROTATE_RIGHT = 4
ROTATE_LEFT = 5
LASER = 6
NOOP = 7

class GatheringEnv(gym.Env):
    metadata = {'render.modes': ['human']}
    scale = 20
    viewbox_width = 10
    viewbox_depth = 20
    padding = max(viewbox_width // 2, viewbox_depth - 1)
    agent_colors = ['red', 'yellow']

    def _text_to_map(self, text):
        m = [list(row) for row in text.splitlines()]
        l = len(m[0])
        for row in m:
            if len(row) != l:
                raise ValueError('the rows in the map are not all the same length')

        def pad(a):
            return np.pad(a, self.padding + 1, 'constant')
        a = np.array(m).T
        self.initial_food = pad(a == 'O').astype(np.int)
        self.walls = pad(a == '#').astype(np.int)

    def __init__(self, n_agents=1, map_name='default'):
        self.n_agents = n_agents
        self.root = None
        if not os.path.exists(map_name):
            expanded = os.path.join('maps', map_name + '.txt')
            if not os.path.exists(expanded):
                raise ValueError('map not found: ' + map_name)
            map_name = expanded
        with open(map_name) as f:
            self._text_to_map(f.read().strip())
        self.width = self.initial_food.shape[0]
        self.height = self.initial_food.shape[1]
        self.state_size = self.viewbox_width * self.viewbox_depth * 4
        self.action_space = gym.spaces.MultiDiscrete([[0, 7]] * n_agents)
        self.observation_space = gym.spaces.MultiDiscrete([[[0, 1]] * self.state_size] * n_agents)
        self._spec = gym.envs.registration.EnvSpec(**_spec)
        self.reset()
        self.done = False

    def _step(self, action_n):
        assert len(action_n) == self.n_agents
        action_n = [NOOP if self.tagged[i] else a for i, a in enumerate(action_n)]
        self.beams[:] = 0
        movement_n = [(0, 0) for a in action_n]
        for i, (a, orientation) in enumerate(zip(action_n, self.orientations)):
            if a not in [UP, DOWN, LEFT, RIGHT]:
                continue
            # a is relative to the agent's orientation, so add the orientation
            # before interpreting in the global coordinate system.
            #
            # This line is really not obvious to read. Replace it with something
            # clearer if you have a better idea.
            a = (a + orientation) % 4
            movement_n[i] = [
                (0, -1),  # up/forward
                (1, 0),   # right
                (0, 1),   # down/backward
                (-1, 0),  # left
            ][a]
        next_locations = [a for a in self.agents]
        next_locations_map = collections.defaultdict(list)
        for i, ((dx, dy), (x, y)) in enumerate(zip(movement_n, self.agents)):
            if self.tagged[i]:
                continue
            next_ = ((x + dx), (y + dy))
            if self.walls[next_]:
                next_ = (x, y)
            next_locations[i] = next_
            next_locations_map[next_].append(i)
        for overlappers in next_locations_map.values():
            if len(overlappers) > 1:
                for i in overlappers:
                    next_locations[i] = self.agents[i]
        self.agents = next_locations

        for i, act in enumerate(action_n):
            if act == ROTATE_RIGHT:
                self.orientations[i] = (self.orientations[i] + 1) % 4
            elif act == ROTATE_LEFT:
                self.orientations[i] = (self.orientations[i] - 1) % 4
            elif act == LASER:
                self.beams[self._viewbox_slice(i, 5, 20, offset=1)] = 1

        obs_n = self.state_n
        reward_n = [0 for _ in range(self.n_agents)]
        done_n = [self.done] * self.n_agents
        info_n = [{}] * self.n_agents

        self.food = (self.food + self.initial_food).clip(max=1)

        for i, a in enumerate(self.agents):
            if self.tagged[i]:
                continue
            if self.food[a] == 1:
                self.food[a] = -15
                reward_n[i] = 1
            if self.beams[a]:
                self.tagged[i] = 25

        for i, tag in enumerate(self.tagged):
            if tag == 1:
                # Relocate to a respawn point.
                for spawn_point in self.spawn_points:
                    if spawn_point not in self.agents:
                        self.agents[i] = spawn_point
                        break

        self.tagged = [max(i - 1, 0) for i in self.tagged]

        return obs_n, reward_n, done_n, info_n

    def _viewbox_slice(self, agent_index, width, depth, offset=0):
        left = width // 2
        right = left if width % 2 == 0 else left + 1
        x, y = self.agents[agent_index]
        return tuple(itertools.starmap(slice, (
            ((x - left, x + right), (y - offset, y - offset - depth, -1)),      # up
            ((x + offset, x + offset + depth), (y - left, y + right)),          # right
            ((x + left, x - right, -1), (y + offset, y + offset + depth)),      # down
            ((x - offset, x - offset - depth, -1), (y + left, y - right, -1)),  # left
        )[self.orientations[agent_index]]))

    @property
    def state_n(self):
        agents = np.zeros_like(self.food)
        for i, a in enumerate(self.agents):
            if not self.tagged[i]:
                agents[a] = 1

        food = self.food.clip(min=0)
        s = np.zeros((self.n_agents, self.viewbox_width, self.viewbox_depth, 4))
        for i, (orientation, (x, y)) in enumerate(zip(self.orientations, self.agents)):
            if self.tagged[i]:
                continue
            full_state = np.stack([food, np.zeros_like(food), agents, self.walls], axis=-1)
            full_state[x, y, 2] = 0

            xs, ys = self._viewbox_slice(i, self.viewbox_width, self.viewbox_depth)
            observation = full_state[xs, ys, :]

            s[i] = observation if orientation in [UP, DOWN] else observation.transpose(1, 0, 2)

        return s.reshape((self.n_agents, self.state_size))

    def _reset(self):
        self.food = self.initial_food.copy()

        p = self.padding
        self.walls[p:-p, p] = 1
        self.walls[p:-p, -p - 1] = 1
        self.walls[p, p:-p] = 1
        self.walls[-p - 1, p:-p] = 1

        self.beams = np.zeros_like(self.food)

        self.agents = [(i + self.padding + 1, self.padding + 1) for i in range(self.n_agents)]
        self.spawn_points = list(self.agents)
        self.orientations = [UP for _ in self.agents]
        self.tagged = [0 for _ in self.agents]

        return self.state_n

    def _close_view(self):
        if self.root:
            self.root.destroy()
            self.root = None
            self.canvas = None
        self.done = True

    def _render(self, mode='human', close=False):
        if close:
            self._close_view()
            return

        canvas_width = self.width * self.scale
        canvas_height = self.height * self.scale

        if self.root is None:
            self.root = tk.Tk()
            self.root.title('Gathering')
            self.root.protocol('WM_DELETE_WINDOW', self._close_view)
            self.canvas = tk.Canvas(self.root, width=canvas_width, height=canvas_height)
            self.canvas.pack()

        self.canvas.delete(tk.ALL)
        self.canvas.create_rectangle(0, 0, canvas_width, canvas_height, fill='black')

        def fill_cell(x, y, color):
            self.canvas.create_rectangle(
                x * self.scale,
                y * self.scale,
                (x + 1) * self.scale,
                (y + 1) * self.scale,
                fill=color,
            )

        for x in range(self.width):
            for y in range(self.height):
                if self.beams[x, y] == 1:
                    fill_cell(x, y, 'yellow')
                if self.food[x, y] == 1:
                    fill_cell(x, y, 'green')
                if self.walls[x, y] == 1:
                    fill_cell(x, y, 'grey')

        for i, (x, y) in enumerate(self.agents):
            if not self.tagged[i]:
                fill_cell(x, y, self.agent_colors[i])

        if False:
            # Debug view: see the first player's viewbox perspective.
            p1_state = self.state_n[0].reshape(self.viewbox_width, self.viewbox_depth, 4)
            for x in range(self.viewbox_width):
                for y in range(self.viewbox_depth):
                    food, me, other, wall = p1_state[x, y]
                    assert sum((food, me, other, wall)) <= 1
                    y_ = self.viewbox_depth - y - 1
                    if food:
                        fill_cell(x, y_, 'green')
                    elif me:
                        fill_cell(x, y_, 'cyan')
                    elif other:
                        fill_cell(x, y_, 'red')
                    elif wall:
                        fill_cell(x, y_, 'gray')
            self.canvas.create_rectangle(
                0,
                0,
                self.viewbox_width * self.scale,
                self.viewbox_depth * self.scale,
                outline='blue',
            )

        self.root.update()

    def _close(self):
        self._close_view()

    def __del__(self):
        self.close()

_spec = {
    'id': 'Gathering-v0',
    'entry_point': GatheringEnv,
    'reward_threshold': 100,
}

gym.envs.registration.register(**_spec)


#!/usr/bin/env python
# coding: utf-8

# In[1]:

import pandas as pd

# In[2]:

df = pd.read_csv("C://Users//savan//OneDrive - Temple University//Documents//ICAtitanic.csv")
subset = df[['PassengerId']]
#print(subset.tail(1))
passenger = df['PassengerId']
print("The number of people that were on the Titanic were")
print(passenger.loc[passenger.shape[0]-1])

# In[3]:

print("The number of people who survived are...")
survived = df[df['Survived'] == 1]
print(len(survived))
print("The number of people who died are...")
died = df[df['Survived'] == 0]
print(len(died))
print("The amount of people in the first class were...")
print(len(df[df['Pclass'] == 1]))
print("The amount of people in the second class were...")
print(len(df[df['Pclass'] == 2]))
print("The amount of people in the third class were...")
print(len(df[df['Pclass'] == 3]))
print("The amount of people who died in the first class were...")
print(len(died[died['Pclass'] == 1]))
print("The amount of people who died in the second class were...")
print(len(died[died['Pclass'] == 2]))
print("The amount of people who died in the third class were...")
print(len(died[died['Pclass'] == 3]))

# In[4]:

print("The amount of men '(who were the age of 18 or older)' that died...")
print(len(died))

# In[7]:

#making a death by class histogram
import matplotlib.pyplot as plt
titanicDeaths = df[df["Survived"] == 0]
titanicSurvived = df[df["Survived"] == 1]
n, bins, patches = plt.hist(titanicDeaths['Pclass'], bins =3)
plt.title('Titanic Deaths by Class')
plt.xlabel('Class')
plt.ylabel('Number of deaths')
plt.show()

# In[20]:

titanicDeathsMale = titanicDeaths[titanicDeaths["Sex"] == "male"]
titanicDeathsMen = titanicDeathsMale[titanicDeathsMale["Age"] >= 18]
print(len(titanicDeathsMale))
print(len(titanicDeathsMen))
titanicDeathsFemale = titanicDeaths[titanicDeaths["Sex"] == "female"]
titanicDeathsWomen = titanicDeathsFemale[titanicDeathsFemale["Age"] >= 18]
titanicDeathsChildren = titanicDeaths[titanicDeaths["Age"] < 18]
n, bins, patches = plt.hist(titanicDeathsMen['Pclass'], bins=3)
plt.title('Titanic Deaths Men by Class')
plt.xlabel('Class')
plt.ylabel('Number of Deaths')
plt.show()
#deaths from the women off the titanic
n, bins, patches = plt.hist(titanicDeathsWomen['Pclass'], bins=3)
plt.title('Titanic Deaths Women by Class')
plt.xlabel('Class')
plt.ylabel('Number of Deaths')
plt.show()
#deaths from children off the titanic
n, bins, patches = plt.hist(titanicDeathsChildren['Pclass'], bins=3)
plt.title('Titanic Deaths Children by Class')
plt.xlabel('Class')
plt.ylabel('Number of Deaths')
plt.show()
#the combined of women and children deaths off the titanic
titanicDeathsWomenAndChildren = pd.concat([titanicDeathsWomen, titanicDeathsChildren])
#combined plot of deaths of men & women and children off the titanic
n, bins, patches = plt.hist(titanicDeathsMen['Pclass'], bins=3, label="Men")
n, bins, patches = plt.hist(titanicDeathsWomenAndChildren['Pclass'], bins=3, label="Women and Children")
plt.title('Titanic Deaths by Class')
plt.xlabel('Class')
plt.ylabel('Number of Deaths')
plt.legend()
plt.show()

# In[1]:

#in class activity create new dataframes for men who survived
import pandas as pd
import matplotlib.pyplot as plt
titanicdf = pd.read_csv("C://Users//savan//OneDrive - Temple University//Documents//ICATitanic.csv")
titanicSurvivors = titanicdf[titanicdf["Survived"] == 1]

titanicSurvivorsMen = titanicSurvivors[(titanicSurvivors["Sex"] == "male") & (titanicSurvivors["Age"] >= 18)]
titanicSurvivorsWomenAndChildren = titanicSurvivors[(titanicSurvivors["Sex"] == "female") | (titanicSurvivors["Age"] < 18)]
n, bins, patches = plt.hist(titanicSurvivorsWomenAndChildren['Pclass'], bins=3, label='Survivors Women and Children')
n, bins, patches = plt.hist(titanicSurvivorsMen['Pclass'], bins=3, label='Survivors Men')
plt.title("Titanic Deaths By Class")
plt.xlabel("Class")
plt.ylabel("Number of Deaths")
plt.legend()
plt.show()

# In[ ]:


from core4.queue.job import CoreJob
from gridfs import GridFS
import pandas as pd
from io import BytesIO
import concurrent.futures
from core4.queue.helper.functool import enqueue
import datetime

MONAT = {
    "Januar": "01",
    "Februar": "02",
    "März": "03",
    "April": "04",
    "Mai": "05",
    "Juni": "06",
    "Juli": "07",
    "August": "08",
    "September": "09",
    "Oktober": "10",
    "November": "11",
    "Dezember": "12"
}

class ProcessFiles(CoreJob):
    author = "mra"
    max_parallel = 10

    def execute(self, test=False, threaded=False, concurrent=False, scope=None,
                chunk_size=10, *args, **kwargs):
        """

        :param test: control, if test don't write data to mongoDB
        :param threaded: boolean, use multiple threads or not
        :param concurrent: boolean, launch job multiple times in parallel
        :param scope: files to be processed
        :param chunk_size: size of files chunk to be passed to each job
        if concurrent is true
        :param args:
        :param kwargs:
        :return:
        """
        # define database
        self.target = self.config.driverlicense.collection.data
        self.gfs = GridFS(self.target.connection[self.target.database])
        self.test =test
        if scope is None:
            # list of exsisting files in the database
            files = self.gfs.list()
            # define files chuncks if concurrent is true
            if concurrent:
                chunks =[files[i:i + chunk_size]
                         for i in range(0, len(files), chunk_size)]
                self.logger.info("found [%d] files to extract in [%d] chunks",
                                 len(files), len(chunks))
                # for each chunck of files enqueue the job ProcessFiles
                for launch in chunks:
                    enqueue(ProcessFiles, scope=launch, test=test)
            else:
                self.extract(files, threaded)
        else:
            self.extract(scope, threaded)

    def extract(self, files, threaded):
        """
        This function calls the process function as single
        or multi-threaded
        :param files:
        :param threaded: boolean,use multiple threads or not
        :return:
        """
        # threaded
        if threaded:
            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=8) as executor:
                executor.map(self.process, files)
        else:
            for f in files:
                self.process(f)
        n = self.target.count_documents({})
        self.logger.info("[%d] records with [%d] files", n, len(files))

    def process(self, filename):
        """
        This function processes the excel files and
        saves them to the database
        :param filename:
        :return:
        """
        basename = filename.split("/")[-1]
        # set the job source to the filename
        self.set_source(basename)
        self.logger.info("extract [%s]", basename)
        # get the last version of the file form the database
        fh = self.gfs.get_last_version(filename)
        body = BytesIO(fh.read())
        body.seek(0)
        # create a dataframe from the retrieved data
        df = pd.read_excel(body, header=None)
        if self.test:
            return
        # process the first lines of the dataframe to create
        # the extra variables
        assert df.iloc[0, 0] == "Analyse"
        analyse = df.iloc[0, 1]
        assert df.iloc[1, 0] == "Grundgesamtheit"
        grundgesamtheit = df.iloc[1, 1]
        assert df.iloc[2, 0] == "Zeitraum"
        zeitraum = df.iloc[2, 1]
        assert df.iloc[3, 0] == "Vorfilter"
        vorfilter = df.iloc[3, 1]
        vorfilter_fallzahl = df.iloc[4, 1]
        assert df.iloc[5, 0] == "Zielgruppe"
        zielgruppe = df.iloc[5, 1]
        zielgruppe_fallzahl = df.iloc[6, 1]
        ln = 7
        while df.iloc[ln, 0] != "Basis":
            ln += 1
            if ln > 1000:
                raise RuntimeError("failed to identify start of data")
        d = df.iloc[ln:].copy()
        cols = list(df.iloc[ln - 1])
        cols[0] = "Titel"
        d.columns = ["" if pd.isnull(c)
                     else c.replace("\n", " ").replace(".", "").replace("\s+"," ") for c in cols]
        if "" in d.columns:
            d.drop([""], axis=1, inplace=True)
        #  add the extra variables to the dataframe
        d["Analyse"] = analyse
        d["Grundgesamtheit"] = grundgesamtheit
        d["Zeitraum"] = zeitraum
        d["Vorfilter"] = vorfilter
        d["Zielgruppe"] = zielgruppe
        d.columns = d.columns.str.replace('\s+', ' ')

        monat = d.Zeitraum.apply(
            lambda s: s.replace("Letzter Monat (", "").replace(")",
                                                               "").split())
        d["Monat"] = [
            datetime.datetime.strptime("01." + MONAT[m[0]] + "." + m[1],
                                       "%d.%m.%Y") for m in monat]
        d["val"] = d["Kontakte Mio"].apply(pd.to_numeric,
                                                     errors='coerce')
        d['Date'] = d.Monat.apply(lambda x: x.date().isoformat())

        doc = d.to_dict("rec")
        n = 0
        # delete any previous version of the file in the database
        d = self.target.delete_many({"_src": basename})
        if d.deleted_count > 0:
            self.logger.info("reset [%d] records for [%s]", d.deleted_count,
                             basename)
        # insert the processed file in the database
        # each row of the dataframe is inserted as a record
        for rec in doc:
            nrec = {}
            for k, v in rec.items():
                if not pd.isnull(v):
                    nrec[k] = v
            self.target.insert_one(nrec)
            n += 1
        self.logger.info("inserted [%d] records for [%s]", n, basename)

if __name__ == '__main__':
    from core4.queue.helper.functool import execute
    execute(ProcessFiles, test=False, threaded=True)


import stcol.db.model
from stcol.data_connector.connector import Connector
import settings
import pandas as pd

class DBConnector(Connector):

    def __init__(self, model):
        super().__init__(model)

    def __enter__(self):
        self.session = settings.session()

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    @property
    def tablename(self):
        return self.model.__tablename__

    def get_daily_data(self, symbols=None, date=None, count=None):
        session = settings.session()

        query = self.model.query
        if symbols is not None and len(symbols) != 0:
            query = query.filter(self.model.Symbol.in_(symbols))

        if date is not None:
            query = query.filter(self.model.Date > date)

        df = pd.read_sql(query.statement, session.bind, index_col='Date')
        df = df.drop('Id', axis=1)
        return df

    def setup(self):
        from stcol.db import Base
        Base.metadata.create_all(bind=settings.Engine)

    def store_data(self, df):

        df.to_sql(
            self.tablename,
            settings.Engine,
            index=True,
            method="multi",
            chunksize=5000,
            if_exists='append')

if __name__ == '__main__':
    dom_stock_rate = stcol.db.model.DomStockRate()
    count = dom_stock_rate.query.count()
    print(count)


#Vamos fazer um menu de caixa eletrônico, executando em loop até que o usuário peça para sair. Suponha que o saldo inicial seja R$1000. O usuário deverá digitar qual item do menu para prossegir. Imprima: """
saldo = 1000
while True:

  while True:
    escolha = int(input('[1] - Ver saldo atual\n[2] - Sacar dinheiro\n[3] - Depositar dinheiro\n[4] - Sair\n'))
    if escolha != 1 or escolha != 2 or escolha != 3 or escolha != 4:
      break

  if escolha == 1:
    print(f'O seu saldo atual é {saldo}')

  elif escolha == 2:
    while True:
      sacarDinheiro = float(input('Digite o saldo que deseja sacar:\n'))
      if sacarDinheiro <= saldo:
        print(f'Você sacou R${sacarDinheiro}')
        saldo -= sacarDinheiro
        break
      print('Seu saldo não é o suficiente')

  elif escolha == 3:
    depositarDinheiro = float(input('Digite o valor que deseja colocar:\n'))
    print(f'Você depositou R${depositarDinheiro}!')
    saldo += depositarDinheiro

  elif escolha == 4:
    print('Fim da operação!')
    break


from io import StringIO
import http
from unittest import TestCase

import pytest
import requests

from tests import stub_request
from directory_client_core.base import AbstractAPIClient
from directory_client_core import authentication, cache_control

class TestAPIClient(AbstractAPIClient):
    version = 1

class AbstractAPIClientTest(TestCase):

    def setUp(self):
        self.client = TestAPIClient(
            base_url='https://example.com/',
            api_key='test',
            sender_id='test-sender-id',
            timeout=2,
        )

    def test_request_signer(self):
        assert self.client.request_signer.secret == 'test'
        assert self.client.request_signer.sender_id == 'test-sender-id'

    @stub_request('https://example.com/test', 'post')
    def test_request(self, stub):
        self.client.request("POST", 'test', data='data')

    @stub_request('https://example.com/test', 'post')
    def test_post_encodes_json(self, stub):
        data = {'key': 'value'}
        self.client.post('test', data=data)
        request = stub.request_history[0]
        assert request.headers['Content-type'] == 'application/json'
        assert request.text == '{"key": "value"}'

    @stub_request('https://example.com/test', 'post')
    def test_post_no_payload(self, stub):
        self.client.post('test')
        request = stub.request_history[0]
        assert request.headers['Content-type'] == 'application/json'
        assert request.text == '{}'

    @stub_request('https://example.com/test', 'put')
    def test_put_encodes_json(self, stub):
        data = {'key': 'value'}
        self.client.put('test', data=data)
        request = stub.request_history[0]
        assert request.headers['Content-type'] == 'application/json'
        assert request.text == '{"key": "value"}'

    @stub_request('https://example.com/test', 'delete')
    def test_delete_encodes_json(self, stub):
        data = {'key': 'value'}
        self.client.delete('test', data=data)
        request = stub.request_history[0]
        assert request.headers['Content-type'] == 'application/x-www-form-urlencoded'
        assert request.text == 'key=value'

    @stub_request('https://example.com/test', 'patch')
    def test_patch_encodes_json_without_file(self, stub):
        data = {'key': 'value'}
        self.client.patch('test', data=data)
        request = stub.request_history[0]
        assert request.headers['Content-type'] == 'application/json'
        assert request.text == '{"key": "value"}'

    @stub_request('https://example.com/thing/', 'patch')
    def test_patch_encodes_form_with_file(self, stub):
        data = {'key': 'value'}
        files = {'logo': StringIO('hello')}
        self.client.patch(url='thing/', data=data, files=files)
        request = stub.request_history[0]
        header = request.headers['Content-type']
        assert header.startswith('multipart/form-data; boundary=')

    def test_sign_request(self):
        url = 'https://example.com'
        prepared_request = requests.Request(
            "POST", url, data='data'
        ).prepare()

        self.client.sign_request(prepared_request=prepared_request)

    @stub_request('https://example.com', 'post')
    def test_send_response_ok(self, stub):
        response = self.client.send(method="POST", url="https://example.com")

        assert response.request.timeout == 2
        assert response.status_code == http.client.OK

    @stub_request('https://example.com', 'post', http.client.BAD_REQUEST)
    def test_send_response_not_ok(self, stub):
        response = self.client.send(method="POST", url="https://example.com")
        assert response.status_code == http.client.BAD_REQUEST

    @stub_request('https://example.com/test', 'get')
    def test_authenticator(self, stub):
        self.client.request(
            "GET",
            'test',
            authenticator=authentication.BearerAuthenticator('123'),
        )

        request = stub.request_history[0]

        assert request.headers['Authorization'] == 'Bearer 123'

    @stub_request('https://example.com/test', 'get')
    def test_cache_control(self, stub):
        self.client.request(
            "GET", 'test', cache_control=cache_control.ETagCacheControl('123'),
        )

        request = stub.request_history[0]

        assert request.headers['If-None-Match'] == '123'

@pytest.mark.parametrize(
    'base_url,partial_url,expected_result',
    [
        (
            'http://test.com/1/',
            '/2/3/',
            'http://test.com/1/2/3/'
        ),
        (
            'http://test.com/1',
            '2/3/',
            'http://test.com/1/2/3/'
        ),
        (
            'http://test.com/1',
            '/2/3/',
            'http://test.com/1/2/3/'
        ),
        (
            'http://test.com/1/',
            '2/3/',
            'http://test.com/1/2/3/'
        )
    ]
)
def test_build_url(base_url, partial_url, expected_result):
    assert TestAPIClient.build_url(base_url, partial_url) == expected_result


import numpy as np

class Histogram:
    def __init__(
        self,
        center_of_first_speed_bin,
        number_of_speed_bins,
        speed_bin_width,
        number_of_direction_bins,
    ):
        self.center_of_first_speed_bin = center_of_first_speed_bin
        self.number_of_speed_bins = number_of_speed_bins
        self.speed_bin_width = speed_bin_width
        self.number_of_direction_bins = number_of_direction_bins

        self.speed_bins = self._create_wind_speed_bins()
        self.direction_bins = self._create_wind_direction_bins()

    def get_bin_for_state(self, state):
        return None

    def get_wind_speed_bin(self, wind_speed):
        wind_speed = float(wind_speed)
        for bin in self.speed_bins.keys():
            edges = self.speed_bins[bin]
            if (wind_speed > edges[0]) and  (wind_speed <= edges[1]):
                return bin

    def get_wind_direction_bin(self, wind_direction):
        if wind_direction >= 345:
            wind_direction = wind_direction - 360
        for bin in self.direction_bins.keys():
            edges = self.direction_bins[bin]
            if (wind_direction > edges[0]) and (wind_direction <= edges[1]):
                return bin

    def get_wind_speed_bins(self):
        return self.speed_bins

    def get_wind_direction_bins(self):
        return self.direction_bins

    def _create_wind_speed_bins(self):
        center_of_last_bin = (
            self.number_of_speed_bins * self.speed_bin_width
            - self.speed_bin_width
            + self.center_of_first_speed_bin
        )
        bin_centers = np.arange(
            start=self.center_of_first_speed_bin,
            stop=center_of_last_bin + self.speed_bin_width,
            step=self.speed_bin_width,
        )
        bins = {}
        for center in bin_centers:
            bins[center] = self._create_bin_interval(center, self.speed_bin_width)
        return bins

    def _create_wind_direction_bins(self):
        bin_width = 360.0 / self.number_of_direction_bins
        bin_centers = np.arange(0.0, 360.0, bin_width)
        bin_edges = np.arange(start=0.0 - bin_width / 2, stop=360.0, step=bin_width)
        bins = {}
        for bin_center in bin_centers:
            bins[bin_center] = self._create_bin_interval(bin_center, bin_width)
        return bins

    def _create_bin_interval(self, bin_center, bin_width):
        lower_bin_limit = bin_center - (bin_width / 2.0)
        upper_bin_limit = bin_center + (bin_width / 2.0)
        return [lower_bin_limit, upper_bin_limit]


#!/usr/bin/env python
"""
Open a sequence of spectra in the new BOSS spectra browser.
"""
#Initial Version: jkp 2010.10.01

from __future__ import print_function

import webbrowser

url='https://spectra.sdss3.org:8000/spectrumDetail?plateid=PLATE&mjd=MJD&fiber=FIBER&reduction2d=v5_4_14'

def open_spectra(data):
    browser = webbrowser.get()
    print('Plate Fiber MJD')
    for x in data:
        print(x['PLATE'],x['MJD'],x['FIBERID'])
        temp = url.replace('FIBER',str(x['FIBERID'])).replace('MJD',str(x['MJD'])).replace('PLATE',str(x['PLATE']))
        # if the browser is Safari, new=1 keeps things in the same window.
        browser.open(temp)
        raw_input('Press enter for next plot, or CTL-C to quit...')
#...


import torch
import torch.nn as nn
import argparse
from transformers import BertTokenizer, GPT2Config, AdamW, get_linear_schedule_with_warmup
from DataProcesser import *
from LSTM_Model import *
from Train import *
import os

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--mode', type=str, default='songci', help='选择数据集')
    parser.add_argument('--max_len', type=int, default=50, help='诗词的最大长度')
    parser.add_argument('--gpu', type=bool, default=True, help='是否使用GPU')
    parser.add_argument('--batch_size', type=int, default=64, help='mini batch')
    parser.add_argument('--weight_decay', type=float, default=0.005, help='L2 norm')
    parser.add_argument('--lr', type=float, default=2e-5, help='学习率')
    parser.add_argument('--warm_up_ratio', type=float, default=0.0, help='warm up')
    parser.add_argument('--epochs', type=int, default=20, help='epochs')
    parser.add_argument('--hidden_dim', type=int, default=768)
    parser.add_argument('--input_dim', type=int, default=768)
    parser.add_argument('--num_layers', type=int, default=1)
    parser.add_argument('--dropout', type=float, default=0.1)
    return parser.parse_args()

if __name__ == '__main__':
    args = get_args()
    args.device = "cuda:1" if torch.cuda.is_available() and args.gpu else "cpu"
    tokenizer = BertTokenizer(vocab_file="../ModelConfig/model_" + args.mode + "/vocab.txt", do_lower_case=False)
    tokenizer.add_tokens("[SPACE]", special_tokens=True)
    tokenizer.add_tokens("[KEYWORD]", special_tokens=True)
    tokenizer.add_tokens("[CONTENT]", special_tokens=True)
    model_config = GPT2Config.from_json_file("../ModelConfig/model_" + args.mode + "/config.json")
    args.vocab_size = len(tokenizer)
    train_path = '../dataset/' + args.mode + '/' + args.mode + '.csv'
    trainset = DataProcesser(tokenizer, model_config.n_ctx, train_path)
    train_loader = create_dataloader(trainset, args.batch_size)

    args.content_id = tokenizer.convert_tokens_to_ids("[CONTENT]")

    model = LSTM_Model(args)
    # model = nn.DataParallel(model)
    model.to(args.device)

    optimizer = AdamW(model.parameters(), lr=args.lr)

    total_steps = len(train_loader) * args.epochs

    scheduler = get_linear_schedule_with_warmup(
        optimizer,
        num_warmup_steps=args.warm_up_ratio * total_steps,
        num_training_steps=total_steps
    )

    Criterion = nn.CrossEntropyLoss(ignore_index=0, reduction="mean")
    train(args, model, optimizer, scheduler, Criterion, train_loader)
    # output_dir = "./ModelConfig/model_" + args.mode + "/"
    # # print('training finished')
    # # if not os.path.exists(output_dir + 'final_model'):
    # #     os.mkdir(output_dir + 'final_model')
    # # torch.save(model.state_dict(), output_dir + 'final_model/model')
    # model.load_state_dict(torch.load(output_dir + 'final_model/model'))


"""
Autor: GAÑAN, Tomas // CERIONI, Enrique
Ejercicio 2: Laberinto
"""

# Importacion de librerias/modulos

import numpy as np
import random

# Laberinto

OPEN = []
CLOSE = []

# Distancias entre los nodos

S = ["S","A",6]

A1 = ["A","B",8]
A2 = ["A","DEAD-END",2]

B1 = ["B","G",2]
B2 = ["B","C",1]

C1 = ["C","D",1]
C2 = ["C","DEAD-END",3]

D1 = ["D","F",1]
D2 = ["D","E",2]

E1 = ["E","DEAD-END",1]
E2 = ["E","H",9]

F1 = ["F","DEAD-END",1]
F2 = ["F","G",3]

G1 = ["G","H",1]

H1 = ["H","DEAD-END",2]
H2 = ["H","I",3]

I1 = ["I","FIN",1]
I2 = ["I","DEAD-END",1]
I3 = ["I","DEAD-END",3]

# Inicio del programa

print("\n<< INICIO DEL LABERINTO >>\n")

# --------------------------- PRIMERA OPCION POR S->A1->B2->C1->D1->F2->G1->H2->I1

CLOSE.append(S[1])
OPEN.append(S[2])

#print("Partimos desde el nodo",S[0],"hasta el nodo",S[1],"con una distancia de",S[2],", por lo tanto agregamos:",S[1],"a la lista CLOSE:",CLOSE)
#print("Expandimos el nodo:",S[1])

# Primera elección

if(A1[2] < A2[2] and A1[1] != 'DEAD-END'):
    CLOSE.append(A1[1])
    OPEN.append(A1[2])
elif(A1[2] > A2[2] and A2[1] == 'DEAD-END'):
    CLOSE.append(A1[1])
    OPEN.append(A1[2])
else:
    CLOSE.append(A2[1])
    OPEN.append(A2[2])

# Segunda elección

if(B1[2] > B2[2] and B1[1] != 'DEAD-END'):
    CLOSE.append(B1[1])
    OPEN.append(B1[2])
elif(B1[2] < B2[2] and B2[1] == 'DEAD-END'):
    CLOSE.append(B1[1])
    OPEN.append(B1[2])
else:
    CLOSE.append(B2[1])
    OPEN.append(B2[2])

# Tercera elección

if(C1[2] < C2[2] and C1[1] != 'DEAD-END'):
    CLOSE.append(C1[1])
    OPEN.append(C1[2])
elif(C1[2] > C2[2] and C2[1] == 'DEAD-END'):
    CLOSE.append(C1[1])
    OPEN.append(C1[2])
else:
    CLOSE.append(C2[1])
    OPEN.append(C2[2])

# Cuarta elección

if(D1[2] < D2[2] and D1[1] != 'DEAD-END'):
    CLOSE.append(D1[1])
    OPEN.append(D1[2])
elif(D1[2] > D2[2] and D2[1] == 'DEAD-END'):
    CLOSE.append(D1[1])
    OPEN.append(D1[2])
else:
    CLOSE.append(D2[1])
    OPEN.append(D2[2])

# Quinta elección

if(F1[2] < F2[2] and F1[1] != 'DEAD-END'):
    CLOSE.append(F1[1])
    OPEN.append(F1[2])
elif(F1[2] > F2[2] and F2[1] == 'DEAD-END'):
    CLOSE.append(F1[1])
    OPEN.append(F1[2])
else:
    CLOSE.append(F2[1])
    OPEN.append(F2[2])

# Sexta elección

CLOSE.append(G1[1]) # UNICA OPCIÓN
OPEN.append(G1[2])

# Septima elección

if(H1[2] < H2[2] and H1[1] != 'DEAD-END'):
    CLOSE.append(H1[1])
    OPEN.append(H1[2])
elif(H1[2] > H2[2] and H2[1] == 'DEAD-END'):
    CLOSE.append(H1[1])
    OPEN.append(H1[2])
else:
    CLOSE.append(H2[1])
    OPEN.append(H2[2])

# Octava elección

if(I1[1] == 'FIN'):
    CLOSE.append(I1[1])
    OPEN.append(I1[2])
elif(I2[1] == 'FIN'):
    CLOSE.append(I2[1])
    OPEN.append(I2[2])
else:
     CLOSE.append(I3[1])
     OPEN.append(I3[2])

# --------------------------- SEGUNDA OPCIÓN OPCION POR S->A1->B1->G1->H2->I1

OPEN2 = []
CLOSE2 = []

CLOSE2.append(S[1])
OPEN2.append(S[2])

# Primera elección

if(A1[2] < A2[2] and A1[1] != 'DEAD-END'):
    CLOSE2.append(A1[1])
    OPEN2.append(A1[2])
elif(A1[2] > A2[2] and A2[1] == 'DEAD-END'):
    CLOSE2.append(A1[1])
    OPEN2.append(A1[2])
else:
    CLOSE2.append(A2[1])
    OPEN2.append(A2[2])

# Segunda elección

if(B1[2] > B2[2] and B1[1] != 'DEAD-END'):
    CLOSE2.append(B1[1])
    OPEN2.append(B1[2])
elif(B1[2] < B2[2] and B2[1] == 'DEAD-END'):
    CLOSE2.append(B2[1])
    OPEN2.append(B2[2])
else:
    CLOSE2.append(B1[1])
    OPEN2.append(B1[2])

# Tercera elección

CLOSE2.append(G1[1]) # UNICA OPCIÓN
OPEN2.append(G1[2])

# Cuarta elección

if(H1[2] < H2[2] and H1[1] != 'DEAD-END'):
    CLOSE2.append(H1[1])
    OPEN2.append(H1[2])
elif(H1[2] > H2[2] and H2[1] == 'DEAD-END'):
    CLOSE2.append(H1[1])
    OPEN2.append(H1[2])
else:
    CLOSE2.append(H2[1])
    OPEN2.append(H2[2])

# Quinta elección

if(I1[1] == 'FIN'):
    CLOSE2.append(I1[1])
    OPEN2.append(I1[2])
elif(I2[1] == 'FIN'):
    CLOSE2.append(I2[1])
    OPEN2.append(I2[2])
else:
     CLOSE2.append(I3[1])
     OPEN2.append(I3[2])

# --------------------------- TERCERA OPCIÓN POR S->A1->B2->C1->D2->E2->H2->I1

OPEN3 = []
CLOSE3 = []

CLOSE3.append(S[1])
OPEN3.append(S[2])

if(A1[2] < A2[2] and A1[1] != 'DEAD-END'):
    CLOSE3.append(A1[1])
    OPEN3.append(A1[2])
elif(A1[2] > A2[2] and A2[1] == 'DEAD-END'):
    CLOSE3.append(A1[1])
    OPEN3.append(A1[2])
else:
    CLOSE3.append(A2[1])
    OPEN3.append(A2[2])

# Segunda elección

if(B1[2] < B2[2] and B1[1] != 'DEAD-END'):
    CLOSE3.append(B1[1])
    OPEN3.append(B1[2])
elif(B1[2] > B2[2] and B2[1] == 'DEAD-END'):
    CLOSE3.append(B2[1])
    OPEN3.append(B2[2])
else:
    CLOSE3.append(B2[1])
    OPEN3.append(B2[2])

# Tercera elección

if(C1[2] < C2[2] and C1[1] != 'DEAD-END'):
    CLOSE3.append(C1[1])
    OPEN3.append(C1[2])
elif(C1[2] > C2[2] and C2[1] == 'DEAD-END'):
    CLOSE3.append(C1[1])
    OPEN3.append(C1[2])
else:
    CLOSE3.append(C2[1])
    OPEN3.append(C2[2])

# Cuarta elección

if(D1[2] < D2[2] and D2[1] != 'DEAD-END'):
    CLOSE3.append(D2[1])
    OPEN3.append(D2[2])
elif(D1[2] > D2[2] and D1[1] == 'DEAD-END'):
    CLOSE3.append(D1[1])
    OPEN3.append(D1[2])
else:
    CLOSE3.append(D2[1])
    OPEN3.append(D2[2])

# Quinta elección

if(E1[2] < E2[2] and E1[1] != 'DEAD-END'):
    CLOSE3.append(E1[1])
    OPEN3.append(E1[2])
elif(E1[2] > E2[2] and E2[1] == 'DEAD-END'):
    CLOSE3.append(E1[1])
    OPEN3.append(E1[2])
else:
    CLOSE3.append(E2[1])
    OPEN3.append(E2[2])

# Sexta elección

if(H1[2] < H2[2] and H1[1] != 'DEAD-END'):
    CLOSE3.append(H1[1])
    OPEN3.append(H1[2])
elif(H1[2] > H2[2] and H2[1] == 'DEAD-END'):
    CLOSE3.append(H1[1])
    OPEN3.append(H1[2])
else:
    CLOSE3.append(H2[1])
    OPEN3.append(H2[2])

# Septima elección

if(I1[1] == 'FIN'):
    CLOSE3.append(I1[1])
    OPEN3.append(I1[2])
elif(I2[1] == 'FIN'):
    CLOSE3.append(I2[1])
    OPEN3.append(I2[2])
else:
     CLOSE3.append(I3[1])
     OPEN3.append(I3[2])

# --------------------------------------------------------- RESULTADOS

costo1 = 0
costo2 = 0
costo3 = 0

# PRIMER CAMINO
print("el camino tomado por el nodo F es el siguiente: ")
print(CLOSE)
print(OPEN)
print("\n")

for i in range(len(CLOSE)):
    costo1 = costo1 + OPEN[i]

# SEGUNDO CAMINO
print("el camino tomado por el nodo G es el siguiente: ")
print(CLOSE2)
print(OPEN2)
print("\n")

for i in range(len(CLOSE2)):
    costo2 = costo2 + OPEN2[i]

# TERCER CAMINO CAMINO
print("el camino tomado por el nodo E es el siguiente: ")
print(CLOSE3)
print(OPEN3)
print("\n")

for i in range(len(CLOSE3)):
    costo3 = costo3 + OPEN3[i]

# CALCULO DEL COSTO
if(costo1 < costo2 and costo1 < costo3):
    print("El camino de menor costo entre el origen",S[0],"y el destino",I1[0],"es por el nodo F con un costo de:",costo1)
    print("\n")
    for i in range(len(CLOSE)):
        n = len(CLOSE)
        num = (n-1) - i
        print("",CLOSE[num])
        print(" ^ ")
        print(" | ")
elif(costo2 < costo1 and costo2 < costo3):
    print("El camino de menor costo entre el origen",S[0],"y el destino",I1[0],"es por el nodo G con un costo de:",costo2)
    print("\n")
    for i in range(len(CLOSE2)):
        n = len(CLOSE2)
        num = (n-1) - i
        print("",CLOSE2[num])
        print(" ^ ")
        print(" | ")
else:
    print("El camino de menor costo entre el origen",S[0],"y el destino",I1[0],"es por el nodo E con un costo de:",costo3)
    print("\n")
    for i in range(len(CLOSE3)):
        n = len(CLOSE3)
        num = (n-1) - i
        print("",CLOSE3[num])
        print(" ^ ")
        print(" | ")


# -*- coding: utf-8 -*-
from datetime import datetime

from django.test import TestCase

from .testapp.models import (
    ModelModificationDateTimeField,
    CustomModelModificationDateTimeField,
    DisabledUpdateModelModificationDateTimeField,
)

class ModificationDatetimeFieldTest(TestCase):
    def test_update_model_with_modification_field(self):
        m = ModelModificationDateTimeField.objects.create()
        current_updated_time = m.modified
        m.field_to_update = False
        m.save()
        self.assertNotEqual(m.modified, current_updated_time)

    def test_custom_modification_field_name(self):
        m = CustomModelModificationDateTimeField.objects.create()
        current_updated_time = m.custom_modified
        m.field_to_update = False
        m.save()
        self.assertNotEqual(m.custom_modified, current_updated_time)

    def test_disabled_update_modification_field(self):
        m = DisabledUpdateModelModificationDateTimeField.objects.create(modified=datetime.now())
        current_updated_time = m.modified
        m.field_to_update = False
        m.save()
        self.assertEqual(m.modified, current_updated_time)


"""
TP 1 : Creation d'un logiciel de caisse
Auteur(s) : Nicolas SAPIN
"""

prix = 0
Quantite = 0
tabResult = {}
PrixTotHT = 0
PrixTotalTTC = 0
PrixTotalHT=0
PrixArtHt = 0
stop=0
i=0
#on demande a l'utilisateur de saisir un prix HT ainsi qu'une quantite

Valeur_saisi1 = input('Entrez un Prix : ')
Prix = float(Valeur_saisi1)
while Prix <= 0:
    print("Erreur de saisi: votre prix doit etre positif!!")
    Valeur_saisi1 = input('Entrez un Prix : ')
    Prix = float(Valeur_saisi1)

# Saisie de la Quantité
Valeur_saisi2 = input('Entrez une Quantité : ')
Quantite = float(Valeur_saisi2)
while Quantite <= 0:
    print("Erreur de saisi: votre Quantite doit etre positif!!")
    Valeur_saisi2 = input('Entrez une Quantité : ')
    Quantite = float(Valeur_saisi2)

#Ceci est la version 1 de la saisie Prix Quantite:
    #Valeur_saisi1 = input('Entrez un Prix : ')
    #Prix= float(Valeur_saisi1 )
    # if Prix <= 0:
    #     print("Erreur de saisi: votre prix doit etre positif")
    #     Valeur_saisi1 = input('Entrez un Prix : ')
    #     Prix = int(Valeur_saisi1)
    #Valeur_saisi2 = input('Entrez une Quantité : ')
    #Quantite=float(Valeur_saisi2 )
    # if Quantite <= 0:
    #     print("Erreur de saisi: votre Quantite doit etre positif")
    #     Valeur_saisi2 = input('Entrez une Quantité : ')
    #     Quantite = float(Valeur_saisi2)

# Calculer et afficher le prix total, sur la base d’une TVA de 20%
# TVA a 20%: multiplier le total par 1.20 revient a faire x*20/100

if Prix >0 or Quantite >0:
    Prix_TTC = (Prix * Quantite) * 1.20
    print("Votre prix HT est de:", Prix * Quantite)
    print("Votre prix TTC est de:", Prix_TTC)
    # Si le total dépasse les 200€, vous effectuerez une remise de 5%
    if (Prix_TTC >= 200):
        Prix_TTC = Prix_TTC * 0.95  # 0.95 signifie 5%
        print("Votre prix TTC  avec remise de 5 % est de:", Prix_TTC)

# Vous prendrez soin de vérifier les saisies utilisateurs : un prix et une quantité ne peuvent pas être nul ou négatif.


# -*-coding:utf-8 -*
"""
test jsonrpc
"""

import json

import requests

### import ujson as json

def main():

    data = {
        "jsonrpc": "2.0",
        "method": "lua_part_get3",
        "params": {
            "values": [1, 2, 3]
        },
        "id": "21",
    }

    print(data)

    url = "http://127.0.0.1:8001/jsonrpc/call"

    r = requests.post(url, json=data)

    print(r.text)

if __name__ == "__main__":
    main()


"""
@author:      13716
@date-time:   2019/7/25-23:18
@ide:         PyCharm
@name:        file_manager.py
"""
import glob
from utils.base_utils import GetUuid
from model.models import Exams, TitleCompare
import xlrd, os, json

class FileManager(object):

    def __init__(self):
        all_list = []
        all_list += glob.glob("*.xlsx")
        all_list += glob.glob("*.xls")

    def add_files(self, content, exp, exam_name, author, raw_name, start_time, end_time, last, score):
        name = GetUuid.get_time_uuid()
        file_name = name + exp
        with open("files/{}".format(file_name), "wb") as f:
            f.write(content)

        work_book = xlrd.open_workbook(os.path.join(os.getcwd(), "files\\", file_name))
        sheet = work_book.sheet_by_index(0)
        rows = sheet.nrows
        exam_number = rows - 1
        cols = sheet.ncols
        if cols == 9:
            choose_list = []
            input_list = []
            judge_list = []
            subjective_list = []
            for i in range(1, rows):

                data_list = sheet.row_values(i)
                classify, no, title, a, b, c, d, correct, analyse = data_list
                if classify == 1:
                    question = {
                        "classify": 1,
                        "no": no,
                        "title": title,
                        "A": a,
                        "B": b,
                        "C": c,
                        "D": d,
                        "correct": correct,
                        "analyse": analyse
                    }
                    choose_list.append(question)
                elif classify == 2:
                    question = {
                        "classify": 2,
                        "no": no,
                        "title": title,
                        "correct": correct,
                        "analyse": analyse
                    }
                    input_list.append(question)
                elif classify == 3:
                    question = {
                        "classify": 3,
                        "no": no,
                        "title": title,
                        "correct": correct,
                        "analyse": analyse
                    }
                    judge_list.append(question)
                else:
                    question = {
                        "classify": 4,
                        "no": no,
                        "title": title,
                        "correct": correct,
                        "analyse": analyse
                    }
                    subjective_list.append(question)
            question_dict = {
                "choose_list": choose_list,
                "input_list": input_list,
                "judge_list": judge_list,
                "subjective_list": subjective_list
            }

            if Exams.add_exam(exam_name, author, raw_name, start_time, end_time, last, score, json.dumps(question_dict)):
                return True
            else:
                return False

        else:
            return False


# -*- coding: utf-8 -*-
"""
Created on Sun Aug 21 17:31:48 2022

@author: Master Zhang
"""

import shutil
import os
import requests
from bs4 import BeautifulSoup

# 将目录的文件复制到指定目录
def copy_demo(src_dir, dst_dir):
    """
    复制src_dir目录下的所有内容到dst_dir目录
    :param src_dir: 源文件目录
    :param dst_dir: 目标目录
    :return:
    """
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    if os.path.exists(src_dir):
        for file in os.listdir(src_dir):
            file_path = os.path.join(src_dir, file)
            dst_path = os.path.join(dst_dir, file)
            if os.path.isfile(os.path.join(src_dir, file)):
                shutil.copyfile(file_path, dst_path)
            else:
                copy_demo(file_path, dst_path)
                print("----------------存在多级文件夹，正在复制------------")

url = "https://blog.csdn.net/weixin_44791964/article/details/113682561"
kv = {'user-agent':'Mozilla/5.0'}	#浏览器身份标识
r = requests.get(url,headers=kv)
r.encoding = 'utf-8'
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
dd = soup.find_all('h2')
dd[0].text

#获取的 bug 的名字, 根据名字创建对应的文件夹
title_name = soup.title.text

print("提取到的bug的名字：" + title_name)

name = title_name

# 创建新的文件夹的基地目录
path = 'D:/source/'

# 获得创建新的文件夹所需要的名字
dst_path =os.path.join(path,name)

print("新建文件夹的名字是：""【",dst_path,"】")

if (os.path.exists(dst_path) == True):
    print("-----------------该文件夹已经存在-----------------")
else:
    os.mkdir(dst_path)
    print("------------------文件夹创建成功------------------")

#获取的资料所在的路径，并去复制粘贴
dd[3] = 'D:/source/ap'

src_path = dd[3]
copy_demo(src_path,dst_path)
print("--------------------所有文件复制完毕------------------")

####以下  是  重命名文件夹
# =============================================================================
# newname = "testtest"
# path = 'D:/source/'
# new_name = path + newname
# if (os.path.exists(dst_path) == True):
#     os.rename(dst_path,new_name)
#     print("文件夹重命名成功。")
# else:
#     print("该文件夹不存在了！")
# =============================================================================

# for i in range(len(dd)):
#     print(dd[i].text)

# dd = soup.text.strip('')


import face_recognition
import imutils
import pickle
import time
import cv2
from scipy.spatial import distance as dist
import numpy as np

import dlib

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
def eye_aspect_ratio(eye):
    # compute the euclidean distances between the two sets of
    # vertical eye landmarks (x, y)-coordinates
    A = dist.euclidean(eye[1], eye[5])
    B = dist.euclidean(eye[2], eye[4])
    # compute the euclidean distance between the horizontal
    # eye landmark (x, y)-coordinates
    C = dist.euclidean(eye[0], eye[3])
    # compute the eye aspect ratio
    ear = (A + B) / (2.0 * C)
    # return the eye aspect ratio
    return ear

def mouth_aspect_ratio(mouth):
    A=dist.euclidean(mouth[2],mouth[10])
    B=dist.euclidean(mouth[3],mouth[9])
    C=dist.euclidean(mouth[4],mouth[8])
    D=dist.euclidean(mouth[0],mouth[6])
    mar=(A+B+C)/(3*D)
    return mar

def lip_distance(shape):
    top_lip = shape[50:53]
    top_lip = np.concatenate((top_lip, shape[61:64]))

    low_lip = shape[56:59]
    low_lip = np.concatenate((low_lip, shape[65:68]))

    top_mean = np.mean(top_lip, axis=0)
    low_mean = np.mean(low_lip, axis=0)

    distance = abs(top_mean[1] - low_mean[1])
    return distance

def glass_detection(img1,present,absent):

    #ref,img1=imcap.read()
    #clone=img.copy()
    #img1 = imcap.capture() # capture frame from video
    cv2.imwrite('temp.jpeg', img1)
    img = dlib.load_rgb_image('temp.jpeg')
    #plt.imshow(img)
    if len(detector(img))>0:
        rect = detector(img)[0]
        sp = predictor(img, rect)
        landmarks = np.array([[p.x, p.y] for p in sp.parts()])

        nose_bridge_x = []
        nose_bridge_y = []

        for i in [20,28,29,30,31,33,34,35]:
            nose_bridge_x.append(landmarks[i][0])
            nose_bridge_y.append(landmarks[i][1])

        ### x_min and x_max
        x_min = min(nose_bridge_x)
        x_max = max(nose_bridge_x)

        ### ymin (from top eyebrow coordinate),  ymax
        y_min = landmarks[20][1]
        y_max = landmarks[30][1]

        #img2=clone[x_min:x_max, y_min:y_max]
        img2 = Image.open('temp.jpeg')
        img2 = img2.crop((x_min,y_min,x_max,y_max))
        #plt.imshow(img2)

        img_blur = cv2.GaussianBlur(np.array(img2),(3,3), sigmaX=0, sigmaY=0)

        edges = cv2.Canny(image =img_blur, threshold1=100, threshold2=200)
        #plt.imshow(edges, cmap =plt.get_cmap('gray'))

        edges_center = edges.T[(int(len(edges.T)/2))]

        if 255 in edges_center:
            present=present+1
            print("Glasses are present")
        else:
                print("Glasses are absent")
                absent=absent+1
        return present,absent
def recog(img,currentname,encodingsP,data ):
    global EYE_AR_THRESH
    global MOUTH_AR_THRESH
    global LIP_DIST_THRESH
    person=0
    #gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    boxes = face_recognition.face_locations(img)
    # compute the facial embeddings for each face bounding box
    encodings = face_recognition.face_encodings(img, boxes)
    names = []
    for encoding in encodings:
        # attempt to match each face in the input image to our known
        # encodings
        matches = face_recognition.compare_faces(data["encodings"],
            encoding)
        name = "Unknown" #if face is not recognized, then print Unknown

        # check to see if we have found a match
        if True in matches:
            # find the indexes of all matched faces then initialize a
            # dictionary to count the total number of times each face
            # was matched
            matchedIdxs = [i for (i, b) in enumerate(matches) if b]
            counts = {}

            # loop over the matched indexes and maintain a count for
            # each recognized face face
            for i in matchedIdxs:
                name = data["names"][i]
                counts[name] = counts.get(name, 0) + 1

            # determine the recognized face with the largest number
            # of votes (note: in the event of an unlikely tie Python
            # will select first entry in the dictionary)
            name = max(counts, key=counts.get)

            #If someone in your dataset is identified, print their name on the screen
            if currentname != name:
                currentname = name
                print(currentname)
                if currentname=="pragi":
                    person=1
                    EYE_AR_THRESH=0.2
                    LIP_DIST_THRESH=50
                    MOUTH_AR_THRESH=0.8
            else:
                EYE_AR_THRESH = 0.2
                #EYE_AR_CONSEC_FRAMES = 15
                #MOUTH_AR_CONSEC_FRAMES = 10
                MOUTH_AR_THRESH=0.8
                LIP_DIST_THRESH=25

    return person


from flask import *
from flask_user import *
from app import app
from app.models import *

from app.utils import *

from flask_wtf import FlaskForm
from wtforms import *
from wtforms.validators import *
from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField

from . import PackageForm

class EditRequestForm(PackageForm):
	edit_title = StringField("Edit Title", [InputRequired(), Length(1, 100)])
	edit_desc  = TextField("Edit Description", [Optional()])

@app.route("/packages/<author>/<name>/requests/new/", methods=["GET","POST"])
@app.route("/packages/<author>/<name>/requests/<id>/edit/", methods=["GET","POST"])
@login_required
@is_package_page
def create_edit_editrequest_page(package, id=None):
	edited_package = package

	erequest = None
	if id is not None:
		erequest = EditRequest.query.get(id)
		if erequest.package != package:
			abort(404)

		if not erequest.checkPerm(current_user, Permission.EDIT_EDITREQUEST):
			abort(403)

		if erequest.status != 0:
			flash("Can't edit EditRequest, it has already been merged or rejected", "error")
			return redirect(erequest.getURL())

		edited_package = Package(package)
		erequest.applyAll(edited_package)

	form = EditRequestForm(request.form, obj=edited_package)
	if request.method == "GET":
		deps = edited_package.dependencies
		form.harddep_str.data  = ",".join([str(x) for x in deps if not x.optional])
		form.softdep_str.data  = ",".join([str(x) for x in deps if     x.optional])
		form.provides_str.data = MetaPackage.ListToSpec(edited_package.provides)

	if request.method == "POST" and form.validate():
		if erequest is None:
			erequest = EditRequest()
			erequest.package = package
			erequest.author  = current_user

		erequest.title   = form["edit_title"].data
		erequest.desc    = form["edit_desc"].data
		db.session.add(erequest)

		EditRequestChange.query.filter_by(request=erequest).delete()

		wasChangeMade = False
		for e in PackagePropertyKey:
			newValue = form[e.name].data
			oldValue = getattr(package, e.name)

			newValueComp = newValue
			oldValueComp = oldValue
			if type(newValue) is str:
				newValue = newValue.replace("\r\n", "\n")
				newValueComp = newValue.strip()
				oldValueComp = "" if oldValue is None else oldValue.strip()

			if newValueComp != oldValueComp:
				change = EditRequestChange()
				change.request = erequest
				change.key = e
				change.oldValue = e.convert(oldValue)
				change.newValue = e.convert(newValue)
				db.session.add(change)
				wasChangeMade = True

		if wasChangeMade:
			msg = "{}: Edit request #{} {}" \
					.format(package.title, erequest.id, "created" if id is None else "edited")
			triggerNotif(package.author, current_user, msg, erequest.getURL())
			triggerNotif(erequest.author, current_user, msg, erequest.getURL())
			db.session.commit()
			return redirect(erequest.getURL())
		else:
			flash("No changes detected", "warning")
	elif erequest is not None:
		form["edit_title"].data = erequest.title
		form["edit_desc"].data  = erequest.desc

	return render_template("packages/editrequest_create_edit.html", package=package, form=form)

@app.route("/packages/<author>/<name>/requests/<id>/")
@is_package_page
def view_editrequest_page(package, id):
	erequest = EditRequest.query.get(id)
	if erequest is None or erequest.package != package:
		abort(404)

	clearNotifications(erequest.getURL())
	return render_template("packages/editrequest_view.html", package=package, request=erequest)

@app.route("/packages/<author>/<name>/requests/<id>/approve/", methods=["POST"])
@is_package_page
def approve_editrequest_page(package, id):
	if not package.checkPerm(current_user, Permission.APPROVE_CHANGES):
		flash("You don't have permission to do that.", "error")
		return redirect(package.getDetailsURL())

	erequest = EditRequest.query.get(id)
	if erequest is None or erequest.package != package:
		abort(404)

	if erequest.status != 0:
		flash("Edit request has already been resolved", "error")

	else:
		erequest.status = 1
		erequest.applyAll(package)

		msg = "{}: Edit request #{} merged".format(package.title, erequest.id)
		triggerNotif(erequest.author, current_user, msg, erequest.getURL())
		triggerNotif(package.author, current_user, msg, erequest.getURL())
		db.session.commit()

	return redirect(package.getDetailsURL())

@app.route("/packages/<author>/<name>/requests/<id>/reject/", methods=["POST"])
@is_package_page
def reject_editrequest_page(package, id):
	if not package.checkPerm(current_user, Permission.APPROVE_CHANGES):
		flash("You don't have permission to do that.", "error")
		return redirect(package.getDetailsURL())

	erequest = EditRequest.query.get(id)
	if erequest is None or erequest.package != package:
		abort(404)

	if erequest.status != 0:
		flash("Edit request has already been resolved", "error")

	else:
		erequest.status = 2

		msg = "{}: Edit request #{} rejected".format(package.title, erequest.id)
		triggerNotif(erequest.author, current_user, msg, erequest.getURL())
		triggerNotif(package.author, current_user, msg, erequest.getURL())
		db.session.commit()

	return redirect(package.getDetailsURL())


N = int(input())
An = sorted(list(map(int,input().split())),reverse=True)
M = int(input())
Bm = list(map(int,input().split()))
X = int(input())

An = list(filter(lambda a: a <= X, An))

stack = list()
visited = [0] * (X+1)

for n in Bm:
    visited[n] = 1

for a in An:
    if visited[a] == 0:
        stack.append(a)
        visited[a] = 1

while len(stack) != 0:
    s = stack.pop()

    for a in An:
        ns = s+a
        if ns <= X and visited[ns] == 0:
            stack.append(ns)
            visited[ns] = 1
            if ns == X:
                print('Yes')
                exit()

print('No')


import re
from pprint import pprint
import csv

with open("phonebook_raw.csv", encoding='utf8') as f:
  rows = csv.reader(f, delimiter=",")
  contacts_list = list(rows)
# pprint(contacts_list)

phone_pattern = r'(8|\+7)[\s\(]*(\d{3})[\-\)\s]*(\d{3})[\-]*(\d{2})[\-]*(\d{2})[\s\(]*(доб\.)*[\s]*(\d+)*[\)]*'
phone_sub = r'+7(\2)\3-\4-\5 \6\7'

new_contacts_list = list()
for i in contacts_list:
    full_name = ' '.join(i[:3]).split(' ')
    result = [full_name[0], full_name[1], full_name[2], i[3], i[4], re.sub(phone_pattern, phone_sub, i[5]), i[6]]
    new_contacts_list.append(result)

new_contacts_list2 = list()
for contacts in new_contacts_list:
   for i in new_contacts_list:
      if contacts[0] == i[0] and contacts[1] == i[1]:
        if contacts[2] == '':
           contacts[2] = i[2]
        if contacts[3] == '':
           contacts[3] = i[3]
        if contacts[4] == '':
           contacts[4] = i[4]
        if contacts[5] == '':
           contacts[5] = i[5]
        if contacts[6] == '':
           contacts[6] = i[6]

for people in new_contacts_list:
   if people not in new_contacts_list2:
      new_contacts_list2.append(people)

with open("phonebook.csv", "w", encoding='utf8' ) as f:
  datawriter = csv.writer(f, delimiter=',')
  datawriter.writerows(new_contacts_list2)


# Задача №39. Решение в группах Даны два массива чисел. Требуется вывести те элементы первого массива (в том порядке, в каком они идут в первом массиве), которых нет во втором массиве. Пользователь вводит  число N - количество элементов в первом массиве, затем N чисел - элементы массива. Затем число M - количество элементов во втором массиве. Затем элементы второго массива

# Ввод: 7
# 3 3 2 12 3 1 3 4 2 4 12
# 6
# 4 15 43 1 15 1

# Вывод: 7 3 3 2 12

# (каждое число вводится с новой строки)

# Вариант 1:

# n = int(input("Введите количество элементов массива arr_n: "))
# arr_first=[]
# arr_second=[]
# arr_n=[]
# for i in range(n):
#     arr_n.append(int(input("Введите значение элементов массива: ")))
# m = int(input("Введите количество элемнетов массива arr_m: "))
# arr_m = []
# for i in range(m):
#     arr_m.append(int(input("Введите значения элементов массива: ")))
# for i in arr_n:
#     if i not in arr_m:
#         arr_first.append(i)
# print(arr_first)
# for i in arr_m:
#     if i not in arr_n:
#         arr_second.append(i)
# print(arr_second)

# Вариант через функции:

import random

def filter_list(array1, array2):
    res_array = []
    for i in array1:
        if i not in array2:
            res_array.append(i)
    return res_array

def create_random_list(number):
    return [random.randint(-10,10) for _ in range(number+1)]

number_1 = int(input("Введите количество элементов первого массива: "))
int_array_1 = create_random_list(number_1)
print(int_array_1)
number_2 = int(input("Введите количество элементов второго массива: "))
int_array_2 = create_random_list(number_2)
print(int_array_2)
print(filter_list(int_array_1, int_array_2))

# Решение в одну строку:

# def filter_list_2(array1, array2):
#     return [i for i in array1 if i in set(array1) - set(array2)]


"""
Demo of a basic pie chart plus a few additional features.

In addition to the basic pie chart, this demo shows a few optional features:

    * slice labels
    * auto-labeling the percentage
    * offsetting a slice with "explode"
    * drop-shadow
    * custom start angle

Note about the custom start angle:

The default ``startangle`` is 0, which would start the "Frogs" slice on the
positive x-axis. This example sets ``startangle = 90`` such that everything is
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
positive y-axis.
"""
import matplotlib.pyplot as plt

# The slices will be ordered and plotted counter-clockwise.
labels = 'Calculation Time', 'Non-Calculation (Data Transfer) Time'
all_sizes = {
    'cpu-001': (19.17495022, 11.15104978),
    'alpha': (27.79285035, 8.755149649),
    'nsls-ii': (22.90918903, 23.21681097),
}
colors = ['yellowgreen', 'gold']

for k in sorted(all_sizes.keys()):
    plt.pie(all_sizes[k], labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    plt.title('cpu-001 server, NSLS-II FMX beamline, sampling factor = 0.7')
    plt.show()


import os
import numpy as np
from PIL import Image
import requests
from io import BytesIO

import configs

def verify_image(image_content):
    image = Image.open(BytesIO(image_content))

    if image.mode != 'RGB':
        raise Exception('Image mode is %s.' % image.mode)

    if np.prod(image.size) < configs.RetrieveConfig.MIN_IMAGE_SIZE:
        raise Exception('Image is too small.')

    image.verify()

def download_image_content(url):
    content = requests.get(url, timeout=configs.RetrieveConfig.IMAGE_DOWNLOAD_TIMEOUT).content

    return content

def download_image(url):
    content = download_image_content(url)

    verify_image(content)

    image = Image.open(BytesIO(content))

    return image

def download_and_save_image(url, save_path, file_name=None):
    # Send a GET request to the URL
    response = requests.get(url, timeout=configs.RetrieveConfig.IMAGE_DOWNLOAD_TIMEOUT)

    # Get the content type of the response
    content_type = response.headers['Content-Type']

    # Get the file extension from the content type
    if content_type == 'image/jpeg':
        extension = 'jpg'
    elif content_type == 'image/png':
        extension = 'png'
    else:
        raise ValueError(f'Unsupported content type: {content_type}')

    # Get the file name from the URL
    if file_name is None:
        file_name = os.path.basename(url)

    # Construct the full file path with extension
    file_path = os.path.join(save_path, file_name + '.' + extension)

    # Write the response content to the file
    with open(file_path, 'wb') as f:
        f.write(response.content)


from rdflib import Namespace, Graph, URIRef

from expander.shared.vo.Condition import Condition
from expander.shared.vo.Container import Container
from expander.shared.vo.Content import Content
from expander.shared.vo.DataComponent import DataComponent
from expander.shared.vo.DataComponentWrapper import DataComponentWrapper
from expander.shared.vo.Date import Date
from expander.shared.vo.DateTime import DateTime
from expander.shared.vo.Email import Email
from expander.shared.vo.Emphasis import Emphasis
from expander.shared.vo.Heading import Heading
from expander.shared.vo.IterativeContainer import IterativeContainer
from expander.shared.vo.Strong import Strong
from expander.shared.vo.Time import Time
from expander.shared.vo.Url import Url

VO = Namespace('http://purl.org/datenzee/view-ontology#')
RDF = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')

NODE_TYPES = (
    VO.Condition,
    VO.Container,
    VO.Emphasis,
    VO.Heading,
    VO.IterativeContainer,
    VO.Strong,
)

LEAF_TYPES = (
    VO.DataComponentWrapper,
    VO.Content,
    VO.Date,
    VO.DateTime,
    VO.Email,
    VO.Time,
    VO.URL
)

class Loader:
    def __init__(self, root_component, source=None, data=None):
        self.root_component = URIRef(root_component)
        self.root_component_name = root_component.split('#')[-1]
        self.source = source
        self.data = data
        self.graph = None
        self.data_components = []
        self.components = []

    def load(self):
        g = Graph()
        try:
            g.parse(source=self.source, data=self.data, format='turtle')
            self.graph = g
            self._load()
        except FileNotFoundError:
            pass

    def _load(self):
        self._create_data_component(self.root_component)

    def _create_data_component(self, data_component):
        component_name = data_component.split('#')[-1]
        component_types = list(self.graph.objects(data_component, RDF.type))

        if VO.DataComponent not in component_types:
            raise Exception(f'The root component {component_name} is not a Data Component')

        if self._data_component_exists(component_name):
            return

        data_component_content = next(self.graph.objects(data_component, VO.dataComponentContent))
        content_component = self._create_component(data_component_content)

        self.data_components.append(DataComponent(component_name, content_component))

    def _create_component(self, component):
        component_name = component.split('#')[-1]
        component_types = list(self.graph.objects(component, RDF.type))

        if self._is_node(component_types):
            return self._create_node(component_name, component_types, component)
        elif self._is_leaf(component_types):
            return self._create_leaf(component_name, component_types, component)
        else:
            raise Exception(f'Component {component_name} is neither Node nor Leaf')

    def _is_node(self, component_types):
        return any(type in NODE_TYPES for type in component_types)

    def _is_leaf(self, component_types):
        return any(type in LEAF_TYPES for type in component_types)

    def _create_leaf(self, component_name, component_types, component):
        order = next(self.graph.objects(component, VO.order))

        if VO.DataComponentWrapper in component_types:
            predicate = next(self.graph.objects(component, VO.dataComponentPredicate))
            data_component = next(self.graph.objects(component, VO.dataComponent))
            self._create_data_component(data_component)

            wrapper = DataComponentWrapper(component_name, order, predicate, data_component)
            self.components.append(wrapper)
            return wrapper
        else:
            predicate = self._load_content_component_predicate(component)
            content = self._load_content_component_content(component)

            if VO.Date in component_types:
                date = Date(component_name, order, predicate, content)
                self.components.append(date)
                return date

            elif VO.DateTime in component_types:
                date_time = DateTime(component_name, order, predicate, content)
                self.components.append(date_time)
                return date_time

            elif VO.Email in component_types:
                email = Email(component_name, order, predicate, content)
                self.components.append(email)
                return email

            elif VO.Time in component_types:
                time = Time(component_name, order, predicate, content)
                self.components.append(time)
                return time

            elif VO.URL in component_types:
                url = Url(component_name, order, predicate, content)
                self.components.append(url)
                return url

            elif VO.Content in component_types:
                c = Content(component_name, order, predicate, content)
                self.components.append(c)
                return c

            else:
                raise Exception('Unknown leaf type')

    def _create_node(self, component_name, component_types, component):
        order = next(self.graph.objects(component, VO.order))
        is_block = next(self.graph.objects(component, VO.isBlock))

        def create_children(predicate=VO.contains):
            children = []
            for child in self.graph.objects(component, predicate):
                children.append(self._create_component(child))
            return sorted(children, key=lambda c: c.order)

        if VO.Condition in component_types:
            condition_predicate = next(self.graph.objects(component, VO.conditionPredicate))
            condition_value = next(self.graph.objects(component, VO.conditionValue))
            contains_positive = create_children(VO.conditionContainsPositive)
            contains_negative = create_children(VO.conditionContainsNegative)

            container = Condition(component_name, order, is_block, condition_predicate, condition_value,
                                  contains_positive, contains_negative)
            self.components.append(container)
            return container

        elif VO.Container in component_types:
            container = Container(component_name, order, is_block, create_children())
            self.components.append(container)
            return container

        elif VO.Emphasis in component_types:
            emphasis = Emphasis(component_name, order, is_block, create_children())
            self.components.append(emphasis)
            return emphasis

        elif VO.Heading in component_types:
            heading = Heading(component_name, order, is_block, create_children())
            self.components.append(heading)
            return heading

        elif VO.IterativeContainer in component_types:
            iterative_container_predicate = next(self.graph.objects(component, VO.iterativeContainerPredicate))
            iterative_container = IterativeContainer(component_name, order, is_block, create_children(),
                                                     iterative_container_predicate)
            self.components.append(iterative_container)
            return iterative_container

        elif VO.Strong in component_types:
            strong = Strong(component_name, order, is_block, create_children())
            self.components.append(strong)
            return strong

        else:
            raise Exception('Unknown node type')

    def _load_content_component_predicate(self, component):
        for predicate in self.graph.objects(component, VO.contentPredicate):
            return predicate
        return None

    def _load_content_component_content(self, component):
        for text_content in self.graph.objects(component, VO.contentContent):
            return next(self.graph.objects(text_content, VO.textContentValue))
        return None

    def _data_component_exists(self, component_name):
        for data_component in self.data_components:
            if data_component.name == component_name:
                return True
        return False