'''
Problem Statement: Rotate Image

Link: https://leetcode.com/problems/rotate-image
Tags: ['Array']
Difficulty: Medium

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Example 3:
Input: matrix = [[1]]
Output: [[1]]

Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

Constraints:

matrix.length == n
matrix[i].length == n
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
'''

from typing import List

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        def printmat(mat):
            for row in mat:
                print(row)
            print()

        n = len(matrix)

        for i in range(0, n // 2):
            coords = [
                (i, i),
                (i, n - i - 1),
                (n - i - 1, n - i - 1),
                (n - i - 1, i)
            ]

            for j in range(i, n - i - 1):
                last_val = [
                    matrix[coords[0][0]][coords[0][1]],
                    matrix[coords[1][0]][coords[1][1]],
                    matrix[coords[2][0]][coords[2][1]],
                    matrix[coords[3][0]][coords[3][1]]
                ]

                for k in range(0, 4):
                    a2, b2 = coords[(k + 1) % 4]
                    matrix[a2][b2] = last_val[k]

                for k in range(0, 4):
                    a, b = coords[k]

                    if k == 0:
                        coords[k] = a, b + 1
                    elif k == 1:
                        coords[k] = a + 1, b
                    elif k == 2:
                        coords[k] = a, b - 1
                    else:
                        coords[k] = a - 1, b


"""Implicit plotting module for SymPy.

Explanation
===========

The module implements a data series called ImplicitSeries which is used by
``Plot`` class to plot implicit plots for different backends. The module,
by default, implements plotting using interval arithmetic. It switches to a
fall back algorithm if the expression cannot be plotted using interval arithmetic.
It is also possible to specify to use the fall back algorithm for all plots.

Boolean combinations of expressions cannot be plotted by the fall back
algorithm.

See Also
========

sympy.plotting.plot

References
==========

.. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
Mathematical Formulae with Two Free Variables.

.. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
Arithmetic. Master's thesis. University of Toronto, 1996

"""

from .plot import BaseSeries, Plot
from .experimental_lambdify import experimental_lambdify, vectorized_lambdify
from .intervalmath import interval
from sympy.core.relational import (Equality, GreaterThan, LessThan,
                Relational, StrictLessThan, StrictGreaterThan)
from sympy import Eq, Tuple, sympify, Symbol, Dummy
from sympy.external import import_module
from sympy.logic.boolalg import BooleanFunction
from sympy.polys.polyutils import _sort_gens
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import flatten
import warnings

class ImplicitSeries(BaseSeries):
    """ Representation for Implicit plot """
    is_implicit = True

    def __init__(self, expr, var_start_end_x, var_start_end_y,
            has_equality, use_interval_math, depth, nb_of_points,
            line_color):
        super().__init__()
        self.expr = sympify(expr)
        self.var_x = sympify(var_start_end_x[0])
        self.start_x = float(var_start_end_x[1])
        self.end_x = float(var_start_end_x[2])
        self.var_y = sympify(var_start_end_y[0])
        self.start_y = float(var_start_end_y[1])
        self.end_y = float(var_start_end_y[2])
        self.get_points = self.get_raster
        self.has_equality = has_equality  # If the expression has equality, i.e.
                                         #Eq, Greaterthan, LessThan.
        self.nb_of_points = nb_of_points
        self.use_interval_math = use_interval_math
        self.depth = 4 + depth
        self.line_color = line_color

    def __str__(self):
        return ('Implicit equation: %s for '
                '%s over %s and %s over %s') % (
                    str(self.expr),
                    str(self.var_x),
                    str((self.start_x, self.end_x)),
                    str(self.var_y),
                    str((self.start_y, self.end_y)))

    def get_raster(self):
        func = experimental_lambdify((self.var_x, self.var_y), self.expr,
                                    use_interval=True)
        xinterval = interval(self.start_x, self.end_x)
        yinterval = interval(self.start_y, self.end_y)
        try:
            func(xinterval, yinterval)
        except AttributeError:
            # XXX: AttributeError("'list' object has no attribute 'is_real'")
            # That needs fixing somehow - we shouldn't be catching
            # AttributeError here.
            if self.use_interval_math:
                warnings.warn("Adaptive meshing could not be applied to the"
                            " expression. Using uniform meshing.")
            self.use_interval_math = False

        if self.use_interval_math:
            return self._get_raster_interval(func)
        else:
            return self._get_meshes_grid()

    def _get_raster_interval(self, func):
        """ Uses interval math to adaptively mesh and obtain the plot"""
        k = self.depth
        interval_list = []
        #Create initial 32 divisions
        np = import_module('numpy')
        xsample = np.linspace(self.start_x, self.end_x, 33)
        ysample = np.linspace(self.start_y, self.end_y, 33)

        #Add a small jitter so that there are no false positives for equality.
        # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2)
        #which will draw a rectangle.
        jitterx = (np.random.rand(
            len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20
        jittery = (np.random.rand(
            len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20
        xsample += jitterx
        ysample += jittery

        xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1],
                           xsample[1:])]
        yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1],
                           ysample[1:])]
        interval_list = [[x, y] for x in xinter for y in yinter]
        plot_list = []

        #recursive call refinepixels which subdivides the intervals which are
        #neither True nor False according to the expression.
        def refine_pixels(interval_list):
            """ Evaluates the intervals and subdivides the interval if the
            expression is partially satisfied."""
            temp_interval_list = []
            plot_list = []
            for intervals in interval_list:

                #Convert the array indices to x and y values
                intervalx = intervals[0]
                intervaly = intervals[1]
                func_eval = func(intervalx, intervaly)
                #The expression is valid in the interval. Change the contour
                #array values to 1.
                if func_eval[1] is False or func_eval[0] is False:
                    pass
                elif func_eval == (True, True):
                    plot_list.append([intervalx, intervaly])
                elif func_eval[1] is None or func_eval[0] is None:
                    #Subdivide
                    avgx = intervalx.mid
                    avgy = intervaly.mid
                    a = interval(intervalx.start, avgx)
                    b = interval(avgx, intervalx.end)
                    c = interval(intervaly.start, avgy)
                    d = interval(avgy, intervaly.end)
                    temp_interval_list.append([a, c])
                    temp_interval_list.append([a, d])
                    temp_interval_list.append([b, c])
                    temp_interval_list.append([b, d])
            return temp_interval_list, plot_list

        while k >= 0 and len(interval_list):
            interval_list, plot_list_temp = refine_pixels(interval_list)
            plot_list.extend(plot_list_temp)
            k = k - 1
        #Check whether the expression represents an equality
        #If it represents an equality, then none of the intervals
        #would have satisfied the expression due to floating point
        #differences. Add all the undecided values to the plot.
        if self.has_equality:
            for intervals in interval_list:
                intervalx = intervals[0]
                intervaly = intervals[1]
                func_eval = func(intervalx, intervaly)
                if func_eval[1] and func_eval[0] is not False:
                    plot_list.append([intervalx, intervaly])
        return plot_list, 'fill'

    def _get_meshes_grid(self):
        """Generates the mesh for generating a contour.

        In the case of equality, ``contour`` function of matplotlib can
        be used. In other cases, matplotlib's ``contourf`` is used.
        """
        equal = False
        if isinstance(self.expr, Equality):
            expr = self.expr.lhs - self.expr.rhs
            equal = True

        elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)):
            expr = self.expr.lhs - self.expr.rhs

        elif isinstance(self.expr, (LessThan, StrictLessThan)):
            expr = self.expr.rhs - self.expr.lhs
        else:
            raise NotImplementedError("The expression is not supported for "
                                    "plotting in uniform meshed plot.")
        np = import_module('numpy')
        xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points)
        yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points)
        x_grid, y_grid = np.meshgrid(xarray, yarray)

        func = vectorized_lambdify((self.var_x, self.var_y), expr)
        z_grid = func(x_grid, y_grid)
        z_grid[np.ma.where(z_grid < 0)] = -1
        z_grid[np.ma.where(z_grid > 0)] = 1
        if equal:
            return xarray, yarray, z_grid, 'contour'
        else:
            return xarray, yarray, z_grid, 'contourf'

