# Different algs for merge sort:
#  First method combines the whole divide/conquer/combine process in one
#  one function that calls itself recursively until sort is completed.
#  Second method breaks this process down into separate functions,
#  merge_sort_v2 and merge_v2. merge_sort splits given list and recursively sorts them.
#  If the lists are singletons, you've got the base case. Another function,
#  merge_v2 is used for merging the sorted sublists and returning the resulting
#  sorted list.

# METHOD ONE:

count = 0

def merge_sort(sort_list):
    if len(sort_list) > 1:
        mid = len(sort_list) // 2
        left_half = sort_list[:mid]
        right_half = sort_list[mid:]
        merge_sort(left_half)
        merge_sort(right_half)

        i = 0
        j = 0
        k = 0
        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                sort_list[k] = left_half[i]
                i = i + 1
            else:
                sort_list[k] = right_half[j]
                j = j + 1
            k = k + 1

        while i < len(left_half):
            sort_list[k] = left_half[i]
            i = i + 1
            k = k + 1

        while j < len(right_half):
            sort_list[k] = right_half[j]
            j = j + 1
            k = k + 1

    global count
    count += 1
    if len(sort_list) == len(lst):
        # print("Sorted: ", sort_list)
        print("Number of comparisons, method one: ", count)
        return lst

# Driver code for testing
lst = [7, 9393, 4, 23, 1, 88, 34, 29, 17, 52]
sorted_lst = merge_sort(lst)
print('Sorted with method one: ', sorted_lst)

#####################################################################

# METHOD TWO:

def merge_V2(sort_list, p, q, r):
    # Initialize vars for length of the first and second sublists
    n1 = q - p + 1
    n2 = r - q

    # Create temporary arrays
    l = [0] * n1
    r = [0] * n2

    # Copy arr[1..q] to temp array l[]
    for i in range(0, n1):
        l[i] = sort_list[p + i]

    # Copy arr[q+1..r] to r[]
    for j in range(0, n2):
        r[j] = sort_list[q + 1 + j]

    # Merge the temp arrays back into arr[l..r]
    i = 0  # Initial index of first subarray
    j = 0  # Initial index of second subarray
    k = p  # Initial index of merged subarray

    while i < n1 and j < n2:
        if l[i] <= r[j]:
            sort_list[k] = l[i]
            i += 1
        else:
            sort_list[k] = r[j]
            j += 1
        k += 1

    # Copy the remaining elements of l[], if there
    # are any
    while i < n1:
        sort_list[k] = l[i]
        i += 1
        k += 1

    # Copy the remaining elements of r[], if there
    # are any
    while j < n2:
        sort_list[k] = r[j]
        j += 1
        k += 1

def merge_sort_V2(sort_list, p, r):
    if p < r:
        # Same as (l+r)/2, but avoids overflow for
        # large l and h
        m = int((p + (r - 1)) / 2)
        # Sort first and second halves
        merge_sort_V2(sort_list, p, m)
        merge_sort_V2(sort_list, m + 1, r)
        merge_V2(sort_list, p, m, r)

# Driver code for testing
lst2 = [12, 11, 13, 5, 6, 7]
n = len(lst2)
merge_sort_V2(lst2, 0, n - 1)
print("Sorted with method two: ", lst2)


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

# # IST 718: Big Data Analytics
#
# - Professor: Willard Williamson <wewillia@syr.edu>
# - Faculty Assistant: Palaniappan Muthukkaruppan
# ## General instructions:
#
# - You are welcome to discuss the problems with your classmates but __you are not allowed to copy any part of your answers from your classmates.  Short code snippets are allowed from the internet.  Any code is allowed from the class text books or class provided code.__
# - Please do not change the file names. The FAs and the professor use these names to grade your homework.
# - Remove or comment out code that contains `raise NotImplementedError`. This is mainly to make the `assert` statement fail if nothing is submitted.
# - The tests shown in some cells (i.e., `assert` and `np.testing.` statements) are used to grade your answers. **However, the professor and FAs will use __additional__ test for your answer. Think about cases where your code should run even if it passess all the tests you see.**
# - Before submitting your work through Blackboard, remember to save and press `Validate` (or go to
# `Kernel`$\rightarrow$`Restart and Run All`).

# ## Math (50 pts)

# ## Probability (40 pts)

# The cell below creates a string named pi out to one million decimal places.  Note that this cell may take a few minutes to run to completion.

# In[4]:

import numpy as np
num_pi_digits = 1000000

try:
    # import version included with old SymPy
    from sympy.mpmath import mp
except ImportError:
    # import newer version
    from mpmath import mp
mp.dps = num_pi_digits  # set number of digits

# convert pi to a string
pi = mp.nstr(mp.pi, num_pi_digits)

# print to 100 decimal places
print(pi[:100])

# remove the decimal point
pi = pi.replace(".", "")

# **Question 3.1 (5 pts)** Compute and print the marginal probabilites $P(X_i)$ where X = 0, 1, 2, 3, ..., 9 across all numbers (before and after the decimal point).  Your answer should print 10 marginal probabilities.

# In[31]:

# Your answer here
counts = [0] * 10 #create an empty list to store the counts
for num in pi:
    counts[int(num)] += 1

probs = []
for count in counts:
    probs.append(str(count/len(pi)))

#print(' '.join(probs))

for i in range(10):
    print("The probability of", i, "is:", float(probs[i])*100,"%")

# **Question 3.2 (5 pts)** What kind of distribution do the probabilities in 3.1 suggest?

# In[15]:

# your answer here
#The distribution of the numbers are pretty even, with each digits appearing around 10% of the time.

# **Question 3.3 (10 pts)** Compute the joint probability $P(x_i = 1, x_i-1 = 3)$.  Based on the result, what can you say about the independence relationship?

# In[32]:

# your answer here
#joint probability is AND

jointCount = 0

for i in range(1, len(pi)):
    if pi[i] == '1' and (pi[i-1]) == '3':
        jointCount +=1

print(jointCount/(len(pi)-1)*100,"%")

#based on the result, the independent relationship is very rare, occuring around 1% of the time.

# **Question 3.4 (10 pts)** Compute the conditional probability $P(x_i = 3 | x_i-1 = 1)$.

# In[33]:

# your answer here
denominator = 0
numerator = 0

for i in range(1, len(pi)):
    if pi[i-1] == '1':
        denominator += 1
        if pi[i] == '3':
            numerator +=1

print((numerator/denominator)*100,"%")

# **Question 3.5 (10 pts)**
# Assuming that the decimal point is removed from pi, let A be the pi values at indices 1-1000, let B be the pi values at indices 2-1001, let C be the pi values at indices 3-1002.  Compute the sample covariance matrix for A, B, C against each other. without using the built-in command (i.e. code it yourself). The result should be a 3x3 matrix.

# In[9]:

# Your answer here
#Cov(X, Y) = Σ ( Xi - X ) ( Yi - Y ) / N = Σ xiyi / N
# without using build in command such as NumPy
def covariance(x,y):
    u = sum(x)/len(x)
    v = sum(y)/len(y)
    E = 0
    for i in range(len(x)):
        E += (x[i] - u) * (y[i] - v)
    return E/(len(x)-1)

#create the three arrays
A = [int(i) for i in pi[1:1000]]
B = [int(i) for i in pi[2:1001]]
C = [int(i) for i in pi[3:1002]]

#3x1000 matrix
stack = [A, B, C]
#create empty matrix
samp_cov_matrix = []

for X in stack:
    row_cov = []
    for Y in stack:
        row_cov.append(covariance(X,Y))
    samp_cov_matrix.append(row_cov)

print(samp_cov_matrix)

# In[10]:

# with NumPy, much easier
arrayA = np.array(A)
arrayB = np.array(B)
arrayC = np.array(C)

x = np.vstack([arrayA,arrayB,arrayC])
samp_cov_matrix = np.cov(x)

print("samp_cov_matrix:\n")
print(samp_cov_matrix)

# ## Linear Algebra (10 pts)

# **Question 3.5 (5 pts)** Compute the following matrix multiplications
# $$
# \quad
# \begin{bmatrix}
# 1 \\
# 2 \\
# 3
# \end{bmatrix}
# \quad
# *
# \quad
# \begin{bmatrix}
# 4 & 5 & 6
# \end{bmatrix}
# \quad
# $$

# In[70]:

# your answer here
# 3x1 matrix
X = np.array([[1],[2],[3]])
# 1x3 matrix
Y = np.array([[4,5,6]])

print(X.dot(Y))

# **Question 3.6 (5 pts)** Compute the following matrix multiplications
#
# $$
# \quad
# \begin{bmatrix}
# 1 & 2 \\
# 3 & 4 \\
# 6 & 0 \\
# \end{bmatrix}
# \quad
# *
# \quad
# \begin{bmatrix}
# 2 & 5 & 3\\
# 2 & 5 & 1
# \end{bmatrix}
# \quad
# *
# \quad
# \begin{bmatrix}
# 1\\
# 2\\
# 1
# \end{bmatrix}
# \quad
# $$

# In[14]:

# your answer here
#3x2 matrix
X = np.array(
    [[1,2],
     [3,4],
     [6,0]])
# 2x3 matrix
Y = np.array(
    [[2,5,3],
     [2,5,1]])
# 3x1 matrix
Z = np.array(
    [[1],
     [2],
     [1]])

print(X.dot(Y).dot(Z))

#[41]
#[97]
#[90]

# **Extra Credit (5 pts)**  This question is optional.  If you choose to answer this question, you will earn 5 extra credit points.  If you choose not to answer this question, no points will be deducted from your score.  Solve the following equation for $c$ symbolically using the python sympy package.  Convert the solved symbolic solution to a latex format (this can be done with a pyton call), then populate the solution cell with the resulting latex code so that your solution shows up symbolically similar the equation below.
#
# $$c g - c h + e \left(a + 1\right)^{b} - \frac{d \left(\left(a + 1\right)^{b} - 1\right)}{a} + \frac{f \left(\left(a + 1\right)^{b} - 1\right)}{a} = 0$$

# In[ ]:

# your code here

# Your solved equation in latex here:
#


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name="index"),
    path('index/', views.index, name="index"),
    path('libros/', views.libros, name="libros"),
    path('crear_libro/', views.crear_libro, name="crear_libro"),
    path('crear_lector/', views.crear_lector, name="crear_lector"),
    path('lectores/', views.lectores, name="lectores"),
    path('crear_autor/', views.crear_autor, name="crear_autor"),
    path('autores/', views.autores, name="autores"),
    path('prestamos/', views.prestamos, name="prestamos"),
    # path('busquedaLibro/',views.busquedaLibro, name="buscar"),
    path('busquedaLibro/',views.busquedaLibro, name="busquedaLibro"),
    path('busquedaLibro/buscar/',views.buscar, name="buscar")
]


from django.urls import path
from django.conf.urls import include
from django.conf import settings
from django.conf.urls.static import static
from . import views
from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token, refresh_jwt_token
from rest_framework_swagger.views import get_swagger_view

