import sys
import time
import os

from numpy.lib.type_check import imag
import carla
import glob
import random
import numpy as np
import cv2
import PIL
from PIL import Image, ImageFile
import matplotlib.pyplot as plt

try:
    sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
        sys.version_info.major,
        sys.version_info.minor,
        'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
    pass

def main():
    actor_list = []
    IMG_HEIGHT = 720
    IMG_WIDTH = 1280
    def process_img(image, l_images):
         i = np.array(image.raw_data, dtype=np.uint8)
         i2 = i.reshape((IMG_HEIGHT, IMG_WIDTH, 4)) #rgba, a for alpha (opacity)
         i3 = i2[:, :, :3] # /255.0 # entire height, entire width, only rgb (no alpha)
         print(i3.shape)
         l_images.append(i3)
         img = Image.fromarray(i3, "RGB")
         img.show()

         return i3/255.0 # normalize the data

    #     #import pdb; pdb.set_trace()
    #     #cv2.imshow("image", i3)
    #     #cv2.waitKey(0)

     # normalize the data
    # # def process(image):
    # #     i = np.array(image.raw_data)
    # #     i2 = i.reshape((IMG_HEIGHT, IMG_WIDTH, 4))
    # #     i3 = i2[:,:, :3]
    # #     cv2.imshow("", i3)
    #     cv2.waitKey(0)
    #     return i3 / 255.0

    try:
        client = carla.Client("localhost", 2000)
        client.set_timeout(2.0)
        world = client.load_world('Town03')
        world = client.get_world()
        blueprint_library = world.get_blueprint_library()

        bp = blueprint_library.find("vehicle.ford.mustang")

        #Transform = carla.Transform()

        #transform = Transform(Location(x=230, y=195, z=40), Rotation(yaw=180))

        #transform = random.choice(world.get_map().get_spawn_points())
        transform = world.get_map().get_spawn_points()

        vehicle = world.spawn_actor(bp, transform[1])

        actor_list.append(vehicle)
        print('created %s' % vehicle.type_id)
        print(client.get_available_maps())

        vehicle.set_autopilot(False)

        camera_bp = blueprint_library.find("sensor.camera.rgb")
        camera_bp.set_attribute("image_size_x", str(IMG_WIDTH))
        camera_bp.set_attribute("image_size_y", str(IMG_HEIGHT))
        camera_bp.set_attribute("fov", str(90))
        #camera_bp.set_attribute("sensor_tick", str(1.0))
        camera_transform = carla.Transform(carla.Location(x=1.5, z=2.4))
        camera = world.spawn_actor(camera_bp, camera_transform, attach_to=vehicle)
        actor_list.append(camera)
        print('created %s' % camera.type_id)

        #cc = carla.ColorConverter.Raw

        #camera.listen(lambda image: image.save_to_disk('_out/%06d.png' % image.frame,))
        l_images = []
        camera.listen(lambda image: process_img(image, l_images))

        vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0.0))

        time.sleep(10)

    finally:

        print('destroying actors')
        camera.destroy()
        client.apply_batch([carla.command.DestroyActor(x) for x in actor_list])
        print('done.')

main()


from skimage.segmentation import felzenszwalb as fz, mark_boundaries
from skimage.feature import canny
from skimage.filters import sobel, difference_of_gaussians, gaussian
from skimage.future.graph import merge_hierarchical, rag_boundary, show_rag
from skimage import color
import numpy as np
import matplotlib.pyplot as plt

def segmentOriginal(original,segmented):
    segmented = np.reshape(segmented, (-1))
    labels_unique = np.unique(segmented)
    n_clusters = len(labels_unique)  # number of clusters
    print(n_clusters)
    # ----- plot the results -----
    sections = [] # contains arrays of each section and index values for each
    for i in labels_unique:
        section = np.squeeze(np.array(np.where(segmented==i)))
        sections.append(section)

    for cluster in labels_unique:
        bar = np.reshape(original.copy(), (-1, 3)) # copy the unchanged original
        for i in np.array(sections[cluster]):
            bar[i] = [255,255,255] # bar is in same shape of foo
        im2 = np.reshape(bar,original.shape)
        plt.imshow(im2)
        plt.show()
def weight_boundary(graph, src, dst, n):
    """
    Handle merging of nodes of a region boundary region adjacency graph.

    This function computes the `"weight"` and the count `"count"`
    attributes of the edge between `n` and the node formed after
    merging `src` and `dst`.

    Parameters
    ----------
    graph : RAG
        The graph under consideration.
    src, dst : int
        The vertices in `graph` to be merged.
    n : int
        A neighbor of `src` or `dst` or both.

    Returns
    -------
    data : dict
        A dictionary with the "weight" and "count" attributes to be
        assigned for the merged node.

    """
    default = {'weight': 0.0, 'count': 0}

    count_src = graph[src].get(n, default)['count']
    count_dst = graph[dst].get(n, default)['count']

    weight_src = graph[src].get(n, default)['weight']
    weight_dst = graph[dst].get(n, default)['weight']

    count = count_src + count_dst
    return {
        'count': count,
        'weight': (count_src * weight_src + count_dst * weight_dst)/count
    }
def merge_boundary(graph, src, dst):
    """Call back called before merging 2 nodes.

    In this case we don't need to do any computation here.
    """
    pass

if __name__ == "__main__":
    # ----- Settings -----
    sobelEdge = True
    blur = False # only applies to sobel
    cannyEdge = False
    diffGaussEdge = False # 697

    # Input Images
    images = ["0073MR0003970000103657E01_DRCL.tif", "0174ML0009370000105185E01_DRCL.tif",
              "0617ML0026350000301836E01_DRCL.tif", "1059ML0046560000306154E01_DRCL.tif",
              "chapstick.jpg"]
    image = plt.imread(images[4])  # File data in numpy each x,y contains array of [R,G,B]
    im = np.array(image)/255

    # oversegmentation
    scale, sigma, ms = 10, 2, 100

    # Felzenszwalb Algorithm (returns MxN array of segment labels)
    segment_im = fz(im,scale = scale, sigma=sigma,min_size=ms) # Takes in image, scale (higher means more clusters), sigma (width of gaussian), min_size (minimum component size), multichannel (default True), channel_axis (which axis of array is channels)

    # FZ image
    FelzColor = color.label2rgb(segment_im, im, kind='avg', bg_label=None)
    FelzColor = mark_boundaries(FelzColor, segment_im, (0, 0, 0))
    plt.imshow(FelzColor)
    plt.title("Segmented Image Using Felzenszwalb:")
    plt.show()

    # Construct Edge Map
    if sobelEdge:
        if blur:
            edges = sobel(color.rgb2gray(gaussian(im, sigma = 5)))
        else:
            edges = sobel(color.rgb2gray(im))

    elif cannyEdge:
        edges = canny(color.rgb2gray(im), sigma = 3, low_threshold=0.94,high_threshold=0.995, use_quantiles=True)
        edges = np.asarray(edges, dtype=np.float32)

    elif diffGaussEdge:
        edges = difference_of_gaussians(color.rgb2gray(im), 5, 9)

    else:
        print("You Choose at Least One Edge")
        quit()

    # show edge graph
    plt.imshow(edges)
    plt.title("Edges Image")
    plt.show()

    # Create the boundary RAG
    rag = rag_boundary(segment_im, edges)
    show_rag(segment_im,rag,im)
    plt.title("Initial RAG")
    plt.show()

    # Hierarchical Merging
    labels = merge_hierarchical(segment_im,rag,
                               thresh=0.1,
                               rag_copy=False,
                               in_place_merge=True,
                               merge_func=merge_boundary,
                               weight_func=weight_boundary)

    show_rag(segment_im, rag, im)
    plt.title("RAG after Hierarchical Merge")
    plt.show()

    merge = color.label2rgb(labels, im, kind='avg', bg_label=None)
    #merge = mark_boundaries(merge,labels,(0,0,0))

    # show the merged colored graph
    plt.imshow(merge)
    plt.title("Merged RAG using Hierarchical Segmentation:")
    plt.show()
    segment_im = labels

    # Takes in the original image, and the labelled segmented image
    segmentOriginal(im,segment_im)


from typing import Any, Tuple

import numpy as np

def fill_gamut(img, dtype=None):
    """Scale image values to fill datatype range

    Sets the lowest value to 0 and the highest to whatever is the highest that
    `dtype` allows, or 1. if dtype is a floating point type.

    Parameters
    ----------
    img : array-like
        Image data
    dtype : numpy.dtype or None, optional
        dtype of the output array. Image will be scaled to fill the value range
        of the type. E.g. if ``dtype=numpy.uint8``, the resulting image will
        take values between 0 and 255. If `None`, use ``img.dtype``. Defaults
        to `None`.

    Returns
    -------
    numpy.ndarray
        Scaled image with `dtype` as data type.
    """
    if dtype is None:
        dtype = img.dtype

    scaled = img - img.min()
    scaled = scaled / scaled.max()

    if np.issubdtype(dtype, np.integer):
        scaled *= np.iinfo(dtype).max

    return scaled.astype(dtype)

def center(obj: np.ndarray, shape: Tuple[int, ...], fill_value: Any = 0
           ) -> np.ndarray:
    """Center an image in an array of different size

    If the new shape is larger, the image will be padded, otherwise it will be
    cropped.

    Parameters
    ----------
    obj
        Image array
    shape
        Output shape
    fill_value
        Value to use for padding

    Returns
    -------
    New array with `obj` centered.
    """
    ret = np.full(shape, fill_value, dtype=obj.dtype)
    ret_slices = []
    obj_slices = []
    for n, o in zip(shape, obj.shape):
        e = min(n, o)
        ret_margin = (n - e) // 2
        ret_slices.append(slice(ret_margin, ret_margin + e))
        obj_margin = (o - e) // 2
        obj_slices.append(slice(obj_margin, obj_margin + e))

    ret[tuple(ret_slices)] = obj[tuple(obj_slices)]
    return ret


import math
from PIL import Image, ImageDraw

number = 50
maxImageHeight = 300
rotateFactor = 30

def GetObjectProperties(labels, areas, imagePath):
    global number
    global rotateFactor
    orientation = 0

    elements = []

    size = len(areas)

    for indexAreas in range(0, size, 1):
        area = GetObjectArea(labels, areas, indexAreas)
        if area < number:
            continue
        perimeter = GetObjectPerimeter(labels, areas, indexAreas)
        compactness = GetObjectCompactness(perimeter, area)

        CreateImage(labels, areas[indexAreas], indexAreas, "Source Images\\")

        xCenter, yCenter = GetObjectCenterOfMass(labels, areas[indexAreas], indexAreas)
        xCenter, yCenter, orientation = GetNeedCenterOfMass(xCenter, yCenter, areas[indexAreas])
        staticMoment11 = GetObjectStaticMoment(labels, areas[indexAreas], indexAreas, xCenter, yCenter, 1, 1, orientation)
        staticMoment20 = GetObjectStaticMoment(labels, areas[indexAreas], indexAreas, xCenter, yCenter, 2, 0, orientation)
        staticMoment02 = GetObjectStaticMoment(labels, areas[indexAreas], indexAreas, xCenter, yCenter, 0, 2, orientation)
        elongation = GetObjectElongation(staticMoment02, staticMoment20, staticMoment11)

        scalingFactor = GetScalingFactor(areas[indexAreas])

        scalingXCenter = scalingFactor * xCenter
        scalingYCenter = scalingFactor * yCenter

        WriteData(str(indexAreas) + ".txt", areas[indexAreas], area, perimeter, compactness, xCenter, yCenter,
                  staticMoment02, staticMoment11, staticMoment20, elongation, scalingXCenter, scalingYCenter)

        elements.append([indexAreas, scalingXCenter, scalingYCenter, compactness * 2, elongation])

    return elements