@doctest_depends_on(modules=('matplotlib',))
def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
                  points=300, line_color="blue", show=True, **kwargs):
    """A plot function to plot implicit equations / inequalities.

    Arguments
    =========

    - ``expr`` : The equation / inequality that is to be plotted.
    - ``x_var`` (optional) : symbol to plot on x-axis or tuple giving symbol
      and range as ``(symbol, xmin, xmax)``
    - ``y_var`` (optional) : symbol to plot on y-axis or tuple giving symbol
      and range as ``(symbol, ymin, ymax)``

    If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
    expression will be assigned in the order they are sorted.

    The following keyword arguments can also be used:

    - ``adaptive`` Boolean. The default value is set to True. It has to be
        set to False if you want to use a mesh grid.

    - ``depth`` integer. The depth of recursion for adaptive mesh grid.
        Default value is 0. Takes value in the range (0, 4).

    - ``points`` integer. The number of points if adaptive mesh grid is not
        used. Default value is 300.

    - ``show`` Boolean. Default value is True. If set to False, the plot will
        not be shown. See ``Plot`` for further information.

    - ``title`` string. The title for the plot.

    - ``xlabel`` string. The label for the x-axis

    - ``ylabel`` string. The label for the y-axis

    Aesthetics options:

    - ``line_color``: float or string. Specifies the color for the plot.
        See ``Plot`` to see how to set color for the plots.
        Default value is "Blue"

    plot_implicit, by default, uses interval arithmetic to plot functions. If
    the expression cannot be plotted using interval arithmetic, it defaults to
    a generating a contour using a mesh grid of fixed number of points. By
    setting adaptive to False, you can force plot_implicit to use the mesh
    grid. The mesh grid method can be effective when adaptive plotting using
    interval arithmetic, fails to plot with small line width.

    Examples
    ========

    Plot expressions:

    .. plot::
        :context: reset
        :format: doctest
        :include-source: True

        >>> from sympy import plot_implicit, symbols, Eq, And
        >>> x, y = symbols('x y')

    Without any ranges for the symbols in the expression:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))

    With the range for the symbols:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p2 = plot_implicit(
        ...     Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))

    With depth of recursion as argument:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p3 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)

    Using mesh grid and not using adaptive meshing:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p4 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
        ...     adaptive=False)

    Using mesh grid without using adaptive meshing with number of points
    specified:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p5 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
        ...     adaptive=False, points=400)

    Plotting regions:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p6 = plot_implicit(y > x**2)

    Plotting Using boolean conjunctions:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p7 = plot_implicit(And(y > x, y > -x))

    When plotting an expression with a single variable (y - 1, for example),
    specify the x or the y variable explicitly:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p8 = plot_implicit(y - 1, y_var=y)
        >>> p9 = plot_implicit(x - 1, x_var=x)
    """
    has_equality = False  # Represents whether the expression contains an Equality,
                     #GreaterThan or LessThan

    def arg_expand(bool_expr):
        """
        Recursively expands the arguments of an Boolean Function
        """
        for arg in bool_expr.args:
            if isinstance(arg, BooleanFunction):
                arg_expand(arg)
            elif isinstance(arg, Relational):
                arg_list.append(arg)

    arg_list = []
    if isinstance(expr, BooleanFunction):
        arg_expand(expr)

    #Check whether there is an equality in the expression provided.
        if any(isinstance(e, (Equality, GreaterThan, LessThan))
               for e in arg_list):
            has_equality = True

    elif not isinstance(expr, Relational):
        expr = Eq(expr, 0)
        has_equality = True
    elif isinstance(expr, (Equality, GreaterThan, LessThan)):
        has_equality = True

    xyvar = [i for i in (x_var, y_var) if i is not None]
    free_symbols = expr.free_symbols
    range_symbols = Tuple(*flatten(xyvar)).free_symbols
    undeclared = free_symbols - range_symbols
    if len(free_symbols & range_symbols) > 2:
        raise NotImplementedError("Implicit plotting is not implemented for "
                                  "more than 2 variables")

    #Create default ranges if the range is not provided.
    default_range = Tuple(-5, 5)
    def _range_tuple(s):
        if isinstance(s, Symbol):
            return Tuple(s) + default_range
        if len(s) == 3:
            return Tuple(*s)
        raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)

    if len(xyvar) == 0:
        xyvar = list(_sort_gens(free_symbols))
    var_start_end_x = _range_tuple(xyvar[0])
    x = var_start_end_x[0]
    if len(xyvar) != 2:
        if x in undeclared or not undeclared:
            xyvar.append(Dummy('f(%s)' % x.name))
        else:
            xyvar.append(undeclared.pop())
    var_start_end_y = _range_tuple(xyvar[1])

    #Check whether the depth is greater than 4 or less than 0.
    if depth > 4:
        depth = 4
    elif depth < 0:
        depth = 0

    series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
                                    has_equality, adaptive, depth,
                                    points, line_color)

    #set the x and y limits
    kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
    kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
    # set the x and y labels
    kwargs.setdefault('xlabel', var_start_end_x[0].name)
    kwargs.setdefault('ylabel', var_start_end_y[0].name)
    p = Plot(series_argument, **kwargs)
    if show:
        p.show()
    return p


# Week 6 - Assignment 1
# Links: http://py4e-data.dr-chuck.net/comments_42.json, http://py4e-data.dr-chuck.net/comments_869371.json

import urllib.request, urllib.parse, urllib.error
import json

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter location: ')
print("Retrieving ", url)

connection = urllib.request.urlopen(url, context=ctx)
url_info   = connection.read().decode()
print("Retrieved ",len(url_info)," characters")

info = json.loads(url_info)
# print(json.dumps(info, indent=2))

count = 0
sum_  = 0
for item in info["comments"]:
    sum_  += int(item['count'])
    count += 1

print("Count: ", count)
print("Sum: ", sum_)


from django.shortcuts import render
from django.contrib.auth.decorators import login_required, user_passes_test
from restau.models import ActiveSetup, Fotos, Horario
from typing import Dict

@login_required
@user_passes_test(lambda user: user.groups.filter(
    name='acesso_restrito').exists())
def admin_home(request):

    return render(
        request,
        'restau/pages/admin_home.html',

    )

def index(request):

    galeria = Fotos.objects \
        .all() \
        .order_by('ordem') \

    active_setup = ActiveSetup.objects.get()

    horarios = Horario.objects.all()

    dict_horarios: Dict[str, int] = {
        'Segunda': 1,
        'Terça': 2,
        'Quarta': 3,
        'Quinta': 4,
        'Sexta': 5,
        'Sábado': 6,
        'Domingo': 7,
        'Feriados': 8,
    }

    horarios_ordenados = sorted(
        horarios,
        key=lambda x: dict_horarios.get(x.dia_semana, 0),  # type: ignore
    )

    return render(
        request,
        'restau/pages/index.html',
        {'active_setup': active_setup,
         'galeria': galeria,
         'horarios_ordenados': horarios_ordenados,
         },
    )


import argparse
import os
import pathlib
import re
import subprocess
from time import process_time

this_dir = pathlib.Path(__file__).parents[1]
# path to binary
VEDIC = this_dir.joinpath("target/release/vedic")
if os.name == "nt":
    VEDIC = VEDIC.with_suffix(".exe")
VEDIC = VEDIC.resolve()