app_name = 'api'
urlpatterns = [
    # ex: /admin/
    path('manage/', views.ManageIndex, name='manage-index'),
    path('manage/events/', views.ManageEvents, name='manage-events'),
    path('manage/events/<int:event_id>/', views.EventDetail, name='event-detail'),
    path('manage/events/<int:event_id>/update/', views.EventUpdate, name='event-update'),
    path('manage/users/', views.ManageUsers, name='manage-users'),
    path('manage/users/<int:user_id>/', views.UserDetail, name='user-detail'),
    path('manage/users/<int:user_id>/update/', views.UserUpdate, name='user-update'),
    path('manage/users/<int:user_id>/message/', views.CreateNotif, name='notif-create'),
    path('manage/users/<int:user_id>/message/send', views.SendNotif, name='notif-send'),
    path('api/', get_swagger_view(title="EventFinder API")),
    path('api/test/', views.TestAPIView.as_view(), name='test-api'),
    path('api/userlist/', views.ListUsers.as_view(), name='list-users'),
    path('api/createuser/', views.CreateUser.as_view(), name='create-user'),
    path('api/getmyinfo/', views.GetMyInfo.as_view(), name='get-my-info'),
    path('api/activateuser/', views.ActivateUser.as_view(), name='activate-user'),
    path('api/getpastevents/', views.GetPastEvents.as_view(), name='get-past-events'),
    path('api/getfutureevents/', views.GetFutureEvents.as_view(), name='get-future-events'),
    path('api/getmyevents/', views.GetMyEvents.as_view(), name='get-my-events'),
    path('api/personslist/', views.ListPersons.as_view(), name='list-persons'),
    path('api/createpersonaccount/', views.CreatePersonAccount.as_view(), name='create-person-account'),
    path('api/updatepersonaccount/', views.UpdatePersonAccount.as_view(), name='update-person-account'),
	path('api/setprofilepicture/', views.SetProfilePicture.as_view(), name='set-profile-picture'),
    path('api/updatepassword/', views.UpdatePassword.as_view(), name='update-password'),
    path('api/updateevent/', views.UpdateEvent.as_view(), name='update-event'),
    path('api/rsvplist/', views.GetRsvpList.as_view(), name='get-rsvps'),
    path('api/creatersvp/', views.CreateRsvp.as_view(), name='create-rsvp'),
    path('api/updatersvp/', views.UpdateRsvp.as_view(), name='update-rsvp'),
	path('api/sendreport/', views.SendReport.as_view(), name='send-report'),
	path('api/token/login/', obtain_jwt_token),
    path('api/token/validate/', verify_jwt_token),
    path('api/token/refresh/', refresh_jwt_token),
    path('api/weblogin/', include('rest_framework.urls')),
    path('api/getperson/<int:id>/', views.GetPerson.as_view(), name='get-person-by-id'),
    path('api/createevent/', views.CreateEvent.as_view(), name='create-event'),
    path('api/getrecentevents/<int:count>/', views.GetRecentEvents.as_view(), name='getrecentevents'),
	path('api/getnotifications/', views.GetNotifications.as_view(), name='getnotifications'),
	path('api/createconversation/', views.CreateConversation.as_view(), name='create-coversation'),
	path('api/createmessage/', views.CreateChatMessage.as_view(), name='create-chat-message')
]

if settings.DEBUG:
	urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import numpy as np
import math

def translate_scale_hyperrectangle(x, x_0, size):
    """
    Perform translation (to origin) and then scaling on a hyperrectangle. This is used
    to translate a mesh within a hyperrectangle to the origin and scale it to
    the interval [-1, 1] in 1-D, and for higher dimensions analogously.
    :param x: the mesh to be transformed
    :param x_0: the center of the hyperrectangle
    :param size: the size of the rectangle in each dimension
    :return: the transformed mesh and the used tranlslation and scale vectors.
    """
    scale = [2 * math.sqrt(len(size)) / (size_dim * len(size)) for size_dim in size]
    translate = [-x_0_dim for x_0_dim in x_0]
    return translate_scale_with(x, translate, scale), translate, scale

def translate_scale_with(x, translate, scale):
    """
    Perform abitrary translation and scaling on a mesh (in this order).
    :param x: the mesh
    :param translate: translation vector
    :param scale: scale vector
    :return: the transformed mesh
    """
    assert (x.shape[0] == len(scale) == len(translate))
    dim = len(scale)
    unit_x = np.empty(x.shape)
    for i in range(dim):
        unit_x[i, :] = (x[i, :] + translate[i]) * scale[i]
    assert (np.all(np.abs(unit_x) <= math.sqrt(2) / 2 + 1e7))
    return unit_x

def get_center_extents(mesh):
    """
    For a given set of points this returns a hyperrectangle that contains all points
    :param mesh: the mesh
    :return: the hyperrectangle, given through a center and extents in each dimension
    """
    dim = mesh.shape[0]
    xmax = [mesh[i, :].max() for i in range(dim)]
    xmin = [mesh[i, :].min() for i in range(dim)]
    extents = [xmax[i] - xmin[i] for i in range(dim)]
    center = [xmin[i] + extents[i] / 2 for i in range(dim)]
    return center, extents

def cart2polar(mesh):
    """
    This performs coordinate transformation in 1,2 and 3-D from cartesian
    coordinates to polar (spherical) coordinates. Convention ISO 80000-2:2009
    is used for spherical coordinates.
    Note that this will copy the mesh even for the trivial 1-D case.
    :param mesh: the mesh
    :return: the mesh in polar (spherical) coordinates
    """
    polarmesh = np.empty(mesh.shape)
    if mesh.shape[0] == 1:
        polarmesh[0, :] = mesh[0, :]
    elif mesh.shape[0] == 2:
        polarmesh[0, :] = np.sqrt(mesh[0, :]**2 + mesh[1, :]**2)
        polarmesh[1, :] = np.arctan2(mesh[1, :], mesh[0, :])
    elif mesh.shape[0] == 3:
        polarmesh[0, :] = np.sqrt(mesh[0, :]**2 + mesh[1, :]**2 + mesh[2, :]**2)
        polarmesh[1, :] = np.arccos(np.nan_to_num(mesh[2, :] / polarmesh[0, :]))
        polarmesh[2, :] = np.arctan2(mesh[1, :], mesh[0, :])
    else:
        raise AssertionError("Mesh has invalid number of dimensions: " + str(mesh.shape[0]))
    return polarmesh


#!/usr/bin/env python3

from packaging.version import Version, parse
from requests import post, get
from yaml import load, dump
from functools import cmp_to_key
from libversion import version_compare
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper
import json
import re
import subprocess
import xml.etree.ElementTree as ET

def getLatestPylsVersion():
    url = 'https://pvsc.blob.core.windows.net/python-language-server-stable?restype=container&comp=list&prefix=Python-Language-Server-linux-x64'
    r = get(url)
    xml = ET.fromstring(r.text)
    p = re.compile(r'^Python-Language-Server-linux-x64\.(?P<version>.*)\.nupkg$')
    def getVersion(e):
        m = p.match(e.text)
        return m.group('version')
    versions = [getVersion(x) for x in xml.findall(".//Blob/Name")]
    versions.sort(key=cmp_to_key(version_compare), reverse=True)
    return versions[0]

def getLatestPyls():
    version = getLatestPylsVersion()
    url = f'https://pvsc.azureedge.net/python-language-server-stable/Python-Language-Server-linux-x64.{version}.nupkg'
    sha256 = prefetchUrl(url)
    return version, url, sha256

def getLatestVersionInfo(publisher, name):
    url = 'https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery'
    data = { 'assetTypes': None
           , 'filters': [
               { 'criteria': [{'filterType': 7, 'value': '{}.{}'.format(publisher,name)}]
               , 'direction': 2
               , 'pageSize': 100
               , 'pageNumber': 1
               , 'sortBy': 0
               , 'sortOrder': 0
               , 'pagingToken': None
               }
             ]
           , 'flags': 103
           }
    headers = { 'Content-type': 'application/json', 'Accept': 'application/json;api-version=6.1-preview.1;excludeUrls=true' }
    r = post(url, data=json.dumps(data), headers=headers)
    versions = r.json()['results'][0]['extensions'][0]['versions']
    latest_version = sorted(versions, key=lambda x: parse(x['version']), reverse=True)[0]
    ver = latest_version['version']
    #files = latest_version['files']
    #vsix = list(filter(lambda x: x['assetType'] == 'Microsoft.VisualStudio.Services.VSIXPackage', files))[0]
    #url = vsix['source']
    #return ver, url
    return ver

def prefetchUrl(url):
    args = ["nix-prefetch-url", url]
    o = subprocess.check_output(args).decode("utf-8")
    return o.strip()

def formatUrl(name, publisher, version):
    return f"https://{publisher}.gallery.vsassets.io/_apis/public/gallery/publisher/{publisher}/extension/{name}/{version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage"

def getExtension(name, publisher):
    ver = getLatestVersionInfo(publisher, name)
    url = formatUrl(name, publisher, ver)
    print(url)
    sha256 = prefetchUrl(url)
    return {'name': name, 'publisher': publisher, 'version': ver, 'sha256': sha256}

def main():
    version, url, sha256 = getLatestPyls()
    with open('rust-analyzer/rust-analyzer.json', 'w+') as src:
        json.dump(getExtension(name='rust-analyzer', publisher='rust-lang'), src, indent=4, sort_keys=True)
    with open('python/pyls.json', 'w+') as pyls:
        json.dump({'version': version, 'url': url, 'sha256': sha256}, pyls, indent=4, sort_keys=True)
    with open('python/vscode-python.json', 'w+') as vsc:
        json.dump(getExtension(name='python', publisher='ms-python'), vsc, indent=4, sort_keys=True)
    with open('extensions.yaml') as f:
        exts = load(f.read(), Loader=Loader)
        result = [getExtension(name=ext['name'], publisher=ext['publisher']) for ext in exts]
        with open('extensions.json', 'w+') as target:
            json.dump(result, target, indent=4, sort_keys=True)

if __name__ == '__main__':
    main()


"""
The full content is this module is copied from xarray.plot.utils.py. Unused
parts are removed, so this module only contains about a third of the original's
content.

Additionally, _easy_facetgrid has been copied from xarray.plot.facetgrid.

The reason is that these functions are all private methods. Hence, Xarray
provides no guarantees on breaking changes.

We heavily discourage editing this file. Any update should only consist of
copying updated parts of the xarray module.

Some minor edits are necessary. These are marked by an comment with "EDIT:".

Xarray is licensed under Apache License 2.0:
https://github.com/pydata/xarray/blob/main/LICENSE
"""
from __future__ import annotations

import importlib
import textwrap
from collections.abc import Callable, Hashable, Iterable, Mapping
from datetime import datetime
from inspect import getfullargspec
from typing import TYPE_CHECKING, Any, Literal, TypeVar, Union

import numpy as np
from xarray import DataArray, Dataset
from xarray.plot.facetgrid import FacetGrid

# EDIT: added these here
AspectOptions = Union[Literal["auto", "equal"], float, None]
ScaleOptions = Literal["linear", "symlog", "log", "logit", None]
T_DataArrayOrSet = TypeVar("T_DataArrayOrSet", bound=Union["Dataset", "DataArray"])
nc_time_axis_available = importlib.util.find_spec("nc_time_axis") is not None

try:
    import cftime
except ImportError:
    cftime = None

if TYPE_CHECKING:
    from matplotlib.axes import Axes
    from numpy.typing import ArrayLike

    try:
        import matplotlib.pyplot as plt
    except ImportError:
        plt: Any = None  # type: ignore

ROBUST_PERCENTILE = 2.0

__all__ = [
    "_add_colorbar",
    "_ensure_plottable",
    "_process_cmap_cbar_kwargs",
    "_update_axes",
    "get_axis",
    "label_from_attrs",
    "_easy_facetgrid",
]

def _determine_extend(calc_data, vmin, vmax):
    extend_min = calc_data.min() < vmin
    extend_max = calc_data.max() > vmax
    if extend_min and extend_max:
        return "both"
    elif extend_min:
        return "min"
    elif extend_max:
        return "max"
    else:
        return "neither"

def _build_discrete_cmap(cmap, levels, extend, filled):
    """
    Build a discrete colormap and normalization of the data.
    """
    import matplotlib as mpl

    if len(levels) == 1:
        levels = [levels[0], levels[0]]

    if not filled:
        # non-filled contour plots
        extend = "max"

    if extend == "both":
        ext_n = 2
    elif extend in ["min", "max"]:
        ext_n = 1
    else:
        ext_n = 0

    n_colors = len(levels) + ext_n - 1
    pal = _color_palette(cmap, n_colors)

    new_cmap, cnorm = mpl.colors.from_levels_and_colors(levels, pal, extend=extend)
    # copy the old cmap name, for easier testing
    new_cmap.name = getattr(cmap, "name", cmap)

    # copy colors to use for bad, under, and over values in case they have been
    # set to non-default values
    try:
        # matplotlib<3.2 only uses bad color for masked values
        bad = cmap(np.ma.masked_invalid([np.nan]))[0]
    except TypeError:
        # cmap was a str or list rather than a color-map object, so there are
        # no bad, under or over values to check or copy
        pass
    else:
        under = cmap(-np.inf)
        over = cmap(np.inf)

        new_cmap.set_bad(bad)

        # Only update under and over if they were explicitly changed by the user
        # (i.e. are different from the lowest or highest values in cmap). Otherwise
        # leave unchanged so new_cmap uses its default values (its own lowest and
        # highest values).
        if under != cmap(0):
            new_cmap.set_under(under)
        if over != cmap(cmap.N - 1):
            new_cmap.set_over(over)

    return new_cmap, cnorm