def GetObjectArea(labels, areas, indexAreas):
    area = 0

    for i in range(areas[indexAreas][0], areas[indexAreas][2] + 1, 1):
        for j in range(areas[indexAreas][1], areas[indexAreas][3] + 1, 1):
            if (labels[i][j] == indexAreas + 1):
                area += 1

    return area

def GetLabel(labels, i, j):
    try:
        return labels[i][j]
    except Exception as exc:
        return 0

def GetObjectPerimeter(labels, areas, indexAreas):
    perimeter = 0

    for i in range(areas[indexAreas][0], areas[indexAreas][2] + 1, 1):
        for j in range(areas[indexAreas][1], areas[indexAreas][3] + 1, 1):
            if labels[i][j] == indexAreas + 1:
                counter = GetLabel(labels, i - 1, j) + GetLabel(labels, i + 1, j) + GetLabel(labels, i,
                                                                                j - 1) + GetLabel(labels,
                                                                                i, j + 1)

                if counter != (indexAreas + 1) * 4:
                    perimeter += 1

    return perimeter

def GetObjectCompactness(perimeter, area):
    return perimeter ** 2 / area

def GetObjectCenterOfMass(labels, areas, indexAreas):
    xCounter = 0
    yCounter = 0
    counter = 0

    for i in range(areas[0], areas[2] + 1, 1):
        for j in range(areas[1], areas[3] + 1, 1):
            if labels[i][j] == indexAreas + 1:
                xCounter += i
                yCounter += j
                counter += 1

    return (xCounter / counter) - areas[0], (yCounter / counter) - areas[1]

def GetObjectStaticMoment(labels, areas, indexAreas, xCenter, yCenter, i, j, orientation):
    staticMoment = 0
    height = areas[2] - areas[0] + 1
    width = areas[3] - areas[1] + 1
    for x in range(areas[0], areas[2] + 1, 1):
        for y in range(areas[1], areas[3] + 1, 1):
            if labels[x][y] == indexAreas + 1:
                valueX = x - areas[0]
                valueY = y - areas[1]
                if orientation == 0:
                    staticMoment += ((valueX - xCenter) ** i) * ((valueY - yCenter) ** j)
                elif orientation == 1:
                    staticMoment += (((height - valueX) - xCenter) ** i) * (((width - valueY) - yCenter) ** j)
                elif orientation == 2:
                    staticMoment += (((width - valueY) - xCenter) ** i) * ((valueX - yCenter) ** j)
                elif orientation == 3:
                    staticMoment += ((valueY - xCenter) ** i) * (((height - valueX) - yCenter) ** j)

    return staticMoment

def GetObjectElongation(staticMoment02, staticMoment20, staticMoment11):
    try:
        part1 = staticMoment20 + staticMoment02
        part2 = math.sqrt((staticMoment20 - staticMoment02) ** 2 + 4 * staticMoment11)

        return (part1 + part2) / (part1 - part2)

    except Exception as exp:
        return math.inf

def GetObjectOrientation(staticMoment02, staticMoment20, staticMoment11):
    try:
        value = 2 * staticMoment11 / (staticMoment20 - staticMoment02)
        return 0.5 * math.atan(value) * 180 / math.pi
    except Exception as exp:
        return 45

def WriteData(fileName, diap, area, perimeter, comp, x, y, stM02, stM20, stM11, el, scalingXCenter,
              scalingYCenter):
    try:
        file = open("Data\\" + fileName, 'w')
        try:
            file.write("Площадь: " + str(area) + "\n")
            file.write("Периметр: " + str(perimeter) + "\n")
            file.write("Компактность: " + str(comp) + "\n")
            file.write("Центр масс x=" + str(x) + " y=" + str(y) + "\n")
            file.write("Статические моменты:\n")
            file.write("stM02=" + str(stM02) + "\n")
            file.write("stM11=" + str(stM11) + "\n")
            file.write("stM20=" + str(stM20) + "\n")
            file.write("Удлинненность: " + str(el) + "\n")
            file.write("Высота: " + str(diap[2] - diap[0] + 1) + "\n")
            file.write("Ширина: " + str(diap[3] - diap[1] + 1) + "\n")
            file.write("Маштабированная координата x центра масс: " + str(scalingXCenter) + "\n")
            file.write("Маштабированная координата y центра масс: " + str(scalingYCenter) + "\n")

        except Exception as ex:
            print(ex)
        finally:
            file.close()
    except Exception as ex:
        print(ex)

def CreateImage(labels, areas, indexAreas, repository):
    height = areas[2] - areas[0] + 1
    width = areas[3] - areas[1] + 1

    image = Image.new("RGB", (height, width))
    draw = ImageDraw.Draw(image)

    for i in range(0, height, 1):
        for j in range(0, width, 1):
            draw.point((i, j), (0, 0, 0))

    for i in range(0, height, 1):
        for j in range(0, width, 1):
            if labels[i + areas[0]][j + areas[1]] == indexAreas + 1:
                draw.point((i, j), (255, 255, 255))

    for i in range(0, height, 1):
        for j in range(0, width, 1):
            if labels[i + areas[0]][j + areas[1]] == 0:
                counter = GetLabel(labels, i - 1 + areas[0], j + areas[1]) + GetLabel(labels, i + 1 + areas[0],
                                                                                j + areas[1]) + GetLabel(labels,
                                                                                i +
                                                                                areas[0],
                                                                                j - 1 +
                                                                                areas[
                                                                                1]) + GetLabel(
                    labels, i + areas[0], j + 1 + areas[1])
                if counter >= 4 * (indexAreas + 1):
                    draw.point((i, j), (255, 255, 255))

    image.save("Images\\" + repository + str(indexAreas) + ".png")

def GetNeedCenterOfMass(xCenter, yCenter, newAreas):
    height = newAreas[2] - newAreas[0] + 1
    width = newAreas[3] - newAreas[1] + 1

    diapX = []
    diapY = []

    diapX.append(xCenter)
    diapX.append(height - xCenter)
    diapX.append(width - yCenter)
    diapX.append(yCenter)

    diapY.append(yCenter)
    diapY.append(width - yCenter)
    diapY.append(xCenter)
    diapY.append(height - xCenter)

    maxValue = max(diapX)
    orientation = diapX.index(maxValue)

    return diapX[orientation], diapY[orientation], orientation

def GetScalingFactor(areas):
    global maxImageHeight

    height = areas[2] - areas[0] + 1
    width = areas[3] - areas[1] + 1

    value = max(height, width)

    return maxImageHeight / value


import sys
from itertools import takewhile

def factorization_2357(x):

    fs = [0]*10

    for p in [2, 3, 5, 7]:
        while x % p == 0:
            fs[p] += 1
            x //= p

    if x > 1:
        fs = []

    return fs

def solve(n):

    if len(n) == 1:
        return '1' + n

    fs = factorization_2357(int(n))

    if not fs:
        return 'There is no such number.'

    fs[9] = fs[3] // 2
    fs[3] %= 2

    fs[8] = fs[2] // 3
    fs[2] %= 3

    if fs[3] > 0 and fs[2] > 0:
        fs[6] = 1
        fs[2] -= 1
        fs[3] -= 1

    fs[4] = fs[2] // 2
    fs[2] %= 2

    x = 0

    for d in range(2, 10):
        while fs[d] > 0:
            x = 10*x + d
            fs[d] -= 1

    return str(x)

if __name__ == '__main__':

    ns = [x.strip() for x in sys.stdin.readlines()]
    ns = takewhile(lambda x: x != '-1', ns)
    xs = map(solve, ns)

    print('\n'.join(xs))


import  pygame

class Cat:
	"""A class for customizing a picture"""

	def __init__(self, i_game):
		"""initialize the drawing and set its current location"""
		self.screen = i_game.screen
		self.screen_rect = i_game.screen.get_rect()

		# Download image.
		self.image = pygame.image.load('images/cat.bmp')
		self.rect = self.image.get_rect()

		# Create each drawing in the center of the screen
		self.rect.center = self.screen_rect.center

	def blitme(self):
		"""Draw a picture in its current location"""
		self.screen.blit(self.image, self.rect)


from django.conf.urls import url
from . import views

urlpatterns = [
    # /student/
    url(r'^$', views.index, name='index'),

    # /student/grace
    url(r'^grace', views.grace, name='grace'),

    # /student/face
    url(r'^face', views.face, name='face')
]


import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import linregress

def draw_plot():
     # Read data from file
    df = pd.read_csv("epa-sea-level.csv", float_precision='legacy')

    # Create scatter plot
    y = df["CSIRO Adjusted Sea Level"]
    x = df["Year"]
    fig, ax = plt.subplots()
    plt.scatter(x, y)

    # Create first line of best fit
    res = linregress(x, y)
    x_guess = pd.Series([i for i in range(1880, 2051)])
    y_guess = res.slope*x_guess + res.intercept
    plt.plot(x_guess, y_guess, "r")

    # Create second line of best fit
    latest_df = df.loc[df['Year'] >= 2000]
    latest_x = latest_df['Year']
    latest_y = latest_df["CSIRO Adjusted Sea Level"]
    res_2 = linregress(latest_x, latest_y)
    x_guess2 = pd.Series([i for i in range(2000, 2051)])
    y_guess2 = res_2.slope*x_guess2 + res_2.intercept
    plt.plot(x_guess2, y_guess2, 'green')

    # Add labels and title
    plt.xlabel('Year')
    plt.ylabel('Sea Level (inches)')
    plt.title("Rise in Sea Level")

    # Save plot and return data for testing (DO NOT MODIFY)
    plt.savefig('sea_level_plot.png')
    return plt.gca()


from django.urls import path, include
from django.conf import settings
from parcel_api import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('parcels', views.ParcelViewSet, basename='parcel')

urlpatterns = [
    path('api/', include([
        path('', include(router.urls)),
        path('register/', views.RegisterParcelGenerics.as_view(), name='register_parcel'),
        path('types/', views.ListParcelsTypesGenerics.as_view(), name='parcel_types'),
    ])),
    path('', views.index, name='parcel_index')
]

# Urls for developer
if settings.DEBUG:
    urlpatterns += [
        path('api/update/', views.UpdatePrices.as_view(), name='update_prices')
    ]


#изменить баланс белого, сделать более "теплую" картинку
from __future__ import (division, absolute_import, print_function, unicode_literals)
import cv2 as cv
import numpy as np

def show(final):
    cv.imshow('Теплый', final)
    cv.waitKey(0)
    cv.destroyAllWindows()

# Поиск изображения по источнику
img = cv.imread('download.jpg')

#Функция создания баланса белого для создания теплой фотографии
def white_balance_loops(img):
    result = cv.cvtColor(img, cv.COLOR_BGR2LAB)
    avg_a = np.average(result[:, :, 1])
    avg_b = np.average(result[:, :, 2])
    for x in range(result.shape[0]):
        for y in range(result.shape[1]):
            l, a, b = result[x, y, :]
            l *= 100 / 255.0
            result[x, y, 1] = a - ((avg_a - 128) * (l / 100.0) * 1.1)
            result[x, y, 2] = b - ((avg_b - 195) * (l / 100.0) * 1.1)
    result = cv.cvtColor(result, cv.COLOR_LAB2BGR)
    return result