# Create test cases from tests folder
def get_test_cases_file():
    tests_path = pathlib.Path("tests")
    tests = sorted(pathlib.Path(tests_path).glob("*/*.ved"))
    return tests

# Clear existing test cases
def clear(file, clear_test=False):
    last = True
    with open(file, "r") as f:
        lines = f.readlines()
    with open(file, "w") as f:
        for line in lines:
            if clear_test:
                if line.startswith("# CTE:"):
                    continue
                if line.startswith("# RTE:"):
                    continue
            if len(line.strip()) == 0:
                if last:
                    f.write("\n")
                    last = False
                    continue
                else:
                    last = True
                    continue
            f.write(line)
            last = True

# Generate test cases for file
def generate_test(file):
    output = subprocess.run(
        [VEDIC, file],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    # out = [x.decode("utf-8").strip() for x in output.stdout.split(b"\n")[:-1]]
    err = [x.decode("utf-8").strip() for x in output.stderr.split(b"\n")[:-1]]

    with open(file, "a") as f:
        if output.returncode > 0 and len(err) > 0:
            for x in err:
                if output.returncode == 65:
                    f.write("\n# CTE: " + x)
                elif output.returncode == 70:
                    f.write("\n# RTE: " + x)
            f.write("\n")
        # else:
        #     with open(file, "a") as f:
        #         for x in out:
        #             f.write("\n# expect: "+out)

def main():
    # clear screen
    os.system("cls" if os.name == "nt" else "clear")

    # get test cases files
    test_files = get_test_cases_file()
    # generate test cases for each file
    for test_file in test_files:
        print("Generating test cases for: " + str(test_file))
        clear(test_file, clear_test=True)
        generate_test(test_file)
        clear(test_file)

if __name__ == "__main__":
    main()


import modules.globalvars as globalvars
# F15 - Melihat Jumlah Tiket Pemain

def tiket_pemain():
  """Program melihat jumlah tiket yang dimiliki oleh pemain
  ---
  Parameter : -
  Output : Jumlah tiket yang dimiliki pemain
  ---
  """
  input_user = input("Masukkan username: ")
  tiket_user = [['','',0] for _ in range(globalvars.list_wahana_count)]
  tiket_user_count = 0
  i = 0
  while i < globalvars.pembelian_count:
    current = globalvars.pembelian_tiket[i]
    if current[0] == input_user:
      j = 0
      found = False
      while not found and j < tiket_user_count:
        if tiket_user[j][0] == current[2]:
          found = True
          tiket_user[j][2] += current[3]
        else: j+=1
      if not found:
        j = 0
        wahana_found = False
        wahana_name = ''
        while not wahana_found and j < globalvars.list_wahana_count:
          if globalvars.list_wahana[j][0] == current[2]:
            wahana_name = globalvars.list_wahana[j][1]
            wahana_found = True
          else:
            j += 1
        tiket_user[tiket_user_count] = [current[2], wahana_name, current[3]]
        tiket_user_count += 1
    i+=1

  print("Riwayat: ")
  for i in range(tiket_user_count):
    print('%s|%s|%d' % (tiket_user[i][0], tiket_user[i][1], tiket_user[i][2]))


# reference:https://pyimagesearch.com/2019/09/02/opencv-stream-video-to-web-browser-html-page/
from imutils.video import VideoStream
from flask import Response
from flask import Flask, render_template
import threading
import argparse
import datetime
import imutils
import time
import cv2
from moveNet import lock, get_web
import moveNet

app = Flask(__name__)

# webpage to connect
@app.route('/')
def main():
    print ('camera got clicked!')
    return render_template('camera.html')

@app.route("/video_feed/")
def video_feed():
	# return the response generated along with the specific media
	# type (mime type)
  print("in video_feed")
  return Response(generate(),
		mimetype = "multipart/x-mixed-replace; boundary=frame")

def generate():
    """
    grab global references to the output frame and lock variables
    iterate through frames from the output stream
    """
    #start a thread to run moveNet
    t = threading.Thread(target=get_web)
    t.daemon = True
    t.start()
    while True:
        # wait until the lock is acquired
        with lock:
            # check if the output frame is available, otherwise skip
            if moveNet.outputFrame is None:
                print("None")
                continue
            (flag, encodedImage) = cv2.imencode(".jpg", moveNet.outputFrame)
            if not flag:
                continue
        # yield the output frame in the byte format
        yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
              bytearray(encodedImage) + b'\r\n')

if __name__ == '__main__':
  app.run(debug=True, threaded=True)


from pathlib import Path
import shutil

import yaml

import pardata

pardata.init(
    DATASET_SCHEMA_FILE_URL='datasets.yaml',
    FORMAT_SCHEMA_FILE_URL='formats.yaml',
    LICENSE_SCHEMA_FILE_URL='licenses.yaml'
)

with open('datasets.yaml') as f:
    datasets = yaml.safe_load(f)

# Datasets name are the same from the schema files. This helps ensure that ParData doesn't miss any dataset during the
# test.
assert frozenset(datasets['datasets']) == frozenset(pardata.list_all_datasets())
# Sanity check. In case of all tests being skipped because of a minor error such as in formatting.
assert len(pardata.list_all_datasets()) > 0

for name, versions in pardata.list_all_datasets().items():
    # Versions must be the same from the schema files. This helps ensure that ParData doesn't miss any dataset during
    # the test.
    assert frozenset(datasets['datasets'][name]) == frozenset(versions)
    # Sanity check. In case of all tests being skipped because of a minor error such as in formatting.
    assert len(versions) > 0
    for version in versions:
        # Print dataset info. This also examines relevant portion in license.yaml
        print(pardata.describe_dataset(name, version), end='\n\n')
        pardata.load_dataset(name=name, version=version, subdatasets=None)
        # Delete all loaded data
        shutil.rmtree(Path.home() / '.pardata/data')


import os
from datetime import timedelta
import phonenumbers
import django
from django.utils import timezone

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SelfStorage.settings')
django.setup()

from storage.models import Container, Customer, Reservation, Delivery

def update_db(size, item, time, customer,
              phone_number, address, reservation, delivery=None):
    now_time = timezone.now()
    if not delivery:
        empty_containers = Container.objects.filter(
            available=True,
            size=size
        )
        container = empty_containers.first()

        new_customer = Customer.objects.create(
            name=customer,
            phone_number=phone_number
        )
        normal_number = phonenumbers.parse(
            new_customer.phone_number, "RU"
        )
        if phonenumbers.is_valid_number(normal_number):
            new_customer.pure_phone = normal_number
        new_customer.save()

        new_reservation = Reservation.objects.create(
            customer=new_customer,
            address=address,
            start_date=now_time,
            end_date=now_time + timedelta(days=time)
        )

        container.available = False
        container.filled_by = item
        container.reserved_by = new_customer
        container.reservation = new_reservation
    else:
        container = Container.objects.get(
            reservation=reservation
        )
        new_delivery = Delivery.objects.create(
            date=delivery
        )
        container.delivery = new_delivery
    container.save()


import requests
import json
from datetime import datetime,date
import threading
import time
from proof_of_concept import api_call
from check_novelty import check_novelty

content = []
filename = "travels.txt"
with open(filename) as f:
    content = f.read().splitlines()

class TravelThread(threading.Thread):
    def __init__(self, date, origin, destination, user_list):
        threading.Thread.__init__(self)
        self.date = datetime.strptime(date,'%Y-%m-%d').date()
        self.origin = origin
        self.destination = destination
        self.id_list = []
        self.user_list = user_list
        self.iteration_counter = 0

    def run(self):
        while self.date >= date.today():
            print("{0} : Checking availibility for the trip from {1} to {2} on {3}".format(datetime.now().strftime('%H:%M:%S'),self.origin, self.destination, self.date.strftime("%Y-%m-%d")))
            info = api_call(self.origin, self.destination, self.date.strftime("%Y-%m-%d"))
            self.id_list = check_novelty(self.id_list, info, self.origin, self.destination, self.date, self.user_list, self.iteration_counter)
            self.iteration_counter += 1
            time.sleep(60 * 10)