def _color_palette(cmap, n_colors):
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap

    colors_i = np.linspace(0, 1.0, n_colors)
    if isinstance(cmap, (list, tuple)):
        # we have a list of colors
        cmap = ListedColormap(cmap, N=n_colors)
        pal = cmap(colors_i)
    elif isinstance(cmap, str):
        # we have some sort of named palette
        try:
            # is this a matplotlib cmap?
            cmap = plt.get_cmap(cmap)
            pal = cmap(colors_i)
        except ValueError:
            # ValueError happens when mpl doesn't like a colormap, try seaborn
            try:
                from seaborn import color_palette

                pal = color_palette(cmap, n_colors=n_colors)
            except (ValueError, ImportError):
                # or maybe we just got a single color as a string
                cmap = ListedColormap([cmap], N=n_colors)
                pal = cmap(colors_i)
    else:
        # cmap better be a LinearSegmentedColormap (e.g. viridis)
        pal = cmap(colors_i)

    return pal

# _determine_cmap_params is adapted from Seaborn:
# https://github.com/mwaskom/seaborn/blob/v0.6/seaborn/matrix.py#L158
# Used under the terms of Seaborn's license, see licenses/SEABORN_LICENSE.

def _determine_cmap_params(
    plot_data,
    vmin=None,
    vmax=None,
    cmap=None,
    center=None,
    robust=False,
    extend=None,
    levels=None,
    filled=True,
    norm=None,
    _is_facetgrid=False,
):
    """
    Use some heuristics to set good defaults for colorbar and range.

    Parameters
    ----------
    plot_data : Numpy array
        Doesn't handle xarray objects

    Returns
    -------
    cmap_params : dict
        Use depends on the type of the plotting function
    """
    import matplotlib as mpl

    if isinstance(levels, Iterable):
        levels = sorted(levels)

    calc_data = np.ravel(plot_data[np.isfinite(plot_data)])

    # Handle all-NaN input data gracefully
    if calc_data.size == 0:
        # Arbitrary default for when all values are NaN
        calc_data = np.array(0.0)

    # Setting center=False prevents a divergent cmap
    possibly_divergent = center is not False

    # Set center to 0 so math below makes sense but remember its state
    center_is_none = False
    if center is None:
        center = 0
        center_is_none = True

    # Setting both vmin and vmax prevents a divergent cmap
    if (vmin is not None) and (vmax is not None):
        possibly_divergent = False

    # Setting vmin or vmax implies linspaced levels
    user_minmax = (vmin is not None) or (vmax is not None)

    # vlim might be computed below
    vlim = None

    # save state; needed later
    vmin_was_none = vmin is None
    vmax_was_none = vmax is None

    if vmin is None:
        if robust:
            vmin = np.percentile(calc_data, ROBUST_PERCENTILE)
        else:
            vmin = calc_data.min()
    elif possibly_divergent:
        vlim = abs(vmin - center)

    if vmax is None:
        if robust:
            vmax = np.percentile(calc_data, 100 - ROBUST_PERCENTILE)
        else:
            vmax = calc_data.max()
    elif possibly_divergent:
        vlim = abs(vmax - center)

    if possibly_divergent:
        levels_are_divergent = (
            isinstance(levels, Iterable) and levels[0] * levels[-1] < 0
        )
        # kwargs not specific about divergent or not: infer defaults from data
        divergent = (
            ((vmin < 0) and (vmax > 0)) or not center_is_none or levels_are_divergent
        )
    else:
        divergent = False

    # A divergent map should be symmetric around the center value
    if divergent:
        if vlim is None:
            vlim = max(abs(vmin - center), abs(vmax - center))
        vmin, vmax = -vlim, vlim

    # Now add in the centering value and set the limits
    vmin += center
    vmax += center

    # now check norm and harmonize with vmin, vmax
    if norm is not None:
        if norm.vmin is None:
            norm.vmin = vmin
        else:
            if not vmin_was_none and vmin != norm.vmin:
                raise ValueError("Cannot supply vmin and a norm with a different vmin.")
            vmin = norm.vmin

        if norm.vmax is None:
            norm.vmax = vmax
        else:
            if not vmax_was_none and vmax != norm.vmax:
                raise ValueError("Cannot supply vmax and a norm with a different vmax.")
            vmax = norm.vmax

    # if BoundaryNorm, then set levels
    if isinstance(norm, mpl.colors.BoundaryNorm):
        levels = norm.boundaries

    # Choose default colormaps if not provided
    if cmap is None:
        # EDIT: replaced OPTIONS
        if divergent:
            cmap = "RdBu_r"
        else:
            cmap = "viridis"

    # Handle discrete levels
    if levels is not None:
        # EDIT: replaced is_scalar(levels) by np.issubdtype(type(levels), np.integer)
        # xarray uses a relatelively complicated is_scalar function here. For
        # the purposes of plotting, checking for an integer should do.
        if np.issubdtype(type(levels), np.integer):
            if user_minmax:
                levels = np.linspace(vmin, vmax, levels)
            elif levels == 1:
                levels = np.asarray([(vmin + vmax) / 2])
            else:
                # N in MaxNLocator refers to bins, not ticks
                ticker = mpl.ticker.MaxNLocator(levels - 1)
                levels = ticker.tick_values(vmin, vmax)
        vmin, vmax = levels[0], levels[-1]

    # GH3734
    if vmin == vmax:
        vmin, vmax = mpl.ticker.LinearLocator(2).tick_values(vmin, vmax)

    if extend is None:
        extend = _determine_extend(calc_data, vmin, vmax)

    if (levels is not None) and (not isinstance(norm, mpl.colors.BoundaryNorm)):
        cmap, newnorm = _build_discrete_cmap(cmap, levels, extend, filled)
        norm = newnorm if norm is None else norm

    # vmin & vmax needs to be None if norm is passed
    # TODO: always return a norm with vmin and vmax
    if norm is not None:
        vmin = None
        vmax = None

    return dict(
        vmin=vmin, vmax=vmax, cmap=cmap, extend=extend, levels=levels, norm=norm
    )

def get_axis(
    figsize: Iterable[float] | None = None,
    size: float | None = None,
    aspect: AspectOptions = None,
    ax: Axes | None = None,
    **subplot_kws: Any,
) -> Axes:
    try:
        import matplotlib as mpl
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError("matplotlib is required for plot.utils.get_axis")

    if figsize is not None:
        if ax is not None:
            raise ValueError("cannot provide both `figsize` and `ax` arguments")
        if size is not None:
            raise ValueError("cannot provide both `figsize` and `size` arguments")
        _, ax = plt.subplots(figsize=figsize, subplot_kw=subplot_kws)
        return ax

    if size is not None:
        if ax is not None:
            raise ValueError("cannot provide both `size` and `ax` arguments")
        if aspect is None or aspect == "auto":
            width, height = mpl.rcParams["figure.figsize"]
            faspect = width / height
        elif aspect == "equal":
            faspect = 1
        else:
            faspect = aspect
        figsize = (size * faspect, size)
        _, ax = plt.subplots(figsize=figsize, subplot_kw=subplot_kws)
        return ax

    if aspect is not None:
        raise ValueError("cannot provide `aspect` argument without `size`")

    if subplot_kws and ax is not None:
        raise ValueError("cannot use subplot_kws with existing ax")

    if ax is None:
        ax = _maybe_gca(**subplot_kws)

    return ax

def _maybe_gca(**subplot_kws: Any) -> Axes:
    import matplotlib.pyplot as plt

    # can call gcf unconditionally: either it exists or would be created by plt.axes
    f = plt.gcf()

    # only call gca if an active axes exists
    if f.axes:
        # can not pass kwargs to active axes
        return plt.gca()

    return plt.axes(**subplot_kws)

def _get_units_from_attrs(da: DataArray) -> str:
    """Extracts and formats the unit/units from a attributes."""
    # EDIT: removed pint support for now.
    # pint_array_type = DuckArrayModule("pint").type
    units = " [{}]"
    # if isinstance(da.data, pint_array_type):
    #    return units.format(str(da.data.units))
    if "units" in da.attrs:
        return units.format(da.attrs["units"])
    if "unit" in da.attrs:
        return units.format(da.attrs["unit"])
    return ""

def label_from_attrs(da: DataArray | None, extra: str = "") -> str:
    """Makes informative labels if variable metadata (attrs) follows
    CF conventions."""
    if da is None:
        return ""

    name: str = "{}"
    if "long_name" in da.attrs:
        name = name.format(da.attrs["long_name"])
    elif "standard_name" in da.attrs:
        name = name.format(da.attrs["standard_name"])
    elif da.name is not None:
        name = name.format(da.name)
    else:
        name = ""

    units = _get_units_from_attrs(da)

    # Treat `name` differently if it's a latex sequence
    if name.startswith("$") and (name.count("$") % 2 == 0):
        return "$\n$".join(
            textwrap.wrap(name + extra + units, 60, break_long_words=False)
        )
    else:
        return "\n".join(textwrap.wrap(name + extra + units, 30))

def _valid_other_type(
    x: ArrayLike, types: type[object] | tuple[type[object], ...]
) -> bool:
    """
    Do all elements of x have a type from types?
    """
    return all(isinstance(el, types) for el in np.ravel(x))

def _valid_numpy_subdtype(x, numpy_types):
    """
    Is any dtype from numpy_types superior to the dtype of x?
    """
    # If any of the types given in numpy_types is understood as numpy.generic,
    # all possible x will be considered valid.  This is probably unwanted.
    for t in numpy_types:
        assert not np.issubdtype(np.generic, t)

    return any(np.issubdtype(x.dtype, t) for t in numpy_types)

def _ensure_plottable(*args) -> None:
    """
    Raise exception if there is anything in args that can't be plotted on an
    axis by matplotlib.
    """
    numpy_types: tuple[type[object], ...] = (
        np.floating,
        np.integer,
        np.timedelta64,
        np.datetime64,
        np.bool_,
        np.str_,
    )
    other_types: tuple[type[object], ...] = (datetime,)
    cftime_datetime_types: tuple[type[object], ...] = (
        () if cftime is None else (cftime.datetime,)
    )
    other_types += cftime_datetime_types

    for x in args:
        if not (
            _valid_numpy_subdtype(np.asarray(x), numpy_types)
            or _valid_other_type(np.asarray(x), other_types)
        ):
            raise TypeError(
                "Plotting requires coordinates to be numeric, boolean, "
                "or dates of type numpy.datetime64, "
                "datetime.datetime, cftime.datetime or "
                f"pandas.Interval. Received data of type {np.asarray(x).dtype} instead."
            )
        if _valid_other_type(np.asarray(x), cftime_datetime_types):
            if nc_time_axis_available:
                # Register cftime datetypes to matplotlib.units.registry,
                # otherwise matplotlib will raise an error:
                import nc_time_axis  # noqa: F401
            else:
                raise ImportError(
                    "Plotting of arrays of cftime.datetime "
                    "objects or arrays indexed by "
                    "cftime.datetime objects requires the "
                    "optional `nc-time-axis` (v1.2.0 or later) "
                    "package."
                )

def _add_colorbar(primitive, ax, cbar_ax, cbar_kwargs, cmap_params):
    cbar_kwargs.setdefault("extend", cmap_params["extend"])
    if cbar_ax is None:
        cbar_kwargs.setdefault("ax", ax)
    else:
        cbar_kwargs.setdefault("cax", cbar_ax)

    # dont pass extend as kwarg if it is in the mappable
    if hasattr(primitive, "extend"):
        cbar_kwargs.pop("extend")

    fig = ax.get_figure()
    cbar = fig.colorbar(primitive, **cbar_kwargs)

    return cbar