final = np.hstack((img, white_balance_loops(img)))
show(final)
cv.imwrite('task15-image/warm_photo.jpg', final)


import fcntl
import os
import shutil
import sys
from contextlib import suppress
from itertools import count, product
from logging import getLogger
from pathlib import Path
from uuid import uuid4

from pypika import SQLLiteQuery as Query
from pypika import Table

from marv.utils import within_pyinstaller_bundle
from marv_api.utils import find_obj
from marv_node.node import Node
from marv_node.run import run_nodes
from marv_store import Store

from .collection import Collections
from .config import Config, ConfigError
from .db import Database, DBNotInitializedError, Tortoise, create_or_ignore, scoped_session
from .model import Dataset, Group, User

log = getLogger(__name__)

class SiteError(Exception):
    pass

def make_config(siteconf):
    return Config.from_file(siteconf)

def load_sitepackages(sitepackages):
    import site  # pylint: disable=import-outside-toplevel
    site.USER_SITE = sitepackages
    sitepackages.mkdir(parents=True, exist_ok=True)
    if str(sitepackages) not in sys.path:
        sys.path.append(str(sitepackages))
    with suppress(FileNotFoundError), \
         (sitepackages / 'easy-install.pth').open('r') as f:
        for directory in f.readlines():
            if directory[0] == '#' or directory.startswith('import'):
                continue
            directory = directory.strip()
            if directory not in sys.path:
                sys.path.append(directory)

class Site:
    Database = Database
    PREFETCH_FOR_RENDER = ('files',)
    PREFETCH_FOR_RUN = ('collection', 'files')

    def __init__(self, siteconf):
        self.config = make_config(siteconf)
        self.collections = Collections(config=self.config, site=self)
        self.db = self.Database(  # pylint: disable=invalid-name
            [y for x in self.collections.values() for y in x.model],
            self.config,
        )

    @classmethod
    async def create(cls, siteconf, init=None):  # noqa: C901
        site = cls(siteconf)
        if within_pyinstaller_bundle():
            load_sitepackages(site.config.marv.sitepackages)
        site.config.marv.resourcedir.mkdir(exist_ok=True)

        site.db.check_db_version(site.config.marv.dburi, missing_ok=init)

        dbpath = Path(site.config.marv.dburi.split('sqlite://', 1)[1])
        store_db_version = not dbpath.exists()

        if init:
            site.init_directory()

        try:
            fd = os.open(
                site.config.marv.sessionkey_file,
                os.O_CREAT | os.O_EXCL | os.O_WRONLY,
                0o600,
            )
        except OSError as e:
            if e.errno != 17:
                raise
        else:
            with os.fdopen(fd, 'w') as f:
                f.write(str(uuid4()))
            log.verbose('Generated %s', site.config.marv.sessionkey_file)

        # Generate all dynamic models
        models = site.db.MODELS + site.db.listing_models

        await Tortoise.init(
            config={
                'connections': {
                    'default': {
                        'engine': 'tortoise.backends.sqlite',
                        'credentials': {
                            'file_path': dbpath,
                            'foreign_keys': 1,
                        },
                    },
                },
                'apps': {
                    'models': {
                        'models': models,
                    },
                },
            },
        )

        await site.db.initialize_connections()

        try:
            if init:
                await site.init_database(store_db_version=store_db_version)

            async with scoped_session(site.db) as txn:
                try:
                    await txn.execute_query('SELECT name FROM sqlite_master WHERE type="table"')
                except ValueError:
                    raise DBNotInitializedError
        except BaseException:
            await site.destroy()
            raise

        return site

    async def destroy(self):
        await self.db.close_connections()
        await Tortoise.close_connections()

    def load_for_web(self):
        _ = [
            getattr(x, y) and None for x, y, in product(
                self.collections.values(),
                (
                    'compare',
                    'filter_specs',
                    'listing_columns',
                    'model',
                    'sortcolumn',
                    'sortorder',
                    'summary_items',
                ),
            )
        ]

    def init_directory(self):
        try:
            os.mkdir(self.config.marv.storedir)
            log.verbose('Created %s', self.config.marv.storedir)
        except OSError as e:
            if e.errno != 17:
                raise

        try:
            dbdir = os.path.dirname(self.config.marv.dburi.replace('sqlite://', ''))
            os.mkdir(dbdir)
            log.verbose('Created %s', dbdir)
        except OSError as e:
            if e.errno != 17:
                raise

    async def store_db_version(self, txn):
        metadata = Table('metadata')
        # yapf: disable
        await txn.exq(
            Query
            .into(metadata)
            .columns(metadata.key, metadata.value)
            .insert('database_version', self.db.VERSION),
        )
        # yapf: enable

    async def drop_listings(self, txn):
        prefixes = [f'l_{col}' for col in self.collections.keys()]
        tables = {
            name for name in [
                x['name'] for x in
                (await txn.execute_query('SELECT name FROM sqlite_master WHERE type="table"'))[1]
            ] if any(name.startswith(prefix) for prefix in prefixes)
        }
        for table in sorted(tables, key=len, reverse=True):
            await txn.execute_query(f'DROP TABLE {table};')

    async def init_database(self, store_db_version=False):
        async with scoped_session(self.db) as txn:
            await self.drop_listings(txn)

        await Tortoise.generate_schemas()

        async with scoped_session(self.db) as txn:
            for name in ('marv:user:anonymous', 'marv:users', 'admin'):
                await Group.get_or_create(name=name, using_db=txn)

            for name in ('marv:anonymous',):
                user = await User.get_or_create(
                    name=name,
                    realm='marv',
                    realmuid='',
                    active=True,
                    using_db=txn,
                )
                await user[0].groups.add(
                    await Group.get(name=name.replace(':', ':user:')).using_db(txn),
                    using_db=txn,
                )

            if store_db_version:
                await self.store_db_version(txn)

            await create_or_ignore('acn', id=1, txn=txn)
            await create_or_ignore('acn', id=2, txn=txn)
            for name in self.collections:
                await create_or_ignore('collection', name=name, acn_id=1, txn=txn)

            log.verbose('Initialized database %s', self.config.marv.dburi)
            await self.render_detail_and_listing_for_all(txn=txn)
        log.info('Initialized from %s', self.config.filename)

    async def render_detail_and_listing_for_all(self, txn):
        for col, collection in self.collections.items():
            loop = count()
            batchsize = 50
            # TODO: increase verbosity and probably introduce --reinit
            while True:
                batch = await Dataset.filter(collection__name=col)\
                                     .using_db(txn)\
                                     .prefetch_related(*self.PREFETCH_FOR_RENDER)\
                                     .limit(batchsize)\
                                     .offset(batchsize * next(loop))\
                                     .all()
                for dataset in batch:
                    collection.render_detail(dataset)
                if batch:
                    await collection.update_listings(batch, txn=txn)
                if len(batch) < batchsize:
                    break

    async def cleanup_discarded(self):
        descs = {key: x.table_descriptors for key, x in self.collections.items()}
        await self.db.cleanup_discarded(descs)
        # TODO: Cleanup corresponding store paths

    async def cleanup_relations(self):
        descs = {key: x.table_descriptors for key, x in self.collections.items()}
        await self.db.delete_listing_rel_values_without_ref(descs)

    async def restore_database(self, **kw):
        await self.db.restore_database(self, kw)

    async def run(
        self,
        setid,
        selected_nodes=None,
        deps=None,
        force=None,
        keep=None,
        force_dependent=None,
        update_detail=None,
        update_listing=None,
        excluded_nodes=None,
        cachesize=None,
    ):
        # pylint: disable=too-many-arguments,too-many-locals,too-many-branches

        assert not force_dependent or selected_nodes

        excluded_nodes = set(excluded_nodes or [])
        async with scoped_session(self.db) as txn:
            dataset = await Dataset.get(setid=setid)\
                                   .prefetch_related(*self.PREFETCH_FOR_RUN)\
                                   .using_db(txn)
        collection = self.collections[dataset.collection.name]
        selected_nodes = set(selected_nodes or [])
        if not (selected_nodes or update_listing or update_detail):
            selected_nodes.update(collection.listing_deps)
            selected_nodes.update(collection.detail_deps)
        persistent = collection.nodes
        try:
            nodes = {
                persistent[name] if ':' not in name else Node.from_dag_node(find_obj(name))
                for name in selected_nodes
                if name not in excluded_nodes if name != 'dataset'
            }
        except KeyError as exc:
            raise ConfigError(f'Collection {collection.name!r} has no node {exc}')

        if force_dependent:
            nodes.update(x for name in selected_nodes for x in persistent[name].dependent)
        nodes = sorted(nodes)

        storedir = self.config.marv.storedir
        store = Store(storedir, persistent)

        changed = False
        try:
            if nodes:
                changed = await run_nodes(
                    dataset,
                    nodes,
                    store,
                    force=force,
                    persistent=persistent,
                    deps=deps,
                    cachesize=cachesize,
                    site=self,
                )
        finally:
            if not keep:
                for stream in store.pending:
                    if stream.streamfile:
                        stream.streamfile.close()
                for stream in store.readstreams:
                    if stream.streamfile:
                        stream.streamfile.close()
                for tmpdir, tmpdir_fd in store.pending.values():
                    store.logdebug('Cleaning up %r', tmpdir)
                    shutil.rmtree(tmpdir)
                    fcntl.flock(tmpdir_fd, fcntl.LOCK_UN)
                    os.close(tmpdir_fd)
                store.pending.clear()

        if changed or update_detail:
            collection.render_detail(dataset)
            log.verbose('%s detail rendered', setid)
        if changed or update_listing:
            await collection.update_listings([dataset])
            log.verbose('%s listing rendered', setid)

        return changed

    async def scan(self, dry_run=None):
        for collection in self.collections.values():
            for scanroot in collection.scanroots:
                await collection.scan(scanroot, dry_run)


import base64
import requests
import saml2

from saml2 import saml, BINDING_HTTP_POST

from django.test.client import RequestFactory
from djangosaml2.conf import get_config
from djangosaml2.overrides import Saml2Client
from djangosaml2.utils import available_idps

# SP init
#########
conf = get_config(None)
client = Saml2Client(conf)
# just needed to initialize the MetadataStore - it automatically fetches remote idp's metadata
configured_idps = available_idps(conf)

# Arguments needed to create an Attribute query
###############################################
message_id = 'MSG_ID1'
entityid = "http://idp1.testunical.it:9000/idp/aa/metadata"
destination = "http://idp1.testunical.it:9000/aap"
subject_id = "E8042FB4-4D5B-48C3-8E14-8EDD852790DD"
attributes = {
    ('urn:oasis:names:tc:SAML:attribute:pairwise-id',
     "urn:oasis:names:tc:SAML:2.0:attrname-format:uri"): "spidCode-3242342342@idp.spid.it",
    ("fiscalCode",
     "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"): "TIN-SDF7SD89F7SD98F",
    ("email",
     "urn:oasis:names:tc:SAML:2.0:attrname-format:basic",
     "email"): None,
}