for travel in content:
    if(len(travel.strip()) > 0):
        info = travel.split(' ')
        names = []
        for name in info[3:]:
            names.append(name)
        info = info[:3]
        info.append(names)
        print(info)
        t = TravelThread(info[0], info[1], info[2], info[3])
        t.start()


import argparse
import os
import time
from src.dependencies.injector import Injector
from src.shared.utils import get_project_root
from src.shared.logger_factory import LoggerFactory

import json
import logging

log = LoggerFactory.logger(__name__, logging.ERROR)

DEFAULT_PATH = str(get_project_root()) + "/src/scripts/config/default_config.yaml"

def ranking(user_name: str, thresh, path=DEFAULT_PATH):

    injector = Injector.get_injector_from_file(path)
    process_module = injector.get_process_module()
    dao_module = injector.get_dao_module()

    local_followers_ranker = process_module.get_ranker("LocalFollowers")
    consumption_ranker = process_module.get_ranker("Consumption")
    production_ranker = process_module.get_ranker()
    ranking_getter = dao_module.get_ranking_getter()
    user_getter = dao_module.get_user_getter()
    user_id = user_getter.get_user_by_screen_name(user_name).id

    # type = 'local_and_global'
    # filename = "./dc2_exp/" + str(type) + '/clusters_local_' + str(thresh) + '_global_50' '/' + str(user_name) + '_clusters_0.json'
    # with open(filename, 'r') as file:
    #     user_lists = json.load(file)
    #     count = len(user_lists)
    #
    # for i in range(count): # Going through each cluster
    #     cluster = user_lists[i]
    #     log.info('Scoring Consumption...')
    #     consumption = consumption_ranker.score_users(cluster)
    #     ranked_consumption = list(sorted(consumption, key=consumption.get, reverse=True))
    #
    #     write_ranking_to_file(user_name, ranked_consumption, i+1, thresh, 'consumption')
    #
    #     log.info('Scoring Production...')
    #     production = production_ranker.score_users(cluster)
    #     ranked_production = list(sorted(production, key=production.get, reverse=True))
    #
    #     write_ranking_to_file(user_name, ranked_production, i+1, thresh, 'production')
    #
    #     log.info('Scoring Local Followers...')
    #     local_followers = local_followers_ranker.score_users(cluster)
    #     log.info(local_followers)
    #     ranked_followers = list(sorted(local_followers, key=local_followers.get, reverse=True))
    #
    #     write_ranking_to_file(user_name, ranked_followers, i+1, thresh, 'followers')

def write_ranking_to_file(user_name, ranking, i, thresh, type):
    path = "./dc2_exp/" + type + "_rankings" + "/local_" + str(thresh) + "_global_50"
    if not os.path.exists(path):
        os.makedirs(path)
    filename = ("./dc2_exp/" + type + "rankings" + "/local_" + str(thresh) + "_global_50" + str("/") + user_name + '_all_cluster_' + str(i) + '.json')

    with open(filename, 'w+') as file:
        json.dump(ranking, file)

if __name__ == "__main__":
    """
    Short script to produce scatter plots
    """
parser = argparse.ArgumentParser(description='Short script to save rankings')

parser.add_argument('-n', '--screen_name', dest='name',
                    help="The screen name of the user to download", required=True)
parser.add_argument('-p', '--path', dest='path', required=False,
                    default=DEFAULT_PATH, help='The path of the config file', type=str)
parser.add_argument('-t', '--thresh', dest='thresh', required=False,
                    default=DEFAULT_PATH, help='thresh', type=float)

args = parser.parse_args()
ranking(args.name, args.thresh)


#Using the max function, which is higher 5 or 23?
x = 5
y = 23
z = max(x,y)
print(z)

#Use the math function to find the square root of 74
#Option 1
import math
x = 74
y = math.sqrt(x)
print(y)

#Option 2
import math as m
x = 74
y = m.sqrt(x)
print(y)

#option 3
from math import sqrt
x = sqrt(74)
print(x)

#Use the easygui to print the message "To be or not to be" titled "What Hamlet elocuted"
#Option 1
import easygui
x = easygui.msgbox("To be or not to be", "What Hamlet elocuted")
print(x)

#Option 2
import easygui as e
e.msgbox("To be or not to be", "What Hamlet elocuted")

#Create a function that add 1 to any number you call
def spam(x):
	x += 1
	return x
print(spam(5))

#Create a function that print the integer value after dividing x by y
def bar(x,y):
	return int(x/y)
print(bar(8, 7))

def closure(a, b, funct):
	return funct(a, b)
print (closure(8, 9, min))

a_list = [1, ["a",["b","c"]], 43, "Too many cooks spoil the broth"] #Create a list
print(len(a_list))#find out how many items are in the list

print(a_list[1][1][1])#To callout "c" from a_list

a_list.append("Foul play") #add string "foul play" to the end of a_list
print(a_list)

a_list.insert(1, "Child's Play" ) #Insert "Child's Play at position 1 of a_list
print(a_list)

a_list.extend([1,2,3]) #unpack the list and add it to the end of a_list
print(a_list)

a_list.pop() #Removes the last item in the list. That would be three in this case
print(a_list)

a_list.pop(3) #Remove the item in position 3 1.e 43
print(a_list)

print(a_list[3]) #Print the third item in the list

print(a_list[2:5]) #Print from the second item to the fifth item i.e. elements in position 2, 3 and 4

print(a_list[:4]) #Print from the beginning item to the fourth item i.e. elements in position 0,1,2,3

print(a_list[1:]) #Print from the first item to the end of the list

print(a_list[-1]) #Print the last item in the list

print(a_list[::-1])  #Print the list backwards, starting from the last item to the first i.e. reverse the list

a_list.remove(2) #Remove the first '2' in the list

a_list[1] = "Sycamore roots" #Change the item in position 1 to "Sycamore roots"
print(a_list)

x = [1,4,5,68,9,45,23,67,33,34]
for items in range(len(x)):
	print(items, x[items])

y = list(range(len(x)))
print(y)

"""Write a function search_list that searches a
list of tuples pair and return the value
associated with the first element of
the pair"""

list_of_tuples = [("AAPL", 96.43), ("IONS", 38), ("GS", 158)]

def search_list(list_of_tuples, value):
	for element in list_of_tuples:
		if element[0] == value.upper():
			return element[1]
	else:
			return("The value you selected is not available")

print(search_list(list_of_tuples, "GS"))

inventory = [("widgets", 100), ("spam", 30), ("eggs", 200)]

def search_list(inventory, value):
	for elements in inventory:
		if elements[0] == value:
			return elements[1]
	else:
		return None
y =search_list(inventory, value = "spam")
print(y)
z= search_list(inventory, value = "hay")
print(z)

dictname = {"AAPL":96.43 , "IONS":38, "GS": 158, "widgets": 100, "spam": 30, "eggs": 200} #Create a dictionary
print(dictname.keys()) #print the keys of the dictionary
print(dictname.values()) #print the values of the dictionary
print(sorted(dictname.keys())) #print the keys in ascending order
print(sorted(dictname.keys(), reverse = True)) #print the keys in descending order
print(sorted(dictname.values())) #print the value in ascendinf order
print(dictname["AAPL"]) #print the vale of AAPL
print(dictname.get("IONS")) #print the value of IONS
dictname["Awarri"] = 89 #Add a new key:value pair to the dictionary
del(dictname["Awarri"]) #delete the key:value pair of Awarri
print(dictname)