def _update_axes(
    ax: Axes,
    xincrease: bool | None,
    yincrease: bool | None,
    xscale: ScaleOptions = None,
    yscale: ScaleOptions = None,
    xticks: ArrayLike | None = None,
    yticks: ArrayLike | None = None,
    xlim: tuple[float, float] | None = None,
    ylim: tuple[float, float] | None = None,
) -> None:
    """
    Update axes with provided parameters
    """
    if xincrease is None:
        pass
    elif xincrease and ax.xaxis_inverted():
        ax.invert_xaxis()
    elif not xincrease and not ax.xaxis_inverted():
        ax.invert_xaxis()

    if yincrease is None:
        pass
    elif yincrease and ax.yaxis_inverted():
        ax.invert_yaxis()
    elif not yincrease and not ax.yaxis_inverted():
        ax.invert_yaxis()

    # The default xscale, yscale needs to be None.
    # If we set a scale it resets the axes formatters,
    # This means that set_xscale('linear') on a datetime axis
    # will remove the date labels. So only set the scale when explicitly
    # asked to. https://github.com/matplotlib/matplotlib/issues/8740
    if xscale is not None:
        ax.set_xscale(xscale)
    if yscale is not None:
        ax.set_yscale(yscale)

    if xticks is not None:
        ax.set_xticks(xticks)
    if yticks is not None:
        ax.set_yticks(yticks)

    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)

def _process_cmap_cbar_kwargs(
    func,
    data,
    cmap=None,
    colors=None,
    cbar_kwargs: Iterable[tuple[str, Any]] | Mapping[str, Any] | None = None,
    levels=None,
    _is_facetgrid=False,
    **kwargs,
) -> tuple[dict[str, Any], dict[str, Any]]:
    """
    Parameters
    ----------
    func : plotting function
    data : ndarray,
        Data values

    Returns
    -------
    cmap_params : dict
    cbar_kwargs : dict
    """
    if func.__name__ == "surface":
        # Leave user to specify cmap settings for surface plots
        kwargs["cmap"] = cmap
        return {
            k: kwargs.get(k, None)
            for k in ["vmin", "vmax", "cmap", "extend", "levels", "norm"]
        }, {}

    cbar_kwargs = {} if cbar_kwargs is None else dict(cbar_kwargs)

    if "contour" in func.__name__ and levels is None:
        levels = 7  # this is the matplotlib default

    # colors is mutually exclusive with cmap
    if cmap and colors:
        raise ValueError("Can't specify both cmap and colors.")

    # colors is only valid when levels is supplied or the plot is of type
    # contour or contourf
    if colors and (("contour" not in func.__name__) and (levels is None)):
        raise ValueError("Can only specify colors with contour or levels")

    # we should not be getting a list of colors in cmap anymore
    # is there a better way to do this test?
    if isinstance(cmap, (list, tuple)):
        raise ValueError(
            "Specifying a list of colors in cmap is deprecated. "
            "Use colors keyword instead."
        )

    cmap_kwargs = {
        "plot_data": data,
        "levels": levels,
        "cmap": colors if colors else cmap,
        "filled": func.__name__ != "contour",
    }

    cmap_args = getfullargspec(_determine_cmap_params).args
    cmap_kwargs.update((a, kwargs[a]) for a in cmap_args if a in kwargs)
    if not _is_facetgrid:
        cmap_params = _determine_cmap_params(**cmap_kwargs)
    else:
        cmap_params = {
            k: cmap_kwargs[k]
            for k in ["vmin", "vmax", "cmap", "extend", "levels", "norm"]
        }

    return cmap_params, cbar_kwargs

def _easy_facetgrid(
    data: T_DataArrayOrSet,
    plotfunc: Callable,
    kind: Literal["line", "dataarray", "dataset", "plot1d"],
    x: Hashable | None = None,
    y: Hashable | None = None,
    row: Hashable | None = None,
    col: Hashable | None = None,
    col_wrap: int | None = None,
    sharex: bool = True,
    sharey: bool = True,
    aspect: float | None = None,
    size: float | None = None,
    subplot_kws: dict[str, Any] | None = None,
    ax: Axes | None = None,
    figsize: Iterable[float] | None = None,
    **kwargs: Any,
) -> FacetGrid[T_DataArrayOrSet]:
    """
    Convenience method to call xarray.plot.FacetGrid from 2d plotting methods

    kwargs are the arguments to 2d plotting method
    """
    if ax is not None:
        raise ValueError("Can't use axes when making faceted plots.")
    if aspect is None:
        aspect = 1
    if size is None:
        size = 3
    elif figsize is not None:
        raise ValueError("cannot provide both `figsize` and `size` arguments")
    if kwargs.get("z") is not None:
        # 3d plots doesn't support sharex, sharey, reset to mpl defaults:
        sharex = False
        sharey = False

    g = FacetGrid(
        data=data,
        col=col,
        row=row,
        col_wrap=col_wrap,
        sharex=sharex,
        sharey=sharey,
        figsize=figsize,
        aspect=aspect,
        size=size,
        subplot_kws=subplot_kws,
    )

    if kind == "line":
        return g.map_dataarray_line(plotfunc, x, y, **kwargs)

    if kind == "dataarray":
        return g.map_dataarray(plotfunc, x, y, **kwargs)

    if kind == "plot1d":
        return g.map_plot1d(plotfunc, x, y, **kwargs)

    if kind == "dataset":
        return g.map_dataset(plotfunc, x, y, **kwargs)

    raise ValueError(
        f"kind must be one of `line`, `dataarray`, `dataset` or `plot1d`, got {kind}"
    )


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 18:37:35 2020