# Create an Authoritative, signed, Attribute Query -> xml
req_id, saml_req = client.create_attribute_query(
            destination,
            subject_id,

            # if I use attribute as argument using the official pysaml2 release
            # a saml2.response.IncorrectlySigned Exception will raise
            # use pplnx's pysaml2-aa fork instead, it will correctly validate signature idp-aa-side
            attribute=attributes,

            consent=True,
            format=saml.NAMEID_FORMAT_TRANSIENT,
            message_id=message_id,
            # sign=True,
            # sign_alg=saml2.xmldsig.SIG_RSA_SHA256,
            # digest_alg=saml2.xmldsig.DIGEST_SHA256
)

data = {'SAMLRequest' : base64.b64encode(saml_req.encode())}
headers = {'User-Agent': 'Mozilla/5.0'}
req = requests.post('http://idp1.testunical.it:9000/aap/', data=data, headers=headers)

# create request with html form in HTTP-POST
request = client.do_attribute_query(
        entityid,
        subject_id,
        attribute=attributes,
        # sp_name_qualifier=None,
        # name_qualifier=None,
        nameid_format=saml.NAMEID_FORMAT_TRANSIENT,
        # real_id=None,
        # consent=None,
        # extensions=None,
        sign=True,
        binding=BINDING_HTTP_POST,
        # nsprefix=None,
        # sign_alg=None,
        # digest_alg=None,
)


'''
ASTGCN
'''
import sys
import math
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import pandas as pd
from scipy.sparse.linalg import eigs
from torchsummary import summary

class Spatial_Attention_layer(nn.Module):
    '''
    compute spatial attention scores
    '''
    def __init__(self, device, in_channels, num_of_vertices, num_of_timesteps):
        super(Spatial_Attention_layer, self).__init__()
        self.W1 = nn.Parameter(torch.FloatTensor(num_of_timesteps).to(device))
        self.W2 = nn.Parameter(torch.FloatTensor(in_channels, num_of_timesteps).to(device))
        self.W3 = nn.Parameter(torch.FloatTensor(in_channels).to(device))
        self.bs = nn.Parameter(torch.FloatTensor(1, num_of_vertices, num_of_vertices).to(device))
        self.Vs = nn.Parameter(torch.FloatTensor(num_of_vertices, num_of_vertices).to(device))

    def forward(self, x):
        '''
        :param x: (batch_size, N, F_in, T)
        :return: (B,N,N)
        '''
        lhs = torch.matmul(torch.matmul(x, self.W1), self.W2)  # (b,N,F,T)(T)->(b,N,F)(F,T)->(b,N,T)
        rhs = torch.matmul(self.W3, x).transpose(-1, -2)  # (F)(b,N,F,T)->(b,N,T)->(b,T,N)
        product = torch.matmul(lhs, rhs)  # (b,N,T) (b,T,N) -> (B, N, N)
        S = torch.matmul(self.Vs, torch.sigmoid(product + self.bs))  # (N,N)(B, N, N)->(B,N,N)
        S_normalized = F.softmax(S, dim=1)
        return S_normalized

class cheb_conv_withSAt(nn.Module):
    '''
    K-order chebyshev graph convolution
    '''

    def __init__(self, K, cheb_polynomials, in_channels, out_channels):
        '''
        :param K: int
        :param in_channles: int, num of channels in the input sequence
        :param out_channels: int, num of channels in the output sequence
        '''
        super(cheb_conv_withSAt, self).__init__()
        self.K = K
        self.cheb_polynomials = cheb_polynomials
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.device = cheb_polynomials[0].device
        self.Theta = nn.ParameterList([nn.Parameter(torch.FloatTensor(in_channels, out_channels).to(self.device)) for _ in range(K)])

    def forward(self, x, spatial_attention):
        '''
        Chebyshev graph convolution operation
        :param x: (batch_size, N, F_in, T)
        :return: (batch_size, N, F_out, T)
        '''
        batch_size, num_of_vertices, in_channels, num_of_timesteps = x.shape
        outputs = []

        for time_step in range(num_of_timesteps):
            graph_signal = x[:, :, :, time_step]  # (b, N, F_in)
            output = torch.zeros(batch_size, num_of_vertices, self.out_channels).to(self.device)  # (b, N, F_out)
            for k in range(self.K):
                T_k = self.cheb_polynomials[k]  # (N,N)
                T_k_with_at = T_k.mul(spatial_attention)   # (N,N)*(N,N) = (N,N) 多行和为1, 按着列进行归一化
                theta_k = self.Theta[k]  # (in_channel, out_channel)
                rhs = T_k_with_at.permute(0, 2, 1).matmul(graph_signal)  # (N, N)(b, N, F_in) = (b, N, F_in) 因为是左乘，所以多行和为1变为多列和为1，即一行之和为1，进行左乘
                output = output + rhs.matmul(theta_k)  # (b, N, F_in)(F_in, F_out) = (b, N, F_out)
            outputs.append(output.unsqueeze(-1))  # (b, N, F_out, 1)
        return F.relu(torch.cat(outputs, dim=-1))  # (b, N, F_out, T)

class Temporal_Attention_layer(nn.Module):
    def __init__(self, device, in_channels, num_of_vertices, num_of_timesteps):
        super(Temporal_Attention_layer, self).__init__()
        self.U1 = nn.Parameter(torch.FloatTensor(num_of_vertices).to(device))
        self.U2 = nn.Parameter(torch.FloatTensor(in_channels, num_of_vertices).to(device))
        self.U3 = nn.Parameter(torch.FloatTensor(in_channels).to(device))
        self.be = nn.Parameter(torch.FloatTensor(1, num_of_timesteps, num_of_timesteps).to(device))
        self.Ve = nn.Parameter(torch.FloatTensor(num_of_timesteps, num_of_timesteps).to(device))

    def forward(self, x):
        '''
        :param x: (batch_size, N, F_in, T)
        :return: (B, T, T)
        '''
        _, num_of_vertices, num_of_features, num_of_timesteps = x.shape

        lhs = torch.matmul(torch.matmul(x.permute(0, 3, 2, 1), self.U1), self.U2)
        # x:(B, N, F_in, T) -> (B, T, F_in, N)
        # (B, T, F_in, N)(N) -> (B,T,F_in)
        # (B,T,F_in)(F_in,N)->(B,T,N)
        rhs = torch.matmul(self.U3, x)  # (F)(B,N,F,T)->(B, N, T)
        product = torch.matmul(lhs, rhs)  # (B,T,N)(B,N,T)->(B,T,T)
        E = torch.matmul(self.Ve, torch.sigmoid(product + self.be))  # (B, T, T)
        E_normalized = F.softmax(E, dim=1)
        return E_normalized

class cheb_conv(nn.Module):
    '''
    K-order chebyshev graph convolution
    '''
    def __init__(self, K, cheb_polynomials, in_channels, out_channels):
        '''
        :param K: int
        :param in_channles: int, num of channels in the input sequence
        :param out_channels: int, num of channels in the output sequence
        '''
        super(cheb_conv, self).__init__()
        self.K = K
        self.cheb_polynomials = cheb_polynomials
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.device = cheb_polynomials[0].device
        self.Theta = nn.ParameterList([nn.Parameter(torch.FloatTensor(in_channels, out_channels).to(self.device)) for _ in range(K)])

    def forward(self, x):
        '''
        Chebyshev graph convolution operation
        :param x: (batch_size, N, F_in, T)
        :return: (batch_size, N, F_out, T)
        '''
        batch_size, num_of_vertices, in_channels, num_of_timesteps = x.shape
        outputs = []

        for time_step in range(num_of_timesteps):
            graph_signal = x[:, :, :, time_step]  # (b, N, F_in)
            output = torch.zeros(batch_size, num_of_vertices, self.out_channels).to(self.device)  # (b, N, F_out)
            for k in range(self.K):
                T_k = self.cheb_polynomials[k]  # (N,N)
                theta_k = self.Theta[k]  # (in_channel, out_channel)
                rhs = graph_signal.permute(0, 2, 1).matmul(T_k).permute(0, 2, 1)
                output = output + rhs.matmul(theta_k)
            outputs.append(output.unsqueeze(-1))
        return F.relu(torch.cat(outputs, dim=-1))

class ASTGCN_block(nn.Module):
    def __init__(self, device, in_channels, K, nb_chev_filter, nb_time_filter, time_strides, cheb_polynomials, num_of_vertices, num_of_timesteps):
        super(ASTGCN_block, self).__init__()
        self.TAt = Temporal_Attention_layer(device, in_channels, num_of_vertices, num_of_timesteps)
        self.SAt = Spatial_Attention_layer(device, in_channels, num_of_vertices, num_of_timesteps)
        self.cheb_conv_SAt = cheb_conv_withSAt(K, cheb_polynomials, in_channels, nb_chev_filter)
        self.time_conv = nn.Conv2d(nb_chev_filter, nb_time_filter, kernel_size=(1, 3), stride=(1, time_strides), padding=(0, 1))
        self.residual_conv = nn.Conv2d(in_channels, nb_time_filter, kernel_size=(1, 1), stride=(1, time_strides))
        self.ln = nn.LayerNorm(nb_time_filter)  #需要将channel放到最后一个维度上

    def forward(self, x):
        '''
        :param x: (batch_size, N, F_in, T)
        :return: (batch_size, N, nb_time_filter, T)
        '''
        batch_size, num_of_vertices, num_of_features, num_of_timesteps = x.shape
        # TAt
        temporal_At = self.TAt(x)  # (b, T, T)
        x_TAt = torch.matmul(x.reshape(batch_size, -1, num_of_timesteps), temporal_At).reshape(batch_size, num_of_vertices, num_of_features, num_of_timesteps)
        # SAt
        spatial_At = self.SAt(x_TAt)
        # cheb gcn
        spatial_gcn = self.cheb_conv_SAt(x, spatial_At)  # (b,N,F,T)
        # spatial_gcn = self.cheb_conv(x)
        # convolution along the time axis
        time_conv_output = self.time_conv(spatial_gcn.permute(0, 2, 1, 3))  # (b,N,F,T)->(b,F,N,T) 用(1,3)的卷积核去做->(b,F,N,T)
        # residual shortcut
        x_residual = self.residual_conv(x.permute(0, 2, 1, 3))  # (b,N,F,T)->(b,F,N,T) 用(1,1)的卷积核去做->(b,F,N,T)
        x_residual = self.ln(F.relu(x_residual + time_conv_output).permute(0, 3, 2, 1)).permute(0, 2, 3, 1)
        # (b,F,N,T)->(b,T,N,F) -ln-> (b,T,N,F)->(b,N,F,T)
        return x_residual