import datetime as d
z= d.date(2016, 12, 24)
y = d.date(2019, 11, 21)
print(max(z,y))
print(y - z) #To check the difference between the two days
print((y-z).days) #To print the just the number of days
print(d.date.today()) #To print today's date
print(d.datetime.today()) #To print today's date and time

#To add days, minutes and seconds using the datetime library
zz = (d.datetime.today())
tt = zz+d.timedelta(days= 5)
print(zz, tt)
ww = tt +d.timedelta(minutes = 5, seconds = 10)
print(tt, ww)

#To convert  Date in string to normal date
finale = "01-Apr-03"
finale_obj = d.datetime.strptime(finale, '%d-%b-%y')
print(finale_obj)

#To convert a time string to time
ending = "2:18:24"
Hours, Minutes, Seconds = ending.split(":")
x = d.timedelta(hours = int(Hours), minutes = int(Minutes), seconds = int(Seconds))
print(x)

#To convert a date to string
today = d.datetime.today()
today_now = d.datetime.strftime(today, "%m-%d-%y %H:%M:%S")
print(today, today_now)

# To open a csv file and view its content
data_tuples = list()
with open("sample_data.csv", 'r') as sample_data:
	for line in sample_data:
		data_tuples.append(line.strip().split(" , "))
print(data_tuples[0:10])

#Getting Data Online Using the request library
import requests
response = requests.get("http://www.epicurious.com/search/Tofu+Chili") #Use requests.get to access webpage
print(type(response)) #View the type of response

#To check if our action was successful i.e. 404 means page not found. 404 means page not found
print(response.status_code)

#or
if response.status_code == 200:
	print("Success")
else:
	print("Failure")

#View and decode the content of the webpage
print(response.content.decode("utf-8"))

#Write a function that takes two items, one a url and the other, a string of words that can be found in the url
def find(url, word):
	import requests as req
	page = req.get(url)
	if page.status_code == 200:
		pagecode = page.content.decode("utf-8")
		return pagecode.find(word)
	else:
		return "Your action wasn't successful, check the url again"

print(find(url = "https://en.wikipedia.org/wiki/main_page", word = "Did you know"))

#Text conversion using JSON
import json
data_string = '[{"b": [2, 4], "c": 3.0, "a": "A"}]' #Create a string
python_data = json.loads(data_string)  #Convert to a list using json
print(python_data)

#View the data types of its contents
print(type(data_string), type(python_data))
print(type(python_data[0]), python_data[0])
print(type(python_data[0]["a"]), python_data[0]["a"])
print(type(python_data[0]["b"]), python_data[0]["b"])
print(type(python_data[0]["c"]), python_data[0]["c"])

#Reading a Json
import json
python_data = json.loads(' "Hello" ')
print(python_data)

#Converting a json to a string
datString = json.dumps(python_data)
print(type(datString), datString)

#To access a url using API Key
address="Columbia University, New York, NY"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % (address)  #Add your API Key to the url
response = requests.get(url).json()
print(type(response))

#XML
data_string = """
<Bookstore>
   <Book ISBN="ISBN-13:978-1599620787" Price="15.23" Weight="1.5">
      <Title>New York Deco</Title>
      <Authors>
         <Author Residence="New York City">
            <First_Name>Richard</First_Name>
            <Last_Name>Berenholtz</Last_Name>
         </Author>
      </Authors>
   </Book>
   <Book ISBN="ISBN-13:978-1579128562" Price="15.80">
      <Remark>
      Five Hundred Buildings of New York and over one million other books are available for Amazon Kindle.
      </Remark>
      <Title>Five Hundred Buildings of New York</Title>
      <Authors>
         <Author Residence="Beijing">
            <First_Name>Bill</First_Name>
            <Last_Name>Harris</Last_Name>
         </Author>
         <Author Residence="New York City">
            <First_Name>Jorg</First_Name>
            <Last_Name>Brockmann</Last_Name>
         </Author>
      </Authors>
   </Book>
</Bookstore>
"""

from lxml import etree    #Import the lxml library and use etree
root = etree.XML(data_string) #Use etree to store the XML as a variable
print(root.tag) #Print main xml tag
print(etree.tostring(root, pretty_print = True).decode("utf-8")) #View the XML file as it is

for element in root.iter(): #using an iterator, print all the element in the xml file and its tag
	print(element, element.tag)

for child in root: #View the child of the XML file and its tag
	print(child, child.tag)

for element in root.iter("Author"): #Iterate through the Author element, print the first name and last name
	print(element.find("First_Name").text, element.find("Last_Name").text)

for element in root.findall("Book/Title"): #print the title of book in the title element
	print(element.text)

for element in root.findall("Book/Authors/Author/Last_Name"):  #using findall, return the only the last name of authors
	print(element.text)

print(root.find('Book[@Weight = "1.5"]/Authors/Author/First_Name').text) # Print the first name of the Author whose book weighs exactly 1.5

#Print first and last names of all authors who live in New York City Option 1
for element in root.findall('Book/Authors/Author[@Residence="New York City"]'):
	print(element.find("First_Name").text, element.find("Last_Name").text)

#Option 2
books = root.findall("Book")
for i in range(len(books)):
    print(root.findall('Book/Authors/Author[@Residence="New York City"]/First_Name')[i].text,
          root.findall('Book/Authors/Author[@Residence="New York City"]/Last_Name')[i].text)

#Getting data from the web

#Import the necessary packages
import requests
from bs4 import BeautifulSoup

#use request to access the webpage and parse with lxml
url = "http://www.epicurious.com/search/Tofu+Chili"
response = requests.get(url)
page_soup = BeautifulSoup(response.content, "lxml")
print(page_soup.prettify())   #print the response in a nice format

print(page_soup.find('a'))      #print the first tags that contains 'a'
print(page_soup.find_all('a')) #print all  the tags that contains 'a'

print(page_soup.find("div")) #Return the first div in the url
print(type(page_soup.find("div")))

#To find the first article with article content card
print(page_soup.find('article', class_ = "article-content-card"))

#or
print(page_soup.find('article', {'class' : "article-content-card"}))

def get_recipes(keywords):
	recipe_list = list()
	import requests
	from bs4 import BeautifulSoup
	url = "https://www.epicurious.com/search" + keywords
	response = requests.get(url)
	if not response.status_code == 200:
		return recipe_list
	try:
		results_page = BeautifulSoup(response.content, 'lxml')
		recipes = results_page.find_all('article', class_ = "article-content-card")
		for recipe in recipes:
			recipe_name = recipes.find('a').get_text()
			recipe_url ="https://epicurious.com" + recipe.find('a').get("href")
		print(recipe_name, recipe_url)
	except:
		return recipe_list
	return recipe_list

print(get_recipes(keywords = "lamb chops"))

#Database Basics with Python
#pip Install pymysql first

import pymysql

#Create a connection to your database using your password
db = pymysql.connect("localhost", "root" , "NewPoint",  db= "schooldb")
cursor = db.cursor() #create a cursor

cursor.execute('SHOW tables;') #Use the execute command to run queries
print(cursor.fetchone(), "\n")  #use fetchone to return just one item

cursor.execute("SELECT * FROM student;")
print(cursor.fetchall()) #Use fetchall to return all response from the query

query = """
SELECT course.name,enrolls_in.score FROM student
INNER JOIN enrolls_in ON student.ssn = enrolls_in.ssn
INNER JOIN course ON course.number = enrolls_in.class
WHERE f_name = "JOHN";
"""
cursor.execute(query)
result = cursor.fetchall()

#iterate over the result and get items in it.
print("Course Name", "Score", sep = "\t")
for thing in result:
	print(thing[0], thing[1], sep = "\t")