@author: batuhankuru
"""
import time

class CodeTimer:
    def __init__(self, name=None):
        self.name = " '"  + name + "'" if name else ''

    def __enter__(self):
        self.start = time.clock()

    def __exit__(self, exc_type, exc_value, traceback):
        self.took = (time.clock() - self.start) * 1000.0
        print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')
sum = 2

def isPrime(n):
    if n % 2 == 0: return False
    for i in range(3, int(n**0.5)+1, 2):
        if n % i == 0: return False
    return True
if __name__ == "__main__":
    n = 1
    with CodeTimer('loop 1'):
     while n < 2000000:
        n += 2
        if isPrime(n):sum += n
print (sum)


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np

def plot_volume(volume, spacing, bx, by, bz, ax):
    # Get the dimensions of the volume
    Nx, Ny, Nz = np.array(volume.shape) * np.array(spacing)
    X, Y, Z = np.meshgrid(
        np.arange(0, Nx, spacing[0]) + bx,
        np.arange(0, Ny, spacing[1]) + by,
        np.arange(0, Nz, spacing[2]) + bz,
    )

    kw = {
        "vmin": volume.min(),
        "vmax": volume.max(),
        "levels": np.linspace(volume.min(), volume.max(), 10),
        "cmap": "gray",
    }

    # Plot contour surfaces
    idx = 256
    _ = ax.contourf(
        X[:, :, 0], Y[:, :, 0], volume[:, :, 0], zdir="z", offset=Z.max(), **kw
    )
    _ = ax.contourf(
        X[idx, :, :], volume[idx, :, :], Z[idx, :, :], zdir="y", offset=Y.min(), **kw
    )
    _ = ax.contourf(
        volume[:, idx, :], Y[:, idx, :], Z[:, idx, :], zdir="x", offset=X.max(), **kw
    )

    # Set limits of the plot from coord limits
    cushion = 350
    xmin, xmax = X.min(), X.max()
    ymin, ymax = Y.min(), Y.max()
    zmin, zmax = Z.min(), Z.max()
    ax.set(
        xlim=[xmin - cushion, xmax + cushion],
        ylim=[ymin - cushion, ymax + cushion],
        zlim=[zmin - cushion, zmax + cushion],
    )

    return ax

def plot_camera(source, rays, ax):
    # Plot the source
    source = source.detach().cpu().numpy()
    ax.scatter3D(source[0], source[1], source[2])

    # Plot the detector plane
    v0 = rays[0, 0, :].detach().cpu().numpy()
    v1 = rays[-1, 0, :].detach().cpu().numpy()
    v2 = rays[0, -1, :].detach().cpu().numpy()
    v3 = rays[-1, -1, :].detach().cpu().numpy()
    pts = np.array([v0, v1, v2, v3])
    ax.scatter3D(pts[:, 0], pts[:, 1], pts[:, 2])
    verts = [[pts[0], pts[1], pts[3], pts[2]]]
    ax.add_collection3d(
        Poly3DCollection(
            verts,
            facecolors="cyan",
            linewidths=1,
            edgecolors="r",
            alpha=0.2,
        )
    )

    # Plot the rays
    nx, ny = rays.shape[:2]
    for i in range(0, nx, nx - 1):
        for j in range(0, ny, ny - 1):
            pt = rays[i, j, :].detach().cpu()
            ax.plot3D(
                [pt[0], source[0]],
                [pt[1], source[1]],
                [pt[2], source[2]],
                "k--",
                alpha=0.75,
            )
    return ax

def plot_drr(drr, title=None, ticks=True, animated=False, ax=None):
    """
    Plot an DRR output by the projector module.

    Inputs
    ------
    drr : torch.Tensor
        DRR image in torch tensor with shape (height, width)
    title : str, optional
        Title for the plot
    ticks : Bool
        Toggle ticks and ticklabels.
    animated : Bool
        Set to true if using in animation.
    ax : matplotlib.axes._subplots.AxesSubplot, optional
        Axis to plot image on, if None is provided, a new axis will be made

    Returns
    -------
    ax : matplotlib.axes._subplots.AxesSubplot
        Axis with plotted image
    """
    drr = drr.detach().cpu()
    nx, ny = drr.shape
    if ax is None:
        _, ax = plt.subplots()
    img = ax.imshow(drr, cmap="gray", animated=animated)
    ax.xaxis.tick_top()
    ax.set(
        title=title,
        xticks=[0, nx - 1],
        xticklabels=[1, nx],
        yticks=[0, ny - 1],
        yticklabels=[1, ny],
    )
    if ticks is False:
        ax.set_xticks([])
        ax.set_yticks([])
    return img


def matrix_decrypt(n, key,s):
    m = [''] * len(s)
    gap = len(s) // n
    for i in range(len(s)):
        m[key.find(str(i//gap+1))+(i%gap)*n] = s[i]
    return ''.join(m)

def matrix_encrypt(n, key,s):
    c=['']*len(s)
    gap=len(s)//n
    for i in range(len(s)):
        c[(int(key[i%n])-1)*gap+i//n]=s[i]
    return ''.join(c)

def main():
    n=int(input())
    key = input().strip()
    s = input().strip()
    op = int(input())
    if op == 0:
        print(matrix_decrypt(n, key,s))
    elif op == 1:
        print(matrix_encrypt(n, key,s))


#!/usr/bin/env python3
import matplotlib.pyplot as plt
from math import sqrt
import json
from math import atan2, sin, cos
from horizontal_lines import get_figure
class PathFinder():
    def __init__(self):
        a = 1
        # self.points = points
        # for i in range(0,len(self.points)):
            # self.points[i][0] = self.points[i][0]/5
            # self.points[i][1] = self.points[i][1]/5

    def find_max_length(self, points):
        x, y = self.distract_coords(points)
        # plt.plot(x,y, '')
        max_dist = 0
        n = 0 #number_of_max_line
        lines = []
        for i in range(1,len(x),1):
            euclidian_distance = sqrt((x[i]-x[i-1])**2 + (y[i]-y[i-1])**2)
            line = {'a': (y[i] - y[i-1]),'b': (x[i-1] - x[i]), 'c': (x[i]*y[i-1] - x[i-1]*y[i]),'x1': x[i],'y1': y[i], 'x2': x[i-1], 'y2': y[i-1]}

            lines.append(line)
            # print(euclidian_distance)
            if euclidian_distance > max_dist:
                max_dist = euclidian_distance
                n = i
        # coord_1 = [x[number_of_max_line], y[number_of_max_line]]
        # coord_2 = [x[number_of_max_line-1], y[number_of_max_line-1]]
        x_of_max = [x[n],x[n-1]]
        y_of_max = [y[n],y[n-1]]
        # plt.plot(x_of_max, y_of_max, 'r--')
        # plt.grid(True)

        n_for_line = n-1
        temp = lines[0]
        lines[0] = lines[n_for_line]
        lines[n_for_line] = temp
        del temp
        line_max = lines[0]
        # print(line_max)
        #find perpendikular ot samoi dalnei tochki do samoi bolshoi priamoi
        distance = []
        for i in range(1, len(x),1):
            if x[i] != line_max['x1'] and x[i] != line_max['x2']:
                # plt.plot(x[i], y[i], 'bo')
                ortoganal = {'a':line_max['b'],
                            'b': line_max['a'],
                            'c': (-(line_max['b']*x[i])-(line_max['a']*y[i]))}
                x_cross_x, y_cross_y = self.find_cross(ortoganal, line_max)
                # plt.plot([x[i],x_cross_x], [y[i],y_cross_y], 'r--')
                euclidian_distance = sqrt((x[i]-x_cross_x)**2 + (y[i]-y_cross_y)**2)
                distance.append(euclidian_distance)
        # print(max(distance))
        iterations = round(max(distance)*2)
        #stroim parallelnie linii
        x_cross = []
        y_cross = []
        # print(it)
        for d in range(1,iterations,1):
            if d%2 == 0 :
                continue
            else:
                parallel_line = {'a': line_max['a'], 'b': line_max['b'], 'c': line_max['c']-d/2*sqrt(line_max['a']**2+line_max['b']**2)}
                #finde cross of parallel with previous line and next line
                for i in range(1, len(lines),1):

                    x_cross_x, y_cross_y = self.find_cross(parallel_line, lines[i])
                    # print(lines[i]['x1'])
                    # print(x_cross_x, lines[i]['x1'])
                    if (x_cross_x > lines[i]['x1'] and x_cross_x < lines[i]['x2']) or (x_cross_x < lines[i]['x1'] and x_cross_x > lines[i]['x2']):
                    # if (y_cross_y < lines[i-1]['y1'] and y_cross_y > lines[i-1]['y2']):
                        if x_cross_x != 0:
                            x_cross.append(x_cross_x)
                            y_cross.append(y_cross_y)

                parallel_line = {'a': line_max['a'], 'b': line_max['b'], 'c': line_max['c']+d/2*sqrt(line_max['a']**2+line_max['b']**2)}
                #finde cross of parallel with previous line and next line
                for i in range(1, len(lines),1):

                    x_cross_x, y_cross_y = self.find_cross(parallel_line, lines[i])
                    # print(lines[i]['x1'])
                    # print(x_cross_x, lines[i]['x1'])
                    if (x_cross_x > lines[i]['x1'] and x_cross_x < lines[i]['x2']) or (x_cross_x < lines[i]['x1'] and x_cross_x > lines[i]['x2']):
                    # if (y_cross_y < lines[i-1]['y1'] and y_cross_y > lines[i-1]['y2']):
                        if x_cross_x != 0:
                            x_cross.append(x_cross_x)
                            y_cross.append(y_cross_y)

        i = 2
        while i < len(x_cross)-1:
            euql_1 = sqrt(x_cross[i-1]**2 + y_cross[i-1]**2)
            euql_2 = sqrt(x_cross[i+1]**2 + y_cross[i+1]**2)
            # print(abs(euql_1 - euql_2), i)
            if abs(euql_1 - euql_2) < 4:
                temp = x_cross[i]
                x_cross[i] = x_cross[i+1]
                x_cross[i+1] = temp
                temp = y_cross[i]
                y_cross[i] = y_cross[i+1]
                i+=2
            else:
                # print(abs(euql_1 - euql_2))
                # if i!= len(x_cross) -2:
                i+=2
                # else:

        #optimize points
        # plt.plot(x_cross, y_cross, 'g--')
        for i in range(0, len(x_cross)-1,2):
            alpha = atan2(y_cross[i] - y_cross[i+1], x_cross[i] - x_cross[i+1])
            delta_x = -abs(0.5*cos(alpha))     #0.4 its 2/5 of 5 meters (1 cell = 5 meter)
            delta_y = -abs(0.5*sin(alpha))
            if x_cross[i] > x_cross[i+1]:
                x_cross[i] -= delta_x
                x_cross[i+1] += delta_x
            else:
                x_cross[i] += delta_x
                x_cross[i+1] -= delta_x
            if y_cross[i] > y_cross[i+1]:
                y_cross[i] -= delta_y
                y_cross[i+1] += delta_y
            else:
                y_cross[i] += delta_y
                y_cross[i+1] -= delta_y

        """x_1 = [x_cross[0], x_cross[1]]
        x_2 = []
        y_1 = [y_cross[0], y_cross[1]]
        y_2 = []
        for i in range(4,len(x_cross)-2,2):
            x_1.append(x_cross[i+1])
            x_1.append(x_cross[i])
            y_1.append(y_cross[i+1])
            y_1.append(y_cross[i])
            x_1.append(x_cross[i+2])
            y_1.append(y_cross[i+2])

        print(x_cross)
        print(x_1)
        l = len(x_1)
        return x_1, y_1, x_of_max, y_of_max, l"""

        return x_cross, y_cross, x_of_max, y_of_max

    def find_cross(self, line1, line2):
        if (line2['a']*line1['b'] - line1['a']*line2['b']) != 0:
            x = (line1['c']*line2['b'] - line1['b']*line2['c'])/(line2['a']*line1['b'] - line1['a']*line2['b'])
        else:
            x = 0
        if (line2['b']*line1['a'] - line1['b']*line2['a']) != 0:
            y = (line1['c']*line2['a'] - line1['a']*line2['c'])/(line2['b']*line1['a'] - line1['b']*line2['a'])
        else:
            y = 0
        return x,y
    def distract_coords(self, points):
        x = []
        y = []
        for point in points:
            x.append(point[0])
            y.append(point[1])
        x.append(points[0][0])
        y.append(points[0][1])
        return x, y
    def get_points(self):
        # with open('points.json', 'w') as write_file:
        with open('figure.json', 'r') as read_file:
            data = json.load(read_file)
        # print(data)
        points = [data['figure1'], data['figure2'], data['figure3']]

        data = {'points_0': 0,'points_1':0, 'points_2':0}
        j = 0
        with open('points.json', 'w') as write_file:
            for point in points:
                for i in range(0,len(point)):
                    point[i][0] = point[i][0]/5
                    point[i][1] = point[i][1]/5

                x, y, x_max, y_max = self.find_max_length(point)
                for i in range(0,len(x)):
                    x[i] = x[i]*5
                    y[i] = y[i]*5
                data_local = {"x": x, "y": y}
                data['points_'+str(j)] = data_local
                j+=1
            json.dump(data,write_file)
        return data
    def sign(self, number):
        if number < 0:
            return(-1)
        else:
            return(1)

def distract_coords(points):
        x = []
        y = []
        for point in points:
            x.append(point[0])
            y.append(point[1])
        x.append(points[0][0])
        y.append(points[0][1])
        return x, y

if __name__ == '__main__':
    x_field = [0, -92.90069267118855, 140.84355006431937, 353.1844363236166, 433.09813506117024, 425.66284007499496, 0]
    y_field = [0, 276.2304132311622, 304.56447871509005, 223.57025571008904, 160.2219372171964, 0.0, 0]
    # get_figure(0.2, 0.4, 0.4)
    # plt.plot(x_field, y_field, 'b')
    with open('figure.json', 'r') as read_file:
        data = json.load(read_file)
    # print(data)
    points = [data['figure1'], data['figure2'], data['figure3']]
    # points = [data['figure1']]
    # points.reverse()
    j = 0
    # flag = True
    plt.plot(x_field, y_field, 'b')

    for point in points:
        x_part, y_part = distract_coords(point)
        plt.plot(x_part, y_part, 'r')
        # if flag == True:
            # flag = False
    j = 0

    with open('points.json', 'w') as write_file:
        data = {'points_0': 0,'points_1':0, 'points_2':0}

        for point in points:
            for i in range(0,len(point)):
                point[i][0] = point[i][0]/5
                point[i][1] = point[i][1]/5

            path = PathFinder()
            x, y, x_max, y_max = path.find_max_length(point)
            # print(len(x))
            for i in range(0,len(x)):
            # for i in range(0,l):
                x[i] = x[i]*5
                y[i] = y[i]*5
            if j == 0:
                plt.plot(x, y, 'g--')
            if j == 1:
                plt.plot(x, y, 'm--')
            if j == 2:
                plt.plot(x, y, 'y--')

            plt.plot([x_max[0]*5,x_max[0]*5], [y_max[0]*5,y_max[0]*5], 'ro')
            # plt.plot(x[0], y[0], 'ro')

            data_local = {"x": x, "y": y}
            data['points_'+str(j)] = data_local
            j+=1

        json.dump(data,write_file)
    plt.grid()
    plt.show()
    j = 0


# Exercício 2: Calcule a média aritmética dos valores contidos em uma lista.

def arithmetic_average(list):
    sum = 0
    quantity = len(list)
    for value in list:
        sum += value
    return sum / quantity

print(arithmetic_average([2, 3, 3, 5, 7, 10]))


import unittest

from photofilmstrip.gui.PnlStory import TreeItm

class TestGeom(unittest.TestCase):

    def setUp(self):
        self.root = TreeItm()

        self.child1 = TreeItm()
        self.child2 = TreeItm()
        self.child3 = TreeItm()

        for idx in range(3):
            self.child1.Insert(idx, TreeItm())
            self.child2.Insert(idx, TreeItm())
            self.child3.Insert(idx, TreeItm())

        self.root.Insert(0, self.child1)
        self.root.Insert(1, self.child2)
        self.root.Insert(2, self.child3)

    def testIndex3(self):
        idx = self.child3.Index()
        self.assertEqual(idx, 2)

    def testRow1(self):
        row = self.child1.Row()
        self.assertEqual(row, 1)

    def testRow2(self):
        row = self.child2.Row()
        self.assertEqual(row, 5)

    def testRow3(self):
        row = self.child3.Row()
        self.assertEqual(row, 9)

    def testRowLast(self):
        lastChild = self.child3.GetChildren()[-1]
        row = lastChild.Row()
        self.assertEqual(row, 12)

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


numero = int(input('Hey cara! Qual é o número? '))

m = numero // 1000
resto = numero % 1000

c = resto // 100
resto = resto % 100

d = resto // 10
u = resto % 10

soma = m + c + d + u

print('A Milhar é', m)
print('A Centena é', c)
print('A Dezena é', d)
print('A Unidade é', u)
print('A soma do dígitos é: ', soma)


import csv, os
from instaloader import Instaloader, Profile
loader = Instaloader()

login_name = "" ## MASUKIN USERNAME INSTAGRAM LOGIN
target_profile = "" ## MASUKIN USERNAME INSTAGRAM YANG INGIN DI CRAWLING

# login
try:
    loader.load_session_from_file(login_name)
except FileNotFoundError:
    loader.context.log("Session file does not exist yet - Logging in.")
if not loader.context.is_logged_in:
    loader.interactive_login(login_name)
    loader.save_session_to_file()

profile = Profile.from_username(loader.context, target_profile)
followers = profile.get_followers()

loader.context.log()
loader.context.log('Profile {} has {} followers:'.format(profile.username, profile.followers))
loader.context.log()

with open('test.csv', 'w', newline='') as csvfile: ## GANTING 'test.csv' DENGAN FILE NAME YANG DIINGINKAN
    writer = csv.writer(csvfile)
    for follower in followers:
        loader.context.log(follower.username, flush=True)
        writer.writerow([follower.username])


import streamlit as st
from streamlit_chat import message as st_message
import numpy as np

# some_css = """
#  <style>
# [data-testid="stVerticalBlock"] {
#         color: red;
# }

# div.css-1mbg4kq.e1tzin5v0 {
#     color: pink;
#     overflow: auto
# }
# </style>
# """

# st.markdown(some_css, unsafe_allow_html=True)

if "history" not in st.session_state:
    st.session_state.history = []
    st.session_state.history.append({"message": "how can I help you today?", "is_user": False} )
    st.session_state.history.append({"message": "Tell me more about you", "is_user": True} )

# # agent_message  = st.text_input(bot_message)
pre_questions = ['who are you?',
                 'What are you doing?',
                 'How old are you?']

pre_answers = ["I don't know",
                 "I'm working at hexamind",
                 "I like NLP"]