class ASTGCN(nn.Module):
    def __init__(self, device, cheb_polynomials, num_for_predict, len_input, num_of_vertices, in_channels, nb_block=2,  K=3, nb_chev_filter=64, nb_time_filter=64, time_strides=2):
        '''
        :param nb_block:
        :param in_channels:
        :param K:
        :param nb_chev_filter:
        :param nb_time_filter:
        :param time_strides:
        :param cheb_polynomials:
        :param nb_predict_step:
        '''
        super(ASTGCN, self).__init__()
        self.BlockList = nn.ModuleList([ASTGCN_block(device, in_channels, K, nb_chev_filter, nb_time_filter, time_strides, cheb_polynomials, num_of_vertices, len_input)])
        self.BlockList.extend([ASTGCN_block(device, nb_time_filter, K, nb_chev_filter, nb_time_filter, 1, cheb_polynomials, num_of_vertices, len_input//time_strides) for _ in range(nb_block-1)])
        self.final_conv = nn.Conv2d(int(len_input/time_strides), num_for_predict, kernel_size=(1, nb_time_filter))
        self.device = device
        self.to(device)

    def forward(self, x):
        '''
        :param x: (B, T, N, C)
        :param x: (B, N, C, T)
        :return: (B, T, N, C)
        '''
        x = x.permute(0, 2, 3, 1) # from (B, T, N, C) to (B, N, C, T)
        for block in self.BlockList:
            x = block(x)
        output = self.final_conv(x.permute(0, 3, 1, 2)) # (b,T,N,C)
        return output

def weight_matrix(W, sigma2=0.1, epsilon=0.5):
    '''
    :param sigma2: float, scalar of matrix W.
    :param epsilon: float, thresholds to control the sparsity of matrix W.
    :param scaling: bool, whether applies numerical scaling on W.
    :return: np.ndarray, [n_route, n_route].
    '''
    n = W.shape[0]
    W = W /10000
    W[W==0]=np.inf
    W2 = W * W
    W_mask = (np.ones([n, n]) - np.identity(n))
    return np.exp(-W2 / sigma2) * (np.exp(-W2 / sigma2) >= epsilon) * W_mask

def scaled_laplacian(A):
    n = A.shape[0]
    d = np.sum(A, axis=1)
    L = np.diag(d) - A
    for i in range(n):
        for j in range(n):
            if d[i] > 0 and d[j] > 0:
                L[i, j] /= np.sqrt(d[i] * d[j])
    lam = np.linalg.eigvals(L).max().real
    return 2 * L / lam - np.eye(n)

def cheb_poly(L, Ks):
    n = L.shape[0]
    LL = [np.eye(n), L[:]]
    for i in range(2, Ks):
        LL.append(np.matmul(2 * L, LL[-1]) - LL[-2])
    return np.asarray(LL)

def main():
    N_NODE, CHANNEL, TIMESTEP_IN, TIMESTEP_OUT = 8, 1, 12, 12
    GPU = '3'
    device = torch.device("cuda:{}".format(GPU)) if torch.cuda.is_available() else torch.device("cpu")
    adj_mx = np.eye(N_NODE)
    L = scaled_laplacian(adj_mx)
    cheb_polynomials = [torch.from_numpy(i).type(torch.FloatTensor).to(device) for i in cheb_poly(L, Ks=3)]
    model = ASTGCN(device, cheb_polynomials, num_for_predict=TIMESTEP_OUT, len_input=TIMESTEP_IN, num_of_vertices=N_NODE, in_channels=CHANNEL).to(device)
    summary(model, (TIMESTEP_IN, N_NODE, CHANNEL), device=device)

if __name__ == '__main__':
    main()


import cv2
import matplotlib.pyplot as plt
# %matplotlib inline

# read images
# img1 = cv2.imread('eye_2.jpg')
# img2 = cv2.imread('eye_1.jpg')

img1 = cv2.imread('odcisk2.jpg')
img2 = cv2.imread('odcisk2.jpg')

img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

figure, ax = plt.subplots(1, 2, figsize=(16, 8))

ax[0].imshow(img1, cmap='gray')
ax[1].imshow(img2, cmap='gray')


class Lagrange:
    def __init__(self, pointlist):
        self.arPoints = pointlist

    def polinom(self):
        result = ''

        for i in range(len(self.arPoints)):
            p = str(self.arPoints[i][1]) + ' * '

            for j in range(i):
                p += '(x-' + str(self.arPoints[j][0]) + ')'
            for j in range(i+1, len(self.arPoints)):
                p += '(x-' + str(self.arPoints[j][0]) + ')'

            p += ' / '

            for j in range(i):
                p += '(' + str(self.arPoints[i][0]) + '-' + str(self.arPoints[j][0]) + ')'
            for j in range(i+1, len(self.arPoints)):
                p += '(' + str(self.arPoints[i][0]) + '-' + str(self.arPoints[j][0]) + ')'

            result += p + ' + '

        return result

    def getValue(self, x):
        result = 0
        for i in range(len(self.arPoints)):
            p = 1
            for j in range(i):
                p *= (x - self.arPoints[j][0]) / (self.arPoints[i][0] - self.arPoints[j][0])
            for j in range(i+1, len(self.arPoints)):
                p *= (x - self.arPoints[j][0]) / (self.arPoints[i][0] - self.arPoints[j][0])
            result += p * self.arPoints[i][1]

        return result
class Chebyshev:
    def __init__(self, rank):
        self.rank = rank + 1
        self.koefs = self.__findkoefs()

    def koeficients(self):
        return self.koefs

    def roots(self):
        return np.roots(self.koefs)

    def Value(self, x):
        result = 0
        for i in len(self.koefs):
            result += x**(self.rank-i) * self.koefs[i]
        return result

    def __findkoefs(self):
        Tprev = [0] * self.rank
        Tprev[-1] = 1
        Tcurr = [0] * self.rank
        Tcurr[-2]  = 1
        for _ in range(2, self.rank):
            Ti = self.__Tnext(Tcurr, Tprev)
            Tprev = Tcurr
            Tcurr = Ti
        return Tcurr

    def __Tnext(self, Tcurr, Tprev):
        result = []
        buff = self.__slide(Tcurr)
        for i in range(self.rank):
            result.append(2 * buff[i] - Tprev[i])
        return result

    def __slide(self, array):
        result = []
        for i in range(len(array) - 1):
            result.append(array[i + 1])
        result.append(0)
        return result
import numpy as np
import math
import matplotlib.pyplot as plt
import random

def randNums(Xarray, lowerlim, upperlim):
    result = []
    for _ in Xarray:
        result.append(random.uniform(lowerlim, upperlim))
    return result

def optValuesX(start, end, count):
    polinom = Chebyshev(count)
    result = polinom.roots()
    for i in range(len(result)):
        result[i] = result[i] * (end-start)/2 + (start+end)/2
    return result

def equidistantValuesX(start, end, count):
    result = []
    step = (float)(end - start) / count
    for i in np.arange(start, end, step):
        result.append(i)
    return result

start = -1
end = 2
count = 8

X = optValuesX(start, end, count)
Y = randNums(X, -2, 4)

points = []
for i in range(count):
    points.append([X[i], Y[i]])

print(points)

polinom = Lagrange(points)

Xgraph = []
Ygraph = []
for i in np.arange(start, end, 0.005):
    Xgraph.append(i)
for x in Xgraph:
    Ygraph.append(polinom.getValue(x))

plt.plot(Xgraph, Ygraph)
plt.grid(True)
plt.show()


from collections import defaultdict
class Graph:
    def __init__(self,vertics):
        self.V = vertics
        self.graph = defaultdict(list)

    def addEdge(self,src,dest):
        self.graph[src].append(dest)
        self.graph[dest].append(src)

    def addEdgeOD(self,src,dest):
        self.graph[src].append(dest)

    #bfs edited
    def BFS (self,start, end ):
        visited = [False] * self.V
        dist = [None]*self.V

        counter = 0

        queue = []

        queue.append(start)
        visited[start] = True
        dist[start] = 0

        while queue :
            start = queue.pop(0)
            # From queue we alwast dequeue the first
            print(start,end="->")
            child_counter = 0

            for i in self.graph[start] :
                if not visited[i]:
                    queue.append(i)
                    visited[i] = True
                    dist[i]=dist[start]+1

        print()
        return dist[end]

    def DFSUtil(self,ver,end, explored,counter):
        explored.add(ver)
        counter = counter+1
        print(ver,end='->')

        for nb in self.graph[ver]:
            if nb not in explored:
                self.DFSUtil(nb, end, explored, counter)
            if end in explored:
                break

    def DFS(self,start,end):
        counter = 0
        explored = set()
        self.DFSUtil(start,end,explored,counter)

    def printGraph(self):
        for i in range(self.V):
            print("[",i,"]",end='=>')
            for j in self.graph[i]:
                print('{',j,'}', end="->")
            print()

    def BFSLevelThree(self,start,end):
        visited = [False] * self.V
        dist = [None] * self.V

        counter = 0

        queue = []

        queue.append(start)
        visited[start] = True
        dist[start] = 0

        while queue:
            start = queue.pop(0)
            # From queue we alwast dequeue the first
            print(start, end="->")
            child_counter = 0

            for i in self.graph[start]:
                if not visited[i]:
                    queue.append(i)
                    visited[i] = True
                    dist[i] = dist[start] + 1

        print()
        return dist[end]


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="gnttb-a2ohm",
    version="1",
    author="Antoine",
    author_email="antoine@2ohm.fr",
    description="A Greek New Testament toolbox",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/a2ohm/gnttb",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
)


#!/usr/bin/env python3

import numpy as np
import matplotlib.pyplot as plt
import glob

def readFile(yay):
    new = []
    with open(yay, 'r') as f:
        f = f.readlines()

    for l in f:
        l = l.replace('\n', "")
        l = l.split()
        new.append(l)
    return new

def getCoords(data):
    list_dist = []
    list_freq = []
    betterData = np.zeros(len(data))
    for i in range(len(data)):
        betterData[i] = float(data[i][1])

    betterData.sort()

    for i in range(len(betterData)):
        if i == 0:
            #print('no')
            list_dist.append(betterData[i])
            list_freq.append(1)
            continue

        for j in range(len(list_dist)):
            if i == 0: print('crap')
            if betterData[i] == list_dist[j]:
                #print('yah')
                list_freq[j] = list_freq[j] + 1
        else:
            list_dist.append(betterData[i])
            list_freq.append(1)

    distance = np.array(list_dist)
    frequency = np.array(list_freq)

    return distance, frequency

def main():
    for filename in glob.glob('distance*.dat'):
        data = readFile(filename)
        dist, freq = getCoords(data)
        plt.plot(dist, freq)

        plt.xlabel('distance')
        plt.ylabel('frequency')

        plt.show()

        print('done')

if __name__ == '__main__':
    main()


from django.urls import path
from django.views.generic import TemplateView
from . import views
app_name = "autheno"
urlpatterns = [
    path("registerd", views.registery.register,name="register"),
    path("logind", views.login.login , name="login"),
    #path("home", TemplateView.as_view(template_name = "authenticate/home.html"), name="home"),
    path("home", views.home, name="home"),
    path("profile/<int:id>", views.profile, name="profile"),
    path("login-register",views.login_register, name="login-register"),
    path("logout", views.logout, name="logout"),
    path("register", views.registere,name="registere"),
    path("login", views.logine , name="logine"),
]


#creates a PDF image of a t-shirt with overlay of text: x took CS50!

from fpdf import FPDF

name = input("What is your name? ")
pdf = FPDF(orientation="landscape", format="A5")
pdf.add_page()
pdf.set_font('helvetica', size=12)
pdf.image("shirtificate.png",x = 0, y=70)
pdf.text(x =100, y=100, txt=(f"{name} took CS50"))
pdf.output("shirtificate.pdf")


import cv2
import numpy as np

def gamma_correction(img: np.ndarray, gamma: float):
    look_up_table = np.empty((1,256), np.uint8)
    for i in range(256):
        look_up_table[0,i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255)
    res = cv2.LUT(img, look_up_table)
    return res

def get_overexposed_mask(gray_img: np.ndarray, threshold: int, need_blur: bool = True):
    """
    Получить маску засвеченных областей с заданным порогом
    на основе перехода к grayscale
    """
    gray = gray_img.copy()
    if need_blur:
        gray = cv2.GaussianBlur(gray_img, (11, 11), 0)
    return cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)[1]

def get_masked(img: np.ndarray, mask: np.ndarray):
    """Получить фрагменты изображения под маской"""
    return cv2.bitwise_and(img, img, mask=mask)

def apply_masked_changes(img: np.ndarray,
                         changed_image: np.ndarray,
                         mask: np.ndarray):
    """Заменить в img маскированные области на области из changed_image"""
    img[np.where(mask == 255)] = changed_image[np.where(mask == 255)]
    return img

def get_map_mask(img, radius):
    bin = get_overexposed_mask(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 220)
    not_bin = cv2.bitwise_not(bin)
    dist = cv2.distanceTransform(not_bin, cv2.DIST_L2, cv2.DIST_MASK_3, not_bin)
    cv2.normalize(dist, dist, 0.0, radius, cv2.NORM_MINMAX)
    not_mask = np.zeros(dist.shape, dtype=np.uint8)
    not_mask[np.where(dist > 1)] = 255
    mask = np.zeros(dist.shape, dtype=np.uint8)
    mask[np.where(not_mask == 0)] = 255
    # cv2.imshow("map", mask)
    return mask

def reduce(img):
    source = img.copy()
    res = img.copy()
    for radius in range(10, 15):
        overexposed_mask = get_map_mask(res, radius)
        mask_inv = cv2.bitwise_not(overexposed_mask)
        source = cv2.bitwise_and(res, res, mask = mask_inv)
        res = cv2.bitwise_and(res, res, mask = overexposed_mask)
        res = gamma_correction(res, 1.1)
        res = cv2.add(source, res)
    cv2.imshow("res", res)
    # return img

if __name__ == '__main__':
    img = cv2.imread('test_1.png')
    img = cv2.resize(img, (650, 350), interpolation=cv2.INTER_AREA)
    reduce(img)
    # get_map_mask(img)
    # cv2.imshow('img', img)
    cv2.waitKey()


"""Provide variant calling with VarScan from TGI at Wash U.

http://varscan.sourceforge.net/
"""

import os
import sys

from bcbio import broad, utils
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.pipeline import config_utils
from bcbio.provenance import do
from bcbio.variation import samtools, vcfutils
from bcbio.variation.vcfutils import (combine_variant_files, write_empty_vcf,
                                      get_paired_bams, bgzip_and_index)

import pysam

def run_varscan(align_bams, items, ref_file, assoc_files,
                region=None, out_file=None):
    paired = get_paired_bams(align_bams, items)
    if paired and paired.normal_bam and paired.tumor_bam:
        call_file = samtools.shared_variantcall(_varscan_paired, "varscan",
                                                align_bams, ref_file, items,
                                                assoc_files, region, out_file)
    else:
        vcfutils.check_paired_problems(items)
        call_file = samtools.shared_variantcall(_varscan_work, "varscan",
                                                align_bams, ref_file,
                                                items, assoc_files,
                                                region, out_file)
    return call_file

def _get_jvm_opts(config, tmp_dir):
    """Retrieve common options for running VarScan.
    Handles jvm_opts, setting user and country to English to avoid issues
    with different locales producing non-compliant VCF.
    """
    resources = config_utils.get_resources("varscan", config)
    jvm_opts = resources.get("jvm_opts", ["-Xmx750m", "-Xmx2g"])
    jvm_opts = config_utils.adjust_opts(jvm_opts,
                                        {"algorithm": {"memory_adjust":
                                                       {"magnitude": 1.1, "direction": "decrease"}}})
    jvm_opts += ["-Duser.language=en", "-Duser.country=US"]
    jvm_opts += broad.get_default_jvm_opts(tmp_dir)
    return " ".join(jvm_opts)

def _varscan_options_from_config(config):
    """Retrieve additional options for VarScan from the configuration.
    """
    opts = ["--min-coverage 5", "--p-value 0.98", "--strand-filter 1"]
    resources = config_utils.get_resources("varscan", config)
    if resources.get("options"):
        opts += [str(x) for x in resources["options"]]
    return opts

def spv_freq_filter(line, tumor_index):
    """Filter VarScan calls based on the SPV value and frequency.

    Removes calls with SPV < 0.05 and a tumor FREQ > 0.35.

    False positives dominate these higher frequency, low SPV calls. They appear
    to be primarily non-somatic/germline variants not removed by other filters.
    """
    if line.startswith("#CHROM"):
        headers = [('##FILTER=<ID=SpvFreq,Description="High frequency (tumor FREQ > 0.35) '
                    'and low p-value for somatic (SPV < 0.05)">')]
        return "\n".join(headers) + "\n" + line
    elif line.startswith("#"):
        return line
    else:
        parts = line.split("\t")
        sample_ft = {a: v for (a, v) in zip(parts[8].split(":"), parts[9 + tumor_index].split(":"))}
        freq = utils.safe_to_float(sample_ft.get("FREQ"))
        spvs = [x for x in parts[7].split(";") if x.startswith("SPV=")]
        spv = utils.safe_to_float(spvs[0].split("=")[-1] if spvs else None)
        fname = None
        if spv is not None and freq is not None:
            if spv < 0.05 and freq > 0.35:
                fname = "SpvFreq"
        if fname:
            if parts[6] in set([".", "PASS"]):
                parts[6] = fname
            else:
                parts[6] += ";%s" % fname
        line = "\t".join(parts)
        return line

def _varscan_paired(align_bams, ref_file, items, target_regions, out_file):

    """Run a paired VarScan analysis, also known as "somatic". """

    max_read_depth = "1000"
    config = items[0]["config"]
    paired = get_paired_bams(align_bams, items)
    if not paired.normal_bam:
        affected_batch = items[0]["metadata"]["batch"]
        message = ("Batch {} requires both tumor and normal BAM files for"
                   " VarScan cancer calling").format(affected_batch)
        raise ValueError(message)

    if not utils.file_exists(out_file):
        assert out_file.endswith(".vcf.gz"), "Expect bgzipped output to VarScan"
        normal_mpileup_cl = samtools.prep_mpileup([paired.normal_bam], ref_file,
                                                  config, max_read_depth,
                                                  target_regions=target_regions,
                                                  want_bcf=False)
        tumor_mpileup_cl = samtools.prep_mpileup([paired.tumor_bam], ref_file,
                                                 config, max_read_depth,
                                                 target_regions=target_regions,
                                                 want_bcf=False)
        base, ext = utils.splitext_plus(out_file)
        indel_file = base + "-indel.vcf"
        snp_file = base + "-snp.vcf"
        with file_transaction(config, indel_file, snp_file) as (tx_indel, tx_snp):
            with tx_tmpdir(items[0]) as tmp_dir:
                jvm_opts = _get_jvm_opts(config, tmp_dir)
                opts = " ".join(_varscan_options_from_config(config))
                remove_zerocoverage = r"{ ifne grep -v -P '\t0\t\t$' || true; }"
                export = utils.local_path_export()
                varscan_cmd = ("{export} varscan {jvm_opts} somatic "
                               "<({normal_mpileup_cl} | {remove_zerocoverage}) "
                               "<({tumor_mpileup_cl} | {remove_zerocoverage}) "
                               "--output-snp {tx_snp} --output-indel {tx_indel} "
                               "--output-vcf {opts} ")
                # add minimum AF
                min_af = float(utils.get_in(paired.tumor_config, ("algorithm",
                                                                  "min_allele_fraction"), 10)) / 100.0
                varscan_cmd += "--min-var-freq {min_af} "
                do.run(varscan_cmd.format(**locals()), "Varscan", None, None)

        to_combine = []
        for fname in [snp_file, indel_file]:
            if utils.file_exists(fname):
                fix_file = "%s-fix.vcf.gz" % (utils.splitext_plus(fname)[0])
                with file_transaction(config, fix_file) as tx_fix_file:
                    fix_ambig_ref = vcfutils.fix_ambiguous_cl()
                    fix_ambig_alt = vcfutils.fix_ambiguous_cl(5)
                    py_cl = os.path.join(os.path.dirname(sys.executable), "py")
                    normal_name = paired.normal_name
                    tumor_name = paired.tumor_name
                    cmd = ("cat {fname} | "
                           "{py_cl} -x 'bcbio.variation.varscan.fix_varscan_output(x,"
                            """ "{normal_name}", "{tumor_name}")' | """
                           "{fix_ambig_ref} | {fix_ambig_alt} | ifne vcfuniqalleles | "
                           """{py_cl} -x 'bcbio.variation.vcfutils.add_contig_to_header(x, "{ref_file}")' | """
                           """bcftools filter -m + -s REJECT -e "SS != '.' && SS != '2'" 2> /dev/null | """
                           "bgzip -c > {tx_fix_file}")
                    do.run(cmd.format(**locals()), "Varscan paired fix")
                to_combine.append(fix_file)

        if not to_combine:
            out_file = write_empty_vcf(out_file, config)
        else:
            out_file = combine_variant_files(to_combine,
                                             out_file, ref_file, config,
                                             region=target_regions)
        if os.path.getsize(out_file) == 0:
            write_empty_vcf(out_file)
        if out_file.endswith(".gz"):
            out_file = bgzip_and_index(out_file, config)

def fix_varscan_output(line, normal_name="", tumor_name=""):
    """Fix a varscan VCF line.

    Fixes the ALT column and also fixes floating point values
    output as strings to by Floats: FREQ, SSC.

    This function was contributed by Sean Davis <sdavis2@mail.nih.gov>,
    with minor modifications by Luca Beltrame <luca.beltrame@marionegri.it>.
    """
    line = line.strip()

    tofix = ("##INFO=<ID=SSC", "##FORMAT=<ID=FREQ")
    if(line.startswith("##")):
        if line.startswith(tofix):
            line = line.replace('Number=1,Type=String',
                                'Number=1,Type=Float')
        return line
    line = line.split("\t")

    if line[0].startswith("#CHROM"):
        if tumor_name and normal_name:
            mapping = {"NORMAL": normal_name, "TUMOR": tumor_name}
            base_header = line[:9]
            old_samples = line[9:]

            if len(old_samples) == 0:
                return "\t".join(line)

            samples = [mapping[sample_name] for sample_name in old_samples]

            assert len(old_samples) == len(samples)
            return "\t".join(base_header + samples)
        else:
            return "\t".join(line)

    try:
        REF, ALT = line[3:5]
    except ValueError:
        return "\t".join(line)

    def _normalize_freq(line, sample_i):
        """Ensure FREQ genotype value is float as defined in header.
        """
        ft_parts = line[8].split(":")
        dat = line[sample_i].split(":")
        # Non-conforming no-call sample, don't try to fix FREQ
        if len(dat) != len(ft_parts):
            return line
        freq_i = ft_parts.index("FREQ")
        try:
            dat[freq_i] = str(float(dat[freq_i].rstrip("%")) / 100)
        except ValueError:  # illegal binary characters -- set frequency to zero
            dat[freq_i] = "0.0"
        line[sample_i] = ":".join(dat)
        return line

    if len(line) > 9:
        line = _normalize_freq(line, 9)
        if len(line) > 10:
            line = _normalize_freq(line, 10)
            # HACK: The position of the SS= changes, so we just search for it
            ss_vals = [item for item in line[7].split(";") if item.startswith("SS=")]
            if len(ss_vals) > 0:
                somatic_status = int(ss_vals[0].split("=")[1])  # Get the number
            else:
                somatic_status = None
            if somatic_status == 5:
                # "Unknown" states are broken in current versions of VarScan
                # so we just bail out here for now
                return
            # fix FREQ for any additional samples -- multi-sample VarScan calling
            if len(line) > 11:
                for i in range(11, len(line)):
                    line = _normalize_freq(line, i)

    #FIXME: VarScan also produces invalid REF records (e.g. CAA/A)
    # This is not handled yet.

    if "+" in ALT or "-" in ALT:
        if "/" not in ALT:
            if ALT[0] == "+":
                R = REF
                A = REF + ALT[1:]
            elif ALT[0] == "-":
                R = REF + ALT[1:]
                A = REF
        else:
            Ins = [p[1:] for p in ALT.split("/") if p[0] == "+"]
            Del = [p[1:] for p in ALT.split("/") if p[0] == "-"]

            if len(Del):
                REF += sorted(Del, key=lambda x: len(x))[-1]

            A = ",".join([REF[::-1].replace(p[::-1], "", 1)[::-1]
                          for p in Del] + [REF + p for p in Ins])
            R = REF

        REF = R
        ALT = A
    else:
        ALT = ALT.replace('/', ',')

    line[3] = REF
    line[4] = ALT
    return "\t".join(line)

def _create_sample_list(in_bams, vcf_file):
    """Pull sample names from input BAMs and create input sample list.
    """
    out_file = "%s-sample_list.txt" % os.path.splitext(vcf_file)[0]
    with open(out_file, "w") as out_handle:
        for in_bam in in_bams:
            with pysam.Samfile(in_bam, "rb") as work_bam:
                for rg in work_bam.header.get("RG", []):
                    out_handle.write("%s\n" % rg["SM"])
    return out_file

def _varscan_work(align_bams, ref_file, items, target_regions, out_file):
    """Perform SNP and indel genotyping with VarScan.
    """
    config = items[0]["config"]

    orig_out_file = out_file
    out_file = orig_out_file.replace(".vcf.gz", ".vcf")

    max_read_depth = "1000"
    sample_list = _create_sample_list(align_bams, out_file)
    mpileup = samtools.prep_mpileup(align_bams, ref_file, config, max_read_depth,
                                    target_regions=target_regions, want_bcf=False)
    # VarScan fails to generate a header on files that start with
    # zerocoverage calls; strip these with grep, we're not going to
    # call on them
    remove_zerocoverage = r"{ ifne grep -v -P '\t0\t\t$' || true; }"
    # we use ifne from moreutils to ensure we process only on files with input, skipping otherwise
    # http://manpages.ubuntu.com/manpages/natty/man1/ifne.1.html
    with tx_tmpdir(items[0]) as tmp_dir:
        jvm_opts = _get_jvm_opts(config, tmp_dir)
        opts = " ".join(_varscan_options_from_config(config))
        min_af = float(utils.get_in(config, ("algorithm", "min_allele_fraction"), 10)) / 100.0
        fix_ambig_ref = vcfutils.fix_ambiguous_cl()
        fix_ambig_alt = vcfutils.fix_ambiguous_cl(5)
        py_cl = os.path.join(os.path.dirname(sys.executable), "py")
        export = utils.local_path_export()
        cmd = ("{export} {mpileup} | {remove_zerocoverage} | "
               "ifne varscan {jvm_opts} mpileup2cns {opts} "
               "--vcf-sample-list {sample_list} --min-var-freq {min_af} --output-vcf --variants | "
               """{py_cl} -x 'bcbio.variation.vcfutils.add_contig_to_header(x, "{ref_file}")' | """
               "{py_cl} -x 'bcbio.variation.varscan.fix_varscan_output(x)' | "
               "{fix_ambig_ref} | {fix_ambig_alt} | ifne vcfuniqalleles > {out_file}")
        do.run(cmd.format(**locals()), "Varscan", None,
                [do.file_exists(out_file)])
    os.remove(sample_list)
    # VarScan can create completely empty files in regions without
    # variants, so we create a correctly formatted empty file
    if os.path.getsize(out_file) == 0:
        write_empty_vcf(out_file)

    if orig_out_file.endswith(".gz"):
        vcfutils.bgzip_and_index(out_file, config)


from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from flask_sqlalchemy import SQLAlchemy
import json

# ==================================== CONNECTION SPECIFICATION ====================================== #
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:password@database-1.c9bzkzbvdsli.ap-southeast-1.rds.amazonaws.com:3306/region'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
CORS(app)

class Region(db.Model):
    __tablename__ = 'region'

    regionID = db.Column(db.Integer)
    spawnDate = db.Column(db.String(50))
    regionName = db.Column(db.String(50), primary_key=True)
    Points = db.Column(db.Integer, nullable=False)

    def __init__(self, regionID,regionName,Points,spawnDate):
        self.regionID = regionID
        self.spawnDate = spawnDate
        self.regionName = regionName
        self.Points = Points

    def json(self):
        region_entry = {
            "regionID": self.regionID,
            "regionName": self.regionName,
            "points": self.Points,
            "spawnDate": self.spawnDate
        }
        return region_entry

    def setSpawnDate(self, spawnDate):
        self.spawnDate = spawnDate
        return True

#region map
class regionMap(db.Model):
    __tablename__ = 'regionMap'
    regionID = db.Column(db.String(50), primary_key=False)
    postalcode = db.Column(db.String(50), primary_key=True)

    def __init__(self, regionID,postalcode):
        self.regionID = regionID
        self.postalcode = postalcode

    def json(self):
        region_entrymap = {
            "regionID": self.regionID,
            "postalcode": self.postalcode
        }
        return region_entrymap

# method to retireve all region maps

# retrieve particular region map area
@app.route("/getCustRegion/<string:postalcode>", methods=["GET"])
@cross_origin(supports_credentials=True)
def getRegionMap(postalcode):
    f2 = postalcode[0] + postalcode[1]
    allRegions = regionMap.query.filter_by(postalcode=f2).first()
    regionID = allRegions.regionID
    reg = Region.query.filter_by(regionID = regionID).first()
    print (reg)

    if reg:
        return jsonify({"RegionName" : reg.regionName}),200
    else:
        return jsonify(False), 404

@app.route("/getSpawnDate/<string:regionName>", methods=["GET"])
@cross_origin(supports_credentials=True)
def getSpawnDate(regionName):
    records = Region.query.get(regionName)
    return jsonify({"spawnDate" :records.spawnDate})

@app.route ("/updateSpawnDate/<string:spawnDate>/<string:regionName>", methods=["PUT"])
@cross_origin(supports_credentials=True)
def updateSpawnDate(spawnDate, regionName):
    records = Region.query.get(regionName)
    records.setSpawnDate(spawnDate)
    db.session.commit()
    return jsonify(True)

@app.route("/getRegions", methods=["GET"])
@cross_origin(supports_credentials=True)
def getRegions():
    return jsonify({"Regions": [region.json() for region in Region.query.all()]})

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


import models.basicblock as B
import numpy as np
import torch.nn.functional as F
from .layers import *
from models import utv_model

"""
# --------------------------------------------
# basic functions
# --------------------------------------------
"""
def splits(a, sf):
    '''split a into sfxsf distinct blocks

    Args:
        a: NxCxWxHx2
        sf: split factor

    Returns:
        b: NxCx(W/sf)x(H/sf)x2x(sf^2)
    '''
    b = torch.stack(torch.chunk(a, sf, dim=2), dim=5)
    b = torch.cat(torch.chunk(b, sf, dim=3), dim=5)
    return b

def c2c(x):
    return torch.from_numpy(np.stack([np.float32(x.real), np.float32(x.imag)], axis=-1))

def r2c(x):
    # convert real to complex
    return torch.stack([x, torch.zeros_like(x)], -1)

def cdiv(x, y):
    # complex division
    a, b = x[..., 0], x[..., 1]
    c, d = y[..., 0], y[..., 1]
    cd2 = c**2 + d**2
    return torch.stack([(a*c+b*d)/cd2, (b*c-a*d)/cd2], -1)

def crdiv(x, y):
    # complex/real division
    a, b = x[..., 0], x[..., 1]
    return torch.stack([a/y, b/y], -1)

def csum(x, y):
    # complex + real
    return torch.stack([x[..., 0] + y, x[..., 1]], -1)

def cabs(x):
    # modulus of a complex number
    return torch.pow(x[..., 0]**2+x[..., 1]**2, 0.5)

def cabs2(x):
    return x[..., 0]**2+x[..., 1]**2

def cmul(t1, t2):
    '''complex multiplication

    Args:
        t1: NxCxHxWx2, complex tensor
        t2: NxCxHxWx2

    Returns:
        output: NxCxHxWx2
    '''
    real1, imag1 = t1[..., 0], t1[..., 1]
    real2, imag2 = t2[..., 0], t2[..., 1]
    return torch.stack([real1 * real2 - imag1 * imag2, real1 * imag2 + imag1 * real2], dim=-1)

def cconj(t, inplace=False):
    '''complex's conjugation

    Args:
        t: NxCxHxWx2

    Returns:
        output: NxCxHxWx2
    '''
    c = t.clone() if not inplace else t
    c[..., 1] *= -1
    return c

def rfft(t):
    # Real-to-complex Discrete Fourier Transform
    return torch.rfft(t, 2, onesided=False)

def irfft(t):
    # Complex-to-real Inverse Discrete Fourier Transform
    return torch.irfft(t, 2, onesided=False)

def fft(t):
    # Complex-to-complex Discrete Fourier Transform
    return torch.fft(t, 2)

def ifft(t):
    # Complex-to-complex Inverse Discrete Fourier Transform
    return torch.ifft(t, 2)

def p2o(psf, shape):
    '''
    Convert point-spread function to optical transfer function.
    otf = p2o(psf) computes the Fast Fourier Transform (FFT) of the
    point-spread function (PSF) array and creates the optical transfer
    function (OTF) array that is not influenced by the PSF off-centering.

    Args:
        psf: NxCxhxw
        shape: [H, W]

    Returns:
        otf: NxCxHxWx2
    '''
    otf = torch.zeros(psf.shape[:-2] + shape).type_as(psf)
    otf[...,:psf.shape[2],:psf.shape[3]].copy_(psf)
    for axis, axis_size in enumerate(psf.shape[2:]):
        otf = torch.roll(otf, -int(axis_size / 2), dims=axis+2)
    otf = torch.rfft(otf, 2, onesided=False)
    n_ops = torch.sum(torch.tensor(psf.shape).type_as(psf) * torch.log2(torch.tensor(psf.shape).type_as(psf)))
    otf[..., 1][torch.abs(otf[..., 1]) < n_ops*2.22e-16] = torch.tensor(0).type_as(psf)
    return otf

def upsample(x, sf=3):
    '''s-fold upsampler

    Upsampling the spatial size by filling the new entries with zeros

    x: tensor image, NxCxWxH
    '''
    st = 0
    z = torch.zeros((x.shape[0], x.shape[1], x.shape[2]*sf, x.shape[3]*sf)).type_as(x)
    z[..., st::sf, st::sf].copy_(x)
    return z

def downsample(x, sf=3):
    '''s-fold downsampler

    Keeping the upper-left pixel for each distinct sfxsf patch and discarding the others

    x: tensor image, NxCxWxH
    '''
    st = 0
    return x[..., st::sf, st::sf]

def downsample_np(x, sf=3):
    st = 0
    return x[st::sf, st::sf, ...]

"""
# --------------------------------------------
# (1) Prior module: CTD Module
# --------------------------------------------
"""
class EBlock(nn.Module):
    def __init__(self, in_channel, out_channel, num_res=8, norm=False, first=False):
        super(EBlock, self).__init__()
        if first:
            layers = [Basic(in_channel, out_channel, kernel_size=3, norm=norm, relu=True, stride=1)]  # 步幅1卷积
        else:
            layers = [Basic(in_channel, out_channel, kernel_size=3, norm=norm, relu=True, stride=2)]  # 步幅2卷积

        layers += [ResBlock(out_channel, out_channel, norm) for _ in range(num_res)]
        self.layers = nn.Sequential(*layers)

    def forward(self, x):
        return self.layers(x)

class DBlock(nn.Module):
    def __init__(self, channel, num_res=8, norm=False, last=False, feature_ensemble=False):
        super(DBlock, self).__init__()

        layers = [ResBlock(channel, channel, norm) for _ in range(num_res)]

        if last:
            if feature_ensemble == False:
                layers.append(Basic(channel, 1, kernel_size=3, norm=norm, relu=False, stride=1))
        else:
            layers.append(
                Basic(channel, channel // 2, kernel_size=4, norm=norm, relu=True, stride=2, transpose=True))

        self.layers = nn.Sequential(*layers)

    def forward(self, x):
        return self.layers(x)

class FOrD_v1(nn.Module):
    def __init__(self, channel, rot_opt=False):
        super(FOrD_v1, self).__init__()

        self.decomp = Basic(channel, channel, kernel_size=1, relu=False, stride=1)

    def forward(self, x):
        x_decomp1 = self.decomp(x)
        x_decomp1_norm = F.normalize(x_decomp1, p=2, dim=1)
        x_decomp2 = x - torch.unsqueeze(torch.sum(x * x_decomp1_norm, dim=1), 1) * x_decomp1_norm
        return x_decomp1, x_decomp2

class TexNet(nn.Module):
    def __init__(self):
        super(TexNet, self).__init__()

        in_channel = 1
        base_channel = 32

        num_res_ENC = 4

        self.Encoder1 = EBlock(in_channel, base_channel, num_res_ENC, first=True)
        self.Encoder2 = EBlock(base_channel, base_channel * 2, num_res_ENC, norm=False)
        self.Encoder3 = EBlock(base_channel * 2, base_channel * 4, num_res_ENC, norm=False)

        self.Convs1_1 = Basic(base_channel * 4, base_channel * 2, kernel_size=1, relu=True, stride=1)
        self.Convs1_2 = Basic(base_channel * 2, base_channel, kernel_size=1, relu=True, stride=1)

        num_res_DEC = 4

        self.Decoder1_1 = DBlock(base_channel * 4, num_res_DEC, norm=False)
        self.Decoder1_2 = DBlock(base_channel * 2, num_res_DEC, norm=False)
        self.Decoder1_3 = DBlock(base_channel, num_res_DEC, last=True, feature_ensemble=True)
        self.Decoder1_4 = Basic(base_channel, 1, kernel_size=3, relu=False, stride=1)

    def forward(self, x):
        output = list()

        # Common encoder
        x_e1 = self.Encoder1(x)
        x_e2 = self.Encoder2(x_e1)
        x_decomp = self.Encoder3(x_e2)

        # Resultant image reconstruction
        x_decomp1 = self.Decoder1_1(x_decomp)
        x_decomp1 = self.Convs1_1(torch.cat([x_decomp1, x_e2], dim=1))
        x_decomp1 = self.Decoder1_2(x_decomp1)
        x_decomp1 = self.Convs1_2(torch.cat([x_decomp1, x_e1], dim=1))
        x_decomp1 = self.Decoder1_3(x_decomp1)
        x_decomp1 = self.Decoder1_4(x_decomp1)
        return x_decomp1

class CarNet(nn.Module):
    def __init__(self):
        super(CarNet, self).__init__()
        self.TV = utv_model.ADMM(1, 6, 1)
        self.device = torch.device('cuda')
        self.hyp = B.HyPaNet()
    def forward(self, x):
        r = x[:, 0, :, :]
        smoothr = self.TV(r).unsqueeze(1)
        return smoothr

"""
# --------------------------------------------
# (2) Data module, closed-form solution
# It is a trainable-parameter-free module  ^_^
# z_k = D(x_{k-1}, s, k, y, alpha_k)
# some can be pre-calculated
# --------------------------------------------
"""
class DataNet(nn.Module):
    def __init__(self):
        super(DataNet, self).__init__()

    def forward(self, x, FB, FBC, F2B, FBFy, alpha, sf):
        FR = FBFy + torch.rfft(alpha*x, 2, onesided=False)
        x1 = cmul(FB, FR)
        FBR = torch.mean(splits(x1, sf), dim=-1, keepdim=False)
        invW = torch.mean(splits(F2B, sf), dim=-1, keepdim=False)
        invWBR = cdiv(FBR, csum(invW, alpha))
        FCBinvWBR = cmul(FBC, invWBR.repeat(1, 1, sf, sf, 1))
        FX = (FR-FCBinvWBR)/alpha.unsqueeze(-1)
        Xest = torch.irfft(FX, 2, onesided=False)
        return Xest

"""
# --------------------------------------------
# (3) Hyper-parameter module
# --------------------------------------------
"""
class HyPaNet(nn.Module):
    def __init__(self, in_nc=2, out_nc=8, channel=64):
        super(HyPaNet, self).__init__()
        self.mlp = nn.Sequential(
                nn.Conv2d(in_nc, channel, 1, padding=0, bias=True),
                nn.ReLU(inplace=True),
                nn.Conv2d(channel, channel, 1, padding=0, bias=True),
                nn.ReLU(inplace=True),
                nn.Conv2d(channel, out_nc, 1, padding=0, bias=True),
                nn.Softplus())
    def forward(self, x):
        x = self.mlp(x) + 1e-6
        return x

"""
# --------------------------------------------
# main CTDNet
# deep unfolding super-resolution network
# --------------------------------------------
"""
class CTDNet(nn.Module):
    def __init__(self, n_iter=8, h_nc=64, in_nc=4, out_nc=3, nc=[64, 128, 256, 512], nb=2, act_mode='R', downsample_mode='strideconv', upsample_mode='convtranspose'):
        super(CTDNet, self).__init__()
        self.d = DataNet()
        self.h = HyPaNet(in_nc=2, out_nc=n_iter*2, channel=h_nc)
        self.n = n_iter
        self.xy = TexNet()
        self.u = CarNet()

    def forward(self, x, k, sf, sigma):
        '''
        x: tensor, NxCxWxH
        k: tensor, Nx(1,3)xwxh
        sf: integer, 1
        sigma: tensor, Nx1x1x1
        '''

        # initialization & pre-calculation
        w, h = x.shape[-2:]
        FB = p2o(k, (w*sf, h*sf))
        FBC = cconj(FB, inplace=False)
        F2B = r2c(cabs2(FB))
        STy = upsample(x, sf=sf)
        FBFy = cmul(FBC, torch.rfft(STy, 2, onesided=False))
        x = nn.functional.interpolate(x, scale_factor=sf, mode='nearest')

        # hyper-parameter
        ab = self.h(torch.cat((sigma, torch.tensor(sf).type_as(sigma).expand_as(sigma)), dim=1))

        # unfolding
        for i in range(self.n):
            x = self.d(x, FB, FBC, F2B, FBFy, ab[:, i:i+1, ...], sf)
            cartoon = self.u(x)
            texture = self.xy(x)
            x = cartoon + texture
        return cartoon, texture, x


from http import HTTPStatus
from random import randint
from unittest import TestCase, mock

from faker import Faker
from faker.providers import internet

from livecode.repository import CharacterRepository

from .factories import CharacterFactory

faker = Faker()
faker.add_provider(internet)

class ResponseMock:
    def __init__(self, status_code, json):
        self.status_code = status_code
        self.json_data = json

    def json(self):
        return self.json_data

class CharacterCollectionFake:
    def __init__(self, find_return):
        self.find_return = find_return

    def find(self, *args, **kwargs):
        return self.find_return

    def insert_one(self, document):
        return document.update({"_id": "..."})

class MongoClientFake:
    def __init__(self, find_return=[]):
        self.find_return = find_return

    @property
    def character(self):
        return CharacterCollectionFake(self.find_return)

DOCUMENTS_MOCK = [
    {
        "_id": "...",
        "name": faker.name_female(),
        "gender": "Female",
        "id": randint(100, 500),
    },
    {"_id": "...", "name": faker.name(), "gender": "Unknown", "id": randint(100, 500)},
    {
        "_id": "...",
        "name": faker.name_male(),
        "gender": "Male",
        "id": randint(100, 500),
    },
    {
        "_id": "...",
        "name": faker.name_female(),
        "gender": "Female",
        "id": randint(100, 500),
    },
]

class CharacterRepositoryTestCase(TestCase):
    def setUp(self):
        self.repository = CharacterRepository(faker.url(), MongoClientFake())

        self.character = CharacterFactory.create(id=0)
        self.response_mock = {
            "results": [
                {
                    "id": randint(1, 100),
                    "name": self.character.name,
                    "gender": self.character.gender,
                },
                {"id": randint(1, 100), "name": faker.name(), "gender": "Unknown",},
            ]
        }

    def test_find_all(self):
        repository = CharacterRepository(faker.url(), MongoClientFake(DOCUMENTS_MOCK))

        characters = repository.find()

        self.assertEqual(len(characters), 4)

    def test_find_filter(self):
        repository = CharacterRepository(
            faker.url(), MongoClientFake(DOCUMENTS_MOCK[0:1])
        )

        filter_name = DOCUMENTS_MOCK[0]["name"]
        characters = repository.find({"name": filter_name})

        self.assertEqual(len(characters), 1)

    def test_create_character(self):
        with mock.patch(
            "requests.get", return_value=ResponseMock(HTTPStatus.OK, self.response_mock)
        ):
            new_character = self.repository.create(self.character)

        self.assertNotEqual(new_character.id, 0, "Id of character should be filled")
        self.assertEqual(new_character.name, self.character.name)
        self.assertEqual(new_character.gender, self.character.gender)

    def test_parse_character_is_valid(self):
        with mock.patch(
            "requests.get", return_value=ResponseMock(HTTPStatus.OK, self.response_mock)
        ):
            try:
                self.repository.parse_character(self.character)
            except ValueError as e:
                self.fail(f"Character is valid: {e}")

    def test_parse_character_not_valid(self):
        character = CharacterFactory.create()

        with mock.patch(
            "requests.get", return_value=ResponseMock(HTTPStatus.OK, {"results": []})
        ):
            with self.assertRaises(ValueError):
                self.repository.parse_character(character)

    def test_parse_character_not_valid_404(self):
        character = CharacterFactory.create()

        with mock.patch(
            "requests.get",
            return_value=ResponseMock(HTTPStatus.NOT_FOUND, self.response_mock),
        ):
            with self.assertRaises(ValueError):
                self.repository.parse_character(character)