#Insert a new row into the student table
query = 'INSERT INTO student VALUES ("678-33-2345","Bing","Crossby","2346789870","New York","10001");'
cursor.execute(query)

cursor.execute('SELECT * FROM student;')
print(cursor.fetchall())

db.commit() #To make the new insert permanent on the client side of the database

db.close() #TO close the connection


from typing import List
import numpy as np
import torch
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cluster import KMeans

from difficulty.metrics.forget import first_unforgettable

__all__ = [
    "prediction_depth",
    "supervised_prototypes",
    "self_supervised_prototypes",
]

def _nearest_neighbour(representations: torch.Tensor, query_points: torch.Tensor, labels: torch.Tensor, k: int) -> torch.Tensor:
    knn = KNeighborsClassifier(k)  # use standard Euclidean distance
    representations = representations.reshape(representations.shape[0], -1).detach().cpu().numpy()
    query_points = query_points.reshape(query_points.shape[0], -1).detach().cpu().numpy()
    knn.fit(query_points, labels.detach().cpu().numpy())
    predictions = knn.predict(representations)
    return torch.tensor(predictions).to(dtype=labels.dtype, device=labels.device)

def prediction_depth(intermediate_activations: List[torch.Tensor], consensus_labels: torch.Tensor,
                     query_activations: List[torch.Tensor], query_labels: torch.Tensor, k: int=30) -> np.ndarray:
    """From
    Baldock, R., Maennel, H., and Neyshabur, B. (2021).
    Deep learning through the lens of example difficulty.
    Advances In Neural Information Processing Systems, 34.

    Args:
        intermediate_activations (List[torch.Tensor]): per-example activations in order of layer depth.
            Activations have shape (N, ...) where N is number of examples, and remaining dimensions are flattened
        consensus_labels (torch.Tensor): labels to compare against KNN predictions, with shape (N,)
            In Baldock et al. (2021), these are set to the predictions of a majority of ensembled models.
        query_activations (List[torch.Tensor]): activations for examples used as KNN query points,
            with shape (M, ...). In Baldock et al. (2021), these are the entire training dataset.
        query_labels (torch.Tensor): labels to match to KNN predictions, with shape (M,)
            In Baldock et al. (2021), these are the consensus labels of the query examples.

    Returns:
        torch.Tensor: prediction depth (note: this is NOT backprop-enabled)
    """
    predictions = [_nearest_neighbour(v, q, query_labels, k)
                   for v, q in zip(intermediate_activations, query_activations)]
    # dims L*C where L is intermediate layers, C is classes
    layer_predict = torch.stack(predictions, dim=0)
    match = (layer_predict == consensus_labels.broadcast_to(layer_predict.shape))
    return first_unforgettable(match)

def supervised_prototypes(representations: torch.Tensor, labels: torch.Tensor, norm_order: int=2):
    """From
    Sorscher, B., Geirhos, R., Shekhar, S., Ganguli, S., & Morcos, A. (2022).
    Beyond neural scaling laws: beating power law scaling via data pruning.
    Advances in Neural Information Processing Systems, 35, 19523-19536.

    Args:
        representations (torch.Tensor): per-example activations. In Sorscher et al. (2022),
            this is the embedding space of an ImageNet pre-trained self-supervised model SWaV.
            Activations have shape (N, ...) where N is number of examples, and remaining dimensions are flattened.
        labels (torch.Tensor): true class labels of examples, with shape (N,)
        norm_order (int): type of norm to compute distance over. Defaults to L^2.

    Returns:
        torch.Tensor: distance from examples to label centroids (prototypes)
            in representation space, of shape (N,)
    """
    distances = torch.empty(representations.shape[0], dtype=representations.dtype, device=representations.device)
    for i in torch.unique(labels):
        # compute centroid as mean over representations of examples
        idx = (labels == i)
        embeddings = representations[idx, ...]
        prototype = torch.mean(embeddings, dim=0).broadcast_to(embeddings.shape)
        # for each example with this label, compute distance to correct label centroid
        distances[idx] = torch.linalg.vector_norm(embeddings - prototype, ord=norm_order)
    return distances

def self_supervised_prototypes(representations: torch.Tensor, k: int, max_iter: int=300):
    """From
    Sorscher, B., Geirhos, R., Shekhar, S., Ganguli, S., & Morcos, A. (2022).
    Beyond neural scaling laws: beating power law scaling via data pruning.
    Advances in Neural Information Processing Systems, 35, 19523-19536.

    Args:
        representations (torch.Tensor): per-example activations. In Sorscher et al. (2022),
            this is the embedding space of an ImageNet pre-trained self-supervised model SWaV.
            Activations have shape (N, ...) where N is number of examples, and remaining dimensions are flattened.
        k (int): number of means for k-means clustering.
            Sorscher et al. (2022) recommends any value within an order of magnitude of the true number classes,
            noting that the performance when using this metric for data pruning is not very sensitive to k.

    Returns:
        torch.Tensor: distance from examples to cluster centroids (self-supervised prototypes)
            in representation space, of shape (N,)
    """
    representations = representations.reshape(representations.shape[0], -1)
    kmeans = KMeans(n_clusters=k, max_iter=max_iter)
    kmeans.fit(representations.detach().cpu().numpy())
    distances = kmeans.transform(representations)
    distances = torch.tensor(distances, dtype=representations.dtype, device=representations.device)
    distance_to_nearest_centroid = torch.min(distances, dim=-1).values
    return distance_to_nearest_centroid


import os
import subprocess
import re
import json

class SimilarityRanking(object):
    FASTTEXT = os.path.join(os.getcwd(), "fasttext")
    TITLE_RE_PATTERN = r'(?P<score>1|0.\d+)\s(\d+)\s(?P<title>((\S+\s?)+))'

    def __init__(self):
        pass

    def loadModel(self, model, corpus, nbest):
        return subprocess.Popen((self.FASTTEXT, 'nnSent', model, corpus, nbest),
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)

    def similarityRanking(self, proc, title):
        # print("\n*** Find the similar books for ", title, " ***")
        lines = []
        proc.stdin.write(str.encode(title + '\n'))
        proc.stdin.flush()
        while True:
            line = proc.stdout.readline()
            if line == b'\n':
                break
            else:
                lines.append(line.decode("utf-8").strip())
        return lines

    def terminateProc(self, proc):
        proc.stdin.close()
        proc.terminate()
        # print("***Process terminated***")

    def filterBookTitleRanking(self, list):
        dictList = []
        for l in list:
            match = re.match(self.TITLE_RE_PATTERN, l)
            if match is not None:
                dictList.append(match.groupdict())
        return json.dumps(dictList)

    def printList(self, list):
        dictList = []
        for l in list:
            match = re.match(self.TITLE_RE_PATTERN, l)
            if match is not None:
                dictList.append(match.groupdict())
                # print(match.groupdict())
        print(json.dumps(dictList))

if __name__ == '__main__':
    similarityRanker = SimilarityRanking()
    proc = similarityRanker.loadModel('model.bin', 'titleSet.txt', '30')
    lines = similarityRanker.similarityRanking(proc, "Animal Farm")
    similarityRanker.printList(lines)
    lines = similarityRanker.similarityRanking(proc, "Dracula")
    similarityRanker.printList(lines)
    lines = similarityRanker.similarityRanking(proc, "Frankenstein")
    similarityRanker.printList(lines)
    lines = similarityRanker.similarityRanking(proc, "pigs")
    similarityRanker.printList(lines)
    lines = similarityRanker.similarityRanking(proc, "The Bible")
    similarityRanker.printList(lines)
    similarityRanker.terminateProc(proc)


from django import forms