if 'input_value' not in st.session_state:
    st.session_state.input_value = ""

col1, col2 = st.columns([2,1])

button1_text = pre_answers[0]
button2_text = pre_answers[1]
button3_text = pre_answers[2]

with col2:
    st.write("#### Candidate answers:")
    button1_clicked = st.button(button1_text)
    button2_clicked = st.button(button2_text)
    button3_clicked = st.button(button3_text)
    st.markdown("---")

# Define the callback functions to update the text input value
def update_input_value(button_text):
    # Update the input value to the text of the clicked button
    st.session_state.input_value = button_text

def send_message():
    st.session_state.history.append({"message": input_value  , "is_user": False})
    st.session_state.history.append({"message": f"{np.random.choice(pre_questions)} + {np.random.randint(low= 0,high =100, size=1)}"   , "is_user": True})

# Call the callback function when a button is clicked
if button1_clicked:
    update_input_value(button1_text)
if button2_clicked:
    update_input_value(button2_text)
if button3_clicked:
    update_input_value(button3_text)

with col1:
    st.write("#### Agent Placeholder:")
    # Update the default value of the text input widget
    input_value = st.text_input('Enter a value',
                                st.session_state.input_value)

    # Display the updated text input value
    # st.write('Updated value:', st.session_state.input_value)

    send_message_button = st.button("Send the message",
                                    on_click=send_message)

    st.markdown("---")

    with st.container():
        st.write("#### Conversation Screen:")
        for chat in st.session_state.history:
            st_message(**chat)


class student:
    stid=12
    stnm='Sanket'

    def getdata(self):
        print("ID:",self.stid)
        print("Name:",self.stnm)

# calling via object
"""st=student()
st.getdata()
st.stid=34
st.stnm='Nirav'
st.getdata()"""

st=student()

# calling via instance
student().getdata()
student().stid=45
student().stnm='Ashok'
student().getdata()