class form_keranjang(forms.Form):
    jumlah = forms.IntegerField(
        label=False,
        widget=forms.TextInput(
            attrs={
                'id':'jumlah',
                'type':'number',
                'min':'0',
                'class':'input-md form-control',
                'placeholder':'Jumlah',
            }
        ))


import unittest
from flask import Flask
from flask_testing import TestCase
import views

class TestIndex(TestCase):
    render_templates = False
    def setUp(self):
        self.app = Flask(__name__)
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.app = views.app.test_client()
        self.client = self.app.test_client(use_cookie=True)

    def tearDown(self):
        self.app_context.pop()

    def test_get_index(self):
        response = self.app.get('/cadastros')
        self.assertTemplateUsed('consulta_cadastro.html')
        self.assertEqual(response.status_code, 200)

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


import pygame
from ListaDoble import ListaDoble, NodoLista

class CartaVuelo:

    def __init__(self, x:int, y:int, width:int, height:int, vuelos: ListaDoble = None, font = None) -> None:
        self.rect = pygame.Rect(x, y, width, height)
        self.font = font if font else pygame.font.Font(None, 45)
        self.colors = {
            'BLACK': (0, 0, 0),
            'WHITE': (255, 255, 255),
            'GRAY': (200, 200, 200),
            'LIGHT_GRAY': (220, 220, 220),
            'BLUE': (0, 0, 255)
        }

        self.set_vuelos(vuelos)

    def set_vuelos(self, vuelos):
        self.vuelos:ListaDoble = vuelos
        self.first_vuelo()

    def first_vuelo(self):
        """
        Coloca el puntero de nodo_vuelo en el primer vuelo de la lista
        """
        if self.vuelos:
            self.nodo_vuelo: NodoLista = self.vuelos.head
        else:
            self.nodo_vuelo: NodoLista = None

    def last_vuelo(self):
        self.nodo_vuelo = self.vuelos.tail

    def next_vuelo(self):
        self.nodo_vuelo = self.nodo_vuelo.next

    def prev_vuelo(self):
        self.nodo_vuelo = self.nodo_vuelo.prev

    def draw(self, screen) -> None:
        """
        Dibuja la información del vuelo
        """
        pygame.draw.rect(screen, self.colors["BLUE"], self.rect)

        x, y = self.rect.center
        text = self.font.render(
            f"{self.nodo_vuelo.get_id()}/{self.vuelos.n_nodos}", True, self.colors["WHITE"])
        text_rect = text.get_rect(center=(x, y - 250))
        screen.blit(text, text_rect)
        text = self.font.render(
            f"Origen: {self.nodo_vuelo.vuelo.origen}", True, self.colors["WHITE"])
        text_rect = text.get_rect(center=(x, y - 150))
        screen.blit(text, text_rect)
        text = self.font.render(
            f"Destino: {self.nodo_vuelo.vuelo.destino}", True, self.colors["WHITE"])
        text_rect = text.get_rect(center=(x, y - 90))
        screen.blit(text, text_rect)
        text = self.font.render(
            f"Trimestre: {self.nodo_vuelo.vuelo.trimestre}", True, self.colors["WHITE"])
        text_rect = text.get_rect(center=(x, y - 30))
        screen.blit(text, text_rect)
        text = self.font.render(
            f"Compañía: {self.nodo_vuelo.vuelo.compania}", True, self.colors["WHITE"])
        text_rect = text.get_rect(center=(x, y + 30))
        screen.blit(text, text_rect)
        text = self.font.render(
            f"Distancia: {self.nodo_vuelo.vuelo.kilometros}km", True, self.colors["WHITE"])
        text_rect = text.get_rect(center=(x, y + 90))
        screen.blit(text, text_rect)
        text = self.font.render(
            f"Precio: {self.nodo_vuelo.vuelo.precio}€", True, self.colors["WHITE"])
        text_rect = text.get_rect(center=(x, y + 150))

        screen.blit(text, text_rect)


import math

import pandas as pd
import flask
import dash
import dash_core_components as dcc
import dash_html_components as html
import dateutil.parser
from plotly import graph_objs as go

# expects a dataframe with two columns
def donut_chart(dataframe, colors, title, margins = dict(l=10,r=10,t=20,b=0)):

    column_values = list(dataframe.columns.values)
    labels = dataframe[column_values[0]].tolist()
    values = dataframe[column_values[1]].tolist()

    trace = go.Pie(
        labels=labels,
        values=values,
        hole=.5,
        marker={"colors": colors},
        title= {
            "text": title,
            "font": {
                "size": 50
            }
        },
        textinfo="none",
        hoverinfo="value",
        direction="counterclockwise",
        sort=False
    )

    layout = dict(
        sort=True,
        showlegend=False,
        margin=margins,
    )

    return dict(data=[trace], layout=layout)

# expects a dataframe with only one row
def bar_chart(dataframe, colors, title, label_overrides = []):
    if len(dataframe.values) == 0:
        return {"data": [], "layout": []}
    column_values = label_overrides if len(label_overrides) != 0 else list(dataframe.columns.values)
    values = dataframe.values.tolist()[0]
    trace = go.Bar(
        x=column_values,
        y=values,
        marker = {"color": colors[0]}
    )

    layout = dict(
        showlegend=False,
        margin=dict(
            l=25,
            r=0,
            t=0,
            b=35
        ),
        animate=True
    )

    return dict(data=[trace], layout=layout)

# expects x dimension as first column
def stacked_bar_chart(dataframe, colors, title, label_overrides = []):
    if len(dataframe.values) == 0:
        return {"data": [], "layout": []}
    labels = label_overrides if len(label_overrides) != 0 else dataframe[dataframe.columns[0]].tolist()
    dataframe.drop(dataframe.columns[0], axis=1, inplace=True)
    traces = [
        go.Bar(
            x=labels,
            y=dataframe[column].tolist(),
            name=column.replace("_", " ").title() + " Score",
            marker = {"color": colors[index]}) for index,column in enumerate(dataframe.columns)
    ]

    data = traces

    layout = go.Layout(
        barmode='stack',
        margin=dict(
            l=25,
            r=5,
            t=5,
            b=65
        ),
    )

    return dict(data=traces, layout=layout)


# importing libraries
import cv2
import numpy as np

# Create a VideoCapture object and read from input file
cap = cv2.VideoCapture('VID_20200218_174114.mp4')

# Check if camera opened successfully
if not cap.isOpened():
    print("Error opening video  file")

def adjust_gamma(image, gamma=1.0):
    # build a lookup table mapping the pixel values [0, 255] to their adjusted gamma values
    invGamma = 1.0 / gamma
    table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
    # apply gamma correction using the lookup table
    return cv2.LUT(image, table)

# Read until video is completed
while cap.isOpened():
    # Capture frame-by-frame
    ret, frame = cap.read()
    frame = cv2.rotate(frame, cv2.ROTATE_180)
    if ret:
        ad_frame = adjust_gamma(frame, gamma=0.5)
        # Display the resulting frame
        cv2.imshow('Frame', ad_frame)
        # Press Q on keyboard to  exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
    # Break the loop
    else:
        break
# When everything done, release
# the video capture object
cap.release()

# Closes all the frames
cv2.destroyAllWindows()


from torch.utils.data import Dataset
import torch
from collections import namedtuple
Data = namedtuple('Data',('masked','original','loss_weights'))
class BertMaskDataset(Dataset):
    """
    Inputs
        data: the sequences for training, where seq lengths are equal
        n_embed: the number of embeddings (i.e. n_embed=5 will have a sequences with integers 0-4)
    Yields
        masked, original, loss_weights
        where masked follows:
          each item in sequence has a 15% chance of being masked
          an item that is masked has a
            80% chance of being a mask token
            10% chance of being unchanged
            10% chance of being a random other token
    The mask token will be n = n_embed (1 higher than the max in data)
    """
    def __init__(self,data,n_embed):
        self.mask_token = n_embed
        self.n_embed = n_embed
        self.data = torch.tensor(data,dtype=torch.int64)
    def __len__(self):
        return len(self.data)
    def __iter__(self):
        for idx in range(self.__len__()):
            yield self[idx]
    def __getitem__(self,idx):
        seq = self.data[idx]
        masked_inds = torch.rand(len(seq),dtype=torch.float32) < 0.15
        loss_weights = masked_inds.float()
        masked = seq.clone()
        masked[masked_inds] = self._mask(masked[masked_inds])
        return Data(masked,seq,loss_weights)._asdict()#'masked','original','loss_weights'
    def _mask(self,seq):
        other_seq = torch.randint(0,self.n_embed,(len(seq),))
        chance = torch.rand(len(seq),dtype=torch.float32)
        # Mask Token
        ind = chance < 0.8
        seq[ind] = self.mask_token
        # Other Replace
        ind = (chance >= 0.8) * (chance < 0.9)
        seq[ind] = other_seq[ind]
        # Else remain unchanged
        return seq


from .enums import (
    ENUMS,
)
from .extensions.opentelemetry import (
    OpenTelemetryExtension,
)
from .resolvers import (
    TYPES,
)
from .scalars import (
    SCALARS,
)
from .types import (
    Operation,
)
from .unions import (
    UNIONS,
)
from .validations.characters import (
    validate_characters,
)
from .validations.directives import (
    validate_directives,
)
from .validations.query_breadth import (
    QueryBreadthValidation,
)
from .validations.query_depth import (
    QueryDepthValidation,
)
from .validations.variables_validation import (
    variables_check,
)
from ariadne import (
    load_schema_from_path,
    make_executable_schema,
    snake_case_fallback_resolvers,
)
from ariadne.asgi import (
    GraphQL,
)
from ariadne.asgi.handlers import (
    GraphQLHTTPHandler,
)
from ariadne.types import (
    ExtensionList,
)
from dataloaders import (
    apply_context_attrs,
)
from graphql import (
    ASTValidationRule,
    DocumentNode,
)
from newutils import (
    logs as logs_utils,
)
import os
from settings.various import (
    DEBUG,
)
from starlette.requests import (
    Request,
)
import sys
from typing import (
    Any,
)

def _get_operation(data: dict[str, Any]) -> Operation:
    return Operation(
        name=data.get("operationName") or "External (unnamed)",
        query=data.get("query", "").replace("\n", "") or "-",
        variables=data.get("variables") or {},
    )

def _log_request(request: Request, operation: Operation) -> None:
    """
    Sends API operation metadata to cloud logging services for
    analytical purposes.
    """
    logs_utils.cloudwatch_log(
        request,
        f"API: {operation.name} with parameters {operation.variables}. "
        f"Complete query: {operation.query}",
    )

def hook_early_validations() -> None:
    """
    Hook into the execution process

    Warning: This is intended as a temporal workaround while some patches
    arrive upstream.
    """
    ariadne_graphql = sys.modules["ariadne.graphql"]
    original_parse = ariadne_graphql.parse_query

    def before_parse(query: str) -> DocumentNode:
        validate_directives(query)

        return original_parse(query)

    ariadne_graphql.parse_query = before_parse  # type: ignore

class IntegratesAPIHTTPHandler(GraphQLHTTPHandler):
    async def get_context_for_request(self, request: Request) -> Request:
        data: dict[str, Any] = await super().extract_data_from_request(request)
        operation = _get_operation(data)
        context = apply_context_attrs(request)
        setattr(context, "operation", operation)

        return context

    async def extract_data_from_request(
        self, request: Request
    ) -> dict[str, Any]:
        """Hook before the execution process begins"""
        data: dict[str, Any] = await super().extract_data_from_request(request)
        operation = _get_operation(data)

        _log_request(request, operation)

        return data

def get_validation_rules(
    context_value: Any | None,
    _document: DocumentNode,
    _data: dict[Any, Any],
) -> tuple[type[ASTValidationRule], ...]:
    return (  # type: ignore
        QueryBreadthValidation,
        QueryDepthValidation,
        validate_characters(context_value),
        variables_check(context_value),
    )

API_EXTENSIONS: ExtensionList = [
    OpenTelemetryExtension,
]
API_PATH = os.path.dirname(__file__)
SDL_CONTENT = "\n".join(
    [
        load_schema_from_path(os.path.join(API_PATH, module))
        for module in os.listdir(API_PATH)
        if os.path.isdir(os.path.join(API_PATH, module))
    ]
)
SCHEMA = make_executable_schema(
    SDL_CONTENT,
    *ENUMS,
    *SCALARS,
    *TYPES,
    *UNIONS,
    snake_case_fallback_resolvers,
)

class IntegratesAPI(GraphQL):  # pylint: disable=too-few-public-methods
    def __init__(self) -> None:
        super().__init__(
            schema=SCHEMA,
            debug=DEBUG,
            http_handler=IntegratesAPIHTTPHandler(),
            validation_rules=get_validation_rules,
        )
        hook_early_validations()


from flask import Flask, render_template, request
from whackamole import clustering, do_nothing, find_contours, jaccard_index, preprocessing
from whackamole.molenet import mole_net_predict
import cv2 as cv
import numpy as np
import os
import time

app = Flask(__name__)

@app.after_request
def add_header(r):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    r.headers['Cache-Control'] = 'public, max-age=0'
    return r

@app.route('/', methods=['GET'])
def home_page():
    return render_template("index.html")

@app.route('/process', methods=['POST'])
def process():

    base_path = "static/img/result/"
    if not os.path.exists(base_path):
        os.mkdir(base_path)
    temps = os.listdir(base_path)
    if len(temps) > 0:
        os.remove(base_path + temps[0])

    out_filename = "result{}.png".format(time.time())

    op = request.form.get("algorithm")
    lesion_form = request.files["lesion"].read()
    lesion_arr = np.frombuffer(lesion_form, np.uint8)
    lesion = cv.imdecode(lesion_arr, cv.IMREAD_COLOR)
    lesion = cv.resize(lesion, (600, 400))

    mask = None
    if "mask" in request.files and request.files["mask"].filename != "" and op != "PP":
        mask_form = request.files["mask"].read()
        mask_arr = np.frombuffer(mask_form, np.uint8)
        mask = cv.imdecode(mask_arr, cv.IMREAD_GRAYSCALE)
        mask = cv.resize(mask, (600, 400))

    algorithm = do_nothing
    jaccard = -1

    if op == "COCOAW":
        algorithm = find_contours
    elif op == "IDC":
        algorithm = clustering
    elif op == "MN":
        algorithm = mole_net_predict

    start = time.time()
    processed_lesion = preprocessing(lesion)
    predicted_mask = algorithm(processed_lesion)
    end = time.time()

    if mask is not None:
        contours_real, _ = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
        cv.drawContours(lesion, contours_real, -1, (0, 0, 255), 2, 4)
        jaccard = round(jaccard_index(predicted_mask, mask), 3)

    if op != "PP":
        contours_pre, _ = cv.findContours(predicted_mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
        cv.drawContours(lesion, contours_pre, -1, (255, 0, 0), 2, 4)
        cv.imwrite(base_path + out_filename, lesion)
    else:
        cv.imwrite(base_path + out_filename, processed_lesion)

    return render_template("result.html",
                           image_filename=out_filename,
                           processing_time=int(end - start),
                           jaccard=jaccard,
                           prediction=(op != "PP"),
                           masked=(mask is not None))

if __name__ == '__main__':
    app.run('127.0.0.1', port=8080)