"""
The sum of the squares of the first ten natural numbers is,

    1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,

    (1 + 2 + ... + 10)^2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""

sumOfSquares = sum([x**2 for x in range(1,101)])
squareOfSums = sum([x for x in range(1,101)])**2
difference = squareOfSums - sumOfSquares
print("Difference between sum of squares and square of sums for 1-100:\n" + str(difference))


#-*- coding: UTF-8 -*-
import os
import pims
import test_video
import threading
import logging
import time
import cv2
import asyncio
import random
from utils.opts import parse_opts
from imutils.video import FileVideoStream
from models import resnext
from mytransforms.spatial_transforms import (
    Compose, Normalize, Scale, CenterCrop, CornerCrop, MultiScaleCornerCrop,
    MultiScaleRandomCrop, RandomHorizontalFlip, ToTensor)
import torch.nn as nn
import torch
import imageio
from multiprocessing import Pool
from imutils.video import FPS
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#设置只可见gpu1
os.environ['CUDA_VISIBLE_DEVICES'] = '1'

NUM_CLIP = 4
NUM_PER_CLIP = 16
INTER_FRAME = 5
frames = []

#start_time = time.time()
#V = pims.Video('/home/zengh/Dataset/AIChallenger/group5/1004255246.mp4')
#total_frame_num = len(V)
#duration = time.time() - start_time
#print('pims video time %.3f s' % duration)

def initial_model():
  opt = parse_opts()
  model = resnext.resnet101(
              num_classes=opt.n_finetune_classes,
              shortcut_type=opt.resnet_shortcut,
              cardinality=opt.resnext_cardinality,
              sample_size=opt.sample_size,
              sample_duration=opt.sample_duration)

  model = model.cuda()
  model = nn.DataParallel(model, device_ids=None)
  model_path = './trained_models/best.pth10.tar'
  if not os.path.exists(model_path):
    print("model path is not true!!")
    return

  model.load_state_dict(torch.load('./trained_models/best.pth10.tar')['state_dict'])
  model.eval()
  return model

# rgb_mean = [0.485, 0.456, 0.406]
# rgb_std = [0.229, 0.224, 0.225]
# opt.scales=[1]
# transform_val = Compose([
#     MultiScaleCornerCrop(opt.scales, opt.sample_size, crop_positions=['c']),
#     ToTensor(),
#     Normalize(rgb_mean, rgb_std),
# ])

#记得去掉每行后面的\n
with open('val_group5.txt','r') as f:
    videos = f.readlines()

#NUM_VIDEO = len(videos)
NUM_VIDEO = 50

for i in range(NUM_VIDEO):
  videos[i] = videos[i].strip()
  if not os.path.exists(videos[i]):
    print("video not exists!")
    break

#NUM_VIDEO = 100
NUM_PROCESS = 1
VIDEO_PER_THREAD = int(NUM_VIDEO / NUM_PROCESS)

def decode_video(path, filename, format_out):
    """ Decodes the selected video file and returns the corresponding tensor
        as a uint8 list of numpy arrays.

        Args:
            path (string) : path to the directory containing the file to be decoded.
            filename (string) : string containing the file name.
            format_out (string) : string containing the file extension of the file to be decoded.

        Returns:
            list of numpy_array
    """

    if filename.endswith(format_out):
        vid = imageio.get_reader(path+filename,'ffmpeg')
        nframes = len(vid)
        list = []
        for i in range(nframes):
            try:
                list.append(vid.get_data(i))
            except:
                e = sys.exc_info()[0]
                print('error {0} at index {1}'.format(e,i))
    else:
        print('There is a non-{} file\n'.format(format_out))

    return(list)

# start_time = time.time()
# V = decode_video('/home/zengh/Dataset/AIChallenger/group5/','1004255246.mp4' ,'mp4')
# duration = time.time() - start_time
#print('decode video time %.3f s' % duration)

def get_logger():
    logger = logging.getLogger("threading_example")
    logger.setLevel(logging.DEBUG)

    fh = logging.FileHandler("threading.log")
    fmt = '%(asctime)s - %(threadName)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(fmt)
    fh.setFormatter(formatter)

    logger.addHandler(fh)
    return logger

def predict_clip_thread(sindex,logger):
  logger.debug('start predicting')
  #s_index = sindex
  s_index = random.randint(0, sindex)
  list_arr = []

  for j in range(s_index, s_index + INTER_FRAME*NUM_PER_CLIP, INTER_FRAME):
    logger.debug('j: {}'.format(j))
    list_arr.append(V[j])

  indexes = test_video.predict(model,list_arr,transform=transform_val)
  logger.debug('result: {}'.format(indexes))

def print_test(n,logger):
  for i in range(n):
    logger.debug('i: {}'.format(i))
    #print(i)

def test_thread():
  start_time = time.time()
  logger = get_logger()
  thread_names = range(1,NUM_CLIP+1)
  threads = []
  total_frame_num = len(V)
  #print("total_frame_num",total_frame_num)
  sindex = total_frame_num - INTER_FRAME * NUM_PER_CLIP + 1
  #sindex = [0,76,152]
  #start_time = time.time()
  for i in range(NUM_CLIP):
    t = threading.Thread(target=predict_clip_thread,name=thread_names[i],args=(sindex,logger))
    #t = threading.Thread(target=print_test,name=thread_names[i],args=(10,logger))
    threads.append(t)

  for t in threads:
    t.setDaemon(True)
    t.start()

  for t in threads:
    t.join()

  duration = time.time() - start_time
  print('test time %.3f s' % duration)

def predict_clip(_sindex):
  sindex = random.randint(0, _sindex)
  list_arr = []
  #for j in range(sindex, sindex + INTER_FRAME*NUM_PER_CLIP, INTER_FRAME):
  for j in range(64):
    list_arr.append(V[j])
  start_time = time.time()
  indexes = test_video.predict(model,list_arr,transform=transform_val)
  duration = time.time() - start_time
  print('test time %.3f s' % duration)
  print("result",indexes)

def test():
  start_time = time.time()
  total_frame_num = len(V)
  #print("total_frame_num",total_frame_num)
  s_index = total_frame_num - INTER_FRAME * NUM_PER_CLIP + 1
  #for i in range(NUM_CLIP):
  predict_clip(s_index)
  duration = time.time() - start_time
  #print('test time %.3f s' % duration)

async def predict_clip_asy(sindex):
  s_index = random.randint(0, sindex)
  list_arr = []

  for j in range(s_index, s_index + INTER_FRAME*NUM_PER_CLIP, INTER_FRAME):
    list_arr.append(V[j])

  print("start predict_clip_asy ", s_index )

  indexes = test_video.predict(model,list_arr,transform=transform_val)
  await asyncio.sleep(1)
  #indexes = []
  return indexes

async def result_clip_async(s_index):
    result = await predict_clip_asy(s_index)
    print(result)

#取的连续帧list
def result_predict(frames,model):
  start_time = time.time()
  frame_num = len(frames)
  #print("frame num is ",frame_num)
  temp = int(frame_num / (NUM_PER_CLIP * NUM_CLIP))
  predict_frame = []
  for i in range(NUM_PER_CLIP * NUM_CLIP):
      predict_frame.append(frames[i * temp])

  result = test_video.predict(model,predict_frame)
  #print("result:",result)
  duration = time.time() - start_time
  #print('test time %.3f s' % duration)
  return result

#先读图片,再预测,图片写入队列作为一个线程
def videostream_predict(video_index,process_num,model):
  try:
    # start the FPS timer
    print('Run task %s (%s)...' % (process_num, os.getpid()))
    st2 = time.time()
    clip = 0
    video_num = 0
    total_video_num = len(video_index)
    frames = []
    video = videos[video_index[video_num]]
    if not os.path.exists(video):
        print("video not exists!")
        return

    fvs = FileVideoStream(video,resize=112).start()

    while video_num < (total_video_num - 1):
      #得到的是图片tensor
      st4 = time.time()
      frame = fvs.read()
      #print("Q size is",fvs.more())
      #print("read time is ",time.time() - st4)
      #clip += 1
      #耗时少
      frames.append(frame)
      #print("Process ",process_num," clip ",clip," is more ",fvs.more())

      #if clip == 200 or frame.dim() == 1:
      #遇到终止帧
      if frame.dim() == 1:
        if video_num == 0:
          st1 = time.time()
        #print("the part is ",time.time() - st1)
        res_frames = frames.copy()  #深拷贝

        fvs.stop()
        #clip = 0
        video_num = video_num + 1
        video = videos[video_index[video_num]]
        if not os.path.exists(video):
          print("video not exists!")
          break
        fvs = FileVideoStream(video,resize=112).start()

        #去掉终止帧
        res_frames.pop(-1)

        frames = []
        #print("start predict**",process_num)
        #读取下一个视频部分的时间,可以读超过128帧的视频帧(读取帧率和视频有关?),所以可以调节队列maxsize的大小
        st = time.time()
        indexes = result_predict(res_frames,model)
        #print("predict time is ",time.time() - st)

        st1 = time.time()
        #print("finish predict**",process_num)

    fvs.stop()
    print('Task %s runs %0.2f seconds.' % (process_num, (time.time() - st2)))

  except Exception as ex:
    msg = "error:%s"%ex
    print(ex)

#图片的写入队列和从队列中取作为两个线程同时进行
def videostream_predict_1(video_index,process_num,model):
  try:
    # start the FPS timer
    print('Run task %s (%s)...' % (process_num, os.getpid()))

    video_num = 0
    total_video_num = len(video_index)
    video = videos[video_index[video_num]]
    if not os.path.exists(video):
        print("video not exists!")
        return
    #st2 = time.time()
    fvs = FileVideoStream(video,resize=112).start_produce_consume()
    #print("read time is ",time.time() - st2)
    #print(fvs.if_read_end())

    st1 = time.time()
    while video_num < (total_video_num - 1):
      if fvs.if_read_end() == True:
        print("read time is ",time.time() - st1)
        frames = fvs.get_frames()
        print("video len is ",len(frames))

        video_num = video_num + 1
        video = videos[video_index[video_num]]
        if not os.path.exists(video):
          print("video not exists!")
          break

        fvs = FileVideoStream(video,resize=112).start_produce_consume()
        indexes = result_predict(frames,model)
        st1 = time.time()
        #print("video ",video_num," indexes",indexes)

    print('Task %s runs %0.2f seconds.' % (process_num, (time.time() - st2)))

  except Exception as ex:
    msg = "error:%s"%ex
    print(ex)

def multiprocess_predict():
  st = time.time()
  print('Parent process %s.' % os.getpid())
  p = Pool(NUM_PROCESS)
  model = initial_model()
  print("model has been restored!",time.time() - st)
  for i in range(NUM_PROCESS):
    index = range(i*VIDEO_PER_THREAD, (i+1)*VIDEO_PER_THREAD)
    if i == (NUM_PROCESS - 1):
      index = range(i*VIDEO_PER_THREAD,NUM_VIDEO)

    p.apply_async(videostream_predict_1, args=(index,i,model, ))

  print('Waiting for all subprocesses done...')
  p.close()
  p.join()
  print('All subprocesses done. %0.2f seconds.' % (time.time() - st))

if __name__=='__main__':
    # start_time = time.time()
    # s_index = total_frame_num - INTER_FRAME * NUM_PER_CLIP + 1

    # loop = asyncio.get_event_loop()

    # loop.run_until_complete(asyncio.gather(result_clip_async(s_index),result_clip_async(s_index),result_clip_async(s_index),result_clip_async(s_index),result_clip_async(s_index),
    #                                       result_clip_async(s_index),result_clip_async(s_index),result_clip_async(s_index),result_clip_async(s_index),result_clip_async(s_index)))

    # #loop.run_until_complete(asyncio.gather(result_clip_async(s_index)))
    # loop.close()
    # duration = time.time() - start_time
    # print('test time %.3f s' % duration)
    multiprocess_predict()
    #test()


import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import librosa
import librosa.display
import numpy as np

# ! Audio functions

def summary_audio(x):
    if x.ndim == 1:
        SUM = ('\n{0:>10s}: {1:>15.4f}').format('min', np.amin(x))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('1st Quar',
                                                 np.percentile(x, 25))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('median', np.median(x))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('mean', np.mean(x))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('3rd Quar',
                                                 np.percentile(x, 75))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('max', np.amax(x))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('sigma', np.std(x))
    elif x.ndim == 2:
        E = x[:, 0]
        D = x[:, 1]
        SUM = ('{0:>%ss} {1:>%ss}' % (27, 15)).format('L', 'R')
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('min',
                                                            np.amin(E), np.amin(D))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('1st Quar',
                                                            np.percentile(E, 25), np.percentile(D, 25))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('median',
                                                            np.median(E), np.median(D))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('mean',
                                                            np.mean(E), np.mean(D))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('3rd Quar',
                                                            np.percentile(E, 75), np.percentile(D, 75))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('max',
                                                            np.amax(E), np.amax(D))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('sigma',
                                                            np.std(E), np.std(D))
    else:
        raise ValueError('Invalid argument! It is not an audio..')
    print(SUM)

def audiovis(x, fs=44100, **kwargs):
    dx, dy = (1536, 512) if 'dims' not in kwargs else kwargs['dims']
    dpi = 72 if 'dpi' not in kwargs else kwargs['dpi']
    text = '' if 'text' not in kwargs else kwargs['text']

    samples = x.shape[0]
    time = samples/fs
    if 'time' not in kwargs:
        to, ti = [0, time]
    else:
        to, ti = kwargs['time'][[0, -1]]
    tmin, tmax = (to, ti) if 'tlim' not in kwargs else kwargs['tlim']
    t = np.linspace(to, ti, samples)

    if x.ndim == 1:
        print('audio mono')
        fig = plt.figure(figsize=(dx/dpi, dy/dpi))
        plt.plot(t, x)
        plt.xlim([tmin, tmax])
    elif x.ndim == 2:
        print('audio stereo')
        fig = plt.figure(figsize=(dx/dpi, 2*dy/dpi))
        plt.subplot(2, 1, 1)
        plt.plot(t, x[:, 0], color='#00ff88')
        plt.xlim([tmin, tmax])
        plt.subplot(2, 1, 2)
        plt.plot(t, x[:, 1], color='#0088ff')
        plt.xlim([tmin, tmax])
    else:
        raise ValueError('Invalid argument! It is not an audio..')
    plt.title(text)
    plt.show()

def spectrogram(x, fs=44100, **kwargs):
    dx, dy = (1536, 512) if 'dims' not in kwargs else kwargs['dims']
    dpi = 72 if 'dpi' not in kwargs else kwargs['dpi']
    fmin, fmax = [0, 8000] if 'flim' not in kwargs else kwargs['flim']
    text = '' if 'text' not in kwargs else kwargs['text']

    x = x.astype(np.float32)

    if x.ndim == 1:
        print('audio mono')
        fig = plt.figure(figsize=(dx/dpi, dy/dpi))
        X = np.abs(librosa.stft(x))
        X = librosa.amplitude_to_db(X, ref=np.max)
        librosa.display.specshow(X, sr=fs, y_axis='linear')
        plt.ylim([fmin, fmax])
        plt.colorbar(format='%+2.0f dB')
    elif x.ndim == 2:
        print('audio stereo')
        fig = plt.figure(figsize=(dx/dpi, 2*dy/dpi))
        plt.subplot(2, 1, 1)
        X = np.abs(librosa.stft(x[:, 0]))
        X = librosa.amplitude_to_db(X, ref=np.max)
        librosa.display.specshow(X, sr=fs, y_axis='linear')
        plt.ylim([fmin, fmax])
        plt.colorbar(format='%+2.0f dB')
        plt.subplot(2, 1, 2)
        X = np.abs(librosa.stft(x[:, 1]))
        X = librosa.amplitude_to_db(X, ref=np.max)
        librosa.display.specshow(X, sr=fs, y_axis='linear')
        plt.ylim([fmin, fmax])
        plt.colorbar(format='%+2.0f dB')
    else:
        raise ValueError('Invalid argument! It is not an audio..')
    plt.title(text)
    plt.show()

# ! Image functions

def summary_image(image):
    if image.ndim == 2:
        SUM = ('\n{0:>10s}: {1:>15.4f}').format('min', np.amin(image))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('1st Quar',
                                                 np.percentile(image, 25))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('median', np.median(image))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('mean', np.mean(image))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('3rd Quar',
                                                 np.percentile(image, 75))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('max', np.amax(image))
        SUM += ('\n{0:>10s}: {1:>15.4f}').format('sigma', np.std(image))
    elif image.ndim == 3:
        R = image[:, :, 0]
        G = image[:, :, 1]
        B = image[:, :, 2]
        SUM = ('{0:>%ss} {1:>%ss} {2:>%ss}' %
               (27, 15, 15)).format('R', 'G', 'B')
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f} {3:>15.4f}').format('min',
                                                                       np.amin(R), np.amin(G), np.amin(B))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f} {3:>15.4f}').format('1st Quar',
                                                                       np.percentile(R, 25), np.percentile(G, 25), np.percentile(B, 25))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f} {3:>15.4f}').format('median',
                                                                       np.median(R), np.median(G), np.median(B))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f} {3:>15.4f}').format('mean',
                                                                       np.mean(R), np.mean(G), np.mean(B))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f} {3:>15.4f}').format('3rd Quar',
                                                                       np.percentile(R, 75), np.percentile(G, 75), np.percentile(B, 75))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f} {3:>15.4f}').format('max',
                                                                       np.amax(R), np.amax(G), np.amax(B))
        SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f} {3:>15.4f}').format('sigma',
                                                                       np.std(R), np.std(G), np.std(B))
    else:
        raise ValueError('Invalid argument! It is not an image..')
    print(SUM)

def histogram(image, **kwargs):
    x, y = (3*(256 + 100), 256) if 'dims' not in kwargs else kwargs['dims']
    dpi = 72 if 'dpi' not in kwargs else kwargs['dpi']
    bins = 256 if 'bins' not in kwargs else kwargs['bins']
    rw = 0.95 if 'rw' not in kwargs else kwargs['rw']
    interval = [0, 255] if 'interval' not in kwargs else kwargs['interval']

    fig = plt.figure(figsize=(x/dpi, y/dpi))

    gs1 = gridspec.GridSpec(1, 3)
    gs1.update(	left=0,
                right=1,
                bottom=0,
                top=1,
                wspace=0,
                hspace=0)
    ax1 = plt.subplot(gs1[:, 0])
    ax1.axis('off')
    ax2 = plt.subplot(gs1[:, 1:])

    img = image.copy()

    if img.ndim == 2:
        ax1.imshow(	img,
                    cmap='gray',
                    vmin=interval[0],
                    vmax=interval[1])
        ax2.hist(	img.ravel(),
                  bins=bins,
                  range=interval,
                  rwidth=rw,
                  color='k')
    elif img.ndim == 3:
        imgo = (img - interval[0])/(interval[1] - interval[0])
        imgo[imgo < 0] = 0
        imgo[imgo > 1] = 1

        R = img[:, :, 0]
        G = img[:, :, 1]
        B = img[:, :, 2]

        ax1.imshow(imgo)
        ax2.hist(	R.ravel(),
                  bins=bins,
                  range=interval,
                  rwidth=rw,
                  fc=(1, 0, 0.25, 0.5))
        ax2.hist(	G.ravel(),
                  bins=bins,
                  range=interval,
                  rwidth=rw,
                  fc=(0.25, 1, 0, 0.5))
        ax2.hist(	B.ravel(),
                  bins=bins,
                  range=interval,
                  rwidth=rw,
                  fc=(0, 0.25, 1, 0.5))
    else:
        raise ValueError('Invalid argument! It is not an image..')
    plt.show()

def panel(images, gspec, **kargs):
    M, N = gspec

    x, y = (1024, 512) if 'dims' not in kargs else kargs['dims']
    dpi = 72 if 'dpi' not in kargs else kargs['dpi']
    texts = [] if 'texts' not in kargs else kargs['texts']
    tx, ty = (10, 10) if 'text_pos' not in kargs else kargs['text_pos']
    tc = 'white' if 'text_color' not in kargs else kargs['text_color']
    ts = 12 if 'text_size' not in kargs else kargs['text_size']
    interval = [0, 255] if 'interval' not in kargs else kargs['interval']

    fig = plt.figure(figsize=(x/dpi, y/dpi))
    gs = gridspec.GridSpec(N, M)
    gs.update(	left=0, right=1,
               bottom=0, top=1,
               wspace=0, hspace=0)
    images = (images - interval[0])/(interval[1] - interval[0])
    images[images < 0] = 0
    images[images > 1] = 1
    for n in range(N):
        for m in range(M):
            ax = plt.subplot(gs[n, m])
            ax.axis('off')
            try:
                image = images[n*M + m]
            except:
                image = images[0]*0
            if image.ndim == 2:
                ax.imshow(image, cmap='gray')
            else:
                ax.imshow(image)
            try:
                text = texts[n*M + m]
            except:
                text = ''
            ax.text(	tx, ty, text,
                     color=tc, size=ts,
                     horizontalalignment='left',
                     verticalalignment='top')
    plt.show()


from flask import Flask, request

#https://docs.google.com/document/d/1802LEUy39LOEYrRhZpHqVZPBKNEAmNBVL7Rxhbl3fCs/edit#

foods = {
    'chocolate' : 'no, only humans can enjoy the joy of chocolates',
    'fish' : 'animals can get salmonella too! Sashimi and cooked fish is usually okay',
    'grapes': 'Cats can, dogs cannot, therefore cats > dogs!'
}

app = Flask(__name__)

@app.route('/ncss')
def ncss():
    return '
ncss
'

@app.route('/greet', methods=['GET', 'POST'])
def greet_person():
    name = request.values.get('text')
    if 'bye' in name:
        return('ok good bye then, I hope to never see you again :(')
    else:
        return f'hi {name}!'

if __name__ == '__main__':
    app.run()


import pandas as pd
import pytest
from numpy.testing import assert_array_equal
from pandas.testing import assert_frame_equal
from pandas.testing import assert_series_equal
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline

from hcrystalball.ensemble import SimpleEnsemble
from hcrystalball.ensemble import StackingEnsemble
from hcrystalball.feature_extraction import HolidayTransformer
from hcrystalball.wrappers import ExponentialSmoothingWrapper
from hcrystalball.wrappers import ProphetWrapper
from hcrystalball.wrappers import SarimaxWrapper
from hcrystalball.wrappers import TBATSWrapper
from hcrystalball.wrappers import get_sklearn_wrapper

@pytest.fixture(scope="module")
def transformers(request):
    if request.param is None:
        return None
    else:
        options = {"holiday": ("holiday", HolidayTransformer(country_code="DE"))}
        transformers = request.param.split(",")

        return [options[t] for t in transformers if t in options.keys()]

@pytest.fixture(scope="module")
def estimators():
    options = {
        "prophet": [
            (
                "prophet",
                ProphetWrapper(
                    daily_seasonality=False,
                    weekly_seasonality=False,
                    yearly_seasonality=False,
                ),
            )
        ],
        "sarimax": [("sarimax", SarimaxWrapper(order=(1, 1, 1), seasonal_order=(1, 1, 1, 2)))],
        "smoothing": [("smoothing", ExponentialSmoothingWrapper())],
        "sklearn": [("sklearn", get_sklearn_wrapper(LinearRegression))],
        "tbats": [("tbats", TBATSWrapper(use_arma_errors=False, use_box_cox=False))],
        "stacking_ensemble": [
            (
                "stacking_ensemble",
                StackingEnsemble(
                    base_learners=[
                        ExponentialSmoothingWrapper(name="smoot_exp1", trend="add"),
                        ExponentialSmoothingWrapper(name="smoot_exp2"),
                    ],
                    meta_model=LinearRegression(),
                ),
            )
        ],
        "simple_ensemble": [
            (
                "simple_ensemble",
                SimpleEnsemble(
                    base_learners=[
                        ExponentialSmoothingWrapper(name="smoot_exp1", trend="add"),
                        ExponentialSmoothingWrapper(name="smoot_exp2"),
                    ]
                ),
            )
        ],
    }

    models = []
    [models.extend(options[key]) for key in options]
    return models

@pytest.mark.parametrize(
    "X_y_linear_trend, transformers",
    [
        ("series_with_freq_D", "holiday"),
        ("ndarray_with_freq_D", "holiday"),
        # no transformers, all estimators, good data
        ("ndarray_with_freq_D", None),
        ("series_with_freq_D", None),
    ],
    indirect=["X_y_linear_trend", "transformers"],
)
def test_data_unchanged(X_y_linear_trend, transformers, estimators):
    X, y = X_y_linear_trend
    X_orig = X
    y_orig = y

    for estimator in estimators:
        fit_transform = False
        if transformers is not None and estimator != "no_estimator":
            pipe = Pipeline([("transformers", Pipeline(transformers)), estimator])
        elif transformers is None and estimator != "no_estimator":
            pipe = Pipeline([estimator])

        if fit_transform:
            pipe.fit_transform(X, y)
        else:
            pipe.fit(X, y)
            pipe.predict(X[-10:])
        assert_frame_equal(X_orig, X)

        if isinstance(y, pd.Series):
            assert_series_equal(y_orig, y)
        else:
            assert_array_equal(y_orig, y)


#!/usr/bin/python3

import os
import sys

data = 1000

print("子プロセス生成前のデータの値: {}".format(data))
pid = os.fork()
if pid < 0:
	print("fork()に失敗しました", file=os.stderr)
elif pid == 0:
	data *= 2
	sys.exit(0)

os.wait()
print("子プロセス終了後のデータの値: {}".format(data))


import sqlite3
import sys

connection = sqlite3.connect("/Users/andrewle/Documents/School/INFO330/INFO330-AccessingDatabases/pokemon.sqlite")
cursor = connection.cursor()

types = ["bug", "dark", "dragon", "electric", "fairy", "fight",
         "fire", "flying", "ghost", "grass", "ground", "ice", "normal",
         "poison", "psychic", "rock", "steel", "water"]

if len(sys.argv) < 6:
    print("You must give me six Pokemon to analyze!")
    sys.exit()

team = []

for i, arg in enumerate(sys.argv):
    if i == 0:
        continue
    # checks to see if input is a number or name (EXTRA CREDIT)
    if arg.isdigit():
        pokedex_number = int(arg)
        # query to select the name of the pokemon if user gives an id and saves it
        cursor.execute("SELECT name FROM pokemon WHERE id=?", (pokedex_number,))
        pokemon = cursor.fetchone()
        pokemon_name = pokemon[0]
    else:
        pokemon_name = arg
        # queries pokedex_number if given a name
        cursor.execute("SELECT id FROM pokemon WHERE name=?", (pokemon_name,))
        pokemon = cursor.fetchone()
        pokedex_number = pokemon[0]

    team.append(pokedex_number)

    # selects type id from the given pokemon and saves it.
    cursor.execute("SELECT type_id, which FROM pokemon_type WHERE pokemon_id=?", (pokedex_number,))
    type_rows = cursor.fetchall()
    type_ids = [row[0] for row in type_rows] #extracts first element in each row, in this case being type_id
    type_names = []

    # fetches types according to it's type_id
    for type_id in type_ids:
        cursor.execute("SELECT name FROM type WHERE id=?", (type_id,))
        type_names.append(cursor.fetchone()[0])
    strong_against = []
    weak_against = []

    # outer loop iterates through the pair of type_names and type_ids
    for poke_type, type_id in zip(type_names, type_ids):
        against_values = []

        # inner loop fetches the against value and appends it to against_values list with the corresponding type_name
        for against_type in types:
            column_name = f"against_{against_type}"
            cursor.execute(f"SELECT {column_name} FROM against WHERE type_source_id1=? OR type_source_id2=?", (type_id, type_id))
            against_value = cursor.fetchone()[0]
            against_values.append((against_type, against_value))

        # loop iterates through the against_values list and appends values to weak or strong against based off effectiveness
        for against_type, against_value in against_values:
            if against_value < 1:
                strong_against.append(against_type)
            elif against_value > 1:
                weak_against.append(against_type)

    strong_against = list(set(strong_against))
    weak_against = list(set(weak_against))

    # printing output from readme example
    print(f"Analyzing {pokedex_number}")
    print(f"{pokemon_name} ({' '.join(type_names)}) is strong against {strong_against} but weak against {weak_against}")

answer = input("Would you like to save this team? (Y)es or (N)o: ")
if answer.upper() == "Y" or answer.upper() == "YES":
    team_name = input("Enter the team name: ")
    connection.commit()

    print(f"Saving {team_name} ...")
else:
    print("Bye for now!")

cursor.close()
connection.close()


#slicing

if __name__ == '__main__':
	t=int(input())
	while t>0:
		n=int(input())
		itm=[int(x) for x in input().split()]
		revItm=itm[-1::-1]
		for x in revItm:
			print(x,end=" ")
		#taking every 3rd element
		l3=[]
		l5=[]
		for i in range(2,len(itm)):
			if(i%3==0):
				l3.append(itm[i]+3)
			if(i%5==0):
				l5.append(itm[i]-7)
		#printing l3 and l5
		for x in l3:
			print(x,end=" ")
		print()
		for x in l5:
			print(x,end=" ")
		#printing sum
		print()
		l3_7=itm[3:8]
		print(sum(l3_7))

		t=t-1


import os
import argparse
import math
import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchvision.transforms import ToTensor, Compose, Normalize
from tqdm import tqdm

from Data import *
from model import *
from utils import setup_seed,measure

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=42)
    parser.add_argument('--batch_size', type=int, default=8)
    parser.add_argument('--max_device_batch_size', type=int, default=8)
    parser.add_argument('--base_learning_rate', type=float, default=1e-3)
    parser.add_argument('--weight_decay', type=float, default=0.05)
    parser.add_argument('--total_epoch', type=int, default=100)
    parser.add_argument('--warmup_epoch', type=int, default=5)
    parser.add_argument('--pretrained_model_path', type=str, default='vit-t-mae.pt')
    parser.add_argument('--output_model_path', type=str, default='vit-t-classifier-from_scratch.pt')
    parser.add_argument('--pretrain', type=str, default='Full')

    args = parser.parse_args()

    setup_seed(args.seed)

    batch_size = args.batch_size
    load_batch_size = min(args.max_device_batch_size, batch_size)

    assert batch_size % load_batch_size == 0
    steps_per_update = batch_size // load_batch_size

    path = os.path.abspath(os.path.dirname(os.getcwd()))
    type_dataset = args.pretrain
    train_dataset = GetTrainSet(path,type_dataset)
    val_dataset = GetValSet(path,type_dataset)

    train_dataloader = torch.utils.data.DataLoader(train_dataset, load_batch_size, shuffle=True, num_workers=4)
    val_dataloader = torch.utils.data.DataLoader(val_dataset, load_batch_size, shuffle=False, num_workers=4)
    device = 'cuda' if torch.cuda.is_available() else 'cpu'

    if args.pretrained_model_path is not None:
        model = torch.load(args.pretrained_model_path, map_location='cpu')
        writer = SummaryWriter(os.path.join('logs', 'cifar10', 'pretrain-cls'))
    else:
        model = MAE_ViT()
        writer = SummaryWriter(os.path.join('logs', 'cifar10', 'scratch-cls'))
    model = ViT_Classifier(model.encoder, num_classes=2).to(device)

    loss_fn = torch.nn.CrossEntropyLoss()
    acc_fn = lambda logit, label: torch.mean((logit.argmax(dim=-1) == label).float())

    optim = torch.optim.AdamW(model.parameters(), lr=args.base_learning_rate * args.batch_size / 256, betas=(0.9, 0.999), weight_decay=args.weight_decay)
    lr_func = lambda epoch: min((epoch + 1) / (args.warmup_epoch + 1e-8), 0.5 * (math.cos(epoch / args.total_epoch * math.pi) + 1))
    lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optim, lr_lambda=lr_func)

    best_val_acc = 0
    step_count = 0
    optim.zero_grad()
    for e in range(args.total_epoch):
        model.train()
        losses = []
        acces = []
        for img, label in train_dataloader:
            step_count += 1
            img = img.to(device)
            label = label.to(device)
            logits = model(img)
            loss = loss_fn(logits, label)
            acc = acc_fn(logits, label)
            loss.backward()
            if step_count % steps_per_update == 0:
                optim.step()
                optim.zero_grad()
            losses.append(loss.item())
            acces.append(acc.item())
        lr_scheduler.step()
        avg_train_loss = sum(losses) / len(losses)
        avg_train_acc = sum(acces) / len(acces)
        print(f'In epoch {e}, average training loss is {avg_train_loss}, average training acc is {avg_train_acc}.')

        model.eval()
        with torch.no_grad():
            losses = []
            acces = []
            for img, label in tqdm(iter(val_dataloader)):
                img = img.to(device)
                label = label.to(device)
                logits = model(img)
                loss = loss_fn(logits, label)
                acc = acc_fn(logits, label)
                losses.append(loss.item())
                acces.append(acc.item())
            avg_val_loss = sum(losses) / len(losses)
            avg_val_acc = sum(acces) / len(acces)
            print(f'In epoch {e}, average validation loss is {avg_val_loss}, average validation acc is {avg_val_acc}.')

        if avg_val_acc > best_val_acc:
            best_val_acc = avg_val_acc
            print(f'saving best model with acc {best_val_acc} at {e} epoch!')
            torch.save(model, args.output_model_path)

        writer.add_scalars('cls/loss', {'train' : avg_train_loss, 'val' : avg_val_loss}, global_step=e)
        writer.add_scalars('cls/acc', {'train' : avg_train_acc, 'val' : avg_val_acc}, global_step=e)

print("Final test:")
test_dataset = GetTestSet(path)
test_dataloader = torch.utils.data.DataLoader(test_dataset, load_batch_size, shuffle=False, num_workers=4)

with torch.no_grad():
    predicts = []
    labels = []
    for img, label in tqdm(iter(test_dataloader)):
        img = img.to(device)
        label = label.to(device)
        logits = model(img)
        predicts+=(logits.argmax(dim=-1)).tolist()
        labels+=label.tolist()
    acc,roc_score,prc_score = measure(torch.tensor(predicts),torch.tensor(labels))

print(f'Test set:acc:{acc},roc_score:{roc_score},prc_score:{prc_score}')